{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "table",
  "title": "Table",
  "description": "Rows of records with their numbers lined up, plain or with the data work a list in an app needs: sorting, search, filters, pages, picked rows and hidden columns, in the browser or on a server, through `useTableData`. One highlight glides from row to row, picked rows join into one block, and rows glide to their new places as they are sorted, filtered, added or removed, while the box follows the table’s height. A wide table scrolls sideways and a tall one under a sticky header. A lined variant draws hairlines between rows.",
  "dependencies": [
    "@ui-sdk/react",
    "class-variance-authority"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/cut.json",
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/collapsible.json",
    "https://kinoui.com/r/column-resize.json",
    "https://kinoui.com/r/flow.json",
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/progress.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/skeleton.json",
    "https://kinoui.com/r/spinner.json",
    "https://kinoui.com/r/table-data.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/table.tsx",
      "content": "'use client'\n\nimport { Button } from '@/registry/components/kino/button'\nimport { CollapsibleIndicator } from '@/registry/components/kino/collapsible'\nimport { Progress } from '@/registry/components/kino/progress'\nimport { SkeletonText } from '@/registry/components/kino/skeleton'\nimport { useSpinner } from '@/registry/components/kino/spinner'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { columnResize, type ColumnResizeReason } from '@/registry/lib/column-resize'\nimport { CutTooltip } from '@/registry/lib/cut'\nimport { flowItemClassName, followFlow } from '@/registry/lib/flow'\nimport {\n  followPointer,\n  type HighlightTarget,\n  rowHighlightClassName,\n  tintedRowTextClassName,\n} from '@/registry/lib/highlight'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { followColumns, followHeight } from '@/registry/lib/resize'\nimport {\n  followEdges,\n  revealBehavior,\n  scrollRegionRingClassName,\n  useScrollRegion,\n} from '@/registry/lib/scroll'\nimport type { ChangeDetails } from '@ui-sdk/core'\nimport { usePart, usePrimitive } from '@ui-sdk/react/primitive'\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport {\n  type ComponentProps,\n  createContext,\n  type ReactNode,\n  use,\n  useEffect,\n  useId,\n  type CSSProperties,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A table whose rows answer as one group: one highlight glides from row to\n * row under the pointer, and picked rows tint and join into one block (the\n * `lined` variant draws hairlines between rows instead). When rows come, go or reorder,\n * each one glides to its new place on `layout` and one that leaves fades\n * where it was on `exit`, while the box follows the table's height, so an\n * empty state that takes the rows' place never makes the page jump. A wide\n * table scrolls sideways, its edges fading while columns are hidden past\n * them; a tall one scrolls under a sticky header.\n */\n\n/**\n * The body row the pointer or focus is in; between rows, where rows glide\n * and the copy of one that leaves still fades, a gap; in the header, footer\n * or caption, none.\n */\nfunction rowOf(node: EventTarget | null): HighlightTarget {\n  if (!(node instanceof Element)) return 'none'\n  const row = node.closest<HTMLElement>('[data-slot=table-body] > [data-slot=table-row]')\n  if (row) return row\n  return node.matches('[data-slot=table]') || node.closest('[data-slot=table-body]')\n    ? 'gap'\n    : 'none'\n}\n\n/** The id of what names the table, for its scroll region to take the same name. */\nconst tableIdOf = (scroller: HTMLElement) => {\n  const table = scroller.querySelector('table')\n  if (!table) return undefined\n  const caption = table.querySelector(':scope > caption')\n  if (caption) return caption.id\n  // A name is followed only one step: point at what names the table, not at the table.\n  return (\n    table.getAttribute('aria-labelledby') ??\n    (table.hasAttribute('aria-label') ? table.id : undefined)\n  )\n}\n\n/** Where focus goes when the box stops scrolling while focused: the table's first control, else the table. */\nconst tableFocusOf = (scroller: HTMLElement) => {\n  const table = scroller.querySelector('table')\n  const control = table?.querySelector<HTMLElement>(\n    'a[href], button:not(:disabled), input:not(:disabled), select, textarea, [tabindex]:not([tabindex=\"-1\"])',\n  )\n  if (control || !table) return control\n  table.tabIndex = -1\n  return table\n}\n\n/**\n * Scrolls what takes focus out from under a sticky column, which would cover\n * it and its ring: the browser counts it as in view. Returns a function that\n * stops.\n */\n/**\n * How far, in px along the x axis, to scroll so `box` sits clear of a\n * column pinned at `pinned`, with 8px for its focus ring; 0 when it already\n * is. A column left of `middle` is pinned to the left edge, so `box`\n * belongs to its right, and one right of it the reverse.\n */\nfunction clearOfPinned(\n  box: { left: number; right: number },\n  pinned: { left: number; right: number; width: number },\n  middle: number,\n): number {\n  if (pinned.left + pinned.width / 2 < middle) {\n    return box.left < pinned.right + 8 ? box.left - pinned.right - 8 : 0\n  }\n  return box.right > pinned.left - 8 ? box.right - pinned.left + 8 : 0\n}\n\nfunction keepFocusInView(scroller: HTMLElement): () => void {\n  const clear = (event: FocusEvent) => {\n    const target = event.target\n    if (!(target instanceof HTMLElement) || target.closest('[data-sticky]')) return\n    const box = target.getBoundingClientRect()\n    const row = target.closest('tr')\n    if (!row) return\n    const middle = scroller.getBoundingClientRect().left + scroller.clientWidth / 2\n    let delta = 0\n    for (const cell of row.querySelectorAll<HTMLElement>(':scope > [data-sticky]')) {\n      delta = clearOfPinned(box, cell.getBoundingClientRect(), middle) || delta\n    }\n    if (delta !== 0)\n      scroller.scrollBy({ left: delta, behavior: revealBehavior(scroller) })\n  }\n  scroller.addEventListener('focusin', clear)\n  return () => scroller.removeEventListener('focusin', clear)\n}\n\n/**\n * A table with a resizable column lays out by its columns' widths: each head\n * without one of its own keeps the width it was laid out at, and the table\n * is as wide as its columns together. Returns a function that stops.\n */\nfunction followResizable(table: HTMLTableElement): () => void {\n  const heads = () => [\n    ...table.querySelectorAll<HTMLTableCellElement>(\n      ':scope > thead > tr:first-child > th',\n    ),\n  ]\n  // The heads whose width this code gave them, as laid out, rather than a resize.\n  const ours = new WeakSet<Element>()\n  const set = (element: HTMLElement, name: string, value: string) => {\n    if (element.style.getPropertyValue(name) !== value)\n      element.style.setProperty(name, value)\n  }\n  const widthOf = (head: HTMLElement) =>\n    Number.parseFloat(head.style.getPropertyValue('--column-width'))\n  const update = () => {\n    const all = heads()\n    if (!all.some((head) => head.hasAttribute('data-resizable'))) {\n      delete table.dataset.resizable\n      table.style.removeProperty('--table-width')\n      return\n    }\n    // A table with no layout (mounted hidden) has no widths to keep yet.\n    if (table.getBoundingClientRect().width === 0) return\n    const unsized = all.filter((head) => !head.style.getPropertyValue('--column-width'))\n    if (unsized.length > 0) {\n      // Measured as the table lays them out on its own, then kept.\n      delete table.dataset.resizable\n      // Within the bounds of a column that resizes, so its handle never reads out of them.\n      const widths = unsized.map((head) => {\n        const width = head.getBoundingClientRect().width\n        const handle = head.querySelector(':scope > [data-slot=column-resize]')\n        if (!handle) return width\n        const min = Number(handle.getAttribute('aria-valuemin') ?? 0)\n        const max = Number(handle.getAttribute('aria-valuemax') ?? Infinity)\n        return Math.min(Math.max(width, min), max)\n      })\n      unsized.forEach((head, index) => {\n        ours.add(head)\n        set(head, '--column-width', `${widths[index]}px`)\n      })\n    }\n    // A handle whose column hasn't been resized reads out the width it was laid out at.\n    for (const head of all) {\n      const handle = head.querySelector<HTMLElement>(':scope > [data-slot=column-resize]')\n      const width = String(Math.round(widthOf(head)))\n      if (handle && handle.getAttribute('aria-valuenow') !== width) {\n        handle.setAttribute('aria-valuenow', width)\n      }\n    }\n    set(table, '--table-width', `${all.reduce((sum, head) => sum + widthOf(head), 0)}px`)\n    if (!table.hasAttribute('data-resizable')) table.dataset.resizable = ''\n  }\n  /** Lays out again the widths this code kept, once fonts have loaded or a hidden table shows. */\n  const remeasure = () => {\n    for (const head of heads()) {\n      if (ours.has(head)) head.style.removeProperty('--column-width')\n    }\n    update()\n  }\n  update()\n  // Only the header holds the widths: the body's rows write styles on every glide.\n  const changes = new MutationObserver(update)\n  const watchHead = () => {\n    if (!table.tHead) return\n    changes.observe(table.tHead, {\n      subtree: true,\n      childList: true,\n      attributes: true,\n      attributeFilter: ['style', 'data-resizable', 'aria-valuenow'],\n    })\n  }\n  watchHead()\n  const sections = new MutationObserver(() => {\n    changes.disconnect()\n    watchHead()\n    update()\n  })\n  sections.observe(table, { childList: true })\n  let shown = table.getBoundingClientRect().width > 0\n  const sizes = new ResizeObserver(() => {\n    const now = table.getBoundingClientRect().width > 0\n    if (now && !shown) remeasure()\n    shown = now\n  })\n  sizes.observe(table)\n  let live = true\n  void document.fonts?.ready.then(() => {\n    if (live) remeasure()\n  })\n  return () => {\n    live = false\n    changes.disconnect()\n    sections.disconnect()\n    sizes.disconnect()\n  }\n}\n\nconst tableVariants = cva(\n  // Resizable, it lays out by its columns' widths and is as wide as they are.\n  'group/table relative w-full caption-bottom border-separate border-spacing-0 bg-inherit text-sm data-resizable:table-fixed data-resizable:w-(--table-width)',\n  {\n    variants: {\n      variant: {\n        default: '',\n        lined: '',\n      },\n    },\n    defaultVariants: { variant: 'default' },\n  },\n)\n\nfunction Table({\n  className,\n  containerClassName,\n  variant = 'default',\n  loading = false,\n  scroll = true,\n  ref,\n  id,\n  ...props\n}: ComponentProps<'table'> &\n  VariantProps<typeof tableVariants> & {\n    /** Sizes the box the table scrolls in: a `max-h-` makes the header stick. */\n    containerClassName?: string\n    /**\n     * New rows are on their way: the rows there are stay, readable, and a\n     * line slides along the header's edge once it lasts 200ms, for at least\n     * 300ms. Before the first rows arrive, show a `TableSkeleton` in the body.\n     */\n    loading?: boolean\n    /**\n     * `false` for a table that never outgrows its width: it doesn't scroll in\n     * a box of its own, so its header sticks to the page as the page scrolls.\n     */\n    scroll?: boolean\n  }) {\n  const busy = useSpinner(loading)\n  // The line mounts the first time the table loads, and stays to fade out.\n  const [hasLoaded, setHasLoaded] = useState(loading)\n  if (loading && !hasLoaded) setHasLoaded(true)\n  const frameRef = useRef<HTMLDivElement>(null)\n  const scrollerRef = useRef<HTMLDivElement>(null)\n  const tableRef = useRef<HTMLTableElement>(null)\n  const areaRef = useRef<HTMLDivElement>(null)\n  const layerRef = useRef<HTMLSpanElement>(null)\n  const ownId = useId()\n  const region = useScrollRegion(scrollerRef, {\n    contentRef: tableRef,\n    axis: 'both',\n    labelledBy: tableIdOf,\n    refocus: tableFocusOf,\n  })\n\n  useEffect(() => {\n    const frame = frameRef.current\n    const scroller = scrollerRef.current\n    const table = tableRef.current\n    const area = areaRef.current\n    const layer = layerRef.current\n    if (!frame || !scroller || !table || !area || !layer) return\n    const stops = [\n      // One highlight for every row, so it glides from row to row.\n      followPointer(area, layer, { itemOf: rowOf, focus: true }),\n      markMounted(table),\n      followEdges(scroller, '--table-fade', table),\n      // The rows' clip follows the table's height, inside the box that scrolls:\n      // rows not yet shown, and the copies of rows still leaving, are clipped\n      // as the height glides, never something to scroll to.\n      followHeight(area, table),\n      // The footer and caption glide with the bottom edge of the rows above them.\n      followFlow(table, 'tbody, tfoot, caption'),\n      followResizable(table),\n      keepFocusInView(scroller),\n    ]\n    return () => {\n      for (const stop of stops) stop?.()\n    }\n  }, [])\n\n  return (\n    <div\n      ref={frameRef}\n      data-slot='table-container'\n      className={cn(\n        scrollRegionRingClassName,\n        'relative flex w-full min-w-0 flex-col overflow-clip bg-inherit',\n        containerClassName,\n      )}\n    >\n      <div\n        ref={scrollerRef}\n        data-slot='table-scroller'\n        {...region}\n        // Its padding keeps what Tab scrolls to clear of the sticky header. Its mask fades\n        // each side with content past it: sideways past the pinned columns, and down\n        // from under the sticky header, which it never fades.\n        className={cn(\n          'group/table-scroller min-h-0 flex-auto bg-inherit scroll-pt-[calc(var(--control-height)+5px)] [mask-image:linear-gradient(to_right,transparent,black_calc(var(--table-fade-start,0px)*var(--table-fade-start-on,1)),black_calc(100%-var(--table-fade-end,0px)*var(--table-fade-end-on,1)),transparent),linear-gradient(to_bottom,black_calc(var(--control-height)+5px),transparent_calc(var(--control-height)+5px),black_calc(var(--control-height)+5px+var(--table-fade-top,0px)),black_calc(100%-var(--table-fade-bottom,0px)),transparent)] rtl:[mask-image:linear-gradient(to_left,transparent,black_calc(var(--table-fade-start,0px)*var(--table-fade-start-on,1)),black_calc(100%-var(--table-fade-end,0px)*var(--table-fade-end-on,1)),transparent),linear-gradient(to_bottom,black_calc(var(--control-height)+5px),transparent_calc(var(--control-height)+5px),black_calc(var(--control-height)+5px+var(--table-fade-top,0px)),black_calc(100%-var(--table-fade-bottom,0px)),transparent)] [mask-composite:intersect] has-[[data-sticky=start]]:[--table-fade-start-on:0] has-[[data-sticky=end]]:[--table-fade-end-on:0] focus-visible:outline-hidden',\n          // Clipped, not scrolled, so the page is what the header sticks to.\n          scroll\n            ? 'scrollbar-thin overflow-auto overscroll-x-contain'\n            : 'overflow-x-clip',\n        )}\n      >\n        {/* As wide as the table, so the highlight scrolls with its rows; its\n            rows sit 4px inside the box, so their corners show. It clips\n            without scrolling, so the header still sticks to the box. */}\n        <div\n          ref={areaRef}\n          className='relative isolate w-fit min-w-full overflow-clip bg-inherit p-1 transition-[height] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none'\n        >\n          <table\n            ref={mergeRefs(tableRef, ref)}\n            id={id ?? ownId}\n            data-slot='table'\n            data-variant={variant}\n            data-loading={busy ? '' : undefined}\n            aria-busy={loading || undefined}\n            className={cn(tableVariants({ variant }), className)}\n            {...props}\n          />\n          <span\n            ref={layerRef}\n            aria-hidden\n            data-slot='table-highlight'\n            className={rowHighlightClassName}\n          />\n        </div>\n      </div>\n      {/* While new rows load, a line slides along the header's bottom edge;\n          the table says it is busy, so the line itself isn't read. */}\n      {hasLoaded ? (\n        <div\n          aria-hidden\n          data-slot='table-loading'\n          className='pointer-events-none absolute inset-x-0 top-[calc(var(--control-height)+3px)] z-40 px-1'\n        >\n          <Progress\n            value={busy ? null : 0}\n            className='[&_[data-slot=progress-track]]:h-0.5 [&_[data-slot=progress-track]]:bg-transparent'\n          />\n        </div>\n      ) : null}\n    </div>\n  )\n}\n\n/**\n * How a row moves: it glides to a new place on `layout` (`followFlow`),\n * fades in on `enter` once its body has painted, and its copy fades where it\n * was on `exit`, finishing a glide it was on.\n */\n\n/**\n * A column that stays in view at the table's start or end edge as the rest\n * scrolls under it, with a line along its inner edge once something is\n * hidden past it.\n */\nconst stickyClassName = {\n  start:\n    'sticky start-0 z-10 bg-inherit after:pointer-events-none after:absolute after:inset-y-0 after:end-0 after:w-px after:bg-border after:opacity-0 after:transition-opacity after:duration-(--motion-enter-duration) after:ease-(--motion-enter-easing) forced-colors:after:bg-[CanvasText] group-data-edge-start/table-scroller:after:opacity-100',\n  end: 'sticky end-0 z-10 bg-inherit after:pointer-events-none after:absolute after:inset-y-0 after:start-0 after:w-px after:bg-border after:opacity-0 after:transition-opacity after:duration-(--motion-enter-duration) after:ease-(--motion-enter-easing) forced-colors:after:bg-[CanvasText] group-data-edge-end/table-scroller:after:opacity-100',\n} as const\n\n/** In the body, where a `TableHead` is a row's header. */\nconst InBodyContext = createContext(false)\n\n// The first and last columns take the box's 4px inset off their padding, so\n// they line up with what is above the table.\nconst headClassName =\n  'group/head relative group-has-[th[data-resizable]]/table:px-[calc(var(--control-padding)*0.8+12px)] group-has-[th[data-resizable]]/table:first:ps-[calc(var(--surface-padding)-4px)] group-data-resizable/table:w-(--column-width) group-data-resizing/table:[transition:none] in-data-columns-moving:overflow-clip text-muted-foreground h-(--control-height) border-b border-transparent px-(--control-padding) text-start align-middle text-xs font-medium whitespace-nowrap [transition:width_var(--motion-layout-duration)_var(--motion-layout-easing),border-color_var(--motion-enter-duration)_var(--motion-enter-fade-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)] group-data-scrolled/table-scroller:border-border group-data-[variant=lined]/table:border-border motion-reduce:[transition:border-color_var(--motion-enter-duration)_var(--motion-enter-fade-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)] first:ps-[calc(var(--surface-padding)-4px)] last:pe-[calc(var(--surface-padding)-4px)]'\n\nconst cellClassName =\n  'group-has-[th[data-resizable]]/table:px-[calc(var(--control-padding)*0.8+12px)] group-has-[th[data-resizable]]/table:first:ps-[calc(var(--surface-padding)-4px)] group-data-resizable/table:overflow-hidden group-data-resizable/table:text-ellipsis in-data-columns-moving:overflow-clip h-(--control-height-lg) px-(--control-padding) align-middle whitespace-nowrap [transition:background-color_var(--motion-press-duration)_var(--motion-press-fade-easing),border-radius_var(--motion-morph-duration)_var(--motion-morph-easing)] motion-reduce:[transition:background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)] first:ps-[calc(var(--surface-padding)-4px)] last:pe-[calc(var(--surface-padding)-4px)] group-data-[variant=default]/table:in-data-[slot=table-body]:first:rounded-s-(--item-radius) group-data-[variant=default]/table:in-data-[slot=table-body]:last:rounded-e-(--item-radius)'\n\n/** Sticks to the top of a table that scrolls, over what passes under it. */\nfunction TableHeader({ className, ...props }: ComponentProps<'thead'>) {\n  return (\n    <thead\n      data-slot='table-header'\n      className={cn('sticky top-0 z-30 bg-inherit', className)}\n      {...props}\n    />\n  )\n}\n\nfunction TableBody({ className, ref, children, ...props }: ComponentProps<'tbody'>) {\n  const bodyRef = useRef<HTMLTableSectionElement>(null)\n  useEffect(() => {\n    const body = bodyRef.current\n    const table = body?.closest('table')\n    if (!body || !table) return\n    // Columns first, so a row that leaves takes the widths they had.\n    const stopColumns = followColumns(table)\n    // A row put back while its copy still leaves (re-expanded mid-close) turns back from where it got to.\n    const stopFlow = followFlow(body, 'tr', { key: 'data-row-id' })\n    // Rows fade in once the body has painted: a body put in fresh, as rows\n    // swap on a page turn, shows its rows at once.\n    const stopMounted = markMounted(body)\n    return () => {\n      stopColumns()\n      stopFlow()\n      stopMounted?.()\n    }\n  }, [])\n  return (\n    <tbody\n      ref={mergeRefs(bodyRef, ref)}\n      data-slot='table-body'\n      className={cn('group/flow relative isolate bg-inherit', className)}\n      {...props}\n    >\n      <InBodyContext value>{children}</InBodyContext>\n    </tbody>\n  )\n}\n\nfunction TableFooter({ className, ...props }: ComponentProps<'tfoot'>) {\n  return (\n    <tfoot\n      data-slot='table-footer'\n      className={cn(\n        'bg-inherit font-medium transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none data-[flow=start]:transition-none [&>tr>*]:border-t',\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\n/** `selected` tints the row, for one picked by its checkbox; picked rows side by side join. */\nfunction TableRow({\n  className,\n  selected = false,\n  ...props\n}: ComponentProps<'tr'> & { selected?: boolean }) {\n  return (\n    <tr\n      data-slot='table-row'\n      data-selected={selected ? '' : undefined}\n      className={cn(\n        flowItemClassName,\n        // Opaque, so rows that cross as they reorder, and the copies of rows that leave, don't show through.\n        'bg-inherit',\n        // Its corners, for the highlight to take; the cells draw them.\n        'group-data-[variant=default]/table:rounded-(--item-radius) forced-colors:[&[data-selected]]:text-[HighlightText]',\n        // Picked rows tint, and picked rows next to each other join into one block.\n        '[&[data-selected]>*]:bg-muted forced-colors:[&[data-selected]>*]:bg-[Highlight] forced-colors:[&[data-selected]>*]:forced-color-adjust-none forced-colors:[&[data-selected]>*]:text-[HighlightText] forced-colors:[&[data-selected]_*]:text-[HighlightText] [&[data-selected]:has(+[data-selected])>*]:rounded-b-none [[data-selected]+&[data-selected]>*]:rounded-t-none',\n        // Lined: a hairline above every row that follows another, not counting\n        // the copies of rows that leave, which fade where they were.\n        'in-data-[slot=table-body]:group-data-[variant=lined]/table:[[data-slot=table-row]:not([data-leaving])~&>*]:border-t',\n        tintedRowTextClassName,\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\n/**\n * `numeric` lines the column up at its end edge in figures of one width.\n * With `onSort`, its label is a button that sorts the column.\n */\nfunction TableHead({\n  className,\n  numeric = false,\n  sort,\n  sortIndex,\n  onSort,\n  sticky,\n  width,\n  minWidth = 64,\n  maxWidth = 800,\n  onWidthChange,\n  resizeLabel,\n  style,\n  children,\n  ...props\n}: ComponentProps<'th'> & {\n  numeric?: boolean\n  /** How the column is sorted now: give it with `onSort`. */\n  sort?: 'ascending' | 'descending' | 'none'\n  /** Its place in a sort by several columns, from 1: shown beside the arrow. */\n  sortIndex?: number\n  /** Called when its label is pressed; Shift may add the column to the sort. */\n  onSort?: (event: { shiftKey: boolean }) => void\n  /** Keeps the column in view at the table's start or end edge as the rest scrolls; give its cells the same. */\n  sticky?: 'start' | 'end'\n  /** The column's width in px, once resized: its laid-out width until then. */\n  width?: number\n  /** The narrowest a resize takes it, in px. */\n  minWidth?: number\n  /** The widest a resize takes it, in px. */\n  maxWidth?: number\n  /** With it, the column's end edge drags, and its handle takes the arrow keys, to resize it; undefined puts it back. `details.reason` says how, and `details.cancel()` refuses it. */\n  onWidthChange?: (\n    width: number | undefined,\n    details: ChangeDetails<ColumnResizeReason>,\n  ) => void\n  /** The handle’s name: “Resize”, the label and “column” by default, so no column’s name sits inside another’s, as Customer’s would in Customer since. */\n  resizeLabel?: string\n}) {\n  // In the body, a row's header reads as a cell of its row.\n  const inBody = use(InBodyContext)\n  const sorted = sort === 'ascending' || sort === 'descending'\n  const resizable = onWidthChange !== undefined && !inBody\n  // With a sort button or a resize handle in it, the column is named by its\n  // label alone, never by what those say they do.\n  const labelId = useId()\n  const ownName = onSort !== undefined || resizable\n  return (\n    <th\n      data-slot='table-head'\n      data-sticky={sticky}\n      data-resizable={resizable ? '' : undefined}\n      // Only the column that sorts first is named as sorted.\n      aria-sort={sorted && (sortIndex ?? 1) === 1 ? sort : undefined}\n      aria-labelledby={ownName ? labelId : undefined}\n      style={\n        width === undefined\n          ? style\n          : ({ ...style, '--column-width': `${width}px` } as CSSProperties)\n      }\n      className={cn(\n        inBody ? cn(cellClassName, 'text-start font-medium') : headClassName,\n        numeric && 'text-end tabular-nums',\n        sticky && stickyClassName[sticky],\n        // The header row's sticky cell sits over the body's.\n        sticky && !inBody && 'z-20',\n        className,\n      )}\n      {...props}\n    >\n      {ownName ? (\n        <span id={labelId} hidden>\n          {children}\n        </span>\n      ) : null}\n      {onSort ? (\n        <TableSortButton\n          sort={sort ?? 'none'}\n          sortIndex={sortIndex}\n          numeric={numeric}\n          onSort={onSort}\n        >\n          {children}\n        </TableSortButton>\n      ) : (\n        // In a column narrowed below it, the label truncates, and shows whole under the pointer.\n        <CutTooltip\n          render={\n            <span\n              data-cut\n              className='group-data-resizable/table:block group-data-resizable/table:truncate'\n            >\n              {children}\n            </span>\n          }\n        />\n      )}\n      {resizable ? (\n        <TableResizeHandle\n          label={\n            resizeLabel ??\n            (typeof children === 'string' ? `Resize ${children} column` : 'Resize column')\n          }\n          name={typeof children === 'string' ? children : 'Column'}\n          width={width}\n          minWidth={minWidth}\n          maxWidth={maxWidth}\n          onWidthChange={onWidthChange}\n        />\n      ) : null}\n    </th>\n  )\n}\n\n/**\n * The edge of a column that resizes it: a separator a pointer drags, the\n * arrow keys move (Shift for farther), Home and End take to its bounds, and\n * Enter or a double press puts back.\n */\nfunction TableResizeHandle({\n  label,\n  name,\n  width,\n  minWidth,\n  maxWidth,\n  onWidthChange,\n}: {\n  label: string\n  name: string\n  width: number | undefined\n  minWidth: number\n  maxWidth: number\n  onWidthChange: (\n    width: number | undefined,\n    details: ChangeDetails<ColumnResizeReason>,\n  ) => void\n}) {\n  const resize = usePrimitive(columnResize, {\n    width: width ?? null,\n    name,\n    min: minWidth,\n    max: maxWidth,\n    onWidthChange: (next, details) => onWidthChange(next ?? undefined, details),\n  })\n  return usePart(\n    resize,\n    'root',\n    {},\n    {\n      'aria-label': label,\n      // 24px across the column's edge: a resizable table gives every column 12px of room beside it.\n      className:\n        'absolute inset-y-0 -end-3 z-10 w-6 cursor-col-resize touch-none rounded-(--control-radius-xs) after:absolute after:inset-y-2 after:start-1/2 after:w-px after:-translate-x-1/2 after:bg-border after:opacity-0 after:transition-[opacity,background-color] after:duration-(--motion-press-duration) after:ease-(--motion-press-fade-easing) group-hover/head:after:opacity-100 focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-hidden focus-visible:after:opacity-100 data-dragging:after:bg-primary data-dragging:after:opacity-100 forced-colors:after:bg-[CanvasText] rtl:after:translate-x-1/2',\n    },\n    'span',\n  )\n}\n\n/** A head's label as a button, with the arrow that says which way the column is sorted. */\nfunction TableSortButton({\n  sort,\n  sortIndex,\n  numeric,\n  onSort,\n  children,\n}: {\n  sort: 'ascending' | 'descending' | 'none'\n  sortIndex?: number\n  numeric: boolean\n  onSort: (event: { shiftKey: boolean }) => void\n  children: ReactNode\n}) {\n  const sorted = sort !== 'none'\n  // Always there, so the label never moves when the arrow appears; it turns to\n  // say which way, and shows faintly on hover before a sort. It sits in the\n  // Button's own icon slot: before the label in a column of numbers, so the\n  // label lines up with the figures at the column's end, and after it otherwise.\n  const arrow = (\n    <span\n      aria-hidden\n      data-icon={numeric ? 'inline-start' : 'inline-end'}\n      className='flex items-center gap-0.5 opacity-0 transition-opacity duration-(--motion-press-duration) ease-(--motion-press-easing) group-hover/sort:opacity-50 group-focus-visible/sort:opacity-50 group-data-sorted/sort:opacity-100'\n    >\n      <span\n        data-slot='table-sort-arrow'\n        className={cn(\n          'flex transition-[rotate] duration-(--motion-morph-duration) ease-(--motion-morph-easing) motion-reduce:transition-none',\n          sort === 'ascending' && 'rotate-180',\n        )}\n      >\n        <IconPlaceholder\n          lucide='ArrowDownIcon'\n          tabler='IconArrowDown'\n          hugeicons='ArrowDown02Icon'\n          phosphor='ArrowDownIcon'\n          remixicon='RiArrowDownLine'\n          aria-hidden\n        />\n      </span>\n      {sortIndex !== undefined ? (\n        <span className='text-[0.625rem] leading-none tabular-nums'>{sortIndex}</span>\n      ) : null}\n    </span>\n  )\n  return (\n    // In a column narrowed below it, the label truncates, and shows whole in a tooltip.\n    <CutTooltip\n      render={\n        <Button\n          variant='ghost'\n          size='xs'\n          data-table-sort=''\n          data-sorted={sorted ? '' : undefined}\n          // Its sides' padding sits outside the column, so the label lines up with the cells.\n          className={cn(\n            'group/sort text-muted-foreground -mx-[calc(var(--control-padding)*0.8)] max-w-none data-sorted:text-foreground',\n            // In a column narrowed below its label, the label truncates.\n            'group-data-resizable/table:max-w-[calc(100%+var(--control-padding)*1.6)]',\n          )}\n          onClick={(event) => onSort({ shiftKey: event.shiftKey })}\n        >\n          {numeric ? arrow : null}\n          {/* Says what a press does, and names it apart from a filter on the same column. */}\n          <span className='sr-only'>Sort by</span> {children}\n          {/* `aria-sort` names only the column sorted first; a later one says its place itself. */}\n          {sortIndex !== undefined && sortIndex > 1 && sorted ? (\n            <span className='sr-only'>\n              , sorted {sort}, {sortIndex} in the order\n            </span>\n          ) : null}\n          {numeric ? null : arrow}\n        </Button>\n      }\n    />\n  )\n}\n\n/** `numeric` lines the column up at its end edge in figures of one width. */\nfunction TableCell({\n  className,\n  numeric = false,\n  sticky,\n  ...props\n}: ComponentProps<'td'> & {\n  numeric?: boolean\n  /** Keeps the cell in view at the table's start or end edge as the rest scrolls, with its head. */\n  sticky?: 'start' | 'end'\n}) {\n  return (\n    <td\n      data-slot='table-cell'\n      data-sticky={sticky}\n      className={cn(\n        cellClassName,\n        numeric && 'text-end tabular-nums',\n        sticky && stickyClassName[sticky],\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\nfunction TableCaption({ className, children, ...props }: ComponentProps<'caption'>) {\n  const id = useId()\n  return (\n    <caption\n      id={id}\n      data-slot='table-caption'\n      className={cn(\n        'bg-inherit transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none data-[flow=start]:transition-none text-muted-foreground pt-(--surface-gap) text-start text-sm',\n        className,\n      )}\n      {...props}\n    >\n      {/* Held to the box's visible width, so it wraps in view in a table that scrolls sideways. */}\n      <div className='sticky start-0 max-w-[calc(var(--scroller-width,100%)-8px)] px-[calc(var(--surface-padding)-4px)]'>\n        {children}\n      </div>\n    </caption>\n  )\n}\n\n/**\n * A row across every column for what shows when the table has no rows,\n * such as an `Empty` with `show`: while that shows nothing, the row takes\n * no room and isn't read.\n */\nfunction TableEmpty({\n  className,\n  colSpan,\n  show,\n  children,\n  ...props\n}: Omit<ComponentProps<'tr'>, 'children'> & {\n  /** How many columns the table has. */\n  colSpan: number\n  /** Whether it shows: give its `Empty` the same. Hidden, the row isn't read as one. */\n  show: boolean\n  children: ComponentProps<'td'>['children']\n}) {\n  return (\n    <tr\n      data-slot='table-empty'\n      aria-hidden={show ? undefined : true}\n      className={className}\n      {...props}\n    >\n      {/* What it holds waits for the rows it replaces to leave. */}\n      <td colSpan={colSpan} className='p-0 [--empty-wait:1]'>\n        {/* Held to the box's visible width, so it shows in the middle of what is in view. */}\n        <div className='sticky start-0 flex w-[calc(var(--scroller-width,100%)-8px)] max-w-full'>\n          {children}\n        </div>\n      </td>\n    </tr>\n  )\n}\n\n/**\n * The button that expands a row, to show its sub-rows or a `TableDetail`\n * under it: its chevron turns to point down while it is open. `depth`\n * indents it, for a sub-row; one that can't expand keeps its room, so the\n * text beside it lines up.\n */\nfunction TableExpand({\n  expanded,\n  onExpandedChange,\n  expandable = true,\n  depth = 0,\n  className,\n  ...props\n}: Omit<ComponentProps<'button'>, 'className' | 'onClick'> & {\n  className?: string\n  expanded: boolean\n  onExpandedChange: (expanded: boolean) => void\n  /** Whether the row has anything to show: one without keeps an empty space. */\n  expandable?: boolean\n  /** How deep the row is, from 0: each step indents it by `--table-indent`. */\n  depth?: number\n  /** Names the row it opens, such as “Show the items of KN-1090”. */\n  'aria-label': string\n}) {\n  const indent = {\n    marginInlineStart: `calc(var(--table-indent, 1.25rem) * ${depth})`,\n  }\n  if (!expandable) {\n    return (\n      <span\n        aria-hidden\n        data-table-expand=''\n        style={indent}\n        className={cn('inline-block size-(--control-height-xs) align-middle', className)}\n      />\n    )\n  }\n  return (\n    <Button\n      variant='ghost'\n      size='icon-xs'\n      data-table-expand=''\n      aria-expanded={expanded}\n      style={indent}\n      className={cn('align-middle', className)}\n      onClick={() => onExpandedChange(!expanded)}\n      {...props}\n    >\n      <CollapsibleIndicator open={expanded} />\n    </Button>\n  )\n}\n\n/**\n * A row across every column under the row it belongs to, for what that row\n * opens: its items, a note, a form. It comes and goes as a row does, and the\n * rows below glide to make room.\n */\nfunction TableDetail({\n  className,\n  colSpan,\n  children,\n  ...props\n}: Omit<ComponentProps<'tr'>, 'children'> & {\n  /** How many columns the table has. */\n  colSpan: number\n  children: ReactNode\n}) {\n  return (\n    <tr\n      data-slot='table-detail'\n      className={cn(flowItemClassName, 'bg-inherit', className)}\n      {...props}\n    >\n      <td colSpan={colSpan} className='p-0'>\n        {/* Held to the box's visible width, so it stays in view in a table that scrolls sideways. */}\n        <div className='sticky start-0 w-[calc(var(--scroller-width,100%)-8px)] max-w-full px-[calc(var(--surface-padding)-4px)] pb-(--surface-gap)'>\n          {children}\n        </div>\n      </td>\n    </tr>\n  )\n}\n\n/** How wide each column's placeholder is, in turn, so the rows look like text of different lengths. */\nconst SKELETON_WIDTHS = ['w-24', 'w-32', 'w-16', 'w-20', 'w-28']\n\n/**\n * Rows that stand in for the first rows while they load, in the body: when\n * the rows arrive they take the placeholders' place. Hidden from screen\n * readers, which hear that the table is busy.\n */\nfunction TableSkeleton({\n  columns,\n  rows = 5,\n  className,\n}: {\n  /**\n   * How many columns the table has, or each column's cell class, for columns\n   * that show only at some widths, so a placeholder hides with its column.\n   */\n  columns: number | readonly string[]\n  /** How many rows stand in. */\n  rows?: number\n  className?: string\n}) {\n  const cells = typeof columns === 'number' ? Array<string>(columns).fill('') : columns\n  return Array.from({ length: rows }, (_, row) => (\n    <tr\n      key={row}\n      aria-hidden\n      data-slot='table-skeleton'\n      // When the rows arrive, the copies of these fade where they were, as a row that leaves does.\n      className={cn(\n        'data-leaving:opacity-0 data-leaving:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing)]',\n        className,\n      )}\n    >\n      {cells.map((cell, column) => (\n        <td key={column} className={cn(cellClassName, cell)}>\n          <SkeletonText\n            className={SKELETON_WIDTHS[(row + column * 2) % SKELETON_WIDTHS.length]}\n          />\n        </td>\n      ))}\n    </tr>\n  ))\n}\n\nexport {\n  Table,\n  TableBody,\n  TableCaption,\n  TableCell,\n  TableDetail,\n  TableEmpty,\n  TableExpand,\n  TableFooter,\n  TableHead,\n  TableHeader,\n  TableRow,\n  TableSkeleton,\n  clearOfPinned,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/table.tsx"
    }
  ],
  "type": "registry:component"
}