# Data Table

A full list screen on TanStack Table: frozen ID and action columns, sticky header, sort on every column, search and faceted filters, selection with bulk actions, paging, column choice, URL state and honest loading, empty and error states.

Docs: https://cozy-ui.solo.engineer/docs/components/data-table/

Install: `npx shadcn@latest add @cozy/data-table`

### Usage

```tsx
import { DataTable, DataTableColumnHeader, IconAction, facetFilter } from "@/components/ui/data-table"

const columns: ColumnDef<Plot>[] = [
  { accessorKey: "id", size: 96, header: ({ column }) => <DataTableColumnHeader column={column} title="ID" /> },
  { accessorKey: "status", filterFn: facetFilter, header: ({ column }) => <DataTableColumnHeader column={column} title="Status" /> },
  { accessorKey: "yield", meta: { align: "end" }, header: ({ column }) => <DataTableColumnHeader column={column} title="Yield" /> },
  { id: "actions", size: 104, cell: ({ row }) => <IconAction label="Open" onClick={() => open(row.original)}><OpenGlyph /></IconAction> },
]

<DataTable
  label="Plots"
  columns={columns}
  data={plots}
  pin={{ left: ["id"], right: ["actions"] }}
  facets={[{ column: "status", title: "Status" }]}
  urlKey="plots"
  onRowClick={open}
  bulkActions={(rows, clear) => <IconAction label="Harvest selected" onClick={clear}><RiceGlyph /></IconAction>}
/>
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| label | `string` | – | Accessible name of the table; also used in the search label. |
| columns / data | `ColumnDef<T>[] / T[]` | – | TanStack Table v8 columns and rows. `meta: { title, align: "end", skeleton }` per column. |
| pin | `{ left?: string[]; right?: string[] }` | – | Columns frozen to the edges (ID/name left, actions right). The middle scrolls. |
| facets | `{ column; title; options? }[]` | – | One faceted filter per fixed-value column, with counts. Give the column `filterFn: facetFilter`. |
| bulkActions | `(rows, clear) => ReactNode` | – | Turns on selection; shown in a bar inside the board when rows are selected. |
| onRowClick | `(row: T) => void` | – | Opens the item. Clicks on controls inside the row are ignored; Enter works too. |
| urlKey | `string` | – | Mirror search, sort, filters, page and size in the query string under this prefix. |
| status | `"ready" \| "loading" \| "error"` | `"ready"` | With `errorText`, `lastGood` and `onRetry` for errors; `empty` replaces the empty message. |
| pageSizes | `number[]` | `[10, 20, 50]` | Choices in Rows per page; the first is the default. |
| maxHeight | `number \| string` | `560` | Height of the scrolling body; the header sticks inside it. |

Table rules this component follows: full width; ID or name frozen left and actions frozen right, only the middle scrolls (on narrow screens only the first left column stays frozen); sticky header; 12 px grey sentence-case headers with no band and no zebra rows; every column sorts, with the arrow on the active column only; search plus one faceted filter per fixed-value column, Reset and the row count; numbers and dates right-aligned; a row opens its detail screen, which has a breadcrumb back; sort and filters live in the URL; every action is an icon button with a tooltip and an accessible name; loading, empty and error states keep the frame.

### Example

```tsx
import { useMemo, useState } from "react";
import { toast } from "sonner";
import type { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
import { DataTable, DataTableColumnHeader, IconAction, facetFilter, type DataTableColumnMeta } from "@/components/ui/data-table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { DotsGlyph, DropGlyph, OpenGlyph, RiceGlyph, TrashGlyph } from "@/components/ui/glyphs";
import { Button } from "@/components/ui/button";
import { plots, statusTone, type Plot } from "./data-table-plots";

const fmt = new Intl.NumberFormat("en");

function PlotDetail({ plot, onBack }: { plot: Plot; onBack: () => void }) {
  const fields: [string, string][] = [
    ["Crop", plot.crop], ["Owner", plot.owner], ["Area", `${plot.area} tiles`], ["Planted", plot.planted], ["Yield", `${fmt.format(plot.yield)} coins`],
  ];
  return (
    <div className="cz-motion-rise grid gap-4">
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem><BreadcrumbLink asChild><button type="button" onClick={onBack}>Plots</button></BreadcrumbLink></BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem><BreadcrumbPage>{plot.id}</BreadcrumbPage></BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>
      <div className="flex flex-wrap items-center gap-3">
        <h3 className="m-0 text-2xl font-normal">{plot.name}</h3>
        <Badge variant={statusTone[plot.status]}>{plot.status}</Badge>
      </div>
      <dl className="cz-card m-0 grid grid-cols-2 gap-4 sm:grid-cols-5">
        {fields.map(([k, v]) => (
          <div key={k} className="grid gap-1"><dt className="text-xs text-text-muted">{k}</dt><dd className="m-0">{v}</dd></div>
        ))}
      </dl>
      <div><Button variant="outline" size="sm" onClick={onBack}>Back to plots</Button></div>
    </div>
  );
}

export default function DataTableDemo() {
  const [open, setOpen] = useState<Plot | null>(null);

  const columns = useMemo<ColumnDef<Plot, any>[]>(() => [
    {
      accessorKey: "id", size: 96, meta: { title: "ID", skeleton: "48px" } satisfies DataTableColumnMeta, enableHiding: false,
      header: ({ column }) => <DataTableColumnHeader column={column} title="ID" />,
    },
    {
      accessorKey: "name", size: 170, meta: { title: "Plot" }, enableHiding: false,
      header: ({ column }) => <DataTableColumnHeader column={column} title="Plot" />,
    },
    {
      accessorKey: "crop", meta: { title: "Crop" }, filterFn: facetFilter as never,
      header: ({ column }) => <DataTableColumnHeader column={column} title="Crop" />,
    },
    {
      accessorKey: "owner", meta: { title: "Owner" }, filterFn: facetFilter as never,
      header: ({ column }) => <DataTableColumnHeader column={column} title="Owner" />,
    },
    {
      accessorKey: "status", meta: { title: "Status", skeleton: "64px" }, filterFn: facetFilter as never,
      header: ({ column }) => <DataTableColumnHeader column={column} title="Status" />,
      cell: ({ row }) => <Badge variant={statusTone[row.original.status]}>{row.original.status}</Badge>,
    },
    {
      accessorKey: "area", meta: { title: "Area", align: "end", skeleton: "40px" },
      header: ({ column }) => <DataTableColumnHeader column={column} title="Area" />,
      cell: ({ getValue }) => `${getValue()} tiles`,
    },
    {
      accessorKey: "planted", meta: { title: "Planted", align: "end", skeleton: "84px" },
      header: ({ column }) => <DataTableColumnHeader column={column} title="Planted" />,
    },
    {
      accessorKey: "yield", meta: { title: "Yield", align: "end", skeleton: "56px" },
      header: ({ column }) => <DataTableColumnHeader column={column} title="Yield" />,
      cell: ({ getValue }) => fmt.format(getValue() as number),
    },
    {
      id: "actions", size: 100, enableSorting: false, enableHiding: false, meta: { title: "Actions", align: "end", skeleton: "60px" },
      header: () => <span className="sr-only">Actions</span>,
      cell: ({ row }) => (
        <div className="cz-dt__row-actions">
          <IconAction label="Open" onClick={() => setOpen(row.original)}><OpenGlyph /></IconAction>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button type="button" className="cz-button cz-button--ghost cz-button--icon cz-button--sm" aria-label={`More for ${row.original.id}`}><DotsGlyph /></button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onSelect={() => toast(`Watered ${row.original.name}`)}><DropGlyph className="size-4" /> Water</DropdownMenuItem>
              <DropdownMenuItem onSelect={() => toast.success(`Harvested ${row.original.name}`)}><RiceGlyph className="size-4" /> Harvest</DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem variant="destructive" onSelect={() => toast.error(`Cleared ${row.original.name}`)}><TrashGlyph className="size-4" /> Clear plot</DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      ),
    },
  ], []);

  if (open) return <div className="w-full"><PlotDetail plot={open} onBack={() => setOpen(null)} /></div>;

  return (
    <DataTable
      label="Plots"
      className="w-full"
      columns={columns}
      data={plots}
      getRowId={(p) => p.id}
      pin={{ left: ["id", "name"], right: ["actions"] }}
      facets={[{ column: "status", title: "Status" }, { column: "crop", title: "Crop" }, { column: "owner", title: "Owner" }]}
      searchPlaceholder="Search plots, crops, owners…"
      initialSort={[{ id: "yield", desc: true }]}
      urlKey="plots"
      onRowClick={setOpen}
      bulkActions={(rows, clear) => (
        <>
          <IconAction label="Water selected" onClick={() => { toast(`Watered ${rows.length} plots`); clear(); }}><DropGlyph /></IconAction>
          <IconAction label="Harvest selected" onClick={() => { toast.success(`Harvested ${rows.length} plots`); clear(); }}><RiceGlyph /></IconAction>
        </>
      )}
    />
  );
}
```

### Source (components/ui/data-table.tsx)

```tsx
import * as React from "react";
import {
  type Column,
  type ColumnDef,
  type ColumnFiltersState,
  type FilterFn,
  type Row,
  type RowSelectionState,
  type SortingState,
  type VisibilityState,
  flexRender,
  getCoreRowModel,
  getFacetedRowModel,
  getFacetedUniqueValues,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { cn } from "@/lib/utils";
import { Button } from "./button";
import { Checkbox } from "./checkbox";
import {
  DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger,
} from "./dropdown-menu";
import { ArrowUpGlyph, ChevronGlyph, ChevronsGlyph, CloseGlyph, ColumnsGlyph, FilterGlyph, RefreshGlyph, SearchGlyph } from "./glyphs";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./select";
import { Skeleton } from "./skeleton";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip";

/* ==========================================================================
   DataTable — a full data table on TanStack Table v8:
   - full width; chosen columns frozen left (id/name) and right (actions), the middle scrolls
   - sticky header; every column sorts (arrow on the active column only)
   - toolbar: search, one faceted filter per fixed-value column (with counts), Reset, the count
   - row selection with a bulk-action bar inside the table board
   - pagination with rows per page; column visibility
   - row click (or Enter) opens the item; sort, filters and page can live in the URL
   - loading, empty and error states keep the table's frame
   ========================================================================== */

export type DataTableColumnMeta = {
  /** Header text, also used in "Columns" and filter labels. */
  title?: string;
  /** "end" right-aligns numbers and dates. */
  align?: "start" | "end";
  /** Width of a loading bar in this column, e.g. "60%". */
  skeleton?: string;
};

export type DataTableFacet = {
  /** Column id to filter. The column should use `filterFn: facetFilter`. */
  column: string;
  title: string;
  /** Fixed options; defaults to the column's unique values. */
  options?: { label: string; value: string }[];
};

/** Filter function for faceted columns: keeps rows whose value is one of the chosen values. */
export const facetFilter: FilterFn<unknown> = (row, id, value: string[]) =>
  !value?.length || value.includes(String(row.getValue(id)));

type DataTableProps<T> = {
  /** Accessible name of the table, e.g. "Plots". */
  label: string;
  columns: ColumnDef<T, any>[];
  data: T[];
  getRowId?: (row: T, index: number) => string;
  /** Column ids frozen to the left and right edges. The selection column is added to the left automatically. */
  pin?: { left?: string[]; right?: string[] };
  facets?: DataTableFacet[];
  searchPlaceholder?: string;
  /** Turns on row selection; renders bulk actions for the selected rows. */
  bulkActions?: (rows: T[], clear: () => void) => React.ReactNode;
  enableSelection?: boolean;
  /** Called on row click or Enter. Clicks on buttons, links and checkboxes inside the row are ignored. */
  onRowClick?: (row: T) => void;
  /** Mirror sort, search, filters, page and page size in the URL query, prefixed with this key. */
  urlKey?: string;
  initialSort?: SortingState;
  pageSizes?: number[];
  /** "loading" draws bars at real size; "error" shows the error inside the frame. */
  status?: "ready" | "loading" | "error";
  errorText?: string;
  /** When the data was last good, shown with an error, e.g. "10:42". */
  lastGood?: string;
  onRetry?: () => void;
  /** Replaces the default empty message. */
  empty?: React.ReactNode;
  /** Extra controls at the right end of the toolbar. */
  toolbarEnd?: React.ReactNode;
  /** Height of the scrolling body; the header sticks inside it. */
  maxHeight?: number | string;
  className?: string;
};

/* ---------- URL state ---------- */

type UrlState = { q: string; sorting: SortingState; filters: ColumnFiltersState; page: number; size?: number };

function readUrl(key: string | undefined): Partial<UrlState> {
  if (!key || typeof window === "undefined") return {};
  try {
    const p = new URLSearchParams(window.location.search);
    const out: Partial<UrlState> = {};
    const q = p.get(`${key}.q`);
    if (q) out.q = q;
    const s = p.get(`${key}.sort`);
    if (s) {
      const [id, dir] = s.split(".");
      out.sorting = [{ id, desc: dir === "desc" }];
    }
    const filters: ColumnFiltersState = [];
    p.forEach((v, k) => {
      if (k.startsWith(`${key}.f.`) && v) filters.push({ id: k.slice(key.length + 3), value: v.split(",") });
    });
    if (filters.length) out.filters = filters;
    const page = Number(p.get(`${key}.page`));
    if (page > 1) out.page = page - 1;
    const size = Number(p.get(`${key}.size`));
    if (size > 0) out.size = size;
    return out;
  } catch {
    return {};
  }
}

function writeUrl(key: string | undefined, st: UrlState, defaultSize: number) {
  if (!key || typeof window === "undefined") return;
  try {
    const url = new URL(window.location.href);
    const p = url.searchParams;
    [...p.keys()].filter((k) => k.startsWith(`${key}.`)).forEach((k) => p.delete(k));
    if (st.q) p.set(`${key}.q`, st.q);
    if (st.sorting[0]) p.set(`${key}.sort`, `${st.sorting[0].id}.${st.sorting[0].desc ? "desc" : "asc"}`);
    st.filters.forEach((f) => {
      const v = f.value as string[];
      if (v?.length) p.set(`${key}.f.${f.id}`, v.join(","));
    });
    if (st.page > 0) p.set(`${key}.page`, String(st.page + 1));
    if (st.size && st.size !== defaultSize) p.set(`${key}.size`, String(st.size));
    window.history.replaceState(window.history.state, "", url);
  } catch {
    /* sandboxed history: keep state in memory only */
  }
}

/* ---------- Small parts ---------- */

/** An icon-only action with a tooltip; the tooltip text is also its accessible name. */
export function IconAction({ label, children, className, variant = "ghost", ...props }: React.ComponentProps<typeof Button> & { label: string }) {
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button variant={variant} size="icon-sm" aria-label={label} className={cn("cz-dt__action", className)} {...props}>
          {children}
        </Button>
      </TooltipTrigger>
      <TooltipContent>{label}</TooltipContent>
    </Tooltip>
  );
}

/** Sortable header. Click cycles ascending → descending → off. */
export function DataTableColumnHeader<T>({ column, title }: { column: Column<T, unknown>; title: string }) {
  if (!column.getCanSort()) return <span>{title}</span>;
  const dir = column.getIsSorted();
  return (
    <button
      type="button"
      className="cz-table__sort"
      data-dir={dir || "none"}
      onClick={column.getToggleSortingHandler()}
      aria-label={`Sort by ${title}${dir ? (dir === "asc" ? ", ascending" : ", descending") : ""}`}
    >
      {title}
      {dir && <ArrowUpGlyph />}
    </button>
  );
}

function FacetFilter<T>({ column, title, options }: { column: Column<T, unknown>; title: string; options?: DataTableFacet["options"] }) {
  const counts = column.getFacetedUniqueValues();
  const opts = options ?? [...counts.keys()].map((v) => ({ label: String(v), value: String(v) })).sort((a, b) => a.label.localeCompare(b.label));
  const chosen = new Set((column.getFilterValue() as string[] | undefined) ?? []);
  const [q, setQ] = React.useState("");
  const shown = opts.filter((o) => o.label.toLowerCase().includes(q.toLowerCase()));
  const set = (next: Set<string>) => column.setFilterValue(next.size ? [...next] : undefined);
  return (
    <Popover>
      <PopoverTrigger asChild>
        <button type="button" className="cz-dt__facet" data-active={chosen.size > 0 || undefined}>
          <FilterGlyph />
          {title}
          {chosen.size > 0 && (
            <span className="cz-dt__facet-values">
              {chosen.size > 2 ? (
                <span className="cz-dt__chip">{chosen.size} selected</span>
              ) : (
                [...chosen].map((v) => <span key={v} className="cz-dt__chip">{opts.find((o) => o.value === v)?.label ?? v}</span>)
              )}
            </span>
          )}
        </button>
      </PopoverTrigger>
      <PopoverContent align="start" className="cz-dt__pop">
        {opts.length > 6 && <input className="cz-input cz-dt__pop-search" placeholder={`Find ${title.toLowerCase()}…`} value={q} onChange={(e) => setQ(e.target.value)} aria-label={`Find ${title}`} />}
        <div className="cz-dt__pop-list" role="group" aria-label={title}>
          {shown.map((o) => {
            const on = chosen.has(o.value);
            return (
              <label key={o.value} className="cz-dt__pop-item">
                <Checkbox
                  checked={on}
                  onCheckedChange={() => {
                    const next = new Set(chosen);
                    on ? next.delete(o.value) : next.add(o.value);
                    set(next);
                  }}
                />
                <span className="min-w-0 flex-1 truncate">{o.label}</span>
                <span className="cz-dt__count">{counts.get(o.value) ?? 0}</span>
              </label>
            );
          })}
          {shown.length === 0 && <p className="m-0 px-2 py-3 text-sm text-text-muted">No match.</p>}
        </div>
        {chosen.size > 0 && (
          <div className="cz-dt__pop-foot">
            <Button size="sm" variant="ghost" className="w-full" onClick={() => set(new Set())}>Clear filter</Button>
          </div>
        )}
      </PopoverContent>
    </Popover>
  );
}

const isInteractive = (el: EventTarget | null) =>
  el instanceof Element && !!el.closest("button, a, input, select, textarea, label, [role='checkbox'], [role='menuitem'], [data-no-row-click]");

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

export function DataTable<T>({
  label,
  columns: userColumns,
  data,
  getRowId,
  pin,
  facets = [],
  searchPlaceholder = "Search…",
  bulkActions,
  enableSelection = !!bulkActions,
  onRowClick,
  urlKey,
  initialSort = [],
  pageSizes = [10, 20, 50],
  status = "ready",
  errorText = "Couldn’t load this list.",
  lastGood,
  onRetry,
  empty,
  toolbarEnd,
  maxHeight = 560,
  className,
}: DataTableProps<T>) {
  const fromUrl = React.useMemo(() => readUrl(urlKey), [urlKey]);
  const [sorting, setSorting] = React.useState<SortingState>(fromUrl.sorting ?? initialSort);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(fromUrl.filters ?? []);
  const [globalFilter, setGlobalFilter] = React.useState(fromUrl.q ?? "");
  const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({});
  const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});
  const [pagination, setPagination] = React.useState({ pageIndex: fromUrl.page ?? 0, pageSize: fromUrl.size ?? pageSizes[0] });

  // On narrow boards (phones) only the first left pin and the right pins stay frozen,
  // so the middle always has room to scroll.
  const scrollRef = React.useRef<HTMLDivElement>(null);
  const [compact, setCompact] = React.useState(false);
  React.useLayoutEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const ro = new ResizeObserver(([e]) => setCompact(e.contentRect.width < 560));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  const leftPins = [...(enableSelection ? ["select"] : []), ...(compact ? (pin?.left ?? []).slice(0, 1) : pin?.left ?? [])];

  const columns = React.useMemo<ColumnDef<T, any>[]>(() => {
    if (!enableSelection) return userColumns;
    const select: ColumnDef<T, any> = {
      id: "select",
      size: 52,
      enableSorting: false,
      enableHiding: false,
      header: ({ table }) => (
        <Checkbox
          checked={table.getIsAllPageRowsSelected() ? true : table.getIsSomePageRowsSelected() ? "indeterminate" : false}
          onCheckedChange={(v) => table.toggleAllPageRowsSelected(!!v)}
          aria-label="Select all rows on this page"
        />
      ),
      cell: ({ row }) => (
        <Checkbox checked={row.getIsSelected()} onCheckedChange={(v) => row.toggleSelected(!!v)} aria-label="Select row" />
      ),
    };
    return [select, ...userColumns];
  }, [enableSelection, userColumns]);

  const table = useReactTable({
    data,
    columns,
    getRowId,
    state: {
      sorting,
      columnFilters,
      globalFilter,
      columnVisibility,
      rowSelection,
      pagination,
      columnPinning: { left: leftPins, right: pin?.right ?? [] },
    },
    enableRowSelection: enableSelection,
    onSortingChange: setSorting,
    onColumnFiltersChange: (u) => { setColumnFilters(u); setPagination((p) => ({ ...p, pageIndex: 0 })); },
    onGlobalFilterChange: (u) => { setGlobalFilter(u); setPagination((p) => ({ ...p, pageIndex: 0 })); },
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    onPaginationChange: setPagination,
    globalFilterFn: "includesString",
    autoResetPageIndex: false,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getFacetedRowModel: getFacetedRowModel(),
    getFacetedUniqueValues: getFacetedUniqueValues(),
    getPaginationRowModel: getPaginationRowModel(),
  });

  React.useEffect(() => {
    writeUrl(urlKey, { q: globalFilter, sorting, filters: columnFilters, page: pagination.pageIndex, size: pagination.pageSize }, pageSizes[0]);
  }, [urlKey, globalFilter, sorting, columnFilters, pagination, pageSizes]);

  // keep the page in range when filters shrink the list
  const pageCount = Math.max(1, table.getPageCount());
  React.useEffect(() => {
    if (pagination.pageIndex > pageCount - 1) setPagination((p) => ({ ...p, pageIndex: pageCount - 1 }));
  }, [pageCount, pagination.pageIndex]);

  const filtered = table.getFilteredRowModel().rows.length;
  const selected = table.getFilteredSelectedRowModel().rows.map((r) => r.original);
  const isFiltered = !!globalFilter || columnFilters.length > 0;
  const reset = () => { setGlobalFilter(""); setColumnFilters([]); };
  const visibleColumns = table.getVisibleLeafColumns().length;
  const meta = (c: Column<T, unknown>) => (c.columnDef.meta ?? {}) as DataTableColumnMeta;

  const pinStyle = (c: Column<T, unknown>): React.CSSProperties => {
    const side = c.getIsPinned();
    if (!side) return {};
    return {
      position: "sticky",
      [side]: side === "left" ? c.getStart("left") : c.getAfter("right"),
      width: c.getSize(),
      minWidth: c.getSize(),
    };
  };
  const pinClass = (c: Column<T, unknown>) =>
    cn(
      c.getIsPinned() && "is-pinned",
      c.getIsPinned() === "left" && c.getIsLastColumn("left") && "is-pinned-edge-start",
      c.getIsPinned() === "right" && c.getIsFirstColumn("right") && "is-pinned-edge-end",
      meta(c).align === "end" && "is-num",
    );

  const rows = table.getRowModel().rows;

  const body = () => {
    if (status === "loading") {
      return Array.from({ length: Math.min(pagination.pageSize, 8) }, (_, i) => (
        <tr key={i} className="cz-table__row" aria-hidden>
          {table.getVisibleLeafColumns().map((c) => (
            <td key={c.id} className={cn("cz-table__cell", pinClass(c))} style={pinStyle(c)}>
              <Skeleton className={cn("h-4", meta(c).align === "end" && "ml-auto")} style={{ width: c.id === "select" ? 22 : meta(c).skeleton ?? "70%" }} />
            </td>
          ))}
        </tr>
      ));
    }
    if (status === "error") {
      return (
        <tr className="cz-table__row">
          <td className="cz-table__cell" colSpan={visibleColumns}>
            <div className="cz-dt__state cz-dt__state--error" role="alert">
              <CloseGlyph />
              <div className="grid">
                <span>{errorText}</span>
                {lastGood && <span className="text-sm text-text-muted">Last good data: {lastGood}</span>}
              </div>
              {onRetry && <IconAction label="Retry" variant="outline" onClick={onRetry}><RefreshGlyph /></IconAction>}
            </div>
          </td>
        </tr>
      );
    }
    if (rows.length === 0) {
      return (
        <tr className="cz-table__row">
          <td className="cz-table__cell" colSpan={visibleColumns}>
            <div className="cz-dt__state">
              {empty ?? (
                <>
                  <span>{isFiltered ? "Nothing matches these filters." : "Nothing here yet."}</span>
                  {isFiltered && <IconAction label="Reset filters" variant="outline" onClick={reset}><RefreshGlyph /></IconAction>}
                </>
              )}
            </div>
          </td>
        </tr>
      );
    }
    return rows.map((row: Row<T>) => (
      <tr
        key={row.id}
        className={cn("cz-table__row", onRowClick && "is-clickable")}
        data-state={row.getIsSelected() ? "selected" : undefined}
        tabIndex={onRowClick ? 0 : undefined}
        onClick={onRowClick ? (e) => !isInteractive(e.target) && onRowClick(row.original) : undefined}
        onKeyDown={onRowClick ? (e) => e.key === "Enter" && e.target === e.currentTarget && onRowClick(row.original) : undefined}
      >
        {row.getVisibleCells().map((cell) => (
          <td key={cell.id} className={cn("cz-table__cell", pinClass(cell.column))} style={pinStyle(cell.column)}>
            {flexRender(cell.column.columnDef.cell, cell.getContext())}
          </td>
        ))}
      </tr>
    ));
  };

  const { pageIndex, pageSize } = table.getState().pagination;
  const from = filtered === 0 ? 0 : pageIndex * pageSize + 1;
  const to = Math.min(filtered, (pageIndex + 1) * pageSize);

  return (
    <TooltipProvider>
      <div data-slot="data-table" className={cn("cz-dt", className)}>
        <div className="cz-dt__toolbar" role="toolbar" aria-label={`${label} filters`}>
          <label className="cz-dt__search">
            <SearchGlyph aria-hidden />
            <input
              className="cz-input"
              placeholder={searchPlaceholder}
              value={globalFilter}
              onChange={(e) => setGlobalFilter(e.target.value)}
              aria-label={`Search ${label}`}
            />
          </label>
          {facets.map((f) => {
            const col = table.getColumn(f.column);
            return col ? <FacetFilter key={f.column} column={col} title={f.title} options={f.options} /> : null;
          })}
          {isFiltered && <Button variant="ghost" size="sm" onClick={reset}>Reset</Button>}
          <span className="cz-dt__total">{filtered} {filtered === 1 ? "row" : "rows"}</span>
          {toolbarEnd}
          <DropdownMenu>
            <Tooltip>
              <TooltipTrigger asChild>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" size="icon-sm" aria-label="Choose columns" className="cz-dt__action"><ColumnsGlyph /></Button>
                </DropdownMenuTrigger>
              </TooltipTrigger>
              <TooltipContent>Choose columns</TooltipContent>
            </Tooltip>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Columns</DropdownMenuLabel>
              <DropdownMenuSeparator />
              {table.getAllLeafColumns().filter((c) => c.getCanHide()).map((c) => (
                <DropdownMenuCheckboxItem key={c.id} checked={c.getIsVisible()} onCheckedChange={(v) => c.toggleVisibility(!!v)} onSelect={(e) => e.preventDefault()}>
                  {meta(c).title ?? c.id}
                </DropdownMenuCheckboxItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
        </div>

        <div className="cz-dt__board">
          {selected.length > 0 && bulkActions && (
            <div className="cz-dt__select-bar" role="region" aria-label="Selected rows">
              <span>{selected.length} selected</span>
              <div className="flex items-center gap-1">{bulkActions(selected, () => table.resetRowSelection())}</div>
              <IconAction label="Clear selection" className="ml-auto" onClick={() => table.resetRowSelection()}><CloseGlyph /></IconAction>
            </div>
          )}
          <div ref={scrollRef} className="cz-dt__scroll" style={{ maxHeight }}>
            <table className="cz-table cz-table--data" aria-label={label} aria-busy={status === "loading" || undefined}>
              <thead className="cz-table__header">
                {table.getHeaderGroups().map((hg) => (
                  <tr key={hg.id}>
                    {hg.headers.map((h) => (
                      <th
                        key={h.id}
                        className={cn("cz-table__head", pinClass(h.column))}
                        style={pinStyle(h.column)}
                        aria-sort={h.column.getIsSorted() === "asc" ? "ascending" : h.column.getIsSorted() === "desc" ? "descending" : undefined}
                      >
                        {h.isPlaceholder ? null : flexRender(h.column.columnDef.header, h.getContext())}
                      </th>
                    ))}
                  </tr>
                ))}
              </thead>
              <tbody className="cz-table__body">{body()}</tbody>
            </table>
          </div>
        </div>

        <div className="cz-dt__pager">
          <span className="cz-dt__range">{from}–{to} of {filtered}</span>
          <div className="cz-dt__pager-controls">
            <span className="cz-dt__size">
              <span className="hidden sm:inline">Rows per page</span>
              <Select value={String(pageSize)} onValueChange={(v) => table.setPageSize(Number(v))}>
                <SelectTrigger aria-label="Rows per page" className="cz-dt__size-trigger"><SelectValue /></SelectTrigger>
                <SelectContent>{pageSizes.map((s) => <SelectItem key={s} value={String(s)}>{s}</SelectItem>)}</SelectContent>
              </Select>
            </span>
            <span className="tabular-nums whitespace-nowrap">Page {pageIndex + 1} of {pageCount}</span>
            <div className="flex gap-1">
              <IconAction label="First page" variant="outline" disabled={!table.getCanPreviousPage()} onClick={() => table.firstPage()}><ChevronsGlyph style={{ rotate: "180deg" }} /></IconAction>
              <IconAction label="Previous page" variant="outline" disabled={!table.getCanPreviousPage()} onClick={() => table.previousPage()}><ChevronGlyph style={{ rotate: "180deg" }} /></IconAction>
              <IconAction label="Next page" variant="outline" disabled={!table.getCanNextPage()} onClick={() => table.nextPage()}><ChevronGlyph /></IconAction>
              <IconAction label="Last page" variant="outline" disabled={!table.getCanNextPage()} onClick={() => table.lastPage()}><ChevronsGlyph /></IconAction>
            </div>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
}
```

npm: `import { IconAction, DataTableColumnHeader, DataTable } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
