@majapisoftwares/ui 6.3.0 → 6.4.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 (81) hide show
  1. package/AGENTS.md +27 -27
  2. package/README.md +79 -79
  3. package/THIRD_PARTY_NOTICES.md +39 -39
  4. package/components.json +25 -25
  5. package/docs/MIGRATION-0.2.md +20 -20
  6. package/docs/MIGRATION-6.0.md +33 -33
  7. package/docs/NEXT-STARTER-VALIDATION.md +14 -14
  8. package/docs/STANDARDS.md +65 -51
  9. package/docs/VALIDATION.md +11 -11
  10. package/docs/VERSIONING.md +32 -28
  11. package/docs/validation/preference-titles.md +22 -22
  12. package/package.json +91 -89
  13. package/scripts/check-standards.mjs +41 -41
  14. package/src/components/ui/accordion.tsx +82 -82
  15. package/src/components/ui/alert-dialog.tsx +187 -187
  16. package/src/components/ui/alert.tsx +77 -77
  17. package/src/components/ui/attachment.tsx +209 -0
  18. package/src/components/ui/avatar.tsx +108 -108
  19. package/src/components/ui/badge.tsx +55 -55
  20. package/src/components/ui/breadcrumb.tsx +125 -125
  21. package/src/components/ui/bubble.tsx +129 -0
  22. package/src/components/ui/button-group.tsx +89 -89
  23. package/src/components/ui/button.tsx +59 -59
  24. package/src/components/ui/card.tsx +101 -101
  25. package/src/components/ui/checkbox.tsx +27 -27
  26. package/src/components/ui/collapsible.tsx +21 -21
  27. package/src/components/ui/context-menu.tsx +271 -271
  28. package/src/components/ui/dialog.tsx +161 -161
  29. package/src/components/ui/dropdown-menu.tsx +271 -271
  30. package/src/components/ui/empty.tsx +105 -105
  31. package/src/components/ui/field.tsx +238 -238
  32. package/src/components/ui/hover-card.tsx +50 -50
  33. package/src/components/ui/input-group.tsx +155 -155
  34. package/src/components/ui/input.tsx +21 -21
  35. package/src/components/ui/item.tsx +203 -0
  36. package/src/components/ui/kbd.tsx +28 -28
  37. package/src/components/ui/label.tsx +19 -19
  38. package/src/components/ui/message-scroller.tsx +166 -0
  39. package/src/components/ui/message.tsx +93 -0
  40. package/src/components/ui/orb.css +1002 -1002
  41. package/src/components/ui/orb.tsx +752 -752
  42. package/src/components/ui/popover.tsx +89 -89
  43. package/src/components/ui/progress.tsx +82 -82
  44. package/src/components/ui/radio-group.tsx +37 -37
  45. package/src/components/ui/scroll-area.tsx +54 -54
  46. package/src/components/ui/select.tsx +204 -204
  47. package/src/components/ui/separator.tsx +24 -24
  48. package/src/components/ui/sheet.tsx +139 -139
  49. package/src/components/ui/sidebar.tsx +1048 -1048
  50. package/src/components/ui/skeleton.tsx +15 -15
  51. package/src/components/ui/slider.tsx +53 -53
  52. package/src/components/ui/sonner.tsx +44 -44
  53. package/src/components/ui/spinner.tsx +32 -32
  54. package/src/components/ui/switch.tsx +31 -31
  55. package/src/components/ui/table.tsx +121 -121
  56. package/src/components/ui/tabs.tsx +81 -81
  57. package/src/components/ui/textarea.tsx +19 -19
  58. package/src/components/ui/toggle-group.tsx +89 -89
  59. package/src/components/ui/toggle.tsx +44 -44
  60. package/src/components/ui/tooltip.tsx +65 -65
  61. package/src/components/ui/trace.tsx +163 -0
  62. package/src/hooks/use-mobile.ts +20 -20
  63. package/src/hooks/use-streamed-text.ts +64 -0
  64. package/src/lib/i18n.tsx +151 -109
  65. package/src/lib/utils.ts +1 -1
  66. package/src/patterns/app-shell.tsx +237 -237
  67. package/src/patterns/chat-markdown.tsx +72 -0
  68. package/src/patterns/chat-trace.tsx +200 -0
  69. package/src/patterns/chat.tsx +317 -0
  70. package/src/patterns/data-table.tsx +2492 -2492
  71. package/src/patterns/filter-tabs.tsx +53 -53
  72. package/src/patterns/majapi-logo.tsx +32 -32
  73. package/src/patterns/page-header.tsx +62 -62
  74. package/src/patterns/prompt-input.tsx +364 -0
  75. package/src/patterns/status-badge.tsx +24 -24
  76. package/src/patterns/user-menu.tsx +218 -218
  77. package/src/patterns/workspace-switcher.tsx +176 -176
  78. package/src/styles.css +170 -165
  79. package/src/templates/admin-dashboard.tsx +44 -44
  80. package/src/templates/auth-layout.tsx +30 -30
  81. package/src/templates/signup-form.tsx +177 -177
@@ -1,2492 +1,2492 @@
1
- "use client";
2
- "use no memo";
3
-
4
- // Ported from the Numa app's data table (majapisoftwares/numa); this is now the
5
- // canonical copy. Effects below intentionally sync restored localStorage
6
- // preferences and incoming props into table state.
7
- /* eslint-disable react-hooks/set-state-in-effect */
8
-
9
- import * as React from "react";
10
- import {
11
- closestCenter,
12
- DndContext,
13
- KeyboardSensor,
14
- MouseSensor,
15
- TouchSensor,
16
- useSensor,
17
- useSensors,
18
- type DragEndEvent,
19
- } from "@dnd-kit/core";
20
- import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
21
- import {
22
- arrayMove,
23
- horizontalListSortingStrategy,
24
- SortableContext,
25
- useSortable,
26
- } from "@dnd-kit/sortable";
27
- import { CSS } from "@dnd-kit/utilities";
28
- import {
29
- CircleAlertIcon,
30
- InboxIcon,
31
- LockIcon,
32
- RotateCwIcon,
33
- TriangleAlertIcon,
34
- ArrowDownWideNarrowIcon,
35
- ArrowUpDownIcon,
36
- ArrowUpNarrowWideIcon,
37
- CheckIcon,
38
- ChevronLeftIcon,
39
- ChevronRightIcon,
40
- ChevronsLeftIcon,
41
- ChevronsRightIcon,
42
- Columns3Icon,
43
- EyeOffIcon,
44
- FunnelIcon,
45
- FunnelXIcon,
46
- GripVerticalIcon,
47
- SearchIcon,
48
- XIcon,
49
- } from "lucide-react";
50
- import {
51
- createTable,
52
- flexRender,
53
- getCoreRowModel,
54
- getFilteredRowModel,
55
- getPaginationRowModel,
56
- getSortedRowModel,
57
- type Column,
58
- type ColumnDef,
59
- type ColumnFiltersState,
60
- type ColumnOrderState,
61
- type ColumnSizingState,
62
- type FilterFn,
63
- type Header,
64
- type OnChangeFn,
65
- type PaginationState,
66
- type RowData,
67
- type RowSelectionState,
68
- type SortingState,
69
- type Table as TanstackTable,
70
- type TableOptions,
71
- type TableOptionsResolved,
72
- type VisibilityState,
73
- } from "@tanstack/react-table";
74
-
75
- import { Badge } from "../components/ui/badge";
76
- import { Button } from "../components/ui/button";
77
- import { Checkbox } from "../components/ui/checkbox";
78
- import { FilterTabs } from "./filter-tabs";
79
- import {
80
- DropdownMenu,
81
- DropdownMenuCheckboxItem,
82
- DropdownMenuContent,
83
- DropdownMenuGroup,
84
- DropdownMenuItem,
85
- DropdownMenuLabel,
86
- DropdownMenuSeparator,
87
- DropdownMenuTrigger,
88
- } from "../components/ui/dropdown-menu";
89
- import { Input } from "../components/ui/input";
90
- import {
91
- InputGroup,
92
- InputGroupAddon,
93
- InputGroupInput,
94
- } from "../components/ui/input-group";
95
- import { Label } from "../components/ui/label";
96
- import {
97
- Popover,
98
- PopoverContent,
99
- PopoverTrigger,
100
- } from "../components/ui/popover";
101
- import {
102
- Select,
103
- SelectContent,
104
- SelectItem,
105
- SelectTrigger,
106
- SelectValue,
107
- } from "../components/ui/select";
108
- import { Separator } from "../components/ui/separator";
109
- import { Skeleton } from "../components/ui/skeleton";
110
- import {
111
- Table,
112
- TableBody,
113
- TableCell,
114
- TableHead,
115
- TableHeader,
116
- TableRow,
117
- } from "../components/ui/table";
118
- import {
119
- Tooltip,
120
- TooltipContent,
121
- TooltipProvider,
122
- TooltipTrigger,
123
- } from "../components/ui/tooltip";
124
- import { cn } from "cn";
125
- import { defineMessages, useMessages, useUiMessages } from "../lib/i18n";
126
- import {
127
- Empty,
128
- EmptyContent,
129
- EmptyDescription,
130
- EmptyHeader,
131
- EmptyMedia,
132
- EmptyTitle,
133
- } from "../components/ui/empty";
134
- import {
135
- Alert,
136
- AlertAction,
137
- AlertDescription,
138
- AlertTitle,
139
- } from "../components/ui/alert";
140
-
141
- export type DataTableColumnAlign = "left" | "center" | "right";
142
- type DataTableSortDirection = false | "asc" | "desc";
143
-
144
- export type DataTableFilterOption = {
145
- label: string;
146
- value: string;
147
- };
148
-
149
- export type DataTableRangeFilter = {
150
- min?: string;
151
- max?: string;
152
- };
153
-
154
- export type DataTableDateRangeFilter = {
155
- from?: string;
156
- to?: string;
157
- };
158
-
159
- // Multi-select filter value: an array keeps the matching rows; the object form
160
- // hides the selected values instead. Server-filtered tables only receive arrays.
161
- export type DataTableMultiFilterValue =
162
- string[] | { exclude: true; values: string[] };
163
-
164
- export type DataTableColumnFilter<TData extends RowData> =
165
- | {
166
- placeholder?: string;
167
- type: "text";
168
- }
169
- | {
170
- options: DataTableFilterOption[];
171
- type: "multi";
172
- }
173
- | {
174
- max?: number;
175
- maxPlaceholder?: string;
176
- min?: number;
177
- minPlaceholder?: string;
178
- type: "number-range";
179
- }
180
- | {
181
- type: "date-range";
182
- }
183
- | {
184
- render: (column: Column<TData, unknown>) => React.ReactNode;
185
- type: "custom";
186
- };
187
-
188
- export type DataTableColumnMeta<TData extends RowData> = {
189
- align?: DataTableColumnAlign;
190
- cellClassName?: string;
191
- filter?: DataTableColumnFilter<TData>;
192
- headerClassName?: string;
193
- label?: string;
194
- };
195
-
196
- declare module "@tanstack/react-table" {
197
- interface ColumnMeta<TData extends RowData, TValue> {
198
- align?: DataTableColumnAlign;
199
- cellClassName?: string;
200
- filter?: DataTableColumnFilter<TData>;
201
- headerClassName?: string;
202
- label?: string;
203
- valueType?: TValue;
204
- }
205
-
206
- interface TableMeta<TData extends RowData> {
207
- enableExcludeFilters?: boolean;
208
- rowType?: TData;
209
- }
210
- }
211
-
212
- /** Window event that clears a table's search and filters (detail: { storageKey? }). */
213
- export const DATA_TABLE_RESET_FILTERS_EVENT =
214
- "majapi-ui:data-table:reset-filters";
215
-
216
- /** Clears search and filters of every table, or only the one with `storageKey`. */
217
- export function resetDataTableFilters(storageKey?: string) {
218
- window.dispatchEvent(
219
- new CustomEvent(DATA_TABLE_RESET_FILTERS_EVENT, { detail: { storageKey } }),
220
- );
221
- }
222
-
223
- const dataTableMessages = defineMessages({
224
- en: {
225
- search: "Search...",
226
- resultCount: (count: number) =>
227
- `${count} ${count === 1 ? "result" : "results"}`,
228
- rowCount: (count: number) => `${count} ${count === 1 ? "row" : "rows"}`,
229
- // English needs no plural form here; pt-BR uses count.
230
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
231
- selected: (rows: string, count: number) => `${rows} selected`,
232
- clearSelection: "Clear selection",
233
- clearFilters: "Clear filters",
234
- open: "Open",
235
- resizeColumn: (label: string) => `Resize column ${label}`,
236
- filterActive: ", filter active",
237
- excludeFilterActive: ", exclusion filter active",
238
- sortCriterion: (n: number) => `Sort #${n}`,
239
- sortCriterionTitle: (n: number) => `Sort criterion #${n}`,
240
- clearAll: "Clear all",
241
- hide: "Hide",
242
- toggleSort: (label: string) => `Toggle sorting for ${label}`,
243
- reorderColumn: (label: string) => `Reorder column ${label}`,
244
- sort: "Sort",
245
- removeSort: "Remove sort",
246
- ascending: "Ascending",
247
- descending: "Descending",
248
- filter: "Filter",
249
- min: "Min.",
250
- max: "Max.",
251
- filterBy: (label: string) => `Filter by ${label}`,
252
- filterMode: "Filter mode",
253
- show: "Show",
254
- exclude: "Exclude",
255
- valuesToExclude: "Values to exclude",
256
- valuesToShow: "Values to show",
257
- customizeColumns: "Customize columns",
258
- columnsTooltip: "Show, hide and reset columns",
259
- columns: "Columns",
260
- resetColumns: "Reset columns",
261
- rowsPerPage: "Rows",
262
- page: (page: number, total: number) => `Page ${page} of ${total}`,
263
- ofSummary: (part: string, total: string) => `${part} of ${total}.`,
264
- firstPage: "First page",
265
- previousPage: "Previous page",
266
- nextPage: "Next page",
267
- lastPage: "Last page",
268
- },
269
- "pt-BR": {
270
- search: "Buscar...",
271
- resultCount: (count: number) =>
272
- `${count} resultado${count === 1 ? "" : "s"}`,
273
- rowCount: (count: number) => `${count} registro${count === 1 ? "" : "s"}`,
274
- selected: (rows: string, count: number) =>
275
- `${rows} selecionado${count === 1 ? "" : "s"}`,
276
- clearSelection: "Limpar seleção",
277
- clearFilters: "Limpar filtros",
278
- open: "Abrir",
279
- resizeColumn: (label: string) => `Redimensionar coluna ${label}`,
280
- filterActive: ", filtro ativo",
281
- excludeFilterActive: ", filtro de exclusão ativo",
282
- sortCriterion: (n: number) => `${n}º critério`,
283
- sortCriterionTitle: (n: number) => `${n}º critério de ordenação`,
284
- clearAll: "Limpar tudo",
285
- hide: "Ocultar",
286
- toggleSort: (label: string) => `Alternar ordenação da coluna ${label}`,
287
- reorderColumn: (label: string) => `Reordenar coluna ${label}`,
288
- sort: "Ordenar",
289
- removeSort: "Remover ordem",
290
- ascending: "Crescente",
291
- descending: "Decrescente",
292
- filter: "Filtrar",
293
- min: "Mín.",
294
- max: "Máx.",
295
- filterBy: (label: string) => `Filtrar por ${label}`,
296
- filterMode: "Modo do filtro",
297
- show: "Mostrar",
298
- exclude: "Excluir",
299
- valuesToExclude: "Valores a excluir",
300
- valuesToShow: "Valores a mostrar",
301
- customizeColumns: "Personalizar colunas",
302
- columnsTooltip: "Mostrar, ocultar e restaurar colunas",
303
- columns: "Colunas",
304
- resetColumns: "Restaurar colunas",
305
- rowsPerPage: "Linhas",
306
- page: (page: number, total: number) => `Página ${page} de ${total}`,
307
- ofSummary: (part: string, total: string) => `${part} de ${total}.`,
308
- firstPage: "Primeira página",
309
- previousPage: "Página anterior",
310
- nextPage: "Próxima página",
311
- lastPage: "Última página",
312
- },
313
- });
314
-
315
- type StoredDataTableSettings = {
316
- columnFilters?: ColumnFiltersState;
317
- columnOrder?: ColumnOrderState;
318
- columnSizing?: ColumnSizingState;
319
- columnVisibility?: VisibilityState;
320
- globalFilter?: string;
321
- pageSize?: number;
322
- sorting?: SortingState;
323
- };
324
-
325
- export type DataTableProps<TData extends RowData> = {
326
- activeRowId?: string | null;
327
- columns: ColumnDef<TData, unknown>[];
328
- data: TData[];
329
- /** Text when there are no rows; defaults to a translated message. */
330
- emptyMessage?: string;
331
- /** Rich empty state (e.g. with a create action), shown when nothing is filtered. */
332
- emptyState?: React.ReactNode;
333
- /**
334
- * Fills the parent's height and scrolls rows inside the table (sticky
335
- * header, toolbar and pagination stay visible). The parent must be a flex
336
- * column with a bounded height, e.g. `AppShell fillHeight`.
337
- */
338
- fillHeight?: boolean;
339
- /** Shows skeleton rows instead of data. */
340
- loading?: boolean;
341
- /** Load failure. With rows it shows as stale data; without, replaces the table. */
342
- error?: string;
343
- onRetry?: () => void;
344
- /** Non-blocking notice, e.g. partial coverage. */
345
- warning?: string;
346
- /** Data can't be shown at all, e.g. missing permission. */
347
- unavailable?: string;
348
- enablePersistence?: boolean;
349
- enableRowSelection?: boolean;
350
- // Offers "Excluir" in multi-select column filters. Defaults to off for
351
- // server-backed tables (onStateChange), whose APIs only read include arrays.
352
- enableExcludeFilters?: boolean;
353
- filterFns?: Record<string, FilterFn<TData>>;
354
- formatResultCount?: (count: number) => string;
355
- formatRowCount?: (count: number) => string;
356
- formatSelectedRowCount?: (count: number) => string;
357
- getRowId: (row: TData) => string;
358
- globalFilterFn?: FilterFn<TData>;
359
- initialColumnFilters?: ColumnFiltersState;
360
- /** Initial search text. */
361
- initialGlobalFilter?: string;
362
- /** Makes rows clickable (and Enter/Space activatable), e.g. to open details. */
363
- onRowClick?: (row: TData) => void;
364
- /** Accessible name for a clickable row; defaults to its id. */
365
- getRowLabel?: (row: TData) => string;
366
- initialColumnOrder?: ColumnOrderState;
367
- initialColumnVisibility?: VisibilityState;
368
- initialPageSize?: number;
369
- initialSorting?: SortingState;
370
- lockedEndColumnIds?: string[];
371
- lockedStartColumnIds?: string[];
372
- manualFiltering?: boolean;
373
- manualPagination?: boolean;
374
- manualSorting?: boolean;
375
- onStateChange?: (state: DataTableStateSnapshot) => void;
376
- pageCount?: number;
377
- pageSizeOptions?: number[];
378
- rowCount?: number;
379
- rowSelectionActions?: (table: TanstackTable<TData>) => React.ReactNode;
380
- searchPlaceholder?: string;
381
- /** Persists sorting, filters, columns and page size in localStorage under this key. */
382
- storageKey?: string;
383
- toolbarBelow?: (table: TanstackTable<TData>) => React.ReactNode;
384
- toolbarEnd?: (table: TanstackTable<TData>) => React.ReactNode;
385
- toolbarStart?: (table: TanstackTable<TData>) => React.ReactNode;
386
- };
387
-
388
- export type DataTableStateSnapshot = {
389
- columnFilters: ColumnFiltersState;
390
- globalFilter: string;
391
- pagination: PaginationState;
392
- sorting: SortingState;
393
- };
394
-
395
- export type DataTableFilterTab = {
396
- count?: number;
397
- label: string;
398
- value: string;
399
- };
400
-
401
- type DataTableObjectFilter = DataTableRangeFilter & DataTableDateRangeFilter;
402
-
403
- function isRecord(value: unknown): value is Record<string, unknown> {
404
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
405
- }
406
-
407
- function readStringProperty(value: unknown, key: string) {
408
- if (!isRecord(value)) {
409
- return undefined;
410
- }
411
-
412
- const property = value[key];
413
- return typeof property === "string" ? property : undefined;
414
- }
415
-
416
- function readStringArrayFilter(value: unknown) {
417
- if (!Array.isArray(value)) {
418
- return [];
419
- }
420
-
421
- return value.filter((item): item is string => typeof item === "string");
422
- }
423
-
424
- export function readMultiFilterValue(value: unknown): {
425
- exclude: boolean;
426
- values: string[];
427
- } {
428
- if (isRecord(value) && value.exclude === true) {
429
- return { exclude: true, values: readStringArrayFilter(value.values) };
430
- }
431
-
432
- return { exclude: false, values: readStringArrayFilter(value) };
433
- }
434
-
435
- function toMultiFilterValue(
436
- exclude: boolean,
437
- values: string[],
438
- ): DataTableMultiFilterValue | undefined {
439
- if (values.length === 0) {
440
- return undefined;
441
- }
442
-
443
- return exclude ? { exclude: true, values } : values;
444
- }
445
-
446
- function isString(value: unknown): value is string {
447
- return typeof value === "string";
448
- }
449
-
450
- function readRangeFilterValue(value: unknown): DataTableRangeFilter {
451
- return {
452
- max: readStringProperty(value, "max"),
453
- min: readStringProperty(value, "min"),
454
- };
455
- }
456
-
457
- function readDateRangeFilterValue(value: unknown): DataTableDateRangeFilter {
458
- return {
459
- from: readStringProperty(value, "from"),
460
- to: readStringProperty(value, "to"),
461
- };
462
- }
463
-
464
- function readObjectFilterValue(value: unknown): Partial<DataTableObjectFilter> {
465
- return {
466
- ...readRangeFilterValue(value),
467
- ...readDateRangeFilterValue(value),
468
- };
469
- }
470
-
471
- export function createArrayIncludesSomeFilter<
472
- TData extends RowData,
473
- >(): FilterFn<TData> {
474
- return (row, columnId, filterValue) => {
475
- const { exclude, values } = readMultiFilterValue(filterValue);
476
-
477
- if (values.length === 0) {
478
- return true;
479
- }
480
-
481
- return values.includes(row.getValue(columnId)) !== exclude;
482
- };
483
- }
484
-
485
- export function createNumberInRangeFilter<
486
- TData extends RowData,
487
- >(): FilterFn<TData> {
488
- return (row, columnId, filterValue) => {
489
- const range = readRangeFilterValue(filterValue);
490
- const min = range?.min ? Number(range.min) : null;
491
- const max = range?.max ? Number(range.max) : null;
492
- const value = Number(row.getValue(columnId));
493
-
494
- if (min !== null && Number.isFinite(min) && value < min) {
495
- return false;
496
- }
497
-
498
- if (max !== null && Number.isFinite(max) && value > max) {
499
- return false;
500
- }
501
-
502
- return true;
503
- };
504
- }
505
-
506
- export function createDateInRangeFilter<
507
- TData extends RowData,
508
- >(): FilterFn<TData> {
509
- return (row, columnId, filterValue) => {
510
- const range = readDateRangeFilterValue(filterValue);
511
- const value = new Date(row.getValue<string>(columnId)).getTime();
512
- const from = range?.from
513
- ? new Date(`${range.from}T00:00:00`).getTime()
514
- : null;
515
- const to = range?.to ? new Date(`${range.to}T23:59:59`).getTime() : null;
516
-
517
- if (from !== null && Number.isFinite(from) && value < from) {
518
- return false;
519
- }
520
-
521
- if (to !== null && Number.isFinite(to) && value > to) {
522
- return false;
523
- }
524
-
525
- return true;
526
- };
527
- }
528
-
529
- export function getSingleArrayFilterValue(
530
- filterValue: unknown,
531
- ): "all" | "custom" | string {
532
- const { exclude, values } = readMultiFilterValue(filterValue);
533
-
534
- if (exclude && values.length > 0) {
535
- return "custom";
536
- }
537
-
538
- if (values.length === 0) {
539
- return "all";
540
- }
541
-
542
- if (values.length === 1) {
543
- return values[0] ?? "all";
544
- }
545
-
546
- return "custom";
547
- }
548
-
549
- export function DataTableColumnFilterTabs<TData extends RowData>({
550
- className,
551
- columnId,
552
- options,
553
- table,
554
- }: {
555
- className?: string;
556
- columnId: string;
557
- options: DataTableFilterTab[];
558
- table: TanstackTable<TData>;
559
- }) {
560
- const column = table.getColumn(columnId);
561
- const value = getSingleArrayFilterValue(column?.getFilterValue());
562
-
563
- const handleValueChange = (nextValue: string) => {
564
- column?.setFilterValue(nextValue === "all" ? undefined : [nextValue]);
565
- };
566
-
567
- return (
568
- <FilterTabs
569
- className={className}
570
- onValueChange={handleValueChange}
571
- options={options}
572
- value={value}
573
- />
574
- );
575
- }
576
-
577
- export function createDataTableFilterTabOptions<TItem>(
578
- items: TItem[],
579
- filters: Array<Pick<DataTableFilterTab, "label" | "value">>,
580
- getItemValue: (item: TItem) => string,
581
- ) {
582
- return filters.map((filter) => ({
583
- ...filter,
584
- count:
585
- filter.value === "all"
586
- ? undefined
587
- : items.filter((item) => getItemValue(item) === filter.value).length,
588
- }));
589
- }
590
-
591
- function getColumnId<TData extends RowData>(
592
- column: ColumnDef<TData, unknown>,
593
- ): string | null {
594
- if ("id" in column && column.id) {
595
- return column.id;
596
- }
597
-
598
- if ("accessorKey" in column && typeof column.accessorKey === "string") {
599
- return column.accessorKey;
600
- }
601
-
602
- return null;
603
- }
604
-
605
- function normalizeColumnOrder(
606
- columnOrder: ColumnOrderState | undefined,
607
- defaultColumnOrder: ColumnOrderState,
608
- lockedStartColumnIds: string[],
609
- lockedEndColumnIds: string[],
610
- ) {
611
- const validColumns = new Set(defaultColumnOrder);
612
- const lockedStart = lockedStartColumnIds.filter((columnId) =>
613
- validColumns.has(columnId),
614
- );
615
- const lockedEnd = lockedEndColumnIds.filter((columnId) =>
616
- validColumns.has(columnId),
617
- );
618
- const lockedColumns = new Set([...lockedStart, ...lockedEnd]);
619
- const movableColumns = (columnOrder ?? []).filter(
620
- (columnId) => validColumns.has(columnId) && !lockedColumns.has(columnId),
621
- );
622
-
623
- for (const columnId of defaultColumnOrder) {
624
- if (!lockedColumns.has(columnId) && !movableColumns.includes(columnId)) {
625
- movableColumns.push(columnId);
626
- }
627
- }
628
-
629
- return [...lockedStart, ...movableColumns, ...lockedEnd];
630
- }
631
-
632
- function areColumnOrdersEqual(left: ColumnOrderState, right: ColumnOrderState) {
633
- return (
634
- left.length === right.length &&
635
- left.every((columnId, index) => columnId === right[index])
636
- );
637
- }
638
-
639
- function getColumnMeta<TData extends RowData>(column: Column<TData, unknown>) {
640
- return column.columnDef.meta;
641
- }
642
-
643
- function getColumnLabel<TData extends RowData>(column: Column<TData, unknown>) {
644
- const header = column.columnDef.header;
645
-
646
- return (
647
- getColumnMeta(column)?.label ??
648
- (typeof header === "string" ? header : column.id)
649
- );
650
- }
651
-
652
- function getColumnAlign<TData extends RowData>(column: Column<TData, unknown>) {
653
- return getColumnMeta(column)?.align ?? "left";
654
- }
655
-
656
- function getColumnAlignClass<TData extends RowData>(
657
- column: Column<TData, unknown>,
658
- ) {
659
- const align = getColumnAlign(column);
660
-
661
- return cn(
662
- align === "center" && "text-center",
663
- align === "right" && "text-right",
664
- );
665
- }
666
-
667
- function getColumnAriaSort(
668
- isSorted: DataTableSortDirection,
669
- ): "ascending" | "descending" | undefined {
670
- if (!isSorted) {
671
- return undefined;
672
- }
673
-
674
- return isSorted === "asc" ? "ascending" : "descending";
675
- }
676
-
677
- function getHeaderControlVisibilityClass(isVisible: boolean) {
678
- if (isVisible) {
679
- return "pointer-events-auto opacity-100";
680
- }
681
-
682
- return "pointer-events-none opacity-0 group-focus-within/header:pointer-events-auto group-focus-within/header:opacity-100 group-hover/header:pointer-events-auto group-hover/header:opacity-100";
683
- }
684
-
685
- function hasRangeFilter(value: unknown) {
686
- const range = readObjectFilterValue(value);
687
- return Boolean(range.min || range.max || range.from || range.to);
688
- }
689
-
690
- function isFilterValueActive(value: unknown) {
691
- if (Array.isArray(value)) {
692
- return value.length > 0;
693
- }
694
-
695
- if (isRecord(value) && value.exclude === true) {
696
- return readMultiFilterValue(value).values.length > 0;
697
- }
698
-
699
- if (typeof value === "object") {
700
- return hasRangeFilter(value);
701
- }
702
-
703
- return Boolean(value);
704
- }
705
-
706
- function setObjectFilterValue<TData extends RowData>(
707
- column: Column<TData, unknown>,
708
- key: keyof DataTableObjectFilter,
709
- value: string,
710
- ) {
711
- const next = {
712
- ...readObjectFilterValue(column.getFilterValue()),
713
- [key]: value,
714
- };
715
-
716
- if (!hasRangeFilter(next)) {
717
- column.setFilterValue(undefined);
718
- return;
719
- }
720
-
721
- column.setFilterValue(next);
722
- }
723
-
724
- function setColumnSorting<TData extends RowData>(
725
- table: TanstackTable<TData>,
726
- columnId: string,
727
- desc: boolean,
728
- ) {
729
- table.setSorting((current) => {
730
- const next = [
731
- ...current.filter((sort) => sort.id !== columnId),
732
- { id: columnId, desc },
733
- ];
734
-
735
- return next.slice(-5);
736
- });
737
- }
738
-
739
- function clearColumnSorting<TData extends RowData>(
740
- table: TanstackTable<TData>,
741
- columnId: string,
742
- ) {
743
- table.setSorting((current) => current.filter((sort) => sort.id !== columnId));
744
- }
745
-
746
- function toggleColumnSorting<TData extends RowData>(
747
- table: TanstackTable<TData>,
748
- columnId: string,
749
- ) {
750
- table.setSorting((current) => {
751
- const currentSort = current.find((sort) => sort.id === columnId);
752
- const next = current.filter((sort) => sort.id !== columnId);
753
-
754
- if (!currentSort) {
755
- return [...next, { id: columnId, desc: false }].slice(-5);
756
- }
757
-
758
- if (!currentSort.desc) {
759
- return [...next, { id: columnId, desc: true }].slice(-5);
760
- }
761
-
762
- return next;
763
- });
764
- }
765
-
766
- function isColumnOrderState(value: unknown): value is ColumnOrderState {
767
- return (
768
- Array.isArray(value) &&
769
- value.every((columnId) => typeof columnId === "string")
770
- );
771
- }
772
-
773
- function isColumnFiltersState(value: unknown): value is ColumnFiltersState {
774
- return (
775
- Array.isArray(value) &&
776
- value.every((filter) => isRecord(filter) && typeof filter.id === "string")
777
- );
778
- }
779
-
780
- function isVisibilityState(value: unknown): value is VisibilityState {
781
- return (
782
- isRecord(value) &&
783
- Object.values(value).every((visible) => typeof visible === "boolean")
784
- );
785
- }
786
-
787
- function isSortingState(value: unknown): value is SortingState {
788
- return (
789
- Array.isArray(value) &&
790
- value.every(
791
- (sort) =>
792
- isRecord(sort) &&
793
- typeof sort.id === "string" &&
794
- typeof sort.desc === "boolean",
795
- )
796
- );
797
- }
798
-
799
- function parseStoredDataTableSettings(
800
- value: string,
801
- ): StoredDataTableSettings | null {
802
- const parsed = JSON.parse(value);
803
-
804
- if (!isRecord(parsed)) {
805
- return null;
806
- }
807
-
808
- const settings: StoredDataTableSettings = {};
809
-
810
- if (isColumnFiltersState(parsed.columnFilters)) {
811
- settings.columnFilters = parsed.columnFilters;
812
- }
813
-
814
- if (isColumnOrderState(parsed.columnOrder)) {
815
- settings.columnOrder = parsed.columnOrder;
816
- }
817
-
818
- if (isVisibilityState(parsed.columnVisibility)) {
819
- settings.columnVisibility = parsed.columnVisibility;
820
- }
821
-
822
- if (typeof parsed.globalFilter === "string") {
823
- settings.globalFilter = parsed.globalFilter;
824
- }
825
-
826
- if (typeof parsed.pageSize === "number" && Number.isFinite(parsed.pageSize)) {
827
- settings.pageSize = parsed.pageSize;
828
- }
829
-
830
- if (isSortingState(parsed.sorting)) {
831
- settings.sorting = parsed.sorting;
832
- }
833
-
834
- return settings;
835
- }
836
-
837
- function getStoredDataTableSettings(storageKey: string) {
838
- if (typeof window === "undefined") {
839
- return null;
840
- }
841
-
842
- try {
843
- const value = window.localStorage.getItem(storageKey);
844
- return value ? parseStoredDataTableSettings(value) : null;
845
- } catch {
846
- return null;
847
- }
848
- }
849
-
850
- function pickKnownColumnEntries<TValue>(
851
- record: Record<string, TValue> | undefined,
852
- columnIds: string[],
853
- ) {
854
- if (!record) {
855
- return undefined;
856
- }
857
-
858
- return Object.fromEntries(
859
- Object.entries(record).filter(([columnId]) => columnIds.includes(columnId)),
860
- );
861
- }
862
-
863
- function retainKnownColumnSettings(
864
- settings: StoredDataTableSettings | null,
865
- columnIds: string[],
866
- ): StoredDataTableSettings | null {
867
- if (!settings) {
868
- return null;
869
- }
870
-
871
- const sorting = settings.sorting?.filter((sort) =>
872
- columnIds.includes(sort.id),
873
- );
874
-
875
- return {
876
- ...settings,
877
- columnFilters: settings.columnFilters?.filter((filter) =>
878
- columnIds.includes(filter.id),
879
- ),
880
- columnSizing: pickKnownColumnEntries(settings.columnSizing, columnIds),
881
- columnVisibility: pickKnownColumnEntries(
882
- settings.columnVisibility,
883
- columnIds,
884
- ),
885
- sorting: sorting?.length ? sorting : undefined,
886
- };
887
- }
888
-
889
- function getResetFiltersStorageKey(event: Event) {
890
- if (!(event instanceof CustomEvent)) {
891
- return null;
892
- }
893
-
894
- const detail = event.detail;
895
- if (!isRecord(detail)) {
896
- return null;
897
- }
898
-
899
- const storageKey = detail.storageKey;
900
- return typeof storageKey === "string" ? storageKey : null;
901
- }
902
-
903
- function isLockedColumn(
904
- columnId: string,
905
- lockedStartColumnIds: string[],
906
- lockedEndColumnIds: string[],
907
- ) {
908
- return (
909
- lockedStartColumnIds.includes(columnId) ||
910
- lockedEndColumnIds.includes(columnId)
911
- );
912
- }
913
-
914
- function getStorageSafeId(storageKey: string) {
915
- return storageKey.replace(/[^a-zA-Z0-9_-]/g, "-");
916
- }
917
-
918
- function getOptionalColumnOrderKey(columnOrder?: ColumnOrderState) {
919
- return columnOrder?.join("|") ?? "";
920
- }
921
-
922
- function getColumnFiltersKey(columnFilters: ColumnFiltersState) {
923
- return JSON.stringify(columnFilters);
924
- }
925
-
926
- function getVisibilityStateKey(visibility: VisibilityState) {
927
- const entries = Object.entries(visibility).sort(([left], [right]) =>
928
- left.localeCompare(right),
929
- );
930
-
931
- return JSON.stringify(entries);
932
- }
933
-
934
- function getSortingKey(sorting: SortingState) {
935
- return JSON.stringify(sorting);
936
- }
937
-
938
- function useStableValueByKey<TValue>(value: TValue, key: string) {
939
- const [stored, setStored] = React.useState({ key, value });
940
-
941
- React.useEffect(() => {
942
- setStored((current) => (current.key === key ? current : { key, value }));
943
- }, [key, value]);
944
-
945
- return stored.value;
946
- }
947
-
948
- function useDataTableInstance<TData extends RowData>(
949
- options: TableOptions<TData>,
950
- ) {
951
- const resolvedOptions: TableOptionsResolved<TData> = {
952
- onStateChange: () => undefined,
953
- renderFallbackValue: null,
954
- state: {},
955
- ...options,
956
- };
957
-
958
- const [table] = React.useState(() => createTable<TData>(resolvedOptions));
959
- const [state, setState] = React.useState(() => table.initialState);
960
-
961
- table.setOptions((previous) => ({
962
- ...previous,
963
- ...options,
964
- onStateChange: (updater) => {
965
- setState(updater);
966
- options.onStateChange?.(updater);
967
- },
968
- state: {
969
- ...state,
970
- ...options.state,
971
- },
972
- }));
973
-
974
- return table;
975
- }
976
-
977
- const emptyColumnFilters: ColumnFiltersState = [];
978
- const emptyColumnSizing: ColumnSizingState = {};
979
- const emptyColumnVisibility: VisibilityState = {};
980
- const emptySorting: SortingState = [];
981
- const emptyLockedColumnIds: string[] = [];
982
- const defaultPageSizeOptions = [10, 20, 30, 50, 100];
983
-
984
- function resolvePageSize(
985
- pageSize: number | undefined,
986
- fallbackPageSize: number,
987
- pageSizeOptions: number[],
988
- ) {
989
- if (typeof pageSize === "number" && pageSizeOptions.includes(pageSize)) {
990
- return pageSize;
991
- }
992
-
993
- if (pageSizeOptions.includes(fallbackPageSize)) {
994
- return fallbackPageSize;
995
- }
996
-
997
- return pageSizeOptions[0] ?? fallbackPageSize;
998
- }
999
-
1000
- export function DataTable<TData extends RowData>(props: DataTableProps<TData>) {
1001
- const {
1002
- activeRowId,
1003
- columns,
1004
- data,
1005
- emptyMessage,
1006
- emptyState,
1007
- fillHeight = false,
1008
- loading = false,
1009
- error,
1010
- onRetry,
1011
- warning,
1012
- unavailable,
1013
- enablePersistence: enablePersistenceProp,
1014
- enableRowSelection = false,
1015
- filterFns,
1016
- formatResultCount: formatResultCountProp,
1017
- formatRowCount: formatRowCountProp,
1018
- formatSelectedRowCount,
1019
- getRowId,
1020
- globalFilterFn,
1021
- initialColumnFilters = emptyColumnFilters,
1022
- initialGlobalFilter = "",
1023
- onRowClick,
1024
- getRowLabel,
1025
- initialColumnOrder,
1026
- initialColumnVisibility = emptyColumnVisibility,
1027
- initialPageSize = 10,
1028
- initialSorting = emptySorting,
1029
- lockedEndColumnIds = emptyLockedColumnIds,
1030
- lockedStartColumnIds = emptyLockedColumnIds,
1031
- manualFiltering = false,
1032
- enableExcludeFilters,
1033
- manualPagination = false,
1034
- manualSorting = false,
1035
- onStateChange,
1036
- pageCount,
1037
- pageSizeOptions = defaultPageSizeOptions,
1038
- rowCount,
1039
- rowSelectionActions,
1040
- searchPlaceholder,
1041
- storageKey: storageKeyProp,
1042
- toolbarBelow,
1043
- toolbarEnd,
1044
- toolbarStart,
1045
- } = props;
1046
- const t = useMessages(dataTableMessages);
1047
- const ui = useUiMessages();
1048
- // Persistence needs a key; without one the table keeps state in memory only.
1049
- const storageKey = storageKeyProp ?? "";
1050
- const enablePersistence =
1051
- Boolean(storageKeyProp) && enablePersistenceProp !== false;
1052
- const formatResultCount = formatResultCountProp ?? t.resultCount;
1053
- const formatRowCount = formatRowCountProp ?? t.rowCount;
1054
-
1055
- const defaultColumnOrder = React.useMemo(
1056
- () => columns.map(getColumnId).filter(isString),
1057
- [columns],
1058
- );
1059
- const defaultColumnOrderKey = defaultColumnOrder.join("|");
1060
- const pageSizeOptionsKey = pageSizeOptions.join("|");
1061
- const lockedStartColumnKey = lockedStartColumnIds.join("|");
1062
- const lockedEndColumnKey = lockedEndColumnIds.join("|");
1063
- const stablePageSizeOptions = useStableValueByKey(
1064
- pageSizeOptions,
1065
- pageSizeOptionsKey,
1066
- );
1067
- const stableDefaultColumnOrder = useStableValueByKey(
1068
- defaultColumnOrder,
1069
- defaultColumnOrderKey,
1070
- );
1071
- const stableInitialColumnFilters = useStableValueByKey(
1072
- initialColumnFilters,
1073
- getColumnFiltersKey(initialColumnFilters),
1074
- );
1075
- const stableInitialColumnOrder = useStableValueByKey(
1076
- initialColumnOrder,
1077
- getOptionalColumnOrderKey(initialColumnOrder),
1078
- );
1079
- const stableInitialColumnVisibility = useStableValueByKey(
1080
- initialColumnVisibility,
1081
- getVisibilityStateKey(initialColumnVisibility),
1082
- );
1083
- const stableInitialSorting = useStableValueByKey(
1084
- initialSorting,
1085
- getSortingKey(initialSorting),
1086
- );
1087
- const stableLockedStartColumnIds = useStableValueByKey(
1088
- lockedStartColumnIds,
1089
- lockedStartColumnKey,
1090
- );
1091
- const stableLockedEndColumnIds = useStableValueByKey(
1092
- lockedEndColumnIds,
1093
- lockedEndColumnKey,
1094
- );
1095
- const [preferencesReady, setPreferencesReady] =
1096
- React.useState(!enablePersistence);
1097
- const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});
1098
- const [columnVisibility, setColumnVisibility] =
1099
- React.useState<VisibilityState>(stableInitialColumnVisibility);
1100
- const [columnOrder, setColumnOrder] = React.useState<ColumnOrderState>(() =>
1101
- normalizeColumnOrder(
1102
- stableInitialColumnOrder ?? stableDefaultColumnOrder,
1103
- stableDefaultColumnOrder,
1104
- stableLockedStartColumnIds,
1105
- stableLockedEndColumnIds,
1106
- ),
1107
- );
1108
- const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
1109
- stableInitialColumnFilters,
1110
- );
1111
- const [columnSizing, setColumnSizing] =
1112
- React.useState<ColumnSizingState>(emptyColumnSizing);
1113
- const [sorting, setSorting] =
1114
- React.useState<SortingState>(stableInitialSorting);
1115
- const [globalFilter, setGlobalFilter] = React.useState(initialGlobalFilter);
1116
- const [pagination, setPagination] = React.useState<PaginationState>({
1117
- pageIndex: 0,
1118
- pageSize: resolvePageSize(
1119
- initialPageSize,
1120
- initialPageSize,
1121
- stablePageSizeOptions,
1122
- ),
1123
- });
1124
- const resetPaginationPage = React.useCallback(() => {
1125
- setPagination((current) =>
1126
- current.pageIndex === 0 ? current : { ...current, pageIndex: 0 },
1127
- );
1128
- }, []);
1129
- const handleColumnFiltersChange = React.useCallback<
1130
- OnChangeFn<ColumnFiltersState>
1131
- >(
1132
- (updater) => {
1133
- setColumnFilters(updater);
1134
- resetPaginationPage();
1135
- },
1136
- [resetPaginationPage],
1137
- );
1138
- const handleGlobalFilterChange = React.useCallback<OnChangeFn<string>>(
1139
- (updater) => {
1140
- setGlobalFilter(updater);
1141
- resetPaginationPage();
1142
- },
1143
- [resetPaginationPage],
1144
- );
1145
- const handleSortingChange = React.useCallback<OnChangeFn<SortingState>>(
1146
- (updater) => {
1147
- setSorting(updater);
1148
- resetPaginationPage();
1149
- },
1150
- [resetPaginationPage],
1151
- );
1152
-
1153
- const dndContextId = React.useId();
1154
- const sensors = useSensors(
1155
- useSensor(MouseSensor, {
1156
- activationConstraint: {
1157
- distance: 6,
1158
- },
1159
- }),
1160
- useSensor(TouchSensor, {
1161
- activationConstraint: {
1162
- delay: 150,
1163
- tolerance: 6,
1164
- },
1165
- }),
1166
- useSensor(KeyboardSensor),
1167
- );
1168
-
1169
- React.useEffect(() => {
1170
- if (!enablePersistence) {
1171
- return;
1172
- }
1173
-
1174
- const settings = retainKnownColumnSettings(
1175
- getStoredDataTableSettings(storageKey),
1176
- stableDefaultColumnOrder,
1177
- );
1178
-
1179
- setColumnVisibility(
1180
- settings?.columnVisibility ?? stableInitialColumnVisibility,
1181
- );
1182
- setColumnOrder(
1183
- normalizeColumnOrder(
1184
- settings?.columnOrder ??
1185
- stableInitialColumnOrder ??
1186
- stableDefaultColumnOrder,
1187
- stableDefaultColumnOrder,
1188
- stableLockedStartColumnIds,
1189
- stableLockedEndColumnIds,
1190
- ),
1191
- );
1192
- setColumnFilters(settings?.columnFilters ?? stableInitialColumnFilters);
1193
- setColumnSizing(settings?.columnSizing ?? emptyColumnSizing);
1194
- setSorting(settings?.sorting ?? stableInitialSorting);
1195
- setGlobalFilter(settings?.globalFilter ?? "");
1196
- setPagination({
1197
- pageIndex: 0,
1198
- pageSize: resolvePageSize(
1199
- settings?.pageSize,
1200
- initialPageSize,
1201
- stablePageSizeOptions,
1202
- ),
1203
- });
1204
- setPreferencesReady(true);
1205
- }, [
1206
- enablePersistence,
1207
- initialPageSize,
1208
- stableDefaultColumnOrder,
1209
- stableInitialColumnFilters,
1210
- stableInitialColumnOrder,
1211
- stableInitialColumnVisibility,
1212
- stableInitialSorting,
1213
- stableLockedEndColumnIds,
1214
- stableLockedStartColumnIds,
1215
- stablePageSizeOptions,
1216
- storageKey,
1217
- ]);
1218
-
1219
- React.useEffect(() => {
1220
- if (!preferencesReady) {
1221
- return;
1222
- }
1223
-
1224
- setColumnOrder((currentOrder) =>
1225
- normalizeColumnOrder(
1226
- currentOrder,
1227
- stableDefaultColumnOrder,
1228
- stableLockedStartColumnIds,
1229
- stableLockedEndColumnIds,
1230
- ),
1231
- );
1232
- }, [
1233
- preferencesReady,
1234
- stableDefaultColumnOrder,
1235
- stableLockedEndColumnIds,
1236
- stableLockedStartColumnIds,
1237
- ]);
1238
-
1239
- React.useEffect(() => {
1240
- if (!enablePersistence || !preferencesReady) {
1241
- return;
1242
- }
1243
-
1244
- window.localStorage.setItem(
1245
- storageKey,
1246
- JSON.stringify({
1247
- columnFilters,
1248
- columnOrder,
1249
- columnSizing,
1250
- columnVisibility,
1251
- globalFilter,
1252
- pageSize: pagination.pageSize,
1253
- sorting,
1254
- } satisfies StoredDataTableSettings),
1255
- );
1256
- }, [
1257
- columnFilters,
1258
- columnOrder,
1259
- columnSizing,
1260
- columnVisibility,
1261
- enablePersistence,
1262
- globalFilter,
1263
- pagination.pageSize,
1264
- preferencesReady,
1265
- sorting,
1266
- storageKey,
1267
- ]);
1268
-
1269
- React.useEffect(() => {
1270
- if (!preferencesReady) {
1271
- return;
1272
- }
1273
-
1274
- onStateChange?.({
1275
- columnFilters,
1276
- globalFilter,
1277
- pagination,
1278
- sorting,
1279
- });
1280
- }, [
1281
- columnFilters,
1282
- globalFilter,
1283
- onStateChange,
1284
- pagination,
1285
- preferencesReady,
1286
- sorting,
1287
- ]);
1288
-
1289
- const table = useDataTableInstance<TData>({
1290
- // TanStack schedules auto resets while evaluating row models during render.
1291
- // Concurrent/Suspense renders may not have committed yet, so reset in an effect.
1292
- autoResetPageIndex: false,
1293
- columnResizeMode: "onChange",
1294
- columns,
1295
- data,
1296
- enableColumnResizing: true,
1297
- enableMultiSort: true,
1298
- enableRowSelection,
1299
- filterFns,
1300
- getCoreRowModel: getCoreRowModel(),
1301
- getFilteredRowModel: getFilteredRowModel(),
1302
- getPaginationRowModel: getPaginationRowModel(),
1303
- getRowId,
1304
- getSortedRowModel: getSortedRowModel(),
1305
- // An explicit undefined would replace TanStack's default and disable search.
1306
- globalFilterFn: globalFilterFn ?? "includesString",
1307
- isMultiSortEvent: () => true,
1308
- manualFiltering,
1309
- manualPagination,
1310
- manualSorting,
1311
- maxMultiSortColCount: 5,
1312
- meta: {
1313
- enableExcludeFilters:
1314
- enableExcludeFilters ?? (!manualFiltering && !onStateChange),
1315
- },
1316
- onColumnFiltersChange: handleColumnFiltersChange,
1317
- onColumnOrderChange: setColumnOrder,
1318
- onColumnSizingChange: setColumnSizing,
1319
- onColumnVisibilityChange: setColumnVisibility,
1320
- onGlobalFilterChange: handleGlobalFilterChange,
1321
- onPaginationChange: setPagination,
1322
- onRowSelectionChange: setRowSelection,
1323
- onSortingChange: handleSortingChange,
1324
- pageCount,
1325
- rowCount,
1326
- state: {
1327
- columnFilters,
1328
- columnOrder,
1329
- columnSizing,
1330
- columnVisibility,
1331
- globalFilter,
1332
- pagination,
1333
- rowSelection,
1334
- sorting,
1335
- },
1336
- });
1337
-
1338
- React.useEffect(() => {
1339
- if (!manualPagination) resetPaginationPage();
1340
- }, [data, manualPagination, resetPaginationPage]);
1341
-
1342
- const handleDragEnd = (event: DragEndEvent) => {
1343
- const { active, over } = event;
1344
-
1345
- if (!over || active.id === over.id) {
1346
- return;
1347
- }
1348
-
1349
- if (
1350
- isLockedColumn(
1351
- String(active.id),
1352
- stableLockedStartColumnIds,
1353
- stableLockedEndColumnIds,
1354
- )
1355
- ) {
1356
- return;
1357
- }
1358
-
1359
- setColumnOrder((currentOrder) => {
1360
- const oldIndex = currentOrder.indexOf(String(active.id));
1361
- const newIndex = currentOrder.indexOf(String(over.id));
1362
-
1363
- if (oldIndex === -1 || newIndex === -1) {
1364
- return currentOrder;
1365
- }
1366
-
1367
- return normalizeColumnOrder(
1368
- arrayMove(currentOrder, oldIndex, newIndex),
1369
- stableDefaultColumnOrder,
1370
- stableLockedStartColumnIds,
1371
- stableLockedEndColumnIds,
1372
- );
1373
- });
1374
- };
1375
-
1376
- const resetColumns = () => {
1377
- setColumnVisibility(stableInitialColumnVisibility);
1378
- setColumnOrder(
1379
- normalizeColumnOrder(
1380
- stableInitialColumnOrder ?? stableDefaultColumnOrder,
1381
- stableDefaultColumnOrder,
1382
- stableLockedStartColumnIds,
1383
- stableLockedEndColumnIds,
1384
- ),
1385
- );
1386
- setColumnSizing(emptyColumnSizing);
1387
- };
1388
-
1389
- const resetFilters = React.useCallback(() => {
1390
- setColumnFilters(stableInitialColumnFilters);
1391
- setGlobalFilter("");
1392
- setPagination((current) => ({ ...current, pageIndex: 0 }));
1393
- }, [stableInitialColumnFilters]);
1394
-
1395
- React.useEffect(() => {
1396
- const handleResetFilters = (event: Event) => {
1397
- const resetStorageKey = getResetFiltersStorageKey(event);
1398
-
1399
- if (resetStorageKey && resetStorageKey !== storageKey) {
1400
- return;
1401
- }
1402
-
1403
- resetFilters();
1404
- };
1405
-
1406
- window.addEventListener(DATA_TABLE_RESET_FILTERS_EVENT, handleResetFilters);
1407
-
1408
- return () => {
1409
- window.removeEventListener(
1410
- DATA_TABLE_RESET_FILTERS_EVENT,
1411
- handleResetFilters,
1412
- );
1413
- };
1414
- }, [resetFilters, storageKey]);
1415
-
1416
- if (!preferencesReady) {
1417
- return <DataTableSkeleton />;
1418
- }
1419
-
1420
- const retry = onRetry ? (
1421
- <Button variant="outline" size="sm" onClick={onRetry}>
1422
- <RotateCwIcon data-icon="inline-start" />
1423
- {ui.retry}
1424
- </Button>
1425
- ) : null;
1426
-
1427
- if (unavailable) {
1428
- return (
1429
- <Empty className="rounded-3xl border border-dashed">
1430
- <EmptyHeader>
1431
- <EmptyMedia variant="icon">
1432
- <LockIcon />
1433
- </EmptyMedia>
1434
- <EmptyTitle>{unavailable}</EmptyTitle>
1435
- </EmptyHeader>
1436
- </Empty>
1437
- );
1438
- }
1439
-
1440
- if (error && !data.length && !loading) {
1441
- return (
1442
- <Empty className="rounded-3xl border border-dashed">
1443
- <EmptyHeader>
1444
- <EmptyMedia variant="icon">
1445
- <CircleAlertIcon />
1446
- </EmptyMedia>
1447
- <EmptyTitle>{ui.loadFailed}</EmptyTitle>
1448
- <EmptyDescription>{error}</EmptyDescription>
1449
- </EmptyHeader>
1450
- {retry ? <EmptyContent>{retry}</EmptyContent> : null}
1451
- </Empty>
1452
- );
1453
- }
1454
-
1455
- const isFiltered = Boolean(globalFilter) || columnFilters.length > 0;
1456
-
1457
- const filteredRowCount = rowCount ?? table.getFilteredRowModel().rows.length;
1458
- const selectedRowCount = table.getFilteredSelectedRowModel().rows.length;
1459
- const selectedRowsLabel =
1460
- formatSelectedRowCount ??
1461
- ((count: number) => t.selected(formatRowCount(count), count));
1462
- const toolbarStartContent = toolbarStart?.(table);
1463
- const toolbarEndContent = toolbarEnd?.(table);
1464
- const toolbarBelowContent = toolbarBelow?.(table);
1465
- const rowSelectionActionsContent = rowSelectionActions?.(table);
1466
-
1467
- return (
1468
- <div
1469
- className={cn(
1470
- "flex w-full min-w-0 flex-col gap-4",
1471
- fillHeight && "min-h-0 flex-1",
1472
- )}
1473
- >
1474
- <div className="flex min-w-0 flex-wrap items-center gap-2">
1475
- {toolbarStartContent}
1476
- <div className="flex min-w-0 flex-1 basis-80 items-center gap-2">
1477
- <InputGroup className="flex-1">
1478
- <InputGroupInput
1479
- value={globalFilter}
1480
- onChange={(event) => handleGlobalFilterChange(event.target.value)}
1481
- placeholder={searchPlaceholder ?? t.search}
1482
- />
1483
- <InputGroupAddon className="pl-2">
1484
- <SearchIcon />
1485
- </InputGroupAddon>
1486
- <InputGroupAddon align="inline-end" className="pr-2">
1487
- {formatResultCount(filteredRowCount)}
1488
- </InputGroupAddon>
1489
- </InputGroup>
1490
- {toolbarEndContent}
1491
- <ColumnSettings
1492
- defaultColumnOrder={defaultColumnOrder}
1493
- lockedEndColumnIds={lockedEndColumnIds}
1494
- lockedStartColumnIds={lockedStartColumnIds}
1495
- onResetColumns={resetColumns}
1496
- table={table}
1497
- />
1498
- </div>
1499
- </div>
1500
-
1501
- {toolbarBelowContent}
1502
-
1503
- {error ? (
1504
- <Alert variant="destructive">
1505
- <CircleAlertIcon />
1506
- <AlertTitle>{ui.staleData}</AlertTitle>
1507
- <AlertDescription>{error}</AlertDescription>
1508
- {retry ? <AlertAction>{retry}</AlertAction> : null}
1509
- </Alert>
1510
- ) : null}
1511
- {warning ? (
1512
- <Alert>
1513
- <TriangleAlertIcon />
1514
- <AlertTitle>{warning}</AlertTitle>
1515
- </Alert>
1516
- ) : null}
1517
-
1518
- {enableRowSelection && selectedRowCount > 0 && (
1519
- <div className="bg-muted/40 flex flex-col gap-2 rounded-2xl border p-2 sm:flex-row sm:items-center sm:justify-between">
1520
- <p className="text-foreground px-1 text-sm font-medium">
1521
- {selectedRowsLabel(selectedRowCount)}
1522
- </p>
1523
- <div className="flex flex-wrap items-center gap-2">
1524
- {rowSelectionActionsContent}
1525
- <Button
1526
- type="button"
1527
- variant="outline"
1528
- size="sm"
1529
- onClick={() => table.resetRowSelection()}
1530
- >
1531
- <XIcon data-icon="inline-start" />
1532
- {t.clearSelection}
1533
- </Button>
1534
- </div>
1535
- </div>
1536
- )}
1537
-
1538
- <DndContext
1539
- // Stable id: dnd-kit's global counter differs between server and client.
1540
- id={dndContextId}
1541
- collisionDetection={closestCenter}
1542
- modifiers={[restrictToHorizontalAxis]}
1543
- onDragEnd={handleDragEnd}
1544
- sensors={sensors}
1545
- >
1546
- <div
1547
- className={cn(
1548
- "bg-card overflow-hidden rounded-2xl border",
1549
- fillHeight && "flex min-h-0 flex-1 flex-col",
1550
- )}
1551
- >
1552
- <Table
1553
- containerClassName={
1554
- // Bottom-only fade: a top fade would dissolve the sticky header.
1555
- fillHeight
1556
- ? "min-h-0 flex-1 overflow-auto scroll-fade-b"
1557
- : undefined
1558
- }
1559
- style={{ minWidth: "100%", width: table.getTotalSize() }}
1560
- >
1561
- {/* Solid background: rows scroll underneath the sticky header. */}
1562
- <TableHeader className="bg-muted sticky top-0 z-10">
1563
- {table.getHeaderGroups().map((headerGroup) => (
1564
- <TableRow key={headerGroup.id}>
1565
- <SortableContext
1566
- items={columnOrder}
1567
- strategy={horizontalListSortingStrategy}
1568
- >
1569
- {headerGroup.headers.map((header) => (
1570
- <DataTableHead
1571
- key={header.id}
1572
- header={header}
1573
- lockedEndColumnIds={lockedEndColumnIds}
1574
- lockedStartColumnIds={lockedStartColumnIds}
1575
- />
1576
- ))}
1577
- </SortableContext>
1578
- </TableRow>
1579
- ))}
1580
- </TableHeader>
1581
- <TableBody>
1582
- {loading ? (
1583
- Array.from({ length: 3 }, (_, index) => (
1584
- <TableRow key={index}>
1585
- {table.getVisibleLeafColumns().map((column) => (
1586
- <TableCell key={column.id}>
1587
- <Skeleton className="h-5 w-full" />
1588
- </TableCell>
1589
- ))}
1590
- </TableRow>
1591
- ))
1592
- ) : table.getRowModel().rows?.length ? (
1593
- table.getRowModel().rows.map((row) => (
1594
- <TableRow
1595
- key={row.id}
1596
- data-active={row.id === activeRowId || undefined}
1597
- aria-current={row.id === activeRowId ? "true" : undefined}
1598
- data-state={row.getIsSelected() && "selected"}
1599
- className={onRowClick ? "cursor-pointer" : undefined}
1600
- tabIndex={onRowClick ? 0 : undefined}
1601
- aria-label={
1602
- onRowClick
1603
- ? `${t.open}: ${getRowLabel?.(row.original) ?? row.id}`
1604
- : undefined
1605
- }
1606
- onClick={
1607
- onRowClick ? () => onRowClick(row.original) : undefined
1608
- }
1609
- onKeyDown={
1610
- onRowClick
1611
- ? (event) => {
1612
- if (event.key === "Enter" || event.key === " ") {
1613
- event.preventDefault();
1614
- onRowClick(row.original);
1615
- }
1616
- }
1617
- : undefined
1618
- }
1619
- >
1620
- {row.getVisibleCells().map((cell) => (
1621
- <TableCell
1622
- key={cell.id}
1623
- className={cn(
1624
- "whitespace-nowrap",
1625
- getColumnAlignClass(cell.column),
1626
- getColumnMeta(cell.column)?.cellClassName,
1627
- )}
1628
- style={{ width: cell.column.getSize() }}
1629
- >
1630
- {flexRender(
1631
- cell.column.columnDef.cell,
1632
- cell.getContext(),
1633
- )}
1634
- </TableCell>
1635
- ))}
1636
- </TableRow>
1637
- ))
1638
- ) : (
1639
- <TableRow>
1640
- <TableCell
1641
- colSpan={table.getVisibleLeafColumns().length}
1642
- className="text-muted-foreground h-24 text-center"
1643
- >
1644
- {isFiltered ? (
1645
- <Empty>
1646
- <EmptyHeader>
1647
- <EmptyTitle>
1648
- {emptyMessage ?? ui.noResults}
1649
- </EmptyTitle>
1650
- </EmptyHeader>
1651
- <EmptyContent>
1652
- <Button
1653
- variant="outline"
1654
- size="sm"
1655
- onClick={resetFilters}
1656
- >
1657
- {t.clearFilters}
1658
- </Button>
1659
- </EmptyContent>
1660
- </Empty>
1661
- ) : (
1662
- (emptyState ?? (
1663
- <Empty>
1664
- <EmptyHeader>
1665
- <EmptyMedia variant="icon">
1666
- <InboxIcon />
1667
- </EmptyMedia>
1668
- <EmptyTitle>{emptyMessage ?? ui.noData}</EmptyTitle>
1669
- </EmptyHeader>
1670
- </Empty>
1671
- ))
1672
- )}
1673
- </TableCell>
1674
- </TableRow>
1675
- )}
1676
- </TableBody>
1677
- </Table>
1678
- </div>
1679
- </DndContext>
1680
-
1681
- <DataTablePagination
1682
- formatRowCount={formatRowCount}
1683
- formatSelectedRowCount={formatSelectedRowCount}
1684
- pageSizeOptions={stablePageSizeOptions}
1685
- rowCount={rowCount}
1686
- storageKey={storageKey}
1687
- table={table}
1688
- />
1689
- </div>
1690
- );
1691
- }
1692
-
1693
- function DataTableHead<TData extends RowData>({
1694
- header,
1695
- lockedEndColumnIds,
1696
- lockedStartColumnIds,
1697
- }: {
1698
- header: Header<TData, unknown>;
1699
- lockedEndColumnIds: string[];
1700
- lockedStartColumnIds: string[];
1701
- }) {
1702
- const t = useMessages(dataTableMessages);
1703
- const column = header.column;
1704
- const table = header.getContext().table;
1705
- const align = getColumnAlign(column);
1706
- const isSorted = column.getIsSorted();
1707
- const sortIndex = table
1708
- .getState()
1709
- .sorting.findIndex((sort) => sort.id === column.id);
1710
- const isLocked = isLockedColumn(
1711
- column.id,
1712
- lockedStartColumnIds,
1713
- lockedEndColumnIds,
1714
- );
1715
- const canOpenColumnMenu = !header.isPlaceholder && !isLocked;
1716
- const {
1717
- attributes,
1718
- isDragging,
1719
- listeners,
1720
- setNodeRef,
1721
- transform,
1722
- transition,
1723
- } = useSortable({
1724
- id: column.id,
1725
- disabled: isLocked,
1726
- });
1727
- const [menuOpen, setMenuOpen] = React.useState(false);
1728
-
1729
- const columnControls =
1730
- column.getCanSort() || !isLocked ? (
1731
- <div
1732
- className={cn(
1733
- "flex shrink-0 items-center gap-1",
1734
- align === "right" ? "order-first mr-1" : "ml-1",
1735
- )}
1736
- >
1737
- {column.getCanSort() && (
1738
- <Button
1739
- type="button"
1740
- variant="ghost"
1741
- size="icon-xs"
1742
- className={cn(
1743
- "transition-opacity",
1744
- isSorted ? "text-foreground bg-accent" : "text-muted-foreground",
1745
- getHeaderControlVisibilityClass(Boolean(isSorted)),
1746
- )}
1747
- onClick={() => toggleColumnSorting(table, column.id)}
1748
- aria-label={t.toggleSort(getColumnLabel(column))}
1749
- >
1750
- <ColumnSortIcon isSorted={isSorted} />
1751
- </Button>
1752
- )}
1753
- {sortIndex >= 0 && table.getState().sorting.length > 1 && (
1754
- <Badge
1755
- variant="secondary"
1756
- className="px-1"
1757
- title={t.sortCriterionTitle(sortIndex + 1)}
1758
- >
1759
- {sortIndex + 1}
1760
- </Badge>
1761
- )}
1762
- {!isLocked && (
1763
- <Button
1764
- type="button"
1765
- variant="ghost"
1766
- size="icon-xs"
1767
- className={cn(
1768
- "text-muted-foreground cursor-grab transition-opacity active:cursor-grabbing",
1769
- getHeaderControlVisibilityClass(isDragging),
1770
- )}
1771
- aria-label={t.reorderColumn(getColumnLabel(column))}
1772
- {...attributes}
1773
- {...listeners}
1774
- >
1775
- <GripVerticalIcon />
1776
- </Button>
1777
- )}
1778
- </div>
1779
- ) : null;
1780
-
1781
- return (
1782
- <TableHead
1783
- ref={setNodeRef}
1784
- colSpan={header.colSpan}
1785
- aria-sort={getColumnAriaSort(isSorted)}
1786
- className={cn(
1787
- "relative whitespace-nowrap",
1788
- getColumnAlignClass(column),
1789
- getColumnMeta(column)?.headerClassName,
1790
- isDragging && "bg-muted relative z-20 opacity-80",
1791
- )}
1792
- style={{
1793
- transform: CSS.Translate.toString(transform),
1794
- transition,
1795
- width: header.getSize(),
1796
- }}
1797
- >
1798
- {header.isPlaceholder ? null : (
1799
- <div
1800
- className={cn(
1801
- "group/header flex w-full items-center",
1802
- align === "center" && "justify-center",
1803
- align === "right" && "justify-end",
1804
- )}
1805
- >
1806
- <div className="flex min-w-0 flex-1 items-center">
1807
- {canOpenColumnMenu ? (
1808
- <ColumnHeaderMenu
1809
- header={header}
1810
- open={menuOpen}
1811
- onOpenChange={setMenuOpen}
1812
- />
1813
- ) : (
1814
- <div className="flex h-8 items-center px-0">
1815
- {flexRender(column.columnDef.header, header.getContext())}
1816
- </div>
1817
- )}
1818
- </div>
1819
- {columnControls}
1820
- </div>
1821
- )}
1822
- {column.getCanResize() && !isLocked ? (
1823
- <div
1824
- role="separator"
1825
- aria-orientation="vertical"
1826
- aria-label={t.resizeColumn(getColumnLabel(column))}
1827
- className={cn(
1828
- "hover:bg-primary/50 absolute inset-y-0 right-0 z-10 w-1 cursor-col-resize touch-none bg-transparent select-none",
1829
- column.getIsResizing() && "bg-primary",
1830
- )}
1831
- onDoubleClick={() => column.resetSize()}
1832
- onMouseDown={header.getResizeHandler()}
1833
- onTouchStart={header.getResizeHandler()}
1834
- />
1835
- ) : null}
1836
- </TableHead>
1837
- );
1838
- }
1839
-
1840
- function ColumnHeaderMenuTrigger<TData extends RowData>({
1841
- className,
1842
- header,
1843
- }: {
1844
- className?: string;
1845
- header: Header<TData, unknown>;
1846
- }) {
1847
- const t = useMessages(dataTableMessages);
1848
- const column = header.column;
1849
- const align = getColumnAlign(column);
1850
- const isFiltered = isFilterValueActive(column.getFilterValue());
1851
- const isExcluding =
1852
- isFiltered && readMultiFilterValue(column.getFilterValue()).exclude;
1853
- const ActiveFilterIcon = isExcluding ? FunnelXIcon : FunnelIcon;
1854
-
1855
- return (
1856
- <PopoverTrigger
1857
- render={
1858
- <Button
1859
- type="button"
1860
- variant="ghost"
1861
- size="sm"
1862
- className={cn(
1863
- "relative -mx-2.5 h-8 w-[calc(100%+1.25rem)] min-w-0 justify-start px-2.5",
1864
- align === "center" && "justify-center",
1865
- align === "right" && "justify-end",
1866
- className,
1867
- )}
1868
- />
1869
- }
1870
- >
1871
- <span className="truncate">{getColumnLabel(column)}</span>
1872
- {isFiltered && (
1873
- <>
1874
- <ActiveFilterIcon data-icon="inline-end" aria-hidden />
1875
- <span className="sr-only">
1876
- {isExcluding ? t.excludeFilterActive : t.filterActive}
1877
- </span>
1878
- </>
1879
- )}
1880
- </PopoverTrigger>
1881
- );
1882
- }
1883
-
1884
- function ColumnSortIcon({ isSorted }: { isSorted: DataTableSortDirection }) {
1885
- if (isSorted === "asc") {
1886
- return <ArrowUpNarrowWideIcon data-icon="inline-end" />;
1887
- }
1888
-
1889
- if (isSorted === "desc") {
1890
- return <ArrowDownWideNarrowIcon data-icon="inline-end" />;
1891
- }
1892
-
1893
- return <ArrowUpDownIcon data-icon="inline-end" />;
1894
- }
1895
-
1896
- function ColumnHeaderMenu<TData extends RowData>({
1897
- header,
1898
- onOpenChange,
1899
- open,
1900
- }: {
1901
- header: Header<TData, unknown>;
1902
- onOpenChange: (open: boolean) => void;
1903
- open: boolean;
1904
- }) {
1905
- const t = useMessages(dataTableMessages);
1906
- const column = header.column;
1907
- const table = header.getContext().table;
1908
- const isSorted = column.getIsSorted();
1909
- const isFiltered = isFilterValueActive(column.getFilterValue());
1910
- const sorting = table.getState().sorting;
1911
- const sortIndex = sorting.findIndex((sort) => sort.id === column.id);
1912
- const sortCount = sorting.length;
1913
- const hasColumnState = Boolean(isSorted) || isFiltered;
1914
-
1915
- const clearColumnState = () => {
1916
- column.setFilterValue(undefined);
1917
- clearColumnSorting(table, column.id);
1918
- };
1919
-
1920
- return (
1921
- <Popover open={open} onOpenChange={onOpenChange}>
1922
- <ColumnHeaderMenuTrigger header={header} />
1923
- <PopoverContent align="start" className="w-72 p-0">
1924
- <div className="flex flex-col gap-3 p-3">
1925
- <div className="flex min-w-0 items-start justify-between gap-2">
1926
- <div className="min-w-0">
1927
- <div className="truncate text-sm font-medium">
1928
- {getColumnLabel(column)}
1929
- </div>
1930
- </div>
1931
- {sortIndex >= 0 && sortCount > 1 && (
1932
- <Badge variant="outline" className="shrink-0">
1933
- {t.sortCriterion(sortIndex + 1)}
1934
- </Badge>
1935
- )}
1936
- </div>
1937
-
1938
- {column.getCanSort() && (
1939
- <ColumnSortControls
1940
- column={column}
1941
- isSorted={isSorted}
1942
- table={table}
1943
- />
1944
- )}
1945
-
1946
- <ColumnFilterControls
1947
- allowExclude={Boolean(table.options.meta?.enableExcludeFilters)}
1948
- column={column}
1949
- />
1950
-
1951
- {(hasColumnState || column.getCanHide()) && (
1952
- <>
1953
- <Separator />
1954
- <div className="flex gap-2">
1955
- {hasColumnState && (
1956
- <Button
1957
- variant="ghost"
1958
- size="sm"
1959
- className="flex-1"
1960
- onClick={clearColumnState}
1961
- >
1962
- <XIcon data-icon="inline-start" />
1963
- {t.clearAll}
1964
- </Button>
1965
- )}
1966
- {column.getCanHide() && (
1967
- <Button
1968
- variant="outline"
1969
- size="sm"
1970
- className="flex-1"
1971
- onClick={() => column.toggleVisibility(false)}
1972
- >
1973
- <EyeOffIcon data-icon="inline-start" />
1974
- {t.hide}
1975
- </Button>
1976
- )}
1977
- </div>
1978
- </>
1979
- )}
1980
- </div>
1981
- </PopoverContent>
1982
- </Popover>
1983
- );
1984
- }
1985
-
1986
- // Pressed option inside the column menu; the selected state uses the primary
1987
- // fill plus a check so it stays distinguishable in both themes.
1988
- function ColumnMenuOption({
1989
- buttonRef,
1990
- children,
1991
- onClick,
1992
- selected,
1993
- }: {
1994
- buttonRef?: React.Ref<HTMLButtonElement>;
1995
- children: React.ReactNode;
1996
- onClick: () => void;
1997
- selected: boolean;
1998
- }) {
1999
- return (
2000
- <Button
2001
- ref={buttonRef}
2002
- variant={selected ? "default" : "outline"}
2003
- size="sm"
2004
- className="justify-start"
2005
- aria-pressed={selected}
2006
- onClick={onClick}
2007
- >
2008
- {children}
2009
- {selected && <CheckIcon data-icon="inline-end" className="ml-auto" />}
2010
- </Button>
2011
- );
2012
- }
2013
-
2014
- function ColumnSortControls<TData extends RowData>({
2015
- column,
2016
- isSorted,
2017
- table,
2018
- }: {
2019
- column: Column<TData, unknown>;
2020
- isSorted: false | "asc" | "desc";
2021
- table: TanstackTable<TData>;
2022
- }) {
2023
- const t = useMessages(dataTableMessages);
2024
- const ascendingRef = React.useRef<HTMLButtonElement>(null);
2025
-
2026
- return (
2027
- <div className="flex flex-col gap-2">
2028
- <div className="flex min-h-6 items-center justify-between gap-2">
2029
- <Label className="text-muted-foreground text-xs">{t.sort}</Label>
2030
- {isSorted && (
2031
- <Button
2032
- variant="ghost"
2033
- size="xs"
2034
- onClick={() => {
2035
- clearColumnSorting(table, column.id);
2036
- ascendingRef.current?.focus();
2037
- }}
2038
- >
2039
- <XIcon data-icon="inline-start" />
2040
- {t.removeSort}
2041
- </Button>
2042
- )}
2043
- </div>
2044
- <div className="grid grid-cols-2 gap-2" role="group" aria-label={t.sort}>
2045
- <ColumnMenuOption
2046
- buttonRef={ascendingRef}
2047
- selected={isSorted === "asc"}
2048
- onClick={() => setColumnSorting(table, column.id, false)}
2049
- >
2050
- <ArrowUpNarrowWideIcon data-icon="inline-start" />
2051
- {t.ascending}
2052
- </ColumnMenuOption>
2053
- <ColumnMenuOption
2054
- selected={isSorted === "desc"}
2055
- onClick={() => setColumnSorting(table, column.id, true)}
2056
- >
2057
- <ArrowDownWideNarrowIcon data-icon="inline-start" />
2058
- {t.descending}
2059
- </ColumnMenuOption>
2060
- </div>
2061
- </div>
2062
- );
2063
- }
2064
-
2065
- function ColumnFilterControls<TData extends RowData>({
2066
- allowExclude,
2067
- column,
2068
- }: {
2069
- allowExclude: boolean;
2070
- column: Column<TData, unknown>;
2071
- }) {
2072
- const t = useMessages(dataTableMessages);
2073
- const filter = getColumnMeta(column)?.filter;
2074
-
2075
- if (!filter) {
2076
- return null;
2077
- }
2078
-
2079
- if (filter.type === "custom") {
2080
- return filter.render(column);
2081
- }
2082
-
2083
- if (filter.type === "multi") {
2084
- return (
2085
- <ColumnMultiFilter
2086
- allowExclude={allowExclude}
2087
- column={column}
2088
- options={filter.options}
2089
- />
2090
- );
2091
- }
2092
-
2093
- if (filter.type === "number-range") {
2094
- const range = readRangeFilterValue(column.getFilterValue());
2095
-
2096
- return (
2097
- <div className="flex flex-col gap-2">
2098
- <Label className="text-muted-foreground text-xs">{t.filter}</Label>
2099
- <div className="grid grid-cols-2 gap-2">
2100
- <Input
2101
- type="number"
2102
- min={filter.min}
2103
- max={filter.max}
2104
- value={range.min ?? ""}
2105
- onChange={(event) =>
2106
- setObjectFilterValue(column, "min", event.target.value)
2107
- }
2108
- placeholder={filter.minPlaceholder ?? t.min}
2109
- />
2110
- <Input
2111
- type="number"
2112
- min={filter.min}
2113
- max={filter.max}
2114
- value={range.max ?? ""}
2115
- onChange={(event) =>
2116
- setObjectFilterValue(column, "max", event.target.value)
2117
- }
2118
- placeholder={filter.maxPlaceholder ?? t.max}
2119
- />
2120
- </div>
2121
- </div>
2122
- );
2123
- }
2124
-
2125
- if (filter.type === "date-range") {
2126
- const range = readDateRangeFilterValue(column.getFilterValue());
2127
-
2128
- return (
2129
- <div className="flex flex-col gap-2">
2130
- <Label className="text-muted-foreground text-xs">{t.filter}</Label>
2131
- <div className="grid grid-cols-2 gap-2">
2132
- <Input
2133
- type="date"
2134
- value={range.from ?? ""}
2135
- onChange={(event) =>
2136
- setObjectFilterValue(column, "from", event.target.value)
2137
- }
2138
- />
2139
- <Input
2140
- type="date"
2141
- value={range.to ?? ""}
2142
- onChange={(event) =>
2143
- setObjectFilterValue(column, "to", event.target.value)
2144
- }
2145
- />
2146
- </div>
2147
- </div>
2148
- );
2149
- }
2150
-
2151
- return <ColumnTextFilter column={column} placeholder={filter.placeholder} />;
2152
- }
2153
-
2154
- function ColumnTextFilter<TData extends RowData>({
2155
- column,
2156
- placeholder,
2157
- }: {
2158
- column: Column<TData, unknown>;
2159
- placeholder?: string;
2160
- }) {
2161
- const t = useMessages(dataTableMessages);
2162
- const label = getColumnLabel(column).toLocaleLowerCase();
2163
-
2164
- return (
2165
- <div className="flex flex-col gap-2">
2166
- <Label className="text-muted-foreground text-xs">{t.filter}</Label>
2167
- <Input
2168
- value={
2169
- readStringProperty({ value: column.getFilterValue() }, "value") ?? ""
2170
- }
2171
- onChange={(event) =>
2172
- column.setFilterValue(event.target.value || undefined)
2173
- }
2174
- placeholder={placeholder ?? t.filterBy(label)}
2175
- />
2176
- </div>
2177
- );
2178
- }
2179
-
2180
- function ColumnMultiFilter<TData extends RowData>({
2181
- allowExclude,
2182
- column,
2183
- options,
2184
- }: {
2185
- allowExclude: boolean;
2186
- column: Column<TData, unknown>;
2187
- options: DataTableFilterOption[];
2188
- }) {
2189
- const t = useMessages(dataTableMessages);
2190
- const stored = readMultiFilterValue(column.getFilterValue());
2191
- const [pendingExclude, setPendingExclude] = React.useState(stored.exclude);
2192
- const selected = stored.values;
2193
- const exclude =
2194
- allowExclude && (selected.length ? stored.exclude : pendingExclude);
2195
-
2196
- const toggleValue = (value: string, checked: boolean) => {
2197
- const next = checked
2198
- ? [...selected, value]
2199
- : selected.filter((item) => item !== value);
2200
-
2201
- column.setFilterValue(toMultiFilterValue(exclude, next));
2202
- };
2203
-
2204
- const setMode = (nextExclude: boolean) => {
2205
- setPendingExclude(nextExclude);
2206
- column.setFilterValue(toMultiFilterValue(nextExclude, selected));
2207
- };
2208
-
2209
- return (
2210
- <div className="flex flex-col gap-2">
2211
- <Label className="text-muted-foreground text-xs">{t.filter}</Label>
2212
- {allowExclude && (
2213
- <div
2214
- className="grid grid-cols-2 gap-2"
2215
- role="group"
2216
- aria-label={t.filterMode}
2217
- >
2218
- <ColumnMenuOption selected={!exclude} onClick={() => setMode(false)}>
2219
- <FunnelIcon data-icon="inline-start" />
2220
- {t.show}
2221
- </ColumnMenuOption>
2222
- <ColumnMenuOption selected={exclude} onClick={() => setMode(true)}>
2223
- <FunnelXIcon data-icon="inline-start" />
2224
- {t.exclude}
2225
- </ColumnMenuOption>
2226
- </div>
2227
- )}
2228
- <div
2229
- className="flex max-h-56 scroll-fade flex-col gap-1 overflow-auto rounded-2xl border p-1"
2230
- role="group"
2231
- aria-label={exclude ? t.valuesToExclude : t.valuesToShow}
2232
- >
2233
- {options.map((option) => (
2234
- <label
2235
- key={option.value}
2236
- className="hover:bg-accent flex items-center gap-2 rounded-xl px-2 py-1.5 text-sm font-normal"
2237
- >
2238
- <Checkbox
2239
- checked={selected.includes(option.value)}
2240
- onCheckedChange={(checked) =>
2241
- toggleValue(option.value, Boolean(checked))
2242
- }
2243
- />
2244
- <span
2245
- className={cn(
2246
- "min-w-0 flex-1 truncate",
2247
- exclude &&
2248
- selected.includes(option.value) &&
2249
- "text-muted-foreground line-through",
2250
- )}
2251
- >
2252
- {option.label}
2253
- </span>
2254
- </label>
2255
- ))}
2256
- </div>
2257
- </div>
2258
- );
2259
- }
2260
-
2261
- function ColumnSettings<TData extends RowData>({
2262
- defaultColumnOrder,
2263
- lockedEndColumnIds,
2264
- lockedStartColumnIds,
2265
- onResetColumns,
2266
- table,
2267
- }: {
2268
- defaultColumnOrder: ColumnOrderState;
2269
- lockedEndColumnIds: string[];
2270
- lockedStartColumnIds: string[];
2271
- onResetColumns: () => void;
2272
- table: TanstackTable<TData>;
2273
- }) {
2274
- const t = useMessages(dataTableMessages);
2275
- const hiddenColumnCount = table
2276
- .getAllLeafColumns()
2277
- .filter((column) => column.getCanHide())
2278
- .filter((column) => !column.getIsVisible()).length;
2279
- const visibleColumnsCustomized = hiddenColumnCount > 0;
2280
- const columnOrderCustomized = !areColumnOrdersEqual(
2281
- normalizeColumnOrder(
2282
- table.getState().columnOrder,
2283
- defaultColumnOrder,
2284
- lockedStartColumnIds,
2285
- lockedEndColumnIds,
2286
- ),
2287
- normalizeColumnOrder(
2288
- defaultColumnOrder,
2289
- defaultColumnOrder,
2290
- lockedStartColumnIds,
2291
- lockedEndColumnIds,
2292
- ),
2293
- );
2294
- const columnsCustomized = visibleColumnsCustomized || columnOrderCustomized;
2295
-
2296
- return (
2297
- <TooltipProvider>
2298
- <Tooltip>
2299
- <DropdownMenu>
2300
- <TooltipTrigger
2301
- render={
2302
- <DropdownMenuTrigger
2303
- render={
2304
- <Button
2305
- variant="outline"
2306
- size="icon-sm"
2307
- className="relative"
2308
- aria-label={t.customizeColumns}
2309
- />
2310
- }
2311
- />
2312
- }
2313
- >
2314
- <Columns3Icon />
2315
- {hiddenColumnCount > 0 && (
2316
- <span className="bg-primary absolute -top-0.5 -right-0.5 size-2 rounded-full" />
2317
- )}
2318
- </TooltipTrigger>
2319
- <TooltipContent side="bottom" align="end">
2320
- {t.columnsTooltip}
2321
- </TooltipContent>
2322
- <DropdownMenuContent align="end" className="w-64">
2323
- <DropdownMenuGroup>
2324
- <DropdownMenuLabel>{t.columns}</DropdownMenuLabel>
2325
- {table
2326
- .getAllLeafColumns()
2327
- .filter((column) => column.getCanHide())
2328
- .map((column) => (
2329
- <DropdownMenuCheckboxItem
2330
- key={column.id}
2331
- checked={column.getIsVisible()}
2332
- onCheckedChange={(value) =>
2333
- column.toggleVisibility(!!value)
2334
- }
2335
- closeOnClick={false}
2336
- >
2337
- {getColumnLabel(column)}
2338
- </DropdownMenuCheckboxItem>
2339
- ))}
2340
- </DropdownMenuGroup>
2341
- {columnsCustomized && (
2342
- <>
2343
- <DropdownMenuSeparator />
2344
- <DropdownMenuItem onClick={onResetColumns}>
2345
- <XIcon />
2346
- {t.resetColumns}
2347
- </DropdownMenuItem>
2348
- </>
2349
- )}
2350
- </DropdownMenuContent>
2351
- </DropdownMenu>
2352
- </Tooltip>
2353
- </TooltipProvider>
2354
- );
2355
- }
2356
-
2357
- function DataTablePagination<TData extends RowData>({
2358
- formatRowCount,
2359
- formatSelectedRowCount,
2360
- pageSizeOptions,
2361
- rowCount,
2362
- storageKey,
2363
- table,
2364
- }: {
2365
- formatRowCount: (count: number) => string;
2366
- formatSelectedRowCount?: (count: number) => string;
2367
- pageSizeOptions: number[];
2368
- rowCount?: number;
2369
- storageKey: string;
2370
- table: TanstackTable<TData>;
2371
- }) {
2372
- const t = useMessages(dataTableMessages);
2373
- const selectedRows = table.getFilteredSelectedRowModel().rows.length;
2374
- const filteredRows = rowCount ?? table.getFilteredRowModel().rows.length;
2375
- const totalRows = rowCount ?? table.getCoreRowModel().rows.length;
2376
- const selectedRowsLabel =
2377
- formatSelectedRowCount ??
2378
- ((count: number) => t.selected(formatRowCount(count), count));
2379
- const fallbackId = React.useId();
2380
- const inputId = storageKey
2381
- ? `${getStorageSafeId(storageKey)}-rows-per-page`
2382
- : fallbackId;
2383
- let paginationSummary = t.ofSummary(
2384
- formatRowCount(filteredRows),
2385
- formatRowCount(totalRows),
2386
- );
2387
-
2388
- if (selectedRows > 0) {
2389
- paginationSummary = t.ofSummary(
2390
- selectedRowsLabel(selectedRows),
2391
- formatRowCount(filteredRows),
2392
- );
2393
- } else if (filteredRows === totalRows) {
2394
- paginationSummary = `${formatRowCount(totalRows)}.`;
2395
- }
2396
-
2397
- return (
2398
- <div className="flex flex-col gap-3 px-1 sm:flex-row sm:items-center sm:justify-between">
2399
- <div className="text-muted-foreground text-sm">{paginationSummary}</div>
2400
- <div className="flex flex-wrap items-center gap-3">
2401
- <div className="flex items-center gap-2">
2402
- <Label htmlFor={inputId} className="text-sm">
2403
- {t.rowsPerPage}
2404
- </Label>
2405
- <Select
2406
- value={`${table.getState().pagination.pageSize}`}
2407
- onValueChange={(value) => table.setPageSize(Number(value))}
2408
- >
2409
- <SelectTrigger id={inputId} size="sm" className="w-20">
2410
- <SelectValue />
2411
- </SelectTrigger>
2412
- <SelectContent side="top">
2413
- {pageSizeOptions.map((pageSize) => (
2414
- <SelectItem key={pageSize} value={`${pageSize}`}>
2415
- {pageSize}
2416
- </SelectItem>
2417
- ))}
2418
- </SelectContent>
2419
- </Select>
2420
- </div>
2421
- <div className="text-sm font-medium">
2422
- {t.page(
2423
- table.getState().pagination.pageIndex + 1,
2424
- Math.max(table.getPageCount(), 1),
2425
- )}
2426
- </div>
2427
- <div className="flex items-center gap-2">
2428
- <Button
2429
- variant="outline"
2430
- className="hidden sm:flex"
2431
- size="icon"
2432
- onClick={() => table.setPageIndex(0)}
2433
- disabled={!table.getCanPreviousPage()}
2434
- >
2435
- <span className="sr-only">{t.firstPage}</span>
2436
- <ChevronsLeftIcon />
2437
- </Button>
2438
- <Button
2439
- variant="outline"
2440
- size="icon"
2441
- onClick={() => table.previousPage()}
2442
- disabled={!table.getCanPreviousPage()}
2443
- >
2444
- <span className="sr-only">{t.previousPage}</span>
2445
- <ChevronLeftIcon />
2446
- </Button>
2447
- <Button
2448
- variant="outline"
2449
- size="icon"
2450
- onClick={() => table.nextPage()}
2451
- disabled={!table.getCanNextPage()}
2452
- >
2453
- <span className="sr-only">{t.nextPage}</span>
2454
- <ChevronRightIcon />
2455
- </Button>
2456
- <Button
2457
- variant="outline"
2458
- className="hidden sm:flex"
2459
- size="icon"
2460
- onClick={() => table.setPageIndex(table.getPageCount() - 1)}
2461
- disabled={!table.getCanNextPage()}
2462
- >
2463
- <span className="sr-only">{t.lastPage}</span>
2464
- <ChevronsRightIcon />
2465
- </Button>
2466
- </div>
2467
- </div>
2468
- </div>
2469
- );
2470
- }
2471
-
2472
- export function DataTableSkeleton() {
2473
- return (
2474
- <div className="flex w-full flex-col gap-4" aria-hidden="true">
2475
- <div className="flex items-center gap-2">
2476
- <Skeleton className="h-9 flex-1 rounded-3xl" />
2477
- <Skeleton className="size-8 rounded-full" />
2478
- </div>
2479
- <div className="bg-card overflow-hidden rounded-2xl border">
2480
- <Skeleton className="h-10 rounded-none" />
2481
- <div className="flex flex-col">
2482
- {Array.from({ length: 8 }).map((_, index) => (
2483
- <Skeleton
2484
- key={index}
2485
- className="bg-muted/40 h-14 rounded-none border-t"
2486
- />
2487
- ))}
2488
- </div>
2489
- </div>
2490
- </div>
2491
- );
2492
- }
1
+ "use client";
2
+ "use no memo";
3
+
4
+ // Ported from the Numa app's data table (majapisoftwares/numa); this is now the
5
+ // canonical copy. Effects below intentionally sync restored localStorage
6
+ // preferences and incoming props into table state.
7
+ /* eslint-disable react-hooks/set-state-in-effect */
8
+
9
+ import * as React from "react";
10
+ import {
11
+ closestCenter,
12
+ DndContext,
13
+ KeyboardSensor,
14
+ MouseSensor,
15
+ TouchSensor,
16
+ useSensor,
17
+ useSensors,
18
+ type DragEndEvent,
19
+ } from "@dnd-kit/core";
20
+ import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
21
+ import {
22
+ arrayMove,
23
+ horizontalListSortingStrategy,
24
+ SortableContext,
25
+ useSortable,
26
+ } from "@dnd-kit/sortable";
27
+ import { CSS } from "@dnd-kit/utilities";
28
+ import {
29
+ CircleAlertIcon,
30
+ InboxIcon,
31
+ LockIcon,
32
+ RotateCwIcon,
33
+ TriangleAlertIcon,
34
+ ArrowDownWideNarrowIcon,
35
+ ArrowUpDownIcon,
36
+ ArrowUpNarrowWideIcon,
37
+ CheckIcon,
38
+ ChevronLeftIcon,
39
+ ChevronRightIcon,
40
+ ChevronsLeftIcon,
41
+ ChevronsRightIcon,
42
+ Columns3Icon,
43
+ EyeOffIcon,
44
+ FunnelIcon,
45
+ FunnelXIcon,
46
+ GripVerticalIcon,
47
+ SearchIcon,
48
+ XIcon,
49
+ } from "lucide-react";
50
+ import {
51
+ createTable,
52
+ flexRender,
53
+ getCoreRowModel,
54
+ getFilteredRowModel,
55
+ getPaginationRowModel,
56
+ getSortedRowModel,
57
+ type Column,
58
+ type ColumnDef,
59
+ type ColumnFiltersState,
60
+ type ColumnOrderState,
61
+ type ColumnSizingState,
62
+ type FilterFn,
63
+ type Header,
64
+ type OnChangeFn,
65
+ type PaginationState,
66
+ type RowData,
67
+ type RowSelectionState,
68
+ type SortingState,
69
+ type Table as TanstackTable,
70
+ type TableOptions,
71
+ type TableOptionsResolved,
72
+ type VisibilityState,
73
+ } from "@tanstack/react-table";
74
+
75
+ import { Badge } from "../components/ui/badge";
76
+ import { Button } from "../components/ui/button";
77
+ import { Checkbox } from "../components/ui/checkbox";
78
+ import { FilterTabs } from "./filter-tabs";
79
+ import {
80
+ DropdownMenu,
81
+ DropdownMenuCheckboxItem,
82
+ DropdownMenuContent,
83
+ DropdownMenuGroup,
84
+ DropdownMenuItem,
85
+ DropdownMenuLabel,
86
+ DropdownMenuSeparator,
87
+ DropdownMenuTrigger,
88
+ } from "../components/ui/dropdown-menu";
89
+ import { Input } from "../components/ui/input";
90
+ import {
91
+ InputGroup,
92
+ InputGroupAddon,
93
+ InputGroupInput,
94
+ } from "../components/ui/input-group";
95
+ import { Label } from "../components/ui/label";
96
+ import {
97
+ Popover,
98
+ PopoverContent,
99
+ PopoverTrigger,
100
+ } from "../components/ui/popover";
101
+ import {
102
+ Select,
103
+ SelectContent,
104
+ SelectItem,
105
+ SelectTrigger,
106
+ SelectValue,
107
+ } from "../components/ui/select";
108
+ import { Separator } from "../components/ui/separator";
109
+ import { Skeleton } from "../components/ui/skeleton";
110
+ import {
111
+ Table,
112
+ TableBody,
113
+ TableCell,
114
+ TableHead,
115
+ TableHeader,
116
+ TableRow,
117
+ } from "../components/ui/table";
118
+ import {
119
+ Tooltip,
120
+ TooltipContent,
121
+ TooltipProvider,
122
+ TooltipTrigger,
123
+ } from "../components/ui/tooltip";
124
+ import { cn } from "cn";
125
+ import { defineMessages, useMessages, useUiMessages } from "../lib/i18n";
126
+ import {
127
+ Empty,
128
+ EmptyContent,
129
+ EmptyDescription,
130
+ EmptyHeader,
131
+ EmptyMedia,
132
+ EmptyTitle,
133
+ } from "../components/ui/empty";
134
+ import {
135
+ Alert,
136
+ AlertAction,
137
+ AlertDescription,
138
+ AlertTitle,
139
+ } from "../components/ui/alert";
140
+
141
+ export type DataTableColumnAlign = "left" | "center" | "right";
142
+ type DataTableSortDirection = false | "asc" | "desc";
143
+
144
+ export type DataTableFilterOption = {
145
+ label: string;
146
+ value: string;
147
+ };
148
+
149
+ export type DataTableRangeFilter = {
150
+ min?: string;
151
+ max?: string;
152
+ };
153
+
154
+ export type DataTableDateRangeFilter = {
155
+ from?: string;
156
+ to?: string;
157
+ };
158
+
159
+ // Multi-select filter value: an array keeps the matching rows; the object form
160
+ // hides the selected values instead. Server-filtered tables only receive arrays.
161
+ export type DataTableMultiFilterValue =
162
+ string[] | { exclude: true; values: string[] };
163
+
164
+ export type DataTableColumnFilter<TData extends RowData> =
165
+ | {
166
+ placeholder?: string;
167
+ type: "text";
168
+ }
169
+ | {
170
+ options: DataTableFilterOption[];
171
+ type: "multi";
172
+ }
173
+ | {
174
+ max?: number;
175
+ maxPlaceholder?: string;
176
+ min?: number;
177
+ minPlaceholder?: string;
178
+ type: "number-range";
179
+ }
180
+ | {
181
+ type: "date-range";
182
+ }
183
+ | {
184
+ render: (column: Column<TData, unknown>) => React.ReactNode;
185
+ type: "custom";
186
+ };
187
+
188
+ export type DataTableColumnMeta<TData extends RowData> = {
189
+ align?: DataTableColumnAlign;
190
+ cellClassName?: string;
191
+ filter?: DataTableColumnFilter<TData>;
192
+ headerClassName?: string;
193
+ label?: string;
194
+ };
195
+
196
+ declare module "@tanstack/react-table" {
197
+ interface ColumnMeta<TData extends RowData, TValue> {
198
+ align?: DataTableColumnAlign;
199
+ cellClassName?: string;
200
+ filter?: DataTableColumnFilter<TData>;
201
+ headerClassName?: string;
202
+ label?: string;
203
+ valueType?: TValue;
204
+ }
205
+
206
+ interface TableMeta<TData extends RowData> {
207
+ enableExcludeFilters?: boolean;
208
+ rowType?: TData;
209
+ }
210
+ }
211
+
212
+ /** Window event that clears a table's search and filters (detail: { storageKey? }). */
213
+ export const DATA_TABLE_RESET_FILTERS_EVENT =
214
+ "majapi-ui:data-table:reset-filters";
215
+
216
+ /** Clears search and filters of every table, or only the one with `storageKey`. */
217
+ export function resetDataTableFilters(storageKey?: string) {
218
+ window.dispatchEvent(
219
+ new CustomEvent(DATA_TABLE_RESET_FILTERS_EVENT, { detail: { storageKey } }),
220
+ );
221
+ }
222
+
223
+ const dataTableMessages = defineMessages({
224
+ en: {
225
+ search: "Search...",
226
+ resultCount: (count: number) =>
227
+ `${count} ${count === 1 ? "result" : "results"}`,
228
+ rowCount: (count: number) => `${count} ${count === 1 ? "row" : "rows"}`,
229
+ // English needs no plural form here; pt-BR uses count.
230
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
231
+ selected: (rows: string, count: number) => `${rows} selected`,
232
+ clearSelection: "Clear selection",
233
+ clearFilters: "Clear filters",
234
+ open: "Open",
235
+ resizeColumn: (label: string) => `Resize column ${label}`,
236
+ filterActive: ", filter active",
237
+ excludeFilterActive: ", exclusion filter active",
238
+ sortCriterion: (n: number) => `Sort #${n}`,
239
+ sortCriterionTitle: (n: number) => `Sort criterion #${n}`,
240
+ clearAll: "Clear all",
241
+ hide: "Hide",
242
+ toggleSort: (label: string) => `Toggle sorting for ${label}`,
243
+ reorderColumn: (label: string) => `Reorder column ${label}`,
244
+ sort: "Sort",
245
+ removeSort: "Remove sort",
246
+ ascending: "Ascending",
247
+ descending: "Descending",
248
+ filter: "Filter",
249
+ min: "Min.",
250
+ max: "Max.",
251
+ filterBy: (label: string) => `Filter by ${label}`,
252
+ filterMode: "Filter mode",
253
+ show: "Show",
254
+ exclude: "Exclude",
255
+ valuesToExclude: "Values to exclude",
256
+ valuesToShow: "Values to show",
257
+ customizeColumns: "Customize columns",
258
+ columnsTooltip: "Show, hide and reset columns",
259
+ columns: "Columns",
260
+ resetColumns: "Reset columns",
261
+ rowsPerPage: "Rows",
262
+ page: (page: number, total: number) => `Page ${page} of ${total}`,
263
+ ofSummary: (part: string, total: string) => `${part} of ${total}.`,
264
+ firstPage: "First page",
265
+ previousPage: "Previous page",
266
+ nextPage: "Next page",
267
+ lastPage: "Last page",
268
+ },
269
+ "pt-BR": {
270
+ search: "Buscar...",
271
+ resultCount: (count: number) =>
272
+ `${count} resultado${count === 1 ? "" : "s"}`,
273
+ rowCount: (count: number) => `${count} registro${count === 1 ? "" : "s"}`,
274
+ selected: (rows: string, count: number) =>
275
+ `${rows} selecionado${count === 1 ? "" : "s"}`,
276
+ clearSelection: "Limpar seleção",
277
+ clearFilters: "Limpar filtros",
278
+ open: "Abrir",
279
+ resizeColumn: (label: string) => `Redimensionar coluna ${label}`,
280
+ filterActive: ", filtro ativo",
281
+ excludeFilterActive: ", filtro de exclusão ativo",
282
+ sortCriterion: (n: number) => `${n}º critério`,
283
+ sortCriterionTitle: (n: number) => `${n}º critério de ordenação`,
284
+ clearAll: "Limpar tudo",
285
+ hide: "Ocultar",
286
+ toggleSort: (label: string) => `Alternar ordenação da coluna ${label}`,
287
+ reorderColumn: (label: string) => `Reordenar coluna ${label}`,
288
+ sort: "Ordenar",
289
+ removeSort: "Remover ordem",
290
+ ascending: "Crescente",
291
+ descending: "Decrescente",
292
+ filter: "Filtrar",
293
+ min: "Mín.",
294
+ max: "Máx.",
295
+ filterBy: (label: string) => `Filtrar por ${label}`,
296
+ filterMode: "Modo do filtro",
297
+ show: "Mostrar",
298
+ exclude: "Excluir",
299
+ valuesToExclude: "Valores a excluir",
300
+ valuesToShow: "Valores a mostrar",
301
+ customizeColumns: "Personalizar colunas",
302
+ columnsTooltip: "Mostrar, ocultar e restaurar colunas",
303
+ columns: "Colunas",
304
+ resetColumns: "Restaurar colunas",
305
+ rowsPerPage: "Linhas",
306
+ page: (page: number, total: number) => `Página ${page} de ${total}`,
307
+ ofSummary: (part: string, total: string) => `${part} de ${total}.`,
308
+ firstPage: "Primeira página",
309
+ previousPage: "Página anterior",
310
+ nextPage: "Próxima página",
311
+ lastPage: "Última página",
312
+ },
313
+ });
314
+
315
+ type StoredDataTableSettings = {
316
+ columnFilters?: ColumnFiltersState;
317
+ columnOrder?: ColumnOrderState;
318
+ columnSizing?: ColumnSizingState;
319
+ columnVisibility?: VisibilityState;
320
+ globalFilter?: string;
321
+ pageSize?: number;
322
+ sorting?: SortingState;
323
+ };
324
+
325
+ export type DataTableProps<TData extends RowData> = {
326
+ activeRowId?: string | null;
327
+ columns: ColumnDef<TData, unknown>[];
328
+ data: TData[];
329
+ /** Text when there are no rows; defaults to a translated message. */
330
+ emptyMessage?: string;
331
+ /** Rich empty state (e.g. with a create action), shown when nothing is filtered. */
332
+ emptyState?: React.ReactNode;
333
+ /**
334
+ * Fills the parent's height and scrolls rows inside the table (sticky
335
+ * header, toolbar and pagination stay visible). The parent must be a flex
336
+ * column with a bounded height, e.g. `AppShell fillHeight`.
337
+ */
338
+ fillHeight?: boolean;
339
+ /** Shows skeleton rows instead of data. */
340
+ loading?: boolean;
341
+ /** Load failure. With rows it shows as stale data; without, replaces the table. */
342
+ error?: string;
343
+ onRetry?: () => void;
344
+ /** Non-blocking notice, e.g. partial coverage. */
345
+ warning?: string;
346
+ /** Data can't be shown at all, e.g. missing permission. */
347
+ unavailable?: string;
348
+ enablePersistence?: boolean;
349
+ enableRowSelection?: boolean;
350
+ // Offers "Excluir" in multi-select column filters. Defaults to off for
351
+ // server-backed tables (onStateChange), whose APIs only read include arrays.
352
+ enableExcludeFilters?: boolean;
353
+ filterFns?: Record<string, FilterFn<TData>>;
354
+ formatResultCount?: (count: number) => string;
355
+ formatRowCount?: (count: number) => string;
356
+ formatSelectedRowCount?: (count: number) => string;
357
+ getRowId: (row: TData) => string;
358
+ globalFilterFn?: FilterFn<TData>;
359
+ initialColumnFilters?: ColumnFiltersState;
360
+ /** Initial search text. */
361
+ initialGlobalFilter?: string;
362
+ /** Makes rows clickable (and Enter/Space activatable), e.g. to open details. */
363
+ onRowClick?: (row: TData) => void;
364
+ /** Accessible name for a clickable row; defaults to its id. */
365
+ getRowLabel?: (row: TData) => string;
366
+ initialColumnOrder?: ColumnOrderState;
367
+ initialColumnVisibility?: VisibilityState;
368
+ initialPageSize?: number;
369
+ initialSorting?: SortingState;
370
+ lockedEndColumnIds?: string[];
371
+ lockedStartColumnIds?: string[];
372
+ manualFiltering?: boolean;
373
+ manualPagination?: boolean;
374
+ manualSorting?: boolean;
375
+ onStateChange?: (state: DataTableStateSnapshot) => void;
376
+ pageCount?: number;
377
+ pageSizeOptions?: number[];
378
+ rowCount?: number;
379
+ rowSelectionActions?: (table: TanstackTable<TData>) => React.ReactNode;
380
+ searchPlaceholder?: string;
381
+ /** Persists sorting, filters, columns and page size in localStorage under this key. */
382
+ storageKey?: string;
383
+ toolbarBelow?: (table: TanstackTable<TData>) => React.ReactNode;
384
+ toolbarEnd?: (table: TanstackTable<TData>) => React.ReactNode;
385
+ toolbarStart?: (table: TanstackTable<TData>) => React.ReactNode;
386
+ };
387
+
388
+ export type DataTableStateSnapshot = {
389
+ columnFilters: ColumnFiltersState;
390
+ globalFilter: string;
391
+ pagination: PaginationState;
392
+ sorting: SortingState;
393
+ };
394
+
395
+ export type DataTableFilterTab = {
396
+ count?: number;
397
+ label: string;
398
+ value: string;
399
+ };
400
+
401
+ type DataTableObjectFilter = DataTableRangeFilter & DataTableDateRangeFilter;
402
+
403
+ function isRecord(value: unknown): value is Record<string, unknown> {
404
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
405
+ }
406
+
407
+ function readStringProperty(value: unknown, key: string) {
408
+ if (!isRecord(value)) {
409
+ return undefined;
410
+ }
411
+
412
+ const property = value[key];
413
+ return typeof property === "string" ? property : undefined;
414
+ }
415
+
416
+ function readStringArrayFilter(value: unknown) {
417
+ if (!Array.isArray(value)) {
418
+ return [];
419
+ }
420
+
421
+ return value.filter((item): item is string => typeof item === "string");
422
+ }
423
+
424
+ export function readMultiFilterValue(value: unknown): {
425
+ exclude: boolean;
426
+ values: string[];
427
+ } {
428
+ if (isRecord(value) && value.exclude === true) {
429
+ return { exclude: true, values: readStringArrayFilter(value.values) };
430
+ }
431
+
432
+ return { exclude: false, values: readStringArrayFilter(value) };
433
+ }
434
+
435
+ function toMultiFilterValue(
436
+ exclude: boolean,
437
+ values: string[],
438
+ ): DataTableMultiFilterValue | undefined {
439
+ if (values.length === 0) {
440
+ return undefined;
441
+ }
442
+
443
+ return exclude ? { exclude: true, values } : values;
444
+ }
445
+
446
+ function isString(value: unknown): value is string {
447
+ return typeof value === "string";
448
+ }
449
+
450
+ function readRangeFilterValue(value: unknown): DataTableRangeFilter {
451
+ return {
452
+ max: readStringProperty(value, "max"),
453
+ min: readStringProperty(value, "min"),
454
+ };
455
+ }
456
+
457
+ function readDateRangeFilterValue(value: unknown): DataTableDateRangeFilter {
458
+ return {
459
+ from: readStringProperty(value, "from"),
460
+ to: readStringProperty(value, "to"),
461
+ };
462
+ }
463
+
464
+ function readObjectFilterValue(value: unknown): Partial<DataTableObjectFilter> {
465
+ return {
466
+ ...readRangeFilterValue(value),
467
+ ...readDateRangeFilterValue(value),
468
+ };
469
+ }
470
+
471
+ export function createArrayIncludesSomeFilter<
472
+ TData extends RowData,
473
+ >(): FilterFn<TData> {
474
+ return (row, columnId, filterValue) => {
475
+ const { exclude, values } = readMultiFilterValue(filterValue);
476
+
477
+ if (values.length === 0) {
478
+ return true;
479
+ }
480
+
481
+ return values.includes(row.getValue(columnId)) !== exclude;
482
+ };
483
+ }
484
+
485
+ export function createNumberInRangeFilter<
486
+ TData extends RowData,
487
+ >(): FilterFn<TData> {
488
+ return (row, columnId, filterValue) => {
489
+ const range = readRangeFilterValue(filterValue);
490
+ const min = range?.min ? Number(range.min) : null;
491
+ const max = range?.max ? Number(range.max) : null;
492
+ const value = Number(row.getValue(columnId));
493
+
494
+ if (min !== null && Number.isFinite(min) && value < min) {
495
+ return false;
496
+ }
497
+
498
+ if (max !== null && Number.isFinite(max) && value > max) {
499
+ return false;
500
+ }
501
+
502
+ return true;
503
+ };
504
+ }
505
+
506
+ export function createDateInRangeFilter<
507
+ TData extends RowData,
508
+ >(): FilterFn<TData> {
509
+ return (row, columnId, filterValue) => {
510
+ const range = readDateRangeFilterValue(filterValue);
511
+ const value = new Date(row.getValue<string>(columnId)).getTime();
512
+ const from = range?.from
513
+ ? new Date(`${range.from}T00:00:00`).getTime()
514
+ : null;
515
+ const to = range?.to ? new Date(`${range.to}T23:59:59`).getTime() : null;
516
+
517
+ if (from !== null && Number.isFinite(from) && value < from) {
518
+ return false;
519
+ }
520
+
521
+ if (to !== null && Number.isFinite(to) && value > to) {
522
+ return false;
523
+ }
524
+
525
+ return true;
526
+ };
527
+ }
528
+
529
+ export function getSingleArrayFilterValue(
530
+ filterValue: unknown,
531
+ ): "all" | "custom" | string {
532
+ const { exclude, values } = readMultiFilterValue(filterValue);
533
+
534
+ if (exclude && values.length > 0) {
535
+ return "custom";
536
+ }
537
+
538
+ if (values.length === 0) {
539
+ return "all";
540
+ }
541
+
542
+ if (values.length === 1) {
543
+ return values[0] ?? "all";
544
+ }
545
+
546
+ return "custom";
547
+ }
548
+
549
+ export function DataTableColumnFilterTabs<TData extends RowData>({
550
+ className,
551
+ columnId,
552
+ options,
553
+ table,
554
+ }: {
555
+ className?: string;
556
+ columnId: string;
557
+ options: DataTableFilterTab[];
558
+ table: TanstackTable<TData>;
559
+ }) {
560
+ const column = table.getColumn(columnId);
561
+ const value = getSingleArrayFilterValue(column?.getFilterValue());
562
+
563
+ const handleValueChange = (nextValue: string) => {
564
+ column?.setFilterValue(nextValue === "all" ? undefined : [nextValue]);
565
+ };
566
+
567
+ return (
568
+ <FilterTabs
569
+ className={className}
570
+ onValueChange={handleValueChange}
571
+ options={options}
572
+ value={value}
573
+ />
574
+ );
575
+ }
576
+
577
+ export function createDataTableFilterTabOptions<TItem>(
578
+ items: TItem[],
579
+ filters: Array<Pick<DataTableFilterTab, "label" | "value">>,
580
+ getItemValue: (item: TItem) => string,
581
+ ) {
582
+ return filters.map((filter) => ({
583
+ ...filter,
584
+ count:
585
+ filter.value === "all"
586
+ ? undefined
587
+ : items.filter((item) => getItemValue(item) === filter.value).length,
588
+ }));
589
+ }
590
+
591
+ function getColumnId<TData extends RowData>(
592
+ column: ColumnDef<TData, unknown>,
593
+ ): string | null {
594
+ if ("id" in column && column.id) {
595
+ return column.id;
596
+ }
597
+
598
+ if ("accessorKey" in column && typeof column.accessorKey === "string") {
599
+ return column.accessorKey;
600
+ }
601
+
602
+ return null;
603
+ }
604
+
605
+ function normalizeColumnOrder(
606
+ columnOrder: ColumnOrderState | undefined,
607
+ defaultColumnOrder: ColumnOrderState,
608
+ lockedStartColumnIds: string[],
609
+ lockedEndColumnIds: string[],
610
+ ) {
611
+ const validColumns = new Set(defaultColumnOrder);
612
+ const lockedStart = lockedStartColumnIds.filter((columnId) =>
613
+ validColumns.has(columnId),
614
+ );
615
+ const lockedEnd = lockedEndColumnIds.filter((columnId) =>
616
+ validColumns.has(columnId),
617
+ );
618
+ const lockedColumns = new Set([...lockedStart, ...lockedEnd]);
619
+ const movableColumns = (columnOrder ?? []).filter(
620
+ (columnId) => validColumns.has(columnId) && !lockedColumns.has(columnId),
621
+ );
622
+
623
+ for (const columnId of defaultColumnOrder) {
624
+ if (!lockedColumns.has(columnId) && !movableColumns.includes(columnId)) {
625
+ movableColumns.push(columnId);
626
+ }
627
+ }
628
+
629
+ return [...lockedStart, ...movableColumns, ...lockedEnd];
630
+ }
631
+
632
+ function areColumnOrdersEqual(left: ColumnOrderState, right: ColumnOrderState) {
633
+ return (
634
+ left.length === right.length &&
635
+ left.every((columnId, index) => columnId === right[index])
636
+ );
637
+ }
638
+
639
+ function getColumnMeta<TData extends RowData>(column: Column<TData, unknown>) {
640
+ return column.columnDef.meta;
641
+ }
642
+
643
+ function getColumnLabel<TData extends RowData>(column: Column<TData, unknown>) {
644
+ const header = column.columnDef.header;
645
+
646
+ return (
647
+ getColumnMeta(column)?.label ??
648
+ (typeof header === "string" ? header : column.id)
649
+ );
650
+ }
651
+
652
+ function getColumnAlign<TData extends RowData>(column: Column<TData, unknown>) {
653
+ return getColumnMeta(column)?.align ?? "left";
654
+ }
655
+
656
+ function getColumnAlignClass<TData extends RowData>(
657
+ column: Column<TData, unknown>,
658
+ ) {
659
+ const align = getColumnAlign(column);
660
+
661
+ return cn(
662
+ align === "center" && "text-center",
663
+ align === "right" && "text-right",
664
+ );
665
+ }
666
+
667
+ function getColumnAriaSort(
668
+ isSorted: DataTableSortDirection,
669
+ ): "ascending" | "descending" | undefined {
670
+ if (!isSorted) {
671
+ return undefined;
672
+ }
673
+
674
+ return isSorted === "asc" ? "ascending" : "descending";
675
+ }
676
+
677
+ function getHeaderControlVisibilityClass(isVisible: boolean) {
678
+ if (isVisible) {
679
+ return "pointer-events-auto opacity-100";
680
+ }
681
+
682
+ return "pointer-events-none opacity-0 group-focus-within/header:pointer-events-auto group-focus-within/header:opacity-100 group-hover/header:pointer-events-auto group-hover/header:opacity-100";
683
+ }
684
+
685
+ function hasRangeFilter(value: unknown) {
686
+ const range = readObjectFilterValue(value);
687
+ return Boolean(range.min || range.max || range.from || range.to);
688
+ }
689
+
690
+ function isFilterValueActive(value: unknown) {
691
+ if (Array.isArray(value)) {
692
+ return value.length > 0;
693
+ }
694
+
695
+ if (isRecord(value) && value.exclude === true) {
696
+ return readMultiFilterValue(value).values.length > 0;
697
+ }
698
+
699
+ if (typeof value === "object") {
700
+ return hasRangeFilter(value);
701
+ }
702
+
703
+ return Boolean(value);
704
+ }
705
+
706
+ function setObjectFilterValue<TData extends RowData>(
707
+ column: Column<TData, unknown>,
708
+ key: keyof DataTableObjectFilter,
709
+ value: string,
710
+ ) {
711
+ const next = {
712
+ ...readObjectFilterValue(column.getFilterValue()),
713
+ [key]: value,
714
+ };
715
+
716
+ if (!hasRangeFilter(next)) {
717
+ column.setFilterValue(undefined);
718
+ return;
719
+ }
720
+
721
+ column.setFilterValue(next);
722
+ }
723
+
724
+ function setColumnSorting<TData extends RowData>(
725
+ table: TanstackTable<TData>,
726
+ columnId: string,
727
+ desc: boolean,
728
+ ) {
729
+ table.setSorting((current) => {
730
+ const next = [
731
+ ...current.filter((sort) => sort.id !== columnId),
732
+ { id: columnId, desc },
733
+ ];
734
+
735
+ return next.slice(-5);
736
+ });
737
+ }
738
+
739
+ function clearColumnSorting<TData extends RowData>(
740
+ table: TanstackTable<TData>,
741
+ columnId: string,
742
+ ) {
743
+ table.setSorting((current) => current.filter((sort) => sort.id !== columnId));
744
+ }
745
+
746
+ function toggleColumnSorting<TData extends RowData>(
747
+ table: TanstackTable<TData>,
748
+ columnId: string,
749
+ ) {
750
+ table.setSorting((current) => {
751
+ const currentSort = current.find((sort) => sort.id === columnId);
752
+ const next = current.filter((sort) => sort.id !== columnId);
753
+
754
+ if (!currentSort) {
755
+ return [...next, { id: columnId, desc: false }].slice(-5);
756
+ }
757
+
758
+ if (!currentSort.desc) {
759
+ return [...next, { id: columnId, desc: true }].slice(-5);
760
+ }
761
+
762
+ return next;
763
+ });
764
+ }
765
+
766
+ function isColumnOrderState(value: unknown): value is ColumnOrderState {
767
+ return (
768
+ Array.isArray(value) &&
769
+ value.every((columnId) => typeof columnId === "string")
770
+ );
771
+ }
772
+
773
+ function isColumnFiltersState(value: unknown): value is ColumnFiltersState {
774
+ return (
775
+ Array.isArray(value) &&
776
+ value.every((filter) => isRecord(filter) && typeof filter.id === "string")
777
+ );
778
+ }
779
+
780
+ function isVisibilityState(value: unknown): value is VisibilityState {
781
+ return (
782
+ isRecord(value) &&
783
+ Object.values(value).every((visible) => typeof visible === "boolean")
784
+ );
785
+ }
786
+
787
+ function isSortingState(value: unknown): value is SortingState {
788
+ return (
789
+ Array.isArray(value) &&
790
+ value.every(
791
+ (sort) =>
792
+ isRecord(sort) &&
793
+ typeof sort.id === "string" &&
794
+ typeof sort.desc === "boolean",
795
+ )
796
+ );
797
+ }
798
+
799
+ function parseStoredDataTableSettings(
800
+ value: string,
801
+ ): StoredDataTableSettings | null {
802
+ const parsed = JSON.parse(value);
803
+
804
+ if (!isRecord(parsed)) {
805
+ return null;
806
+ }
807
+
808
+ const settings: StoredDataTableSettings = {};
809
+
810
+ if (isColumnFiltersState(parsed.columnFilters)) {
811
+ settings.columnFilters = parsed.columnFilters;
812
+ }
813
+
814
+ if (isColumnOrderState(parsed.columnOrder)) {
815
+ settings.columnOrder = parsed.columnOrder;
816
+ }
817
+
818
+ if (isVisibilityState(parsed.columnVisibility)) {
819
+ settings.columnVisibility = parsed.columnVisibility;
820
+ }
821
+
822
+ if (typeof parsed.globalFilter === "string") {
823
+ settings.globalFilter = parsed.globalFilter;
824
+ }
825
+
826
+ if (typeof parsed.pageSize === "number" && Number.isFinite(parsed.pageSize)) {
827
+ settings.pageSize = parsed.pageSize;
828
+ }
829
+
830
+ if (isSortingState(parsed.sorting)) {
831
+ settings.sorting = parsed.sorting;
832
+ }
833
+
834
+ return settings;
835
+ }
836
+
837
+ function getStoredDataTableSettings(storageKey: string) {
838
+ if (typeof window === "undefined") {
839
+ return null;
840
+ }
841
+
842
+ try {
843
+ const value = window.localStorage.getItem(storageKey);
844
+ return value ? parseStoredDataTableSettings(value) : null;
845
+ } catch {
846
+ return null;
847
+ }
848
+ }
849
+
850
+ function pickKnownColumnEntries<TValue>(
851
+ record: Record<string, TValue> | undefined,
852
+ columnIds: string[],
853
+ ) {
854
+ if (!record) {
855
+ return undefined;
856
+ }
857
+
858
+ return Object.fromEntries(
859
+ Object.entries(record).filter(([columnId]) => columnIds.includes(columnId)),
860
+ );
861
+ }
862
+
863
+ function retainKnownColumnSettings(
864
+ settings: StoredDataTableSettings | null,
865
+ columnIds: string[],
866
+ ): StoredDataTableSettings | null {
867
+ if (!settings) {
868
+ return null;
869
+ }
870
+
871
+ const sorting = settings.sorting?.filter((sort) =>
872
+ columnIds.includes(sort.id),
873
+ );
874
+
875
+ return {
876
+ ...settings,
877
+ columnFilters: settings.columnFilters?.filter((filter) =>
878
+ columnIds.includes(filter.id),
879
+ ),
880
+ columnSizing: pickKnownColumnEntries(settings.columnSizing, columnIds),
881
+ columnVisibility: pickKnownColumnEntries(
882
+ settings.columnVisibility,
883
+ columnIds,
884
+ ),
885
+ sorting: sorting?.length ? sorting : undefined,
886
+ };
887
+ }
888
+
889
+ function getResetFiltersStorageKey(event: Event) {
890
+ if (!(event instanceof CustomEvent)) {
891
+ return null;
892
+ }
893
+
894
+ const detail = event.detail;
895
+ if (!isRecord(detail)) {
896
+ return null;
897
+ }
898
+
899
+ const storageKey = detail.storageKey;
900
+ return typeof storageKey === "string" ? storageKey : null;
901
+ }
902
+
903
+ function isLockedColumn(
904
+ columnId: string,
905
+ lockedStartColumnIds: string[],
906
+ lockedEndColumnIds: string[],
907
+ ) {
908
+ return (
909
+ lockedStartColumnIds.includes(columnId) ||
910
+ lockedEndColumnIds.includes(columnId)
911
+ );
912
+ }
913
+
914
+ function getStorageSafeId(storageKey: string) {
915
+ return storageKey.replace(/[^a-zA-Z0-9_-]/g, "-");
916
+ }
917
+
918
+ function getOptionalColumnOrderKey(columnOrder?: ColumnOrderState) {
919
+ return columnOrder?.join("|") ?? "";
920
+ }
921
+
922
+ function getColumnFiltersKey(columnFilters: ColumnFiltersState) {
923
+ return JSON.stringify(columnFilters);
924
+ }
925
+
926
+ function getVisibilityStateKey(visibility: VisibilityState) {
927
+ const entries = Object.entries(visibility).sort(([left], [right]) =>
928
+ left.localeCompare(right),
929
+ );
930
+
931
+ return JSON.stringify(entries);
932
+ }
933
+
934
+ function getSortingKey(sorting: SortingState) {
935
+ return JSON.stringify(sorting);
936
+ }
937
+
938
+ function useStableValueByKey<TValue>(value: TValue, key: string) {
939
+ const [stored, setStored] = React.useState({ key, value });
940
+
941
+ React.useEffect(() => {
942
+ setStored((current) => (current.key === key ? current : { key, value }));
943
+ }, [key, value]);
944
+
945
+ return stored.value;
946
+ }
947
+
948
+ function useDataTableInstance<TData extends RowData>(
949
+ options: TableOptions<TData>,
950
+ ) {
951
+ const resolvedOptions: TableOptionsResolved<TData> = {
952
+ onStateChange: () => undefined,
953
+ renderFallbackValue: null,
954
+ state: {},
955
+ ...options,
956
+ };
957
+
958
+ const [table] = React.useState(() => createTable<TData>(resolvedOptions));
959
+ const [state, setState] = React.useState(() => table.initialState);
960
+
961
+ table.setOptions((previous) => ({
962
+ ...previous,
963
+ ...options,
964
+ onStateChange: (updater) => {
965
+ setState(updater);
966
+ options.onStateChange?.(updater);
967
+ },
968
+ state: {
969
+ ...state,
970
+ ...options.state,
971
+ },
972
+ }));
973
+
974
+ return table;
975
+ }
976
+
977
+ const emptyColumnFilters: ColumnFiltersState = [];
978
+ const emptyColumnSizing: ColumnSizingState = {};
979
+ const emptyColumnVisibility: VisibilityState = {};
980
+ const emptySorting: SortingState = [];
981
+ const emptyLockedColumnIds: string[] = [];
982
+ const defaultPageSizeOptions = [10, 20, 30, 50, 100];
983
+
984
+ function resolvePageSize(
985
+ pageSize: number | undefined,
986
+ fallbackPageSize: number,
987
+ pageSizeOptions: number[],
988
+ ) {
989
+ if (typeof pageSize === "number" && pageSizeOptions.includes(pageSize)) {
990
+ return pageSize;
991
+ }
992
+
993
+ if (pageSizeOptions.includes(fallbackPageSize)) {
994
+ return fallbackPageSize;
995
+ }
996
+
997
+ return pageSizeOptions[0] ?? fallbackPageSize;
998
+ }
999
+
1000
+ export function DataTable<TData extends RowData>(props: DataTableProps<TData>) {
1001
+ const {
1002
+ activeRowId,
1003
+ columns,
1004
+ data,
1005
+ emptyMessage,
1006
+ emptyState,
1007
+ fillHeight = false,
1008
+ loading = false,
1009
+ error,
1010
+ onRetry,
1011
+ warning,
1012
+ unavailable,
1013
+ enablePersistence: enablePersistenceProp,
1014
+ enableRowSelection = false,
1015
+ filterFns,
1016
+ formatResultCount: formatResultCountProp,
1017
+ formatRowCount: formatRowCountProp,
1018
+ formatSelectedRowCount,
1019
+ getRowId,
1020
+ globalFilterFn,
1021
+ initialColumnFilters = emptyColumnFilters,
1022
+ initialGlobalFilter = "",
1023
+ onRowClick,
1024
+ getRowLabel,
1025
+ initialColumnOrder,
1026
+ initialColumnVisibility = emptyColumnVisibility,
1027
+ initialPageSize = 10,
1028
+ initialSorting = emptySorting,
1029
+ lockedEndColumnIds = emptyLockedColumnIds,
1030
+ lockedStartColumnIds = emptyLockedColumnIds,
1031
+ manualFiltering = false,
1032
+ enableExcludeFilters,
1033
+ manualPagination = false,
1034
+ manualSorting = false,
1035
+ onStateChange,
1036
+ pageCount,
1037
+ pageSizeOptions = defaultPageSizeOptions,
1038
+ rowCount,
1039
+ rowSelectionActions,
1040
+ searchPlaceholder,
1041
+ storageKey: storageKeyProp,
1042
+ toolbarBelow,
1043
+ toolbarEnd,
1044
+ toolbarStart,
1045
+ } = props;
1046
+ const t = useMessages(dataTableMessages);
1047
+ const ui = useUiMessages();
1048
+ // Persistence needs a key; without one the table keeps state in memory only.
1049
+ const storageKey = storageKeyProp ?? "";
1050
+ const enablePersistence =
1051
+ Boolean(storageKeyProp) && enablePersistenceProp !== false;
1052
+ const formatResultCount = formatResultCountProp ?? t.resultCount;
1053
+ const formatRowCount = formatRowCountProp ?? t.rowCount;
1054
+
1055
+ const defaultColumnOrder = React.useMemo(
1056
+ () => columns.map(getColumnId).filter(isString),
1057
+ [columns],
1058
+ );
1059
+ const defaultColumnOrderKey = defaultColumnOrder.join("|");
1060
+ const pageSizeOptionsKey = pageSizeOptions.join("|");
1061
+ const lockedStartColumnKey = lockedStartColumnIds.join("|");
1062
+ const lockedEndColumnKey = lockedEndColumnIds.join("|");
1063
+ const stablePageSizeOptions = useStableValueByKey(
1064
+ pageSizeOptions,
1065
+ pageSizeOptionsKey,
1066
+ );
1067
+ const stableDefaultColumnOrder = useStableValueByKey(
1068
+ defaultColumnOrder,
1069
+ defaultColumnOrderKey,
1070
+ );
1071
+ const stableInitialColumnFilters = useStableValueByKey(
1072
+ initialColumnFilters,
1073
+ getColumnFiltersKey(initialColumnFilters),
1074
+ );
1075
+ const stableInitialColumnOrder = useStableValueByKey(
1076
+ initialColumnOrder,
1077
+ getOptionalColumnOrderKey(initialColumnOrder),
1078
+ );
1079
+ const stableInitialColumnVisibility = useStableValueByKey(
1080
+ initialColumnVisibility,
1081
+ getVisibilityStateKey(initialColumnVisibility),
1082
+ );
1083
+ const stableInitialSorting = useStableValueByKey(
1084
+ initialSorting,
1085
+ getSortingKey(initialSorting),
1086
+ );
1087
+ const stableLockedStartColumnIds = useStableValueByKey(
1088
+ lockedStartColumnIds,
1089
+ lockedStartColumnKey,
1090
+ );
1091
+ const stableLockedEndColumnIds = useStableValueByKey(
1092
+ lockedEndColumnIds,
1093
+ lockedEndColumnKey,
1094
+ );
1095
+ const [preferencesReady, setPreferencesReady] =
1096
+ React.useState(!enablePersistence);
1097
+ const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});
1098
+ const [columnVisibility, setColumnVisibility] =
1099
+ React.useState<VisibilityState>(stableInitialColumnVisibility);
1100
+ const [columnOrder, setColumnOrder] = React.useState<ColumnOrderState>(() =>
1101
+ normalizeColumnOrder(
1102
+ stableInitialColumnOrder ?? stableDefaultColumnOrder,
1103
+ stableDefaultColumnOrder,
1104
+ stableLockedStartColumnIds,
1105
+ stableLockedEndColumnIds,
1106
+ ),
1107
+ );
1108
+ const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
1109
+ stableInitialColumnFilters,
1110
+ );
1111
+ const [columnSizing, setColumnSizing] =
1112
+ React.useState<ColumnSizingState>(emptyColumnSizing);
1113
+ const [sorting, setSorting] =
1114
+ React.useState<SortingState>(stableInitialSorting);
1115
+ const [globalFilter, setGlobalFilter] = React.useState(initialGlobalFilter);
1116
+ const [pagination, setPagination] = React.useState<PaginationState>({
1117
+ pageIndex: 0,
1118
+ pageSize: resolvePageSize(
1119
+ initialPageSize,
1120
+ initialPageSize,
1121
+ stablePageSizeOptions,
1122
+ ),
1123
+ });
1124
+ const resetPaginationPage = React.useCallback(() => {
1125
+ setPagination((current) =>
1126
+ current.pageIndex === 0 ? current : { ...current, pageIndex: 0 },
1127
+ );
1128
+ }, []);
1129
+ const handleColumnFiltersChange = React.useCallback<
1130
+ OnChangeFn<ColumnFiltersState>
1131
+ >(
1132
+ (updater) => {
1133
+ setColumnFilters(updater);
1134
+ resetPaginationPage();
1135
+ },
1136
+ [resetPaginationPage],
1137
+ );
1138
+ const handleGlobalFilterChange = React.useCallback<OnChangeFn<string>>(
1139
+ (updater) => {
1140
+ setGlobalFilter(updater);
1141
+ resetPaginationPage();
1142
+ },
1143
+ [resetPaginationPage],
1144
+ );
1145
+ const handleSortingChange = React.useCallback<OnChangeFn<SortingState>>(
1146
+ (updater) => {
1147
+ setSorting(updater);
1148
+ resetPaginationPage();
1149
+ },
1150
+ [resetPaginationPage],
1151
+ );
1152
+
1153
+ const dndContextId = React.useId();
1154
+ const sensors = useSensors(
1155
+ useSensor(MouseSensor, {
1156
+ activationConstraint: {
1157
+ distance: 6,
1158
+ },
1159
+ }),
1160
+ useSensor(TouchSensor, {
1161
+ activationConstraint: {
1162
+ delay: 150,
1163
+ tolerance: 6,
1164
+ },
1165
+ }),
1166
+ useSensor(KeyboardSensor),
1167
+ );
1168
+
1169
+ React.useEffect(() => {
1170
+ if (!enablePersistence) {
1171
+ return;
1172
+ }
1173
+
1174
+ const settings = retainKnownColumnSettings(
1175
+ getStoredDataTableSettings(storageKey),
1176
+ stableDefaultColumnOrder,
1177
+ );
1178
+
1179
+ setColumnVisibility(
1180
+ settings?.columnVisibility ?? stableInitialColumnVisibility,
1181
+ );
1182
+ setColumnOrder(
1183
+ normalizeColumnOrder(
1184
+ settings?.columnOrder ??
1185
+ stableInitialColumnOrder ??
1186
+ stableDefaultColumnOrder,
1187
+ stableDefaultColumnOrder,
1188
+ stableLockedStartColumnIds,
1189
+ stableLockedEndColumnIds,
1190
+ ),
1191
+ );
1192
+ setColumnFilters(settings?.columnFilters ?? stableInitialColumnFilters);
1193
+ setColumnSizing(settings?.columnSizing ?? emptyColumnSizing);
1194
+ setSorting(settings?.sorting ?? stableInitialSorting);
1195
+ setGlobalFilter(settings?.globalFilter ?? "");
1196
+ setPagination({
1197
+ pageIndex: 0,
1198
+ pageSize: resolvePageSize(
1199
+ settings?.pageSize,
1200
+ initialPageSize,
1201
+ stablePageSizeOptions,
1202
+ ),
1203
+ });
1204
+ setPreferencesReady(true);
1205
+ }, [
1206
+ enablePersistence,
1207
+ initialPageSize,
1208
+ stableDefaultColumnOrder,
1209
+ stableInitialColumnFilters,
1210
+ stableInitialColumnOrder,
1211
+ stableInitialColumnVisibility,
1212
+ stableInitialSorting,
1213
+ stableLockedEndColumnIds,
1214
+ stableLockedStartColumnIds,
1215
+ stablePageSizeOptions,
1216
+ storageKey,
1217
+ ]);
1218
+
1219
+ React.useEffect(() => {
1220
+ if (!preferencesReady) {
1221
+ return;
1222
+ }
1223
+
1224
+ setColumnOrder((currentOrder) =>
1225
+ normalizeColumnOrder(
1226
+ currentOrder,
1227
+ stableDefaultColumnOrder,
1228
+ stableLockedStartColumnIds,
1229
+ stableLockedEndColumnIds,
1230
+ ),
1231
+ );
1232
+ }, [
1233
+ preferencesReady,
1234
+ stableDefaultColumnOrder,
1235
+ stableLockedEndColumnIds,
1236
+ stableLockedStartColumnIds,
1237
+ ]);
1238
+
1239
+ React.useEffect(() => {
1240
+ if (!enablePersistence || !preferencesReady) {
1241
+ return;
1242
+ }
1243
+
1244
+ window.localStorage.setItem(
1245
+ storageKey,
1246
+ JSON.stringify({
1247
+ columnFilters,
1248
+ columnOrder,
1249
+ columnSizing,
1250
+ columnVisibility,
1251
+ globalFilter,
1252
+ pageSize: pagination.pageSize,
1253
+ sorting,
1254
+ } satisfies StoredDataTableSettings),
1255
+ );
1256
+ }, [
1257
+ columnFilters,
1258
+ columnOrder,
1259
+ columnSizing,
1260
+ columnVisibility,
1261
+ enablePersistence,
1262
+ globalFilter,
1263
+ pagination.pageSize,
1264
+ preferencesReady,
1265
+ sorting,
1266
+ storageKey,
1267
+ ]);
1268
+
1269
+ React.useEffect(() => {
1270
+ if (!preferencesReady) {
1271
+ return;
1272
+ }
1273
+
1274
+ onStateChange?.({
1275
+ columnFilters,
1276
+ globalFilter,
1277
+ pagination,
1278
+ sorting,
1279
+ });
1280
+ }, [
1281
+ columnFilters,
1282
+ globalFilter,
1283
+ onStateChange,
1284
+ pagination,
1285
+ preferencesReady,
1286
+ sorting,
1287
+ ]);
1288
+
1289
+ const table = useDataTableInstance<TData>({
1290
+ // TanStack schedules auto resets while evaluating row models during render.
1291
+ // Concurrent/Suspense renders may not have committed yet, so reset in an effect.
1292
+ autoResetPageIndex: false,
1293
+ columnResizeMode: "onChange",
1294
+ columns,
1295
+ data,
1296
+ enableColumnResizing: true,
1297
+ enableMultiSort: true,
1298
+ enableRowSelection,
1299
+ filterFns,
1300
+ getCoreRowModel: getCoreRowModel(),
1301
+ getFilteredRowModel: getFilteredRowModel(),
1302
+ getPaginationRowModel: getPaginationRowModel(),
1303
+ getRowId,
1304
+ getSortedRowModel: getSortedRowModel(),
1305
+ // An explicit undefined would replace TanStack's default and disable search.
1306
+ globalFilterFn: globalFilterFn ?? "includesString",
1307
+ isMultiSortEvent: () => true,
1308
+ manualFiltering,
1309
+ manualPagination,
1310
+ manualSorting,
1311
+ maxMultiSortColCount: 5,
1312
+ meta: {
1313
+ enableExcludeFilters:
1314
+ enableExcludeFilters ?? (!manualFiltering && !onStateChange),
1315
+ },
1316
+ onColumnFiltersChange: handleColumnFiltersChange,
1317
+ onColumnOrderChange: setColumnOrder,
1318
+ onColumnSizingChange: setColumnSizing,
1319
+ onColumnVisibilityChange: setColumnVisibility,
1320
+ onGlobalFilterChange: handleGlobalFilterChange,
1321
+ onPaginationChange: setPagination,
1322
+ onRowSelectionChange: setRowSelection,
1323
+ onSortingChange: handleSortingChange,
1324
+ pageCount,
1325
+ rowCount,
1326
+ state: {
1327
+ columnFilters,
1328
+ columnOrder,
1329
+ columnSizing,
1330
+ columnVisibility,
1331
+ globalFilter,
1332
+ pagination,
1333
+ rowSelection,
1334
+ sorting,
1335
+ },
1336
+ });
1337
+
1338
+ React.useEffect(() => {
1339
+ if (!manualPagination) resetPaginationPage();
1340
+ }, [data, manualPagination, resetPaginationPage]);
1341
+
1342
+ const handleDragEnd = (event: DragEndEvent) => {
1343
+ const { active, over } = event;
1344
+
1345
+ if (!over || active.id === over.id) {
1346
+ return;
1347
+ }
1348
+
1349
+ if (
1350
+ isLockedColumn(
1351
+ String(active.id),
1352
+ stableLockedStartColumnIds,
1353
+ stableLockedEndColumnIds,
1354
+ )
1355
+ ) {
1356
+ return;
1357
+ }
1358
+
1359
+ setColumnOrder((currentOrder) => {
1360
+ const oldIndex = currentOrder.indexOf(String(active.id));
1361
+ const newIndex = currentOrder.indexOf(String(over.id));
1362
+
1363
+ if (oldIndex === -1 || newIndex === -1) {
1364
+ return currentOrder;
1365
+ }
1366
+
1367
+ return normalizeColumnOrder(
1368
+ arrayMove(currentOrder, oldIndex, newIndex),
1369
+ stableDefaultColumnOrder,
1370
+ stableLockedStartColumnIds,
1371
+ stableLockedEndColumnIds,
1372
+ );
1373
+ });
1374
+ };
1375
+
1376
+ const resetColumns = () => {
1377
+ setColumnVisibility(stableInitialColumnVisibility);
1378
+ setColumnOrder(
1379
+ normalizeColumnOrder(
1380
+ stableInitialColumnOrder ?? stableDefaultColumnOrder,
1381
+ stableDefaultColumnOrder,
1382
+ stableLockedStartColumnIds,
1383
+ stableLockedEndColumnIds,
1384
+ ),
1385
+ );
1386
+ setColumnSizing(emptyColumnSizing);
1387
+ };
1388
+
1389
+ const resetFilters = React.useCallback(() => {
1390
+ setColumnFilters(stableInitialColumnFilters);
1391
+ setGlobalFilter("");
1392
+ setPagination((current) => ({ ...current, pageIndex: 0 }));
1393
+ }, [stableInitialColumnFilters]);
1394
+
1395
+ React.useEffect(() => {
1396
+ const handleResetFilters = (event: Event) => {
1397
+ const resetStorageKey = getResetFiltersStorageKey(event);
1398
+
1399
+ if (resetStorageKey && resetStorageKey !== storageKey) {
1400
+ return;
1401
+ }
1402
+
1403
+ resetFilters();
1404
+ };
1405
+
1406
+ window.addEventListener(DATA_TABLE_RESET_FILTERS_EVENT, handleResetFilters);
1407
+
1408
+ return () => {
1409
+ window.removeEventListener(
1410
+ DATA_TABLE_RESET_FILTERS_EVENT,
1411
+ handleResetFilters,
1412
+ );
1413
+ };
1414
+ }, [resetFilters, storageKey]);
1415
+
1416
+ if (!preferencesReady) {
1417
+ return <DataTableSkeleton />;
1418
+ }
1419
+
1420
+ const retry = onRetry ? (
1421
+ <Button variant="outline" size="sm" onClick={onRetry}>
1422
+ <RotateCwIcon data-icon="inline-start" />
1423
+ {ui.retry}
1424
+ </Button>
1425
+ ) : null;
1426
+
1427
+ if (unavailable) {
1428
+ return (
1429
+ <Empty className="rounded-3xl border border-dashed">
1430
+ <EmptyHeader>
1431
+ <EmptyMedia variant="icon">
1432
+ <LockIcon />
1433
+ </EmptyMedia>
1434
+ <EmptyTitle>{unavailable}</EmptyTitle>
1435
+ </EmptyHeader>
1436
+ </Empty>
1437
+ );
1438
+ }
1439
+
1440
+ if (error && !data.length && !loading) {
1441
+ return (
1442
+ <Empty className="rounded-3xl border border-dashed">
1443
+ <EmptyHeader>
1444
+ <EmptyMedia variant="icon">
1445
+ <CircleAlertIcon />
1446
+ </EmptyMedia>
1447
+ <EmptyTitle>{ui.loadFailed}</EmptyTitle>
1448
+ <EmptyDescription>{error}</EmptyDescription>
1449
+ </EmptyHeader>
1450
+ {retry ? <EmptyContent>{retry}</EmptyContent> : null}
1451
+ </Empty>
1452
+ );
1453
+ }
1454
+
1455
+ const isFiltered = Boolean(globalFilter) || columnFilters.length > 0;
1456
+
1457
+ const filteredRowCount = rowCount ?? table.getFilteredRowModel().rows.length;
1458
+ const selectedRowCount = table.getFilteredSelectedRowModel().rows.length;
1459
+ const selectedRowsLabel =
1460
+ formatSelectedRowCount ??
1461
+ ((count: number) => t.selected(formatRowCount(count), count));
1462
+ const toolbarStartContent = toolbarStart?.(table);
1463
+ const toolbarEndContent = toolbarEnd?.(table);
1464
+ const toolbarBelowContent = toolbarBelow?.(table);
1465
+ const rowSelectionActionsContent = rowSelectionActions?.(table);
1466
+
1467
+ return (
1468
+ <div
1469
+ className={cn(
1470
+ "flex w-full min-w-0 flex-col gap-4",
1471
+ fillHeight && "min-h-0 flex-1",
1472
+ )}
1473
+ >
1474
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
1475
+ {toolbarStartContent}
1476
+ <div className="flex min-w-0 flex-1 basis-80 items-center gap-2">
1477
+ <InputGroup className="flex-1">
1478
+ <InputGroupInput
1479
+ value={globalFilter}
1480
+ onChange={(event) => handleGlobalFilterChange(event.target.value)}
1481
+ placeholder={searchPlaceholder ?? t.search}
1482
+ />
1483
+ <InputGroupAddon className="pl-2">
1484
+ <SearchIcon />
1485
+ </InputGroupAddon>
1486
+ <InputGroupAddon align="inline-end" className="pr-2">
1487
+ {formatResultCount(filteredRowCount)}
1488
+ </InputGroupAddon>
1489
+ </InputGroup>
1490
+ {toolbarEndContent}
1491
+ <ColumnSettings
1492
+ defaultColumnOrder={defaultColumnOrder}
1493
+ lockedEndColumnIds={lockedEndColumnIds}
1494
+ lockedStartColumnIds={lockedStartColumnIds}
1495
+ onResetColumns={resetColumns}
1496
+ table={table}
1497
+ />
1498
+ </div>
1499
+ </div>
1500
+
1501
+ {toolbarBelowContent}
1502
+
1503
+ {error ? (
1504
+ <Alert variant="destructive">
1505
+ <CircleAlertIcon />
1506
+ <AlertTitle>{ui.staleData}</AlertTitle>
1507
+ <AlertDescription>{error}</AlertDescription>
1508
+ {retry ? <AlertAction>{retry}</AlertAction> : null}
1509
+ </Alert>
1510
+ ) : null}
1511
+ {warning ? (
1512
+ <Alert>
1513
+ <TriangleAlertIcon />
1514
+ <AlertTitle>{warning}</AlertTitle>
1515
+ </Alert>
1516
+ ) : null}
1517
+
1518
+ {enableRowSelection && selectedRowCount > 0 && (
1519
+ <div className="bg-muted/40 flex flex-col gap-2 rounded-2xl border p-2 sm:flex-row sm:items-center sm:justify-between">
1520
+ <p className="text-foreground px-1 text-sm font-medium">
1521
+ {selectedRowsLabel(selectedRowCount)}
1522
+ </p>
1523
+ <div className="flex flex-wrap items-center gap-2">
1524
+ {rowSelectionActionsContent}
1525
+ <Button
1526
+ type="button"
1527
+ variant="outline"
1528
+ size="sm"
1529
+ onClick={() => table.resetRowSelection()}
1530
+ >
1531
+ <XIcon data-icon="inline-start" />
1532
+ {t.clearSelection}
1533
+ </Button>
1534
+ </div>
1535
+ </div>
1536
+ )}
1537
+
1538
+ <DndContext
1539
+ // Stable id: dnd-kit's global counter differs between server and client.
1540
+ id={dndContextId}
1541
+ collisionDetection={closestCenter}
1542
+ modifiers={[restrictToHorizontalAxis]}
1543
+ onDragEnd={handleDragEnd}
1544
+ sensors={sensors}
1545
+ >
1546
+ <div
1547
+ className={cn(
1548
+ "bg-card overflow-hidden rounded-2xl border",
1549
+ fillHeight && "flex min-h-0 flex-1 flex-col",
1550
+ )}
1551
+ >
1552
+ <Table
1553
+ containerClassName={
1554
+ // Bottom-only fade: a top fade would dissolve the sticky header.
1555
+ fillHeight
1556
+ ? "min-h-0 flex-1 overflow-auto scroll-fade-b"
1557
+ : undefined
1558
+ }
1559
+ style={{ minWidth: "100%", width: table.getTotalSize() }}
1560
+ >
1561
+ {/* Solid background: rows scroll underneath the sticky header. */}
1562
+ <TableHeader className="bg-muted sticky top-0 z-10">
1563
+ {table.getHeaderGroups().map((headerGroup) => (
1564
+ <TableRow key={headerGroup.id}>
1565
+ <SortableContext
1566
+ items={columnOrder}
1567
+ strategy={horizontalListSortingStrategy}
1568
+ >
1569
+ {headerGroup.headers.map((header) => (
1570
+ <DataTableHead
1571
+ key={header.id}
1572
+ header={header}
1573
+ lockedEndColumnIds={lockedEndColumnIds}
1574
+ lockedStartColumnIds={lockedStartColumnIds}
1575
+ />
1576
+ ))}
1577
+ </SortableContext>
1578
+ </TableRow>
1579
+ ))}
1580
+ </TableHeader>
1581
+ <TableBody>
1582
+ {loading ? (
1583
+ Array.from({ length: 3 }, (_, index) => (
1584
+ <TableRow key={index}>
1585
+ {table.getVisibleLeafColumns().map((column) => (
1586
+ <TableCell key={column.id}>
1587
+ <Skeleton className="h-5 w-full" />
1588
+ </TableCell>
1589
+ ))}
1590
+ </TableRow>
1591
+ ))
1592
+ ) : table.getRowModel().rows?.length ? (
1593
+ table.getRowModel().rows.map((row) => (
1594
+ <TableRow
1595
+ key={row.id}
1596
+ data-active={row.id === activeRowId || undefined}
1597
+ aria-current={row.id === activeRowId ? "true" : undefined}
1598
+ data-state={row.getIsSelected() && "selected"}
1599
+ className={onRowClick ? "cursor-pointer" : undefined}
1600
+ tabIndex={onRowClick ? 0 : undefined}
1601
+ aria-label={
1602
+ onRowClick
1603
+ ? `${t.open}: ${getRowLabel?.(row.original) ?? row.id}`
1604
+ : undefined
1605
+ }
1606
+ onClick={
1607
+ onRowClick ? () => onRowClick(row.original) : undefined
1608
+ }
1609
+ onKeyDown={
1610
+ onRowClick
1611
+ ? (event) => {
1612
+ if (event.key === "Enter" || event.key === " ") {
1613
+ event.preventDefault();
1614
+ onRowClick(row.original);
1615
+ }
1616
+ }
1617
+ : undefined
1618
+ }
1619
+ >
1620
+ {row.getVisibleCells().map((cell) => (
1621
+ <TableCell
1622
+ key={cell.id}
1623
+ className={cn(
1624
+ "whitespace-nowrap",
1625
+ getColumnAlignClass(cell.column),
1626
+ getColumnMeta(cell.column)?.cellClassName,
1627
+ )}
1628
+ style={{ width: cell.column.getSize() }}
1629
+ >
1630
+ {flexRender(
1631
+ cell.column.columnDef.cell,
1632
+ cell.getContext(),
1633
+ )}
1634
+ </TableCell>
1635
+ ))}
1636
+ </TableRow>
1637
+ ))
1638
+ ) : (
1639
+ <TableRow>
1640
+ <TableCell
1641
+ colSpan={table.getVisibleLeafColumns().length}
1642
+ className="text-muted-foreground h-24 text-center"
1643
+ >
1644
+ {isFiltered ? (
1645
+ <Empty>
1646
+ <EmptyHeader>
1647
+ <EmptyTitle>
1648
+ {emptyMessage ?? ui.noResults}
1649
+ </EmptyTitle>
1650
+ </EmptyHeader>
1651
+ <EmptyContent>
1652
+ <Button
1653
+ variant="outline"
1654
+ size="sm"
1655
+ onClick={resetFilters}
1656
+ >
1657
+ {t.clearFilters}
1658
+ </Button>
1659
+ </EmptyContent>
1660
+ </Empty>
1661
+ ) : (
1662
+ (emptyState ?? (
1663
+ <Empty>
1664
+ <EmptyHeader>
1665
+ <EmptyMedia variant="icon">
1666
+ <InboxIcon />
1667
+ </EmptyMedia>
1668
+ <EmptyTitle>{emptyMessage ?? ui.noData}</EmptyTitle>
1669
+ </EmptyHeader>
1670
+ </Empty>
1671
+ ))
1672
+ )}
1673
+ </TableCell>
1674
+ </TableRow>
1675
+ )}
1676
+ </TableBody>
1677
+ </Table>
1678
+ </div>
1679
+ </DndContext>
1680
+
1681
+ <DataTablePagination
1682
+ formatRowCount={formatRowCount}
1683
+ formatSelectedRowCount={formatSelectedRowCount}
1684
+ pageSizeOptions={stablePageSizeOptions}
1685
+ rowCount={rowCount}
1686
+ storageKey={storageKey}
1687
+ table={table}
1688
+ />
1689
+ </div>
1690
+ );
1691
+ }
1692
+
1693
+ function DataTableHead<TData extends RowData>({
1694
+ header,
1695
+ lockedEndColumnIds,
1696
+ lockedStartColumnIds,
1697
+ }: {
1698
+ header: Header<TData, unknown>;
1699
+ lockedEndColumnIds: string[];
1700
+ lockedStartColumnIds: string[];
1701
+ }) {
1702
+ const t = useMessages(dataTableMessages);
1703
+ const column = header.column;
1704
+ const table = header.getContext().table;
1705
+ const align = getColumnAlign(column);
1706
+ const isSorted = column.getIsSorted();
1707
+ const sortIndex = table
1708
+ .getState()
1709
+ .sorting.findIndex((sort) => sort.id === column.id);
1710
+ const isLocked = isLockedColumn(
1711
+ column.id,
1712
+ lockedStartColumnIds,
1713
+ lockedEndColumnIds,
1714
+ );
1715
+ const canOpenColumnMenu = !header.isPlaceholder && !isLocked;
1716
+ const {
1717
+ attributes,
1718
+ isDragging,
1719
+ listeners,
1720
+ setNodeRef,
1721
+ transform,
1722
+ transition,
1723
+ } = useSortable({
1724
+ id: column.id,
1725
+ disabled: isLocked,
1726
+ });
1727
+ const [menuOpen, setMenuOpen] = React.useState(false);
1728
+
1729
+ const columnControls =
1730
+ column.getCanSort() || !isLocked ? (
1731
+ <div
1732
+ className={cn(
1733
+ "flex shrink-0 items-center gap-1",
1734
+ align === "right" ? "order-first mr-1" : "ml-1",
1735
+ )}
1736
+ >
1737
+ {column.getCanSort() && (
1738
+ <Button
1739
+ type="button"
1740
+ variant="ghost"
1741
+ size="icon-xs"
1742
+ className={cn(
1743
+ "transition-opacity",
1744
+ isSorted ? "text-foreground bg-accent" : "text-muted-foreground",
1745
+ getHeaderControlVisibilityClass(Boolean(isSorted)),
1746
+ )}
1747
+ onClick={() => toggleColumnSorting(table, column.id)}
1748
+ aria-label={t.toggleSort(getColumnLabel(column))}
1749
+ >
1750
+ <ColumnSortIcon isSorted={isSorted} />
1751
+ </Button>
1752
+ )}
1753
+ {sortIndex >= 0 && table.getState().sorting.length > 1 && (
1754
+ <Badge
1755
+ variant="secondary"
1756
+ className="px-1"
1757
+ title={t.sortCriterionTitle(sortIndex + 1)}
1758
+ >
1759
+ {sortIndex + 1}
1760
+ </Badge>
1761
+ )}
1762
+ {!isLocked && (
1763
+ <Button
1764
+ type="button"
1765
+ variant="ghost"
1766
+ size="icon-xs"
1767
+ className={cn(
1768
+ "text-muted-foreground cursor-grab transition-opacity active:cursor-grabbing",
1769
+ getHeaderControlVisibilityClass(isDragging),
1770
+ )}
1771
+ aria-label={t.reorderColumn(getColumnLabel(column))}
1772
+ {...attributes}
1773
+ {...listeners}
1774
+ >
1775
+ <GripVerticalIcon />
1776
+ </Button>
1777
+ )}
1778
+ </div>
1779
+ ) : null;
1780
+
1781
+ return (
1782
+ <TableHead
1783
+ ref={setNodeRef}
1784
+ colSpan={header.colSpan}
1785
+ aria-sort={getColumnAriaSort(isSorted)}
1786
+ className={cn(
1787
+ "relative whitespace-nowrap",
1788
+ getColumnAlignClass(column),
1789
+ getColumnMeta(column)?.headerClassName,
1790
+ isDragging && "bg-muted relative z-20 opacity-80",
1791
+ )}
1792
+ style={{
1793
+ transform: CSS.Translate.toString(transform),
1794
+ transition,
1795
+ width: header.getSize(),
1796
+ }}
1797
+ >
1798
+ {header.isPlaceholder ? null : (
1799
+ <div
1800
+ className={cn(
1801
+ "group/header flex w-full items-center",
1802
+ align === "center" && "justify-center",
1803
+ align === "right" && "justify-end",
1804
+ )}
1805
+ >
1806
+ <div className="flex min-w-0 flex-1 items-center">
1807
+ {canOpenColumnMenu ? (
1808
+ <ColumnHeaderMenu
1809
+ header={header}
1810
+ open={menuOpen}
1811
+ onOpenChange={setMenuOpen}
1812
+ />
1813
+ ) : (
1814
+ <div className="flex h-8 items-center px-0">
1815
+ {flexRender(column.columnDef.header, header.getContext())}
1816
+ </div>
1817
+ )}
1818
+ </div>
1819
+ {columnControls}
1820
+ </div>
1821
+ )}
1822
+ {column.getCanResize() && !isLocked ? (
1823
+ <div
1824
+ role="separator"
1825
+ aria-orientation="vertical"
1826
+ aria-label={t.resizeColumn(getColumnLabel(column))}
1827
+ className={cn(
1828
+ "hover:bg-primary/50 absolute inset-y-0 right-0 z-10 w-1 cursor-col-resize touch-none bg-transparent select-none",
1829
+ column.getIsResizing() && "bg-primary",
1830
+ )}
1831
+ onDoubleClick={() => column.resetSize()}
1832
+ onMouseDown={header.getResizeHandler()}
1833
+ onTouchStart={header.getResizeHandler()}
1834
+ />
1835
+ ) : null}
1836
+ </TableHead>
1837
+ );
1838
+ }
1839
+
1840
+ function ColumnHeaderMenuTrigger<TData extends RowData>({
1841
+ className,
1842
+ header,
1843
+ }: {
1844
+ className?: string;
1845
+ header: Header<TData, unknown>;
1846
+ }) {
1847
+ const t = useMessages(dataTableMessages);
1848
+ const column = header.column;
1849
+ const align = getColumnAlign(column);
1850
+ const isFiltered = isFilterValueActive(column.getFilterValue());
1851
+ const isExcluding =
1852
+ isFiltered && readMultiFilterValue(column.getFilterValue()).exclude;
1853
+ const ActiveFilterIcon = isExcluding ? FunnelXIcon : FunnelIcon;
1854
+
1855
+ return (
1856
+ <PopoverTrigger
1857
+ render={
1858
+ <Button
1859
+ type="button"
1860
+ variant="ghost"
1861
+ size="sm"
1862
+ className={cn(
1863
+ "relative -mx-2.5 h-8 w-[calc(100%+1.25rem)] min-w-0 justify-start px-2.5",
1864
+ align === "center" && "justify-center",
1865
+ align === "right" && "justify-end",
1866
+ className,
1867
+ )}
1868
+ />
1869
+ }
1870
+ >
1871
+ <span className="truncate">{getColumnLabel(column)}</span>
1872
+ {isFiltered && (
1873
+ <>
1874
+ <ActiveFilterIcon data-icon="inline-end" aria-hidden />
1875
+ <span className="sr-only">
1876
+ {isExcluding ? t.excludeFilterActive : t.filterActive}
1877
+ </span>
1878
+ </>
1879
+ )}
1880
+ </PopoverTrigger>
1881
+ );
1882
+ }
1883
+
1884
+ function ColumnSortIcon({ isSorted }: { isSorted: DataTableSortDirection }) {
1885
+ if (isSorted === "asc") {
1886
+ return <ArrowUpNarrowWideIcon data-icon="inline-end" />;
1887
+ }
1888
+
1889
+ if (isSorted === "desc") {
1890
+ return <ArrowDownWideNarrowIcon data-icon="inline-end" />;
1891
+ }
1892
+
1893
+ return <ArrowUpDownIcon data-icon="inline-end" />;
1894
+ }
1895
+
1896
+ function ColumnHeaderMenu<TData extends RowData>({
1897
+ header,
1898
+ onOpenChange,
1899
+ open,
1900
+ }: {
1901
+ header: Header<TData, unknown>;
1902
+ onOpenChange: (open: boolean) => void;
1903
+ open: boolean;
1904
+ }) {
1905
+ const t = useMessages(dataTableMessages);
1906
+ const column = header.column;
1907
+ const table = header.getContext().table;
1908
+ const isSorted = column.getIsSorted();
1909
+ const isFiltered = isFilterValueActive(column.getFilterValue());
1910
+ const sorting = table.getState().sorting;
1911
+ const sortIndex = sorting.findIndex((sort) => sort.id === column.id);
1912
+ const sortCount = sorting.length;
1913
+ const hasColumnState = Boolean(isSorted) || isFiltered;
1914
+
1915
+ const clearColumnState = () => {
1916
+ column.setFilterValue(undefined);
1917
+ clearColumnSorting(table, column.id);
1918
+ };
1919
+
1920
+ return (
1921
+ <Popover open={open} onOpenChange={onOpenChange}>
1922
+ <ColumnHeaderMenuTrigger header={header} />
1923
+ <PopoverContent align="start" className="w-72 p-0">
1924
+ <div className="flex flex-col gap-3 p-3">
1925
+ <div className="flex min-w-0 items-start justify-between gap-2">
1926
+ <div className="min-w-0">
1927
+ <div className="truncate text-sm font-medium">
1928
+ {getColumnLabel(column)}
1929
+ </div>
1930
+ </div>
1931
+ {sortIndex >= 0 && sortCount > 1 && (
1932
+ <Badge variant="outline" className="shrink-0">
1933
+ {t.sortCriterion(sortIndex + 1)}
1934
+ </Badge>
1935
+ )}
1936
+ </div>
1937
+
1938
+ {column.getCanSort() && (
1939
+ <ColumnSortControls
1940
+ column={column}
1941
+ isSorted={isSorted}
1942
+ table={table}
1943
+ />
1944
+ )}
1945
+
1946
+ <ColumnFilterControls
1947
+ allowExclude={Boolean(table.options.meta?.enableExcludeFilters)}
1948
+ column={column}
1949
+ />
1950
+
1951
+ {(hasColumnState || column.getCanHide()) && (
1952
+ <>
1953
+ <Separator />
1954
+ <div className="flex gap-2">
1955
+ {hasColumnState && (
1956
+ <Button
1957
+ variant="ghost"
1958
+ size="sm"
1959
+ className="flex-1"
1960
+ onClick={clearColumnState}
1961
+ >
1962
+ <XIcon data-icon="inline-start" />
1963
+ {t.clearAll}
1964
+ </Button>
1965
+ )}
1966
+ {column.getCanHide() && (
1967
+ <Button
1968
+ variant="outline"
1969
+ size="sm"
1970
+ className="flex-1"
1971
+ onClick={() => column.toggleVisibility(false)}
1972
+ >
1973
+ <EyeOffIcon data-icon="inline-start" />
1974
+ {t.hide}
1975
+ </Button>
1976
+ )}
1977
+ </div>
1978
+ </>
1979
+ )}
1980
+ </div>
1981
+ </PopoverContent>
1982
+ </Popover>
1983
+ );
1984
+ }
1985
+
1986
+ // Pressed option inside the column menu; the selected state uses the primary
1987
+ // fill plus a check so it stays distinguishable in both themes.
1988
+ function ColumnMenuOption({
1989
+ buttonRef,
1990
+ children,
1991
+ onClick,
1992
+ selected,
1993
+ }: {
1994
+ buttonRef?: React.Ref<HTMLButtonElement>;
1995
+ children: React.ReactNode;
1996
+ onClick: () => void;
1997
+ selected: boolean;
1998
+ }) {
1999
+ return (
2000
+ <Button
2001
+ ref={buttonRef}
2002
+ variant={selected ? "default" : "outline"}
2003
+ size="sm"
2004
+ className="justify-start"
2005
+ aria-pressed={selected}
2006
+ onClick={onClick}
2007
+ >
2008
+ {children}
2009
+ {selected && <CheckIcon data-icon="inline-end" className="ml-auto" />}
2010
+ </Button>
2011
+ );
2012
+ }
2013
+
2014
+ function ColumnSortControls<TData extends RowData>({
2015
+ column,
2016
+ isSorted,
2017
+ table,
2018
+ }: {
2019
+ column: Column<TData, unknown>;
2020
+ isSorted: false | "asc" | "desc";
2021
+ table: TanstackTable<TData>;
2022
+ }) {
2023
+ const t = useMessages(dataTableMessages);
2024
+ const ascendingRef = React.useRef<HTMLButtonElement>(null);
2025
+
2026
+ return (
2027
+ <div className="flex flex-col gap-2">
2028
+ <div className="flex min-h-6 items-center justify-between gap-2">
2029
+ <Label className="text-muted-foreground text-xs">{t.sort}</Label>
2030
+ {isSorted && (
2031
+ <Button
2032
+ variant="ghost"
2033
+ size="xs"
2034
+ onClick={() => {
2035
+ clearColumnSorting(table, column.id);
2036
+ ascendingRef.current?.focus();
2037
+ }}
2038
+ >
2039
+ <XIcon data-icon="inline-start" />
2040
+ {t.removeSort}
2041
+ </Button>
2042
+ )}
2043
+ </div>
2044
+ <div className="grid grid-cols-2 gap-2" role="group" aria-label={t.sort}>
2045
+ <ColumnMenuOption
2046
+ buttonRef={ascendingRef}
2047
+ selected={isSorted === "asc"}
2048
+ onClick={() => setColumnSorting(table, column.id, false)}
2049
+ >
2050
+ <ArrowUpNarrowWideIcon data-icon="inline-start" />
2051
+ {t.ascending}
2052
+ </ColumnMenuOption>
2053
+ <ColumnMenuOption
2054
+ selected={isSorted === "desc"}
2055
+ onClick={() => setColumnSorting(table, column.id, true)}
2056
+ >
2057
+ <ArrowDownWideNarrowIcon data-icon="inline-start" />
2058
+ {t.descending}
2059
+ </ColumnMenuOption>
2060
+ </div>
2061
+ </div>
2062
+ );
2063
+ }
2064
+
2065
+ function ColumnFilterControls<TData extends RowData>({
2066
+ allowExclude,
2067
+ column,
2068
+ }: {
2069
+ allowExclude: boolean;
2070
+ column: Column<TData, unknown>;
2071
+ }) {
2072
+ const t = useMessages(dataTableMessages);
2073
+ const filter = getColumnMeta(column)?.filter;
2074
+
2075
+ if (!filter) {
2076
+ return null;
2077
+ }
2078
+
2079
+ if (filter.type === "custom") {
2080
+ return filter.render(column);
2081
+ }
2082
+
2083
+ if (filter.type === "multi") {
2084
+ return (
2085
+ <ColumnMultiFilter
2086
+ allowExclude={allowExclude}
2087
+ column={column}
2088
+ options={filter.options}
2089
+ />
2090
+ );
2091
+ }
2092
+
2093
+ if (filter.type === "number-range") {
2094
+ const range = readRangeFilterValue(column.getFilterValue());
2095
+
2096
+ return (
2097
+ <div className="flex flex-col gap-2">
2098
+ <Label className="text-muted-foreground text-xs">{t.filter}</Label>
2099
+ <div className="grid grid-cols-2 gap-2">
2100
+ <Input
2101
+ type="number"
2102
+ min={filter.min}
2103
+ max={filter.max}
2104
+ value={range.min ?? ""}
2105
+ onChange={(event) =>
2106
+ setObjectFilterValue(column, "min", event.target.value)
2107
+ }
2108
+ placeholder={filter.minPlaceholder ?? t.min}
2109
+ />
2110
+ <Input
2111
+ type="number"
2112
+ min={filter.min}
2113
+ max={filter.max}
2114
+ value={range.max ?? ""}
2115
+ onChange={(event) =>
2116
+ setObjectFilterValue(column, "max", event.target.value)
2117
+ }
2118
+ placeholder={filter.maxPlaceholder ?? t.max}
2119
+ />
2120
+ </div>
2121
+ </div>
2122
+ );
2123
+ }
2124
+
2125
+ if (filter.type === "date-range") {
2126
+ const range = readDateRangeFilterValue(column.getFilterValue());
2127
+
2128
+ return (
2129
+ <div className="flex flex-col gap-2">
2130
+ <Label className="text-muted-foreground text-xs">{t.filter}</Label>
2131
+ <div className="grid grid-cols-2 gap-2">
2132
+ <Input
2133
+ type="date"
2134
+ value={range.from ?? ""}
2135
+ onChange={(event) =>
2136
+ setObjectFilterValue(column, "from", event.target.value)
2137
+ }
2138
+ />
2139
+ <Input
2140
+ type="date"
2141
+ value={range.to ?? ""}
2142
+ onChange={(event) =>
2143
+ setObjectFilterValue(column, "to", event.target.value)
2144
+ }
2145
+ />
2146
+ </div>
2147
+ </div>
2148
+ );
2149
+ }
2150
+
2151
+ return <ColumnTextFilter column={column} placeholder={filter.placeholder} />;
2152
+ }
2153
+
2154
+ function ColumnTextFilter<TData extends RowData>({
2155
+ column,
2156
+ placeholder,
2157
+ }: {
2158
+ column: Column<TData, unknown>;
2159
+ placeholder?: string;
2160
+ }) {
2161
+ const t = useMessages(dataTableMessages);
2162
+ const label = getColumnLabel(column).toLocaleLowerCase();
2163
+
2164
+ return (
2165
+ <div className="flex flex-col gap-2">
2166
+ <Label className="text-muted-foreground text-xs">{t.filter}</Label>
2167
+ <Input
2168
+ value={
2169
+ readStringProperty({ value: column.getFilterValue() }, "value") ?? ""
2170
+ }
2171
+ onChange={(event) =>
2172
+ column.setFilterValue(event.target.value || undefined)
2173
+ }
2174
+ placeholder={placeholder ?? t.filterBy(label)}
2175
+ />
2176
+ </div>
2177
+ );
2178
+ }
2179
+
2180
+ function ColumnMultiFilter<TData extends RowData>({
2181
+ allowExclude,
2182
+ column,
2183
+ options,
2184
+ }: {
2185
+ allowExclude: boolean;
2186
+ column: Column<TData, unknown>;
2187
+ options: DataTableFilterOption[];
2188
+ }) {
2189
+ const t = useMessages(dataTableMessages);
2190
+ const stored = readMultiFilterValue(column.getFilterValue());
2191
+ const [pendingExclude, setPendingExclude] = React.useState(stored.exclude);
2192
+ const selected = stored.values;
2193
+ const exclude =
2194
+ allowExclude && (selected.length ? stored.exclude : pendingExclude);
2195
+
2196
+ const toggleValue = (value: string, checked: boolean) => {
2197
+ const next = checked
2198
+ ? [...selected, value]
2199
+ : selected.filter((item) => item !== value);
2200
+
2201
+ column.setFilterValue(toMultiFilterValue(exclude, next));
2202
+ };
2203
+
2204
+ const setMode = (nextExclude: boolean) => {
2205
+ setPendingExclude(nextExclude);
2206
+ column.setFilterValue(toMultiFilterValue(nextExclude, selected));
2207
+ };
2208
+
2209
+ return (
2210
+ <div className="flex flex-col gap-2">
2211
+ <Label className="text-muted-foreground text-xs">{t.filter}</Label>
2212
+ {allowExclude && (
2213
+ <div
2214
+ className="grid grid-cols-2 gap-2"
2215
+ role="group"
2216
+ aria-label={t.filterMode}
2217
+ >
2218
+ <ColumnMenuOption selected={!exclude} onClick={() => setMode(false)}>
2219
+ <FunnelIcon data-icon="inline-start" />
2220
+ {t.show}
2221
+ </ColumnMenuOption>
2222
+ <ColumnMenuOption selected={exclude} onClick={() => setMode(true)}>
2223
+ <FunnelXIcon data-icon="inline-start" />
2224
+ {t.exclude}
2225
+ </ColumnMenuOption>
2226
+ </div>
2227
+ )}
2228
+ <div
2229
+ className="flex max-h-56 scroll-fade flex-col gap-1 overflow-auto rounded-2xl border p-1"
2230
+ role="group"
2231
+ aria-label={exclude ? t.valuesToExclude : t.valuesToShow}
2232
+ >
2233
+ {options.map((option) => (
2234
+ <label
2235
+ key={option.value}
2236
+ className="hover:bg-accent flex items-center gap-2 rounded-xl px-2 py-1.5 text-sm font-normal"
2237
+ >
2238
+ <Checkbox
2239
+ checked={selected.includes(option.value)}
2240
+ onCheckedChange={(checked) =>
2241
+ toggleValue(option.value, Boolean(checked))
2242
+ }
2243
+ />
2244
+ <span
2245
+ className={cn(
2246
+ "min-w-0 flex-1 truncate",
2247
+ exclude &&
2248
+ selected.includes(option.value) &&
2249
+ "text-muted-foreground line-through",
2250
+ )}
2251
+ >
2252
+ {option.label}
2253
+ </span>
2254
+ </label>
2255
+ ))}
2256
+ </div>
2257
+ </div>
2258
+ );
2259
+ }
2260
+
2261
+ function ColumnSettings<TData extends RowData>({
2262
+ defaultColumnOrder,
2263
+ lockedEndColumnIds,
2264
+ lockedStartColumnIds,
2265
+ onResetColumns,
2266
+ table,
2267
+ }: {
2268
+ defaultColumnOrder: ColumnOrderState;
2269
+ lockedEndColumnIds: string[];
2270
+ lockedStartColumnIds: string[];
2271
+ onResetColumns: () => void;
2272
+ table: TanstackTable<TData>;
2273
+ }) {
2274
+ const t = useMessages(dataTableMessages);
2275
+ const hiddenColumnCount = table
2276
+ .getAllLeafColumns()
2277
+ .filter((column) => column.getCanHide())
2278
+ .filter((column) => !column.getIsVisible()).length;
2279
+ const visibleColumnsCustomized = hiddenColumnCount > 0;
2280
+ const columnOrderCustomized = !areColumnOrdersEqual(
2281
+ normalizeColumnOrder(
2282
+ table.getState().columnOrder,
2283
+ defaultColumnOrder,
2284
+ lockedStartColumnIds,
2285
+ lockedEndColumnIds,
2286
+ ),
2287
+ normalizeColumnOrder(
2288
+ defaultColumnOrder,
2289
+ defaultColumnOrder,
2290
+ lockedStartColumnIds,
2291
+ lockedEndColumnIds,
2292
+ ),
2293
+ );
2294
+ const columnsCustomized = visibleColumnsCustomized || columnOrderCustomized;
2295
+
2296
+ return (
2297
+ <TooltipProvider>
2298
+ <Tooltip>
2299
+ <DropdownMenu>
2300
+ <TooltipTrigger
2301
+ render={
2302
+ <DropdownMenuTrigger
2303
+ render={
2304
+ <Button
2305
+ variant="outline"
2306
+ size="icon-sm"
2307
+ className="relative"
2308
+ aria-label={t.customizeColumns}
2309
+ />
2310
+ }
2311
+ />
2312
+ }
2313
+ >
2314
+ <Columns3Icon />
2315
+ {hiddenColumnCount > 0 && (
2316
+ <span className="bg-primary absolute -top-0.5 -right-0.5 size-2 rounded-full" />
2317
+ )}
2318
+ </TooltipTrigger>
2319
+ <TooltipContent side="bottom" align="end">
2320
+ {t.columnsTooltip}
2321
+ </TooltipContent>
2322
+ <DropdownMenuContent align="end" className="w-64">
2323
+ <DropdownMenuGroup>
2324
+ <DropdownMenuLabel>{t.columns}</DropdownMenuLabel>
2325
+ {table
2326
+ .getAllLeafColumns()
2327
+ .filter((column) => column.getCanHide())
2328
+ .map((column) => (
2329
+ <DropdownMenuCheckboxItem
2330
+ key={column.id}
2331
+ checked={column.getIsVisible()}
2332
+ onCheckedChange={(value) =>
2333
+ column.toggleVisibility(!!value)
2334
+ }
2335
+ closeOnClick={false}
2336
+ >
2337
+ {getColumnLabel(column)}
2338
+ </DropdownMenuCheckboxItem>
2339
+ ))}
2340
+ </DropdownMenuGroup>
2341
+ {columnsCustomized && (
2342
+ <>
2343
+ <DropdownMenuSeparator />
2344
+ <DropdownMenuItem onClick={onResetColumns}>
2345
+ <XIcon />
2346
+ {t.resetColumns}
2347
+ </DropdownMenuItem>
2348
+ </>
2349
+ )}
2350
+ </DropdownMenuContent>
2351
+ </DropdownMenu>
2352
+ </Tooltip>
2353
+ </TooltipProvider>
2354
+ );
2355
+ }
2356
+
2357
+ function DataTablePagination<TData extends RowData>({
2358
+ formatRowCount,
2359
+ formatSelectedRowCount,
2360
+ pageSizeOptions,
2361
+ rowCount,
2362
+ storageKey,
2363
+ table,
2364
+ }: {
2365
+ formatRowCount: (count: number) => string;
2366
+ formatSelectedRowCount?: (count: number) => string;
2367
+ pageSizeOptions: number[];
2368
+ rowCount?: number;
2369
+ storageKey: string;
2370
+ table: TanstackTable<TData>;
2371
+ }) {
2372
+ const t = useMessages(dataTableMessages);
2373
+ const selectedRows = table.getFilteredSelectedRowModel().rows.length;
2374
+ const filteredRows = rowCount ?? table.getFilteredRowModel().rows.length;
2375
+ const totalRows = rowCount ?? table.getCoreRowModel().rows.length;
2376
+ const selectedRowsLabel =
2377
+ formatSelectedRowCount ??
2378
+ ((count: number) => t.selected(formatRowCount(count), count));
2379
+ const fallbackId = React.useId();
2380
+ const inputId = storageKey
2381
+ ? `${getStorageSafeId(storageKey)}-rows-per-page`
2382
+ : fallbackId;
2383
+ let paginationSummary = t.ofSummary(
2384
+ formatRowCount(filteredRows),
2385
+ formatRowCount(totalRows),
2386
+ );
2387
+
2388
+ if (selectedRows > 0) {
2389
+ paginationSummary = t.ofSummary(
2390
+ selectedRowsLabel(selectedRows),
2391
+ formatRowCount(filteredRows),
2392
+ );
2393
+ } else if (filteredRows === totalRows) {
2394
+ paginationSummary = `${formatRowCount(totalRows)}.`;
2395
+ }
2396
+
2397
+ return (
2398
+ <div className="flex flex-col gap-3 px-1 sm:flex-row sm:items-center sm:justify-between">
2399
+ <div className="text-muted-foreground text-sm">{paginationSummary}</div>
2400
+ <div className="flex flex-wrap items-center gap-3">
2401
+ <div className="flex items-center gap-2">
2402
+ <Label htmlFor={inputId} className="text-sm">
2403
+ {t.rowsPerPage}
2404
+ </Label>
2405
+ <Select
2406
+ value={`${table.getState().pagination.pageSize}`}
2407
+ onValueChange={(value) => table.setPageSize(Number(value))}
2408
+ >
2409
+ <SelectTrigger id={inputId} size="sm" className="w-20">
2410
+ <SelectValue />
2411
+ </SelectTrigger>
2412
+ <SelectContent side="top">
2413
+ {pageSizeOptions.map((pageSize) => (
2414
+ <SelectItem key={pageSize} value={`${pageSize}`}>
2415
+ {pageSize}
2416
+ </SelectItem>
2417
+ ))}
2418
+ </SelectContent>
2419
+ </Select>
2420
+ </div>
2421
+ <div className="text-sm font-medium">
2422
+ {t.page(
2423
+ table.getState().pagination.pageIndex + 1,
2424
+ Math.max(table.getPageCount(), 1),
2425
+ )}
2426
+ </div>
2427
+ <div className="flex items-center gap-2">
2428
+ <Button
2429
+ variant="outline"
2430
+ className="hidden sm:flex"
2431
+ size="icon"
2432
+ onClick={() => table.setPageIndex(0)}
2433
+ disabled={!table.getCanPreviousPage()}
2434
+ >
2435
+ <span className="sr-only">{t.firstPage}</span>
2436
+ <ChevronsLeftIcon />
2437
+ </Button>
2438
+ <Button
2439
+ variant="outline"
2440
+ size="icon"
2441
+ onClick={() => table.previousPage()}
2442
+ disabled={!table.getCanPreviousPage()}
2443
+ >
2444
+ <span className="sr-only">{t.previousPage}</span>
2445
+ <ChevronLeftIcon />
2446
+ </Button>
2447
+ <Button
2448
+ variant="outline"
2449
+ size="icon"
2450
+ onClick={() => table.nextPage()}
2451
+ disabled={!table.getCanNextPage()}
2452
+ >
2453
+ <span className="sr-only">{t.nextPage}</span>
2454
+ <ChevronRightIcon />
2455
+ </Button>
2456
+ <Button
2457
+ variant="outline"
2458
+ className="hidden sm:flex"
2459
+ size="icon"
2460
+ onClick={() => table.setPageIndex(table.getPageCount() - 1)}
2461
+ disabled={!table.getCanNextPage()}
2462
+ >
2463
+ <span className="sr-only">{t.lastPage}</span>
2464
+ <ChevronsRightIcon />
2465
+ </Button>
2466
+ </div>
2467
+ </div>
2468
+ </div>
2469
+ );
2470
+ }
2471
+
2472
+ export function DataTableSkeleton() {
2473
+ return (
2474
+ <div className="flex w-full flex-col gap-4" aria-hidden="true">
2475
+ <div className="flex items-center gap-2">
2476
+ <Skeleton className="h-9 flex-1 rounded-3xl" />
2477
+ <Skeleton className="size-8 rounded-full" />
2478
+ </div>
2479
+ <div className="bg-card overflow-hidden rounded-2xl border">
2480
+ <Skeleton className="h-10 rounded-none" />
2481
+ <div className="flex flex-col">
2482
+ {Array.from({ length: 8 }).map((_, index) => (
2483
+ <Skeleton
2484
+ key={index}
2485
+ className="bg-muted/40 h-14 rounded-none border-t"
2486
+ />
2487
+ ))}
2488
+ </div>
2489
+ </div>
2490
+ </div>
2491
+ );
2492
+ }