@dinachi/cli 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/index.js +244 -72
  3. package/package.json +5 -1
  4. package/templates/agent/agent.tsx +35 -18
  5. package/templates/alert/alert.tsx +345 -0
  6. package/templates/alert/index.ts +16 -0
  7. package/templates/ask-bar/ask-bar.tsx +1061 -0
  8. package/templates/ask-bar/index.ts +1 -0
  9. package/templates/autocomplete/autocomplete.tsx +0 -1
  10. package/templates/breadcrumb/breadcrumb.tsx +606 -0
  11. package/templates/breadcrumb/index.ts +9 -0
  12. package/templates/calendar/calendar.tsx +1155 -0
  13. package/templates/calendar/index.ts +15 -0
  14. package/templates/combobox/combobox.tsx +0 -1
  15. package/templates/command-items/command-items.tsx +69 -0
  16. package/templates/command-items/index.ts +1 -0
  17. package/templates/command-palette/command-palette.tsx +954 -0
  18. package/templates/command-palette/index.ts +1 -0
  19. package/templates/comparison-table/comparison-table.tsx +540 -0
  20. package/templates/comparison-table/index.ts +15 -0
  21. package/templates/data-table/data-table.tsx +2077 -0
  22. package/templates/data-table/index.ts +14 -0
  23. package/templates/date-picker/date-picker.tsx +527 -0
  24. package/templates/date-picker/index.ts +2 -0
  25. package/templates/date-range-picker/date-range-picker.tsx +504 -0
  26. package/templates/date-range-picker/index.ts +2 -0
  27. package/templates/detail-list/detail-list.tsx +419 -0
  28. package/templates/detail-list/index.ts +12 -0
  29. package/templates/heat-table/heat-table.tsx +613 -0
  30. package/templates/heat-table/index.ts +9 -0
  31. package/templates/menu/menu.tsx +8 -3
  32. package/templates/month-picker/index.ts +1 -0
  33. package/templates/month-picker/month-picker.tsx +351 -0
  34. package/templates/omnibar/index.ts +1 -0
  35. package/templates/omnibar/omnibar.tsx +1009 -0
  36. package/templates/pagination/index.ts +8 -0
  37. package/templates/pagination/pagination.tsx +389 -0
  38. package/templates/table/index.ts +13 -0
  39. package/templates/table/table.tsx +265 -0
  40. package/templates/time-slots/index.ts +1 -0
  41. package/templates/time-slots/time-slots.tsx +589 -0
  42. package/templates/week-strip/index.ts +1 -0
  43. package/templates/week-strip/week-strip.tsx +329 -0
  44. package/templates/year-view/index.ts +1 -0
  45. package/templates/year-view/year-view.tsx +362 -0
@@ -0,0 +1,2077 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import {
5
+ createColumnHelper,
6
+ flexRender,
7
+ getCoreRowModel,
8
+ getExpandedRowModel,
9
+ getFacetedRowModel,
10
+ getFacetedUniqueValues,
11
+ getFilteredRowModel,
12
+ getPaginationRowModel,
13
+ getSortedRowModel,
14
+ useReactTable,
15
+ type Cell,
16
+ type ColumnOrderState,
17
+ type ColumnSizingState,
18
+ type CellContext,
19
+ type Column,
20
+ type ColumnDef,
21
+ type ColumnFiltersState,
22
+ type ExpandedState,
23
+ type Header,
24
+ type PaginationState,
25
+ type Row,
26
+ type RowData,
27
+ type RowSelectionState,
28
+ type SortingState,
29
+ type Table as TanstackTable,
30
+ type Updater,
31
+ type VisibilityState,
32
+ } from "@tanstack/react-table"
33
+ import { useVirtualizer } from "@tanstack/react-virtual"
34
+ import { ArrowDown, ArrowUp, ArrowUpDown, ChevronRight, Columns3, Ellipsis, Search, X } from "lucide-react"
35
+ import { cn } from "@/lib/utils"
36
+ import { changeAsAgent, createAgentChangeDetails, isAgentChange, useAgentControl, useAgentState, useHasAgent } from "@/components/ui/agent"
37
+ import { Button } from "@/components/ui/button"
38
+ import { Checkbox } from "@/components/ui/checkbox"
39
+ import { Drawer, DrawerClose, DrawerContent, DrawerTitle } from "@/components/ui/drawer"
40
+ import { Input } from "@/components/ui/input"
41
+ import {
42
+ Menu,
43
+ MenuCheckboxItem,
44
+ MenuContent,
45
+ MenuItem,
46
+ MenuRadioGroup,
47
+ MenuRadioItem,
48
+ MenuSeparator,
49
+ MenuSub,
50
+ MenuSubContent,
51
+ MenuSubTrigger,
52
+ MenuTrigger,
53
+ } from "@/components/ui/menu"
54
+ import { Pagination } from "@/components/ui/pagination"
55
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
56
+ import { Skeleton } from "@/components/ui/skeleton"
57
+ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
58
+ import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
59
+
60
+ declare module "@tanstack/react-table" {
61
+ // TanStack declares ColumnMeta with these parameters, and a merge must repeat them.
62
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
63
+ interface ColumnMeta<TData extends RowData, TValue> {
64
+ /** The column's name wherever the header itself is not shown: menus, the sheet, the agent. */
65
+ label?: string
66
+ /** Right-aligns the column in tabular figures. */
67
+ numeric?: boolean
68
+ /** Keeps the column at the left edge while the table scrolls sideways. */
69
+ pin?: "left"
70
+ /** Where the column goes in the phone list: the first line's `title` or `value`, or the `meta` line under it. */
71
+ phone?: "title" | "value" | "meta"
72
+ /** Order within its phone line, lowest first. Ties keep column order. Defaults to 0. */
73
+ phoneOrder?: number
74
+ /** Renders the cell in the phone list instead of `cell`, such as a date without its time. The sheet still uses `cell`. */
75
+ phoneCell?: (context: CellContext<TData, TValue>) => React.ReactNode
76
+ /** What the phone sort calls each direction, ascending first, such as `["Oldest", "Newest"]`. */
77
+ sortLabels?: [ascending: string, descending: string]
78
+ }
79
+ }
80
+
81
+ export { createColumnHelper }
82
+ export type { ColumnDef }
83
+
84
+ export interface DataTableChangeDetails {
85
+ reason: string
86
+ event?: Event
87
+ isCanceled: boolean
88
+ cancel(): void
89
+ }
90
+
91
+ export interface DataTableState {
92
+ sorting: SortingState
93
+ columnFilters: ColumnFiltersState
94
+ globalFilter: string
95
+ pagination: PaginationState
96
+ rowSelection: RowSelectionState
97
+ columnVisibility: VisibilityState
98
+ /** The movable columns, left to right, by id. Pinned and built-in columns keep their place. */
99
+ columnOrder: ColumnOrderState
100
+ /** Widths in px by column id, for the columns someone has resized. */
101
+ columnSizing: ColumnSizingState
102
+ }
103
+
104
+ /** What the selection bar's actions act on. */
105
+ export interface DataTableSelection {
106
+ /** The selected ids the filters show. In server mode, every selected id loaded so far. */
107
+ ids: string[]
108
+ /** True once someone chose every row on the server, including pages never loaded. */
109
+ all: boolean
110
+ /** How many rows are selected: the server's total when `all`, otherwise `ids.length`. */
111
+ count: number
112
+ /** Selected ids the current filters hide. Actions get neither these rows nor their ids. */
113
+ hidden: string[]
114
+ }
115
+
116
+ type Change<V> = (value: V, details: DataTableChangeDetails) => void
117
+
118
+ export interface DataTableFacetOption {
119
+ value: string
120
+ label?: string
121
+ /** Shown on the chip. Server mode has no rows to count, so it reads these. */
122
+ count?: number
123
+ }
124
+
125
+ export interface DataTableEmptyContext {
126
+ /** The search, when one is set. */
127
+ query: string
128
+ /** The facet's value, when one is set. */
129
+ filter: string | undefined
130
+ /** True once rows exist and the filters hide them all. */
131
+ filtered: boolean
132
+ clear: () => void
133
+ }
134
+
135
+ export interface DataTableProps<T> {
136
+ data: T[]
137
+ columns: ColumnDef<T, any>[]
138
+ /** A stable id per row. Defaults to the row's `id` field, then its index. */
139
+ getRowId?: (row: T, index: number, parent?: Row<T>) => string
140
+ /** What a row is called in checkbox names, the sheet title and the agent. Defaults to `Order ord_1`. */
141
+ getRowLabel?: (row: T, id: string) => string
142
+ /** What the rows are, for counts, empty states and names. */
143
+ noun?: { singular: string; plural: string }
144
+ /** The heading over the table. Defaults to the count, such as `248 orders`; `null` hides it. */
145
+ title?: React.ReactNode
146
+ /** The column whose values become filter chips. */
147
+ facet?: { column: string; options?: (string | DataTableFacetOption)[] }
148
+
149
+ sorting?: SortingState
150
+ defaultSorting?: SortingState
151
+ onSortingChange?: Change<SortingState>
152
+ columnFilters?: ColumnFiltersState
153
+ defaultColumnFilters?: ColumnFiltersState
154
+ onColumnFiltersChange?: Change<ColumnFiltersState>
155
+ globalFilter?: string
156
+ defaultGlobalFilter?: string
157
+ onGlobalFilterChange?: Change<string>
158
+ pagination?: PaginationState
159
+ defaultPagination?: PaginationState
160
+ onPaginationChange?: Change<PaginationState>
161
+ rowSelection?: RowSelectionState
162
+ defaultRowSelection?: RowSelectionState
163
+ onRowSelectionChange?: Change<RowSelectionState>
164
+ columnVisibility?: VisibilityState
165
+ defaultColumnVisibility?: VisibilityState
166
+ onColumnVisibilityChange?: Change<VisibilityState>
167
+ columnOrder?: ColumnOrderState
168
+ defaultColumnOrder?: ColumnOrderState
169
+ onColumnOrderChange?: Change<ColumnOrderState>
170
+ columnSizing?: ColumnSizingState
171
+ defaultColumnSizing?: ColumnSizingState
172
+ onColumnSizingChange?: Change<ColumnSizingState>
173
+ /** Runs after any slice changes, with the whole state. */
174
+ onStateChange?: (state: DataTableState, details: DataTableChangeDetails) => void
175
+
176
+ /** The total on the server. Setting it hands sorting, filtering and paging to you. */
177
+ rowCount?: number
178
+ pageSizes?: number[]
179
+
180
+ /** Marks the table busy. Rows on screen stay, dimmed; with none, skeleton rows stand in. */
181
+ loading?: boolean
182
+ /** `true` reads Couldn't load orders. A node replaces the message. */
183
+ error?: boolean | React.ReactNode
184
+ onRetry?: () => void
185
+ emptyState?: (context: DataTableEmptyContext) => React.ReactNode
186
+
187
+ density?: "comfortable" | "compact"
188
+ /** Adds the checkbox column and the selection bar. */
189
+ selectable?: boolean
190
+ /** Buttons for the selection bar, given the selected rows the filters show. */
191
+ selectionActions?: (rows: T[], clear: () => void, selection: DataTableSelection) => React.ReactNode
192
+ /** Opens a row on click, Enter or its row trigger, in place of the built-in sheet. */
193
+ onRowOpen?: (row: T, details: DataTableChangeDetails) => void
194
+ /** Waits this many ms after the last keystroke before searching. */
195
+ searchDelay?: number
196
+ /** More controls for the toolbar, after the filter chips, such as a second filter. */
197
+ toolbar?: React.ReactNode
198
+ /** Runs with the rows left after search and filters, before paging. Client mode only. */
199
+ onFilteredRowsChange?: (rows: T[]) => void
200
+ /** Menu items for a row's actions menu, such as `DataTableAction`. */
201
+ rowActions?: (row: T) => React.ReactNode
202
+ getSubRows?: (row: T, index: number) => T[] | undefined
203
+ /** A panel under an expanded row. Not drawn while virtualized. */
204
+ renderSubComponent?: (row: Row<T>) => React.ReactNode
205
+ getRowCanExpand?: (row: Row<T>) => boolean
206
+ /** Drag a header edge to resize, or focus it and press the arrows. */
207
+ resizable?: boolean
208
+ /** Drag a header to move its column, or use the Columns menu. */
209
+ reorderable?: boolean
210
+ /** Renders only the rows in view and scrolls instead of paging. */
211
+ virtualize?: boolean
212
+ /** Height of the scrolling area in px. Virtualized tables default to 452. */
213
+ maxHeight?: number
214
+ disabled?: boolean
215
+ className?: string
216
+ ref?: React.Ref<HTMLDivElement>
217
+ }
218
+
219
+ const SELECT = "select"
220
+ const EXPAND = "expand"
221
+ const ACTIONS = "actions"
222
+ const SYSTEM = new Set([SELECT, EXPAND, ACTIONS])
223
+ const SYSTEM_WIDTH: Record<string, number> = { [SELECT]: 44, [EXPAND]: 28, [ACTIONS]: 44 }
224
+ const FLEX_MIN = 140
225
+ const ALL = "all"
226
+
227
+ const INTERACTIVE = "button, a, input, select, textarea, label, [role='checkbox'], [role='separator'], [role='menuitem']"
228
+
229
+ const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
230
+ const resolve = <V,>(updater: Updater<V>, old: V): V =>
231
+ typeof updater === "function" ? (updater as (old: V) => V)(old) : updater
232
+ const seed = (n: number) => {
233
+ const x = Math.sin(n * 9301 + 49297) * 233280
234
+ return x - Math.floor(x)
235
+ }
236
+
237
+ function defaultRowId<T>(row: T, index: number, parent?: Row<T>) {
238
+ const id = (row as { id?: unknown }).id
239
+ return id != null ? String(id) : parent ? `${parent.id}.${index}` : String(index)
240
+ }
241
+
242
+ function personDetails(reason: string, event?: Event): DataTableChangeDetails {
243
+ const details: DataTableChangeDetails = {
244
+ reason,
245
+ event,
246
+ isCanceled: false,
247
+ cancel() {
248
+ details.isCanceled = true
249
+ },
250
+ }
251
+ return details
252
+ }
253
+
254
+ /** Details for a change another one causes, such as the page going back to 1 on a sort, kept as the agent's when it was. */
255
+ function follow(details: DataTableChangeDetails): DataTableChangeDetails {
256
+ return isAgentChange(details)
257
+ ? createAgentChangeDetails<DataTableChangeDetails>(details.reason)
258
+ : personDetails(details.reason, details.event)
259
+ }
260
+
261
+ function labelOf<T>(column: Column<T, unknown>): string {
262
+ const meta = column.columnDef.meta
263
+ if (meta?.label) return meta.label
264
+ const header = column.columnDef.header
265
+ return typeof header === "string" ? header : column.id
266
+ }
267
+
268
+ const PHONE = "(max-width: 767px)"
269
+ function subscribePhone(callback: () => void) {
270
+ if (typeof window === "undefined" || !window.matchMedia) return () => {}
271
+ const query = window.matchMedia(PHONE)
272
+ query.addEventListener?.("change", callback)
273
+ return () => query.removeEventListener?.("change", callback)
274
+ }
275
+ const phoneNow = () => typeof window !== "undefined" && Boolean(window.matchMedia?.(PHONE).matches)
276
+ const phoneOnServer = () => false
277
+
278
+ /* ---------------- grid keyboard ---------------- */
279
+
280
+ const STOPS = 'button:not([disabled]), a[href], input:not([disabled]), [role="checkbox"], [role="separator"]'
281
+
282
+ function stopsOf(cell: HTMLElement): HTMLElement[] {
283
+ // A checkbox keeps a hidden native input beside it for forms, which is never a stop.
284
+ const inner = Array.from(cell.querySelectorAll<HTMLElement>(STOPS)).filter(
285
+ (el) => !el.hidden && !el.closest("[aria-hidden=\"true\"]")
286
+ )
287
+ return inner.length ? inner : [cell]
288
+ }
289
+
290
+ function gridRows(grid: HTMLElement): HTMLElement[] {
291
+ return Array.from(grid.querySelectorAll<HTMLElement>(":scope > thead > tr, :scope > tbody > tr")).filter(
292
+ (tr) => tr.children.length > 0 && !tr.hasAttribute("data-spacer")
293
+ )
294
+ }
295
+
296
+ interface Position {
297
+ row: number
298
+ cell: number
299
+ stop: number
300
+ }
301
+
302
+ /** One tab stop for the whole grid: the active cell's control, or the cell itself. */
303
+ function rove(grid: HTMLElement, active: Position) {
304
+ const rows = gridRows(grid)
305
+ if (!rows.length) return
306
+ const row = Math.min(active.row, rows.length - 1)
307
+ rows.forEach((tr, r) =>
308
+ Array.from(tr.children as HTMLCollectionOf<HTMLElement>).forEach((cell, c) => {
309
+ const stops = stopsOf(cell)
310
+ stops.forEach((stop, s) => {
311
+ const on = r === row && c === Math.min(active.cell, tr.children.length - 1) && s === Math.min(active.stop, stops.length - 1)
312
+ stop.tabIndex = on ? 0 : -1
313
+ })
314
+ })
315
+ )
316
+ }
317
+
318
+ function positionOf(grid: HTMLElement, target: HTMLElement): Position | null {
319
+ const cell = target.closest<HTMLElement>("td, th")
320
+ const tr = cell?.parentElement
321
+ if (!cell || !tr) return null
322
+ const row = gridRows(grid).indexOf(tr)
323
+ if (row < 0) return null
324
+ return { row, cell: Array.prototype.indexOf.call(tr.children, cell), stop: Math.max(0, stopsOf(cell).indexOf(target)) }
325
+ }
326
+
327
+ function moveFocus(grid: HTMLElement, from: Position, key: string, ctrl: boolean): Position | null {
328
+ const rows = gridRows(grid)
329
+ const cellsOf = (r: number) => Array.from(rows[r].children as HTMLCollectionOf<HTMLElement>)
330
+ const flat = (r: number) => cellsOf(r).flatMap((cell, c) => stopsOf(cell).map((_, s) => ({ row: r, cell: c, stop: s })))
331
+ const here = flat(from.row)
332
+ const index = here.findIndex((p) => p.cell === from.cell && p.stop === from.stop)
333
+ const vertical = (r: number) => ({ row: r, cell: Math.min(from.cell, cellsOf(r).length - 1), stop: 0 })
334
+ switch (key) {
335
+ case "ArrowRight":
336
+ return here[Math.min(index + 1, here.length - 1)]
337
+ case "ArrowLeft":
338
+ return here[Math.max(index - 1, 0)]
339
+ case "ArrowDown":
340
+ return vertical(Math.min(from.row + 1, rows.length - 1))
341
+ case "ArrowUp":
342
+ return vertical(Math.max(from.row - 1, 0))
343
+ case "Home":
344
+ return ctrl ? flat(0)[0] : here[0]
345
+ case "End": {
346
+ if (!ctrl) return here[here.length - 1]
347
+ const last = flat(rows.length - 1)
348
+ return last[last.length - 1]
349
+ }
350
+ }
351
+ return null
352
+ }
353
+
354
+ function focusAt(grid: HTMLElement, p: Position) {
355
+ const cell = gridRows(grid)[p.row]?.children[p.cell] as HTMLElement | undefined
356
+ if (!cell) return
357
+ const stops = stopsOf(cell)
358
+ stops[Math.min(p.stop, stops.length - 1)]?.focus()
359
+ }
360
+
361
+ /* ---------------- parts ---------------- */
362
+
363
+ interface RowContextValue {
364
+ id: string
365
+ /** Set inside the phone list and the sheet, where the row trigger has nothing to open. */
366
+ inert: boolean
367
+ open: (id: string, event?: Event) => void
368
+ }
369
+
370
+ const RowContext = React.createContext<RowContextValue | null>(null)
371
+
372
+ /** Opens the row's detail sheet. Inside the phone list or the sheet it is plain text, as the row already opens it. */
373
+ const DataTableRowTrigger = React.forwardRef<HTMLButtonElement, React.ButtonHTMLAttributes<HTMLButtonElement>>(
374
+ ({ className, onClick, children, ...props }, ref) => {
375
+ const row = React.useContext(RowContext)
376
+ if (!row || row.inert) return <span data-slot="data-table-row-trigger" className={className}>{children}</span>
377
+ return (
378
+ <button
379
+ ref={ref}
380
+ type="button"
381
+ data-slot="data-table-row-trigger"
382
+ className={cn(
383
+ "cursor-pointer rounded-sm font-mono text-[12.5px] underline-offset-[3px] hover:underline",
384
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
385
+ className
386
+ )}
387
+ onClick={(event) => {
388
+ onClick?.(event)
389
+ if (!event.defaultPrevented) row.open(row.id, event.nativeEvent)
390
+ }}
391
+ {...props}
392
+ >
393
+ {children}
394
+ </button>
395
+ )
396
+ }
397
+ )
398
+ DataTableRowTrigger.displayName = "DataTableRowTrigger"
399
+
400
+ /** An item in a row's actions menu. `destructive` colours it as a warning. */
401
+ const DataTableAction = React.forwardRef<
402
+ React.ComponentRef<typeof MenuItem>,
403
+ React.ComponentProps<typeof MenuItem> & { destructive?: boolean }
404
+ >(({ className, destructive, ...props }, ref) => (
405
+ <MenuItem
406
+ ref={ref}
407
+ data-slot="data-table-action"
408
+ className={cn(
409
+ "text-[13px]",
410
+ destructive &&
411
+ "text-destructive focus:bg-[color:color-mix(in_oklab,var(--destructive)_10%,transparent)] focus:text-destructive data-[highlighted]:bg-[color:color-mix(in_oklab,var(--destructive)_10%,transparent)] data-[highlighted]:text-destructive",
412
+ className
413
+ )}
414
+ {...props}
415
+ />
416
+ ))
417
+ DataTableAction.displayName = "DataTableAction"
418
+
419
+ const rowBg = cn(
420
+ "[&>td]:bg-card",
421
+ "hover:[&>td]:[background-color:color-mix(in_oklab,var(--muted)_85%,var(--card))]",
422
+ "aria-selected:[&>td]:[background-color:color-mix(in_oklab,var(--secondary)_55%,var(--card))]",
423
+ "aria-selected:hover:[&>td]:[background-color:color-mix(in_oklab,var(--secondary)_75%,var(--card))]"
424
+ )
425
+ const inView = "sticky left-0 w-[var(--data-table-viewport,100%)]"
426
+ const subRowCell =
427
+ "h-[34px] border-b-0 text-[12.5px] text-muted-foreground [background-color:color-mix(in_oklab,var(--muted)_60%,var(--card))]"
428
+ const indeterminate =
429
+ "data-[indeterminate]:bg-primary data-[indeterminate]:text-primary-foreground data-[indeterminate]:[&_svg]:hidden data-[indeterminate]:after:h-0.5 data-[indeterminate]:after:w-2 data-[indeterminate]:after:rounded-full data-[indeterminate]:after:bg-current data-[indeterminate]:after:content-[''] inline-flex items-center justify-center"
430
+
431
+ /* ---------------- DataTable ---------------- */
432
+
433
+ function DataTable<T>(props: DataTableProps<T>) {
434
+ const {
435
+ data,
436
+ columns,
437
+ getRowId,
438
+ getRowLabel,
439
+ noun = { singular: "row", plural: "rows" },
440
+ facet,
441
+ rowCount,
442
+ pageSizes = [10, 25, 50],
443
+ loading = false,
444
+ error,
445
+ onRetry,
446
+ emptyState,
447
+ density = "comfortable",
448
+ selectable = true,
449
+ selectionActions,
450
+ onRowOpen,
451
+ searchDelay,
452
+ onFilteredRowsChange,
453
+ rowActions,
454
+ getSubRows,
455
+ renderSubComponent,
456
+ getRowCanExpand,
457
+ resizable = true,
458
+ reorderable = true,
459
+ virtualize = false,
460
+ disabled = false,
461
+ className,
462
+ ref,
463
+ } = props
464
+ const maxHeight = props.maxHeight ?? (virtualize ? 452 : undefined)
465
+ const manual = rowCount !== undefined
466
+ const plural = noun.plural
467
+ const hasAgent = useHasAgent()
468
+ const phone = React.useSyncExternalStore(subscribePhone, phoneNow, phoneOnServer)
469
+
470
+ /* ---- state ---- */
471
+ const latest = React.useRef<DataTableState>(null as unknown as DataTableState)
472
+ const [touched, setTouched] = React.useState(false)
473
+ const slice = <K extends keyof DataTableState>(key: K, own?: Change<DataTableState[K]>) =>
474
+ ((value: DataTableState[K], details: DataTableChangeDetails) => {
475
+ own?.(value, details)
476
+ if (details.isCanceled) return
477
+ // A sort also resets the page, a second change in the same event; it must see the first.
478
+ latest.current = { ...latest.current, [key]: value }
479
+ props.onStateChange?.(latest.current, details)
480
+ if (!details.isCanceled && (key === "sorting" || key === "columnFilters" || key === "globalFilter")) setTouched(true)
481
+ }) as Change<DataTableState[K]>
482
+
483
+ const [sorting, changeSorting] = useAgentState(props.sorting, props.defaultSorting ?? [], slice("sorting", props.onSortingChange))
484
+ const [columnFilters, changeFilters] = useAgentState(
485
+ props.columnFilters,
486
+ props.defaultColumnFilters ?? [],
487
+ slice("columnFilters", props.onColumnFiltersChange)
488
+ )
489
+ const [globalFilter, changeSearch] = useAgentState(
490
+ props.globalFilter,
491
+ props.defaultGlobalFilter ?? "",
492
+ slice("globalFilter", props.onGlobalFilterChange)
493
+ )
494
+ const [pagination, changePagination] = useAgentState(
495
+ props.pagination,
496
+ props.defaultPagination ?? { pageIndex: 0, pageSize: pageSizes[0] ?? 10 },
497
+ slice("pagination", props.onPaginationChange)
498
+ )
499
+ const [rowSelection, changeSelection] = useAgentState(
500
+ props.rowSelection,
501
+ props.defaultRowSelection ?? {},
502
+ slice("rowSelection", props.onRowSelectionChange)
503
+ )
504
+ const [columnVisibility, changeVisibility] = useAgentState(
505
+ props.columnVisibility,
506
+ props.defaultColumnVisibility ?? {},
507
+ slice("columnVisibility", props.onColumnVisibilityChange)
508
+ )
509
+ const [order, changeOrder] = useAgentState(
510
+ props.columnOrder,
511
+ props.defaultColumnOrder ?? [],
512
+ slice("columnOrder", props.onColumnOrderChange)
513
+ )
514
+ const [sizes, changeSizing] = useAgentState(
515
+ props.columnSizing,
516
+ props.defaultColumnSizing ?? {},
517
+ slice("columnSizing", props.onColumnSizingChange)
518
+ )
519
+
520
+ // Server mode: every row on the server is selected, so each page that loads arrives selected.
521
+ const [everything, setEverything] = React.useState(false)
522
+ const rowIdOf = getRowId ?? defaultRowId
523
+ const effectiveSelection = React.useMemo(() => {
524
+ if (!everything || !manual) return rowSelection
525
+ const next = { ...rowSelection }
526
+ data.forEach((row, i) => (next[rowIdOf(row, i)] = true))
527
+ return next
528
+ // eslint-disable-next-line react-hooks/exhaustive-deps
529
+ }, [everything, manual, rowSelection, data])
530
+ React.useEffect(() => {
531
+ if (effectiveSelection !== rowSelection && Object.keys(effectiveSelection).some((id) => !rowSelection[id]))
532
+ changeSelection(effectiveSelection, personDetails("select-all"))
533
+ }, [effectiveSelection, rowSelection, changeSelection])
534
+
535
+ latest.current = {
536
+ sorting,
537
+ columnFilters,
538
+ globalFilter,
539
+ pagination,
540
+ rowSelection: effectiveSelection,
541
+ columnVisibility,
542
+ columnOrder: order,
543
+ columnSizing: sizes,
544
+ }
545
+
546
+ const [expanded, setExpanded] = React.useState<ExpandedState>({})
547
+ const [sheet, setSheet] = React.useState<string | null>(null)
548
+ const [picking, setPicking] = React.useState(false)
549
+ const press = React.useRef<{ timer: number; fired: boolean } | null>(null)
550
+ React.useEffect(() => () => window.clearTimeout(press.current?.timer), [])
551
+
552
+ // Sorting, filtering or searching changes which rows page 1 holds, so it goes back there.
553
+ const backToFirstPage = (details: DataTableChangeDetails) => {
554
+ const current = latest.current.pagination
555
+ if (current.pageIndex !== 0) changePagination({ ...current, pageIndex: 0 }, follow(details))
556
+ }
557
+ const setSorting: Change<SortingState> = (next, details) => {
558
+ changeSorting(next, details)
559
+ if (!details.isCanceled) backToFirstPage(details)
560
+ }
561
+ const setFilters: Change<ColumnFiltersState> = (next, details) => {
562
+ changeFilters(next, details)
563
+ if (details.isCanceled) return
564
+ setEverything(false)
565
+ backToFirstPage(details)
566
+ }
567
+ const setSearch: Change<string> = (next, details) => {
568
+ window.clearTimeout(searchTimer.current)
569
+ setDraft(null)
570
+ changeSearch(next, details)
571
+ if (details.isCanceled) return
572
+ setEverything(false)
573
+ backToFirstPage(details)
574
+ }
575
+ const [draft, setDraft] = React.useState<string | null>(null)
576
+ const searchTimer = React.useRef(0)
577
+ React.useEffect(() => () => window.clearTimeout(searchTimer.current), [])
578
+ const typeSearch = (value: string, details: DataTableChangeDetails) => {
579
+ if (!searchDelay) return setSearch(value, details)
580
+ setDraft(value)
581
+ window.clearTimeout(searchTimer.current)
582
+ searchTimer.current = window.setTimeout(() => setSearch(value, details), searchDelay)
583
+ }
584
+ const setSelection: Change<RowSelectionState> = (next, details) => {
585
+ const before = latest.current.rowSelection
586
+ if (Object.keys(before).some((id) => before[id] && !next[id])) setEverything(false)
587
+ changeSelection(next, details)
588
+ }
589
+
590
+ /* ---- columns ---- */
591
+ const expandable = Boolean(getSubRows || renderSubComponent)
592
+ const hasActions = Boolean(rowActions)
593
+ const facetId = facet?.column
594
+ const userIds = React.useMemo(
595
+ () => columns.map((c) => c.id ?? (c as { accessorKey?: string }).accessorKey ?? "").filter(Boolean),
596
+ [columns]
597
+ )
598
+ const allColumns = React.useMemo<ColumnDef<T, any>[]>(() => {
599
+ const list: ColumnDef<T, any>[] = []
600
+ if (selectable) list.push({ id: SELECT, size: SYSTEM_WIDTH[SELECT], enableSorting: false, enableHiding: false })
601
+ if (expandable) list.push({ id: EXPAND, size: SYSTEM_WIDTH[EXPAND], enableSorting: false, enableHiding: false })
602
+ for (const column of columns) {
603
+ const id = column.id ?? (column as { accessorKey?: string }).accessorKey
604
+ list.push(facetId && id === facetId && !column.filterFn ? { ...column, filterFn: "equalsString" } : column)
605
+ }
606
+ if (hasActions) list.push({ id: ACTIONS, size: SYSTEM_WIDTH[ACTIONS], enableSorting: false, enableHiding: false })
607
+ return list
608
+ }, [columns, selectable, expandable, hasActions, facetId])
609
+
610
+ const pinned = React.useMemo(() => {
611
+ const left = [selectable && SELECT, expandable && EXPAND].filter(Boolean) as string[]
612
+ for (const column of columns) {
613
+ const id = column.id ?? (column as { accessorKey?: string }).accessorKey
614
+ if (id && column.meta?.pin === "left") left.push(id)
615
+ }
616
+ return { left, right: hasActions ? [ACTIONS] : [] }
617
+ }, [columns, selectable, expandable, hasActions])
618
+
619
+ // A saved order may predate a column, or name one since removed.
620
+ const columnOrder = React.useMemo(() => {
621
+ const known = order.filter((id) => userIds.includes(id))
622
+ return [...known, ...userIds.filter((id) => !known.includes(id))]
623
+ }, [order, userIds])
624
+ const deferredSearch = React.useDeferredValue(globalFilter)
625
+ // The system columns go in the order too, so every list of leaf columns matches the header.
626
+ const fullOrder = [...pinned.left.filter((id) => SYSTEM.has(id)), ...columnOrder, ...pinned.right]
627
+
628
+ const table = useReactTable<T>({
629
+ data,
630
+ columns: allColumns,
631
+ getRowId: rowIdOf,
632
+ getSubRows,
633
+ getRowCanExpand: getRowCanExpand ?? (renderSubComponent ? () => true : (row) => row.subRows.length > 0),
634
+ state: {
635
+ sorting,
636
+ columnFilters,
637
+ globalFilter: deferredSearch,
638
+ pagination,
639
+ rowSelection: effectiveSelection,
640
+ columnVisibility,
641
+ columnOrder: fullOrder,
642
+ columnPinning: pinned,
643
+ expanded,
644
+ },
645
+ // Against the latest state, not this render's, so two changes in one event both count.
646
+ onSortingChange: (u) => setSorting(resolve(u, latest.current.sorting), personDetails("sort")),
647
+ onColumnFiltersChange: (u) => setFilters(resolve(u, latest.current.columnFilters), personDetails("filter")),
648
+ onGlobalFilterChange: (u) => setSearch(resolve(u, latest.current.globalFilter), personDetails("search")),
649
+ onPaginationChange: (u) => changePagination(resolve(u, latest.current.pagination), personDetails("page")),
650
+ onRowSelectionChange: (u) => setSelection(resolve(u, latest.current.rowSelection), personDetails("select")),
651
+ onColumnVisibilityChange: (u) => changeVisibility(resolve(u, latest.current.columnVisibility), personDetails("visibility")),
652
+ onExpandedChange: setExpanded,
653
+ enableRowSelection: (row) => selectable && row.depth === 0 && !disabled,
654
+ enableSortingRemoval: false,
655
+ manualSorting: manual,
656
+ manualFiltering: manual,
657
+ manualPagination: manual || virtualize,
658
+ rowCount,
659
+ autoResetPageIndex: false,
660
+ autoResetExpanded: false,
661
+ maxLeafRowFilterDepth: 0,
662
+ paginateExpandedRows: virtualize,
663
+ // Zero marks a column with no width of its own, which shares what the fixed ones leave.
664
+ defaultColumn: { size: 0 },
665
+ getCoreRowModel: getCoreRowModel(),
666
+ getSortedRowModel: getSortedRowModel(),
667
+ getFilteredRowModel: getFilteredRowModel(),
668
+ getPaginationRowModel: getPaginationRowModel(),
669
+ getExpandedRowModel: getExpandedRowModel(),
670
+ getFacetedRowModel: getFacetedRowModel(),
671
+ getFacetedUniqueValues: getFacetedUniqueValues(),
672
+ })
673
+
674
+ const widthOf = (id: string) => sizes[id] ?? table.getColumn(id)?.columnDef.size ?? 0
675
+ const userColumns = table.getAllLeafColumns().filter((c) => !SYSTEM.has(c.id))
676
+ const visibleUser = table.getVisibleLeafColumns().filter((c) => !SYSTEM.has(c.id))
677
+ const leftOffsets = new Map<string, number>()
678
+ {
679
+ let left = 0
680
+ for (const column of table.getLeftVisibleLeafColumns()) {
681
+ leftOffsets.set(column.id, left)
682
+ left += widthOf(column.id) || 160
683
+ }
684
+ }
685
+ const lastPinned = table.getLeftVisibleLeafColumns().slice(-1)[0]?.id
686
+
687
+ const total = manual ? (rowCount ?? 0) : table.getFilteredRowModel().rows.length
688
+ const pageRows = table.getRowModel().rows
689
+ const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize))
690
+ const rowLabel = (row: Row<T>) => (getRowLabel ? getRowLabel(row.original, row.id) : `${capitalize(noun.singular)} ${row.id}`)
691
+ const selectableRows = (rows: Row<T>[]) => rows.filter((r) => r.depth === 0 && r.getCanSelect())
692
+
693
+ /* ---- facet ---- */
694
+ const facetColumn = facet ? table.getColumn(facet.column) : undefined
695
+ const facetValue = columnFilters.find((f) => f.id === facet?.column)?.value as string | undefined
696
+ const facetOptions = React.useMemo<DataTableFacetOption[]>(() => {
697
+ if (!facet) return []
698
+ if (facet.options) return facet.options.map((o) => (typeof o === "string" ? { value: o } : o))
699
+ const counts = new Map<string, number>()
700
+ for (const row of data) {
701
+ const value = (row as Record<string, unknown>)[facet.column]
702
+ if (value != null) counts.set(String(value), (counts.get(String(value)) ?? 0) + 1)
703
+ }
704
+ return Array.from(counts, ([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count)
705
+ }, [data, facet])
706
+ const facetCounts = manual ? undefined : facetColumn?.getFacetedUniqueValues()
707
+ const setFacet = (value: string, details: DataTableChangeDetails) => {
708
+ if (!facet) return
709
+ const rest = columnFilters.filter((f) => f.id !== facet.column)
710
+ setFilters(value === ALL ? rest : [...rest, { id: facet.column, value }], details)
711
+ }
712
+
713
+ const clearFilters = () => {
714
+ const details = personDetails("clear-filters")
715
+ if (globalFilter) setSearch("", details)
716
+ if (columnFilters.length) setFilters([], globalFilter ? personDetails("clear-filters") : details)
717
+ }
718
+
719
+ /* ---- selection ---- */
720
+ const coreModel = table.getCoreRowModel()
721
+ const filteredModel = table.getFilteredRowModel()
722
+ const filteredRef = React.useRef(onFilteredRowsChange)
723
+ filteredRef.current = onFilteredRowsChange
724
+ React.useEffect(() => {
725
+ if (!manual) filteredRef.current?.(filteredModel.rows.map((r) => r.original))
726
+ }, [manual, filteredModel])
727
+
728
+ // Selected rows the filters hide stay selected, but are counted apart and kept from the actions.
729
+ const picked = React.useMemo(() => {
730
+ const ids: string[] = []
731
+ const hidden: string[] = []
732
+ const rows: T[] = []
733
+ for (const id in effectiveSelection) {
734
+ if (!effectiveSelection[id]) continue
735
+ const shown = (manual ? coreModel : filteredModel).rowsById[id]
736
+ if (shown) {
737
+ ids.push(id)
738
+ rows.push(shown.original)
739
+ } else if (manual) ids.push(id)
740
+ else if (coreModel.rowsById[id]) hidden.push(id)
741
+ }
742
+ return { ids, hidden, rows }
743
+ }, [effectiveSelection, manual, coreModel, filteredModel])
744
+ const selectedCount = picked.ids.length + picked.hidden.length
745
+ const shownCount = everything && manual ? total : picked.ids.length
746
+ const selection: DataTableSelection = { ids: picked.ids, all: everything && manual, count: shownCount, hidden: picked.hidden }
747
+ const clearSelection = () => {
748
+ setEverything(false)
749
+ changeSelection({}, personDetails("clear"))
750
+ }
751
+ const loadedAll = !manual || data.length >= total
752
+ const matching = React.useMemo(
753
+ () => selectableRows(manual ? coreModel.rows : filteredModel.rows),
754
+ // eslint-disable-next-line react-hooks/exhaustive-deps
755
+ [manual, coreModel, filteredModel, disabled, selectable]
756
+ )
757
+ const pageSelectable = React.useMemo(
758
+ () => selectableRows(pageRows),
759
+ // eslint-disable-next-line react-hooks/exhaustive-deps
760
+ [pageRows, disabled, selectable]
761
+ )
762
+ const pageOn = React.useMemo(
763
+ () => pageSelectable.filter((r) => effectiveSelection[r.id]).length,
764
+ [pageSelectable, effectiveSelection]
765
+ )
766
+ const pageAll = pageSelectable.length > 0 && pageOn === pageSelectable.length
767
+ const pageSome = pageOn > 0
768
+
769
+ /* ---- sorting choices, for the phone picker and the agent ---- */
770
+ const sortable = visibleUser.filter((c) => c.getCanSort())
771
+ const sortLabel = (id: string, desc: boolean) => {
772
+ const column = table.getColumn(id)
773
+ return column ? `${labelOf(column)} ${desc ? "descending" : "ascending"}` : id
774
+ }
775
+ const parseSort = (wanted: unknown): { id: string; desc: boolean } | string => {
776
+ const want = String(wanted ?? "").trim().toLowerCase()
777
+ for (const column of sortable) {
778
+ const named = column.columnDef.meta?.sortLabels
779
+ if (named) {
780
+ if (named[0].toLowerCase() === want) return { id: column.id, desc: false }
781
+ if (named[1].toLowerCase() === want) return { id: column.id, desc: true }
782
+ }
783
+ const label = labelOf(column).toLowerCase()
784
+ if (want !== label && !want.startsWith(`${label} `) && want !== column.id.toLowerCase()) continue
785
+ const rest = want === label || want === column.id.toLowerCase() ? "" : want.slice(label.length).trim()
786
+ if (!rest) return { id: column.id, desc: column.getFirstSortDir() === "desc" }
787
+ if (/^(asc|ascending|up|a-z|low.*)$/.test(rest)) return { id: column.id, desc: false }
788
+ if (/^(desc|descending|down|z-a|high.*)$/.test(rest)) return { id: column.id, desc: true }
789
+ }
790
+ return `No column "${String(wanted)}" to sort by. Sortable: ${sortable.map((c) => labelOf(c)).join(", ")}.`
791
+ }
792
+ const phoneSorts = React.useMemo(() => {
793
+ const named = sortable.filter((c) => c.columnDef.meta?.sortLabels)
794
+ return (named.length ? named : sortable).flatMap((c) => {
795
+ const labels = c.columnDef.meta?.sortLabels
796
+ return [
797
+ { key: `${c.id}:desc`, id: c.id, desc: true, label: labels ? labels[1] : `${labelOf(c)}, descending` },
798
+ { key: `${c.id}:asc`, id: c.id, desc: false, label: labels ? labels[0] : `${labelOf(c)}, ascending` },
799
+ ]
800
+ })
801
+ // eslint-disable-next-line react-hooks/exhaustive-deps
802
+ }, [sortable.map((c) => c.id).join()])
803
+
804
+ /* ---- agent ---- */
805
+ const headRef = React.useRef<HTMLTableSectionElement>(null)
806
+ const bodyRef = React.useRef<HTMLTableSectionElement>(null)
807
+ const phoneHeadRef = React.useRef<HTMLDivElement>(null)
808
+ const phoneListRef = React.useRef<HTMLUListElement>(null)
809
+
810
+ useAgentControl(() => {
811
+ if (!sortable.length) return null
812
+ const parse = (list: unknown[]) => {
813
+ const next: SortingState = []
814
+ for (const one of list) {
815
+ const sort = parseSort(one)
816
+ if (typeof sort === "string") return sort
817
+ if (!next.some((s) => s.id === sort.id)) next.push(sort)
818
+ }
819
+ return next
820
+ }
821
+ const apply = (next: SortingState | string) =>
822
+ typeof next === "string"
823
+ ? next
824
+ : JSON.stringify(next) === JSON.stringify(sorting)
825
+ ? undefined
826
+ : changeAsAgent(setSorting, next, "sort")
827
+ return {
828
+ kind: "select",
829
+ element: phone ? phoneHeadRef.current : headRef.current,
830
+ label: `Sort ${plural}`,
831
+ value: sorting.map((s) => sortLabel(s.id, s.desc)),
832
+ items: sortable.flatMap((c) => [sortLabel(c.id, false), sortLabel(c.id, true)]),
833
+ multiple: true,
834
+ disabled,
835
+ actions: {
836
+ select: (wanted: unknown) => apply(parse([wanted])),
837
+ setValue: (wanted: unknown) => apply(parse(Array.isArray(wanted) ? wanted : [wanted])),
838
+ clear: () => apply(props.defaultSorting ?? []),
839
+ },
840
+ }
841
+ })
842
+
843
+ useAgentControl(() => {
844
+ if (!selectable) return null
845
+ const shown = virtualize ? matching : pageSelectable
846
+ const pool = selectableRows(table.getCoreRowModel().rows)
847
+ const pick = (wanted: unknown[]): string[] | string => {
848
+ const ids: string[] = []
849
+ for (const one of wanted.flat()) {
850
+ const want = String(one ?? "").trim().toLowerCase()
851
+ if (want === "all") {
852
+ ids.push(...matching.map((r) => r.id))
853
+ continue
854
+ }
855
+ const row = pool.find((r) => r.id.toLowerCase() === want || rowLabel(r).toLowerCase() === want)
856
+ if (!row) return `No ${noun.singular} "${String(one)}". On this page: ${shown.map(rowLabel).join(", ")}.`
857
+ ids.push(row.id)
858
+ }
859
+ return ids
860
+ }
861
+ const apply = (next: RowSelectionState) => changeAsAgent(setSelection, next, "select")
862
+ return {
863
+ kind: "checkbox-group",
864
+ element: phone ? phoneListRef.current : bodyRef.current,
865
+ label: `Select ${plural}`,
866
+ value: pool.filter((r) => r.getIsSelected()).map(rowLabel),
867
+ items: shown.map(rowLabel),
868
+ multiple: true,
869
+ disabled,
870
+ actions: {
871
+ select: (...wanted: unknown[]) => {
872
+ const ids = pick(wanted)
873
+ if (typeof ids === "string") return ids
874
+ const fresh = ids.filter((id) => !rowSelection[id])
875
+ if (!fresh.length) return undefined
876
+ return apply({ ...rowSelection, ...Object.fromEntries(fresh.map((id) => [id, true])) })
877
+ },
878
+ setValue: (...wanted: unknown[]) => {
879
+ const ids = pick(wanted)
880
+ return typeof ids === "string" ? ids : apply(Object.fromEntries(ids.map((id) => [id, true])))
881
+ },
882
+ clear: () => (selectedCount ? apply({}) : undefined),
883
+ },
884
+ }
885
+ })
886
+
887
+ /* ---- announcements ---- */
888
+ const sortSpeech = sorting
889
+ .map((s, i) => `${i ? "then " : "Sorted by "}${labelOf(table.getColumn(s.id) ?? ({ id: s.id, columnDef: {} } as Column<T, unknown>))}, ${s.desc ? "descending" : "ascending"}`)
890
+ .join(", ")
891
+ const announcement = touched && !loading && !error ? [sortSpeech, `${total.toLocaleString()} ${total === 1 ? noun.singular : plural}.`].filter(Boolean).join(". ") : ""
892
+
893
+ /* ---- scroll container ---- */
894
+ const scrollRef = React.useRef<HTMLDivElement | null>(null)
895
+ const [scroller, setScroller] = React.useState<HTMLDivElement | null>(null)
896
+ const containerRef = React.useCallback(
897
+ (node: HTMLDivElement | null) => {
898
+ scrollRef.current = node
899
+ if (virtualize) setScroller(node)
900
+ },
901
+ [virtualize]
902
+ )
903
+ React.useEffect(() => {
904
+ const node = scrollRef.current
905
+ if (!node) return
906
+ // An attribute rather than state, so scrolling never renders the table again.
907
+ const onScroll = () => node.toggleAttribute("data-scrolled", node.scrollLeft > 0)
908
+ onScroll()
909
+ node.addEventListener("scroll", onScroll, { passive: true })
910
+ // Messages and expanded panels span every column, so they size to what is in view, not to the table.
911
+ const fit = () => node.style.setProperty("--data-table-viewport", `${node.clientWidth}px`)
912
+ fit()
913
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(fit)
914
+ observer?.observe(node)
915
+ return () => {
916
+ node.removeEventListener("scroll", onScroll)
917
+ observer?.disconnect()
918
+ }
919
+ }, [phone])
920
+
921
+ /* ---- opening a row ---- */
922
+ const openRef = React.useRef<(id: string, event?: Event) => void>(() => {})
923
+ openRef.current = (id, event) => {
924
+ const row = table.getCoreRowModel().rowsById[id] ?? table.getRowModel().rowsById[id]
925
+ if (!row) return
926
+ if (onRowOpen) onRowOpen(row.original, personDetails("open", event))
927
+ else setSheet(id)
928
+ }
929
+ const openRow = React.useCallback((id: string, event?: Event) => openRef.current(id, event), [])
930
+ const onRowClick = (event: React.MouseEvent<HTMLTableRowElement>) => {
931
+ const target = event.target as HTMLElement
932
+ // Clicks bubble out of portalled menus too, and a drag to select text is not a click on the row.
933
+ if (!event.currentTarget.contains(target) || target.closest(INTERACTIVE)) return
934
+ if (window.getSelection?.()?.toString()) return
935
+ const id = event.currentTarget.getAttribute("data-row-id")
936
+ if (id) openRow(id, event.nativeEvent)
937
+ }
938
+
939
+ /* ---- grid keyboard ---- */
940
+ const gridRef = React.useRef<HTMLTableElement>(null)
941
+ const active = React.useRef<Position>({ row: 1, cell: 0, stop: 0 })
942
+ React.useLayoutEffect(() => {
943
+ const grid = gridRef.current
944
+ if (!grid) return
945
+ rove(grid, active.current)
946
+ // Retry took focus to the grid while the rows loaded; hand it back to the cell it left.
947
+ if (document.activeElement === grid && !loading && !error && pageRows.length) focusAt(grid, active.current)
948
+ })
949
+ const retry = () => {
950
+ gridRef.current?.focus()
951
+ onRetry?.()
952
+ }
953
+ const onGridFocus = (event: React.FocusEvent<HTMLTableElement>) => {
954
+ const grid = gridRef.current
955
+ if (!grid || !grid.contains(event.target)) return
956
+ const p = positionOf(grid, event.target as HTMLElement)
957
+ if (p) {
958
+ active.current = p
959
+ rove(grid, p)
960
+ }
961
+ }
962
+ const onGridKeyDown = (event: React.KeyboardEvent<HTMLTableElement>) => {
963
+ const grid = gridRef.current
964
+ const target = event.target as HTMLElement
965
+ // React sends events from portalled menus through here too; only the grid's own count.
966
+ if (!grid || !grid.contains(target) || event.altKey || event.metaKey) return
967
+ if (target.getAttribute("role") === "separator" && (event.key === "ArrowLeft" || event.key === "ArrowRight")) return
968
+ if (event.key === "Enter" && !target.closest(INTERACTIVE)) {
969
+ const id = target.closest("tbody > tr")?.getAttribute("data-row-id")
970
+ if (id) {
971
+ event.preventDefault()
972
+ openRow(id, event.nativeEvent)
973
+ }
974
+ return
975
+ }
976
+ if (event.key === " " && !target.closest("button, a, input, [role='checkbox']")) {
977
+ const id = target.closest("tr")?.getAttribute("data-row-id")
978
+ const row = id ? table.getRow(id) : undefined
979
+ if (row?.getCanSelect()) {
980
+ event.preventDefault()
981
+ row.toggleSelected()
982
+ }
983
+ return
984
+ }
985
+ const from = positionOf(grid, target)
986
+ if (!from) return
987
+ const to = moveFocus(grid, from, event.key, event.ctrlKey)
988
+ if (!to) return
989
+ event.preventDefault()
990
+ event.stopPropagation()
991
+ active.current = to
992
+ rove(grid, to)
993
+ focusAt(grid, to)
994
+ }
995
+
996
+ /* ---- resize and reorder ---- */
997
+ const drag = React.useRef<{ id: string; x: number; width: number } | null>(null)
998
+ const dragColumn = React.useRef<string | null>(null)
999
+ const setWidth = (id: string, width: number) => {
1000
+ const prev = latest.current.columnSizing
1001
+ const next = Math.max(48, Math.round(width))
1002
+ if (prev[id] !== next) changeSizing({ ...prev, [id]: next }, personDetails("resize"))
1003
+ }
1004
+ const resizeBy = (id: string, delta: number) => {
1005
+ const th = gridRef.current?.querySelector<HTMLElement>(`th[data-column="${CSS.escape(id)}"]`)
1006
+ setWidth(id, (widthOf(id) || th?.getBoundingClientRect().width || FLEX_MIN) + delta)
1007
+ }
1008
+ /** Moves a column to the other side of `target`, its visible neighbour, wherever hidden columns sit. */
1009
+ const moveColumn = (id: string, target: string) => {
1010
+ const center = columnOrder.filter((c) => !pinned.left.includes(c))
1011
+ const from = center.indexOf(id)
1012
+ const at = center.indexOf(target)
1013
+ if (from < 0 || at < 0 || from === at) return
1014
+ center.splice(from, 1)
1015
+ center.splice(center.indexOf(target) + (from < at ? 1 : 0), 0, id)
1016
+ changeOrder([...pinned.left.filter((c) => userIds.includes(c)), ...center], personDetails("move"))
1017
+ }
1018
+ const centerIds = columnOrder.filter((c) => !pinned.left.includes(c) && table.getColumn(c)?.getIsVisible())
1019
+
1020
+ /* ---- rows ---- */
1021
+ const uid = React.useId()
1022
+ const actionsRef = React.useRef(rowActions)
1023
+ actionsRef.current = rowActions
1024
+ const drawRef = React.useRef<(row: Row<T>, index: number) => React.ReactNode>(() => null)
1025
+ const drawRow = React.useCallback((row: Row<T>, index: number) => drawRef.current(row, index), [])
1026
+ // Everything a row draws from besides itself. While it holds, a row renders again only when its own data,
1027
+ // place, selection or expansion changes.
1028
+ const view = React.useMemo(
1029
+ () => ({}),
1030
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1031
+ [allColumns, fullOrder.join(), columnVisibility, sizes, disabled, hasAgent, density, virtualize, selectable, renderSubComponent, Boolean(onRowOpen), noun.singular, getSubRows]
1032
+ )
1033
+
1034
+ /* ---- rendering helpers ---- */
1035
+ const rowContext = (row: Row<T>, inert: boolean): RowContextValue => ({ id: row.id, inert, open: openRow })
1036
+ const sheetRow = sheet ? table.getCoreRowModel().rowsById[sheet] ?? table.getRowModel().rowsById[sheet] : undefined
1037
+ const stickyStyle = (id: string): React.CSSProperties | undefined =>
1038
+ leftOffsets.has(id) ? { left: leftOffsets.get(id) } : undefined
1039
+ const pinClass = (id: string, head: boolean) =>
1040
+ leftOffsets.has(id) &&
1041
+ cn(
1042
+ "sticky",
1043
+ head ? "z-[3]" : "z-[1]",
1044
+ id === lastPinned &&
1045
+ "group-data-[scrolled]/dt:shadow-[8px_0_8px_-8px_rgb(0_0_0/0.18)] group-data-[scrolled]/dt:[clip-path:inset(0_-12px_0_0)]"
1046
+ )
1047
+
1048
+ const emptyContext: DataTableEmptyContext = {
1049
+ query: globalFilter,
1050
+ filter: facetValue,
1051
+ filtered: data.length > 0 || Boolean(globalFilter || columnFilters.length),
1052
+ clear: clearFilters,
1053
+ }
1054
+ // Rows already on screen stay, dimmed, while the next ones load.
1055
+ const stale = loading && pageRows.length > 0
1056
+ const status: "loading" | "error" | "empty" | "rows" = stale
1057
+ ? "rows"
1058
+ : loading
1059
+ ? "loading"
1060
+ : error
1061
+ ? "error"
1062
+ : pageRows.length === 0
1063
+ ? "empty"
1064
+ : "rows"
1065
+ // Dims over the fast token and returns at once, so the new rows never fade in.
1066
+ const dim =
1067
+ "data-[stale]:opacity-60 data-[stale]:transition-opacity data-[stale]:duration-[var(--motion-duration-fast,150ms)] data-[stale]:ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]"
1068
+
1069
+ const stateBlock = (() => {
1070
+ if (status === "error")
1071
+ return (
1072
+ <div role="alert" data-slot="data-table-state" data-state="error" className="grid h-[var(--data-table-state-height)] place-content-center justify-items-center gap-3 text-center">
1073
+ <p className="m-0 text-sm">{error === true ? `Couldn't load ${plural}.` : error}</p>
1074
+ {onRetry && (
1075
+ <Button variant="outline" size="sm" className="h-8" onClick={retry}>
1076
+ Try again
1077
+ </Button>
1078
+ )}
1079
+ </div>
1080
+ )
1081
+ if (status !== "empty") return null
1082
+ if (emptyState) return emptyState(emptyContext)
1083
+ const message = globalFilter
1084
+ ? `No ${plural} match “${globalFilter}”`
1085
+ : facetValue
1086
+ ? `No ${String(facetValue).toLowerCase()} ${plural}`
1087
+ : `No ${plural} yet`
1088
+ return (
1089
+ <div data-slot="data-table-state" data-state="empty" className="grid h-[var(--data-table-state-height)] place-content-center justify-items-center gap-3 text-center">
1090
+ <p className="m-0 text-sm">{message}</p>
1091
+ {(globalFilter || columnFilters.length > 0) && (
1092
+ <Button variant="outline" size="sm" className="h-8" onClick={clearFilters}>
1093
+ Clear filters
1094
+ </Button>
1095
+ )}
1096
+ </div>
1097
+ )
1098
+ })()
1099
+
1100
+ const chips = (layout: "desktop" | "phone") =>
1101
+ facet && facetColumn ? (
1102
+ <ToggleGroup
1103
+ data-slot="data-table-filters"
1104
+ aria-label={`Filter ${plural} by ${labelOf(facetColumn)}`}
1105
+ value={[facetValue ?? ALL]}
1106
+ disabled={disabled}
1107
+ onValueChange={(next, details) => {
1108
+ if (next.length) setFacet(String(next[next.length - 1]), details as DataTableChangeDetails)
1109
+ }}
1110
+ className={cn(
1111
+ "justify-start",
1112
+ layout === "desktop" ? "gap-0.5" : "-mx-4 flex-nowrap gap-1.5 overflow-x-auto px-4 [scrollbar-width:none]"
1113
+ )}
1114
+ >
1115
+ {[{ value: ALL, label: "All", count: undefined } as DataTableFacetOption, ...facetOptions].map((option) => {
1116
+ const count = option.value === ALL ? undefined : manual ? option.count : (facetCounts?.get(option.value) ?? 0)
1117
+ return (
1118
+ <ToggleGroupItem
1119
+ key={option.value}
1120
+ value={option.value}
1121
+ className={cn(
1122
+ "shrink-0 gap-1.5 rounded-full font-normal",
1123
+ layout === "desktop"
1124
+ ? "h-7 border-0 px-2.5 text-[12.5px] text-muted-foreground hover:bg-transparent hover:text-foreground data-[pressed]:bg-secondary data-[pressed]:font-medium data-[pressed]:text-foreground"
1125
+ : "h-[34px] border-border px-3.5 text-sm data-[pressed]:border-primary data-[pressed]:bg-primary data-[pressed]:text-primary-foreground"
1126
+ )}
1127
+ >
1128
+ {option.label ?? option.value}
1129
+ {count !== undefined && " "}
1130
+ {count !== undefined && <span className="font-normal tabular-nums">{count}</span>}
1131
+ </ToggleGroupItem>
1132
+ )
1133
+ })}
1134
+ </ToggleGroup>
1135
+ ) : null
1136
+
1137
+ const search = (layout: "desktop" | "phone") => (
1138
+ <div data-slot="data-table-search" className={cn("relative", layout === "desktop" ? "w-[220px]" : "w-full")}>
1139
+ <Search
1140
+ aria-hidden
1141
+ className={cn(
1142
+ "pointer-events-none absolute top-1/2 -translate-y-1/2 text-muted-foreground",
1143
+ layout === "desktop" ? "left-2.5 h-4 w-4" : "left-[13px] h-[18px] w-[18px]"
1144
+ )}
1145
+ />
1146
+ <Input
1147
+ type="search"
1148
+ aria-label={`Search ${plural}`}
1149
+ placeholder={`Search ${plural}`}
1150
+ value={draft ?? globalFilter}
1151
+ disabled={disabled}
1152
+ onValueChange={(value, details) => typeSearch(value, details as unknown as DataTableChangeDetails)}
1153
+ className={cn(
1154
+ "[&::-webkit-search-cancel-button]:hidden",
1155
+ layout === "desktop"
1156
+ ? "h-8 pl-8 text-[13px] md:text-[13px]"
1157
+ : "h-[42px] rounded-xl border-0 bg-muted pl-[38px] text-base md:text-base"
1158
+ )}
1159
+ />
1160
+ </div>
1161
+ )
1162
+
1163
+ const titleText = props.title === undefined ? `${total.toLocaleString()} ${total === 1 ? noun.singular : plural}` : props.title
1164
+
1165
+ const sheetPart = (
1166
+ <Drawer
1167
+ open={sheetRow !== undefined}
1168
+ onOpenChange={(open) => {
1169
+ if (!open) setSheet(null)
1170
+ }}
1171
+ swipeDirection={phone ? "down" : "right"}
1172
+ >
1173
+ <DrawerContent
1174
+ side={phone ? "bottom" : "right"}
1175
+ data-slot="data-table-sheet"
1176
+ className={cn("gap-0 p-0", phone ? "max-h-[85vh] rounded-t-[22px]" : "w-[380px] max-w-[90vw]")}
1177
+ >
1178
+ {sheetRow && (
1179
+ <RowContext.Provider value={rowContext(sheetRow, true)}>
1180
+ <div className="flex items-center gap-1 px-5 pb-3 pt-5">
1181
+ <DrawerTitle className="mr-auto text-[17px] font-semibold">{rowLabel(sheetRow)}</DrawerTitle>
1182
+ {rowActions && sheetRow.depth === 0 && (
1183
+ <Menu>
1184
+ <MenuTrigger
1185
+ aria-label={`Actions for ${rowLabel(sheetRow)}`}
1186
+ disabled={disabled}
1187
+ data-slot="data-table-sheet-actions"
1188
+ className={cn("border-0 bg-transparent p-0 text-muted-foreground", phone ? "h-11 w-11" : "h-8 w-8")}
1189
+ >
1190
+ <Ellipsis className="h-4 w-4" />
1191
+ </MenuTrigger>
1192
+ <MenuContent align="end" className="min-w-[180px]">
1193
+ {rowActions(sheetRow.original)}
1194
+ </MenuContent>
1195
+ </Menu>
1196
+ )}
1197
+ <DrawerClose
1198
+ aria-label="Close"
1199
+ className={cn(
1200
+ "inline-flex items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
1201
+ phone ? "-mr-2.5 h-11 w-11" : "h-8 w-8"
1202
+ )}
1203
+ >
1204
+ <X className="h-4 w-4" />
1205
+ </DrawerClose>
1206
+ </div>
1207
+ <dl className="m-0 px-5 pb-6">
1208
+ {sheetRow
1209
+ .getVisibleCells()
1210
+ .filter((cell) => !SYSTEM.has(cell.column.id))
1211
+ .map((cell) => (
1212
+ <div key={cell.id} className="grid min-h-12 grid-cols-[150px_1fr] items-center gap-3 border-t py-2">
1213
+ <dt className="text-[13px] text-muted-foreground">{labelOf(cell.column)}</dt>
1214
+ <dd className="m-0 min-w-0 text-sm">{flexRender(cell.column.columnDef.cell, cell.getContext())}</dd>
1215
+ </div>
1216
+ ))}
1217
+ </dl>
1218
+ </RowContext.Provider>
1219
+ )}
1220
+ </DrawerContent>
1221
+ </Drawer>
1222
+ )
1223
+
1224
+ const live = (
1225
+ <div role="status" aria-live="polite" className="sr-only">
1226
+ {announcement}
1227
+ </div>
1228
+ )
1229
+
1230
+ /* ---------------- phone ---------------- */
1231
+ if (phone) {
1232
+ const byRole = (role: "title" | "value" | "meta") =>
1233
+ visibleUser
1234
+ .filter((c) => c.columnDef.meta?.phone === role)
1235
+ .sort((a, b) => (a.columnDef.meta?.phoneOrder ?? 0) - (b.columnDef.meta?.phoneOrder ?? 0))
1236
+ const currentSort = sorting[0] ? `${sorting[0].id}:${sorting[0].desc ? "desc" : "asc"}` : ""
1237
+ const currentLabel = phoneSorts.find((s) => s.key === currentSort)?.label ?? "Sort"
1238
+ const cellOf = (row: Row<T>, column: Column<T, unknown>) => {
1239
+ const cell = row.getAllCells().find((c) => c.column.id === column.id)
1240
+ return cell ? flexRender(column.columnDef.meta?.phoneCell ?? cell.column.columnDef.cell, cell.getContext()) : null
1241
+ }
1242
+ // Selecting is a mode on phone: there is no room for a checkbox column, and a tap already opens the row.
1243
+ const choosing = selectable && status === "rows" && (picking || selectedCount > 0)
1244
+ const finish = () => {
1245
+ setPicking(false)
1246
+ if (selectedCount) clearSelection()
1247
+ }
1248
+ const endPress = () => {
1249
+ if (press.current) window.clearTimeout(press.current.timer)
1250
+ }
1251
+ const startPress = (event: React.PointerEvent, row: Row<T>) => {
1252
+ // A long-press whose click never came must not swallow this one.
1253
+ press.current = null
1254
+ if (!selectable || choosing || disabled || event.pointerType === "mouse" || !row.getCanSelect()) return
1255
+ const held = { fired: false, timer: 0 }
1256
+ held.timer = window.setTimeout(() => {
1257
+ held.fired = true
1258
+ setPicking(true)
1259
+ changeSelection({ ...rowSelection, [row.id]: true }, personDetails("long-press", event.nativeEvent))
1260
+ }, 500)
1261
+ press.current = held
1262
+ }
1263
+ return (
1264
+ <div
1265
+ ref={ref}
1266
+ data-slot="data-table"
1267
+ data-layout="phone"
1268
+ className={cn("flex flex-col", className)}
1269
+ style={{ "--data-table-max-height": maxHeight ? `${maxHeight}px` : "none" } as React.CSSProperties}
1270
+ >
1271
+ <div ref={phoneHeadRef} data-slot="data-table-heading" className="flex items-baseline justify-between gap-3">
1272
+ {titleText !== null && <h2 className="m-0 text-[28px] font-semibold tracking-[-0.015em]">{titleText}</h2>}
1273
+ {selectable && status === "rows" && !choosing && (
1274
+ <button
1275
+ type="button"
1276
+ disabled={disabled}
1277
+ data-slot="data-table-select-mode"
1278
+ onClick={() => setPicking(true)}
1279
+ className="ml-auto h-11 cursor-pointer text-[15px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default disabled:opacity-50"
1280
+ >
1281
+ Select
1282
+ </button>
1283
+ )}
1284
+ {phoneSorts.length > 0 && (
1285
+ <span data-agent-hidden={hasAgent ? "" : undefined}>
1286
+ <Menu>
1287
+ <MenuTrigger
1288
+ disabled={disabled}
1289
+ aria-label={`Sort ${plural}: ${currentLabel}`}
1290
+ className="h-11 gap-1 border-0 bg-transparent px-0 text-[15px] font-normal text-muted-foreground hover:bg-transparent hover:text-foreground data-[popup-open]:bg-transparent"
1291
+ >
1292
+ {currentLabel}
1293
+ <ArrowUpDown aria-hidden className="h-4 w-4" />
1294
+ </MenuTrigger>
1295
+ <MenuContent align="end">
1296
+ <MenuRadioGroup
1297
+ value={currentSort}
1298
+ onValueChange={(key) => {
1299
+ const pick = phoneSorts.find((s) => s.key === key)
1300
+ if (pick) setSorting([{ id: pick.id, desc: pick.desc }], personDetails("sort"))
1301
+ }}
1302
+ >
1303
+ {phoneSorts.map((s) => (
1304
+ <MenuRadioItem key={s.key} value={s.key} className="min-h-11 text-[15px]">
1305
+ {s.label}
1306
+ </MenuRadioItem>
1307
+ ))}
1308
+ </MenuRadioGroup>
1309
+ </MenuContent>
1310
+ </Menu>
1311
+ </span>
1312
+ )}
1313
+ </div>
1314
+ {choosing ? (
1315
+ <div
1316
+ data-slot="data-table-selection-bar"
1317
+ className="mt-3 flex min-h-[42px] items-center gap-2 rounded-xl px-3.5 text-[15px] [background-color:color-mix(in_oklab,var(--secondary)_70%,var(--card))]"
1318
+ >
1319
+ <span className="mr-auto whitespace-nowrap">
1320
+ <b className="font-semibold tabular-nums">{shownCount.toLocaleString()}</b> selected
1321
+ </span>
1322
+ {shownCount > 0 && selectionActions?.(picked.rows, clearSelection, selection)}
1323
+ <Button variant="ghost" className="-mr-2 h-11 px-3 text-[15px]" disabled={disabled} onClick={finish}>
1324
+ Done
1325
+ </Button>
1326
+ </div>
1327
+ ) : (
1328
+ <>
1329
+ <div className="mt-3">{search("phone")}</div>
1330
+ {facet && <div className="mt-3">{chips("phone")}</div>}
1331
+ {props.toolbar && <div className="mt-3 flex flex-wrap items-center gap-2">{props.toolbar}</div>}
1332
+ </>
1333
+ )}
1334
+ {live}
1335
+ {status === "rows" ? (
1336
+ <ul
1337
+ ref={phoneListRef}
1338
+ data-slot="data-table-phone-list"
1339
+ aria-label={capitalize(plural)}
1340
+ aria-busy={loading || undefined}
1341
+ data-stale={stale || undefined}
1342
+ className={cn("m-0 mt-2 max-h-[var(--data-table-max-height)] list-none overflow-y-auto overscroll-contain p-0 [-webkit-overflow-scrolling:touch]", dim)}
1343
+ >
1344
+ {pageRows
1345
+ .filter((row) => row.depth === 0)
1346
+ .map((row) => (
1347
+ <li key={row.id} className="border-b">
1348
+ <RowContext.Provider value={rowContext(row, true)}>
1349
+ <button
1350
+ type="button"
1351
+ role={choosing ? "checkbox" : undefined}
1352
+ aria-checked={choosing ? row.getIsSelected() : undefined}
1353
+ disabled={disabled || (choosing && !row.getCanSelect())}
1354
+ data-slot="data-table-phone-row"
1355
+ onPointerDown={(event) => startPress(event, row)}
1356
+ onPointerUp={endPress}
1357
+ onPointerLeave={endPress}
1358
+ onPointerCancel={endPress}
1359
+ onContextMenu={(event) => {
1360
+ // Android opens a context menu on long-press, which would cut selection short.
1361
+ if (selectable && (event.nativeEvent as PointerEvent).pointerType !== "mouse") event.preventDefault()
1362
+ }}
1363
+ onClick={(event) => {
1364
+ if (press.current?.fired) {
1365
+ press.current = null
1366
+ return
1367
+ }
1368
+ if (choosing) row.toggleSelected()
1369
+ else openRow(row.id, event.nativeEvent)
1370
+ }}
1371
+ className={cn(
1372
+ "grid w-full cursor-pointer select-none grid-cols-[1fr_auto] gap-x-3 gap-y-[3px] py-[13px] text-left [-webkit-touch-callout:none]",
1373
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
1374
+ choosing && "grid-cols-[auto_1fr_auto]"
1375
+ )}
1376
+ >
1377
+ {choosing && (
1378
+ <span
1379
+ aria-hidden
1380
+ data-checked={row.getIsSelected() ? "" : undefined}
1381
+ className="row-span-2 inline-flex h-5 w-5 items-center justify-center self-center rounded-[5px] border border-primary data-[checked]:bg-primary data-[checked]:text-primary-foreground"
1382
+ >
1383
+ {row.getIsSelected() && (
1384
+ <svg viewBox="0 0 16 16" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="2.2">
1385
+ <path d="M3.5 8.5l3 3 6-7" />
1386
+ </svg>
1387
+ )}
1388
+ </span>
1389
+ )}
1390
+ <span className="min-w-0 truncate text-base font-medium">
1391
+ {byRole("title").map((c) => (
1392
+ <React.Fragment key={c.id}>{cellOf(row, c)}</React.Fragment>
1393
+ ))}
1394
+ </span>
1395
+ <span className="text-right text-base tabular-nums">
1396
+ {byRole("value").map((c) => (
1397
+ <React.Fragment key={c.id}>{cellOf(row, c)}</React.Fragment>
1398
+ ))}
1399
+ </span>
1400
+ <span className="col-span-2 col-end-[-1] flex min-w-0 flex-wrap items-center gap-x-2 text-[13px] text-muted-foreground">
1401
+ {byRole("meta").map((c) => (
1402
+ <span key={c.id} className="inline-flex items-center">
1403
+ {cellOf(row, c)}
1404
+ </span>
1405
+ ))}
1406
+ </span>
1407
+ </button>
1408
+ </RowContext.Provider>
1409
+ </li>
1410
+ ))}
1411
+ </ul>
1412
+ ) : status === "loading" ? (
1413
+ <ul aria-busy className="m-0 mt-2 list-none p-0" aria-label={capitalize(plural)}>
1414
+ {Array.from({ length: Math.min(pagination.pageSize, 8) }, (_, i) => (
1415
+ <li key={i} className="grid grid-cols-[1fr_auto] gap-x-3 gap-y-2 border-b py-[15px]">
1416
+ <Skeleton className="h-4" style={{ width: `${40 + seed(i) * 30}%` }} />
1417
+ <Skeleton className="h-4 w-14" />
1418
+ <Skeleton className="col-span-2 h-3" style={{ width: `${50 + seed(i + 3) * 30}%` }} />
1419
+ </li>
1420
+ ))}
1421
+ </ul>
1422
+ ) : (
1423
+ <div className="py-[60px] text-center text-[15px] text-muted-foreground">
1424
+ {status === "error" || emptyState ? stateBlock : globalFilter ? `No ${plural} match` : (stateBlock ?? null)}
1425
+ </div>
1426
+ )}
1427
+ {status === "rows" && !virtualize && pageCount > 1 && (
1428
+ <div data-slot="data-table-footer" className="mt-4 flex justify-center">
1429
+ <Pagination
1430
+ aria-label={`Pages of ${plural}`}
1431
+ variant="compact"
1432
+ size="lg"
1433
+ count={pageCount}
1434
+ page={pagination.pageIndex + 1}
1435
+ disabled={disabled}
1436
+ onPageChange={(page, details) => changePagination({ ...pagination, pageIndex: page - 1 }, details)}
1437
+ />
1438
+ </div>
1439
+ )}
1440
+ {sheetPart}
1441
+ </div>
1442
+ )
1443
+ }
1444
+
1445
+ /* ---------------- desktop ---------------- */
1446
+ const headerCell = (header: Header<T, unknown>) => {
1447
+ const column = header.column
1448
+ const id = column.id
1449
+ const meta = column.columnDef.meta
1450
+ const width = widthOf(id)
1451
+ const sorted = column.getIsSorted()
1452
+ const index = column.getSortIndex()
1453
+ const label = labelOf(column)
1454
+ const draggable = reorderable && !SYSTEM.has(id) && !leftOffsets.has(id)
1455
+ const labelId = `${uid}-h${header.index}`
1456
+ const content =
1457
+ id === SELECT ? (
1458
+ pageSelectable.length > 0 && status === "rows" ? (
1459
+ <span data-agent-hidden={hasAgent ? "" : undefined} className="inline-flex">
1460
+ <Checkbox
1461
+ // A virtualized table has one page, so this box covers every row.
1462
+ aria-label={virtualize ? "Select all" : "Select page"}
1463
+ checked={pageAll}
1464
+ indeterminate={!pageAll && pageSome}
1465
+ disabled={disabled}
1466
+ className={indeterminate}
1467
+ onCheckedChange={(on) => table.toggleAllPageRowsSelected(Boolean(on))}
1468
+ />
1469
+ </span>
1470
+ ) : null
1471
+ ) : SYSTEM.has(id) ? (
1472
+ id === ACTIONS ? <span className="sr-only">Actions</span> : null
1473
+ ) : column.getCanSort() ? (
1474
+ <button
1475
+ type="button"
1476
+ data-slot="data-table-sort"
1477
+ data-agent-part={hasAgent ? "" : undefined}
1478
+ disabled={disabled}
1479
+ onClick={column.getToggleSortingHandler()}
1480
+ className={cn(
1481
+ "group/sort -mx-0.5 inline-flex h-[26px] max-w-full cursor-pointer items-center gap-0.5 rounded-md hover:text-foreground",
1482
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
1483
+ meta?.numeric && "flex-row-reverse",
1484
+ sorted && "text-foreground"
1485
+ )}
1486
+ >
1487
+ <span className="truncate">{flexRender(column.columnDef.header, header.getContext())}</span>
1488
+ <span
1489
+ aria-hidden
1490
+ className={cn(
1491
+ "inline-grid w-3.5 shrink-0 place-items-center opacity-0 transition-opacity duration-100 group-hover/sort:opacity-100 motion-reduce:transition-none",
1492
+ // The arrow hangs into the cell padding, so a short header is not cut to make room for it.
1493
+ meta?.numeric ? "-ml-2" : "-mr-2",
1494
+ sorted && "opacity-100"
1495
+ )}
1496
+ >
1497
+ {sorted === "asc" ? <ArrowUp className="h-3.5 w-3.5" /> : <ArrowDown className="h-3.5 w-3.5" />}
1498
+ </span>
1499
+ {sorted && sorting.length > 1 && <sup className="-ml-0.5 text-[9px] text-muted-foreground">{index + 1}</sup>}
1500
+ </button>
1501
+ ) : (
1502
+ flexRender(column.columnDef.header, header.getContext())
1503
+ )
1504
+ return (
1505
+ <TableHead
1506
+ key={header.id}
1507
+ data-column={id}
1508
+ numeric={meta?.numeric}
1509
+ // Named by its label alone, so the resize handle's width is not read with it.
1510
+ aria-labelledby={SYSTEM.has(id) ? undefined : labelId}
1511
+ aria-sort={sorted ? (sorted === "asc" ? "ascending" : "descending") : undefined}
1512
+ style={stickyStyle(id)}
1513
+ draggable={draggable && !disabled}
1514
+ onDragStart={
1515
+ draggable
1516
+ ? (event) => {
1517
+ if (drag.current) return event.preventDefault()
1518
+ dragColumn.current = id
1519
+ event.dataTransfer.effectAllowed = "move"
1520
+ event.dataTransfer.setData("text/plain", id)
1521
+ }
1522
+ : undefined
1523
+ }
1524
+ onDragOver={draggable ? (event) => dragColumn.current && event.preventDefault() : undefined}
1525
+ onDrop={
1526
+ draggable
1527
+ ? (event) => {
1528
+ event.preventDefault()
1529
+ if (dragColumn.current && dragColumn.current !== id) moveColumn(dragColumn.current, id)
1530
+ dragColumn.current = null
1531
+ }
1532
+ : undefined
1533
+ }
1534
+ onDragEnd={() => (dragColumn.current = null)}
1535
+ className={cn(
1536
+ "group/th sticky top-0 z-[2] overflow-hidden text-ellipsis bg-card",
1537
+ pinClass(id, true),
1538
+ id === SELECT && "pr-0",
1539
+ id === EXPAND && "p-0",
1540
+ width === 0 && "min-w-[140px]"
1541
+ )}
1542
+ >
1543
+ {SYSTEM.has(id) ? content : <span id={labelId} className="contents">{content}</span>}
1544
+ {resizable && !SYSTEM.has(id) && (
1545
+ <div
1546
+ role="separator"
1547
+ aria-orientation="vertical"
1548
+ aria-label={`Resize ${label}`}
1549
+ aria-valuemin={48}
1550
+ // An unsized column reports the width it rendered at, since a focusable separator needs a value.
1551
+ aria-valuenow={Math.round(width) || undefined}
1552
+ ref={(el) => {
1553
+ if (el && !width) el.setAttribute("aria-valuenow", String(Math.round(el.parentElement?.getBoundingClientRect().width ?? 0)))
1554
+ }}
1555
+ data-slot="data-table-resize"
1556
+ tabIndex={-1}
1557
+ onPointerDown={(event) => {
1558
+ event.preventDefault()
1559
+ event.stopPropagation()
1560
+ const th = event.currentTarget.parentElement
1561
+ drag.current = { id, x: event.clientX, width: th?.getBoundingClientRect().width ?? width }
1562
+ event.currentTarget.setPointerCapture?.(event.pointerId)
1563
+ }}
1564
+ onPointerMove={(event) => {
1565
+ const d = drag.current
1566
+ if (!d) return
1567
+ setWidth(d.id, d.width + event.clientX - d.x)
1568
+ }}
1569
+ onPointerUp={() => (drag.current = null)}
1570
+ onKeyDown={(event) => {
1571
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return
1572
+ event.preventDefault()
1573
+ resizeBy(id, event.key === "ArrowLeft" ? -16 : 16)
1574
+ }}
1575
+ className={cn(
1576
+ "absolute right-0 top-0 h-full w-2 cursor-col-resize touch-none select-none opacity-0",
1577
+ "after:absolute after:right-0.5 after:top-1/4 after:h-1/2 after:w-px after:bg-border after:content-['']",
1578
+ "hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:after:w-0.5 focus-visible:after:bg-ring group-hover/th:opacity-100"
1579
+ )}
1580
+ />
1581
+ )}
1582
+ </TableHead>
1583
+ )
1584
+ }
1585
+
1586
+ const bodyCell = (cell: Cell<T, unknown>, row: Row<T>) => {
1587
+ const id = cell.column.id
1588
+ const meta = cell.column.columnDef.meta
1589
+ const sub = row.depth > 0
1590
+ let content: React.ReactNode = null
1591
+ if (id === SELECT) {
1592
+ content = row.getCanSelect() ? (
1593
+ <span data-agent-hidden={hasAgent ? "" : undefined} className="inline-flex">
1594
+ <Checkbox
1595
+ aria-label={`Select ${rowLabel(row)}`}
1596
+ checked={row.getIsSelected()}
1597
+ disabled={disabled}
1598
+ onCheckedChange={(on) => row.toggleSelected(Boolean(on))}
1599
+ />
1600
+ </span>
1601
+ ) : null
1602
+ } else if (id === EXPAND) {
1603
+ content = row.getCanExpand() ? (
1604
+ <button
1605
+ type="button"
1606
+ aria-label={row.getIsExpanded() ? "Hide details" : "Show details"}
1607
+ aria-expanded={row.getIsExpanded()}
1608
+ disabled={disabled}
1609
+ onClick={row.getToggleExpandedHandler()}
1610
+ className={cn(
1611
+ "inline-flex h-7 w-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground",
1612
+ "transition-transform [transition-duration:160ms] aria-expanded:rotate-90 motion-reduce:transition-none",
1613
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
1614
+ )}
1615
+ >
1616
+ <ChevronRight className="h-4 w-4" />
1617
+ </button>
1618
+ ) : null
1619
+ } else if (id === ACTIONS) {
1620
+ content =
1621
+ rowActions && !sub ? (
1622
+ <RowMenu label={`Actions for ${rowLabel(row)}`} disabled={disabled} items={() => actionsRef.current?.(row.original)} />
1623
+ ) : null
1624
+ } else if (!sub || cell.getValue() != null) {
1625
+ content = flexRender(cell.column.columnDef.cell, cell.getContext())
1626
+ }
1627
+ return (
1628
+ <TableCell
1629
+ key={cell.id}
1630
+ numeric={meta?.numeric}
1631
+ style={stickyStyle(id)}
1632
+ className={cn(
1633
+ "overflow-hidden text-ellipsis",
1634
+ pinClass(id, false),
1635
+ id === SELECT && "pr-0",
1636
+ id === EXPAND && "p-0 text-center",
1637
+ id === ACTIONS && "px-1.5",
1638
+ sub && subRowCell,
1639
+ sub && row.getParentRow()?.subRows.slice(-1)[0] === row && "border-b"
1640
+ )}
1641
+ >
1642
+ {content}
1643
+ </TableCell>
1644
+ )
1645
+ }
1646
+
1647
+ drawRef.current = (row: Row<T>, index: number) => (
1648
+ <>
1649
+ <TableRow
1650
+ data-row-id={row.id}
1651
+ data-depth={row.depth || undefined}
1652
+ aria-rowindex={index}
1653
+ aria-selected={row.depth === 0 && selectable ? row.getIsSelected() : undefined}
1654
+ onClick={onRowOpen ? onRowClick : undefined}
1655
+ className={cn("group/row", rowBg, onRowOpen && "cursor-pointer")}
1656
+ >
1657
+ <RowContext.Provider value={rowContext(row, false)}>
1658
+ {row.getVisibleCells().map((cell) => bodyCell(cell, row))}
1659
+ </RowContext.Provider>
1660
+ </TableRow>
1661
+ {renderSubComponent && !virtualize && row.getIsExpanded() && (
1662
+ <TableRow data-slot="data-table-sub-row">
1663
+ <TableCell colSpan={row.getVisibleCells().length} className="h-auto whitespace-normal bg-[color:color-mix(in_oklab,var(--muted)_40%,transparent)] p-0">
1664
+ <div data-slot="data-table-sub-panel" className={inView}>
1665
+ {renderSubComponent(row)}
1666
+ </div>
1667
+ </TableCell>
1668
+ </TableRow>
1669
+ )}
1670
+ </>
1671
+ )
1672
+ const bodyRow = (row: Row<T>, i: number) => (
1673
+ <DataTableBodyRow
1674
+ key={row.id}
1675
+ row={row}
1676
+ index={virtualize ? i + 2 : pagination.pageIndex * pagination.pageSize + i + 2}
1677
+ selected={row.getIsSelected()}
1678
+ expanded={row.getIsExpanded()}
1679
+ view={view}
1680
+ render={drawRow}
1681
+ />
1682
+ )
1683
+
1684
+ const span = table.getVisibleLeafColumns().length
1685
+ const rowHeight = density === "compact" ? 36 : 48
1686
+
1687
+ const skeletonRows = Array.from({ length: Math.min(pagination.pageSize, 10) }, (_, i) => (
1688
+ <TableRow key={`loading-${i}`} className="[&>td]:bg-card">
1689
+ {table.getVisibleLeafColumns().map((column, j) => (
1690
+ <TableCell
1691
+ key={column.id}
1692
+ numeric={column.columnDef.meta?.numeric}
1693
+ style={stickyStyle(column.id)}
1694
+ className={cn(pinClass(column.id, false), column.id === SELECT && "pr-0")}
1695
+ >
1696
+ {column.id === SELECT ? (
1697
+ <Skeleton className="h-4 w-4 rounded-[4px]" />
1698
+ ) : SYSTEM.has(column.id) ? null : (
1699
+ <Skeleton
1700
+ className={cn("h-3 max-w-full", column.columnDef.meta?.numeric && "ml-auto")}
1701
+ style={{
1702
+ width: `${Math.round((column.columnDef.meta?.numeric ? 50 + seed(i * 9 + j) * 40 : 60 + seed(i * 7 + j) * 60) / 1.4)}%`,
1703
+ }}
1704
+ />
1705
+ )}
1706
+ </TableCell>
1707
+ ))}
1708
+ </TableRow>
1709
+ ))
1710
+
1711
+ const minWidth = table
1712
+ .getVisibleLeafColumns()
1713
+ .reduce((sum, column) => sum + (widthOf(column.id) || FLEX_MIN), 0)
1714
+
1715
+ const from = total ? pagination.pageIndex * pagination.pageSize + 1 : 0
1716
+ const to = Math.min(total, (pagination.pageIndex + 1) * pagination.pageSize)
1717
+
1718
+ return (
1719
+ <div
1720
+ ref={ref}
1721
+ data-slot="data-table"
1722
+ className={cn("flex flex-col gap-3.5", className)}
1723
+ style={
1724
+ {
1725
+ "--data-table-max-height": maxHeight ? `${maxHeight}px` : "none",
1726
+ // A message taller than the scroll area would centre itself out of view; 44px leaves room for the header.
1727
+ "--data-table-state-height": maxHeight ? `${Math.min(300, Math.max(120, maxHeight - 44))}px` : "300px",
1728
+ } as React.CSSProperties
1729
+ }
1730
+ >
1731
+ {titleText !== null && (
1732
+ <h2 data-slot="data-table-title" className="m-0 text-xl font-semibold tracking-[-0.015em]">
1733
+ {titleText}
1734
+ </h2>
1735
+ )}
1736
+ <div className="overflow-hidden rounded-xl border bg-card text-card-foreground shadow-sm">
1737
+ <div data-slot="data-table-toolbar" className="flex h-14 items-center gap-2 border-b px-3">
1738
+ {search("desktop")}
1739
+ {chips("desktop")}
1740
+ {props.toolbar}
1741
+ <span className="flex-1" />
1742
+ <Menu>
1743
+ <MenuTrigger
1744
+ aria-label="Columns"
1745
+ disabled={disabled}
1746
+ data-slot="data-table-columns"
1747
+ className="h-8 w-8 border-0 bg-transparent p-0 text-muted-foreground hover:text-foreground"
1748
+ >
1749
+ <Columns3 className="h-4 w-4" />
1750
+ </MenuTrigger>
1751
+ <MenuContent align="end" className="min-w-[180px]">
1752
+ {userColumns
1753
+ .filter((c) => c.getCanHide())
1754
+ .map((column) => (
1755
+ <MenuCheckboxItem
1756
+ key={column.id}
1757
+ checked={column.getIsVisible()}
1758
+ closeOnClick={false}
1759
+ onCheckedChange={(on) => column.toggleVisibility(Boolean(on))}
1760
+ className="group gap-2.5 pl-2 text-[13px] [&>span.absolute]:hidden"
1761
+ >
1762
+ <span
1763
+ aria-hidden
1764
+ className="inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border border-primary group-data-[checked]:bg-primary group-data-[checked]:text-primary-foreground"
1765
+ >
1766
+ <svg viewBox="0 0 16 16" className="hidden h-3 w-3 group-data-[checked]:block" fill="none" stroke="currentColor" strokeWidth="2.2">
1767
+ <path d="M3.5 8.5l3 3 6-7" />
1768
+ </svg>
1769
+ </span>
1770
+ {labelOf(column)}
1771
+ </MenuCheckboxItem>
1772
+ ))}
1773
+ {reorderable && centerIds.length > 1 && (
1774
+ <>
1775
+ <MenuSeparator />
1776
+ <MenuSub>
1777
+ <MenuSubTrigger className="text-[13px]">Move columns</MenuSubTrigger>
1778
+ <MenuSubContent className="min-w-[200px]">
1779
+ {centerIds.map((id, i) => {
1780
+ const name = labelOf(table.getColumn(id)!)
1781
+ return (
1782
+ <React.Fragment key={id}>
1783
+ <MenuItem closeOnClick={false} disabled={i === 0} onClick={() => moveColumn(id, centerIds[i - 1])} className="text-[13px]">
1784
+ Move {name} left
1785
+ </MenuItem>
1786
+ <MenuItem
1787
+ closeOnClick={false}
1788
+ disabled={i === centerIds.length - 1}
1789
+ onClick={() => moveColumn(id, centerIds[i + 1])}
1790
+ className="text-[13px]"
1791
+ >
1792
+ Move {name} right
1793
+ </MenuItem>
1794
+ </React.Fragment>
1795
+ )
1796
+ })}
1797
+ </MenuSubContent>
1798
+ </MenuSub>
1799
+ </>
1800
+ )}
1801
+ </MenuContent>
1802
+ </Menu>
1803
+ </div>
1804
+ {selectedCount > 0 && (status === "rows" || status === "loading") && (
1805
+ <div
1806
+ data-slot="data-table-selection-bar"
1807
+ className="flex h-12 items-center gap-2 border-b px-3 text-[13px] [background-color:color-mix(in_oklab,var(--secondary)_70%,var(--card))]"
1808
+ >
1809
+ <span className="whitespace-nowrap">
1810
+ {selection.all && "All "}
1811
+ <b className="font-semibold tabular-nums">{shownCount.toLocaleString()}</b> selected
1812
+ </span>
1813
+ {picked.hidden.length > 0 && (
1814
+ <span className="whitespace-nowrap text-muted-foreground">
1815
+ <span aria-hidden>· </span>
1816
+ {picked.hidden.length.toLocaleString()} hidden by filters
1817
+ </span>
1818
+ )}
1819
+ {pageAll && !selection.all && (loadedAll ? picked.ids.length < matching.length : picked.ids.length < total) && (
1820
+ <button
1821
+ type="button"
1822
+ disabled={disabled}
1823
+ onClick={() => {
1824
+ if (!loadedAll) return setEverything(true)
1825
+ changeSelection(
1826
+ { ...rowSelection, ...Object.fromEntries(matching.map((r) => [r.id, true])) },
1827
+ personDetails("select-all")
1828
+ )
1829
+ }}
1830
+ className="cursor-pointer underline decoration-[color:color-mix(in_oklab,currentColor_40%,transparent)] underline-offset-[3px] hover:decoration-current focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
1831
+ >
1832
+ Select all {(loadedAll ? matching.length : total).toLocaleString()}
1833
+ </button>
1834
+ )}
1835
+ <span className="flex-1" />
1836
+ {shownCount > 0 && selectionActions?.(picked.rows, clearSelection, selection)}
1837
+ <Button variant="ghost" size="sm" className="h-8" disabled={disabled} onClick={clearSelection}>
1838
+ Clear
1839
+ </Button>
1840
+ </div>
1841
+ )}
1842
+ {live}
1843
+ <Table
1844
+ ref={gridRef}
1845
+ role="grid"
1846
+ aria-label={typeof titleText === "string" ? titleText : capitalize(plural)}
1847
+ aria-rowcount={total + 1}
1848
+ aria-multiselectable={selectable || undefined}
1849
+ aria-busy={loading || undefined}
1850
+ tabIndex={-1}
1851
+ density={density}
1852
+ containerRef={containerRef}
1853
+ containerClassName="group/dt max-h-[var(--data-table-max-height)] overflow-auto overscroll-contain [scrollbar-width:thin]"
1854
+ className="table-fixed focus:outline-none"
1855
+ style={{ minWidth }}
1856
+ onFocus={onGridFocus}
1857
+ onKeyDown={onGridKeyDown}
1858
+ >
1859
+ <colgroup>
1860
+ {table.getVisibleLeafColumns().map((column) => {
1861
+ const width = widthOf(column.id)
1862
+ return <col key={column.id} style={width ? { width } : undefined} />
1863
+ })}
1864
+ </colgroup>
1865
+ <TableHeader ref={headRef}>
1866
+ {table.getHeaderGroups().map((group) => (
1867
+ <TableRow key={group.id} aria-rowindex={1}>
1868
+ {group.headers.map((header) => headerCell(header))}
1869
+ </TableRow>
1870
+ ))}
1871
+ </TableHeader>
1872
+ <TableBody ref={bodyRef} data-stale={stale || undefined} className={cn("[&>tr:hover]:bg-transparent", dim)}>
1873
+ {status === "loading" ? (
1874
+ skeletonRows
1875
+ ) : status !== "rows" ? (
1876
+ <TableRow className="hover:bg-transparent">
1877
+ <TableCell colSpan={span} className="h-auto border-0 p-0">
1878
+ <div className={inView}>{stateBlock}</div>
1879
+ </TableCell>
1880
+ </TableRow>
1881
+ ) : virtualize ? (
1882
+ scroller && (
1883
+ <VirtualRows
1884
+ rows={pageRows}
1885
+ scroller={scroller}
1886
+ rowHeight={rowHeight}
1887
+ height={maxHeight ?? 452}
1888
+ span={span}
1889
+ render={bodyRow}
1890
+ />
1891
+ )
1892
+ ) : (
1893
+ pageRows.map((row, i) => bodyRow(row, i))
1894
+ )}
1895
+ </TableBody>
1896
+ </Table>
1897
+ {/* The pager stays while a page loads, so the button pressed keeps focus. */}
1898
+ {status === "rows" || (status === "loading" && total > 0 && !virtualize) ? (
1899
+ <div
1900
+ data-slot="data-table-footer"
1901
+ className="flex items-center gap-4 border-t px-3 py-2.5 text-[12.5px] text-muted-foreground"
1902
+ >
1903
+ {virtualize ? (
1904
+ <span data-slot="data-table-range" className="tabular-nums">
1905
+ {total.toLocaleString()} {total === 1 ? noun.singular : plural}
1906
+ </span>
1907
+ ) : (
1908
+ <>
1909
+ <span data-slot="data-table-range" className="whitespace-nowrap tabular-nums">
1910
+ {from}–{to} of {total.toLocaleString()}
1911
+ </span>
1912
+ {pageSizes.length > 1 && (
1913
+ <span className="inline-flex items-center gap-2 whitespace-nowrap">
1914
+ Rows
1915
+ <Select
1916
+ items={pageSizes.map((n) => ({ value: n, label: String(n) }))}
1917
+ value={pagination.pageSize}
1918
+ disabled={disabled}
1919
+ onValueChange={(size, details) => {
1920
+ if (size != null)
1921
+ changePagination({ pageIndex: 0, pageSize: Number(size) }, details as unknown as DataTableChangeDetails)
1922
+ }}
1923
+ >
1924
+ <SelectTrigger aria-label="Rows per page" className="h-7 w-auto gap-1 px-2 text-[12.5px]">
1925
+ <SelectValue />
1926
+ </SelectTrigger>
1927
+ <SelectContent>
1928
+ {pageSizes.map((n) => (
1929
+ <SelectItem key={n} value={n} className="text-[13px]">
1930
+ {n}
1931
+ </SelectItem>
1932
+ ))}
1933
+ </SelectContent>
1934
+ </Select>
1935
+ </span>
1936
+ )}
1937
+ <span className="flex-1" />
1938
+ <Pagination
1939
+ aria-label={`Pages of ${plural}`}
1940
+ count={pageCount}
1941
+ page={pagination.pageIndex + 1}
1942
+ disabled={disabled}
1943
+ onPageChange={(page, details) => {
1944
+ changePagination({ ...pagination, pageIndex: page - 1 }, details)
1945
+ if (!details.isCanceled && scrollRef.current) scrollRef.current.scrollTop = 0
1946
+ }}
1947
+ />
1948
+ </>
1949
+ )}
1950
+ </div>
1951
+ ) : status === "loading" ? (
1952
+ <div data-slot="data-table-footer" className="flex items-center gap-4 border-t px-3 py-2.5">
1953
+ <Skeleton className="h-3 w-[90px]" />
1954
+ <span className="flex-1" />
1955
+ <Skeleton className="h-3 w-[220px]" />
1956
+ </div>
1957
+ ) : null}
1958
+ </div>
1959
+ {sheetPart}
1960
+ </div>
1961
+ )
1962
+ }
1963
+
1964
+ interface BodyRowProps {
1965
+ row: Row<any>
1966
+ /** The row's aria-rowindex. */
1967
+ index: number
1968
+ selected: boolean
1969
+ expanded: boolean
1970
+ view: object
1971
+ render: (row: Row<any>, index: number) => React.ReactNode
1972
+ }
1973
+
1974
+ const DataTableBodyRow = React.memo(
1975
+ function DataTableBodyRow({ row, index, render }: BodyRowProps) {
1976
+ return <>{render(row, index)}</>
1977
+ },
1978
+ // A sort copies every row object, so a row is the same when its data and id are.
1979
+ (a, b) =>
1980
+ a.row.original === b.row.original &&
1981
+ a.row.id === b.row.id &&
1982
+ a.index === b.index &&
1983
+ a.selected === b.selected &&
1984
+ a.expanded === b.expanded &&
1985
+ a.view === b.view
1986
+ )
1987
+
1988
+ const rowMenuClass = cn(
1989
+ "inline-flex h-7 w-7 items-center justify-center rounded-md border-0 bg-transparent p-0 text-muted-foreground opacity-0",
1990
+ "hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
1991
+ "group-hover/row:opacity-100 group-focus-within/row:opacity-100 data-[popup-open]:opacity-100 focus-visible:opacity-100",
1992
+ "disabled:pointer-events-none disabled:opacity-50 data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
1993
+ )
1994
+
1995
+ /** A row's actions button. Its menu mounts the first time it opens, so a page of rows costs one button each. */
1996
+ function RowMenu({ label, disabled, items }: { label: string; disabled: boolean; items: () => React.ReactNode }) {
1997
+ const [open, setOpen] = React.useState<boolean | null>(null)
1998
+ const trigger = React.useRef<HTMLButtonElement>(null)
1999
+ React.useLayoutEffect(() => {
2000
+ if (open) trigger.current?.focus()
2001
+ }, [open])
2002
+ if (open === null)
2003
+ return (
2004
+ <button
2005
+ type="button"
2006
+ aria-label={label}
2007
+ aria-haspopup="menu"
2008
+ aria-expanded={false}
2009
+ disabled={disabled}
2010
+ className={rowMenuClass}
2011
+ onClick={() => setOpen(true)}
2012
+ >
2013
+ <Ellipsis className="h-4 w-4" />
2014
+ </button>
2015
+ )
2016
+ return (
2017
+ <Menu open={open} onOpenChange={setOpen}>
2018
+ <MenuTrigger ref={trigger} aria-label={label} disabled={disabled} className={rowMenuClass}>
2019
+ <Ellipsis className="h-4 w-4" />
2020
+ </MenuTrigger>
2021
+ <MenuContent align="end" className="min-w-[180px]">
2022
+ {items()}
2023
+ </MenuContent>
2024
+ </Menu>
2025
+ )
2026
+ }
2027
+
2028
+ function VirtualRows<T>({
2029
+ rows,
2030
+ scroller,
2031
+ rowHeight,
2032
+ height,
2033
+ span,
2034
+ render,
2035
+ }: {
2036
+ rows: Row<T>[]
2037
+ scroller: HTMLDivElement
2038
+ rowHeight: number
2039
+ /** The scroll area's height, for the first render before it is measured. */
2040
+ height: number
2041
+ span: number
2042
+ render: (row: Row<T>, index: number) => React.ReactNode
2043
+ }) {
2044
+ const virtualizer = useVirtualizer({
2045
+ count: rows.length,
2046
+ getScrollElement: () => scroller,
2047
+ // Sub rows are a fixed 34px; counting them as full rows would leave the spacers wrong.
2048
+ estimateSize: (i) => (rows[i]?.depth ? 34 : rowHeight),
2049
+ overscan: 8,
2050
+ initialRect: { width: 0, height },
2051
+ })
2052
+ // Sizes are cached per row, so a density change has to drop them.
2053
+ React.useEffect(() => {
2054
+ virtualizer.measure()
2055
+ }, [virtualizer, rowHeight])
2056
+ const items = virtualizer.getVirtualItems()
2057
+ const top = items[0]?.start ?? 0
2058
+ const bottom = virtualizer.getTotalSize() - (items[items.length - 1]?.end ?? 0)
2059
+ return (
2060
+ <>
2061
+ {top > 0 && (
2062
+ <tr data-spacer aria-hidden>
2063
+ <td colSpan={span} style={{ height: top, padding: 0, border: 0 }} />
2064
+ </tr>
2065
+ )}
2066
+ {items.map((item) => render(rows[item.index], item.index))}
2067
+ {bottom > 0 && (
2068
+ <tr data-spacer aria-hidden>
2069
+ <td colSpan={span} style={{ height: bottom, padding: 0, border: 0 }} />
2070
+ </tr>
2071
+ )}
2072
+ </>
2073
+ )
2074
+ }
2075
+
2076
+ export type { TanstackTable as DataTableInstance }
2077
+ export { DataTable, DataTableAction, DataTableRowTrigger }