@dashforge/tw 0.5.0-beta → 0.7.0-beta

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 (105) hide show
  1. package/CHANGELOG.md +526 -0
  2. package/THEME-AUDIT.md +175 -0
  3. package/dist/index.esm.js +2504 -51
  4. package/dist/src/components/Accordion/accordion.variants.d.ts.map +1 -1
  5. package/dist/src/components/Box/box.variants.d.ts.map +1 -1
  6. package/dist/src/components/DataGrid/DataGrid.d.ts +29 -0
  7. package/dist/src/components/DataGrid/DataGrid.d.ts.map +1 -0
  8. package/dist/src/components/DataGrid/dataGrid.types.d.ts +171 -0
  9. package/dist/src/components/DataGrid/dataGrid.types.d.ts.map +1 -0
  10. package/dist/src/components/DataGrid/dataGrid.variants.d.ts +216 -0
  11. package/dist/src/components/DataGrid/dataGrid.variants.d.ts.map +1 -0
  12. package/dist/src/components/Dialog/dialog.variants.d.ts.map +1 -1
  13. package/dist/src/components/Divider/divider.variants.d.ts.map +1 -1
  14. package/dist/src/components/Pagination/Pagination.d.ts.map +1 -1
  15. package/dist/src/components/Pagination/pagination.variants.d.ts.map +1 -1
  16. package/dist/src/components/Popover/popover.variants.d.ts.map +1 -1
  17. package/dist/src/components/Skeleton/skeleton.variants.d.ts.map +1 -1
  18. package/dist/src/components/Table/Table.d.ts +24 -0
  19. package/dist/src/components/Table/Table.d.ts.map +1 -0
  20. package/dist/src/components/Table/cells/RenderButton.d.ts +13 -0
  21. package/dist/src/components/Table/cells/RenderButton.d.ts.map +1 -0
  22. package/dist/src/components/Table/cells/RenderChip.d.ts +80 -0
  23. package/dist/src/components/Table/cells/RenderChip.d.ts.map +1 -0
  24. package/dist/src/components/Table/cells/RenderText.d.ts +21 -0
  25. package/dist/src/components/Table/cells/RenderText.d.ts.map +1 -0
  26. package/dist/src/components/Table/cells/RenderTwoLine.d.ts +20 -0
  27. package/dist/src/components/Table/cells/RenderTwoLine.d.ts.map +1 -0
  28. package/dist/src/components/Table/cells/RowActionsMenu.d.ts +36 -0
  29. package/dist/src/components/Table/cells/RowActionsMenu.d.ts.map +1 -0
  30. package/dist/src/components/Table/cells/index.d.ts +11 -0
  31. package/dist/src/components/Table/cells/index.d.ts.map +1 -0
  32. package/dist/src/components/Table/table.types.d.ts +312 -0
  33. package/dist/src/components/Table/table.types.d.ts.map +1 -0
  34. package/dist/src/components/Table/table.variants.d.ts +285 -0
  35. package/dist/src/components/Table/table.variants.d.ts.map +1 -0
  36. package/dist/src/components/Tabs/tabs.variants.d.ts.map +1 -1
  37. package/dist/src/components/Tooltip/tooltip.variants.d.ts.map +1 -1
  38. package/dist/src/components/Typography/typography.variants.d.ts.map +1 -1
  39. package/dist/src/components/_shared/data/getNestedValue.d.ts +20 -0
  40. package/dist/src/components/_shared/data/getNestedValue.d.ts.map +1 -0
  41. package/dist/src/components/_shared/data/useColumnAutoDetect.d.ts +45 -0
  42. package/dist/src/components/_shared/data/useColumnAutoDetect.d.ts.map +1 -0
  43. package/dist/src/components/_shared/data/useControllableState.d.ts +23 -0
  44. package/dist/src/components/_shared/data/useControllableState.d.ts.map +1 -0
  45. package/dist/src/components/_shared/data/useDebouncedValue.d.ts +10 -0
  46. package/dist/src/components/_shared/data/useDebouncedValue.d.ts.map +1 -0
  47. package/dist/src/components/_shared/data/useTableFilter.d.ts +13 -0
  48. package/dist/src/components/_shared/data/useTableFilter.d.ts.map +1 -0
  49. package/dist/src/components/_shared/data/useTableSearch.d.ts +23 -0
  50. package/dist/src/components/_shared/data/useTableSearch.d.ts.map +1 -0
  51. package/dist/src/components/_shared/data/useTableSelection.d.ts +25 -0
  52. package/dist/src/components/_shared/data/useTableSelection.d.ts.map +1 -0
  53. package/dist/src/components/_shared/data/useTableSort.d.ts +20 -0
  54. package/dist/src/components/_shared/data/useTableSort.d.ts.map +1 -0
  55. package/dist/src/components/_shared/data/useVirtualizer.d.ts +107 -0
  56. package/dist/src/components/_shared/data/useVirtualizer.d.ts.map +1 -0
  57. package/dist/src/index.d.ts +10 -1
  58. package/dist/src/index.d.ts.map +1 -1
  59. package/package.json +3 -3
  60. package/src/components/Accordion/accordion.variants.ts +5 -3
  61. package/src/components/Box/Box.test.tsx +32 -11
  62. package/src/components/Box/box.variants.ts +23 -4
  63. package/src/components/DataGrid/DataGrid.test.tsx +496 -0
  64. package/src/components/DataGrid/DataGrid.tsx +831 -0
  65. package/src/components/DataGrid/dataGrid.types.ts +189 -0
  66. package/src/components/DataGrid/dataGrid.variants.ts +144 -0
  67. package/src/components/Dialog/dialog.variants.ts +10 -6
  68. package/src/components/Divider/Divider.test.tsx +3 -1
  69. package/src/components/Divider/Divider.tsx +1 -1
  70. package/src/components/Divider/divider.variants.ts +2 -1
  71. package/src/components/Pagination/Pagination.tsx +3 -1
  72. package/src/components/Pagination/pagination.variants.ts +19 -13
  73. package/src/components/Popover/popover.variants.ts +10 -4
  74. package/src/components/Skeleton/skeleton.variants.ts +2 -1
  75. package/src/components/Table/Table.test.tsx +603 -0
  76. package/src/components/Table/Table.tsx +816 -0
  77. package/src/components/Table/cells/RenderButton.tsx +23 -0
  78. package/src/components/Table/cells/RenderChip.tsx +103 -0
  79. package/src/components/Table/cells/RenderText.tsx +37 -0
  80. package/src/components/Table/cells/RenderTwoLine.tsx +34 -0
  81. package/src/components/Table/cells/RowActionsMenu.tsx +147 -0
  82. package/src/components/Table/cells/index.ts +14 -0
  83. package/src/components/Table/table.types.ts +346 -0
  84. package/src/components/Table/table.variants.ts +207 -0
  85. package/src/components/Tabs/tabs.variants.ts +19 -8
  86. package/src/components/Tooltip/tooltip.variants.ts +12 -2
  87. package/src/components/Typography/Typography.test.tsx +3 -1
  88. package/src/components/Typography/typography.variants.ts +6 -2
  89. package/src/components/_shared/data/getNestedValue.test.ts +50 -0
  90. package/src/components/_shared/data/getNestedValue.ts +32 -0
  91. package/src/components/_shared/data/useColumnAutoDetect.test.ts +123 -0
  92. package/src/components/_shared/data/useColumnAutoDetect.ts +100 -0
  93. package/src/components/_shared/data/useControllableState.ts +48 -0
  94. package/src/components/_shared/data/useDebouncedValue.ts +24 -0
  95. package/src/components/_shared/data/useTableFilter.ts +37 -0
  96. package/src/components/_shared/data/useTableSearch.test.ts +115 -0
  97. package/src/components/_shared/data/useTableSearch.ts +66 -0
  98. package/src/components/_shared/data/useTableSelection.test.ts +100 -0
  99. package/src/components/_shared/data/useTableSelection.ts +100 -0
  100. package/src/components/_shared/data/useTableSort.test.ts +150 -0
  101. package/src/components/_shared/data/useTableSort.ts +141 -0
  102. package/src/components/_shared/data/useVirtualizer.test.ts +158 -0
  103. package/src/components/_shared/data/useVirtualizer.ts +199 -0
  104. package/src/components/_shared/themeIdentity.test.ts +113 -0
  105. package/src/index.ts +59 -1
@@ -0,0 +1,831 @@
1
+ import { useMemo, type ReactNode, type MouseEvent } from 'react';
2
+ import { cn } from '../../utils/cn.js';
3
+ import { useAccessState } from '../../hooks/useAccessState.js';
4
+ import { Skeleton } from '../Skeleton/Skeleton.js';
5
+ import { Pagination } from '../Pagination/Pagination.js';
6
+ import { dataGridVariants } from './dataGrid.variants.js';
7
+ import { useControllableState } from '../_shared/data/useControllableState.js';
8
+ import { useDebouncedValue } from '../_shared/data/useDebouncedValue.js';
9
+ import { useTableSearch } from '../_shared/data/useTableSearch.js';
10
+ import { useTableFilter } from '../_shared/data/useTableFilter.js';
11
+ import { useTableSort, cycleSortFor } from '../_shared/data/useTableSort.js';
12
+ import { useTableSelection } from '../_shared/data/useTableSelection.js';
13
+ import { getNestedValue } from '../_shared/data/getNestedValue.js';
14
+ import { useVirtualizer } from '../_shared/data/useVirtualizer.js';
15
+ import {
16
+ useColumnAutoDetect,
17
+ resolveAlign,
18
+ resolveMonospace,
19
+ resolveTabularNums,
20
+ } from '../_shared/data/useColumnAutoDetect.js';
21
+ import type {
22
+ TableColumn,
23
+ TableSortModel,
24
+ TableFilterModel,
25
+ TableLabels,
26
+ } from '../Table/table.types.js';
27
+ import type { DataGridProps } from './dataGrid.types.js';
28
+
29
+ const DEFAULT_LABELS: Required<TableLabels> = {
30
+ searchPlaceholder: 'Search...',
31
+ noData: 'No data',
32
+ loading: 'Loading…',
33
+ ariaSortNone: 'Not sorted. Click to sort ascending.',
34
+ ariaSortAscending: 'Sorted ascending. Click to sort descending.',
35
+ ariaSortDescending: 'Sorted descending. Click to clear sort.',
36
+ ariaSelectRow: 'Select row',
37
+ ariaSelectAllRows: 'Select all rows',
38
+ ariaExpandRow: 'Expand row',
39
+ ariaCollapseRow: 'Collapse row',
40
+ selectedCount: '{count} selected',
41
+ clearSelection: 'Clear selection',
42
+ filterColumn: 'Filter',
43
+ filterApply: 'Apply',
44
+ filterClear: 'Clear',
45
+ density: 'Density',
46
+ densityCompact: 'Compact',
47
+ densityComfortable: 'Comfortable',
48
+ densitySpacious: 'Spacious',
49
+ };
50
+
51
+ /**
52
+ * Dashforge TW `<DataGrid>` — virtualized data table.
53
+ *
54
+ * Companion to `<Table>` for large data sets (~500+ rows up to
55
+ * millions via virtualization). Same column model, sort/search/
56
+ * filter/selection logic (shared via `_shared/data/` helpers) —
57
+ * differs in render path: only the visible window of rows is mounted
58
+ * in DOM, with spacer `<tr>` above and below to preserve scrollbar
59
+ * size.
60
+ *
61
+ * Virtualization: hand-rolled (`useVirtualizer`) using
62
+ * `IntersectionObserver` + scroll-event + `requestAnimationFrame`
63
+ * debounce + `ResizeObserver`. Zero new runtime deps.
64
+ *
65
+ * Server-side mode (4 independent opt-in flags):
66
+ * - `serverSideSort` — emits `onSortChange` but does NOT sort locally
67
+ * - `serverSideFilter` — emits `onFilterChange` but does NOT filter
68
+ * - `serverSideSearch` — emits `onSearchQueryChange` (debounced)
69
+ * - `serverSidePagination` — `totalCount` prop sizes the virtual
70
+ * scrollbar; `rows` is the page slice from the server
71
+ *
72
+ * Selection at scale: `selectAllScope`:
73
+ * - `'allLoaded'` (default) — header checkbox toggles all rows in
74
+ * `rows` prop
75
+ * - `'visible'` — toggles only the current viewport window
76
+ */
77
+ export function DataGrid<T extends object>(props: DataGridProps<T>) {
78
+ const {
79
+ rows,
80
+ cols,
81
+ getRowId,
82
+ totalCount: totalCountProp,
83
+
84
+ rowHeight,
85
+ overscan = 5,
86
+ height,
87
+
88
+ sortModel: sortModelProp,
89
+ onSortChange,
90
+ defaultSortModel,
91
+ serverSideSort = false,
92
+
93
+ enableSearch = false,
94
+ searchQuery: searchQueryProp,
95
+ onSearchQueryChange,
96
+ searchPlaceholder,
97
+ searchDebounceMs = 200,
98
+ serverSideSearch = false,
99
+
100
+ filterModel: filterModelProp,
101
+ onFilterChange,
102
+ serverSideFilter = false,
103
+
104
+ rowSelection = 'none',
105
+ selectedRowIds: selectedRowIdsProp,
106
+ onSelectionChange,
107
+ bulkActions,
108
+ selectAllScope = 'allLoaded',
109
+
110
+ pagination,
111
+ serverSidePagination = false,
112
+
113
+ rowActions,
114
+
115
+ loading = false,
116
+ loadingRowCount = 8,
117
+ emptyState,
118
+
119
+ stickyHeader = true,
120
+ caption,
121
+ showCaption = false,
122
+
123
+ access: gridAccess,
124
+
125
+ labels: labelsProp,
126
+
127
+ variant,
128
+ size,
129
+ density,
130
+
131
+ sx,
132
+ slotProps,
133
+ } = props;
134
+
135
+ const labels = { ...DEFAULT_LABELS, ...labelsProp };
136
+ const gridAccessState = useAccessState(gridAccess);
137
+
138
+ // ───── Controllable state ─────
139
+
140
+ const [sortModel, setSortModel] = useControllableState<TableSortModel>({
141
+ controlledValue: sortModelProp,
142
+ defaultValue: defaultSortModel ?? [],
143
+ onChange: onSortChange,
144
+ });
145
+ const [searchQuery, setSearchQuery] = useControllableState<string>({
146
+ controlledValue: searchQueryProp,
147
+ defaultValue: '',
148
+ onChange: onSearchQueryChange,
149
+ });
150
+ // filterModel: read-only in v1 (no in-table filter UI; deferred to
151
+ // v1-bis). Consumer wires it via filterModelProp + onFilterChange.
152
+ void onFilterChange;
153
+ const filterModel: TableFilterModel = filterModelProp ?? [];
154
+ const [selectedRowIds, setSelectedRowIds] = useControllableState<string[]>({
155
+ controlledValue: selectedRowIdsProp,
156
+ defaultValue: [],
157
+ onChange: onSelectionChange,
158
+ });
159
+
160
+ // ───── RBAC: filter columns ─────
161
+ const visibleCols = useMemo(
162
+ () =>
163
+ cols.filter(
164
+ (col) => !col.access || col.access.onUnauthorized !== 'hide',
165
+ ),
166
+ [cols],
167
+ );
168
+
169
+ // ───── Smart-default column types ─────
170
+ const columnTypes = useColumnAutoDetect(rows, visibleCols);
171
+
172
+ // ───── Pipeline: search → filter → sort (skip when server-side) ─────
173
+ //
174
+ // Each pipeline hook is ALWAYS called (React hooks rules). The
175
+ // server-side flags decide whether to use the local-computed result
176
+ // or pass the upstream rows through unchanged. The hooks are
177
+ // `useMemo`-based internally so they're cheap when their inputs
178
+ // are unchanged.
179
+
180
+ const debouncedSearchQuery = useDebouncedValue(searchQuery, searchDebounceMs);
181
+ const localSearched = useTableSearch(rows, visibleCols, debouncedSearchQuery);
182
+ const searchedRows = serverSideSearch ? rows : localSearched;
183
+
184
+ const localFiltered = useTableFilter(searchedRows, filterModel);
185
+ const filteredRows = serverSideFilter ? searchedRows : localFiltered;
186
+
187
+ const localSorted = useTableSort(filteredRows, visibleCols, sortModel);
188
+ const sortedRows = serverSideSort ? filteredRows : localSorted;
189
+
190
+ // ───── Virtualization ─────
191
+
192
+ // Effective row count for the virtual scrollbar:
193
+ // - Client-side: actual sorted rows count
194
+ // - Server-side pagination: caller-provided totalCount
195
+ const effectiveTotalCount = serverSidePagination
196
+ ? totalCountProp ?? sortedRows.length
197
+ : sortedRows.length;
198
+
199
+ const initialViewportHeight = height ? parseInt(height, 10) || 400 : 400;
200
+ const { scrollRef, window: vWindow } = useVirtualizer({
201
+ totalCount: effectiveTotalCount,
202
+ rowHeight,
203
+ overscan,
204
+ initialViewportHeight,
205
+ });
206
+
207
+ // The rows actually mounted in DOM.
208
+ const renderedRows = useMemo(() => {
209
+ if (serverSidePagination) {
210
+ // In server-side pagination, `rows` IS the page slice; we
211
+ // render all of it (virtualization within the page is still
212
+ // useful for very large page sizes).
213
+ return rows.slice(vWindow.startIndex, vWindow.endIndex + 1);
214
+ }
215
+ return sortedRows.slice(vWindow.startIndex, vWindow.endIndex + 1);
216
+ }, [serverSidePagination, rows, sortedRows, vWindow.startIndex, vWindow.endIndex]);
217
+
218
+ // ───── Selection helpers ─────
219
+
220
+ // For `selectAllScope='visible'`, the select-all scope is the
221
+ // current window. For `'allLoaded'`, it's the whole sorted set.
222
+ const selectAllPool = useMemo(() => {
223
+ if (selectAllScope === 'visible') {
224
+ return renderedRows.map((row, idx) =>
225
+ getRowId(row, vWindow.startIndex + idx),
226
+ );
227
+ }
228
+ return sortedRows.map((row, idx) => getRowId(row, idx));
229
+ }, [selectAllScope, renderedRows, sortedRows, getRowId, vWindow.startIndex]);
230
+
231
+ const selection = useTableSelection(rowSelection, selectedRowIds, setSelectedRowIds);
232
+
233
+ const selectedRows = useMemo(
234
+ () => sortedRows.filter((row, idx) => selection.isSelected(getRowId(row, idx))),
235
+ [sortedRows, selection, getRowId],
236
+ );
237
+
238
+ // ───── Variant recipe ─────
239
+ const v = dataGridVariants({ variant, size, density });
240
+
241
+ // ───── Render ─────
242
+
243
+ if (!gridAccessState.visible) return null;
244
+
245
+ const isInteractive = !gridAccessState.disabled;
246
+ const showSelectionColumn = rowSelection !== 'none';
247
+ const showRowActionsColumn = rowActions != null;
248
+
249
+ const totalColumnCount =
250
+ visibleCols.length +
251
+ (showSelectionColumn ? 1 : 0) +
252
+ (showRowActionsColumn ? 1 : 0);
253
+
254
+ return (
255
+ <div
256
+ className={cn(v.root(), sx, slotProps?.root?.className)}
257
+ data-disabled={!isInteractive ? 'true' : undefined}
258
+ >
259
+ {/* ───── Toolbar ───── */}
260
+ {enableSearch && (
261
+ <div className={cn(v.toolbar(), slotProps?.toolbar?.className)}>
262
+ <label className={cn(v.search(), slotProps?.search?.className)}>
263
+ <span className="sr-only">{labels.searchPlaceholder}</span>
264
+ <SearchIcon className="ml-2 shrink-0 text-neutral-500" />
265
+ <input
266
+ type="text"
267
+ value={searchQuery}
268
+ onChange={(e) => setSearchQuery(e.target.value)}
269
+ placeholder={searchPlaceholder ?? labels.searchPlaceholder}
270
+ disabled={!isInteractive}
271
+ className={cn(
272
+ 'flex-1 bg-transparent border-0 outline-none',
273
+ 'px-2 py-1.5',
274
+ 'placeholder:text-neutral-400',
275
+ 'disabled:opacity-50 disabled:cursor-not-allowed',
276
+ )}
277
+ />
278
+ </label>
279
+ </div>
280
+ )}
281
+
282
+ {/* ───── Scroll wrapper (bounded height — required for virt) ───── */}
283
+ <div
284
+ ref={scrollRef}
285
+ className={cn(v.scroll(), slotProps?.scroll?.className)}
286
+ style={height ? { height, maxHeight: height } : undefined}
287
+ >
288
+ <table className={cn(v.table(), slotProps?.table?.className)}>
289
+ {caption != null && (
290
+ <caption className={cn(!showCaption && 'sr-only', 'py-2 text-sm text-neutral-500')}>
291
+ {caption}
292
+ </caption>
293
+ )}
294
+
295
+ <thead
296
+ className={cn(
297
+ stickyHeader ? v.thead() : 'bg-neutral-50',
298
+ slotProps?.thead?.className,
299
+ )}
300
+ >
301
+ <tr className={cn(v.headerRow(), slotProps?.headerRow?.className)}>
302
+ {showSelectionColumn && (
303
+ <th
304
+ scope="col"
305
+ className={cn(
306
+ v.headerCell(),
307
+ v.selectionCell(),
308
+ v.stickyLeftHeaderCell(),
309
+ slotProps?.headerCell?.className,
310
+ slotProps?.selectionCell?.className,
311
+ )}
312
+ >
313
+ {rowSelection === 'multiple' && (
314
+ <input
315
+ type="checkbox"
316
+ aria-label={labels.ariaSelectAllRows}
317
+ checked={selection.isAllSelected(selectAllPool)}
318
+ ref={(el) => {
319
+ if (el)
320
+ el.indeterminate = selection.isIndeterminate(selectAllPool);
321
+ }}
322
+ onChange={() => selection.toggleAll(selectAllPool)}
323
+ disabled={!isInteractive}
324
+ className="cursor-pointer"
325
+ />
326
+ )}
327
+ </th>
328
+ )}
329
+
330
+ {visibleCols.map((col) => (
331
+ <HeaderCell
332
+ key={col.field as string}
333
+ col={col}
334
+ sortModel={sortModel}
335
+ onSortClick={(e) =>
336
+ handleSortClick(col, e, sortModel, setSortModel)
337
+ }
338
+ inferredType={columnTypes.get(col.field as string)}
339
+ labels={labels}
340
+ className={cn(
341
+ v.headerCell(),
342
+ col.sticky === 'left' && v.stickyLeftHeaderCell(),
343
+ slotProps?.headerCell?.className,
344
+ )}
345
+ buttonClassName={v.headerCellButton()}
346
+ disabled={!isInteractive}
347
+ />
348
+ ))}
349
+
350
+ {showRowActionsColumn && (
351
+ <th
352
+ scope="col"
353
+ aria-hidden="true"
354
+ className={cn(
355
+ v.headerCell(),
356
+ 'w-12',
357
+ slotProps?.headerCell?.className,
358
+ )}
359
+ />
360
+ )}
361
+ </tr>
362
+ </thead>
363
+
364
+ <tbody className={cn(v.tbody(), slotProps?.tbody?.className)}>
365
+ {loading
366
+ ? renderLoadingRows({
367
+ count: loadingRowCount,
368
+ visibleCols,
369
+ showSelectionColumn,
370
+ showRowActionsColumn,
371
+ rowHeight,
372
+ rowClass: cn(v.row(), slotProps?.row?.className),
373
+ cellClass: cn(v.cell(), slotProps?.cell?.className),
374
+ })
375
+ : sortedRows.length === 0
376
+ ? renderEmptyState({
377
+ totalColumnCount,
378
+ emptyState,
379
+ fallback: labels.noData,
380
+ cellClass: cn(
381
+ v.cell(),
382
+ v.emptyState(),
383
+ slotProps?.emptyState?.className,
384
+ ),
385
+ })
386
+ : renderVirtualizedBody({
387
+ vWindow,
388
+ rowHeight,
389
+ renderedRows,
390
+ visibleCols,
391
+ columnTypes,
392
+ selection,
393
+ rowSelection,
394
+ showSelectionColumn,
395
+ showRowActionsColumn,
396
+ rowActions,
397
+ getRowId,
398
+ isInteractive,
399
+ labels,
400
+ serverSidePagination,
401
+ classes: {
402
+ row: cn(v.row(), slotProps?.row?.className),
403
+ cell: cn(v.cell(), slotProps?.cell?.className),
404
+ selectionCell: cn(
405
+ v.cell(),
406
+ v.selectionCell(),
407
+ v.stickyLeftCell(),
408
+ slotProps?.cell?.className,
409
+ slotProps?.selectionCell?.className,
410
+ ),
411
+ stickyLeftCell: v.stickyLeftCell(),
412
+ rowActionsCell: cn(
413
+ v.cell(),
414
+ v.rowActionsCell(),
415
+ slotProps?.cell?.className,
416
+ slotProps?.rowActionsCell?.className,
417
+ ),
418
+ },
419
+ })}
420
+ </tbody>
421
+ </table>
422
+ </div>
423
+
424
+ {/* ───── Bulk action footer ───── */}
425
+ {bulkActions && selectedRows.length > 0 && (
426
+ <div
427
+ className={cn(v.bulkActionFooter(), slotProps?.bulkActionFooter?.className)}
428
+ role="region"
429
+ aria-label={labels.selectedCount.replace(
430
+ '{count}',
431
+ String(selectedRows.length),
432
+ )}
433
+ >
434
+ <span className="text-sm text-neutral-700">
435
+ {labels.selectedCount.replace('{count}', String(selectedRows.length))}
436
+ </span>
437
+ <div className="flex items-center gap-2">
438
+ {bulkActions(selectedRows)}
439
+ <button
440
+ type="button"
441
+ onClick={selection.clearSelection}
442
+ className={cn(
443
+ 'text-sm text-neutral-500 hover:text-neutral-900',
444
+ 'underline-offset-2 hover:underline',
445
+ 'focus:outline-none focus-visible:underline',
446
+ )}
447
+ >
448
+ {labels.clearSelection}
449
+ </button>
450
+ </div>
451
+ </div>
452
+ )}
453
+
454
+ {/* ───── Optional pagination footer ───── */}
455
+ {pagination && (
456
+ <div className={cn(v.paginationFooter(), slotProps?.pagination?.className)}>
457
+ <Pagination
458
+ page={pagination.page}
459
+ pageSize={pagination.pageSize}
460
+ totalCount={totalCountProp ?? sortedRows.length}
461
+ onPageChange={pagination.onPageChange}
462
+ onPageSizeChange={pagination.onPageSizeChange}
463
+ pageSizeOptions={pagination.pageSizeOptions}
464
+ />
465
+ </div>
466
+ )}
467
+ </div>
468
+ );
469
+ }
470
+
471
+ // ───── Header cell ─────
472
+
473
+ function HeaderCell<T extends object>(props: {
474
+ col: TableColumn<T>;
475
+ sortModel: TableSortModel;
476
+ onSortClick: (e: MouseEvent<HTMLButtonElement>) => void;
477
+ inferredType: string | undefined;
478
+ labels: Required<TableLabels>;
479
+ className: string;
480
+ buttonClassName: string;
481
+ disabled: boolean;
482
+ }) {
483
+ const {
484
+ col,
485
+ sortModel,
486
+ onSortClick,
487
+ inferredType,
488
+ labels,
489
+ className,
490
+ buttonClassName,
491
+ disabled,
492
+ } = props;
493
+
494
+ const align = resolveAlign(col, inferredType as never);
495
+ const alignClass =
496
+ align === 'right' ? 'text-right' : align === 'center' ? 'text-center' : 'text-left';
497
+
498
+ const sortEntry = sortModel.find((s) => s.field === col.field);
499
+ const ariaSort: 'ascending' | 'descending' | 'none' =
500
+ sortEntry?.direction === 'asc'
501
+ ? 'ascending'
502
+ : sortEntry?.direction === 'desc'
503
+ ? 'descending'
504
+ : 'none';
505
+
506
+ const headerContent =
507
+ typeof col.header === 'function' ? col.header() : col.header;
508
+
509
+ const cellStyle = {
510
+ width: col.width != null ? `${col.width}px` : undefined,
511
+ minWidth: col.minWidth != null ? `${col.minWidth}px` : undefined,
512
+ flex: col.flex,
513
+ };
514
+
515
+ if (col.sortable) {
516
+ return (
517
+ <th
518
+ scope="col"
519
+ aria-sort={ariaSort}
520
+ className={cn(className, alignClass)}
521
+ style={cellStyle}
522
+ >
523
+ <button
524
+ type="button"
525
+ onClick={onSortClick}
526
+ disabled={disabled}
527
+ aria-label={
528
+ ariaSort === 'ascending'
529
+ ? labels.ariaSortAscending
530
+ : ariaSort === 'descending'
531
+ ? labels.ariaSortDescending
532
+ : labels.ariaSortNone
533
+ }
534
+ className={cn(
535
+ buttonClassName,
536
+ align === 'right' && 'flex-row-reverse',
537
+ 'disabled:cursor-not-allowed disabled:opacity-50',
538
+ )}
539
+ >
540
+ <span>{headerContent}</span>
541
+ <SortIcon direction={sortEntry?.direction} />
542
+ </button>
543
+ </th>
544
+ );
545
+ }
546
+
547
+ return (
548
+ <th scope="col" className={cn(className, alignClass)} style={cellStyle}>
549
+ {headerContent}
550
+ </th>
551
+ );
552
+ }
553
+
554
+ // ───── Virtualized body ─────
555
+
556
+ function renderVirtualizedBody<T extends object>(args: {
557
+ vWindow: { startIndex: number; endIndex: number; paddingTop: number; paddingBottom: number };
558
+ rowHeight: number;
559
+ renderedRows: T[];
560
+ visibleCols: TableColumn<T>[];
561
+ columnTypes: Map<string, string>;
562
+ selection: ReturnType<typeof useTableSelection>;
563
+ rowSelection: 'none' | 'single' | 'multiple';
564
+ showSelectionColumn: boolean;
565
+ showRowActionsColumn: boolean;
566
+ rowActions: ((row: T) => ReactNode) | undefined;
567
+ getRowId: (row: T, index: number) => string;
568
+ isInteractive: boolean;
569
+ labels: Required<TableLabels>;
570
+ serverSidePagination: boolean;
571
+ classes: {
572
+ row: string;
573
+ cell: string;
574
+ selectionCell: string;
575
+ stickyLeftCell: string;
576
+ rowActionsCell: string;
577
+ };
578
+ }): ReactNode {
579
+ const {
580
+ vWindow,
581
+ renderedRows,
582
+ visibleCols,
583
+ columnTypes,
584
+ selection,
585
+ rowSelection,
586
+ showSelectionColumn,
587
+ showRowActionsColumn,
588
+ rowActions,
589
+ getRowId,
590
+ isInteractive,
591
+ labels,
592
+ classes,
593
+ } = args;
594
+
595
+ return (
596
+ <>
597
+ {vWindow.paddingTop > 0 && (
598
+ <tr aria-hidden="true" style={{ height: vWindow.paddingTop }} />
599
+ )}
600
+ {renderedRows.map((row, localIdx) => {
601
+ const absoluteIdx = vWindow.startIndex + localIdx;
602
+ const rowId = getRowId(row, absoluteIdx);
603
+ const isSelected = selection.isSelected(rowId);
604
+ return (
605
+ <tr
606
+ key={rowId}
607
+ data-selected={isSelected ? 'true' : 'false'}
608
+ aria-selected={rowSelection !== 'none' ? isSelected : undefined}
609
+ className={classes.row}
610
+ >
611
+ {showSelectionColumn && (
612
+ <td className={classes.selectionCell}>
613
+ <input
614
+ type="checkbox"
615
+ aria-label={labels.ariaSelectRow}
616
+ checked={isSelected}
617
+ onChange={() => selection.toggleRow(rowId)}
618
+ disabled={!isInteractive}
619
+ className="cursor-pointer"
620
+ />
621
+ </td>
622
+ )}
623
+ {visibleCols.map((col) => (
624
+ <DataCell
625
+ key={col.field as string}
626
+ col={col}
627
+ row={row}
628
+ rowIndex={absoluteIdx}
629
+ isSelected={isSelected}
630
+ inferredType={columnTypes.get(col.field as string)}
631
+ cellClass={classes.cell}
632
+ stickyLeftClass={classes.stickyLeftCell}
633
+ />
634
+ ))}
635
+ {showRowActionsColumn && rowActions && (
636
+ <td className={classes.rowActionsCell}>{rowActions(row)}</td>
637
+ )}
638
+ </tr>
639
+ );
640
+ })}
641
+ {vWindow.paddingBottom > 0 && (
642
+ <tr aria-hidden="true" style={{ height: vWindow.paddingBottom }} />
643
+ )}
644
+ </>
645
+ );
646
+ }
647
+
648
+ // ───── Data cell ─────
649
+
650
+ function DataCell<T extends object>(props: {
651
+ col: TableColumn<T>;
652
+ row: T;
653
+ rowIndex: number;
654
+ isSelected: boolean;
655
+ inferredType: string | undefined;
656
+ cellClass: string;
657
+ stickyLeftClass: string;
658
+ }) {
659
+ const { col, row, rowIndex, isSelected, inferredType, cellClass, stickyLeftClass } = props;
660
+ const value = getNestedValue(row, col.field as string);
661
+ const align = resolveAlign(col, inferredType as never);
662
+ const tabularNums = resolveTabularNums(col, inferredType as never);
663
+ const monospace = resolveMonospace(col);
664
+ const alignClass =
665
+ align === 'right' ? 'text-right' : align === 'center' ? 'text-center' : 'text-left';
666
+
667
+ const columnAccessState = col.access
668
+ ? {
669
+ hidden: col.access.onUnauthorized === 'hide',
670
+ disabled: col.access.onUnauthorized === 'disable',
671
+ readonly: col.access.onUnauthorized === 'readonly',
672
+ }
673
+ : null;
674
+
675
+ const content = col.cellRenderer
676
+ ? col.cellRenderer({
677
+ row,
678
+ value,
679
+ rowIndex,
680
+ isSelected,
681
+ isExpanded: false, // DataGrid v1 doesn't support expansion (defer)
682
+ access: columnAccessState,
683
+ })
684
+ : renderDefaultCell(value);
685
+
686
+ return (
687
+ <td
688
+ className={cn(
689
+ cellClass,
690
+ alignClass,
691
+ tabularNums && 'tabular-nums',
692
+ monospace && 'font-mono',
693
+ col.sticky === 'left' && stickyLeftClass,
694
+ )}
695
+ style={{
696
+ width: col.width != null ? `${col.width}px` : undefined,
697
+ minWidth: col.minWidth != null ? `${col.minWidth}px` : undefined,
698
+ }}
699
+ >
700
+ {content}
701
+ </td>
702
+ );
703
+ }
704
+
705
+ // ───── Helpers ─────
706
+
707
+ function renderDefaultCell(value: unknown): ReactNode {
708
+ if (value == null) return null;
709
+ if (typeof value === 'boolean') return value ? '✓' : '✗';
710
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
711
+ if (typeof value === 'object') return JSON.stringify(value);
712
+ return value as ReactNode;
713
+ }
714
+
715
+ function handleSortClick<T extends object>(
716
+ col: TableColumn<T>,
717
+ event: MouseEvent<HTMLButtonElement>,
718
+ current: TableSortModel,
719
+ setSortModel: (
720
+ next: TableSortModel | ((prev: TableSortModel) => TableSortModel),
721
+ ) => void,
722
+ ) {
723
+ if (!col.sortable) return;
724
+ const multi = event.shiftKey;
725
+ setSortModel((prev) => cycleSortFor(prev, col.field as string, multi));
726
+ }
727
+
728
+ function renderLoadingRows<T extends object>(args: {
729
+ count: number;
730
+ visibleCols: TableColumn<T>[];
731
+ showSelectionColumn: boolean;
732
+ showRowActionsColumn: boolean;
733
+ rowHeight: number;
734
+ rowClass: string;
735
+ cellClass: string;
736
+ }): ReactNode {
737
+ const {
738
+ count,
739
+ visibleCols,
740
+ showSelectionColumn,
741
+ showRowActionsColumn,
742
+ rowHeight,
743
+ rowClass,
744
+ cellClass,
745
+ } = args;
746
+ return Array.from({ length: count }).map((_, i) => (
747
+ <tr
748
+ key={`loading-${i}`}
749
+ className={rowClass}
750
+ aria-busy="true"
751
+ style={{ height: rowHeight }}
752
+ >
753
+ {showSelectionColumn && (
754
+ <td className={cellClass}>
755
+ <Skeleton variant="rectangle" width="16px" height="16px" />
756
+ </td>
757
+ )}
758
+ {visibleCols.map((col) => (
759
+ <td key={col.field as string} className={cellClass}>
760
+ <Skeleton variant="text" width="80%" />
761
+ </td>
762
+ ))}
763
+ {showRowActionsColumn && (
764
+ <td className={cellClass}>
765
+ <Skeleton variant="rectangle" width="24px" height="24px" />
766
+ </td>
767
+ )}
768
+ </tr>
769
+ ));
770
+ }
771
+
772
+ function renderEmptyState(args: {
773
+ totalColumnCount: number;
774
+ emptyState: ReactNode;
775
+ fallback: string;
776
+ cellClass: string;
777
+ }): ReactNode {
778
+ return (
779
+ <tr>
780
+ <td colSpan={args.totalColumnCount} className={args.cellClass}>
781
+ {args.emptyState ?? args.fallback}
782
+ </td>
783
+ </tr>
784
+ );
785
+ }
786
+
787
+ // ───── Icons ─────
788
+
789
+ function SortIcon(props: { direction?: 'asc' | 'desc' }) {
790
+ return (
791
+ <svg
792
+ width="0.75em"
793
+ height="0.75em"
794
+ viewBox="0 0 16 16"
795
+ fill="currentColor"
796
+ aria-hidden="true"
797
+ className="shrink-0 opacity-60 group-hover:opacity-100"
798
+ >
799
+ {props.direction === 'asc' ? (
800
+ <path d="M8 4l4 6H4z" />
801
+ ) : props.direction === 'desc' ? (
802
+ <path d="M8 12L4 6h8z" />
803
+ ) : (
804
+ <>
805
+ <path d="M8 3l3 4H5z" opacity="0.5" />
806
+ <path d="M8 13l-3-4h6z" opacity="0.5" />
807
+ </>
808
+ )}
809
+ </svg>
810
+ );
811
+ }
812
+
813
+ function SearchIcon(props: { className?: string }) {
814
+ return (
815
+ <svg
816
+ width="0.875em"
817
+ height="0.875em"
818
+ viewBox="0 0 16 16"
819
+ fill="none"
820
+ stroke="currentColor"
821
+ strokeWidth="1.5"
822
+ strokeLinecap="round"
823
+ strokeLinejoin="round"
824
+ aria-hidden="true"
825
+ className={props.className}
826
+ >
827
+ <circle cx="7" cy="7" r="4.5" />
828
+ <path d="M11 11l3 3" />
829
+ </svg>
830
+ );
831
+ }