Habit heatmap
A year of one habit at a glance: a 52-week grid of days in five intensities, month and weekday labels, a legend, and current and longest streaks. A Select switches between habits, Grid lays out the stats, and the heatmap itself is an app-owned table.
A year of habits
Dec 2025 – Dec 2026
Habit
- Current streak
- 14 days
- Longest streak
- 24 days
- Active days
- 242 of 360
- Total
- 2,011 km
| Dec | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | |||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Sunday | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Mon | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Tuesday | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Wed | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Thursday | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Fri | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Saturday | ||||||||||||||||||||||||||||||||||||||||||||||||||||
LessMoreDarker squares mean more: up to 5, 8, 11 km, or more.
Source · recipes/habit-heatmap.tsx
'use client'
import { BodySmall, Field, Grid, Heading, Select, Stack, Text } from '@blocks/design-system'
import { Flame, Trophy } from 'lucide-react'
import { type KeyboardEvent, useEffect, useId, useMemo, useRef, useState } from 'react'
import styles from './habit-heatmap.module.css'
const DAY = 24 * 60 * 60 * 1000
// A fixed "today" keeps the server and client renders identical.
const today = Date.UTC(2026, 11, 1)
const weeks = 52
// The grid starts on the Sunday 51 weeks before this week's Sunday.
const start = today - new Date(today).getUTCDay() * DAY - (weeks - 1) * 7 * DAY
const dayCount = Math.round((today - start) / DAY) + 1
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
const longDate = new Intl.DateTimeFormat('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC',
})
const shortMonth = new Intl.DateTimeFormat('en-US', { month: 'short', timeZone: 'UTC' })
interface Habit {
value: string
label: string
unit: string
seed: number
/** Chance of doing it on a given day, from day index and whether yesterday counted. */
chance: (index: number, weekday: number, yesterday: boolean) => number
amount: [number, number]
/** Upper bounds of intensity levels 1–3; anything above is level 4. */
levels: [number, number, number]
}
const habits: [Habit, ...Habit[]] = [
{
value: 'run',
label: 'Morning run',
unit: 'km',
seed: 12,
// Weekends are likelier, and two weeks in July are a holiday.
chance: (index, weekday, yesterday) =>
index >= 215 && index < 229 ? 0 : (weekday === 0 || weekday === 6 ? 0.75 : 0.45) + (yesterday ? 0.15 : 0),
amount: [3, 14],
levels: [5, 8, 11],
},
{
value: 'read',
label: 'Read 20 pages',
unit: 'pages',
seed: 21,
chance: (_index, _weekday, yesterday) => (yesterday ? 0.88 : 0.55),
amount: [20, 80],
levels: [30, 45, 60],
},
{
value: 'cello',
label: 'Cello practice',
unit: 'min',
seed: 8,
// A new habit that sticks: rare in winter, nearly daily by autumn.
chance: (index, _weekday, yesterday) => 0.15 + (index / dayCount) * 0.7 + (yesterday ? 0.1 : 0),
amount: [10, 75],
levels: [20, 35, 50],
},
]
// A small seeded generator (mulberry32): the same habit always draws the same year.
function seeded(seed: number) {
let state = seed
return () => {
state = (state + 0x6d2b79f5) | 0
let t = Math.imul(state ^ (state >>> 15), 1 | state)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
function buildYear(habit: Habit) {
const random = seeded(habit.seed)
const days: { time: number; amount: number; level: number }[] = []
for (let index = 0; index < dayCount; index++) {
const time = start + index * DAY
const yesterday = (days[index - 1]?.amount ?? 0) > 0
const did = random() < habit.chance(index, new Date(time).getUTCDay(), yesterday)
const [min, max] = habit.amount
const amount = did ? Math.round(min + random() * (max - min)) : 0
const level = amount === 0 ? 0 : 1 + habit.levels.filter((bound) => amount > bound).length
days.push({ time, amount, level })
}
return days
}
function streaks(days: { amount: number }[]) {
let longest = 0
let run = 0
for (const day of days) {
run = day.amount > 0 ? run + 1 : 0
longest = Math.max(longest, run)
}
return { current: run, longest }
}
// Month labels span the week columns whose Sunday falls in that month.
const months: { key: string; label: string; span: number }[] = []
for (let week = 0; week < weeks; week++) {
const sunday = new Date(start + week * 7 * DAY)
const key = `${sunday.getUTCFullYear()}-${sunday.getUTCMonth()}`
const last = months.at(-1)
if (last?.key === key) last.span++
else months.push({ key, label: shortMonth.format(sunday), span: 1 })
}
const levels = [0, 1, 2, 3, 4]
const weekColumns = Array.from({ length: weeks }, (_, week) => week)
export default function HabitHeatmap() {
const [habitValue, setHabitValue] = useState('run')
const habit = habits.find((candidate) => candidate.value === habitValue) ?? habits[0]
const days = useMemo(() => buildYear(habit), [habit])
const [active, setActive] = useState(dayCount - 1)
const [hovered, setHovered] = useState<number | null>(null)
const cells = useRef<(HTMLButtonElement | null)[]>([])
const scroller = useRef<HTMLDivElement>(null)
const id = useId()
// On a phone the grid scrolls; start at the most recent weeks.
useEffect(() => {
scroller.current?.scrollTo({ left: scroller.current.scrollWidth })
}, [])
const { current, longest } = streaks(days)
const activeDays = days.filter((day) => day.amount > 0)
const total = activeDays.reduce((sum, day) => sum + day.amount, 0)
const dayLabel = (index: number) => {
const day = days[index]
if (!day) return ''
const date = longDate.format(day.time)
return day.amount ? `${date}: ${day.amount} ${habit.unit}` : `${date}: none`
}
// Arrow keys move a day (up and down) or a week (left and right), like a calendar.
function move(event: KeyboardEvent, index: number) {
const steps: Record<string, number> = { ArrowUp: -1, ArrowDown: 1, ArrowLeft: -7, ArrowRight: 7 }
let next = index + (steps[event.key] ?? 0)
if (event.key === 'Home') next = 0
if (event.key === 'End') next = dayCount - 1
if (next === index || next < 0 || next >= dayCount) return
event.preventDefault()
setActive(next)
cells.current[next]?.focus()
}
return (
<section aria-labelledby={`${id}-title`} className={styles.heatmap}>
<Stack direction="row" justify="space-between" align="end" gap="md" wrap="wrap">
<Stack gap="xs">
<Heading as="h3" id={`${id}-title`} fontSize="lg">
A year of habits
</Heading>
<BodySmall margin="none" color="text-muted">
Dec 2025 – Dec 2026
</BodySmall>
</Stack>
<Field>
<Select
items={habits}
value={habitValue}
onValueChange={(value) => {
if (!value) return
setHabitValue(value)
setActive(dayCount - 1)
}}
>
<Select.Label>Habit</Select.Label>
<Select.Trigger size="sm" />
<Select.Content>
{habits.map((option) => (
<Select.Item key={option.value} value={option.value}>
{option.label}
</Select.Item>
))}
</Select.Content>
</Select>
</Field>
</Stack>
<Grid as="dl" columns={{ base: 2, sm: 4 }} gap="sm" margin="none" dangerouslySetClassName={styles.stats}>
<div>
<dt>
<Flame aria-hidden size={14} /> Current streak
</dt>
<dd>{current} days</dd>
</div>
<div>
<dt>
<Trophy aria-hidden size={14} /> Longest streak
</dt>
<dd>{longest} days</dd>
</div>
<div>
<dt>Active days</dt>
<dd>
{activeDays.length}
<Text fontSize="sm" color="text-muted">
{' '}
of {dayCount}
</Text>
</dd>
</div>
<div>
<dt>Total</dt>
<dd>
{total.toLocaleString('en-US')}
<Text fontSize="sm" color="text-muted">
{' '}
{habit.unit}
</Text>
</dd>
</div>
</Grid>
<section ref={scroller} aria-labelledby={`${id}-caption`} className={styles.scroller}>
<table className={styles.grid} onMouseLeave={() => setHovered(null)}>
<caption id={`${id}-caption`} className={styles.visuallyHidden}>
{habit.label} by day, past year. Use the arrow keys to move between days.
</caption>
<thead>
<tr>
<td />
{months.map((month) => (
<th key={month.key} scope="colgroup" colSpan={month.span}>
<span className={month.span > 2 ? styles.month : styles.visuallyHidden}>{month.label}</span>
</th>
))}
</tr>
</thead>
<tbody>
{weekdays.map((weekday, row) => (
<tr key={weekday}>
<th scope="row">
{row % 2 === 1 ? weekday.slice(0, 3) : <span className={styles.visuallyHidden}>{weekday}</span>}
</th>
{weekColumns.map((week) => {
const index = week * 7 + row
const day = days[index]
return (
<td key={`${weekday}-${week}`}>
{day && (
<button
ref={(node) => {
cells.current[index] = node
}}
type="button"
tabIndex={index === active ? 0 : -1}
aria-label={dayLabel(index)}
data-active={index === active || undefined}
data-level={day.level}
className={styles.cell}
onClick={() => setActive(index)}
onFocus={() => setActive(index)}
onMouseOver={() => setHovered(index)}
onKeyDown={(event) => move(event, index)}
/>
)}
</td>
)
})}
</tr>
))}
</tbody>
</table>
</section>
<Stack direction="row" justify="space-between" align="center" gap="md" wrap="wrap">
<Text fontSize="sm" aria-hidden dangerouslySetClassName={styles.readout}>
{dayLabel(hovered ?? active)}
</Text>
<div className={styles.legend}>
<Text fontSize="xs" color="text-muted">
Less
</Text>
{levels.map((level) => (
<span key={level} data-level={level} className={styles.swatch} />
))}
<Text fontSize="xs" color="text-muted">
More
</Text>
<span className={styles.visuallyHidden}>
Darker squares mean more: up to {habit.levels[0]}, {habit.levels[1]}, {habit.levels[2]} {habit.unit}, or more.
</span>
</div>
</Stack>
</section>
)
}How it works
- The data is deterministic: a fixed “today” and a small seeded random generator per habit, so the server and client draw the same year and nothing changes between renders. Each habit has its own shape (weekend runs and a summer holiday, reading streaks, a cello habit that grows through the year).
- The grid is a table whose rows are weekdays and whose cells hold buttons. Each button’s label is the date and amount (“Tue, Mar 3, 2026: 9 km”), so the intensity never relies on color alone. Only one day is in the tab order; the arrow keys move by a day or a week and Home and End jump to the ends, as in a calendar.
- Hovering or focusing a day shows it in the readout under the grid. The readout is hidden from screen readers, which already hear the focused day’s label.
- Intensity is one hue: the empty surface, then
--ds-color-accentmixed with transparent at 25, 50 and 75 percent, then the accent itself, so it holds up in both themes. - On a phone the grid keeps its size and scrolls sideways inside its region, starting at the most recent weeks, while the weekday column stays in view and each month label sticks beside it rather than sliding under it.
App-owned CSS
.heatmap {
display: flex;
flex-direction: column;
gap: var(--ds-space-lg);
}
.stats {
& > div {
padding: var(--ds-space-md) var(--ds-space-lg);
background-color: var(--ds-color-bg-subtle);
border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
border-radius: var(--ds-border-radius-md);
}
& dt {
display: flex;
align-items: center;
gap: var(--ds-space-sm);
font-size: var(--ds-font-size-xs);
color: var(--ds-color-text-muted);
}
& dd {
margin: var(--ds-space-xs) 0 0;
font-size: var(--ds-font-size-lg);
font-weight: var(--ds-font-weight-semibold);
font-variant-numeric: tabular-nums;
}
}
/* The year scrolls inside its own region when the column is too narrow for it. */
.scroller {
position: relative;
overflow-x: auto;
padding-block: var(--ds-space-xs);
overscroll-behavior-x: contain;
}
.grid {
width: 100%;
min-width: calc(var(--ds-space-xxxxl) * 2.25);
table-layout: fixed;
border-collapse: collapse;
& th {
padding: 0;
font-size: var(--ds-font-size-xxs);
font-weight: var(--ds-font-weight-body);
color: var(--ds-color-text-muted);
text-align: left;
white-space: nowrap;
}
/* The weekday labels stay put while the weeks scroll under them. */
& tbody th,
& thead td {
position: sticky;
left: 0;
z-index: 1;
width: calc(var(--ds-space-xl) - var(--ds-space-sm));
background-color: var(--ds-color-bg);
}
/* Half the gap on each side of every cell. */
& td,
& thead th {
padding: var(--ds-space-xxs);
}
}
/*
* Month labels stick just right of the weekday column, so the month you've
* scrolled into keeps a whole label instead of a fragment under the column.
*/
.month {
position: sticky;
left: calc(var(--ds-space-xl) - var(--ds-space-sm) + var(--ds-space-xs));
display: inline-block;
}
.cell {
display: block;
width: 100%;
aspect-ratio: 1;
padding: 0;
background-color: var(--ds-color-surface);
border: none;
border-radius: calc(var(--ds-border-radius-sm) / 2);
cursor: pointer;
&:hover {
outline: var(--ds-border-width-sm) solid var(--ds-color-border-strong);
}
&[data-active] {
outline: var(--ds-border-width-md) solid var(--ds-color-text);
outline-offset: var(--ds-space-xxs);
}
&:focus-visible {
outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
outline-offset: var(--ds-space-xxs);
}
}
.swatch {
width: calc(var(--ds-space-md) + var(--ds-space-xs));
aspect-ratio: 1;
background-color: var(--ds-color-surface);
border-radius: calc(var(--ds-border-radius-sm) / 2);
}
/* Five steps of one hue: the empty surface, then the accent at rising strength. */
.cell[data-level="1"],
.swatch[data-level="1"] {
background-color: color-mix(in srgb, var(--ds-color-accent) 40%, transparent);
}
.cell[data-level="2"],
.swatch[data-level="2"] {
background-color: color-mix(in srgb, var(--ds-color-accent) 60%, transparent);
}
.cell[data-level="3"],
.swatch[data-level="3"] {
background-color: color-mix(in srgb, var(--ds-color-accent) 80%, transparent);
}
.cell[data-level="4"],
.swatch[data-level="4"] {
background-color: var(--ds-color-accent);
}
.readout {
min-height: calc(var(--ds-font-size-sm) * var(--ds-line-height-body));
font-variant-numeric: tabular-nums;
}
.legend {
display: flex;
align-items: center;
gap: var(--ds-space-xs);
}
.visuallyHidden {
position: absolute;
width: var(--ds-space-xxs);
height: var(--ds-space-xxs);
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}