Sortable table
FreeRecords in columns: click a header and the rows glide into order, numbers line up at the end, and picked rows raise a bulk bar that counts them. Airy in lively, compact lines in quiet.
npx shadcn@latest add https://pixilui.com/r/sortable-table.jsonPreview
import { useRef, useState } from "react";
import { Badge } from "@/components/pixilui/badge";
import { Button } from "@/components/pixilui/button";
import { appendRows } from "@/components/pixilui/list-row";
import { SortableTable, type SortableTableRow } from "@/components/pixilui/sortable-table";
// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
select: ["on", "off"],
} as const;
const INV: [string, string, number, string, string][] = [
["INV-1048", "Ava Chen", 2500, "2026-09-28", "Sent"],
["INV-1047", "Marcus Lee", 3850, "2026-09-24", "Paid"],
["INV-1046", "Priya Nair", 640.5, "2026-09-20", "Overdue"],
["INV-1045", "Tom Becker", 4800, "2026-09-12", "Paid"],
["INV-1044", "Sofia Reyes", 1240, "2026-09-09", "Paid"],
["INV-1042", "Elena Rossi", 980.25, "2026-08-28", "Draft"],
["INV-1041", "Omar Haddad", 12400, "2026-08-21", "Paid"],
["INV-1039", "Hana Ito", 310, "2026-08-14", "Overdue"],
];
const SHOW = 6;
const money = (n: number) => `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
const day = (d: string) => new Date(`${d}T12:00:00`).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
const TONE = { Paid: "ok", Overdue: "bad", Sent: "read", Draft: "neutral" } as const;
const rows: SortableTableRow[] = INV.map(([id, who, amt, issued, st]) => ({
id,
selectLabel: `Select ${id}`,
cells: { id, who: <span className="pixilui-table-primary"><b>{who}</b></span>, amt: money(amt), issued: day(issued), status: <Badge tone={TONE[st as keyof typeof TONE]}>{st}</Badge> },
sort: { id: Number(id.slice(4)), who, amt, issued: Number(issued.replace(/-/g, "")) },
}));
/** Invoices: sort by any header, pick a few and act on them together, and Load more lands the rest one stagger apart. */
export default function SortableTableDemo({ select = "on" }: KnobValues<typeof knobs>) {
const table = useRef<HTMLDivElement>(null);
const [shown, setShown] = useState(SHOW);
return (
<div className="w-full max-w-3xl rounded-panel bg-surface py-4 elevation-raised">
<SortableTable
ref={table}
aria-label="Invoices"
selectable={select === "on"}
selectAllLabel="Select all invoices"
columns={[
{ key: "id", label: "Invoice", sortable: true, kind: "num", width: "112px" },
{ key: "who", label: "Customer", sortable: true, kind: "primary", width: "minmax(0, 1.4fr)" },
{ key: "amt", label: "Amount", sortable: true, kind: "num", align: "end", width: "120px" },
{ key: "issued", label: "Issued", sortable: true, kind: "date", width: "132px" },
{ key: "status", label: "Status", width: "104px" },
]}
rows={rows.slice(0, shown)}
bulkName="Selected invoices"
bulk={() => (
<>
<Button size="sm">Mark as paid</Button>
<Button size="sm" variant="secondary-2">
Download
</Button>
</>
)}
footer={
shown < rows.length ? (
<>
<span>
Showing {shown} of {rows.length}
</span>
<Button size="sm" onClick={(e) => appendRows(table.current!, () => setShown(rows.length), { keyboard: e.detail === 0 })}>
Load more
</Button>
</>
) : (
<span>Showing {rows.length} of {rows.length} · That's everything</span>
)
}
/>
</div>
);
}When to use
Use it when
- Invoices, members, deals: records with the same few fields, sorted by any of them.
- Acting on several records at once: selectable, with bulk actions (Mark as paid, Download).
Use something else when
- A list of runs or logs: use list rows (one mark, a title, one line, one time).
- A box inside a card around the table, or two line weights: the lock leaves both out.
- Thousands of rows: page them; the table renders every row.
Installation
npx shadcn@latest add https://pixilui.com/r/sortable-table.jsonAdds sortable-table.tsx with checkbox.tsx, field.tsx and list-row.tsx, and installs clsx and tailwind-merge. The URL works in any app with a components.json, with no registry to add first.
"use client";
import { forwardRef, useEffect, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef, type CSSProperties, type MouseEvent, type ReactNode } from "react";
import { flushSync } from "react-dom";
import { IconSort } from "./icons/sort";
import { cn } from "./lib/utils";
import { close, flip, open } from "./lib/motion/surface";
import { Checkbox } from "./checkbox";
/** A missing list prop (plain JavaScript, a guessing agent): one stable empty list, so nothing throws or re-renders. */
const NONE: never[] = [];
/*
The table (B12, locked 1 Dec 2026, "Lock rows"): records in columns on one subgrid. A port of rows.js's table half. Look is
foundation.css section 8 (.pixilui-table): lively has a rounded header band and soft lines; quiet copies Lightfield's spacing
(44 rows, a 46 header between two lines, 12 cell padding, one 10% line between rows and columns, header icons, the second line
beside the name). A header click sorts and the rows glide to their new places (the system's flip); from the keyboard the
reorder is instant. The check column picks rows (the locked checkbox; the header box reads true, false or mixed), a picked
row is aria-selected, and the bulk bar counts them and rises from the foot. Every cell is at least a row tall.
Rows that come and go move with list-row's functions on the table: removeRow (a row leaves, the rest close the gap) and
appendRows (Load more: the body glides to its new height and the new rows arrive one stagger apart).
*/
export type SortableTableColumn = {
/** The key into each row's cells. */
key: string;
/** The header's words. Leave out for an actions column and give srLabel. */
label?: ReactNode;
/** A header's words for screen readers only (an actions column). */
srLabel?: string;
/** The header's icon (quiet shows it, after Lightfield). */
icon?: ReactNode;
/** A header button that sorts by this column. */
sortable?: boolean;
/** end right-aligns (numbers line up, tabular). */
align?: "start" | "end";
/** primary: the name cell (bold name, grey line); num, date and actions style their cells. */
kind?: "primary" | "num" | "date" | "actions";
/** The column's grid track: "minmax(0, 1fr)", "120px". */
width: string;
};
export type SortableTableRow = {
/** Stable id: a row keeps its element (and its glide) when sorted. */
id: string;
/** Each column's cell, by key. */
cells: Record<string, ReactNode>;
/** What each column sorts by (a number or text); the cell's text otherwise. */
sort?: Record<string, string | number>;
/** The check box's accessible name ("Select INV-1048"). */
selectLabel?: string;
};
export type SortableTableSort = { key: string; direction: "ascending" | "descending" };
export type SortableTableProps = Omit<ComponentPropsWithoutRef<"div">, "children"> & {
/** The columns, in order. */
columns: SortableTableColumn[];
/** The rows, in their resting order. */
rows: SortableTableRow[];
/** The table's accessible name ("Invoices"). */
"aria-label": string;
/** The sort, controlled. Pair with onSortChange. */
sort?: SortableTableSort | null;
/** The sort at first, uncontrolled. */
defaultSort?: SortableTableSort | null;
/** Runs when a header sorts the table. */
onSortChange?: (sort: SortableTableSort) => void;
/** A check column that picks rows. */
selectable?: boolean;
/** The picked row ids, controlled. Pair with onSelectedChange. */
selected?: string[];
/** The picked row ids at first, uncontrolled. */
defaultSelected?: string[];
/** Runs with the picked row ids when a box is clicked. */
onSelectedChange?: (ids: string[]) => void;
/** The header box's accessible name. */
selectAllLabel?: string;
/** The bulk bar's actions for the picked rows (buttons); it rises while any row is picked. */
bulk?: (ids: string[]) => ReactNode;
/** The bulk bar's count and accessible name: "3 selected". */
bulkLabel?: (count: number) => string;
/** The bulk bar's toolbar name ("Selected invoices"). */
bulkName?: string;
/** The foot under the rows ("Showing 8 of 12", Load more). */
footer?: ReactNode;
/** Extra room at the two ends, for a table that spans its card. */
edgeX?: string;
};
const sortValue = (row: SortableTableRow, key: string, text: string) => {
const v = row.sort?.[key] ?? text;
const n = typeof v === "number" ? v : Number(v);
return v !== "" && !Number.isNaN(n) ? n : String(v).toLowerCase();
};
/** Records in columns: click a header and the rows glide into order; pick rows and the bulk bar rises. */
export const SortableTable = forwardRef<HTMLDivElement, SortableTableProps>(function SortableTable(
{ columns = NONE, rows = NONE, sort: sortProp, defaultSort = null, onSortChange, selectable, selected: selectedProp, defaultSelected = [], onSelectedChange, selectAllLabel = "Select all", bulk, bulkLabel = (n) => `${n} selected`, bulkName, footer, edgeX, className, style, ...rest },
ref,
) {
const [innerSort, setInnerSort] = useState<SortableTableSort | null>(defaultSort);
const sort = sortProp === undefined ? innerSort : sortProp;
const [innerSel, setInnerSel] = useState<string[]>(defaultSelected);
const selected = selectedProp ?? innerSel;
const setSelected = (ids: string[]) => {
if (selectedProp === undefined) setInnerSel(ids);
onSelectedChange?.(ids);
};
const body = useRef<HTMLDivElement>(null);
const bar = useRef<HTMLDivElement>(null);
// the rows in order: each sort value is the cell's text unless the row names one
const [texts, setTexts] = useState<Record<string, Record<string, string>>>({});
useLayoutEffect(() => {
const out: Record<string, Record<string, string>> = {};
body.current?.querySelectorAll<HTMLElement>(":scope > .pixilui-table-row").forEach((r) => {
const id = r.dataset.rowId!;
out[id] = {};
const cells = [...r.querySelectorAll<HTMLElement>(":scope > .pixilui-table-cell")].slice(selectable ? 1 : 0);
columns.forEach((c, i) => (out[id]![c.key] = cells[i]?.textContent?.trim() ?? ""));
});
setTexts(out);
// the cells' words change with the rows and columns
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [rows, columns]);
const ordered = sort
? [...rows].sort((a, b) => {
const x = sortValue(a, sort.key, texts[a.id]?.[sort.key] ?? "");
const y = sortValue(b, sort.key, texts[b.id]?.[sort.key] ?? "");
return (x > y ? 1 : x < y ? -1 : 0) * (sort.direction === "ascending" ? 1 : -1);
})
: rows;
const sortBy = (key: string, e: MouseEvent) => {
const next: SortableTableSort = { key, direction: sort?.key === key && sort.direction === "descending" ? "ascending" : "descending" };
const change = () =>
flushSync(() => {
if (sortProp === undefined) setInnerSort(next);
onSortChange?.(next);
});
const nodes = [...(body.current?.querySelectorAll<HTMLElement>(":scope > .pixilui-table-row") ?? [])];
// rows glide to their new places; from the keyboard the reorder just happens
if (e.detail === 0) change();
else flip(nodes, change);
};
// the bulk bar rises from the foot while any row is picked; it counts the picked rows still in the table (a removed row leaves the count)
const count = rows.filter((r) => selected.includes(r.id)).length;
const was = useRef(0);
useEffect(() => {
const el = bar.current;
if (!el) return;
if (count && !was.current) open(el);
else if (!count && was.current) void close(el);
was.current = count;
}, [count]);
const all = rows.length > 0 && rows.every((r) => selected.includes(r.id));
const some = rows.some((r) => selected.includes(r.id));
const tracks = [...(selectable ? ["40px"] : []), ...columns.map((c) => c.width)].join(" ");
const vars = { "--pixilui-table-cols": tracks, ...(edgeX ? { "--pixilui-table-edge-x": edgeX } : {}), ...style } as CSSProperties;
return (
<div ref={ref} role="table" className={cn("pixilui-table font-body", className)} style={vars} {...rest}>
<div className="pixilui-table-head" role="row">
{selectable ? (
<span className="pixilui-table-cell" role="columnheader" data-kind="check">
<Checkbox aria-label={selectAllLabel} checked={all ? true : some ? "mixed" : false} onCheckedChange={(on) => setSelected(on ? rows.map((r) => r.id) : [])} />
</span>
) : null}
{columns.map((c) => {
const end = c.align === "end";
const hic = c.icon ? (
<span className="pixilui-table-head-ic" aria-hidden="true">
{c.icon}
</span>
) : null;
const words = c.label ?? (c.srLabel ? <span className="sr-only">{c.srLabel}</span> : null);
return (
<span
key={c.key}
className="pixilui-table-cell"
role="columnheader"
aria-sort={c.sortable ? (sort?.key === c.key ? sort.direction : "none") : undefined}
data-kind={c.kind === "actions" ? "actions" : undefined}
data-align={end ? "end" : undefined}
>
{c.sortable ? (
// a right-aligned header keeps its icon beside its label: the button runs right to left (arrow, icon, label)
end ? (
<button className="pixilui-table-sort" type="button" onClick={(e) => sortBy(c.key, e)}>
{words}
{hic}
<IconSort />
</button>
) : (
<>
{hic}
<button className="pixilui-table-sort" type="button" onClick={(e) => sortBy(c.key, e)}>
{words}
<IconSort />
</button>
</>
)
) : (
<>
{hic}
{words}
</>
)}
</span>
);
})}
</div>
<div ref={body} className="pixilui-table-body" role="rowgroup">
{ordered.map((r) => {
const on = selected.includes(r.id);
return (
<div key={r.id} className="pixilui-table-row" role="row" data-row-id={r.id} aria-selected={selectable ? on : undefined}>
{selectable ? (
<span className="pixilui-table-cell" role="cell" data-kind="check">
<Checkbox aria-label={r.selectLabel ?? `Select ${r.id}`} checked={on} onCheckedChange={(v) => setSelected(v ? [...selected, r.id] : selected.filter((x) => x !== r.id))} />
</span>
) : null}
{columns.map((c) => (
<span key={c.key} className="pixilui-table-cell" role="cell" data-kind={c.kind} data-sort={r.sort?.[c.key]} data-align={c.align === "end" ? "end" : undefined}>
{r.cells[c.key]}
</span>
))}
</div>
);
})}
</div>
{footer != null ? <div className="pixilui-table-foot">{footer}</div> : null}
{bulk ? (
<div ref={bar} className="pixilui-table-bulk" role="toolbar" aria-label={bulkName} data-surface="edge" hidden>
<span className="pixilui-table-bulk-count">{bulkLabel(count)}</span>
{bulk(selected)}
</div>
) : null}
</div>
);
});
It uses Checkbox, Field and List row: add them the same way. Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
import { SortableTable } from "@/components/pixilui/sortable-table";
<SortableTable
aria-label={aria-label}
columns={columns}
rows={rows}
onSortChange={onSortChange}
onSelectedChange={onSelectedChange}
/>Fills its container; give each column a track ("minmax(0, 1fr)", "120px"). Every cell is at least a row tall, so nothing inside can unstretch it.
API reference
aria-labelRequiredstring–The table's accessible name ("Invoices").columnsRequiredSortableTableColumn[]NONEThe columns, in order.rowsRequiredSortableTableRow[]NONEThe rows, in their resting order.sortSortableTableSort | null–The sort, controlled. Pair with onSortChange.defaultSortSortableTableSort | nullnullThe sort at first, uncontrolled.onSortChange(sort: SortableTableSort) => void–Runs when a header sorts the table.selectableboolean–A check column that picks rows.selectedstring[]–The picked row ids, controlled. Pair with onSelectedChange.defaultSelectedstring[][]The picked row ids at first, uncontrolled.onSelectedChange(ids: string[]) => void–Runs with the picked row ids when a box is clicked.selectAllLabelstring"Select all"The header box's accessible name.bulk(ids: string[]) => ReactNode–The bulk bar's actions for the picked rows (buttons); it rises while any row is picked.bulkLabel(count: number) => string(n) => `${n} selected`The bulk bar's count and accessible name: "3 selected".bulkNamestring–The bulk bar's toolbar name ("Selected invoices").footerReactNode–The foot under the rows ("Showing 8 of 12", Load more).edgeXstring–Extra room at the two ends, for a table that spans its card.Also takes every native <div> attribute, and a ref.
Keyboard
Accessibility
- table, rowgroup, row, columnheader and cell roles; a sorted header carries aria-sort.
- The header check box reads true, false or mixed; a picked row is aria-selected; the bulk bar is a named toolbar with a live count.
- An actions column names itself for screen readers (srLabel).
Motion
- A header click glides the rows to their new places (the system's flip, 420ms); from the keyboard the reorder is instant.
- The sort arrow shows on hover and stays once sorted; hover washes a row in 150ms.
- The bulk bar rises from the foot as the first row is picked and leaves with the last.
- A removed row fades into a blur, then the rest glide up to close the gap; Load more's rows arrive 35ms apart while the body glides taller.
- Reduced motion: every change instant.