@whity/ui 0.0.0-stage → 0.5.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 (169) hide show
  1. package/README.md +107 -3
  2. package/package.json +192 -6
  3. package/src/access-denied.stories.tsx +179 -0
  4. package/src/access-denied.tsx +305 -0
  5. package/src/action-proposal.tsx +302 -0
  6. package/src/actor-chip.tsx +71 -0
  7. package/src/agent-activity.tsx +163 -0
  8. package/src/agent-collaboration.stories.tsx +156 -0
  9. package/src/agent-run-status.tsx +196 -0
  10. package/src/alert-dialog.stories.tsx +45 -0
  11. package/src/alert-dialog.tsx +147 -0
  12. package/src/alert.stories.tsx +91 -0
  13. package/src/alert.tsx +89 -0
  14. package/src/app-sidebar.stories.tsx +195 -0
  15. package/src/app-sidebar.tsx +500 -0
  16. package/src/approval-queue.tsx +108 -0
  17. package/src/audience-group-picker.stories.tsx +198 -0
  18. package/src/audience-group-picker.tsx +362 -0
  19. package/src/audience-people-picker.stories.tsx +102 -0
  20. package/src/audience-people-picker.tsx +279 -0
  21. package/src/avatar.tsx +83 -0
  22. package/src/badge.stories.tsx +105 -0
  23. package/src/badge.tsx +68 -0
  24. package/src/beta-warning.stories.tsx +79 -0
  25. package/src/beta-warning.tsx +189 -0
  26. package/src/bilingual-input.stories.tsx +82 -0
  27. package/src/bilingual-input.tsx +183 -0
  28. package/src/breadcrumb.stories.tsx +51 -0
  29. package/src/breadcrumb.tsx +90 -0
  30. package/src/button.stories.tsx +87 -0
  31. package/src/button.tsx +118 -0
  32. package/src/card.stories.tsx +423 -0
  33. package/src/card.tsx +180 -0
  34. package/src/chart.stories.tsx +66 -0
  35. package/src/chart.tsx +228 -0
  36. package/src/checkbox.stories.tsx +62 -0
  37. package/src/checkbox.tsx +54 -0
  38. package/src/collapsible.stories.tsx +48 -0
  39. package/src/collapsible.tsx +34 -0
  40. package/src/color-card.stories.tsx +61 -0
  41. package/src/color-card.tsx +270 -0
  42. package/src/color-picker.stories.tsx +65 -0
  43. package/src/color-picker.tsx +425 -0
  44. package/src/command-palette.tsx +306 -0
  45. package/src/copy-block.stories.tsx +38 -0
  46. package/src/copy-block.tsx +85 -0
  47. package/src/data-table.stories.tsx +200 -0
  48. package/src/data-table.tsx +1106 -0
  49. package/src/date-picker.stories.tsx +61 -0
  50. package/src/date-picker.tsx +422 -0
  51. package/src/design-cards.stories.tsx +458 -0
  52. package/src/dialog.stories.tsx +48 -0
  53. package/src/dialog.tsx +166 -0
  54. package/src/documents/barcode-svg.stories.tsx +72 -0
  55. package/src/documents/barcode-svg.tsx +79 -0
  56. package/src/dropdown-menu.stories.tsx +77 -0
  57. package/src/dropdown-menu.tsx +271 -0
  58. package/src/editor/behaviour.ts +279 -0
  59. package/src/editor/block-ids.ts +44 -0
  60. package/src/editor/block-list.tsx +101 -0
  61. package/src/editor/block-toolbar.tsx +477 -0
  62. package/src/editor/bubble.tsx +93 -0
  63. package/src/editor/catalogue.ts +103 -0
  64. package/src/editor/collab-rail.tsx +746 -0
  65. package/src/editor/collab.stories.tsx +207 -0
  66. package/src/editor/collab.ts +87 -0
  67. package/src/editor/contract.ts +408 -0
  68. package/src/editor/convert.ts +362 -0
  69. package/src/editor/doc-editor.stories.tsx +98 -0
  70. package/src/editor/doc-editor.tsx +1287 -0
  71. package/src/editor/editor.css +536 -0
  72. package/src/editor/extensions.ts +86 -0
  73. package/src/editor/field-picker.tsx +107 -0
  74. package/src/editor/fields.ts +100 -0
  75. package/src/editor/gutter.tsx +367 -0
  76. package/src/editor/index.ts +22 -0
  77. package/src/editor/label-sheet.tsx +289 -0
  78. package/src/editor/labels.ts +310 -0
  79. package/src/editor/link-tools.tsx +141 -0
  80. package/src/editor/node-views.tsx +450 -0
  81. package/src/editor/page-view.tsx +353 -0
  82. package/src/editor/publish-check.tsx +182 -0
  83. package/src/editor/rich-blocks.stories.tsx +146 -0
  84. package/src/editor/sample.ts +40 -0
  85. package/src/editor/schema-rich.ts +150 -0
  86. package/src/editor/schema.ts +315 -0
  87. package/src/editor/services.tsx +127 -0
  88. package/src/editor/slash.ts +64 -0
  89. package/src/editor/suggesting.ts +372 -0
  90. package/src/editor/suggestions.ts +763 -0
  91. package/src/editor/table-keys.ts +66 -0
  92. package/src/editor/templates.stories.tsx +324 -0
  93. package/src/editor/toolbar.tsx +358 -0
  94. package/src/empty-state.stories.tsx +51 -0
  95. package/src/empty-state.tsx +100 -0
  96. package/src/empty-state.usage-notes.md +30 -0
  97. package/src/form.stories.tsx +112 -0
  98. package/src/form.tsx +176 -0
  99. package/src/globals.css +20 -0
  100. package/src/icon-button.tsx +85 -0
  101. package/src/icon-map.ts +244 -0
  102. package/src/icon.tsx +41 -0
  103. package/src/index.ts +67 -0
  104. package/src/input.stories.tsx +157 -0
  105. package/src/input.tsx +759 -0
  106. package/src/locked-screen.stories.tsx +29 -0
  107. package/src/locked-screen.tsx +61 -0
  108. package/src/mark.tsx +62 -0
  109. package/src/math-text.stories.tsx +33 -0
  110. package/src/math-text.tsx +43 -0
  111. package/src/menu-bar.stories.tsx +198 -0
  112. package/src/menu-bar.tsx +373 -0
  113. package/src/money/currency.ts +230 -0
  114. package/src/page-header.stories.tsx +95 -0
  115. package/src/page-header.tsx +122 -0
  116. package/src/page-shell.stories.tsx +42 -0
  117. package/src/page-shell.tsx +32 -0
  118. package/src/pagination.stories.tsx +45 -0
  119. package/src/pagination.tsx +98 -0
  120. package/src/plugin-card.stories.tsx +180 -0
  121. package/src/plugin-card.tsx +848 -0
  122. package/src/popover.stories.tsx +48 -0
  123. package/src/popover.tsx +55 -0
  124. package/src/radio-group.stories.tsx +26 -0
  125. package/src/radio-group.tsx +44 -0
  126. package/src/route-flow/editor.tsx +1014 -0
  127. package/src/route-flow/model.ts +716 -0
  128. package/src/scope-grant.tsx +139 -0
  129. package/src/screen-too-small.stories.tsx +61 -0
  130. package/src/screen-too-small.tsx +104 -0
  131. package/src/select.stories.tsx +44 -0
  132. package/src/select.tsx +197 -0
  133. package/src/separator.stories.tsx +34 -0
  134. package/src/separator.tsx +34 -0
  135. package/src/sheet.stories.tsx +49 -0
  136. package/src/sheet.tsx +168 -0
  137. package/src/skeleton.stories.tsx +28 -0
  138. package/src/skeleton.tsx +19 -0
  139. package/src/slider.stories.tsx +78 -0
  140. package/src/slider.tsx +300 -0
  141. package/src/spinner.stories.tsx +33 -0
  142. package/src/spinner.tsx +55 -0
  143. package/src/switch.stories.tsx +42 -0
  144. package/src/switch.tsx +41 -0
  145. package/src/switcher.stories.tsx +111 -0
  146. package/src/switcher.tsx +131 -0
  147. package/src/table.stories.tsx +48 -0
  148. package/src/table.tsx +121 -0
  149. package/src/tabs.stories.tsx +74 -0
  150. package/src/tabs.tsx +90 -0
  151. package/src/tag-input.stories.tsx +67 -0
  152. package/src/tag-input.tsx +117 -0
  153. package/src/tenant-logo.tsx +63 -0
  154. package/src/tenant-switcher.stories.tsx +38 -0
  155. package/src/tenant-switcher.tsx +164 -0
  156. package/src/textarea.stories.tsx +27 -0
  157. package/src/textarea.tsx +18 -0
  158. package/src/theme-mode.ts +52 -0
  159. package/src/time-picker.stories.tsx +62 -0
  160. package/src/time-picker.tsx +615 -0
  161. package/src/toggle-group.tsx +138 -0
  162. package/src/tooltip.stories.tsx +43 -0
  163. package/src/tooltip.tsx +73 -0
  164. package/src/top-nav.stories.tsx +58 -0
  165. package/src/top-nav.tsx +324 -0
  166. package/src/undo-bar.tsx +107 -0
  167. package/src/utils.ts +45 -0
  168. package/src/view-toggle.stories.tsx +84 -0
  169. package/src/view-toggle.tsx +110 -0
@@ -0,0 +1,1106 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import {
5
+ type ColumnDef,
6
+ type ColumnFiltersState,
7
+ type ColumnVisibilityState,
8
+ type PaginationState,
9
+ type SortingState,
10
+ columnFilteringFeature,
11
+ columnResizingFeature,
12
+ columnSizingFeature,
13
+ columnVisibilityFeature,
14
+ createCoreRowModel,
15
+ createFilteredRowModel,
16
+ createPaginatedRowModel,
17
+ createSortedRowModel,
18
+ filterFn_arrIncludes,
19
+ filterFn_equals,
20
+ filterFn_inDateRange,
21
+ filterFn_inNumberRange,
22
+ filterFn_includesString,
23
+ filterFn_weakEquals,
24
+ flexRender,
25
+ globalFilteringFeature,
26
+ rowPaginationFeature,
27
+ rowSortingFeature,
28
+ sortFn_alphanumeric,
29
+ sortFn_basic,
30
+ sortFn_datetime,
31
+ sortFn_text,
32
+ useTable,
33
+ } from "@tanstack/react-table"
34
+ import {
35
+ IconArrowsSort,
36
+ IconChevronDown,
37
+ IconChevronUp,
38
+ IconLayoutColumns,
39
+ IconSearch,
40
+ } from "@tabler/icons-react"
41
+
42
+ import { cn } from "./utils"
43
+ import {
44
+ Table,
45
+ TableBody,
46
+ TableCell,
47
+ TableHead,
48
+ TableHeader,
49
+ TableRow,
50
+ } from "./table"
51
+ import { Button } from "./button"
52
+ import { Input } from "./input"
53
+ import { Pagination } from "./pagination"
54
+ import { Skeleton } from "./skeleton"
55
+ import { EmptyState, ErrorState, type EmptyStateProps } from "./empty-state"
56
+ import {
57
+ DropdownMenu,
58
+ DropdownMenuCheckboxItem,
59
+ DropdownMenuContent,
60
+ DropdownMenuTrigger,
61
+ } from "./dropdown-menu"
62
+
63
+ /**
64
+ * One column definition. A thin, purpose-shaped wrapper over TanStack
65
+ * Table's `ColumnDef` — callers describe WHAT a column is (key/header/cell),
66
+ * this component wires up HOW it sorts/filters/resizes/hides.
67
+ */
68
+ /** What the table calls to render one cell, given the cell's context. */
69
+ type CellRenderer<TRow> = (info: { row: { original: TRow } }) => React.ReactNode
70
+
71
+ export interface DataTableColumn<TData> {
72
+ /** Unique column id. Defaults to `accessorKey` when omitted. */
73
+ id?: string
74
+ /** Dot-free top-level key read from each row when `cell` is omitted. */
75
+ accessorKey?: Extract<keyof TData, string>
76
+ header: React.ReactNode
77
+ /** Custom cell renderer — receives the full row, returns any node. */
78
+ cell?: (row: TData) => React.ReactNode
79
+ enableSorting?: boolean
80
+ enableColumnFilter?: boolean
81
+ /** Whether this column can be hidden via the column-visibility menu. Default true. */
82
+ enableHiding?: boolean
83
+ /** Initial/fixed width in px, also used as the resize starting point. */
84
+ size?: number
85
+ className?: string
86
+ }
87
+
88
+ /** Server-driven pagination: caller owns the page/pageSize/total, we just render controls. */
89
+ export interface DataTableServerPagination {
90
+ pageIndex: number
91
+ pageSize: number
92
+ pageCount: number
93
+ /** Total row count across all pages — drives the "N entries" label. */
94
+ total: number
95
+ onPaginationChange: (pageIndex: number, pageSize: number) => void
96
+ }
97
+
98
+ /**
99
+ * Server-driven sorting: the caller owns the sort column and direction, we
100
+ * render the header affordances and call back. The same shape of bargain as
101
+ * {@link DataTableServerPagination}.
102
+ *
103
+ * WHY THIS HAS TO EXIST. Without it, a table in server-pagination mode still
104
+ * sorts CLIENT-side, and the registered `sortedRowModel` sorts THE ROWS IT WAS
105
+ * HANDED — the twenty five on screen. Clicking "Name" then reorders one page and
106
+ * presents the result as a sorted list; page 2 re-sorts a different twenty
107
+ * five. Nothing errors and nothing looks wrong, which is the whole problem:
108
+ * the reader has no way to tell a sorted list from a sorted page. Screens hit
109
+ * this already and worked around it by making their columns non-sortable and
110
+ * moving sort into their own toolbar (see the document library's
111
+ * `LibraryToolbar`), because the alternative was shipping the untruth.
112
+ */
113
+ export interface DataTableServerSorting {
114
+ /** Column id currently sorted, or null for "no column chosen". */
115
+ sortKey: string | null
116
+ direction: "asc" | "desc"
117
+ /**
118
+ * Called with the NEXT sort when the user clicks a sortable header.
119
+ *
120
+ * `sortKey` is null when a column is cycled past descending back to
121
+ * unsorted (TanStack's default asc → desc → none cycle). `direction` is then
122
+ * not meaningful — send no `dir` upstream in that case, so the endpoint's own
123
+ * default ordering applies rather than one this component invented.
124
+ *
125
+ * Changing the sort invalidates the current page offset. Resetting to page 1
126
+ * is the caller's to do, since the caller owns the pagination state.
127
+ */
128
+ onSortingChange: (sortKey: string | null, direction: "asc" | "desc") => void
129
+ }
130
+
131
+ /**
132
+ * Quiet period before a keystroke becomes a request, in ms.
133
+ *
134
+ * Exported so a caller or a test can reach the default by name instead of
135
+ * re-stating the number, and overridable per table via
136
+ * {@link DataTableServerSearch.debounceMs} — typing "engineering" is twelve
137
+ * requests without it.
138
+ */
139
+ export const DATA_TABLE_SEARCH_DEBOUNCE_MS = 300
140
+
141
+ /**
142
+ * Server-driven global search: the caller owns the term, we own the input.
143
+ *
144
+ * Same hazard as {@link DataTableServerSorting}: a client-side global filter
145
+ * over a server-paginated table filters the current page, so a search that
146
+ * matches nothing on page 1 reports "no results" while the match sits on
147
+ * page 4.
148
+ */
149
+ export interface DataTableServerSearch {
150
+ /**
151
+ * The term the caller has APPLIED. This is not necessarily what is in the
152
+ * box: the input keeps its own draft so typing stays responsive while the
153
+ * request is debounced. An external change to this value (a "clear search"
154
+ * button elsewhere on the page) is adopted into the box; the echo of our own
155
+ * callback is not, because adopting it would overwrite whatever was typed
156
+ * while the request was in flight.
157
+ */
158
+ value: string
159
+ onSearchChange: (value: string) => void
160
+ /**
161
+ * Quiet period after typing stops, in ms. Defaults to
162
+ * {@link DATA_TABLE_SEARCH_DEBOUNCE_MS}. Pass 0 to call back on every
163
+ * keystroke (the caller is debouncing, or a test wants determinism).
164
+ */
165
+ debounceMs?: number
166
+ }
167
+
168
+ export interface DataTableProps<TData> {
169
+ columns: DataTableColumn<TData>[]
170
+ data: TData[]
171
+ getRowId?: (row: TData, index: number) => string
172
+ /** Trailing actions cell render-prop, matching the previous DataTable's convention. */
173
+ rowActions?: (row: TData) => React.ReactNode
174
+ isLoading?: boolean
175
+ /** Replaces the ENTIRE table (chrome included) — e.g. a 403 Access Denied screen. */
176
+ overrideContent?: React.ReactNode
177
+ emptyState?: Omit<EmptyStateProps, "variant">
178
+ errorState?: Omit<EmptyStateProps, "variant">
179
+ /** Free-text search across every column's string value. Off by default. */
180
+ enableGlobalFilter?: boolean
181
+ globalFilterPlaceholder?: string
182
+ /** Header text for the row-actions column. Defaults to "Actions". */
183
+ rowActionsLabel?: string
184
+ /**
185
+ * Accessible name for the table element, applied in EVERY state that renders
186
+ * a `table` — the loading skeleton and the loaded rows alike.
187
+ *
188
+ * A page with two DataTables gives assistive technology — and any test
189
+ * selecting by role — two identical, unnamed `table` landmarks with no way to
190
+ * tell them apart. Naming them is the a11y answer and it is what makes
191
+ * `getByRole('table', { name })` a stable selector instead of a positional
192
+ * guess that breaks the next time a panel is added.
193
+ *
194
+ * It was originally wired into the skeleton branch ONLY (#967). Both halves of
195
+ * that sentence then failed: a screen reader met the LOADED users table — the
196
+ * state anybody actually reads — as an unnamed twin of the invitations table,
197
+ * and `getByRole('table', { name })` silently became an assertion about the
198
+ * skeleton, satisfied only while the request was still in flight. It passed
199
+ * when the backend was slow and failed when it was fast, which is why it read
200
+ * as flakiness on unrelated PRs and cost three CI cycles before it was
201
+ * diagnosed. Any new branch here that renders a `table` must name it too.
202
+ */
203
+ ariaLabel?: string
204
+ /**
205
+ * Title shown when there are no rows and the caller passed no `emptyState`.
206
+ * `emptyState` still wins — this only replaces the built-in English default,
207
+ * so a caller translating just this string does not have to reconstruct the
208
+ * whole empty state.
209
+ */
210
+ emptyStateTitle?: string
211
+ /** Placeholder for the per-column filter inputs. Defaults to "Filter…". */
212
+ columnFilterPlaceholder?: string
213
+ /** Text of the column-visibility menu trigger. Defaults to "Columns". */
214
+ columnsMenuLabel?: string
215
+ /**
216
+ * Copy for the pagination controls this table renders for itself.
217
+ *
218
+ * Forwarded to <Pagination>. Without this the table's own footer — 'N
219
+ * entries', 'page 2 of 7', the prev/next buttons — would be the one part
220
+ * of a translated table still stuck in English, with no way for a caller
221
+ * to reach it.
222
+ */
223
+ paginationLabels?: Pick<
224
+ React.ComponentProps<typeof Pagination>,
225
+ "entriesLabel" | "pageLabel" | "navLabel" | "previousLabel" | "nextLabel"
226
+ >
227
+ /** Show/hide-columns menu. Off by default. */
228
+ enableColumnVisibility?: boolean
229
+ /** Drag-resize column borders. Off by default. */
230
+ enableColumnResizing?: boolean
231
+ /**
232
+ * Omit for no pagination. Pass `{ pageSize }` (a plain number of rows per
233
+ * page) for automatic CLIENT-side pagination. Pass a
234
+ * {@link DataTableServerPagination} object when the caller's API already
235
+ * paginates server-side (manual mode — this component then just renders
236
+ * controls and calls back, never re-slices `data` itself).
237
+ */
238
+ pagination?: DataTableServerPagination | { pageSize: number }
239
+ /**
240
+ * Omit to let this component sort the rows it holds (the default, and what
241
+ * every existing caller gets). Pass a {@link DataTableServerSorting} object
242
+ * when the SERVER sorts: the headers then reflect the caller's state and
243
+ * report clicks, and the rows are rendered in the order they arrived.
244
+ */
245
+ sorting?: DataTableServerSorting
246
+ /**
247
+ * Omit to let `enableGlobalFilter` filter the rows it holds. Pass a
248
+ * {@link DataTableServerSearch} object when the SERVER searches: the same
249
+ * search box renders (passing this implies it, `enableGlobalFilter` or not)
250
+ * and reports what is typed, and no row is filtered out locally.
251
+ *
252
+ * Per-column filters are deliberately LEFT ALONE by this — see the note on
253
+ * `manualFiltering` at the `useTable` call.
254
+ */
255
+ search?: DataTableServerSearch
256
+ className?: string
257
+ }
258
+
259
+ function isServerPagination(
260
+ p: DataTableServerPagination | { pageSize: number }
261
+ ): p is DataTableServerPagination {
262
+ return "onPaginationChange" in p
263
+ }
264
+
265
+ /**
266
+ * The TanStack v9 feature set this table runs on.
267
+ *
268
+ * v9 REPLACED THE v8 `getXRowModel()` OPTIONS WITH EXPLICIT REGISTRATION. In v8
269
+ * a table got sorting because you passed `getSortedRowModel()`; in v9 it gets
270
+ * sorting because `rowSortingFeature` is registered here and the matching
271
+ * `sortedRowModel` factory sits beside it. Nothing is implicit, and a feature
272
+ * left out of this object does not merely go unused — its options and its slice
273
+ * of table state stop existing, and TypeScript says so at the call site.
274
+ *
275
+ * DECLARED AT MODULE SCOPE because the identity is read on every render and a
276
+ * fresh object each time would rebuild the table's feature registry for no
277
+ * reason. It carries no per-table state, so one shared value is correct.
278
+ *
279
+ * `columnMeta` is a TYPE-ONLY slot: the value is stripped at runtime and only
280
+ * its type is used, which is how `meta: { className }` on a column definition
281
+ * type-checks again. In v8 `meta` was loosely typed and ours assigned by luck;
282
+ * v9 threads `ExtractColumnMeta<TFeatures>` through, so the shape has to be
283
+ * declared once — here — rather than asserted at each of the 26 call sites.
284
+ */
285
+ /**
286
+ * The feature set's own type, and the row type v9 will accept.
287
+ *
288
+ * v9 constrains table data to `RowData` (`Record<string, any> | Array<any>`).
289
+ * {@link DataTableProps} deliberately does NOT constrain `TData` — 26 call sites
290
+ * pass plain interfaces, and adding the constraint to the public prop would push
291
+ * this migration out into every one of them, which is exactly what this rewrite
292
+ * exists to avoid. So the bridge is here, once, and the props contract is
293
+ * unchanged.
294
+ */
295
+ type TableFeatureSet = typeof tableFeatures
296
+ type TableRow<TData> = TData & Record<string, unknown>
297
+
298
+ const tableFeatures = {
299
+ columnFilteringFeature,
300
+ columnResizingFeature,
301
+ columnSizingFeature,
302
+ columnVisibilityFeature,
303
+ globalFilteringFeature,
304
+ rowPaginationFeature,
305
+ rowSortingFeature,
306
+ coreRowModel: createCoreRowModel(),
307
+ filteredRowModel: createFilteredRowModel(),
308
+ sortedRowModel: createSortedRowModel(),
309
+ // Client-side paging is still a supported v9 row model — `createPaginatedRowModel`
310
+ // is the rename of v8's `getPaginationRowModel`, not a removal. Registering it
311
+ // unconditionally is safe: with `manualPagination` on, the server owns the
312
+ // slice and this model is never consulted.
313
+ paginatedRowModel: createPaginatedRowModel(),
314
+ /**
315
+ * THE FILTER AND SORT FUNCTIONS THE AUTO-RESOLVER CAN ASK FOR.
316
+ *
317
+ * v9 resolves an unconfigured column to a filter/sort function BY NAME and
318
+ * looks that name up here. The two halves fail differently, and both quietly:
319
+ *
320
+ * - an unregistered FILTER function returns `undefined`, and the column
321
+ * filter becomes a no-op. Typing in the filter box narrows nothing.
322
+ * - an unregistered SORT function falls back to `sortFn_basic`, so the
323
+ * column still sorts — just wrongly. `basic` compares with `<`, so
324
+ * "item 10" lands before "item 2" and case is handled differently from
325
+ * the `text`/`alphanumeric` functions v8 chose automatically.
326
+ *
327
+ * Neither raises anything outside a development console warning, which is why
328
+ * these are listed explicitly rather than left to a default that no longer
329
+ * exists. The six filter functions are exactly the ones the auto-resolver can
330
+ * pick (string / number / boolean / array / date / fallback); registering the
331
+ * whole exported registry instead would put every built-in in the bundle.
332
+ */
333
+ filterFns: {
334
+ arrIncludes: filterFn_arrIncludes,
335
+ equals: filterFn_equals,
336
+ inDateRange: filterFn_inDateRange,
337
+ inNumberRange: filterFn_inNumberRange,
338
+ includesString: filterFn_includesString,
339
+ weakEquals: filterFn_weakEquals,
340
+ },
341
+ sortFns: {
342
+ alphanumeric: sortFn_alphanumeric,
343
+ basic: sortFn_basic,
344
+ datetime: sortFn_datetime,
345
+ text: sortFn_text,
346
+ },
347
+ columnMeta: {} as { className?: string },
348
+ }
349
+
350
+ export function DataTable<TData>({
351
+ columns,
352
+ data,
353
+ getRowId,
354
+ rowActions,
355
+ isLoading = false,
356
+ overrideContent,
357
+ emptyState,
358
+ errorState,
359
+ enableGlobalFilter = false,
360
+ globalFilterPlaceholder = "Search…",
361
+ rowActionsLabel = "Actions",
362
+ ariaLabel,
363
+ emptyStateTitle = "No data available",
364
+ columnFilterPlaceholder = "Filter…",
365
+ columnsMenuLabel = "Columns",
366
+ paginationLabels,
367
+ enableColumnVisibility = false,
368
+ enableColumnResizing = false,
369
+ pagination,
370
+ sorting: serverSorting,
371
+ search: serverSearch,
372
+ className,
373
+ }: DataTableProps<TData>) {
374
+ const [clientSorting, setClientSorting] = React.useState<SortingState>([])
375
+ const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
376
+ const [globalFilter, setGlobalFilter] = React.useState("")
377
+ const [columnVisibility, setColumnVisibility] = React.useState<ColumnVisibilityState>({})
378
+
379
+ const serverMode = pagination != null && isServerPagination(pagination)
380
+
381
+ /**
382
+ * The caller's sort, in the shape TanStack keeps it in. One column at a
383
+ * time: the server contract this pairs with takes a single `sort` key, so
384
+ * offering multi-sort in the UI would promise an ordering the request cannot
385
+ * express.
386
+ */
387
+ const sortingState: SortingState = serverSorting
388
+ ? serverSorting.sortKey
389
+ ? [{ id: serverSorting.sortKey, desc: serverSorting.direction === "desc" }]
390
+ : []
391
+ : clientSorting
392
+ const [clientPagination, setClientPagination] = React.useState<PaginationState>({
393
+ pageIndex: 0,
394
+ pageSize: pagination && !serverMode ? pagination.pageSize : 10,
395
+ })
396
+
397
+ // What is TYPED, which is not what has been SENT. The box must stay
398
+ // responsive while the request is debounced, so it renders this draft rather
399
+ // than `serverSearch.value`; a controlled input bound straight to a value
400
+ // that only updates after the round trip drops characters typed in between.
401
+ const appliedSearch = serverSearch?.value ?? ""
402
+ const [searchDraft, setSearchDraft] = React.useState(appliedSearch)
403
+ const searchTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null)
404
+ // The last term we handed to `onSearchChange`. When the caller sets `value`
405
+ // to exactly this, it is the ECHO of our own callback, not somebody else
406
+ // changing the search, and adopting it would clobber the characters typed
407
+ // between the timer firing and the caller re-rendering.
408
+ const lastEmittedSearch = React.useRef<string | null>(null)
409
+
410
+ const clearSearchTimer = () => {
411
+ if (searchTimer.current !== null) {
412
+ clearTimeout(searchTimer.current)
413
+ searchTimer.current = null
414
+ }
415
+ }
416
+
417
+ React.useEffect(() => {
418
+ if (lastEmittedSearch.current === appliedSearch) return
419
+ lastEmittedSearch.current = null
420
+ // An external change wins over anything still pending — a "clear search"
421
+ // button elsewhere on the page must not be undone a moment later by a
422
+ // timer carrying the term it just cleared.
423
+ clearSearchTimer()
424
+ setSearchDraft(appliedSearch)
425
+ }, [appliedSearch])
426
+
427
+ // A pending timer outliving the component would call back into an unmounted
428
+ // caller. Cancelling on unmount is the whole of it.
429
+ React.useEffect(() => clearSearchTimer, [])
430
+
431
+ const handleSearchInput = (next: string) => {
432
+ if (!serverSearch) {
433
+ setGlobalFilter(next)
434
+ return
435
+ }
436
+ setSearchDraft(next)
437
+ clearSearchTimer()
438
+ const delay = serverSearch.debounceMs ?? DATA_TABLE_SEARCH_DEBOUNCE_MS
439
+ if (delay <= 0) {
440
+ lastEmittedSearch.current = next
441
+ serverSearch.onSearchChange(next)
442
+ return
443
+ }
444
+ searchTimer.current = setTimeout(() => {
445
+ searchTimer.current = null
446
+ lastEmittedSearch.current = next
447
+ serverSearch.onSearchChange(next)
448
+ }, delay)
449
+ }
450
+
451
+ /** Passing `search` implies the search box, whether or not the flag is set. */
452
+ const showSearchInput = enableGlobalFilter || serverSearch != null
453
+
454
+ // ONE RENDERER PER COLUMN, FOR THE LIFE OF THE TABLE (WHIT-800).
455
+ //
456
+ // The table renders a cell's function as a React component, so a new function
457
+ // is a new component type. Callers build `columns` and `rowActions` inline,
458
+ // which made them new on every render, so React unmounted and remounted every
459
+ // cell each time the page re-rendered: an open row menu closed and its items
460
+ // detached mid-click. So the function handed to the table never changes, and
461
+ // reads the caller's current closures here when it runs. Assigned during render
462
+ // rather than in an effect because the cells render in this same pass.
463
+ const latestCells = React.useRef({ columns, rowActions })
464
+ latestCells.current = { columns, rowActions }
465
+ const cellRenderers = React.useRef(new Map<string, CellRenderer<TableRow<TData>>>())
466
+ const stableCell = (id: string, render: CellRenderer<TableRow<TData>>) => {
467
+ const existing = cellRenderers.current.get(id)
468
+ if (existing) return existing
469
+ cellRenderers.current.set(id, render)
470
+ return render
471
+ }
472
+
473
+ const columnDefs = React.useMemo<ColumnDef<TableFeatureSet, TableRow<TData>, unknown>[]>(() => {
474
+ const defs: ColumnDef<TableFeatureSet, TableRow<TData>, unknown>[] = columns.map((column) => {
475
+ const id = column.id ?? column.accessorKey
476
+ if (!id) {
477
+ throw new Error("DataTable: every column needs an `id` or `accessorKey`")
478
+ }
479
+ return {
480
+ id,
481
+ accessorKey: column.accessorKey,
482
+ header: column.header as string,
483
+ cell: stableCell(id, (info) => {
484
+ const current = latestCells.current.columns.find((c) => (c.id ?? c.accessorKey) === id)
485
+ if (current?.cell) return current.cell(info.row.original)
486
+ const value = current?.accessorKey
487
+ ? (info.row.original as Record<string, unknown>)[current.accessorKey]
488
+ : undefined
489
+ return value == null || value === "" ? (
490
+ <span className="text-muted-foreground">—</span>
491
+ ) : (
492
+ String(value)
493
+ )
494
+ }),
495
+ enableSorting: column.enableSorting ?? false,
496
+ enableColumnFilter: column.enableColumnFilter ?? false,
497
+ enableHiding: column.enableHiding ?? true,
498
+ size: column.size,
499
+ meta: { className: column.className },
500
+ }
501
+ })
502
+ if (rowActions) {
503
+ defs.push({
504
+ id: "__row-actions",
505
+ header: rowActionsLabel,
506
+ cell: stableCell("__row-actions", (info) => latestCells.current.rowActions?.(info.row.original) ?? null),
507
+ enableSorting: false,
508
+ enableColumnFilter: false,
509
+ enableHiding: false,
510
+ })
511
+ }
512
+ return defs
513
+ // `stableCell` only touches a ref, so it needs no place here.
514
+ }, [columns, rowActions, rowActionsLabel])
515
+
516
+ const table = useTable<TableFeatureSet, TableRow<TData>>({
517
+ features: tableFeatures,
518
+ data: data as TableRow<TData>[],
519
+ columns: columnDefs,
520
+ getRowId: getRowId
521
+ ? (row, index) => getRowId(row, index)
522
+ : undefined,
523
+ state: {
524
+ sorting: sortingState,
525
+ columnFilters,
526
+ // In server-search mode the term never enters table state, so there is
527
+ // nothing here for TanStack to filter by. See `manualFiltering` below.
528
+ globalFilter: enableGlobalFilter && !serverSearch ? globalFilter : undefined,
529
+ columnVisibility,
530
+ // NO PAGINATION MEANS ONE PAGE OF EVERYTHING, SAID EXPLICITLY.
531
+ //
532
+ // In v8 a table without pagination simply had no paginated row model, so
533
+ // `getRowModel()` returned every row. In v9 the row model is registered
534
+ // on the feature set for the whole component, so it applies here too and
535
+ // an omitted `pagination` state falls back to the library default of ten
536
+ // rows — silently hiding row 11 onward on every unpaginated table.
537
+ //
538
+ // `pageSize: Infinity` with `pageIndex: 0` is the documented escape:
539
+ // `createPaginatedRowModel` skips slicing entirely for exactly that pair.
540
+ // (`manualPagination` does NOT do this — that model never consults it.)
541
+ pagination: serverMode
542
+ ? { pageIndex: pagination.pageIndex, pageSize: pagination.pageSize }
543
+ : pagination
544
+ ? clientPagination
545
+ : { pageIndex: 0, pageSize: Number.POSITIVE_INFINITY },
546
+ },
547
+ onSortingChange: serverSorting
548
+ ? (updater) => {
549
+ const next = typeof updater === "function" ? updater(sortingState) : updater
550
+ // Single-column, so the head of the list IS the sort. An empty list
551
+ // is the third click of asc → desc → none: no column chosen, and the
552
+ // direction that goes with it is not meaningful — see the prop docs.
553
+ const [next0] = next
554
+ serverSorting.onSortingChange(
555
+ next0 ? next0.id : null,
556
+ next0?.desc ? "desc" : "asc"
557
+ )
558
+ }
559
+ : setClientSorting,
560
+ onColumnFiltersChange: setColumnFilters,
561
+ onGlobalFilterChange: setGlobalFilter,
562
+ onColumnVisibilityChange: setColumnVisibility,
563
+ onPaginationChange: serverMode
564
+ ? (updater) => {
565
+ const next =
566
+ typeof updater === "function"
567
+ ? updater({ pageIndex: pagination.pageIndex, pageSize: pagination.pageSize })
568
+ : updater
569
+ pagination.onPaginationChange(next.pageIndex, next.pageSize)
570
+ }
571
+ : setClientPagination,
572
+ manualPagination: serverMode,
573
+ /**
574
+ * THIS is what stops the reordering, not the absence of a row model.
575
+ *
576
+ * `sortedRowModel` stays registered on the module-scope `tableFeatures` —
577
+ * it is shared by every table this component renders, so it cannot be
578
+ * withheld per-instance the way v8's per-call `getSortedRowModel()` could.
579
+ * The flag is the per-instance control: v9 gates the pipeline in
580
+ * `table_getSortedRowModel` (`core/row-models/coreRowModelsFeature.utils.js`,
581
+ * table-core 9.2.4), which returns the PRE-sorted model when
582
+ * `manualSorting` is set and never consults the comparator.
583
+ *
584
+ * Drop this flag and the headers keep working and the callback keeps
585
+ * firing, and the rows ALSO get re-sorted locally on top of the server's
586
+ * order — a sort that is nearly right, which is the hardest kind to notice.
587
+ */
588
+ manualSorting: serverSorting != null,
589
+ /*
590
+ * NO `manualFiltering`, deliberately, and it is not an oversight.
591
+ *
592
+ * Re-checked against v9, because v9 splits `columnFilteringFeature` and
593
+ * `globalFilteringFeature` into separate features and the split looks like
594
+ * it should have brought a global-only flag with it. It did not.
595
+ * `manualFiltering` is still the only one, it is still declared on
596
+ * `columnFilteringFeature`, and `globalFilteringFeature` has no manual
597
+ * option at all. The gate is one stage of the shared row-model pipeline —
598
+ * `table_getFilteredRowModel`, documented as "the row model after column
599
+ * AND global filtering" — so setting the flag would take the per-column
600
+ * filter inputs down with the global one, exactly as in v8. Those are used
601
+ * by around eighteen columns across the admin screens, the users table
602
+ * included — the first screen expected to adopt server search — and they
603
+ * would keep rendering and keep accepting text while filtering nothing.
604
+ *
605
+ * Keeping the search term out of `state.globalFilter` (above) achieves what
606
+ * the flag would have achieved for search, and nothing more:
607
+ * `createFilteredRowModel` treats `undefined` as "no global filter" and
608
+ * applies none, while column filters go on working client-side.
609
+ * Server-side column filters are a contract that does not exist yet; when
610
+ * it does, this is where it lands.
611
+ */
612
+ pageCount: serverMode ? pagination.pageCount : undefined,
613
+ columnResizeMode: "onChange",
614
+ enableColumnResizing,
615
+ })
616
+
617
+ if (overrideContent) {
618
+ return <>{overrideContent}</>
619
+ }
620
+
621
+ const filterableColumns = table
622
+ .getAllLeafColumns()
623
+ .filter((column) => column.getCanFilter())
624
+ const hideableColumns = table
625
+ .getAllLeafColumns()
626
+ .filter((column) => column.getCanHide())
627
+
628
+ if (isLoading) {
629
+ const visibleCount = table.getVisibleLeafColumns().length
630
+ return (
631
+ <div className={cn("rounded-lg border border-border", className)}>
632
+ {/* `aria-busy` marks this as the PLACEHOLDER, not the data.
633
+ It carries the same `aria-label` as the real table — deliberately,
634
+ so assistive technology names the region consistently while it
635
+ loads — and the consequence is that `getByRole('table', {name})`
636
+ matches this skeleton exactly as it matches a populated table. A
637
+ test written against that selector can be satisfied by five rows of
638
+ grey bars: it passes when the data arrived, when the folder is
639
+ empty and the assertion merely won the race, and when the request
640
+ failed and the retry is in flight. One shipped that way (#1006's
641
+ "the pane is never simply blank" asserted `toBeVisible()` and
642
+ `not.toBeEmpty()` and both were true of THIS markup), passed
643
+ locally, and failed in CI on the one stack where the fetch resolved
644
+ first — which is the only run that was telling the truth.
645
+ `aria-busy` is the standard signal for it and is additive, so no
646
+ existing selector changes. Prefer waiting on a terminal state
647
+ (a row, or the empty state's own text) over waiting on the table. */}
648
+ <Table aria-label={ariaLabel} aria-busy="true">
649
+ <TableHeader>
650
+ <TableRow>
651
+ {columns.map((column, index) => (
652
+ <TableHead key={column.id ?? column.accessorKey ?? index}>
653
+ {column.header}
654
+ </TableHead>
655
+ ))}
656
+ {rowActions && <TableHead>{rowActionsLabel}</TableHead>}
657
+ </TableRow>
658
+ </TableHeader>
659
+ <TableBody>
660
+ {Array.from({ length: 5 }).map((_, rowIndex) => (
661
+ <TableRow key={rowIndex}>
662
+ {Array.from({ length: visibleCount }).map((__, colIndex) => (
663
+ <TableCell key={colIndex}>
664
+ <Skeleton className="h-4 w-3/4" />
665
+ </TableCell>
666
+ ))}
667
+ </TableRow>
668
+ ))}
669
+ </TableBody>
670
+ </Table>
671
+ <span className="sr-only" role="status" aria-live="polite">
672
+ Loading…
673
+ </span>
674
+ </div>
675
+ )
676
+ }
677
+
678
+ const rows = table.getRowModel().rows
679
+
680
+ return (
681
+ <div className={cn("flex flex-col gap-3", className)}>
682
+ {(showSearchInput || enableColumnVisibility) && (
683
+ <div className="flex items-center justify-between gap-2">
684
+ {showSearchInput ? (
685
+ <div className="relative w-full max-w-xs">
686
+ <IconSearch className="pointer-events-none absolute start-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
687
+ <Input
688
+ value={serverSearch ? searchDraft : globalFilter}
689
+ onChange={(event) => handleSearchInput(event.target.value)}
690
+ placeholder={globalFilterPlaceholder}
691
+ className="ps-7"
692
+ />
693
+ </div>
694
+ ) : (
695
+ <div />
696
+ )}
697
+ {enableColumnVisibility && hideableColumns.length > 0 && (
698
+ <DropdownMenu>
699
+ <DropdownMenuTrigger asChild>
700
+ <Button type="button" variant="outline" size="xs">
701
+ <IconLayoutColumns className="size-3.5" />
702
+ {columnsMenuLabel}
703
+ </Button>
704
+ </DropdownMenuTrigger>
705
+ <DropdownMenuContent align="end">
706
+ {hideableColumns.map((column) => (
707
+ <DropdownMenuCheckboxItem
708
+ key={column.id}
709
+ checked={column.getIsVisible()}
710
+ onCheckedChange={(value) => column.toggleVisibility(!!value)}
711
+ onSelect={(event) => event.preventDefault()}
712
+ >
713
+ {typeof column.columnDef.header === "string"
714
+ ? column.columnDef.header
715
+ : column.id}
716
+ </DropdownMenuCheckboxItem>
717
+ ))}
718
+ </DropdownMenuContent>
719
+ </DropdownMenu>
720
+ )}
721
+ </div>
722
+ )}
723
+
724
+ {errorState ? (
725
+ <ErrorState {...errorState} />
726
+ ) : rows.length === 0 ? (
727
+ <EmptyState title={emptyStateTitle} {...emptyState} />
728
+ ) : (
729
+ <div className="overflow-hidden rounded-lg border border-border">
730
+ <Table
731
+ aria-label={ariaLabel}
732
+ style={enableColumnResizing ? { width: table.getCenterTotalSize() } : undefined}
733
+ >
734
+ <TableHeader>
735
+ {table.getHeaderGroups().map((headerGroup) => (
736
+ <TableRow key={headerGroup.id}>
737
+ {headerGroup.headers.map((header) => {
738
+ const canSort = header.column.getCanSort()
739
+ const sorted = header.column.getIsSorted()
740
+ const content = (
741
+ <>
742
+ {flexRender(header.column.columnDef.header, header.getContext())}
743
+ {canSort &&
744
+ (sorted === "asc" ? (
745
+ <IconChevronUp className="size-3.5" />
746
+ ) : sorted === "desc" ? (
747
+ <IconChevronDown className="size-3.5" />
748
+ ) : (
749
+ <IconArrowsSort className="size-3.5 opacity-40" />
750
+ ))}
751
+ </>
752
+ )
753
+ return (
754
+ <TableHead
755
+ key={header.id}
756
+ style={
757
+ enableColumnResizing ? { width: header.getSize(), position: "relative" } : undefined
758
+ }
759
+ className={cn(
760
+ canSort && "cursor-pointer select-none hover:bg-muted/60"
761
+ )}
762
+ /**
763
+ * WHICH COLUMN IS SORTED, SAID OUT LOUD.
764
+ *
765
+ * Read straight off `getIsSorted()`, which is fed by
766
+ * `state.sorting` — and `sortingState` above resolves that
767
+ * from `serverSorting` when the caller owns the sort and from
768
+ * `clientSorting` when this component does. One expression
769
+ * therefore covers BOTH modes; deriving it from
770
+ * `clientSorting` instead would have left every
771
+ * server-sorted table (the ones where the header is the only
772
+ * route to rows on another page) announcing "not sorted"
773
+ * while visibly sorted.
774
+ *
775
+ * Only on columns that can sort. `aria-sort="none"` on a
776
+ * fixed column would advertise a control that is not there.
777
+ */
778
+ aria-sort={
779
+ canSort
780
+ ? sorted === "asc"
781
+ ? "ascending"
782
+ : sorted === "desc"
783
+ ? "descending"
784
+ : "none"
785
+ : undefined
786
+ }
787
+ /**
788
+ * THE HANDLER STAYS ON THE CELL — the button below has none,
789
+ * deliberately.
790
+ *
791
+ * A `<button>` activated by Enter or Space dispatches a real
792
+ * `click` that bubbles, so keyboard activation lands on this
793
+ * exact handler and does exactly what a mouse click does,
794
+ * third-click-back-to-unsorted included. Duplicating the
795
+ * handler onto the button instead would fire it twice for
796
+ * one mouse click (button, then bubbled to the cell).
797
+ *
798
+ * Keeping it here also keeps the WHOLE CELL a click target
799
+ * rather than shrinking it to the label, which is both the
800
+ * behaviour 26 callers already have and what every existing
801
+ * test that clicks `getByRole('columnheader')` exercises.
802
+ */
803
+ onClick={header.column.getToggleSortingHandler()}
804
+ >
805
+ {canSort ? (
806
+ /**
807
+ * The focusable, activatable control the cell itself could
808
+ * never be (#1129). A `th` takes no keyboard focus and has
809
+ * no activation behaviour, so before this a keyboard user
810
+ * could not sort ANY admin table at all.
811
+ *
812
+ * Inside the cell rather than instead of it, matching the
813
+ * W3C APG sortable-table pattern: the `th` keeps its
814
+ * `columnheader` role and carries `aria-sort`, the button
815
+ * carries focus and activation.
816
+ *
817
+ * NO `aria-label`. It is tempting to name this "Sort by
818
+ * Email", but a `columnheader`'s name is computed from its
819
+ * contents and an `aria-label` on a descendant REPLACES
820
+ * that descendant's contribution — so the cell would stop
821
+ * being named "Email" and every
822
+ * `getByRole('columnheader', { name })` selector across the
823
+ * suites would be asserting against a name no user asked
824
+ * for. `aria-sort` already carries the state; the role
825
+ * carries the affordance.
826
+ *
827
+ * `cursor-pointer` is not redundant: Tailwind v4's preflight
828
+ * resets buttons to `cursor: default`, which would undo the
829
+ * pointer cursor the cell sets.
830
+ *
831
+ * RTL: `flex` + `gap` + `text-start` are direction-relative,
832
+ * so the label leads and the chevron trails on whichever
833
+ * side "trailing" means, and the symmetric `-mx-1 px-1`
834
+ * has no side to get wrong. The three icons are vertical
835
+ * arrows — nothing to mirror.
836
+ */
837
+ <button
838
+ type="button"
839
+ className="-mx-1 flex cursor-pointer items-center gap-1 rounded-sm px-1 text-start font-medium tracking-wider text-inherit uppercase outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
840
+ >
841
+ {content}
842
+ </button>
843
+ ) : (
844
+ <div className="flex items-center gap-1">{content}</div>
845
+ )}
846
+ {enableColumnResizing && header.column.getCanResize() && (
847
+ <div
848
+ onMouseDown={header.getResizeHandler()}
849
+ onTouchStart={header.getResizeHandler()}
850
+ className="absolute end-0 top-0 h-full w-1 cursor-col-resize touch-none select-none bg-border/0 hover:bg-ring/50"
851
+ />
852
+ )}
853
+ </TableHead>
854
+ )
855
+ })}
856
+ </TableRow>
857
+ ))}
858
+ {filterableColumns.length > 0 && (
859
+ <TableRow>
860
+ {table.getHeaderGroups()[0]?.headers.map((header) => {
861
+ const canFilter = header.column.getCanFilter()
862
+ const label =
863
+ typeof header.column.columnDef.header === "string"
864
+ ? header.column.columnDef.header
865
+ : header.column.id
866
+ return (
867
+ <TableHead key={`filter-${header.id}`} className="py-1.5">
868
+ {canFilter ? (
869
+ <Input
870
+ value={(header.column.getFilterValue() as string) ?? ""}
871
+ onChange={(event) =>
872
+ header.column.setFilterValue(event.target.value)
873
+ }
874
+ placeholder={columnFilterPlaceholder}
875
+ aria-label={`Filter ${label}`}
876
+ className="h-6 text-xs font-normal normal-case tracking-normal"
877
+ />
878
+ ) : null}
879
+ </TableHead>
880
+ )
881
+ })}
882
+ </TableRow>
883
+ )}
884
+ </TableHeader>
885
+ <TableBody>
886
+ {rows.map((row) => (
887
+ <TableRow key={row.id}>
888
+ {row.getVisibleCells().map((cell) => (
889
+ <TableCell
890
+ key={cell.id}
891
+ className={(cell.column.columnDef.meta as { className?: string } | undefined)?.className}
892
+ style={enableColumnResizing ? { width: cell.column.getSize() } : undefined}
893
+ >
894
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
895
+ </TableCell>
896
+ ))}
897
+ </TableRow>
898
+ ))}
899
+ </TableBody>
900
+ </Table>
901
+ </div>
902
+ )}
903
+
904
+ {pagination && rows.length > 0 && (
905
+ <Pagination
906
+ page={table.state.pagination.pageIndex + 1}
907
+ perPage={table.state.pagination.pageSize}
908
+ total={serverMode ? pagination.total : table.getFilteredRowModel().rows.length}
909
+ onPageChange={(nextPage) => table.setPageIndex(nextPage - 1)}
910
+ {...paginationLabels}
911
+ />
912
+ )}
913
+ </div>
914
+ )
915
+ }
916
+
917
+ /* ──────────────────────────────────────────────────────────────────────────
918
+ * The CALLER's half of server mode
919
+ * ────────────────────────────────────────────────────────────────────────── */
920
+
921
+ /**
922
+ * One list request's page, sort and search — the client mirror of the server's
923
+ * `ListQuery` (`src/Http/ListQuery.php`).
924
+ *
925
+ * `sort`/`dir` and `q` are OPTIONAL, and their absence is meaningful rather than
926
+ * a default nobody filled in. Sending `sort=` with nothing in it, or `dir=asc`
927
+ * with no column, would have the endpoint order by something the UI invented;
928
+ * leaving them out is how a caller says "use your own default order", which is
929
+ * the only honest thing to say when no column is chosen.
930
+ */
931
+ export interface DataTableQueryRequest {
932
+ /** 1-based, the way the endpoints count pages. */
933
+ page: number
934
+ perPage: number
935
+ /** The ENDPOINT's sort key (not the column id) — absent when none is chosen. */
936
+ sort?: string
937
+ /** Absent exactly when `sort` is. */
938
+ dir?: "asc" | "desc"
939
+ /** Absent when there is nothing to search for. */
940
+ q?: string
941
+ }
942
+
943
+ /**
944
+ * A {@link DataTableQueryRequest} as a query string, no leading `?`.
945
+ *
946
+ * Written here rather than at each screen so the "absent means absent" rule
947
+ * above is applied once: a helper that always set `sort` and `dir` would undo
948
+ * the whole point of making them optional.
949
+ */
950
+ export function dataTableQueryString(request: DataTableQueryRequest): string {
951
+ const params = new URLSearchParams()
952
+ params.set("page", String(request.page))
953
+ params.set("per_page", String(request.perPage))
954
+ if (request.sort !== undefined && request.sort !== "") {
955
+ params.set("sort", request.sort)
956
+ params.set("dir", request.dir ?? "asc")
957
+ }
958
+ if (request.q !== undefined && request.q !== "") {
959
+ params.set("q", request.q)
960
+ }
961
+ return params.toString()
962
+ }
963
+
964
+ /** Rows per page for a server-driven admin list, matching the API's own default. */
965
+ export const DEFAULT_DATA_TABLE_PER_PAGE = 25
966
+
967
+ export interface UseDataTableQueryOptions {
968
+ /** Rows per request. Defaults to {@link DEFAULT_DATA_TABLE_PER_PAGE}. */
969
+ perPage?: number
970
+ /**
971
+ * The COLUMN ID the table starts sorted by. Omit — the default — to start
972
+ * with no column chosen, so the first request carries no `sort` and the
973
+ * reader gets the endpoint's own default ordering. Naming one here just to
974
+ * restate that default would be a claim the UI cannot keep if the endpoint's
975
+ * default ever moves.
976
+ */
977
+ initialSortKey?: string | null
978
+ initialDirection?: "asc" | "desc"
979
+ /**
980
+ * Column id → the endpoint's `sort` key, for the columns whose names differ.
981
+ * Identity for anything absent, which is why this holds the RENAMES only.
982
+ *
983
+ * The two vocabularies are genuinely separate. A column id is whatever the
984
+ * screen called it (`accountStatus`, `createdAt`, `ruleLabel`); the sort key
985
+ * is whatever that endpoint's `ListSpec` declared (`status`, `created`,
986
+ * `rule`). Getting it wrong is an error nowhere: `ListQuery` reads an unknown
987
+ * key as "no sort was asked for" and falls back to the endpoint's default, so
988
+ * the column would look sortable, respond to clicks, and quietly reorder
989
+ * nothing. Only mark a column `enableSorting` when that endpoint's spec
990
+ * actually offers the key it maps to.
991
+ */
992
+ sortKeys?: Record<string, string>
993
+ /** Forwarded to {@link DataTableServerSearch.debounceMs}. */
994
+ searchDebounceMs?: number
995
+ }
996
+
997
+ /**
998
+ * The page/sort/search state of ONE server-driven table, plus the three props
999
+ * {@link DataTable} needs to render it.
1000
+ */
1001
+ export interface DataTableQuery {
1002
+ /** What to ask the endpoint for. Thread it through EVERY request. */
1003
+ request: DataTableQueryRequest
1004
+ /** 1-based current page, for a caller that needs it outside `request`. */
1005
+ page: number
1006
+ setPage: (page: number) => void
1007
+ /** Hand straight to `<DataTable sorting={…}>`. */
1008
+ sorting: DataTableServerSorting
1009
+ /** Hand straight to `<DataTable search={…}>`. */
1010
+ search: DataTableServerSearch
1011
+ /** Build `<DataTable pagination={…}>` once the response's totals are known. */
1012
+ pagination: (meta: { total: number; totalPages: number }) => DataTableServerPagination
1013
+ }
1014
+
1015
+ /**
1016
+ * Hold a server-driven table's page, sort and search in one place.
1017
+ *
1018
+ * WHY A HOOK RATHER THAN THREE `useState` CALLS PER SCREEN. Changing the sort or
1019
+ * the search term invalidates the current page offset, and resetting to page 1
1020
+ * is the CALLER's job because the caller owns the pagination state (see
1021
+ * {@link DataTableServerSorting.onSortingChange}). Written out per screen that
1022
+ * reset is one line every screen has to remember, and nothing notices its
1023
+ * absence until somebody on page 7 searches for a term with three matches and
1024
+ * gets an empty table with nothing on screen explaining it. Here it is written
1025
+ * once and cannot be forgotten.
1026
+ *
1027
+ * It also owns the rule that is easiest to get subtly wrong: a `sortKey` of null
1028
+ * — the third click of asc → desc → none — must send NO `sort` and NO `dir`, so
1029
+ * the endpoint applies its own default ordering rather than one this component
1030
+ * made up.
1031
+ *
1032
+ * Debouncing is NOT here: {@link DataTableServerSearch} already debounces the
1033
+ * input, and a second timer on top would make the table lag a keystroke behind
1034
+ * for no benefit at all.
1035
+ *
1036
+ * ```tsx
1037
+ * const query = useDataTableQuery({ sortKeys: { accountStatus: 'status' } })
1038
+ * const queryString = dataTableQueryString(query.request)
1039
+ * const { data } = useFetch(() => fetchUsers(queryString), [queryString])
1040
+ * <DataTable
1041
+ * sorting={query.sorting}
1042
+ * search={query.search}
1043
+ * pagination={query.pagination({ total, totalPages })}
1044
+ * />
1045
+ * ```
1046
+ */
1047
+ export function useDataTableQuery({
1048
+ perPage: initialPerPage = DEFAULT_DATA_TABLE_PER_PAGE,
1049
+ initialSortKey = null,
1050
+ initialDirection = "asc",
1051
+ sortKeys,
1052
+ searchDebounceMs,
1053
+ }: UseDataTableQueryOptions = {}): DataTableQuery {
1054
+ const [page, setPage] = React.useState(1)
1055
+ const [perPage, setPerPage] = React.useState(initialPerPage)
1056
+ const [sortKey, setSortKey] = React.useState<string | null>(initialSortKey)
1057
+ const [direction, setDirection] = React.useState<"asc" | "desc">(initialDirection)
1058
+ const [search, setSearch] = React.useState("")
1059
+
1060
+ const endpointSort = sortKey === null ? undefined : (sortKeys?.[sortKey] ?? sortKey)
1061
+
1062
+ const request: DataTableQueryRequest = {
1063
+ page,
1064
+ perPage,
1065
+ ...(endpointSort === undefined ? {} : { sort: endpointSort, dir: direction }),
1066
+ ...(search === "" ? {} : { q: search }),
1067
+ }
1068
+
1069
+ return {
1070
+ request,
1071
+ page,
1072
+ setPage,
1073
+ sorting: {
1074
+ sortKey,
1075
+ direction,
1076
+ onSortingChange: (nextSortKey, nextDirection) => {
1077
+ setSortKey(nextSortKey)
1078
+ setDirection(nextDirection)
1079
+ // The reset this hook exists for. Page 7 of the old ordering is not
1080
+ // page 7 of the new one — it is an arbitrary window into a different
1081
+ // list.
1082
+ setPage(1)
1083
+ },
1084
+ },
1085
+ search: {
1086
+ value: search,
1087
+ debounceMs: searchDebounceMs,
1088
+ onSearchChange: (next) => {
1089
+ setSearch(next)
1090
+ // Same reason, more visibly: a search that narrows the list to three
1091
+ // rows has no page 7 at all, so staying there renders an empty table.
1092
+ setPage(1)
1093
+ },
1094
+ },
1095
+ pagination: ({ total, totalPages }) => ({
1096
+ pageIndex: page - 1,
1097
+ pageSize: perPage,
1098
+ pageCount: totalPages,
1099
+ total,
1100
+ onPaginationChange: (nextPageIndex, nextPageSize) => {
1101
+ setPage(nextPageIndex + 1)
1102
+ setPerPage(nextPageSize)
1103
+ },
1104
+ }),
1105
+ }
1106
+ }