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

## Description
Lists records with the same fields, as many as a server holds: it renders only the rows in view, sorts and filters through each column's header, selects rows to act on together, and turns into a two-line list on a phone.

`import { DataTable, DataTableColumns, DataTableSort, DataTableToolbar, type Column, type RowKey, type Rows, type Sort, defaultLabels } from "@/components/cobalt/ui/data-table"`, source `registry/cobalt/ui/data-table.tsx`, status `ready-with-gaps`.
Foundation: `hand-rolled`. Traps checked: `trap/table-divs`, `trap/empty-value`, `trap/numbers-shift`, `trap/color-only-status`, `trap/list-dead-gap`, `trap/narrow-hidden-nav`, `trap/scroll-chain`, `trap/overflow-scrollbar`, `trap/loading-layout-shift`, `trap/menu-only-path`, `trap/menu-navigation`, `trap/open-trigger-unfocused`, `trap/escape-nested`, `trap/overlay-focus-return`, `trap/motion-blocks-input`, `trap/reduced-motion-ignored`, `trap/motion-frequent`.

The window: of 60 rows at 1280 the first render holds 20 and a scroll holds at most 30; of 10,000 rows it holds 21 to 31. Twenty scroll steps of three rows paint in a mean of 16.6ms per step, with no step past 36ms (`.design-system/evidence/data-table/measure-1280.json`). `scripts/table-bench.mjs` scrolls a production build of a Fund Census style screener (10,000 funds, nine columns with a linked name, a flag, tags and figures, fill mode, 1440x900) 60 frames of three rows each: at 4x CPU the frame time is 16.7ms at p50, 16.8ms at p95 and 16.8ms at most, against 33.3, 50.0 and 50.1ms before, and at 6x 16.7, 33.4 and 33.4ms against 50.0, 66.7 and 66.7ms rows rendered only when they changed and each figure was measured once; `getBoundingClientRect` falls from 10,560 calls to 900 (15 a step, the new rows' figures), `getComputedStyle` from 10,440 to 0, and DOM mutations stay at 530 (`.design-system/evidence/data-table/bench-before.json`, `.design-system/evidence/data-table/bench-after.json`). Run again after the held figure room, the deep first load, the missing-value cells and the phone header line, it reads the same: 16.7, 16.8 and 16.8ms at 4x, 16.7, 33.4 and 33.4ms at 6x, 900 rects, 0 styles and 530 mutations, against 16.7, 16.8, 16.8 and 16.7, 33.3, 33.4ms before (`.design-system/evidence/data-table/bench-pd.json`). Run again after the words that give way, the phone's half row, the eased landing and the centred empty slot, it reads 16.7, 16.7 and 16.8ms at 4x and 16.7, 33.3 and 33.4ms at 6x, with 900 rects, 0 styles and 530 mutations, against 16.7, 16.8, 16.8 and 16.7, 33.4, 33.4ms before (`.design-system/evidence/data-table/bench-pe.json`). Run again after the table's one tooltip, the rows drawn after the first measurements and the quiet row window, it reads as at 04e3058: 16.7, 16.7 and 16.8ms at 4x and 16.7, 33.4 and 33.4ms at 6x, with 900 rects, 0 styles and 530 mutations (`.design-system/evidence/perf/table-bench-before.json`, `.design-system/evidence/perf/table-bench-after.json`). A mirror of Fund Census's funds screener on a `useRowWindow`, built with esbuild for React 19 and for Preact 11 through preact/compat, draws its first row at 4x CPU and 1440 in 446ms under React and 357ms under Preact, against 554 and 468ms at 04e3058, with 86 and 89ms of style before the first paint, against 151 and 149ms; it scrolls at 17, 26 and 42ms a frame (p50, p95, max) under React and 21, 25 and 28ms under Preact, against 51, 64, 70 and 57, 76, 85ms, with no long task where there were 8 and 34; at 1x the first row comes in 113 and 94ms against 148 and 128ms, and at 390 and 4x in 366 and 296ms against 419 and 320ms (`.design-system/evidence/perf/screener-bench.json`, `.design-system/evidence/perf/bench/measure.mjs`). The header is 40px and a row 40px on a desktop; on a phone the header line is 44px and a row 60px (`.design-system/evidence/data-table/measure-390.json`). The headers answer `trap/table-divs` (Accessibility), `trap/empty-value` and `trap/numbers-shift` (Content and Anti-slop), `trap/color-only-status` (Anti-slop), `trap/list-dead-gap`, `trap/loading-layout-shift` and `trap/open-trigger-unfocused` (States), `trap/narrow-hidden-nav` and `trap/overflow-scrollbar` (Limits), `trap/scroll-chain` (Foundation), `trap/menu-only-path`, `trap/menu-navigation`, `trap/escape-nested` and `trap/overlay-focus-return` (Keyboard), `trap/motion-blocks-input`, `trap/reduced-motion-ignored` and `trap/motion-frequent` (Motion).

### Foundation
| Given by the foundation | Added by the team |
|---|---|
| The native `table`, `thead`, `tbody`, `tfoot`, `tr`, `th` and `td`, each with its implicit role restated so the `block` and `grid` display keeps the table semantics; Base UI `Popover` for the column menu: the portal, placement below the header's start edge with a 4px offset, Escape, and focus back to the trigger on close | The `table` as the scroll container with `overscroll-behavior: none`, so the sticky header stays pinned past either end and nothing chains to the page, no top border, a thin scrollbar (`scrollbar-width: thin`) in the ink at 20 percent on a clear track with `scrollbar-gutter: stable`, a hairline on the sticky first column's end edge once a column has slid under it, and none at rest, the sorted column's arrow in the ink, 4px beside its label on the side away from the cell's edge (before a figure's label, after a word's), set in 30px held on that side so it takes no width from the label and sorting moves nothing, and on an unsorted sortable header a faint two-way arrow only under the pointer, and the filter mark, a 12px glyph in a 20px badge; the focus outline drawn 2px inside the table (`--focus-offset: -2px`, inherited by the header buttons and the rows) so the card's clip never hides it, and a header button reached with Tab while partly past a scroll edge scrolled fully into view, while one taken by a press stays where it is, so the table never slides sideways under the pointer (it moved 36px and 46px in frame 1 before, 0px now, audit B, 17 October); the column menu on the menu recipe, 8px around 38px rows with a 12px corner, concentric with its 20px corner, and a filter 10px from its edge so a 10px control there is concentric too, the column menu's highlight following the pointer, no fixed height when there are no rows and nothing pending, so the empty slot shows in full, `hideBelow` read against the table's own width through a ResizeObserver on the table and not the window's, the sticky header and sticky first column, the row window (10 rows of overscan, a re-render every 3 rows), a `Rows` source for arrays and server windows, widths measured from the header labels in their own font, with beside each label only the room its marks need (20px of padding, 18px more for the sort mark where the column sorts, 18px more for the filter mark where it can filter), over floors by kind: text 120px, number 64px, date 88px, code 64px, tags 220px and the main column 160px, so a column of figures starts narrow and grows to its widest figure on screen (the five-column bookings tables measure 624px in a 624px card at 1440, against 670px before); when those floors pass the table's box by no more than its columns of words can give, each column of words gives way toward its least in proportion, 96px for words, 168px for tags and 128px for the main column, never under its label and marks and never a width the host set, so a table a few pixels too wide fits with its words cut sooner, and past that the floors stand and it scrolls sideways by at least what the words could give (`registry/cobalt/ui/data-table.tsx:562`): over every example at each frame content width from 230 to 704px, no table scrolls sideways by under 24px, against 415 table widths that scrolled by 1 to 22px before, such as Filtered column from 560 to 581px (`.design-system/evidence/data-table/fit-sweep-before.json`, `.design-system/evidence/data-table/fit-sweep-after.json`), the `status` states from `registry/cobalt/lib/status.ts`, the two-line phone layout, whose second figure at the row's end joins the meta line when the table is under 340px wide so no row is clipped, under one header line with the row count (`labels.rowCount`, plural through `counted`) and one ghost `sm` sort button at its end that opens a `DropdownMenu` of the sortable columns and the two directions in words (Highest first, Newest first, A to Z), with the column headers kept for the screen reader and no column menus, since the phone row has a fixed shape; that line drawn only with something in it: an empty or failed table with no sort menu keeps the line's place but draws nothing there, no strip and no hairline, and its words stand over it, so a retry's placeholders start where they would have (the body moved 44px down on Retry at 390 before, 0px now, `registry/cobalt/ui/data-table.tsx:2119`), and `phoneSort={false}` with `DataTableSort` in the toolbar above for a table whose toolbar already counts and selects, so a phone has one header line; half of the last row shown when there are more rows than the view, as a first load's placeholders show it, so rows that all fit show whole and nothing scrolls (five of five at 390, against four and a half before), and rows that exactly fill the view keep the height the table has, the placeholders' five and a half after a first load, so the arrivals' three rows in a view of three land 0px taller at 390, against 30px before (`registry/cobalt/ui/data-table.tsx:2011`, `.design-system/evidence/data-table/first-load-landing.json`); a meta line that shows each value whole or not at all, a figure or a date with its label whole or out of sight, and only a first word value ending in an ellipsis while about four characters of it show (`min-w-10`), and out of sight with the rest when fewer would, never a lone letter or a mid-word cut under a fading mask; a code or a rank before the name at its own width, so it never runs into the name, which truncates instead, and as wide as the widest value the column holds, measured in pixels from an unseen copy of it: the longest of every row an array holds or a window has loaded, and for a column of figures the count's own digits, since a rank runs to the count; a rank set to the end, so every name starts at the same place on every row and every page, and a wider value further on moves nothing (the funds' names at x 84 on all 25 rows of pages 1 and 2 at 390, light and dark, and the remote bookings' at x 142 on every row, against 75.5 for ranks 1 to 9 and 83.8 from rank 10 before, when the width was held in characters and counted the cell's 8px of padding, `registry/cobalt/ui/data-table.tsx:1833`); figures, dates and codes never cut, set `dir="ltr"` so a sign stays in front on a right-to-left page, with their column grown to the widest one on screen; an empty value read as None even when the column has a `cell` renderer, and a tags cell with no tags read as None too, on the phone's meta line as well, after its column's name; a value the source did not give, `missing(reason)` from `registry/cobalt/lib/missing.ts`, read as its reason through MissingValue, "Withheld" or "Could not be read", never through the column's `cell`, held whole in a column of figures, which grows to it, and cut with the tooltip in a column of words (`registry/cobalt/ui/data-table.tsx:468`), in `labels.missing` for another language; words with `dir="auto"`, so a name in another script is cut at its own end; a tag strip that counts the tags it cannot show (+6) and lists them all in its title; every width set for 14px text and grown with the reader's text size; logical sides throughout (`start-0`, `border-e`, `text-end`), so the sticky column and the alignment follow a right-to-left page; one tab stop for the body with arrow keys between rows, `labels` with English defaults for every string, formatting through `registry/cobalt/lib/format.ts`; the column menu's move rows say Move earlier and Move later, since the order is a reading order and the arrows already turn on a right-to-left page (base.css), and its rows and keys come from `registry/cobalt/lib/rove.ts`, shared with `FilterList`; a column's `filter` takes the same `FilterList` a `FilterPill` opens, so a header filter and a toolbar filter look alike; with `selection`, a 40px checkbox column pinned before the first column, which pins after it, each box named after its row's main cell, the header box over the loaded rows with its mixed state, Shift with a click for a range, Space on the focused row, and the selected row in the accent's soft fill; `DataTableColumns`, the way back for a hidden column, which shows a column the table's width hides (`hideBelow`) unticked and out of reach, with "Hidden at this width" beside its name (`registry/cobalt/ui/data-table.tsx:2521-2530`); `DataTableToolbar`, which stands the selection bar in the toolbar's own grid cell so the line never changes height (D37); rows that render only when they change (`BodyRow`, a memo over one shared object, `registry/cobalt/ui/data-table.tsx:1515`), so a scroll step renders the three rows it brings in, and headers that render only when their column or its sort changes (a memo over one actions object that reads the host's latest callbacks); one tooltip for every cut cell, flag and tag count (`TruncatedTextGroup`), with no tooltip part in any cell: the group finds the label from the pointer or the keyboard, asks whether it is cut at that moment, and mounts the system tooltip anchored to it (`registry/cobalt/lib/truncated-text.tsx:411`); a label taken out of the page while its tooltip shows, by a scroll or by its own cell, takes the tooltip with it (`registry/cobalt/lib/truncated-text.tsx:142`); Escape with the pointer on the tooltip leaves the label free to open it again (`registry/cobalt/lib/truncated-text.tsx:229`); a cut label inside a host's own tooltip trigger leaves the tooltip to that trigger, so one shows (`registry/cobalt/lib/truncated-text.tsx:87`; checked React and Preact, `.design-system/evidence/perf/tooltip-edges.txt`); the group listens on the page's `document`, so a table drawn into another document, such as an iframe's through a portal, shows no cut-label tooltip; a row link's own words lifted over its cover so a cut name still shows it; rows drawn once the first measurements are in, so a client render lays the page out and reads the box, the labels, the row and header heights and the probes in one pass before the rows are styled, with their final columns, and the server's markup and its hydration draw them at once (`registry/cobalt/ui/data-table.tsx:2102-2109`); first-load placeholders in each column's shape (`Column.skeleton`, `registry/cobalt/ui/data-table.tsx:378-379`), a date column as wide as a wide date before its dates land, and each figure or code column the host has not sized holding a wide value's room from a query that starts with no rows, "$0,000.00" for a column with a `cell`, "000,000" for a count and "AA-00000" for a code, measured in the cells' own font and kept for the query, so its header stands still when the figures land (`registry/cobalt/ui/data-table.tsx:331`, `registry/cobalt/ui/data-table.tsx:1683`); a first load that opens further down (`scrollTop`) drawing its placeholders where the rows will land, so nothing jumps from the top to the target (`registry/cobalt/ui/data-table.tsx:1812`); the rows of a new query kept on screen, dimmed and `inert`, until its first block lands (`registry/cobalt/ui/data-table.tsx:1581`); a notice slot inside the frame (`registry/cobalt/ui/data-table.tsx:2405`) that takes no room, for a block that did not load, a refresh that failed and a load past `SLOW_NOTICE_MS` (`LongWaitNotice`); empty and failure held at the height the table had, with their words in the middle of it, so the box never reads as half empty (an empty phone table's words stand 76px from the top of its 224px box, where they stood at the top with 152px blank under them before, `registry/cobalt/ui/data-table.tsx:1797`, `registry/cobalt/ui/data-table.tsx:2124`, `.design-system/evidence/data-table/empty-centred.json`); a first load whose rows do not fill its guessed height taking theirs on the layout spring, once (`registry/cobalt/ui/data-table.tsx:2037-2039`); a phone row whose block failed drawing no cells, so nothing in it moves as the placeholders around it leave (a layout shift of 0.0008 at 390 before, none now, `registry/cobalt/ui/data-table.tsx:1213`, `.design-system/evidence/data-table/deep-390-shift.json`); the filtered empty state with Clear filters; the capped line after the last row, whose words wrap and whose link stays whole, after them or on a line of its own, so nothing on it is cut (`registry/cobalt/ui/data-table.tsx:2306`); scroll restore through `query`, `scrollTop` and `onScrollChange`; phone pages under a pager (`pageSize`); and the prefetch seam on the row link's `onPointerEnter` and `onFocus` |

## Examples
Sixty funds sorted in memory. Header menus move and hide columns, and the Columns menu above the table brings a hidden one back.

Real uses, 0 call sites (`rg -n "<DataTable\b" app docs/system/examples --glob '!docs/system/examples/data-table/*'`): the showcase chrome lists no records, and the examples folder does not count.

Planned uses, the two examples the system ships (product uses once the first screen lands on the system):
- A list of 60 funds in memory, sorted, reordered and hidden through the header menus, with a row link, `docs/system/examples/data-table/default.tsx:122`.
- 24 bookings selected with checkboxes and acted on from the selection bar, `docs/system/examples/data-table/selection.tsx:184`.
- A list of 10,000 bookings fetched in blocks of 200 through `useRowWindow`, in fill mode with `status`, the count line, a retry and a kept query, `docs/system/examples/data-table/windowed.tsx:77`.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/data-table/default.tsx` | default | Sixty funds sorted in memory; header menus move and hide columns, and Columns brings them back. On a phone the funds flow in the page 25 at a time, under a pager |
| `docs/system/examples/data-table/selection.tsx` | state:selected | Bookings picked with their checkboxes, a range with Shift, and acted on from the bar that takes the toolbar's place |
| Not applicable: default.tsx holds its rows in an array | rows=array | An array of records, sorted by the host |
| `docs/system/examples/data-table/windowed.tsx` | rows=window | Ten thousand rows, fetched 200 at a time as you scroll; a new order keeps the old rows, dimmed, until its first block lands, and coming back to the page finds the rows where you left them |
| Not applicable: default.tsx is as tall as maxRows and scrolls past them | fill=false | Fixed-height mode, 10 rows tall |
| Not applicable: windowed.tsx fills its 480px container | fill=true | Fill mode, the table takes its container's height |
| Not applicable: default.tsx leaves status at idle | status=idle | Rows with nothing in flight |
| `docs/system/examples/data-table/state-pending.tsx` | status=pending | On a first load each column's placeholder takes the shape of its cells, a flag beside a bar, tags, figures at the end, and the rows fade in where they were |
| `docs/system/examples/data-table/state-empty.tsx` | status=success | A successful answer with no rows shows the empty message |
| `docs/system/examples/data-table/state-missing.tsx` | state:missing | A value the filing did not give says why in its cell, Withheld, Could not be read or Does not apply, never None or a dash, and sorts after every figure whichever way the column runs |
| `docs/system/examples/data-table/state-failure.tsx` | status=failure | A failed load with no rows offers one retry |
| Not applicable: default.tsx is the idle state | state:idle | Rows on screen, nothing in flight |
| Not applicable: state-pending.tsx is the pending state with no rows | state:pending | Skeleton rows at the row height |
| `docs/system/examples/data-table/pending-with-rows.tsx` | state:pending-with-rows | Rows already shown stay, dimmed and out of reach after 250ms, while the next week loads; a week that does not load is said inside the table, with a retry |
| `docs/system/examples/data-table/block-failed.tsx` | state:block-failed | The table opens at row 196, where the first block ends; the second block fails on its first try, and a notice over the last row says which rows did not load, with a retry, while the rows above stay |
| `docs/system/examples/data-table/slow-load.tsx` | state:long-wait | The first answer hangs: placeholders hold the rows' places, and after 8 seconds the notice over the last row says the load is taking longer than usual, with a retry that asks again |
| `docs/system/examples/data-table/filtered-empty.tsx` | state:filtered-empty | The Room filter leaves no booking this month, so the table says nothing matches and offers to clear the filters, at the height the rows will take |
| Not applicable: windowed.tsx sorts a window, and the rows of the old order stay until the new one lands | state:stale | The previous query's rows, dimmed and inert |
| Not applicable: the capped line is shown in `docs/system/examples/result-count/capped.tsx`, the count's own page | state:capped | One line after the last row: "End of the first 500 funds", since the count line above says the cap, and the host's link, on a line of its own on a phone |
| Not applicable: default.tsx pages on a phone | state:phone-paged | 25 rows in the page's own scroll, under a pager, every page as tall as a full one |
| Not applicable: state-failure.tsx is the failure state | state:failure | The empty slot as an alert with a retry |
| Not applicable: state-empty.tsx is the empty state | state:empty | The empty slot in the host's words |
| Not applicable: default.tsx is sorted by rank on first render | state:sorted | The sort mark and the inked label in the header, and aria-sort |
| `docs/system/examples/data-table/filtered.tsx` | state:filtered | The Room column is filtered, and its menu holds the same option list as a filter pill, with a count per room |
| Not applicable: overflowing is reached by narrowing any example's frame below its columns | state:overflowing | A thin scrollbar, and a hairline beside the sticky first column once a column slides under it |
| Not applicable: every example takes the phone layout below 640px | state:phone | Two-line rows under the count and one sort menu |
| Not applicable: hover is reached with the pointer on any example | state:hover | The row and its sticky first cell lift together |
| Not applicable: focus-visible is reached with the keyboard on any example | state:focus-visible | The row tint and the link's outline |
| Not applicable: expanded is reached by opening a header's menu on any example | state:expanded | The header keeps its fill while its menu is open |
| `docs/system/examples/data-table/in-section.tsx` | composition:Section | A table in a card under a section heading |
| Not applicable: windowed.tsx is the window in fill mode and default.tsx the array at a fixed height | matrix:rows,fill | The two sources at the two heights |

Example: Sixty funds sorted in memory; header menus move and hide columns, and Columns brings them back. On a phone the funds flow in the page 25 at a time, under a pager (`docs/system/examples/data-table/default.tsx`)

```tsx
import { useMemo, useState } from "react";

import { type Column, DataTable, DataTableColumns, type Sort } from "@/components/cobalt/ui/data-table";
import { Flag } from "@/components/cobalt/ui/flag";
import { change, compactMoney, counted, digitsFor, unitFor } from "@/lib/cobalt/format";

type Fund = {
  rank: number;
  fund: string;
  domicile: string;
  /** The domicile as an ISO 3166-1 code, for its flag. */
  country: string;
  assets: number;
  change: number;
  filed: string;
  strategy: string[];
};

const houses = [
  "Northgate",
  "Halden",
  "Larkspur",
  "Corran",
  "Wexley",
  "Ashbury",
  "Redfern",
  "Calder",
  "Brightwater",
  "Elmstead",
  "Kestrel",
  "Marlow",
];
const lines: [string, string[]][] = [
  ["Credit Opportunities", ["credit", "distressed"]],
  ["Global Equity", ["equity", "global"]],
  ["Municipal Income", ["income", "municipal"]],
  ["Small Cap Value", ["equity", "value"]],
  ["Macro", ["macro"]],
];
const domiciles: [string, string][] = [
  ["United States", "US"],
  ["Luxembourg", "LU"],
  ["Ireland", "IE"],
  ["Cayman Islands", "KY"],
  ["United Kingdom", "GB"],
  ["Jersey", "JE"],
];
const pad = (n: number) => String(n).padStart(2, "0");

// Computed from the index, so the table reads the same on every visit. Ranked by gross assets.
const funds: Fund[] = Array.from({ length: 60 }, (_, i) => {
  const [line, strategy] = lines[(i * 3 + Math.floor(i / 5)) % lines.length]!;
  return {
    rank: i + 1,
    fund: `${houses[(i * 5) % houses.length] ?? ""} ${line}`,
    domicile: domiciles[(i * 7) % domiciles.length]![0],
    country: domiciles[(i * 7) % domiciles.length]![1],
    assets: Math.round(42_000_000_000 / (1 + i * 0.45)),
    change: ((i * 37) % 90) / 10 - 2.5,
    filed: `2026-${pad(1 + ((i * 5) % 9))}-${pad(1 + ((i * 11) % 28))}`,
    strategy,
  };
});

// One unit and one precision for the whole column, so $42.0B sits above $22.1B and the points line up.
const assets = funds.map((f) => f.assets);
const unit = unitFor(assets);
const digits = digitsFor(assets, unit);

const columns: Column<Fund>[] = [
  { key: "rank", label: "Rank", kind: "number", width: 76, phone: "pre" },
  { key: "fund", label: "Fund", kind: "text" },
  {
    key: "domicile",
    label: "Domicile",
    kind: "text",
    hideBelow: 900,
    // The name is written beside the flag, so the flag is not read again.
    cell: (row) => (
      <span className="inline-flex min-w-0 items-center gap-2">
        <Flag code={row.country} decorative />
        <span className="truncate">{row.domicile}</span>
      </span>
    ),
  },
  { key: "assets", label: "Gross assets", kind: "number", cell: (row) => compactMoney(row.assets, unit, "en-US", "USD", { digits }) },
  {
    key: "change",
    label: "1Y change",
    kind: "number",
    cell: (row) => <span className={row.change < 0 ? "text-bad" : row.change > 0 ? "text-good" : "text-muted-foreground"}>{change(row.change)}</span>,
  },
  { key: "filed", label: "Last filed", kind: "date", hideBelow: 1100 },
  { key: "strategy", label: "Strategy", kind: "tags", sortable: false, hideBelow: 720 },
];

const compare = (a: unknown, b: unknown) =>
  typeof a === "number" && typeof b === "number" ? a - b : String(a).localeCompare(String(b));

export default function Example() {
  const [sort, setSort] = useState<Sort>({ key: "rank", dir: "asc" });
  const [order, setOrder] = useState(columns.map((c) => c.key));
  const [hidden, setHidden] = useState<string[]>([]);
  // Every fund is already loaded, so sorting happens here and answers at once.
  const rows = useMemo(() => {
    const key = sort.key as keyof Fund;
    const sign = sort.dir === "asc" ? 1 : -1;
    return [...funds].sort((a, b) => compare(a[key], b[key]) * sign);
  }, [sort]);
  return (
    <div className="w-full overflow-hidden rounded-2xl bg-card">
      {/* On a phone the table's own header line counts the funds beside its sort button, and the
          rows keep one shape, so this bar and its column menu step aside. */}
      <div className="flex items-center justify-between gap-3 px-4 py-3 max-sm:hidden">
        <p className="text-sm text-muted-foreground">
          <span className="font-medium text-foreground tabular-nums">{rows.length}</span> funds
        </p>
        {/* A column hidden from its header menu comes back here. */}
        <DataTableColumns columns={columns} hiddenColumns={hidden} onHiddenColumnsChange={setHidden} locked={["fund"]} />
      </div>
      <DataTable
        label="Funds"
        labels={{ rowCount: (count) => counted(count, { one: "fund", other: "funds" }) }}
        columns={columns}
        rows={rows}
        getRowId={(row) => row.rank}
        sort={sort}
        onSortChange={setSort}
        columnOrder={order}
        onColumnOrderChange={setOrder}
        hiddenColumns={hidden}
        onHiddenColumnsChange={setHidden}
        maxRows={10}
        // A phone pages through the funds in the page's own scroll instead of a box that scrolls inside it;
        // scroll-mt-20 keeps a new page's first rows clear of the page's sticky header.
        pageSize={25}
        className="scroll-mt-20"
        phoneMain="fund"
        rowHref={(row) => `#fund-${row.rank}`}
      />
    </div>
  );
}
```

Example: A table in a card under a section heading (`docs/system/examples/data-table/in-section.tsx`)

```tsx
import { type Column, DataTable } from "@/components/cobalt/ui/data-table";
import { Section } from "@/components/cobalt/ui/section";
import { TextLink } from "@/components/cobalt/ui/text-link";
import { counted, money } from "@/lib/cobalt/format";

type Booking = { ref: string; guest: string; room: string; nights: number; total: number; checkIn: string };

const arrivals: Booking[] = [
  { ref: "BK-48201", guest: "Amara Okafor", room: "Harbour suite", nights: 3, total: 1260, checkIn: "2026-10-19" },
  { ref: "BK-48214", guest: "Lukas Brandt", room: "Garden double", nights: 2, total: 360, checkIn: "2026-10-19" },
  { ref: "BK-48227", guest: "Priya Raman", room: "Loft studio", nights: 5, total: 1050, checkIn: "2026-10-20" },
  { ref: "BK-48233", guest: "Tomás Ibarra", room: "Family room", nights: 4, total: 960, checkIn: "2026-10-22" },
  { ref: "BK-48240", guest: "Hanna Lindqvist", room: "Corner king", nights: 1, total: 260, checkIn: "2026-10-23" },
];

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text" },
  { key: "room", label: "Room", kind: "text" },
  { key: "nights", label: "Nights", kind: "number", hideBelow: 560 },
  { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
  { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 700 },
];

export default function Example() {
  return (
    <Section
      className="w-full"
      id="example-section-arrivals"
      heading="Arriving this week"
      action={
        <TextLink href="#arrivals" className="text-sm">
          See all
        </TextLink>
      }
    >
      <div className="w-full overflow-hidden rounded-2xl bg-card">
        <DataTable
          label="Arriving this week"
          labels={{ rowCount: (count) => counted(count, { one: "arrival", other: "arrivals" }) }}
          columns={columns}
          rows={arrivals}
          getRowId={(row) => row.ref}
          maxRows={5}
          phoneMain="guest"
          rowHref={(row) => `#${row.ref.toLowerCase()}`}
        />
      </div>
    </Section>
  );
}
```

## Variants

### rows
- `array`: the records are in memory and the host sorts and filters them. Used at 1 planned use, the funds list.
- `window`: a `Rows` object from `useRowWindow`, with `onRangeChange` so the table can ask for blocks. Used at 1 planned use, the bookings list.

Example: Ten thousand rows, fetched 200 at a time as you scroll; a new order keeps the old rows, dimmed, until its first block lands, and coming back to the page finds the rows where you left them (`docs/system/examples/data-table/windowed.tsx`)

```tsx
import { useState } from "react";

import { type Column, DataTable, type Sort } from "@/components/cobalt/ui/data-table";
import { ResultCount } from "@/components/cobalt/ui/result-count";
import { money } from "@/lib/cobalt/format";
import { useRowWindow } from "@/lib/cobalt/row-window";

type Booking = { ref: string; guest: string; room: string; nights: number; total: number; checkIn: string };

const TOTAL = 10_000;
const guests = [
  "Amara Okafor",
  "Lukas Brandt",
  "Priya Raman",
  "Tomás Ibarra",
  "Hanna Lindqvist",
  "Kenji Morita",
  "Sofia Marchetti",
  "Daniel Mensah",
  "Elena Petrova",
  "Omar Haddad",
  "Clara Dubois",
  "Mateo Rojas",
];
const rooms: [string, number][] = [
  ["Garden double", 180],
  ["Harbour suite", 420],
  ["Courtyard twin", 150],
  ["Loft studio", 210],
  ["Corner king", 260],
  ["Family room", 240],
];
const pad = (n: number) => String(n).padStart(2, "0");

// Every booking is computed from its index, so the server stores nothing.
const bookingAt = (i: number, dir: Sort["dir"]): Booking => {
  const n = dir === "asc" ? i : TOTAL - 1 - i;
  const [room, rate] = rooms[(n * 5) % rooms.length]!;
  const nights = 1 + ((n * 3) % 6);
  return {
    ref: `BK-${38_201 + n}`,
    guest: guests[(n * 7) % guests.length] ?? "",
    room,
    nights,
    total: rate * nights,
    checkIn: `20${24 + Math.floor(n / 4000)}-${pad(1 + (Math.floor(n / 334) % 12))}-${pad(1 + (n % 28))}`,
  };
};

// Stands in for your API: one page of bookings after 600ms. It fails while the browser is offline or
// the address has ?network=offline.
const fetchPage = (start: number, count: number, dir: Sort["dir"], signal: AbortSignal) =>
  new Promise<{ rows: Booking[]; total: number }>((resolve, reject) => {
    const timer = setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("The server did not answer"));
      else resolve({ rows: Array.from({ length: count }, (_, k) => bookingAt(start + k, dir)), total: TOTAL });
    }, 600);
    signal.addEventListener("abort", () => clearTimeout(timer));
  });

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text", sortable: false },
  { key: "room", label: "Room", kind: "text", sortable: false },
  { key: "nights", label: "Nights", kind: "number", sortable: false, hideBelow: 560 },
  { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total), sortable: false },
  { key: "checkIn", label: "Check-in", kind: "date", sortable: false, hideBelow: 700 },
];

export default function Example() {
  const [sort, setSort] = useState<Sort>({ key: "ref", dir: "asc" });
  // Sorting ten thousand rows is the server's work, so a new order is a new fetch. Each order is
  // kept under its own key, so Back to this page shows the same rows at the same place, unasked.
  const bookings = useRowWindow<Booking>(
    (start, count, signal) => fetchPage(start, count, sort.dir, signal),
    [sort.dir],
    { retain: `bookings:${sort.dir}` },
  );
  return (
    <div className="flex w-full flex-col gap-3">
      <ResultCount
        count={bookings.total}
        noun={{ one: "booking", other: "bookings" }}
        status={bookings.countStatus}
        className="min-h-(--control-sm)"
      />
      <div className="h-120 overflow-hidden rounded-2xl bg-card">
        <DataTable
          label="Bookings"
          labels={{ nothingToShow: "No bookings", notLoaded: "The bookings did not load" }}
          columns={columns}
          rows={bookings.rows}
          getRowId={(row) => row.ref}
          fill
          sort={sort}
          onSortChange={setSort}
          onRangeChange={bookings.onRangeChange}
          query={bookings.query}
          scrollTop={bookings.scrollTop}
          onScrollChange={bookings.onScrollChange}
          status={bookings.status}
          onRetry={bookings.retry}
          attempt={bookings.attempt}
          phoneMain="guest"
          // The line above counts the bookings, so the phone's header line does not count them again.
          phoneCount={false}
        />
      </div>
    </div>
  );
}
```

### fill
- `false`: fixed-height mode, as tall as `maxRows` rows (10 by default, 6 on a phone) and scrolling past them. Used at 1 planned use.
- `true`: fill mode, the table takes its container's height and wins over `maxRows`. Used at 1 planned use.

### status
- `idle`: rows on screen with nothing in flight; 0 rows shows the empty slot. Used at 1 planned use, the funds list.
- `pending`: placeholder rows in each column's shape when there are none, the previous rows dimmed and inert after 250ms when they answer another query, and the loaded rows as they are when only a block further down is on its way. Used at 1 planned use, through `useRowWindow`.
- `success`: the rows, or the empty slot when there are none. Used at 1 planned use, through `useRowWindow`.
- `failure`: the empty slot as an alert with a retry when there are no rows; when there are, they stay and the notice inside the frame says which rows did not load, or that the new rows did not, with the retry. Used at 1 planned use, through `useRowWindow`.

Example: On a first load each column's placeholder takes the shape of its cells, a flag beside a bar, tags, figures at the end, and the rows fade in where they were (`docs/system/examples/data-table/state-pending.tsx`)

```tsx
import { useCallback, useEffect, useRef, useState } from "react";

import { type Column, DataTable } from "@/components/cobalt/ui/data-table";
import { Flag, countryName } from "@/components/cobalt/ui/flag";
import { counted, money } from "@/lib/cobalt/format";
import type { Status } from "@/lib/cobalt/status";

type Booking = {
  ref: string;
  guest: string;
  country: string;
  room: string;
  total: number;
  payment: string[];
  checkIn: string;
};

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text" },
  {
    key: "country",
    label: "From",
    kind: "text",
    // The country's name is written beside its flag, so the flag is not read again.
    value: (row) => countryName(row.country),
    cell: (row) => (
      <span className="inline-flex min-w-0 items-center gap-2">
        <Flag code={row.country} decorative />
        <span className="truncate">{countryName(row.country)}</span>
      </span>
    ),
    skeleton: "flag",
  },
  { key: "room", label: "Room", kind: "text", hideBelow: 860 },
  { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
  { key: "payment", label: "Payment", kind: "tags", sortable: false, width: 120, hideBelow: 720 },
  { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 560 },
];

// As many arrivals as the table's view of six, so loading and loaded are the same height: six rows
// on a desktop, and five and a half on a phone, the sign that the list scrolls.
const arrivals: Booking[] = [
  { ref: "BK-48201", guest: "Amara Okafor", country: "NG", room: "Harbour suite", total: 1260, payment: ["paid"], checkIn: "2026-10-19" },
  { ref: "BK-48214", guest: "Lukas Brandt", country: "DE", room: "Garden double", total: 360, payment: ["deposit"], checkIn: "2026-10-19" },
  { ref: "BK-48227", guest: "Priya Raman", country: "IN", room: "Loft studio", total: 1050, payment: ["paid"], checkIn: "2026-10-20" },
  { ref: "BK-48233", guest: "Tomás Ibarra", country: "AR", room: "Family room", total: 960, payment: ["deposit"], checkIn: "2026-10-22" },
  { ref: "BK-48240", guest: "Hanna Lindqvist", country: "SE", room: "Corner king", total: 260, payment: ["paid"], checkIn: "2026-10-23" },
  { ref: "BK-48252", guest: "Kenji Morita", country: "JP", room: "Courtyard twin", total: 300, payment: ["on arrival"], checkIn: "2026-10-24" },
];

// Stands in for your API call. It answers after 1200ms, and fails while the browser is offline or the
// address has ?network=offline.
const request = () =>
  new Promise<Booking[]>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve(arrivals);
    }, 1200),
  );

export default function Example() {
  const [rows, setRows] = useState<Booking[]>([]);
  const [status, setStatus] = useState<Status>("pending");
  const latest = useRef(0);
  // A first load starts from nothing: no rows, so the table shows placeholder rows until the answer.
  // A retry after a failure is a first load too, since no rows ever arrived.
  const load = useCallback(() => {
    const id = ++latest.current;
    setStatus("pending");
    request().then(
      (next) => {
        if (id !== latest.current) return;
        setRows(next);
        setStatus("success");
      },
      () => {
        if (id === latest.current) setStatus("failure");
      },
    );
  }, []);
  useEffect(load, [load]);
  return (
    <div className="w-full overflow-hidden rounded-2xl bg-card">
      <DataTable
        label="Arrivals"
        labels={{
          notLoaded: "The arrivals did not load",
          rowCount: (count) => counted(count, { one: "arrival", other: "arrivals" }),
        }}
        columns={columns}
        rows={rows}
        getRowId={(row) => row.ref}
        status={status}
        onRetry={load}
        maxRows={6}
        phoneMain="guest"
      />
    </div>
  );
}
```

Example: A successful answer with no rows shows the empty message (`docs/system/examples/data-table/state-empty.tsx`)

```tsx
import { type Column, DataTable } from "@/components/cobalt/ui/data-table";

type Booking = { ref: string; guest: string; room: string; nights: number; total: number; checkIn: string };

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text" },
  { key: "room", label: "Room", kind: "text" },
  { key: "nights", label: "Nights", kind: "number", hideBelow: 560 },
  { key: "total", label: "Total", kind: "number" },
  { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 700 },
];

export default function Example() {
  return (
    <div className="w-full overflow-hidden rounded-2xl bg-card">
      <DataTable
        label="Arrivals on Dec 24"
        labels={{ nothingToShow: "No arrivals on Dec 24" }}
        columns={columns}
        rows={[]}
        status="success"
        maxRows={6}
        phoneMain="guest"
      />
    </div>
  );
}
```

Example: A failed load with no rows offers one retry (`docs/system/examples/data-table/state-failure.tsx`)

```tsx
import { useState } from "react";

import { type Column, DataTable } from "@/components/cobalt/ui/data-table";
import { counted, money } from "@/lib/cobalt/format";
import type { Status } from "@/lib/cobalt/status";

type Booking = { ref: string; guest: string; room: string; nights: number; total: number; checkIn: string };

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text" },
  { key: "room", label: "Room", kind: "text" },
  { key: "nights", label: "Nights", kind: "number", hideBelow: 560 },
  { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
  { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 700 },
];

// What the retry brings back.
const arrivals: Booking[] = [
  { ref: "BK-48201", guest: "Amara Okafor", room: "Harbour suite", nights: 3, total: 1260, checkIn: "2026-10-19" },
  { ref: "BK-48214", guest: "Lukas Brandt", room: "Garden double", nights: 2, total: 360, checkIn: "2026-10-19" },
  { ref: "BK-48227", guest: "Priya Raman", room: "Loft studio", nights: 5, total: 1050, checkIn: "2026-10-20" },
];

// Stands in for your API call. It answers after 900ms, and fails while the browser is offline or the
// address has ?network=offline.
const request = () =>
  new Promise<Booking[]>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve(arrivals);
    }, 900),
  );

export default function Example() {
  // The first load has already failed, so the table opens on the failure. Retry asks again for real.
  const [status, setStatus] = useState<Status>("failure");
  const [rows, setRows] = useState<Booking[]>([]);
  const [tries, setTries] = useState(0);
  const retry = () => {
    setStatus("pending");
    setTries((n) => n + 1);
    request().then(
      (next) => {
        setRows(next);
        setStatus("success");
      },
      () => setStatus("failure"),
    );
  };
  return (
    <div className="flex w-full flex-col gap-3">
      <p className="text-sm text-muted-foreground">Arrivals for Monday and Tuesday</p>
      <div className="overflow-hidden rounded-2xl bg-card">
        <DataTable
          label="Arrivals"
          // The failure is said once, in the place the rows would be.
          labels={{
            nothingToShow: "No arrivals to show",
            notLoaded: tries === 0 ? "The arrivals did not load" : "Still no answer. Check your connection",
            rowCount: (count) => counted(count, { one: "arrival", other: "arrivals" }),
          }}
          columns={columns}
          rows={rows}
          getRowId={(row) => row.ref}
          status={status}
          onRetry={retry}
          maxRows={3}
          phoneMain="guest"
        />
      </div>
    </div>
  );
}
```

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| idle | render with rows | scroll, sort through a header menu, open a row | the rows and the header | test |
| pending | `status="pending"` with 0 rows | wait | nothing for the first 250ms, then placeholders in each column's shape (`Column.skeleton`, from `kind` when left out: a bar for words, a shorter one at the end for figures, a date's width, one or two tag shapes, or a flag or a round picture beside a bar), each one line of the cell's own text tall, measured 20px against 20px text at 1440 and 24px against 24px at 390, so a row is 40px loading and loaded (60px on a phone); their widths vary by row and hold on every render; as many rows as the box: the view in fill mode, the last height in fixed-height mode, a page on a phone page; once shown they stay at least 400ms (`useSlowWait`), then the rows fade in over `--t-fade`; `aria-busy`, `aria-rowcount="-1"` while the count is unknown, the "Loading" row for a screen reader; a first load that opens further down (`scrollTop`) asks for the rows there and draws its placeholders there, with the room above them, so the rows land in place: the bookings that open at row 196 stood at 7,800px in every frame at 1440 and at row 195 at 390, against the top and then 7,800px before (`.design-system/evidence/data-table/first-load-held.json`); a figure column the host has not sized holds a wide figure's room, so the headers stand still when the figures land: every header of the arrivals at the same x and width in every frame at 1440, light, dark and Pill corners, against the Guest header widening 22px, the five headers after it sliding by up to 22px and a layout shift of 0.0002 before, in the frame the totals landed (the same file); rows fewer than the guessed height, such as four funds in a guess of six, take theirs on the layout spring (`--t-layout`, 450ms, on `--curve-layout`), once, measured 280 to 200px over 9 frames at 1440 and 374 to 284px at 390, light, dark and Pill corners, against one frame before, and what follows the table moves with it (`.design-system/evidence/data-table/first-load-landing.json`) | test |
| stale | the query changed (`query`), and `rows` are the previous query's (`rows.stale`, a window's stand-in), or an array is reloading | read the rows that are there; nothing is pressable once dimmed | the rows at 55 percent and `inert` after 250ms, at least 400ms, the table back at the first row; the new rows replace them in place, measured 0px of shift and the old rows on screen in every frame of a sort at 1440 (they went to 10 blank placeholder rows for 650ms before) | test |
| block-failed | a block in or beside the view failed (`rows.failures`), `status="failure"` | read the rows above, retry | its rows draw nothing, and the notice over the last row in view, the header's height with its hairline, says "Rows 201 to 400 did not load" (`labels.rowsNotLoaded`) with Retry; it takes no room, the rows gain one row so the last can scroll above it, and the frame does not move (measured 0px at 1440 and 390; Fund Census inserts a line above its grid and moves the page 54px); before, the rows of a failed block kept pulsing placeholders and nothing said they would not come | test |
| long-wait | `status="pending"` past `SLOW_NOTICE_MS` (8 seconds), first load or not | retry, which cancels the request still out and sends it again | `LongWaitNotice` in the notice slot: "This is taking longer than usual." with Retry, faded in over `--t-fade`, gone the moment the answer lands; the clock starts over with each query and each `attempt` | screenshot |
| filtered-empty | 0 rows, and a column's `filtered` or the table's `filtered` is set | clear the filters | "Nothing matches these filters" (`labels.noMatches`) with Clear filters when `onClearFilters` is given, `reason="filtered"`, at the height the rows will take | test |
| capped | `rows.total` above `rows.n`: the server hands out fewer rows than match | read the rows it hands out, follow the host's link | one line after the last row, "Showing the first 500 of 12,400 rows" (`labels.capped`) and the host's `capped` node; the words wrap and the link stays whole, after them on one 40px line at 1440 and on a line of its own inside the 60px row at 390, where the words were cut to "Showing the first 500 o…" and the link broke over two lines before | test |
| phone-paged | a phone and `pageSize` | page with the pager | `pageSize` rows in the page's own scroll, no box scrolling inside it, Pagination under them; every page a full page tall, so the pager never moves; a page change brings the table's top into view | test |
| pending-with-rows | `status="pending"` with rows on screen that are current (`rows.stale === false`): a window fetching a block further down | read and use the rows | the loaded rows as they are, placeholders in the rows still on their way, `aria-busy` | test |
| failure | `status="failure"` with 0 rows | retry | the empty slot as an alert with "The rows did not load" (`labels.notLoaded`) and "Retry", aligned to the start, in the middle of the room the table holds; with rows on screen, the rows stay and the notice says "The new rows did not load" (`labels.notRefreshed`) with Retry; in fixed-height mode the table keeps the height it last had, at least three rows, and grows only if the slot needs more | test |
| empty | `status` idle or success with 0 rows | the host's `empty` action, if any | "Nothing to show" in the empty slot, at the height the table last had (three rows when it opens empty, a full view when it opens on a load or filtered), its words in the middle of it | test |
| sorted | `sort` names a column | change or reverse the sort through the header menu | the label in the ink and the sort mark 4px beside it (two stacked chevrons, the sorted direction in the ink and the other faint), before the label on a figure column and after it on a word column, `aria-sort`; on a phone the sort button at the end of the header line reads the sorted column and its mark, so a change of width moves nothing, and the hidden column headers keep `aria-sort` | test |
| filtered | a column's `filtered` is true | open the menu and change the filter | the filter mark in the header, with "Filtered" for a screen reader | screenshot |
| overflowing | more columns lie past the right edge | scroll sideways with a trackpad, the wheel with Shift, the scrollbar, or the arrow keys | the thin scrollbar where the platform draws one, and a 1px `--border` line on the sticky first column's right edge; only once the columns' floors pass the box by more than the columns of words can give, so a table a few pixels too wide fits instead | screenshot |
| phone | viewport below 640px | change the sort through the one menu, open a row | two-line rows 60px tall under a 44px header line with the count and the sort button; on a first load the line is already there with a bar where the count will be, so the rows arriving move nothing (they shrank the example 44px before); an empty or failed table with no sort menu keeps the line's 44px, drawn as nothing, with its words centred over the whole box; half of the last row shows when more rows wait below, and stays when rows that exactly fill the view land on a first load | screenshot |
| missing | a cell's value is `missing(reason)` | read why the value is not there | the reason's words in the label's ink through MissingValue, "Withheld", "Not reported", "Could not be read" or "Does not apply", on a desktop row, in a phone row's figure and, after the column's name, on its meta line | test |
| hover | pointer over a row, under `(hover: hover)` | open the row | pointer only, colour change: the row and its sticky first cell lift together with `--hover`, with no gap between rows | by hand |
| focus-visible | keyboard focus on the row or its link | open with Enter, move with the arrows | the row tint and the link's 2px outline | by hand |
| expanded | a header's menu is open | sort, filter, move or hide the column | the header keeps its hover fill while open, `aria-expanded`, the menu below its start edge | by hand |
| selected | a row's key is in `selection` | clear it with its box or Space, extend a range with Shift and a click, act on the selection from the toolbar | the checked box and the row in `--primary-soft`, its pinned cells too; the header box mixed while some are selected and checked when every loaded row is; the toolbar line reads "3 selected" in the same height (`DataTableToolbar`) | test |

Example: Bookings picked with their checkboxes, a range with Shift, and acted on from the bar that takes the toolbar's place (`docs/system/examples/data-table/selection.tsx`)

```tsx
import { useMemo, useState } from "react";
import { toast } from "sonner";

import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogError,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/cobalt/ui/alert-dialog";
import { Button } from "@/components/cobalt/ui/button";
import {
  type Column,
  DataTable,
  DataTableColumns,
  DataTableSort,
  DataTableToolbar,
  type RowKey,
  type Sort,
} from "@/components/cobalt/ui/data-table";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { counted, money } from "@/lib/cobalt/format";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call. It answers after 900ms, and fails while the browser is offline or the
// address has ?network=offline.
const request = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve();
    }, 900),
  );

type Booking = { ref: string; guest: string; room: string; nights: number; total: number; checkIn: string };

const guests = [
  "Amara Okafor",
  "Lukas Brandt",
  "Priya Raman",
  "Tomás Ibarra",
  "Hanna Lindqvist",
  "Kenji Morita",
  "Sofia Marchetti",
  "Daniel Mensah",
  "Elena Petrova",
  "Clara Dubois",
  "Mateo Rojas",
  "Grace Whitfield",
];
const rooms: [string, number][] = [
  ["Garden double", 180],
  ["Harbour suite", 420],
  ["Courtyard twin", 150],
  ["Loft studio", 210],
];
const pad = (n: number) => String(n).padStart(2, "0");

// Computed from the index, so the table reads the same on every visit.
const all: Booking[] = Array.from({ length: 24 }, (_, i) => {
  const [room, rate] = rooms[(i * 3) % rooms.length]!;
  const nights = 1 + ((i * 5) % 6);
  return {
    ref: `BK-${48_201 + i}`,
    guest: guests[(i * 7 + Math.floor(i / 4)) % guests.length] ?? "",
    room,
    nights,
    total: rate * nights,
    checkIn: `2026-11-${pad(1 + ((i * 2) % 28))}`,
  };
});

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text" },
  { key: "room", label: "Room", kind: "text", hideBelow: 620 },
  { key: "nights", label: "Nights", kind: "number", hideBelow: 720 },
  { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
  { key: "checkIn", label: "Check-in", kind: "date" },
];

const bookingsWord = (n: number) => counted(n, { one: "booking", other: "bookings" });

export default function Example() {
  const [bookings, setBookings] = useState(all);
  const [sort, setSort] = useState<Sort>({ key: "checkIn", dir: "asc" });
  const [hidden, setHidden] = useState<string[]>([]);
  const [selection, setSelection] = useState<Set<RowKey>>(new Set());
  const [asking, setAsking] = useState(false);
  const rows = useMemo(() => {
    const key = sort.key as keyof Booking;
    const sign = sort.dir === "asc" ? 1 : -1;
    return [...bookings].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0) * sign);
  }, [bookings, sort]);

  // Each action reaches the server, so it reports on its own button (D39).
  const remind = useAction(request);
  const cancel = useAction(async () => {
    await request();
    const gone = selection.size;
    setBookings((list) => list.filter((row) => !selection.has(row.ref)));
    setSelection(new Set());
    setAsking(false);
    // The dialog that held the result has closed, so a toast says it happened.
    toast(`${bookingsWord(gone)} cancelled`, { description: "Each guest gets an email with the refund." });
  });

  return (
    <div className="w-full overflow-hidden rounded-2xl bg-card">
      <div className="px-4 py-3">
      <DataTableToolbar
        selected={selection.size}
        onClearSelection={() => setSelection(new Set())}
        actions={
          <>
            <StateButton
              variant="ghost"
              size="sm"
              status={remind.status}
              pendingLabel="Sending"
              successLabel="Sent"
              failureLabel="Not sent"
              onClick={() => void remind.run()}
            >
              Send reminders
            </StateButton>
            {/* Cancelling cannot be undone, so it asks first. */}
            <AlertDialog
              open={asking}
              onOpenChange={(next) => {
                setAsking(next);
                if (!next) cancel.reset();
              }}
            >
              <AlertDialogTrigger render={<Button variant="destructive" size="sm" />}>Cancel bookings</AlertDialogTrigger>
              <AlertDialogContent status={cancel.status}>
                <AlertDialogHeader>
                  <AlertDialogTitle>Cancel {bookingsWord(selection.size)}?</AlertDialogTitle>
                  <AlertDialogDescription>
                    The rooms go back on sale and each guest is refunded. This cannot be undone.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  {cancel.error !== null && (
                    <AlertDialogError>Nothing was cancelled. Check your connection and try again.</AlertDialogError>
                  )}
                  <AlertDialogCancel>Keep bookings</AlertDialogCancel>
                  <StateButton
                    variant="destructive"
                    status={cancel.status}
                    pendingLabel="Cancelling"
                    failureLabel="Not cancelled"
                    onClick={() => void cancel.run()}
                  >
                    Cancel bookings
                  </StateButton>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </>
        }
      >
        <p tabIndex={-1} className="text-sm text-muted-foreground outline-none">
          <span className="font-medium text-foreground tabular-nums">{rows.length}</span> November bookings
        </p>
        {/* A phone's rows have one shape, so the Columns menu gives way to the sort menu: one header line. */}
        <DataTableColumns
          columns={columns}
          hiddenColumns={hidden}
          onHiddenColumnsChange={setHidden}
          locked={["ref"]}
          className="max-sm:hidden"
        />
        <DataTableSort columns={columns} sort={sort} onSortChange={setSort} className="sm:hidden" />
      </DataTableToolbar>
      </div>
      <DataTable
        label="November bookings"
        columns={columns}
        rows={rows}
        getRowId={(row) => row.ref}
        selection={selection}
        onSelectionChange={setSelection}
        sort={sort}
        onSortChange={setSort}
        hiddenColumns={hidden}
        onHiddenColumnsChange={setHidden}
        maxRows={8}
        // The guest names the row on a phone; the reference and the total share the line under it.
        phoneMain="guest"
        phoneCount={false}
        phoneSort={false}
      />
    </div>
  );
}
```

Example: A value the filing did not give says why in its cell, Withheld, Could not be read or Does not apply, never None or a dash, and sorts after every figure whichever way the column runs (`docs/system/examples/data-table/state-missing.tsx`)

```tsx
import { useMemo, useState } from "react";

import { type Column, DataTable, type Sort } from "@/components/cobalt/ui/data-table";
import { knownOr } from "@/components/cobalt/ui/missing-value";
import { change, compactMoney, counted, digitsFor, unitFor } from "@/lib/cobalt/format";
import { compareKnown, isMissing, missing, type Known } from "@/lib/cobalt/missing";

type Fund = { id: number; fund: string; adviser: Known<string>; assets: Known<number>; growth: Known<number> };

// Inert sample data: invented funds as their filings report them. A field the filing did not give
// holds its reason instead of null.
const funds: Fund[] = [
  { id: 1, fund: "Northgate Global Equity Fund", adviser: "Northgate Capital", assets: 4_200_000_000, growth: 3.1 },
  { id: 2, fund: "Pryor Dean Real Assets Trust", adviser: "Pryor Dean Partners", assets: missing("withheld"), growth: -1.4 },
  { id: 3, fund: "Calder Credit Opportunities Fund II", adviser: missing("unreadable"), assets: 860_000_000, growth: 0.8 },
  // Launched this year, so a change over one year does not apply.
  { id: 4, fund: "Kestrel Short Duration Fund", adviser: "Kestrel Advisers", assets: 120_000_000, growth: missing("not-applicable") },
  { id: 5, fund: "Hollis Crane Municipal Income Trust", adviser: "Hollis Crane", assets: missing("not-reported"), growth: 1.9 },
  { id: 6, fund: "Larkspur Small Cap Value Portfolio", adviser: "Larkspur Capital", assets: 2_400_000_000, growth: 5.6 },
];

// One unit and one precision for the figures the filings gave.
const sizes = funds.flatMap((f) => (isMissing(f.assets) ? [] : [f.assets]));
const unit = unitFor(sizes);
const digits = digitsFor(sizes, unit);

const columns: Column<Fund>[] = [
  { key: "fund", label: "Fund", kind: "text" },
  { key: "adviser", label: "Adviser", kind: "text" },
  // The table says a missing value's reason itself and never calls `cell` for it; `knownOr` only
  // narrows the type for the renderer.
  {
    key: "assets",
    label: "Gross assets",
    kind: "number",
    cell: (row) => knownOr(row.assets, (v) => compactMoney(v, unit, "en-US", "USD", { digits })),
  },
  {
    key: "growth",
    label: "1Y change",
    kind: "number",
    // A phone's second line holds the adviser beside the size; the change waits for a wider screen.
    phone: "hide",
    cell: (row) => knownOr(row.growth, (v) => <span className={v < 0 ? "text-bad" : v > 0 ? "text-good" : "text-muted-foreground"}>{change(v)}</span>),
  },
];

const byText = (a: string, b: string) => a.localeCompare(b);
const byNumber = (a: number, b: number) => a - b;

export default function Example() {
  const [sort, setSort] = useState<Sort>({ key: "assets", dir: "desc" });
  // Every missing value sorts after every figure, whichever way the column runs.
  const rows = useMemo(
    () =>
      [...funds].sort((a, b) =>
        sort.key === "assets" || sort.key === "growth"
          ? compareKnown(a[sort.key], b[sort.key], byNumber, sort.dir)
          : compareKnown(a[sort.key as "fund" | "adviser"], b[sort.key as "fund" | "adviser"], byText, sort.dir),
      ),
    [sort],
  );
  return (
    <div className="w-full overflow-hidden rounded-2xl bg-card">
      <DataTable
        label="Funds"
        labels={{ rowCount: (count) => counted(count, { one: "fund", other: "funds" }) }}
        columns={columns}
        rows={rows}
        getRowId={(row) => row.id}
        sort={sort}
        onSortChange={setSort}
        maxRows={6}
        phoneMain="fund"
      />
    </div>
  );
}
```

Example: Rows already shown stay, dimmed and out of reach after 250ms, while the next week loads; a week that does not load is said inside the table, with a retry (`docs/system/examples/data-table/pending-with-rows.tsx`)

```tsx
import { useRef, useState } from "react";

import { type Column, DataTable } from "@/components/cobalt/ui/data-table";
import { SegmentedControl, type Segment } from "@/components/cobalt/ui/segmented-control";
import { counted, money } from "@/lib/cobalt/format";
import type { Status } from "@/lib/cobalt/status";

type Booking = { ref: string; guest: string; room: string; nights: number; total: number; checkIn: string };
type Week = "this" | "next";

const weeks: readonly Segment<Week>[] = [
  { value: "this", label: "This week" },
  { value: "next", label: "Next week" },
];
const guests = [
  "Amara Okafor",
  "Lukas Brandt",
  "Priya Raman",
  "Tomás Ibarra",
  "Hanna Lindqvist",
  "Kenji Morita",
  "Sofia Marchetti",
  "Daniel Mensah",
  "Elena Petrova",
  "Omar Haddad",
  "Clara Dubois",
  "Mateo Rojas",
];
const rooms: [string, number][] = [
  ["Garden double", 180],
  ["Harbour suite", 420],
  ["Courtyard twin", 150],
  ["Loft studio", 210],
  ["Corner king", 260],
  ["Family room", 240],
];

// The arrivals of one week, computed from the index so each week reads the same on every visit.
const arrivalsFor = (week: Week): Booking[] =>
  Array.from({ length: 12 }, (_, k) => {
    const i = week === "this" ? k : k + 12;
    const [room, rate] = rooms[(i * 5) % rooms.length]!;
    const nights = 1 + ((i * 3) % 6);
    return {
      ref: `BK-${48_201 + i * 3}`,
      guest: guests[(i * 7) % guests.length] ?? "",
      room,
      nights,
      total: rate * nights,
      checkIn: `2026-10-${19 + (week === "this" ? 0 : 7) + Math.floor(k / 3)}`,
    };
  });

// Stands in for your API call. It answers after 900ms, and fails while the browser is offline or the
// address has ?network=offline.
const request = (week: Week) =>
  new Promise<Booking[]>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve(arrivalsFor(week));
    }, 900),
  );

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text" },
  { key: "room", label: "Room", kind: "text" },
  { key: "nights", label: "Nights", kind: "number", hideBelow: 560 },
  { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
  { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 700 },
];

export default function Example() {
  // The week on screen, and the week asked for: the choice moves at once, the rows when they arrive.
  const [shown, setShown] = useState<Week>("this");
  const [asked, setAsked] = useState<Week>("this");
  const [rows, setRows] = useState(() => arrivalsFor("this"));
  const [status, setStatus] = useState<Status>("idle");
  const [failed, setFailed] = useState<Week | null>(null);
  const latest = useRef(0);
  const choose = (week: Week) => {
    setAsked(week);
    setFailed(null);
    setStatus("pending");
    const id = ++latest.current;
    request(week).then(
      (next) => {
        if (id !== latest.current) return;
        setRows(next);
        setShown(week);
        setStatus("success");
      },
      () => {
        if (id !== latest.current) return;
        // The rows on screen stay, and the choice goes back to the week they belong to.
        setAsked(shown);
        setFailed(week);
        setStatus("failure");
      },
    );
  };
  return (
    <div className="flex w-full flex-col gap-3">
      <SegmentedControl label="Arrivals" value={asked} options={weeks} onChange={choose} />
      <div className="overflow-hidden rounded-2xl bg-card">
        <DataTable
          label="Arrivals"
          // The rows on screen stay where they are when a week does not load; the notice over the
          // last row says which week, and its retry asks for it again.
          labels={{
            notRefreshed: `${failed === "next" ? "Next" : "This"} week did not load`,
            rowCount: (count) => counted(count, { one: "arrival", other: "arrivals" }),
          }}
          columns={columns}
          rows={rows}
          getRowId={(row) => row.ref}
          status={status}
          onRetry={() => failed !== null && choose(failed)}
          maxRows={6}
          phoneMain="guest"
        />
      </div>
    </div>
  );
}
```

Example: The table opens at row 196, where the first block ends; the second block fails on its first try, and a notice over the last row says which rows did not load, with a retry, while the rows above stay (`docs/system/examples/data-table/block-failed.tsx`)

```tsx
import { type Column, DataTable } from "@/components/cobalt/ui/data-table";
import { ResultCount } from "@/components/cobalt/ui/result-count";
import { money } from "@/lib/cobalt/format";
import { useRowWindow } from "@/lib/cobalt/row-window";
import { usePhone } from "@/lib/cobalt/use-media-query";

type Booking = { ref: string; guest: string; room: string; total: number; checkIn: string };

const TOTAL = 2_400;
const guests = ["Amara Okafor", "Lukas Brandt", "Priya Raman", "Tomás Ibarra", "Hanna Lindqvist", "Kenji Morita"];
const rooms: [string, number][] = [
  ["Garden double", 180],
  ["Harbour suite", 420],
  ["Courtyard twin", 150],
  ["Loft studio", 210],
];
const pad = (n: number) => String(n).padStart(2, "0");

const bookingAt = (i: number): Booking => {
  const [room, rate] = rooms[(i * 3) % rooms.length]!;
  return {
    ref: `BK-${52_001 + i}`,
    guest: guests[(i * 5) % guests.length] ?? "",
    room,
    total: rate * (1 + (i % 4)),
    checkIn: `2026-${pad(1 + (Math.floor(i / 200) % 12))}-${pad(1 + (i % 28))}`,
  };
};

// Stands in for your API: one block after 500ms. The block from row 201 fails the first time it is
// asked for, as a busy server does, and answers when asked again.
let refused = false;
const fetchPage = (start: number, count: number, signal: AbortSignal) =>
  new Promise<{ rows: Booking[]; total: number }>((resolve, reject) => {
    const timer = setTimeout(() => {
      if (start === 200 && !refused) {
        refused = true;
        reject(new Error("The server is busy"));
        return;
      }
      resolve({ rows: Array.from({ length: Math.min(count, TOTAL - start) }, (_, k) => bookingAt(start + k)), total: TOTAL });
    }, 500);
    signal.addEventListener("abort", () => clearTimeout(timer));
  });

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text" },
  { key: "room", label: "Room", kind: "text" },
  { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
  { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 700 },
];

export default function Example() {
  const bookings = useRowWindow<Booking>(fetchPage, []);
  // A row is 40px tall, and 60px on a phone, where it takes two lines.
  const row = usePhone() ? 60 : 40;
  return (
    <div className="flex w-full flex-col gap-3">
      <ResultCount count={bookings.total} noun={{ one: "booking", other: "bookings" }} status={bookings.countStatus} />
      <div className="h-96 overflow-hidden rounded-2xl bg-card">
        <DataTable
          label="Bookings"
          columns={columns}
          rows={bookings.rows}
          getRowId={(row) => row.ref}
          fill
          onRangeChange={bookings.onRangeChange}
          query={bookings.query}
          // Opens where the first block ends, so both blocks are in view.
          scrollTop={195 * row}
          status={bookings.status}
          onRetry={bookings.retry}
          attempt={bookings.attempt}
          phoneMain="guest"
          phoneCount={false}
        />
      </div>
    </div>
  );
}
```

Example: The first answer hangs: placeholders hold the rows' places, and after 8 seconds the notice over the last row says the load is taking longer than usual, with a retry that asks again (`docs/system/examples/data-table/slow-load.tsx`)

```tsx
import { useCallback, useEffect, useRef, useState } from "react";

import { type Column, DataTable } from "@/components/cobalt/ui/data-table";
import { counted, money } from "@/lib/cobalt/format";
import type { Status } from "@/lib/cobalt/status";

type Booking = { ref: string; guest: string; room: string; total: number; checkIn: string };

const columns: Column<Booking>[] = [
  { key: "ref", label: "Booking", kind: "code", width: 110 },
  { key: "guest", label: "Guest", kind: "text" },
  { key: "room", label: "Room", kind: "text", hideBelow: 560 },
  { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
  { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 700 },
];

const departures: Booking[] = [
  { ref: "BK-48190", guest: "Sofia Marchetti", room: "Harbour suite", total: 1680, checkIn: "2026-10-15" },
  { ref: "BK-48193", guest: "Daniel Mensah", room: "Garden double", total: 540, checkIn: "2026-10-16" },
  { ref: "BK-48197", guest: "Elena Petrova", room: "Loft studio", total: 630, checkIn: "2026-10-16" },
  { ref: "BK-48199", guest: "Omar Haddad", room: "Corner king", total: 780, checkIn: "2026-10-17" },
];

// Stands in for your API call. The load on opening hangs for 20 seconds, as a stuck one does; a retry
// cancels it and asks again, and that answers after 900ms.
const request = (stuck: boolean, signal: AbortSignal) =>
  new Promise<Booking[]>((resolve, reject) => {
    const timer = setTimeout(() => resolve(departures), stuck ? 20_000 : 900);
    signal.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(new Error("cancelled"));
    });
  });

export default function Example() {
  const [rows, setRows] = useState<Booking[]>([]);
  const [status, setStatus] = useState<Status>("pending");
  const [attempt, setAttempt] = useState(0);
  const out = useRef<AbortController | null>(null);
  const tries = useRef(0);
  // Each load cancels the one still out, so a retry is a fresh request and a fresh wait.
  const load = useCallback((stuck: boolean) => {
    out.current?.abort();
    const controller = new AbortController();
    out.current = controller;
    const next = ++tries.current;
    setAttempt(next);
    setStatus("pending");
    request(stuck, controller.signal).then(
      (answer) => {
        if (out.current !== controller) return;
        setRows(answer);
        setStatus("success");
      },
      () => {
        if (out.current === controller) setStatus("failure");
      },
    );
  }, []);
  useEffect(() => {
    load(true);
    return () => out.current?.abort();
  }, [load]);
  return (
    <div className="w-full overflow-hidden rounded-2xl bg-card">
      <DataTable
        label="Departures"
        labels={{
          notLoaded: "The departures did not load",
          rowCount: (count) => counted(count, { one: "departure", other: "departures" }),
        }}
        columns={columns}
        rows={rows}
        getRowId={(row) => row.ref}
        status={status}
        attempt={attempt}
        onRetry={() => load(false)}
        maxRows={4}
        phoneMain="guest"
      />
    </div>
  );
}
```

Example: The Room filter leaves no booking this month, so the table says nothing matches and offers to clear the filters, at the height the rows will take (`docs/system/examples/data-table/filtered-empty.tsx`)

```tsx
import { useMemo, useState } from "react";

import { type Column, DataTable, type Sort } from "@/components/cobalt/ui/data-table";
import { FilterList } from "@/components/cobalt/ui/filter-bar";
import { ResultCount } from "@/components/cobalt/ui/result-count";
import { money } from "@/lib/cobalt/format";

type Booking = { ref: string; guest: string; room: string; nights: number; total: number; checkIn: string };

const guests = ["Amara Okafor", "Lukas Brandt", "Priya Raman", "Tomás Ibarra", "Hanna Lindqvist", "Kenji Morita"];
const rooms: [string, number][] = [
  ["Garden double", 180],
  ["Harbour suite", 420],
  ["Courtyard twin", 150],
  ["Loft studio", 210],
];
const pad = (n: number) => String(n).padStart(2, "0");

// Computed from the index, so the table reads the same on every visit. No one booked the penthouse.
const bookings: Booking[] = Array.from({ length: 24 }, (_, i) => {
  const [room, rate] = rooms[(i * 3) % rooms.length]!;
  const nights = 1 + ((i * 5) % 6);
  return {
    ref: `BK-${48_301 + i}`,
    guest: guests[(i * 7) % guests.length] ?? "",
    room,
    nights,
    total: rate * nights,
    checkIn: `2026-11-${pad(1 + ((i * 2) % 28))}`,
  };
});
const options = [...rooms.map(([name]) => name), "Penthouse"];

const compare = (a: unknown, b: unknown) =>
  typeof a === "number" && typeof b === "number" ? a - b : String(a).localeCompare(String(b));

export default function Example() {
  const [sort, setSort] = useState<Sort>({ key: "ref", dir: "asc" });
  const [room, setRoom] = useState<string[]>(["Penthouse"]);
  const columns = useMemo<Column<Booking>[]>(
    () => [
      { key: "ref", label: "Booking", kind: "code", width: 110 },
      { key: "guest", label: "Guest", kind: "text" },
      {
        key: "room",
        label: "Room",
        kind: "text",
        filtered: room.length > 0,
        filter: ({ close }) => (
          <FilterList
            label="Room"
            options={options.map((name) => ({
              value: name,
              label: name,
              count: bookings.filter((row) => row.room === name).length,
            }))}
            value={room}
            onValueChange={setRoom}
            close={close}
          />
        ),
      },
      { key: "nights", label: "Nights", kind: "number", hideBelow: 560 },
      { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
      { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 700 },
    ],
    [room],
  );
  // Every booking is already loaded, so the filter and the sort happen here and answer at once.
  const rows = useMemo(() => {
    const kept = room.length === 0 ? bookings : bookings.filter((row) => room.includes(row.room));
    const key = sort.key as keyof Booking;
    const sign = sort.dir === "asc" ? 1 : -1;
    return [...kept].sort((a, b) => compare(a[key], b[key]) * sign);
  }, [room, sort]);
  return (
    <div className="flex w-full flex-col gap-3">
      <ResultCount count={rows.length} noun={{ one: "booking", other: "bookings" }} />
      <div className="overflow-hidden rounded-2xl bg-card">
        <DataTable
          label="November bookings"
          labels={{ noMatches: "No November bookings in these rooms" }}
          // The count line above counts the bookings, so the phone's header line does not repeat it.
          phoneCount={false}
          columns={columns}
          rows={rows}
          getRowId={(row) => row.ref}
          sort={sort}
          onSortChange={setSort}
          onClearFilters={() => setRoom([])}
          maxRows={6}
          phoneMain="guest"
        />
      </div>
    </div>
  );
}
```

Example: The Room column is filtered, and its menu holds the same option list as a filter pill, with a count per room (`docs/system/examples/data-table/filtered.tsx`)

```tsx
import { useMemo, useState } from "react";

import { type Column, DataTable, type Sort } from "@/components/cobalt/ui/data-table";
import { FilterList } from "@/components/cobalt/ui/filter-bar";
import { counted, money } from "@/lib/cobalt/format";

type Booking = { ref: string; guest: string; room: string; nights: number; total: number; checkIn: string };

const guests = [
  "Amara Okafor",
  "Lukas Brandt",
  "Priya Raman",
  "Tomás Ibarra",
  "Hanna Lindqvist",
  "Kenji Morita",
  "Sofia Marchetti",
  "Daniel Mensah",
  "Elena Petrova",
  "Omar Haddad",
  "Clara Dubois",
  "Mateo Rojas",
];
const rooms: [string, number][] = [
  ["Garden double", 180],
  ["Harbour suite", 420],
  ["Courtyard twin", 150],
  ["Loft studio", 210],
];
const pad = (n: number) => String(n).padStart(2, "0");

// Computed from the index, so the table reads the same on every visit.
const bookings: Booking[] = Array.from({ length: 40 }, (_, i) => {
  const [room, rate] = rooms[(i * 3) % rooms.length]!;
  const nights = 1 + ((i * 5 + Math.floor(i / 3)) % 6);
  return {
    ref: `BK-${48_201 + i}`,
    guest: guests[(i * 7 + Math.floor(i / 4)) % guests.length] ?? "",
    room,
    nights,
    total: rate * nights,
    checkIn: `2026-11-${pad(1 + ((i * 2) % 28))}`,
  };
});

const compare = (a: unknown, b: unknown) =>
  typeof a === "number" && typeof b === "number" ? a - b : String(a).localeCompare(String(b));

export default function Example() {
  const [sort, setSort] = useState<Sort>({ key: "ref", dir: "asc" });
  const [room, setRoom] = useState<string[]>(["Harbour suite"]);
  const columns = useMemo<Column<Booking>[]>(
    () => [
      { key: "ref", label: "Booking", kind: "code", width: 110 },
      { key: "guest", label: "Guest", kind: "text" },
      {
        key: "room",
        label: "Room",
        kind: "text",
        filtered: room.length > 0,
        filter: ({ close }) => (
          <FilterList
            label="Room"
            options={rooms.map(([name]) => ({
              value: name,
              label: name,
              count: bookings.filter((row) => row.room === name).length,
            }))}
            value={room}
            onValueChange={setRoom}
            close={close}
          />
        ),
      },
      { key: "nights", label: "Nights", kind: "number", hideBelow: 560 },
      { key: "total", label: "Total", kind: "number", cell: (row) => money(row.total) },
      { key: "checkIn", label: "Check-in", kind: "date", hideBelow: 700 },
    ],
    [room],
  );
  // Every booking is already loaded, so the filter and the sort happen here and answer at once.
  const rows = useMemo(() => {
    const kept = room.length === 0 ? bookings : bookings.filter((row) => room.includes(row.room));
    const key = sort.key as keyof Booking;
    const sign = sort.dir === "asc" ? 1 : -1;
    return [...kept].sort((a, b) => compare(a[key], b[key]) * sign);
  }, [room, sort]);
  return (
    <div className="w-full overflow-hidden rounded-2xl bg-card">
      <DataTable
        label="November bookings"
        labels={{ rowCount: (count) => counted(count, { one: "booking", other: "bookings" }) }}
        columns={columns}
        rows={rows}
        getRowId={(row) => row.ref}
        sort={sort}
        onSortChange={setSort}
        maxRows={6}
        phoneMain="guest"
      />
    </div>
  );
}
```

### State precedence
- Pending-with-rows and hover: pending wins. The body takes no pointer events once dimmed, so no row lifts.
- Pending and empty: pending wins. The skeleton rows show and the empty slot never does.
- Failure and empty: failure wins. The empty slot carries the alert role and the retry.
- Failure and rows on screen: the rows' state wins. They stay where they are and the host says what went wrong beside the table.
- Pending and failure: Not applicable: `status` is one value.
- Stale and a new query's failure: failure wins. A window drops the previous query's rows when its first block fails, since they answer another question, and the empty slot says the rows did not load.
- Block-failed and long-wait: Not applicable: a failure is not pending, and a retry ends the failure.
- Long-wait and stale: both show. The old rows stay dimmed and the notice stands over the last row in view.
- Filtered-empty and failure: failure wins. The slot says the rows did not load.
- Phone-paged and fill or maxRows: phone-paged wins. The rows flow in the page and nothing scrolls inside the table.
- Capped and phone-paged: phone-paged wins on a phone. The pager counts the rows handed out; the host's count line says the cap.
- Sorted and filtered: both show. The sort mark and the filter mark sit in the same header, its label in the ink.
- Hover and focus-visible: both show. The tint is the same and the link adds its outline.
- Expanded and hover: expanded wins. The fill is already the hover fill.
- Expanded and focus-visible: both show. The trigger keeps its fill and the menu's first row takes focus; once the pointer moves over another row, focus and the fill follow it.
- Selected and hover: selected wins. The row keeps the soft accent fill under the pointer.
- Selected and focus-visible: both show. The fill stays and the focused box or link draws its outline.
- Selected and pending-with-rows: both show. The selected rows dim with the rest and keep their fill.
- Selected and phone: both show. The box sits before the main cell on the first line, and a `pre` column moves to the meta line.
- Phone and sorted: both show. The sort button reads the sorted column, and its menu checks it and its direction.
- Hidden by width and the Columns menu: width wins. The menu shows the column unticked and out of reach, with "Hidden at this width" beside its name, and the column comes back, as the reader left it, when the table is wide enough.
- Sorted and a hidden column: hidden wins. The rows keep the order and no header shows the sort mark; the host moves the sort when it hides the sorted column.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| pointer over and out of a header | announce | `--t-press` on `--curve` | background-color, color | the same colour change |
| pointer down on the phone's sort button | input | `pressable`, `--t-press` on `--curve`, the ghost Button's own press | box-shadow | `box-shadow` is not in the reduced-motion list, so the press tint is instant |
| stale rows, after the 250ms delay, and back | announce | `--t-fade` on `--curve` | opacity | the same fade; opacity transitions stay under `reduce` |
| rows landing on a first load | announce | `--t-fade` on `--curve`, from `@starting-style` on a body that mounts once per first load | opacity, 0 to 1 | the same fade; a block that lands while you scroll, and the rows of a new sort, do not fade |
| a first load's rows landing short of its guessed height | announce | the layout spring, `duration-layout` (`--t-layout`, 450ms) on `ease-layout` (`--curve-layout`), once | height | `motion-reduce:transition-none`: the height changes at once |
| a notice arriving in the slot | announce | `--t-fade` on `--curve`, from `@starting-style` | opacity | the same fade |
| skeleton rows while pending | announce | `animate-pulse` | opacity | `motion-reduce:animate-none`, the grey bars stand still and `aria-busy` carries the state |
| header menu open and close | announce | `popup-motion`, `--t-pop` on `--curve` | opacity | the fade stays |
| a row's box checked or cleared | input | Checkbox's own, `--t-press` on `--curve` | background-color, border-color | the same colour change |
| scroll | announce | Not applicable: rows are placed by a transform with no transition, so a scroll paints at the frame rate | transform | the same |

## Props

<!-- Props generated from registry/cobalt/ui/data-table.tsx with TypeScript by scripts/props-table.mjs -->
### DataTable

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `columns` | `Column<Row>[]` |  |  |
| `label` | `string` |  | The table's accessible name. |
| `rows` | `Row[] \| Rows<Row>` |  | `array` the records are in memory and the host sorts and filters them; `window` a `Rows` object from `useRowWindow`. |
| `attempt?` | `number` |  | The request's attempt, such as `useRowWindow`'s `attempt`, so a restarted load starts the long-wait clock again. |
| `capped?` | `ReactNode` |  | What follows `labels.capped` on the line after the last row, when the server holds more rows than it hands out (`rows.total` above `rows.n`): the way to lift the cap, such as a sign-in link. |
| `className?` | `string` |  |  |
| `columnOrder?` | `string[]` |  |  |
| `empty?` | `ReactNode` |  | Replaces the default empty state. |
| `fill?` | `boolean` | `false` | Fill mode: the table takes its container's height and scrolls inside it. |
| `filtered?` | `boolean` | `false` | The rows are narrowed by filters outside the table, such as a FilterBar. |
| `getRowId?` | `(row: Row, index: number) => RowKey` |  | Stable keys for rows, so a reorder keeps each row's DOM, and the keys of `selection`. |
| `hiddenColumns?` | `string[]` |  |  |
| `labels?` | `Partial<{ columnMenu: (column: string) => string; sortAscending: string; sortDescending: string; moveEarlier: string; moveLater: string; hideColumn: string; filter: string; filterBy: (column: string) => string; filtered: string; none: string; missing: Record<MissingReason, string>; nothingToShow: string; notLoaded: string; rowsNotLoaded: (from: string, to: string) => string; notRefreshed: string; noMatches: string; clearFilters: string; capped: (shown: string, total: string) => string; pages: string; retry: string; loading: string; rowCount: (count: number) => string; sort: string; sortBy: string; sortedBy: string; order: string; select: string; selectRow: (name: string) => string; selectAll: (loaded: number, total: number) => string; selected: (count: number) => string; clearSelection: string; columns: string; shownColumns: string; showAll: string; hiddenAtWidth: string; direction: { number: { asc: string; desc: string; }; date: { asc: string; desc: string; }; text: { asc: string; desc: string; }; }; }>` |  |  |
| `maxRows?` | `number` | `10` | Fixed-height mode: the table is as tall as this many rows and scrolls past them. |
| `onClearFilters?` | `() => void` |  | Clears every filter, offered when filters leave no rows. |
| `onColumnOrderChange?` | `(keys: string[]) => void` |  |  |
| `onHiddenColumnsChange?` | `(keys: string[]) => void` |  |  |
| `onPageChange?` | `(page: number) => void` |  |  |
| `onRangeChange?` | `(start: number, end: number) => void` |  | The half-open index range the table wants, including overscan. |
| `onRetry?` | `() => void` |  | Offered in the empty slot and the notice on failure, and by the long-wait notice: once a load has been pending for SLOW_NOTICE_MS (8 seconds), the notice slot says it is taking longer than usual. |
| `onRowClick?` | `(row: Row) => void` |  |  |
| `onScrollChange?` | `(top: number) => void` |  | Where the rows are scrolled to, on every scroll, so a host can keep it. |
| `onSelectionChange?` | `(selection: Set<RowKey>) => void` |  |  |
| `onSortChange?` | `(sort: Sort) => void` |  |  |
| `page?` | `number` |  | The phone page, from 1, when the host keeps it (in the address, say). |
| `pageSize?` | `number` |  | On a phone, the rows flow in the page this many at a time under a pager, instead of scrolling inside the table. |
| `phoneCount?` | `boolean` | `true` | The row count on the phone's header line. |
| `phoneMain?` | `string` |  | The column that names the row. |
| `phoneSort?` | `boolean` | `true` | The sort menu on the phone's header line. |
| `prefetch?` | `(row: Row) => void` |  | Warms a row's page: called when the pointer comes onto a row's link or the keyboard focuses it, through the link's `onPointerEnter` and `onFocus`, so the host can fetch the record first. |
| `query?` | `unknown` |  | Which query the rows answer, such as `useRowWindow`'s `query`. |
| `renderLink?` | `RenderLink` | `defaultLink` |  |
| `rowHeight?` | `number` |  | Row height in pixels. |
| `rowHref?` | `(row: Row) => string` |  | Makes the main cell a link that covers the row. |
| `scrollTop?` | `number` |  | Where the rows start when the table mounts or `query` changes: a position kept from an earlier visit. |
| `selection?` | `ReadonlySet<RowKey>` |  | The keys of the selected rows. |
| `sort?` | `Sort` |  |  |
| `status?` | `Status` | `"idle"` | Pending with no rows shows skeleton rows; pending with rows dims them once the wait is long enough to admit to, and takes them out of reach; failure with no rows shows the empty slot with a retry. |

### DataTableSort

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `columns` | `Column<Row>[]` |  | The table's columns; the sortable ones become the menu's rows. |
| `onSortChange` | `(sort: Sort) => void` |  |  |
| `sort` | `Sort` |  |  |
| `className?` | `string` |  | Placement only, such as `sm:hidden` where the column headers sort on a wide screen. |
| `labels?` | `Partial<{ columnMenu: (column: string) => string; sortAscending: string; sortDescending: string; moveEarlier: string; moveLater: string; hideColumn: string; filter: string; filterBy: (column: string) => string; filtered: string; none: string; missing: Record<MissingReason, string>; nothingToShow: string; notLoaded: string; rowsNotLoaded: (from: string, to: string) => string; notRefreshed: string; noMatches: string; clearFilters: string; capped: (shown: string, total: string) => string; pages: string; retry: string; loading: string; rowCount: (count: number) => string; sort: string; sortBy: string; sortedBy: string; order: string; select: string; selectRow: (name: string) => string; selectAll: (loaded: number, total: number) => string; selected: (count: number) => string; clearSelection: string; columns: string; shownColumns: string; showAll: string; hiddenAtWidth: string; direction: { number: { asc: string; desc: string; }; date: { asc: string; desc: string; }; text: { asc: string; desc: string; }; }; }>` |  |  |

### DataTableColumns

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `columns` | `Column<Row>[]` |  |  |
| `hiddenColumns` | `string[]` |  |  |
| `onHiddenColumnsChange` | `(keys: string[]) => void` |  |  |
| `className?` | `string` |  |  |
| `labels?` | `Partial<{ columnMenu: (column: string) => string; sortAscending: string; sortDescending: string; moveEarlier: string; moveLater: string; hideColumn: string; filter: string; filterBy: (column: string) => string; filtered: string; none: string; missing: Record<MissingReason, string>; nothingToShow: string; notLoaded: string; rowsNotLoaded: (from: string, to: string) => string; notRefreshed: string; noMatches: string; clearFilters: string; capped: (shown: string, total: string) => string; pages: string; retry: string; loading: string; rowCount: (count: number) => string; sort: string; sortBy: string; sortedBy: string; order: string; select: string; selectRow: (name: string) => string; selectAll: (loaded: number, total: number) => string; selected: (count: number) => string; clearSelection: string; columns: string; shownColumns: string; showAll: string; hiddenAtWidth: string; direction: { number: { asc: string; desc: string; }; date: { asc: string; desc: string; }; text: { asc: string; desc: string; }; }; }>` |  |  |
| `locked?` | `string[]` |  | Columns that cannot be hidden. |

### DataTableToolbar

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `onClearSelection` | `() => void` |  |  |
| `selected` | `number` |  | How many rows are selected. |
| `actions?` | `ReactNode` |  | What can be done to the selected rows: buttons, each through `useAction` and a `StateButton`. |
| `children?` | `ReactNode` |  | The toolbar while nothing is selected: a count, the Columns menu, an export. |
| `className?` | `string` |  |  |
| `labels?` | `Partial<{ columnMenu: (column: string) => string; sortAscending: string; sortDescending: string; moveEarlier: string; moveLater: string; hideColumn: string; filter: string; filterBy: (column: string) => string; filtered: string; none: string; missing: Record<MissingReason, string>; nothingToShow: string; notLoaded: string; rowsNotLoaded: (from: string, to: string) => string; notRefreshed: string; noMatches: string; clearFilters: string; capped: (shown: string, total: string) => string; pages: string; retry: string; loading: string; rowCount: (count: number) => string; sort: string; sortBy: string; sortedBy: string; order: string; select: string; selectRow: (name: string) => string; selectAll: (loaded: number, total: number) => string; selected: (count: number) => string; clearSelection: string; columns: string; shownColumns: string; showAll: string; hiddenAtWidth: string; direction: { number: { asc: string; desc: string; }; date: { asc: string; desc: string; }; text: { asc: string; desc: string; }; }; }>` |  |  |

`label` is the table's accessible name and is required. `columns` takes `Column` objects: `key`, `label`, a `kind` of `text`, `number`, `date`, `code` or `tags` that sets the format, the alignment and the minimum width, `width` as a number or `{ min, grow }` in pixels at 14px text, grown with the reader's text size, either of which replaces the wide figure's room a figure or code column holds from a query that starts with no rows, `sortable`, `hideBelow` (hide the column when the table's own width is under that many pixels), a `phone` slot, `filter` and `filtered`, and `cell` and `value` renderers. `rows` is an array or a `Rows` window; `getRowId` keys the rows. `rowHeight` overrides the `--row` token; `maxRows` and `fill` set the height. `sort`, `columnOrder` and `hiddenColumns` are controlled through `onSortChange`, `onColumnOrderChange` and `onHiddenColumnsChange`; the header menu offers only what the host handles. `onRangeChange` reports the half-open index range in view, with overscan; a `useRowWindow` tells its host of a new range only when it moves onto rows not loaded yet or that failed, or back off them, so a scroll within the loaded rows renders nothing outside the table (`registry/cobalt/lib/row-window.ts:252`). `status` and `onRetry` drive the pending, failure and empty states; `empty` replaces the default empty slot. `phoneMain` names the column that leads the phone row; `phoneCount={false}` drops the row count from the phone's header line when a toolbar above already counts the rows, and `phoneSort={false}` drops its sort menu when the toolbar holds `DataTableSort` (`columns`, `sort`, `onSortChange`, `labels`, `className`), so a phone has one header line. `onRowClick`, `rowHref` and `renderLink` make rows open. A row renders again only when its own data, place, selection or tab stop changes, or `columns`, `onRowClick`, `rowHref`, `renderLink` or `prefetch` does, so a host keeps those the same from one of its renders to the next (a function outside the component, or `useCallback`); `labels` may be written inline, since a row reads only `none`, `missing` and `selectRow` from it. `selection` (a set of `getRowId` keys) with `onSelectionChange` adds the checkbox column; the header box selects the loaded rows, every row of an array and the blocks a window holds, and a key it has dropped stays selected. `DataTableColumns` takes the table's `columns`, `hiddenColumns` and `onHiddenColumnsChange`, with `locked` for the columns that cannot hide (the first by default); given the same `columns` array as the table, it shows a column the table's width hides (`hideBelow`) unticked and disabled, with `labels.hiddenAtWidth` ("Hidden at this width") beside its name. `DataTableToolbar` takes `selected`, `onClearSelection`, the bulk `actions`, and the toolbar as `children`. `labels` replaces any string in `defaultLabels`, including the phone's `rowCount` ("60 rows"; pass your own noun, such as funds), the direction words, and `missing`, the words for each reason a value the source did not give reads (`missingWords` in English). `query` names the query the rows answer (a window's `query`): when it changes the table goes back to `scrollTop` (the first row unless given) and the first row's tab stop; `scrollTop` with `onScrollChange` keeps and restores the scroll position, which `useRowWindow`'s `retain` stores per query. `attempt` restarts the long-wait clock with each new request. `filtered` says filters outside the table narrow the rows, and `onClearFilters` is the empty state's Clear filters. `capped` follows `labels.capped` on the line after the last row. `pageSize`, with `page` and `onPageChange` when the host keeps the page, pages a phone table in the page's own scroll; give the table `scroll-mt-*`, or the page `scroll-padding-top`, when a sticky bar covers its top: a new page brings the table's top into view whenever it sits above that line. `prefetch` warms a row's page through its link's `onPointerEnter` and `onFocus` (`registry/cobalt/ui/data-table.tsx:1418`). `Column.skeleton` sets a column's first-load placeholder. `className` is merged last and is for placement.

## Usage

### When to use
- A screen lists records with the same fields, and you scan, sort or filter them by column.
- The list may be longer than a screen, or it lives on a server and arrives in pages.
- The same list must read on a phone, as rows of two lines led by one field.

### When not to use
- The items are prose or cards with different shapes. Use a Card per item instead.
- You pick one row to move on, with a search. Use Select instead.
- A handful of rows where a person acts on one at a time, such as a settings list. Use Item rows in an ItemGroup instead, or leave `selection` off and give rows `rowHref`.
- The page needs numbered pages from a server. Use Pagination instead, or the row window through `useRowWindow` for rows the client holds.

### Rules
- `rule/data-table-status-not-booleans`: When the rows come from a server, pass `status` from `registry/cobalt/lib/status.ts` and `onRetry` instead of an `isLoading` flag that swaps the table for a Spinner, because pending with no rows draws skeleton rows at the row height so the box never changes, pending with rows keeps them on screen and dims them after 250ms, and failure shows the empty slot with one retry. Evidence: person D2; person D25; single use `docs/system/examples/data-table/windowed.tsx:104`, the bookings list passes the window's status straight through. Check: test `data-table.test.tsx` renders pending with no rows and expects `aria-busy`, a full view of skeleton rows and no empty slot.
  - Don't: `{loading ? <Spinner label="Loading" /> : <DataTable label="Orders" columns={columns} rows={rows} />}`
  - Do: `<DataTable label="Orders" columns={columns} rows={rows} status={status} onRetry={retry} />`
- `rule/data-table-row-link`: When a row opens a record, give `rowHref` instead of `onRowClick` alone, because the main cell becomes a link that covers the row, so a middle click, a new tab and a screen reader's link list all work, and only the focused row's link is in the tab order while the arrows reach the rest. Evidence: principle platform: a link navigates and a button acts, so a row that opens a page is a link; person D19; single use `docs/system/examples/data-table/default.tsx:138`, the fund row opens its record. Check: test `data-table.test.tsx` renders `rowHref` and expects one link at `tabindex="0"` and the other 19 at `-1`.
  - Don't: `<DataTable label="Cities" columns={columns} rows={rows} onRowClick={(row) => navigate(\`/cities/${row.id}\`)} />`
  - Do: `<DataTable label="Cities" columns={columns} rows={rows} rowHref={(row) => \`/cities/${row.id}\`} />`
- `rule/data-table-sort-is-controlled`: When columns sort, hold `sort` in the host and reorder or refetch the rows in `onSortChange`, instead of sorting the array once and leaving `onSortChange` off, because the table never reorders rows itself, and `aria-sort` and the header menu appear only when `onSortChange` is given, so a sorted array without it hides the order from a screen reader and offers no way to change it. Evidence: app 2/2 planned uses hold the sort in state and pass `onSortChange`, `docs/system/examples/data-table/default.tsx:129` and `docs/system/examples/data-table/windowed.tsx:99`; principle wcag: 1.3.1 Info and relationships, the sort order is exposed through `aria-sort`. Check: test `data-table.test.tsx` expects no `aria-sort` without `onSortChange` and `aria-sort="descending"` on the sorted column with it.
  - Don't: `<DataTable label="Cities" columns={columns} rows={[...cities].sort(byRank)} />`
  - Do: `<DataTable label="Cities" columns={columns} rows={rows} sort={sort} onSortChange={setSort} />`
- `rule/data-table-stable-row-ids`: When rows can reorder, refetch or arrive in blocks, pass `getRowId` with the record's own id instead of leaving the key to the index, because the key falls back to the row's position, so a sort or a new block re-mounts every row and drops the focused row. Evidence: app 2/2 planned uses pass `getRowId`, `docs/system/examples/data-table/default.tsx:127` and `docs/system/examples/data-table/windowed.tsx:96`; principle platform: React reconciles list children by key, and an index key re-mounts a row that moved. Check: review of every call site that passes `sort` or a window.
  - Don't: `<DataTable label="Orders" columns={columns} rows={rows} sort={sort} onSortChange={setSort} />`
  - Do: `<DataTable label="Orders" columns={columns} rows={rows} getRowId={(row) => row.id} sort={sort} onSortChange={setSort} />`
- `rule/data-table-window-past-200-rows`: When the list can pass 200 rows or lives on a server, pass a `Rows` window from `useRowWindow` with `onRangeChange`, and `fill` inside a box of a set height, instead of fetching every row into an array, because the table renders only the rows in view plus 10 either side, so an array of 10,000 costs one fetch of 10,000 while the window fetches blocks of 200 (`BLOCK_SIZE`) and keeps at most 8 (`MAX_BLOCKS`). Evidence: measured 21 rendered rows of 10,000 at 1280 and 18 at 390, `.design-system/evidence/data-table/measure-1280.json` and `.design-system/evidence/data-table/measure-390.json`; single use `docs/system/examples/data-table/windowed.tsx:77`, the bookings list. Check: test `row-window.test.ts` on the block math; test `data-table.test.tsx` expects 20 rendered rows of 60.
  - Don't: `<DataTable label="Orders" columns={columns} rows={await fetchAllOrders()} />`
  - Do: `<DataTable label="Orders" columns={columns} rows={rows} fill status={status} onRangeChange={onRangeChange} onRetry={retry} />`
- `rule/data-table-phone-main`: When a table has more than 1 column of kind `text` or `code`, name the column that identifies the row with `phoneMain`, because below 640px the row becomes two lines led by one cell, and the fallback takes the first column that is not a number, which is the first in order and not always the name. Evidence: app 2/2 planned uses pass `phoneMain`, `docs/system/examples/data-table/default.tsx:137` and `docs/system/examples/data-table/windowed.tsx:107`; measured one main cell of 246px in a 60px row at 390, `.design-system/evidence/data-table/measure-390.json`. Check: review of every call site at 390.
  - Don't: `<DataTable label="Orders" columns={[order, customer, item, amount]} rows={rows} />`
  - Do: `<DataTable label="Orders" columns={[order, customer, item, amount]} rows={rows} phoneMain="customer" />`

- `rule/data-table-hidden-columns-come-back`: When the header menu can hide columns (`onHiddenColumnsChange`), render `DataTableColumns` above the table with the same `hiddenColumns`, instead of leaving Hide column with no way back, because a hidden column has no header left to open, so without the menu it is gone until the page reloads. Evidence: principle heuristic: user control and freedom, a hidden column has a way back; app 2/2 lists that hide columns render it, `docs/system/examples/data-table/default.tsx:120` and `docs/system/examples/blocks/screener.tsx:985`. Check: test `data-table.test.tsx` renders `DataTableColumns` as one menu button; review of every `onHiddenColumnsChange`.
  - Don't: `<DataTable label="Funds" columns={columns} rows={rows} hiddenColumns={hidden} onHiddenColumnsChange={setHidden} />` alone
  - Do: `<DataTableColumns columns={columns} hiddenColumns={hidden} onHiddenColumnsChange={setHidden} />` in the toolbar above it
- `rule/data-table-columns-menu-same-columns`: When the columns set `hideBelow` and a `DataTableColumns` sits beside the table, pass both the same `columns` array instead of a copy, because the menu learns which columns the table's width hides from the column objects the table holds, and shows each of them unticked and out of reach with "Hidden at this width" (`labels.hiddenAtWidth`), where a copied column reads as ticked while the reader cannot see it. The menu does not let a reader tick such a column back on: `hideBelow` is the host's choice that the column does not fit at that width, and ticking it would bring back the sideways scroll the host took away; the column comes back on its own, as the reader left it, once the table is wide enough. Evidence: measured on the funds list at 1440, an 840px table, Domicile and Last filed unticked and disabled with the note, where both were ticked and unseen before (`.design-system/evidence/data-table/columns-menu-1440.png`); app 3/3 Columns menus pass the table's own `columns` (`rg -n "<DataTableColumns" -A1 docs/system/examples`), `docs/system/examples/data-table/default.tsx:120`, `docs/system/examples/data-table/selection.tsx:175` and `docs/system/examples/blocks/screener.tsx:985`; principle heuristic: visibility of system status, a menu never says a column shows when it does not. Check: review of every `DataTableColumns` beside a table whose columns set `hideBelow`.
  - Don't: `<DataTableColumns columns={columns.map((col) => ({ ...col }))} hiddenColumns={hidden} onHiddenColumnsChange={setHidden} />`
  - Do: `<DataTableColumns columns={columns} hiddenColumns={hidden} onHiddenColumnsChange={setHidden} />` beside `<DataTable label="Funds" columns={columns} rows={rows} />`
- `rule/data-table-selection-in-the-toolbar`: When selected rows can be acted on, pass the actions to `DataTableToolbar` as `actions`, each a `StateButton` through `useAction` and a destructive one behind an `AlertDialog`, instead of a bar that appears above or below the table, because the toolbar holds both lines in one grid cell, so selecting the first row moves nothing, and each action reports on its own button. Evidence: person D37; person D39; single use `docs/system/examples/data-table/selection.tsx:130-142`, the bookings send reminders and cancel after asking. Check: test `data-table.test.tsx` expects both layers in one cell, the hidden one inert.
  - Don't: `{selection.size > 0 && <div className="flex gap-2"><Button onClick={cancelAll}>Cancel</Button></div>}`
  - Do: `<DataTableToolbar selected={selection.size} onClearSelection={clear} actions={<StateButton status={remind.status} onClick={() => void remind.run()}>Send reminders</StateButton>}>{toolbar}</DataTableToolbar>`

- `rule/data-table-window-keeps-the-query`: When rows come from `useRowWindow`, pass its `query`, `scrollTop` and `onScrollChange` to the table, and its `retain` key when the list is a page a person leaves and comes back to, instead of the rows and status alone, because the window keeps the previous query's rows on screen while the next loads and the table must know the query changed to start at its first row, and a kept window shows the same rows at the same place after Back with no request. Evidence: measured on a sort at 1440, the old rows stayed in every frame and the table moved 0px, where the window without them went to 10 blank placeholder rows for 650ms (`.design-system/evidence/data-table/sort-1440-after.json`, `.design-system/evidence/data-table/sort-1440-before.json`); single use `docs/system/examples/data-table/windowed.tsx:101-103`, the bookings list. Check: test `row-window.test.ts` keeps a seeded window's rows stale until its first block, and a retained key returns the same window with its scroll position.
  - Don't: `<DataTable label="Funds" columns={columns} rows={funds.rows} status={funds.status} onRangeChange={funds.onRangeChange} />`
  - Do: `<DataTable label="Funds" columns={columns} rows={funds.rows} status={funds.status} onRangeChange={funds.onRangeChange} query={funds.query} scrollTop={funds.scrollTop} onScrollChange={funds.onScrollChange} />`
- `rule/data-table-figure-floor-before-load`: When a column of figures that loads after the table mounts can run past the room the table holds for it, a figure wider than "$0,000.00" with a `cell` renderer or wider than "000,000" without one, such as balances in the millions to the cent, give it `width: { min }` wide enough for its usual widest value, such as 128 for $9,999,999.00, instead of leaving it to the held room, because a query that starts with no rows holds that wide figure's room in every figure column with no `width` and keeps it, so only a figure wider than it widens the column and slides the headers beside it in the frame the rows arrive. Leave `width` off a column whose figures fit: the held room is measured in the reader's own font, and dates need nothing, since a date column starts as wide as a wide date. Evidence: measured every header of the arrivals at the same x and width in every frame of a first load at 1440, in light, dark and Pill corners, with no `width` on Total, against the Guest header widening 22px and the headers after it sliding by up to 22px before (`.design-system/evidence/data-table/first-load-held.json`); single use `docs/system/examples/data-table/state-pending.tsx:38`, whose Total gives no `width`. Check: probe the recorder's header rects and layout-shift entries on a first load; review of every amount column in a list that loads.
  - Don't: `{ key: "balance", label: "Balance", kind: "number", cell: (row) => money(row.balance) }` for balances in the millions
  - Do: `{ key: "balance", label: "Balance", kind: "number", width: { min: 128 }, cell: (row) => money(row.balance) }`
- `rule/data-table-phone-pages-in-the-page`: When a long table is the page's main list, pass `pageSize` (25 for a list of records) instead of letting a phone scroll a box inside a page that also scrolls, because two scrollers fight under one thumb and the half row at the box's edge is the only sign there is more; with `pageSize` the rows flow in the page under a pager whose place never moves. Evidence: principle platform: one scroll per screen on a phone, as Fund Census pages its phone screener 25 rows at a time (`docs/research/2026-10-17-fund-census-states.md`, section 3, item 10); single use `docs/system/examples/data-table/default.tsx:136`. Check: test `data-table.test.tsx` renders 25 rows in a page with no fixed height and the pager under them.
  - Don't: `<DataTable label="Funds" columns={columns} rows={funds} maxRows={10} />` as a screen's main list
  - Do: `<DataTable label="Funds" columns={columns} rows={funds} maxRows={10} pageSize={25} />`

### Content
- Follows `rule/writing-empty-title-object`.
- Follows `rule/writing-no-em-dash`.
- `rule/data-table-words-through-labels`: When the table must speak in the product's words or another language, pass `labels` with the keys of `defaultLabels`, such as `labels={{ nothingToShow: "No orders yet" }}`, instead of an `empty` node for a wording change, because every string the table speaks is a prop with an English default, and the default empty slot keeps its alert role and its retry on failure. Evidence: person D6; person D25; single use `docs/system/examples/data-table/windowed.tsx:93`, the bookings list names its empty state. Check: test `data-table.test.tsx` renders `labels.nothingToShow` and expects the host's words in the empty slot.
  - Don't: `<DataTable label="Orders" columns={columns} rows={rows} status={status} empty={<p>No orders yet</p>} />`
  - Do: `<DataTable label="Orders" columns={columns} rows={rows} status={status} labels={{ nothingToShow: "No orders yet" }} />`
- `rule/data-table-header-is-a-noun`: When a column is named, its `label` is the noun of what the cells hold, such as "Population", in sentence case, with the unit written in the cell instead of the label and never in capitals, because the label is the header menu's name ("Population column") and a row of the phone's sort menu. Evidence: person D11; app 12/12 column labels in the two planned uses are one noun in sentence case (`rg -n "label:" docs/system/examples/data-table/default.tsx docs/system/examples/data-table/windowed.tsx`). Check: lint rule/ban-uppercase (scripts/check-system.mjs); review.
  - Don't: `{ key: "amount", label: "AMOUNT (USD)", kind: "number" }`
  - Do: `{ key: "amount", label: "Amount", kind: "number", cell: (row) => money(row.amount) }`
- `rule/data-table-empty-cell-is-none`: When a value is null, undefined or an empty string, the answer that there is nothing, leave the cell to the table, which writes `labels.none` ("None") in the muted ink, and when the source did not give the value, hold `missing(reason)` in the row, which the table writes as the reason through MissingValue, instead of a `cell` renderer that returns a dash or "N/A", because a dash reads as a minus beside numbers and a screen reader may skip it, a null for a value nobody reported reads None, an answer the source never gave, and one word for every empty cell keeps the column scannable. Evidence: person D12; principle wcag: 1.3.1 Info and relationships, the empty value is text a screen reader announces. Check: test `data-table.test.tsx` renders a null value and expects "None" and no dash, and `missing("withheld")` and expects "Withheld" on a desktop and a phone, never through the renderer.
  - Don't: `cell: (row) => row.population ?? "—"`
  - Do: `{ key: "population", label: "Population", kind: "number" }`
- `rule/data-table-capped-says-it-once`: When a count line above the table already says the cap, such as a ResultCount with `available`, give `labels.capped` a shorter line that says where the list ends, such as "End of the first 500 funds", with the same link as `capped`, instead of the default sentence, because the count line and the line after the last row share one screen in a short list, and the same sentence twice reads as an echo. Evidence: single use `docs/system/examples/result-count/capped.tsx:90`; measured at 390 the end line on one line and the link whole on the line under it, inside the 60px row (`.design-system/evidence/data-table/capped-390.png`), where the default sentence beside the link was cut to "Showing the first 500 o…" before. Check: review of every capped table under a ResultCount.
  - Don't: `<DataTable label="Funds" columns={columns} rows={funds.rows} capped={signIn} />` under `<ResultCount count={funds.total} available={funds.rows.n}>`
  - Do: `<DataTable label="Funds" labels={{ capped: (shown) => \`End of the first ${shown} funds\` }} columns={columns} rows={funds.rows} capped={signIn} />`
- `rule/data-table-count-names-the-rows`: When the phone's header line counts the rows, pass `labels.rowCount` with the noun the product uses, such as `(count) => counted(count, { one: "booking", other: "bookings" })`, instead of leaving the default "rows", because "12 rows" names the table's machinery while "12 bookings" names what the person is looking at. Evidence: app 11/11 example tables that count rows on a phone pass their own noun (`rg -n "rowCount" docs/system/examples`), `docs/system/examples/filter-bar/in-data-table.tsx` with "4 bookings" and `docs/system/examples/blocks/record.tsx` with holdings among them, and the one other table that keeps the count on, `docs/system/examples/data-table/state-empty.tsx`, never has a row to count; principle heuristic: match between system and the real world. Check: review of every DataTable that leaves `phoneCount` on.
  - Don't: `<DataTable label="Arrivals" columns={columns} rows={rows} />`
  - Do: `<DataTable label="Arrivals" labels={{ rowCount: (count) => counted(count, { one: "arrival", other: "arrivals" }) }} columns={columns} rows={rows} />`

### Anti-slop
- `rule/data-table-not-a-div-grid`: When a screen lists records with the same fields, render them through `DataTable` instead of a `div` grid with `role="row"` or a hand-written `table` inside `overflow-auto`, because the component carries the table semantics, the row window, the sticky header, the keyboard model and the phone layout, and a grid of divs drops the header a screen reader reads with each cell. Evidence: principle wcag: 1.3.1 Info and relationships, a table exposes each cell's header; principle heuristic: consistency and standards, one table on every screen. Check: test `data-table.test.tsx` expects a `table` root with `columnheader` cells; review of every list of records.
  - Don't: `<div className="grid grid-cols-4 overflow-auto">{rows.map((row) => <div role="row" key={row.id}>...</div>)}</div>`
  - Do: `<DataTable label="Orders" columns={columns} rows={rows} getRowId={(row) => row.id} />`
- `rule/data-table-figures-through-format`: When a cell shows a number, a date or an amount, give the column its `kind` or format it through `registry/cobalt/lib/format.ts` (`compact`, `compactMoney`, `money`, `change`, `date`, `integer`) instead of `toFixed`, `toLocaleString` or a hand-written template, because every figure then takes tabular figures and the real minus sign, so a column of numbers lines up and reads as arithmetic. Evidence: person D10; app 4/4 number and date cells in the two planned uses format through `kind` or `registry/cobalt/lib/format.ts` (`rg -n "kind: \"number\"|kind: \"date\"" docs/system/examples/data-table/default.tsx docs/system/examples/data-table/windowed.tsx`); measured `font-variant-numeric: tabular-nums` on every cell, `.design-system/evidence/data-table/measure-1280.json`. Check: review of every `cell` renderer that returns a figure.
  - Don't: `cell: (row) => "$" + row.amount.toFixed(2)`
  - Do: `cell: (row) => money(row.amount)`
- `rule/data-table-one-unit-per-column`: When a column shows sizes with a K, M or B suffix, read one unit for the whole column with `unitFor(values)` and pass it to every cell as `compact(value, unit)` or `compactMoney(value, unit)`, instead of `compact(value)` per cell, because a column that mixes "$1.4B" and "$835M" has to be read row by row to compare, while "$1,400M" above "$835M" compares at a glance down the right edge. Evidence: principle heuristic: consistency and standards, one unit and one precision per column; measured `unitFor([1.4e9, 835e6, 12e6])` as "M" with cells "1,400M", "835M" and "12M", `registry/cobalt/lib/format.test.ts`. Check: test `format.test.ts`, a column through unitFor and compact reads in one unit; review of every `cell` renderer that calls `compact` or `compactMoney`.
  - Don't: `cell: (row) => compactMoney(row.assets)`
  - Do: `const unit = unitFor(rows.map((row) => row.assets))` and `cell: (row) => compactMoney(row.assets, unit)`
- `rule/data-table-money-is-exact`: When a cell holds an amount a person pays, is paid or reconciles, such as an order total or a balance, format it with `money(value)`, which keeps the cents, instead of `compactMoney`, because "$4.8K" for a $4,812.00 order cannot be checked against an invoice. Evidence: measured `money(4812)` as "$4,812.00" and `money(12.5)` as "$12.50", `registry/cobalt/lib/format.test.ts`; principle heuristic: match between system and the real world, an amount reads as the receipt does. Check: test `format.test.ts`, money is exact to the cent; review of every amount column.
  - Don't: `{ key: "amount", label: "Amount", kind: "number", cell: (row) => compactMoney(row.amount) }`
  - Do: `{ key: "amount", label: "Amount", kind: "number", cell: (row) => money(row.amount) }`
- `rule/data-table-status-has-a-word`: When a cell carries a status or a direction, such as growth, write the sign or the word beside the colour, such as `change(row.growth)` in `text-good` or `text-bad`, instead of the colour alone, because a colour-blind reader and a screen reader get the direction only from the text. Evidence: principle wcag: 1.4.1 Use of color, colour is never the only cue; single use `docs/system/examples/data-table/default.tsx:92`, the growth cell shows the signed percentage in colour. Check: review of every `cell` renderer that sets `text-good` or `text-bad`.
  - Don't: `cell: (row) => <span className={row.growth < 0 ? "text-bad" : "text-good"}>{Math.abs(row.growth)}%</span>`
  - Do: `cell: (row) => <span className={row.growth < 0 ? "text-bad" : "text-good"}>{change(row.growth)}</span>`

### Limits
- `rule/data-table-columns-in-840`: When a table in an 840px box has more than 6 columns of the default kinds, give the columns past the sixth `hideBelow`, read against the table's own width, or a fixed `width` instead of letting them scroll, because at 7 columns the minimum widths sum to over 900px (963px as first guessed from the labels' length, before they are measured), so the last column sits past the box's edge and the table scrolls sideways under its sticky first column. Evidence: measured scrollWidth 975 > clientWidth 840 at 7 columns at 1280, `.design-system/evidence/data-table/measure-1280.json`; single use `docs/system/examples/data-table/default.tsx:71-95`, the 7-column list hides 3 columns below 720, 900 and 1100px. Check: probe `.design-system/scripts/measure-table.mjs` on the showcase at 1280.
  - Don't: `columns={[rank, city, country, population, growth, founded, tags]}`
  - Do: `columns={[rank, city, { ...country, hideBelow: 900 }, population, growth, { ...founded, hideBelow: 1100 }, tags]}`
- `rule/data-table-text-cell-length`: When a text value can pass 27 characters, give the column `width: { min: 280 }` or accept the truncation, which keeps the full value in the cell's `title`, instead of a `cell` renderer that wraps the text, because the main column truncates at 27 characters in its 200px floor at 1280 and at 33 in the 246px phone cell, and a wrapped cell breaks the fixed row height the window positions by. Evidence: measured truncation at 27 characters at 1280 and 33 at 390, `.design-system/evidence/data-table/measure-1280.json` and `.design-system/evidence/data-table/measure-390.json`. Check: probe `.design-system/scripts/measure-table.mjs`; review of every `cell` renderer for `whitespace-normal`.
  - Don't: `cell: (row) => <span className="whitespace-normal">{row.city}</span>`
  - Do: `{ key: "city", label: "City", kind: "text", width: { min: 280, grow: 2 } }`

## Accessibility
Rests on the native `table` with its sections restated as roles, and on Base UI `Popover` for the column menu.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Tab | before the table | focuses the table when it scrolls, then the header buttons left to right, then the focused row's link or the row | the table, a header, then one row | by hand |
| Enter or Space | a header button | opens the column menu | the menu's first row | by hand |
| ArrowDown or ArrowUp | a menu row | moves to the next or previous row, wrapping | the next row | by hand |
| Enter or Space | a menu row | sorts, moves or hides the column and closes the menu | the header button | by hand |
| Escape | the column menu | closes the menu only | the header button | by hand |
| ArrowDown or ArrowUp | a row or its link | moves one row, scrolling it into view | the next row's link or button, else the row | by hand |
| PageDown or PageUp | a row or its link | moves a view of rows minus 2 | the target row's link or the row | by hand |
| Home or End | a row or its link | moves to the first or last row | that row's link or the row | by hand |
| Enter or Space | a row with `onRowClick` | opens the row | the row | by hand |
| Enter | a row link | follows the link | the new page | by hand |
| Space | a row or its link, with `selection` | selects or clears the row; with Shift, the rows from the last one clicked | stays | by hand |
| Space | a row's box | selects or clears the row | the box | by hand |
| ArrowDown or ArrowUp | a row's box | moves one row, staying in the checkbox column | the next row's box | by hand |
| Shift and a click | a row's box | selects or clears every loaded row from the last box clicked to this one, as this one goes, with no text selected between | the box | by hand |

The column menu is the one path to sort, move and hide, and it opens from a button on click, Enter or Space, so nothing needs a right click or a hover. Its rows are commands and none navigates. Escape is handled by the popover, so inside a dialog it closes the menu and the dialog stays. Focus returns to the header button on close.

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| root | table | `label` through `aria-label` | `aria-rowcount`, `aria-colcount`, `aria-busy` while pending | the name, "table", and the row and column counts on entry | test |
| header cell | columnheader | the column `label` | `aria-colindex`; `aria-sort` of none, ascending or descending when sortable | the label and "sorted ascending" or "descending" | test |
| header button | button | the column `label`, plus "Filtered" when a filter narrows the rows | `aria-expanded` while its menu is open, `disabled` when there is no menu | the label, "button", "collapsed" or "expanded" | a11y scan |
| column menu | menu, or group when it holds a filter control | "{column} column" through `aria-label` | each row a `menuitem` button with `aria-disabled` at the ends | the menu name on open, each row's text on focus | by hand |
| filter group | group (fieldset) | "Filter by {column}" from a visually hidden legend | the host's filter control | the legend on entry | by hand |
| row | row | its cells | `aria-rowindex`; `aria-hidden` on a placeholder row; `tabindex` 0 on the focused row with `onRowClick` | the row index and the cells | test |
| cell | cell | the formatted value, "None" when empty, or the reason when the source did not give it | `aria-colindex` | the header and the value | test |
| row link | link | the main cell's text | `tabindex` 0 on the focused row, -1 on the rest | the text and "link" | test |
| checkbox column header | columnheader | "Select", visually hidden | `aria-colindex` 1; the data columns count from 2 | "Select" | test |
| header box | checkbox | "Select all 24 rows", or "Select the 200 loaded rows" while a server holds more | `aria-checked` false, mixed or true | the name and the state | test |
| row box | checkbox | "Select" and the main cell, such as "Select BK-48201" | `aria-checked`; `tabindex` 0 on the focused row only | the name and the state | test |
| selection count | status | "3 selected" | empty while nothing is selected | the count as it changes | by hand |
| loading row | row | "Loading", visually hidden | shown only while pending with 0 rows | "Loading" | test |
| root, first load | table | `label` | `aria-rowcount="-1"` while the count is not known | the name, and no row count yet | test |
| stale body | rowgroup | Not applicable: a group of rows | `inert` once dimmed, so the pointer, the keyboard and the screen reader skip rows of another query; focus inside moves to the table first | nothing until the new rows land | by hand |
| notice slot | status | its words | always mounted, empty and no taller than nothing until it has a notice, so what lands in it is read once; the long-wait notice inside it is the LongWaitNotice part | "Rows 201 to 400 did not load, Retry", "The new rows did not load", "This is taking longer than usual." | test |
| capped line | row | its words and the host's link | after the last row, outside `aria-rowcount` | "Showing the first 500 of 12,400 rows" | test |
| Columns menu row, hidden at this width | menuitemcheckbox | the column's label and "Hidden at this width" (`labels.hiddenAtWidth`) | `aria-checked="false"`, `aria-disabled="true"` | "Domicile, Hidden at this width, not checked, dimmed" | by hand |
| phone pager | navigation | "Pages" (`labels.pages`) | Pagination's own | the range and Previous and Next | test |
| empty slot | alert on failure, none on empty | "The rows did not load" and the "Retry" button on failure, "Nothing to show" when empty | shown only at 0 rows and not pending | the title, at once on failure | test |

Contrast as drawn, light theme (`.design-system/evidence/data-table/measure-1280.json`, `measure-390.json`): header text on the card 6.01:1, body text on the card 19.8:1, the "None" and muted meta text on the card 6.01:1. The phone's sort button is the ghost Button and takes its contrast from Button. Dark theme: checked by eye at 390 and 320 (fix-data stress run, 2026-10-16), NEEDS REVIEW for measured ratios.

## Tokens
| Part | State | Token |
|---|---|---|
| root | all | `--row`, `--control-lg`, `--touch`, `--gutter`, `--border`, `--card`, `--ring` |
| scrollbar | all | `--foreground` at 20 percent on a transparent track |
| sticky first column | overflowing | `--border` |
| row | hover and focus-within | `--hover` |
| row | selected | `--primary-soft` |
| row box | checked and mixed | the Checkbox's tokens: `--primary`, `--primary-foreground`, `--control-edge` |
| header | rest | `--muted-foreground` |
| header | hover and expanded | `--muted`, `--foreground` |
| header | transition | `--t-press`, `--curve` |
| sort mark | sorted | `--foreground` for the sorted direction and 25 percent for the other, on the header and on the phone's sort button; unsorted, the whole mark at 50 percent under the pointer only; `--line-icon` |
| filter mark | filtered | a 14px funnel in `--foreground`, with the label in the ink |
| row link | hover | the row's `--hover` tint; the link keeps the ink |
| phone sort button | rest | the ghost `sm` Button: `--control-sm`, `--muted-foreground`, the sorted column in `--foreground` |
| phone count | rest | `--muted-foreground` |
| empty cell | all | `--muted-foreground` |
| missing cell | all | `--muted-foreground`, through MissingValue |
| skeleton | pending | `--foreground` at 8 percent (Skeleton's bar), `--r-tag` for tag shapes, `--r-xs` for the flag box |
| body | dimmed | `--t-fade`, `--curve` |
| body | first load landing | `--t-fade`, `--curve` |
| root | first load landing short of its guessed height | `--t-layout`, `--curve-layout` |
| notice | shown | `--card`, `--border`, `--head-h` (`--control-lg`), `--t-fade` |
| capped line | all | `--muted-foreground`, `--border` |
| column menu | open | `--popover`, `--popover-foreground`, `--t-pop`, `--curve` |
| menu row | hover and focus | `--accent`, `--accent-foreground` |

## Related
- Item: a handful of rows with one action each.
- FilterBar: the pills above the table, whose `FilterList` a column's `filter` can hold.
- Checkbox: the box in the selection column.
- Empty: the slot the table shows at 0 rows, for a host that wants its own words and next step.
- Skeleton: the bars the pending state draws.
- Popover: the surface the column menu opens in.
- DropdownMenu: the phone's sort menu, opened from a ghost `sm` Button.
- Tag: the cell a `tags` column renders.
- Card: a white box that groups one item's title, details and actions.
- Pagination: Previous and Next for a short list that the table does not window, and the pager under a phone page.
- MissingValue: the words a cell says for a value the source did not give.
- ResultCount: the count line above the table, exact, approximate, partial or capped, from a window's `total` and `countStatus`.
- LongWaitNotice: what the notice slot says when a load runs past 8 seconds.
- BarList: ranked names with their values, each row filled to its share of the largest.
- Chart: the frame every chart draws in: size, states, hover, tooltip, keyboard, legend and change chip.
- MessageAttachment: pictures and files sent in a message, with upload progress and a failure you can retry.
- FileTile: one file as a tile: its type, name and size, with the upload or the failure drawn on it.
- List and detail: a list beside the record that is open, which becomes two screens on a phone.
- MemberList: the people who can see something shared, their roles and the invitations still open.
