{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "table",
  "title": "Table",
  "description": "Presentational table parts on utilities: Table, TableHeader, TableBody, TableRow, TableHead, TableCell, TableCaption, TableSortHeader, TableBulkBar and TablePager, each with render and a className that may be a function of its state, plus the frame's views, toolbar, index column, expanded detail, empty/error rows and pagination. No part holds state.",
  "dependencies": [
    "@base-ui/react@1.9.0"
  ],
  "registryDependencies": [
    "@keyline-ui/keyline",
    "utils",
    "@keyline-ui/keyline-render",
    "@keyline-ui/scroll-area",
    "@keyline-ui/keyline-motion",
    "@keyline-ui/checkbox",
    "@keyline-ui/tabs",
    "@keyline-ui/status",
    "@keyline-ui/empty",
    "@keyline-ui/toolbar",
    "@keyline-ui/collection"
  ],
  "files": [
    {
      "path": "src/registry/keyline/ui/table.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { useRender } from \"@base-ui/react/use-render\";\n\nimport { cn } from \"@/lib/utils\";\nimport { resolveClassName, resolveStyle, type PartProps } from \"../lib/keyline-render\";\nimport { ScrollArea } from \"./scroll-area\";\nimport { floodHandlers, tokenMs, usePresence } from \"../lib/keyline-motion\";\nimport { Checkbox } from \"./checkbox\";\nimport { Tabs, TabsList, TabsTab } from \"./tabs\";\nimport { Status } from \"./status\";\nimport { Empty } from \"./empty\";\nimport { ToolbarButton, ToolbarGroup, useInToolbar } from \"./toolbar\";\nimport {\n  nextSort,\n  sortOf,\n  compareValues,\n  nextSortList,\n  sortLevel,\n  compareBy,\n  type Sort,\n  type SortList,\n  type SortDirection,\n} from \"../lib/collection\";\n\n/* ------------------------------------------------------------------ *\n * TABLE: presentational parts. Every part renders one element, takes `render`, a `className` and `style` that may\n * be functions of its state, and passes every other prop through; none holds state. The caller (or Data Table,\n * which wraps TanStack Table) owns sorting, selection, expansion and paging, and tells the parts through props\n * that become attributes:\n *   TableRow         data-selected, data-expanded\n *   TableSortHeader  data-sort (\"ascending\" | \"descending\"), aria-sort on the first level only\n *   TableHead/Cell   data-align=\"end\" for figures\n * The frame stacks its rows as cells: views, toolbar, bulk bar, the scrolling grid, pager.\n * ------------------------------------------------------------------ */\n\ntype Align = \"end\" | undefined;\ntype NoState = Record<string, never>;\nconst NO_STATE: NoState = {};\n\n/** The props useRender takes for a part Keyline renders: the caller's props, then the part's own, its slot last. */\nfunction part<Tag extends keyof React.JSX.IntrinsicElements, State extends object>(\n  tag: Tag,\n  slot: string,\n  base: string,\n  state: State,\n  { render, className, style, ...props }: PartProps<Tag, State>,\n  own: Record<string, unknown> = {},\n) {\n  return {\n    defaultTagName: tag,\n    render,\n    state,\n    props: mergeProps<Tag>(\n      props as never,\n      {\n        ...own,\n        className: resolveClassName(base, className)(state),\n        style: resolveStyle(undefined, style)(state),\n        \"data-slot\": slot,\n      } as never,\n    ),\n  };\n}\n\n/* ------------------------------------------------------------------ *\n * CLASSES\n * ------------------------------------------------------------------ */\n\n/** the narrow TABLE (not a narrow viewport): the frame is its own size container, kl-tf */\nconst frame = \"kl-frame kl-rows flex min-h-0 min-w-0 flex-col @container/kl-tf\";\n\n/** a row of the frame never grows or shrinks; the grid's scroller takes the frame's spare height */\nconst views = cn(\n  \"kl-cells min-h-[58px] flex-none\",\n  // the tabs scroll before the toolbar gives up its last cell, so \"More\" always stays in the row. The row reads its\n  // own children and the tabs read --kl-tv-shrink: a :has() on the row's selector for the tabs would restyle the\n  // whole document on every DOM change (see item.tsx)\n  \"[--kl-tv-shrink:0] has-[>[data-slot=table-views-end]>[data-slot=toolbar]]:[--kl-tv-shrink:1]\",\n);\nconst viewsEnd = cn(\n  \"ms-auto flex items-center gap-2.5 px-(--kl-inset)\",\n  // a cell Toolbar as the row's end: it stretches to the row's height and starts on the row's seam\n  \"has-[>[data-slot=toolbar]]:flex-[0_1_auto] has-[>[data-slot=toolbar]]:self-stretch\",\n  \"has-[>[data-slot=toolbar]]:min-w-[calc(var(--kl-row)+var(--kl-k1))] has-[>[data-slot=toolbar]]:gap-0\",\n  \"has-[>[data-slot=toolbar]]:border-s-(length:--kl-k1) has-[>[data-slot=toolbar]]:px-0\",\n  \"has-[>[data-slot=toolbar]]:border-s-kl-seam\",\n  \"*:data-[slot=toolbar]:min-h-0 *:data-[slot=toolbar]:self-stretch\",\n);\n\n/** narrow: the filters stack, one per row, each on a seam (a filter token keeps its width) */\nconst toolbar = cn(\n  \"kl-cells min-h-(--kl-row) flex-none\",\n  \"[@container_kl-tf_(max-width:560px)]:flex-wrap\",\n  \"[@container_kl-tf_(max-width:560px)]:[&>:not([data-slot=filter-token])]:flex-[1_1_100%]\",\n  \"[@container_kl-tf_(max-width:560px)]:*:max-w-none [@container_kl-tf_(max-width:560px)]:*:border-s-0\",\n  \"[@container_kl-tf_(max-width:560px)]:[&>*+*]:border-t-(length:--kl-k1)\",\n  \"[@container_kl-tf_(max-width:560px)]:[&>*+*]:border-t-kl-seam\",\n);\n\nconst search = \"kl-cell kl-edge flex-[1_1_200px] cursor-text\";\nconst searchInput = cn(\n  \"h-full min-w-0 flex-1 border-0 bg-transparent leading-[inherit] [font-weight:inherit] [font-style:inherit] outline-0\",\n  \"font-(family-name:--kl-font) text-[15px] text-inherit\",\n  \"placeholder:text-kl-ink-3 placeholder:opacity-100 [&::-webkit-search-cancel-button]:hidden\",\n);\n\nconst tokenWords = \"[&_i]:text-kl-ink-2 [&_b]:font-(--kl-weight-display)\";\n\n/** narrow: count and scope on the first line, the actions under them on a seam */\nconst bulk = cn(\n  \"group/bulk kl-cells min-h-12 flex-none\",\n  \"[:where(&>.kl-cell)]:font-(--kl-weight-strong) [:where(&>.kl-cell)]:whitespace-nowrap\",\n  \"[:where(&>button.kl-cell:disabled,&>[data-disabled])]:cursor-not-allowed\",\n  \"[:where(&>button.kl-cell:disabled,&>[data-disabled])]:text-kl-dis\",\n  // a cell Toolbar of actions: stretched to the bar, never grown; it ends on the frame's edge, which draws its last\n  // item's end (no closing filler), and its measuring slack goes before its first item\n  \"*:data-[slot=toolbar]:min-h-0 *:data-[slot=toolbar]:grow-0 *:data-[slot=toolbar]:self-stretch\",\n  \"*:data-[slot=toolbar]:last:justify-end\",\n  \"[&>[data-slot=toolbar][data-slot=toolbar][data-slot=toolbar]:last-child]:after:content-none\",\n  \"[@container_kl-tf_(max-width:560px)]:flex-wrap\",\n  \"[@container_kl-tf_(max-width:560px)]:[&>[data-slot=table-bulk-scope]~:not([hidden])]:flex-[1_1_auto]\",\n  \"[@container_kl-tf_(max-width:560px)]:[&>[data-slot=table-bulk-scope]~:not([hidden])]:border-t-(length:--kl-k1)\",\n  \"[@container_kl-tf_(max-width:560px)]:[&>[data-slot=table-bulk-scope]~:not([hidden])]:border-t-kl-seam\",\n  \"[@container_kl-tf_(max-width:560px)]:[&>[data-slot=table-bulk-scope]+:not([hidden])]:border-s-0\",\n  \"[@container_kl-tf_(max-width:560px)]:[&>[data-slot=table-bulk-scope]+[hidden]+*]:border-s-0\",\n);\nconst bulkCount = cn(\n  \"kl-cell kl-flood min-w-[104px] gap-2.5 px-[calc(var(--kl-inset)+2px)]\",\n  \"font-(--kl-weight-strong) whitespace-nowrap group-data-empty/bulk:text-kl-ink-3\",\n);\nconst bulkScope = cn(\n  \"kl-cell flex-1 flex-wrap gap-1.5 gap-y-0 text-[13px] font-(--kl-weight-strong) whitespace-nowrap\",\n  \"[&_button]:cursor-pointer [&_button]:border-0 [&_button]:bg-transparent [&_button]:p-0\",\n  \"[&_button]:text-[13px] [&_button]:leading-[inherit] [&_button]:[font-style:inherit]\",\n  \"[&_button]:font-(family-name:--kl-font) [&_button]:font-(--kl-weight-strong) [&_button]:text-kl-cobalt-text\",\n  \"[&_button]:underline [&_button]:decoration-[1.5px] [&_button]:underline-offset-[3px]\",\n  \"[@container_kl-tf_(max-width:560px)]:flex-[1_1_calc(100%-120px)]\",\n  \"[@container_kl-tf_(max-width:560px)]:py-1.5 [@container_kl-tf_(max-width:560px)]:whitespace-normal\",\n);\n\n/* The grid sits in the flow of a page, so only its inline axis is contained (a sideways swipe at the edge never\n   becomes the browser's back gesture), as the Toolbar does. The block axis chains: a wheel or trackpad scroll over\n   a table that cannot scroll that way, or has reached its edge, moves the page, and the table never rubber-bands on\n   its own. Containing both axes is for overlays (Dialog, Drawer, Select), not for regions in the flow. */\nconst scroll = \"min-h-0 flex-[1_1_auto] *:data-[slot=scroll-area-viewport]:[overscroll-behavior-inline:contain]\";\n\nconst table = \"kl-type w-full border-separate border-spacing-0 text-[14px]\";\n\nconst row = cn(\n  \"cursor-default\",\n  \"focus-visible:outline-(length:--kl-ring) focus-visible:outline-offset-(--kl-ring-in) focus-visible:outline-kl-focus focus-visible:outline-solid\",\n  // the expand column is part of the row's tone\n  \"hover:not-data-selected:[&>:is([data-slot=table-cell],[data-slot=table-expand-cell])]:bg-kl-tint\",\n  \"data-selected:[&>:is([data-slot=table-cell],[data-slot=table-expand-cell])]:bg-kl-yellow-row\",\n  \"data-selected:hover:[&>:is([data-slot=table-cell],[data-slot=table-expand-cell])]:bg-[color-mix(in_oklab,var(--kl-yellow-row),var(--kl-ink)_6%)]\",\n  \"data-expanded:[&>:is([data-slot=table-cell],[data-slot=table-expand-cell])]:border-b-kl-line\",\n  // useRowMotion: the leading edge of an opening (returning rows) is the keyline the row below carries on its top\n  \"data-kl-opening:*:[box-shadow:inset_0_var(--kl-k1)_var(--kl-line-soft)]\",\n  \"forced-colors:data-selected:[&>[data-slot=table-cell]:nth-child(2)]:underline\",\n  \"forced-colors:data-selected:[&>[data-slot=table-cell]:nth-child(2)]:decoration-2\",\n);\n\n/** a header cell: sticky to the scroller's top, on a seam from the header cell before it */\nconst head = cn(\n  \"sticky top-0 z-2 h-[34px] border-b-(length:--kl-k1) border-b-kl-line bg-kl-cell px-(--kl-inset) py-0\",\n  \"text-start text-[12px] font-(--kl-weight-strong) whitespace-nowrap text-kl-ink-2\",\n  \"[:is([data-slot=table-head],[data-slot=table-sort-header])+&]:border-s-(length:--kl-k1)\",\n  \"[:is([data-slot=table-head],[data-slot=table-sort-header])+&]:border-s-kl-line-soft\",\n  \"data-[align=end]:text-end data-[align=end]:tabular-nums [&_.kl-code]:ms-1\",\n);\n\n/* SORTABLE HEADER: the button fills the header cell; the sorted column's header carries an ink band laid on its\n   bottom keyline (the border turns ink and an inset shadow thickens it upward, so nothing moves). A later sort\n   level keeps the seam weight, so the first level reads as the order. */\nconst sortHeader = cn(\n  head,\n  \"p-0 data-sort:border-b-kl-inverse data-sort:text-kl-ink\",\n  \"data-sort:shadow-[inset_0_calc(var(--kl-k1)-var(--kl-k2))_0_var(--kl-inverse)]\",\n  \"data-kl-level:not-data-[kl-level=1]:shadow-none\",\n  \"forced-colors:data-sort:border-b-[CanvasText] forced-colors:data-sort:underline\",\n  \"forced-colors:data-sort:decoration-2 forced-colors:data-sort:shadow-none\",\n);\nconst sortButton = cn(\n  \"m-0 box-border flex h-full min-h-[34px] w-full cursor-pointer items-center gap-1.5 border-0 bg-transparent px-(--kl-inset) py-0\",\n  \"[text-align:inherit] leading-[inherit] [font-weight:inherit] text-inherit [font-style:inherit]\",\n  \"hover:bg-kl-tint hover:text-kl-ink active:*:translate-y-px\",\n  \"focus-visible:outline-(length:--kl-ring) focus-visible:outline-offset-(--kl-ring-in) focus-visible:outline-kl-focus focus-visible:outline-solid\",\n  \"in-data-[align=end]:flex-row-reverse in-data-[align=end]:justify-start\",\n);\n/* the mark is two triangles: both open when unsorted, one filled when sorted (the other a faint outline), so the\n   direction is a shape, not a colour, and the glyph never moves */\nconst sortMark = \"group/sort grid flex-none place-items-center data-[dir=none]:text-kl-ink-3\";\nconst sortPath = cn(\n  \"fill-none stroke-current [stroke-width:1.25] [stroke-linejoin:miter]\",\n  \"forced-colors:stroke-[CanvasText] forced-colors:[forced-color-adjust:none]\",\n);\nconst sortUp = cn(\n  sortPath,\n  \"group-data-[dir=ascending]/sort:fill-current group-data-[dir=descending]/sort:stroke-kl-ink-3\",\n  \"forced-colors:group-data-[dir=ascending]/sort:fill-[CanvasText]\",\n);\nconst sortDown = cn(\n  sortPath,\n  \"group-data-[dir=ascending]/sort:stroke-kl-ink-3 group-data-[dir=descending]/sort:fill-current\",\n  \"forced-colors:group-data-[dir=descending]/sort:fill-[CanvasText]\",\n);\n\nconst cell = cn(\n  \"h-(--kl-row) border-b-(length:--kl-k1) border-b-kl-line-soft px-(--kl-inset) py-0 whitespace-nowrap\",\n  \"[[data-slot=table-cell]+&]:border-s-(length:--kl-k1) [[data-slot=table-cell]+&]:border-s-kl-line-soft\",\n  \"data-[align=end]:text-end data-[align=end]:tabular-nums\",\n  // a button in a body cell nearly fills the row: an outside ring would cross the row keylines (and the scroller clips it\n  // in the last row), so like every cell it takes the inset ring\n  \"[&_[data-slot=button]:focus-visible]:outline-offset-(--kl-ring-in)\",\n);\n\nconst caption = \"caption-top px-(--kl-inset) py-2 text-start text-[13px] text-kl-ink-2\";\n\n/** the index column: the ink spine. Its flood owns the selected fill, so the cell's own fill is set only while off. */\nconst indexCell = cn(\n  \"group/ix kl-flood w-[72px] border-e-(length:--kl-k1) border-b-(length:--kl-k1) border-e-kl-line\",\n  \"border-b-kl-line-soft p-0 align-top not-data-kl-on:bg-kl-cell\",\n);\nconst indexHead = \"sticky top-0 z-3 border-b-kl-line align-middle\";\n/* KEY: pressing anywhere in the cell presses its checkbox (an empty box darkens, a tick travels 1px) */\nconst indexLabel = cn(\n  \"flex h-(--kl-row) min-h-[34px] cursor-pointer items-center gap-2.5 px-3\",\n  \"active:[&_[data-slot=checkbox]:not([data-disabled],[data-checked],[data-indeterminate])]:bg-kl-press\",\n  \"active:[&_[data-slot=checkbox]:not([data-disabled])>[data-slot=checkbox-indicator]]:translate-y-px\",\n);\nconst indexCode = \"kl-code group-data-kl-on/ix:font-(--kl-weight-strong) group-data-kl-on/ix:text-inherit\";\n\nconst expandCell = cn(\n  \"w-11 border-b-(length:--kl-k1) border-b-kl-line-soft p-0\",\n  \"[[data-slot=table-cell]+&]:border-s-(length:--kl-k1) [[data-slot=table-cell]+&]:border-s-kl-line-soft\",\n);\n/* the cell's width is only a hint in auto table layout: when the table overflows its scroller the column would\n   shrink to the glyph. A minimum on the button is the column's minimum content width, which layout keeps. A button\n   nearly filling the row takes the inset ring, so it never crosses the row's keyline. */\nconst expandButton = cn(\n  \"group/xp grid h-(--kl-row) w-full min-w-11 cursor-pointer place-items-center border-0 bg-transparent text-kl-ink-2\",\n  \"hover:bg-kl-tint hover:text-kl-ink active:bg-kl-press active:text-kl-ink active:*:translate-y-px\",\n  \"focus-visible:outline-offset-(--kl-ring-in) aria-expanded:text-kl-ink\",\n);\nconst expandGlyph = cn(\n  \"[transition:rotate_var(--kl-t-unfold)_var(--kl-ease-out)] group-aria-expanded/xp:[rotate:90deg]\",\n  \"kl-rtl:[scale:-1_1] kl-rtl:group-aria-expanded/xp:[rotate:-90deg]\",\n);\n\nconst detailCell = \"border-b-(length:--kl-k1) border-b-kl-seam bg-kl-paper p-0 whitespace-normal\";\n\nconst loadingBar = cn(\n  \"relative block h-2.5 overflow-hidden border-(length:--kl-k1) border-kl-line-soft bg-kl-tint\",\n  \"after:absolute after:inset-y-0 after:left-0 after:w-[30%] after:bg-kl-line-soft after:content-['']\",\n  \"after:animate-[kl-run-30_1100ms_linear_infinite_var(--kl-run-dir,normal)]\",\n  \"in-data-[kl-motion=reduce]:after:hidden in-data-[kl-motion=reduce]:after:animate-none\",\n  \"motion-reduce:after:hidden motion-reduce:after:animate-none\",\n);\n\nconst pager = \"kl-cells min-h-12 flex-none [&_.kl-count]:text-[20px]\";\nconst pageButton = \"kl-cell kl-key w-11 flex-none justify-center text-[20px]\";\nconst pageGlyph = \"inline-block kl-rtl:[scale:-1_1]\";\n\n/* ------------------------------------------------------------------ *\n * FRAME\n * ------------------------------------------------------------------ */\n\n/** The table is one region frame. Views, toolbar, bulk bar, the grid and the pager are rows stacked inside it. */\nfunction TableFrame(props: PartProps<\"section\", NoState>): React.ReactElement {\n  return useRender(part(\"section\", \"table-frame\", frame, NO_STATE, props));\n}\n\ntype View = { value: string; label: React.ReactNode; count?: React.ReactNode };\ntype TableViewsProps = Omit<PartProps<\"div\", NoState>, \"onChange\"> & {\n  views: View[];\n  value: string;\n  onValueChange: (value: string) => void;\n  /** the tab list's name */\n  label?: string;\n};\n\n/** The table's view tabs (built on Tabs, so keyboard and aria come from Base UI), then an end slot. */\nfunction TableViews({\n  views: items,\n  value,\n  onValueChange,\n  label = \"Views\",\n  children,\n  ...props\n}: TableViewsProps): React.ReactElement {\n  const content = (\n    <>\n      <Tabs\n        value={value}\n        onValueChange={(v) => onValueChange(v as string)}\n        className=\"flex flex-[0_var(--kl-tv-shrink,0)_auto] gap-0\"\n      >\n        <TabsList\n          layout=\"cell\"\n          aria-label={label}\n          className=\"bg-transparent [&>[data-orientation][data-orientation]]:min-w-[112px]\"\n        >\n          {items.map((v) => (\n            <TabsTab key={v.value} value={v.value} count={v.count}>\n              {v.label}\n            </TabsTab>\n          ))}\n        </TabsList>\n      </Tabs>\n      {children ? (\n        <div data-slot=\"table-views-end\" className={viewsEnd}>\n          {children}\n        </div>\n      ) : null}\n    </>\n  );\n  return useRender(part(\"div\", \"table-views\", views, NO_STATE, { ...props, children: content }));\n}\n\n/**\n * The filter row: search and pickers (Multiselect, DateRangePicker) side by side as cells. It is a named group, not\n * a Toolbar, on purpose: a combobox and a picker own their arrow keys (to move in the text, to open and walk the\n * list), so they cannot be items of a one-Tab-stop toolbar. Rows of plain commands and toggles are: the views row's\n * end, the status row and the bulk bar's actions take a cell Toolbar, and a FilterToken inside a Toolbar becomes a\n * pair of toolbar items.\n */\nfunction TableToolbar(props: PartProps<\"div\", NoState>): React.ReactElement {\n  return useRender(part(\"div\", \"table-toolbar\", toolbar, NO_STATE, props, { role: \"group\" }));\n}\n\ntype TableSearchProps = Omit<React.ComponentProps<\"input\">, \"type\"> & {\n  /** the field's name, read but not shown */\n  label?: string;\n  /** classes for the cell around the input; `className` goes to the input */\n  cellClassName?: string;\n};\n\n/** A search field as a cell of the toolbar. `className`, `ref` and the input's props go to the input. */\nfunction TableSearch({ className, cellClassName, label = \"Search\", ...props }: TableSearchProps): React.ReactElement {\n  return (\n    <label data-slot=\"table-search\" className={cn(search, cellClassName)}>\n      <svg\n        viewBox=\"0 0 16 16\"\n        width=\"16\"\n        height=\"16\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.75\"\n        strokeLinecap=\"square\"\n        aria-hidden\n      >\n        <circle cx=\"7\" cy=\"7\" r=\"4.5\" />\n        <path d=\"m10.5 10.5 3.5 3.5\" />\n      </svg>\n      <span className=\"kl-sr\">{label}</span>\n      <input type=\"search\" {...props} className={cn(searchInput, className)} />\n    </label>\n  );\n}\n\nconst RemoveGlyph = () => (\n  <svg\n    viewBox=\"0 0 16 16\"\n    width=\"14\"\n    height=\"14\"\n    fill=\"none\"\n    stroke=\"currentColor\"\n    strokeWidth=\"2\"\n    strokeLinecap=\"square\"\n    aria-hidden\n  >\n    <path d=\"m4.5 4.5 7 7m0-7-7 7\" />\n  </svg>\n);\n\n/** A filter as a token: `field op value`, pressed to edit, with a remove cell. Inside a Toolbar it is a group of two\n *  toolbar items (one Tab stop for the row); elsewhere, two cells. */\nfunction FilterToken({\n  field,\n  op,\n  value,\n  onRemove,\n  onEdit,\n  className,\n}: {\n  field: string;\n  op: string;\n  value: React.ReactNode;\n  onRemove?: () => void;\n  onEdit?: () => void;\n  className?: string;\n}): React.ReactElement {\n  const inToolbar = useInToolbar();\n  const editLabel = `Edit filter: ${field} ${op} ${typeof value === \"string\" ? value : \"\"}`.trim();\n  const words = (\n    <>\n      <span className=\"kl-code\">{field}</span>\n      <i>{op}</i>\n      <b>{value}</b>\n    </>\n  );\n  if (inToolbar) {\n    return (\n      <ToolbarGroup\n        keepTogether\n        aria-label={`${field} filter`}\n        data-kl-token=\"\"\n        className={cn(\n          tokenWords,\n          \"[&_[data-kl-tb-item]:not([data-kl-token-x])]:font-normal [&_[data-slot=toolbar-label]]:gap-1.5\",\n          className,\n        )}\n      >\n        <ToolbarButton onClick={onEdit} aria-label={editLabel}>\n          {words}\n        </ToolbarButton>\n        {onRemove ? (\n          <ToolbarButton icon data-kl-token-x=\"\" onClick={onRemove} aria-label={`Remove ${field} filter`}>\n            <RemoveGlyph />\n          </ToolbarButton>\n        ) : null}\n      </ToolbarGroup>\n    );\n  }\n  return (\n    <div data-slot=\"filter-token\" className={cn(\"kl-cells flex-none\", tokenWords, className)}>\n      <button\n        type=\"button\"\n        className=\"kl-cell kl-key gap-1.5 whitespace-nowrap\"\n        onClick={onEdit}\n        aria-label={`Edit filter: ${field} ${op} ${typeof value === \"string\" ? value : \"\"}`}\n      >\n        {words}\n      </button>\n      {onRemove ? (\n        <button type=\"button\" className=\"kl-cell px-2.5\" onClick={onRemove} aria-label={`Remove ${field} filter`}>\n          <RemoveGlyph />\n        </button>\n      ) : null}\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------ *\n * BULK BAR: the working set\n * ------------------------------------------------------------------ */\n\ntype TableBulkBarState = { count: number };\ntype TableBulkBarProps = PartProps<\"div\", TableBulkBarState> & {\n  /** how many rows are selected; 0 empties the bar (its count goes quiet) */\n  count: number;\n  /** what the selection covers (\"3 of 64 on this page\"), and the ways to widen or narrow it */\n  scope?: React.ReactNode;\n};\n\n/** The bulk bar: the selected count (floods yellow while rows are selected), its scope, then the actions. Changes\n *  to it are announced politely. */\nfunction TableBulkBar({ count, scope, children, ...props }: TableBulkBarProps): React.ReactElement {\n  const content = (\n    <>\n      <div data-slot=\"table-bulk-count\" className={bulkCount} data-kl-on={count > 0 ? \"\" : undefined}>\n        <span className=\"kl-count text-[26px]\">{count}</span>\n        <span className=\"kl-code\">SELECTED</span>\n      </div>\n      <div data-slot=\"table-bulk-scope\" className={bulkScope}>\n        {scope}\n      </div>\n      {children}\n    </>\n  );\n  return useRender(\n    part(\n      \"div\",\n      \"table-bulk-bar\",\n      bulk,\n      { count },\n      { ...props, children: content },\n      { \"aria-live\": \"polite\", \"data-empty\": count === 0 ? \"\" : undefined },\n    ),\n  );\n}\n\n/* ------------------------------------------------------------------ *\n * GRID\n * ------------------------------------------------------------------ */\n\n/** The grid's scroller: a Keyline Scroll Area with both bars (wide tables scroll sideways inside their frame, never\n *  the page); the header cells stick to its viewport. */\nfunction TableScroll({ className, children, ...props }: React.ComponentProps<typeof ScrollArea>): React.ReactElement {\n  return (\n    <ScrollArea data-slot=\"table-scroll\" scrollbars=\"both\" className={cn(scroll, className as string)} {...props}>\n      {children}\n    </ScrollArea>\n  );\n}\n\nfunction Table(props: PartProps<\"table\", NoState>): React.ReactElement {\n  return useRender(part(\"table\", \"table\", table, NO_STATE, props));\n}\n\nfunction TableHeader(props: PartProps<\"thead\", NoState>): React.ReactElement {\n  return useRender(part(\"thead\", \"table-header\", \"\", NO_STATE, props));\n}\n\nfunction TableBody(props: PartProps<\"tbody\", NoState>): React.ReactElement {\n  return useRender(part(\"tbody\", \"table-body\", \"\", NO_STATE, props));\n}\n\ntype TableRowState = { selected: boolean; expanded: boolean };\ntype TableRowProps = PartProps<\"tr\", TableRowState> & {\n  /** writes data-selected: the row's cells take the selected fill */\n  selected?: boolean;\n  /** writes data-expanded: its detail row is open under it, so its cells end on a full keyline */\n  expanded?: boolean;\n};\n\nfunction TableRow({ selected = false, expanded = false, ...props }: TableRowProps): React.ReactElement {\n  return useRender(\n    part(\"tr\", \"table-row\", row, { selected, expanded }, props, {\n      \"data-selected\": selected ? \"\" : undefined,\n      \"data-expanded\": expanded ? \"\" : undefined,\n    }),\n  );\n}\n\ntype TableHeadState = { align: Align };\ntype TableHeadProps = Omit<PartProps<\"th\", TableHeadState>, \"align\"> & {\n  /** \"end\" for a column of figures: the label aligns with the numbers' edge */\n  align?: Align;\n};\n\n/** A header cell. */\nfunction TableHead({ align, ...props }: TableHeadProps): React.ReactElement {\n  return useRender(part(\"th\", \"table-head\", head, { align }, props, { \"data-align\": align }));\n}\n\ntype TableSortHeaderState = { sort: SortDirection | null; priority: number | undefined };\ntype TableSortHeaderProps = Omit<PartProps<\"th\", TableSortHeaderState>, \"align\" | \"onClick\"> & {\n  align?: Align;\n  /** the column's direction, or null when it does not sort the table */\n  sort: SortDirection | null;\n  /** the header was pressed; `additive` is true when Shift was held (add the column as a further level) */\n  onSort: (event: { additive: boolean }) => void;\n  /** with several sort levels: this column's 1-based place */\n  priority?: number;\n  /** with several sort levels: how many columns sort */\n  levels?: number;\n};\n\n/**\n * A sortable column header. The whole header cell is the button; aria-sort sits on the <th>. The direction is a\n * shape (▲ ascending, ▼ descending, both open when unsorted), and the sorted column's header carries an ink band on\n * its bottom keyline. End-aligned (numeric) columns put the mark before the label, so the label stays on the\n * numbers' edge. Use nextSort/sortOf from the collection lib for the cycle (ascending → descending → none).\n *\n * Several columns: pass `priority` (1-based) and `levels`. Each sorted header prints its place; `onSort` gets\n * `{ additive }`, true when Shift was held, for nextSortList. ARIA allows aria-sort on one header at a time, so only\n * the first level carries it; every sorted header's button also says its place (\"sort 2 of 2, descending\") in text.\n */\nfunction TableSortHeader({\n  align,\n  sort,\n  onSort,\n  priority,\n  levels,\n  children,\n  ...props\n}: TableSortHeaderProps): React.ReactElement {\n  const multi = sort != null && priority != null && (levels ?? 2) > 1;\n  const ariaSort = sort == null ? \"none\" : multi && priority !== 1 ? undefined : sort;\n  const content = (\n    <button\n      type=\"button\"\n      data-slot=\"table-sort-button\"\n      className={sortButton}\n      onClick={(e) => onSort({ additive: e.shiftKey })}\n    >\n      <span data-slot=\"table-sort-label\" className=\"min-w-0 overflow-hidden text-ellipsis\">\n        {children}\n      </span>\n      <span data-slot=\"table-sort-mark\" className={sortMark} data-dir={sort ?? \"none\"} aria-hidden>\n        <svg viewBox=\"0 0 12 16\" width=\"10\" height=\"14\">\n          <path className={sortUp} d=\"M6 1.5 10.5 7h-9z\" />\n          <path className={sortDown} d=\"M6 14.5 1.5 9h9z\" />\n        </svg>\n      </span>\n      {multi ? (\n        <>\n          <span className=\"kl-code\" data-slot=\"table-sort-level\" aria-hidden>\n            {priority}\n          </span>\n          <span className=\"kl-sr\">\n            , sort {priority} of {levels ?? priority}, {sort}\n          </span>\n        </>\n      ) : null}\n    </button>\n  );\n  return useRender(\n    part(\n      \"th\",\n      \"table-sort-header\",\n      sortHeader,\n      { sort, priority },\n      { ...props, children: content },\n      {\n        \"data-align\": align,\n        \"data-sort\": sort ?? undefined,\n        \"data-kl-level\": multi ? priority : undefined,\n        \"aria-sort\": ariaSort,\n      },\n    ),\n  );\n}\n\ntype TableCellProps = Omit<PartProps<\"td\", TableHeadState>, \"align\"> & {\n  /** \"end\" for figures: aligned to the end, with tabular numerals */\n  align?: Align;\n};\n\n/** A body cell. To make it the row's header, render it as one: `render={<th scope=\"row\" />}`. */\nfunction TableCell({ align, ...props }: TableCellProps): React.ReactElement {\n  return useRender(part(\"td\", \"table-cell\", cell, { align }, props, { \"data-align\": align }));\n}\n\n/** The table's caption: its name, read before its rows. Hide it with `className=\"kl-sr\"` when a heading already\n *  shows the name. */\nfunction TableCaption(props: PartProps<\"caption\", NoState>): React.ReactElement {\n  return useRender(part(\"caption\", \"table-caption\", caption, NO_STATE, props));\n}\n\n/** Index cell: selection checkbox + row code. Floods yellow from the press point when the row is selected. */\nfunction TableIndexCell({\n  checked,\n  indeterminate,\n  onCheckedChange,\n  code,\n  label,\n  header,\n  rowSpan,\n  className,\n}: {\n  checked: boolean;\n  indeterminate?: boolean;\n  /** the new value; `eventDetails` is Base UI's checkbox change details (its `event` carries Shift) */\n  onCheckedChange: (checked: boolean, eventDetails: Parameters<NonNullable<CheckboxChange>>[1]) => void;\n  code?: React.ReactNode;\n  label: string;\n  header?: boolean;\n  rowSpan?: number;\n  className?: string;\n}): React.ReactElement {\n  const Tag = header ? \"th\" : \"td\";\n  return (\n    <Tag\n      rowSpan={rowSpan}\n      data-slot=\"table-index-cell\"\n      className={cn(indexCell, header && indexHead, className)}\n      data-kl-on={checked && !header ? \"\" : undefined}\n      {...floodHandlers}\n    >\n      {/* oxlint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions -- only stops the press reaching the row; the checkbox inside handles keys */}\n      <label className={cn(indexLabel, header && \"h-[34px]\")} onClick={(e) => e.stopPropagation()}>\n        <Checkbox\n          checked={checked}\n          indeterminate={indeterminate}\n          onCheckedChange={(v, details) => onCheckedChange(!!v, details)}\n          aria-label={label}\n        />\n        {code != null ? <span className={indexCode}>{code}</span> : null}\n      </label>\n    </Tag>\n  );\n}\ntype CheckboxChange = React.ComponentProps<typeof Checkbox>[\"onCheckedChange\"];\n\n/** The expand toggle column. `header` renders the column's header cell (labelled, empty); with neither, an empty\n *  cell keeps the column in a row that has no detail. */\nfunction TableExpandCell(\n  props:\n    | { header: true; label?: string }\n    | { header?: false; expanded: boolean; onToggle: () => void; label: string }\n    | { header?: false; expanded?: undefined },\n): React.ReactElement {\n  if (props.header)\n    return (\n      <th data-slot=\"table-expand-cell\" className={expandCell}>\n        <span className=\"kl-sr\">{props.label ?? \"Expand\"}</span>\n      </th>\n    );\n  if (props.expanded === undefined) return <td data-slot=\"table-expand-cell\" className={expandCell} />;\n  const { expanded, onToggle, label } = props;\n  return (\n    <td data-slot=\"table-expand-cell\" className={expandCell}>\n      <button\n        type=\"button\"\n        className={expandButton}\n        aria-expanded={expanded}\n        aria-label={label}\n        onClick={(e) => (e.stopPropagation(), onToggle())}\n      >\n        <svg\n          viewBox=\"0 0 16 16\"\n          width=\"16\"\n          height=\"16\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth=\"1.75\"\n          strokeLinecap=\"square\"\n          className={expandGlyph}\n          aria-hidden\n        >\n          <path d=\"m6 4 4 4-4 4\" />\n        </svg>\n      </button>\n    </td>\n  );\n}\n\n/**\n * Expanded detail. UNFOLDS from the row's bottom keyline; the row never moves. The parent row's index cell spans\n * this row (rowSpan=2 while `presence.mounted`), so object and detail share one index cell. The caller holds the\n * presence: `const presence = useDetailPresence(open)`.\n */\nfunction TableDetail({\n  presence,\n  colSpan,\n  children,\n  id,\n}: {\n  presence: { mounted: boolean; shown: boolean };\n  colSpan: number;\n  children: React.ReactNode;\n  id?: string;\n}): React.ReactElement | null {\n  if (!presence.mounted) return null;\n  return (\n    <tr data-slot=\"table-detail\" id={id}>\n      <td colSpan={colSpan} className={detailCell}>\n        <div className=\"kl-unfold\" data-open={presence.shown ? \"\" : undefined}>\n          <div>{children}</div>\n        </div>\n      </td>\n    </tr>\n  );\n}\n\n/**\n * ROWS THAT LEAVE OR COME BACK. Put `ref` on TableBody and call `arm()` just before a change that removes rows or\n * puts them back (a cancellation, its Undo). On the next commit only:\n *   - the rows that stayed slide from where they were, so the gap a removal leaves closes (fold timing) and the room\n *     a returning row needs opens (unfold timing);\n *   - a returning row unfolds from the keyline above it, in step with the rows below it making room;\n *   - rows arriving at the end (from the next page) come up with the rows above them.\n * Nothing else moves: filtering, sorting and paging stay instant, because arm() is never called for them. Rows move\n * inside the table's scroller; the frame, header and pager never move. Reduced motion: instant.\n */\nfunction useRowMotion() {\n  const ref = React.useRef<HTMLTableSectionElement>(null);\n  const armed = React.useRef<Map<Element, number> | null>(null);\n  const arm = React.useCallback(() => {\n    const body = ref.current;\n    if (!body) return;\n    const tops = new Map<Element, number>();\n    for (const tr of Array.from(body.children)) tops.set(tr, tr.getBoundingClientRect().top);\n    armed.current = tops;\n  }, []);\n  React.useLayoutEffect(() => {\n    const before = armed.current;\n    const body = ref.current;\n    if (!before || !body) return;\n    armed.current = null;\n    const open = tokenMs(body, \"--kl-t-unfold\", 160);\n    const close = tokenMs(body, \"--kl-t-fold\", 120);\n    if (!open) return;\n    const ease = getComputedStyle(body).getPropertyValue(\"--kl-ease-out\").trim() || \"ease-out\";\n    const rows = Array.from(body.children) as HTMLElement[];\n    const boxes = rows.map((r) => r.getBoundingClientRect());\n    const slide = (r: HTMLElement, dy: number) =>\n      Math.abs(dy) > 0.5 &&\n      r.animate([{ transform: `translateY(${dy}px)` }, { transform: \"none\" }], {\n        duration: dy > 0 ? close : open,\n        easing: ease,\n      });\n    let carry = 0; // where the nearest row above that stayed was, relative to where it is now\n    const stayed = (k: number) => {\n      const r = rows[k];\n      return r !== undefined && before.has(r);\n    };\n    for (let i = 0; i < rows.length;) {\n      const row = rows[i];\n      const box = boxes[i];\n      if (!row || !box) break;\n      const was = before.get(row);\n      if (was != null) {\n        carry = was - box.top;\n        slide(row, carry);\n        i++;\n        continue;\n      }\n      // a run of rows that were not there: the room for the whole run opens as one, from the keyline above it\n      let j = i;\n      while (j < rows.length && !stayed(j)) j++;\n      const next = rows[j];\n      const runEnd = boxes[j - 1];\n      if (next && runEnd) {\n        const top = box.top;\n        const H = runEnd.bottom - top;\n        for (let k = i; k < j; k++) {\n          const r = rows[k];\n          const b = boxes[k];\n          if (!r || !b) continue;\n          const h = b.height;\n          const o = Math.min(1, (b.top - top) / H);\n          const e = Math.min(1, (b.bottom - top) / H);\n          // carried with the row above; clipped where the opening has reached (top-anchored, like a fold)\n          const at = (t: number, inset: number) => ({\n            offset: t,\n            transform: `translateY(${carry * (1 - t)}px)`,\n            clipPath: `inset(0 0 ${inset}px 0)`,\n          });\n          r.animate([at(0, h), at(o, h), at(e, 0), at(1, 0)], { duration: open, easing: ease });\n        }\n        // the opening's leading edge is a keyline: the row below the run carries one on its top while it travels\n        next.setAttribute(\"data-kl-opening\", \"\");\n        setTimeout(() => next.removeAttribute(\"data-kl-opening\"), open);\n      } else for (const r of rows.slice(i, j)) slide(r, carry); // arrived at the end (from the next page): up with the rows above\n      i = j;\n    }\n  });\n  return { ref, arm };\n}\n\n/** Presence for a row's detail (TableDetail's `presence`): the row keeps its merged index cell (rowSpan) until the\n *  fold finishes. */\nconst useDetailPresence = (open: boolean) => usePresence(open);\n\n/* ------------------------------------------------------------------ *\n * STATES\n * ------------------------------------------------------------------ */\n\n/** The table's empty or error row: an Empty (layout=\"cell\") spanning the grid. Errors are announced. */\nfunction TableState({\n  kind,\n  count,\n  title,\n  body,\n  action,\n  colSpan,\n}: {\n  kind: \"empty\" | \"error\";\n  count: React.ReactNode;\n  title: React.ReactNode;\n  body?: React.ReactNode;\n  action?: React.ReactNode;\n  colSpan: number;\n}): React.ReactElement {\n  return (\n    <tr data-slot=\"table-state\">\n      <td colSpan={colSpan} className=\"p-0\">\n        <Empty\n          layout=\"cell\"\n          kind={kind}\n          count={count}\n          title={title}\n          description={body}\n          actions={action}\n          live={kind === \"error\"}\n          className=\"min-h-[240px] whitespace-normal\"\n        />\n      </td>\n    </tr>\n  );\n}\n\n/** Rows standing in while data loads: hidden from assistive technology (the frame says it is busy). */\nfunction TableLoadingRows({ rows = 8, cols }: { rows?: number; cols: number }): React.ReactElement {\n  return (\n    <>\n      {Array.from({ length: rows }, (_, r) => (\n        <TableRow key={r} data-slot=\"table-loading-row\" aria-hidden>\n          {Array.from({ length: cols }, (_, c) =>\n            c === 0 ? (\n              <td key={c} className={cn(indexCell, \"px-3 align-middle\")}>\n                <span className=\"kl-code\">{String(r + 1).padStart(2, \"0\")}</span>\n              </td>\n            ) : (\n              <TableCell key={c}>\n                <span\n                  data-slot=\"table-loading-bar\"\n                  className={loadingBar}\n                  style={{ width: `${40 + ((r * 7 + c * 13) % 45)}%` }}\n                />\n              </TableCell>\n            ),\n          )}\n        </TableRow>\n      ))}\n    </>\n  );\n}\n\n/* ------------------------------------------------------------------ *\n * PAGER\n * ------------------------------------------------------------------ */\n\n/** The pager row: cells for the range, the page and the page buttons. */\nfunction TablePager(props: PartProps<\"div\", NoState>): React.ReactElement {\n  return useRender(part(\"div\", \"table-pager\", pager, NO_STATE, props));\n}\n\n/**\n * Range + previous / page / next as cells of the pager. `page` is 0-based. While data is not ready, pass\n * `total={null}`: the range and page count show \"–\" and the buttons are disabled (no stale numbers).\n */\nfunction TablePagination({\n  page,\n  pageSize,\n  total,\n  onPageChange,\n  noun = \"rows\",\n  children,\n  className,\n}: {\n  page: number;\n  pageSize: number;\n  total: number | null;\n  onPageChange: (page: number) => void;\n  noun?: string;\n  /** Fills the cell between the range and the buttons, e.g. <ToastDock />. */\n  children?: React.ReactNode;\n  className?: string;\n}): React.ReactElement {\n  const pages = total == null ? 0 : Math.max(1, Math.ceil(total / pageSize));\n  const from = total ? page * pageSize + 1 : 0;\n  const to = total == null ? 0 : Math.min(total, (page + 1) * pageSize);\n  return (\n    <TablePager className={className}>\n      <span data-slot=\"table-range\" className=\"kl-cell flex-none tabular-nums\">\n        {total == null ? (\n          \"–\"\n        ) : (\n          <>\n            <bdi>\n              {from}–{to}\n            </bdi>\n            &nbsp;of&nbsp;<b>{total.toLocaleString()}</b>&nbsp;{noun}\n          </>\n        )}\n      </span>\n      {children ? (\n        <div className=\"kl-cell flex min-w-0 flex-1 items-stretch p-0 *:flex-1\">{children}</div>\n      ) : (\n        <span className=\"min-w-0 flex-1 p-0\" />\n      )}\n      <button\n        type=\"button\"\n        className={pageButton}\n        disabled={total == null || page === 0}\n        onClick={() => onPageChange(page - 1)}\n        aria-label=\"Previous page\"\n      >\n        <span className={pageGlyph} aria-hidden>\n          ‹\n        </span>\n      </button>\n      <span className=\"kl-cell kl-code flex-none\" aria-live=\"polite\">\n        {total == null ? \"–\" : `${page + 1}/${pages}`}\n      </span>\n      <button\n        type=\"button\"\n        className={pageButton}\n        disabled={total == null || page >= pages - 1}\n        onClick={() => onPageChange(page + 1)}\n        aria-label=\"Next page\"\n      >\n        <span className={pageGlyph} aria-hidden>\n          ›\n        </span>\n      </button>\n    </TablePager>\n  );\n}\n\nexport {\n  TableFrame,\n  TableViews,\n  TableToolbar,\n  TableSearch,\n  FilterToken,\n  TableBulkBar,\n  TableScroll,\n  Table,\n  TableHeader,\n  TableBody,\n  TableRow,\n  TableHead,\n  TableSortHeader,\n  TableCell,\n  TableCaption,\n  TableIndexCell,\n  useRowMotion,\n  TableExpandCell,\n  TableDetail,\n  useDetailPresence,\n  TableState,\n  TableLoadingRows,\n  TablePager,\n  TablePagination,\n  Status,\n  nextSort,\n  sortOf,\n  compareValues,\n  nextSortList,\n  sortLevel,\n  compareBy,\n  type Sort,\n  type SortList,\n  type SortDirection,\n  type TableBulkBarProps,\n  type TableRowProps,\n  type TableHeadProps,\n  type TableSortHeaderProps,\n  type TableCellProps,\n};\n",
      "type": "registry:ui",
      "target": "components/keyline/ui/table.tsx"
    }
  ],
  "type": "registry:ui"
}