Streak heatmap
A calendar heatmap of rounded cells in five shades of one theme colour. The year layout shows weeks by weekdays with month and day labels; the week-hours layout shows weekdays by hour. On narrow screens it shows the most recent weeks that fit instead of scrolling. The header has a total, a period picker and current and longest streak badges worked out from the data. Clicking a step in the Less to More legend shows only cells at that level, and hovering a cell outlines its week. Arrow keys, Home and End move through the grid, with a tooltip on focus as well as hover.
Source
"use client";
import * as React from "react";
import { Flame, Trophy } from "lucide-react";
import { cn } from "@/lib/utils";
export type HeatmapDatum = {
/** ISO date ("2026-11-04") for the year layout, or ISO date-time ("2026-11-04T14:00") for week-hours. */
date: string;
count: number;
};
export type HeatmapLayout = "year" | "week-hours";
export type HeatmapLabels = {
/** Singular and plural noun for a count, e.g. ["contribution", "contributions"]. */
unit?: [string, string];
/** Full accessible text for one cell. */
cell?: (count: number, when: string) => string;
};
export type StreakHeatmapProps = {
data: HeatmapDatum[];
layout?: HeatmapLayout;
/** First and last day shown (year layout). Defaults to the 52 weeks up to the latest date in the data. */
from?: string;
to?: string;
/** Four ascending thresholds for levels 1–4, or "auto" for quantiles of the non-zero counts. */
levels?: [number, number, number, number] | "auto";
/** 0 starts weeks on Sunday, 1 on Monday. */
weekStart?: 0 | 1;
/** CSS colour for the strongest step. */
colorVar?: string;
onSelect?: (date: string) => void;
labels?: HeatmapLabels;
/** Shows the period picker (year layout). */
showPicker?: boolean;
/** Shows the current and longest streak badges (year layout). */
showStreaks?: boolean;
title?: string;
className?: string;
};
type Cell = { key: string; count: number; level: number; when: string; label: string; inRange: boolean; col: number; row: number };
const DAY = 86_400_000;
const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const SHORT_DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const STEP_MIX = [0, 28, 52, 76, 100];
const GAP = 3;
const LABEL_COL = 30;
const toDay = (iso: string) => Date.parse(`${iso.slice(0, 10)}T00:00:00Z`);
const isoDay = (ms: number) => new Date(ms).toISOString().slice(0, 10);
const shortDate = (ms: number) => {
const date = new Date(ms);
return `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]}`;
};
const number = new Intl.NumberFormat("en");
function stepColor(level: number, colorVar: string) {
if (level === 0) return "var(--muted)";
return `color-mix(in oklab, ${colorVar} ${STEP_MIX[level]}%, var(--muted))`;
}
function quantile(sorted: number[], q: number) {
if (!sorted.length) return 1;
const pos = (sorted.length - 1) * q;
const base = Math.floor(pos);
const rest = pos - base;
return sorted[base + 1] !== undefined ? sorted[base] + rest * (sorted[base + 1] - sorted[base]) : sorted[base];
}
function thresholds(counts: number[], levels: StreakHeatmapProps["levels"]): number[] {
if (Array.isArray(levels)) return levels;
const sorted = counts.filter((count) => count > 0).sort((a, b) => a - b);
const t = [sorted[0] ?? 1, quantile(sorted, 0.4), quantile(sorted, 0.7), quantile(sorted, 0.9)].map((value) => Math.max(1, Math.ceil(value)));
for (let i = 1; i < t.length; i++) if (t[i] <= t[i - 1]) t[i] = t[i - 1] + 1;
return t;
}
const levelOf = (count: number, t: number[]) => (count <= 0 ? 0 : count >= t[3] ? 4 : count >= t[2] ? 3 : count >= t[1] ? 2 : 1);
/** Current streak (ending today, or yesterday if today is still empty) and longest run of active days. */
export function streaks(byDay: Map<string, number>, fromMs: number, toMs: number) {
let longest = 0;
let run = 0;
for (let ms = fromMs; ms <= toMs; ms += DAY) {
run = (byDay.get(isoDay(ms)) ?? 0) > 0 ? run + 1 : 0;
longest = Math.max(longest, run);
}
let end = toMs;
if (!(byDay.get(isoDay(end)) ?? 0)) end -= DAY;
let current = 0;
for (let ms = end; ms >= fromMs && (byDay.get(isoDay(ms)) ?? 0) > 0; ms -= DAY) current++;
return { current, longest };
}
function useReducedMotion() {
const [reduced, setReduced] = React.useState(false);
React.useEffect(() => {
const query = window.matchMedia?.("(prefers-reduced-motion: reduce)");
if (!query) return;
setReduced(query.matches);
const listen = () => setReduced(query.matches);
query.addEventListener("change", listen);
return () => query.removeEventListener("change", listen);
}, []);
return reduced;
}
export function StreakHeatmap({
data,
layout = "year",
from,
to,
levels = "auto",
weekStart = 1,
colorVar = "var(--chart-1)",
onSelect,
labels,
showPicker = true,
showStreaks = true,
title = "Activity",
className,
}: StreakHeatmapProps) {
const uid = React.useId();
const reduced = useReducedMotion();
const unit = labels?.unit ?? ["contribution", "contributions"];
const noun = (count: number) => (count === 1 ? unit[0] : unit[1]);
/* ---------- period ---------- */
const latest = React.useMemo(() => data.reduce((max, item) => Math.max(max, toDay(item.date)), 0) || toDay(new Date().toISOString()), [data]);
const years = React.useMemo(
() => Array.from(new Set(data.map((item) => Number(item.date.slice(0, 4))))).sort((a, b) => b - a),
[data],
);
const [period, setPeriod] = React.useState<string>("recent");
const range = React.useMemo(() => {
if (period !== "recent") return { from: Date.UTC(Number(period), 0, 1), to: Date.UTC(Number(period), 11, 31) };
const end = to ? toDay(to) : latest;
return { from: from ? toDay(from) : end - 364 * DAY, to: end };
}, [period, from, to, latest]);
/* ---------- measure, so narrow containers show the most recent weeks that fit ---------- */
const wrapRef = React.useRef<HTMLDivElement>(null);
const [width, setWidth] = React.useState(0);
React.useLayoutEffect(() => {
const node = wrapRef.current;
if (!node) return;
const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));
observer.observe(node);
setWidth(node.getBoundingClientRect().width);
return () => observer.disconnect();
}, []);
/* ---------- cells ---------- */
const model = React.useMemo(() => {
if (layout === "week-hours") {
const buckets = new Map<string, number>();
for (const item of data) {
const date = new Date(item.date.length > 10 ? `${item.date.replace(/Z$/, "")}Z` : `${item.date}T00:00:00Z`);
const key = `${date.getUTCDay()}-${date.getUTCHours()}`;
buckets.set(key, (buckets.get(key) ?? 0) + item.count);
}
const t = thresholds([...buckets.values()], levels);
const rows: Cell[][] = [];
for (let r = 0; r < 7; r++) {
const weekday = (r + weekStart) % 7;
const row: Cell[] = [];
for (let hour = 0; hour < 24; hour++) {
const count = buckets.get(`${weekday}-${hour}`) ?? 0;
const when = `${SHORT_DAYS[weekday]} ${String(hour).padStart(2, "0")}:00`;
row.push({
key: `${weekday}-${hour}`, count, level: levelOf(count, t), when, inRange: true, col: hour, row: r,
label: labels?.cell?.(count, when) ?? `${number.format(count)} ${noun(count)} on ${SHORT_DAYS[weekday]} at ${String(hour).padStart(2, "0")}:00`,
});
}
rows.push(row);
}
const total = [...buckets.values()].reduce((sum, value) => sum + value, 0);
return { rows, columns: 24, t, total, months: [] as { col: number; label: string }[], rowNames: rows.map((_, r) => WEEKDAYS[(r + weekStart) % 7]), byDay: new Map<string, number>() };
}
const byDay = new Map<string, number>();
for (const item of data) {
const key = item.date.slice(0, 10);
byDay.set(key, (byDay.get(key) ?? 0) + item.count);
}
const inRange: number[] = [];
for (let ms = range.from; ms <= range.to; ms += DAY) inRange.push(byDay.get(isoDay(ms)) ?? 0);
const t = thresholds(inRange, levels);
const offset = (new Date(range.from).getUTCDay() - weekStart + 7) % 7;
const gridStart = range.from - offset * DAY;
const allColumns = Math.ceil(((range.to - gridStart) / DAY + 1) / 7);
const fit = width ? Math.max(4, Math.floor((width - LABEL_COL + GAP) / (10 + GAP))) : allColumns;
const columns = Math.min(allColumns, fit);
const skip = allColumns - columns;
const rows: Cell[][] = Array.from({ length: 7 }, () => []);
const months: { col: number; label: string }[] = [];
for (let c = 0; c < columns; c++) {
const weekStartMs = gridStart + (c + skip) * 7 * DAY;
for (let r = 0; r < 7; r++) {
const ms = weekStartMs + r * DAY;
const key = isoDay(ms);
const count = byDay.get(key) ?? 0;
const within = ms >= range.from && ms <= range.to;
const when = shortDate(ms);
rows[r].push({
key, count, level: within ? levelOf(count, t) : 0, when, inRange: within, col: c, row: r,
label: labels?.cell?.(count, key) ?? `${count ? number.format(count) : "No"} ${noun(count)} on ${when}`,
});
if (r === 0) {
const firstOfMonth = Array.from({ length: 7 }, (_, d) => new Date(weekStartMs + d * DAY)).find((date) => date.getUTCDate() === 1);
if (c === 0 || firstOfMonth) {
const month = (firstOfMonth ?? new Date(Math.max(weekStartMs, range.from))).getUTCMonth();
if (!months.length || months[months.length - 1].label !== MONTHS[month]) months.push({ col: c, label: MONTHS[month] });
}
}
}
}
// Drop a first month label that would collide with the next one.
if (months.length > 1 && months[1].col - months[0].col < 3) months.shift();
const total = inRange.reduce((sum, count) => sum + count, 0);
return { rows, columns, t, total, months, rowNames: rows.map((_, r) => WEEKDAYS[(r + weekStart) % 7]), byDay };
}, [data, layout, range, levels, weekStart, width, labels, unit[0], unit[1]]);
const cellSize = layout === "year" && width
? Math.max(10, Math.min(16, Math.floor((width - LABEL_COL + GAP) / model.columns - GAP)))
: 12;
const streak = React.useMemo(
() => (layout === "year" ? streaks(model.byDay, range.from, range.to) : null),
[layout, model.byDay, range],
);
/* ---------- interaction ---------- */
const [focus, setFocus] = React.useState<{ row: number; col: number }>(() => ({ row: 0, col: 0 }));
const [tipOpen, setTipOpen] = React.useState(false);
const [hoverCol, setHoverCol] = React.useState<number | null>(null);
const [selected, setSelected] = React.useState<string | null>(null);
const [onlyLevel, setOnlyLevel] = React.useState<number | null>(null);
const cellRefs = React.useRef(new Map<string, HTMLElement>());
// Start the roving tab stop on the latest in-range cell.
React.useEffect(() => {
const flat = model.rows.flat().filter((cell) => cell.inRange);
const last = layout === "year" ? flat.reduce((best, cell) => (cell.col > best.col || (cell.col === best.col && cell.row > best.row) ? cell : best), flat[0]) : flat[0];
if (last) setFocus({ row: last.row, col: last.col });
}, [model, layout]);
const cellAt = (row: number, col: number) => model.rows[row]?.[col];
const go = (row: number, col: number, dRow: number, dCol: number) => {
let r = row;
let c = col;
for (let guard = 0; guard < 400; guard++) {
r += dRow;
c += dCol;
const cell = cellAt(r, c);
if (!cell) return;
if (cell.inRange) {
setFocus({ row: r, col: c });
setTipOpen(true);
cellRefs.current.get(`${r}:${c}`)?.focus();
return;
}
}
};
const edge = (row: number, toEnd: boolean) => {
const cells = model.rows[row].filter((cell) => cell.inRange);
const target = toEnd ? cells[cells.length - 1] : cells[0];
if (!target) return;
setFocus({ row, col: target.col });
setTipOpen(true);
cellRefs.current.get(`${row}:${target.col}`)?.focus();
};
const onKeyDown = (event: React.KeyboardEvent) => {
const { row, col } = focus;
const map: Record<string, () => void> = {
ArrowRight: () => go(row, col, 0, 1),
ArrowLeft: () => go(row, col, 0, -1),
ArrowDown: () => go(row, col, 1, 0),
ArrowUp: () => go(row, col, -1, 0),
Home: () => edge(row, false),
End: () => edge(row, true),
Escape: () => setTipOpen(false),
Enter: () => choose(cellAt(row, col)),
" ": () => choose(cellAt(row, col)),
};
const action = map[event.key];
if (!action) return;
event.preventDefault();
action();
};
const choose = (cell: Cell | undefined) => {
if (!cell?.inRange) return;
setSelected(cell.key);
onSelect?.(layout === "year" ? cell.key : cell.when);
};
/* ---------- tooltip position ---------- */
const [tip, setTip] = React.useState<{ x: number; y: number } | null>(null);
const active = cellAt(focus.row, focus.col);
React.useLayoutEffect(() => {
if (!tipOpen) return setTip(null);
const node = cellRefs.current.get(`${focus.row}:${focus.col}`);
const wrap = wrapRef.current;
if (!node || !wrap) return;
const a = node.getBoundingClientRect();
const b = wrap.getBoundingClientRect();
setTip({ x: a.left - b.left + a.width / 2, y: a.top - b.top });
}, [tipOpen, focus, cellSize, model]);
const tooltipId = `${uid}-tip`;
const fade = reduced ? "" : "motion-safe:transition-[opacity,transform] motion-safe:duration-200";
const gridColumns = `${LABEL_COL - GAP}px repeat(${model.columns}, minmax(0, 1fr))`;
const gridMax = layout === "year" ? LABEL_COL + model.columns * (16 + GAP) : undefined;
const periodLabel = period === "recent" ? "in the last year" : `in ${period}`;
return (
<section aria-label={title} className={cn("min-w-0 rounded-xl border border-border bg-card p-4 text-card-foreground sm:p-5", className)}>
<header className="mb-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-3">
<div className="min-w-0">
<h3 className="text-sm font-semibold text-foreground">{title}</h3>
<p className="text-xs text-muted-foreground">
<span className="font-medium tabular-nums text-foreground">{number.format(model.total)}</span> {noun(model.total)}{" "}
{layout === "year" ? periodLabel : "by weekday and hour"}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{streak && showStreaks && (
<>
<span className="inline-flex items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 text-xs">
<Flame aria-hidden="true" className="size-3.5" style={{ color: colorVar }} />
<span className="text-muted-foreground">Current</span>
<span className="font-semibold tabular-nums text-foreground">{streak.current}d</span>
</span>
<span className="inline-flex items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 text-xs">
<Trophy aria-hidden="true" className="size-3.5 text-muted-foreground" />
<span className="text-muted-foreground">Longest</span>
<span className="font-semibold tabular-nums text-foreground">{streak.longest}d</span>
</span>
</>
)}
{layout === "year" && showPicker && years.length > 0 && (
<label className="relative">
<span className="sr-only">Period</span>
<select
value={period}
onChange={(event) => {
setPeriod(event.target.value);
setTipOpen(false);
}}
className="h-7 appearance-none rounded-md border border-border bg-background pl-2.5 pr-7 text-xs font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<option value="recent">Last 12 months</option>
{years.map((year) => (
<option key={year} value={String(year)}>
{year}
</option>
))}
</select>
<svg aria-hidden="true" viewBox="0 0 12 12" className="pointer-events-none absolute right-2 top-1/2 size-3 -translate-y-1/2 text-muted-foreground">
<path d="M3 4.5 6 7.5 9 4.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</label>
)}
</div>
</header>
<div ref={wrapRef} className="relative min-w-0">
<div
role="grid"
aria-label={`${title}, ${layout === "year" ? "days by week" : "weekdays by hour"}`}
aria-readonly="true"
onKeyDown={onKeyDown}
onMouseLeave={() => {
setHoverCol(null);
setTipOpen(false);
}}
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node)) setTipOpen(false);
}}
className="relative grid"
style={{ gridTemplateColumns: gridColumns, gap: GAP, maxWidth: gridMax }}
>
{/* Column labels: months on top for a year, a few hours for week-hours. */}
<div aria-hidden="true" className="contents">
{layout === "year"
? model.months.map((month) => (
<span key={`${month.col}-${month.label}`} className="whitespace-nowrap text-[10px] leading-4 text-muted-foreground" style={{ gridRow: 1, gridColumn: month.col + 2 }}>
{month.label}
</span>
))
: [0, 6, 12, 18].map((hour) => (
<span key={hour} className="whitespace-nowrap text-[10px] leading-4 text-muted-foreground" style={{ gridRow: 1, gridColumn: hour + 2 }}>
{String(hour).padStart(2, "0")}:00
</span>
))}
<span style={{ gridRow: 1, gridColumn: 1 }} className="h-4" />
</div>
{/* The hovered week (or hour) column gets a faint outline. */}
{hoverCol != null && (
<div
aria-hidden="true"
className="pointer-events-none -m-[2px] rounded-[5px] ring-1 ring-foreground/25"
style={{ gridRow: "2 / span 7", gridColumn: hoverCol + 2 }}
/>
)}
{model.rows.map((row, r) => (
<div role="row" key={r} aria-label={model.rowNames[r]} className="contents">
<span aria-hidden="true" className="self-center text-[10px] leading-none text-muted-foreground" style={{ gridRow: r + 2, gridColumn: 1 }}>
{[1, 3, 5].includes((r + weekStart) % 7) ? model.rowNames[r].slice(0, 3) : ""}
</span>
{row.map((cell) => {
const isFocus = focus.row === r && focus.col === cell.col;
const dimmed = onlyLevel != null && cell.level !== onlyLevel;
const isSelected = selected === cell.key;
return (
<div
key={cell.key}
ref={(node) => {
if (node) cellRefs.current.set(`${r}:${cell.col}`, node);
else cellRefs.current.delete(`${r}:${cell.col}`);
}}
role="gridcell"
tabIndex={cell.inRange && isFocus ? 0 : -1}
aria-label={cell.inRange ? cell.label : undefined}
aria-hidden={cell.inRange ? undefined : true}
aria-selected={cell.inRange ? isSelected : undefined}
aria-describedby={isFocus && tipOpen ? tooltipId : undefined}
onMouseEnter={() => {
setHoverCol(cell.col);
if (!cell.inRange) return setTipOpen(false);
setFocus({ row: r, col: cell.col });
setTipOpen(true);
}}
onFocus={() => {
setFocus({ row: r, col: cell.col });
setTipOpen(true);
}}
onClick={() => choose(cell)}
className={cn(
"aspect-square rounded-[3px] outline-none",
cell.inRange ? "cursor-pointer" : "invisible",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card",
isSelected && "ring-2 ring-foreground ring-offset-1 ring-offset-card",
fade,
)}
style={{
gridRow: r + 2,
gridColumn: cell.col + 2,
background: stepColor(cell.level, colorVar),
opacity: dimmed ? 0.18 : 1,
boxShadow: cell.level === 0 ? "inset 0 0 0 1px color-mix(in oklab, var(--foreground) 5%, transparent)" : undefined,
}}
/>
);
})}
</div>
))}
</div>
{tipOpen && tip && active?.inRange && (
<div
id={tooltipId}
role="tooltip"
className="pointer-events-none absolute z-20 -translate-x-1/2 -translate-y-full whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-[11px] font-medium text-background shadow-md"
style={{ left: `clamp(4.5rem, ${tip.x}px, calc(100% - 4.5rem))`, top: tip.y - 6 }}
>
{active.label}
</div>
)}
</div>
<footer className="mt-4 flex flex-wrap items-center justify-between gap-3 text-[11px] text-muted-foreground">
<span aria-live="polite">
{onlyLevel != null ? (
<button
type="button"
onClick={() => setOnlyLevel(null)}
className="rounded underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring"
>
Showing level {onlyLevel} only · Clear
</button>
) : (
"Select a step to filter"
)}
</span>
<div role="group" aria-label="Intensity filter" className="flex items-center gap-1.5">
<span>Less</span>
{[0, 1, 2, 3, 4].map((level) => {
const low = level === 0 ? 0 : model.t[level - 1];
const high = level === 4 ? null : level === 0 ? 0 : model.t[level] - 1;
const rangeText = level === 0 ? "none" : high == null ? `${low} or more` : low === high ? `${low}` : `${low} to ${high}`;
return (
<button
key={level}
type="button"
aria-pressed={onlyLevel === level}
aria-label={`Show only level ${level} (${rangeText})`}
title={rangeText}
onClick={() => setOnlyLevel((current) => (current === level ? null : level))}
className={cn(
"size-3.5 rounded-[3px] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card",
onlyLevel === level && "ring-2 ring-foreground ring-offset-1 ring-offset-card",
onlyLevel != null && onlyLevel !== level && "opacity-40",
)}
style={{ background: stepColor(level, colorVar) }}
/>
);
})}
<span>More</span>
</div>
</footer>
</section>
);
}
