{
  "schemaVersion": 1,
  "target": "react",
  "name": "data-table",
  "version": "0.1.0",
  "category": "data",
  "title": "Data Table",
  "description": "A table with column sorting, a text filter, checkbox row selection, pagination, and empty states, built on Table without a table library.",
  "tags": [
    "table",
    "data",
    "sort",
    "filter",
    "pagination",
    "selection"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "@base-ui/react": "^1.9.0"
  },
  "registryDependencies": [
    {
      "name": "table",
      "version": "0.1.0"
    },
    {
      "name": "button",
      "version": "0.2.1"
    },
    {
      "name": "input",
      "version": "0.1.1"
    }
  ],
  "docsPath": "/components/data-table",
  "props": [
    {
      "name": "columns",
      "type": "DataTableColumn<Row>[]",
      "description": "Column definitions: id, header, accessor, cell, sortable, sortFn, filterable, numeric, className, headerClassName."
    },
    {
      "name": "data",
      "type": "Row[]",
      "description": "The rows."
    },
    {
      "name": "getRowId",
      "type": "(row) => string",
      "description": "Stable id per row, used for selection and keys."
    },
    {
      "name": "getRowLabel",
      "type": "(row) => string",
      "description": "Names a row in its checkbox label. Defaults to the id."
    },
    {
      "name": "caption / captionHidden",
      "type": "string / boolean",
      "description": "Accessible name for the table, optionally visually hidden."
    },
    {
      "name": "selectable",
      "type": "boolean",
      "default": "false",
      "description": "Adds a checkbox column with a select-all-on-page header checkbox."
    },
    {
      "name": "selected / defaultSelected / onSelectedChange",
      "type": "string[] / string[] / (ids) => void",
      "description": "Selection state, controlled or not."
    },
    {
      "name": "selectionActions",
      "type": "(ids) => ReactNode",
      "description": "Toolbar buttons shown while rows are selected."
    },
    {
      "name": "filterable / filterPlaceholder",
      "type": "boolean / string",
      "default": "false",
      "description": "Shows a search field that filters by string columns or columns marked filterable."
    },
    {
      "name": "filter / onFilterChange",
      "type": "string / (value) => void",
      "description": "Filter text, controlled."
    },
    {
      "name": "sort / defaultSort / onSortChange",
      "type": "{ id, direction } | null",
      "description": "Sort state. Header buttons cycle ascending, descending, off."
    },
    {
      "name": "pageSize",
      "type": "number",
      "default": "10",
      "description": "Rows per page. 0 turns pagination off."
    },
    {
      "name": "empty",
      "type": "ReactNode",
      "description": "Shown when data is empty. A filter with no matches shows its own message with a clear button."
    },
    {
      "name": "toolbar",
      "type": "ReactNode",
      "description": "Extra controls at the end of the toolbar."
    },
    {
      "name": "stickyHeader / density / tableClassName",
      "type": "boolean / \"default\" | \"compact\" / string",
      "description": "Passed to Table."
    }
  ],
  "accessibility": [
    "Sortable headers are buttons inside th elements that carry aria-sort (ascending, descending, or none).",
    "Checkboxes are Base UI Checkbox with an aria-label per row (\"Select run_4f2a, docs-writer\"); the header checkbox shows a mixed state when some rows on the page are selected.",
    "The row count and page range sit in a polite live region, and the filter field is described by it, so filtering announces how many rows match.",
    "Pagination buttons are labelled \"Previous page\" and \"Next page\" inside a nav named Pagination, and are disabled at the ends.",
    "A filter with no matches keeps the table structure and offers a Clear filter button."
  ],
  "states": [
    "default",
    "sorted",
    "filtered",
    "no matches",
    "empty",
    "rows selected",
    "paginated"
  ],
  "files": [
    {
      "path": "ui/data-table.tsx",
      "content": "\"use client\";\n\nimport { Checkbox } from \"@base-ui/react/checkbox\";\nimport { type ReactNode, useEffect, useId, useMemo, useState } from \"react\";\nimport { Button } from \"./button\";\nimport { Input } from \"./input\";\nimport { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from \"./table\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nexport type SortDirection = \"asc\" | \"desc\";\nexport type DataTableSort = { id: string; direction: SortDirection } | null;\ntype Sortable = string | number | boolean | Date | null | undefined;\n\nexport interface DataTableColumn<Row> {\n  /** Stable id, used for sorting state and React keys. */\n  id: string;\n  header: ReactNode;\n  /** The raw value for sorting and filtering. Defaults to `row[id]`. */\n  accessor?: (row: Row) => Sortable;\n  /** Renders the cell. Defaults to the accessor value as text. */\n  cell?: (row: Row) => ReactNode;\n  /** Shows a sort button in the header. */\n  sortable?: boolean;\n  /** Custom comparison for ascending order. */\n  sortFn?: (a: Row, b: Row) => number;\n  /** Whether the text filter searches this column. Defaults to true for string values. */\n  filterable?: boolean;\n  /** Right-aligns the column with tabular figures. */\n  numeric?: boolean;\n  /** Classes for every body cell in this column, for example a width. */\n  className?: string;\n  /** Classes for the header cell. */\n  headerClassName?: string;\n}\n\nexport interface DataTableProps<Row> {\n  columns: DataTableColumn<Row>[];\n  data: Row[];\n  /** A stable id per row, used for selection. */\n  getRowId: (row: Row) => string;\n  /** How a row is named in its checkbox label (\"Select checkout-api\"). Defaults to the row id. */\n  getRowLabel?: (row: Row) => string;\n  /** Names the table for assistive technology. Shown below the table unless `captionHidden`. */\n  caption: string;\n  captionHidden?: boolean;\n\n  /** Adds a checkbox column. */\n  selectable?: boolean;\n  /** Selected row ids (controlled). */\n  selected?: string[];\n  defaultSelected?: string[];\n  onSelectedChange?: (ids: string[]) => void;\n  /** Buttons shown in the toolbar while rows are selected, for example a bulk action. */\n  selectionActions?: (ids: string[]) => ReactNode;\n\n  /** Shows a search field that filters rows by the filterable columns. */\n  filterable?: boolean;\n  filterPlaceholder?: string;\n  /** Filter text (controlled). */\n  filter?: string;\n  onFilterChange?: (value: string) => void;\n  /** Extra controls at the end of the toolbar. */\n  toolbar?: ReactNode;\n\n  /** Sort state (controlled). `null` keeps the data order. */\n  sort?: DataTableSort;\n  defaultSort?: DataTableSort;\n  onSortChange?: (sort: DataTableSort) => void;\n\n  /** Rows per page. `0` turns pagination off. */\n  pageSize?: number;\n  /** Shown when `data` is empty. A filter with no matches has its own message. */\n  empty?: ReactNode;\n  stickyHeader?: boolean;\n  density?: \"default\" | \"compact\";\n  className?: string;\n  /** Classes for the table's scroll container, for example a max height with `stickyHeader`. */\n  tableClassName?: string;\n}\n\nfunction useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {\n  const [inner, setInner] = useState(defaultValue);\n  const controlled = value !== undefined;\n  const current = controlled ? value : inner;\n  const set = (next: T) => {\n    if (!controlled) setInner(next);\n    onChange?.(next);\n  };\n  return [current, set] as const;\n}\n\nconst collator = new Intl.Collator(undefined, { numeric: true, sensitivity: \"base\" });\n\nfunction compare(a: Sortable, b: Sortable) {\n  // Empty values sort last in both directions; the caller flips only the populated part.\n  if (a == null || a === \"\") return b == null || b === \"\" ? 0 : 1;\n  if (b == null || b === \"\") return -1;\n  if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n  if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n  if (typeof a === \"boolean\" && typeof b === \"boolean\") return Number(a) - Number(b);\n  return collator.compare(String(a), String(b));\n}\n\nfunction readValue<Row>(column: DataTableColumn<Row>, row: Row): Sortable {\n  if (column.accessor) return column.accessor(row);\n  return (row as Record<string, Sortable>)[column.id];\n}\n\n/**\n * A table with sorting, a text filter, row selection, and pagination, built on `Table`.\n * All state can be controlled or left to the component. No table library is involved; sorting\n * and filtering run in memory, which suits a few thousand rows.\n */\nexport function DataTable<Row>({\n  columns,\n  data,\n  getRowId,\n  getRowLabel,\n  caption,\n  captionHidden = false,\n  selectable = false,\n  selected: selectedProp,\n  defaultSelected = [],\n  onSelectedChange,\n  selectionActions,\n  filterable = false,\n  filterPlaceholder = \"Filter\",\n  filter: filterProp,\n  onFilterChange,\n  toolbar,\n  sort: sortProp,\n  defaultSort = null,\n  onSortChange,\n  pageSize = 10,\n  empty,\n  stickyHeader,\n  density,\n  className,\n  tableClassName,\n}: DataTableProps<Row>) {\n  const statusId = useId();\n  const [filter, setFilter] = useControllable(filterProp, \"\", onFilterChange);\n  const [sort, setSort] = useControllable<DataTableSort>(sortProp, defaultSort, onSortChange);\n  const [selected, setSelected] = useControllable(selectedProp, defaultSelected, onSelectedChange);\n  const [page, setPage] = useState(0);\n\n  const filtered = useMemo(() => {\n    const query = filter.trim().toLowerCase();\n    if (!query) return data;\n    const searchable = columns.filter((column) => column.filterable !== false);\n    return data.filter((row) =>\n      searchable.some((column) => {\n        const value = readValue(column, row);\n        if (column.filterable === undefined && typeof value !== \"string\") return false;\n        return value != null && String(value instanceof Date ? value.toISOString() : value).toLowerCase().includes(query);\n      }),\n    );\n  }, [data, columns, filter]);\n\n  const sorted = useMemo(() => {\n    if (!sort) return filtered;\n    const column = columns.find((candidate) => candidate.id === sort.id);\n    if (!column) return filtered;\n    const sign = sort.direction === \"asc\" ? 1 : -1;\n    return [...filtered].sort((a, b) => {\n      if (column.sortFn) return column.sortFn(a, b) * sign;\n      const va = readValue(column, a);\n      const vb = readValue(column, b);\n      const emptyA = va == null || va === \"\";\n      const emptyB = vb == null || vb === \"\";\n      if (emptyA || emptyB) return compare(va, vb);\n      return compare(va, vb) * sign;\n    });\n  }, [filtered, sort, columns]);\n\n  const paginated = pageSize > 0;\n  const pageCount = paginated ? Math.max(1, Math.ceil(sorted.length / pageSize)) : 1;\n  const currentPage = Math.min(page, pageCount - 1);\n  const rows = paginated ? sorted.slice(currentPage * pageSize, currentPage * pageSize + pageSize) : sorted;\n\n  // A new filter starts from the first page, so matches are never hidden on a later page.\n  useEffect(() => setPage(0), [filter]);\n\n  const selectedSet = useMemo(() => new Set(selected), [selected]);\n  const pageIds = rows.map(getRowId);\n  const pageSelected = pageIds.filter((id) => selectedSet.has(id)).length;\n  const allOnPage = pageIds.length > 0 && pageSelected === pageIds.length;\n\n  function toggleRow(id: string, checked: boolean) {\n    setSelected(checked ? [...selected.filter((value) => value !== id), id] : selected.filter((value) => value !== id));\n  }\n\n  function togglePage(checked: boolean) {\n    const ids = new Set(pageIds);\n    setSelected(checked ? [...selected.filter((id) => !ids.has(id)), ...pageIds] : selected.filter((id) => !ids.has(id)));\n  }\n\n  function cycleSort(id: string) {\n    if (sort?.id !== id) setSort({ id, direction: \"asc\" });\n    else if (sort.direction === \"asc\") setSort({ id, direction: \"desc\" });\n    else setSort(null);\n  }\n\n  const colSpan = columns.length + (selectable ? 1 : 0);\n  const showToolbar = filterable || toolbar || (selectable && selected.length > 0);\n  const first = sorted.length === 0 ? 0 : currentPage * pageSize + 1;\n  const last = paginated ? Math.min(sorted.length, (currentPage + 1) * pageSize) : sorted.length;\n  const status = filter.trim()\n    ? `${sorted.length} ${sorted.length === 1 ? \"row matches\" : \"rows match\"}`\n    : `${sorted.length} ${sorted.length === 1 ? \"row\" : \"rows\"}`;\n\n  return (\n    <div data-slot=\"data-table\" className={cx(\"grid gap-3\", className)}>\n      {showToolbar ? (\n        <div className=\"flex min-h-9 flex-wrap items-center gap-2\">\n          {filterable ? (\n            <Input\n              type=\"search\"\n              aria-label={filterPlaceholder}\n              placeholder={filterPlaceholder}\n              value={filter}\n              onChange={(event) => setFilter(event.target.value)}\n              aria-describedby={statusId}\n              containerClassName=\"w-full sm:w-64\"\n              className=\"h-8\"\n            />\n          ) : null}\n          {selectable && selected.length > 0 ? (\n            <div className=\"flex items-center gap-2 text-sm text-zinc-600 dark:text-zinc-400\">\n              <span className=\"tabular-nums\">{selected.length} selected</span>\n              <Button variant=\"ghost\" size=\"sm\" onClick={() => setSelected([])}>\n                Clear\n              </Button>\n              {selectionActions?.(selected)}\n            </div>\n          ) : null}\n          {toolbar ? <div className=\"ms-auto flex items-center gap-2\">{toolbar}</div> : null}\n        </div>\n      ) : null}\n\n      <Table framed stickyHeader={stickyHeader} density={density} containerClassName={tableClassName}>\n        <TableCaption className={captionHidden ? \"sr-only\" : undefined}>{caption}</TableCaption>\n        <TableHeader>\n          <TableRow>\n            {selectable ? (\n              <TableHead className=\"w-10 pr-0\">\n                <SelectBox\n                  label={allOnPage ? \"Deselect all rows on this page\" : \"Select all rows on this page\"}\n                  checked={allOnPage}\n                  indeterminate={pageSelected > 0 && !allOnPage}\n                  disabled={pageIds.length === 0}\n                  onCheckedChange={togglePage}\n                />\n              </TableHead>\n            ) : null}\n            {columns.map((column) => {\n              const direction = sort?.id === column.id ? sort.direction : null;\n              return (\n                <TableHead\n                  key={column.id}\n                  numeric={column.numeric}\n                  aria-sort={column.sortable ? (direction === \"asc\" ? \"ascending\" : direction === \"desc\" ? \"descending\" : \"none\") : undefined}\n                  className={cx(column.sortable && (column.numeric ? \"pr-1.5 last:pr-2.5\" : \"pl-1.5 first:pl-2.5\"), column.headerClassName)}\n                >\n                  {column.sortable ? (\n                    <button\n                      type=\"button\"\n                      onClick={() => cycleSort(column.id)}\n                      className={cx(\n                        \"group/sort -my-1 inline-flex h-7 items-center gap-1 rounded-md px-1.5 font-medium\",\n                        column.numeric && \"flex-row-reverse\",\n                        direction ? \"text-zinc-950 dark:text-white\" : \"text-zinc-500\",\n                        \"transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none\",\n                        \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n                        \"focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-sky-500\",\n                      )}\n                    >\n                      {column.header}\n                      <SortGlyph direction={direction} />\n                    </button>\n                  ) : (\n                    column.header\n                  )}\n                </TableHead>\n              );\n            })}\n          </TableRow>\n        </TableHeader>\n        <TableBody>\n          {rows.map((row) => {\n            const id = getRowId(row);\n            const isSelected = selectedSet.has(id);\n            return (\n              <TableRow key={id} selected={selectable ? isSelected : undefined}>\n                {selectable ? (\n                  <TableCell className=\"w-10 pr-0\">\n                    <SelectBox label={`Select ${getRowLabel ? getRowLabel(row) : id}`} checked={isSelected} onCheckedChange={(checked) => toggleRow(id, checked)} />\n                  </TableCell>\n                ) : null}\n                {columns.map((column) => {\n                  const value = readValue(column, row);\n                  return (\n                    <TableCell key={column.id} numeric={column.numeric} className={cx(\"whitespace-nowrap\", column.className)}>\n                      {column.cell ? column.cell(row) : value instanceof Date ? value.toLocaleDateString() : value == null ? \"\" : String(value)}\n                    </TableCell>\n                  );\n                })}\n              </TableRow>\n            );\n          })}\n          {rows.length === 0 ? (\n            <TableRow className=\"hover:bg-transparent dark:hover:bg-transparent\">\n              <TableCell colSpan={colSpan} className=\"h-40 text-center\">\n                {data.length > 0 && filter.trim() ? (\n                  <div className=\"grid justify-items-center gap-1\">\n                    <p className=\"text-sm font-medium\">No rows match “{filter.trim()}”</p>\n                    <p className=\"text-sm text-zinc-500\">Try a shorter search, or clear the filter.</p>\n                    <Button variant=\"secondary\" size=\"sm\" className=\"mt-2\" onClick={() => setFilter(\"\")}>\n                      Clear filter\n                    </Button>\n                  </div>\n                ) : (\n                  (empty ?? <p className=\"text-sm text-zinc-500\">No rows yet.</p>)\n                )}\n              </TableCell>\n            </TableRow>\n          ) : null}\n        </TableBody>\n      </Table>\n\n      <div className=\"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-zinc-500\">\n        <p id={statusId} aria-live=\"polite\" className=\"tabular-nums\">\n          {paginated && sorted.length > pageSize ? `${first} to ${last} of ${sorted.length}` : status}\n        </p>\n        {paginated && pageCount > 1 ? (\n          <nav aria-label=\"Pagination\" className=\"flex items-center gap-1\">\n            <span className=\"me-2 tabular-nums\">\n              Page {currentPage + 1} of {pageCount}\n            </span>\n            <Button\n              variant=\"secondary\"\n              size=\"sm\"\n              className=\"size-8 px-0\"\n              aria-label=\"Previous page\"\n              disabled={currentPage === 0}\n              onClick={() => setPage(currentPage - 1)}\n            >\n              <Chevron direction=\"left\" />\n            </Button>\n            <Button\n              variant=\"secondary\"\n              size=\"sm\"\n              className=\"size-8 px-0\"\n              aria-label=\"Next page\"\n              disabled={currentPage >= pageCount - 1}\n              onClick={() => setPage(currentPage + 1)}\n            >\n              <Chevron direction=\"right\" />\n            </Button>\n          </nav>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n\nfunction SelectBox({\n  label,\n  checked,\n  indeterminate = false,\n  disabled,\n  onCheckedChange,\n}: {\n  label: string;\n  checked: boolean;\n  indeterminate?: boolean;\n  disabled?: boolean;\n  onCheckedChange: (checked: boolean) => void;\n}) {\n  return (\n    <Checkbox.Root\n      aria-label={label}\n      checked={checked}\n      indeterminate={indeterminate}\n      disabled={disabled}\n      onCheckedChange={(next) => onCheckedChange(next)}\n      className={cx(\n        \"flex size-4 items-center justify-center rounded-[4px] border align-middle\",\n        \"border-zinc-950/25 bg-white dark:border-white/30 dark:bg-black\",\n        \"data-[checked]:border-zinc-950 data-[checked]:bg-zinc-950 data-[indeterminate]:border-zinc-950 data-[indeterminate]:bg-zinc-950\",\n        \"dark:data-[checked]:border-white dark:data-[checked]:bg-white dark:data-[indeterminate]:border-white dark:data-[indeterminate]:bg-white\",\n        \"transition-[background-color,border-color] duration-150 ease-out motion-reduce:transition-none\",\n        \"hover:border-zinc-950/45 dark:hover:border-white/50\",\n        \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n        \"data-[disabled]:opacity-40\",\n      )}\n    >\n      <Checkbox.Indicator\n        keepMounted\n        className={cx(\n          \"flex text-white dark:text-black\",\n          \"transition-[opacity,scale] duration-150 ease-out motion-reduce:transition-none\",\n          \"data-[unchecked]:opacity-0 motion-safe:data-[unchecked]:scale-75\",\n        )}\n      >\n        <svg aria-hidden=\"true\" viewBox=\"0 0 12 12\" fill=\"none\" className=\"size-3\">\n          {indeterminate ? (\n            <path d=\"M3 6h6\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" />\n          ) : (\n            <path d=\"M2.75 6.25 5 8.5l4.25-5\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n          )}\n        </svg>\n      </Checkbox.Indicator>\n    </Checkbox.Root>\n  );\n}\n\nfunction SortGlyph({ direction }: { direction: SortDirection | null }) {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 12 12\" fill=\"none\" className=\"size-3 shrink-0\">\n      <path\n        d=\"M3.5 4.75 6 2.25l2.5 2.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.25\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        className={cx(\n          \"transition-opacity duration-150 motion-reduce:transition-none\",\n          direction === \"asc\" ? \"opacity-100\" : direction === \"desc\" ? \"opacity-25\" : \"opacity-40 group-hover/sort:opacity-70\",\n        )}\n      />\n      <path\n        d=\"M3.5 7.25 6 9.75l2.5-2.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.25\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        className={cx(\n          \"transition-opacity duration-150 motion-reduce:transition-none\",\n          direction === \"desc\" ? \"opacity-100\" : direction === \"asc\" ? \"opacity-25\" : \"opacity-40 group-hover/sort:opacity-70\",\n        )}\n      />\n    </svg>\n  );\n}\n\nfunction Chevron({ direction }: { direction: \"left\" | \"right\" }) {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\">\n      <path\n        d={direction === \"left\" ? \"M10 3.5 5.5 8l4.5 4.5\" : \"M6 3.5 10.5 8 6 12.5\"}\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      />\n    </svg>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { Button } from \"@/components/shaken/ui/button\";\nimport { DataTable, type DataTableColumn } from \"@/components/shaken/ui/data-table\";\n\ntype Run = {\n  id: string;\n  agent: string;\n  status: \"succeeded\" | \"failed\" | \"running\" | \"waiting\";\n  durationMs: number | null;\n  tokens: number;\n  started: Date;\n};\n\nconst agents = [\"docs-writer\", \"triage\", \"release-notes\", \"migration-planner\", \"test-fixer\", \"sql-analyst\"];\nconst statuses: Run[\"status\"][] = [\"succeeded\", \"succeeded\", \"failed\", \"succeeded\", \"running\", \"succeeded\", \"waiting\", \"succeeded\"];\n\nconst runs: Run[] = Array.from({ length: 27 }, (_, i) => {\n  const status = statuses[i % statuses.length]!;\n  return {\n    id: `run_${(0x4f2a + i * 397).toString(16)}`,\n    agent: agents[(i * 5) % agents.length]!,\n    status,\n    durationMs: status === \"running\" || status === \"waiting\" ? null : 4_200 + ((i * 7_919) % 180_000),\n    tokens: 1_800 + ((i * 15_485) % 96_000),\n    started: new Date(2026, 10, 14, 9, 58 - i * 7),\n  };\n});\n\nconst tone: Record<Run[\"status\"], string> = {\n  succeeded: \"bg-emerald-500\",\n  failed: \"bg-red-500\",\n  running: \"bg-sky-500\",\n  waiting: \"bg-amber-500\",\n};\nconst label: Record<Run[\"status\"], string> = {\n  succeeded: \"Succeeded\",\n  failed: \"Failed\",\n  running: \"Running\",\n  waiting: \"Needs approval\",\n};\n\nconst time = new Intl.DateTimeFormat(\"en-US\", { hour: \"numeric\", minute: \"2-digit\" });\nconst number = new Intl.NumberFormat(\"en-US\");\n\nfunction duration(ms: number) {\n  const seconds = Math.round(ms / 1000);\n  return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, \"0\")}s`;\n}\n\nconst columns: DataTableColumn<Run>[] = [\n  {\n    id: \"id\",\n    header: \"Run\",\n    cell: (run) => <span className=\"font-mono text-xs text-zinc-600 dark:text-zinc-400\">{run.id}</span>,\n  },\n  { id: \"agent\", header: \"Agent\", sortable: true, cell: (run) => <span className=\"font-medium\">{run.agent}</span> },\n  {\n    id: \"status\",\n    header: \"Status\",\n    sortable: true,\n    accessor: (run) => label[run.status],\n    cell: (run) => (\n      <span className=\"inline-flex items-center gap-2 whitespace-nowrap text-zinc-700 dark:text-zinc-300\">\n        <span aria-hidden=\"true\" className={`size-1.5 rounded-full ${tone[run.status]}`} />\n        {label[run.status]}\n      </span>\n    ),\n  },\n  {\n    id: \"durationMs\",\n    header: \"Duration\",\n    numeric: true,\n    sortable: true,\n    cell: (run) => (run.durationMs === null ? <span className=\"text-zinc-400 dark:text-zinc-600\">In progress</span> : duration(run.durationMs)),\n  },\n  { id: \"tokens\", header: \"Tokens\", numeric: true, sortable: true, cell: (run) => number.format(run.tokens) },\n  {\n    id: \"started\",\n    header: \"Started\",\n    numeric: true,\n    sortable: true,\n    cell: (run) => <span className=\"text-zinc-600 dark:text-zinc-400\">{time.format(run.started)}</span>,\n  },\n];\n\nexport default function DataTableExample() {\n  return (\n    <DataTable\n      className=\"w-full max-w-3xl\"\n      caption=\"Agent runs today\"\n      captionHidden\n      columns={columns}\n      data={runs}\n      getRowId={(run) => run.id}\n      getRowLabel={(run) => `${run.id}, ${run.agent}`}\n      selectable\n      filterable\n      filterPlaceholder=\"Filter by run or agent\"\n      defaultSort={{ id: \"started\", direction: \"desc\" }}\n      pageSize={8}\n      selectionActions={() => (\n        <Button variant=\"secondary\" size=\"sm\">\n          Re-run\n        </Button>\n      )}\n    />\n  );\n}\n"
  }
}
