{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "table-data",
  "title": "Table data",
  "description": "The data behind a Table: sorting by one column or several, searching, filtering by picked values or a range, pages, picked rows across pages with Shift for a range, and hidden columns, in the browser or on a server. TanStack Table works it out; the hook hands back plain values for the Table’s parts. The Table installs it.",
  "dependencies": [
    "@tanstack/react-table@~9.3.1"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/dates.json",
    "https://kinoui.com/r/pages.json"
  ],
  "files": [
    {
      "path": "registry/lib/table-data.tsx",
      "content": "'use client'\n\nimport { announce } from '@/registry/lib/announce'\nimport { useControllable } from '@/registry/lib/controllable'\nimport { daysBetween, isISODate, useLocale } from '@/registry/lib/dates'\nimport { clampPage, pageCountOf, pageForSize, pageRange } from '@/registry/lib/pages'\nimport {\n  columnFacetingFeature,\n  columnFilteringFeature,\n  columnSizingFeature,\n  columnVisibilityFeature,\n  createExpandedRowModel,\n  createFacetedRowModel,\n  createFacetedUniqueValues,\n  constructFilterFn,\n  createFilteredRowModel,\n  createSortedRowModel,\n  filterFn_includesString,\n  globalFilteringFeature,\n  rowExpandingFeature,\n  rowSelectionFeature,\n  rowSortingFeature,\n  tableFeatures,\n  type ExpandedState,\n  type RowData,\n  type RowSelectionState,\n  type Updater,\n  useTable,\n} from '@tanstack/react-table'\nimport {\n  type ReactNode,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\n/*\n * The data behind a Table: what it sorts, searches, filters, pages, picks\n * and hides, in the browser or on a server. TanStack Table works it out, as\n * a function of state kept here, and the hook hands back plain values for\n * Kino's parts: nothing reads state through TanStack's own objects, which\n * stay the same while the state changes (the React Compiler would keep a\n * part that reads them as it was).\n */\n\n/** What a column sorts, filters and searches by: text, a number, a `yyyy-mm-dd` date or a yes or no. */\nexport type TableValue = string | number | boolean | null | undefined\n\nexport type TableSortDirection = 'ascending' | 'descending'\n\nexport interface TableSortBy {\n  column: string\n  direction: TableSortDirection\n}\n\n/** Values from `from` to `to`, both included; numbers, or `yyyy-mm-dd` dates. Either end may be left open. */\nexport interface TableRange {\n  from?: number | string\n  to?: number | string\n}\n\n/** The values picked in an `options` filter, or the range of a `range` filter. */\nexport type TableFilter = readonly string[] | TableRange\n\n/** Everything that decides which rows show and how: one object, for the URL, a saved view or a server. */\nexport interface TableView {\n  sort: TableSortBy[]\n  search: string\n  /** By column id; columns all have to match, a column's picked values any one. */\n  filters: Record<string, TableFilter>\n  /** Counted from 1. */\n  page: number\n  /** Rows on a page; none for one page of every row. */\n  pageSize?: number\n  hiddenColumns: string[]\n  /** Widths in px of the columns a person has resized, by column id. */\n  columnWidths: Record<string, number>\n}\n\nexport interface TableOption {\n  value: string\n  label: string\n  /** How many rows have it, with the other filters and the search applied. */\n  count?: number\n}\n\nexport interface TableColumn<Row> {\n  id: string\n  /** Its header, and its name in a columns menu, a filter and what is read out. */\n  label: string\n  /** What it sorts, filters and searches by. */\n  value?: (row: Row) => TableValue\n  /** What its cells show: `value` by default. */\n  cell?: (row: Row) => ReactNode\n  sortable?: boolean\n  /** Whether the search reads it: by default, when its values are text. */\n  searchable?: boolean\n  /** `options` picks among its values; `range` keeps the values between two. */\n  filter?: 'options' | 'range'\n  /** The values an `options` filter offers: the distinct values in the rows by default, or the server's, with its counts. */\n  options?: readonly TableOption[]\n  /** Lines it up at its end edge in figures of one width. */\n  numeric?: boolean\n  /** Its width and how its text wraps, given to its head and cells. */\n  className?: string\n  /** Whether a columns menu may hide it; true by default. */\n  hideable?: boolean\n  /** Whether a person may drag its edge to resize it. */\n  resizable?: boolean\n  /** Its width in px until it is resized; its laid-out width by default. */\n  width?: number\n  /** The narrowest a resize takes it, in px: 64 by default. */\n  minWidth?: number\n  /** The widest a resize takes it, in px: 800 by default. */\n  maxWidth?: number\n  /** What it writes in a CSV export: `value` by default. */\n  csv?: (row: Row) => string | number | boolean | null | undefined\n}\n\n/** Every word the hook reads out, for a table in another language. */\nexport interface TableMessages {\n  /** One column of a sort: “Amount, highest first”. */\n  sortedBy: (label: string, direction: TableSortDirection, kind: TableValueKind) => string\n  /** After a sort, its columns in order: “Sorted by Customer, A to Z, then Amount, highest first”. */\n  sorted: (columns: string[]) => string\n  /** After a page turn: “Page 2 of 5”. */\n  page: (page: number, pageCount: number) => string\n  /** After a filter changes or clears, how many rows match: “6 rows”. */\n  matched: (count: number) => string\n}\n\n/** What kind of values a column holds, which decides the way it sorts first and the words for its order. */\nexport type TableValueKind = 'text' | 'number' | 'date' | 'boolean'\n\nconst ORDER_WORDS: Record<TableValueKind, Record<TableSortDirection, string>> = {\n  text: { ascending: 'A to Z', descending: 'Z to A' },\n  number: { ascending: 'lowest first', descending: 'highest first' },\n  date: { ascending: 'oldest first', descending: 'newest first' },\n  boolean: { ascending: 'no first', descending: 'yes first' },\n}\n\nconst defaultMessages: TableMessages = {\n  sortedBy: (label, direction, kind) => `${label}, ${ORDER_WORDS[kind][direction]}`,\n  sorted: (columns) => `Sorted by ${columns.join(', then ')}`,\n  page: (page, pageCount) => `Page ${page} of ${pageCount}`,\n  matched: (count) => `${count} ${count === 1 ? 'row' : 'rows'}`,\n}\n\n/** How a `TableHead` sorts its column. */\nexport interface TableSortProps {\n  sort: TableSortDirection | 'none'\n  /** Its place in a sort by several columns, from 1; none when it sorts alone or not at all. */\n  sortIndex?: number\n  /** Shift adds the column to the sort. */\n  onSort: (event: { shiftKey: boolean }) => void\n}\n\n/** How a `TableExpand` shows its row. */\nexport interface TableExpandProps {\n  depth: number\n  expandable: boolean\n  expanded: boolean\n  onExpandedChange: (expanded: boolean) => void\n}\n\n/** A resizable `TableHead`'s width, in px, and its change: undefined puts it back. */\nexport interface TableWidthProps {\n  width: number | undefined\n  minWidth: number\n  maxWidth: number\n  onWidthChange: (width: number | undefined) => void\n}\n\n/** The props of the `CheckboxGroup` around the table: this page's rows, merged into everything picked. */\nexport interface TableSelectionProps {\n  value: string[]\n  allValues: string[]\n  onValueChange: (value: string[], details: { event?: Event }) => void\n}\n\nexport interface UseTableDataOptions<Row> {\n  rows: readonly Row[]\n  /** The language its text sorts in. The visitor's own by default. */\n  locale?: string\n  /** Keep it the same between renders: a constant, or memoised. */\n  columns: readonly TableColumn<Row>[]\n  /** What tells one row from another, kept across pages, sorts and filters. */\n  rowId: (row: Row) => string\n  /** `rows` are already sorted, searched, filtered and paged, by a server. */\n  manual?: boolean\n  /** With `manual`: how many rows match on the server. */\n  rowCount?: number\n\n  view?: Partial<TableView>\n  defaultView?: Partial<TableView>\n  onViewChange?: (view: TableView) => void\n  sort?: TableSortBy[]\n  defaultSort?: TableSortBy[]\n  onSortChange?: (sort: TableSortBy[]) => void\n  search?: string\n  defaultSearch?: string\n  onSearchChange?: (search: string) => void\n  filters?: Record<string, TableFilter>\n  defaultFilters?: Record<string, TableFilter>\n  onFiltersChange?: (filters: Record<string, TableFilter>) => void\n  page?: number\n  defaultPage?: number\n  onPageChange?: (page: number) => void\n  pageSize?: number\n  defaultPageSize?: number\n  onPageSizeChange?: (pageSize: number) => void\n  hiddenColumns?: string[]\n  defaultHiddenColumns?: string[]\n  onHiddenColumnsChange?: (hidden: string[]) => void\n  columnWidths?: Record<string, number>\n  defaultColumnWidths?: Record<string, number>\n  onColumnWidthsChange?: (widths: Record<string, number>) => void\n\n  /** The ids of the rows picked. */\n  selected?: string[]\n  defaultSelected?: string[]\n  onSelectedChange?: (selected: string[]) => void\n  /** With `manual`: every row that matches is picked, beyond the ones loaded. It clears when the view changes. */\n  allMatching?: boolean\n  defaultAllMatching?: boolean\n  onAllMatchingChange?: (allMatching: boolean) => void\n\n  /** A row's own rows, shown under it, indented, once it is expanded. */\n  subRows?: (row: Row) => readonly Row[] | undefined\n  /** Without `subRows`: which rows open a detail row of their own; every row with `true`. */\n  expandable?: boolean | ((row: Row) => boolean)\n  /** The ids of the rows expanded. */\n  expanded?: string[]\n  defaultExpanded?: string[]\n  onExpandedChange?: (expanded: string[]) => void\n\n  /** How long the search waits after the last keystroke, in ms: 0 by default, 300 with `manual`. */\n  searchWait?: number\n  messages?: Partial<TableMessages>\n}\n\nconst EMPTY: never[] = []\nconst EMPTY_FILTERS: Record<string, TableFilter> = {}\nconst EMPTY_WIDTHS: Record<string, number> = {}\nconst MIN_WIDTH = 64\nconst MAX_WIDTH = 800\n\nconst collators = new Map<string, Intl.Collator>()\n\n/** How `locale` orders text as people read it (“Item 2” before “Item 10”), made once. */\nfunction collatorFor(locale: string): Intl.Collator {\n  let collator = collators.get(locale)\n  if (!collator) {\n    collator = new Intl.Collator(locale, { numeric: true, sensitivity: 'base' })\n    collators.set(locale, collator)\n  }\n  return collator\n}\n\n/** A row as a sort reads it: its value in a column. */\ninterface SortedRow {\n  getValue: (columnId: string) => unknown\n}\n\n/** The table's sort for `locale`: its rows by their values in a column, empty ones placed by `sortUndefined`. */\nfunction sortFnFor(locale: string) {\n  return (a: SortedRow, b: SortedRow, columnId: string) =>\n    compareValues(\n      a.getValue(columnId) as TableValue,\n      b.getValue(columnId) as TableValue,\n      locale,\n    )\n}\n\nconst features = tableFeatures({\n  rowSortingFeature,\n  globalFilteringFeature,\n  columnFilteringFeature,\n  columnFacetingFeature,\n  rowSelectionFeature,\n  columnVisibilityFeature,\n  columnSizingFeature,\n  rowExpandingFeature,\n  sortedRowModel: createSortedRowModel(),\n  expandedRowModel: createExpandedRowModel(),\n  filteredRowModel: createFilteredRowModel(),\n  facetedRowModel: createFacetedRowModel(),\n  facetedUniqueValues: createFacetedUniqueValues(),\n  filterFns: {\n    includesString: filterFn_includesString,\n    options: constructFilterFn({\n      filter: (value: unknown, picked: unknown) =>\n        Array.isArray(picked) && matchesOptions(value as TableValue, picked as string[]),\n    }),\n    range: constructFilterFn({\n      filter: (value: unknown, range: unknown) =>\n        inRange(value as TableValue, range as TableRange),\n    }),\n  },\n})\n\n/** An empty value, which sorts last either way and matches no filter. */\nfunction isEmpty(value: TableValue): value is null | undefined | '' {\n  return value === null || value === undefined || value === ''\n}\n\n/** What kind of values these are, from the first one that isn't empty. */\nfunction kindOf(values: Iterable<TableValue>): TableValueKind {\n  for (const value of values) {\n    if (isEmpty(value)) continue\n    if (typeof value === 'number') return 'number'\n    if (typeof value === 'boolean') return 'boolean'\n    return isISODate(value) ? 'date' : 'text'\n  }\n  return 'text'\n}\n\n/** Two values in order: numbers by size, dates by day, text as people read it in `locale` (“Item 2” before “Item 10”), no before yes. */\nfunction compareValues(a: TableValue, b: TableValue, locale = 'en-US'): number {\n  if (typeof a === 'number' && typeof b === 'number') return a - b\n  if (typeof a === 'boolean' && typeof b === 'boolean') return Number(a) - Number(b)\n  if (isISODate(a) && isISODate(b)) return -daysBetween(a, b)\n  return collatorFor(locale).compare(String(a ?? ''), String(b ?? ''))\n}\n\n/**\n * Rows as CSV: a header line of `labels`, then a line per row, each field\n * quoted where it holds a comma, a quote or a line break. A text field that\n * starts with `=`, `+`, `-`, `@` or a tab is kept as text with a leading `'`,\n * so a spreadsheet never runs it as a formula.\n */\nfunction csvOf(\n  labels: readonly string[],\n  rows: readonly (readonly (string | number | boolean | null | undefined)[])[],\n): string {\n  const field = (value: string | number | boolean | null | undefined) => {\n    if (value === null || value === undefined) return ''\n    let text = String(value)\n    if (typeof value === 'string' && /^[=+\\-@\\t\\r]/.test(text)) text = `'${text}`\n    return /[\",\\r\\n]/.test(text) ? `\"${text.replaceAll('\"', '\"\"')}\"` : text\n  }\n  return [labels, ...rows].map((line) => line.map(field).join(',')).join('\\r\\n')\n}\n\n/** Whether a value is one of the picked ones; none picked matches every row. */\nfunction matchesOptions(value: TableValue, picked: readonly string[]): boolean {\n  if (picked.length === 0) return true\n  return !isEmpty(value) && picked.includes(String(value))\n}\n\n/** Whether a value lies in a range, both ends included; an open end lets everything past it in. */\nfunction inRange(value: TableValue, { from, to }: TableRange): boolean {\n  const open = (end: unknown) => end === undefined || end === null || end === ''\n  if (open(from) && open(to)) return true\n  if (isEmpty(value) || typeof value === 'boolean') return false\n  if (!open(from) && compareValues(value, from as TableValue) < 0) return false\n  return open(to) || compareValues(value, to as TableValue) <= 0\n}\n\n/** Whether a filter lets every row through, so it can be left out. */\nfunction isOpenFilter(filter: TableFilter | undefined): boolean {\n  if (filter === undefined) return true\n  if (isPicked(filter)) return filter.length === 0\n  const open = (end: unknown) => end === undefined || end === null || end === ''\n  return open(filter.from) && open(filter.to)\n}\n\nfunction isPicked(filter: TableFilter): filter is readonly string[] {\n  return Array.isArray(filter)\n}\n\n/** The filters with the open ones left out, so an empty filter never counts as one. */\nfunction activeFilters(\n  filters: Record<string, TableFilter>,\n): Record<string, TableFilter> {\n  const active: Record<string, TableFilter> = {}\n  for (const [column, filter] of Object.entries(filters)) {\n    if (!isOpenFilter(filter)) active[column] = filter\n  }\n  return active\n}\n\n/** The items on `page`, counted from 1; all of them when nothing pages them. */\nfunction pageSlice<T>(\n  items: readonly T[],\n  page: number,\n  pageSize: number | undefined,\n): T[] {\n  if (!pageSize || pageSize <= 0) return [...items]\n  return items.slice((page - 1) * pageSize, page * pageSize)\n}\n\n/** Everything picked once this page's boxes say `pageValue`: the page's own picks replaced, the rest kept in order. */\nfunction mergePageSelection(\n  selected: readonly string[],\n  pageIds: readonly string[],\n  pageValue: readonly string[],\n): string[] {\n  const onPage = new Set(pageIds)\n  const kept = selected.filter((id) => !onPage.has(id))\n  const picked = new Set(pageValue)\n  return [...kept, ...pageIds.filter((id) => picked.has(id))]\n}\n\n/** A sort with each column once and a known column, so a stale view never breaks the table. */\nfunction cleanSort(\n  sort: readonly TableSortBy[],\n  known: ReadonlySet<string>,\n): TableSortBy[] {\n  const seen = new Set<string>()\n  return sort.filter(({ column }) => {\n    if (!known.has(column) || seen.has(column)) return false\n    seen.add(column)\n    return true\n  })\n}\n\n/** Hidden columns that leave at least one shown. */\nfunction cleanHidden(hidden: readonly string[], columns: readonly string[]): string[] {\n  const kept = hidden.filter((id) => columns.includes(id))\n  return kept.length >= columns.length ? kept.slice(0, columns.length - 1) : kept\n}\n\n/** The view's slices that change which rows show, in a form that only changes when they do. */\nfunction viewKey(view: TableView): string {\n  return JSON.stringify([view.sort, view.search, view.filters, view.pageSize])\n}\n\nfunction useTableData<Row extends object>(options: UseTableDataOptions<Row>) {\n  const {\n    rows: data,\n    columns,\n    rowId,\n    manual = false,\n    rowCount: serverCount,\n    searchWait = manual ? 300 : 0,\n    subRows,\n    expandable = false,\n  } = options\n  const locale = useLocale(options.locale)\n  const messages = { ...defaultMessages, ...options.messages }\n  const columnIds = useMemo(() => columns.map((column) => column.id), [columns])\n  const known = useMemo(() => new Set(columnIds), [columnIds])\n\n  // The view: the whole of it the caller's, each slice the caller's, or kept here.\n  const initialView = (): TableView => {\n    const from = options.defaultView ?? {}\n    return {\n      sort: options.defaultSort ?? from.sort ?? EMPTY,\n      search: options.defaultSearch ?? from.search ?? '',\n      filters: options.defaultFilters ?? from.filters ?? EMPTY_FILTERS,\n      page: options.defaultPage ?? from.page ?? 1,\n      pageSize: options.defaultPageSize ?? from.pageSize,\n      hiddenColumns: options.defaultHiddenColumns ?? from.hiddenColumns ?? EMPTY,\n      columnWidths: options.defaultColumnWidths ?? from.columnWidths ?? EMPTY_WIDTHS,\n    }\n  }\n  const [ownView, setOwnView] = useState(initialView)\n  const given = options.view\n  const view: TableView = {\n    sort: cleanSort(options.sort ?? given?.sort ?? ownView.sort, known),\n    search: options.search ?? given?.search ?? ownView.search,\n    filters: options.filters ?? given?.filters ?? ownView.filters,\n    page: options.page ?? given?.page ?? ownView.page,\n    pageSize:\n      options.pageSize ??\n      (given && 'pageSize' in given ? given.pageSize : ownView.pageSize),\n    hiddenColumns: cleanHidden(\n      options.hiddenColumns ?? given?.hiddenColumns ?? ownView.hiddenColumns,\n      columnIds,\n    ),\n    columnWidths: options.columnWidths ?? given?.columnWidths ?? ownView.columnWidths,\n  }\n\n  const [expanded, setExpanded] = useControllable(\n    options.expanded,\n    options.defaultExpanded ?? EMPTY,\n    options.onExpandedChange,\n  )\n  const [selected, setSelected] = useControllable(\n    options.selected,\n    options.defaultSelected ?? EMPTY,\n    options.onSelectedChange,\n  )\n  const [allMatchingGiven, setAllMatchingFlag] = useControllable(\n    options.allMatching,\n    options.defaultAllMatching ?? false,\n    options.onAllMatchingChange,\n  )\n  // Every row that matched is no longer every row that matches once the view\n  // changes, from here or from the app: the flag holds for the view it was set in.\n  const [allMatchingFor, setAllMatchingFor] = useState<string | null>(null)\n  const allMatchingFlag =\n    allMatchingGiven && (allMatchingFor === null || allMatchingFor === viewKey(view))\n  useEffect(() => {\n    if (allMatchingGiven && !allMatchingFlag) setAllMatchingFlag(false)\n  })\n\n  // A change made since the last render, so a second one in the same event, such as a pager's\n  // new page after its new page size, builds on it rather than on the view this render saw.\n  const changedRef = useRef<TableView | null>(null)\n  useLayoutEffect(() => {\n    changedRef.current = null\n  })\n\n  /** One change to the view, told once to each listener, so a server fetches once. */\n  const changeView = (patch: Partial<TableView>) => {\n    const was = changedRef.current ?? view\n    const next: TableView = { ...was, ...patch }\n    changedRef.current = next\n    // The caller's slices win where given; the rest are kept here.\n    setOwnView(next)\n    const told: [keyof TableView, ((value: never) => void) | undefined][] = [\n      ['sort', options.onSortChange],\n      ['search', options.onSearchChange],\n      ['filters', options.onFiltersChange],\n      ['page', options.onPageChange],\n      ['pageSize', options.onPageSizeChange],\n      ['hiddenColumns', options.onHiddenColumnsChange],\n      ['columnWidths', options.onColumnWidthsChange],\n    ]\n    for (const [key, onChange] of told) {\n      if (key in patch && !Object.is(patch[key], was[key])) onChange?.(next[key] as never)\n    }\n    options.onViewChange?.(next)\n    // Every row that matched is no longer every row that matches.\n    if (allMatchingFlag && viewKey(next) !== viewKey(was)) setAllMatchingFlag(false)\n  }\n\n  // The search the field shows, ahead of the one the rows follow while it waits.\n  const [draft, setDraft] = useState({ text: view.search, from: view.search })\n  if (draft.from !== view.search) setDraft({ text: view.search, from: view.search })\n  const pendingSearch = useRef<ReturnType<typeof setTimeout>>(undefined)\n  const changeViewRef = useRef(changeView)\n  useEffect(() => {\n    changeViewRef.current = changeView\n  })\n  useEffect(() => () => clearTimeout(pendingSearch.current), [])\n\n  const filters = activeFilters(view.filters)\n\n  // What kind of values each column holds, from the first rows: one string,\n  // so the columns are rebuilt only when a kind changes, not with every row.\n  const kindList = columns\n    .map((column) => {\n      const value = column.value\n      return value ? kindOf(data.slice(0, 20).map((row) => value(row))) : 'text'\n    })\n    .join(' ')\n  const columnDefs = useMemo(() => {\n    const listed = kindList.split(' ') as TableValueKind[]\n    const kinds = new Map(\n      columns.map((column, index) => [column.id, listed[index] ?? 'text']),\n    )\n    return {\n      kinds,\n      defs: columns.map((column) => {\n        const kind = kinds.get(column.id) ?? 'text'\n        const value = column.value\n        return {\n          id: column.id,\n          header: column.label,\n          // Empty values are undefined to the table, so they sort last either way.\n          accessorFn: value\n            ? (row: Row) => {\n                const got = value(row)\n                return isEmpty(got) ? undefined : got\n              }\n            : () => undefined,\n          enableSorting: Boolean(column.sortable && value),\n          sortFn: sortFnFor(locale),\n          sortUndefined: 'last' as const,\n          // Numbers, dates and yes or no start from the top; text starts at A.\n          sortDescFirst: kind !== 'text',\n          enableGlobalFilter: column.searchable ?? kind === 'text',\n          enableColumnFilter: Boolean(column.filter),\n          filterFn: column.filter === 'range' ? ('range' as const) : ('options' as const),\n          enableHiding: column.hideable ?? true,\n          size: column.width,\n          minSize: column.minWidth ?? MIN_WIDTH,\n          maxSize: column.maxWidth ?? MAX_WIDTH,\n        }\n      }),\n    }\n  }, [columns, kindList, locale])\n\n  const pageSize = view.pageSize && view.pageSize > 0 ? view.pageSize : undefined\n  const table = useTable({\n    features,\n    data: data as unknown as RowData[],\n    columns: columnDefs.defs,\n    getRowId: (row: RowData) => rowId(row as Row),\n    manualSorting: manual,\n    manualFiltering: manual,\n    // Rows that change never close the ones open; ids whose rows are gone simply match none.\n    autoResetExpanded: false,\n    getSubRows: subRows\n      ? (row: RowData) => subRows(row as Row) as RowData[] | undefined\n      : undefined,\n    getRowCanExpand: subRows\n      ? undefined\n      : (row: { original: RowData }) =>\n          typeof expandable === 'function'\n            ? expandable(row.original as Row)\n            : Boolean(expandable),\n    // A page counts the rows it shows, sub-rows too, and a sub-row that\n    // matches keeps its parent.\n    filterFromLeafRows: Boolean(subRows),\n    enableSortingRemoval: false,\n    enableMultiRemove: false,\n    isMultiSortEvent: (event: unknown) =>\n      Boolean((event as { shiftKey?: boolean })?.shiftKey),\n    isRowRangeSelectionEvent: (event: unknown) =>\n      Boolean((event as { shiftKey?: boolean })?.shiftKey),\n    getColumnCanGlobalFilter: () => true,\n    globalFilterFn: 'includesString',\n    state: {\n      sorting: view.sort.map(({ column, direction }) => ({\n        id: column,\n        desc: direction === 'descending',\n      })),\n      globalFilter: view.search,\n      columnFilters: Object.entries(filters).map(([id, value]) => ({ id, value })),\n      rowSelection: Object.fromEntries(selected.map((id) => [id, true as const])),\n      columnVisibility: Object.fromEntries(view.hiddenColumns.map((id) => [id, false])),\n      expanded: Object.fromEntries(expanded.map((id) => [id, true])) as ExpandedState,\n      columnSizing: view.columnWidths,\n    },\n    onSortingChange: (updater: Updater<{ id: string; desc: boolean }[]>) => {\n      const sorting = resolve(\n        updater,\n        view.sort.map(({ column, direction }) => ({\n          id: column,\n          desc: direction === 'descending',\n        })),\n      )\n      setSort(\n        sorting.map(({ id, desc }) => ({\n          column: id,\n          direction: desc ? 'descending' : 'ascending',\n        })),\n      )\n    },\n    onExpandedChange: (updater: Updater<ExpandedState>) => {\n      const now = Object.fromEntries(expanded.map((id) => [id, true]))\n      const next = resolve<ExpandedState>(updater, now)\n      // `true` is TanStack's word for every row: the ids of every row that can expand.\n      setExpanded(\n        next === true\n          ? table\n              .getCoreRowModel()\n              .flatRows.filter((row) => row.getCanExpand())\n              .map((row) => row.id)\n          : Object.keys(next).filter((id) => next[id]),\n      )\n    },\n    onRowSelectionChange: (updater: Updater<RowSelectionState>) => {\n      const next = resolve<RowSelectionState>(\n        updater,\n        Object.fromEntries(selected.map((id) => [id, true as const])),\n      )\n      setSelected(Object.keys(next).filter((id) => next[id]))\n    },\n  })\n\n  // What shows: in the browser, worked out here; from a server, as given.\n  // Sorted, searched and filtered by TanStack; a page is a slice of what matches.\n  // A page holds whole rows: each one's sub-rows, once it is expanded, follow it there.\n  const topRows = table.getPreExpandedRowModel().rows\n  const matchingRows = table.getPreExpandedRowModel().flatRows\n  const rowCount = manual ? (serverCount ?? data.length) : topRows.length\n  const pageCount = pageCountOf(rowCount, pageSize)\n  const page = clampPage(view.page, pageCount)\n  // While the search or a filter narrows the rows, a row whose sub-rows match opens to show them.\n  const narrowed = view.search !== '' || Object.keys(filters).length > 0\n  // Rows a person closed while this search held them open stay closed until the search changes.\n  const narrowKey = narrowed ? JSON.stringify([view.search, filters]) : ''\n  const [closed, setClosed] = useState<{ key: string; ids: readonly string[] }>({\n    key: '',\n    ids: EMPTY,\n  })\n  const closedIds = closed.key === narrowKey ? closed.ids : EMPTY\n  const opened = (row: {\n    id: string\n    getIsExpanded: () => boolean\n    subRows: readonly unknown[]\n  }) =>\n    row.getIsExpanded() ||\n    (narrowed &&\n      Boolean(subRows) &&\n      row.subRows.length > 0 &&\n      !closedIds.includes(row.id))\n  const pageRows = withExpanded(\n    manual ? topRows : pageSlice(topRows, page, pageSize),\n    opened,\n  )\n  const rows = pageRows.map((row) => row.original as Row)\n  const rowIds = pageRows.map((row) => row.id)\n  const allIds = manual ? rowIds : table.getCoreRowModel().flatRows.map((row) => row.id)\n  // Every row that matches, counted as `rowCount` counts them: top-level rows.\n  const matchingIds = manual ? rowIds : topRows.map((row) => row.id)\n\n  // In the browser, a pick whose row has gone isn't one.\n  const knownIds = new Set(allIds)\n  const picked = manual ? selected : selected.filter((id) => knownIds.has(id))\n  const pickedSet = new Set(picked)\n  const matchingSet = new Set(matchingRows.map((row) => row.id))\n  const allMatching = manual\n    ? allMatchingFlag\n    : matchingIds.length > 0 && matchingIds.every((id) => pickedSet.has(id))\n  const isSelected = (id: string) => (manual && allMatchingFlag) || pickedSet.has(id)\n  const pageSelected = rowIds.length > 0 && rowIds.every(isSelected)\n\n  const rowsById = new Map(pageRows.map((row) => [row.id, row]))\n  const shownColumns = columns.filter((column) => !view.hiddenColumns.includes(column.id))\n  const sortIndex = new Map(view.sort.map(({ column }, index) => [column, index]))\n\n  const setSort = (sort: TableSortBy[]) => {\n    const next = cleanSort(sort, known)\n    changeView({ sort: next })\n    const said = next.flatMap(({ column: id, direction }) => {\n      const column = columns.find((each) => each.id === id)\n      return column\n        ? [messages.sortedBy(column.label, direction, columnDefs.kinds.get(id) ?? 'text')]\n        : []\n    })\n    if (said.length > 0) announce(messages.sorted(said))\n  }\n\n  // After a filter changes or clears, how many rows match is read out once\n  // they are shown: at once in the browser, once the next rows arrive from a\n  // server. The Search field reads out its own count while it holds text.\n  const [counting, setCounting] = useState<{ from: readonly Row[] } | null>(null)\n  if (counting !== null && (!manual || counting.from !== data)) {\n    setCounting(null)\n    announce(messages.matched(rowCount))\n  }\n\n  const sortProps = (id: string): TableSortProps => {\n    const at = sortIndex.get(id)\n    const by = at === undefined ? undefined : view.sort[at]\n    return {\n      sort: by?.direction ?? 'none',\n      sortIndex: at !== undefined && view.sort.length > 1 ? at + 1 : undefined,\n      // TanStack's own toggle: the first press per kind of value, then a flip; Shift adds the column.\n      onSort: (event) => table.getColumn(id)?.getToggleSortingHandler()?.(event),\n    }\n  }\n\n  const setSearch = (search: string) => {\n    setDraft({ text: search, from: view.search })\n    clearTimeout(pendingSearch.current)\n    if (searchWait <= 0) {\n      changeView({ search, page: 1 })\n      return\n    }\n    pendingSearch.current = setTimeout(\n      () => changeViewRef.current({ search, page: 1 }),\n      searchWait,\n    )\n  }\n\n  const setFilter = (column: string, filter: TableFilter | undefined) => {\n    const next = { ...view.filters }\n    if (filter === undefined || isOpenFilter(filter)) delete next[column]\n    else next[column] = filter\n    changeView({ filters: next, page: 1 })\n    setCounting({ from: data })\n  }\n\n  const setPage = (next: number) => {\n    // Against the pages there are at the size this event already set, if it set one.\n    const sized = changedRef.current?.pageSize\n    const count = sized ? pageCountOf(rowCount, sized) : pageCount\n    const to = clampPage(next, count)\n    // Already there, also when a change earlier in the same event moved it, as a new page size does.\n    if (to === (changedRef.current?.page ?? page)) return\n    changeView({ page: to })\n    announce(messages.page(to, count))\n  }\n\n  const facets = (id: string): TableOption[] => {\n    const column = columns.find((each) => each.id === id)\n    if (!column) return []\n    if (manual) return [...(column.options ?? [])]\n    const counts =\n      table.getColumn(id)?.getFacetedUniqueValues() ?? new Map<unknown, number>()\n    const byValue = new Map<string, number>()\n    for (const [value, count] of counts) {\n      if (isEmpty(value as TableValue)) continue\n      const key = String(value)\n      byValue.set(key, (byValue.get(key) ?? 0) + count)\n    }\n    if (column.options) {\n      return column.options.map((option) => ({\n        ...option,\n        count: byValue.get(option.value) ?? 0,\n      }))\n    }\n    return [...byValue.keys()]\n      .sort((a, b) => collatorFor(locale).compare(a, b))\n      .map((value) => ({ value, label: value, count: byValue.get(value) ?? 0 }))\n  }\n\n  const selection: TableSelectionProps = {\n    value: rowIds.filter(isSelected),\n    allValues: rowIds,\n    onValueChange: (value, details) => {\n      const now = rowIds.filter(isSelected)\n      const added = value.filter((id) => !now.includes(id))\n      const removed = now.filter((id) => !value.includes(id))\n      const changed = [...added, ...removed]\n      // Every row was picked through the flag: picking from here starts from the loaded rows.\n      const base = manual && allMatchingFlag ? rowIds : picked\n      if (manual && allMatchingFlag) setAllMatchingFlag(false)\n      const shift = Boolean((details.event as MouseEvent | undefined)?.shiftKey)\n      const only = changed.length === 1 ? changed[0] : undefined\n      const row = only === undefined ? undefined : table.getRow(only, true)\n      if (row && !(manual && allMatchingFlag)) {\n        // One box: TanStack's own toggle, which picks a range from the last one on Shift.\n        row.getToggleSelectedHandler()({\n          target: { checked: added.length === 1 },\n          shiftKey: shift,\n        })\n        return\n      }\n      setSelected(mergePageSelection(base, rowIds, value))\n    },\n  }\n\n  const setHiddenColumns = (hidden: string[]) =>\n    changeView({ hiddenColumns: cleanHidden(hidden, columnIds) })\n\n  return {\n    /** This page's rows, in order. */\n    rows,\n    rowIds,\n    rowId,\n    /** How many rows match the search and filters. */\n    rowCount,\n    /** The columns shown, in order. */\n    columns: shownColumns,\n    allColumns: columns,\n    hiddenColumns: view.hiddenColumns,\n    setHiddenColumns,\n    /** Whether a columns menu may hide this column: never the last one shown. */\n    canHide: (id: string) =>\n      (columns.find((column) => column.id === id)?.hideable ?? true) &&\n      (view.hiddenColumns.includes(id) || shownColumns.length > 1),\n    cell: (row: Row, column: TableColumn<Row>): ReactNode =>\n      column.cell ? column.cell(row) : String(column.value?.(row) ?? ''),\n\n    sort: view.sort,\n    setSort,\n    sortProps,\n\n    /** What the search field shows, which runs ahead of the rows while the search waits. */\n    search: draft.text,\n    setSearch,\n    filters,\n    setFilter,\n    facets,\n    /** Whether the search or a filter leaves rows out. */\n    filtered: view.search !== '' || Object.keys(filters).length > 0,\n    /** Clears the search and every filter. */\n    reset: () => {\n      clearTimeout(pendingSearch.current)\n      setDraft({ text: '', from: view.search })\n      changeView({ search: '', filters: {}, page: 1 })\n      setCounting({ from: data })\n    },\n\n    page,\n    pageCount,\n    setPage,\n    pageSize,\n    /** A new size keeps the first row the page showed. */\n    setPageSize: (size: number) =>\n      changeView({\n        pageSize: size,\n        page: pageForSize(page, pageSize ?? rowCount, size),\n      }),\n    /** “11–20 of 42”. */\n    range: pageRange(page, pageSize, rowCount),\n    /**\n     * Give it to `TableBody` as its `key`: when most rows shown change at\n     * once, as a page turns, they swap in place; when most stay, they glide.\n     */\n    bodyKey: useBodyKey(rowIds),\n\n    selected: manual && allMatchingFlag ? rowIds : picked,\n    /** How many rows are picked, counting every match when they all are. */\n    selectedCount: manual && allMatchingFlag ? rowCount : picked.length,\n    /**\n     * How many picked rows the search and filters leave out, in the\n     * browser; on a server, which can't tell, undefined.\n     */\n    selectedHidden: manual\n      ? undefined\n      : picked.filter((id) => !matchingSet.has(id)).length,\n    setSelected: (ids: string[]) => {\n      if (manual && allMatchingFlag) setAllMatchingFlag(false)\n      setSelected(ids)\n    },\n    isSelected,\n    selection,\n    /** Whether every row on this page is picked. */\n    pageSelected,\n    /** Whether every row that matches is picked, beyond this page. */\n    allMatching,\n    /** Picks every row that matches: their ids in the browser, the `allMatching` flag on a server. */\n    selectAllMatching: () => {\n      if (manual) {\n        setAllMatchingFor(viewKey(view))\n        setAllMatchingFlag(true)\n      } else setSelected([...new Set([...picked, ...matchingIds])])\n    },\n    clearSelection: () => {\n      if (allMatchingFlag) setAllMatchingFlag(false)\n      setSelected([])\n    },\n\n    /** How a row's expand button shows it: its depth, whether it can expand, and whether it is. */\n    expandProps: (id: string): TableExpandProps => {\n      const row = rowsById.get(id)\n      return {\n        depth: row?.depth ?? 0,\n        expandable: row?.getCanExpand() ?? false,\n        expanded: row !== undefined && opened(row),\n        onExpandedChange: (open: boolean) => {\n          setExpanded(\n            open\n              ? [...expanded.filter((each) => each !== id), id]\n              : expanded.filter((each) => each !== id),\n          )\n          // Closing one a search opened keeps it closed for this search; opening it again undoes that.\n          if (narrowed) {\n            setClosed({\n              key: narrowKey,\n              ids: open ? closedIds.filter((each) => each !== id) : [...closedIds, id],\n            })\n          }\n        },\n      }\n    },\n    isExpanded: (id: string) => {\n      const row = rowsById.get(id)\n      return row !== undefined && opened(row)\n    },\n    /** The row a sub-row sits under, for a screen reader to hear what it belongs to. */\n    parentOf: (id: string): Row | undefined =>\n      rowsById.get(id)?.getParentRow()?.original as Row | undefined,\n    expanded,\n    setExpanded,\n\n    /** A resizable column's width and its change, for its `TableHead`; nothing for one that isn't. */\n    widthProps: (id: string): TableWidthProps | Record<string, never> => {\n      const column = columns.find((each) => each.id === id)\n      if (!column?.resizable) return {}\n      const sized =\n        id in view.columnWidths ? table.getColumn(id)?.getSize() : column.width\n      return {\n        width: sized,\n        minWidth: column.minWidth ?? MIN_WIDTH,\n        maxWidth: column.maxWidth ?? MAX_WIDTH,\n        onWidthChange: (width: number | undefined) => {\n          const next = { ...view.columnWidths }\n          // The head has held it between its bounds already.\n          if (width === undefined) delete next[id]\n          else next[id] = width\n          changeView({ columnWidths: next })\n        },\n      }\n    },\n    columnWidths: view.columnWidths,\n\n    /**\n     * The rows as CSV, in their order, with the shown columns: every row that\n     * matches (on a server, the rows loaded), the picked ones, or this page's.\n     */\n    toCsv: ({\n      rows: which = 'matching',\n    }: { rows?: 'matching' | 'selected' | 'page' } = {}) => {\n      const source =\n        which === 'page'\n          ? pageRows\n          : which === 'selected'\n            ? // In the table's order, then the picked rows the search and filters leave out.\n              [\n                ...matchingRows.filter((row) => isSelected(row.id)),\n                ...table\n                  .getCoreRowModel()\n                  .flatRows.filter(\n                    (row) => isSelected(row.id) && !matchingSet.has(row.id),\n                  ),\n              ]\n            : matchingRows\n      return csvOf(\n        shownColumns.map((column) => column.label),\n        source.map((row) =>\n          shownColumns.map((column) => {\n            const original = row.original as Row\n            return column.csv ? column.csv(original) : column.value?.(original)\n          }),\n        ),\n      )\n    },\n\n    view: { ...view, page },\n  }\n}\n\n/**\n * Whether going from the rows shown to the next ones swaps them rather than\n * moving them: when fewer than half stay, as on a page turn or a sort across\n * pages, the rows that leave and the rows that come would fade over each\n * other in the same places.\n */\nfunction swapsRows(from: readonly string[], to: readonly string[]): boolean {\n  if (from.length === 0 || to.length === 0) return false\n  const kept = new Set(from)\n  const shared = to.filter((id) => kept.has(id)).length\n  // Against the shorter list, so opening a row's many sub-rows, which keeps every row there was, moves.\n  return shared * 2 < Math.min(from.length, to.length)\n}\n\n/** A key that changes each time the rows shown swap rather than move. */\nfunction useBodyKey(rowIds: readonly string[]): number {\n  const [seen, setSeen] = useState({ ids: rowIds, key: 0 })\n  if (seen.ids.join('\\u0000') === rowIds.join('\\u0000')) return seen.key\n  const key = swapsRows(seen.ids, rowIds) ? seen.key + 1 : seen.key\n  setSeen({ ids: rowIds, key })\n  return key\n}\n\n/** Rows with the sub-rows of each expanded one after it, at every depth. */\nfunction withExpanded<T extends { subRows: readonly T[] }>(\n  rows: readonly T[],\n  open: (row: T) => boolean,\n): T[] {\n  return rows.flatMap((row) =>\n    open(row) && row.subRows.length > 0\n      ? [row, ...withExpanded(row.subRows, open)]\n      : [row],\n  )\n}\n\nfunction resolve<T>(updater: Updater<T>, current: T): T {\n  return typeof updater === 'function' ? (updater as (old: T) => T)(current) : updater\n}\n\nexport type TableData<Row extends object> = ReturnType<typeof useTableData<Row>>\n\nexport {\n  cleanHidden,\n  cleanSort,\n  compareValues,\n  inRange,\n  kindOf,\n  matchesOptions,\n  mergePageSelection,\n  csvOf,\n  pageSlice,\n  swapsRows,\n  useTableData,\n}\n",
      "type": "registry:lib",
      "target": "@lib/table-data.tsx"
    }
  ],
  "type": "registry:lib"
}