Bruno DelorenceBruno
Appearance
Appearance

Choose your reading theme.

Contact

Query table

New

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.

query-table/query-table.tsx
Live · interactive

Accounts by MRR

1,284 rows · ran 0.2 s

Larkspur Health, owner Mara QuintEnterprise$48,200Up 16% over twelve weeks212 of 240 seats used, 88%Healthy
Corvid Labs, owner Teo VargaEnterprise$41,750Up 4% over twelve weeks168 of 200 seats used, 84%Healthy
Brightwater Co, owner Mara QuintGrowth$22,400Down 14% over twelve weeks31 of 50 seats used, 62%Healthy
Quayside Freight, owner Teo VargaGrowth$19,980Up 16% over twelve weeks44 of 50 seats used, 88%Healthy
Juniper Row, owner Mara QuintGrowth$17,120Up 4% over twelve weeks36 of 50 seats used, 72%Healthy
Alder Dental, owner Teo VargaStarter$9,860Up 32% over twelve weeks22 of 25 seats used, 88%Healthy
Kiln & Oak, owner Mara QuintStarter$8,410Down 22% over twelve weeks8 of 25 seats used, 32%At risk

1 selected · showing 7 of 1,284

The live component, numbered part by part. Every measurement is read from it as it is drawn. Point at a row to outline its part, or at a part to find its row.

The choices it offers, each value drawn live and the default marked, with how to pick one.

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.

Each one drawn with the component itself, used well or badly.

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 $.

You can add this component with the shadcn CLI or by hand:

Into components/query-table of any React project, with no setup:

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

Either way it needs React 19 and a bundler that supports CSS Modules, such as Next.js or Vite. It has a dark colour scheme: 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

accounts-report.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}    />  );}

Each state below is a live instance, locked so you can study it.

The pieces it is built from, each with its measurements read live.

Below are variations of this component, each live, with its code.

Grouped by plan

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

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.

SQL view

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

Accounts at risk

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

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.

  • 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.
PropTypeDefaultDescription
rowsAccount[]seventeen accountsThe rows the query can return: name, plan, owner, MRR, twelve weeks of MRR, seats used and bought, and health.
ownersOwner[]four peopleEveryone who can own an account: an id, a name and an avatar tint.
titlestring'Accounts by MRR'The query’s name, in the header and the SQL’s first comment.
totalnumber1284How many rows the query returns with its default filters; the counts scale from it as the filters change.
defaultFiltersPartial<Filters>{ 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.
defaultSortSort{ key: 'mrr', desc: true }The column sorted at first, and which way.
defaultSelectedstring[]['brightwater']Row ids selected at first.
defaultStateQueryTableState—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.
autoplaybooleantrueWhile 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.
classNamestring—Classes for the stage.

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.

The complete source behind this demo. Open source under the MIT license, © 2026 Bruno Delorence: copy it, change it, ship it.

query-table.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,
cells.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. */
views.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 };
query.ts
// 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 }[] = [
query-table.module.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;
data.ts
// 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. */
menu.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"]';
glyphs.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',
demo-pointer.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 = {
use-autoplay.ts
// 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(