# Animated Data table for UI SDK (/docs/components/data-table)

The full list screen on top of Table, with no table library: give it data and columns and it owns the search, faceted filters with live counts, the sort, hidden columns, row selection, the page and the page size, each one controlled or not so a page can keep it in the URL. Rows cascade in after a sort or a page turn, a hidden column folds away while the others close the gap, Reset slides in while anything is filtered, and a bulk bar rises from the bottom centre while rows are selected.

<ComponentPreview slug="data-table" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport { CircleCheck, CircleDashed, Download, Package, Truck, XCircle } from \&#x22;lucide-react\&#x22;\nimport * as React from \&#x22;react\&#x22;\n\nimport { Badge } from \&#x22;@/components/keyframery/badge\&#x22;\nimport { DataTable, DataTableBulkAction, type DataTableColumnDef } from \&#x22;@/components/keyframery/data-table\&#x22;\nimport { MenuItem, MenuSeparator } from \&#x22;@/components/keyframery/menu\&#x22;\n\n/* ---------------------------------------------------------------- the orders */\n\ntype Payment = \&#x22;Paid\&#x22; | \&#x22;Pending\&#x22; | \&#x22;Refunded\&#x22; | \&#x22;Failed\&#x22;\ntype Fulfilment = \&#x22;Unfulfilled\&#x22; | \&#x22;Packed\&#x22; | \&#x22;Shipped\&#x22; | \&#x22;Delivered\&#x22;\ntype Order = { id: string; number: number; customer: string; date: string; payment: Payment; fulfilment: Fulfilment; items: number; total: number }\n\n/* A small seeded generator, run once when the file loads: the same 120 orders every time. */\nfunction seeded(seed: number) {\n  let a = seed\n  return () => {\n    a = (a + 0x6d2b79f5) | 0\n    let t = Math.imul(a ^ (a >>> 15), 1 | a)\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n  }\n}\n\nconst firstNames = [\&#x22;Maya\&#x22;, \&#x22;Tom\&#x22;, \&#x22;Ines\&#x22;, \&#x22;Sam\&#x22;, \&#x22;Lena\&#x22;, \&#x22;Joe\&#x22;, \&#x22;Aiko\&#x22;, \&#x22;Ravi\&#x22;, \&#x22;Clara\&#x22;, \&#x22;Ola\&#x22;, \&#x22;Ben\&#x22;, \&#x22;Nia\&#x22;, \&#x22;Marco\&#x22;, \&#x22;Priya\&#x22;, \&#x22;Hugo\&#x22;, \&#x22;Elif\&#x22;, \&#x22;Mariam\&#x22;, \&#x22;Theo\&#x22;, \&#x22;Zara\&#x22;, \&#x22;Luca\&#x22;, \&#x22;Noor\&#x22;, \&#x22;Felix\&#x22;, \&#x22;Marta\&#x22;, \&#x22;Kofi\&#x22;]\nconst lastNames = [\&#x22;Chen\&#x22;, \&#x22;Okafor\&#x22;, \&#x22;Duarte\&#x22;, \&#x22;Price\&#x22;, \&#x22;Brandt\&#x22;, \&#x22;Walsh\&#x22;, \&#x22;Mori\&#x22;, \&#x22;Shah\&#x22;, \&#x22;Ruiz\&#x22;, \&#x22;Nord\&#x22;, \&#x22;Carter\&#x22;, \&#x22;Evans\&#x22;, \&#x22;Rossi\&#x22;, \&#x22;Iyer\&#x22;, \&#x22;Laurent\&#x22;, \&#x22;Demir\&#x22;, \&#x22;Haddad\&#x22;, \&#x22;Becker\&#x22;, \&#x22;Ali\&#x22;, \&#x22;Moretti\&#x22;, \&#x22;Khan\&#x22;, \&#x22;Novak\&#x22;, \&#x22;Silva\&#x22;, \&#x22;Mensah\&#x22;]\n\nfunction makeOrders(): Order[] {\n  const random = seeded(1042)\n  const pick = <T,>(list: readonly T[]) => list[Math.floor(random() * list.length)]\n  const today = Date.UTC(2026, 10, 19)\n  let day = 0\n  return Array.from({ length: 120 }, (_, i) => {\n    day += random() < 0.55 ? 0 : 1\n    const age = day\n    /* Newer orders are less far along. */\n    const fulfilment: Fulfilment = age < 2 ? pick([\&#x22;Unfulfilled\&#x22;, \&#x22;Unfulfilled\&#x22;, \&#x22;Packed\&#x22;] as const) : age < 6 ? pick([\&#x22;Packed\&#x22;, \&#x22;Shipped\&#x22;, \&#x22;Shipped\&#x22;, \&#x22;Unfulfilled\&#x22;] as const) : pick([\&#x22;Shipped\&#x22;, \&#x22;Delivered\&#x22;, \&#x22;Delivered\&#x22;, \&#x22;Delivered\&#x22;] as const)\n    const roll = random()\n    const payment: Payment = roll < 0.72 ? \&#x22;Paid\&#x22; : roll < 0.86 ? \&#x22;Pending\&#x22; : roll < 0.95 ? \&#x22;Refunded\&#x22; : \&#x22;Failed\&#x22;\n    const items = 1 + Math.floor(random() * random() * 6)\n    const total = Math.round((items * (14 + random() * 86) + (random() < 0.3 ? 4.9 : 0)) * 100) / 100\n    const number = 1160 - i\n    return {\n      id: String(number),\n      number,\n      customer: `${pick(firstNames)} ${pick(lastNames)}`,\n      date: new Date(today - age * 86400000).toISOString().slice(0, 10),\n      payment,\n      fulfilment,\n      items,\n      total,\n    }\n  })\n}\n\nconst seedOrders = makeOrders()\n\nconst euro = new Intl.NumberFormat(\&#x22;en-GB\&#x22;, { style: \&#x22;currency\&#x22;, currency: \&#x22;EUR\&#x22; })\nconst dayFormat = new Intl.DateTimeFormat(\&#x22;en-GB\&#x22;, { day: \&#x22;numeric\&#x22;, month: \&#x22;short\&#x22;, timeZone: \&#x22;UTC\&#x22; })\n\nconst paymentBadge: Record<Payment, \&#x22;success\&#x22; | \&#x22;outline\&#x22; | \&#x22;secondary\&#x22; | \&#x22;destructive\&#x22;> = { Paid: \&#x22;success\&#x22;, Pending: \&#x22;outline\&#x22;, Refunded: \&#x22;secondary\&#x22;, Failed: \&#x22;destructive\&#x22; }\nconst fulfilmentIcon: Record<Fulfilment, React.ReactNode> = {\n  Unfulfilled: <CircleDashed size={16} strokeWidth={1.75} aria-hidden />,\n  Packed: <Package size={16} strokeWidth={1.75} aria-hidden />,\n  Shipped: <Truck size={16} strokeWidth={1.75} aria-hidden />,\n  Delivered: <CircleCheck size={16} strokeWidth={1.75} aria-hidden />,\n}\n\nfunction columnsFor(sticky: boolean): DataTableColumnDef<Order>[] {\n  return [\n    { id: \&#x22;number\&#x22;, header: \&#x22;Order\&#x22;, accessor: (o) => `#${o.number}`, sortValue: (o) => o.number, searchable: true, hideable: false, sticky, cell: (o) => <span className=\&#x22;font-medium\&#x22;>#{o.number}</span> },\n    { id: \&#x22;customer\&#x22;, header: \&#x22;Customer\&#x22;, searchable: true, cell: (o) => <span className=\&#x22;font-medium\&#x22;>{o.customer}</span> },\n    { id: \&#x22;date\&#x22;, header: \&#x22;Date\&#x22;, hideBelow: \&#x22;md\&#x22;, cell: (o) => <span className=\&#x22;text-muted-foreground\&#x22;>{dayFormat.format(new Date(o.date))}</span> },\n    {\n      id: \&#x22;payment\&#x22;,\n      header: \&#x22;Payment\&#x22;,\n      filter: { options: ([\&#x22;Paid\&#x22;, \&#x22;Pending\&#x22;, \&#x22;Refunded\&#x22;, \&#x22;Failed\&#x22;] as const).map((value) => ({ value })) },\n      cell: (o) => <Badge variant={paymentBadge[o.payment]}>{o.payment}</Badge>,\n    },\n    {\n      id: \&#x22;fulfilment\&#x22;,\n      header: \&#x22;Fulfilment\&#x22;,\n      hideBelow: \&#x22;sm\&#x22;,\n      filter: { options: ([\&#x22;Unfulfilled\&#x22;, \&#x22;Packed\&#x22;, \&#x22;Shipped\&#x22;, \&#x22;Delivered\&#x22;] as const).map((value) => ({ value, icon: fulfilmentIcon[value] })) },\n      sortValue: (o) => [\&#x22;Unfulfilled\&#x22;, \&#x22;Packed\&#x22;, \&#x22;Shipped\&#x22;, \&#x22;Delivered\&#x22;].indexOf(o.fulfilment),\n      cell: (o) => (\n        <span className=\&#x22;flex items-center gap-1.5 text-muted-foreground [&_svg]:shrink-0\&#x22;>\n          {fulfilmentIcon[o.fulfilment]}\n          <span className=\&#x22;text-foreground\&#x22;>{o.fulfilment}</span>\n        </span>\n      ),\n    },\n    { id: \&#x22;items\&#x22;, header: \&#x22;Items\&#x22;, align: \&#x22;end\&#x22;, hideBelow: \&#x22;lg\&#x22; },\n    { id: \&#x22;total\&#x22;, header: \&#x22;Total\&#x22;, align: \&#x22;end\&#x22;, cell: (o) => <span className=\&#x22;font-medium\&#x22;>{euro.format(o.total)}</span> },\n  ]\n}\n\nexport default function DataTableDemo({\n  title = \&#x22;Orders\&#x22;,\n  searchPlaceholder = \&#x22;Search orders or customers\&#x22;,\n  pageSize = \&#x22;8\&#x22;,\n  selectable = true,\n  rowMenu = true,\n  loading = false,\n  hidden = \&#x22;none\&#x22;,\n  sticky = true,\n  width = 940,\n  rowHeight = 44,\n  radius = 14,\n  surface = \&#x22;\&#x22;,\n  border = \&#x22;\&#x22;,\n  accent = \&#x22;\&#x22;,\n  bar = \&#x22;\&#x22;,\n}: {\n  title?: string\n  searchPlaceholder?: string\n  pageSize?: \&#x22;5\&#x22; | \&#x22;8\&#x22; | \&#x22;10\&#x22; | \&#x22;20\&#x22;\n  selectable?: boolean\n  rowMenu?: boolean\n  loading?: boolean\n  hidden?: \&#x22;none\&#x22; | \&#x22;date\&#x22; | \&#x22;items\&#x22; | \&#x22;fulfilment\&#x22;\n  sticky?: boolean\n  width?: number\n  rowHeight?: number\n  radius?: number\n  surface?: string\n  border?: string\n  accent?: string\n  bar?: string\n}) {\n  const [orders, setOrders] = React.useState(seedOrders)\n  const [selected, setSelected] = React.useState<string[]>([])\n  const columns = React.useMemo(() => columnsFor(sticky), [sticky])\n\n  const update = (ids: string[], change: (o: Order) => Order | null) =>\n    setOrders((now) => now.flatMap((o) => (ids.includes(o.id) ? (change(o) ?? []) : [o])))\n\n  const theme = {\n    maxWidth: width,\n    \&#x22;--data-table-row-height\&#x22;: `${rowHeight}px`,\n    \&#x22;--data-table-radius\&#x22;: `${radius}px`,\n    ...(surface ? { \&#x22;--data-table-surface\&#x22;: surface } : null),\n    ...(border ? { \&#x22;--data-table-border\&#x22;: border } : null),\n    ...(accent ? { \&#x22;--data-table-accent\&#x22;: accent } : null),\n    ...(bar ? { \&#x22;--data-table-bar\&#x22;: bar } : null),\n  } as React.CSSProperties\n\n  return (\n    <div style={theme} className=\&#x22;flex w-full flex-col gap-4 self-start\&#x22;>\n      <div>\n        <div className=\&#x22;text-[15px] font-semibold tracking-tight\&#x22;>{title}</div>\n        <div className=\&#x22;mt-1 text-[12px] text-muted-foreground tabular-nums\&#x22;>{orders.length} orders in the last 8 weeks</div>\n      </div>\n      <DataTable<Order>\n        key={`${pageSize}-${hidden}`}\n        label={title}\n        data={orders}\n        columns={columns}\n        loading={loading}\n        selectable={selectable}\n        defaultSort={{ id: \&#x22;date\&#x22;, direction: \&#x22;descending\&#x22; }}\n        defaultPageSize={Number(pageSize)}\n        pageSizes={[5, 8, 10, 20, 50]}\n        defaultHiddenColumns={hidden === \&#x22;none\&#x22; ? [] : [hidden]}\n        selected={selected}\n        onSelectedChange={(next) => setSelected(next)}\n        searchPlaceholder={searchPlaceholder}\n        rowActions={\n          rowMenu\n            ? (o) => (\n                <>\n                  <MenuItem value=\&#x22;view\&#x22;>View order</MenuItem>\n                  <MenuItem value=\&#x22;ship\&#x22; disabled={o.fulfilment === \&#x22;Shipped\&#x22; || o.fulfilment === \&#x22;Delivered\&#x22;} onSelect={() => update([o.id], (x) => ({ ...x, fulfilment: \&#x22;Shipped\&#x22; }))}>\n                    Mark as shipped\n                  </MenuItem>\n                  <MenuItem value=\&#x22;refund\&#x22; disabled={o.payment !== \&#x22;Paid\&#x22;} onSelect={() => update([o.id], (x) => ({ ...x, payment: \&#x22;Refunded\&#x22; }))}>\n                    Refund\n                  </MenuItem>\n                  <MenuSeparator />\n                  <MenuItem value=\&#x22;cancel\&#x22; destructive onSelect={() => update([o.id], () => null)}>\n                    Cancel order\n                  </MenuItem>\n                </>\n              )\n            : undefined\n        }\n        bulkActions={(ids) => (\n          <>\n            <DataTableBulkAction\n              data-bulk=\&#x22;ship\&#x22;\n              icon={<Truck size={16} strokeWidth={1.75} aria-hidden />}\n              label=\&#x22;Mark as shipped\&#x22;\n              onClick={() => update(ids, (x) => (x.fulfilment === \&#x22;Delivered\&#x22; ? x : { ...x, fulfilment: \&#x22;Shipped\&#x22; }))}\n            />\n            <DataTableBulkAction data-bulk=\&#x22;export\&#x22; icon={<Download size={16} strokeWidth={1.75} aria-hidden />} label=\&#x22;Export\&#x22; />\n            <DataTableBulkAction\n              tone=\&#x22;destructive\&#x22;\n              data-bulk=\&#x22;cancel\&#x22;\n              icon={<XCircle size={16} strokeWidth={1.75} aria-hidden />}\n              label=\&#x22;Cancel\&#x22;\n              onClick={() => {\n                update(ids, () => null)\n                setSelected([])\n              }}\n            />\n          </>\n        )}\n      />\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;title&#x22;:[5073,5081],&#x22;searchPlaceholder&#x22;:[5105,5133],&#x22;pageSize&#x22;:[5148,5151],&#x22;selectable&#x22;:[5168,5172],&#x22;rowMenu&#x22;:[5186,5190],&#x22;loading&#x22;:[5204,5209],&#x22;hidden&#x22;:[5222,5228],&#x22;sticky&#x22;:[5241,5245],&#x22;width&#x22;:[5257,5260],&#x22;rowHeight&#x22;:[5276,5278],&#x22;radius&#x22;:[5291,5293],&#x22;surface&#x22;:[5307,5309],&#x22;border&#x22;:[5322,5324],&#x22;accent&#x22;:[5337,5339],&#x22;bar&#x22;:[5349,5351]},&#x22;root&#x22;:[6460,9034],&#x22;importOffset&#x22;:371}" />

## Installation [#installation]

**CLI**

```bash
npx shadcn@latest add @keyframery/data-table
```

This adds `components/keyframery/data-table.tsx` and its primitive to your project, and installs UI SDK, along with [badge](/docs/components/badge), [button](/docs/components/button), [checkbox](/docs/components/checkbox), [empty](/docs/components/empty), [filter](/docs/components/filter), [input-group](/docs/components/input-group), [menu](/docs/components/menu), [pagination](/docs/components/pagination), [select](/docs/components/select), [skeleton](/docs/components/skeleton), [table](/docs/components/table), [toolbar](/docs/components/toolbar), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.9 @ui-sdk/react@0.1.0-beta.9 lucide-react clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation#what-the-cli-adds-to-your-css) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"springy"` (the default), `"calm"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [badge](/docs/components/badge), [button](/docs/components/button), [checkbox](/docs/components/checkbox), [empty](/docs/components/empty), [filter](/docs/components/filter), [input-group](/docs/components/input-group), [menu](/docs/components/menu), [pagination](/docs/components/pagination), [select](/docs/components/select), [skeleton](/docs/components/skeleton), [table](/docs/components/table), [toolbar](/docs/components/toolbar) the same way first.

**Copy the component**

**components/keyframery/data-table.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/data-table"

/* Styled data table: the animated primitive composed with Keyframery's own components. A toolbar
   (search field, filter chips with counts, Reset, View), a table in a card whose headers sort and
   hide from a small menu, rows with checkboxes and a row menu, an empty state and loading rows at
   the table's own geometry, a footer with "Rows per page", "Page X of Y" and the pages, and a bulk
   bar that rises while rows are selected.

   `DataTable` with no children renders all of it. Pass children to compose the parts yourself
   (`DataTableToolbar`, `DataTableContent`, `DataTableFooter`, `DataTableBulkBar`, …).

   Theming: set these CSS variables on the table or anything around it. Each falls back to the
   theme's own token, so nothing changes until you set one.
     --data-table-surface     the table's card and its sticky cells   (default: --card)
     --data-table-border      the card's hairline                     (default: black 7%, white 8% in dark)
     --data-table-accent      the hover and selected row tint         (default: --foreground)
     --data-table-radius      the card's corners                      (default: 14px)
     --data-table-row-height  each row's height                       (default: 2.75rem)
     --data-table-bar         the bulk bar's surface                  (default: --popover) */

import { ArrowDown, ArrowUp, ChevronsUpDown, Ellipsis, EyeOff, Search, SearchX, Settings2, X } from "lucide-react"
import * as React from "react"

import { type DataTableColumn, type DataTableOptions, textOf, valueOf } from "@/components/keyframery/core/data-table-core"
import {
  DataTableBulkBar as DataTableBulkBarPrimitive,
  dataTableBodyMotion,
  dataTableCellMotion,
  DataTableContent as DataTableContentPrimitive,
  DataTableEmpty as DataTableEmptyPrimitive,
  DataTableFilters as DataTableFiltersPrimitive,
  DataTableFooter as DataTableFooterPrimitive,
  DataTableHead as DataTableHeadPrimitive,
  DataTableReset as DataTableResetPrimitive,
  DataTableRoot,
  DataTableRow as DataTableRowPrimitive,
  DataTableSearch as DataTableSearchPrimitive,
  DataTableToolbar as DataTableToolbarPrimitive,
  DataTableView as DataTableViewPrimitive,
  useColumnPresence,
  useDataTable,
} from "@/components/keyframery/primitives/data-table"
import { Roll } from "@/components/keyframery/badge"
import { Button } from "@/components/keyframery/button"
import { Checkbox } from "@/components/keyframery/checkbox"
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/keyframery/empty"
import { Filter } from "@/components/keyframery/filter"
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/keyframery/input-group"
import {
  Menu,
  MenuCheckboxItem,
  MenuContent,
  MenuGroup,
  MenuGroupLabel,
  MenuItem,
  MenuItemIcon,
  MenuItemIndicator,
  MenuSeparator,
  MenuTrigger,
} from "@/components/keyframery/menu"
import { Pagination, PaginationFirst, PaginationItem, PaginationLast, PaginationLink, PaginationEllipsis, PaginationList, PaginationNext, PaginationPrevious, PaginationRoll } from "@/components/keyframery/pagination"
import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger, SelectValue } from "@/components/keyframery/select"
import { Skeleton } from "@/components/keyframery/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/keyframery/table"
import { Toolbar, ToolbarButton, ToolbarSeparator } from "@/components/keyframery/toolbar"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* One size and one stroke for every icon in the data table. */
const icon = { size: 16, strokeWidth: 1.75, "aria-hidden": true } as const

/* ---------------------------------------------------------------- types */

/** A column, with a React cell renderer: `cell: (row, value) => <Badge>{value}</Badge>`. */
type DataTableColumnDef<Row = never> = DataTableColumn<Row, (row: Row, value: unknown) => React.ReactNode, React.ReactNode> & {
  /** Classes for this column's header and cells. */
  className?: string
}

type DataTableProps<Row> = Omit<DataTableOptions, "data" | "columns" | "getRowId"> &
  SpeedProps &
  Omit<React.ComponentProps<typeof DataTableRoot>, keyof DataTableOptions | "children"> & {
    data: readonly Row[]
    columns: DataTableColumnDef<Row>[]
    getRowId?: (row: Row, index: number) => string
    /** The search field's placeholder. Defaults to "Search…". */
    searchPlaceholder?: string
    /** The row menu's items (`MenuItem`s). Leave it out for no row menu. */
    rowActions?: (row: Row) => React.ReactNode
    /** The bulk bar's actions (`DataTableBulkAction`s), for the selected row ids. */
    bulkActions?: (selected: string[]) => React.ReactNode
    /** More controls at the end of the toolbar, before View. */
    toolbar?: React.ReactNode
    /** What the empty state says. */
    emptyTitle?: string
    emptyDescription?: string
    /** Your own composition of the parts. Leave it out for the whole screen. */
    children?: React.ReactNode
  }

/* ---------------------------------------------------------------- layout helpers */

const hideBelow = {
  sm: "@max-[30rem]/data-table:hidden",
  md: "@max-[40rem]/data-table:hidden",
  lg: "@max-[52rem]/data-table:hidden",
} as const

const alignment = { start: "text-start", center: "text-center", end: "text-end" } as const

/* A sticky cell takes the card's surface, tinted like its row, so the rows slide under it. */
const stickyCell = cn(
  "@max-[40rem]/data-table:sticky @max-[40rem]/data-table:z-[1] @max-[40rem]/data-table:bg-[var(--data-table-surface,var(--card))]",
  /* Once the rows scroll under it, the last sticky cell gets a hairline edge. */
  "@max-[40rem]/data-table:[[data-scroll-start]_&[data-sticky-edge]]:shadow-[inset_-1px_0_0_var(--border)]",
  /* The row's own translucent tint, layered over the surface, so a sticky cell matches its row exactly. */
  "@max-[40rem]/data-table:[tr:hover>&]:bg-[linear-gradient(color-mix(in_oklab,var(--data-table-accent,var(--foreground))_3%,transparent),color-mix(in_oklab,var(--data-table-accent,var(--foreground))_3%,transparent))]",
  "@max-[40rem]/data-table:[tr[data-selected]>&]:bg-[linear-gradient(color-mix(in_oklab,var(--data-table-accent,var(--foreground))_6%,transparent),color-mix(in_oklab,var(--data-table-accent,var(--foreground))_6%,transparent))]",
)

function columnClass(column: DataTableColumnDef<never>, selectable: boolean) {
  return cn(
    alignment[column.align ?? "start"],
    column.hideBelow && hideBelow[column.hideBelow],
    column.sticky && [stickyCell, selectable ? "@max-[40rem]/data-table:left-10" : "@max-[40rem]/data-table:left-0"],
    column.className,
  )
}

/* ---------------------------------------------------------------- root */

/** The whole list screen from `data` and `columns`, or the parts you compose inside. */
function DataTable<Row>({
  speed,
  className,
  style,
  children,
  data,
  columns,
  getRowId,
  searchPlaceholder,
  rowActions,
  bulkActions,
  toolbar,
  emptyTitle,
  emptyDescription,
  ...props
}: DataTableProps<Row>) {
  return (
    <Speed speed={speed}>
      <DataTableRoot
        data={data as unknown[]}
        columns={columns as DataTableColumn[]}
        getRowId={getRowId as DataTableOptions["getRowId"]}
        className={cn("gap-3 text-[13px] text-foreground", typeof className === "string" ? className : undefined)}
        style={style}
        {...props}
      >
        {children ?? (
          <>
            <DataTableToolbar searchPlaceholder={searchPlaceholder}>{toolbar}</DataTableToolbar>
            <DataTableContent rowActions={rowActions as ((row: unknown) => React.ReactNode) | undefined} emptyTitle={emptyTitle} emptyDescription={emptyDescription} />
            <DataTableBulkBar>{bulkActions ? (selected) => bulkActions(selected) : null}</DataTableBulkBar>
            <DataTableFooter />
          </>
        )}
      </DataTableRoot>
    </Speed>
  )
}

/* ---------------------------------------------------------------- toolbar */

/** Search, the filter chips, Reset, then anything you pass and View. It wraps on a narrow container. */
function DataTableToolbar({ searchPlaceholder, className, children }: { searchPlaceholder?: string; className?: string; children?: React.ReactNode }) {
  return (
    <DataTableToolbarPrimitive className={cn("flex flex-wrap items-center gap-2 [--filter-height:var(--data-table-control,2rem)]", className)}>
      <DataTableSearch placeholder={searchPlaceholder} />
      <DataTableFilters />
      <DataTableReset />
      <div className="ms-auto flex items-center gap-2">
        {children}
        <DataTableView />
      </div>
    </DataTableToolbarPrimitive>
  )
}

/** The search field, with a clear button while it holds text. */
function DataTableSearch({ placeholder = "Search…", className }: { placeholder?: string; className?: string }) {
  const api = useDataTable()
  return (
    <DataTableSearchPrimitive className={cn("w-[15rem] @max-[40rem]/data-table:w-full", className)}>
      {(state) => (
        <InputGroup className="h-[var(--data-table-control,2rem)] min-h-0 [--input-group-height:var(--data-table-control,2rem)]">
          <InputGroupAddon>
            <Search {...icon} />
          </InputGroupAddon>
          <InputGroupInput
            data-data-table-search=""
            aria-label={state.label}
            placeholder={placeholder}
            value={state.value}
            disabled={state.disabled}
            onValueChange={(value: string, details: { event?: Event }) => api.setSearch(value, details.event ?? new Event("input"))}
          />
          {state.value ? (
            <InputGroupAddon align="inline-end">
              <InputGroupButton size="icon-xs" aria-label="Clear search" onClick={(event) => api.clearSearch(event.nativeEvent)}>
                <X {...icon} />
              </InputGroupButton>
            </InputGroupAddon>
          ) : null}
        </InputGroup>
      )}
    </DataTableSearchPrimitive>
  )
}

/** A filter chip per filterable column, with the number of rows each value would leave. */
function DataTableFilters({ className }: { className?: string }) {
  const api = useDataTable()
  return (
    <DataTableFiltersPrimitive className={cn("contents", className)}>
      {(state) =>
        state.items.map((item) => (
          <Filter
            key={item.id}
            data-filter={item.id}
            label={item.title}
            options={item.options.map((o) => ({ value: o.value, label: o.label, count: o.count, icon: o.icon as React.ReactNode }))}
            value={item.selected}
            onValueChange={(value: string[]) => api.setFilter(item.id, value, new Event("change"))}
          />
        ))
      }
    </DataTableFiltersPrimitive>
  )
}

/** Clears the search and every filter. It slides in only while something is filtered. */
function DataTableReset({ className, children = "Reset" }: { className?: string; children?: React.ReactNode }) {
  const api = useDataTable()
  return (
    <DataTableResetPrimitive className={className}>
      <Button variant="ghost" size="sm" data-data-table-reset="" className="h-[var(--data-table-control,2rem)] bg-none shadow-none dark:bg-none dark:shadow-none" onClick={(event) => api.resetFilters(event.nativeEvent)}>
        {children}
        <X {...icon} />
      </Button>
    </DataTableResetPrimitive>
  )
}

/** "View": a menu of the columns, each with a check while it shows. */
function DataTableView({ className, label = "View" }: { className?: string; label?: string }) {
  const api = useDataTable()
  return (
    <DataTableViewPrimitive className={className}>
      {(state) => (
        <Menu>
          <MenuTrigger data-data-table-view="" className="h-[var(--data-table-control,2rem)] @max-[30rem]/data-table:px-2">
            <Settings2 {...icon} />
            <span className="@max-[30rem]/data-table:sr-only">{label}</span>
          </MenuTrigger>
          <MenuContent align="end" className="w-48">
            <MenuGroup>
              <MenuGroupLabel>Toggle columns</MenuGroupLabel>
              {state.columns.map((column) => (
                <MenuCheckboxItem
                  key={column.id}
                  value={column.id}
                  checked={column.visible}
                  onCheckedChange={(checked: boolean) => (checked ? api.showColumn(column.id, new Event("change")) : api.hideColumn(column.id, new Event("change")))}
                >
                  {column.label}
                  <MenuItemIndicator />
                </MenuCheckboxItem>
              ))}
            </MenuGroup>
          </MenuContent>
        </Menu>
      )}
    </DataTableViewPrimitive>
  )
}

/* ---------------------------------------------------------------- the table */

/** A header that sorts and hides from a small menu: Asc, Desc, Hide. A column that doesn't sort shows its label. */
function DataTableColumnHeader({ id, label, sort, sortable, hideable, align }: { id: string; label: string; sort: "ascending" | "descending" | "none"; sortable: boolean; hideable: boolean; align?: "start" | "center" | "end" }) {
  const api = useDataTable()
  if (!sortable && !hideable) return <span className="px-0.5">{label}</span>
  const SortIcon = sort === "ascending" ? ArrowUp : sort === "descending" ? ArrowDown : ChevronsUpDown
  /* For a column whose values end on the right, the icon goes first so the label ends where the numbers end. */
  const sortIcon = (
    <SortIcon
      {...icon}
      className={cn(
        "size-3.5 transition-[opacity,rotate] duration-[calc(420ms*var(--kf-speed,1))] ease-spring motion-reduce:transition-none",
        sort === "none" && "opacity-45",
      )}
    />
  )
  return (
    <Menu
      onAction={(value: string) => {
        const event = new Event("select")
        if (value === "asc") api.setSort(id, "ascending", event)
        else if (value === "desc") api.setSort(id, "descending", event)
        else if (value === "hide") api.hideColumn(id, event)
      }}
    >
      <MenuTrigger
        data-data-table-sort={id}
        aria-label={`${label}, ${sort === "none" ? "not sorted" : `sorted ${sort}`}. Sort or hide`}
        render={<Button variant="ghost" size="sm" />}
        className={cn(
          "-mx-1.5 h-7 gap-1 bg-none px-1.5 text-[12px] font-medium text-[color:inherit] shadow-none dark:bg-none dark:shadow-none data-open:bg-accent",
        )}
      >
        {align === "end" ? (
          <>
            {sortIcon}
            {label}
          </>
        ) : (
          <>
            {label}
            {sortIcon}
          </>
        )}
      </MenuTrigger>
      <MenuContent align={align === "end" ? "end" : "start"} className="w-36">
        {sortable ? (
          <>
            <MenuItem value="asc" data-value="asc">
              <MenuItemIcon>
                <ArrowUp {...icon} />
              </MenuItemIcon>
              Asc
            </MenuItem>
            <MenuItem value="desc" data-value="desc">
              <MenuItemIcon>
                <ArrowDown {...icon} />
              </MenuItemIcon>
              Desc
            </MenuItem>
          </>
        ) : null}
        {sortable && hideable ? <MenuSeparator /> : null}
        {hideable ? (
          <MenuItem value="hide" data-value="hide">
            <MenuItemIcon>
              <EyeOff {...icon} />
            </MenuItemIcon>
            Hide
          </MenuItem>
        ) : null}
      </MenuContent>
    </Menu>
  )
}

/* Loading bars vary their width row to row, so they read as text, not a grid. */
const barWidths = ["72%", "54%", "64%", "46%", "68%", "58%"]

/** The table in its card: headers, rows (or the loading rows, or the empty state). */
function DataTableContent({
  rowActions,
  emptyTitle = "No results",
  emptyDescription,
  className,
}: {
  rowActions?: (row: never) => React.ReactNode
  emptyTitle?: string
  emptyDescription?: string
  className?: string
}) {
  return (
    <DataTableContentPrimitive
      className={cn(
        "overflow-hidden rounded-[var(--data-table-radius,14px)] bg-[var(--data-table-surface,var(--card))]",
        "shadow-[0_0_0_1px_var(--data-table-border,rgb(0_0_0/0.07)),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_var(--data-table-border,rgb(255_255_255/0.08))]",
        "[--table-height:var(--data-table-row-height,2.75rem)] [--table-accent:var(--data-table-accent,var(--foreground))]",
        /* On a narrow container the first columns stay put, so the scroll edge needs no fade. */
        "@max-[40rem]/data-table:[&_[data-slot=table-container]]:[mask-image:none]",
        className,
      )}
    >
      {(state) => <ContentTable state={state} rowActions={rowActions as ((row: unknown) => React.ReactNode) | undefined} emptyTitle={emptyTitle} emptyDescription={emptyDescription} />}
    </DataTableContentPrimitive>
  )
}

type ContentState = Parameters<Extract<React.ComponentProps<typeof DataTableContentPrimitive>["children"], (state: never) => unknown>>[0]

function ContentTable({
  state,
  rowActions,
  emptyTitle,
  emptyDescription,
}: {
  state: ContentState
  rowActions?: (row: unknown) => React.ReactNode
  emptyTitle: string
  emptyDescription?: string
}) {
  const api = useDataTable()
  const all = state.allColumns as DataTableColumnDef<never>[]
  const { columns, ref } = useColumnPresence(all, state.columns as DataTableColumnDef<never>[])
  const span = columns.length + (state.selectable ? 1 : 0) + (rowActions ? 1 : 0)
  const edge = "first:ps-4 last:pe-4"

  return (
    <Table aria-label={state.label || undefined} ref={ref as React.Ref<HTMLTableElement>}>
      <TableHeader>
        <TableRow>
          {state.selectable ? (
            <TableHead className={cn("w-10 ps-4", stickyCell, "@max-[40rem]/data-table:left-0")}>
              <Checkbox
                aria-label="Select every row on this page"
                data-data-table-select-all=""
                disabled={state.loading || !state.entries.length}
                checked={state.pageSelection === "all" ? true : state.pageSelection === "some" ? "indeterminate" : false}
                onCheckedChange={(_checked: unknown, details: { event?: Event }) => api.togglePage(details.event)}
              />
            </TableHead>
          ) : null}
          {columns.map(({ column, leaving }) => {
            const sortable = column.sortable ?? true
            const hideable = column.hideable ?? true
            const sort = state.sort?.id === column.id ? state.sort.direction : "none"
            return (
              <DataTableHeadPrimitive
                key={column.id}
                value={column.id}
                data-leaving={leaving ? "" : undefined}
                data-sticky-edge={column.sticky ? "" : undefined}
                aria-hidden={leaving ? "true" : undefined}
                render={<TableHead />}
                className={cn(dataTableCellMotion, edge, columnClass(column, state.selectable))}
              >
                <div data-data-table-cell="" className={cn("flex items-center", column.align === "end" && "justify-end", column.align === "center" && "justify-center")}>
                  <DataTableColumnHeader id={column.id} label={column.header} sort={sort} sortable={sortable} hideable={hideable} align={column.align} />
                </div>
              </DataTableHeadPrimitive>
            )
          })}
          {rowActions ? (
            <TableHead className="w-12 pe-3">
              <span className="sr-only">Actions</span>
            </TableHead>
          ) : null}
        </TableRow>
      </TableHeader>
      <TableBody className={dataTableBodyMotion}>
        {state.loading ? (
          Array.from({ length: Math.min(state.pageSize, 12) }, (_, r) => (
            <TableRow key={`loading-${r}`} className="hover:bg-transparent" aria-hidden="true">
              {state.selectable ? (
                <TableCell className="ps-4">
                  <Skeleton className="size-4 rounded-[5px]" />
                </TableCell>
              ) : null}
              {columns.map(({ column }, c) => (
                <TableCell key={column.id} className={cn(edge, columnClass(column, state.selectable))}>
                  <Skeleton className={cn("h-3", column.align === "end" && "ms-auto")} style={{ width: barWidths[(r + c * 2) % barWidths.length] }} />
                </TableCell>
              ))}
              {rowActions ? <TableCell /> : null}
            </TableRow>
          ))
        ) : state.empty ? (
          <TableRow className="hover:bg-transparent">
            <TableCell colSpan={span} className="h-auto p-0 whitespace-normal">
              <DataTableEmpty title={emptyTitle} description={emptyDescription} />
            </TableCell>
          </TableRow>
        ) : (
          state.entries.map((entry) => {
            const label = api.rowLabel(entry.id)
            return (
              <DataTableRowPrimitive key={`${state.epoch}:${entry.id}`} value={entry.id} render={<TableRow />}>
                {state.selectable ? (
                  <TableCell className={cn("w-10 ps-4", stickyCell, "@max-[40rem]/data-table:left-0")}>
                    <Checkbox
                      aria-label={`Select ${label}`}
                      data-data-table-select={entry.id}
                      checked={state.selected.includes(entry.id)}
                      onCheckedChange={(_checked: unknown, details: { event?: Event }) => api.toggleRow(entry.id, details.event)}
                    />
                  </TableCell>
                ) : null}
                {columns.map(({ column, leaving }) => {
                  const value = valueOf(column as DataTableColumn, entry.row)
                  return (
                    <TableCell
                      key={column.id}
                      data-leaving={leaving ? "" : undefined}
                      data-sticky-edge={column.sticky ? "" : undefined}
                      aria-hidden={leaving ? "true" : undefined}
                      className={cn(dataTableCellMotion, edge, columnClass(column, state.selectable))}
                    >
                      <div data-data-table-cell="">{column.cell ? (column.cell as (row: unknown, value: unknown) => React.ReactNode)(entry.row, value) : textOf(value)}</div>
                    </TableCell>
                  )
                })}
                {rowActions ? (
                  <TableCell className="w-12 pe-3 text-end">
                    <Menu>
                      <MenuTrigger
                        data-data-table-row-menu={entry.id}
                        aria-label={`Actions for ${label}`}
                        render={<Button variant="ghost" size="icon-sm" />}
                        className="ms-auto bg-none text-muted-foreground shadow-none dark:bg-none hover:text-foreground data-open:bg-accent data-open:text-foreground dark:shadow-none"
                      >
                        <Ellipsis {...icon} />
                      </MenuTrigger>
                      <MenuContent align="end" className="w-44">
                        {rowActions(entry.row)}
                      </MenuContent>
                    </Menu>
                  </TableCell>
                ) : null}
              </DataTableRowPrimitive>
            )
          })
        )}
      </TableBody>
    </Table>
  )
}

/** "No results", with a button that clears the search and the filters. */
function DataTableEmpty({ title = "No results", description, className }: { title?: string; description?: string; className?: string }) {
  const api = useDataTable()
  return (
    <DataTableEmptyPrimitive className={className}>
      {(state) => (
        <Empty className="py-12">
          <EmptyHeader>
            <EmptyMedia variant="icon">
              <SearchX {...icon} className="size-5" />
            </EmptyMedia>
            <EmptyTitle>{title}</EmptyTitle>
            <EmptyDescription>
              {description ?? (state.search.trim() ? `Nothing matches “${state.search.trim()}”.` : "No rows match these filters.")}
            </EmptyDescription>
          </EmptyHeader>
          {state.filtered ? (
            <EmptyContent>
              <Button size="sm" data-data-table-clear="" onClick={(event) => api.resetFilters(event.nativeEvent)}>
                Clear filters
              </Button>
            </EmptyContent>
          ) : null}
        </Empty>
      )}
    </DataTableEmptyPrimitive>
  )
}

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

/** The selection count, "Rows per page", "Page X of Y" and the pages. First and last leave on a narrow container. */
function DataTableFooter({ className, label = "rows" }: { className?: string; label?: string }) {
  const api = useDataTable()
  return (
    <DataTableFooterPrimitive className={cn("flex flex-wrap items-center gap-x-6 gap-y-3 px-1 text-[13px] text-muted-foreground tabular-nums", className)}>
      {(state) => (
        <>
          <div className="me-auto @max-[40rem]/data-table:hidden">
            {state.selectable && state.selectedCount ? (
              <>
                <PaginationRoll value={state.selectedCount} /> of {state.total} selected
              </>
            ) : (
              <>
                <PaginationRoll value={state.total} /> {label}
              </>
            )}
          </div>
          <div className="flex items-center gap-2 @max-[30rem]/data-table:hidden">
            <span className="font-medium text-foreground">Rows per page</span>
            <Select value={String(state.pageSize)} onValueChange={(value: string | null) => value && api.setPageSize(Number(value), new Event("change"))}>
              <SelectTrigger aria-label="Rows per page" data-data-table-page-size="" className="h-8 w-[4.5rem] [--select-height:2rem]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {state.pageSizes.map((size) => (
                  <SelectItem key={size} value={String(size)}>
                    <SelectItemText>{size}</SelectItemText>
                    <SelectItemIndicator />
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="font-medium text-foreground @max-[40rem]/data-table:me-auto">
            Page <PaginationRoll value={state.page} /> of {state.pageCount}
          </div>
          <Pagination
            aria-label="Pages"
            total={state.total}
            pageSize={state.pageSize}
            page={state.page}
            onPageChange={(page: number) => api.setPage(page, new Event("change"))}
          >
            <PaginationList className="@max-[30rem]/data-table:before:opacity-0!">
              {({ items }) => (
                <>
                  <PaginationItem className="@max-[40rem]/data-table:hidden">
                    <PaginationFirst />
                  </PaginationItem>
                  <PaginationItem>
                    <PaginationPrevious data-data-table-previous="" />
                  </PaginationItem>
                  {items.map((item) => (
                    <PaginationItem key={item} className="@max-[30rem]/data-table:hidden">
                      {typeof item === "number" ? <PaginationLink page={item} /> : <PaginationEllipsis />}
                    </PaginationItem>
                  ))}
                  <PaginationItem>
                    <PaginationNext data-data-table-next="" />
                  </PaginationItem>
                  <PaginationItem className="@max-[40rem]/data-table:hidden">
                    <PaginationLast />
                  </PaginationItem>
                </>
              )}
            </PaginationList>
          </Pagination>
        </>
      )}
    </DataTableFooterPrimitive>
  )
}

/* ---------------------------------------------------------------- bulk bar */

/** Rises from the bottom centre while rows are selected: clear (or Escape), "N selected", then your actions.
    Place it right after `DataTableContent`: it opens a room of its own there while rows are selected. */
function DataTableBulkBar({ className, children }: { className?: string; children?: React.ReactNode | ((selected: string[]) => React.ReactNode) }) {
  const api = useDataTable()
  /* While it sinks away the count keeps its last number instead of rolling to 0. */
  const last = React.useRef({ count: 0, selected: [] as string[] })
  return (
    <DataTableBulkBarPrimitive className={className}>
      {(state) => {
        if (state.count) last.current = { count: state.count, selected: state.selected }
        const { count, selected } = last.current
        return (
          <Toolbar
            aria-label="Selected rows"
            data-data-table-bulk=""
            className="gap-1 rounded-[14px] bg-[var(--data-table-bar,var(--popover))] p-1.5 whitespace-nowrap"
          >
            <ToolbarButton aria-label="Clear selection (Escape)" data-data-table-bulk-clear="" onClick={(event) => api.clearSelection(event.nativeEvent)}>
              <X {...icon} />
            </ToolbarButton>
            <span className="px-1.5 text-[13px] font-medium text-foreground tabular-nums" aria-live="off">
              <Roll text={String(count)} /> selected
            </span>
            {children ? <ToolbarSeparator /> : null}
            {typeof children === "function" ? children(selected) : children}
          </Toolbar>
        )
      }}
    </DataTableBulkBarPrimitive>
  )
}

/** One action in the bulk bar: an `icon` and a `label` (the label folds away on a narrow
    container and stays for screen readers). `tone="destructive"` for one that removes. */
function DataTableBulkAction({
  tone,
  icon: actionIcon,
  label,
  className,
  children,
  ...props
}: React.ComponentProps<typeof ToolbarButton> & { tone?: "destructive"; icon?: React.ReactNode; label?: string }) {
  return (
    <ToolbarButton
      title={label}
      className={cn(
        /* Ordinary actions in full ink, their icon a step quieter; only a destructive one is red. */
        "px-2 text-foreground not-data-disabled:hover:text-foreground [&_svg]:size-4 [&_svg]:text-muted-foreground",
        tone === "destructive" && "text-destructive not-data-disabled:hover:text-destructive data-kf-toolbar-hl:text-destructive [&_svg]:text-destructive",
        typeof className === "string" ? className : undefined,
      )}
      {...props}
    >
      {children ?? (
        <>
          {actionIcon}
          <span className="@max-[34rem]/data-table:sr-only">{label}</span>
        </>
      )}
    </ToolbarButton>
  )
}

export {
  DataTable,
  DataTableBulkAction,
  DataTableBulkBar,
  DataTableColumnHeader,
  type DataTableColumnDef,
  DataTableContent,
  DataTableEmpty,
  DataTableFilters,
  DataTableFooter,
  type DataTableProps,
  DataTableReset,
  DataTableSearch,
  DataTableToolbar,
  DataTableView,
}
```

**components/keyframery/primitives/data-table.tsx**

```tsx
"use client"

/* Animated data table, on UI SDK's core. UI SDK ships no data table, so its state (sort, search,
   filters, hidden columns, selection, page and page size) and its row model are defined in
   `@/components/core/data-table` with `definePrimitive`, and rendered here as parts. Each part hands
   its children the state they show, so you compose the controls inside with any UI SDK components
   (the styled `@/components/ui/data-table` does it with Keyframery's). This file adds motion only.
   Colours, radii, shadows and spacing stay yours.

   - Cascade: after a sort or a page turn every row of the page arrives again, one after another,
     from the side the page was reached from (below for Next, above for Previous). After a search
     or a filter, only the rows that are new to the page arrive. Selecting does not replay anything.
   - Collapse: a hidden column folds to nothing while the others close the gap; a column shown
     again opens out of nothing.
   - Rise: the bulk bar rises from the bottom centre while rows are selected, and sinks away.
   - Slide: Reset slides in beside the filters while anything is filtered, and out again.

   Parts: DataTableRoot, DataTableToolbar, DataTableSearch, DataTableFilters, DataTableReset,
   DataTableView, DataTableContent, DataTableHead, DataTableRow, DataTableEmpty, DataTableFooter,
   DataTableBulkBar; helpers: useDataTable (the api), useColumnPresence, dataTableBodyMotion,
   dataTableCellMotion. */

import type { SlotName, StateOf } from "@ui-sdk/core"
import { type PartProps, type PrimitiveHandle, usePart, usePrimitive } from "@ui-sdk/react/primitive"
import * as React from "react"

import { type DataTableColumn, type DataTableOptions, dataTable } from "@/components/keyframery/core/data-table-core"
import { cn } from "@/lib/utils"

type Part<Slot extends SlotName<typeof dataTable>, Tag extends keyof React.JSX.IntrinsicElements = "div"> = PartProps<Tag, StateOf<typeof dataTable, Slot>>

/* UI SDK parts take a class name or a function of the part's state. Keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* ---------------------------------------------------------------- motion */

/* Rows rise (or drop) in with a little blur. The delay per row comes from the table's own
   stylesheet (`--kf-row`, set by nth-child on the table body), so the two tables cascade alike. */
const keyframes =
  "@keyframes kf-data-table-row{from{opacity:0;translate:0 var(--kf-dt-from,8px);filter:blur(3px)}}" +
  "@keyframes kf-data-table-rise{from{opacity:0;translate:0 14px;scale:.94;filter:blur(6px)}}"

/** For the table body: the cascade, with the direction from the content part's `data-direction`. */
const dataTableBodyMotion = cn(
  "[&>tr]:animate-[kf-data-table-row_calc(420ms*var(--kf-speed,1))_var(--ease-spring)_backwards]",
  "[&>tr]:[animation-delay:calc(var(--kf-row,0)*30ms*var(--kf-speed,1))]",
  "[[data-direction=backward]_&]:[--kf-dt-from:-8px]",
  "motion-reduce:[&>tr]:animate-none",
)

/** For every header and cell: a column that leaves folds to nothing; one that arrives opens out.
    Put the cell's content in an element with `data-data-table-cell` (the styled table does). */
const dataTableCellMotion = cn(
  "transition-[padding] duration-[calc(320ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none",
  "data-leaving:px-0! data-leaving:duration-[calc(240ms*var(--kf-speed,1))]",
  "[&>[data-data-table-cell]]:[interpolate-size:allow-keywords] [&>[data-data-table-cell]]:w-auto [&>[data-data-table-cell]]:overflow-hidden",
  "[&>[data-data-table-cell]]:transition-[width,opacity,filter] [&>[data-data-table-cell]]:duration-[calc(360ms*var(--kf-speed,1))] [&>[data-data-table-cell]]:ease-house",
  "[&>[data-data-table-cell]]:starting:w-0 [&>[data-data-table-cell]]:starting:opacity-0 [&>[data-data-table-cell]]:starting:blur-[4px]",
  "data-leaving:[&>[data-data-table-cell]]:w-0 data-leaving:[&>[data-data-table-cell]]:opacity-0 data-leaving:[&>[data-data-table-cell]]:blur-[4px] data-leaving:[&>[data-data-table-cell]]:duration-[calc(240ms*var(--kf-speed,1))]",
  "motion-reduce:[&>[data-data-table-cell]]:transition-none",
)

/* Each column that was just hidden stays for this long, folding, before it leaves the page. */
const LEAVE_MS = 260

/** The columns to draw: the visible ones, plus any that were just hidden and are still folding
    away (with `leaving`). Columns keep their definition order. */
function useColumnPresence<C extends { id: string }>(all: readonly C[], visible: readonly C[]) {
  const ids = visible.map((c) => c.id).join("\u0000")
  const [seen, setSeen] = React.useState(ids)
  const [leaving, setLeaving] = React.useState<string[]>([])
  const ref = React.useRef<HTMLElement | null>(null)
  /* Worked out during render, so a hidden column never leaves the page for a frame before it folds. */
  if (seen !== ids) {
    const now = ids ? ids.split("\u0000") : []
    const gone = (seen ? seen.split("\u0000") : []).filter((id) => !now.includes(id))
    setSeen(ids)
    setLeaving((current) => [...new Set([...current.filter((id) => !now.includes(id)), ...gone])])
  }
  React.useEffect(() => {
    if (!leaving.length) return
    const el = ref.current
    const speed = (el && parseFloat(getComputedStyle(el).getPropertyValue("--kf-speed"))) || 1
    const reduce = typeof matchMedia !== "undefined" && matchMedia("(prefers-reduced-motion: reduce)").matches
    const done = leaving
    const timer = setTimeout(() => setLeaving((current) => current.filter((id) => !done.includes(id))), reduce ? 0 : LEAVE_MS * speed)
    return () => clearTimeout(timer)
  }, [leaving])
  const shown = all.filter((c) => visible.some((v) => v.id === c.id) || leaving.includes(c.id))
  return { columns: shown.map((column) => ({ column, leaving: leaving.includes(column.id) })), ref }
}

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

/* The instance, for controls composed inside that call its api. */
const DataTableHandle = React.createContext<PrimitiveHandle<typeof dataTable> | null>(null)

type DataTableRootProps = DataTableOptions & Omit<Part<"root">, keyof DataTableOptions>

/** The list screen. Pass `data`, `columns` and a `label`; compose the parts inside. */
function DataTableRoot({
  data,
  columns,
  getRowId,
  label,
  loading,
  selectable,
  pageSizes,
  sort,
  defaultSort,
  onSortChange,
  search,
  defaultSearch,
  onSearchChange,
  filters,
  defaultFilters,
  onFiltersChange,
  hiddenColumns,
  defaultHiddenColumns,
  onHiddenColumnsChange,
  selected,
  defaultSelected,
  onSelectedChange,
  page,
  defaultPage,
  onPageChange,
  pageSize,
  defaultPageSize,
  onPageSizeChange,
  className,
  children,
  ...props
}: DataTableRootProps) {
  const handle = usePrimitive(dataTable, {
    data,
    columns,
    getRowId,
    label,
    loading,
    selectable,
    pageSizes,
    sort,
    defaultSort,
    onSortChange,
    search,
    defaultSearch,
    onSearchChange,
    filters,
    defaultFilters,
    onFiltersChange,
    hiddenColumns,
    defaultHiddenColumns,
    onHiddenColumnsChange,
    selected,
    defaultSelected,
    onSelectedChange,
    page,
    defaultPage,
    onPageChange,
    pageSize,
    defaultPageSize,
    onPageSizeChange,
  })
  const root = usePart(
    handle,
    "root",
    {},
    { ...props, className: withClass("@container/data-table relative flex min-w-0 flex-col", className), children },
    "div",
  )
  return (
    <>
      <style href="kf-data-table" precedence="default">
        {keyframes}
      </style>
      <DataTableHandle value={handle}>{root}</DataTableHandle>
    </>
  )
}

/** The api, for a control you compose inside: `useDataTable().setSearch("…")`. */
function useDataTable() {
  const handle = React.use(DataTableHandle)
  if (!handle) throw new Error("useDataTable must be used inside a DataTable")
  return handle.api
}

function slotPart<S extends Exclude<SlotName<typeof dataTable>, "root" | "head" | "row">>(slot: S, base = "") {
  return function DataTablePart({ className, ...props }: Part<S>) {
    return usePart(dataTable, slot, {} as never, { ...props, className: withClass(base, className) } as never, "div")
  }
}

/** The row above the table. */
const DataTableToolbar = slotPart("toolbar")
/** Holds the search field: its children get `{ value, label, disabled }`. */
const DataTableSearch = slotPart("search")
/** Holds the filter chips: its children get `{ items }`, each with its options and their counts. */
const DataTableFilters = slotPart("filters")
/** Holds the content of the table: its children get the page's rows, the visible columns, the sort and the selection. */
const DataTableContent = slotPart("content")
/** Holds "View": its children get `{ columns }` with whether each shows. */
const DataTableView = slotPart("view")
/** Shown in place of the rows when nothing matches: its children get `{ filtered, search }`. */
const DataTableEmpty = slotPart("empty")
/** Under the table: its children get the page, the page count, the sizes and the selection count. */
const DataTableFooter = slotPart("footer")

/** Holds Reset. It slides in from the start while anything is filtered and takes no room otherwise. */
function DataTableReset({ className, children, ...props }: Part<"reset">) {
  return usePart(
    dataTable,
    "reset",
    {},
    {
      ...props,
      className: withClass(
        cn(
          "grid grid-cols-[0fr] opacity-0 -translate-x-2 blur-[3px] data-shown:grid-cols-[1fr] data-shown:translate-x-0 data-shown:opacity-100 data-shown:blur-none",
          "transition-[grid-template-columns,opacity,translate,filter] duration-[calc(200ms*var(--kf-speed,1))] ease-house",
          "data-shown:duration-[calc(380ms*var(--kf-speed,1))] data-shown:ease-spring",
          "[&>*]:min-w-0 [&>*]:overflow-hidden data-shown:[&>*]:overflow-visible",
          "motion-reduce:transition-none",
        ),
        className,
      ),
      children: (state) => (
        /* While hidden it can't be reached. */
        <div inert={!state.shown}>{typeof children === "function" ? children(state) : children}</div>
      ),
    },
    "div",
  )
}

/** One column's header. Pass `render` to draw it as your table's header cell. */
function DataTableHead({ value, className, ...props }: { value: string } & Omit<Part<"head", "th">, "value">) {
  return usePart(dataTable, "head", { value }, { ...props, className } as Part<"head", "th">, "th")
}

/** One row. Pass `render` to draw it as your table's row. */
function DataTableRow({ value, className, ...props }: { value: string } & Omit<Part<"row", "tr">, "value">) {
  return usePart(dataTable, "row", { value }, { ...props, className } as Part<"row", "tr">, "tr")
}

/** The bar that rises from the bottom centre while rows are selected. Place it after the content:
    it opens a room of its own there (`--data-table-bar-room`, its height) and floats at the bottom
    of the view while the content is taller than the screen. */
function DataTableBulkBar({ className, children, ...props }: Part<"bulk-bar">) {
  return usePart(
    dataTable,
    "bulk-bar",
    {},
    {
      ...props,
      className: withClass(
        cn(
          /* Height: while rows are selected the bar has a room of its own between the content and
             what follows, opened once on the first selection and closed when it clears, so it never
             covers a row. While the content runs past the screen it floats at the bottom of the view. */
          "pointer-events-none sticky bottom-4 z-20 flex justify-center",
          "-mt-3 h-0 data-open:mt-0 data-open:h-[var(--data-table-bar-room,2.5rem)]",
          "transition-[height,margin-top] duration-[calc(240ms*var(--kf-speed,1))] ease-house data-open:duration-[calc(380ms*var(--kf-speed,1))]",
          "[&>*]:pointer-events-auto [&>*]:absolute [&>*]:bottom-0 [&>*]:origin-bottom",
          "[&>*]:transition-[opacity,translate,scale,filter]",
          "data-open:[&>*]:animate-[kf-data-table-rise_calc(460ms*var(--kf-speed,1))_var(--ease-spring)_backwards]",
          "data-closed:[&>*]:pointer-events-none data-closed:[&>*]:translate-y-3 data-closed:[&>*]:scale-[0.96] data-closed:[&>*]:opacity-0 data-closed:[&>*]:blur-[4px]",
          "data-closed:[&>*]:duration-[calc(160ms*var(--kf-speed,1))] data-closed:[&>*]:ease-house",
          "motion-reduce:transition-none motion-reduce:[&>*]:animate-none motion-reduce:[&>*]:transition-none",
        ),
        className,
      ),
      children: (state) => <div inert={!state.open}>{typeof children === "function" ? children(state) : children}</div>,
    },
    "div",
  )
}

export {
  type DataTableColumn,
  dataTableBodyMotion,
  dataTableCellMotion,
  DataTableBulkBar,
  DataTableContent,
  DataTableEmpty,
  DataTableFilters,
  DataTableFooter,
  DataTableHead,
  DataTableReset,
  DataTableRoot,
  DataTableRow,
  DataTableSearch,
  DataTableToolbar,
  DataTableView,
  useColumnPresence,
  useDataTable,
}
export {
  dataTable,
  type DataTableFilters as DataTableFilterValues,
  type DataTableOptions,
  type DataTableSort,
  type DataTableSortDirection,
  facetCounts,
  filterRows,
  paginateRows,
  rowModel,
  searchRows,
  sortRows,
} from "@/components/keyframery/core/data-table-core"
```

**components/keyframery/core/data-table-core.ts**

```ts
/* A data table, as a UI SDK primitive. UI SDK ships no data table, so it is defined with its core:
   the same definition renders in React, Vue, Svelte, Solid and web components.

   `table` is the presentational table (headers, rows, a sort arrow). `dataTable` is the list screen
   built on it: it takes `data` and `columns` and owns the state a list screen needs: the sort, a
   search over chosen columns, a faceted filter per column, which columns are hidden, which rows are
   selected, the page and the page size. Every piece works uncontrolled (`defaultSort`) and
   controlled (`sort` with `onSortChange`), so a page can keep it in the URL.

   No table library: the row model at the bottom of this file (search, filter, sort, paginate and
   the facet counts) is plain functions with no DOM, exported for anyone who needs the same rows on
   the server. They stay fast at 500 rows and more: one pass to filter, one sort, one slice.

   Screen readers hear "N results" a moment after the search or a filter changes, and "N rows
   selected" when the selection does. Escape inside the table clears the selection. */

import { announce, type ChangeDetails, createChange, definePrimitive, elements } from "@ui-sdk/core"

/* ---------------------------------------------------------------- types */

/** A row of your data. Any object. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- rows are the caller's own type
type DataTableRow = any

type DataTableSortDirection = "ascending" | "descending"

/** The sorted column and its direction, or `null` for the data's own order. */
type DataTableSort = { id: string; direction: DataTableSortDirection } | null

/** The values chosen in each column's filter, by column id. A column with no values is unfiltered. */
type DataTableFilters = Record<string, string[]>

/** One value a column can be filtered by. `icon` is whatever your framework renders, like a React component. */
type DataTableFilterOption<Icon = unknown> = { value: string; label?: string; icon?: Icon }

/** One column. Everything but `id` and `header` is optional. */
type DataTableColumn<Row = DataTableRow, Cell = unknown, Icon = unknown> = {
  /** Names the column in state, in `filters`, in `hiddenColumns` and for agents. */
  id: string
  /** The column's label: the header, the "Toggle columns" menu, the filter chip, the agent. */
  header: string
  /** How to read the value: a key of the row, or a function. Defaults to `row[id]`. */
  accessor?: keyof Row | ((row: Row) => unknown)
  /** Renders the cell. Your framework's renderer, like a React function of the row. Defaults to the value as text. */
  cell?: Cell
  /** Offers Asc and Desc in the header's menu. Defaults to true. */
  sortable?: boolean
  /** The value to sort by, when it isn't the cell's value (a status in its own order, a date as a number). */
  sortValue?: (row: Row) => number | string
  /** Offers Hide in the header's menu and a row in "Toggle columns". Defaults to true. */
  hideable?: boolean
  /** The search field looks in this column. */
  searchable?: boolean
  /** Gives the column a faceted filter in the toolbar, with these values. */
  filter?: { title?: string; options: DataTableFilterOption<Icon>[] }
  /** Where the header and cells sit. Numbers usually go at the end. Defaults to "start". */
  align?: "start" | "center" | "end"
  /** Stays in view while the table scrolls sideways on a narrow container (the first column, usually). */
  sticky?: boolean
  /** Leaves the column out below this container width: "sm" 30rem, "md" 40rem, "lg" 52rem. */
  hideBelow?: "sm" | "md" | "lg"
}

/** One row of the current page, with its id. */
type DataTableEntry<Row = DataTableRow> = { id: string; row: Row }

/** How many rows would match each value of a column's filter, given everything else. */
type DataTableFacets = Record<string, Record<string, number>>

type DataTableModel<Row = DataTableRow> = {
  /** The rows of the current page. */
  entries: DataTableEntry<Row>[]
  /** How many rows match the search and filters, on every page. */
  total: number
  pageCount: number
  facets: DataTableFacets
}

type SortReason = "item-press" | "agent" | "none"
type SearchReason = "input-change" | "clear-press" | "agent" | "none"
type FiltersReason = "item-press" | "clear-press" | "agent" | "none"
type ColumnsReason = "item-press" | "agent" | "none"
type SelectedReason = "item-press" | "select-all" | "clear-press" | "escape-key" | "agent" | "none"
type PageReason = "item-press" | "filter-change" | "page-size-change" | "data-change" | "agent" | "none"

type DataTableOptions = {
  /** The rows. */
  data?: DataTableRow[]
  /** The columns, in order. */
  columns?: DataTableColumn[]
  /** Each row's id, for selection and for keys. Defaults to `row.id`, then the row's index. */
  getRowId?: (row: DataTableRow, index: number) => string
  /** The table's name, for screen readers and agents, like "Orders". */
  label?: string
  /** Shows skeleton rows at the table's own geometry while the data loads. */
  loading?: boolean
  /** Adds a checkbox to every row and a select-all to the header. Defaults to true. */
  selectable?: boolean
  /** The choices under "Rows per page". Defaults to 10, 20, 30, 40 and 50. */
  pageSizes?: number[]

  sort?: DataTableSort
  defaultSort?: DataTableSort
  onSortChange?: (sort: DataTableSort, details: ChangeDetails<SortReason>) => void
  /** The text in the search field. */
  search?: string
  defaultSearch?: string
  onSearchChange?: (search: string, details: ChangeDetails<SearchReason>) => void
  filters?: DataTableFilters
  defaultFilters?: DataTableFilters
  onFiltersChange?: (filters: DataTableFilters, details: ChangeDetails<FiltersReason>) => void
  /** The ids of the columns that are hidden. */
  hiddenColumns?: string[]
  defaultHiddenColumns?: string[]
  onHiddenColumnsChange?: (hidden: string[], details: ChangeDetails<ColumnsReason>) => void
  /** The ids of the selected rows, on every page. */
  selected?: string[]
  defaultSelected?: string[]
  onSelectedChange?: (selected: string[], details: ChangeDetails<SelectedReason>) => void
  /** The page, from 1. */
  page?: number
  defaultPage?: number
  onPageChange?: (page: number, details: ChangeDetails<PageReason>) => void
  pageSize?: number
  defaultPageSize?: number
  onPageSizeChange?: (pageSize: number, details: ChangeDetails<PageReason>) => void
}

/** What an agent and the column parts read about a column. */
type DataTableColumnInfo = {
  id: string
  label: string
  visible: boolean
  sortable: boolean
  hideable: boolean
  filterable: boolean
}

type Inputs = {
  data: DataTableRow[]
  defs: DataTableColumn[]
  getRowId: (row: DataTableRow, index: number) => string
  label: string
  loading: boolean
  selectable: boolean
  pageSizes: number[]
}

type DataTableState = Inputs & {
  sort: DataTableSort
  search: string
  filters: DataTableFilters
  hiddenColumns: string[]
  selected: string[]
  page: number
  pageSize: number
  model: DataTableModel
  /** Readable for agents: every column, with whether it shows. */
  columns: DataTableColumnInfo[]
  /** Readable for agents: the ids of the rows on this page, in order. */
  rows: string[]
  /** Readable for agents: how many rows match, on every page. */
  total: number
  pageCount: number
  /** Turns over when the rows are re-ordered (a sort, a page turn), so they cascade in again. */
  epoch: number
  /** Which way the last page turn went, so the new rows arrive from that side. */
  direction: "forward" | "backward" | "none"
}

/* ---------------------------------------------------------------- the row model */

const emptyRows: DataTableRow[] = []
const emptyColumns: DataTableColumn[] = []
const emptyList: string[] = []
const emptyFilters: DataTableFilters = {}
const defaultPageSizes = [10, 20, 30, 40, 50]
const defaultRowId = (row: DataTableRow, index: number) => {
  const id = row && typeof row === "object" ? (row as { id?: unknown }).id : undefined
  return id === undefined || id === null ? String(index) : String(id)
}

/** A column's value in a row. */
function valueOf(column: DataTableColumn, row: DataTableRow): unknown {
  const { accessor } = column
  if (typeof accessor === "function") return accessor(row)
  return row?.[(accessor ?? column.id) as string]
}

/** A value as the text a search and a filter compare. */
function textOf(value: unknown): string {
  if (value === null || value === undefined) return ""
  if (value instanceof Date) return value.toISOString()
  if (Array.isArray(value)) return value.map(textOf).join(" ")
  return String(value)
}

const collator = typeof Intl !== "undefined" ? new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }) : null

/** Compares two values: numbers and dates by size, text in reading order, empty last. */
function compareValues(a: unknown, b: unknown): number {
  const emptyA = a === null || a === undefined || a === ""
  const emptyB = b === null || b === undefined || b === ""
  if (emptyA || emptyB) return emptyA === emptyB ? 0 : emptyA ? 1 : -1
  const na = a instanceof Date ? a.getTime() : a
  const nb = b instanceof Date ? b.getTime() : b
  if (typeof na === "number" && typeof nb === "number") return na - nb
  if (typeof na === "boolean" && typeof nb === "boolean") return Number(na) - Number(nb)
  const sa = textOf(na)
  const sb = textOf(nb)
  return collator ? collator.compare(sa, sb) : sa < sb ? -1 : sa > sb ? 1 : 0
}

/** Whether a row's value is one of the chosen values. A list value matches when any item does. */
function matchesFilter(value: unknown, chosen: string[]) {
  if (!chosen.length) return true
  if (Array.isArray(value)) return value.some((item) => chosen.includes(textOf(item)))
  return chosen.includes(textOf(value))
}

/** The rows whose searchable columns hold the search text, ignoring case. */
function searchRows<Row>(rows: Row[], columns: DataTableColumn<Row>[], search: string): Row[] {
  const needle = search.trim().toLowerCase()
  if (!needle) return rows
  const searchable = columns.filter((column) => column.searchable)
  if (!searchable.length) return rows
  return rows.filter((row) => searchable.some((column) => textOf(valueOf(column as DataTableColumn, row)).toLowerCase().includes(needle)))
}

/** The rows that pass every column filter, leaving out `skip` (for that column's own facet counts). */
function filterRows<Row>(rows: Row[], columns: DataTableColumn<Row>[], filters: DataTableFilters, skip?: string): Row[] {
  const active = columns.filter((column) => column.id !== skip && filters[column.id]?.length)
  if (!active.length) return rows
  return rows.filter((row) => active.every((column) => matchesFilter(valueOf(column as DataTableColumn, row), filters[column.id])))
}

/** The rows in the sort's order. Stable: rows that tie keep the order they had. */
function sortRows<Row>(rows: Row[], columns: DataTableColumn<Row>[], sort: DataTableSort): Row[] {
  if (!sort) return rows
  const column = columns.find((c) => c.id === sort.id)
  if (!column) return rows
  const read = column.sortValue ?? ((row: Row) => valueOf(column as DataTableColumn, row))
  const sign = sort.direction === "descending" ? -1 : 1
  return rows
    .map((row, index) => ({ row, index, key: read(row) }))
    .sort((a, b) => {
      const compared = compareValues(a.key, b.key)
      /* Empty values stay last in either direction. */
      const emptyA = a.key === null || a.key === undefined || a.key === ""
      const emptyB = b.key === null || b.key === undefined || b.key === ""
      return (emptyA || emptyB ? compared : compared * sign) || a.index - b.index
    })
    .map((item) => item.row)
}

/** How many rows match each value of each filterable column, given the search and the other filters. */
function facetCounts<Row>(rows: Row[], columns: DataTableColumn<Row>[], filters: DataTableFilters): DataTableFacets {
  const facets: DataTableFacets = {}
  for (const column of columns) {
    if (!column.filter) continue
    const counts: Record<string, number> = {}
    for (const option of column.filter.options) counts[option.value] = 0
    for (const row of filterRows(rows, columns, filters, column.id)) {
      const value = valueOf(column as DataTableColumn, row)
      for (const item of Array.isArray(value) ? value : [value]) {
        const key = textOf(item)
        counts[key] = (counts[key] ?? 0) + 1
      }
    }
    facets[column.id] = counts
  }
  return facets
}

/** The number of pages for `total` rows, never less than one. */
function pageCountOf(total: number, pageSize: number) {
  return Math.max(1, Math.ceil(total / Math.max(1, pageSize)))
}

/** The rows of one page, from 1. */
function paginateRows<Row>(rows: Row[], page: number, pageSize: number): Row[] {
  const size = Math.max(1, pageSize)
  const at = (Math.min(Math.max(1, page), pageCountOf(rows.length, size)) - 1) * size
  return rows.slice(at, at + size)
}

/** Everything the table shows, from the data and the state: search, filter, facet, sort, page. */
function rowModel<Row>(input: {
  data: Row[]
  columns: DataTableColumn<Row>[]
  getRowId?: (row: Row, index: number) => string
  search?: string
  filters?: DataTableFilters
  sort?: DataTableSort
  page?: number
  pageSize?: number
}): DataTableModel<Row> {
  const getRowId = input.getRowId ?? defaultRowId
  const ids = new Map<Row, string>()
  input.data.forEach((row, index) => ids.set(row, getRowId(row, index)))
  const searched = searchRows(input.data, input.columns, input.search ?? "")
  const filters = input.filters ?? emptyFilters
  const filtered = filterRows(searched, input.columns, filters)
  const sorted = sortRows(filtered, input.columns, input.sort ?? null)
  const pageSize = input.pageSize ?? 10
  return {
    entries: paginateRows(sorted, input.page ?? 1, pageSize).map((row) => ({ id: ids.get(row) ?? "", row })),
    total: filtered.length,
    pageCount: pageCountOf(filtered.length, pageSize),
    facets: facetCounts(searched, input.columns, filters),
  }
}

/* ---------------------------------------------------------------- helpers */

const sameList = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((item, i) => item === b[i])

const sameFilters = (a: DataTableFilters, b: DataTableFilters) => {
  const keys = new Set([...Object.keys(a), ...Object.keys(b)])
  for (const key of keys) if (!sameList(a[key] ?? emptyList, b[key] ?? emptyList)) return false
  return true
}

/** Leaves out columns with no values, so `{}` means "no filters". */
function cleanFilters(filters: DataTableFilters): DataTableFilters {
  const next: DataTableFilters = {}
  for (const [key, values] of Object.entries(filters)) if (values?.length) next[key] = [...values]
  return next
}

const isFiltered = (state: Pick<DataTableState, "search" | "filters">) =>
  state.search.trim() !== "" || Object.values(state.filters).some((values) => values.length > 0)

function inputsOf(options: DataTableOptions): Inputs {
  return {
    data: options.data ?? emptyRows,
    defs: options.columns ?? emptyColumns,
    getRowId: options.getRowId ?? defaultRowId,
    label: options.label ?? "",
    loading: options.loading ?? false,
    selectable: options.selectable ?? true,
    pageSizes: options.pageSizes ?? defaultPageSizes,
  }
}

function columnInfo(defs: DataTableColumn[], hidden: string[]): DataTableColumnInfo[] {
  return defs.map((column) => ({
    id: column.id,
    label: column.header,
    visible: !hidden.includes(column.id),
    sortable: column.sortable ?? true,
    hideable: column.hideable ?? true,
    filterable: !!column.filter,
  }))
}

function derive(state: Omit<DataTableState, "model" | "columns" | "rows" | "total" | "pageCount">) {
  const model = rowModel({
    data: state.data,
    columns: state.defs,
    getRowId: state.getRowId,
    search: state.search,
    filters: state.filters,
    sort: state.sort,
    page: state.page,
    pageSize: state.pageSize,
  })
  return {
    model,
    columns: columnInfo(state.defs, state.hiddenColumns),
    rows: model.entries.map((entry) => entry.id),
    total: model.total,
    pageCount: model.pageCount,
  }
}

/** A short line of a row's values, for agents and the row's checkbox name. */
function rowText(defs: DataTableColumn[], row: DataTableRow) {
  return defs
    .map((column) => textOf(valueOf(column, row)))
    .filter(Boolean)
    .slice(0, 4)
    .join(", ")
}

/* ---------------------------------------------------------------- the primitive */

const dataTable = definePrimitive({
  name: "data-table",
  options: {
    data: "value",
    columns: "value",
    getRowId: "value",
    label: "string",
    loading: "boolean",
    selectable: "boolean",
    pageSizes: "list",
    sort: "value",
    defaultSort: "value",
    onSortChange: "callback",
    search: "string",
    defaultSearch: "string",
    onSearchChange: "callback",
    filters: "value",
    defaultFilters: "value",
    onFiltersChange: "callback",
    hiddenColumns: "list",
    defaultHiddenColumns: "list",
    onHiddenColumnsChange: "callback",
    selected: "list",
    defaultSelected: "list",
    onSelectedChange: "callback",
    page: "number",
    defaultPage: "number",
    onPageChange: "callback",
    pageSize: "number",
    defaultPageSize: "number",
    onPageSizeChange: "callback",
  },
  controlled: ["sort", "search", "filters", "hiddenColumns", "selected", "page", "pageSize", "columns", "rows", "total", "pageCount", "loading"],
  state: (options: DataTableOptions): DataTableState => {
    const base = {
      ...inputsOf(options),
      sort: options.sort !== undefined ? options.sort : (options.defaultSort ?? null),
      search: options.search ?? options.defaultSearch ?? "",
      filters: cleanFilters(options.filters ?? options.defaultFilters ?? emptyFilters),
      hiddenColumns: options.hiddenColumns ?? options.defaultHiddenColumns ?? emptyList,
      selected: options.selected ?? options.defaultSelected ?? emptyList,
      page: Math.max(1, options.page ?? options.defaultPage ?? 1),
      pageSize: Math.max(1, options.pageSize ?? options.defaultPageSize ?? 10),
      epoch: 0,
      direction: "none" as const,
    }
    return { ...base, ...derive(base) }
  },
  sync: (options) => ({
    ...inputsOf(options),
    ...(options.sort === undefined ? {} : { sort: options.sort }),
    ...(options.search === undefined ? {} : { search: options.search }),
    ...(options.filters === undefined ? {} : { filters: cleanFilters(options.filters) }),
    ...(options.hiddenColumns === undefined ? {} : { hiddenColumns: options.hiddenColumns }),
    ...(options.selected === undefined ? {} : { selected: options.selected }),
    ...(options.page === undefined ? {} : { page: Math.max(1, options.page) }),
    ...(options.pageSize === undefined ? {} : { pageSize: Math.max(1, options.pageSize) }),
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)

    /* The model is derived from the data and the state, which a parent may control. Recompute it
       whenever one of them is a new value, and keep the page inside the page count. */
    const inputKeys = ["data", "defs", "getRowId", "search", "filters", "sort", "page", "pageSize", "hiddenColumns"] as const
    let from = store.get()
    context.onDestroy(
      store.subscribe(() => {
        const now = store.get()
        if (inputKeys.every((key) => now[key] === from[key])) return
        const reordered = now.sort !== from.sort || now.page !== from.page || now.pageSize !== from.pageSize
        const direction = now.page > from.page ? "forward" : now.page < from.page ? "backward" : now.sort !== from.sort ? "none" : now.direction
        const derived = derive(now)
        from = { ...now, ...derived }
        store.set({ ...derived, ...(reordered ? { epoch: now.epoch + 1, direction } : {}) })
        from = store.get()
        /* Fewer rows than before can leave the page past the end. */
        if (now.page > derived.pageCount) change("page", derived.pageCount, { reason: "data-change" })
      }),
    )

    const pageTo = (page: number, reason: PageReason, event?: Event) => {
      const { pageCount } = store.get()
      const next = Math.min(Math.max(1, Math.round(page)), pageCount)
      if (next === store.get().page) return false
      return change("page", next, { reason, event })
    }
    const firstPage = (reason: PageReason) => {
      if (store.get().page !== 1) change("page", 1, { reason })
    }

    const setFilters = (filters: DataTableFilters, reason: FiltersReason, event?: Event) => {
      const next = cleanFilters(filters)
      if (sameFilters(next, store.get().filters)) return false
      const done = change("filters", next, { reason, event })
      firstPage("filter-change")
      return done
    }

    const setSelected = (ids: string[], reason: SelectedReason, event?: Event) => {
      const next = [...new Set(ids)]
      if (sameList(next, store.get().selected)) return false
      return change("selected", next, { reason, event })
    }

    const setHidden = (hidden: string[], reason: ColumnsReason, event?: Event) => {
      const { defs } = store.get()
      /* Only hideable columns hide, and one column always stays. */
      const next = defs.filter((c) => hidden.includes(c.id) && (c.hideable ?? true)).map((c) => c.id)
      if (defs.length && next.length >= defs.length) return false
      if (sameList(next, store.get().hiddenColumns)) return false
      return change("hiddenColumns", next, { reason, event })
    }

    /* The bulk bar closes and turns inert when the selection clears. If focus was in it, put it
       back in the table (the select-all, or the first control there) instead of losing it. */
    const keepFocus = (clear: () => boolean) => {
      const active = typeof document === "undefined" ? null : document.activeElement
      const bar = elements(context, "bulk-bar")[0]?.el
      const inBar = !!(active && bar && bar.contains(active))
      const done = clear()
      if (done && inBar) {
        const content = elements(context, "content")[0]?.el
        content?.querySelector<HTMLElement>('[role="checkbox"]:not([aria-disabled="true"]), button:not([disabled]), [tabindex="0"]')?.focus()
      }
      return done
    }

    const column = (id: string) => store.get().defs.find((c) => c.id === id || c.header.toLowerCase() === String(id).toLowerCase())

    return {
      /* ---- sort */
      /** Sorts by a column ("ascending" or "descending"), or clears the sort with "none". */
      setSort(columnId: string, direction: DataTableSortDirection | "none" = "ascending", event?: Event) {
        const target = column(columnId)
        if (direction === "none" || !target) {
          if (store.get().sort === null) return false
          return change("sort", null, { reason: event ? "item-press" : "agent", event })
        }
        if (!(target.sortable ?? true)) return false
        const now = store.get().sort
        if (now?.id === target.id && now.direction === direction) return false
        return change("sort", { id: target.id, direction }, { reason: event ? "item-press" : "agent", event })
      },
      /** Turns a column's sort over: unsorted or descending becomes ascending, ascending descending. */
      toggleSort(columnId: string, event?: Event) {
        const now = store.get().sort
        const target = column(columnId)
        if (!target) return false
        const direction: DataTableSortDirection = now?.id === target.id && now.direction === "ascending" ? "descending" : "ascending"
        return this.setSort(target.id, direction, event)
      },
      clearSort: () => (store.get().sort === null ? false : change("sort", null, { reason: "agent" })),

      /* ---- search */
      /** Searches the searchable columns. An empty string clears the search. */
      setSearch(text: string, event?: Event) {
        const next = String(text ?? "")
        if (next === store.get().search) return false
        const done = change("search", next, { reason: event ? "input-change" : "agent", event })
        firstPage("filter-change")
        return done
      },
      clearSearch: (event?: Event) => {
        if (!store.get().search) return false
        const done = change("search", "", { reason: event ? "clear-press" : "agent", event })
        firstPage("filter-change")
        return done
      },

      /* ---- filters */
      /** Keeps only rows whose column holds one of these values. An empty list clears that filter. */
      setFilter(columnId: string, values: string[], event?: Event) {
        const target = column(columnId)
        if (!target?.filter) return false
        /* Agents may pass labels: map them to values. */
        const options = target.filter.options
        const mapped = (Array.isArray(values) ? values : [values]).map((v) => options.find((o) => o.value === v || [o.value, o.label ?? ""].some((name) => name.toLowerCase() === String(v).toLowerCase()))?.value ?? String(v))
        return setFilters({ ...store.get().filters, [target.id]: mapped }, event ? "item-press" : "agent", event)
      },
      /** Adds a value to a column's filter, or takes it out. */
      toggleFilterValue(columnId: string, value: string, event?: Event) {
        const target = column(columnId)
        if (!target?.filter) return false
        const now = store.get().filters[target.id] ?? emptyList
        return this.setFilter(target.id, now.includes(value) ? now.filter((v) => v !== value) : [...now, value], event)
      },
      clearFilter(columnId: string, event?: Event) {
        const target = column(columnId)
        if (!target) return false
        return setFilters({ ...store.get().filters, [target.id]: [] }, event ? "clear-press" : "agent", event)
      },
      /** Clears the search and every filter: the toolbar's Reset. */
      resetFilters(event?: Event) {
        const reason = event ? "clear-press" : "agent"
        const searched = store.get().search ? change("search", "", { reason, event }) : false
        const filtered = setFilters({}, reason, event)
        firstPage("filter-change")
        return searched || filtered
      },

      /* ---- columns */
      hideColumn(columnId: string, event?: Event) {
        const target = column(columnId)
        if (!target) return false
        return setHidden([...store.get().hiddenColumns, target.id], event ? "item-press" : "agent", event)
      },
      showColumn(columnId: string, event?: Event) {
        const target = column(columnId)
        if (!target) return false
        return setHidden(store.get().hiddenColumns.filter((id) => id !== target.id), event ? "item-press" : "agent", event)
      },
      toggleColumn(columnId: string, event?: Event) {
        const target = column(columnId)
        if (!target) return false
        return store.get().hiddenColumns.includes(target.id) ? this.showColumn(target.id, event) : this.hideColumn(target.id, event)
      },

      /* ---- selection */
      /** Selects these rows (by id) and only these. */
      setSelected: (ids: string[], event?: Event) => setSelected(Array.isArray(ids) ? ids.map(String) : [String(ids)], event ? "item-press" : "agent", event),
      /** Adds rows (by id) to the selection. */
      selectRows: (ids: string[], event?: Event) =>
        setSelected([...store.get().selected, ...(Array.isArray(ids) ? ids.map(String) : [String(ids)])], event ? "item-press" : "agent", event),
      toggleRow(id: string, event?: Event) {
        const now = store.get().selected
        const key = String(id)
        return setSelected(now.includes(key) ? now.filter((x) => x !== key) : [...now, key], event ? "item-press" : "agent", event)
      },
      /** Selects every row on this page, or lets go of them when all are selected. */
      togglePage(event?: Event) {
        const { selected, rows } = store.get()
        const all = rows.length > 0 && rows.every((id) => selected.includes(id))
        return setSelected(all ? selected.filter((id) => !rows.includes(id)) : [...selected, ...rows], "select-all", event)
      },
      selectPage: () => setSelected([...store.get().selected, ...store.get().rows], "agent"),
      clearSelection: (event?: Event) => keepFocus(() => setSelected([], event?.type === "keydown" ? "escape-key" : event ? "clear-press" : "agent", event)),

      /* ---- pages */
      /** Goes to a page, from 1. */
      setPage: (page: number, event?: Event) => pageTo(Number(page), event ? "item-press" : "agent", event),
      nextPage: (event?: Event) => pageTo(store.get().page + 1, event ? "item-press" : "agent", event),
      previousPage: (event?: Event) => pageTo(store.get().page - 1, event ? "item-press" : "agent", event),
      /** Shows this many rows per page, and goes back to the first page. */
      setPageSize(size: number, event?: Event) {
        const next = Math.max(1, Math.round(Number(size)))
        if (!Number.isFinite(next) || next === store.get().pageSize) return false
        const done = change("pageSize", next, { reason: event ? "page-size-change" : "agent", event })
        firstPage("page-size-change")
        return done
      },

      /* ---- reading */
      /** The rows of this page, for agents: each row's id and a short line of its values. */
      visibleRows() {
        const { model, defs, hiddenColumns } = store.get()
        const shown = defs.filter((c) => !hiddenColumns.includes(c.id))
        return model.entries.map((entry) => ({ value: entry.id, label: rowText(shown, entry.row) }))
      },
      /** A short line of a row's values, to name its checkbox. */
      rowLabel(id: string) {
        const { model, defs } = store.get()
        const entry = model.entries.find((e) => e.id === id)
        return entry ? rowText(defs, entry.row) : id
      },

      /* ---- the element */
      /** Escape inside the table clears the selection, unless something inside used it first. */
      keydown(event: KeyboardEvent, el: HTMLElement) {
        if (event.key !== "Escape" || event.defaultPrevented) return
        if (!(event.target instanceof Node) || !el.contains(event.target)) return
        if (!store.get().selected.length) return
        event.preventDefault()
        keepFocus(() => setSelected([], "escape-key", event))
      },
      /** Tells screen readers how many rows match and how many are selected, as those change. */
      announcements(el: HTMLElement) {
        const doc = el.ownerDocument
        let last = store.get()
        let timer: ReturnType<typeof setTimeout> | undefined
        const stop = store.subscribe(() => {
          const now = store.get()
          if (now.selected !== last.selected && now.selected.length !== last.selected.length) {
            const n = now.selected.length
            announce(n ? `${n} ${n === 1 ? "row" : "rows"} selected` : "Selection cleared", { doc })
          }
          if (now.search !== last.search || now.filters !== last.filters) {
            clearTimeout(timer)
            /* After the person stops typing, once. */
            timer = setTimeout(() => {
              const total = store.get().total
              announce(`${total} ${total === 1 ? "result" : "results"}`, { doc })
            }, 600)
          }
          last = now
        })
        return () => {
          clearTimeout(timer)
          stop()
        }
      },
    }
  },
  slots: (slot) => {
    const pageSelection = (state: DataTableState): "all" | "some" | "none" => {
      const onPage = state.rows.filter((id) => state.selected.includes(id)).length
      return onPage === 0 ? "none" : onPage === state.rows.length ? "all" : "some"
    }
    const visibleDefs = (state: DataTableState) => state.defs.filter((c) => !state.hiddenColumns.includes(c.id))

    return {
      /* The whole list screen. Name it with `label` (or `aria-label`). */
      root: slot<{}, { loading: boolean; filtered: boolean; selectedCount: number; total: number }>({
        role: "group",
        state: (state) => ({ loading: state.loading, filtered: isFiltered(state), selectedCount: state.selected.length, total: state.total }),
        attrs: (state) => ({
          "aria-label": state.label || undefined,
          "data-loading": state.loading ? "" : undefined,
          "data-filtered": isFiltered(state) ? "" : undefined,
          "data-selecting": state.selected.length ? "" : undefined,
        }),
        on: {
          keydown: (event, { el, api }) => {
            if (el) api.keydown(event as KeyboardEvent, el)
          },
        },
        bind: (el, part) => part.api.announcements(el),
      }),

      /* The row above the table: search, filters, Reset, then View. */
      toolbar: slot<{}, { filtered: boolean }>({
        state: (state) => ({ filtered: isFiltered(state) }),
        attrs: (state) => ({ "data-filtered": isFiltered(state) ? "" : undefined }),
      }),

      /* Holds the search field. */
      search: slot<{}, { value: string; label: string; disabled: boolean }>({
        present: (state) => state.defs.some((c) => c.searchable),
        state: (state) => ({
          value: state.search,
          label: `Search by ${state.defs.filter((c) => c.searchable).map((c) => c.header.toLowerCase()).join(" and ")}`,
          disabled: state.loading,
        }),
      }),

      /* Holds a filter chip per filterable column, with the counts from the row model. */
      filters: slot<{}, { items: { id: string; title: string; selected: string[]; options: { value: string; label: string; count: number; icon?: unknown }[] }[] }>({
        state: (state) => ({
          items: state.defs
            .filter((c) => c.filter)
            .map((c) => ({
              id: c.id,
              title: c.filter?.title ?? c.header,
              selected: state.filters[c.id] ?? emptyList,
              options: (c.filter?.options ?? []).map((o) => ({ value: o.value, label: o.label ?? o.value, count: state.model.facets[c.id]?.[o.value] ?? 0, icon: o.icon })),
            })),
        }),
      }),

      /* Holds Reset, which shows only while the search or a filter is on. The renderer makes it inert while hidden. */
      reset: slot<{}, { shown: boolean }>({
        state: (state) => ({ shown: isFiltered(state) }),
        attrs: (state) => ({
          "data-shown": isFiltered(state) ? "" : undefined,
          "aria-hidden": isFiltered(state) ? undefined : "true",
        }),
      }),

      /* Holds View, the "Toggle columns" menu. */
      view: slot<{}, { columns: DataTableColumnInfo[] }>({
        state: (state) => ({ columns: state.columns.filter((c) => c.hideable) }),
      }),

      /* Holds the table: headers, rows, the empty state and the loading rows. */
      content: slot<
        {},
        {
          loading: boolean
          empty: boolean
          entries: DataTableEntry[]
          columns: DataTableColumn[]
          allColumns: DataTableColumn[]
          sort: DataTableSort
          selectable: boolean
          selected: string[]
          pageSelection: "all" | "some" | "none"
          pageSize: number
          epoch: number
          direction: "forward" | "backward" | "none"
          label: string
        }
      >({
        state: (state) => ({
          loading: state.loading,
          empty: !state.loading && state.total === 0,
          entries: state.model.entries,
          columns: visibleDefs(state),
          allColumns: state.defs,
          sort: state.sort,
          selectable: state.selectable,
          selected: state.selected,
          pageSelection: pageSelection(state),
          pageSize: state.pageSize,
          epoch: state.epoch,
          direction: state.direction,
          label: state.label,
        }),
        attrs: (state) => ({
          "aria-busy": state.loading ? "true" : undefined,
          "data-loading": state.loading ? "" : undefined,
          "data-direction": state.direction,
        }),
      }),

      /* One column's header: it reports its sort with `aria-sort`. Keyed by the column's id. */
      head: slot<{ value: string }, { sort: DataTableSortDirection | "none"; sortable: boolean; hideable: boolean; label: string }>({
        props: { value: "key" },
        state: (state, part) => {
          const c = state.defs.find((d) => d.id === part.key)
          return {
            sort: state.sort?.id === part.key ? state.sort.direction : "none",
            sortable: c?.sortable ?? true,
            hideable: c?.hideable ?? true,
            label: c?.header ?? part.key,
          }
        },
        attrs: (state, part) => {
          const c = state.defs.find((d) => d.id === part.key)
          const sortable = c?.sortable ?? true
          const sort = state.sort?.id === part.key ? state.sort.direction : "none"
          return {
            "aria-sort": sortable ? sort : undefined,
            "data-sorted": sortable ? sort : undefined,
            "data-column": part.key,
            "data-align": c?.align ?? "start",
          }
        },
      }),

      /* One row. Keyed by the row's id. */
      row: slot<{ value: string }, { selected: boolean }>({
        props: { value: "key" },
        state: (state, part) => ({ selected: state.selected.includes(part.key) }),
        attrs: (state, part) => ({
          "data-row": part.key,
          "data-selected": state.selected.includes(part.key) ? "" : undefined,
          "aria-selected": state.selectable ? String(state.selected.includes(part.key)) : undefined,
        }),
      }),

      /* Shown in place of the rows when nothing matches. */
      empty: slot<{}, { filtered: boolean; search: string }>({
        present: (state) => !state.loading && state.total === 0,
        state: (state) => ({ filtered: isFiltered(state), search: state.search }),
      }),

      /* Under the table: the selection count, "Rows per page", "Page X of Y" and the pages. */
      footer: slot<{}, { page: number; pageCount: number; pageSize: number; pageSizes: number[]; total: number; selectedCount: number; selectable: boolean }>({
        state: (state) => ({
          page: state.page,
          pageCount: state.pageCount,
          pageSize: state.pageSize,
          pageSizes: state.pageSizes.includes(state.pageSize) ? state.pageSizes : [...state.pageSizes, state.pageSize].sort((a, b) => a - b),
          total: state.total,
          selectedCount: state.selected.length,
          selectable: state.selectable,
        }),
      }),

      /* The bar that rises from the bottom centre while rows are selected. The renderer makes it inert while closed. */
      "bulk-bar": slot<{}, { open: boolean; count: number; selected: string[] }>({
        state: (state) => ({ open: state.selected.length > 0, count: state.selected.length, selected: state.selected }),
        attrs: (state) => ({
          "data-open": state.selected.length ? "" : undefined,
          "data-closed": state.selected.length ? undefined : "",
          "aria-hidden": state.selected.length ? undefined : "true",
        }),
      }),
    }
  },
  agent: {
    actions: [
      "setSort",
      "clearSort",
      "setSearch",
      "clearSearch",
      "setFilter",
      "clearFilter",
      "resetFilters",
      "hideColumn",
      "showColumn",
      "setPage",
      "nextPage",
      "previousPage",
      "setPageSize",
      "setSelected",
      "selectRows",
      "toggleRow",
      "selectPage",
      "clearSelection",
    ],
    items: (api) => api.visibleRows(),
  },
})

export {
  compareValues,
  type DataTableColumn,
  type DataTableColumnInfo,
  type DataTableEntry,
  type DataTableFacets,
  type DataTableFilterOption,
  type DataTableFilters,
  type DataTableModel,
  type DataTableOptions,
  type DataTableRow,
  type DataTableSort,
  type DataTableSortDirection,
  type DataTableState,
  dataTable,
  facetCounts,
  filterRows,
  pageCountOf,
  paginateRows,
  rowModel,
  searchRows,
  sortRows,
  textOf,
  valueOf,
}
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

## Usage [#usage]

```tsx
import { DataTable, type DataTableColumnDef } from "@/components/keyframery/data-table"

type Order = { id: string; customer: string; status: string; total: number }

const orders: Order[] = [
  { id: "1042", customer: "Maya Chen", status: "Paid", total: 184 },
  { id: "1041", customer: "Tom Okafor", status: "Pending", total: 62.5 },
]

const columns: DataTableColumnDef<Order>[] = [
  { id: "id", header: "Order", searchable: true },
  { id: "customer", header: "Customer", searchable: true },
  { id: "status", header: "Status", filter: { options: [{ value: "Paid" }, { value: "Pending" }] } },
  { id: "total", header: "Total", align: "end" },
]

export default function Usage() {
  return <DataTable label="Orders" data={orders} columns={columns} />
}
```

## Examples [#examples]

### A list screen [#a-list-screen]

Search, filters with counts, sortable headers, selection, a row menu and a bulk bar, all from `data` and `columns`.

<ExamplePreview name="data-table/orders">
  ```tsx
  import { Download } from "lucide-react"

  import { Badge } from "@/components/keyframery/badge"
  import { DataTable, DataTableBulkAction, type DataTableColumnDef } from "@/components/keyframery/data-table"
  import { MenuItem } from "@/components/keyframery/menu"

  type Member = { id: string; name: string; team: string; role: "Owner" | "Editor" | "Viewer"; trips: number }

  const people = ["Maya Chen", "Tom Okafor", "Ines Duarte", "Sam Price", "Lena Brandt", "Joe Walsh", "Aiko Mori", "Ravi Shah", "Clara Ruiz", "Ola Nord", "Ben Carter", "Nia Evans"]
  const teams = ["Lisbon", "Leeds", "Berlin"]
  const roles = ["Owner", "Editor", "Viewer"] as const
  const members: Member[] = people.map((name, i) => ({ id: String(i + 1), name, team: teams[i % 3], role: roles[(i * 7) % 3], trips: (i * 5) % 13 }))

  const columns: DataTableColumnDef<Member>[] = [
    { id: "name", header: "Name", searchable: true, hideable: false, sticky: true, cell: (m) => <span className="font-medium">{m.name}</span> },
    { id: "team", header: "Team", filter: { options: teams.map((value) => ({ value })) } },
    { id: "role", header: "Role", filter: { options: roles.map((value) => ({ value })) }, cell: (m) => <Badge variant={m.role === "Owner" ? "default" : "secondary"}>{m.role}</Badge> },
    { id: "trips", header: "Trips", align: "end", hideBelow: "sm" },
  ]

  export default function DataTableMembers() {
    return (
      <DataTable
        label="Team members"
        className="w-full max-w-[720px]"
        data={members}
        columns={columns}
        defaultPageSize={5}
        pageSizes={[5, 10, 20]}
        searchPlaceholder="Search people"
        rowActions={() => (
          <>
            <MenuItem value="edit">Edit</MenuItem>
            <MenuItem value="remove" destructive>
              Remove
            </MenuItem>
          </>
        )}
        bulkActions={() => <DataTableBulkAction icon={<Download size={16} strokeWidth={1.75} aria-hidden />} label="Export" />}
      />
    )
  }
  ```
</ExamplePreview>

### State in your hands [#state-in-your-hands]

Every piece of state is controlled or not: here the search, the filters, the sort and the page live in the page's own state, the way you would keep them in the URL.

<ExamplePreview name="data-table/controlled">
  ```tsx
  import * as React from "react"

  import { DataTable, type DataTableColumnDef, type DataTableFilterValues, type DataTableSort } from "@/components/keyframery/data-table"

  type Trip = { id: string; city: string; month: string; nights: number }

  const trips: Trip[] = ["Lisbon", "Porto", "Kyoto", "Oslo", "Seville", "Dublin", "Bristol", "Berlin"].flatMap((city, i) =>
    ["Mar", "Jun", "Sep"].map((month, j) => ({ id: `${city}-${month}`, city, month, nights: 2 + ((i + j * 3) % 6) })),
  )

  const columns: DataTableColumnDef<Trip>[] = [
    { id: "city", header: "City", searchable: true },
    { id: "month", header: "Month", filter: { options: ["Mar", "Jun", "Sep"].map((value) => ({ value })) }, sortValue: (t) => ["Mar", "Jun", "Sep"].indexOf(t.month) },
    { id: "nights", header: "Nights", align: "end" },
  ]

  export default function DataTableControlled() {
    const [search, setSearch] = React.useState("")
    const [filters, setFilters] = React.useState<DataTableFilterValues>({ month: ["Jun"] })
    const [sort, setSort] = React.useState<DataTableSort>({ id: "nights", direction: "descending" })
    const [page, setPage] = React.useState(1)
    return (
      <div className="flex w-full max-w-[560px] flex-col gap-3">
        <DataTable
          label="Trips"
          data={trips}
          columns={columns}
          selectable={false}
          defaultPageSize={5}
          search={search}
          onSearchChange={setSearch}
          filters={filters}
          onFiltersChange={setFilters}
          sort={sort}
          onSortChange={setSort}
          page={page}
          onPageChange={setPage}
        />
        <code className="text-[12px] text-muted-foreground">
          ?q={search}&month={(filters.month ?? []).join(",")}&sort={sort ? `${sort.id}.${sort.direction}` : ""}&page={page}
        </code>
      </div>
    )
  }
  ```
</ExamplePreview>

### Loading [#loading]

`loading` keeps the toolbar and headers and draws skeleton rows at the table's own geometry, one per row of the page.

<ExamplePreview name="data-table/loading">
  ```tsx
  import { DataTable, type DataTableColumnDef } from "@/components/keyframery/data-table"

  type Invoice = { id: string; client: string; due: string; amount: number }

  const columns: DataTableColumnDef<Invoice>[] = [
    { id: "id", header: "Invoice", searchable: true },
    { id: "client", header: "Client", searchable: true },
    { id: "due", header: "Due" },
    { id: "amount", header: "Amount", align: "end" },
  ]

  export default function DataTableLoading() {
    return <DataTable label="Invoices" className="w-full max-w-[640px]" data={[]} columns={columns} loading defaultPageSize={5} />
  }
  ```
</ExamplePreview>

## Motion [#motion]

| Move         | What you see                                                                                                                                                                                                                       |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Cascade**  | After a sort or a page turn the page's rows arrive one after another, rising from below for Next and dropping from above for Previous. After a search or a filter only the rows new to the page arrive; selecting replays nothing. |
| **Collapse** | A hidden column folds to nothing, its text blurring out, while the other columns close the gap; a column shown again opens out of nothing.                                                                                         |
| **Rise**     | The bulk bar rises from the bottom centre on a spring, from a smaller, blurred start, and sinks away when the selection is cleared.                                                                                                |
| **Roll**     | The selected count, the row count and the page number roll to each new number.                                                                                                                                                     |
| **Slide**    | Reset slides in beside the filters while the search or a filter is on, and folds away when they clear.                                                                                                                             |
| **Draw**     | Row checks and the select-all dash draw themselves (from Checkbox).                                                                                                                                                                |
| **Glide**    | The current page key glides along the pagination, and the highlight glides through every menu and the bulk bar.                                                                                                                    |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this data table moves, pass `speed`:

```tsx
<DataTable speed="fast">
  …
</DataTable>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                  | What it changes                       | Default                    |
| ------------------------- | ------------------------------------- | -------------------------- |
| `--data-table-surface`    | The table's card and its sticky cells | --card                     |
| `--data-table-border`     | The card's hairline                   | black 7%; white 8% in dark |
| `--data-table-accent`     | The hover and selected row tint       | --foreground               |
| `--data-table-radius`     | The card's corners                    | 14px                       |
| `--data-table-row-height` | Each row's height                     | 2.75rem                    |
| `--data-table-bar`        | The bulk bar's surface                | --popover                  |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### DataTable [#datatable]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;fast\&#x22;, \&#x22;normal\&#x22;, \&#x22;slow\&#x22; or a multiplier.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;search&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The search text, controlled; with `defaultSearch` and `onSearchChange`. It looks in the columns marked `searchable`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;sort&#x22;,&#x22;type&#x22;:&#x22;{ id: string; direction: DataTableSortDirecti…&#x22;,&#x22;full&#x22;:&#x22;{ id: string; direction: DataTableSortDirection; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;`{ id, direction: \&#x22;ascending\&#x22; | \&#x22;descending\&#x22; }` or `null`, controlled; with `defaultSort` and `onSortChange`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;page&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The page from 1, controlled; with `defaultPage` and `onPageChange`. A page past the end after the data shrinks moves back to the last one.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The table's name, for screen readers and agents, like \&#x22;Orders\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;loading&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Draws skeleton rows at the table's own geometry, one per row of the page.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;selected&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The ids of selected rows on every page, controlled; with `defaultSelected` and `onSelectedChange`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;selectable&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Adds a checkbox to every row and a select-all for the page. Defaults to true.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;pageSizes&#x22;,&#x22;type&#x22;:&#x22;number[]&#x22;,&#x22;full&#x22;:&#x22;number[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The choices under \&#x22;Rows per page\&#x22;. Defaults to 10, 20, 30, 40 and 50.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultSort&#x22;,&#x22;type&#x22;:&#x22;{ id: string; direction: DataTableSortDirecti…&#x22;,&#x22;full&#x22;:&#x22;{ id: string; direction: DataTableSortDirection; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onSortChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(sort: DataTableSort, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;agent\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultSearch&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onSearchChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(search: string, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;clear-press\&#x22; | \&#x22;input-change\&#x22; | \&#x22;agent\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;filters&#x22;,&#x22;type&#x22;:&#x22;DataTableFilters&#x22;,&#x22;full&#x22;:&#x22;DataTableFilters&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The chosen values per column, like `{ payment: [\&#x22;Paid\&#x22;] }`, controlled; with `defaultFilters` and `onFiltersChange`. Changing a filter or the search goes back to page 1.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultFilters&#x22;,&#x22;type&#x22;:&#x22;DataTableFilters&#x22;,&#x22;full&#x22;:&#x22;DataTableFilters&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onFiltersChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(filters: DataTableFilters, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;clear-press\&#x22; | \&#x22;agent\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;hiddenColumns&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The ids of hidden columns, controlled; with `defaultHiddenColumns` and `onHiddenColumnsChange`. One column always stays.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultHiddenColumns&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onHiddenColumnsChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(hidden: string[], details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;agent\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultSelected&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onSelectedChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(selected: string[], details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;escape-key\&#x22; | \&#x22;clear-press\&#x22; | \&#x22;agent\&#x22; | \&#x22;select-all\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultPage&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onPageChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(page: number, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;agent\&#x22; | \&#x22;filter-change\&#x22; | \&#x22;page-size-change\&#x22; | \&#x22;data-change\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;pageSize&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Rows per page, controlled; with `defaultPageSize` (10) and `onPageSizeChange`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultPageSize&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onPageSizeChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(pageSize: number, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;agent\&#x22; | \&#x22;filter-change\&#x22; | \&#x22;page-size-change\&#x22; | \&#x22;data-change\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;data&#x22;,&#x22;type&#x22;:&#x22;readonly Row[]&#x22;,&#x22;full&#x22;:&#x22;readonly Row[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The rows. Any objects.&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;columns&#x22;,&#x22;type&#x22;:&#x22;DataTableColumnDef<Row>[]&#x22;,&#x22;full&#x22;:&#x22;DataTableColumnDef<Row>[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The columns, in order: `{ id, header, accessor?, cell?, sortable?, sortValue?, hideable?, searchable?, filter?: { title?, options }, align?, sticky?, hideBelow?, className? }`. `accessor` is a key or a function and defaults to `row[id]`; `cell(row, value)` renders the cell.&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;getRowId&#x22;,&#x22;type&#x22;:&#x22;(row: Row, index: number) => string&#x22;,&#x22;full&#x22;:&#x22;(row: Row, index: number) => string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Each row's id for selection and keys. Defaults to `row.id`, then the index.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;searchPlaceholder&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The search field's placeholder.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;rowActions&#x22;,&#x22;type&#x22;:&#x22;(row: Row) => React.ReactNode&#x22;,&#x22;full&#x22;:&#x22;(row: Row) => React.ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;`(row) => MenuItem`s for the row menu (\&#x22;…\&#x22;). Leave it out for no row menu.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;bulkActions&#x22;,&#x22;type&#x22;:&#x22;(selected: string[]) => React.ReactNode&#x22;,&#x22;full&#x22;:&#x22;(selected: string[]) => React.ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;`(selectedIds) => DataTableBulkAction`s for the bulk bar.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;toolbar&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;More controls at the end of the toolbar, before View.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;emptyTitle&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;What the empty state says. Defaults to \&#x22;No results\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;emptyDescription&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### DataTableBulkAction [#datatablebulkaction]

Renders a `<button>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;tone&#x22;,&#x22;type&#x22;:&#x22;\&#x22;destructive\&#x22;&#x22;,&#x22;full&#x22;:&#x22;\&#x22;destructive\&#x22;&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;destructive\&#x22; for an action that removes.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;icon&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The action's icon.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The action's name; it folds to icon only on a narrow container and stays for screen readers.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;disabled&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Stops the item from being used. It stays focusable with `aria-disabled`, so arrow keys still reach it and a tooltip can say why.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;focusableWhenDisabled&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;true&#x22;,&#x22;description&#x22;:&#x22;Whether a disabled item stays reachable with arrow keys. Turn it off to skip it, natively disabled.&#x22;,&#x22;required&#x22;:false}]" />

### DataTableColumnHeader [#datatablecolumnheader]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;sort&#x22;,&#x22;type&#x22;:&#x22;\&#x22;none\&#x22; | \&#x22;ascending\&#x22; | \&#x22;descending\&#x22;&#x22;,&#x22;full&#x22;:&#x22;\&#x22;none\&#x22; | \&#x22;ascending\&#x22; | \&#x22;descending\&#x22;&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;sortable&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;hideable&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true}]" />

### DataTableContent [#datatablecontent]

<PropsTable rows="[{&#x22;name&#x22;:&#x22;rowActions&#x22;,&#x22;type&#x22;:&#x22;(row: never) => React.ReactNode&#x22;,&#x22;full&#x22;:&#x22;(row: never) => React.ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;emptyTitle&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:&#x22;\&#x22;No results\&#x22;&#x22;,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;emptyDescription&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### DataTableEmpty [#datatableempty]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;description&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### DataTableToolbar [#datatabletoolbar]

<PropsTable rows="[{&#x22;name&#x22;:&#x22;searchPlaceholder&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### DataTableRoot [#datatableroot]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;data&#x22;,&#x22;type&#x22;:&#x22;any[]&#x22;,&#x22;full&#x22;:&#x22;any[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The rows.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;columns&#x22;,&#x22;type&#x22;:&#x22;DataTableColumn<any, unknown, unknown>[]&#x22;,&#x22;full&#x22;:&#x22;DataTableColumn<any, unknown, unknown>[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The columns, in order.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;getRowId&#x22;,&#x22;type&#x22;:&#x22;(row: DataTableRow, index: number) => string&#x22;,&#x22;full&#x22;:&#x22;(row: DataTableRow, index: number) => string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Each row's id, for selection and for keys. Defaults to `row.id`, then the row's index.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The table's name, for screen readers and agents, like \&#x22;Orders\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;loading&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Shows skeleton rows at the table's own geometry while the data loads.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;selectable&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Adds a checkbox to every row and a select-all to the header. Defaults to true.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;pageSizes&#x22;,&#x22;type&#x22;:&#x22;number[]&#x22;,&#x22;full&#x22;:&#x22;number[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The choices under \&#x22;Rows per page\&#x22;. Defaults to 10, 20, 30, 40 and 50.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;sort&#x22;,&#x22;type&#x22;:&#x22;{ id: string; direction: DataTableSortDirecti…&#x22;,&#x22;full&#x22;:&#x22;{ id: string; direction: DataTableSortDirection; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultSort&#x22;,&#x22;type&#x22;:&#x22;{ id: string; direction: DataTableSortDirecti…&#x22;,&#x22;full&#x22;:&#x22;{ id: string; direction: DataTableSortDirection; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onSortChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(sort: DataTableSort, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;agent\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;search&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The text in the search field.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultSearch&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onSearchChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(search: string, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;clear-press\&#x22; | \&#x22;input-change\&#x22; | \&#x22;agent\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;filters&#x22;,&#x22;type&#x22;:&#x22;DataTableFilters&#x22;,&#x22;full&#x22;:&#x22;DataTableFilters&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultFilters&#x22;,&#x22;type&#x22;:&#x22;DataTableFilters&#x22;,&#x22;full&#x22;:&#x22;DataTableFilters&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onFiltersChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(filters: DataTableFilters, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;clear-press\&#x22; | \&#x22;agent\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;hiddenColumns&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The ids of the columns that are hidden.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultHiddenColumns&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onHiddenColumnsChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(hidden: string[], details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;agent\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;selected&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The ids of the selected rows, on every page.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultSelected&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onSelectedChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(selected: string[], details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;escape-key\&#x22; | \&#x22;clear-press\&#x22; | \&#x22;agent\&#x22; | \&#x22;select-all\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;page&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The page, from 1.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultPage&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onPageChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(page: number, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;agent\&#x22; | \&#x22;filter-change\&#x22; | \&#x22;page-size-change\&#x22; | \&#x22;data-change\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;pageSize&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultPageSize&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onPageSizeChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(pageSize: number, details: ChangeDetails<\&#x22;none\&#x22; | \&#x22;item-press\&#x22; | \&#x22;agent\&#x22; | \&#x22;filter-change\&#x22; | \&#x22;page-size-change\&#x22; | \&#x22;data-change\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `DataTableBulkBar`
* `DataTableFilters`
* `DataTableFooter`: a `<div>`
* `DataTableReset`
* `DataTableSearch`: a `<div>`
* `DataTableView`: a `<div>`
* `DataTableHead`: a `<tableheadercell>`
* `DataTableRow`: a `<tr>`

## Hooks [#hooks]

### useColumnPresence [#usecolumnpresence]

Call it inside the component to read and change its state.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;columns&#x22;,&#x22;type&#x22;:&#x22;{ column: C; leaving: boolean; }[]&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;ref&#x22;,&#x22;type&#x22;:&#x22;React.RefObject<HTMLElement | null>&#x22;,&#x22;description&#x22;:&#x22;&#x22;}]" />

### useDataTable [#usedatatable]

Call it inside the component to read and change its state.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;setSort&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;description&#x22;:&#x22;Sorts by a column (\&#x22;ascending\&#x22; or \&#x22;descending\&#x22;), or clears the sort with \&#x22;none\&#x22;.&#x22;},{&#x22;name&#x22;:&#x22;toggleSort&#x22;,&#x22;type&#x22;:&#x22;(columnId: string, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;Turns a column's sort over: unsorted or descending becomes ascending, ascending descending.&#x22;},{&#x22;name&#x22;:&#x22;clearSort&#x22;,&#x22;type&#x22;:&#x22;() => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;setSearch&#x22;,&#x22;type&#x22;:&#x22;(text: string, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;Searches the searchable columns. An empty string clears the search.&#x22;},{&#x22;name&#x22;:&#x22;clearSearch&#x22;,&#x22;type&#x22;:&#x22;(event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;setFilter&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;description&#x22;:&#x22;Keeps only rows whose column holds one of these values. An empty list clears that filter.&#x22;},{&#x22;name&#x22;:&#x22;toggleFilterValue&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;description&#x22;:&#x22;Adds a value to a column's filter, or takes it out.&#x22;},{&#x22;name&#x22;:&#x22;clearFilter&#x22;,&#x22;type&#x22;:&#x22;(columnId: string, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;resetFilters&#x22;,&#x22;type&#x22;:&#x22;(event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;Clears the search and every filter: the toolbar's Reset.&#x22;},{&#x22;name&#x22;:&#x22;hideColumn&#x22;,&#x22;type&#x22;:&#x22;(columnId: string, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;showColumn&#x22;,&#x22;type&#x22;:&#x22;(columnId: string, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;toggleColumn&#x22;,&#x22;type&#x22;:&#x22;(columnId: string, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;setSelected&#x22;,&#x22;type&#x22;:&#x22;(ids: string[], event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;Selects these rows (by id) and only these.&#x22;},{&#x22;name&#x22;:&#x22;selectRows&#x22;,&#x22;type&#x22;:&#x22;(ids: string[], event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;Adds rows (by id) to the selection.&#x22;},{&#x22;name&#x22;:&#x22;toggleRow&#x22;,&#x22;type&#x22;:&#x22;(id: string, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;togglePage&#x22;,&#x22;type&#x22;:&#x22;(event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;Selects every row on this page, or lets go of them when all are selected.&#x22;},{&#x22;name&#x22;:&#x22;selectPage&#x22;,&#x22;type&#x22;:&#x22;() => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;clearSelection&#x22;,&#x22;type&#x22;:&#x22;(event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;setPage&#x22;,&#x22;type&#x22;:&#x22;(page: number, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;Goes to a page, from 1.&#x22;},{&#x22;name&#x22;:&#x22;nextPage&#x22;,&#x22;type&#x22;:&#x22;(event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;previousPage&#x22;,&#x22;type&#x22;:&#x22;(event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;&#x22;},{&#x22;name&#x22;:&#x22;setPageSize&#x22;,&#x22;type&#x22;:&#x22;(size: number, event?: Event) => boolean&#x22;,&#x22;description&#x22;:&#x22;Shows this many rows per page, and goes back to the first page.&#x22;},{&#x22;name&#x22;:&#x22;visibleRows&#x22;,&#x22;type&#x22;:&#x22;() => { value: string; label: string; }[]&#x22;,&#x22;description&#x22;:&#x22;The rows of this page, for agents: each row's id and a short line of its values.&#x22;},{&#x22;name&#x22;:&#x22;rowLabel&#x22;,&#x22;type&#x22;:&#x22;(id: string) => string&#x22;,&#x22;description&#x22;:&#x22;A short line of a row's values, to name its checkbox.&#x22;},{&#x22;name&#x22;:&#x22;keydown&#x22;,&#x22;type&#x22;:&#x22;(event: KeyboardEvent, el: HTMLElement) => void&#x22;,&#x22;description&#x22;:&#x22;Escape inside the table clears the selection, unless something inside used it first.&#x22;},{&#x22;name&#x22;:&#x22;announcements&#x22;,&#x22;type&#x22;:&#x22;(el: HTMLElement) => () => void&#x22;,&#x22;description&#x22;:&#x22;Tells screen readers how many rows match and how many are selected, as those change.&#x22;}]" />

## Keyboard [#keyboard]

| Key                  | What it does                                                                                                                                                         |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <kbd>Tab</kbd>       | Moves through the search field, the filter chips, Reset, View, the select-all, each sortable header, then each row's checkbox and menu, the bulk bar and the footer. |
| <kbd>Enter</kbd>     | On a header, opens its menu: Asc, Desc and Hide. On a filter chip or View, opens it.                                                                                 |
| <kbd>ArrowDown</kbd> | Moves through the open menu's items; in the bulk bar, ArrowRight and ArrowLeft move between its buttons.                                                             |
| <kbd>Space</kbd>     | Checks or unchecks the focused row's checkbox or the select-all for the page; toggles a column in View.                                                              |
| <kbd>Escape</kbd>    | Closes an open menu; with nothing open, clears the selection while focus is in the table.                                                                            |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a data table, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/data-table-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/data-table`.

## Questions

### How does the animated Data table for UI SDK move?

Cascade: After a sort or a page turn the page's rows arrive one after another, rising from below for Next and dropping from above for Previous. After a search or a filter only the rows new to the page arrive; selecting replays nothing. Collapse: A hidden column folds to nothing, its text blurring out, while the other columns close the gap; a column shown again opens out of nothing. Rise: The bulk bar rises from the bottom centre on a spring, from a smaller, blurred start, and sinks away when the selection is cleared. Roll: The selected count, the row count and the page number roll to each new number. Slide: Reset slides in beside the filters while the search or a filter is on, and folds away when they clear. Draw: Row checks and the select-all dash draw themselves (from Checkbox). Glide: The current page key glides along the pagination, and the highlight glides through every menu and the bulk bar.

### Do I need Motion or Framer Motion for the animated Data table?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no data table. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/data-table-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Data table when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
