Repository navigation
Expand file tree
/
Copy pathdata-table.tsx
More file actions
5722 lines (5492 loc) · 286 KB
/
Copy pathdata-table.tsx
File metadata and controls
5722 lines (5492 loc) · 286 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 { hasDeclaredVisibilityGate } from '../action/visibility-gate';
import { DisabledReasonMenuLabel, menuItemReasonAria, useDisabledReason } from '../action/disabled-reason';
import { useGridFieldAuthoring } from '../../context/gridFieldAuthoring';
import { useGridCellSelection } from '../../context/gridCellSelection';
import { useGridHeaderMenu } from '../../context/gridHeaderMenu';
import { caretToEnd, defaultTyping, defaultValueFromText, firstEditorControl, isCellWidgetTarget, isCommandLetter, isImeKey, isPrintableKey } from './dataTableCellSelection';
import { useHorizontalOverflow, HOVER_SCROLLBAR_CLASSES } from '../../custom/use-horizontal-overflow';
import { ActiveListRow, listRecordIdOf } from '../../custom/record-list-face';
import { describeIgnoredBind, describeNonArrayData } from './dataTableBindDiagnostic';
import { CellOverlay } from './dataTableCellOverlay';
import { CELL_OVERLAY_HOST_CLASS, isCellContentTruncated, type CellOverlaySize } from './dataTableCellOverlayDom';
import { ComponentRegistry, compareSortValues, csvBlob, evalRowPredicate, formatDate, hasDeclaredPredicate, isActionSwitchedOff, formatDateTime, fromDateTimeInputValue, getSortValue, isEmptyValue, isImpossibleStoredDay, toDateInputValue, toDateTimeInputValue } from '@object-ui/core';
import type { DataTableSchema, TableColumn, TableSortItem, TableColumnType } from '@object-ui/types';
import type { SortDirection } from '@objectstack/spec/shared';
import { SchemaRenderer, toRenderableSchema, useCapabilityGate, useRowPredicate, usePredicateScope, extractFieldErrors, unmarkedRefusalLines } from '@object-ui/react';
import { createSafeTranslation, useDisplayLocale } from '@object-ui/i18n';
import {
Table,
TableHeader,
TableBody,
TableHead,
TableRow,
TableCell,
TableCaption
} from '../../ui/table';
import { Button } from '../../ui/button';
import { Popover, PopoverContent } from '../../ui/popover';
import { Anchor as PopoverAnchor } from '@radix-ui/react-popover';
import { Input } from '../../ui/input';
import { Checkbox } from '../../ui/checkbox';
import { TriStateCheckbox } from '../../custom/tri-state-checkbox';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '../../ui/select';
import {
ChevronUp,
ChevronDown,
ChevronsUpDown,
Search,
Download,
Edit,
Pencil,
Trash2,
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
GripVertical,
Save,
X,
Plus,
MoreHorizontal,
AlertCircle,
Check,
Loader2,
} from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '../../ui/dropdown-menu';
/**
* The inline date editors read and write through `@object-ui/core`'s native
* date adapters (`toDateInputValue` / `toDateTimeInputValue` /
* `fromDateTimeInputValue`), the one set `@object-ui/fields`' date widgets
* use. The table used to keep private copies of them, with no check for a
* stored day that does not exist: a `datetime` value written on 30 February
* showed as March 2nd and a minutes-only edit wrote that day back, and a
* `date` value on it blanked silently (objectui#10625). A `date` field stays a
* plain `yyyy-MM-dd` string; a `datetime` field round-trips through ISO.
*/
// Column types that should edit as a numeric `<Input type="number">`.
//
// `int` / `integer` / `float` / `double` USED to be members (`fc62bb490`).
// They were never declared by `TableColumn.type` — they arrived because
// column-inference producers forwarded an object schema's field type verbatim,
// which is also why this key had to be read through an `as any` below. Those
// producers now fold their inferred value onto the declared vocabulary at their
// emit seam (`normalizeTableColumnType`), so an undeclared spelling can no
// longer reach this set. Typed as `TableColumnType` so re-adding one is a tsc
// error rather than a silent re-opening of the undeclared dialect.
/**
* objectstack#35688 — how wide a built-in editor's layer starts (a host's
* injected editor sizes its own). Never narrower than the cell.
*/
function builtInEditorWidthClass(type: TableColumnType | undefined): string {
return type === 'date' || type === 'datetime' ? 'min-w-56' : 'min-w-40';
}
const NUMERIC_EDIT_TYPES = new Set<TableColumnType>(['number', 'currency', 'percent']);
/**
* The identity a pending edit is kept under (objectui#12310): the record's id
* (`row.id`, the id `getRowId` reads; a null one names no record), or, for a
* row that carries none, the row object itself. Never a position. A pending edit used to be keyed by its
* row's page-local index, so any re-read that put the page in a new order (a
* row save's refresh, the data-invalidation bus, a page change) drew a kept
* edit on whichever record now sat at that index, and Save All wrote it
* there.
*
* An id-less row has no identity that survives a re-read, so its edit follows
* the row OBJECT: it stays put through a client-side sort, filter or page
* change, and a re-read that hands over new objects leaves it pending against
* the object it was typed on, never against the row now in its place.
*/
type PendingRowKey = unknown;
function pendingRowKeyOf(row: unknown): PendingRowKey {
if (row !== null && typeof row === 'object' && 'id' in row && row.id != null) return row.id;
return row;
}
/**
* One row's staged edits, per column key, and the row they were last staged
* against. The row is read only when the rows the table holds no longer
* include that record (a re-read dropped it, or it sits on another server
* page): Save All then hands the edit over with the row it was typed on,
* never with the row at its old position.
*/
interface PendingRow {
row: any;
changes: Record<string, any>;
}
type PendingChanges = Map<PendingRowKey, PendingRow>;
/** The cell an inline editor is open on, and the row it was opened on. */
interface EditingCell {
rowKey: PendingRowKey;
columnKey: string;
row: any;
}
/** A decimal numeral, as a number `<input>` hands it back — never hex, `Infinity` or blank. */
const DECIMAL_NUMERAL = /^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$/;
/** A number and the decimal string that spells it (`5` and `'5.0'`) are one value. */
function isSameCellScalar(a: unknown, b: unknown): boolean {
if (Object.is(a, b)) return true;
if (typeof a === 'number' && typeof b === 'string') {
const s = b.trim();
return DECIMAL_NUMERAL.test(s) && Number(s) === a;
}
if (typeof b === 'number' && typeof a === 'string') return isSameCellScalar(b, a);
if (a !== null && b !== null && typeof a === 'object' && typeof b === 'object') {
try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; }
}
return false;
}
/**
* Whether a value an inline editor hands back is the value the row LOADED with
* (objectui#11816) — the one question that decides whether a cell is staged as
* an edit. Before this, every commit was staged, so clicking into a cell and
* out again showed "1 row modified · Save All (1)" for a row nobody changed.
*
* Each rule answers a round trip the editors measurably make:
*
* - **The emptiness floor** (`isEmptyValue`, `@object-ui/core`): `null`,
* `undefined`, `''` and `[]` are one blank here. `startEdit` seeds the
* editor with `''` for a cell that loaded `null`, so a text cell left as it
* was hands back `''`, and an emptied multi-select hands back `[]`.
* - **A number against its decimal string**: the built-in number editor stores
* the `<input>`'s string, so retyping `5` over a loaded `5` hands back `'5'`.
* - **A multi-value set in another order**: toggling an option off and on
* again appends it, so `['a', 'b']` comes back as `['b', 'a']`.
* - **Two objects that serialize alike** are the same value.
*
* ⚠️ The failure direction is asymmetric, as `isSameStoredValue` in
* `@object-ui/plugin-form` says of its own rule: "unchanged" about a changed
* pair drops the user's edit, "changed" about an equal pair costs one redundant
* write. So nothing else is equal — in particular a select's stored code is
* never compared with an option LABEL: the table holds no options, and the
* option widgets hand back `option.value`, the code the row stores.
*/
function isUnchangedCellValue(staged: unknown, loaded: unknown): boolean {
if (isEmptyValue(staged) && isEmptyValue(loaded)) return true;
if (Array.isArray(staged) && Array.isArray(loaded)) {
if (staged.length !== loaded.length) return false;
const unmatched = [...loaded];
return staged.every((item) => {
const at = unmatched.findIndex((other) => isSameCellScalar(item, other));
if (at < 0) return false;
unmatched.splice(at, 1);
return true;
});
}
return isSameCellScalar(staged, loaded);
}
/**
* `prev` with one cell's edit staged — or, when `value` is the loaded value,
* with that cell's entry REMOVED, and the row's with it once nothing else is
* staged on it (objectui#11816). That is what makes staging a value back to
* the loaded one un-mark the row. Returns `prev` itself when nothing changes,
* so a no-op commit schedules no state update.
*
* The edit is kept under the record's key, with `row` (the row it is staged
* against, whose own value for the column is the loaded one) as its snapshot
* (objectui#12310).
*
* `inFlight` is what a running save sent for this record (objectui#12322).
* While a save of the cell is in flight, the record will hold the value sent,
* or the loaded one if the save fails, so no commit there is called
* unchanged: it is staged, and the save's settle (`removeSentEdits`) decides
* what stays. Otherwise a cell re-edited back to its loaded value during its
* save would be dropped here, and the save would then write the old edit.
*/
function stageCellChange(
prev: PendingChanges,
rowKey: PendingRowKey,
row: any,
columnKey: string,
value: unknown,
inFlight?: Record<string, unknown>,
): PendingChanges {
const current = prev.get(rowKey);
const unchanged = !(inFlight && columnKey in inFlight) && isUnchangedCellValue(value, row?.[columnKey]);
if (unchanged && !(current && columnKey in current.changes)) return prev;
const next = new Map(prev);
const rowChanges = { ...(current?.changes || {}) };
if (unchanged) delete rowChanges[columnKey];
else rowChanges[columnKey] = value;
if (Object.keys(rowChanges).length > 0) next.set(rowKey, { row, changes: rowChanges });
else next.delete(rowKey);
return next;
}
/**
* The pending edits once a save of `sent` (record key -> the changes it
* handed over) has landed (objectui#12322). For each record sent, each column
* whose staged value is still the very value sent is removed, and the
* record's entry goes once nothing else is staged on it. Everything else
* stays: an edit staged on another record during the save, another column
* staged on the record being saved, a new value for a column being saved.
*
* It is applied as a `setPendingChanges` updater, to the edits as they stand
* when the save settles. Applied to the copy read when the save was pressed,
* it would drop every edit made during the round trip, with no signal.
*
* "Still the value sent" means the same value (`Object.is`), not
* `isUnchangedCellValue`'s equality. The question here is whether the cell was
* staged again since it was sent. A value staged again with an equal copy (a
* lookup picked again) stays pending, which costs at most one redundant
* write. An equality judged too loosely would drop an edit instead.
*
* Returns `prev` itself when nothing is removed.
*/
function removeSentEdits(
prev: PendingChanges,
sent: ReadonlyMap<PendingRowKey, Record<string, unknown>>,
): PendingChanges {
let next: PendingChanges | null = null;
for (const [rowKey, sentChanges] of sent) {
const current = prev.get(rowKey);
if (!current) continue;
const remaining = { ...current.changes };
let removed = false;
for (const columnKey of Object.keys(sentChanges)) {
if (columnKey in remaining && Object.is(remaining[columnKey], sentChanges[columnKey])) {
delete remaining[columnKey];
removed = true;
}
}
if (!removed) continue;
next ??= new Map(prev);
if (Object.keys(remaining).length > 0) next.set(rowKey, { row: current.row, changes: remaining });
else next.delete(rowKey);
}
return next ?? prev;
}
/**
* 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}}',
// objectui#12124 — the pager's four icon buttons' accessible names.
'table.firstPage': 'First page',
'table.previousPage': 'Previous page',
'table.nextPage': 'Next page',
'table.lastPage': 'Last page',
'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',
// A count family (objectui#11445): `fallbackT` reads the `_one` / `_other`
// row for a numeric `count`, as i18next reads the `en` pack.
'table.modified_one': '{{count}} row modified',
'table.modified_other': '{{count}} rows modified',
'table.saveFailed': 'Save failed',
'table.selected': '{{count}} selected',
// objectui#11690 — the selection checkboxes' accessible names.
'table.selectAllRows': 'Select all rows',
'table.selectRow': 'Select row',
// objectui#12145 — the row menu trigger's accessible name.
'table.rowActions': 'Row actions',
'table.edit': 'Edit',
'table.delete': 'Delete',
// #25916 — the hover open affordance and the inline-edit row buttons.
'table.openRecord': 'Open record',
'table.cancelChanges': 'Cancel changes',
'table.saveRow': 'Save row',
// objectstack#35684 — a selected cell that opens no editor, when its host
// gives no reason of its own.
'table.cellReadOnly': 'This cell can\'t be edited here.',
// objectstack#35685 — a list cell's own save state, and the way out of a
// rule the list cannot complete.
'table.cellSaving': 'Saving…',
'table.cellSaved': 'Saved',
'table.openRecordToFinish': 'Open the record to finish this change',
'common.actions': 'Actions',
// objectui#10625 — the inline date editors' notice for a stored value
// written on a day that does not exist. The SAME keys `DateField` /
// `DateTimeField` use, with the `en` pack's values, for provider-less
// rendering.
'fields.date.impossibleDay':
'The stored value "{{value}}" is not a real date. Pick a date to replace it.',
'fields.dateTime.impossibleDay':
'The stored value "{{value}}" is not a real date. Pick a date and time to replace it.',
};
/**
* 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`; the local copy
* this replaced wrapped the hook in try/catch (rules-of-hooks, objectui#2879).
* Only the COPY comes from here: the date cells below format with
* `useDisplayLocale()`, never with the `language` this hook also reports
* (objectui#10442).
*/
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 lines a refused save shows in the save bar: one per reason the refusals
* list (a `VALIDATION_FAILED` answer keeps one `fields[]` entry per failed
* rule), else each refusal's one message — distinct, in the order the rows
* were sent. Said whole, never cut to one line (objectstack-ai/objectstack#27520).
*/
function saveRefusalLines(errors: readonly unknown[]): string[] {
const lines: string[] = [];
for (const error of errors) {
const listed = unmarkedRefusalLines(error, () => false);
for (const line of listed && listed.length > 0 ? listed : [extractSaveErrorMessage(error)]) {
if (!lines.includes(line)) lines.push(line);
}
}
return lines;
}
/**
* The cells a refused row save names, field → reason, read from the refusal's
* own field entries (`extractFieldErrors`); `null` when it names none. A field
* the table draws no column for simply marks nothing: its reason is still in
* the save bar.
*/
function refusedCellsOf(error: unknown): Record<string, string> | null {
const entries = extractFieldErrors(error);
if (!entries) return null;
const cells: Record<string, string> = {};
for (const { field, message } of entries) {
if (!(field in cells)) cells[field] = message || extractSaveErrorMessage(error);
}
return cells;
}
/**
* 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];
/** The element type of `DataTableSchema.rowGroups` (objectui#12620). */
type RowGroup = NonNullable<DataTableSchema['rowGroups']>[number];
/**
* The per-row outcome `onBatchSave` may resolve with (objectui#12292), derived
* from the slot's declared return rather than restated here.
*/
type BatchSaveOutcome = Exclude<
Awaited<ReturnType<NonNullable<DataTableSchema['onBatchSave']>>>,
void
>;
/**
* The authoring shape of the built-in row Edit/Delete predicates — derived from
* `DataTableSchema`, never restated by hand (objectui#4354). Everything below
* reads what the production caller hands it (`schema.rowEditPredicates` /
* `rowDeletePredicates`), so a hand-written `{ visibleWhen?: unknown; … }` here
* would be a second definition of one authoring shape, free to drift from the
* type it is supposed to mirror without a single test going red.
*
* The union of the two twins is deliberate: every consumer below serves BOTH
* built-ins (`name: 'edit' | 'delete'`), so it may only read keys that BOTH
* schema keys declare — if either twin dropped one, the read stops compiling
* instead of silently reading `undefined`.
*/
type BuiltinRowPredicates = NonNullable<
DataTableSchema['rowEditPredicates'] | DataTableSchema['rowDeletePredicates']
>;
/**
* Evaluate a row-action visibility predicate the way the row menu's items do —
* on the canonical CEL engine, failing CLOSED with a diagnosable warning — but
* WITHOUT a hook.
*
* Hook-free matters because the row-level guard below asks this question for a
* VARIABLE number of custom actions inside a single `useMemo`; one
* `useRowPredicate` per action would tie the hook count to
* `schema.rowActionDefs.length`. Mirrors
* `useRowPredicate(pred, row, { fallback: false, warnOnError: true, label })`,
* boolean short-circuit included — a boolean handed to the engine faults
* ("AST-only evaluation not yet supported") and fails closed, which is how
* `visible: true` once hid a bulk button from everyone (objectui#3492; the same
* short-circuit is spelled out in plugin-grid's `bulkEligibility`).
*/
function evalRowActionVisibility(
pred: unknown,
row: any,
scope: Record<string, unknown>,
label: string,
fields?: unknown,
): boolean {
if (typeof pred === 'boolean') return pred;
// Not dead, and not the place that decides "was a gate declared?" — the two
// callers below answer that first, each by its own rule. `''` still arrives
// here from `isBuiltinRowActionVisible`, whose gate is `!= null` alone; a
// nothing-to-evaluate predicate that reached an evaluator fails CLOSED like
// any other unevaluable one.
if (pred == null || pred === '') return false;
return evalRowPredicate(pred as never, row ?? {}, {
fallback: false,
scope,
warnOnError: true,
label,
// Only plugin-grid's row menu passes the object's fields (see
// `isCustomRowActionVisible`). This file's own callers pass none, and
// `undefined` keeps the row payload verbatim, as before.
fields: fields as never,
});
}
/**
* Does the built-in Edit/Delete item render for THIS row? The single
* definition, read both by the item itself and by the row-level guard that
* decides whether the "⋮" trigger exists at all. The two disagreeing is
* objectui#3562: the guard counted handlers, the items were then filtered by
* these predicates, and a row with every item suppressed still got a trigger
* that opened an empty 128×10 box.
*
* `visibleWhen` counts as a declared gate by `!= null`, not by truthiness —
* `visibleWhen: false` hides the item rather than reading as "ungated".
*
* The parameter is consumption-shaped — visibility is all this decides, so
* `disabledWhen` is deliberately absent — but `Pick`ed from the authoring type
* rather than hand-written, so it is a SUBSET of that type by construction
* (objectui#4354).
*/
export function isBuiltinRowActionVisible(
predicates: Pick<BuiltinRowPredicates, 'visibleWhen'> | undefined,
name: 'edit' | 'delete',
row: any,
scope: Record<string, unknown>,
): boolean {
const pred = predicates?.visibleWhen;
if (pred == null) return true;
return evalRowActionVisibility(pred, row, scope, `builtin:${name}:visibleWhen`);
}
/**
* Does this schema-driven custom row action render for THIS row? Same
* single-definition rule as the built-ins above, and the ONE definition for
* every row menu: this file's (the related list's data table) and
* plugin-grid's `RowActionMenu` (its "⋮" items, its inline primary buttons and
* its "⋮" guard), which imports it from the `@object-ui/components` barrel
* rather than keeping a twin (objectui#11294).
*
* Whether a gate is DECLARED at all is asked with `hasDeclaredVisibilityGate`,
* the action family's one definition (objectui#3812): the related list's
* toolbar, `action:*`, `DeclaredActionsBar` and the rest ask it too, so an
* action cannot show in a list's header and be missing from its rows.
*
* - `visible: false` is a declared gate that excludes every row. Truthiness
* cannot answer the question: testing `!action.visible` read it as ungated
* and rendered the item for everyone (objectui#3758). The boolean then
* decides in {@link evalRowActionVisibility}, which short-circuits it instead
* of handing it to the engine.
* - A blank predicate is no gate, so the action shows: `''`, a whitespace-only
* string, and an envelope whose `source` is blank. The blank is still
* reported (ADR-0137 D4) through the family's one `[blank]` report, once per
* blank spelling rather than once per row. This test used to be
* `pred == null || pred === ''`, so a whitespace-only `visible` counted as
* declared, was evaluated, and failed closed: the action showed in a related
* list's toolbar and was missing from its rows (objectui#11294).
* - A value that is not a predicate at all (`0`, `{}`, an array, an
* `ast`-only envelope) IS a declared gate, one that cannot be evaluated
* (objectui#11358): the family's definition answers "declared", the row fold
* faults on it and fails closed, so the action is hidden and the fault is
* reported — as on every other member of the family.
*
* `fields` is the object's field definitions, for a caller that has them:
* plugin-grid passes them so a relation compares as its stored foreign key
* (see `evalRowPredicate`). This file's own callers pass none.
*/
export function isCustomRowActionVisible(
action: { name?: string; visible?: unknown } | undefined,
row: any,
scope: Record<string, unknown>,
fields?: unknown,
): boolean {
const pred = action?.visible;
if (!hasDeclaredVisibilityGate(pred)) return true;
return evalRowActionVisibility(pred, row, scope, action?.name ?? 'row-action', fields);
}
/** What the row overflow menu will actually render for ONE row. */
export interface DataTableRowMenuPlan {
/** The built-in Edit item renders for this row. */
edit: boolean;
/** The built-in Delete item renders for this row. */
remove: boolean;
/** Custom actions surviving their own `visible` predicate, in declared order. */
custom: RowActionDef[];
/** Items that will render. `0` means: render no trigger at all (#3562). */
count: number;
}
/**
* Resolve the row overflow menu for ONE row — which items survive their
* per-record predicates, and how many that leaves.
*
* Per ROW, not per table: `visibleWhen` / `visible` are per-record predicates,
* so two rows of the same table legitimately differ (one keeps Edit, the next
* has nothing left). A table-level guard cannot express that, which is why the
* trigger decision lives here and is recomputed for every row.
*
* Only visibility is decided here — a `disabled` item still renders (greyed
* out) and still counts, exactly as before. That counting is pinned where it
* can be OBSERVED, on the rendered menu, by
* `data-table-row-menu-empty-guard.test.tsx`'s "keeps the trigger for a row
* whose only item renders merely DISABLED".
*
* The predicate parameters are consumption-shaped — this function reads
* `visibleWhen` and nothing else, and the signature keeps saying so — but each
* is `Pick`ed from the authoring key its production caller passes, rather than
* hand-restated (objectui#4354). Same subset, minus the drift: a rename in
* `@object-ui/types` fails here at compile time instead of leaving a stale
* hand-copy that still type-checks against nothing.
*/
export function planDataTableRowMenu(input: {
onRowEdit?: unknown;
onRowDelete?: unknown;
editPredicates?: Pick<NonNullable<DataTableSchema['rowEditPredicates']>, 'visibleWhen'>;
deletePredicates?: Pick<NonNullable<DataTableSchema['rowDeletePredicates']>, 'visibleWhen'>;
customActions: readonly RowActionDef[];
row: any;
scope: Record<string, unknown>;
}): DataTableRowMenuPlan {
const { row, scope } = input;
const edit = !!input.onRowEdit && isBuiltinRowActionVisible(input.editPredicates, 'edit', row, scope);
const remove = !!input.onRowDelete && isBuiltinRowActionVisible(input.deletePredicates, 'delete', row, scope);
const custom = input.customActions.filter((action) => isCustomRowActionVisible(action, row, scope));
return {
edit,
remove,
custom,
count: (edit ? 1 : 0) + (remove ? 1 : 0) + custom.length,
};
}
/**
* 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 }) => {
// Evaluate on the canonical CEL engine (issue #1584): row bound as
// `record.*`, ambient `features`/`current_user` scope merged. Both keys fail
// CLOSED, each in its own direction: a `visible` that faults hides the item,
// a `disabled` that faults DISABLES it, and both warn.
//
// `disabled` used to fail soft (not disabled), so `disabled:
// !current_user.can(…)` left the item pressable until the permissions
// payload arrived (objectui#11242 — Rider 1 of objectui#4421). Same
// mechanism as `page:header` (objectui#11212) and plugin-grid's
// `RowActionMenuItem`: the key's fail direction is the evaluator's
// `fallback`, per key rather than a `can()` special case, and since that
// fallback also answers an ABSENT predicate the verdict only counts where a
// gate is DECLARED. The built-in `disabledWhen` below stays fail-soft.
//
// `visible` goes through the shared `isCustomRowActionVisible` — the SAME
// function the row-level guard uses to decide whether this row gets a "⋮"
// trigger at all, so an item can never be suppressed behind a trigger that
// survived (objectui#3562).
const scope = usePredicateScope();
const isVisible = useMemo(() => isCustomRowActionVisible(action, row, scope), [action, row, scope]);
const disabledVerdict = useRowPredicate(action.disabled, row, { fallback: true, warnOnError: true, label: `${action.name}:disabled` });
const isDisabled = hasDeclaredPredicate(action.disabled) && disabledVerdict;
// The reason the record header gives for the same verdict: the declared
// `disabledReason`, else the generic sentence, as the item's second line and
// its accessible description. Only the declared `disabled` earns it.
const disabledReason = useDisabledReason(isDisabled, action.disabledReason);
if (!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}`}
{...menuItemReasonAria(disabledReason)}
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" />}
{/* An item with no reason keeps its bare label, as before. */}
{disabledReason
? <DisabledReasonMenuLabel reason={disabledReason}>{action.label || action.name}</DisabledReasonMenuLabel>
: 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';
/**
* The whole authoring pair, because this component reads both keys — derived
* from `DataTableSchema` rather than hand-copied (objectui#4354).
*/
predicates?: BuiltinRowPredicates;
row: any;
icon: React.ReactNode;
label: string;
className?: string;
onSelect: (row: any) => void;
}> = ({ name, predicates, row, icon, label, className, onSelect }) => {
// `visibleWhen` is read through the shared `isBuiltinRowActionVisible`, the
// same function the row-level guard counts with — see objectui#3562.
const scope = usePredicateScope();
const isVisible = useMemo(
() => isBuiltinRowActionVisible(predicates, name, row, scope),
[predicates, name, row, scope],
);
const isDisabled = useRowPredicate(predicates?.disabledWhen, row, {
fallback: false,
warnOnError: true,
label: `builtin:${name}:disabledWhen`,
});
const disabled = predicates?.disabledWhen != null && isDisabled;
// The reason the record page gives for the same verdict (objectstack#35135,
// objectstack#35293): `userActions` declares no reason key, so the declared
// `disabledWhen` holding earns the generic `actions.notAvailableForRecord`
// sentence, as the item's second line and its accessible description — the
// shape `DataTableRowActionItem` above gives a custom action. Called ahead of
// the early return, with the other hooks.
const disabledReason = useDisabledReason(disabled);
if (!isVisible) return null;
return (
<DropdownMenuItem
disabled={disabled}
onClick={() => { if (!disabled) onSelect(row); }}
data-testid={`row-action-builtin-${name}`}
{...menuItemReasonAria(disabledReason)}
className={className}
>
{icon}
{/* An item with no reason keeps its bare label, as before. */}
{disabledReason
? <DisabledReasonMenuLabel reason={disabledReason}>{label}</DisabledReasonMenuLabel>
: label}
</DropdownMenuItem>
);
};
/**
* The row "⋮" menu's custom actions: `rowActionDefs`, capability-gated and
* switch-off-filtered, and only when there is a handler to dispatch them to.
* One definition, read by the menu's hook below and by the row context menu's
* open decision (objectstack#28434), so the two cannot disagree on a row.
*/
function gatedDataTableRowActions(
schema: Pick<DataTableSchema, 'rowActionDefs' | 'onRowActionDef'>,
mayInvoke: ReturnType<typeof useCapabilityGate>,
): RowActionDef[] {
return Array.isArray(schema.rowActionDefs) && schema.onRowActionDef
? schema.rowActionDefs.filter((d) => mayInvoke(d.requiredPermissions) && !isActionSwitchedOff(d))
: [];
}
/**
* THE resolver of ONE row's "⋮" menu, read by {@link DataTableRowActionsMenu}
* and by the row context menu this table opens when no host draws its own
* (objectstack#28434): same gate, same predicates, same order.
*/
function useDataTableRowMenuPlan(schema: DataTableSchema, row: any): DataTableRowMenuPlan {
const scope = usePredicateScope();
/**
* [ADR-0066 D4 / objectui#9623] The capability gate, applied ONCE to the
* whole declared set so `plan.count` (the "⋮" trigger) and the items it
* renders agree — the objectui#3562 invariant, and verbatim the posture
* `plugin-grid`'s `RowActionMenu` already takes for the standalone grid.
*
* This surface filters its own action list instead of routing through
* `ActionEngine.getActionsForLocation`, so the engine's gate never reached
* it. That left `requiredPermissions` INERT on every `list_item` action a
* data-table renders — the record page's related-list panel above all, which
* feeds a child object's `list_item` actions in as `rowActionDefs`
* (`RelatedRecordActionsBridge`). The record surface one level up gates the
* same declaration correctly, off the SAME `<ActionProvider>` this hook
* reads: the capability was on the page all along, this renderer just never
* asked (objectui#9623, cloud#2224 — a plain member was offered Set as
* Primary and read a 403 toast on click).
*
* A UI MIRROR of a decision the server still enforces, nothing more: unknown
* capabilities fail OPEN (see `useCapabilityGate`), an EMPTY held set gates
* normally, and the server remains the authority.
*
* Custom defs are only dispatchable when there is a handler to dispatch them
* to, so an unhandled `rowActionDefs` contributes no items (unchanged).
*/
const mayInvoke = useCapabilityGate();
const customActions = useMemo(
() => gatedDataTableRowActions(schema, mayInvoke),
[schema.rowActionDefs, schema.onRowActionDef, mayInvoke],
);
return useMemo(
() =>
planDataTableRowMenu({
onRowEdit: schema.onRowEdit,
onRowDelete: schema.onRowDelete,
editPredicates: schema.rowEditPredicates,
deletePredicates: schema.rowDeletePredicates,
customActions,
row,
scope,
}),
[
schema.onRowEdit,
schema.onRowDelete,
schema.rowEditPredicates,
schema.rowDeletePredicates,
customActions,
row,
scope,
],
);
}
/**
* The row overflow ("⋮") menu for ONE row — trigger included, or nothing at all.
*
* A component per row rather than inline JSX in the row loop, because deciding
* whether the trigger exists means evaluating THIS row's predicates, and that
* needs a hook scope of its own (the row loop's arity is the page's row count).
*
* objectui#3562: the old guard asked whether HANDLERS were supplied
* (`onRowEdit` / `onRowDelete` / `rowActionDefs`) while the items were filtered
* a second time by their per-record predicates. Handlers present + every item
* suppressed = a trigger that opens an empty box (measured at 128×10 with zero
* `[role=menu]` children). The guard now counts the items that will actually
* render, so the two can't disagree.
*
* The actions `<TableCell>` around this is NOT conditional: a row with no
* surviving actions renders an empty cell, keeping every row aligned with the
* `Actions` header — the same shape a table with no handlers at all has always
* produced.
*/
const DataTableRowActionsMenu: React.FC<{
schema: DataTableSchema;
row: any;
t: (key: string) => string;
}> = ({ schema, row, t }) => {
const plan = useDataTableRowMenuPlan(schema, row);
// Nothing to show → no trigger. An affordance that opens empty reads as a
// broken page, which is the whole of #3562.
if (plan.count === 0) return null;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
// Drawn on every row at rest, on every pointer type, in the muted
// tone (objectstack#28923): an `Actions` header over a column of cells
// that look empty until the pointer reaches a row reads as "no
// actions". Full strength on row hover, on focus-within, on a
// selected row, on its own keyboard focus, while its menu is open and
// on a coarse pointer, where no hover will ever lift it. The tone is a
// text colour, never an opacity. `RowActionMenu`
// (`@object-ui/plugin-grid`, objectstack#28871) carries the same set.
className="h-8 w-8 text-muted-foreground transition-colors group-hover/row:text-foreground group-focus-within/row:text-foreground group-data-[state=selected]/row:text-foreground data-[state=open]:text-foreground focus-visible:text-foreground pointer-coarse:text-foreground"
onClick={(e) => e.stopPropagation()}
aria-label={t('table.rowActions')}
data-testid="data-table-row-actions"
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
<DataTableRowMenuItems schema={schema} row={row} t={t} plan={plan} />
</DropdownMenuContent>
</DropdownMenu>
);
};
/**
* The items of ONE row's "⋮" plan — Edit, the surviving custom actions,
* Delete — for whichever menu content hosts them: {@link DataTableRowActionsMenu}
* and the row context menu (objectstack#28434) render this one list.
*/
const DataTableRowMenuItems: React.FC<{
schema: DataTableSchema;
row: any;
t: (key: string) => string;
plan: DataTableRowMenuPlan;
}> = ({ schema, row, t, plan }) => (
<>
{plan.edit && (
<DataTableBuiltinRowActionItem
name="edit"
predicates={schema.rowEditPredicates}
row={row}
icon={<Edit className="mr-2 h-4 w-4" />}
label={t('table.edit')}
onSelect={(r) => schema.onRowEdit?.(r)}
/>
)}
{/* Child-object custom actions (e.g. a related list surfacing the
child's `list_item` actions). Dispatched with the clicked row.
Separators are placed off the SURVIVING groups, so a suppressed
group can no longer leave a stray rule behind. */}
{plan.custom.length > 0 && plan.edit && <DropdownMenuSeparator />}
{plan.custom.map((action) => (
<DataTableRowActionItem
key={action.name}
action={action}
row={row}
onActionDef={schema.onRowActionDef}
/>
))}
{plan.remove && (plan.edit || plan.custom.length > 0) && <DropdownMenuSeparator />}
{plan.remove && (
<DataTableBuiltinRowActionItem
name="delete"
predicates={schema.rowDeletePredicates}
row={row}
icon={<Trash2 className="mr-2 h-4 w-4" />}
label={t('table.delete')}
className="text-destructive focus:text-destructive"
onSelect={(r) => schema.onRowDelete?.(r)}
/>
)}
</>
);
/**
* The row context menu this table draws for ITSELF, when no host draws one
* through `renderRowContextMenu` (objectstack#28434) — the related-list
* tables, whose rows have this table's own "⋮" menu: Open (what a click on the
* row does), then exactly that row's "⋮" items, from the same resolver.
*/
const DataTableRowContextMenuItems: React.FC<{
schema: DataTableSchema;
row: any;
t: (key: string) => string;
}> = ({ schema, row, t }) => {
const plan = useDataTableRowMenuPlan(schema, row);
return (
<>
{schema.onRowClick && (
<DropdownMenuItem onClick={() => schema.onRowClick?.(row)} data-testid="row-context-open">
<ChevronRight className="mr-2 h-4 w-4" />
{t('table.open')}
</DropdownMenuItem>
)}
{schema.onRowClick && plan.count > 0 && <DropdownMenuSeparator />}
<DataTableRowMenuItems schema={schema} row={row} t={t} plan={plan} />
</>
);
};
/**
* The selection modes this table implements — the renderer half of the spec's
* `SelectionConfigSchema.type` vocabulary (`ui/view.zod.ts`). Kept as an
* explicit export so a parity test can fail the moment either side moves
* (#2941; template: plugin-grid `summary-spec-parity.test.ts`).
*/
export const SUPPORTED_SELECTION_MODES: ReadonlySet<string> = new Set(['none', 'single', 'multiple']);
type SelectionMode = 'none' | 'single' | 'multiple';
/**
* Resolve the `selectable` prop — `boolean | 'single' | 'multiple'` (plus