-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdata-table.tsx
More file actions
2086 lines (1965 loc) · 94.4 KB
/
Copy pathdata-table.tsx
File metadata and controls
2086 lines (1965 loc) · 94.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Enterprise-level DataTable Component (Airtable-like)
import React, { useState, useMemo, useRef, useEffect, useLayoutEffect } from 'react';
import { cn } from '../../lib/utils';
import { resolveIcon } from '../action/resolve-icon';
import { useGridFieldAuthoring } from '../../context/gridFieldAuthoring';
import { ComponentRegistry } from '@object-ui/core';
import type { DataTableSchema } from '@object-ui/types';
import { useRowPredicate } from '@object-ui/react';
import { createSafeTranslation } from '@object-ui/i18n';
import {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption
} from '../../ui/table';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Checkbox } from '../../ui/checkbox';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '../../ui/select';
import {
ChevronUp,
ChevronDown,
ChevronsUpDown,
Search,
Download,
Edit,
Trash2,
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
GripVertical,
Save,
X,
Plus,
Expand,
MoreHorizontal,
AlertCircle,
} from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '../../ui/dropdown-menu';
type SortDirection = 'asc' | 'desc' | null;
/**
* Inline-edit helpers: convert a stored cell value to the string a native
* `<input type="date">` / `<input type="datetime-local">` expects, and back.
*
* Native date inputs require `yyyy-MM-dd`; datetime-local requires
* `yyyy-MM-ddTHH:mm`. We pad to the LOCAL wall-clock so the picker shows the
* same day the user sees, then convert back on change. A `date` field stays a
* plain `yyyy-MM-dd` string; a `datetime` field round-trips through an ISO
* string (matching how display/format code already treats ISO datetimes).
*/
function pad2(n: number): string {
return String(n).padStart(2, '0');
}
function toDateInputValue(value: unknown): string {
if (value == null || value === '') return '';
// A bare yyyy-MM-dd (or its leading slice of an ISO string) is already in the
// exact shape the native control wants. Pass it through verbatim — parsing it
// through `new Date()` would interpret it as UTC midnight and can shift the
// displayed day by one in negative-offset timezones.
if (typeof value === 'string') {
const m = value.match(/^(\d{4}-\d{2}-\d{2})/);
if (m) return m[1];
}
const d = value instanceof Date ? value : new Date(String(value));
if (Number.isNaN(d.getTime())) return '';
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
}
function toDateTimeInputValue(value: unknown): string {
if (value == null || value === '') return '';
const d = value instanceof Date ? value : new Date(String(value));
if (Number.isNaN(d.getTime())) return '';
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
}
// Field types that should edit as a numeric `<Input type="number">`.
const NUMERIC_EDIT_TYPES = new Set(['number', 'currency', 'percent', 'int', 'integer', 'float', 'double']);
/**
* Human label for an object/array cell value (e.g. an expanded reference like
* `{ id, name: 'Dev Admin' }`) shown in the read-only inline editor so we never
* render "[object Object]". Mirrors @object-ui/fields' `coerceToSafeValue`
* (which @object-ui/components can't import — it would be a circular dep).
*/
function safeObjectLabel(value: unknown): string {
if (value == null) return '';
if (Array.isArray(value)) {
return value
.map((v) =>
v != null && typeof v === 'object'
? safeObjectLabel(v)
: String(v),
)
.filter(Boolean)
.join(', ');
}
if (typeof value === 'object') {
const o = value as Record<string, unknown>;
return String(o.name ?? o.label ?? o.externalId ?? o.id ?? o._id ?? '');
}
return String(value);
}
// Default English fallback translations for the data table
const TABLE_DEFAULT_TRANSLATIONS: Record<string, string> = {
'table.rowsPerPage': 'Rows per page',
'table.pageInfo': 'Page {{current}} of {{total}}',
'table.totalRecords': '{{count}} total',
'table.noResults': 'No results found',
'table.noResultsHint': 'Try adjusting your filters or search query.',
'table.sortAsc': 'Sort ascending',
'table.sortDesc': 'Sort descending',
'table.hideColumn': 'Hide column',
'table.cancelAll': 'Cancel All',
'table.saveAll': 'Save All ({{count}})',
'table.exportCSV': 'Export CSV',
'table.addRecord': 'Add record',
'table.open': 'Open',
'table.search': 'Search...',
'table.modified': '{{count}} row modified',
'table.saveFailed': 'Save failed',
'table.selected': '{{count}} selected',
'table.edit': 'Edit',
'table.delete': 'Delete',
'common.actions': 'Actions',
};
/**
* Safe wrapper for useObjectTranslation that falls back to English defaults
* when I18nProvider is not available (e.g., standalone usage).
*
* Delegates to `@object-ui/i18n`'s `createSafeTranslation` (which also
* surfaces `language` for the date/number formatting below); the local copy
* this replaced wrapped the hook in try/catch (rules-of-hooks, objectui#2879).
*/
const useTableTranslation = createSafeTranslation(TABLE_DEFAULT_TRANSLATIONS, 'table.rowsPerPage');
/**
* Pull the most useful human-readable message out of whatever the save path
* threw. The ObjectStack adapter decorates thrown errors with the parsed
* response body on `details` (e.g. a `{ message, error }` from a validation
* failure), so prefer that; fall back to `error.message`, then a raw string.
* Never returns empty — callers render it as the save-failure reason.
*/
function extractSaveErrorMessage(error: unknown): string {
if (error && typeof error === 'object') {
const e = error as { message?: unknown; details?: { message?: unknown; error?: unknown } };
const detail = e.details && (e.details.message ?? e.details.error);
if (typeof detail === 'string' && detail.trim()) return detail.trim();
if (typeof e.message === 'string' && e.message.trim()) return e.message.trim();
}
return typeof error === 'string' && error.trim() ? error.trim() : 'Unknown error';
}
/**
* The element type of `DataTableSchema.rowActionDefs`. Derived via indexed
* access rather than imported by name: `@object-ui/types` defines
* `DataTableRowAction` but doesn't re-export it from its public entry, so it's
* only reachable structurally through `DataTableSchema`.
*/
type RowActionDef = NonNullable<DataTableSchema['rowActionDefs']>[number];
/**
* One schema-driven custom row action in the data-table's inline row overflow
* menu. Extracted into its own component so the action's `visible` (and
* `disabled`) CEL predicate can be evaluated with a hook (`useCondition`)
* without violating the rules-of-hooks inside a `.map()`.
*
* Mirrors `RowActionMenuItem` on the ObjectGrid path so BOTH row-menu
* renderers honor `visible`/`disabled` identically. Previously this path
* (used by a detail page's related list) rendered every custom action
* unconditionally, so e.g. a member row's "Transfer Ownership"
* (`visible: "record.role != 'owner' && …"`) showed on the owner's own row.
*
* Bare field references (`role`) resolve against the row record and `record.`
* references (`record.role`) against the same, while `features`/`user` come
* from the ambient ExpressionProvider scope — so gating stays consistent with
* the grid's own row menu.
*
* Exported for unit tests — NOT part of the package's public API: the
* `@object-ui/components` barrel only side-effect-imports this module (to run
* its `ComponentRegistry.register`), so this named export is reachable solely
* via the deep module path the colocated test uses.
*/
export const DataTableRowActionItem: React.FC<{
action: RowActionDef;
row: any;
onActionDef?: (action: RowActionDef, row: any) => void | Promise<void>;
}> = ({ action, row, onActionDef }) => {
const visiblePred = action.visible;
// Evaluate on the canonical CEL engine (issue #1584): row bound bare + as
// `record.*`, ambient `features`/`user` scope merged. `visible` fails CLOSED
// (hidden + warn); `disabled` fails soft (not disabled).
const isVisible = useRowPredicate(visiblePred, row, { fallback: false, warnOnError: true, label: action.name });
const isDisabled = useRowPredicate(action.disabled, row, { fallback: false, warnOnError: true, label: `${action.name}:disabled` });
if (visiblePred && !isVisible) return null;
const ActionIcon = resolveIcon(action.icon);
return (
<DropdownMenuItem
disabled={isDisabled}
onClick={() => { if (!isDisabled) void onActionDef?.(action, row); }}
data-testid={`row-action-${action.name}`}
className={cn(
action.variant === 'danger' && 'text-destructive focus:text-destructive',
)}
>
{/* Dynamic icon resolution from Lucide, not component creation during render */}
{/* eslint-disable-next-line react-hooks/static-components */}
{ActionIcon && <ActionIcon className="mr-2 h-4 w-4" />}
{action.label || action.name}
</DropdownMenuItem>
);
};
/**
* A built-in Edit/Delete item in the data-table's row overflow menu, gated by
* the per-record CEL predicates from the object's `userActions.edit` /
* `delete` object form (objectui#2614) — `schema.rowEditPredicates` /
* `rowDeletePredicates`. Mirrors `BuiltinRowActionItem` on the ObjectGrid
* path so BOTH row-menu renderers honor the predicates identically (the
* related-list case is where the master-detail scenario from the issue
* actually renders). Same posture: `visibleWhen` fails CLOSED, `disabledWhen`
* fails soft. Evaluation only happens when the menu is open (Radix mounts
* content lazily), so declared predicates cost nothing at table render time.
*
* Exported for unit tests — NOT part of the package's public API (the barrel
* only side-effect-imports this module; see `DataTableRowActionItem`).
*/
export const DataTableBuiltinRowActionItem: React.FC<{
name: 'edit' | 'delete';
predicates?: { visibleWhen?: unknown; disabledWhen?: unknown };
row: any;
icon: React.ReactNode;
label: string;
className?: string;
onSelect: (row: any) => void;
}> = ({ name, predicates, row, icon, label, className, onSelect }) => {
const isVisible = useRowPredicate(predicates?.visibleWhen, row, {
fallback: false,
warnOnError: true,
label: `builtin:${name}:visibleWhen`,
});
const isDisabled = useRowPredicate(predicates?.disabledWhen, row, {
fallback: false,
warnOnError: true,
label: `builtin:${name}:disabledWhen`,
});
if (predicates?.visibleWhen != null && !isVisible) return null;
const disabled = predicates?.disabledWhen != null && isDisabled;
return (
<DropdownMenuItem
disabled={disabled}
onClick={() => { if (!disabled) onSelect(row); }}
data-testid={`row-action-builtin-${name}`}
className={className}
>
{icon}
{label}
</DropdownMenuItem>
);
};
/**
* Enterprise-level data table component with Airtable-like features.
*
* Provides comprehensive table functionality including:
* - Multi-column sorting (ascending/descending/none)
* - Real-time search across all columns
* - Pagination with configurable page sizes
* - Row selection with persistence across pages
* - CSV export of filtered/sorted data
* - Row action buttons (edit/delete)
*
* @example
* ```json
* {
* "type": "data-table",
* "pagination": true,
* "searchable": true,
* "selectable": true,
* "sortable": true,
* "exportable": true,
* "rowActions": true,
* "columns": [
* { "header": "ID", "accessorKey": "id", "width": "80px" },
* { "header": "Name", "accessorKey": "name" }
* ],
* "data": [
* { "id": 1, "name": "John Doe" }
* ]
* }
* ```
*
* @param {Object} props - Component props
* @param {DataTableSchema} props.schema - Table schema configuration
* @returns {JSX.Element} Rendered data table component
*/
const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
const {
caption,
columns: rawColumns = [],
data: rawData = [],
pagination = true,
pageSize: initialPageSize = 10,
pageSizeOptions,
manualPagination = false,
rowCount,
page: controlledPage,
onPageChange,
onPageSizeChange,
searchable = true,
selectable = false,
showSelectionCount = true,
selectionResetKey,
sortable = true,
exportable = false,
rowActions = false,
resizableColumns = true,
reorderableColumns = true,
editable = false,
singleClickEdit = false,
selectionStyle = 'always',
rowClassName,
rowStyle,
className,
cellClassName,
frozenColumns = 0,
showRowNumbers = false,
showAddRow = false,
borderless = false,
disableInnerScroll = false,
} = schema;
// Ambient design-surface affordance: when a host (Studio) provides it, render
// a trailing "+ add field" column header. `null` for every runtime table, so
// existing tables render unchanged.
const fieldAuthoring = useGridFieldAuthoring();
const addColumnEnabled = !!fieldAuthoring?.onAddColumn;
const editColumnEnabled = !!fieldAuthoring?.onEditColumn;
// The table already implements column drag-reorder; a design host enables it by
// providing onReorderFields (to persist the order to the object's field metadata).
const reorderEnabled = reorderableColumns || !!fieldAuthoring?.onReorderFields;
// i18n support for pagination labels
const { t, language } = useTableTranslation();
/**
* Format a cell value for display. ISO date / datetime strings are
* formatted using the current i18n locale so that calendar dates render
* naturally per language (e.g. zh-CN → 2024/12/15, en-US → 12/15/2024).
* Non-date values are returned untouched.
*/
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
const formatCellValue = React.useCallback((value: unknown): unknown => {
if (typeof value !== 'string' || value.length < 8) return value;
if (!ISO_DATE_RE.test(value)) return value;
const ts = Date.parse(value);
if (Number.isNaN(ts)) return value;
const hasTime = value.includes('T');
try {
const fmt = new Intl.DateTimeFormat(language, hasTime
? { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }
: { year: 'numeric', month: 'short', day: 'numeric' });
return fmt.format(new Date(ts));
} catch {
return value;
}
}, [language]);
// Ensure data is always an array – provider config objects or null/undefined
// must not reach array operations like .filter() / .some()
const data = Array.isArray(rawData) ? rawData : [];
// Normalize columns to support legacy keys (label/name) from existing JSONs
const initialColumns = useMemo(() => {
return rawColumns.map((col: any) => ({
...col,
header: col.header || col.label,
accessorKey: col.accessorKey || col.name
}));
}, [rawColumns]);
// Auto-size columns: estimate width from header and data content for columns without explicit widths
const autoSizedWidths = useMemo(() => {
const widths: Record<string, number> = {};
const cols = rawColumns.map((col: any) => ({
header: col.header || col.label,
accessorKey: col.accessorKey || col.name,
width: col.width,
fitContent: col.fitContent,
}));
for (const col of cols) {
if (col.width) continue; // Skip columns with explicit widths
// `fitContent` columns (e.g. the row-actions column) size to their own
// content via a `width:1%` + nowrap cell, not a char-count estimate —
// estimating them from an absent string value pins them to the 80px
// floor and clips inline buttons. Leave them out of the width map.
if (col.fitContent) continue;
const headerLen = (col.header || '').length;
let maxLen = headerLen;
// Sample up to 50 rows for content width estimation
const sampleRows = data.slice(0, 50);
for (const row of sampleRows) {
const val = row[col.accessorKey];
const len = val != null ? String(val).length : 0;
if (len > maxLen) maxLen = len;
}
// Estimate pixel width: ~8px per character + 48px padding, min 80, max 400
widths[col.accessorKey] = Math.min(400, Math.max(80, maxLen * 8 + 48));
}
return widths;
}, [rawColumns, data]);
// State management
const [searchQuery, setSearchQuery] = useState('');
const [sortColumn, setSortColumn] = useState<string | null>(null);
const [sortDirection, setSortDirection] = useState<SortDirection>(null);
const [selectedRowIds, setSelectedRowIds] = useState<Set<any>>(new Set());
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(initialPageSize);
const [columns, setColumns] = useState(initialColumns);
const [columnWidths, setColumnWidths] = useState<Record<string, number>>({});
// Sticky-left offsets for the leading pinned cells (checkbox, row number,
// frozen data columns), measured from the REAL rendered header-cell widths.
// The table's auto layout does not guarantee the utility columns their
// declared `w-10`: the checkbox column can collapse to its ~28px min-content
// while the row-number column stretches past 40px. Hardcoded 40px offsets
// then leave an uncovered strip between pinned cells where horizontally
// scrolled content shows through (titanwind-ehr#418), so pin each cell at
// the cumulative measured width of the cells before it instead.
const headerRowRef = useRef<HTMLTableRowElement | null>(null);
const [measuredStickyLefts, setMeasuredStickyLefts] = useState<number[] | null>(null);
const stickyLeadingCount = frozenColumns > 0
? (selectable ? 1 : 0) + (showRowNumbers ? 1 : 0) + Math.min(frozenColumns, columns.length)
: 0;
useLayoutEffect(() => {
const headerRow = headerRowRef.current;
if (stickyLeadingCount === 0 || !headerRow) {
setMeasuredStickyLefts(null);
return;
}
const measure = () => {
const cells = Array.from(headerRow.children).slice(0, stickyLeadingCount) as HTMLElement[];
let acc = 0;
const lefts = cells.map((cell) => {
const left = acc;
acc += cell.getBoundingClientRect().width;
return left;
});
setMeasuredStickyLefts((prev) =>
prev && prev.length === lefts.length && prev.every((v, i) => Math.abs(v - lefts[i]) < 0.5)
? prev
: lefts
);
};
measure();
if (typeof ResizeObserver === 'undefined') return;
// Header-cell widths ARE the column widths, and they change outside React
// (column resize drag, density toggle, content growth), so re-measure on
// any of the observed cells resizing.
const observer = new ResizeObserver(measure);
Array.from(headerRow.children)
.slice(0, stickyLeadingCount)
.forEach((cell) => observer.observe(cell));
return () => observer.disconnect();
}, [stickyLeadingCount, columns]);
const [draggedColumn, setDraggedColumn] = useState<number | null>(null);
const [dragOverColumn, setDragOverColumn] = useState<number | null>(null);
const [editingCell, setEditingCell] = useState<{ rowIndex: number; columnKey: string } | null>(null);
// Mirror of `editingCell` that is mutated synchronously, so the `startEdit`
// re-entry guard can't be defeated by a stale closure. A lookup/select option
// renders in a Portal; picking it fires the option's onChange (which stages
// the value) and — because React synthetic events still bubble through the
// component tree — the cell's onClick, re-invoking `startEdit` for the SAME
// cell within one event. Reading `editingCell` state there can observe a stale
// (pre-edit) value under batching/contention, so the guard misses and the
// just-picked value is reset from empty `pendingChanges`. The ref always
// reflects the latest edit target within the same tick, so re-entry is caught.
const editingCellRef = useRef<{ rowIndex: number; columnKey: string } | null>(null);
const [editValue, setEditValue] = useState<any>('');
// Track pending changes for multi-cell editing: rowIndex -> { columnKey -> newValue }
const [pendingChanges, setPendingChanges] = useState<Map<number, Record<string, any>>>(new Map());
const [isSaving, setIsSaving] = useState(false);
// Last save failure message (server validation text, etc.) shown in the
// toolbar; null when the last save attempt succeeded or nothing's been saved.
const [saveError, setSaveError] = useState<string | null>(null);
// Row indices whose last save attempt failed — tinted destructive so the
// author sees exactly which rows didn't persist (no silent "phantom save").
const [erroredRows, setErroredRows] = useState<Set<number>>(new Set());
// Column header context menu state
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; columnKey: string } | null>(null);
// Refs for column resizing
const resizingColumn = useRef<string | null>(null);
const startX = useRef<number>(0);
const startWidth = useRef<number>(0);
const editInputRef = useRef<HTMLInputElement>(null);
// When an edit ends via Enter (already saved) or Escape (cancelled), the
// input also blurs. This flag tells the blur handler not to save again so we
// don't double-commit (Enter) or resurrect a cancelled value (Escape).
const skipBlurSaveRef = useRef(false);
// DOM node of a host-injected widget editor (rendered via `renderCellEditor`),
// captured while it's mounted. The built-in `<input>` editors commit via their
// own onBlur, but the injected widgets (text, number, date, lookup, …) have no
// such handler — a document-level pointerdown listener (see below) uses this
// node to detect click-outside and commit them. Null ⇒ no injected editor is
// active (a built-in editor, or nothing, is showing).
const injectedEditorElRef = useRef<HTMLDivElement | null>(null);
// Snapshot of the active cell's pending value when editing began, so Escape /
// cancel can revert this session's changes. Injected widgets stage on every
// change (unlike built-ins, which only commit on blur/Enter), so without this
// an Escape would leave the half-typed value staged. `had` distinguishes "no
// pending change existed" from "the pending value was undefined".
const editRevertRef = useRef<{ had: boolean; value: any } | null>(null);
// Update columns when schema changes
useEffect(() => {
setColumns(initialColumns);
}, [initialColumns]);
// Clear the internal checkbox selection when the host bumps selectionResetKey.
// Row selection is otherwise table-internal state a host can't reach; this lets
// e.g. a grid reset the checkboxes after a bulk action. On mount the selection
// is already empty, so the initial run is a no-op.
useEffect(() => {
if (selectionResetKey === undefined) return;
setSelectedRowIds(new Set());
}, [selectionResetKey]);
// Filtering
const filteredData = useMemo(() => {
if (!searchQuery) return data;
return data.filter((row) =>
columns.some((col) => {
const value = row[col.accessorKey];
return value?.toString().toLowerCase().includes(searchQuery.toLowerCase());
})
);
}, [data, searchQuery, columns]);
// Sorting
const sortedData = useMemo(() => {
if (!sortColumn || !sortDirection) return filteredData;
return [...filteredData].sort((a, b) => {
const aValue = a[sortColumn];
const bValue = b[sortColumn];
if (aValue === bValue) return 0;
const comparison = aValue < bValue ? -1 : 1;
return sortDirection === 'asc' ? comparison : -comparison;
});
}, [filteredData, sortColumn, sortDirection]);
// Pagination. Under manual (server-side) pagination the parent controls the
// page and supplies the grand total via `rowCount`; `data` already IS the
// current page, so we never slice it locally. Otherwise we paginate the
// in-memory rows client-side (legacy behavior).
const effectivePage = manualPagination
? Math.max(1, controlledPage ?? 1)
: currentPage;
const totalPages = manualPagination
? Math.max(1, Math.ceil((rowCount ?? sortedData.length) / pageSize))
: Math.ceil(sortedData.length / pageSize);
const paginatedData = (pagination && !manualPagination)
? sortedData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
: sortedData;
// Route page / page-size changes to the parent under manual pagination,
// otherwise drive the internal state.
const goToPage = (p: number) => {
const clamped = Math.min(totalPages, Math.max(1, p));
if (manualPagination) onPageChange?.(clamped);
else setCurrentPage(clamped);
};
const changePageSize = (size: number) => {
setPageSize(size);
if (manualPagination) {
onPageSizeChange?.(size);
onPageChange?.(1);
} else {
setCurrentPage(1);
}
};
// Rows-per-page choices: caller-supplied options (e.g. view metadata's
// pagination.pageSizeOptions) or the built-in fallback. The active pageSize
// is always merged in and the list de-duplicated + sorted so the selector can
// display the current value even when it is not one of the configured steps.
const pageSizeChoices = React.useMemo(() => {
const base = pageSizeOptions && pageSizeOptions.length > 0
? pageSizeOptions
: [5, 10, 20, 50, 100];
return Array.from(new Set([...base, pageSize]))
.filter((n) => Number.isFinite(n) && n > 0)
.sort((a, b) => a - b);
}, [pageSizeOptions, pageSize]);
/**
* Generates a unique identifier for each row to maintain stable selection state
* across pagination and sorting operations.
*
* @param {any} row - The data row object
* @param {number} index - The row's index in the dataset
* @returns {string | number} Unique row identifier (uses 'id' field if available, falls back to index)
*/
const getRowId = (row: any, index: number) => {
// Try to use 'id' field, fall back to index
return row.id !== undefined ? row.id : `row-${index}`;
};
// Handlers
const handleSort = (columnKey: string) => {
if (!sortable) return;
if (sortColumn === columnKey) {
if (sortDirection === 'asc') {
setSortDirection('desc');
} else if (sortDirection === 'desc') {
setSortDirection(null);
setSortColumn(null);
}
} else {
setSortColumn(columnKey);
setSortDirection('asc');
}
};
// Column header context menu handler
const handleColumnContextMenu = (e: React.MouseEvent, columnKey: string) => {
e.preventDefault();
setContextMenu({ x: e.clientX, y: e.clientY, columnKey });
};
const hideColumn = (columnKey: string) => {
setColumns(prev => prev.filter(c => c.accessorKey !== columnKey));
setContextMenu(null);
};
// Close context menu on outside click
useEffect(() => {
if (!contextMenu) return;
const close = () => setContextMenu(null);
document.addEventListener('click', close);
return () => document.removeEventListener('click', close);
}, [contextMenu]);
const handleSelectAll = (checked: boolean) => {
const newSelected = new Set<any>();
if (checked) {
paginatedData.forEach((row, idx) => {
const globalIndex = (effectivePage - 1) * pageSize + idx;
const rowId = getRowId(row, globalIndex);
newSelected.add(rowId);
});
}
setSelectedRowIds(newSelected);
// Call callback if provided
if (schema.onSelectionChange) {
const selectedData = sortedData.filter((row, idx) => {
const rowId = getRowId(row, idx);
return newSelected.has(rowId);
});
schema.onSelectionChange(selectedData);
}
};
const handleSelectRow = (rowId: any, checked: boolean) => {
const newSelected = new Set(selectedRowIds);
if (checked) {
newSelected.add(rowId);
} else {
newSelected.delete(rowId);
}
setSelectedRowIds(newSelected);
// Call callback if provided
if (schema.onSelectionChange) {
const selectedData = sortedData.filter((row, idx) => {
const id = getRowId(row, idx);
return newSelected.has(id);
});
schema.onSelectionChange(selectedData);
}
};
const handleExport = () => {
const csvContent = [
columns.map(col => col.header).join(','),
...sortedData.map(row =>
columns.map(col => JSON.stringify(row[col.accessorKey] || '')).join(',')
)
].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'table-export.csv';
a.click();
window.URL.revokeObjectURL(url);
};
const getSortIcon = (columnKey: string) => {
if (sortColumn !== columnKey) {
return <ChevronsUpDown className="h-3 w-3 ml-0.5 opacity-0 group-hover:opacity-50 transition-opacity" />;
}
if (sortDirection === 'asc') {
return <ChevronUp className="h-3 w-3 ml-0.5 text-primary" />;
}
return <ChevronDown className="h-3 w-3 ml-0.5 text-primary" />;
};
// Column resizing handlers
const handleResizeStart = (e: React.MouseEvent, columnKey: string) => {
if (!resizableColumns) return;
e.preventDefault();
e.stopPropagation();
resizingColumn.current = columnKey;
startX.current = e.clientX;
const headerCell = (e.target as HTMLElement).closest('th');
if (headerCell) {
startWidth.current = headerCell.offsetWidth;
}
document.addEventListener('mousemove', handleResizeMove);
document.addEventListener('mouseup', handleResizeEnd);
};
const handleResizeMove = (e: MouseEvent) => {
if (!resizingColumn.current) return;
const diff = e.clientX - startX.current;
const newWidth = Math.max(50, startWidth.current + diff); // Min width 50px
setColumnWidths(prev => ({
...prev,
[resizingColumn.current!]: newWidth
}));
};
const handleResizeEnd = () => {
resizingColumn.current = null;
document.removeEventListener('mousemove', handleResizeMove);
document.removeEventListener('mouseup', handleResizeEnd);
};
// Column reordering handlers
const handleColumnDragStart = (e: React.DragEvent, index: number) => {
if (!reorderEnabled) return;
setDraggedColumn(index);
e.dataTransfer.effectAllowed = 'move';
};
const handleColumnDragOver = (e: React.DragEvent, index: number) => {
if (!reorderEnabled) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
setDragOverColumn(index);
};
const handleColumnDrop = (e: React.DragEvent, dropIndex: number) => {
if (!reorderEnabled || draggedColumn === null) return;
e.preventDefault();
if (draggedColumn === dropIndex) {
setDraggedColumn(null);
setDragOverColumn(null);
return;
}
const newColumns = [...columns];
const [removed] = newColumns.splice(draggedColumn, 1);
newColumns.splice(dropIndex, 0, removed);
setColumns(newColumns);
setDraggedColumn(null);
setDragOverColumn(null);
// Call callback if provided
if (schema.onColumnsReorder) {
schema.onColumnsReorder(newColumns);
}
// Design host: persist the new order to the object's field metadata.
fieldAuthoring?.onReorderFields?.(newColumns.map((c) => c.accessorKey));
};
const handleColumnDragEnd = () => {
setDraggedColumn(null);
setDragOverColumn(null);
};
// Cell editing handlers
const startEdit = (rowIndex: number, columnKey: string) => {
if (!editable) return;
// Already editing THIS cell — do nothing. Re-entering would reset `editValue`
// from `pendingChanges`, and when a widget-injected editor commits via an
// overlay (a lookup/select popover renders in a Portal, but React events
// still bubble through the component tree to this cell's onClick), that reset
// reads a stale `pendingChanges` — before the just-staged value has flushed —
// and clobbers the freshly picked value. Guard on the synchronous ref (not
// the `editingCell` state, which can read stale under batching/contention —
// the intermittent CI failure #2150) so the re-entrant call is always caught.
const active = editingCellRef.current;
if (active?.rowIndex === rowIndex && active?.columnKey === columnKey) return;
const column = columns.find(col => col.accessorKey === columnKey);
if (column?.editable === false) return;
editingCellRef.current = { rowIndex, columnKey };
setEditingCell({ rowIndex, columnKey });
// Check if there's a pending change for this cell, otherwise use current data value
const rowChanges = pendingChanges.get(rowIndex);
const currentValue = paginatedData[rowIndex][columnKey];
const valueToEdit = rowChanges?.[columnKey] ?? currentValue ?? '';
setEditValue(valueToEdit);
// Snapshot the cell's pending state so Escape/cancel can revert an injected
// widget edit (which stages on every change) back to exactly what it was.
editRevertRef.current = rowChanges && columnKey in rowChanges
? { had: true, value: rowChanges[columnKey] }
: { had: false, value: undefined };
};
const saveEdit = (force: boolean = false, explicitValue?: any) => {
if (!editingCell) return;
// Don't save if we're in cancelled state (unless forced)
if (!force && editingCell === null) return;
const { rowIndex, columnKey } = editingCell;
const globalIndex = (effectivePage - 1) * pageSize + rowIndex;
// Under manual pagination `sortedData` IS the current page, so address it
// page-locally; otherwise it's the full in-memory set indexed absolutely.
const row = sortedData[manualPagination ? rowIndex : globalIndex];
// Discrete editors (select / checkbox) commit the chosen value synchronously
// via `explicitValue` — their `setEditValue` hasn't flushed to state yet.
const valueToStage = explicitValue !== undefined ? explicitValue : editValue;
// Update pending changes
const newPendingChanges = new Map(pendingChanges);
const rowChanges = newPendingChanges.get(rowIndex) || {};
rowChanges[columnKey] = valueToStage;
newPendingChanges.set(rowIndex, rowChanges);
setPendingChanges(newPendingChanges);
// Call the legacy onCellChange callback if provided
if (schema.onCellChange) {
schema.onCellChange(globalIndex, columnKey, valueToStage, row);
}
editRevertRef.current = null;
editingCellRef.current = null;
setEditingCell(null);
setEditValue('');
};
// Latest-ref to `saveEdit` so the document-level click-outside listener (whose
// closure is captured once per edit session) always commits with the CURRENT
// editValue rather than a stale one. Updated in an effect (after every render)
// so it's current well before any user pointer event fires.
const saveEditRef = useRef(saveEdit);
useEffect(() => {
saveEditRef.current = saveEdit;
});
// Exit edit mode. When `revert` is true, roll the active cell's pending value
// back to the snapshot taken when editing began (see `editRevertRef`) — this
// is what makes Escape/cancel discard an injected widget's staged changes. For
// built-in editors (which don't stage until commit) the snapshot equals the
// live pending value, so the revert is a no-op.
const exitEdit = (revert: boolean) => {
const active = editingCellRef.current;
const snap = editRevertRef.current;
editRevertRef.current = null;
if (revert && active && snap) {
const { rowIndex, columnKey } = active;
setPendingChanges((prev) => {
const cur = prev.get(rowIndex);
const staged = !!cur && columnKey in cur;
if (!staged && !snap.had) return prev; // nothing changed for this cell
const next = new Map(prev);
const rc = { ...(cur || {}) };
if (snap.had) rc[columnKey] = snap.value;
else delete rc[columnKey];
if (Object.keys(rc).length > 0) next.set(rowIndex, rc);
else next.delete(rowIndex);
return next;
});
}
editingCellRef.current = null;
setEditingCell(null);
setEditValue('');
};
const cancelEdit = () => {
// A built-in <input>'s ensuing blur must not re-save the value we're
// discarding; injected editors have no such blur, so they call `exitEdit`
// directly (setting this flag there would leak to the next built-in blur).
skipBlurSaveRef.current = true;
exitEdit(true);
};
// Stage an in-flight edit into pendingChanges WITHOUT closing the editor —
// used by injected widget editors (multi-value pickers, free text) that
// commit when the user moves on rather than on each keystroke/toggle. Mirrors
// what saveEdit stages, minus the close.
const stageEdit = (value: any) => {
if (!editingCell) return;
const { rowIndex, columnKey } = editingCell;
setEditValue(value);
setPendingChanges((prev) => {
const next = new Map(prev);
const rowChanges = { ...(next.get(rowIndex) || {}) };
rowChanges[columnKey] = value;
next.set(rowIndex, rowChanges);
return next;
});
};
// Commit the in-flight edit when the input loses focus (e.g. the user clicks
// another cell). Without this, switching cells discards the typed value.
const handleEditBlur = () => {
if (skipBlurSaveRef.current) {
skipBlurSaveRef.current = false;
return;
}
saveEdit(true);
};
const saveRow = async (rowIndex: number) => {
const globalIndex = (effectivePage - 1) * pageSize + rowIndex;
const row = sortedData[manualPagination ? rowIndex : globalIndex];
const rowChanges = pendingChanges.get(rowIndex);
if (!rowChanges || Object.keys(rowChanges).length === 0) return;
setIsSaving(true);
try {
if (schema.onRowSave) {
await schema.onRowSave(globalIndex, rowChanges, row);
}
// Clear pending changes for this row
const newPendingChanges = new Map(pendingChanges);
newPendingChanges.delete(rowIndex);
setPendingChanges(newPendingChanges);
// A staged editor (e.g. a lookup picker, which keeps its widget open on
// pick rather than committing) must exit edit mode once its value is
// persisted — otherwise the saved cell stays stuck showing the editor.
if (editingCell?.rowIndex === rowIndex) {
editingCellRef.current = null;
setEditingCell(null);
setEditValue('');
}
// Saved — drop any prior error for this row, and clear the banner once
// no errored rows remain.
setErroredRows((prev) => {
if (!prev.has(rowIndex)) return prev;
const next = new Set(prev);
next.delete(rowIndex);
if (next.size === 0) setSaveError(null);
return next;