@whity/ui 0.0.0-stage → 1.0.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 (205) hide show
  1. package/README.md +106 -2
  2. package/package.json +219 -4
  3. package/src/access-denied.stories.tsx +179 -0
  4. package/src/access-denied.tsx +305 -0
  5. package/src/action-proposal.tsx +338 -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 +604 -0
  16. package/src/approval-queue.tsx +109 -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-pattern.ts +138 -0
  22. package/src/avatar.tsx +125 -0
  23. package/src/badge.stories.tsx +105 -0
  24. package/src/badge.tsx +68 -0
  25. package/src/beta-warning.stories.tsx +79 -0
  26. package/src/beta-warning.tsx +189 -0
  27. package/src/bilingual-input.stories.tsx +82 -0
  28. package/src/bilingual-input.tsx +188 -0
  29. package/src/board.tsx +216 -0
  30. package/src/breadcrumb.stories.tsx +51 -0
  31. package/src/breadcrumb.tsx +90 -0
  32. package/src/built-on-whity.tsx +52 -0
  33. package/src/button.stories.tsx +87 -0
  34. package/src/button.tsx +123 -0
  35. package/src/card.stories.tsx +423 -0
  36. package/src/card.tsx +180 -0
  37. package/src/chart.stories.tsx +66 -0
  38. package/src/chart.tsx +228 -0
  39. package/src/checkbox.stories.tsx +62 -0
  40. package/src/checkbox.tsx +54 -0
  41. package/src/collapsible.stories.tsx +48 -0
  42. package/src/collapsible.tsx +34 -0
  43. package/src/color-card.stories.tsx +61 -0
  44. package/src/color-card.tsx +270 -0
  45. package/src/color-picker.stories.tsx +65 -0
  46. package/src/color-picker.tsx +425 -0
  47. package/src/column-matcher.tsx +84 -0
  48. package/src/command-palette.tsx +398 -0
  49. package/src/confirm-action.tsx +98 -0
  50. package/src/copy-block.stories.tsx +38 -0
  51. package/src/copy-block.tsx +85 -0
  52. package/src/data-table.stories.tsx +200 -0
  53. package/src/data-table.tsx +1686 -0
  54. package/src/date-picker.stories.tsx +61 -0
  55. package/src/date-picker.tsx +456 -0
  56. package/src/design-cards.stories.tsx +551 -0
  57. package/src/dialog.stories.tsx +48 -0
  58. package/src/dialog.tsx +179 -0
  59. package/src/display-preferences.tsx +50 -0
  60. package/src/documents/barcode-svg.stories.tsx +72 -0
  61. package/src/documents/barcode-svg.tsx +79 -0
  62. package/src/dropdown-menu.stories.tsx +77 -0
  63. package/src/dropdown-menu.tsx +271 -0
  64. package/src/editor/agent-panel.tsx +222 -0
  65. package/src/editor/agents.stories.tsx +81 -0
  66. package/src/editor/agents.ts +55 -0
  67. package/src/editor/behaviour.ts +279 -0
  68. package/src/editor/block-ids.ts +44 -0
  69. package/src/editor/block-list.tsx +104 -0
  70. package/src/editor/block-toolbar.tsx +490 -0
  71. package/src/editor/bubble.tsx +119 -0
  72. package/src/editor/catalogue.ts +169 -0
  73. package/src/editor/collab-rail.tsx +746 -0
  74. package/src/editor/collab.stories.tsx +207 -0
  75. package/src/editor/collab.ts +87 -0
  76. package/src/editor/contract.ts +476 -0
  77. package/src/editor/convert.ts +414 -0
  78. package/src/editor/doc-editor.stories.tsx +98 -0
  79. package/src/editor/doc-editor.tsx +1492 -0
  80. package/src/editor/editor.css +636 -0
  81. package/src/editor/extensions.ts +86 -0
  82. package/src/editor/field-bar.tsx +154 -0
  83. package/src/editor/field-picker.tsx +109 -0
  84. package/src/editor/fields.ts +100 -0
  85. package/src/editor/gutter.tsx +443 -0
  86. package/src/editor/index.ts +23 -0
  87. package/src/editor/label-sheet.tsx +289 -0
  88. package/src/editor/labels.ts +394 -0
  89. package/src/editor/link-tools.tsx +141 -0
  90. package/src/editor/node-views.tsx +461 -0
  91. package/src/editor/page-view.tsx +372 -0
  92. package/src/editor/phone.tsx +310 -0
  93. package/src/editor/plugin-block-view.tsx +230 -0
  94. package/src/editor/plugin-blocks.stories.tsx +96 -0
  95. package/src/editor/plugin-blocks.ts +52 -0
  96. package/src/editor/publish-check.tsx +201 -0
  97. package/src/editor/rich-blocks.stories.tsx +146 -0
  98. package/src/editor/sample.ts +40 -0
  99. package/src/editor/save-block-dialog.tsx +141 -0
  100. package/src/editor/saved-block-view.tsx +205 -0
  101. package/src/editor/saved-blocks.stories.tsx +105 -0
  102. package/src/editor/saved-parts.ts +192 -0
  103. package/src/editor/schema-rich.ts +156 -0
  104. package/src/editor/schema.ts +368 -0
  105. package/src/editor/services.tsx +205 -0
  106. package/src/editor/slash.ts +64 -0
  107. package/src/editor/suggesting.ts +372 -0
  108. package/src/editor/suggestions.ts +763 -0
  109. package/src/editor/table-keys.ts +66 -0
  110. package/src/editor/templates.stories.tsx +324 -0
  111. package/src/editor/toolbar.tsx +364 -0
  112. package/src/empty-state.stories.tsx +51 -0
  113. package/src/empty-state.tsx +126 -0
  114. package/src/empty-state.usage-notes.md +30 -0
  115. package/src/form.stories.tsx +112 -0
  116. package/src/form.tsx +176 -0
  117. package/src/globals.css +20 -0
  118. package/src/icon-button.tsx +85 -0
  119. package/src/icon-map.ts +335 -0
  120. package/src/icon.tsx +41 -0
  121. package/src/index.ts +90 -0
  122. package/src/input.stories.tsx +157 -0
  123. package/src/input.tsx +768 -0
  124. package/src/kpi-strip.tsx +47 -0
  125. package/src/localized-text.ts +76 -0
  126. package/src/locked-screen.stories.tsx +29 -0
  127. package/src/locked-screen.tsx +75 -0
  128. package/src/lockup.tsx +42 -0
  129. package/src/lottie.tsx +441 -0
  130. package/src/mark.tsx +62 -0
  131. package/src/math-text.stories.tsx +33 -0
  132. package/src/math-text.tsx +43 -0
  133. package/src/menu-bar.stories.tsx +198 -0
  134. package/src/menu-bar.tsx +373 -0
  135. package/src/message-thread.tsx +181 -0
  136. package/src/money/currency.ts +244 -0
  137. package/src/money/money-input.tsx +131 -0
  138. package/src/money/money.tsx +33 -0
  139. package/src/open-on-computer.tsx +150 -0
  140. package/src/otp-input.tsx +161 -0
  141. package/src/page-header.stories.tsx +95 -0
  142. package/src/page-header.tsx +122 -0
  143. package/src/page-shell.stories.tsx +42 -0
  144. package/src/page-shell.tsx +32 -0
  145. package/src/page-states.tsx +277 -0
  146. package/src/pagination.stories.tsx +45 -0
  147. package/src/pagination.tsx +98 -0
  148. package/src/paper-sheet.stories.tsx +88 -0
  149. package/src/paper-sheet.tsx +85 -0
  150. package/src/phone-tab-bar.tsx +152 -0
  151. package/src/plugin-card.stories.tsx +208 -0
  152. package/src/plugin-card.tsx +931 -0
  153. package/src/popover.stories.tsx +48 -0
  154. package/src/popover.tsx +55 -0
  155. package/src/radio-group.stories.tsx +26 -0
  156. package/src/radio-group.tsx +44 -0
  157. package/src/route-flow/editor.tsx +1087 -0
  158. package/src/route-flow/model.ts +771 -0
  159. package/src/save-bar.tsx +94 -0
  160. package/src/scope-grant.tsx +139 -0
  161. package/src/screen-too-small.stories.tsx +61 -0
  162. package/src/screen-too-small.tsx +104 -0
  163. package/src/search-field.tsx +65 -0
  164. package/src/select.stories.tsx +44 -0
  165. package/src/select.tsx +197 -0
  166. package/src/separator.stories.tsx +34 -0
  167. package/src/separator.tsx +34 -0
  168. package/src/sheet.stories.tsx +49 -0
  169. package/src/sheet.tsx +168 -0
  170. package/src/skeleton.stories.tsx +28 -0
  171. package/src/skeleton.tsx +19 -0
  172. package/src/slider.stories.tsx +78 -0
  173. package/src/slider.tsx +300 -0
  174. package/src/spinner.stories.tsx +33 -0
  175. package/src/spinner.tsx +55 -0
  176. package/src/stepper.tsx +85 -0
  177. package/src/switch.stories.tsx +42 -0
  178. package/src/switch.tsx +41 -0
  179. package/src/switcher.stories.tsx +111 -0
  180. package/src/switcher.tsx +131 -0
  181. package/src/system-state.tsx +55 -0
  182. package/src/table.stories.tsx +48 -0
  183. package/src/table.tsx +121 -0
  184. package/src/tabs.stories.tsx +74 -0
  185. package/src/tabs.tsx +90 -0
  186. package/src/tag-input.stories.tsx +67 -0
  187. package/src/tag-input.tsx +117 -0
  188. package/src/tenant-logo.tsx +63 -0
  189. package/src/tenant-switcher.stories.tsx +38 -0
  190. package/src/tenant-switcher.tsx +164 -0
  191. package/src/textarea.stories.tsx +27 -0
  192. package/src/textarea.tsx +18 -0
  193. package/src/theme-mode.ts +52 -0
  194. package/src/time-grid.tsx +163 -0
  195. package/src/time-picker.stories.tsx +62 -0
  196. package/src/time-picker.tsx +615 -0
  197. package/src/toggle-group.tsx +138 -0
  198. package/src/tooltip.stories.tsx +43 -0
  199. package/src/tooltip.tsx +73 -0
  200. package/src/top-nav.stories.tsx +58 -0
  201. package/src/top-nav.tsx +324 -0
  202. package/src/undo-bar.tsx +107 -0
  203. package/src/utils.ts +45 -0
  204. package/src/view-toggle.stories.tsx +84 -0
  205. package/src/view-toggle.tsx +110 -0
@@ -0,0 +1,1686 @@
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
+ IconCheck,
37
+ IconChevronDown,
38
+ IconFilter,
39
+ IconPlus,
40
+ IconX,
41
+ IconChevronUp,
42
+ IconLayoutColumns,
43
+ IconSearch,
44
+ } from "@tabler/icons-react"
45
+
46
+ import { cn } from "./utils"
47
+ import {
48
+ Table,
49
+ TableBody,
50
+ TableFooter,
51
+ TableCell,
52
+ TableHead,
53
+ TableHeader,
54
+ TableRow,
55
+ } from "./table"
56
+ import { Button } from "./button"
57
+ import { Checkbox } from "./checkbox"
58
+ import { Input } from "./input"
59
+ import { Pagination } from "./pagination"
60
+ import { Skeleton } from "./skeleton"
61
+ import { EmptyState, ErrorState, type EmptyStateProps } from "./empty-state"
62
+ import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "./sheet"
63
+ import {
64
+ DropdownMenu,
65
+ DropdownMenuCheckboxItem,
66
+ DropdownMenuContent,
67
+ DropdownMenuTrigger,
68
+ } from "./dropdown-menu"
69
+
70
+ /**
71
+ * One column definition. A thin, purpose-shaped wrapper over TanStack
72
+ * Table's `ColumnDef` — callers describe WHAT a column is (key/header/cell),
73
+ * this component wires up HOW it sorts/filters/resizes/hides.
74
+ */
75
+ /** What the table calls to render one cell, given the cell's context. */
76
+ type CellRenderer<TRow> = (info: { row: { id: string; original: TRow } }) => React.ReactNode
77
+
78
+ export interface DataTableColumn<TData> {
79
+ /** Unique column id. Defaults to `accessorKey` when omitted. */
80
+ id?: string
81
+ /** Dot-free top-level key read from each row when `cell` is omitted. */
82
+ accessorKey?: Extract<keyof TData, string>
83
+ header: React.ReactNode
84
+ /** Custom cell renderer — receives the full row, returns any node. */
85
+ cell?: (row: TData) => React.ReactNode
86
+ enableSorting?: boolean
87
+ enableColumnFilter?: boolean
88
+ /** Whether this column can be hidden via the column-visibility menu. Default true. */
89
+ enableHiding?: boolean
90
+ /** Initial/fixed width in px, also used as the resize starting point. */
91
+ size?: number
92
+ className?: string
93
+ }
94
+
95
+ /** Server-driven pagination: caller owns the page/pageSize/total, we just render controls. */
96
+ export interface DataTableServerPagination {
97
+ pageIndex: number
98
+ pageSize: number
99
+ pageCount: number
100
+ /** Total row count across all pages — drives the "N entries" label. */
101
+ total: number
102
+ onPaginationChange: (pageIndex: number, pageSize: number) => void
103
+ }
104
+
105
+ /**
106
+ * Server-driven sorting: the caller owns the sort column and direction, we
107
+ * render the header affordances and call back. The same shape of bargain as
108
+ * {@link DataTableServerPagination}.
109
+ *
110
+ * WHY THIS HAS TO EXIST. Without it, a table in server-pagination mode still
111
+ * sorts CLIENT-side, and the registered `sortedRowModel` sorts THE ROWS IT WAS
112
+ * HANDED — the twenty five on screen. Clicking "Name" then reorders one page and
113
+ * presents the result as a sorted list; page 2 re-sorts a different twenty
114
+ * five. Nothing errors and nothing looks wrong, which is the whole problem:
115
+ * the reader has no way to tell a sorted list from a sorted page. Screens hit
116
+ * this already and worked around it by making their columns non-sortable and
117
+ * moving sort into their own toolbar (see the document library's
118
+ * `LibraryToolbar`), because the alternative was shipping the untruth.
119
+ */
120
+ export interface DataTableServerSorting {
121
+ /** Column id currently sorted, or null for "no column chosen". */
122
+ sortKey: string | null
123
+ direction: "asc" | "desc"
124
+ /**
125
+ * Called with the NEXT sort when the user clicks a sortable header.
126
+ *
127
+ * `sortKey` is null when a column is cycled past descending back to
128
+ * unsorted (TanStack's default asc → desc → none cycle). `direction` is then
129
+ * not meaningful — send no `dir` upstream in that case, so the endpoint's own
130
+ * default ordering applies rather than one this component invented.
131
+ *
132
+ * Changing the sort invalidates the current page offset. Resetting to page 1
133
+ * is the caller's to do, since the caller owns the pagination state.
134
+ */
135
+ onSortingChange: (sortKey: string | null, direction: "asc" | "desc") => void
136
+ }
137
+
138
+ /**
139
+ * Quiet period before a keystroke becomes a request, in ms.
140
+ *
141
+ * Exported so a caller or a test can reach the default by name instead of
142
+ * re-stating the number, and overridable per table via
143
+ * {@link DataTableServerSearch.debounceMs} — typing "engineering" is twelve
144
+ * requests without it.
145
+ */
146
+ export const DATA_TABLE_SEARCH_DEBOUNCE_MS = 300
147
+
148
+ /**
149
+ * Server-driven global search: the caller owns the term, we own the input.
150
+ *
151
+ * Same hazard as {@link DataTableServerSorting}: a client-side global filter
152
+ * over a server-paginated table filters the current page, so a search that
153
+ * matches nothing on page 1 reports "no results" while the match sits on
154
+ * page 4.
155
+ */
156
+ export interface DataTableServerSearch {
157
+ /**
158
+ * The term the caller has APPLIED. This is not necessarily what is in the
159
+ * box: the input keeps its own draft so typing stays responsive while the
160
+ * request is debounced. An external change to this value (a "clear search"
161
+ * button elsewhere on the page) is adopted into the box; the echo of our own
162
+ * callback is not, because adopting it would overwrite whatever was typed
163
+ * while the request was in flight.
164
+ */
165
+ value: string
166
+ onSearchChange: (value: string) => void
167
+ /**
168
+ * Quiet period after typing stops, in ms. Defaults to
169
+ * {@link DATA_TABLE_SEARCH_DEBOUNCE_MS}. Pass 0 to call back on every
170
+ * keystroke (the caller is debouncing, or a test wants determinism).
171
+ */
172
+ debounceMs?: number
173
+ }
174
+
175
+ /** Row selection with the bulk bar (decision 7.6). The caller owns which rows are selected. */
176
+ export interface DataTableSelection<TData> {
177
+ /** Row ids, as `getRowId` gives them. `getRowId` is required with selection. */
178
+ selected: ReadonlySet<string>
179
+ onSelectedChange: (next: Set<string>) => void
180
+ /** The bulk actions, normally `<Button variant="outline" size="sm">`. */
181
+ actions?: React.ReactNode
182
+ /** The money total of the selected rows, shown beside the count. */
183
+ summary?: (rows: TData[]) => React.ReactNode
184
+ /**
185
+ * Which rows may be ticked (AQ.1: only Ordinary approvals go together). A row
186
+ * this refuses shows a disabled checkbox and is skipped by Select all.
187
+ * Omitted, every row may be ticked.
188
+ */
189
+ canSelect?: (row: TData) => boolean
190
+ labels?: {
191
+ /** "{count} selected" */
192
+ count?: (count: number) => string
193
+ clear?: string
194
+ selectAll?: string
195
+ selectRow?: string
196
+ }
197
+ }
198
+
199
+ export interface DataTableProps<TData> {
200
+ columns: DataTableColumn<TData>[]
201
+ data: TData[]
202
+ getRowId?: (row: TData, index: number) => string
203
+ /**
204
+ * Opens the row (P.1). A click on a control inside the row does not count, so
205
+ * row menus and links keep working. Rows stay reachable by keyboard through
206
+ * whatever link or button the row itself holds.
207
+ */
208
+ onRowClick?: (row: TData) => void
209
+ /** Checkbox column and the bulk bar at the foot (7.6). */
210
+ selection?: DataTableSelection<TData>
211
+ /** Keep the header in view while the table scrolls inside `maxHeight` (7.6). */
212
+ stickyHeader?: boolean
213
+ /** The scroll height for `stickyHeader`, such as "60vh". */
214
+ maxHeight?: string
215
+ /** One cell per visible column, for money totals; rendered as the table's foot. */
216
+ totals?: React.ReactNode[]
217
+ /** Trailing actions cell render-prop, matching the previous DataTable's convention. */
218
+ rowActions?: (row: TData) => React.ReactNode
219
+ isLoading?: boolean
220
+ /** Replaces the ENTIRE table (chrome included) — e.g. a 403 Access Denied screen. */
221
+ overrideContent?: React.ReactNode
222
+ emptyState?: Omit<EmptyStateProps, "variant">
223
+ errorState?: Omit<EmptyStateProps, "variant">
224
+ /** Free-text search across every column's string value. Off by default. */
225
+ enableGlobalFilter?: boolean
226
+ globalFilterPlaceholder?: string
227
+ /** Header text for the row-actions column. Defaults to "Actions". */
228
+ rowActionsLabel?: string
229
+ /**
230
+ * Accessible name for the table element, applied in EVERY state that renders
231
+ * a `table` — the loading skeleton and the loaded rows alike.
232
+ *
233
+ * A page with two DataTables gives assistive technology — and any test
234
+ * selecting by role — two identical, unnamed `table` landmarks with no way to
235
+ * tell them apart. Naming them is the a11y answer and it is what makes
236
+ * `getByRole('table', { name })` a stable selector instead of a positional
237
+ * guess that breaks the next time a panel is added.
238
+ *
239
+ * It was originally wired into the skeleton branch ONLY (#967). Both halves of
240
+ * that sentence then failed: a screen reader met the LOADED users table — the
241
+ * state anybody actually reads — as an unnamed twin of the invitations table,
242
+ * and `getByRole('table', { name })` silently became an assertion about the
243
+ * skeleton, satisfied only while the request was still in flight. It passed
244
+ * when the backend was slow and failed when it was fast, which is why it read
245
+ * as flakiness on unrelated PRs and cost three CI cycles before it was
246
+ * diagnosed. Any new branch here that renders a `table` must name it too.
247
+ */
248
+ ariaLabel?: string
249
+ /**
250
+ * Title shown when there are no rows and the caller passed no `emptyState`.
251
+ * `emptyState` still wins — this only replaces the built-in English default,
252
+ * so a caller translating just this string does not have to reconstruct the
253
+ * whole empty state.
254
+ */
255
+ emptyStateTitle?: string
256
+ /** Placeholder for the per-column filter inputs. Defaults to "Filter…". */
257
+ columnFilterPlaceholder?: string
258
+ /** Text of the column-visibility menu trigger. Defaults to "Columns". */
259
+ columnsMenuLabel?: string
260
+ /**
261
+ * Copy for the pagination controls this table renders for itself.
262
+ *
263
+ * Forwarded to <Pagination>. Without this the table's own footer — 'N
264
+ * entries', 'page 2 of 7', the prev/next buttons — would be the one part
265
+ * of a translated table still stuck in English, with no way for a caller
266
+ * to reach it.
267
+ */
268
+ paginationLabels?: Pick<
269
+ React.ComponentProps<typeof Pagination>,
270
+ "entriesLabel" | "pageLabel" | "navLabel" | "previousLabel" | "nextLabel"
271
+ >
272
+ /** Show/hide-columns menu. Off by default. */
273
+ enableColumnVisibility?: boolean
274
+ /** Drag-resize column borders. Off by default. */
275
+ enableColumnResizing?: boolean
276
+ /**
277
+ * Omit for no pagination. Pass `{ pageSize }` (a plain number of rows per
278
+ * page) for automatic CLIENT-side pagination. Pass a
279
+ * {@link DataTableServerPagination} object when the caller's API already
280
+ * paginates server-side (manual mode — this component then just renders
281
+ * controls and calls back, never re-slices `data` itself).
282
+ */
283
+ pagination?: DataTableServerPagination | { pageSize: number }
284
+ /**
285
+ * Omit to let this component sort the rows it holds (the default, and what
286
+ * every existing caller gets). Pass a {@link DataTableServerSorting} object
287
+ * when the SERVER sorts: the headers then reflect the caller's state and
288
+ * report clicks, and the rows are rendered in the order they arrived.
289
+ */
290
+ sorting?: DataTableServerSorting
291
+ /**
292
+ * Omit to let `enableGlobalFilter` filter the rows it holds. Pass a
293
+ * {@link DataTableServerSearch} object when the SERVER searches: the same
294
+ * search box renders (passing this implies it, `enableGlobalFilter` or not)
295
+ * and reports what is typed, and no row is filtered out locally.
296
+ *
297
+ * Per-column filters are deliberately LEFT ALONE by this — see the note on
298
+ * `manualFiltering` at the `useTable` call.
299
+ */
300
+ search?: DataTableServerSearch
301
+ /**
302
+ * Below 640px: "stack" (the default) shows each row as a small card, the
303
+ * first column as its title and the others as label and value lines under
304
+ * it (the "Your fields" rows of the phone designs), so nothing scrolls
305
+ * sideways. "scroll" keeps the table and lets it scroll inside its frame,
306
+ * for the few tables that only make sense as a grid.
307
+ */
308
+ phoneLayout?: "stack" | "scroll"
309
+ /** The phone's list chrome (`PwLists`, PW.4); only with `phoneLayout="stack"`. */
310
+ phone?: DataTablePhone
311
+ className?: string
312
+ }
313
+
314
+ /**
315
+ * Lists on a phone (`PwLists`): under 640px a stacked table also gets the phone
316
+ * app's controls. Sort is a button by the list (a sheet, one choice per line);
317
+ * Select turns the boxes on, with Cancel, the count and Clear all / Choose all
318
+ * at the top and the bulk actions in a bar in the tab bar's place; search,
319
+ * Filter and the page's main button sit at the bottom, above the tab bar;
320
+ * filters on show are chips with a cross. Desktop is untouched.
321
+ */
322
+ export type DataTablePhoneLabels = NonNullable<DataTablePhone["labels"]>
323
+
324
+ /**
325
+ * The phone controls' words for every table below it, so an app translates
326
+ * them once (the web shell mounts it) instead of on every screen. A table's
327
+ * own `phone.labels` wins over it.
328
+ */
329
+ const DataTablePhoneLabelsContext = React.createContext<DataTablePhoneLabels>({})
330
+
331
+ export function DataTablePhoneLabelsProvider({
332
+ labels,
333
+ children,
334
+ }: {
335
+ labels: DataTablePhoneLabels
336
+ children: React.ReactNode
337
+ }) {
338
+ return <DataTablePhoneLabelsContext.Provider value={labels}>{children}</DataTablePhoneLabelsContext.Provider>
339
+ }
340
+
341
+ export interface DataTablePhone {
342
+ /** The page's main action, the "+" at the end of the bottom bar. */
343
+ mainAction?: { label: string; onClick?: () => void; href?: string }
344
+ /** Filters in a bottom sheet, opened by Filter in the bottom bar. */
345
+ filters?: {
346
+ content: React.ReactNode
347
+ /** Filters on show, as chips under the list's controls. */
348
+ chips?: { id: string; label: string; onRemove: () => void }[]
349
+ onClear?: () => void
350
+ }
351
+ labels?: {
352
+ sort?: string
353
+ sortTitle?: string
354
+ /** "{column}, lowest first" */
355
+ ascending?: (column: string) => string
356
+ /** "{column}, highest first" */
357
+ descending?: (column: string) => string
358
+ defaultOrder?: string
359
+ select?: string
360
+ cancel?: string
361
+ /** "{count} chosen" */
362
+ chosen?: (count: number) => string
363
+ clearAll?: string
364
+ chooseAll?: string
365
+ filter?: string
366
+ filtersTitle?: string
367
+ clearFilters?: string
368
+ done?: string
369
+ removeFilter?: (label: string) => string
370
+ }
371
+ }
372
+
373
+ function isServerPagination(
374
+ p: DataTableServerPagination | { pageSize: number }
375
+ ): p is DataTableServerPagination {
376
+ return "onPaginationChange" in p
377
+ }
378
+
379
+ /**
380
+ * The TanStack v9 feature set this table runs on.
381
+ *
382
+ * v9 REPLACED THE v8 `getXRowModel()` OPTIONS WITH EXPLICIT REGISTRATION. In v8
383
+ * a table got sorting because you passed `getSortedRowModel()`; in v9 it gets
384
+ * sorting because `rowSortingFeature` is registered here and the matching
385
+ * `sortedRowModel` factory sits beside it. Nothing is implicit, and a feature
386
+ * left out of this object does not merely go unused — its options and its slice
387
+ * of table state stop existing, and TypeScript says so at the call site.
388
+ *
389
+ * DECLARED AT MODULE SCOPE because the identity is read on every render and a
390
+ * fresh object each time would rebuild the table's feature registry for no
391
+ * reason. It carries no per-table state, so one shared value is correct.
392
+ *
393
+ * `columnMeta` is a TYPE-ONLY slot: the value is stripped at runtime and only
394
+ * its type is used, which is how `meta: { className }` on a column definition
395
+ * type-checks again. In v8 `meta` was loosely typed and ours assigned by luck;
396
+ * v9 threads `ExtractColumnMeta<TFeatures>` through, so the shape has to be
397
+ * declared once — here — rather than asserted at each of the 26 call sites.
398
+ */
399
+ /**
400
+ * The feature set's own type, and the row type v9 will accept.
401
+ *
402
+ * v9 constrains table data to `RowData` (`Record<string, any> | Array<any>`).
403
+ * {@link DataTableProps} deliberately does NOT constrain `TData` — 26 call sites
404
+ * pass plain interfaces, and adding the constraint to the public prop would push
405
+ * this migration out into every one of them, which is exactly what this rewrite
406
+ * exists to avoid. So the bridge is here, once, and the props contract is
407
+ * unchanged.
408
+ */
409
+ type TableFeatureSet = typeof tableFeatures
410
+ type TableRow<TData> = TData & Record<string, unknown>
411
+
412
+ const tableFeatures = {
413
+ columnFilteringFeature,
414
+ columnResizingFeature,
415
+ columnSizingFeature,
416
+ columnVisibilityFeature,
417
+ globalFilteringFeature,
418
+ rowPaginationFeature,
419
+ rowSortingFeature,
420
+ coreRowModel: createCoreRowModel(),
421
+ filteredRowModel: createFilteredRowModel(),
422
+ sortedRowModel: createSortedRowModel(),
423
+ // Client-side paging is still a supported v9 row model — `createPaginatedRowModel`
424
+ // is the rename of v8's `getPaginationRowModel`, not a removal. Registering it
425
+ // unconditionally is safe: with `manualPagination` on, the server owns the
426
+ // slice and this model is never consulted.
427
+ paginatedRowModel: createPaginatedRowModel(),
428
+ /**
429
+ * THE FILTER AND SORT FUNCTIONS THE AUTO-RESOLVER CAN ASK FOR.
430
+ *
431
+ * v9 resolves an unconfigured column to a filter/sort function BY NAME and
432
+ * looks that name up here. The two halves fail differently, and both quietly:
433
+ *
434
+ * - an unregistered FILTER function returns `undefined`, and the column
435
+ * filter becomes a no-op. Typing in the filter box narrows nothing.
436
+ * - an unregistered SORT function falls back to `sortFn_basic`, so the
437
+ * column still sorts — just wrongly. `basic` compares with `<`, so
438
+ * "item 10" lands before "item 2" and case is handled differently from
439
+ * the `text`/`alphanumeric` functions v8 chose automatically.
440
+ *
441
+ * Neither raises anything outside a development console warning, which is why
442
+ * these are listed explicitly rather than left to a default that no longer
443
+ * exists. The six filter functions are exactly the ones the auto-resolver can
444
+ * pick (string / number / boolean / array / date / fallback); registering the
445
+ * whole exported registry instead would put every built-in in the bundle.
446
+ */
447
+ filterFns: {
448
+ arrIncludes: filterFn_arrIncludes,
449
+ equals: filterFn_equals,
450
+ inDateRange: filterFn_inDateRange,
451
+ inNumberRange: filterFn_inNumberRange,
452
+ includesString: filterFn_includesString,
453
+ weakEquals: filterFn_weakEquals,
454
+ },
455
+ sortFns: {
456
+ alphanumeric: sortFn_alphanumeric,
457
+ basic: sortFn_basic,
458
+ datetime: sortFn_datetime,
459
+ text: sortFn_text,
460
+ },
461
+ columnMeta: {} as { className?: string },
462
+ }
463
+
464
+ /** A click on one of these inside a row is that control's, not the row's. */
465
+ function isInteractiveTarget(target: EventTarget): boolean {
466
+ return (
467
+ target instanceof Element &&
468
+ target.closest('a,button,input,select,textarea,label,[role="button"],[role="menuitem"],[role="checkbox"],[role="switch"]') !== null
469
+ )
470
+ }
471
+
472
+ type SelectionRef<TData> = React.RefObject<{
473
+ selection?: DataTableSelection<TData>
474
+ data: TData[]
475
+ getRowId?: (row: TData, index: number) => string
476
+ }>
477
+
478
+ function pageRowIds<TData>(latest: SelectionRef<TData>): string[] {
479
+ const { data, getRowId, selection } = latest.current
480
+ const ids: string[] = []
481
+ data.forEach((row, index) => {
482
+ if (selection?.canSelect && !selection.canSelect(row)) return
483
+ ids.push(getRowId ? getRowId(row, index) : String(index))
484
+ })
485
+ return ids
486
+ }
487
+
488
+ function rowById<TData>(latest: SelectionRef<TData>, rowId: string): TData | undefined {
489
+ const { data, getRowId } = latest.current
490
+ return data.find((row, index) => (getRowId ? getRowId(row, index) : String(index)) === rowId)
491
+ }
492
+
493
+ function SelectAllCell<TData>({ latest }: { latest: SelectionRef<TData> }) {
494
+ const { selection } = latest.current
495
+ if (!selection) return null
496
+ const ids = pageRowIds(latest)
497
+ const chosen = ids.filter((id) => selection.selected.has(id)).length
498
+ return (
499
+ <Checkbox
500
+ aria-label={selection.labels?.selectAll ?? "Select all"}
501
+ disabled={ids.length === 0}
502
+ checked={chosen === 0 ? false : chosen === ids.length ? true : "indeterminate"}
503
+ onCheckedChange={(checked) => {
504
+ const next = new Set(selection.selected)
505
+ for (const id of ids) {
506
+ if (checked === true) next.add(id)
507
+ else next.delete(id)
508
+ }
509
+ selection.onSelectedChange(next)
510
+ }}
511
+ />
512
+ )
513
+ }
514
+
515
+ function SelectRowCell<TData>({ latest, rowId }: { latest: SelectionRef<TData>; rowId: string }) {
516
+ const { selection } = latest.current
517
+ if (!selection) return null
518
+ const row = selection.canSelect ? rowById(latest, rowId) : undefined
519
+ const selectable = !selection.canSelect || (row !== undefined && selection.canSelect(row))
520
+ return (
521
+ <Checkbox
522
+ aria-label={selection.labels?.selectRow ?? "Select row"}
523
+ disabled={!selectable}
524
+ checked={selectable && selection.selected.has(rowId)}
525
+ onCheckedChange={(checked) => {
526
+ const next = new Set(selection.selected)
527
+ if (checked === true) next.add(rowId)
528
+ else next.delete(rowId)
529
+ selection.onSelectedChange(next)
530
+ }}
531
+ />
532
+ )
533
+ }
534
+
535
+ /**
536
+ * True under 640px, where a stacked table takes the phone's list chrome
537
+ * (PwLists). Rendered only there, not merely hidden, so a wide window has one
538
+ * search box rather than two and the sheets never mount.
539
+ */
540
+ function usePhoneWidth(): boolean {
541
+ const [phone, setPhone] = React.useState(false)
542
+ React.useEffect(() => {
543
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return
544
+ const query = window.matchMedia("(max-width: 639.98px)")
545
+ const update = () => setPhone(query.matches)
546
+ update()
547
+ query.addEventListener?.("change", update)
548
+ return () => query.removeEventListener?.("change", update)
549
+ }, [])
550
+ return phone
551
+ }
552
+
553
+ /** `.wy-bulkbar`: the dark bar with the count, the total, the actions and Clear. */
554
+ function BulkBar<TData>({
555
+ selection,
556
+ data,
557
+ getRowId,
558
+ phone = false,
559
+ }: {
560
+ selection: DataTableSelection<TData>
561
+ data: TData[]
562
+ getRowId?: (row: TData, index: number) => string
563
+ /** On a phone the bar takes the tab bar's place at the bottom (PwLists). */
564
+ phone?: boolean
565
+ }) {
566
+ const count = selection.selected.size
567
+ const rows = data.filter((row, index) => selection.selected.has(getRowId ? getRowId(row, index) : String(index)))
568
+ return (
569
+ <div
570
+ data-slot="data-table-bulk-bar"
571
+ role="region"
572
+ aria-live="polite"
573
+ className={cn(
574
+ "sticky bottom-4 z-[2] mt-3 flex flex-wrap items-center gap-2 rounded-control-lg bg-foreground py-2 ps-3.5 pe-2.5 text-sm text-background shadow-float",
575
+ phone &&
576
+ "max-sm:fixed max-sm:inset-x-0 max-sm:bottom-0 max-sm:z-50 max-sm:mt-0 max-sm:rounded-none max-sm:px-4 max-sm:pt-2.5 max-sm:pb-[calc(0.625rem+env(safe-area-inset-bottom))]"
577
+ )}
578
+ >
579
+ <span className="me-auto font-semibold tabular-nums">
580
+ {selection.labels?.count?.(count) ?? `${count} selected`}
581
+ {selection.summary && <span className="ms-2 font-normal">{selection.summary(rows)}</span>}
582
+ </span>
583
+ {selection.actions}
584
+ <Button
585
+ type="button"
586
+ variant="ghost"
587
+ size="sm"
588
+ className="text-background hover:bg-background/15"
589
+ onClick={() => selection.onSelectedChange(new Set())}
590
+ >
591
+ {selection.labels?.clear ?? "Clear"}
592
+ </Button>
593
+ </div>
594
+ )
595
+ }
596
+
597
+ export function DataTable<TData>({
598
+ columns,
599
+ data,
600
+ getRowId,
601
+ rowActions,
602
+ onRowClick,
603
+ selection,
604
+ stickyHeader = false,
605
+ maxHeight,
606
+ totals,
607
+ isLoading = false,
608
+ overrideContent,
609
+ emptyState,
610
+ errorState,
611
+ enableGlobalFilter = false,
612
+ globalFilterPlaceholder = "Search…",
613
+ rowActionsLabel = "Actions",
614
+ ariaLabel,
615
+ emptyStateTitle = "No data available",
616
+ columnFilterPlaceholder = "Filter…",
617
+ columnsMenuLabel = "Columns",
618
+ paginationLabels,
619
+ enableColumnVisibility = false,
620
+ enableColumnResizing = false,
621
+ pagination,
622
+ sorting: serverSorting,
623
+ search: serverSearch,
624
+ phoneLayout = "stack",
625
+ phone,
626
+ className,
627
+ }: DataTableProps<TData>) {
628
+ // Totals are a grid by nature, so a table with a foot keeps scrolling.
629
+ const stack = phoneLayout === "stack" && !totals
630
+ // The phone's list chrome (PwLists): Select mode, and the two sheets.
631
+ const [phoneSelectMode, setPhoneSelectMode] = React.useState(false)
632
+ const [sortSheetOpen, setSortSheetOpen] = React.useState(false)
633
+ const [filterSheetOpen, setFilterSheetOpen] = React.useState(false)
634
+ const isPhone = usePhoneWidth()
635
+ const sharedPhoneLabels = React.useContext(DataTablePhoneLabelsContext)
636
+ const [clientSorting, setClientSorting] = React.useState<SortingState>([])
637
+ const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
638
+ const [globalFilter, setGlobalFilter] = React.useState("")
639
+ const [columnVisibility, setColumnVisibility] = React.useState<ColumnVisibilityState>({})
640
+
641
+ const serverMode = pagination != null && isServerPagination(pagination)
642
+
643
+ /**
644
+ * The caller's sort, in the shape TanStack keeps it in. One column at a
645
+ * time: the server contract this pairs with takes a single `sort` key, so
646
+ * offering multi-sort in the UI would promise an ordering the request cannot
647
+ * express.
648
+ */
649
+ const sortingState: SortingState = serverSorting
650
+ ? serverSorting.sortKey
651
+ ? [{ id: serverSorting.sortKey, desc: serverSorting.direction === "desc" }]
652
+ : []
653
+ : clientSorting
654
+ const [clientPagination, setClientPagination] = React.useState<PaginationState>({
655
+ pageIndex: 0,
656
+ pageSize: pagination && !serverMode ? pagination.pageSize : 10,
657
+ })
658
+
659
+ // What is TYPED, which is not what has been SENT. The box must stay
660
+ // responsive while the request is debounced, so it renders this draft rather
661
+ // than `serverSearch.value`; a controlled input bound straight to a value
662
+ // that only updates after the round trip drops characters typed in between.
663
+ const appliedSearch = serverSearch?.value ?? ""
664
+ const [searchDraft, setSearchDraft] = React.useState(appliedSearch)
665
+ const searchTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null)
666
+ // The last term we handed to `onSearchChange`. When the caller sets `value`
667
+ // to exactly this, it is the ECHO of our own callback, not somebody else
668
+ // changing the search, and adopting it would clobber the characters typed
669
+ // between the timer firing and the caller re-rendering.
670
+ const lastEmittedSearch = React.useRef<string | null>(null)
671
+
672
+ const clearSearchTimer = () => {
673
+ if (searchTimer.current !== null) {
674
+ clearTimeout(searchTimer.current)
675
+ searchTimer.current = null
676
+ }
677
+ }
678
+
679
+ React.useEffect(() => {
680
+ if (lastEmittedSearch.current === appliedSearch) return
681
+ lastEmittedSearch.current = null
682
+ // An external change wins over anything still pending — a "clear search"
683
+ // button elsewhere on the page must not be undone a moment later by a
684
+ // timer carrying the term it just cleared.
685
+ clearSearchTimer()
686
+ setSearchDraft(appliedSearch)
687
+ }, [appliedSearch])
688
+
689
+ // A pending timer outliving the component would call back into an unmounted
690
+ // caller. Cancelling on unmount is the whole of it.
691
+ React.useEffect(() => clearSearchTimer, [])
692
+
693
+ const handleSearchInput = (next: string) => {
694
+ if (!serverSearch) {
695
+ setGlobalFilter(next)
696
+ return
697
+ }
698
+ setSearchDraft(next)
699
+ clearSearchTimer()
700
+ const delay = serverSearch.debounceMs ?? DATA_TABLE_SEARCH_DEBOUNCE_MS
701
+ if (delay <= 0) {
702
+ lastEmittedSearch.current = next
703
+ serverSearch.onSearchChange(next)
704
+ return
705
+ }
706
+ searchTimer.current = setTimeout(() => {
707
+ searchTimer.current = null
708
+ lastEmittedSearch.current = next
709
+ serverSearch.onSearchChange(next)
710
+ }, delay)
711
+ }
712
+
713
+ /** Passing `search` implies the search box, whether or not the flag is set. */
714
+ const showSearchInput = enableGlobalFilter || serverSearch != null
715
+
716
+ // ONE RENDERER PER COLUMN, FOR THE LIFE OF THE TABLE (WHIT-800).
717
+ //
718
+ // The table renders a cell's function as a React component, so a new function
719
+ // is a new component type. Callers build `columns` and `rowActions` inline,
720
+ // which made them new on every render, so React unmounted and remounted every
721
+ // cell each time the page re-rendered: an open row menu closed and its items
722
+ // detached mid-click. So the function handed to the table never changes, and
723
+ // reads the caller's current closures here when it runs. Assigned during render
724
+ // rather than in an effect because the cells render in this same pass.
725
+ const latestCells = React.useRef({ columns, rowActions, selection, data, getRowId })
726
+ latestCells.current = { columns, rowActions, selection, data, getRowId }
727
+ const hasSelection = selection !== undefined
728
+ const cellRenderers = React.useRef(new Map<string, CellRenderer<TableRow<TData>>>())
729
+ const stableCell = (id: string, render: CellRenderer<TableRow<TData>>) => {
730
+ const existing = cellRenderers.current.get(id)
731
+ if (existing) return existing
732
+ cellRenderers.current.set(id, render)
733
+ return render
734
+ }
735
+
736
+ const columnDefs = React.useMemo<ColumnDef<TableFeatureSet, TableRow<TData>, unknown>[]>(() => {
737
+ const defs: ColumnDef<TableFeatureSet, TableRow<TData>, unknown>[] = columns.map((column) => {
738
+ const id = column.id ?? column.accessorKey
739
+ if (!id) {
740
+ throw new Error("DataTable: every column needs an `id` or `accessorKey`")
741
+ }
742
+ return {
743
+ id,
744
+ accessorKey: column.accessorKey,
745
+ header: column.header as string,
746
+ cell: stableCell(id, (info) => {
747
+ const current = latestCells.current.columns.find((c) => (c.id ?? c.accessorKey) === id)
748
+ if (current?.cell) return current.cell(info.row.original)
749
+ const value = current?.accessorKey
750
+ ? (info.row.original as Record<string, unknown>)[current.accessorKey]
751
+ : undefined
752
+ return value == null || value === "" ? (
753
+ <span className="text-muted-foreground">—</span>
754
+ ) : (
755
+ String(value)
756
+ )
757
+ }),
758
+ enableSorting: column.enableSorting ?? false,
759
+ enableColumnFilter: column.enableColumnFilter ?? false,
760
+ enableHiding: column.enableHiding ?? true,
761
+ size: column.size,
762
+ meta: { className: column.className },
763
+ }
764
+ })
765
+ if (rowActions) {
766
+ defs.push({
767
+ id: "__row-actions",
768
+ header: rowActionsLabel,
769
+ cell: stableCell("__row-actions", (info) => latestCells.current.rowActions?.(info.row.original) ?? null),
770
+ enableSorting: false,
771
+ enableColumnFilter: false,
772
+ enableHiding: false,
773
+ })
774
+ }
775
+ if (hasSelection) {
776
+ defs.unshift({
777
+ id: "__select",
778
+ header: () => <SelectAllCell latest={latestCells} />,
779
+ cell: stableCell("__select", (info) => <SelectRowCell latest={latestCells} rowId={info.row.id} />),
780
+ enableSorting: false,
781
+ enableColumnFilter: false,
782
+ enableHiding: false,
783
+ meta: { className: "w-10" },
784
+ })
785
+ }
786
+ return defs
787
+ // `stableCell` only touches a ref, so it needs no place here.
788
+ }, [columns, rowActions, rowActionsLabel, hasSelection])
789
+
790
+ const table = useTable<TableFeatureSet, TableRow<TData>>({
791
+ features: tableFeatures,
792
+ data: data as TableRow<TData>[],
793
+ columns: columnDefs,
794
+ getRowId: getRowId
795
+ ? (row, index) => getRowId(row, index)
796
+ : undefined,
797
+ state: {
798
+ sorting: sortingState,
799
+ columnFilters,
800
+ // In server-search mode the term never enters table state, so there is
801
+ // nothing here for TanStack to filter by. See `manualFiltering` below.
802
+ globalFilter: enableGlobalFilter && !serverSearch ? globalFilter : undefined,
803
+ columnVisibility,
804
+ // NO PAGINATION MEANS ONE PAGE OF EVERYTHING, SAID EXPLICITLY.
805
+ //
806
+ // In v8 a table without pagination simply had no paginated row model, so
807
+ // `getRowModel()` returned every row. In v9 the row model is registered
808
+ // on the feature set for the whole component, so it applies here too and
809
+ // an omitted `pagination` state falls back to the library default of ten
810
+ // rows — silently hiding row 11 onward on every unpaginated table.
811
+ //
812
+ // `pageSize: Infinity` with `pageIndex: 0` is the documented escape:
813
+ // `createPaginatedRowModel` skips slicing entirely for exactly that pair.
814
+ // (`manualPagination` does NOT do this — that model never consults it.)
815
+ pagination: serverMode
816
+ ? { pageIndex: pagination.pageIndex, pageSize: pagination.pageSize }
817
+ : pagination
818
+ ? clientPagination
819
+ : { pageIndex: 0, pageSize: Number.POSITIVE_INFINITY },
820
+ },
821
+ onSortingChange: serverSorting
822
+ ? (updater) => {
823
+ const next = typeof updater === "function" ? updater(sortingState) : updater
824
+ // Single-column, so the head of the list IS the sort. An empty list
825
+ // is the third click of asc → desc → none: no column chosen, and the
826
+ // direction that goes with it is not meaningful — see the prop docs.
827
+ const [next0] = next
828
+ serverSorting.onSortingChange(
829
+ next0 ? next0.id : null,
830
+ next0?.desc ? "desc" : "asc"
831
+ )
832
+ }
833
+ : setClientSorting,
834
+ onColumnFiltersChange: setColumnFilters,
835
+ onGlobalFilterChange: setGlobalFilter,
836
+ onColumnVisibilityChange: setColumnVisibility,
837
+ onPaginationChange: serverMode
838
+ ? (updater) => {
839
+ const next =
840
+ typeof updater === "function"
841
+ ? updater({ pageIndex: pagination.pageIndex, pageSize: pagination.pageSize })
842
+ : updater
843
+ pagination.onPaginationChange(next.pageIndex, next.pageSize)
844
+ }
845
+ : setClientPagination,
846
+ manualPagination: serverMode,
847
+ /**
848
+ * THIS is what stops the reordering, not the absence of a row model.
849
+ *
850
+ * `sortedRowModel` stays registered on the module-scope `tableFeatures` —
851
+ * it is shared by every table this component renders, so it cannot be
852
+ * withheld per-instance the way v8's per-call `getSortedRowModel()` could.
853
+ * The flag is the per-instance control: v9 gates the pipeline in
854
+ * `table_getSortedRowModel` (`core/row-models/coreRowModelsFeature.utils.js`,
855
+ * table-core 9.2.4), which returns the PRE-sorted model when
856
+ * `manualSorting` is set and never consults the comparator.
857
+ *
858
+ * Drop this flag and the headers keep working and the callback keeps
859
+ * firing, and the rows ALSO get re-sorted locally on top of the server's
860
+ * order — a sort that is nearly right, which is the hardest kind to notice.
861
+ */
862
+ manualSorting: serverSorting != null,
863
+ /*
864
+ * NO `manualFiltering`, deliberately, and it is not an oversight.
865
+ *
866
+ * Re-checked against v9, because v9 splits `columnFilteringFeature` and
867
+ * `globalFilteringFeature` into separate features and the split looks like
868
+ * it should have brought a global-only flag with it. It did not.
869
+ * `manualFiltering` is still the only one, it is still declared on
870
+ * `columnFilteringFeature`, and `globalFilteringFeature` has no manual
871
+ * option at all. The gate is one stage of the shared row-model pipeline —
872
+ * `table_getFilteredRowModel`, documented as "the row model after column
873
+ * AND global filtering" — so setting the flag would take the per-column
874
+ * filter inputs down with the global one, exactly as in v8. Those are used
875
+ * by around eighteen columns across the admin screens, the users table
876
+ * included — the first screen expected to adopt server search — and they
877
+ * would keep rendering and keep accepting text while filtering nothing.
878
+ *
879
+ * Keeping the search term out of `state.globalFilter` (above) achieves what
880
+ * the flag would have achieved for search, and nothing more:
881
+ * `createFilteredRowModel` treats `undefined` as "no global filter" and
882
+ * applies none, while column filters go on working client-side.
883
+ * Server-side column filters are a contract that does not exist yet; when
884
+ * it does, this is where it lands.
885
+ */
886
+ pageCount: serverMode ? pagination.pageCount : undefined,
887
+ columnResizeMode: "onChange",
888
+ enableColumnResizing,
889
+ })
890
+
891
+ if (overrideContent) {
892
+ return <>{overrideContent}</>
893
+ }
894
+
895
+ const filterableColumns = table
896
+ .getAllLeafColumns()
897
+ .filter((column) => column.getCanFilter())
898
+ const hideableColumns = table
899
+ .getAllLeafColumns()
900
+ .filter((column) => column.getCanHide())
901
+
902
+ // ── The phone's list chrome (PwLists) ───────────────────────────────────
903
+ const phoneLabels: DataTablePhoneLabels = { ...sharedPhoneLabels, ...phone?.labels }
904
+ const sortableColumns = table
905
+ .getAllLeafColumns()
906
+ .filter((column) => column.getCanSort() && typeof column.columnDef.header === "string")
907
+ const headerOf = (id: string) => {
908
+ const header = table.getAllLeafColumns().find((column) => column.id === id)?.columnDef.header
909
+ return typeof header === "string" ? header : id
910
+ }
911
+ const ascendingLabel = phoneLabels.ascending ?? ((column: string) => `${column}, lowest first`)
912
+ const descendingLabel = phoneLabels.descending ?? ((column: string) => `${column}, highest first`)
913
+ const currentSort = sortingState[0]
914
+ const currentSortLabel = currentSort
915
+ ? (currentSort.desc ? descendingLabel : ascendingLabel)(headerOf(currentSort.id))
916
+ : (phoneLabels.defaultOrder ?? "Default order")
917
+ const chosenCount = selection?.selected.size ?? 0
918
+ // A choice made on a wider window carries the boxes over to the phone.
919
+ const phoneSelecting = hasSelection && (phoneSelectMode || chosenCount > 0)
920
+ const phoneBottomBar =
921
+ stack && isPhone && (showSearchInput || phone?.filters != null || phone?.mainAction != null)
922
+ const phoneToolbar = stack && isPhone && (sortableColumns.length > 0 || hasSelection)
923
+ const chips = phone?.filters?.chips ?? []
924
+ const pageIds = hasSelection ? pageRowIds(latestCells) : []
925
+ const allOnPageChosen = pageIds.length > 0 && pageIds.every((id) => selection?.selected.has(id))
926
+
927
+ if (isLoading) {
928
+ const visibleCount = table.getVisibleLeafColumns().length
929
+ return (
930
+ <div className={cn("rounded-lg border border-border", className)}>
931
+ {/* `aria-busy` marks this as the PLACEHOLDER, not the data.
932
+ It carries the same `aria-label` as the real table — deliberately,
933
+ so assistive technology names the region consistently while it
934
+ loads — and the consequence is that `getByRole('table', {name})`
935
+ matches this skeleton exactly as it matches a populated table. A
936
+ test written against that selector can be satisfied by five rows of
937
+ grey bars: it passes when the data arrived, when the folder is
938
+ empty and the assertion merely won the race, and when the request
939
+ failed and the retry is in flight. One shipped that way (#1006's
940
+ "the pane is never simply blank" asserted `toBeVisible()` and
941
+ `not.toBeEmpty()` and both were true of THIS markup), passed
942
+ locally, and failed in CI on the one stack where the fetch resolved
943
+ first — which is the only run that was telling the truth.
944
+ `aria-busy` is the standard signal for it and is additive, so no
945
+ existing selector changes. Prefer waiting on a terminal state
946
+ (a row, or the empty state's own text) over waiting on the table. */}
947
+ <Table aria-label={ariaLabel} aria-busy="true">
948
+ <TableHeader>
949
+ <TableRow>
950
+ {columns.map((column, index) => (
951
+ <TableHead key={column.id ?? column.accessorKey ?? index}>
952
+ {column.header}
953
+ </TableHead>
954
+ ))}
955
+ {rowActions && <TableHead>{rowActionsLabel}</TableHead>}
956
+ </TableRow>
957
+ </TableHeader>
958
+ <TableBody>
959
+ {Array.from({ length: 5 }).map((_, rowIndex) => (
960
+ <TableRow key={rowIndex}>
961
+ {Array.from({ length: visibleCount }).map((__, colIndex) => (
962
+ <TableCell key={colIndex}>
963
+ <Skeleton className="h-4 w-3/4" />
964
+ </TableCell>
965
+ ))}
966
+ </TableRow>
967
+ ))}
968
+ </TableBody>
969
+ </Table>
970
+ <span className="sr-only" role="status" aria-live="polite">
971
+ Loading…
972
+ </span>
973
+ </div>
974
+ )
975
+ }
976
+
977
+ const rows = table.getRowModel().rows
978
+
979
+ return (
980
+ <div className={cn("flex flex-col gap-3", className)}>
981
+ {((showSearchInput && !phoneBottomBar) || enableColumnVisibility) && (
982
+ <div className="flex items-center justify-between gap-2">
983
+ {showSearchInput && !phoneBottomBar ? (
984
+ <div className="relative w-full max-w-xs">
985
+ <IconSearch className="pointer-events-none absolute start-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
986
+ <Input
987
+ value={serverSearch ? searchDraft : globalFilter}
988
+ onChange={(event) => handleSearchInput(event.target.value)}
989
+ placeholder={globalFilterPlaceholder}
990
+ className="ps-7"
991
+ />
992
+ </div>
993
+ ) : (
994
+ <div />
995
+ )}
996
+ {enableColumnVisibility && hideableColumns.length > 0 && (
997
+ <DropdownMenu>
998
+ <DropdownMenuTrigger asChild>
999
+ <Button type="button" variant="outline" size="xs">
1000
+ <IconLayoutColumns className="size-3.5" />
1001
+ {columnsMenuLabel}
1002
+ </Button>
1003
+ </DropdownMenuTrigger>
1004
+ <DropdownMenuContent align="end">
1005
+ {hideableColumns.map((column) => (
1006
+ <DropdownMenuCheckboxItem
1007
+ key={column.id}
1008
+ checked={column.getIsVisible()}
1009
+ onCheckedChange={(value) => column.toggleVisibility(!!value)}
1010
+ onSelect={(event) => event.preventDefault()}
1011
+ >
1012
+ {typeof column.columnDef.header === "string"
1013
+ ? column.columnDef.header
1014
+ : column.id}
1015
+ </DropdownMenuCheckboxItem>
1016
+ ))}
1017
+ </DropdownMenuContent>
1018
+ </DropdownMenu>
1019
+ )}
1020
+ </div>
1021
+ )}
1022
+
1023
+ {phoneToolbar && (
1024
+ <div data-slot="data-table-phone-toolbar" className="flex min-h-11 items-center gap-2 sm:hidden">
1025
+ {phoneSelecting ? (
1026
+ <>
1027
+ <Button
1028
+ type="button"
1029
+ variant="ghost"
1030
+ className="text-primary"
1031
+ onClick={() => {
1032
+ setPhoneSelectMode(false)
1033
+ selection?.onSelectedChange(new Set())
1034
+ }}
1035
+ >
1036
+ {phoneLabels.cancel ?? "Cancel"}
1037
+ </Button>
1038
+ <span className="flex-1 text-center text-base font-semibold tabular-nums" aria-live="polite">
1039
+ {phoneLabels.chosen?.(chosenCount) ?? `${chosenCount} chosen`}
1040
+ </span>
1041
+ <Button
1042
+ type="button"
1043
+ variant="ghost"
1044
+ className="text-primary"
1045
+ onClick={() => {
1046
+ const next = new Set(selection?.selected)
1047
+ for (const id of pageIds) {
1048
+ if (allOnPageChosen) next.delete(id)
1049
+ else next.add(id)
1050
+ }
1051
+ selection?.onSelectedChange(next)
1052
+ }}
1053
+ >
1054
+ {allOnPageChosen ? (phoneLabels.clearAll ?? "Clear all") : (phoneLabels.chooseAll ?? "Choose all")}
1055
+ </Button>
1056
+ </>
1057
+ ) : (
1058
+ <>
1059
+ {sortableColumns.length > 0 ? (
1060
+ <Button
1061
+ type="button"
1062
+ variant="ghost"
1063
+ className="min-w-0 gap-1.5 px-2 text-muted-foreground"
1064
+ aria-label={`${phoneLabels.sort ?? "Sort"}: ${currentSortLabel}`}
1065
+ onClick={() => setSortSheetOpen(true)}
1066
+ data-testid="data-table-phone-sort"
1067
+ >
1068
+ <IconArrowsSort className="size-4 shrink-0" />
1069
+ <span className="truncate text-sm">{currentSortLabel}</span>
1070
+ </Button>
1071
+ ) : (
1072
+ <span />
1073
+ )}
1074
+ <span className="flex-1" />
1075
+ {hasSelection && (
1076
+ <Button
1077
+ type="button"
1078
+ variant="ghost"
1079
+ className="text-primary"
1080
+ onClick={() => setPhoneSelectMode(true)}
1081
+ data-testid="data-table-phone-select"
1082
+ >
1083
+ {phoneLabels.select ?? "Select"}
1084
+ </Button>
1085
+ )}
1086
+ </>
1087
+ )}
1088
+ </div>
1089
+ )}
1090
+
1091
+ {stack && isPhone && chips.length > 0 && (
1092
+ <ul className="flex flex-wrap gap-2 sm:hidden" data-slot="data-table-phone-chips">
1093
+ {chips.map((chip) => (
1094
+ <li key={chip.id}>
1095
+ <button
1096
+ type="button"
1097
+ onClick={chip.onRemove}
1098
+ aria-label={phoneLabels.removeFilter?.(chip.label) ?? `Remove filter: ${chip.label}`}
1099
+ className="flex min-h-9 items-center gap-1 rounded-full bg-primary-tint px-3 text-sm text-primary outline-none focus-visible:ring-2 focus-visible:ring-ring"
1100
+ >
1101
+ {chip.label}
1102
+ <IconX className="size-3.5" aria-hidden />
1103
+ </button>
1104
+ </li>
1105
+ ))}
1106
+ </ul>
1107
+ )}
1108
+
1109
+ {errorState ? (
1110
+ <ErrorState {...errorState} />
1111
+ ) : rows.length === 0 ? (
1112
+ <EmptyState title={emptyStateTitle} {...emptyState} />
1113
+ ) : (
1114
+ <div
1115
+ className={cn("rounded-card border border-border bg-card", maxHeight ? "overflow-auto" : "overflow-hidden")}
1116
+ style={maxHeight ? { maxHeight } : undefined}
1117
+ >
1118
+ <Table
1119
+ aria-label={ariaLabel}
1120
+ data-phone-layout={stack ? "stack" : undefined}
1121
+ className={stack ? "max-sm:block max-sm:!w-full max-sm:[&_tbody]:block" : undefined}
1122
+ style={enableColumnResizing ? { width: table.getCenterTotalSize() } : undefined}
1123
+ >
1124
+ <TableHeader className={cn(stickyHeader && "sticky top-0 z-[1]", stack && "max-sm:hidden")}>
1125
+ {table.getHeaderGroups().map((headerGroup) => (
1126
+ <TableRow key={headerGroup.id}>
1127
+ {headerGroup.headers.map((header) => {
1128
+ const canSort = header.column.getCanSort()
1129
+ const sorted = header.column.getIsSorted()
1130
+ const content = (
1131
+ <>
1132
+ {flexRender(header.column.columnDef.header, header.getContext())}
1133
+ {canSort &&
1134
+ (sorted === "asc" ? (
1135
+ <IconChevronUp className="size-3.5" />
1136
+ ) : sorted === "desc" ? (
1137
+ <IconChevronDown className="size-3.5" />
1138
+ ) : (
1139
+ <IconArrowsSort className="size-3.5 opacity-40" />
1140
+ ))}
1141
+ </>
1142
+ )
1143
+ return (
1144
+ <TableHead
1145
+ key={header.id}
1146
+ style={
1147
+ enableColumnResizing ? { width: header.getSize(), position: "relative" } : undefined
1148
+ }
1149
+ className={cn(
1150
+ canSort && "cursor-pointer select-none hover:bg-muted/60"
1151
+ )}
1152
+ /**
1153
+ * WHICH COLUMN IS SORTED, SAID OUT LOUD.
1154
+ *
1155
+ * Read straight off `getIsSorted()`, which is fed by
1156
+ * `state.sorting` — and `sortingState` above resolves that
1157
+ * from `serverSorting` when the caller owns the sort and from
1158
+ * `clientSorting` when this component does. One expression
1159
+ * therefore covers BOTH modes; deriving it from
1160
+ * `clientSorting` instead would have left every
1161
+ * server-sorted table (the ones where the header is the only
1162
+ * route to rows on another page) announcing "not sorted"
1163
+ * while visibly sorted.
1164
+ *
1165
+ * Only on columns that can sort. `aria-sort="none"` on a
1166
+ * fixed column would advertise a control that is not there.
1167
+ */
1168
+ aria-sort={
1169
+ canSort
1170
+ ? sorted === "asc"
1171
+ ? "ascending"
1172
+ : sorted === "desc"
1173
+ ? "descending"
1174
+ : "none"
1175
+ : undefined
1176
+ }
1177
+ /**
1178
+ * THE HANDLER STAYS ON THE CELL — the button below has none,
1179
+ * deliberately.
1180
+ *
1181
+ * A `<button>` activated by Enter or Space dispatches a real
1182
+ * `click` that bubbles, so keyboard activation lands on this
1183
+ * exact handler and does exactly what a mouse click does,
1184
+ * third-click-back-to-unsorted included. Duplicating the
1185
+ * handler onto the button instead would fire it twice for
1186
+ * one mouse click (button, then bubbled to the cell).
1187
+ *
1188
+ * Keeping it here also keeps the WHOLE CELL a click target
1189
+ * rather than shrinking it to the label, which is both the
1190
+ * behaviour 26 callers already have and what every existing
1191
+ * test that clicks `getByRole('columnheader')` exercises.
1192
+ */
1193
+ onClick={header.column.getToggleSortingHandler()}
1194
+ >
1195
+ {canSort ? (
1196
+ /**
1197
+ * The focusable, activatable control the cell itself could
1198
+ * never be (#1129). A `th` takes no keyboard focus and has
1199
+ * no activation behaviour, so before this a keyboard user
1200
+ * could not sort ANY admin table at all.
1201
+ *
1202
+ * Inside the cell rather than instead of it, matching the
1203
+ * W3C APG sortable-table pattern: the `th` keeps its
1204
+ * `columnheader` role and carries `aria-sort`, the button
1205
+ * carries focus and activation.
1206
+ *
1207
+ * NO `aria-label`. It is tempting to name this "Sort by
1208
+ * Email", but a `columnheader`'s name is computed from its
1209
+ * contents and an `aria-label` on a descendant REPLACES
1210
+ * that descendant's contribution — so the cell would stop
1211
+ * being named "Email" and every
1212
+ * `getByRole('columnheader', { name })` selector across the
1213
+ * suites would be asserting against a name no user asked
1214
+ * for. `aria-sort` already carries the state; the role
1215
+ * carries the affordance.
1216
+ *
1217
+ * `cursor-pointer` is not redundant: Tailwind v4's preflight
1218
+ * resets buttons to `cursor: default`, which would undo the
1219
+ * pointer cursor the cell sets.
1220
+ *
1221
+ * RTL: `flex` + `gap` + `text-start` are direction-relative,
1222
+ * so the label leads and the chevron trails on whichever
1223
+ * side "trailing" means, and the symmetric `-mx-1 px-1`
1224
+ * has no side to get wrong. The three icons are vertical
1225
+ * arrows — nothing to mirror.
1226
+ */
1227
+ <button
1228
+ type="button"
1229
+ className="-mx-1 flex min-h-10 cursor-pointer items-center gap-1 rounded-sm px-1 text-start font-medium text-inherit outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
1230
+ >
1231
+ {content}
1232
+ </button>
1233
+ ) : (
1234
+ <div className="flex items-center gap-1">{content}</div>
1235
+ )}
1236
+ {enableColumnResizing && header.column.getCanResize() && (
1237
+ <div
1238
+ onMouseDown={header.getResizeHandler()}
1239
+ onTouchStart={header.getResizeHandler()}
1240
+ className="absolute end-0 top-0 h-full w-1 cursor-col-resize touch-none select-none bg-border/0 hover:bg-ring/50"
1241
+ />
1242
+ )}
1243
+ </TableHead>
1244
+ )
1245
+ })}
1246
+ </TableRow>
1247
+ ))}
1248
+ {filterableColumns.length > 0 && (
1249
+ <TableRow>
1250
+ {table.getHeaderGroups()[0]?.headers.map((header) => {
1251
+ const canFilter = header.column.getCanFilter()
1252
+ const label =
1253
+ typeof header.column.columnDef.header === "string"
1254
+ ? header.column.columnDef.header
1255
+ : header.column.id
1256
+ return (
1257
+ <TableHead key={`filter-${header.id}`} className="py-1.5">
1258
+ {canFilter ? (
1259
+ <Input
1260
+ value={(header.column.getFilterValue() as string) ?? ""}
1261
+ onChange={(event) =>
1262
+ header.column.setFilterValue(event.target.value)
1263
+ }
1264
+ placeholder={columnFilterPlaceholder}
1265
+ aria-label={`Filter ${label}`}
1266
+ className="h-8 text-xs font-normal normal-case tracking-normal"
1267
+ />
1268
+ ) : null}
1269
+ </TableHead>
1270
+ )
1271
+ })}
1272
+ </TableRow>
1273
+ )}
1274
+ </TableHeader>
1275
+ <TableBody>
1276
+ {rows.map((row) => (
1277
+ <TableRow
1278
+ key={row.id}
1279
+ aria-selected={selection ? selection.selected.has(row.id) : undefined}
1280
+ className={cn(
1281
+ onRowClick && "cursor-pointer",
1282
+ selection?.selected.has(row.id) && "bg-primary-tint hover:bg-primary-tint",
1283
+ stack && "max-sm:flex max-sm:flex-wrap max-sm:items-start max-sm:gap-x-3 max-sm:px-4 max-sm:py-3"
1284
+ )}
1285
+ onClick={
1286
+ onRowClick
1287
+ ? (event) => {
1288
+ if (!isInteractiveTarget(event.target)) onRowClick(row.original)
1289
+ }
1290
+ : undefined
1291
+ }
1292
+ >
1293
+ {row.getVisibleCells().map((cell, cellIndex, cells) => {
1294
+ const role = stack ? phoneCellRole(cell.column.id, cellIndex, cells) : undefined
1295
+ const header = cell.column.columnDef.header
1296
+ return (
1297
+ <TableCell
1298
+ key={cell.id}
1299
+ data-label={role === "line" && typeof header === "string" ? header : undefined}
1300
+ className={cn(
1301
+ (cell.column.columnDef.meta as { className?: string } | undefined)?.className,
1302
+ role && PHONE_CELL[role],
1303
+ role === "select" && !phoneSelecting && "max-sm:hidden"
1304
+ )}
1305
+ style={enableColumnResizing ? { width: cell.column.getSize() } : undefined}
1306
+ >
1307
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
1308
+ </TableCell>
1309
+ )
1310
+ })}
1311
+ </TableRow>
1312
+ ))}
1313
+ </TableBody>
1314
+ {totals && (
1315
+ <TableFooter>
1316
+ <TableRow>
1317
+ {hasSelection && <TableCell />}
1318
+ {totals.map((cell, index) => (
1319
+ <TableCell key={index} className="font-medium">
1320
+ {cell}
1321
+ </TableCell>
1322
+ ))}
1323
+ {rowActions && <TableCell />}
1324
+ </TableRow>
1325
+ </TableFooter>
1326
+ )}
1327
+ </Table>
1328
+ </div>
1329
+ )}
1330
+
1331
+ {selection && selection.selected.size > 0 && (
1332
+ <BulkBar selection={selection} data={data} getRowId={getRowId} phone={stack} />
1333
+ )}
1334
+
1335
+ {phoneBottomBar && !phoneSelecting && (
1336
+ <div
1337
+ data-slot="data-table-phone-bar"
1338
+ className="sticky bottom-0 z-[3] -mx-4 flex items-center gap-2 border-t border-border bg-card px-4 py-2 sm:hidden"
1339
+ >
1340
+ {showSearchInput ? (
1341
+ <div className="relative min-w-0 flex-1">
1342
+ <IconSearch className="pointer-events-none absolute start-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
1343
+ <Input
1344
+ type="search"
1345
+ value={serverSearch ? searchDraft : globalFilter}
1346
+ onChange={(event) => handleSearchInput(event.target.value)}
1347
+ placeholder={globalFilterPlaceholder}
1348
+ aria-label={globalFilterPlaceholder}
1349
+ className="h-11 ps-9 text-base"
1350
+ />
1351
+ </div>
1352
+ ) : (
1353
+ <span className="flex-1" />
1354
+ )}
1355
+ {phone?.filters && (
1356
+ <Button
1357
+ type="button"
1358
+ variant="outline"
1359
+ className="h-11 gap-1.5"
1360
+ onClick={() => setFilterSheetOpen(true)}
1361
+ data-testid="data-table-phone-filter"
1362
+ >
1363
+ <IconFilter className="size-4" />
1364
+ {phoneLabels.filter ?? "Filter"}
1365
+ {chips.length > 0 && <span className="tabular-nums">({chips.length})</span>}
1366
+ </Button>
1367
+ )}
1368
+ {phone?.mainAction &&
1369
+ (phone.mainAction.href ? (
1370
+ <a
1371
+ href={phone.mainAction.href}
1372
+ aria-label={phone.mainAction.label}
1373
+ className="grid size-11 shrink-0 place-items-center rounded-control-lg bg-primary text-primary-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
1374
+ >
1375
+ <IconPlus className="size-5" />
1376
+ </a>
1377
+ ) : (
1378
+ <Button
1379
+ type="button"
1380
+ aria-label={phone.mainAction.label}
1381
+ onClick={phone.mainAction.onClick}
1382
+ className="size-11 shrink-0 p-0"
1383
+ >
1384
+ <IconPlus className="size-5" />
1385
+ </Button>
1386
+ ))}
1387
+ </div>
1388
+ )}
1389
+
1390
+ {stack && isPhone && sortableColumns.length > 0 && (
1391
+ <Sheet open={sortSheetOpen} onOpenChange={setSortSheetOpen}>
1392
+ <SheetContent side="bottom" className="gap-3 rounded-t-2xl pb-[calc(1.25rem+env(safe-area-inset-bottom))] text-base">
1393
+ <SheetHeader>
1394
+ <SheetTitle className="text-lg font-semibold">{phoneLabels.sortTitle ?? "Sort"}</SheetTitle>
1395
+ <SheetDescription className="sr-only">{currentSortLabel}</SheetDescription>
1396
+ </SheetHeader>
1397
+ <ul className="divide-y divide-border overflow-hidden rounded-xl border border-border" role="radiogroup">
1398
+ {[
1399
+ { key: "none", label: phoneLabels.defaultOrder ?? "Default order", id: null as string | null, desc: false },
1400
+ ...sortableColumns.flatMap((column) => {
1401
+ const header = headerOf(column.id)
1402
+ return [
1403
+ { key: `${column.id}:asc`, label: ascendingLabel(header), id: column.id as string | null, desc: false },
1404
+ { key: `${column.id}:desc`, label: descendingLabel(header), id: column.id as string | null, desc: true },
1405
+ ]
1406
+ }),
1407
+ ].map((option) => {
1408
+ const on =
1409
+ option.id === null
1410
+ ? !currentSort
1411
+ : currentSort?.id === option.id && !!currentSort.desc === option.desc
1412
+ return (
1413
+ <li key={option.key}>
1414
+ <button
1415
+ type="button"
1416
+ role="radio"
1417
+ aria-checked={on}
1418
+ onClick={() => {
1419
+ table.setSorting(option.id === null ? [] : [{ id: option.id, desc: option.desc }])
1420
+ setSortSheetOpen(false)
1421
+ }}
1422
+ className="flex min-h-12 w-full items-center gap-3 px-4 text-start outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
1423
+ >
1424
+ <span className="flex-1">{option.label}</span>
1425
+ {on && <IconCheck className="size-4 text-primary" aria-hidden />}
1426
+ </button>
1427
+ </li>
1428
+ )
1429
+ })}
1430
+ </ul>
1431
+ </SheetContent>
1432
+ </Sheet>
1433
+ )}
1434
+
1435
+ {stack && isPhone && phone?.filters && (
1436
+ <Sheet open={filterSheetOpen} onOpenChange={setFilterSheetOpen}>
1437
+ <SheetContent side="bottom" className="gap-4 rounded-t-2xl pb-[calc(1.25rem+env(safe-area-inset-bottom))] text-base">
1438
+ <SheetHeader>
1439
+ <SheetTitle className="text-lg font-semibold">{phoneLabels.filtersTitle ?? "Filters"}</SheetTitle>
1440
+ <SheetDescription className="sr-only">{phoneLabels.filtersTitle ?? "Filters"}</SheetDescription>
1441
+ </SheetHeader>
1442
+ <div className="flex flex-col gap-3">{phone.filters.content}</div>
1443
+ <div className="flex gap-2">
1444
+ {phone.filters.onClear && (
1445
+ <Button type="button" variant="outline" className="h-11 flex-1" onClick={phone.filters.onClear}>
1446
+ {phoneLabels.clearFilters ?? "Clear all"}
1447
+ </Button>
1448
+ )}
1449
+ <Button type="button" className="h-11 flex-[2]" onClick={() => setFilterSheetOpen(false)}>
1450
+ {phoneLabels.done ?? "Done"}
1451
+ </Button>
1452
+ </div>
1453
+ </SheetContent>
1454
+ </Sheet>
1455
+ )}
1456
+
1457
+ {pagination && rows.length > 0 && (
1458
+ <Pagination
1459
+ page={table.state.pagination.pageIndex + 1}
1460
+ perPage={table.state.pagination.pageSize}
1461
+ total={serverMode ? pagination.total : table.getFilteredRowModel().rows.length}
1462
+ onPageChange={(nextPage) => table.setPageIndex(nextPage - 1)}
1463
+ {...paginationLabels}
1464
+ />
1465
+ )}
1466
+ </div>
1467
+ )
1468
+ }
1469
+
1470
+ /* ──────────────────────────────────────────────────────────────────────────
1471
+ * The CALLER's half of server mode
1472
+ * ────────────────────────────────────────────────────────────────────────── */
1473
+
1474
+ /**
1475
+ * One list request's page, sort and search — the client mirror of the server's
1476
+ * `ListQuery` (`src/Http/ListQuery.php`).
1477
+ *
1478
+ * `sort`/`dir` and `q` are OPTIONAL, and their absence is meaningful rather than
1479
+ * a default nobody filled in. Sending `sort=` with nothing in it, or `dir=asc`
1480
+ * with no column, would have the endpoint order by something the UI invented;
1481
+ * leaving them out is how a caller says "use your own default order", which is
1482
+ * the only honest thing to say when no column is chosen.
1483
+ */
1484
+ export interface DataTableQueryRequest {
1485
+ /** 1-based, the way the endpoints count pages. */
1486
+ page: number
1487
+ perPage: number
1488
+ /** The ENDPOINT's sort key (not the column id) — absent when none is chosen. */
1489
+ sort?: string
1490
+ /** Absent exactly when `sort` is. */
1491
+ dir?: "asc" | "desc"
1492
+ /** Absent when there is nothing to search for. */
1493
+ q?: string
1494
+ }
1495
+
1496
+ /**
1497
+ * A {@link DataTableQueryRequest} as a query string, no leading `?`.
1498
+ *
1499
+ * Written here rather than at each screen so the "absent means absent" rule
1500
+ * above is applied once: a helper that always set `sort` and `dir` would undo
1501
+ * the whole point of making them optional.
1502
+ */
1503
+ export function dataTableQueryString(request: DataTableQueryRequest): string {
1504
+ const params = new URLSearchParams()
1505
+ params.set("page", String(request.page))
1506
+ params.set("per_page", String(request.perPage))
1507
+ if (request.sort !== undefined && request.sort !== "") {
1508
+ params.set("sort", request.sort)
1509
+ params.set("dir", request.dir ?? "asc")
1510
+ }
1511
+ if (request.q !== undefined && request.q !== "") {
1512
+ params.set("q", request.q)
1513
+ }
1514
+ return params.toString()
1515
+ }
1516
+
1517
+ /** Rows per page for a server-driven admin list, matching the API's own default. */
1518
+ export const DEFAULT_DATA_TABLE_PER_PAGE = 25
1519
+
1520
+ export interface UseDataTableQueryOptions {
1521
+ /** Rows per request. Defaults to {@link DEFAULT_DATA_TABLE_PER_PAGE}. */
1522
+ perPage?: number
1523
+ /**
1524
+ * The COLUMN ID the table starts sorted by. Omit — the default — to start
1525
+ * with no column chosen, so the first request carries no `sort` and the
1526
+ * reader gets the endpoint's own default ordering. Naming one here just to
1527
+ * restate that default would be a claim the UI cannot keep if the endpoint's
1528
+ * default ever moves.
1529
+ */
1530
+ initialSortKey?: string | null
1531
+ initialDirection?: "asc" | "desc"
1532
+ /**
1533
+ * Column id → the endpoint's `sort` key, for the columns whose names differ.
1534
+ * Identity for anything absent, which is why this holds the RENAMES only.
1535
+ *
1536
+ * The two vocabularies are genuinely separate. A column id is whatever the
1537
+ * screen called it (`accountStatus`, `createdAt`, `ruleLabel`); the sort key
1538
+ * is whatever that endpoint's `ListSpec` declared (`status`, `created`,
1539
+ * `rule`). Getting it wrong is an error nowhere: `ListQuery` reads an unknown
1540
+ * key as "no sort was asked for" and falls back to the endpoint's default, so
1541
+ * the column would look sortable, respond to clicks, and quietly reorder
1542
+ * nothing. Only mark a column `enableSorting` when that endpoint's spec
1543
+ * actually offers the key it maps to.
1544
+ */
1545
+ sortKeys?: Record<string, string>
1546
+ /** Forwarded to {@link DataTableServerSearch.debounceMs}. */
1547
+ searchDebounceMs?: number
1548
+ }
1549
+
1550
+ /**
1551
+ * The page/sort/search state of ONE server-driven table, plus the three props
1552
+ * {@link DataTable} needs to render it.
1553
+ */
1554
+ export interface DataTableQuery {
1555
+ /** What to ask the endpoint for. Thread it through EVERY request. */
1556
+ request: DataTableQueryRequest
1557
+ /** 1-based current page, for a caller that needs it outside `request`. */
1558
+ page: number
1559
+ setPage: (page: number) => void
1560
+ /** Hand straight to `<DataTable sorting={…}>`. */
1561
+ sorting: DataTableServerSorting
1562
+ /** Hand straight to `<DataTable search={…}>`. */
1563
+ search: DataTableServerSearch
1564
+ /** Build `<DataTable pagination={…}>` once the response's totals are known. */
1565
+ pagination: (meta: { total: number; totalPages: number }) => DataTableServerPagination
1566
+ }
1567
+
1568
+ /**
1569
+ * Hold a server-driven table's page, sort and search in one place.
1570
+ *
1571
+ * WHY A HOOK RATHER THAN THREE `useState` CALLS PER SCREEN. Changing the sort or
1572
+ * the search term invalidates the current page offset, and resetting to page 1
1573
+ * is the CALLER's job because the caller owns the pagination state (see
1574
+ * {@link DataTableServerSorting.onSortingChange}). Written out per screen that
1575
+ * reset is one line every screen has to remember, and nothing notices its
1576
+ * absence until somebody on page 7 searches for a term with three matches and
1577
+ * gets an empty table with nothing on screen explaining it. Here it is written
1578
+ * once and cannot be forgotten.
1579
+ *
1580
+ * It also owns the rule that is easiest to get subtly wrong: a `sortKey` of null
1581
+ * — the third click of asc → desc → none — must send NO `sort` and NO `dir`, so
1582
+ * the endpoint applies its own default ordering rather than one this component
1583
+ * made up.
1584
+ *
1585
+ * Debouncing is NOT here: {@link DataTableServerSearch} already debounces the
1586
+ * input, and a second timer on top would make the table lag a keystroke behind
1587
+ * for no benefit at all.
1588
+ *
1589
+ * ```tsx
1590
+ * const query = useDataTableQuery({ sortKeys: { accountStatus: 'status' } })
1591
+ * const queryString = dataTableQueryString(query.request)
1592
+ * const { data } = useFetch(() => fetchUsers(queryString), [queryString])
1593
+ * <DataTable
1594
+ * sorting={query.sorting}
1595
+ * search={query.search}
1596
+ * pagination={query.pagination({ total, totalPages })}
1597
+ * />
1598
+ * ```
1599
+ */
1600
+ export function useDataTableQuery({
1601
+ perPage: initialPerPage = DEFAULT_DATA_TABLE_PER_PAGE,
1602
+ initialSortKey = null,
1603
+ initialDirection = "asc",
1604
+ sortKeys,
1605
+ searchDebounceMs,
1606
+ }: UseDataTableQueryOptions = {}): DataTableQuery {
1607
+ const [page, setPage] = React.useState(1)
1608
+ const [perPage, setPerPage] = React.useState(initialPerPage)
1609
+ const [sortKey, setSortKey] = React.useState<string | null>(initialSortKey)
1610
+ const [direction, setDirection] = React.useState<"asc" | "desc">(initialDirection)
1611
+ const [search, setSearch] = React.useState("")
1612
+
1613
+ const endpointSort = sortKey === null ? undefined : (sortKeys?.[sortKey] ?? sortKey)
1614
+
1615
+ const request: DataTableQueryRequest = {
1616
+ page,
1617
+ perPage,
1618
+ ...(endpointSort === undefined ? {} : { sort: endpointSort, dir: direction }),
1619
+ ...(search === "" ? {} : { q: search }),
1620
+ }
1621
+
1622
+ return {
1623
+ request,
1624
+ page,
1625
+ setPage,
1626
+ sorting: {
1627
+ sortKey,
1628
+ direction,
1629
+ onSortingChange: (nextSortKey, nextDirection) => {
1630
+ setSortKey(nextSortKey)
1631
+ setDirection(nextDirection)
1632
+ // The reset this hook exists for. Page 7 of the old ordering is not
1633
+ // page 7 of the new one — it is an arbitrary window into a different
1634
+ // list.
1635
+ setPage(1)
1636
+ },
1637
+ },
1638
+ search: {
1639
+ value: search,
1640
+ debounceMs: searchDebounceMs,
1641
+ onSearchChange: (next) => {
1642
+ setSearch(next)
1643
+ // Same reason, more visibly: a search that narrows the list to three
1644
+ // rows has no page 7 at all, so staying there renders an empty table.
1645
+ setPage(1)
1646
+ },
1647
+ },
1648
+ pagination: ({ total, totalPages }) => ({
1649
+ pageIndex: page - 1,
1650
+ pageSize: perPage,
1651
+ pageCount: totalPages,
1652
+ total,
1653
+ onPaginationChange: (nextPageIndex, nextPageSize) => {
1654
+ setPage(nextPageIndex + 1)
1655
+ setPerPage(nextPageSize)
1656
+ },
1657
+ }),
1658
+ }
1659
+ }
1660
+
1661
+ /* ──────────────────────────────────────────────────────────────────────────
1662
+ * The phone layout of a row (below 640px, `phoneLayout="stack"`).
1663
+ *
1664
+ * The row becomes a wrapping flex box: the checkbox (if any), the first
1665
+ * column as the title and the row's actions share the top line (`order`
1666
+ * moves the actions up from the end of the row); every other
1667
+ * column is a full-width line with its header as a muted label at the start
1668
+ * and the value at the end. The header row is hidden, since each line now
1669
+ * names itself. Classes only, so the markup and every selector stay the same.
1670
+ * ────────────────────────────────────────────────────────────────────────── */
1671
+ type PhoneCellRole = "select" | "title" | "actions" | "line"
1672
+
1673
+ const PHONE_CELL: Record<PhoneCellRole, string> = {
1674
+ select: "max-sm:order-1 max-sm:h-auto max-sm:p-0 max-sm:pt-0.5",
1675
+ title: "max-sm:order-2 max-sm:h-auto max-sm:min-w-0 max-sm:flex-1 max-sm:overflow-hidden max-sm:p-0 max-sm:whitespace-normal max-sm:font-medium",
1676
+ actions: "max-sm:order-3 max-sm:ms-auto max-sm:h-auto max-sm:p-0",
1677
+ line:
1678
+ "max-sm:order-4 max-sm:flex max-sm:h-auto max-sm:min-w-0 max-sm:basis-full max-sm:items-baseline max-sm:justify-between max-sm:gap-3 max-sm:p-0 max-sm:pt-1.5 max-sm:text-end max-sm:whitespace-normal max-sm:break-words max-sm:before:shrink-0 max-sm:before:text-start max-sm:before:text-muted-foreground max-sm:before:content-[attr(data-label)]",
1679
+ }
1680
+
1681
+ function phoneCellRole(columnId: string, index: number, cells: { column: { id: string } }[]): PhoneCellRole {
1682
+ if (columnId === "__select") return "select"
1683
+ if (columnId === "__row-actions") return "actions"
1684
+ const firstData = cells.findIndex((c) => c.column.id !== "__select" && c.column.id !== "__row-actions")
1685
+ return index === firstData ? "title" : "line"
1686
+ }