<!-- generated by scripts/gen-docs.mjs from docs/system/heatmap.md. Edit the source and rerun. -->
# Heatmap

## Description
Lays values out on a grid and shades each cell by size, as two sets of names crossed or as days across a year, so a person can see where the values gather.

`import { Heatmap } from "@/components/cobalt/ui/heatmap"`, source `registry/cobalt/ui/heatmap.tsx`, status `ready-with-gaps`.
Foundation: `hand-rolled`. Traps checked: `trap/loading-layout-shift`, `trap/color-only-status`, `trap/live-region-double`, `trap/reduced-motion-ignored`, `trap/motion-transition-all`, `trap/motion-layout-property`, `trap/numbers-shift`, `trap/tooltip-essential`, `trap/tooltip-interactive`, `trap/touch-hover-flash`, `trap/hover-unguarded` (n/a: no CSS hover reveals anything; the overlay follows the hover store), `trap/demo-on-timers` (n/a: every example holds fixed data), `trap/illustration-announced` (n/a: the cells are `aria-hidden` and the table carries the data), `trap/loop-offscreen` (n/a: nothing loops).

### Foundation
Not applicable: hand-rolled.

| Given by the foundation | Added by the team |
|---|---|
| The `Chart` frame from `registry/cobalt/ui/chart.tsx` (a box of fixed height, one measured size, the hover store, the tooltip, the keyboard, the empty, pending and failure states, the hidden summary and table, `ChartXAxis` and `ChartCanvas`), and `rampColor`, `labelIndexes`, `pointDate`, `timeOf` and `tableRows` from `chart-math.ts` | The grid itself: a cell per value, shaded from the grey to the series colour in five steps, and from the grey toward `--chart-3` below zero when the range crosses zero; a matrix whose rows and columns take the order in which each name first appears; a calendar whose days fall in Monday weeks, a column a week, with the days between the first and the last filled with 0, the rows of one day summed, months above and Mon, Wed and Fri at the start; a calendar narrower than 9px a day shows the latest weeks that fit while the table keeps them all; square days kept in the middle of the box; a `Less` to `More` legend of swatches under the chart; arrows by column and by row; past 5,000 cells the fills are painted on a canvas while the labels, the hover and the focus stay SVG |

## Examples
Filings by weekday and hour, stronger where more arrive.

Real uses, 0 call sites (`rg -n "<Heatmap\b" app registry docs/system/examples --glob '!docs/system/examples/heatmap/*'`): the showcase chrome renders no Heatmap of its own, and the examples folder does not count.

Uses inside the registry: none. `registry/cobalt/ui/heatmap.test.tsx` renders it for the tests.

### Example files
| File | Covers | Caption |
|---|---|---|
| Not applicable: the matrix is the default layout, the grid in default.tsx | layout=matrix | Two sets of names crossed |
| `docs/system/examples/heatmap/default.tsx` | default | Filings by weekday and hour, stronger where more arrive |
| `docs/system/examples/heatmap/layout-calendar.tsx` | layout=calendar | Filings per day across a year, a column a week, busier midweek and in the days before each 13F deadline |
| `docs/system/examples/heatmap/in-card.tsx` | composition:Card | Booking requests by weekday and hour in a chart card, with the busiest hour, read from the same cells, as the headline |

Example: Filings by weekday and hour, stronger where more arrive (`docs/system/examples/heatmap/default.tsx`)

```tsx
import { Heatmap } from "@/components/cobalt/ui/heatmap";

const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
const hours = ["8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00"];
// Filings received by weekday and hour over the last quarter.
const counts = [
  [4, 12, 22, 31, 18, 24, 35, 28, 16, 6],
  [6, 15, 26, 34, 21, 27, 38, 30, 18, 8],
  [5, 14, 24, 30, 19, 26, 33, 27, 15, 7],
  [7, 16, 28, 36, 22, 29, 41, 34, 20, 9],
  [3, 10, 18, 25, 14, 17, 22, 15, 8, 2],
];
const cells = days.flatMap((day, d) => hours.map((hour, h) => ({ day, hour, filings: counts[d]?.[h] ?? 0 })));

export default function Example() {
  return (
    <Heatmap
      label="Filings by weekday and hour"
      data={cells}
      row="day"
      column="hour"
      value="filings"
      unit={{ one: "filing", other: "filings" }}
    />
  );
}
```

Example: Booking requests by weekday and hour in a chart card, with the busiest hour, read from the same cells, as the headline (`docs/system/examples/heatmap/in-card.tsx`)

```tsx
import { ChartCard } from "@/components/cobalt/ui/chart-card";
import { Heatmap } from "@/components/cobalt/ui/heatmap";
import { integer } from "@/lib/cobalt/format";

const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const hours = ["6:00", "9:00", "12:00", "15:00", "18:00", "21:00"];
// Booking requests across 42 hotels in September, by weekday and the three hours from each time.
const counts = [
  [38, 142, 121, 133, 168, 96],
  [41, 151, 128, 139, 172, 101],
  [36, 147, 124, 131, 165, 98],
  [44, 158, 133, 146, 188, 117],
  [52, 139, 118, 162, 231, 174],
  [61, 97, 144, 171, 204, 163],
  [57, 88, 152, 166, 149, 92],
];
const cells = days.flatMap((day, d) => hours.map((hour, h) => ({ day, hour, requests: counts[d]?.[h] ?? 0 })));
const busiest = cells.reduce((best, cell) => (cell.requests > best.requests ? cell : best));

export default function Example() {
  return (
    <ChartCard
      className="w-full max-w-xl"
      title="Busiest time to book"
      value={`${busiest.day} ${busiest.hour}`}
      note={`${integer(busiest.requests)} requests in September`}
    >
      <Heatmap
        label="Booking requests by weekday and hour"
        data={cells}
        row="day"
        column="hour"
        value="requests"
        unit={{ one: "request", other: "requests" }}
      />
    </ChartCard>
  );
}
```

## Variants

### layout
- `matrix`: two sets of names crossed, such as weekday by hour, with row names at the start and column names under the grid; the default, 192px tall. Used at 0 call sites.
- `calendar`: one value per day laid out in weeks, a column a week from Monday, with months above and Mon, Wed and Fri at the start; 128px tall unless `height` says otherwise. Used at 0 call sites.

Example: Filings per day across a year, a column a week, busier midweek and in the days before each 13F deadline (`docs/system/examples/heatmap/layout-calendar.tsx`)

```tsx
import { Heatmap } from "@/components/cobalt/ui/heatmap";

// 13F holdings are due 45 days after each quarter ends: Nov 14, Feb 14, May 15 and Aug 14.
const deadlines = ["2025-11-14", "2026-02-14", "2026-05-15", "2026-08-14"].map((day) => Date.parse(day));
const start = Date.UTC(2025, 9, 13);

// A count per day for 52 weeks: low at weekends, higher midweek, and heavy in the six days before a deadline.
const days = Array.from({ length: 364 }, (_, i) => {
  const time = start + i * 86_400_000;
  const weekday = new Date(time).getUTCDay();
  const rush = deadlines.some((due) => due >= time && due - time < 6 * 86_400_000) ? 30 : 0;
  return {
    date: new Date(time).toISOString().slice(0, 10),
    filings: weekday === 0 || weekday === 6 ? i % 5 : 6 + ((i * 7) % 11) + rush,
  };
});

export default function Example() {
  return (
    <Heatmap
      label="Filings per day"
      layout="calendar"
      data={days}
      date="date"
      value="filings"
      unit={{ one: "filing", other: "filings" }}
    />
  );
}
```

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| idle | at least one cell with a finite value, and a range above zero | read the grid, hover, tab in | the shaded cells, the labels, the `Less` to `More` legend | screenshot |
| hover | the pointer over a cell | read the tooltip, move along | a 1.5px outline whose inner edge lies on the cell and whose corners are the cell's radius plus 0.75px, concentric with it and inside the 2px gap, and the tooltip 6px above it with the cell's title and its value written out, the row named by `unit` when it is passed | screenshot |
| focus | Tab reaches the box | step with the arrow keys | the system focus outline on the box, a ring around the last cell, the live line read aloud | screenshot |
| no value | a cell of a matrix with no finite value | read "Unknown" | a grey cell, and "Unknown" in the muted ink in the tooltip and the table, never "None", which reads as zero | by hand |
| trimmed | a calendar whose weeks would be under 9px a day | read the latest weeks | the weeks that fit; the summary and the table still hold every day | by hand |
| canvas | more than 5,000 cells | the same as idle | the fills on a canvas under the same labels, with the same rounded corners; the outline stays SVG and the tooltip HTML | screenshot |
| pending | `status="pending"` with nothing drawn yet | wait | `aria-busy`; nothing for 250ms, then a Skeleton block at the box's size | test |
| refreshing | `status="pending"` with marks on screen | read the old marks | `aria-busy`; after 250ms the marks dim to 55% and the hover stops; the new marks fade in when they arrive | by hand |
| empty | no finite value, or every value zero, and not pending | read why | the sentence "Nothing to show for this period." centred in the box, and no legend | test |
| failure | `status="failure"` | press Retry | the title "Could not load the chart" announced once as an alert, and Retry when `onRetry` is passed | test |

### State precedence
- Failure and pending: failure wins. The box shows the failure and its Retry.
- Pending and empty: pending wins. The box stays blank, then shows the Skeleton after the slow wait; the empty sentence never flashes.
- Pending and idle: both show. The old cells stay, dimmed to 55% once the slow wait passes, until the new data arrives.
- Hover and focus: the last one wins. The pointer and the keys move the same ring, so one cell shows at a time.
- Trimmed and focus: both show. The arrows walk only the weeks the grid shows, and the table keeps every day for a screen reader.
- Canvas and hover: both show. The canvas paints the cells, the SVG overlay draws the outline above them, and the tooltip sits above both.

### Motion
Not applicable: no motion in the heatmap's own code; the fade of the hover overlay belongs to the Chart frame (chart.md).

## Props

<!-- Props generated from registry/cobalt/ui/heatmap.tsx with TypeScript by scripts/props-table.mjs -->
| Prop | Type | Default | Purpose |
|---|---|---|---|
| `data` | `readonly T[]` |  |  |
| `label` | `string` |  |  |
| `value` | `Accessor<T, number>` |  |  |
| `active?` | `number` |  |  |
| `className?` | `string` |  |  |
| `column?` | `Accessor<T, string>` |  |  |
| `date?` | `Accessor<T, string \| Date>` |  | For a calendar: the day, as a Date or an ISO date. |
| `format?` | `ValueFormat` | `"number"` |  |
| `height?` | `ChartHeight` | `layout === "calendar" ? "sm" : "md"` |  |
| `labels?` | `Partial<ChartLabels>` |  |  |
| `layout?` | `"matrix" \| "calendar"` | `"matrix"` | "matrix" crosses two sets of names; "calendar" lays days out in weeks, a column a week. |
| `locale?` | `string` |  |  |
| `onActiveChange?` | `((index: number) => void)` |  |  |
| `onRetry?` | `(() => void)` |  |  |
| `row?` | `Accessor<T, string>` |  | For a matrix: the row and the column a value belongs to, in the order they first appear. |
| `scale?` | `{ low: string; high: string; }` | `SCALE` | The words at the two ends of the scale under the chart. |
| `status?` | `Status` |  |  |
| `summary?` | `string` |  | Your own sentence for screen readers; one is written from the data otherwise. |
| `tooltip?` | `boolean` |  |  |
| `unit?` | `PluralForms` |  | What one cell counts, in each plural form: { one: "filing", other: "filings" }. |

`data` is the rows and `value` reads a number from each, as a key or a function. With `layout="matrix"`, `row` and `column` read the names a cell belongs to, in the order they first appear; with `layout="calendar"`, `date` reads a day as a Date or an ISO date, and a day that has several rows sums them. `format` shapes the values in the tooltip, the summary and the table. `unit` names what one cell counts in each plural form, `{ one: "filing", other: "filings" }`, and its plural, capitalised, names the tooltip's row and the table's column in place of the whole `label`. `scale` holds the two words at the ends of the legend, "Less" and "More" by default; the legend holds its line in every state, hidden until there are values. `height` defaults to `md` for a matrix and `sm` for a calendar. The frame's props pass through: `label`, `summary`, `status`, `onRetry`, `labels`, `tooltip`, `active`, `onActiveChange` and `locale`; `active` and `onActiveChange` speak in the cell's index across the whole grid, column times rows plus row, whether or not a narrow calendar leaves its first weeks off. It takes no `layers`. `HEATMAP_CANVAS_FROM` is exported, 5,000.

## Usage

### When to use
- Counts or amounts by two names, where the pattern across the grid is the point, such as filings by weekday and hour.
- One value per day across a year or more, where busy and quiet stretches are the point.

### When not to use
- Two measures of many things, one dot each. Use ScatterChart instead.
- One measure over time, read by value. Use LineChart instead.
- A few names with values read one by one. Use BarList instead.

### Rules
- `rule/heatmap-calendar-for-days`: When the values are one per day across a stretch of time, pass `layout="calendar"` and `date` instead of a matrix with a month and a day as names, because the calendar lays days in Monday weeks, fills the days between the first and the last with 0, sums the rows of one day and labels the months, and a matrix of names does none of it. Evidence: measured 6 for two rows on one day and 0 for the day between, registry/cobalt/ui/heatmap.test.tsx. Check: test `heatmap.test.tsx` expects `<th scope="row">Mar 2, 2026</th><td>6</td>` and `<td>0</td>` for Mar 3.
  - Don't: `<Heatmap label="Filings per day" data={days} row="month" column="day" value="filings" />`
  - Do: `<Heatmap label="Filings per day" layout="calendar" data={days} date="date" value="filings" />`
- `rule/heatmap-sort-before-passing`: When rows or columns have an order, such as Mon to Fri or 8:00 to 17:00, sort the data in that order before passing it instead of expecting the heatmap to sort it, because rows and columns take the order in which each name first appears. Evidence: single use registry/cobalt/ui/heatmap.tsx:168-169. Check: review of every `Heatmap` `data` for its order.
  - Don't: `<Heatmap label="Filings" data={[...cells].sort((a, b) => b.filings - a.filings)} row="day" column="hour" value="filings" />`
  - Do: `<Heatmap label="Filings" data={cellsByDayThenHour} row="day" column="hour" value="filings" />`
- `rule/heatmap-calendar-shows-latest-weeks`: When a `layout="calendar"` heatmap must fit a narrow width, pass every day instead of slicing the data to the weeks that fit, because the grid already shows the latest weeks that fit at 9px a day, and the summary and the table keep every day. Evidence: single use registry/cobalt/ui/heatmap.tsx:253-255. Check: review of every calendar's `data` for a slice.
  - Don't: `<Heatmap label="Filings per day" layout="calendar" data={days.slice(-120)} date="date" value="filings" />`
  - Do: `<Heatmap label="Filings per day" layout="calendar" data={days} date="date" value="filings" />`

### Content
- Follows `rule/writing-no-invented-numbers`.
- `rule/heatmap-label-names-the-measure`: When a heatmap is placed, give `label` the measure and the two names it is crossed by, such as "Filings by weekday and hour", because the label is the accessible name, the head of the table's value column and the first words of the summary, and a shade has no axis to say what it measures. Evidence: principle wcag: 1.1.1 Non-text content; principle wcag: 4.1.2 Name, role, value. Check: test `heatmap.test.tsx` expects the summary "Highest 30 at Tue, 9:00." and the table's row headers.
  - Don't: `<Heatmap label="Chart" data={cells} row="day" column="hour" value="filings" />`
  - Do: `<Heatmap label="Filings by weekday and hour" data={cells} row="day" column="hour" value="filings" />`

### Anti-slop
- `rule/heatmap-one-hue-ramp`: When a grid needs shading, let `Heatmap` shade it from the grey to `--chart-1`, and toward `--chart-3` below zero, instead of a rainbow ramp or a colour per cell, because five steps of one hue read as less and more, and a rainbow reads as categories. Evidence: person D13; principle wcag: 1.4.1 Use of color. Check: review of every file that draws a grid for an inline cell fill; the tooltip writes each value out.
  - Don't: `<rect style={{ fill: `hsl(${value * 3} 80% 50%)` }} />`
  - Do: `<Heatmap label="Filings by weekday and hour" data={cells} row="day" column="hour" value="filings" />`

### Limits
- `rule/heatmap-canvas-past-5000`: When a heatmap holds more than 5,000 cells, let it paint them on its canvas, which it does by itself, instead of forcing SVG cells, because one SVG node per cell costs what one per dot does, 6.7ms at 5,000 and 30.6ms at 20,000 against 1.0ms and 1.9ms on a canvas. Evidence: measured 6.7ms for 5,000 SVG circles and 30.6ms for 20,000 against 1.0ms and 1.9ms on canvas, docs/research/2026-10-17-charts.md; measured hover median 2.9ms and layout shift 0 on 100,000 cells, .design-system/evidence/charts/hover-cost.jsonl. Check: test `heatmap.test.tsx` expects the 5,000 threshold.
  - Don't: `cells.map((c) => <rect x={c.x} y={c.y} width={8} height={8} />)`
  - Do: `<Heatmap label="Filings by desk and hour" data={cells} row="desk" column="hour" value="filings" />`

## Accessibility
Rests on the Chart frame: a focusable `div` with `role="group"` and `aria-roledescription="chart"`, one tab stop per chart. The cells are `aria-hidden`; the data is a visually hidden sentence ("Filings by weekday and hour: 50 cells from 0 to 41. Highest 41 at Thu, 14:00.") through `aria-describedby` and a visually hidden `table` with one row per cell, sampled to 200 evenly spaced rows with a note past that. A cell's shade is told in the tooltip, the live line and the table as the value written out. Contrast of the lightest shades against the card: NEEDS REVIEW. Screen reader pass with VoiceOver: NEEDS REVIEW.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Tab | before the chart | focuses the box and shows the last cell | the box | by hand |
| Right, Left | the box | the next or previous column, in the same row | the box | by hand |
| Down, Up | the box | the next or previous row, in the same column | the box | by hand |
| Home, End | the box | the first or the last cell | the box | by hand |
| Page Down, Page Up | the box | a tenth of the cells on or back, at least 2 | the box | by hand |
| Escape | the box, or the pointer over it | hides the ring and the tooltip | stays | by hand |
| Tab | the box | leaves the chart | the next control | by hand |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| box | group | `label`, through `aria-label`; `aria-roledescription` from `labels.chart` | `aria-describedby` the summary; `aria-busy` while pending | the name, "chart" and the summary when it is reached | test |
| live line | none, `aria-live="polite"` | nothing | none | the cell's title and its value as the keys move; pointer moves are silent | by hand |
| table | table | its caption, the `label` | a row header per cell, "Mon, 9:00" or "Mar 2, 2026" | read on request from the table list | test |
| legend | none | nothing | the swatches are `aria-hidden`; the two words are text | "Less" and "More" | by hand |
| failure | alert | its title | none | "Could not load the chart" once | test |

## Tokens
| Part | State | Token |
|---|---|---|
| cell, no value or zero | all | `--muted` |
| cell, shaded | all | `--chart-1` mixed into `--muted` in oklab in five steps, so every step keeps the hue (262 measured at each step in both themes) and only the lightness moves: 0.86 to 0.50 in light, 0.36 to 0.72 in dark |
| cell, below zero | all | `--chart-3` mixed into `--muted` in oklab in five steps |
| row and column labels | all | `--muted-foreground` |
| ring | hover | `--foreground` |
| tooltip | hover | `--tip`, `--tip-foreground`, `--r-md`, `--t-press`, `--curve` |
| legend swatch | all | `--r-xs` |
| legend words | all | `--muted-foreground` |

## Related
- Chart: the frame every chart draws in, and its hover, keyboard and states.
- ScatterChart: two measures of many things, one dot each.
- LineChart: one measure over time, read by value.
- BarList: a few names whose values are read one by one.
