# Query table

> A saved query’s result as a card: filter chips, column menus that sort, group, hide and answer a question, and the same rows as a table, bars or SQL.

The result of a query in an analytics tool, Accounts by MRR, on a dark card. Chips filter it by owner and an MRR threshold, and + Filter adds plan, health, seat use or trend. Each row reads its cells: the plan as a tinted pill, twelve weeks of MRR as a line that turns red when it falls, seats as a segmented meter that fades under half used, health as a dot or a red ring. Every column header opens a menu to sort, filter (F), group by plan with subtotals, hide the column, or ask about it for a line read from the rows in view. The header switches the rows to a bar chart or to the SQL that returns them; the footer walks rows with the keyboard and exports a CSV. Light and dark.

A React component by Bruno Delorence: https://brunodelorence.com/components/query-table. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: Data.

## Anatomy

1. **Header**: The table icon, the query’s name, and its row count with how long it took to run; Running… while the filters change.
2. **View switch**: Table, Chart and SQL as a tablist over the same result; the arrow keys move between them. The share button sits beside it.
3. **Filter chip**: A filter’s name and value as a menu button, with × to remove it. Owner shows the owners’ initials; + Filter adds plan, health, seats or trend.
4. **Density toggle**: Comfortable or compact rows, a radio group of two icons.
5. **Answer**: What Ask about wrote for a column: a line read from the rows in view, updated as the filters change, with a button to dismiss it.
6. **Column header**: A menu button with the column’s name; the sorted one carries an arrow in the accent and a chevron shows on hover.
7. **Row**: A checkbox, the account, its plan, MRR, twelve weeks of MRR, seats used and health. Selected rows take a tint; the keyboard’s row an accent edge.
8. **Column menu**: Sort either way, Filter (F), Group by plan, Hide column, and Ask about the column in the accent, under a rule.
9. **Footer**: How many are selected and how many of the result are showing, ↑ and ↓ to walk the rows, and Export for a CSV of the rows in view.

## Properties

### Opening filters (`defaultFilters`)

1. **None**: Every row the query returns, with only + Filter in the toolbar.
2. **Owner and MRR (default)**: Two chips that say whose accounts and how big: the result someone opens most days.
3. **Health and trend**: A narrower question, at-risk accounts with MRR falling: a few rows that need someone.

Open with the one or two filters that make the query what its title says. Every chip left out is one less thing to read, and + Filter is there for the rest.

### Opening sort (`defaultSort`)

1. **MRR, highest first (default)**: The biggest accounts at the top, for a report about revenue.
2. **Seats, lowest first**: The accounts using the least of what they bought, for a review of seat use.
3. **Trend, falling first**: The accounts losing the most over twelve weeks, for a churn review.

Sort by the column the question is about, in the direction that puts the rows to act on first. The header shows the arrow, so the order explains itself.

## When to use

- The result of a saved query in an analytics or BI tool, where people narrow it with a few filters and want the same rows as a table, a chart or the SQL behind them.
- A ranked list of accounts, customers or projects with a handful of numbers per row, best read with small cells: a pill for the tier, a line for the trend, a meter for use, a dot for health.
- Reviews where someone picks rows and takes them elsewhere: select a few, walk them with the keyboard, export what is in view.
- A column-first way of working: each header sorts, filters, groups, hides and answers a question about itself, so the toolbar stays short.

## When not to use

- Editing records. Use a data grid with inline editing and validation; this card reads a result, it never writes one.
- Thousands of rows at once. The card shows the rows in view of a larger result; page or virtualise on the server and keep the count honest.
- Writing queries. Use a query editor with completion and errors; the SQL here is read-only and follows the filters.
- A single number or a trend over time. Use a stat card or a time-series chart; a table makes people read every row.
- Free-form questions about the data. Ask about answers one column from the rows in view; a full assistant needs its own thread.

### Setting up the query

- **`title`** names the result as a noun phrase: `Accounts by MRR`. It heads the card and the SQL’s first comment.
- **`rows`** is a sample of the result, filtered and sorted in the browser. **`total`** is what the whole query returns with the opening filters; the counts scale from it by the share of the sample still in view, so they are estimates once the filters change.
- **`defaultFilters`**, **`defaultSort`** and **`defaultSelected`** only set the first moment. After that the card holds its own state.
- **`onSelectionChange`** hears the selected ids; **`onExport`** gets the CSV and the rows. Export also saves the file itself, named after the title.

### Table, chart or SQL

- **Table** for reading and picking rows: the only view where ↑, ↓ and Space work.
- **Chart** to compare sizes: the same rows in the same order and grouping, as bars of MRR. It draws MRR only, whatever the sort.
- **SQL** to check what the result is, or copy it: the shown columns, a `WHERE` line per filter and the sort, read-only.

### Ask about

- Each column has its own question: the top two accounts’ share of MRR, who rose and fell most, how many use under half their seats, what the at-risk accounts hold.
- The line is written from the rows in view by a fixed rule per column, so the same rows always give the same answer. No model is called.
- It follows the filters as they change, and says to loosen a filter when no rows are left.

### Query table vs. filter table

**Query table**
- A saved result with several numbers per row, to sort, filter, group and export.
- Filters combine: owners, MRR, plan, health, seats and trend at once.
- For analysts and account reviews, where the question changes.

**Filter table**
- A short list of tasks narrowed by one status at a time.
- One row of chips with counts; the rows fold away in place.
- For a team’s own list, where the only question is which status.

## Do’s and don’ts

- **Do**: Open with the filters that define the query, like an owner and an MRR threshold.
- **Don’t**: Set every filter up front. The chips crowd the toolbar and the rows thin to a few before anyone has asked.
- **Do**: Sort by what the title promises: `Accounts by MRR`, MRR highest first.
- **Don’t**: Open a revenue report in alphabetical order. The biggest accounts end up wherever their names fall.
- **Do**: Group by plan when the rows span plans, so the subtotals compare them.
- **Don’t**: Group rows already filtered to one plan. A single group repeats what the chip says and adds a row.

## Content

Most words in the card are drawn from the data; the few you write should read like the result they name.

- **The title**: a noun phrase in sentence case, what the rows are and how they’re ranked: `Accounts by MRR`, `Accounts at risk`. No verbs, no full stop.
- **Account names** stay whole: they head their rows and hold the left edge when the table scrolls sideways.
- **Owner names** in full, first and last. The chip shows their initials and the menu their names.
- **MRR** in whole dollars, as a number. The card adds the separators and the `$`.

## Installation

Install it with the shadcn CLI, into components/query-table of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/query-table.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

```json
{
  "registries": {
    "@brunodelorence": "https://brunodelorence.com/r/{name}.json"
  }
}
```

```sh
npx shadcn@latest add @brunodelorence/query-table
```

Or copy all the source files below into one folder of your project. Either way it needs React 19 and a bundler with CSS Modules (Next.js, Vite).

It has a dark colour scheme. Its colours are CSS light-dark() pairs, kept inside @supports so that builds which rewrite light-dark() for older browsers leave them alone: it follows your page’s color-scheme (light unless the page sets one) or its colorScheme prop, with nothing to configure. Browsers without light-dark() show it light.

## Usage

```tsx
import { QueryTable } from './query-table';

export function AccountsReport() {
  return (
    <QueryTable
      title="Accounts by MRR"
      total={1284}
      defaultFilters={{ owners: ['mara', 'teo'], mrr: 5000 }}
      defaultSort={{ key: 'mrr', desc: true }}
      onSelectionChange={(ids) => console.log('Selected', ids)}
      onExport={(csv) => console.log(csv)}
      autoplay={false}
    />
  );
}
```

## States

- **Accounts by MRR**: Two owners and MRR over $5k: seven rows sorted by MRR, one selected.
- **Column menu**: The Seats header open: sort, filter, group, hide and Ask about Seats.
- **Ask about Seats**: A line read from the rows in view: how many use under half their seats, the lowest, the average.
- **Grouped by plan**: A header row per plan with its count, MRR subtotal, average seat use and accounts at risk.
- **Chart**: The rows as bars of MRR in the plan’s colour, in the table’s order; a bar’s tooltip follows the pointer or the focus, and pressing it selects the row.
- **SQL**: The query for the current filters, sort and columns, coloured by kind and read-only, with Copy.
- **Owner filter**: The Owner chip’s menu: a checkable list of people with their account counts; it stays open while you tick.
- **Add a filter**: + Filter lists the filters not in use; picking one adds its chip and opens its menu.
- **Compact, columns hidden**: Compact rows with Plan and Trend hidden: a Hidden button in the toolbar brings them back.
- **Keyboard row**: The row ↑ and ↓ stand on, with an accent edge; Space selects it and the live region reads it out.
- **No rows**: Filters that match nothing: the count drops to zero and Reset filters brings the defaults back.
- **Phone**: Under 640 px the view switch takes its own row, the density toggle sits over the chips, and the table scrolls sideways with the account held.

## Examples

### Grouped by plan

Every owner’s accounts over $5k, grouped by plan with subtotals, and the answer to Ask about Plan above them.

```tsx
import { QueryTable } from './query-table';

export function GroupedByPlan() {
  return (
    <QueryTable
      autoplay={false}
      defaultFilters={{ mrr: 5000 }}
      total={3480}
      defaultSelected={[]}
      defaultState={{ grouped: true, insight: 'plan' }}
    />
  );
}
```

### Compact, columns hidden

A seat-use query in compact rows, sorted by seats ascending, with Plan and Trend hidden behind the Hidden button and two rows selected.

```tsx
import { QueryTable } from './query-table';

export function CompactWithHiddenColumns() {
  return (
    <QueryTable
      autoplay={false}
      title="Seat use by account"
      defaultFilters={{ seats: 'under75' }}
      defaultSort={{ key: 'seats', desc: false }}
      total={612}
      defaultSelected={['vesper', 'kiln']}
      defaultState={{ density: 'compact', hidden: ['trend', 'plan'] }}
    />
  );
}
```

### SQL view

Two owners’ Enterprise and Growth accounts sorted by trend, shown as the SQL that returns them.

```tsx
import { QueryTable } from './query-table';

export function SqlView() {
  return (
    <QueryTable
      autoplay={false}
      defaultFilters={{ owners: ['bruno', 'lena'], plans: ['Enterprise', 'Growth'] }}
      defaultSort={{ key: 'trend', desc: true }}
      total={418}
      defaultSelected={[]}
      defaultState={{ view: 'sql' }}
    />
  );
}
```

### Accounts at risk

A different query, at-risk accounts with falling MRR, opened on the chart with a bar’s tooltip.

```tsx
import { QueryTable } from './query-table';

export function AccountsAtRisk() {
  return (
    <QueryTable
      autoplay={false}
      title="Accounts at risk"
      defaultFilters={{ health: 'risk', trend: 'falling' }}
      defaultSort={{ key: 'mrr', desc: true }}
      total={96}
      defaultSelected={[]}
      defaultState={{ view: 'chart', tip: 'vesper' }}
    />
  );
}
```

## How it works

- The rows are a sample of the result, filtered and sorted in the browser. The header’s count scales from the `total` the default filters return, so narrowing the filters lowers it in step; each change of filters runs a beat of Running… and dims the rows.
- The filters are chips of two buttons: the value opens its menu (a checkable list of owners, MRR thresholds as radios, plans as checkboxes) and × removes it. + Filter lists only the filters not in use; picking one adds its chip and opens its menu at once.
- A column header is a menu button. Its menu sorts either way, opens that column’s filter (F runs it from the open menu), groups the rows by plan, hides the column, or asks about it. Grouping draws a header row per plan with its count, MRR subtotal, average seat use and accounts at risk; a hidden column comes back from a Hidden button by the density toggle.
- Ask about reads the rows in view for a moment, then writes a line from them: the top two accounts’ share of MRR, the plan that carries the most, who rose and fell most, how many use under half their seats, what the at-risk accounts hold. The line updates as the filters change.
- The trend is twelve weekly points in a small SVG with a dot at the end, blue when the last week is above the first and red when below. Seats are twelve segments lit to the share used, faded under half; health is a dot, or a red dot in a ring when at risk.
- Chart draws the same rows, in the same order and grouping, as horizontal bars of MRR in the plan’s colour on a rounded scale; the tooltip follows the pointer or sits under a focused bar, and pressing a bar selects its row. SQL writes the query from the state, token by token, so it can colour keywords, functions, strings, numbers and comments: the shown columns, a WHERE line per filter, the sort, and a subtotals query when grouped.
- The rows’ box takes the focus: ↑ and ↓ (or the footer’s buttons) move a keyboard row with an accent edge, Space selects it, Home and End jump. Export saves the rows in view, with the shown columns, as CSV; the share menu copies the SQL or the rows.
- While on screen and untouched, a demo pointer asks about Seats, groups by plan, shows the chart and the SQL, selects a row and raises the MRR threshold. Any real input hands it over; it comes back after 9 s of quiet.

## API reference

- **rows** (`Account[]`, default `seventeen accounts`): The rows the query can return: name, plan, owner, MRR, twelve weeks of MRR, seats used and bought, and health.
- **owners** (`Owner[]`, default `four people`): Everyone who can own an account: an id, a name and an avatar tint.
- **title** (`string`, default `'Accounts by MRR'`): The query’s name, in the header and the SQL’s first comment.
- **total** (`number`, default `1284`): How many rows the query returns with its default filters; the counts scale from it as the filters change.
- **defaultFilters** (`Partial<Filters>`, default `{ owners: ['mara', 'teo'], mrr: 5000 }`): The chips at first: owners, mrr (over), plans, health, seats (a band of use) and trend. Leave one out for no chip.
- **defaultSort** (`Sort`, default `{ key: 'mrr', desc: true }`): The column sorted at first, and which way.
- **defaultSelected** (`string[]`, default `['brightwater']`): Row ids selected at first.
- **defaultState** (`QueryTableState`): Opens locked in a moment, with the demo off: the view, grouping, density, hidden columns, selection, keyboard row, an answer, an open menu or a bar’s tooltip.
- **onSelectionChange** (`(ids: string[]) => void`): Called with the selected row ids when they change.
- **onExport** (`(csv: string, rows: Account[]) => void`): Called with the CSV when Export saves the rows in view.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer shows the main interactions. Any real input stops it.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): Classes for the stage.

## Accessibility

### Reading the result

- It is a real table: column headers, each account’s name as its row’s header, and `aria-sort` on the sorted column.
- Colour is never the only sign (WCAG 1.4.1): every plan pill carries its name, a falling trend and an at-risk account are said in words, and at risk adds a ring around the dot.

### Contrast

In both schemes every text colour reaches at least 4.5:1 on what it sits on, hovered, selected and keyboard rows included: the column headers, the quieter seat percent, the SQL’s line numbers and comments, and the accent links (WCAG 1.4.3, Contrast (Minimum)). Checkbox edges and the grey icons reach well over 3:1 (WCAG 1.4.11, Non-text Contrast).

### Keyboard

The rows’ box is one stop in the Tab order: inside it ↑ and ↓ move a keyboard row, Home and End jump, Space selects and Escape lets go. Leaving the box drops the keyboard row. Menus open from their buttons and Escape brings the focus back to the button that opened them.

### Announcements

One polite status region says sorts, removed filters, the keyboard row with its place (“Row 3 of 7”), selections, the Ask about line, copies and exports (WCAG 4.1.3). The footer’s count is a live region too, so a change of selection is heard. The short notice that shows on screen is hidden from screen readers, so nothing is said twice.

### Small screens

Under 640 px the toolbar stacks and the table scrolls sideways with the account column held. Data tables may scroll in two directions under Reflow (WCAG 1.4.10), and each row stays named while it does.

### In this build

- The table has column headers with aria-sort on the sorted one; each account’s name is its row’s header, and grouped rows sit in a tbody per plan with its own header row.
- Every cell says in words what it draws: “Down 14% over twelve weeks”, “8 of 25 seats used, 32%”, “At risk”. The lines, segments and dots are hidden from assistive technology; the chart is a group whose label gives its count and range, and each bar a toggle button that reads its row.
- Table, Chart and SQL are a tablist moved with the arrow keys; the density toggle is a radio group. Column headers, chips, + Filter and share are menu buttons; their menus move with the arrows, Home and End, F runs Filter, and Escape closes with the focus back on the button.
- The rows’ box is focusable: ↑, ↓, Home and End move a keyboard row and Space selects it, each read out by a polite live region, which also says sorts, groupings, removed filters and the Ask about answer. The checkboxes are role="checkbox" buttons, the header one mixed while some rows are chosen.
- Under reduced motion nothing fades, pops or spins and the demo never plays. The demo pointer is decorative.

## Source

### query-table/query-table.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useEffectEvent,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type ReactNode,
} from 'react';
import { Avatar, HealthDot, PlanPill, SeatMeter, Sparkline, describe } from './cells';
import { ACCOUNTS, OWNERS, PLANS, money, type Account, type Owner } from './data';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Icon, type IconName } from './glyphs';
import { Menu, MenuItem, MenuLabel, MenuSeparator } from './menu';
import {
  COLUMNS,
  FILTER_LABEL,
  FILTER_OF,
  MRR_STEPS,
  NO_FILTERS,
  SEAT_BANDS,
  columnLabel,
  groupRows,
  insight,
  matches,
  sortRows,
  sqlText,
  toCsv,
  toSql,
  type ColumnId,
  type FilterId,
  type Filters,
  type Sort,
} from './query';
import { useAutoplay } from './use-autoplay';
import { BarChart, SqlView } from './views';
import styles from './query-table.module.css';

/*
 * Query table: the result of a saved query, as a dark card in an analytics tool.
 *
 * - The header names the query and its row count, and switches between the rows as a table, as
 *   bars of MRR, and as the SQL that returns them (it follows every filter, sort and column).
 * - The filter chips narrow the rows: owners from a checkable list, an MRR threshold, and more
 *   from + Filter (plan, health, seat use, trend). The density toggle packs the rows tighter.
 * - Each column's header opens a menu: sort either way, filter by it (F), group the rows by plan
 *   with subtotals, hide it (a Hidden button brings it back), or ask about it: a line read from
 *   the rows in view.
 * - The footer counts the selection, walks the rows with ↑ and ↓ (Space selects) and exports the
 *   rows in view as CSV.
 * - While on screen and untouched, a demo pointer asks about Seats, groups by plan, shows the
 *   chart and the SQL, selects a row and raises the MRR threshold, in a loop.
 */

export type { Account, Owner, Plan, Health } from './data';
export type { ColumnId, Filters, Sort } from './query';

export type View = 'table' | 'chart' | 'sql';
export type Density = 'comfortable' | 'compact';
type MenuId = `column:${ColumnId}` | `chip:${FilterId}` | 'add' | 'share' | 'columns';
type MenuState = { id: MenuId; anchor: HTMLElement; byReader: boolean };

/** A moment to open in, locked: the demo stays off. Used by the docs. */
export type QueryTableState = {
  view?: View;
  filters?: Partial<Filters>;
  sort?: Sort;
  grouped?: boolean;
  density?: Density;
  hidden?: ColumnId[];
  selected?: string[];
  /** The row the keyboard stands on. */
  cursor?: string;
  /** The column whose Ask about line shows. */
  insight?: ColumnId;
  /** A menu held open. */
  menu?: MenuId;
  /** The chart's bar whose tooltip shows. */
  tip?: string;
};

const VIEWS: { id: View; label: string }[] = [
  { id: 'table', label: 'Table' },
  { id: 'chart', label: 'Chart' },
  { id: 'sql', label: 'SQL' },
];

const ADD_ICON: Record<FilterId, IconName> = {
  owners: 'filter',
  mrr: 'filter',
  plans: 'group',
  health: 'filter',
  seats: 'columns',
  trend: 'arrowDown',
};

const DEFAULT_FILTERS: Partial<Filters> = { owners: ['mara', 'teo'], mrr: 5000 };
const DEFAULT_SORT: Sort = { key: 'mrr', desc: true };

/** What a filter starts at when it is added. */
const fresh = (id: FilterId, owners: Owner[]): Filters[FilterId] => {
  const start: Filters = {
    owners: owners.map((o) => o.id),
    mrr: 5000,
    plans: [...PLANS],
    health: 'risk',
    seats: 'under50',
    trend: 'falling',
  };
  return start[id];
};

/** How long a query takes to run, from its filters: the same filters, the same time. */
function runtime(filters: Filters) {
  let hash = 7;
  for (const char of JSON.stringify(filters)) hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
  return (2 + (hash % 5)) / 10;
}

export function QueryTable({
  rows: source = ACCOUNTS,
  owners = OWNERS,
  title = 'Accounts by MRR',
  total = 1284,
  defaultFilters = DEFAULT_FILTERS,
  defaultSort = DEFAULT_SORT,
  defaultSelected = ['brightwater'],
  defaultState,
  onSelectionChange,
  onExport,
  autoplay = true,
  colorScheme,
  className = '',
}: {
  /** The rows the query can return: a sample of the result, filtered here. */
  rows?: Account[];
  /** Everyone who can own an account. */
  owners?: Owner[];
  /** The query's name. */
  title?: string;
  /** How many rows the query returns with its default filters; the counts scale from it. */
  total?: number;
  defaultFilters?: Partial<Filters>;
  defaultSort?: Sort;
  /** Row ids selected at first. */
  defaultSelected?: string[];
  /** Opens locked in a moment, with the demo off. */
  defaultState?: QueryTableState;
  /** Called with the selected row ids when they change. */
  onSelectionChange?: (ids: string[]) => void;
  /** Called with the CSV when Export saves the rows in view. */
  onExport?: (csv: string, rows: Account[]) => void;
  autoplay?: boolean;
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const uid = useId();
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>(9000);
  const pointer = useRef<HTMLSpanElement>(null);
  const scroller = useRef<HTMLDivElement>(null);
  const locked = defaultState !== undefined;
  const s = defaultState ?? {};

  const start = useMemo(
    () => ({
      filters: { ...NO_FILTERS, ...defaultFilters },
      sort: defaultSort,
      selected: defaultSelected,
    }),
    // Only the first values count.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const [view, setView] = useState<View>(s.view ?? 'table');
  const [filters, setFilters] = useState<Filters>({ ...start.filters, ...s.filters });
  const [sort, setSort] = useState<Sort>(s.sort ?? start.sort);
  const [grouped, setGrouped] = useState(s.grouped ?? false);
  const [density, setDensity] = useState<Density>(s.density ?? 'comfortable');
  const [hidden, setHidden] = useState<ColumnId[]>(s.hidden ?? []);
  const [selected, setSelected] = useState<Set<string>>(new Set(s.selected ?? start.selected));
  const [cursor, setCursor] = useState<string | null>(s.cursor ?? null);
  const [asked, setAsked] = useState<{ column: ColumnId; ready: boolean } | null>(
    s.insight ? { column: s.insight, ready: true } : null,
  );
  const [menu, setMenu] = useState<MenuState | null>(null);
  const [want, setWant] = useState<{ id: MenuId; byReader: boolean } | null>(
    s.menu ? { id: s.menu, byReader: false } : null,
  );
  const [running, setRunning] = useState(false);
  const [toast, setToast] = useState<{ n: number; text: string } | null>(null);
  const [live, setLive] = useState('');

  // ---- The rows in view --------------------------------------------------------------------------

  const inView = useMemo(
    () =>
      sortRows(
        source.filter((row) => matches(row, filters)),
        sort,
      ),
    [source, filters, sort],
  );
  const groups = useMemo(() => (grouped ? groupRows(inView) : null), [grouped, inView]);
  const ordered = groups ? groups.flatMap((g) => g.rows) : inView;
  const base = source.filter((row) => matches(row, start.filters)).length;
  const matched = base ? Math.round((total * inView.length) / base) : inView.length;
  const shown = COLUMNS.filter((c) => !hidden.includes(c.id));
  const chosen = ordered.filter((row) => selected.has(row.id));
  const ownerOf = (id: string) => owners.find((o) => o.id === id);

  const sql = useMemo(
    () => toSql({ title, filters, sort, grouped, hidden, owners }),
    [title, filters, sort, grouped, hidden, owners],
  );

  // ---- Changes -----------------------------------------------------------------------------------

  const say = (text: string, visible = false) => {
    setLive(text);
    if (visible) setToast((now) => ({ n: (now?.n ?? 0) + 1, text }));
  };

  useEffect(() => {
    if (!toast) return;
    const timer = window.setTimeout(() => setToast(null), 2600);
    return () => window.clearTimeout(timer);
  }, [toast]);

  // A change of filters runs the query again: a beat of Running…, then the new count.
  const signature = JSON.stringify(filters);
  const ran = useRef(signature);
  useEffect(() => {
    if (ran.current === signature) return;
    ran.current = signature;
    setRunning(true);
    const timer = window.setTimeout(() => setRunning(false), 420);
    return () => window.clearTimeout(timer);
  }, [signature]);

  // Ask about reads the rows for a beat, then writes its line, and the live region reads it out.
  const readOut = useEffectEvent((column: ColumnId) => setLive(insight(column, inView, owners)));
  useEffect(() => {
    if (!asked || asked.ready) return;
    const timer = window.setTimeout(() => {
      setAsked((now) => (now ? { ...now, ready: true } : now));
      readOut(asked.column);
    }, 700);
    return () => window.clearTimeout(timer);
  }, [asked]);

  const announceSelection = useEffectEvent((ids: string[]) => onSelectionChange?.(ids));
  const lastSelection = useRef(selected);
  useEffect(() => {
    if (lastSelection.current === selected) return;
    lastSelection.current = selected;
    announceSelection([...selected]);
  }, [selected]);

  const openMenu = (id: MenuId, anchor: HTMLElement, byReader = true) =>
    setMenu((now) => (now?.id === id ? null : { id, anchor, byReader }));
  const closeMenu = (back: boolean) => {
    if (back) menu?.anchor.focus();
    setMenu(null);
  };

  // A menu asked for before its trigger was drawn (a chip just added, a locked state).
  useLayoutEffect(() => {
    if (!want) return;
    const stage = root.current;
    const key = want.id.includes(':') ? want.id : `${want.id}:`;
    const anchor = stage?.querySelector<HTMLElement>(`[data-menu="${key}"]`);
    if (anchor) setMenu({ id: want.id, anchor, byReader: want.byReader });
    setWant(null);
  }, [want, root]);

  const setFilter = <K extends FilterId>(id: K, value: Filters[K]) =>
    setFilters((now) => ({ ...now, [id]: value }));

  /** Opens a filter's menu, adding its chip first when there is none. */
  const editFilter = (id: FilterId, byReader = true) => {
    if (filters[id] === null) setFilter(id, fresh(id, owners));
    setMenu(null);
    setWant({ id: `chip:${id}`, byReader });
  };

  const removeFilter = (id: FilterId) => {
    setFilter(id, null);
    say(`${FILTER_LABEL[id]} filter removed`);
  };

  const sortBy = (key: ColumnId, desc: boolean) => {
    setSort({ key, desc });
    say(`Sorted by ${columnLabel(key)}, ${desc ? 'descending' : 'ascending'}`);
  };

  const toggleRow = (id: string) =>
    setSelected((now) => {
      const next = new Set(now);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });

  const moveCursor = (step: number | 'first' | 'last') => {
    if (!ordered.length) return;
    const i = ordered.findIndex((row) => row.id === cursor);
    const to =
      step === 'first'
        ? 0
        : step === 'last'
          ? ordered.length - 1
          : i < 0
            ? step > 0
              ? 0
              : ordered.length - 1
            : Math.max(0, Math.min(ordered.length - 1, i + step));
    const row = ordered[to];
    setCursor(row.id);
    say(
      `${describe(row)}. Row ${to + 1} of ${ordered.length}${selected.has(row.id) ? ', selected' : ''}`,
    );
    requestAnimationFrame(() =>
      scroller.current
        ?.querySelector(`[data-row="${row.id}"]`)
        ?.scrollIntoView({ block: 'nearest' }),
    );
  };

  const onTableKey = (event: ReactKeyboardEvent) => {
    if (event.target !== event.currentTarget) return;
    if (event.key === 'ArrowDown') moveCursor(1);
    else if (event.key === 'ArrowUp') moveCursor(-1);
    else if (event.key === 'Home') moveCursor('first');
    else if (event.key === 'End') moveCursor('last');
    else if (event.key === ' ' && cursor) {
      toggleRow(cursor);
      const row = ordered.find((r) => r.id === cursor);
      say(`${row?.name} ${selected.has(cursor) ? 'deselected' : 'selected'}`);
    } else if (event.key === 'Escape') setCursor(null);
    else return;
    event.preventDefault();
  };

  const ask = (column: ColumnId) => {
    setAsked({ column, ready: false });
    setMenu(null);
  };

  const copy = (text: string, what: string) => {
    navigator.clipboard?.writeText(text).then(
      () => say(`${what} copied`, true),
      () => say(`Couldn’t copy the ${what.toLowerCase()}`, true),
    );
  };

  const exportCsv = () => {
    const csv = toCsv(ordered, hidden, owners);
    onExport?.(csv, ordered);
    const link = document.createElement('a');
    link.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
    link.download = `${title.toLowerCase().replace(/[^a-z0-9]+/g, '-')}.csv`;
    link.click();
    URL.revokeObjectURL(link.href);
    say(`Exported ${ordered.length} ${ordered.length === 1 ? 'row' : 'rows'} as CSV`, true);
  };

  // ---- The demo ----------------------------------------------------------------------------------

  const demo = autoplay && !locked && playing;
  const dirty = useEffectEvent(
    () =>
      view !== 'table' ||
      grouped ||
      asked !== null ||
      JSON.stringify(filters) !== JSON.stringify(start.filters) ||
      selected.size !== start.selected.length,
  );
  const reset = useEffectEvent(() => {
    setView('table');
    setFilters(start.filters);
    setSort(start.sort);
    setGrouped(false);
    setDensity('comfortable');
    setHidden([]);
    setSelected(new Set(start.selected));
    setCursor(null);
    setAsked(null);
    setMenu(null);
  });
  const demoClear = useEffectEvent(() => setMenu(null));

  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    const find = (name: string) => stage.querySelector<HTMLElement>(`[data-demo="${name}"]`);
    const on = (element: Element | null, fx = 0.5, fy = 0.5): Point => {
      const frame = stage.getBoundingClientRect();
      const scale = frame.width / stage.offsetWidth || 1;
      const rect = element?.getBoundingClientRect() ?? frame;
      return {
        x: (rect.left + rect.width * fx - frame.left) / scale,
        y: (rect.top + rect.height * fy - frame.top) / scale,
      };
    };
    let over: HTMLElement | null = null;
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      const press = async (name: string, ms: number, after: number, fx = 0.5, fy = 0.5) => {
        const element = find(name);
        if (!element) return;
        const box = element.closest<HTMLElement>('[data-part="scroller"]');
        if (box) {
          const b = box.getBoundingClientRect();
          const r = element.getBoundingClientRect();
          if (r.right > b.right || r.left < b.left) {
            box.scrollBy({ left: r.left - b.left - b.width / 2 + r.width / 2, behavior: 'smooth' });
            await wait(420);
          }
        }
        glyph('arrow');
        await glide(on(element, fx, fy), ms);
        glyph('hand');
        over = element;
        element.dataset.over = '';
        await wait(240);
        const current = find(name) ?? element;
        delete element.dataset.over;
        over = null;
        current.click();
        await wait(after);
      };
      for (;;) {
        if (dirty()) {
          reset();
          await wait(400);
        }
        await wait(900);
        // What the seats say, then the rows by plan.
        await press('head-seats', 750, 650, 0.35);
        await press('menu-ask', 560, 2600, 0.3);
        await press('head-seats', 600, 600, 0.35);
        await press('menu-group', 520, 1700, 0.3);
        // The same rows as bars, then as SQL.
        await press('view-chart', 760, 2100);
        await press('view-sql', 420, 2300);
        await press('view-table', 480, 700);
        // One more row picked, and a higher bar for MRR.
        await press('check-quayside', 700, 900);
        await press('chip-mrr', 760, 600, 0.4);
        await press('mrr-10000', 520, 2000, 0.3);
        glyph('arrow');
        await glide(on(stage, 0.84, 0.94), 800);
        await wait(1600);
      }
    });
    return () => {
      stop();
      if (over) delete over.dataset.over;
      demoClear();
    };
  }, [demo, root]);

  // ---- Drawing -----------------------------------------------------------------------------------

  const allChecked = ordered.length > 0 && ordered.every((row) => selected.has(row.id));
  const someChecked = ordered.some((row) => selected.has(row.id));

  const chip = (id: FilterId, value: ReactNode, lead?: ReactNode) => (
    <span key={id} className={styles.chip} data-part="filter-chip">
      <button
        type="button"
        className={styles.chipMain}
        aria-haspopup="menu"
        aria-expanded={menu?.id === `chip:${id}`}
        data-menu={`chip:${id}`}
        data-demo={`chip-${id}`}
        onClick={(event) => openMenu(`chip:${id}`, event.currentTarget)}
      >
        <span className={styles.chipKey}>{FILTER_LABEL[id]}</span>
        {lead}
        <span className={styles.chipValue}>{value}</span>
      </button>
      <button
        type="button"
        className={styles.chipX}
        aria-label={`Remove the ${FILTER_LABEL[id]} filter`}
        onClick={() => removeFilter(id)}
      >
        <Icon name="close" width={2} />
      </button>
    </span>
  );

  const chips: ReactNode[] = [];
  if (filters.owners) {
    const people = filters.owners.map(ownerOf).filter((o): o is Owner => !!o);
    const names = people.map((p) => p.name.split(' ')[0]);
    chips.push(
      chip(
        'owners',
        names.length === 0
          ? 'None'
          : names.length > 2
            ? `${names.slice(0, 2).join(', ')} +${names.length - 2}`
            : names.join(', '),
        people.length > 0 && (
          <span className={styles.faces}>
            {people.slice(0, 3).map((p) => (
              <Avatar key={p.id} owner={p} />
            ))}
          </span>
        ),
      ),
    );
  }
  if (filters.mrr !== null)
    chips.push(chip('mrr', `> $${filters.mrr >= 1000 ? `${filters.mrr / 1000}k` : filters.mrr}`));
  if (filters.plans)
    chips.push(
      chip(
        'plans',
        filters.plans.length === PLANS.length
          ? 'Any'
          : filters.plans.length
            ? filters.plans.join(', ')
            : 'None',
      ),
    );
  if (filters.health) chips.push(chip('health', filters.health === 'risk' ? 'At risk' : 'Healthy'));
  if (filters.seats)
    chips.push(chip('seats', SEAT_BANDS.find((b) => b.id === filters.seats)!.label));
  if (filters.trend) chips.push(chip('trend', filters.trend === 'rising' ? 'Rising' : 'Falling'));

  const head = (column: (typeof COLUMNS)[number]) => {
    const active = sort.key === column.id;
    const open = menu?.id === `column:${column.id}`;
    return (
      <th
        key={column.id}
        scope="col"
        data-col={column.id}
        aria-sort={active ? (sort.desc ? 'descending' : 'ascending') : undefined}
      >
        <button
          type="button"
          className={styles.head}
          aria-haspopup="menu"
          aria-expanded={open}
          data-active={active || undefined}
          data-menu={`column:${column.id}`}
          data-demo={`head-${column.id}`}
          data-part="column-head"
          onClick={(event) => openMenu(`column:${column.id}`, event.currentTarget)}
        >
          {active && (
            <Icon
              name={sort.desc ? 'arrowDown' : 'arrowUp'}
              className={styles.sortIcon}
              width={2.2}
            />
          )}
          <span>{column.label}</span>
          <Icon name="chevronDown" className={styles.headChevron} width={2.2} />
        </button>
      </th>
    );
  };

  const cell = (row: Account, column: ColumnId) => {
    switch (column) {
      case 'account':
        return (
          <th key={column} scope="row" data-col="account">
            <span className={styles.name}>{row.name}</span>
            <span className={styles.srOnly}>, owner {ownerOf(row.owner)?.name}</span>
          </th>
        );
      case 'plan':
        return (
          <td key={column} data-col="plan">
            <PlanPill plan={row.plan} />
          </td>
        );
      case 'mrr':
        return (
          <td key={column} data-col="mrr">
            ${money(row.mrr)}
          </td>
        );
      case 'trend':
        return (
          <td key={column} data-col="trend">
            <Sparkline values={row.trend} />
          </td>
        );
      case 'seats':
        return (
          <td key={column} data-col="seats">
            <SeatMeter used={row.seats.used} total={row.seats.total} />
          </td>
        );
      case 'health':
        return (
          <td key={column} data-col="health">
            <HealthDot health={row.health} />
          </td>
        );
    }
  };

  const rowOf = (row: Account) => {
    const checked = selected.has(row.id);
    return (
      <tr
        key={row.id}
        data-row={row.id}
        data-part="row"
        data-selected={checked || undefined}
        data-cursor={cursor === row.id || undefined}
        onClick={(event) => {
          if ((event.target as HTMLElement).closest('button')) return;
          setCursor(row.id);
        }}
      >
        <td data-col="check">
          <button
            type="button"
            role="checkbox"
            className={styles.check}
            aria-checked={checked}
            aria-label={`Select ${row.name}`}
            data-demo={`check-${row.id}`}
            onClick={() => {
              toggleRow(row.id);
              setCursor(row.id);
            }}
          >
            <Icon name="check" width={3} />
          </button>
        </td>
        {shown.map((column) => cell(row, column.id))}
      </tr>
    );
  };

  const groupHead = (group: NonNullable<typeof groups>[number]) => (
    <tr className={styles.groupRow} data-part="group-row">
      <td data-col="check" />
      {shown.map((column) => {
        switch (column.id) {
          case 'account':
            return (
              <th key={column.id} scope="rowgroup" data-col="account">
                <span className={styles.groupName}>
                  <span className={styles.groupKey} data-plan={group.plan.toLowerCase()} />
                  {group.plan}
                </span>
                <span className={styles.groupCount}>
                  {group.rows.length} {group.rows.length === 1 ? 'account' : 'accounts'}
                </span>
              </th>
            );
          case 'mrr':
            return (
              <td key={column.id} data-col="mrr" className={styles.subtotal}>
                ${money(group.mrr)}
              </td>
            );
          case 'seats':
            return (
              <td key={column.id} data-col="seats" className={styles.groupNote}>
                avg {group.seats}%
              </td>
            );
          case 'health':
            return (
              <td key={column.id} data-col="health" className={styles.groupNote}>
                {group.risk ? `${group.risk} at risk` : ''}
              </td>
            );
          default:
            return <td key={column.id} data-col={column.id} />;
        }
      })}
    </tr>
  );

  // The rows' box takes the focus so the arrows can walk it (and scroll it); the rows stay a table.
  const table = (
    // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
    <div
      ref={scroller}
      className={styles.scroller}
      data-part="scroller"
      // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
      tabIndex={0}
      role="group"
      aria-label={`${title}: ↑ and ↓ move between rows, Space selects`}
      onKeyDown={onTableKey}
      onBlur={(event) => {
        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setCursor(null);
      }}
    >
      <table className={styles.table} aria-labelledby={`${uid}-title`}>
        <thead>
          <tr>
            <th scope="col" data-col="check">
              <button
                type="button"
                role="checkbox"
                className={styles.check}
                aria-checked={allChecked ? true : someChecked ? 'mixed' : false}
                aria-label="Select every row in view"
                onClick={() =>
                  setSelected(allChecked ? new Set() : new Set(ordered.map((row) => row.id)))
                }
              >
                <Icon name={someChecked && !allChecked ? 'minus' : 'check'} width={3} />
              </button>
            </th>
            {shown.map(head)}
          </tr>
        </thead>
        {groups ? (
          groups.map((group) => (
            <tbody key={group.plan} aria-label={group.plan}>
              {groupHead(group)}
              {group.rows.map(rowOf)}
            </tbody>
          ))
        ) : (
          <tbody>{inView.map(rowOf)}</tbody>
        )}
        {ordered.length === 0 && (
          <tbody>
            <tr>
              <td colSpan={shown.length + 1} className={styles.none}>
                No accounts match these filters.{' '}
                <button
                  type="button"
                  className={styles.linkButton}
                  onClick={() => setFilters(start.filters)}
                >
                  Reset filters
                </button>
              </td>
            </tr>
          </tbody>
        )}
      </table>
    </div>
  );

  const unset = (Object.keys(FILTER_LABEL) as FilterId[]).filter((id) => filters[id] === null);
  const column = menu?.id.startsWith('column:') ? (menu.id.slice(7) as ColumnId) : null;
  const chipMenu = menu?.id.startsWith('chip:') ? (menu.id.slice(5) as FilterId) : null;

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      data-density={density}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onWheel={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <section className={styles.card} data-part="card" aria-labelledby={`${uid}-title`}>
        <header className={styles.header} data-part="header">
          <span className={styles.badge} aria-hidden="true">
            <Icon name="table" />
          </span>
          <div className={styles.titles}>
            <h2 id={`${uid}-title`} className={styles.title}>
              {title}
            </h2>
            <p className={styles.meta} data-running={running || undefined}>
              {running ? (
                'Running…'
              ) : (
                <>
                  {matched.toLocaleString('en-US')} rows · ran {runtime(filters)} s
                </>
              )}
            </p>
          </div>
          <div className={styles.headerEnd}>
            <div
              className={styles.views}
              role="tablist"
              aria-label="Show the result as"
              data-part="view-switch"
            >
              {VIEWS.map((v) => (
                <button
                  key={v.id}
                  type="button"
                  role="tab"
                  id={`${uid}-tab-${v.id}`}
                  aria-selected={view === v.id}
                  aria-controls={`${uid}-panel`}
                  tabIndex={view === v.id ? 0 : -1}
                  className={styles.viewTab}
                  data-demo={`view-${v.id}`}
                  onClick={() => setView(v.id)}
                  onKeyDown={(event) => {
                    if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;
                    event.preventDefault();
                    const i = VIEWS.findIndex((x) => x.id === view);
                    const next =
                      VIEWS[
                        (i + (event.key === 'ArrowRight' ? 1 : VIEWS.length - 1)) % VIEWS.length
                      ];
                    setView(next.id);
                    document.getElementById(`${uid}-tab-${next.id}`)?.focus();
                  }}
                >
                  {v.label}
                </button>
              ))}
            </div>
            <button
              type="button"
              className={styles.iconButton}
              aria-label="Share or export"
              aria-haspopup="menu"
              aria-expanded={menu?.id === 'share'}
              data-menu="share:"
              onClick={(event) => openMenu('share', event.currentTarget)}
            >
              <Icon name="share" />
            </button>
          </div>
        </header>

        <div className={styles.panel} data-part="panel" data-running={running || undefined}>
          <div className={styles.filters} data-part="filters">
            <div className={styles.chips}>
              {chips}
              <button
                type="button"
                className={styles.addFilter}
                aria-haspopup="menu"
                aria-expanded={menu?.id === 'add'}
                data-menu="add:"
                data-demo="add"
                onClick={(event) => openMenu('add', event.currentTarget)}
              >
                <Icon name="plus" width={2} />
                Filter
              </button>
            </div>
            <div className={styles.tools}>
              {hidden.length > 0 && (
                <button
                  type="button"
                  className={styles.hiddenButton}
                  aria-haspopup="menu"
                  aria-expanded={menu?.id === 'columns'}
                  data-menu="columns:"
                  onClick={(event) => openMenu('columns', event.currentTarget)}
                >
                  <Icon name="eyeOff" />
                  {hidden.length} hidden
                </button>
              )}
              <div
                className={styles.density}
                role="radiogroup"
                aria-label="Row density"
                data-part="density"
              >
                {(['comfortable', 'compact'] as Density[]).map((d) => (
                  <button
                    key={d}
                    type="button"
                    role="radio"
                    aria-checked={density === d}
                    aria-label={d === 'comfortable' ? 'Comfortable rows' : 'Compact rows'}
                    tabIndex={density === d ? 0 : -1}
                    className={styles.densityButton}
                    data-density-option={d}
                    onClick={() => setDensity(d)}
                    onKeyDown={(event) => {
                      if (!['ArrowRight', 'ArrowLeft', 'ArrowUp', 'ArrowDown'].includes(event.key))
                        return;
                      event.preventDefault();
                      const next = density === 'comfortable' ? 'compact' : 'comfortable';
                      setDensity(next);
                      event.currentTarget.parentElement
                        ?.querySelector<HTMLElement>(`[data-density-option="${next}"]`)
                        ?.focus();
                    }}
                  >
                    <Icon name={d} />
                  </button>
                ))}
              </div>
            </div>
          </div>

          {asked && (
            <div
              className={styles.insight}
              data-part="insight"
              data-ready={asked.ready || undefined}
            >
              <Icon name="spark" className={styles.insightIcon} />
              <p className={styles.insightText}>
                <span className={styles.insightKey}>{columnLabel(asked.column)}</span>
                {asked.ready ? (
                  insight(asked.column, inView, owners)
                ) : (
                  <span className={styles.thinking}>Reading {inView.length} rows…</span>
                )}
              </p>
              <button
                type="button"
                className={styles.insightClose}
                aria-label="Dismiss the answer"
                onClick={() => setAsked(null)}
              >
                <Icon name="close" width={2} />
              </button>
            </div>
          )}

          <div
            className={styles.body}
            role="tabpanel"
            id={`${uid}-panel`}
            aria-labelledby={`${uid}-tab-${view}`}
          >
            {view === 'table' && table}
            {view === 'chart' && (
              <BarChart
                rows={inView}
                groups={groups}
                selected={selected}
                owners={owners}
                defaultTip={s.tip}
                onToggle={toggleRow}
              />
            )}
            {view === 'sql' && <SqlView lines={sql} onCopy={() => copy(sqlText(sql), 'SQL')} />}
          </div>
        </div>

        <footer className={styles.footer} data-part="footer">
          <p className={styles.count} aria-live="polite">
            {chosen.length > 0 && <strong>{chosen.length} selected</strong>}
            <span className={styles.showing}>
              {chosen.length > 0 ? ' · s' : 'S'}howing {ordered.length} of{' '}
              {matched.toLocaleString('en-US')}
            </span>
          </p>
          <div className={styles.nav}>
            <button
              type="button"
              className={styles.iconButton}
              aria-label="Previous row"
              disabled={view !== 'table'}
              onClick={() => moveCursor(-1)}
            >
              <Icon name="arrowUp" />
            </button>
            <button
              type="button"
              className={styles.iconButton}
              aria-label="Next row"
              disabled={view !== 'table'}
              onClick={() => moveCursor(1)}
            >
              <Icon name="arrowDown" />
            </button>
            <span className={styles.navLabel} aria-hidden="true">
              Navigate
            </span>
          </div>
          <button type="button" className={styles.export} onClick={exportCsv}>
            <Icon name="share" />
            Export
          </button>
        </footer>
      </section>

      {menu && (
        <Menu
          anchor={menu.anchor}
          label={menuLabel(menu.id)}
          align={menu.id === 'share' || column === 'health' ? 'end' : 'start'}
          takeFocus={menu.byReader}
          onClose={closeMenu}
          shortcuts={column ? { f: () => editFilter(FILTER_OF[column]) } : undefined}
        >
          {column && (
            <>
              <MenuItem
                kind="radio"
                icon="arrowUp"
                checked={sort.key === column && !sort.desc}
                onSelect={() => {
                  sortBy(column, false);
                  closeMenu(true);
                }}
              >
                Sort ascending
              </MenuItem>
              <MenuItem
                kind="radio"
                icon="arrowDown"
                checked={sort.key === column && sort.desc}
                onSelect={() => {
                  sortBy(column, true);
                  closeMenu(true);
                }}
              >
                Sort descending
              </MenuItem>
              <MenuItem icon="filter" kbd="F" onSelect={() => editFilter(FILTER_OF[column])}>
                Filter
              </MenuItem>
              <MenuItem
                kind="checkbox"
                icon="group"
                checked={grouped}
                demo="menu-group"
                onSelect={() => {
                  setGrouped(!grouped);
                  say(grouped ? 'Ungrouped' : 'Grouped by plan, with subtotals');
                  closeMenu(true);
                }}
              >
                Group by plan
              </MenuItem>
              <MenuItem
                icon="eyeOff"
                disabled={column === 'account'}
                onSelect={() => {
                  setHidden((now) => [...now, column]);
                  say(`${columnLabel(column)} hidden`);
                  closeMenu(false);
                }}
              >
                Hide column
              </MenuItem>
              <MenuSeparator />
              <MenuItem icon="spark" tone="accent" demo="menu-ask" onSelect={() => ask(column)}>
                Ask about {columnLabel(column)}
              </MenuItem>
            </>
          )}
          {chipMenu === 'owners' &&
            owners.map((p) => {
              const on = filters.owners?.includes(p.id) ?? false;
              return (
                <MenuItem
                  key={p.id}
                  kind="checkbox"
                  checked={on}
                  lead={<Avatar owner={p} />}
                  trail={source.filter((r) => r.owner === p.id).length}
                  onSelect={() =>
                    setFilter(
                      'owners',
                      on
                        ? (filters.owners ?? []).filter((id) => id !== p.id)
                        : [...(filters.owners ?? []), p.id],
                    )
                  }
                >
                  {p.name}
                </MenuItem>
              );
            })}
          {chipMenu === 'mrr' && (
            <>
              <MenuLabel>MRR greater than</MenuLabel>
              {MRR_STEPS.map((step) => (
                <MenuItem
                  key={step}
                  kind="radio"
                  checked={filters.mrr === step}
                  demo={`mrr-${step}`}
                  trail={source.filter((r) => matches(r, { ...filters, mrr: step })).length}
                  onSelect={() => {
                    setFilter('mrr', step);
                    closeMenu(true);
                  }}
                >
                  ${money(step)}
                </MenuItem>
              ))}
            </>
          )}
          {chipMenu === 'plans' &&
            PLANS.map((plan) => {
              const on = filters.plans?.includes(plan) ?? false;
              return (
                <MenuItem
                  key={plan}
                  kind="checkbox"
                  checked={on}
                  lead={<PlanPill plan={plan} />}
                  trail={source.filter((r) => r.plan === plan).length}
                  onSelect={() =>
                    setFilter(
                      'plans',
                      on
                        ? (filters.plans ?? []).filter((p) => p !== plan)
                        : PLANS.filter((p) => p === plan || filters.plans?.includes(p)),
                    )
                  }
                >
                  <span className={styles.srOnly}>{plan}</span>
                </MenuItem>
              );
            })}
          {chipMenu === 'health' &&
            (['risk', 'ok'] as const).map((h) => (
              <MenuItem
                key={h}
                kind="radio"
                checked={filters.health === h}
                lead={<HealthDot health={h} />}
                onSelect={() => {
                  setFilter('health', h);
                  closeMenu(true);
                }}
              >
                {h === 'risk' ? 'At risk' : 'Healthy'}
              </MenuItem>
            ))}
          {chipMenu === 'seats' &&
            SEAT_BANDS.map((band) => (
              <MenuItem
                key={band.id}
                kind="radio"
                checked={filters.seats === band.id}
                onSelect={() => {
                  setFilter('seats', band.id);
                  closeMenu(true);
                }}
              >
                {band.label}
              </MenuItem>
            ))}
          {chipMenu === 'trend' &&
            (['rising', 'falling'] as const).map((d) => (
              <MenuItem
                key={d}
                kind="radio"
                icon={d === 'rising' ? 'arrowUp' : 'arrowDown'}
                checked={filters.trend === d}
                onSelect={() => {
                  setFilter('trend', d);
                  closeMenu(true);
                }}
              >
                {d === 'rising' ? 'Rising over 12 weeks' : 'Falling over 12 weeks'}
              </MenuItem>
            ))}
          {menu.id === 'add' &&
            (unset.length ? (
              unset.map((id) => (
                <MenuItem
                  key={id}
                  icon={ADD_ICON[id]}
                  onSelect={() => editFilter(id, menu.byReader)}
                >
                  {FILTER_LABEL[id]}
                </MenuItem>
              ))
            ) : (
              <MenuItem disabled onSelect={() => {}}>
                Every filter is in use
              </MenuItem>
            ))}
          {menu.id === 'columns' &&
            COLUMNS.map((c) => (
              <MenuItem
                key={c.id}
                kind="checkbox"
                checked={!hidden.includes(c.id)}
                disabled={c.id === 'account'}
                onSelect={() =>
                  setHidden((now) =>
                    now.includes(c.id) ? now.filter((x) => x !== c.id) : [...now, c.id],
                  )
                }
              >
                {c.label}
              </MenuItem>
            ))}
          {menu.id === 'share' && (
            <>
              <MenuItem
                icon="copy"
                onSelect={() => {
                  copy(sqlText(sql), 'SQL');
                  closeMenu(true);
                }}
              >
                Copy SQL
              </MenuItem>
              <MenuItem
                icon="link"
                onSelect={() => {
                  copy(toCsv(ordered, hidden, owners), 'CSV');
                  closeMenu(true);
                }}
              >
                Copy rows as CSV
              </MenuItem>
              <MenuItem
                icon="download"
                onSelect={() => {
                  exportCsv();
                  closeMenu(true);
                }}
              >
                Download CSV
              </MenuItem>
            </>
          )}
        </Menu>
      )}

      {toast && (
        <div key={toast.n} className={styles.toast} aria-hidden="true">
          <Icon name="check" width={2.4} />
          {toast.text}
        </div>
      )}
      <p className={styles.srOnly} role="status">
        {live}
      </p>

      <div className={styles.pointerLayer}>
        <DemoPointer
          ref={pointer}
          className={styles.pointer}
          arrowClass={styles.arrow}
          handClass={styles.hand}
        />
      </div>
    </div>
  );
}

function menuLabel(id: MenuId) {
  if (id.startsWith('column:')) return `${columnLabel(id.slice(7) as ColumnId)} column`;
  if (id.startsWith('chip:')) return `${FILTER_LABEL[id.slice(5) as FilterId]} filter`;
  if (id === 'add') return 'Add a filter';
  if (id === 'columns') return 'Columns shown';
  return 'Share or export';
}
```

### query-table/cells.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { change, seatShare, type Account, type Health, type Owner, type Plan } from './data';
import styles from './query-table.module.css';

/*
 * The cells: the plan as a tinted pill, twelve weeks of MRR as a line with its end dot, seats as a
 * row of segments with the percent, and health as a dot. Each says in words what it draws; the
 * drawing itself is hidden from assistive technology.
 */

export function PlanPill({ plan }: { plan: Plan }) {
  return (
    <span className={styles.plan} data-plan={plan.toLowerCase()} data-part="plan-pill">
      {plan}
    </span>
  );
}

const SPARK = { w: 58, h: 20, pad: 2.5 };

/** The trend: blue when the twelve weeks end higher than they began, red when lower. */
export function Sparkline({ values }: { values: number[] }) {
  const min = Math.min(...values);
  const max = Math.max(...values);
  const span = max - min || 1;
  const points = values.map((value, i) => ({
    x: SPARK.pad + (i / (values.length - 1)) * (SPARK.w - SPARK.pad * 2),
    y: SPARK.pad + (1 - (value - min) / span) * (SPARK.h - SPARK.pad * 2),
  }));
  const end = points[points.length - 1];
  const delta = values[values.length - 1] / values[0] - 1;
  const rising = delta >= 0;
  return (
    <span className={styles.spark} data-dir={rising ? 'up' : 'down'} data-part="sparkline">
      <svg viewBox={`0 0 ${SPARK.w} ${SPARK.h}`} aria-hidden="true">
        <polyline
          points={points.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ')}
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinejoin="round"
          strokeLinecap="round"
          vectorEffect="non-scaling-stroke"
        />
        <circle cx={end.x} cy={end.y} r="2.1" fill="currentColor" />
      </svg>
      <span className={styles.srOnly}>
        {rising ? 'Up' : 'Down'} {Math.abs(Math.round(delta * 100))}% over twelve weeks
      </span>
    </span>
  );
}

export const SEGMENTS = 12;

/** Seats used as segments; under half used, the lit segments fade and the percent greys. */
export function SeatMeter({ used, total }: { used: number; total: number }) {
  const share = Math.round((used / total) * 100);
  const on = Math.round((used / total) * SEGMENTS);
  return (
    <span className={styles.seats} data-low={share < 50 || undefined} data-part="seat-meter">
      <span className={styles.segments} aria-hidden="true">
        {Array.from({ length: SEGMENTS }, (_, i) => (
          <span key={i} className={styles.segment} data-on={i < on || undefined} />
        ))}
      </span>
      <span className={styles.seatPct} aria-hidden="true">
        {share}%
      </span>
      <span className={styles.srOnly}>
        {used} of {total} seats used, {share}%
      </span>
    </span>
  );
}

export function HealthDot({ health }: { health: Health }) {
  return (
    <span className={styles.health} data-health={health} data-part="health-dot">
      <span className={styles.healthDot} aria-hidden="true" />
      <span className={styles.srOnly}>{health === 'risk' ? 'At risk' : 'Healthy'}</span>
    </span>
  );
}

export function Avatar({ owner }: { owner: Owner }) {
  return (
    <span className={styles.avatar} data-tone={owner.tone} aria-hidden="true">
      {owner.name[0]}
    </span>
  );
}

/** What a row's cells say, in one line: for the chart's tooltip and the live region. */
export const describe = (row: Account) =>
  `${row.name}, ${row.plan}, $${row.mrr.toLocaleString('en-US')} MRR, ${change(row) >= 0 ? 'up' : 'down'} ${Math.abs(Math.round(change(row) * 100))}%, ${seatShare(row)}% of seats, ${row.health === 'risk' ? 'at risk' : 'healthy'}`;
```

### query-table/views.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useState } from 'react';
import { Avatar, describe } from './cells';
import { money, shortMoney, type Account, type Owner } from './data';
import { Icon } from './glyphs';
import type { Group, Token } from './query';
import styles from './query-table.module.css';

/*
 * The other two views of the same result: the rows as horizontal bars of MRR, in the table's
 * order and grouping, and the SQL that returns them, coloured by kind and read-only.
 */

/** A round top for the axis: 48,200 → 50,000. */
function niceMax(value: number) {
  const step = 10 ** Math.floor(Math.log10(Math.max(1, value)));
  return Math.ceil(value / (step / 2)) * (step / 2);
}

type Tip = { id: string; x: number; y: number };

export function BarChart({
  rows,
  groups,
  selected,
  owners,
  onToggle,
  defaultTip,
}: {
  rows: Account[];
  /** When grouped by plan: the groups, in order, with their subtotals. */
  groups: Group[] | null;
  selected: Set<string>;
  owners: Owner[];
  onToggle: (id: string) => void;
  /** The row whose tooltip shows at first (docs). */
  defaultTip?: string;
}) {
  const [tip, setTip] = useState<Tip | null>(defaultTip ? { id: defaultTip, x: -1, y: -1 } : null);
  const max = niceMax(Math.max(1, ...rows.map((row) => row.mrr)));
  const total = rows.reduce((sum, row) => sum + row.mrr, 0);
  const ticks = [0, max / 2, max];

  /** Places the tooltip in the bar's row: under the pointer, or under the bar's end. */
  const at = (element: HTMLElement, id: string, clientX?: number, clientY?: number) => {
    const box = element.closest<HTMLElement>('[data-part="chart"]');
    const row = element.parentElement;
    if (!box || !row) return;
    const frame = box.getBoundingClientRect();
    const scale = frame.width / box.offsetWidth || 1;
    const r = row.getBoundingClientRect();
    if (clientX === undefined || clientY === undefined) return setTip({ id, x: -1, y: -1 });
    setTip({ id, x: (clientX - r.left) / scale, y: (clientY - r.top) / scale });
  };

  const bar = (row: Account, index: number) => {
    const owner = owners.find((o) => o.id === row.owner);
    return (
      <li key={row.id} className={styles.barRow}>
        <button
          type="button"
          className={styles.bar}
          aria-pressed={selected.has(row.id)}
          aria-label={describe(row)}
          data-tip={tip?.id === row.id || undefined}
          data-demo={`bar-${row.id}`}
          onClick={() => onToggle(row.id)}
          onPointerMove={(event) => at(event.currentTarget, row.id, event.clientX, event.clientY)}
          onPointerLeave={() => setTip(null)}
          onFocus={(event) => at(event.currentTarget, row.id)}
          onBlur={() => setTip(null)}
        >
          <span className={styles.barName}>
            {selected.has(row.id) && <Icon name="check" className={styles.barCheck} width={2.6} />}
            {row.name}
          </span>
          <span className={styles.barTrack} aria-hidden="true">
            <span
              className={styles.barFill}
              data-plan={row.plan.toLowerCase()}
              style={{ width: `${(row.mrr / max) * 100}%` }}
            />
          </span>
          <span className={styles.barValue}>{shortMoney(row.mrr)}</span>
        </button>
        {tip?.id === row.id && (
          <span
            className={styles.tip}
            role="tooltip"
            data-part="chart-tip"
            data-at={tip.x < 0 ? 'bar' : 'pointer'}
            data-below={index < 2 || undefined}
            style={tip.x < 0 ? undefined : { left: tip.x, top: tip.y }}
          >
            <span className={styles.tipHead}>
              {owner && <Avatar owner={owner} />}
              <strong>{row.name}</strong>
            </span>
            <span className={styles.tipLine}>
              <span className={styles.tipKey} data-plan={row.plan.toLowerCase()} />
              {row.plan} · ${money(row.mrr)}
            </span>
            <span className={styles.tipMuted}>
              {total ? Math.round((row.mrr / total) * 100) : 0}% of MRR in view
            </span>
          </span>
        )}
      </li>
    );
  };

  return (
    <div
      className={styles.chart}
      data-part="chart"
      role="group"
      aria-label={`Bar chart of MRR by account: ${rows.length} bars, ${rows.length ? `from ${shortMoney(Math.min(...rows.map((r) => r.mrr)))} to ${shortMoney(Math.max(...rows.map((r) => r.mrr)))}` : 'none'}. Press a bar to select its row.`}
    >
      <div className={styles.axis} aria-hidden="true">
        <span />
        <span className={styles.axisTicks}>
          {ticks.map((tick) => (
            <span key={tick} style={{ left: `${(tick / max) * 100}%` }}>
              {shortMoney(tick)}
            </span>
          ))}
        </span>
        <span />
      </div>
      {groups ? (
        groups.map((group) => (
          <section key={group.plan} className={styles.barGroup} aria-label={group.plan}>
            <p className={styles.barGroupHead}>
              <span className={styles.tipKey} data-plan={group.plan.toLowerCase()} />
              {group.plan}
              <span className={styles.barGroupSum}>
                {group.rows.length} · ${money(group.mrr)}
              </span>
            </p>
            <ul className={styles.bars}>{group.rows.map(bar)}</ul>
          </section>
        ))
      ) : (
        <ul className={styles.bars}>{rows.map(bar)}</ul>
      )}
      {rows.length === 0 && <p className={styles.none}>No accounts match these filters.</p>}
    </div>
  );
}

export function SqlView({ lines, onCopy }: { lines: Token[][]; onCopy: () => void }) {
  return (
    <div className={styles.sql} data-part="sql">
      <div className={styles.sqlBar}>
        <span className={styles.sqlTag}>PostgreSQL · read-only</span>
        <button type="button" className={styles.ghost} onClick={onCopy}>
          <Icon name="copy" />
          Copy
        </button>
      </div>
      {/* Focusable, so the keyboard can scroll the lines. */}
      {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}
      <pre className={styles.sqlCode} tabIndex={0} aria-label="The query's SQL, read-only">
        <code>
          {lines.map((line, i) => (
            <span key={i} className={styles.sqlLine}>
              <span className={styles.sqlNumber} aria-hidden="true">
                {i + 1}
              </span>
              <span>
                {line.map((token, j) => (
                  <span key={j} data-kind={token.kind}>
                    {token.text}
                  </span>
                ))}
              </span>
            </span>
          ))}
        </code>
      </pre>
    </div>
  );
}
```

### query-table/query.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

import {
  PLANS,
  PLAN_RANK,
  change,
  money,
  seatShare,
  shortMoney,
  type Account,
  type Health,
  type Owner,
  type Plan,
} from './data';

/*
 * What the query is and what it returns, with no React: the columns, the filters and the sort,
 * the rows they keep, the SQL that says the same thing, the line Ask about writes for a column,
 * and the CSV that Export saves.
 */

export type ColumnId = 'account' | 'plan' | 'mrr' | 'trend' | 'seats' | 'health';

export const COLUMNS: { id: ColumnId; label: string; sql: string }[] = [
  { id: 'account', label: 'Account', sql: 'account' },
  { id: 'plan', label: 'Plan', sql: 'plan' },
  { id: 'mrr', label: 'MRR', sql: 'mrr' },
  { id: 'trend', label: 'Trend', sql: 'mrr_12w' },
  { id: 'seats', label: 'Seats', sql: 'seats_used / seats_total AS seat_use' },
  { id: 'health', label: 'Health', sql: 'health' },
];

export const columnLabel = (id: ColumnId) => COLUMNS.find((c) => c.id === id)!.label;

export type SeatBand = 'under50' | 'under75' | 'over75';
export type Direction = 'rising' | 'falling';

/** Each filter is a chip when set; null means no chip. */
export type Filters = {
  /** Owner ids, any of. */
  owners: string[] | null;
  /** MRR over this many dollars. */
  mrr: number | null;
  plans: Plan[] | null;
  health: Health | null;
  seats: SeatBand | null;
  trend: Direction | null;
};

export type FilterId = keyof Filters;

export const NO_FILTERS: Filters = {
  owners: null,
  mrr: null,
  plans: null,
  health: null,
  seats: null,
  trend: null,
};

export const FILTER_LABEL: Record<FilterId, string> = {
  owners: 'Owner',
  mrr: 'MRR',
  plans: 'Plan',
  health: 'Health',
  seats: 'Seats',
  trend: 'Trend',
};

/** The filter a column's menu opens. */
export const FILTER_OF: Record<ColumnId, FilterId> = {
  account: 'owners',
  plan: 'plans',
  mrr: 'mrr',
  trend: 'trend',
  seats: 'seats',
  health: 'health',
};

export const MRR_STEPS = [1000, 2500, 5000, 10000, 20000];

export const SEAT_BANDS: { id: SeatBand; label: string; sql: string }[] = [
  { id: 'under50', label: 'Under 50% used', sql: 'seats_used < 0.5 * seats_total' },
  { id: 'under75', label: 'Under 75% used', sql: 'seats_used < 0.75 * seats_total' },
  { id: 'over75', label: '75% used or more', sql: 'seats_used >= 0.75 * seats_total' },
];

export type Sort = { key: ColumnId; desc: boolean };

export function matches(row: Account, f: Filters) {
  if (f.owners && !f.owners.includes(row.owner)) return false;
  if (f.mrr !== null && row.mrr <= f.mrr) return false;
  if (f.plans && !f.plans.includes(row.plan)) return false;
  if (f.health && row.health !== f.health) return false;
  if (f.seats) {
    const share = row.seats.used / row.seats.total;
    if (f.seats === 'under50' && share >= 0.5) return false;
    if (f.seats === 'under75' && share >= 0.75) return false;
    if (f.seats === 'over75' && share < 0.75) return false;
  }
  if (f.trend === 'rising' && change(row) <= 0) return false;
  if (f.trend === 'falling' && change(row) >= 0) return false;
  return true;
}

const valueOf = (row: Account, key: ColumnId): number | string => {
  switch (key) {
    case 'account':
      return row.name.toLowerCase();
    case 'plan':
      return PLAN_RANK[row.plan] * 1e7 + row.mrr;
    case 'mrr':
      return row.mrr;
    case 'trend':
      return change(row);
    case 'seats':
      return row.seats.used / row.seats.total;
    case 'health':
      return (row.health === 'risk' ? 1e7 : 0) + row.mrr;
  }
};

export function sortRows(rows: Account[], sort: Sort) {
  return [...rows].sort((a, b) => {
    const x = valueOf(a, sort.key);
    const y = valueOf(b, sort.key);
    const order = x < y ? -1 : x > y ? 1 : 0;
    return sort.desc ? -order : order;
  });
}

export type Group = { plan: Plan; rows: Account[]; mrr: number; seats: number; risk: number };

export function groupRows(rows: Account[]): Group[] {
  return PLANS.map((plan) => {
    const list = rows.filter((row) => row.plan === plan);
    return {
      plan,
      rows: list,
      mrr: list.reduce((sum, row) => sum + row.mrr, 0),
      seats: list.length
        ? Math.round(list.reduce((sum, row) => sum + seatShare(row), 0) / list.length)
        : 0,
      risk: list.filter((row) => row.health === 'risk').length,
    };
  }).filter((group) => group.rows.length > 0);
}

// ---- SQL ---------------------------------------------------------------------------------------

/** A run of SQL, by kind, so the view can colour it. */
export type Token = { kind: 'kw' | 'id' | 'str' | 'num' | 'op' | 'cm' | 'fn'; text: string };
const kw = (text: string): Token => ({ kind: 'kw', text });
const id = (text: string): Token => ({ kind: 'id', text });
const str = (text: string): Token => ({ kind: 'str', text: `'${text}'` });
const num = (text: string | number): Token => ({ kind: 'num', text: String(text) });
const op = (text: string): Token => ({ kind: 'op', text });
const cm = (text: string): Token => ({ kind: 'cm', text: `-- ${text}` });
const fn = (text: string): Token => ({ kind: 'fn', text });

/** A list of quoted strings: ('a', 'b'). */
const list = (items: string[]) => [
  op('('),
  ...items.flatMap((item, i) => (i ? [op(', '), str(item)] : [str(item)])),
  op(')'),
];

/** Words of SQL inside an expression, keywords picked out. */
const words = (text: string) =>
  text.split(/(\s+|[()*,<>=/]+)/).flatMap((part): Token[] => {
    if (!part) return [];
    if (/^\s+$/.test(part)) return [op(part)];
    if (/^[()*,<>=/]+$/.test(part)) return [op(part)];
    if (/^\d/.test(part)) return [num(part)];
    if (/^(AS|AND|OR|NOT|NULL|IS)$/.test(part)) return [kw(part)];
    return [id(part)];
  });

function conditions(f: Filters, owners: Owner[]): Token[][] {
  const out: Token[][] = [];
  if (f.owners) {
    const names = f.owners.map((o) => owners.find((p) => p.id === o)?.name ?? o);
    out.push(
      names.length
        ? [id('owner'), op(' '), kw('IN'), op(' '), ...list(names)]
        : [kw('FALSE'), op('  '), cm('no owner chosen')],
    );
  }
  if (f.mrr !== null) out.push([id('mrr'), op(' > '), num(f.mrr)]);
  if (f.plans)
    out.push(
      f.plans.length
        ? [id('plan'), op(' '), kw('IN'), op(' '), ...list(f.plans)]
        : [kw('FALSE'), op('  '), cm('no plan chosen')],
    );
  if (f.health)
    out.push([id('health'), op(' = '), str(f.health === 'risk' ? 'at_risk' : 'healthy')]);
  if (f.seats) out.push(words(SEAT_BANDS.find((b) => b.id === f.seats)!.sql));
  if (f.trend)
    out.push([fn('mrr_change_12w'), op('()'), op(f.trend === 'rising' ? ' > ' : ' < '), num(0)]);
  return out;
}

const ORDER: Record<ColumnId, string> = {
  account: 'account',
  plan: 'plan_rank',
  mrr: 'mrr',
  trend: 'mrr_change_12w()',
  seats: 'seats_used / seats_total',
  health: 'health',
};

/** The query, line by line, for the filters, the sort, the grouping and the columns shown. */
export function toSql({
  title,
  filters,
  sort,
  grouped,
  hidden,
  owners,
}: {
  title: string;
  filters: Filters;
  sort: Sort;
  grouped: boolean;
  hidden: ColumnId[];
  owners: Owner[];
}): Token[][] {
  const shown = COLUMNS.filter((c) => !hidden.includes(c.id));
  const where = conditions(filters, owners);
  const lines: Token[][] = [[cm(title)], [kw('SELECT')]];
  shown.forEach((column, i) => {
    lines.push([op('  '), ...words(column.sql), ...(i < shown.length - 1 ? [op(',')] : [])]);
  });
  lines.push([kw('FROM'), op(' '), id('accounts')]);
  where.forEach((condition, i) => {
    lines.push([i ? op('  ') : kw('WHERE'), ...(i ? [kw('AND')] : []), op(' '), ...condition]);
  });
  const by: Token[] = [op(' '), ...words(ORDER[sort.key]), op(' '), kw(sort.desc ? 'DESC' : 'ASC')];
  lines.push(
    grouped ? [kw('ORDER BY'), op(' '), id('plan_rank'), op(','), ...by] : [kw('ORDER BY'), ...by],
  );
  lines[lines.length - 1].push(op(';'));
  if (grouped) {
    lines.push([]);
    lines.push([cm('Subtotals per plan')]);
    lines.push([
      kw('SELECT'),
      op(' '),
      id('plan'),
      op(', '),
      fn('COUNT'),
      op('(*), '),
      fn('SUM'),
      op('('),
      id('mrr'),
      op(') '),
      kw('AS'),
      op(' '),
      id('mrr'),
    ]);
    lines.push([kw('FROM'), op(' '), id('accounts')]);
    where.forEach((condition, i) => {
      lines.push([i ? op('  ') : kw('WHERE'), ...(i ? [kw('AND')] : []), op(' '), ...condition]);
    });
    lines.push([kw('GROUP BY'), op(' '), id('plan'), op(';')]);
  }
  return lines;
}

export const sqlText = (lines: Token[][]) =>
  lines.map((line) => line.map((t) => t.text).join('')).join('\n');

// ---- Ask about ---------------------------------------------------------------------------------

const pct = (share: number) => `${Math.round(share * 100)}%`;
const signed = (share: number) => `${share >= 0 ? '+' : '−'}${Math.abs(Math.round(share * 100))}%`;

/** A line on a column, read from the rows in view. */
export function insight(column: ColumnId, rows: Account[], owners: Owner[]): string {
  const n = rows.length;
  if (!n) return 'No rows in view to read: loosen a filter first.';
  const total = rows.reduce((sum, row) => sum + row.mrr, 0);
  const by = (fnc: (row: Account) => number) => [...rows].sort((a, b) => fnc(b) - fnc(a));
  switch (column) {
    case 'account': {
      const counts = owners
        .map((o) => ({ o, rows: rows.filter((r) => r.owner === o.id) }))
        .filter((x) => x.rows.length)
        .sort((a, b) => b.rows.length - a.rows.length);
      const top = counts[0];
      return `${n} accounts across ${counts.length} ${counts.length === 1 ? 'owner' : 'owners'}; ${top.o.name.split(' ')[0]} holds ${top.rows.length} of them, ${shortMoney(top.rows.reduce((s, r) => s + r.mrr, 0))} in MRR.`;
    }
    case 'plan': {
      const groups = groupRows(rows);
      const big = [...groups].sort((a, b) => b.mrr - a.mrr)[0];
      const avg = groups.map((g) => `${g.plan} ${shortMoney(g.mrr / g.rows.length)}`).join(', ');
      return `${big.plan} is ${big.rows.length} of ${n} accounts but ${pct(big.mrr / total)} of MRR. Average per account: ${avg}.`;
    }
    case 'mrr': {
      const top = by((r) => r.mrr).slice(0, 2);
      const share = top.reduce((s, r) => s + r.mrr, 0) / total;
      if (n === 1) return `${top[0].name} alone: $${money(top[0].mrr)} a month.`;
      return `The top two, ${top[0].name} and ${top[1].name}, make ${pct(share)} of the $${money(total)} in view; the median account brings ${shortMoney(by((r) => r.mrr)[Math.floor(n / 2)].mrr)}.`;
    }
    case 'trend': {
      const rising = rows.filter((r) => change(r) > 0).length;
      const worst = by((r) => -change(r))[0];
      const best = by(change)[0];
      return `${rising} rising, ${n - rising} falling over twelve weeks. ${best.name} grew most (${signed(change(best))}); ${worst.name} fell most (${signed(change(worst))}).`;
    }
    case 'seats': {
      const low = rows.filter((r) => seatShare(r) < 50);
      const lowest = by((r) => -seatShare(r))[0];
      const avg = Math.round(rows.reduce((s, r) => s + seatShare(r), 0) / n);
      return low.length
        ? `${low.length} of ${n} accounts use under half their seats; ${lowest.name} is lowest at ${seatShare(lowest)}%. Average use is ${avg}%.`
        : `Every account uses at least half its seats; average use is ${avg}%, ${lowest.name} lowest at ${seatShare(lowest)}%.`;
    }
    case 'health': {
      const risk = rows.filter((r) => r.health === 'risk');
      if (!risk.length)
        return `All ${n} accounts are healthy, $${money(total)} of MRR with no flags.`;
      const falling = risk.filter((r) => change(r) < 0).length;
      return `${risk.length} at risk, holding $${money(risk.reduce((s, r) => s + r.mrr, 0))} of MRR; ${falling === risk.length ? 'all' : falling} of them with MRR falling, seats at ${Math.round(risk.reduce((s, r) => s + seatShare(r), 0) / risk.length)}% on average.`;
    }
  }
}

// ---- Export ------------------------------------------------------------------------------------

export function toCsv(rows: Account[], hidden: ColumnId[], owners: Owner[]) {
  const cells: Record<ColumnId, { head: string[]; of: (r: Account) => (string | number)[] }> = {
    account: {
      head: ['Account', 'Owner'],
      of: (r) => [r.name, owners.find((o) => o.id === r.owner)?.name ?? ''],
    },
    plan: { head: ['Plan'], of: (r) => [r.plan] },
    mrr: { head: ['MRR'], of: (r) => [r.mrr] },
    trend: { head: ['12-week change'], of: (r) => [`${Math.round(change(r) * 1000) / 10}%`] },
    seats: { head: ['Seats used', 'Seats'], of: (r) => [r.seats.used, r.seats.total] },
    health: { head: ['Health'], of: (r) => [r.health === 'risk' ? 'At risk' : 'Healthy'] },
  };
  const shown = COLUMNS.filter((c) => !hidden.includes(c.id)).map((c) => cells[c.id]);
  const quote = (cell: string | number) => `"${String(cell).replace(/"/g, '""')}"`;
  return [
    shown
      .flatMap((c) => c.head)
      .map(quote)
      .join(','),
    ...rows.map((r) =>
      shown
        .flatMap((c) => c.of(r))
        .map(quote)
        .join(','),
    ),
  ].join('\n');
}
```

### query-table/query-table.module.css

```css
/* Query table (query-table.tsx): a query's result as a card on a grey stage, near-black by night
   and white by day. The header names the query and switches its view; an inset panel holds the
   filter chips, the Ask about line and the rows (a table, bars or SQL); the footer counts and
   exports.

   The table scrolls inside its own box, the checkbox and Account columns held at its left. Under
   640 px of stage the view switch takes a row of its own and the footer drops its Navigate label.

   Colours are the tokens below, light-dark(light, dark) where the two differ: the component takes
   the color-scheme it inherits from the page, or the one its colorScheme prop sets
   (data-color-scheme). Every text colour, --ink-3 and the SQL comment included, holds 4.5:1 on the
   card, the panel, the menus and their hovered, selected and cursor rows in both schemes. */

.root {
  --stage: #e7e7ea;
  --card: #ffffff;
  --card-edge: #e2e2e6;
  --panel: #fbfbfc;
  --panel-edge: #ececef;
  --line: #efeff2;
  --ink: #18181b;
  --ink-2: #6b6b73;
  --ink-3: #6e6e76;
  --chip: #ffffff;
  --chip-edge: #e3e3e8;
  --hover: #f3f3f5;
  --tab-on: #ffffff;
  --tab-edge: #dedee3;
  --tab-shadow: rgb(0 0 0 / 0.06);
  --row-hover: #f6f6f8;
  --row-selected: #f1f5ff;
  --row-cursor: #eef3ff;
  --menu: #ffffff;
  --menu-edge: #e5e5ea;
  --shadow: rgb(16 16 24 / 0.14);
  --accent: #2c66e0;
  --accent-ink: #ffffff;
  --accent-soft: #eef3ff;
  --accent-edge: #d5e1fc;
  --up: #2f6ae6;
  --down: #d9473a;
  --risk: #e0483b;
  --ok: #3274f0;
  --seg-on: #3f3f46;
  --seg-off: #e4e4e9;
  /* The plans: fill and text. */
  --violet-bg: #f1ecff;
  --violet-ink: #6a43da;
  --violet: #8b66f0;
  --green-bg: #e6f6ec;
  --green-ink: #1c7b43;
  --green: #35b46a;
  --amber-bg: #fcf2da;
  --amber-ink: #925f00;
  --amber: #e1a52b;
  --blue: #4f86f0;
  /* The SQL. */
  --code-kw: #6a43da;
  --code-fn: #0f7ea0;
  --code-str: #1c7b43;
  --code-num: #b35b00;
  --code-cm: #73737b;
  /* The same on both schemes. */
  --focus: #5b8cff;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: var(--body, Inter, ui-sans-serif, system-ui, sans-serif);
  --mono: var(--code, ui-monospace, 'SF Mono', Menlo, monospace);
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#e7e7ea, #2a2a2d);
    --card: light-dark(#ffffff, #121212);
    --card-edge: light-dark(#e2e2e6, #262626);
    --panel: light-dark(#fbfbfc, #181818);
    --panel-edge: light-dark(#ececef, #262626);
    --line: light-dark(#efeff2, #232323);
    --ink: light-dark(#18181b, #f1f1f1);
    --ink-2: light-dark(#6b6b73, #9b9b9b);
    --ink-3: light-dark(#6e6e76, #8e8e8e);
    --chip: light-dark(#ffffff, #1b1b1b);
    --chip-edge: light-dark(#e3e3e8, #2f2f2f);
    --hover: light-dark(#f3f3f5, #242424);
    --tab-on: light-dark(#ffffff, #262626);
    --tab-edge: light-dark(#dedee3, #353535);
    --tab-shadow: light-dark(rgb(0 0 0 / 0.06), rgb(0 0 0 / 0.4));
    --row-hover: light-dark(#f6f6f8, #1d1d1d);
    --row-selected: light-dark(#f1f5ff, #222222);
    --row-cursor: light-dark(#eef3ff, #1f2430);
    --menu: light-dark(#ffffff, #262626);
    --menu-edge: light-dark(#e5e5ea, #363636);
    --shadow: light-dark(rgb(16 16 24 / 0.14), rgb(0 0 0 / 0.6));
    --accent: light-dark(#2c66e0, #4c8df6);
    --accent-soft: light-dark(#eef3ff, #172236);
    --accent-edge: light-dark(#d5e1fc, #243757);
    --up: light-dark(#2f6ae6, #4c8df6);
    --down: light-dark(#d9473a, #ee6352);
    --risk: light-dark(#e0483b, #f0584a);
    --ok: light-dark(#3274f0, #4a86ee);
    --seg-on: light-dark(#3f3f46, #d9d9d9);
    --seg-off: light-dark(#e4e4e9, #303030);
    --violet-bg: light-dark(#f1ecff, #241d44);
    --violet-ink: light-dark(#6a43da, #a88bff);
    --violet: light-dark(#8b66f0, #8f6cf5);
    --green-bg: light-dark(#e6f6ec, #10291b);
    --green-ink: light-dark(#1c7b43, #45d483);
    --green: light-dark(#35b46a, #3cbf74);
    --amber-bg: light-dark(#fcf2da, #2e220b);
    --amber-ink: light-dark(#925f00, #f1b23e);
    --amber: light-dark(#e1a52b, #e3a634);
    --code-kw: light-dark(#6a43da, #b49cff);
    --code-fn: light-dark(#0f7ea0, #5cc8e6);
    --code-str: light-dark(#1c7b43, #6fdc9b);
    --code-num: light-dark(#b35b00, #f3b45a);
    --code-cm: light-dark(#73737b, #838383);
  }
}
.root[data-color-scheme='light'] {
  color-scheme: light;
}
.root[data-color-scheme='dark'] {
  color-scheme: dark;
}
.root[data-color-scheme='system'] {
  color-scheme: light dark;
}

.root {
  position: relative;
  container-type: inline-size;
  width: 100%;
  /* Shares of the stage's own width: a container query cannot reach the container itself. */
  padding: clamp(14px, 5%, 40px) clamp(10px, 3.5%, 28px);
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: var(--stage);
  color: var(--ink);
  font-family: var(--sans);
  font-size: 13px;
  line-height: 1.35;
  -webkit-tap-highlight-color: transparent;
}
/* Low specificity, so every part's own colour wins. */
.root :where(button, input) {
  font: inherit;
  color: inherit;
}
.root button {
  cursor: pointer;
}
.root button:disabled,
.root button[aria-disabled='true'] {
  cursor: default;
}
.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}
.root svg {
  flex: none;
  display: block;
}
.srOnly {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

/* ---- The card --------------------------------------------------------------------------------- */

.card {
  max-width: 760px;
  margin: 0 auto;
  padding: 4px;
  border: 1px solid var(--card-edge);
  border-radius: 20px;
  background: var(--card);
  box-shadow: 0 24px 48px -28px var(--shadow);
}
.header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 13px 14px 14px 18px;
}
.badge {
  display: grid;
  place-items: center;
  width: 22px;
  height: 22px;
  color: var(--ink-2);
}
.badge svg {
  width: 19px;
  height: 19px;
}
.titles {
  flex: 1;
  min-width: 0;
}
.title {
  margin: 0;
  font-size: 14.5px;
  font-weight: 600;
  letter-spacing: -0.005em;
}
.meta {
  margin: 2px 0 0;
  color: var(--ink-2);
  font-size: 12.5px;
  font-variant-numeric: tabular-nums;
}
.meta[data-running] {
  animation: breathe 0.9s ease-in-out infinite alternate;
}
@keyframes breathe {
  to {
    opacity: 0.45;
  }
}
.headerEnd {
  display: flex;
  align-items: center;
  gap: 10px;
}
.views {
  display: flex;
  gap: 2px;
}
.viewTab {
  height: 32px;
  padding: 0 14px;
  border: 1px solid transparent;
  border-radius: 10px;
  background: none;
  color: var(--ink-2) !important;
  font-weight: 500;
  transition:
    background 0.15s ease,
    color 0.15s ease;
}
.viewTab:hover,
.viewTab[data-over] {
  color: var(--ink) !important;
}
.viewTab[aria-selected='true'] {
  border-color: var(--tab-edge);
  background: var(--tab-on);
  color: var(--ink) !important;
  box-shadow: 0 1px 2px var(--tab-shadow);
}
.iconButton {
  display: grid;
  place-items: center;
  width: 32px;
  height: 32px;
  padding: 0;
  border: 1px solid var(--chip-edge);
  border-radius: 10px;
  background: var(--chip);
  color: var(--ink-2) !important;
}
.iconButton svg {
  width: 16px;
  height: 16px;
}
.iconButton:hover:not(:disabled),
.iconButton[aria-expanded='true'] {
  background: var(--hover);
  color: var(--ink) !important;
}
.iconButton:disabled {
  opacity: 0.4;
}

/* ---- The panel: filters, the answer, the rows --------------------------------------------------- */

.panel {
  overflow: hidden;
  border: 1px solid var(--panel-edge);
  border-radius: 16px;
  background: var(--panel);
}
.filters {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 11px 11px 11px 11px;
  border-bottom: 1px solid var(--line);
}
.chips {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
  gap: 7px;
  min-width: 0;
}
.chip {
  display: inline-flex;
  align-items: center;
  height: 30px;
  border: 1px solid var(--chip-edge);
  border-radius: 9px;
  background: var(--chip);
  animation: pop 0.18s ease;
}
.chipMain {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  height: 100%;
  padding: 0 4px 0 10px;
  border: 0;
  border-radius: 8px 0 0 8px;
  background: none;
  white-space: nowrap;
}
.chipMain:hover,
.chipMain[aria-expanded='true'],
.chipMain[data-over] {
  background: var(--hover);
}
.chipKey {
  color: var(--ink-2);
}
.chipValue {
  font-weight: 550;
}
.chipX {
  display: grid;
  place-items: center;
  width: 26px;
  height: 100%;
  padding: 0;
  border: 0;
  border-radius: 0 8px 8px 0;
  background: none;
  color: var(--ink-3) !important;
}
.chipX svg {
  width: 13px;
  height: 13px;
}
.chipX:hover {
  background: var(--hover);
  color: var(--ink) !important;
}
.faces {
  display: inline-flex;
}
.faces > * + * {
  margin-left: -5px;
}
.avatar {
  display: inline-grid;
  place-items: center;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  box-shadow: 0 0 0 1.5px var(--chip);
  color: #fff;
  font-size: 10px;
  font-weight: 650;
  line-height: 1;
}
.avatar[data-tone='violet'] {
  background: var(--violet);
}
.avatar[data-tone='green'] {
  background: var(--green);
}
.avatar[data-tone='blue'] {
  background: var(--blue);
}
.avatar[data-tone='amber'] {
  background: var(--amber);
}
.addFilter {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  height: 30px;
  padding: 0 11px 0 9px;
  border: 1px dashed var(--tab-edge);
  border-radius: 9px;
  background: none;
  color: var(--ink-2) !important;
}
.addFilter svg {
  width: 14px;
  height: 14px;
}
.addFilter:hover,
.addFilter[aria-expanded='true'],
.addFilter[data-over] {
  border-color: var(--ink-3);
  color: var(--ink) !important;
}
.tools {
  display: flex;
  align-items: center;
  gap: 7px;
}
.hiddenButton {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 30px;
  padding: 0 10px;
  border: 1px solid var(--chip-edge);
  border-radius: 9px;
  background: var(--chip);
  color: var(--ink-2) !important;
  white-space: nowrap;
}
.hiddenButton svg {
  width: 15px;
  height: 15px;
}
.hiddenButton:hover,
.hiddenButton[aria-expanded='true'] {
  color: var(--ink) !important;
}
.density {
  display: flex;
  padding: 2px;
  border: 1px solid var(--chip-edge);
  border-radius: 10px;
  background: var(--chip);
}
.densityButton {
  display: grid;
  place-items: center;
  width: 30px;
  height: 24px;
  padding: 0;
  border: 1px solid transparent;
  border-radius: 7px;
  background: none;
  color: var(--ink-3) !important;
}
.densityButton svg {
  width: 16px;
  height: 16px;
}
.densityButton[aria-checked='true'] {
  border-color: var(--tab-edge);
  background: var(--tab-on);
  color: var(--ink) !important;
}

.insight {
  display: flex;
  align-items: flex-start;
  gap: 9px;
  margin: 10px 11px 0;
  padding: 9px 8px 9px 11px;
  border: 1px solid var(--accent-edge);
  border-radius: 11px;
  background: var(--accent-soft);
  animation: pop 0.2s ease;
}
.insightIcon {
  width: 15px;
  height: 15px;
  margin-top: 1px;
  color: var(--accent);
}
.insight:not([data-ready]) .insightIcon {
  animation: spin 1.2s linear infinite;
}
@keyframes spin {
  to {
    rotate: 1turn;
  }
}
.insightText {
  flex: 1;
  margin: 0;
  font-size: 12.5px;
  line-height: 1.45;
}
.insightKey {
  margin-right: 6px;
  color: var(--accent);
  font-weight: 600;
}
.thinking {
  color: var(--ink-2);
}
.insightClose {
  display: grid;
  place-items: center;
  width: 22px;
  height: 22px;
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--ink-2) !important;
}
.insightClose svg {
  width: 13px;
  height: 13px;
}
.insightClose:hover {
  background: var(--hover);
}

.body {
  transition: opacity 0.2s ease;
}
.panel[data-running] .body {
  opacity: 0.5;
}

/* ---- The table -------------------------------------------------------------------------------- */

.scroller {
  max-height: 470px;
  overflow: auto;
  outline-offset: -2px !important;
  scrollbar-width: thin;
}
.table {
  width: 100%;
  min-width: 600px;
  border-collapse: separate;
  border-spacing: 0;
  font-variant-numeric: tabular-nums;
}
.table th,
.table td {
  height: 46px;
  padding: 0 10px;
  border-bottom: 1px solid var(--line);
  background: var(--panel);
  text-align: left;
  vertical-align: middle;
  white-space: nowrap;
  transition: background 0.12s ease;
}
.root[data-density='compact'] .table th,
.root[data-density='compact'] .table td {
  height: 34px;
}
.table thead th {
  position: sticky;
  top: 0;
  z-index: 2;
  height: 44px;
  color: var(--ink-3);
  font-size: 12.5px;
  font-weight: 450;
}
.root[data-density='compact'] .table thead th {
  height: 38px;
}
.table tbody:last-of-type tr:last-child > * {
  border-bottom: 0;
}
.table [data-col='check'] {
  position: sticky;
  left: 0;
  z-index: 1;
  box-sizing: border-box;
  width: 40px;
  min-width: 40px;
  max-width: 40px;
  padding: 0 4px 0 14px;
}
.table [data-col='account'] {
  position: sticky;
  left: 40px;
  z-index: 1;
  min-width: 150px;
  font-weight: 400;
}
.table thead [data-col='check'],
.table thead [data-col='account'] {
  z-index: 3;
}
.table [data-col='plan'] {
  width: 104px;
}
.table [data-col='mrr'] {
  width: 92px;
  text-align: right;
  font-size: 13.5px;
}
.table [data-col='trend'] {
  width: 76px;
}
.table [data-col='seats'] {
  width: 128px;
}
.table [data-col='health'] {
  width: 64px;
  padding-right: 16px;
  text-align: right;
}
.table tbody tr:hover > * {
  background: var(--row-hover);
}
.table tbody tr[data-selected] > * {
  background: var(--row-selected);
}
.table tbody tr[data-cursor] > * {
  background: var(--row-cursor);
}
.table tbody tr[data-cursor] > [data-col='check'] {
  box-shadow: inset 2px 0 0 var(--accent);
}
.name {
  font-size: 13.5px;
  font-weight: 550;
}

.head {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  height: 28px;
  margin-left: -8px;
  padding: 0 6px 0 8px;
  border: 0;
  border-radius: 8px;
  background: none;
  color: var(--ink-3) !important;
  font-weight: inherit;
}
.table [data-col='mrr'] .head,
.table [data-col='health'] .head {
  margin-right: -8px;
  margin-left: 0;
}
.head[data-active] {
  color: var(--ink) !important;
  font-weight: 550;
}
.head:hover,
.head[data-over] {
  color: var(--ink) !important;
}
.head[aria-expanded='true'] {
  background: var(--tab-on);
  color: var(--ink) !important;
  box-shadow: 0 0 0 1px var(--tab-edge);
}
.sortIcon {
  width: 13px;
  height: 13px;
  color: var(--accent);
}
.headChevron {
  width: 13px;
  height: 13px;
  opacity: 0;
  transition: opacity 0.12s ease;
}
.head:hover .headChevron,
.head:focus-visible .headChevron,
.head[aria-expanded='true'] .headChevron,
.head[data-over] .headChevron {
  opacity: 1;
}

.check {
  display: grid;
  place-items: center;
  width: 17px;
  height: 17px;
  padding: 0;
  border: 1.5px solid var(--ink-3);
  border-radius: 5px;
  background: none;
  color: transparent !important;
}
.check svg {
  width: 12px;
  height: 12px;
}
.check[aria-checked='true'],
.check[aria-checked='mixed'] {
  border-color: var(--accent);
  background: var(--accent);
  color: var(--accent-ink) !important;
}
.check[data-over] {
  border-color: var(--ink-2);
}

.plan {
  display: inline-flex;
  align-items: center;
  height: 22px;
  padding: 0 8px;
  border-radius: 6px;
  font-size: 12.5px;
  font-weight: 500;
}
.plan[data-plan='enterprise'] {
  background: var(--violet-bg);
  color: var(--violet-ink);
}
.plan[data-plan='growth'] {
  background: var(--green-bg);
  color: var(--green-ink);
}
.plan[data-plan='starter'] {
  background: var(--amber-bg);
  color: var(--amber-ink);
}

.spark {
  display: inline-block;
  vertical-align: middle;
}
.spark svg {
  width: 58px;
  height: 20px;
  overflow: visible;
}
.spark[data-dir='up'] {
  color: var(--up);
}
.spark[data-dir='down'] {
  color: var(--down);
}

.seats {
  display: inline-flex;
  align-items: center;
  gap: 7px;
}
.segments {
  display: flex;
  gap: 2px;
}
.segment {
  width: 3.5px;
  height: 11px;
  border-radius: 1px;
  background: var(--seg-off);
}
.segment[data-on] {
  background: var(--seg-on);
}
.seats[data-low] .segment[data-on] {
  opacity: 0.55;
}
.seatPct {
  min-width: 30px;
  color: var(--ink-2);
  font-size: 12.5px;
}
.seats[data-low] .seatPct {
  color: var(--ink-3);
}

.health {
  display: inline-grid;
  place-items: center;
  width: 16px;
  height: 16px;
  vertical-align: middle;
}
.healthDot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: var(--ok);
}
.health[data-health='risk'] .healthDot {
  width: 8px;
  height: 8px;
  background: var(--risk);
  box-shadow:
    0 0 0 2.5px var(--panel),
    0 0 0 4px var(--risk);
}

.groupRow > * {
  height: 34px !important;
  background: var(--hover) !important;
  font-size: 12.5px;
}
.groupName {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  font-weight: 600;
}
.groupKey,
.tipKey {
  width: 8px;
  height: 8px;
  border-radius: 2px;
}
.groupKey[data-plan='enterprise'],
.tipKey[data-plan='enterprise'],
.barFill[data-plan='enterprise'] {
  background: var(--violet);
}
.groupKey[data-plan='growth'],
.tipKey[data-plan='growth'],
.barFill[data-plan='growth'] {
  background: var(--green);
}
.groupKey[data-plan='starter'],
.tipKey[data-plan='starter'],
.barFill[data-plan='starter'] {
  background: var(--amber);
}
.groupCount {
  margin-left: 8px;
  color: var(--ink-2);
  font-weight: 400;
}
.subtotal {
  font-weight: 600;
}
.groupNote {
  color: var(--ink-2);
}
.none {
  padding: 28px 16px !important;
  color: var(--ink-2);
  text-align: center !important;
}
.linkButton {
  padding: 0;
  border: 0;
  background: none;
  color: var(--accent) !important;
  font-weight: 550;
}

/* ---- The chart and the SQL ---------------------------------------------------------------------- */

.chart {
  position: relative;
  max-height: 470px;
  padding: 10px 16px 16px;
  overflow: auto;
  scrollbar-width: thin;
}
.axis,
.bar {
  display: grid;
  grid-template-columns: minmax(96px, 150px) minmax(0, 1fr) 54px;
  align-items: center;
  gap: 12px;
}
.axis {
  height: 24px;
  color: var(--ink-3);
  font-size: 11.5px;
}
.axisTicks {
  position: relative;
  height: 100%;
}
.axisTicks > span {
  position: absolute;
  top: 50%;
  translate: -50% -50%;
}
.axisTicks > span:first-child {
  translate: 0 -50%;
}
.axisTicks > span:last-child {
  translate: -100% -50%;
}
.bars {
  margin: 0;
  padding: 0;
  list-style: none;
}
.barRow {
  position: relative;
}
.barRow:has([data-tip]) {
  z-index: 2;
}
.bar {
  width: 100%;
  height: 32px;
  padding: 0 4px;
  border: 0;
  border-radius: 7px;
  background: none;
  text-align: left;
}
.root[data-density='compact'] .bar {
  height: 25px;
}
.bar:hover,
.bar[data-tip],
.bar[data-over] {
  background: var(--hover);
}
.barName {
  display: flex;
  align-items: center;
  gap: 5px;
  overflow: hidden;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.barCheck {
  width: 13px;
  height: 13px;
  color: var(--accent);
}
.barTrack {
  position: relative;
  height: 14px;
  background: repeating-linear-gradient(to right, var(--line) 0 1px, transparent 1px 50%);
}
.barFill {
  position: absolute;
  inset: 0 auto 0 0;
  border-radius: 4px;
  opacity: 0.85;
  transition: width 0.35s cubic-bezier(0.3, 0.7, 0.2, 1);
}
.bar[aria-pressed='true'] .barFill {
  opacity: 1;
  box-shadow:
    0 0 0 1.5px var(--panel),
    0 0 0 3px var(--accent);
}
.barValue {
  color: var(--ink-2);
  font-variant-numeric: tabular-nums;
  text-align: right;
}
.barGroup + .barGroup {
  margin-top: 8px;
}
.barGroupHead {
  display: flex;
  align-items: center;
  gap: 7px;
  margin: 6px 4px 2px;
  font-size: 12px;
  font-weight: 600;
}
.barGroupSum {
  color: var(--ink-2);
  font-weight: 400;
}
.tip {
  position: absolute;
  z-index: 3;
  display: grid;
  gap: 3px;
  min-width: 170px;
  padding: 9px 11px;
  border: 1px solid var(--menu-edge);
  border-radius: 10px;
  background: var(--menu);
  box-shadow: 0 12px 28px -10px var(--shadow);
  font-size: 12px;
  pointer-events: none;
  translate: -50% calc(-100% - 12px);
}
.tip[data-at='bar'] {
  top: 0;
  left: 50%;
}
.tip[data-below] {
  translate: -50% 14px;
}
.tip[data-at='bar'][data-below] {
  top: 100%;
  translate: -50% 4px;
}
.tipHead {
  display: flex;
  align-items: center;
  gap: 7px;
  font-size: 12.5px;
}
.tipHead .avatar {
  box-shadow: none;
}
.tipLine {
  display: flex;
  align-items: center;
  gap: 7px;
}
.tipMuted {
  color: var(--ink-2);
}

.sql {
  display: grid;
}
.sqlBar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 10px 0 16px;
}
.sqlTag {
  color: var(--ink-3);
  font-size: 11.5px;
  letter-spacing: 0.02em;
}
.ghost {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 28px;
  padding: 0 10px;
  border: 1px solid var(--chip-edge);
  border-radius: 8px;
  background: var(--chip);
  color: var(--ink-2) !important;
  font-size: 12.5px;
}
.ghost svg {
  width: 14px;
  height: 14px;
}
.ghost:hover {
  color: var(--ink) !important;
}
.sqlCode {
  max-height: 430px;
  margin: 0;
  padding: 8px 0 16px;
  overflow: auto;
  outline-offset: -2px !important;
  font-family: var(--mono);
  font-size: 12.5px;
  line-height: 1.7;
  scrollbar-width: thin;
}
.sqlLine {
  display: grid;
  grid-template-columns: 40px auto;
  gap: 14px;
  padding-right: 16px;
  white-space: pre;
}
.sqlNumber {
  color: var(--ink-3);
  text-align: right;
  user-select: none;
}
.sqlCode [data-kind='kw'] {
  color: var(--code-kw);
  font-weight: 600;
}
.sqlCode [data-kind='fn'] {
  color: var(--code-fn);
}
.sqlCode [data-kind='str'] {
  color: var(--code-str);
}
.sqlCode [data-kind='num'] {
  color: var(--code-num);
}
.sqlCode [data-kind='cm'] {
  color: var(--code-cm);
  font-style: italic;
}
.sqlCode [data-kind='op'] {
  color: var(--ink-2);
}

/* ---- The footer ------------------------------------------------------------------------------- */

.footer {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 6px 6px 14px;
}
.count {
  flex: 1;
  min-width: 0;
  margin: 0;
  font-variant-numeric: tabular-nums;
}
.count strong {
  font-weight: 600;
}
.showing {
  color: var(--ink-2);
}
.nav {
  display: flex;
  align-items: center;
  gap: 6px;
}
.nav .iconButton {
  width: 30px;
  height: 30px;
}
.nav .iconButton svg {
  width: 15px;
  height: 15px;
}
.navLabel {
  margin: 0 4px 0 2px;
  color: var(--ink-2);
}
.export {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  height: 36px;
  padding: 0 15px 0 13px;
  border: 1px solid var(--tab-edge);
  border-radius: 11px;
  background: var(--tab-on);
  font-weight: 600;
  box-shadow: 0 1px 2px var(--tab-shadow);
}
.export svg {
  width: 16px;
  height: 16px;
}
.export:hover {
  background: var(--hover);
}

/* ---- Menus and the toast ----------------------------------------------------------------------- */

.menu {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 6;
  display: grid;
  min-width: 200px;
  max-height: 360px;
  padding: 5px;
  overflow-y: auto;
  border: 1px solid var(--menu-edge);
  border-radius: 13px;
  outline: none;
  background: var(--menu);
  box-shadow: 0 18px 40px -12px var(--shadow);
  animation: pop 0.16s ease;
  scrollbar-width: thin;
}
@keyframes pop {
  from {
    opacity: 0;
    scale: 0.97;
  }
}
.menuItem {
  display: flex;
  align-items: center;
  gap: 10px;
  min-height: 34px;
  padding: 0 9px;
  border: 0;
  border-radius: 8px;
  outline: none;
  background: none;
  font-size: 13px;
  text-align: left;
}
.menuItem:hover:not([aria-disabled]),
.menuItem:focus-visible,
.menuItem[data-over] {
  background: var(--hover);
}
.menuItem[aria-disabled='true'] {
  color: var(--ink-3) !important;
}
.menuItem[data-tone='accent'] {
  color: var(--accent) !important;
}
.menuIcon {
  width: 16px;
  height: 16px;
  color: var(--ink-2);
}
.menuItem[data-tone='accent'] .menuIcon {
  color: var(--accent);
}
.menuText {
  flex: 1;
  white-space: nowrap;
}
.menuTrail {
  color: var(--ink-3);
  font-size: 12px;
  font-variant-numeric: tabular-nums;
}
.kbd {
  display: grid;
  place-items: center;
  min-width: 22px;
  height: 22px;
  padding: 0 5px;
  border: 1px solid var(--menu-edge);
  border-radius: 6px;
  color: var(--ink-2);
  font-family: var(--sans);
  font-size: 11.5px;
}
.menuCheck {
  width: 14px;
  height: 14px;
  color: var(--accent);
  opacity: 0;
}
.menuCheck[data-on] {
  opacity: 1;
}
.menuCheck svg {
  width: 100%;
  height: 100%;
}
.menuSeparator {
  height: 1px;
  margin: 4px 2px;
  background: var(--menu-edge);
}
.menuLabel {
  padding: 7px 9px 3px;
  color: var(--ink-3);
  font-size: 11.5px;
}
.menuItem .health {
  width: 16px;
}
.menuItem .health[data-health='risk'] .healthDot {
  box-shadow:
    0 0 0 2.5px var(--menu),
    0 0 0 4px var(--risk);
}
.menuItem .avatar {
  box-shadow: none;
}

.toast {
  position: absolute;
  bottom: 18px;
  left: 50%;
  z-index: 7;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 9px 13px;
  border: 1px solid var(--menu-edge);
  border-radius: 11px;
  background: var(--menu);
  box-shadow: 0 14px 34px -10px var(--shadow);
  white-space: nowrap;
  translate: -50% 0;
  animation: rise 0.22s ease;
}
.toast svg {
  width: 14px;
  height: 14px;
  color: var(--accent);
}
@keyframes rise {
  from {
    opacity: 0;
    transform: translateY(8px);
  }
}

/* ---- Narrow stages ---------------------------------------------------------------------------- */

@container (max-width: 640px) {
  .header {
    flex-wrap: wrap;
    padding: 12px 10px 12px 12px;
  }
  .headerEnd {
    flex-basis: 100%;
  }
  .views {
    flex: 1;
  }
  .viewTab {
    flex: 1;
    padding: 0 8px;
  }
  /* The chips and the tools flow as one wrapping row, the tools at its end. */
  .filters {
    flex-wrap: wrap;
    gap: 7px;
  }
  .chips {
    display: contents;
  }
  .tools {
    margin-left: auto;
  }
  .navLabel {
    display: none;
  }
  .footer {
    padding-left: 10px;
  }
  .axis,
  .bar {
    grid-template-columns: minmax(80px, 108px) minmax(0, 1fr) 48px;
    gap: 8px;
  }
  .chart {
    padding: 8px 8px 12px;
  }
}
@container (max-width: 420px) {
  .footer {
    flex-wrap: wrap;
    row-gap: 8px;
  }
  .count {
    flex-basis: 100%;
  }
  .nav {
    margin-right: auto;
  }
  .export {
    padding: 0 11px;
  }
  .count {
    font-size: 12px;
  }
  .table [data-col='account'] {
    min-width: 128px;
  }
}

/* ---- The demo's pointer ----------------------------------------------------------------------- */

.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 8;
  pointer-events: none;
}
.pointer {
  width: 20px;
  height: 20px;
}
.hand {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .hand {
  visibility: visible;
}

@media (prefers-reduced-motion: reduce) {
  .viewTab,
  .body,
  .barFill,
  .headChevron,
  .table th,
  .table td {
    transition: none;
  }
  .menu,
  .toast,
  .chip,
  .insight,
  .meta[data-running],
  .insight:not([data-ready]) .insightIcon {
    animation: none;
  }
}
```

### query-table/data.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The query's rows: a sample of a SaaS company's accounts, each with its plan, owner, monthly
 * recurring revenue, twelve weeks of MRR as a trend, seats used of seats bought, and its health.
 * The table shows the rows that match the filters; the header's count is the whole result's.
 */

export type Plan = 'Enterprise' | 'Growth' | 'Starter';
export type Health = 'ok' | 'risk';

export type Owner = {
  id: string;
  name: string;
  /** The avatar's tint. */
  tone: 'violet' | 'green' | 'blue' | 'amber';
};

export type Account = {
  id: string;
  name: string;
  plan: Plan;
  owner: string;
  /** Monthly recurring revenue, in dollars. */
  mrr: number;
  /** MRR over the last twelve weeks, oldest first, in dollars. */
  trend: number[];
  seats: { used: number; total: number };
  health: Health;
};

export const PLANS: Plan[] = ['Enterprise', 'Growth', 'Starter'];

export const OWNERS: Owner[] = [
  { id: 'mara', name: 'Mara Quint', tone: 'violet' },
  { id: 'teo', name: 'Teo Varga', tone: 'green' },
  { id: 'bruno', name: 'Bruno Delorence', tone: 'blue' },
  { id: 'lena', name: 'Lena Ortiz', tone: 'amber' },
];

/** Twelve weeks that end on `end`, moving by `steps` (shares of the end), with a little wobble. */
function weeks(end: number, steps: number[]) {
  let value = end;
  const out = [end];
  for (let i = steps.length - 1; i >= 0; i -= 1) {
    value = Math.round(value / (1 + steps[i]));
    out.unshift(value);
  }
  return out;
}

const RISING = [0.01, 0.02, -0.005, 0.015, 0.03, 0.01, 0.02, -0.01, 0.025, 0.02, 0.015];
const STEADY = [0.005, -0.01, 0.01, 0.0, 0.015, -0.005, 0.005, 0.01, -0.005, 0.01, 0.005];
const CLIMB = [0.02, 0.03, 0.01, 0.04, 0.02, 0.035, 0.01, 0.03, 0.02, 0.04, 0.03];
const FALLING = [0.0, -0.01, 0.01, -0.02, -0.015, -0.03, -0.01, -0.025, -0.02, -0.015, -0.01];
const SLIDE = [-0.01, 0.0, -0.02, -0.03, -0.01, -0.04, -0.02, -0.035, -0.02, -0.03, -0.025];

const account = (
  id: string,
  name: string,
  plan: Plan,
  owner: string,
  mrr: number,
  steps: number[],
  used: number,
  total: number,
  health: Health = 'ok',
): Account => ({
  id,
  name,
  plan,
  owner,
  mrr,
  trend: weeks(mrr, steps),
  seats: { used, total },
  health,
});

export const ACCOUNTS: Account[] = [
  account('larkspur', 'Larkspur Health', 'Enterprise', 'mara', 48200, RISING, 212, 240),
  account('corvid', 'Corvid Labs', 'Enterprise', 'teo', 41750, STEADY, 168, 200),
  account('brightwater', 'Brightwater Co', 'Growth', 'mara', 22400, FALLING, 31, 50),
  account('quayside', 'Quayside Freight', 'Growth', 'teo', 19980, RISING, 44, 50),
  account('juniper', 'Juniper Row', 'Growth', 'mara', 17120, STEADY, 36, 50),
  account('alder', 'Alder Dental', 'Starter', 'teo', 9860, CLIMB, 22, 25),
  account('kiln', 'Kiln & Oak', 'Starter', 'mara', 8410, SLIDE, 8, 25, 'risk'),
  account('saltmarsh', 'Saltmarsh Studio', 'Starter', 'teo', 3240, STEADY, 9, 10),
  account('petrel', 'Petrel Goods', 'Starter', 'mara', 1980, FALLING, 3, 10, 'risk'),
  account('tidewell', 'Tidewell Bank', 'Enterprise', 'bruno', 52300, CLIMB, 410, 450),
  account('ferro', 'Ferro Systems', 'Enterprise', 'bruno', 36900, STEADY, 120, 200),
  account('vesper', 'Vesper Air', 'Enterprise', 'lena', 33800, SLIDE, 74, 180, 'risk'),
  account('arden', 'Arden Analytics', 'Growth', 'lena', 27350, RISING, 47, 60),
  account('cobalt', 'Cobalt Yard', 'Growth', 'bruno', 14600, CLIMB, 38, 40),
  account('mosswood', 'Mosswood Clinic', 'Starter', 'lena', 6120, STEADY, 14, 20),
  account('ostrava', 'Ostrava Print', 'Growth', 'lena', 11240, FALLING, 18, 40, 'risk'),
  account('pinehollow', 'Pine Hollow Co', 'Starter', 'bruno', 4450, SLIDE, 4, 15, 'risk'),
];

/** 48200 → 48,200. */
export const money = (value: number) => Math.round(value).toLocaleString('en-US');

/** 48200 → $48.2k, 5000 → $5k, 1250000 → $1.25M. */
export function shortMoney(value: number) {
  if (value >= 1e6) return `$${+(value / 1e6).toFixed(2)}M`;
  if (value >= 1000) return `$${+(value / 1000).toFixed(value >= 1e5 ? 0 : 1)}k`;
  return `$${Math.round(value)}`;
}

/** The trend's change over its twelve weeks, as a share: -0.14 is down 14%. */
export const change = (row: Account) => row.trend[row.trend.length - 1] / row.trend[0] - 1;

/** Seats used, as a whole percent. */
export const seatShare = (row: Account) => Math.round((row.seats.used / row.seats.total) * 100);

export const PLAN_RANK: Record<Plan, number> = { Enterprise: 3, Growth: 2, Starter: 1 };
```

### query-table/menu.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type ReactNode,
} from 'react';
import { Icon, type IconName } from './glyphs';
import styles from './query-table.module.css';

/*
 * The menus: placed on the stage under their trigger (over it when there is no room below), in
 * the stage's own px, since a gallery card may scale the whole stage. The arrows, Home and End
 * move between items; a letter with a shortcut runs it; Escape closes and gives the focus back;
 * a press elsewhere closes.
 */

const ITEMS = '[role="menuitem"], [role="menuitemradio"], [role="menuitemcheckbox"]';

export function Menu({
  anchor,
  label,
  align = 'start',
  takeFocus,
  onClose,
  shortcuts,
  children,
}: {
  anchor: HTMLElement;
  label: string;
  align?: 'start' | 'end';
  /** Moves the focus to the checked or first item: when the reader opened it, not the demo. */
  takeFocus: boolean;
  /** `back`: give the focus back to the trigger. */
  onClose: (back: boolean) => void;
  /** Keys that run an item at once, as the item's shortcut shows. */
  shortcuts?: Record<string, () => void>;
  children: ReactNode;
}) {
  const box = useRef<HTMLDivElement>(null);
  const [at, setAt] = useState<{ x: number; y: number } | null>(null);

  useLayoutEffect(() => {
    const menu = box.current;
    const frame = menu?.offsetParent as HTMLElement | null;
    if (!frame || !menu) return;
    const place = () => {
      const s = frame.getBoundingClientRect();
      const scale = s.width / frame.offsetWidth || 1;
      const a = anchor.getBoundingClientRect();
      const left = (a.left - s.left) / scale;
      const right = (a.right - s.left) / scale;
      const top = (a.top - s.top) / scale;
      const bottom = (a.bottom - s.top) / scale;
      const w = menu.offsetWidth;
      const h = menu.offsetHeight;
      let x = align === 'end' ? right - w : left;
      x = Math.max(8, Math.min(x, frame.clientWidth - w - 8));
      let y = bottom + 6;
      if (y + h > frame.clientHeight - 8 && top - h - 6 > 8) y = top - h - 6;
      setAt({ x, y });
    };
    place();
    const observer = new ResizeObserver(place);
    observer.observe(menu);
    return () => observer.disconnect();
  }, [anchor, align]);

  useEffect(() => {
    if (!takeFocus || !at) return;
    box.current
      ?.querySelector<HTMLElement>('[aria-checked="true"], [role^="menuitem"]')
      ?.focus({ preventScroll: true });
    // Only when it first shows.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [takeFocus, at === null]);

  useEffect(() => {
    const away = (event: PointerEvent) => {
      const target = event.target as Node;
      if (box.current?.contains(target) || anchor.contains(target)) return;
      onClose(false);
    };
    document.addEventListener('pointerdown', away);
    return () => document.removeEventListener('pointerdown', away);
  }, [anchor, onClose]);

  const onKeyDown = (event: ReactKeyboardEvent) => {
    const items = [...(box.current?.querySelectorAll<HTMLElement>(ITEMS) ?? [])];
    const index = items.indexOf(document.activeElement as HTMLElement);
    const move = (to: number) => {
      event.preventDefault();
      items[(to + items.length) % items.length]?.focus();
    };
    const run = shortcuts?.[event.key.toLowerCase()];
    if (run && !event.metaKey && !event.ctrlKey && !event.altKey) {
      event.preventDefault();
      run();
    } else if (event.key === 'ArrowDown') move(index + 1);
    else if (event.key === 'ArrowUp') move(index - 1);
    else if (event.key === 'Home') move(0);
    else if (event.key === 'End') move(items.length - 1);
    else if (event.key === 'Escape') {
      event.preventDefault();
      event.stopPropagation();
      onClose(true);
    } else if (event.key === 'Tab') onClose(false);
  };

  return (
    <div
      ref={box}
      role="menu"
      tabIndex={-1}
      aria-label={label}
      className={styles.menu}
      data-part="menu"
      style={{
        transform: at ? `translate(${at.x}px, ${at.y}px)` : undefined,
        visibility: at ? undefined : 'hidden',
      }}
      onKeyDown={onKeyDown}
    >
      {children}
    </div>
  );
}

export function MenuItem({
  onSelect,
  kind = 'action',
  checked,
  tone,
  icon,
  lead,
  kbd,
  trail,
  disabled,
  demo,
  children,
}: {
  onSelect: () => void;
  /** A plain action, one of a set (radio), or an on/off (checkbox): both show a check. */
  kind?: 'action' | 'radio' | 'checkbox';
  checked?: boolean;
  tone?: 'accent';
  icon?: IconName;
  /** Before the text, in place of an icon: a face, a pill. */
  lead?: ReactNode;
  /** The key that runs it from the open menu. */
  kbd?: string;
  /** At the right end: a count. */
  trail?: ReactNode;
  disabled?: boolean;
  demo?: string;
  children: ReactNode;
}) {
  const role =
    kind === 'radio' ? 'menuitemradio' : kind === 'checkbox' ? 'menuitemcheckbox' : 'menuitem';
  return (
    <button
      type="button"
      role={role}
      aria-checked={kind === 'action' ? undefined : !!checked}
      aria-disabled={disabled || undefined}
      aria-keyshortcuts={kbd}
      tabIndex={-1}
      className={styles.menuItem}
      data-tone={tone}
      data-demo={demo}
      onClick={() => {
        if (!disabled) onSelect();
      }}
    >
      {icon && <Icon name={icon} className={styles.menuIcon} />}
      {lead}
      <span className={styles.menuText}>{children}</span>
      {trail !== undefined && <span className={styles.menuTrail}>{trail}</span>}
      {kbd && (
        <kbd className={styles.kbd} aria-hidden="true">
          {kbd}
        </kbd>
      )}
      {kind !== 'action' && (
        <span className={styles.menuCheck} data-on={checked || undefined} aria-hidden="true">
          <Icon name="check" width={2.6} />
        </span>
      )}
    </button>
  );
}

export function MenuSeparator() {
  return <div role="separator" className={styles.menuSeparator} />;
}

export function MenuLabel({ children }: { children: ReactNode }) {
  return (
    <div className={styles.menuLabel} role="presentation">
      {children}
    </div>
  );
}
```

### query-table/glyphs.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The interface's line icons: a 24-unit box, drawn with currentColor.
 */

const PATHS = {
  table: 'M4 5h16v14H4zM4 10h16M10 10v9',
  share: 'M12 15V4M7.5 8.5 12 4l4.5 4.5M5 13v6h14v-6',
  close: 'M7 7l10 10M17 7 7 17',
  plus: 'M12 5v14M5 12h14',
  comfortable: 'M5 7h14M5 12h14M5 17h14',
  compact: 'M5 5.5h14M5 10h14M5 14.5h14M5 19h14',
  arrowUp: 'M12 19V5M6.5 10.5 12 5l5.5 5.5',
  arrowDown: 'M12 5v14M6.5 13.5 12 19l5.5-5.5',
  chevronDown: 'M7.5 10l4.5 4.5 4.5-4.5',
  filter: 'M4.5 7h15M7.5 12h9M10.5 17h3',
  group: 'M5 5h5.5v5.5H5zM13.5 5H19v5.5h-5.5zM5 13.5h5.5V19H5zM13.5 13.5H19V19h-5.5z',
  eye: 'M2.5 12s3.5-6.5 9.5-6.5 9.5 6.5 9.5 6.5-3.5 6.5-9.5 6.5S2.5 12 2.5 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
  eyeOff:
    'M4 4l16 16M10 5.7a9 9 0 0 1 2-.2c6 0 9.5 6.5 9.5 6.5a16 16 0 0 1-2.6 3.4M14.1 14.2A3 3 0 0 1 9.8 9.9M6.4 6.9C3.9 8.6 2.5 12 2.5 12s3.5 6.5 9.5 6.5a9 9 0 0 0 4.2-1',
  spark:
    'M12 3.5c.6 4.6 3.9 7.9 8.5 8.5-4.6.6-7.9 3.9-8.5 8.5-.6-4.6-3.9-7.9-8.5-8.5 4.6-.6 7.9-3.9 8.5-8.5z',
  check: 'M5 12.5l4.5 4.5L19 7.5',
  minus: 'M6 12h12',
  copy: 'M9 9h10v10H9zM15 9V5H5v10h4',
  link: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1',
  download: 'M12 4v11M7.5 10.5 12 15l4.5-4.5M5 19h14',
  columns: 'M4 5h16v14H4zM9.5 5v14M14.5 5v14',
} as const;

export type IconName = keyof typeof PATHS;

export function Icon({
  name,
  className,
  width = 1.8,
}: {
  name: IconName;
  className?: string;
  /** The stroke, in the 24-unit box. */
  width?: number;
}) {
  return (
    <svg
      viewBox="0 0 24 24"
      className={className}
      fill="none"
      stroke="currentColor"
      strokeWidth={width}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d={PATHS[name]} />
    </svg>
  );
}
```

### query-table/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it. The arrow and the
 * hand are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the hand a link shows. */
  glyph: (name: 'arrow' | 'hand') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (query-table.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, the hand white on a dark one, as the system draws them. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const HAND: CSSProperties = { fill: 'var(--pointer-edge)', stroke: 'var(--pointer)' };

/**
 * The pointer the demo moves around: an arrow, or a pointing hand over what it can press. It is
 * decorative: what it does shows on the table itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  handClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  handClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={handClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The tip of the finger sits where the arrow's tip is. */}
          <path
            d="M6.4 3.3c0-.8.6-1.4 1.3-1.4S9 2.5 9 3.3v5.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.7c.2-.4.6-.7 1.1-.7.7 0 1.2.5 1.2 1.2v3.5c0 2.8-1.9 4.9-4.6 4.9h-1.2c-1.8 0-3.1-.8-4.1-2.3l-2.6-3.9c-.4-.6-.2-1.3.4-1.7.6-.3 1.3-.2 1.7.4l.6.9z"
            style={HAND}
            strokeWidth="1.1"
            strokeLinejoin="round"
            transform="translate(-4.7 0.1)"
          />
        </svg>
      </span>
    </span>
  );
}
```

### query-table/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and not while the reader is using it. `take()` hands it to the reader; it
 * takes back over `idle` ms after their last input.
 */
export function useAutoplay<T extends HTMLElement>(idle = 6000) {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);
  const timer = useRef(0);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => {
    setTaken(true);
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setTaken(false), idle);
  }, [idle]);
  useEffect(() => () => window.clearTimeout(timer.current), []);

  return { ref, take, visible, reduced, playing: visible && !reduced && !taken };
}
```