{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-table",
  "title": "Data Table",
  "description": "Server-driven TanStack data table with row links, sorting, offset or cursor pagination, tabs, column visibility, context menus, split view, expandable rows and cross-page selection.",
  "dependencies": [
    "@tanstack/react-table@^8.21.3",
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "checkbox",
    "dropdown-menu",
    "context-menu"
  ],
  "files": [
    {
      "path": "components/dentil/data-table/types.ts",
      "content": "import type { RowData } from '@tanstack/react-table';\n\ndeclare module '@tanstack/react-table' {\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  interface ColumnMeta<TData extends RowData, TValue> {\n    /** Horizontal alignment of the header and cells. Defaults to `'left'`. */\n    align?: 'left' | 'center' | 'right';\n    /** Where a cell sits when its row is taller than the cell, e.g. beside a multi-line cell. Defaults to `'middle'`. */\n    verticalAlign?: 'top' | 'middle' | 'bottom';\n    /**\n     * Vertical alignment of the cell's content within its 40px minimum height. Defaults to `'center'`.\n     * `'start'` keeps the content top-aligned. Doesn't move the cell in a taller row; use `verticalAlign` for that.\n     */\n    itemAlign?: 'center' | 'start';\n    /** Shrink the column to its content width (`w-px`). */\n    minimize?: boolean;\n    /** Keep the cell out of the row link when it renders its own link or control. */\n    disableRowLink?: boolean;\n  }\n}\n\n/**\n * The controlled query that drives a server-side table. Reserved keys:\n * - `offset`: zero-based page index\n * - `after` / `before`: the `nextCursor` or `previousCursor` of the page the user came from (cursor pagination)\n * - `sort` / `sort_field`: `'ascending' | 'descending'` and the API field name\n *\n * Every other key is a filter or tab value passed straight to your API.\n */\nexport type TableQuery = Record<string, string | string[] | number | object>;\n\n/** Keys that locate the current page. Any change except paging drops them, so the user lands on the first page. */\nexport const PAGE_KEYS: ReadonlyArray<string> = ['offset', 'after', 'before'];\n\nexport function withoutPage(query: TableQuery): TableQuery {\n  return Object.fromEntries(Object.entries(query).filter(([key]) => !PAGE_KEYS.includes(key)));\n}\n\nexport interface TableTab {\n  label: string;\n  query: TableQuery;\n}\n\nexport interface TableTabsOptions {\n  /** Where to place the \"All\" tab. Defaults to `'end'`. */\n  allPosition?: 'start' | 'end';\n  /** Whether to show the \"All\" tab. Defaults to `true`. */\n  showAll?: boolean;\n}\n\n/** Props passed to a custom `linkComponent`. Compatible with `next/link`, React Router's `Link`, or a plain `<a>`. */\nexport interface DataTableLinkProps {\n  href: string;\n  className?: string;\n  children?: React.ReactNode;\n}\n\nexport type DataTableLinkComponent = React.ElementType<DataTableLinkProps>;\n\nexport function defaultGetRowId<TData>(row: TData): string {\n  return String((row as { id: string | number }).id);\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/data-table/types.ts"
    },
    {
      "path": "components/dentil/data-table/primitives.tsx",
      "content": "'use client';\n\nimport * as React from 'react';\n\nimport { cn } from '@/lib/utils';\n\nfunction Table({\n  className,\n  containerClassName,\n  ...props\n}: React.ComponentProps<'table'> & { containerClassName?: string }) {\n  return (\n    <div data-slot=\"table-container\" className={cn('relative w-full overflow-x-auto', containerClassName)}>\n      <table data-slot=\"table\" className={cn('w-full caption-bottom text-sm', className)} {...props} />\n    </div>\n  );\n}\n\nfunction TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {\n  return <thead data-slot=\"table-header\" className={cn('[&_tr]:border-b', className)} {...props} />;\n}\n\nfunction TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {\n  return <tbody data-slot=\"table-body\" className={cn('[&_tr:last-child]:border-0', className)} {...props} />;\n}\n\nfunction TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {\n  return (\n    <tfoot\n      data-slot=\"table-footer\"\n      className={cn('bg-muted/50 border-t font-medium [&>tr]:last:border-b-0', className)}\n      {...props}\n    />\n  );\n}\n\nfunction TableRow({ className, ...props }: React.ComponentProps<'tr'>) {\n  return <tr data-slot=\"table-row\" className={cn('border-b', className)} {...props} />;\n}\n\nfunction TableHead({ className, ...props }: React.ComponentProps<'th'>) {\n  return (\n    <th\n      data-slot=\"table-head\"\n      className={cn(\n        'text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',\n        'first:pl-5 last:pr-5',\n        className\n      )}\n      {...props}\n    />\n  );\n}\n\nfunction TableCell({ className, ...props }: React.ComponentProps<'td'>) {\n  return (\n    <td\n      data-slot=\"table-cell\"\n      className={cn(\n        'align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',\n        'first:[&_[data-slot=table-cell-content]]:pl-5 last:[&_[data-slot=table-cell-content]]:pr-5',\n        className\n      )}\n      {...props}\n    />\n  );\n}\n\n/** Padded inner wrapper so a link or button inside a cell covers the full cell area. */\nfunction TableCellContent({ className, ...props }: React.ComponentProps<'div'>) {\n  return <div data-slot=\"table-cell-content\" className={cn('flex p-2', className)} {...props} />;\n}\n\nfunction TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {\n  return (\n    <caption data-slot=\"table-caption\" className={cn('text-muted-foreground mt-4 text-sm', className)} {...props} />\n  );\n}\n\nexport { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCellContent, TableCaption };\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/primitives.tsx"
    },
    {
      "path": "components/dentil/data-table/hooks.ts",
      "content": "'use client';\n\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nfunction isFormTarget(target: EventTarget | null) {\n  if (!(target instanceof HTMLElement)) return false;\n  return target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName);\n}\n\n/**\n * Calls `handler` when `key` (a `KeyboardEvent.key` value such as `'ArrowDown'` or `'a'`) is pressed\n * without modifiers. Ignored while focus is in a form field or a dialog/menu has focus.\n */\nexport function useHotkey(key: string, handler: (event: KeyboardEvent) => void, enabled = true) {\n  const handlerRef = useRef(handler);\n  useEffect(() => {\n    handlerRef.current = handler;\n  });\n\n  useEffect(() => {\n    if (!enabled) return;\n    const onKeyDown = (event: KeyboardEvent) => {\n      if (event.key !== key || event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented) return;\n      if (isFormTarget(event.target)) return;\n      if (event.target instanceof HTMLElement && event.target.closest('[role=dialog],[role=menu],[role=listbox]')) {\n        return;\n      }\n      event.preventDefault();\n      handlerRef.current(event);\n    };\n    window.addEventListener('keydown', onKeyDown);\n    return () => window.removeEventListener('keydown', onKeyDown);\n  }, [key, enabled]);\n}\n\nexport function useMediaQuery(query: string) {\n  return useSyncExternalStore(\n    (onChange) => {\n      const mql = window.matchMedia(query);\n      mql.addEventListener('change', onChange);\n      return () => mql.removeEventListener('change', onChange);\n    },\n    () => window.matchMedia(query).matches,\n    () => false\n  );\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/data-table/hooks.ts"
    },
    {
      "path": "components/dentil/data-table/error.tsx",
      "content": "'use client';\n\nimport * as React from 'react';\n\nexport function TableError({ error }: { error: Error | string }) {\n  return (\n    <div className=\"px-5\">\n      <div className=\"flex items-center justify-center gap-2 rounded-md border border-dashed p-10\">\n        <div className=\"text-muted-foreground text-sm\">{typeof error === 'string' ? error : error.message}</div>\n      </div>\n    </div>\n  );\n}\n\ninterface TableErrorBoundaryProps {\n  children: React.ReactNode;\n  /** When any of these change identity, a caught error is cleared and the table re-renders. */\n  resetKeys?: unknown[];\n  fallback?: (error: Error) => React.ReactNode;\n}\n\ninterface TableErrorBoundaryState {\n  error: Error | null;\n  resetKeys?: unknown[];\n}\n\nexport class TableErrorBoundary extends React.Component<TableErrorBoundaryProps, TableErrorBoundaryState> {\n  state: TableErrorBoundaryState = { error: null, resetKeys: this.props.resetKeys };\n\n  static getDerivedStateFromError(error: Error): Partial<TableErrorBoundaryState> {\n    return { error };\n  }\n\n  static getDerivedStateFromProps(\n    props: TableErrorBoundaryProps,\n    state: TableErrorBoundaryState\n  ): Partial<TableErrorBoundaryState> | null {\n    const prev = state.resetKeys ?? [];\n    const next = props.resetKeys ?? [];\n    const changed = prev.length !== next.length || prev.some((key, index) => !Object.is(key, next[index]));\n    if (!changed) return null;\n    return { resetKeys: next, error: null };\n  }\n\n  componentDidCatch(error: Error, info: React.ErrorInfo) {\n    console.error('[DataTable]', error, info.componentStack);\n  }\n\n  render() {\n    if (this.state.error) {\n      return (\n        this.props.fallback?.(this.state.error) ?? <TableError error=\"Something went wrong displaying this table.\" />\n      );\n    }\n    return this.props.children;\n  }\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/error.tsx"
    },
    {
      "path": "components/dentil/data-table/tabs.tsx",
      "content": "'use client';\n\nimport * as React from 'react';\n\nimport { cn } from '@/lib/utils';\n\nimport { PAGE_KEYS, type TableQuery, type TableTab, type TableTabsOptions } from './types';\n\nconst ALL_TAB: TableTab = { label: 'All', query: {} };\n\n/**\n * Underlined tabs that each apply a query. Built on plain buttons rather than shadcn `Tabs` so it looks the same\n * whichever shadcn style the host app uses.\n */\nexport function DataTableTabs({\n  tabs,\n  query,\n  setQuery,\n  options,\n  onChange,\n  className,\n}: {\n  tabs: TableTab[];\n  query: TableQuery;\n  setQuery: (query: TableQuery) => void;\n  onChange?: (tab: TableTab) => void;\n  options?: TableTabsOptions;\n  className?: string;\n}) {\n  const showAll = options?.showAll !== false;\n  const combinedTabs = showAll ? (options?.allPosition === 'start' ? [ALL_TAB, ...tabs] : [...tabs, ALL_TAB]) : tabs;\n  const tabRefs = React.useRef<(HTMLButtonElement | null)[]>([]);\n\n  // A tab is active when every key in its query matches; otherwise fall back to \"All\", then the first tab.\n  const activeTab =\n    combinedTabs.find(\n      (tab) =>\n        Object.keys(tab.query).length > 0 && Object.entries(tab.query).every(([key, value]) => query[key] === value)\n    ) ??\n    combinedTabs.find((tab) => Object.keys(tab.query).length === 0) ??\n    combinedTabs[0];\n\n  const tabKeys = new Set(combinedTabs.flatMap((tab) => Object.keys(tab.query)));\n\n  const select = (tab: TableTab) => {\n    if (tab === activeTab) return;\n    // Keep filters and sort, but drop other tabs' keys and reset pagination.\n    const preserved: TableQuery = {};\n    for (const [key, value] of Object.entries(query)) {\n      if (tabKeys.has(key) || PAGE_KEYS.includes(key)) continue;\n      preserved[key] = value;\n    }\n    setQuery({ ...preserved, ...tab.query });\n    onChange?.(tab);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent, index: number) => {\n    const last = combinedTabs.length - 1;\n    const next =\n      event.key === 'ArrowRight'\n        ? index === last\n          ? 0\n          : index + 1\n        : event.key === 'ArrowLeft'\n          ? index === 0\n            ? last\n            : index - 1\n          : event.key === 'Home'\n            ? 0\n            : event.key === 'End'\n              ? last\n              : null;\n    if (next === null) return;\n    event.preventDefault();\n    // Stop the table's left/right pagination hotkeys from also firing.\n    event.stopPropagation();\n    tabRefs.current[next]?.focus();\n    select(combinedTabs[next]!);\n  };\n\n  return (\n    <div role=\"tablist\" className={cn('flex items-center gap-4 overflow-x-auto px-5', className)}>\n      {combinedTabs.map((tab, index) => {\n        const isActive = tab === activeTab;\n        return (\n          <button\n            key={tab.label}\n            ref={(el) => {\n              tabRefs.current[index] = el;\n            }}\n            type=\"button\"\n            role=\"tab\"\n            aria-selected={isActive}\n            tabIndex={isActive ? 0 : -1}\n            data-state={isActive ? 'active' : 'inactive'}\n            onClick={() => select(tab)}\n            onKeyDown={(event) => onKeyDown(event, index)}\n            className={cn(\n              'text-muted-foreground hover:text-foreground focus-visible:ring-ring/50 relative h-9 shrink-0 text-sm font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-[3px]',\n              'after:absolute after:inset-x-0 after:bottom-0 after:h-0.5 after:rounded-full after:bg-transparent after:transition-colors',\n              isActive && 'text-foreground after:bg-primary'\n            )}>\n            {tab.label}\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/tabs.tsx"
    },
    {
      "path": "components/dentil/data-table/display.tsx",
      "content": "'use client';\n\nimport type { Table } from '@tanstack/react-table';\nimport { SlidersHorizontal } from 'lucide-react';\n\nimport { Button } from '@/components/ui/button';\nimport {\n  DropdownMenu,\n  DropdownMenuCheckboxItem,\n  DropdownMenuContent,\n  DropdownMenuTrigger,\n} from '@/components/ui/dropdown-menu';\n\ninterface DataTableDisplayProps<TData> {\n  align?: 'start' | 'end';\n  table: Table<TData>;\n}\n\nfunction columnLabel<TData>(column: ReturnType<Table<TData>['getAllColumns']>[number]) {\n  const header = column.columnDef.header;\n  return typeof header === 'string' && header ? header : column.id.replaceAll('_', ' ');\n}\n\n/** Dropdown for toggling column visibility. Lists every column where `enableHiding` isn't `false`. */\nexport function DataTableDisplay<TData>({ table, align = 'end' }: DataTableDisplayProps<TData>) {\n  const displayFields = table.getAllColumns().filter((column) => column.getCanHide());\n  if (displayFields.length === 0) return null;\n  return (\n    <DropdownMenu>\n      <DropdownMenuTrigger asChild>\n        <Button variant=\"secondary\" size=\"sm\" className=\"h-7 gap-1.5 px-2 text-xs\">\n          <SlidersHorizontal className=\"size-3\" />\n          Display\n        </Button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent align={align} className=\"w-[150px]\">\n        {displayFields.map((column) => (\n          <DropdownMenuCheckboxItem\n            key={column.id}\n            className=\"capitalize\"\n            checked={column.getIsVisible()}\n            onCheckedChange={(value) => column.toggleVisibility(!!value)}\n            // Keeps a Radix menu open after a toggle. Base UI checkbox items stay open anyway and ignore this.\n            onSelect={(event) => event.preventDefault()}>\n            {columnLabel(column)}\n          </DropdownMenuCheckboxItem>\n        ))}\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/display.tsx"
    },
    {
      "path": "components/dentil/data-table/actions-button.tsx",
      "content": "'use client';\n\nimport { Ellipsis } from 'lucide-react';\nimport { useState } from 'react';\n\nimport { Button } from '@/components/ui/button';\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from '@/components/ui/dropdown-menu';\n\nexport interface ActionItem {\n  name: string;\n  onClick: () => void;\n  variant?: 'default' | 'destructive';\n  disabled?: boolean;\n}\n\n/** The `…` row-actions dropdown. Render it from an `actions` column. */\nexport function ActionsButton({ actions, label = 'Row actions' }: { actions: ActionItem[]; label?: string }) {\n  const [open, setOpen] = useState(false);\n\n  if (actions.length === 0) {\n    return null;\n  }\n\n  return (\n    <DropdownMenu open={open} onOpenChange={setOpen}>\n      <DropdownMenuTrigger asChild>\n        <Button\n          variant=\"ghost\"\n          size=\"icon\"\n          aria-label={label}\n          onClick={(e) => e.stopPropagation()}\n          className=\"hover:bg-card h-[26px] w-8 hover:shadow-xs\">\n          <Ellipsis className=\"size-4\" />\n        </Button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent align=\"end\" className=\"w-40\">\n        {actions.map((action) => (\n          <DropdownMenuItem\n            key={action.name}\n            variant={action.variant || 'default'}\n            disabled={action.disabled}\n            // onClick (not Radix's onSelect) so this works with both Radix and Base UI shadcn components.\n            // Radix fires click for keyboard selection too.\n            onClick={(e) => {\n              e.stopPropagation();\n              setOpen(false);\n              // Let the menu close and release pointer-events before the action opens anything (e.g. a dialog).\n              setTimeout(() => action.onClick(), 0);\n            }}>\n            {action.name}\n          </DropdownMenuItem>\n        ))}\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/actions-button.tsx"
    },
    {
      "path": "components/dentil/data-table/date-cell.tsx",
      "content": "import { cn } from '@/lib/utils';\n\nexport type DateCellValue = number | string | Date | null | undefined;\n\n/** Unix timestamps in seconds are what most APIs return; anything above this is treated as milliseconds. */\nconst MAX_UNIX_SECONDS = 1e11;\n\nexport function toDate(value: DateCellValue): Date | null {\n  if (value === null || value === undefined || value === '') return null;\n  if (value instanceof Date) return value;\n  if (typeof value === 'number') return new Date(value < MAX_UNIX_SECONDS ? value * 1000 : value);\n  const date = new Date(value);\n  return Number.isNaN(date.getTime()) ? null : date;\n}\n\nexport function formatDate(date: Date, { showTime = true, locale }: { showTime?: boolean; locale?: string } = {}) {\n  const isThisYear = date.getFullYear() === new Date().getFullYear();\n  return new Intl.DateTimeFormat(locale, {\n    month: 'short',\n    day: 'numeric',\n    year: isThisYear ? undefined : 'numeric',\n    hour: showTime ? '2-digit' : undefined,\n    minute: showTime ? '2-digit' : undefined,\n    hourCycle: 'h23',\n  }).format(date);\n}\n\n/**\n * Compact date such as \"Mar 4, 14:30\" (or \"Mar 4, 2024, 14:30\" outside the current year).\n * Accepts unix seconds, milliseconds, ISO strings or `Date`.\n */\nexport function DateCell({\n  align = 'left',\n  date,\n  showTime = true,\n  locale,\n  fallback = '-',\n}: {\n  align?: 'left' | 'right';\n  date: DateCellValue;\n  showTime?: boolean;\n  locale?: string;\n  fallback?: React.ReactNode;\n}) {\n  const parsed = toDate(date);\n  return (\n    <div className={cn(align === 'right' && 'text-right')}>\n      {parsed ? (\n        <time dateTime={parsed.toISOString()} suppressHydrationWarning>\n          {formatDate(parsed, { showTime, locale })}\n        </time>\n      ) : (\n        fallback\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/date-cell.tsx"
    },
    {
      "path": "components/dentil/data-table/context-menu.tsx",
      "content": "'use client';\n\nimport { Copy, ExternalLink } from 'lucide-react';\nimport * as React from 'react';\n\nimport {\n  ContextMenu,\n  ContextMenuContent,\n  ContextMenuGroup,\n  ContextMenuItem,\n  ContextMenuLabel,\n  ContextMenuSeparator,\n  ContextMenuSub,\n  ContextMenuSubContent,\n  ContextMenuSubTrigger,\n  ContextMenuTrigger,\n} from '@/components/ui/context-menu';\nimport { cn } from '@/lib/utils';\n\nexport interface ItemAction<T> {\n  id: string;\n  type: 'item';\n  label: string;\n  onClick: (row: T) => void;\n  disabled?: boolean;\n  icon?: React.ReactNode;\n  variant?: 'default' | 'destructive';\n}\n\nexport interface SeparatorAction {\n  id: string;\n  type: 'separator';\n}\n\nexport interface LabelAction {\n  id: string;\n  type: 'label';\n  label: string;\n}\n\nexport interface SubMenuAction<T> {\n  id: string;\n  type: 'submenu';\n  label: string;\n  actions: Action<T>[];\n  disabled?: boolean;\n  icon?: React.ReactNode;\n}\n\nexport type Action<T> = ItemAction<T> | SeparatorAction | LabelAction | SubMenuAction<T>;\n\nfunction renderAction<T>(action: Action<T>, row: T): React.ReactNode {\n  switch (action.type) {\n    case 'item':\n      return (\n        <ContextMenuItem\n          key={action.id}\n          variant={action.variant}\n          disabled={action.disabled}\n          onClick={(e) => {\n            e.stopPropagation();\n            action.onClick(row);\n          }}>\n          {action.icon}\n          {action.label}\n        </ContextMenuItem>\n      );\n    case 'separator':\n      return <ContextMenuSeparator key={action.id} />;\n    case 'label':\n      // Base UI throws if a menu label isn't inside a group.\n      return (\n        <ContextMenuGroup key={action.id}>\n          <ContextMenuLabel>{action.label}</ContextMenuLabel>\n        </ContextMenuGroup>\n      );\n    case 'submenu':\n      return (\n        <ContextMenuSub key={action.id}>\n          <ContextMenuSubTrigger disabled={action.disabled} className=\"gap-2\">\n            {action.icon}\n            {action.label}\n          </ContextMenuSubTrigger>\n          <ContextMenuSubContent>\n            {action.actions.map((subAction) => renderAction(subAction, row))}\n          </ContextMenuSubContent>\n        </ContextMenuSub>\n      );\n    default:\n      return null;\n  }\n}\n\ntype Props = Record<string, unknown>;\n\nfunction setRef(ref: unknown, value: unknown) {\n  if (typeof ref === 'function') ref(value);\n  else if (ref && typeof ref === 'object') (ref as { current: unknown }).current = value;\n}\n\n/**\n * Passes the trigger's props and ref on to its one child element, so the child (e.g. a `<tr>`) is the trigger.\n * It exists so the trigger below can use `asChild` with a JSX child: the shadcn CLI only rewrites `asChild` to Base UI's\n * `render` prop when the child is a JSX element, not `{children}`.\n */\nfunction TriggerTarget({ children, ...injected }: Props & { children?: React.ReactNode }) {\n  if (!React.isValidElement<Props>(children)) return null;\n  const own = children.props;\n  const merged: Props = { ...injected };\n  for (const [key, value] of Object.entries(own)) {\n    const theirs = merged[key];\n    if (value === undefined) continue;\n    if (key === 'className') merged[key] = cn(theirs as string, value as string);\n    else if (key === 'style') merged[key] = { ...(theirs as object), ...(value as object) };\n    else if (key === 'ref' && theirs) {\n      merged[key] = (node: unknown) => {\n        setRef(theirs, node);\n        setRef(value, node);\n      };\n    } else if (/^on[A-Z]/.test(key) && typeof theirs === 'function' && typeof value === 'function') {\n      merged[key] = (...args: unknown[]) => {\n        value(...args);\n        theirs(...args);\n      };\n    } else merged[key] = value;\n  }\n  return React.cloneElement(children, merged);\n}\n\n/** Right-click menu for a row. Renders `children` untouched when there are no actions. */\nexport function TableContextMenu<T>({\n  children,\n  className,\n  actions,\n  row,\n  childAsTrigger,\n}: {\n  children: React.ReactNode;\n  className?: string;\n  actions?: Action<T>[];\n  row: T;\n  /** Use the child element (e.g. a `<tr>`) as the trigger instead of wrapping it, so one menu covers the whole row. */\n  childAsTrigger?: boolean;\n}) {\n  if (!actions || actions.length === 0) {\n    return <>{children}</>;\n  }\n\n  return (\n    <ContextMenu>\n      {childAsTrigger ? (\n        <ContextMenuTrigger asChild>\n          <TriggerTarget>{children}</TriggerTarget>\n        </ContextMenuTrigger>\n      ) : (\n        <ContextMenuTrigger className={className}>{children}</ContextMenuTrigger>\n      )}\n      <ContextMenuContent className=\"max-w-56\">{actions.map((action) => renderAction(action, row))}</ContextMenuContent>\n    </ContextMenu>\n  );\n}\n\n/** \"Copy ID\" and \"Open in new tab\" actions. */\nexport function createCommonActions<T>(\n  // Unused at runtime; lets TypeScript infer `T` from the row at the call site.\n  _row: T,\n  options: {\n    getId?: (row: T) => string;\n    /** Called after the ID is copied, e.g. to show a toast. */\n    onCopyId?: (id: string) => void;\n    /** Overrides the default `window.open(\\`${baseUrl}/${id}\\`)`. */\n    onOpenInNewTab?: (row: T) => void;\n    baseUrl?: string;\n    showCopyId?: boolean;\n    showOpenInNewTab?: boolean;\n  } = {}\n): Action<T>[] {\n  const {\n    getId = (r: T) => String((r as { id: string | number }).id),\n    onCopyId,\n    onOpenInNewTab,\n    baseUrl,\n    showCopyId = true,\n    showOpenInNewTab = true,\n  } = options;\n\n  const actions: Action<T>[] = [];\n\n  if (showCopyId) {\n    actions.push({\n      id: 'copy-id',\n      type: 'item',\n      label: 'Copy ID',\n      icon: <Copy className=\"size-4\" />,\n      onClick: (r) => {\n        const id = getId(r);\n        void navigator.clipboard.writeText(id).then(() => onCopyId?.(id));\n      },\n    });\n  }\n\n  if (showOpenInNewTab && (baseUrl || onOpenInNewTab)) {\n    actions.push({\n      id: 'new-tab',\n      type: 'item',\n      label: 'Open in new tab',\n      icon: <ExternalLink className=\"size-4\" />,\n      onClick: (r) => {\n        if (onOpenInNewTab) onOpenInNewTab(r);\n        else window.open(`${baseUrl}/${getId(r)}`, '_blank', 'noopener');\n      },\n    });\n  }\n\n  return actions;\n}\n\nexport function createCustomAction<T>(\n  id: string,\n  label: string,\n  onClick: (row: T) => void,\n  icon?: React.ReactNode,\n  disabled?: boolean\n): Action<T> {\n  return { id, type: 'item', label, onClick, icon, disabled };\n}\n\nexport function createSeparator<T>(id: string): Action<T> {\n  return { id, type: 'separator' };\n}\n\nexport function createLabel<T>(id: string, label: string): Action<T> {\n  return { id, type: 'label', label };\n}\n\nexport function createSubMenu<T>(\n  id: string,\n  label: string,\n  actions: Action<T>[],\n  icon?: React.ReactNode,\n  disabled?: boolean\n): Action<T> {\n  return { id, type: 'submenu', label, actions, icon, disabled };\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/context-menu.tsx"
    },
    {
      "path": "components/dentil/data-table/selection-action-bar.tsx",
      "content": "'use client';\n\nimport { Loader2, XIcon } from 'lucide-react';\nimport * as React from 'react';\n\nimport { Button } from '@/components/ui/button';\n\nimport { useHotkey } from './hooks';\n\nexport interface SelectionAction<TData> {\n  /** Stable key; defaults to `label`. */\n  id?: string;\n  label: string;\n  /** Receives every selected row (across pages). Return a promise to show a pending state until it settles. */\n  onClick: (rows: TData[]) => void | Promise<void>;\n  variant?: React.ComponentProps<typeof Button>['variant'];\n  icon?: React.ComponentType<{ className?: string }>;\n  disabled?: boolean | ((rows: TData[]) => boolean);\n  hidden?: boolean | ((rows: TData[]) => boolean);\n  /** Clear the selection once `onClick` resolves. Defaults to `false`. */\n  clearOnSuccess?: boolean;\n}\n\nexport interface SelectionActionBarProps<TData> {\n  selectedRows: TData[];\n  actions: SelectionAction<TData>[];\n  onClearSelection: () => void;\n  onSelectAll: () => void;\n  /**\n   * Replace the bar's contents with a custom status view (e.g. progress of a long-running bulk job).\n   * Return `null` to show the default bar.\n   */\n  renderStatus?: (ctx: { selectedRows: TData[]; dismiss: () => void }) => React.ReactNode;\n}\n\nfunction resolve<TData>(value: boolean | ((rows: TData[]) => boolean) | undefined, rows: TData[]) {\n  return typeof value === 'function' ? value(rows) : Boolean(value);\n}\n\n/** Floating bar shown at the bottom of the viewport while rows are selected. */\nexport function SelectionActionBar<TData>({\n  selectedRows,\n  actions,\n  onClearSelection,\n  onSelectAll,\n  renderStatus,\n}: SelectionActionBarProps<TData>) {\n  const [pending, setPending] = React.useState<string | null>(null);\n\n  useHotkey('a', onSelectAll, pending === null);\n\n  const handleClick = async (action: SelectionAction<TData>, key: string) => {\n    const result = action.onClick(selectedRows);\n    if (!(result instanceof Promise)) {\n      if (action.clearOnSuccess) onClearSelection();\n      return;\n    }\n    setPending(key);\n    try {\n      await result;\n      if (action.clearOnSuccess) onClearSelection();\n    } finally {\n      setPending(null);\n    }\n  };\n\n  const status = renderStatus?.({ selectedRows, dismiss: onClearSelection });\n\n  return (\n    <div className=\"pointer-events-none fixed inset-x-0 bottom-5 z-50 flex justify-center px-4\">\n      <div\n        role=\"toolbar\"\n        aria-label=\"Selection actions\"\n        className=\"bg-background/95 supports-backdrop-filter:bg-background/60 pointer-events-auto rounded-full border shadow-2xl backdrop-blur\">\n        {status ? (\n          <div className=\"flex items-center gap-3 px-4 py-3\">\n            {status}\n            <Button\n              variant=\"ghost\"\n              size=\"sm\"\n              className=\"ml-1 size-7 rounded-full p-0\"\n              onClick={onClearSelection}\n              aria-label=\"Dismiss\">\n              <XIcon className=\"size-4\" />\n            </Button>\n          </div>\n        ) : (\n          <div className=\"flex items-center gap-4 px-4 py-3\">\n            <div className=\"text-sm font-medium tabular-nums\">{selectedRows.length} selected</div>\n\n            <button type=\"button\" className=\"hover:text-primary text-sm font-medium\" onClick={onClearSelection}>\n              Deselect\n            </button>\n\n            <button\n              type=\"button\"\n              className=\"hover:text-primary flex items-center gap-1.5 text-sm font-medium\"\n              onClick={onSelectAll}>\n              Select all\n              <kbd className=\"bg-muted text-muted-foreground rounded border px-1 font-mono text-[10px] leading-4\">\n                A\n              </kbd>\n            </button>\n\n            {actions.map((action) => {\n              if (resolve(action.hidden, selectedRows)) return null;\n              const key = action.id ?? action.label;\n              const Icon = action.icon;\n              const isPending = pending === key;\n              return (\n                <Button\n                  key={key}\n                  variant={action.variant ?? 'default'}\n                  size=\"sm\"\n                  className=\"rounded-full\"\n                  disabled={pending !== null || resolve(action.disabled, selectedRows)}\n                  onClick={() => handleClick(action, key)}>\n                  {isPending ? <Loader2 className=\"size-4 animate-spin\" /> : Icon && <Icon className=\"size-4\" />}\n                  {action.label}\n                </Button>\n              );\n            })}\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/selection-action-bar.tsx"
    },
    {
      "path": "components/dentil/data-table/data-table.tsx",
      "content": "'use client';\n\nimport {\n  type ColumnDef,\n  type ExpandedState,\n  type RowSelectionState,\n  type TableMeta,\n  type Updater,\n  type VisibilityState,\n  flexRender,\n  getCoreRowModel,\n  useReactTable,\n} from '@tanstack/react-table';\nimport { ArrowDown, ArrowRight, ArrowUp, ChevronDown, Loader2 } from 'lucide-react';\nimport * as React from 'react';\n\nimport { Button } from '@/components/ui/button';\nimport { Checkbox } from '@/components/ui/checkbox';\nimport { cn } from '@/lib/utils';\n\nimport { type Action, TableContextMenu } from './context-menu';\nimport { DataTableDisplay } from './display';\nimport { TableError, TableErrorBoundary } from './error';\nimport { useHotkey, useMediaQuery } from './hooks';\nimport { Table, TableBody, TableCell, TableCellContent, TableHead, TableHeader, TableRow } from './primitives';\nimport { useDataTableRouter } from './router';\nimport { type SelectionAction, SelectionActionBar } from './selection-action-bar';\nimport { DataTableTabs } from './tabs';\nimport {\n  type DataTableLinkComponent,\n  type TableQuery,\n  type TableTab,\n  type TableTabsOptions,\n  defaultGetRowId,\n  withoutPage,\n} from './types';\n\n// Callers commonly pass `data={list?.data || []}`, which creates a fresh `[]` every render while loading and\n// resets the TanStack table. Normalising empty data to one constant keeps the reference stable.\nconst EMPTY_DATA: ReadonlyArray<unknown> = [];\nconst EMPTY_SELECTED_ROWS: ReadonlyArray<unknown> = [];\nconst EMPTY_SELECTION_ACTIONS: ReadonlyArray<unknown> = [];\nconst PREFETCH_DELAY_MS = 100;\n\nexport interface DataTableProps<TData> {\n  // `any` is TanStack's recommended type for arrays mixing column value types (e.g. from `createColumnHelper`).\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  columns: ColumnDef<TData, any>[];\n  data: TData[];\n  loading?: boolean;\n  /**\n   * The current rows are stale while a new query loads (SWR's `isValidating`, React Query's `isFetching`). Fades the\n   * rows instead of swapping them for the spinner.\n   */\n  fetching?: boolean;\n  /** Enables the \"Next\" button. */\n  hasMore?: boolean;\n  /**\n   * Cursor pagination. \"Next\" writes this into `query.after`; `null` disables it. Setting either cursor switches the\n   * table from `offset` to cursors, and `hasMore` is ignored.\n   */\n  nextCursor?: string | null;\n  /** Cursor pagination. \"Previous\" writes this into `query.before`; `null` disables it. */\n  previousCursor?: string | null;\n  /** Controlled query (filters, tab, sort, and the `offset` page index or `after` / `before` cursor). */\n  query: TableQuery;\n  setQuery: (query: TableQuery) => void;\n  /** Row identity used for selection and split view. Defaults to `row.id`. */\n  getRowId?: (row: TData) => string;\n\n  /** Left side of the toolbar, typically `<DataTableFilters />`. */\n  toolbar?: React.ReactNode;\n  /** Right side of the toolbar, e.g. an export button. */\n  toolbarActions?: React.ReactNode;\n  /** Show the column visibility dropdown. */\n  showDisplay?: boolean;\n\n  tabs?: TableTab[];\n  tabsOptions?: TableTabsOptions;\n  onTabChange?: (tab: TableTab) => void;\n\n  showPagination?: boolean;\n  /** Render a \"Show more\" link to this URL in the footer (ignored when `showPagination`). */\n  showMore?: string | null;\n  /**\n   * Closing hairline under the last row when there is no pagination or \"Show more\" footer.\n   * Leave this off when the table sits inside a bordered container.\n   */\n  showBottomBorder?: boolean;\n\n  /** Make each row a link. Cells in `select`/`actions` columns, or with `meta.disableRowLink`, are excluded. */\n  url?: (row: TData) => string | undefined;\n  onRowClick?: (row: TData) => void;\n  /** Component used for row links and \"Show more\". Overrides `DataTableRouter`. Defaults to `<a>`. */\n  linkComponent?: DataTableLinkComponent;\n  /** Programmatic navigation, used on mobile when split view is enabled. Overrides `DataTableRouter`. */\n  onNavigate?: (url: string) => void;\n  /** Called (debounced, once per URL) when a linked row is hovered. Overrides `DataTableRouter`. */\n  onPrefetch?: (url: string) => void;\n\n  customRowClassName?: (row: TData) => string | undefined;\n  noResultsText?: string;\n  /** Replaces the \"no results\" message. */\n  emptyState?: React.ReactNode;\n  /** Replaces the loading spinner. */\n  loadingState?: React.ReactNode;\n\n  /** Map column id → API sort field for server-side sortable columns, e.g. `{ created: 'createdAt' }`. */\n  sortableColumns?: Record<string, string>;\n\n  contextMenuActions?: Action<TData>[] | ((row: TData) => Action<TData>[]);\n\n  /** Render a detail panel beside the table. Up/down arrow keys move between rows. */\n  splitView?: {\n    component: (row: TData | null) => React.ReactNode;\n  };\n\n  /** Adds a chevron column at the end; each chevron toggles a full-width panel under its row. Several can be open. */\n  expandable?: {\n    component: (row: TData) => React.ReactNode;\n    /** Return `false` to hide a row's chevron. */\n    canExpand?: (row: TData) => boolean;\n    /**\n     * `'row'` makes a click anywhere on an expandable row toggle it, so `url` doesn't link those rows. The chevron stays\n     * as the keyboard control. Defaults to `'chevron'`.\n     */\n    trigger?: 'chevron' | 'row';\n  };\n\n  enableSelection?: boolean;\n  /** Selected rows; persists across pages. */\n  selectedRows?: TData[];\n  onSelectionChange?: (selectedRows: TData[]) => void;\n  /** Return `false` to make a row unselectable. */\n  selectedRowFilter?: (row: TData) => boolean;\n  selectionActions?: SelectionAction<TData>[];\n  renderSelectionStatus?: React.ComponentProps<typeof SelectionActionBar<TData>>['renderStatus'];\n\n  /** Passed through to TanStack's `table.options.meta`, available to cells via `table.options.meta`. */\n  meta?: TableMeta<TData>;\n  className?: string;\n}\n\nfunction DataTableInner<TData>({\n  columns,\n  data: dataProp,\n  loading,\n  fetching = false,\n  hasMore,\n  nextCursor,\n  previousCursor,\n  query,\n  setQuery,\n  getRowId = defaultGetRowId,\n  toolbar,\n  toolbarActions,\n  showDisplay = false,\n  tabs,\n  tabsOptions,\n  onTabChange,\n  showPagination = false,\n  showMore = null,\n  showBottomBorder = false,\n  url,\n  onRowClick,\n  linkComponent,\n  onNavigate,\n  onPrefetch,\n  customRowClassName,\n  noResultsText = 'No results',\n  emptyState,\n  loadingState,\n  sortableColumns,\n  contextMenuActions,\n  splitView,\n  expandable,\n  enableSelection = false,\n  selectedRows = EMPTY_SELECTED_ROWS as TData[],\n  onSelectionChange,\n  selectedRowFilter,\n  selectionActions = EMPTY_SELECTION_ACTIONS as SelectionAction<TData>[],\n  renderSelectionStatus,\n  meta,\n  className,\n}: DataTableProps<TData>) {\n  const routing = useDataTableRouter();\n  const Link = linkComponent ?? routing.linkComponent ?? 'a';\n  const navigate = onNavigate ?? routing.onNavigate ?? ((href: string) => window.location.assign(href));\n  const prefetch = onPrefetch ?? routing.onPrefetch;\n\n  const data = dataProp.length === 0 ? (EMPTY_DATA as TData[]) : dataProp;\n  const isMobile = useMediaQuery('(max-width: 768px)');\n\n  const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({});\n  const [expanded, setExpanded] = React.useState<ExpandedState>({});\n  const [splitViewRow, setSplitViewRow] = React.useState<TData | null>(null);\n  const splitViewRowId = splitViewRow ? getRowId(splitViewRow) : null;\n\n  // --- Prefetch on hover ---------------------------------------------------\n  const prefetchedUrls = React.useRef(new Set<string>());\n  const prefetchTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const cancelPrefetch = React.useCallback(() => {\n    if (prefetchTimer.current) {\n      clearTimeout(prefetchTimer.current);\n      prefetchTimer.current = null;\n    }\n  }, []);\n\n  const debouncedPrefetch = React.useCallback(\n    (rowUrl: string) => {\n      if (!prefetch) return;\n      cancelPrefetch();\n      prefetchTimer.current = setTimeout(() => {\n        if (prefetchedUrls.current.has(rowUrl)) return;\n        prefetchedUrls.current.add(rowUrl);\n        prefetch(rowUrl);\n      }, PREFETCH_DELAY_MS);\n    },\n    [prefetch, cancelPrefetch]\n  );\n\n  React.useEffect(() => cancelPrefetch, [cancelPrefetch]);\n\n  // --- Selection -----------------------------------------------------------\n  const selectedIds = React.useMemo(() => new Set(selectedRows.map(getRowId)), [selectedRows, getRowId]);\n  const rowSelection = React.useMemo<RowSelectionState>(\n    () => Object.fromEntries(Array.from(selectedIds, (id) => [id, true])),\n    [selectedIds]\n  );\n  const isSelectable = React.useCallback(\n    (row: TData) => !selectedRowFilter || selectedRowFilter(row),\n    [selectedRowFilter]\n  );\n\n  const handleRowSelectionChange = React.useCallback(\n    (updater: Updater<RowSelectionState>) => {\n      if (!onSelectionChange) return;\n      const next = typeof updater === 'function' ? updater(rowSelection) : updater;\n      const pageIds = new Set(data.map(getRowId));\n      // Rows selected on other pages stay selected; this page's selection is replaced.\n      const otherPages = selectedRows.filter((row) => !pageIds.has(getRowId(row)));\n      const thisPage = data.filter((row) => next[getRowId(row)]);\n      onSelectionChange([...thisPage, ...otherPages]);\n    },\n    [onSelectionChange, rowSelection, data, getRowId, selectedRows]\n  );\n\n  const selectAllRows = React.useCallback(() => {\n    const additions = data.filter((row) => isSelectable(row) && !selectedIds.has(getRowId(row)));\n    onSelectionChange?.([...selectedRows, ...additions]);\n  }, [data, isSelectable, selectedIds, getRowId, onSelectionChange, selectedRows]);\n\n  const hasExpandable = Boolean(expandable);\n  const panelIdPrefix = React.useId();\n\n  const selectionColumn = React.useMemo<ColumnDef<TData> | null>(() => {\n    if (!enableSelection) return null;\n\n    const selectableRows = data.filter(isSelectable);\n    const allSelected = selectableRows.length > 0 && selectableRows.every((row) => selectedIds.has(getRowId(row)));\n\n    return {\n      id: 'select',\n      header: () => (\n        <Checkbox\n          checked={allSelected}\n          disabled={selectableRows.length === 0}\n          onCheckedChange={(value) => {\n            if (value) {\n              selectAllRows();\n            } else {\n              const pageIds = new Set(selectableRows.map(getRowId));\n              onSelectionChange?.(selectedRows.filter((row) => !pageIds.has(getRowId(row))));\n            }\n          }}\n          onClick={(e) => e.stopPropagation()}\n          aria-label=\"Select all\"\n        />\n      ),\n      cell: ({ row }) => {\n        const id = getRowId(row.original);\n        return (\n          <Checkbox\n            checked={selectedIds.has(id)}\n            disabled={!isSelectable(row.original)}\n            onCheckedChange={(value) => {\n              onSelectionChange?.(\n                value ? [...selectedRows, row.original] : selectedRows.filter((r) => getRowId(r) !== id)\n              );\n            }}\n            onClick={(e) => e.stopPropagation()}\n            aria-label=\"Select row\"\n          />\n        );\n      },\n      enableSorting: false,\n      enableHiding: false,\n      meta: { minimize: true },\n    };\n  }, [enableSelection, data, isSelectable, selectedIds, getRowId, selectAllRows, onSelectionChange, selectedRows]);\n\n  const expandColumn = React.useMemo<ColumnDef<TData> | null>(() => {\n    if (!hasExpandable) return null;\n\n    return {\n      id: 'expand',\n      header: () => null,\n      cell: ({ row }) => {\n        if (!row.getCanExpand()) return null;\n        const isExpanded = row.getIsExpanded();\n        return (\n          <Button\n            variant=\"ghost\"\n            size=\"icon\"\n            className=\"text-muted-foreground -my-1 size-8 md:size-6\"\n            aria-expanded={isExpanded}\n            aria-controls={`${panelIdPrefix}-${row.id}`}\n            aria-label={isExpanded ? 'Collapse row' : 'Expand row'}\n            onClick={(e) => {\n              e.stopPropagation();\n              row.toggleExpanded();\n            }}>\n            <ChevronDown\n              className={cn(\n                'size-4 transition-transform duration-150 motion-reduce:transition-none',\n                isExpanded && 'rotate-180'\n              )}\n            />\n          </Button>\n        );\n      },\n      enableSorting: false,\n      enableHiding: false,\n      meta: { align: 'right', minimize: true },\n    };\n  }, [hasExpandable, panelIdPrefix]);\n\n  const tableColumns = React.useMemo(() => {\n    if (!selectionColumn && !expandColumn) return columns;\n    return [selectionColumn, ...columns, expandColumn].filter((column) => column !== null);\n  }, [selectionColumn, expandColumn, columns]);\n\n  const table = useReactTable({\n    data,\n    columns: tableColumns,\n    getCoreRowModel: getCoreRowModel(),\n    getRowId: (row) => getRowId(row),\n    onColumnVisibilityChange: setColumnVisibility,\n    onRowSelectionChange: handleRowSelectionChange,\n    onExpandedChange: setExpanded,\n    state: { columnVisibility, rowSelection, expanded },\n    enableRowSelection: enableSelection ? (row) => isSelectable(row.original) : false,\n    getRowCanExpand: (row) => (expandable ? (expandable.canExpand?.(row.original) ?? true) : false),\n    meta,\n  });\n\n  // --- Pagination & sorting ------------------------------------------------\n  const offset = Number(query.offset || 0);\n  // Cursors are usually `undefined` while a page loads, so a cursor already in the query keeps cursor mode on.\n  const usesCursors =\n    nextCursor !== undefined || previousCursor !== undefined || query.after !== undefined || query.before !== undefined;\n  const isFirstPage = usesCursors ? query.after === undefined && query.before === undefined : offset === 0;\n  const canGoNext = usesCursors ? Boolean(nextCursor) : Boolean(hasMore);\n  const canGoPrevious = usesCursors ? Boolean(previousCursor) : offset > 0;\n\n  const goToNextPage = () => {\n    if (!usesCursors) return setQuery({ ...query, offset: offset + 1 });\n    if (nextCursor) setQuery({ ...withoutPage(query), after: nextCursor });\n  };\n  const goToPreviousPage = () => {\n    if (!usesCursors) return setQuery({ ...query, offset: Math.max(offset - 1, 0) });\n    if (previousCursor) setQuery({ ...withoutPage(query), before: previousCursor });\n  };\n\n  const sortField = (query.sort_field as string | undefined) ?? '';\n  const sortDirection = (query.sort as string | undefined) || 'descending';\n\n  const handleSort = (columnId: string) => {\n    const field = sortableColumns?.[columnId];\n    if (!field) return;\n    const nextSort = sortField === field && sortDirection === 'descending' ? 'ascending' : 'descending';\n    setQuery({ ...withoutPage(query), sort: nextSort, sort_field: field });\n  };\n\n  // --- Split view ----------------------------------------------------------\n  const hasSplitView = Boolean(splitView);\n\n  React.useEffect(() => {\n    if (!hasSplitView) return;\n    // Keep the selected row (with fresh data) if it's still on the page, otherwise fall back to the first row.\n    setSplitViewRow((current) => {\n      const currentId = current ? getRowId(current) : null;\n      return data.find((row) => getRowId(row) === currentId) ?? data[0] ?? null;\n    });\n  }, [hasSplitView, data, getRowId]);\n\n  const moveSplitView = (delta: 1 | -1) => {\n    if (data.length === 0) return;\n    const index = data.findIndex((row) => getRowId(row) === splitViewRowId);\n    const next = index < 0 ? 0 : Math.min(Math.max(index + delta, 0), data.length - 1);\n    setSplitViewRow(data[next] ?? null);\n  };\n\n  const paginationHotkeys = (showPagination || hasSplitView) && data.length > 0;\n  useHotkey('ArrowDown', () => moveSplitView(1), hasSplitView);\n  useHotkey('ArrowUp', () => moveSplitView(-1), hasSplitView);\n  useHotkey('ArrowRight', goToNextPage, paginationHotkeys && canGoNext);\n  useHotkey('ArrowLeft', goToPreviousPage, paginationHotkeys && canGoPrevious);\n\n  const hasToolbar = Boolean(toolbar || toolbarActions || showDisplay);\n  const hasTopBorder = hasToolbar || Boolean(tabs);\n\n  return (\n    <div data-slot=\"data-table\" className={cn('flex flex-col', hasSplitView && 'flex-1', className)}>\n      {hasToolbar && (\n        <div\n          className={cn(\n            'flex flex-col items-start justify-between gap-4 px-5 md:flex-row md:gap-2',\n            !tabs && 'pb-2.5'\n          )}>\n          {toolbar ?? <div />}\n          <div className=\"flex items-center gap-2\">\n            {toolbarActions}\n            {showDisplay && <DataTableDisplay table={table} align={toolbar ? 'end' : 'start'} />}\n          </div>\n        </div>\n      )}\n\n      {tabs && (\n        <div className=\"pt-1\">\n          <DataTableTabs tabs={tabs} query={query} setQuery={setQuery} options={tabsOptions} onChange={onTabChange} />\n        </div>\n      )}\n\n      <div className={cn('flex w-full flex-row', hasSplitView && 'flex-1')}>\n        <div className={cn('min-w-0 flex-1', hasTopBorder && 'border-t', hasSplitView && 'border-r md:w-1/2')}>\n          {loading ? (\n            (loadingState ?? (\n              <div className=\"flex h-30 items-center justify-center\" role=\"status\" aria-label=\"Loading\">\n                <Loader2 className=\"text-muted-foreground size-5 animate-spin\" />\n              </div>\n            ))\n          ) : (\n            <>\n              <div\n                aria-busy={fetching}\n                className={cn(\n                  'transition-opacity duration-150 motion-reduce:transition-none',\n                  // The delay applies only on the way in, so quick responses don't flicker.\n                  fetching && 'opacity-60 delay-100'\n                )}>\n                <Table containerClassName={cn(expandable && '@container')}>\n                  {data.length > 0 && (\n                    <TableHeader>\n                      {table.getHeaderGroups().map((headerGroup) => (\n                        <TableRow key={headerGroup.id} className=\"hover:bg-transparent\">\n                          {headerGroup.headers.map((header) => {\n                            const columnMeta = header.column.columnDef.meta;\n                            const columnId = header.column.id;\n                            const isSortable = Boolean(sortableColumns && columnId in sortableColumns);\n                            const isSorted = isSortable && sortField === sortableColumns?.[columnId];\n                            const content = header.isPlaceholder\n                              ? null\n                              : flexRender(header.column.columnDef.header, header.getContext());\n                            return (\n                              <TableHead\n                                key={header.id}\n                                className={cn(\n                                  'text-xs font-bold uppercase',\n                                  columnMeta?.align === 'center' && 'text-center',\n                                  columnMeta?.align === 'right' && 'text-right',\n                                  columnMeta?.minimize && 'w-px'\n                                )}\n                                aria-sort={\n                                  isSortable\n                                    ? isSorted\n                                      ? (sortDirection as 'ascending' | 'descending')\n                                      : 'none'\n                                    : undefined\n                                }>\n                                {isSortable ? (\n                                  <Button\n                                    variant=\"ghost\"\n                                    size=\"sm\"\n                                    className=\"hover:bg-muted -ml-2 h-8 gap-1.5 px-2 text-xs font-bold uppercase\"\n                                    onClick={() => handleSort(columnId)}>\n                                    {content}\n                                    {isSorted && sortDirection === 'ascending' ? (\n                                      <ArrowUp className=\"size-3.5 opacity-70\" />\n                                    ) : isSorted ? (\n                                      <ArrowDown className=\"size-3.5 opacity-70\" />\n                                    ) : (\n                                      <ArrowUp className=\"size-3.5 opacity-30\" aria-hidden />\n                                    )}\n                                  </Button>\n                                ) : (\n                                  content\n                                )}\n                              </TableHead>\n                            );\n                          })}\n                        </TableRow>\n                      ))}\n                    </TableHeader>\n                  )}\n                  <TableBody>\n                    {table.getRowModel().rows.map((row) => {\n                      const isActive = hasSplitView && row.id === splitViewRowId;\n                      const expandsOnClick = expandable?.trigger === 'row' && row.getCanExpand();\n                      const rowUrl = expandsOnClick ? undefined : url?.(row.original);\n                      const isInteractive = Boolean(rowUrl || hasSplitView || onRowClick || expandsOnClick);\n\n                      const handleRowClick = () => {\n                        if (expandsOnClick) row.toggleExpanded();\n                        if (hasSplitView) setSplitViewRow(row.original);\n                        onRowClick?.(row.original);\n                        // The split panel is hidden on mobile, so go to the row's page instead.\n                        if (hasSplitView && isMobile && rowUrl) navigate(rowUrl);\n                      };\n\n                      // One context menu per row (not per cell) keeps the number of menu trees down.\n                      const rowActions =\n                        typeof contextMenuActions === 'function'\n                          ? contextMenuActions(row.original)\n                          : contextMenuActions;\n\n                      return (\n                        <React.Fragment key={row.id}>\n                          <TableContextMenu childAsTrigger row={row.original} actions={rowActions}>\n                            <TableRow\n                              data-state={row.getIsSelected() ? 'selected' : undefined}\n                              data-active={isActive || undefined}\n                              onMouseEnter={rowUrl && prefetch ? () => debouncedPrefetch(rowUrl) : undefined}\n                              onMouseLeave={rowUrl && prefetch ? cancelPrefetch : undefined}\n                              className={cn(\n                                customRowClassName?.(row.original),\n                                isInteractive && 'hover:bg-muted/50 cursor-pointer',\n                                'data-[state=selected]:bg-muted/40',\n                                isActive && 'bg-muted/75 shadow-[inset_4px_0px_var(--primary)]'\n                              )}>\n                              {row.getVisibleCells().map((cell) => {\n                                const columnMeta = cell.column.columnDef.meta;\n                                const content = (\n                                  <TableCellContent\n                                    className={cn(\n                                      'h-full min-h-10 w-full',\n                                      columnMeta?.align === 'center' && 'justify-center',\n                                      columnMeta?.align === 'right' && 'justify-end',\n                                      columnMeta?.itemAlign === 'start' ? 'items-start' : 'items-center'\n                                    )}>\n                                    {flexRender(cell.column.columnDef.cell, cell.getContext())}\n                                  </TableCellContent>\n                                );\n                                const skipRowLink =\n                                  cell.column.id === 'select' ||\n                                  cell.column.id === 'expand' ||\n                                  cell.column.id === 'actions' ||\n                                  columnMeta?.disableRowLink;\n\n                                let wrapped = content;\n                                if (!skipRowLink) {\n                                  if (hasSplitView || (!rowUrl && onRowClick)) {\n                                    wrapped = (\n                                      <div\n                                        role=\"button\"\n                                        tabIndex={0}\n                                        onClick={handleRowClick}\n                                        onKeyDown={(e) => {\n                                          if (e.key === 'Enter' || e.key === ' ') {\n                                            e.preventDefault();\n                                            handleRowClick();\n                                          }\n                                        }}\n                                        className=\"block h-full w-full text-left outline-none\">\n                                        {content}\n                                      </div>\n                                    );\n                                  } else if (expandsOnClick) {\n                                    // Mouse only: the chevron's button is the keyboard control and carries aria-expanded.\n                                    wrapped = (\n                                      <div onClick={handleRowClick} className=\"block h-full w-full\">\n                                        {content}\n                                      </div>\n                                    );\n                                  } else if (rowUrl) {\n                                    wrapped = (\n                                      <Link\n                                        href={rowUrl}\n                                        className=\"block h-full w-full\"\n                                        {...(onRowClick ? { onClick: () => onRowClick(row.original) } : {})}>\n                                        {content}\n                                      </Link>\n                                    );\n                                  }\n                                }\n\n                                return (\n                                  <TableCell\n                                    key={cell.id}\n                                    className={cn(\n                                      'leading-6.5',\n                                      columnMeta?.verticalAlign === 'top' && 'align-top',\n                                      columnMeta?.verticalAlign === 'bottom' && 'align-bottom',\n                                      columnMeta?.minimize && 'w-px'\n                                    )}>\n                                    {wrapped}\n                                  </TableCell>\n                                );\n                              })}\n                            </TableRow>\n                          </TableContextMenu>\n                          {expandable && row.getIsExpanded() && (\n                            <TableRow data-slot=\"table-row-expanded\" className=\"hover:bg-transparent\">\n                              <TableCell\n                                id={`${panelIdPrefix}-${row.id}`}\n                                colSpan={row.getVisibleCells().length}\n                                className=\"p-0 whitespace-normal\">\n                                {/* Pinned to the visible width so wide tables don't scroll the panel out of view. */}\n                                <div className=\"animate-in fade-in sticky left-0 max-w-[100cqw] px-5 py-3 duration-150\">\n                                  {expandable.component(row.original)}\n                                </div>\n                              </TableCell>\n                            </TableRow>\n                          )}\n                        </React.Fragment>\n                      );\n                    })}\n                  </TableBody>\n                </Table>\n\n                {data.length === 0 &&\n                  (emptyState ? (\n                    <div className=\"p-4\">{emptyState}</div>\n                  ) : (\n                    <div className=\"py-4\">\n                      <TableError error={noResultsText} />\n                    </div>\n                  ))}\n              </div>\n\n              {data.length > 0 && !showPagination && !showMore && showBottomBorder && <div className=\"border-t\" />}\n\n              {data.length > 0 && showMore && !showPagination && (\n                <div className=\"flex items-center justify-center border-t px-5 py-2.5\">\n                  <Link\n                    href={showMore}\n                    className=\"text-primary hover:text-primary/80 flex items-center gap-1 text-sm font-medium\">\n                    Show more\n                    <ArrowRight className=\"size-4\" />\n                  </Link>\n                </div>\n              )}\n\n              {showPagination && (data.length > 0 || !isFirstPage) && (\n                <div className=\"flex items-center justify-between border-t px-5 py-3\">\n                  <p className=\"text-muted-foreground text-sm tabular-nums\">\n                    {data.length} result{data.length === 1 ? '' : 's'}\n                    {!usesCursors && offset > 0 && ` · page ${offset + 1}`}\n                  </p>\n                  <div className=\"flex items-center gap-x-2\">\n                    <Button variant=\"outline\" size=\"sm\" onClick={goToPreviousPage} disabled={!canGoPrevious}>\n                      Previous\n                    </Button>\n                    <Button variant=\"outline\" size=\"sm\" onClick={goToNextPage} disabled={!canGoNext}>\n                      Next\n                    </Button>\n                  </div>\n                </div>\n              )}\n            </>\n          )}\n        </div>\n\n        {splitView && (\n          <div className={cn('relative hidden flex-1 md:block', hasTopBorder && 'border-t')}>\n            <div className=\"absolute inset-0 overflow-y-auto\">{splitView.component(splitViewRow)}</div>\n          </div>\n        )}\n      </div>\n\n      {enableSelection && selectedRows.length > 0 && (\n        <SelectionActionBar\n          selectedRows={selectedRows}\n          actions={selectionActions}\n          onClearSelection={() => onSelectionChange?.([])}\n          onSelectAll={selectAllRows}\n          renderStatus={renderSelectionStatus}\n        />\n      )}\n    </div>\n  );\n}\n\n/**\n * Server-driven data table built on TanStack Table. Data fetching stays with you: read `query`, fetch, and pass\n * `data`/`loading` and `hasMore` (or `nextCursor`/`previousCursor`) back in.\n */\nexport function DataTable<TData>(props: DataTableProps<TData>) {\n  // Reset the boundary when the data or query changes so a transient render error doesn't wedge the table.\n  return (\n    <TableErrorBoundary resetKeys={[props.data, props.query]}>\n      <DataTableInner<TData> {...props} />\n    </TableErrorBoundary>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/data-table.tsx"
    },
    {
      "path": "components/dentil/data-table/router.tsx",
      "content": "'use client';\n\nimport { createContext, use, type ReactNode } from 'react';\n\nimport type { DataTableLinkComponent } from './types';\n\nexport interface DataTableRouterProps {\n  /** Component used for row links and \"Show more\". Pass `next/link`, React Router's `Link`, etc. */\n  linkComponent?: DataTableLinkComponent;\n  /** Programmatic navigation, used on mobile when split view is enabled. */\n  onNavigate?: (url: string) => void;\n  /** Called (debounced, once per URL) when a linked row is hovered, e.g. `router.prefetch`. */\n  onPrefetch?: (url: string) => void;\n  children: ReactNode;\n}\n\nconst DataTableRouterContext = createContext<Omit<DataTableRouterProps, 'children'>>({});\n\n/** Sets the link component and navigation for every `DataTable` below it. A table's own props override these. */\nexport function DataTableRouter({ linkComponent, onNavigate, onPrefetch, children }: DataTableRouterProps) {\n  return <DataTableRouterContext value={{ linkComponent, onNavigate, onPrefetch }}>{children}</DataTableRouterContext>;\n}\n\nexport function useDataTableRouter() {\n  return use(DataTableRouterContext);\n}\n",
      "type": "registry:component",
      "target": "components/dentil/data-table/router.tsx"
    }
  ],
  "type": "registry:block"
}
