Sortable Data Table
Sort and search native table rows, select ranges with Shift, and clear a mixed selection.
pnpm dlx shadcn@latest add @haze/sortable-data-table---
import { ArrowDown, ArrowUpDown, Check, Minus } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import SearchField from "./search-field.astro";
interface Column { key: string; label: string; numeric?: boolean; editable?: boolean }
interface Props {
id: string;
caption?: string;
columns?: Column[];
rows?: Record<string, string | number>[];
selectable?: boolean;
searchable?: boolean;
editable?: boolean;
class?: string;
}
const {
id, caption = "Project budgets", selectable = true, searchable = true, editable = false, class: className,
columns = [{ key: "name", label: "Project" }, { key: "owner", label: "Owner" }, { key: "budget", label: "Budget", numeric: true }],
rows = [{ name: "Fieldnote", owner: "Mila", budget: 4800 }, { name: "Waymark", owner: "Owen", budget: 2100 }, { name: "Northline", owner: "Lea", budget: 7200 }],
} = Astro.props;
---
<div data-haze-sortable-data-table class={cn("group/table grid min-w-0 gap-3", className)}>
{searchable && <SearchField id={`${id}-search`} label={`Filter ${caption}`} placeholder="Search records" />}
<div class="min-w-0 overflow-hidden rounded-xl border border-border bg-card">
<div role="region" aria-label={caption} tabindex="0" class="max-h-96 min-w-0 overflow-auto focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring">
<table id={id} data-editable={editable || undefined} class="w-full border-collapse text-left text-[0.8125rem]/5 tracking-[-0.01em]">
<caption class="border-b border-border px-4 py-3 text-start text-[0.8125rem]/5 font-medium">{caption}</caption>
<thead class="sticky top-0 z-10 bg-card">
<tr class="border-b border-border">
{selectable && <th scope="col" class="w-11 px-4"><span class="relative inline-grid size-4.5 shrink-0 place-items-center"><input data-select-all type="checkbox" aria-label="Select all visible records" disabled class="peer col-start-1 row-start-1 size-4.5 cursor-pointer appearance-none rounded-sm border border-border-strong bg-field transition-[background-color,border-color,scale] duration-150 ease-snappy hover:border-foreground active:scale-90 active:duration-75 checked:border-primary checked:hover:border-primary checked:bg-primary indeterminate:border-primary indeterminate:bg-primary focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed forced-colors:appearance-auto" /><Check class="pointer-events-none col-start-1 row-start-1 size-3.5 scale-50 text-primary-foreground opacity-0 transition-[opacity,scale] duration-200 ease-spring forced-colors:hidden peer-checked:scale-100 peer-checked:opacity-100 peer-indeterminate:opacity-0" stroke-width={3} aria-hidden="true" /><Minus class="pointer-events-none col-start-1 row-start-1 size-3.5 scale-50 text-primary-foreground opacity-0 transition-[opacity,scale] duration-200 ease-spring forced-colors:hidden peer-indeterminate:scale-100 peer-indeterminate:opacity-100" stroke-width={3} aria-hidden="true" /></span></th>}
{columns.map(column => <th scope="col" data-column={column.key} data-numeric={column.numeric || undefined} aria-sort="none" class={cn("h-11 px-4 font-medium text-muted-foreground aria-[sort=ascending]:text-foreground aria-[sort=descending]:text-foreground", column.numeric && "text-end")}>
<button disabled data-sort type="button" class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-md text-inherit motion-safe:transition-colors motion-safe:duration-150 enabled:hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring" aria-label={`Sort by ${column.label}`}>
{column.label}<ArrowUpDown data-sort-none aria-hidden="true" class="size-3" /><ArrowDown data-sort-arrow aria-hidden="true" class="hidden size-3 motion-safe:transition-[rotate] motion-safe:duration-150 motion-safe:ease-snappy" />
</button>
</th>)}
</tr>
</thead>
<tbody data-table-body>
{rows.map((row, index) => <tr data-record data-record-key={index} class="border-t border-border first:border-t-0 hover:bg-accent has-checked:bg-muted has-checked:hover:bg-accent motion-safe:transition-colors motion-safe:duration-150 motion-safe:ease-snappy [&[hidden]]:hidden">
{selectable && <td class="px-4"><span class="relative inline-grid size-4.5 shrink-0 place-items-center"><input data-select-row type="checkbox" name={`${id}-selection`} value={index} aria-label={`Select ${String(row[columns[0]?.key] ?? index + 1)}`} class="peer col-start-1 row-start-1 size-4.5 cursor-pointer appearance-none rounded-sm border border-border-strong bg-field transition-[background-color,border-color,scale] duration-150 ease-snappy hover:border-foreground active:scale-90 active:duration-75 checked:border-primary checked:hover:border-primary checked:bg-primary indeterminate:border-primary indeterminate:bg-primary focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed forced-colors:appearance-auto" /><Check class="pointer-events-none col-start-1 row-start-1 size-3.5 scale-50 text-primary-foreground opacity-0 transition-[opacity,scale] duration-200 ease-spring forced-colors:hidden peer-checked:scale-100 peer-checked:opacity-100 peer-indeterminate:opacity-0" stroke-width={3} aria-hidden="true" /></span></td>}
{columns.map(column => <td data-cell data-field={column.key} data-numeric={column.numeric || undefined} data-readonly={column.editable === false || undefined}
class={cn("relative h-13 min-w-20 px-4 whitespace-nowrap data-[selected]:bg-muted data-[active]:outline-2 data-[active]:-outline-offset-2 data-[active]:outline-ring", column.numeric && "text-end font-mono tabular-nums")}>{row[column.key] ?? ""}</td>)}
</tr>)}
</tbody>
</table>
<p data-no-records hidden class="p-6 text-center text-[0.8125rem] text-muted-foreground [&[hidden]]:hidden">No matching records.</p>
</div>
<div class="flex min-w-0 flex-wrap items-center justify-between gap-2 border-t border-border px-4 py-2 text-[0.8125rem]/5 text-muted-foreground">
<span data-table-count role="status">{rows.length} records</span>
<Button data-clear-selection hidden variant="ghost" size="sm" class="h-8 [&[hidden]]:hidden">Clear selection</Button>
</div>
</div>
<span data-table-status class="sr-only" role="status"></span>
</div>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const table = root.querySelector("table");
const body = root.querySelector<HTMLTableSectionElement>("[data-table-body]");
const counter = root.querySelector<HTMLElement>("[data-table-count]");
const status = root.querySelector<HTMLElement>("[data-table-status]");
if (!table || !body || !counter || !status) return;
const all = root.querySelector<HTMLInputElement>("[data-select-all]");
const clear = root.querySelector<HTMLButtonElement>("[data-clear-selection]");
const search = root.querySelector<HTMLInputElement>("input[type=search]");
const records = Array.from(body.querySelectorAll<HTMLTableRowElement>("[data-record]"));
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
let lastSelected: HTMLTableRowElement | undefined;
let direction = 1;
let sorted = "";
const visible = () => records.filter(row => !row.hidden);
const sync = () => {
const shown = visible();
const checked = records.filter(row => row.querySelector<HTMLInputElement>("[data-select-row]")?.checked);
const visibleChecked = shown.filter(row => row.querySelector<HTMLInputElement>("[data-select-row]")?.checked).length;
if (all) { all.checked = shown.length > 0 && visibleChecked === shown.length; all.indeterminate = visibleChecked > 0 && visibleChecked < shown.length; all.disabled = shown.length === 0; }
if (clear) clear.hidden = checked.length === 0;
counter.textContent = `${shown.length} ${shown.length === 1 ? "record" : "records"}${checked.length ? ` · ${checked.length} selected` : ""}`;
const empty = root.querySelector<HTMLElement>("[data-no-records]");
if (empty) empty.hidden = shown.length > 0;
};
root.querySelectorAll<HTMLButtonElement>("[data-sort]").forEach(button => {
button.disabled = false;
button.addEventListener("click", () => {
const head = button.closest("th")!;
const key = head.dataset.column!;
if (!root.dispatchEvent(new CustomEvent("haze:table-before-sort", { bubbles: true, cancelable: true, detail: { key } }))) return;
direction = sorted === key ? -direction : 1;
sorted = key;
const before = new Map(records.map(row => [row, row.getBoundingClientRect().top]));
const content = (row: HTMLTableRowElement) => Array.from(row.querySelectorAll<HTMLElement>("[data-cell]")).find(cell => cell.dataset.field === key)?.textContent?.trim() ?? "";
const ordered = records.toSorted((a, b) => {
const left = content(a), right = content(b);
const comparison = head.hasAttribute("data-numeric") && left !== "" && right !== "" && Number.isFinite(Number(left)) && Number.isFinite(Number(right))
? Number(left) - Number(right) : collator.compare(left, right);
return direction * comparison || Number(a.dataset.recordKey) - Number(b.dataset.recordKey);
});
ordered.forEach(row => body.append(row));
if (!matchMedia("(prefers-reduced-motion: reduce)").matches) {
ordered.filter(row => !row.hidden).forEach(row => {
const distance = (before.get(row) ?? 0) - row.getBoundingClientRect().top;
if (distance) row.animate([{ translate: `0 ${distance}px` }, { translate: "0 0" }], { duration: 300, easing: getComputedStyle(root).getPropertyValue("--ease-snappy").trim() || "ease" });
});
}
table.querySelectorAll("th[data-column]").forEach(other => {
const current = other === head;
other.setAttribute("aria-sort", current ? direction === 1 ? "ascending" : "descending" : "none");
const arrow = other.querySelector<HTMLElement>("[data-sort-arrow]");
const idle = other.querySelector<HTMLElement>("[data-sort-none]");
if (arrow) { arrow.classList.toggle("hidden", !current); arrow.style.rotate = direction === 1 ? "180deg" : "0deg"; }
idle?.classList.toggle("hidden", current);
});
status.textContent = `Sorted by ${button.textContent?.trim()}, ${direction === 1 ? "ascending" : "descending"}.`;
root.dispatchEvent(new CustomEvent("haze:table-sort", { bubbles: true, detail: { key, direction } }));
});
});
search?.addEventListener("input", () => {
const term = search.value.trim().toLocaleLowerCase();
records.forEach(row => { row.hidden = !(row.textContent ?? "").toLocaleLowerCase().includes(term); });
sync();
});
all?.addEventListener("change", () => { visible().forEach(row => { const box = row.querySelector<HTMLInputElement>("[data-select-row]"); if (box) box.checked = all.checked; }); sync(); });
body.addEventListener("click", event => {
const target = event.target;
if (!(target instanceof HTMLInputElement) || !target.matches("[data-select-row]")) return;
const ordered = Array.from(body.querySelectorAll<HTMLTableRowElement>("[data-record]:not([hidden])"));
const index = ordered.indexOf(target.closest("tr")!);
const anchor = lastSelected ? ordered.indexOf(lastSelected) : index;
if (event.shiftKey && anchor >= 0) ordered.slice(Math.min(anchor, index), Math.max(anchor, index) + 1).forEach(row => { row.querySelector<HTMLInputElement>("[data-select-row]")!.checked = target.checked; });
lastSelected = ordered[index];
sync();
});
clear?.addEventListener("click", () => {
records.forEach(row => { const box = row.querySelector<HTMLInputElement>("[data-select-row]"); if (box) box.checked = false; });
(all ?? search)?.focus();
sync();
});
sync();
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-sortable-data-table]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-sortable-data-table-listener")) {
document.documentElement.setAttribute("data-haze-sortable-data-table-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- A list has comparable fields people sort in ascending and descending order.
- Reviewers need to select several adjacent records for a bulk action.
When not to use
- Cells need direct editing and clipboard ranges. Use data-grid.
Installation
Add the Haze registry to components.json once, then install Sortable Data Table with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/sortable-data-tablenpx shadcn@latest add @haze/sortable-data-tableyarn dlx shadcn@latest add @haze/sortable-data-tablebunx --bun shadcn@latest add @haze/sortable-data-tableFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique table and filter IDs. |
| caption | string | – | Visible table caption and scroll-region name. |
| columns | Column[] | – | key and label, with numeric comparison and an editable flag for grid composition. |
| rows | Record<string, string | number>[] | – | Records in initial order. |
| selectable | boolean | – | Show native row selection checkboxes. Defaults to true. |
| searchable | boolean | – | Show live record search. Defaults to true. |
| editable | boolean | – | Marks cells for data-grid enhancement. Defaults to false. |
| class | string | – | Additional classes on the component wrapper. |
Keyboard interactions
- EnterSpace
- Sort a focused column or toggle a row selection.
- Shiftclick
- Extend selection across adjacent visible rows.
Accessibility
- Scoped native headers expose the current sort. Select all affects visible matches and reports a mixed state when only some are checked.
- The unenhanced table keeps all supplied records readable. Sorting slides rows for 300 ms and skips travel under reduced motion.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Sortable Data Table" with `npx shadcn@latest add @haze/sortable-data-table`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import SortableDataTable from "@/components/haze/ui/sortable-data-table.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/sortable-data-table.md
Customize with real content
Adapt the Haze sortable-data-table ui for our product. Replace the demo values of these props with our real content: id, caption, columns, rows, selectable, searchable, editable, class. Keep the layout, the heading level rules and these accessibility details: Scoped native headers expose the current sort. Select all affects visible matches and reports a mixed state when only some are checked. The unenhanced table keeps all supplied records readable. Sorting slides rows for 300 ms and skips travel under reduced motion. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using sortable-data-table, check it fits: use it when a list has comparable fields people sort in ascending and descending order.; reviewers need to select several adjacent records for a bulk action.. Avoid it when cells need direct editing and clipboard ranges. use data-grid.. Alternatives: @haze/table, @haze/data-grid, @haze/filter-toolbar.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/search-field
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.