Repository navigation
Expand file tree
/
Copy pathObjectGrid.tsx
More file actions
7689 lines (7402 loc) · 417 KB
/
Copy pathObjectGrid.tsx
File metadata and controls
7689 lines (7402 loc) · 417 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.
*/
/**
* ObjectGrid Component
*
* A specialized grid component built on top of data-table.
* Auto-generates columns from ObjectQL schema with type-aware rendering.
* Implements the grid view type from @objectstack/spec view.zod ListView schema.
*
* Features:
* - Traditional table/grid with CRUD operations
* - Search, filters, pagination
* - Column resizing, sorting
* - Row selection
* - Inline editing support
*/
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import type { ObjectGridSchema, DataSource, DependsOnInput, ListColumn, TableColumn, ViewData, TableSortItem, DataTableSchema, ListViewExportFormat, RecordNavigateAction } from '@object-ui/types';
import { isSystemManagedField, normalizeTableColumnType } from '@object-ui/types';
import type { I18nLabel } from '@objectstack/spec/ui';
import { parseFilterAST, resolveFieldScale, type FilterCondition } from '@objectstack/spec/data';
import { SchemaRenderer, useDataScope, useNavigationOverlay, useAction, useSafeFieldLabel, usePredicateScope, useCapabilityGate, useRelatedRecordActions, RelatedRecordActionsProvider, useDataInvalidation, notifyDataChanged, useFilterScope, useMetadata, isSameAuthoredFilter } from '@object-ui/react';
import { createSafeTranslation } from '@object-ui/i18n';
// objectui#8920 — the grid reaches a cell renderer through THIS module and
// nowhere else. `getCellRenderer` / `resolveCellRendererType` are deliberately
// NOT imported here: six sites spelling the resolve three different ways is
// what dropped a `format`-hinted column's renderer, and one shared owner is
// what stops a seventh site picking a convention of its own.
import { resolveGridCellRendering, gridCellRendererForFixedKey, linkCellRenderer, BADGE_PREFIX_RENDERER_KEY } from './cellRendererResolution';
import { isMaskedGridColumn, isWithheldGridColumn } from './maskedColumn';
import { formatCurrency, formatCompactCurrency, formatDate, formatDateTime, formatRelativeDate, formatPercent, percentCellScale, humanizeLabel, getBadgeColorClasses, getBadgeHexAppearance, FieldEditWidget, hasFieldEditWidget, DISCRETE_EDIT_TYPES, coerceToSafeValue, MaskedCellRenderer, withKnownObjects, RICH_TEXT_FIELD_TYPES, resolveRecordPointer } from '@object-ui/fields';
import { RecordPointerCell, type RecordPointerSource } from './RecordPointerCell';
import { useLocalization, useDisplayLocale, resolveFieldCurrency, pickLocalized } from '@object-ui/i18n';
// Two resolvers, two vocabularies — the repo spells the distinction into the
// NAMES (objectui#4167). `resolveInlineI18nLabel` is the spec's own
// `resolveI18nLabel`: it resolves the INLINE per-locale map
// (`{ en: …, 'fr-FR': … }`) that `I18nLabel` carries. It does NOT accept
// objectui's keyed `{ key, defaultValue, params }` ref — that vocabulary lives
// on the FLAT `schema.ariaLabel` and is resolved by `SchemaRenderer` instead.
// Needed here since objectui#9092 restored `ObjectGridSchema.label` to the
// `string | I18nLabel` form `BaseSchema` has carried since objectui#4580: the
// two reads below put the label in STRING positions, so a map-valued label used
// to reach them as an object and the compiler could not say so.
import { resolveI18nLabel as resolveInlineI18nLabel, PaginationConfigSchema } from '@objectstack/spec/ui';
import { stateMachineNextValues, isFieldInlineEditable } from './inline-edit-options';
import {
Badge, Button, NavigationOverlay, EmptyValue,
legacyRecordDrawerWidthKey, recordOverlayWidthStorageKey, useOverlayAnchor,
Popover, PopoverContent, PopoverTrigger,
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
RefreshIndicator,
DataEmptyState, EmptyStateLink, resolveIcon,
HorizontalOverflowBox, PINNED_RIGHT_SEAM_SHADOW_CLASSES,
toast,
} from '@object-ui/components';
import { usePullToRefresh } from '@object-ui/mobile';
import { resolveConditionalFormatting, resolveDependsOnFields, isDeadlineSettled, leadWithNameField, declaredNameField, buildExpandFields, buildExportFileName, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, resolveAffordance, resolveFieldAffordance, type SchemaLike, isProjectableField, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, toFilterNodeSafely, filterRefusalSubject, FilterOperatorError, convertSortToQueryParams, normalizeSortEntries, type QuerySortEntry, ROW_HEIGHT_TO_DENSITY_MODE, resolveRecordSourceConfig, resolveRecordSourceObjectName, resolveFilterPlaceholders, partitionRowsByPredicate, buildCategoryOrder, buildCategoryRank, toDisplayDate, type FilterTokenScope } from '@object-ui/core';
import { usePermissions } from '@object-ui/permissions';
import {
RECORD_OVERLAY_DEFAULT_WIDTH,
RecordDetailPanel,
ConcurrentUpdateDialog,
isConcurrentUpdateError,
useDetailTranslation,
type ConcurrentUpdateConflict,
} from '@object-ui/plugin-detail';
import { ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, Download, Rows2, Rows3, Rows4, AlignJustify, Type, Hash, Calendar, CheckSquare, User, Tag, Clock, Loader2 } from 'lucide-react';
import { useRowColor } from './useRowColor';
import { useGroupedDataInOptionOrder, usableGroupingFields, type GroupOptionRanks, type ServerGroupSource } from './useGroupedData';
import { groupSearchOf, useServerGroupHeaders, useServerGroupRows, type ServerGroupLeaf } from './useServerGrouping';
import { GroupRow } from './GroupRow';
import { useScopedColumnSummary } from './useColumnSummary';
import { useWholeSetSummary } from './useWholeSetSummary';
import { resolveRowCrudAffordances, resolveRowRecordCrudAffordance } from './rowCrudAffordances';
import { useRecordCrudVerdicts } from './hooks/useRecordCrudVerdicts';
import { resolveLegacyRowActions } from './resolveLegacyRowActions';
import { applyRelationalMeta } from './relationalMetaKeys';
import { resolveBulkActions, describeUnusableBulkActionDefs, resolvePromotedBulkParams } from './resolveBulkActions';
import { partitionBulkRows } from './bulkEligibility';
import { resolvesToDataColumn, describeUnresolvedColumns } from './columnSpellingDiagnostics';
import { RowActionMenu, formatActionLabel, planRowActionMenu } from './components/RowActionMenu';
import { BulkActionBar } from './components/BulkActionBar';
import { BulkActionDialog } from './components/BulkActionDialog';
import type { BulkResult } from './hooks/useBulkExecutor';
import type { BulkActionDef } from '@object-ui/types';
/**
* The node's own authored filter: the canonical `filter`. Its deprecated alias
* `defaultFilters` is not read: `@objectstack/spec` 18 retired it as a
* tombstone that refuses by name (objectstack#11509), and the alias read went
* with it (objectui#12030).
*/
interface AuthoredGridFilters {
filter: ObjectGridSchema['filter'];
}
/** One resolution, remembered with the inputs it was computed from. */
interface HeldGridFilters {
authored: AuthoredGridFilters;
currentUserId: FilterTokenScope['currentUserId'];
currentOrgId: FilterTokenScope['currentOrgId'];
recordId: FilterTokenScope['recordId'];
onUnresolved: FilterTokenScope['onUnresolved'];
resolved: AuthoredGridFilters;
}
function resolveGridFilters(authored: AuthoredGridFilters, scope: FilterTokenScope): HeldGridFilters {
return {
authored,
currentUserId: scope.currentUserId,
currentOrgId: scope.currentOrgId,
recordId: scope.recordId,
onUnresolved: scope.onUnresolved,
resolved: resolveFilterPlaceholders(authored, scope),
};
}
/**
* objectui#10607 — resolve the node's own filter ONCE, through
* `@object-ui/core`'s shared `resolveFilterPlaceholders`, against the session
* scope the host provides (`useFilterScope`). Before this, a directly authored
* `object-grid` with `filter: [['owner', '=', '{current_user_id}']]` sent the
* literal token on `$filter`. `object-view` already resolves the filters it
* hands this grid (objectui#10506); resolving that value again changes
* nothing, because a resolved id no longer matches the whole-token pattern.
*
* ⛔ Not a second resolver, and no fallback: a token the scope cannot resolve
* is whatever `resolveFilterPlaceholders` makes of it (left intact, with one
* warning naming it).
*
* The result is HELD against its inputs, the shape `plugin-view`'s
* `useResolvedFilterSegments` uses. The load effect keys on the filter this
* grid lowers, so a resolved copy minted on every render would refetch on
* every render; and a date macro such as `{now}` resolves to a new value at
* every call, so comparing OUTPUTS cannot stop that. The key is the authored
* filters, compared by structure (a host that rebuilds an equal filter inline
* must not re-query), plus each scope member read one by one (`recordId`
* among them, objectui#7297), never the scope object's identity (AGENTS.md
* #10). The held pair lives in state,
* so the value handed out is always the one React committed.
*/
function useResolvedGridFilters(authored: AuthoredGridFilters, scope: FilterTokenScope): AuthoredGridFilters {
const [held, setHeld] = useState(() => resolveGridFilters(authored, scope));
if (
held.currentUserId !== scope.currentUserId
|| held.currentOrgId !== scope.currentOrgId
|| held.recordId !== scope.recordId
|| held.onUnresolved !== scope.onUnresolved
|| !isSameAuthoredFilter(held.authored, authored)
) {
// React's documented "information from previous renders" shape: a set
// during render re-renders this component at once, before any child sees
// the discarded pass, and the re-render finds the inputs equal.
const next = resolveGridFilters(authored, scope);
setHeld(next);
return next.resolved;
}
return held.resolved;
}
/**
* A declared `sort` → the `"field order"` join string THIS block sends as
* `$orderby` (objectui#8973).
*
* ⚠️ Read the split before editing either half. WHICH entries survive and what
* a missing `order` means is `normalizeSortEntries`' decision — the governed
* one in `@object-ui/core`, shared with `convertSortToQueryParams` and every
* sibling block. Only the JOIN is this block's, because only this block sends
* a join string: the sink's `{field: direction}` map is route B on
* objectui#8767, declined by the maintainer 2026-09-10 pending a card that
* measures the server contract and both readers. So the operation with two
* copies (the normalization) has one implementation, and the shape the
* declination protects does not move.
*
* What this closes: the arms below used to interpolate every key
* unconditionally, so an entry missing `field` or `order` reached the wire as
* the literal text `undefined`. `$orderby: 'name undefined'` is not a
* degraded ordering — `normalizeSortNodes` (`@objectstack/metadata-protocol`,
* the one normalizer every server ingress funnels through) reads `undefined`
* as a direction that is "neither 'asc' nor 'desc'" and answers
* `400 INVALID_QUERY`.
*
* @returns `undefined` when nothing orderable survives, so the caller omits
* `$orderby` entirely instead of sending `""` — the same correction
* `toFilterNode` already made for `$filter: {}` on the filter leg above.
*/
function toOrderByClause(sort: QuerySortEntry[] | undefined | null): string | undefined {
const ordered = normalizeSortEntries(sort);
if (!ordered) return undefined;
return ordered.map((s) => `${s.field} ${s.order}`).join(', ');
}
/**
* A view's declared `sort` → the shape the table's header indicators read.
*
* `[{ field, order }, …]` is the ONE spelling `@objectstack/spec` still
* declares for `ObjectGridPropsSchema.sort` (objectui#8221 retired the string
* clauses), and since objectui#8961 it is the only spelling this reader
* admits. The headers agree with the fetch path on it: a view that arrives
* sorted by `created_at desc` shows that arrow before anyone clicks anything —
* otherwise the first click on that column produces `asc` while the list was
* already `desc`, and the arrow tells the truth only from the second click on.
*
* ⭐ A retired string spelling (`"name desc"`, `["name desc", …]`) yields
* NOTHING here, so it lights no arrow. That is the agreement, not an omission:
* the fetch path REFUSES the same spelling and sends no `$orderby`
* (objectui#8767). Between #8767 and objectui#8961 this reader was WIDER than
* that path — it parsed the string and drew a confident arrow for an ordering
* the query did not carry, a UI element stating something untrue about the rows
* beside it, with nothing but a console line to say so.
*
* ⛔ Do not re-widen it for a stored `sys_metadata` row still carrying the old
* spelling. The author is already told, once per spelling, by PR #8758's own
* diagnostic at the fetch path — it quotes the offending value and prescribes
* the array form. A second reading here would restore exactly the arrow the
* wire cannot honour.
*
* The wire shape is NOT what moved: this block still sends its own
* `"field order"` join string (see {@link toOrderByClause}), the shared sink's
* `{field: direction}` map stays declined, and the server-side export path
* reads `schema.sort` itself rather than through this function, so it was
* already array-only and is untouched.
*
* Exported for the test that pins it against the fetch path's own reading.
*/
export function parseSchemaSort(sort: unknown): TableSortItem[] {
const entries = Array.isArray(sort) ? sort : [];
const items: TableSortItem[] = [];
for (const entry of entries) {
if (entry && typeof entry === 'object' && typeof (entry as any).field === 'string') {
const { field, order } = entry as { field: string; order?: string };
items.push({ field, order: String(order).toLowerCase() === 'desc' ? 'desc' : 'asc' });
}
}
return items;
}
/**
* The class list both faces of {@link LinkCell} wear — the anchor is a visual
* no-op against the span it upgrades, so a list does not change appearance
* depending on whether its host publishes record URLs.
*/
/**
* The field types whose grid cell draws chips: the ones `@object-ui/fields`
* maps to `SelectCellRenderer` (a badge per selected option). Their column
* carries `chips`, so `data-table` floors it at its widest drawn chip and a
* single-word value is never ellipsized (objectui#12708).
*/
const CHIP_FIELD_TYPES: ReadonlySet<string> = new Set(['select', 'status', 'multiselect', 'radio', 'checkboxes', 'tags']);
function isChipFieldType(type: unknown): boolean {
return typeof type === 'string' && CHIP_FIELD_TYPES.has(type);
}
const LINK_CELL_CLASS =
'text-primary font-medium underline-offset-4 hover:underline cursor-pointer truncate block max-w-full';
/**
* The same list with the one-line clamp swapped for wrapping — what a cell in a
* column carrying an authored `wrap: true` wears (objectui#6650).
*
* ⭐ DERIVED from {@link LINK_CELL_CLASS} rather than written out, so the two
* cannot drift: every future edit to the link cell's appearance lands in both
* faces of both variants, and the no-wrap variant stays byte-identical to what
* `ObjectGrid.linkCellAnchor.test.tsx` pins as full markup.
*
* ⚠️ Why this exists at all — the outer read in `data-table.tsx` is NOT enough
* on its own. `data-table` puts the wrap/truncate decision on the cell BODY it
* owns, but a link column's content is this component, and its own `truncate`
* clamps the text back to one line INSIDE a body that is willing to wrap. So
* `wrap: true` on the record-link column — column one of almost every grid —
* would have rendered as silently nothing: the very failure mode this card
* exists to end, reproduced one element deeper. Measured, not reasoned: the
* end-to-end pin in `ObjectGrid.columnWrapForward.test.tsx` failed on exactly
* this, reading back `…cursor-pointer truncate block max-w-full` from a column
* authored `wrap: true`.
*/
const LINK_CELL_CLASS_WRAP = LINK_CELL_CLASS.replace('truncate', 'whitespace-normal break-words');
/**
* A row's primary key — the value the host's record-URL builder addresses.
* Mirrors what `useNavigationOverlay.handleClick` reads off the same row, so
* the anchor's href and the click path can never point at different records.
*/
function rowRecordId(row: unknown): string | number | undefined {
const rec = row as Record<string, unknown> | null | undefined;
const id = rec?.id ?? rec?._id;
return typeof id === 'string' || typeof id === 'number' ? id : undefined;
}
// Clickable text cell that can safely contain other interactive content
// (e.g., EmailCellRenderer's copy button). Using <button> here would
// produce an invalid <button> > <button> nesting (hydration error +
// breaks the inner copy click). role="link" + tabIndex + keyboard
// handlers preserves accessibility while allowing arbitrary children.
//
// objectui#4490 — that span was the whole cell, so the list's link column had
// none of a link's native affordances: no middle-click / ⌘-click open-in-new-
// tab, no "copy link address", no hover status-bar URL, and `role="link"` with
// no `href` is a weaker contract for assistive tech than a real anchor. PR
// #4489 had just given detail-page and related-list lookup VALUES real anchors,
// which left the list — the surface users open records from — as the weakest of
// the three.
//
// So when the host publishes a record URL this renders a real `<a href>`, with
// the split #4489 established:
// - plain left click → `preventDefault()` + the existing `onActivate`, so SPA
// navigation (drawer / modal / page, whatever the view configured) is
// completely unchanged;
// - modifier / non-primary click → NOT prevented, so the browser does what it
// does with any link.
//
// **The URL is not built here.** This package has no router and no business
// knowing what a record route looks like; the host publishes its own builder
// through `RelatedRecordActionsContext.recordHref` — the same seam #4489 used,
// and for the console list surface the same builder its "open in new window"
// action already navigates with. No host, or a host that cannot route to this
// object, renders EXACTLY the span below: same markup, same behavior, nothing
// to un-learn (the Studio designer, embedded renderers, standalone grids).
const LinkCell: React.FC<{
testId: string;
onActivate: () => void;
/** Object whose record this row is — passed to the host's URL builder. */
objectName?: string;
/** This row's primary key. Absent (a row with no id) ⇒ no anchor. */
recordId?: string | number | null;
/**
* The column's authored `wrap` (objectui#6650). `true` ⇒ this cell drops its
* one-line clamp so long link text flows onto further lines, matching what
* `data-table` does to the body around it. Absent / `false` ⇒ unchanged.
*/
wrap?: boolean;
children: React.ReactNode;
}> = ({ testId, onActivate, objectName, recordId, wrap, children }) => {
const host = useRelatedRecordActions();
const cellClass = wrap ? LINK_CELL_CLASS_WRAP : LINK_CELL_CLASS;
const href =
objectName && recordId != null && recordId !== '' && host?.recordHref
? host.recordHref(objectName, recordId)
: null;
if (href && host) {
// objectui#11817 — no anchor inside this anchor. A reference value in the
// cell (`LookupCellRenderer`'s `ReferencedRecordLink`) draws its own `a`
// whenever the host answers `recordHref` for the referenced object, so the
// children are rendered under the same host with no record destination:
// "the host cannot route to that object", which the context documents as
// render the plain value. The self-linking faces (`mailto:`, URL, `tel:`)
// never ask the host; the cell is handed their text face instead
// (`linkCellRenderer` in `./cellRendererResolution`).
const unlinkedHost = { ...host, recordHref: undefined, openRecord: undefined };
return (
<a
href={href}
data-testid={testId}
className={cellClass}
onClick={(e) => {
// The row underneath carries its own click handler (open the record,
// and on a modifier click open it in a new tab). Following this link
// must never ALSO fire that — on a modifier click that would open two
// tabs, one from the anchor and one from the row.
e.stopPropagation();
// Modifier and non-primary clicks belong to the browser (new tab, new
// window) — that is the entire point of rendering a real href.
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
e.preventDefault();
onActivate();
}}
onKeyDown={(e) => {
// Enter is the anchor's OWN activation: the browser fires a click for
// it, which the handler above turns into the SPA path. Handling it
// here too would activate twice. Space is the one the span had that a
// link does not do natively, so it is carried over explicitly.
if (e.key === ' ') {
e.preventDefault();
e.stopPropagation();
onActivate();
}
}}
>
<RelatedRecordActionsProvider value={unlinkedHost}>{children}</RelatedRecordActionsProvider>
</a>
);
}
return (
<span
role="link"
tabIndex={0}
data-testid={testId}
className={cellClass}
onClick={(e) => {
e.stopPropagation();
onActivate();
}}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
e.stopPropagation();
onActivate();
}
}}
>
{children}
</span>
);
};
/**
* objectui#12608 — the face a `referenceVia` pointer column draws its rows
* with, or `null` when the field declares no pointer pair.
*
* The pair is resolved per row by `resolveRecordPointer` (`@object-ui/fields`),
* the one rule the record details grid asks too; `referenceVia` is read off the
* OBJECT field, where the spec declares it, and the type is the column's
* declared one, so a view that re-types the column keeps its own face. A row
* the rule answers `null` for (a half-addressed pair) is drawn by the column's
* ordinary face: the returned function answers `null` and the caller falls
* through to it. Inside a link cell the face is drawn under `LinkCell`'s
* unlinked host, so it draws the name without a second anchor.
*/
function recordPointerFace(
fieldName: string,
declaredType: string | null,
fieldDef: { referenceVia?: unknown } | null | undefined,
dataSource: RecordPointerSource | null | undefined,
): ((row: any) => React.ReactElement | null) | null {
const referenceVia = fieldDef?.referenceVia;
if (typeof referenceVia !== 'string' || referenceVia === '') return null;
return (row: any) => {
const pointer = resolveRecordPointer({ name: fieldName, type: declaredType, referenceVia }, row);
return pointer ? <RecordPointerCell pointer={pointer} dataSource={dataSource} /> : null;
};
}
// Default English fallback translations for the grid
const GRID_DEFAULT_TRANSLATIONS: Record<string, string> = {
'grid.actions': 'Actions',
'grid.edit': 'Edit',
'grid.delete': 'Delete',
'grid.export': 'Export',
'grid.exportAs': 'Export as {{format}}',
'grid.loading': 'Loading grid…',
'grid.errorLoading': 'Error loading grid',
// objectui#9050 — the malformed-filter state, shared with `RelatedList`
// and `LineItemsPanel` because it is one sentence about one authored
// value, not three. Byte-identical to the `en` pack, which
// `defaults-maps-mirror-en-pack` enforces.
'view.malformedFilter': 'This view’s filter is malformed, so no records are shown: the {{subject}} condition cannot be applied.',
'grid.pullToRefresh': 'Pull to refresh',
'grid.refreshing': 'Refreshing…',
'grid.openRecord': 'Open record',
'grid.empty': 'Empty',
'grid.yes': 'Yes',
'grid.no': 'No',
'grid.systemFields': 'System',
// The grouped grid's refusal over a data source that cannot answer the
// group header query (objectui#10881, ruling F). It must exist HERE as well
// as in the locale packs: a provider-less host (a standalone grid, this
// package's own tests) never reaches them, and it is the only thing such a
// grid draws.
'grid.grouping.needsHeaderQuery':
'This view is grouped, but its data source does not implement queryGroupHeaders, so the groups cannot be counted. Remove the grouping to show the records.',
// …and over rows a host handed in while declaring them one page of more.
'grid.grouping.needsWholeRows':
'Grouping needs every record, but this grid was handed one page of them, so the groups cannot be counted. Hand in every record, or let the grid fetch them from a data source that implements queryGroupHeaders.',
// Reused by the grouped-view pager (falls back here when no I18nProvider).
'table.rowsPerPage': 'Rows per page',
'table.pageInfo': 'Page {{current}} of {{total}}',
// The grouped-view pager's four icon buttons are named by these
// (objectui#12143): the `data-table` pager's own keys, objectui#12124.
'table.firstPage': 'First page',
'table.previousPage': 'Previous page',
'table.nextPage': 'Next page',
'table.lastPage': 'Last page',
// The default inline-edit saves' success toast (objectui#12303), counted in
// the rows the server accepted — the `table.modified` unit the table's
// "Save All" bar counts in.
'table.saved': '{{count}} row saved',
'table.saved_one': '{{count}} row saved',
'table.saved_other': '{{count}} rows saved',
// The heading of an authored `emptyState` that declares no `title`
// (objectui#11068): the words the table's own empty row shows, so leaving the
// member out changes nothing a user reads.
'table.noResults': 'No results found',
// The empty state an empty grid draws when no authored `emptyState` and no
// search term are in force (objectui#13142). Borrowed from the `list.*`
// namespace `ListEmptyState` reads, so a grid and a list say the same thing
// about the same empty object; the rows exist HERE too for a provider-less
// host.
'list.firstRunTitle': 'Nothing here yet',
'list.firstRunMessage': 'Create your first record to get started.',
'list.noMatches': 'No matching records',
'list.viewFilterNoMatchesMessage': 'No records match this view’s filter.',
// objectstack#25898 — a grid filtered to the signed-in user, and an
// unfiltered grid for a caller who may not create (`ListEmptyState` says
// both in the same words).
'list.ownedNoneTitle': 'Nothing of yours yet',
'list.ownedNoneMessage': 'This view lists only records that are yours, and you don’t have any yet.',
'list.noneVisibleTitle': 'No records you can see',
'list.noneVisibleMessage': 'There are no records here that you have access to. If you expected to see some, ask your administrator for access.',
// Heading of the record-detail overlay this grid opens on row click
// (objectui#3426). Borrowed from the `detail.*` namespace rather than minted
// as `grid.recordDetail`: `NavigationOverlay` already resolves
// `detail.recordDetail` for hosts that pass no title, and one heading on one
// control should not get two translations that can drift apart. Both entries
// must exist HERE too — a provider-less host (a standalone grid, this
// package's own tests) never reaches the locale packs.
'detail.recordDetail': 'Record Detail',
'detail.recordDetailWithLabel': '{{label}} Detail',
};
/**
* 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).
*/
const useGridTranslation = createSafeTranslation(GRID_DEFAULT_TRANSLATIONS, 'grid.actions');
/**
* Resolve a column header `label` (`ListColumnSchema.label`, the spec's
* `I18nLabel`) to the string the header prints, in the viewer's `language`.
*
* A plain string passes through unchanged. An inline locale map
* (`{ en: 'Amount', 'zh-CN': '金额' }`) is picked by `pickLocalized` — the one
* locale pick the console uses for `I18nLabel`, with its own floor when the
* viewer's locale is absent — rather than a second implementation here.
* objectui#12358: this used to keep only a plain string and answer `undefined`
* for a map, so an authored map header silently fell back to the field label.
* A map with no usable entry still answers `undefined`, so the field-label
* fallback at the call site applies exactly as for an absent label.
*/
function resolveColumnLabel(label: string | I18nLabel | undefined, language: string | undefined): string | undefined {
if (label == null) return undefined;
if (typeof label === 'string') return label;
return pickLocalized(label, language) || undefined;
}
/**
* The column layout ObjectGrid persists and reports back — the merged result of
* a resize and a reorder, not either event on its own. Named so the state hook
* below and the `onColumnStateChange` prop cannot drift apart.
*/
export interface ObjectGridColumnState {
order?: string[];
widths?: Record<string, number>;
}
/**
* One column summary as the grid's footer would draw it — `header: label`,
* e.g. `Annual Revenue` and `Sum: 109,800,000.00` — handed to a host through
* {@link ObjectGridComponentProps.onColumnSummaryChange} (objectui#12528).
*/
export interface ObjectGridFooterSummary {
/** The column's accessor key. */
key: string;
/** The column's header text. */
header: string;
/** The formatted summary, scope included (`Sum: 109,800,000.00`). */
label: string;
}
/**
* The HOST-DRIVEN ("external") mode of ObjectGrid — framework#2212.
*
* The ordinary authoring surface hands ObjectGrid a `schema` and a `dataSource`
* and lets it fetch, page, sort and search for itself. In this mode a host
* (ListView, a designer preview, an app screen with its own toolbar) has
* already fetched one window of a larger collection and drives the controls
* itself: it passes the window as `data` plus the real match total and the
* page/sort/search state, and ObjectGrid forwards them straight to its
* DataTable instead of client-slicing the window it was handed.
*
* Kept as its own named interface rather than flattened into `ObjectGridComponentProps`
* (#4277 裁决 B, 2026-08-11): the two are different classes of contract, and a
* dozen more members merged into the authoring surface would erase that
* boundary. Until this existed, every member below was read out of `...rest`
* through an `as any` cast and was declared nowhere at all.
*
* DERIVATION (#4277 裁决 §3, the anti-drift pin): this vocabulary is already
* declared once, on `DataTableSchema` — which is exactly where ObjectGrid
* forwards it — so the members that have a counterpart there are TYPE-DERIVED
* from that declaration rather than hand-copied into a second enumeration. Two
* hand-written copies of one vocabulary is how the next drift happens. The
* `Partial<...>` wrapper is deliberate and is the only shape change: the whole
* mode is opt-in, and `DataTableSchema['data']` is required because a table
* always has rows, while a grid that was given no `data` fetches its own.
*
* `search` is read outside this mode too (objectui#11021): a host that passes
* it owns the search term even where the grid fetches for itself, and the
* grid's own queries carry it. `ListView` hands its toolbar term to a grid
* that groups on the server that way, with no rows.
*/
export interface ObjectGridExternalPaginationProps
extends Partial<
Pick<
DataTableSchema,
// The host's already-fetched window. Highest-priority data source: it
// wins over `schema.data` / `schema.bind` when present.
| 'data'
// Turns off client slicing. With `rowCount` + `onPageChange` it is what
// makes the mode active at all (see `externalManualPagination` below).
| 'manualPagination'
| 'rowCount'
| 'page'
| 'pageSize'
| 'onPageChange'
| 'onPageSizeChange'
| 'sort'
| 'onSortChange'
| 'search'
| 'onSearchChange'
>
> {
/**
* Grid-only: `DataTableSchema` has no counterpart to derive from.
*
* The table vocabulary reports column changes as separate per-event
* callbacks — `onColumnResize(columnKey, width)` and
* `onColumnReorder(newOrder)` — whereas this reports the MERGED, persisted
* `{ order, widths }` layout after ObjectGrid has folded either event into
* the state it also writes to `localStorage`, so a host can save one blob
* (the console stores it on the signed-in user's own list state). Deriving
* it from either table
* callback would misstate both the payload and when it fires.
*/
onColumnStateChange?: (state: ObjectGridColumnState) => void;
/**
* Grid-only: `DataTableSchema` has no counterpart to derive from — a table is
* handed rows, it never issues a query.
*
* The params the host passed to `dataSource.find()` for the window it is
* handing down in `data` — the SAME shape this grid's own loader stores in
* `lastFindParamsRef` (`$filter` / `$orderby` / `$select` / `$search` /
* `$searchFields` / `$expand` / `$top` / `$skip`), so both paths feed one
* reader. `$top`/`$skip` may be present and are ignored: the fan-out windows
* the replay itself.
*
* Why a prop rather than a fallback inside the grid (objectui#4501): the
* cross-page "select all N matching" escalation re-issues the view's query to
* collect the whole match set, and the query has to come from whichever side
* owns the fetch. Under external pagination that is the host, and the grid's
* own ref is either empty or stale — replaying it asked the server for the
* WHOLE OBJECT (no `$filter`) and handed up to 5000 unmatched records to a
* destructive executor. A grid-side `?? {}` default is what produced that,
* which is why the missing case is not defaulted but REFUSED: with no params
* for the current data path the escalation is not offered at all (see
* `bulkFanoutParams` in the component body).
*
* A changed value is also the host's query-change signal: it resets the
* escalation, mirroring the `setSelectAllMatching(false)` the internal loader
* runs next to its own `lastFindParamsRef` write. Compared by CONTENT, so a
* host re-render that rebuilds an equal object does not drop the user's
* escalation.
*/
findParams?: Record<string, unknown> | null;
}
/**
* Props of the `ObjectGrid` React component.
*
* Renamed off the bare `ObjectGridProps` (objectui#4650): from 17.0.0
* `@objectstack/spec/ui` owns that name, where it is the AUTHORED props
* document of the `object-grid` element — `z.input<typeof
* ObjectGridPropsSchema>`, i.e. serialisable authoring keys only (`label`,
* `fields`, `filter`, `pagination`, …). This is the RENDERER's props: a
* live `dataSource`, the host pagination handles below, and eleven callbacks,
* none of which can exist in authored metadata. Two layers under one word,
* resolved the way this repo already resolved it for `PageHeaderProps` ->
* `PageHeaderComponentProps` (app-shell) and the `Record*ComponentProps` family
* in `@object-ui/types`.
*
* The barrel keeps `ObjectGridProps` as a deprecated alias of this type, so no
* importer breaks. Tripwire: `__tests__/spec-symbol-4650.test.ts`.
*/
/**
* The subset of the grid-level `operations` block that a row may answer for
* ITSELF — the vocabulary {@link ObjectGridComponentProps.rowOperations} speaks.
*
* `update` / `delete` are the two the row kebab renders, and they are spelled
* exactly as the authored `operations` block spells them, so one word means one
* thing whether it is declared for the whole grid or resolved for one row. The
* block's other members (`create`, `export`) are deliberately absent: neither
* is a row affordance, so a per-row answer for them would have nowhere to land.
*/
export interface ObjectGridRowOperations {
update?: boolean;
delete?: boolean;
}
export interface ObjectGridComponentProps extends ObjectGridExternalPaginationProps {
schema: ObjectGridSchema;
dataSource?: DataSource;
className?: string;
/**
* [objectui#10657] The object's field catalogue (`fields` of the definition
* `getObjectSchema(objectName)` returns), handed down by a HOST that has
* already read it. `ListView` passes the definition it fetched before its
* rows; the grid answers every field-type question from it until its own
* read of the definition lands, and from its own read after that.
*
* ## Why a host hands it down
*
* A host that fetches the rows hands them down as `data`, so they paint
* before the grid's own schema read settles. Until then an untyped view
* column over a `password` / `secret` field has no type, and the grid can
* only withhold it (drawn as the mask, never as text). With the catalogue in
* hand there is no such window: the column draws, and is flagged, from its
* declared type at first paint.
*
* ## A RUNTIME prop, never authored metadata
*
* The name is the host channel decision batch #70 ruled for the object's
* field catalogue (objectui#7742): `SchemaRenderer` strips an AUTHORED
* `objectFields` on every spelling (objectui#8818), so only a host's React
* prop can reach this slot, and no view author can supply a catalogue that
* types a credential field as text.
*/
objectFields?: Readonly<Record<string, unknown>>;
/**
* [objectui#12423] Row numbers on the leading cell, as a HOST says: `ListView`
* passes its Display control's Row numbers switch here (session-only, never
* stored). Absent ⇒ on, the grid's default since it drew them. A RUNTIME
* prop: the protocol declares no row-number key on a view, and none is read
* off the node.
*/
showRowNumbers?: boolean;
/**
* [objectui#12528] A HOST that draws its own footer row takes the column
* summaries into it. When this is passed the grid draws no summary row of
* its own and reports, in column order, what that row would have drawn —
* `null` when it would draw none (no summary, a grouped grid, unmounted).
* `ListView` passes it so the summaries sit at the right of its record-count
* row: one footer row instead of two. Reported on a change of CONTENT, never
* of identity. A RUNTIME prop, never authored metadata.
*/
onColumnSummaryChange?: (summaries: readonly ObjectGridFooterSummary[] | null) => void;
/**
* [objectui#8674] Narrow ONE row's generic Edit / Delete entries — the layer
* that lets a host withhold an operation the record itself cannot accept.
*
* ## Why this exists
*
* `operations` and the `onEdit` / `onDelete` wiring are GRID-level: they say
* whether the affordance exists at all, identically for every row. A host
* whose refusal is per RECORD had nowhere to put it, so it put the refusal in
* the callback instead — `FieldDesigner`'s delete handler returned early on a
* system field, after the grid had already drawn the button. The two states
* it was distinguishing (`readOnly`, which withholds the callback, and
* `isSystem`, which swallowed the click) differed in the code and did not
* differ on screen: the author clicked a button drawn as available and got no
* dialog, no toast, no console message. The operation an affordance cannot
* perform is not offered.
*
* ## The contract
*
* Called with a row record; returns the overrides for THAT row. It is an
* INTERSECTION, like every layer around it (the ADR-0103 bucket, the object's
* `userActions`, the server's effective API operations, the principal's own
* grant and the record-level explain verdict): `false` WITHHOLDS, and nothing
* it returns can re-open what those closed. `true`, an omitted member, a
* `null` / `undefined` return, and an absent prop all leave the verdict
* exactly as the grid resolved it — so a caller that passes nothing renders
* what it rendered before this prop existed.
*
* Scope is the row's kebab. Bulk delete rides `onBulkDelete` and the object
* verdict behind the selection bar, which no per-row answer can speak for:
* one selected row's `false` must not silently drop the other rows' action.
*/
rowOperations?: (record: any) => ObjectGridRowOperations | null | undefined;
/**
* [objectui#13330] A host-drawn node beside ONE row's title: the cell of the
* object's declared name field when a column shows it, else the first shown
* column (the row actions are never it), and the title of the row's card in
* the card view. Called with the row record; `null` / `undefined` draws
* nothing, and so does an absent prop, so a caller that passes nothing
* renders exactly what it rendered before this prop existed.
*
* The console's Users list on a managed environment passes a marker for a
* user who holds nothing beyond the baseline. What the node says is the
* host's; the grid only places it, after the cell's own content and never in
* place of it, so the value, its link and its mask all stay as drawn.
*
* A RUNTIME prop, never authored metadata: it is a React node a host
* composes, nothing an author writes, and no node key reaches it.
*/
rowAdornment?: (record: any) => React.ReactNode;
/**
* TWO parameters since objectui#9357, and the second is not decoration: this
* prop reaches `useNavigationOverlay` as its `onRowClick`, and `handleClick`
* invokes it as `onRowClick(record, event)` — the modifier payload a host
* needs to implement Cmd/Ctrl/middle-click for itself. Declaring one
* parameter hid the second on the ONE line a host reads. Spelled `any` and
* not `HandleClickModifiers` for the reason objectui#9341 measured on
* `ObjectKanbanSchema.onCardClick`: that interface lives in
* `@object-ui/react`, the published twins in `@object-ui/types` may not name
* it, and a host that discovered the payload from the implementation
* annotated it `React.MouseEvent` — which a narrower declaration refuses
* contravariantly. `BaseSchema`'s own `onClick` / `onChange` / `onSubmit`
* already use this spelling for exactly this situation.
*/
onRowClick?: (record: any, event?: any) => void;
/**
* Called for page-level navigation with the record id and a
* {@link RecordNavigateAction} — a navigation-MODE token from a closed
* vocabulary: `'view'` opens the record page, `'new_window'` opens it in a
* new browser tab.
*
* [objectui#9547] The tenth callback on this interface, and the channel a
* programmatic caller should use: its nine siblings below are props here
* too, and `ObjectGridSchema.onNavigate`'s own docblock sends callers to
* this interface for it. That schema key still works — it is the
* same slot reached off the node — and when BOTH are supplied, THIS PROP
* WINS (maintainer ruling C on objectui#9547: the programmatic caller is the
* nearer party). `onRowClick` above still takes full priority over either:
* a host that owns the row click owns navigation too.
*/
onNavigate?: (recordId: string | number, action: RecordNavigateAction) => void;
onEdit?: (record: any) => void;
onDelete?: (record: any) => void;
onBulkDelete?: (records: any[]) => void;
onCellChange?: (rowIndex: number, columnKey: string, newValue: any, row: any) => void;
onRowSave?: (rowIndex: number, changes: Record<string, any>, row: any) => void | Promise<void>;
onBatchSave?: (changes: Array<{ rowIndex: number; changes: Record<string, any>; row: any }>) => void | Promise<void>;
onRowSelect?: (selectedRows: any[]) => void;
onAddRecord?: () => void;
}
/**
* Helper to get data configuration from schema.
*
* The ruled three-rung ladder itself (`data`, then `staticData`, then
* `objectName`) is `resolveRecordSourceConfig` in `@object-ui/core` — ONE
* implementation of a contract published on both faces (`77cb489b4`), which
* this file used to hand-copy (`ce2aaefe1`).
*
* What used to stay here was the head above it: the bare-array `data`
* shorthand, which lifted `data: [...]` to `{ provider: 'value', items }`.
* ⛔ IT IS GONE (objectui#8348, decision batch #83, maintainer verbatim
* 「8348 以协议为准」 — the contract decides).
*
* MEASURED on `@objectstack/spec` 17.4.0:
* `ComponentPropsMap['object-grid'].data` is the `ViewData` union, and its own
* description names the refusal — *"Static inline rows live at
* `{ provider: 'value', items: [...] }`; the bare-array shortcut is refused —
* see migration `object-grid-data-view-data-converged`"*. This block's own
* registration publishes the same arm (`{ name: 'data', type: 'object' }` in
* `index.tsx`), and `gridDataInputContract.test.ts` has pinned that declaration
* since objectui#5090. The head was the last carrier of a spelling every one of
* those faces refuses, so `data` is honoured here on the OBJECT arm only and
* the shared rung is passed `'view-data'`.
*
* ⛔ WHAT THIS REACHES, measured per CARRIER — do NOT read it as "the array is
* gone". An authored `data` array reaches this component TWICE: as
* `schema.data`, which this function used to lift, and as the `data` PROP,
* because `SchemaRenderer` spreads every non-metadata node key and
* `index.tsx` forwards `{...rest}`. That prop is `passedData` below, and it
* lifts an array to `{ provider: 'value', items }` at HIGHER priority than this
* ladder — it is the channel a host such as `ListView` uses to hand down rows it
* already fetched, and it is indistinguishable here from an authored key.
*
* ⇒ at the ladder the array is no longer a record source; through
* `SchemaRenderer` an authored `data: [ …rows… ]` still draws, from the props
* channel. Both halves are pinned in
* `__tests__/gridBareArrayDataRefused-8348.test.tsx`, which had to correct its
* own first draft on exactly this point. Collapsing the two carriers would take
* the host path with it and is outside objectui#8348's scope — reported on the
* card, not changed in passing.
*
* The declared spelling for inline rows is
* `data: { provider: 'value', items: [...] }`, and the deprecated `staticData`
* array still works as before.
*/
function getDataConfig(schema: ObjectGridSchema): ViewData | null {
return resolveRecordSourceConfig(schema, 'view-data');
}
/**
* The relational copy set and `applyRelationalMeta` moved to
* `./relationalMetaKeys` for objectui#6875. The list there is DERIVED from a
* table classifying every key swept off the three `@object-ui/fields` consumers,
* and a gate re-derives that read set from their sources — so the copy set can
* no longer drift into being a strict subset of what those consumers read,
* which is what it had silently become. Read that file's docblock before
* adding, removing or re-spelling a key.
*
* ⚠️ What this bag actually feeds is ONE of those three: the read-only cell.
* `fieldMeta` is handed to `<CellRenderer field={…}>` and nowhere else in this
* file. The inline picker is the OTHER seam — `renderCellEditor` below looks
* the field up in `objectSchema` and spreads the whole def into the widget, so
* a picker key reaches `LookupField` whether or not it is on the copy set.
* Measured in `__tests__/lookupPickerKeys-7154.test.tsx` (objectui#7154).
*/
/**
* Content signature of a host's find-params, used as the query-change signal for
* the cross-page escalation (objectui#4501 clause 2).
*
* CONTENT and not identity: a host re-render that rebuilds an equal params
* object must not drop an escalation the user just made, and identity is the
* one thing a host cannot be relied on to keep stable. Top-level keys are
* sorted so key ORDER — which differs between the host's literal and this
* grid's own loader — never reads as a query change.
*/
function findParamsSignature(params: Record<string, unknown> | null | undefined): string | null {
if (!params) return null;
return JSON.stringify(
Object.keys(params).sort().map((k) => [k, params[k] ?? null]),
);
}
/**
* Helper to normalize columns configuration
* Handles both string[] and ListColumn[] formats
*/
function normalizeColumns(
columns: string[] | ListColumn[] | undefined
): ListColumn[] | string[] | undefined {
if (!columns || columns.length === 0) return undefined;
// Already in ListColumn format - check for object type with optional chaining
if (typeof columns[0] === 'object' && columns[0] !== null) {
return columns as ListColumn[];
}
// String array format
return columns as string[];
}
/**
* ⭐ WHAT THIS GRID'S COLUMN PRODUCER IS ALLOWED TO EMIT (objectui#6004).
*
* `generateColumns()` below builds the column array this component hands to
* `data-table`, whose slot is `DataTableSchema.columns: TableColumn[]`. It had
* no return annotation, so its four emit paths were inferred structurally and
* nothing ever compared them to the slot's declaration — and all four call
* sites re-widened to `any` on the way out, so even an annotation would have
* been discarded one hop later.
*
* ## ⭐ Why this is not just `: TableColumn[]`
*
* objectui#6373 measured, at the sibling producer in `plugin-dashboard`, that a
* bare `TableColumn` annotation raises no error on a `{ ...spread }` emit,
* because TypeScript's excess-property check is a FRESHNESS check on the
* properties an object literal WRITES OUT and spread properties are exempt.
*
* Measured again HERE before choosing this shape, because this seam is worse
* than that one and the difference matters:
*
* 1. `generateColumns = useCallback((): TableColumn[] => {`, everything else
* unchanged → `tsc --noEmit` exit 0, ZERO diagnostics.
* 2. Same, PLUS an undeclared key `wrapControl: true` WRITTEN OUT in the path-A
* column literal (not arriving through a spread) → exit 0, ZERO diagnostics.
*
* Run 2 is the one that fixes the mechanism. At objectui#6373's seam the object
* literal sits in `enrich()`'s return position, so freshness still caught keys
* written out longhand and only the spread escaped. Here every literal is the
* return value of a `.map()` callback, so it is inferred into the callback's
* return type FIRST and reaches the annotation as a non-fresh `X[]`. Freshness
* is gone entirely: written-out keys escape too. A bare annotation at this seam
* is not a weak instrument, it is an inert one — a green gate and no guard.
*
* The `?: never` members are what make the annotation able to fail. They are
* ADR-0049 retirement tombstones — this repo's convention for a key that is
* REFUSED rather than merely absent (`StaticTableColumn` in `@object-ui/types`)
* — and they bite by ASSIGNABILITY, which survives `.map()` because it never
* depended on freshness. Re-adding `...(col.summary && { summary: col.summary })`
* to a column literal is a compile error naming `summary`.
*
* ## The rule (objectui#6373's, applied to this producer's key set)
*
* A producer may write into a `TableColumn[]` slot only keys the CONSUMER of
* that slot reads, and the read set is MEASURED from the consumer's source,
* never assumed. A key the consumer reads and `TableColumn` declares is
* written; a key the consumer reads that `TableColumn` does not declare is HELD
* where a ruling already holds it; a key nothing reads is RETIRED — never
* declared, because declaring a key nothing reads is the same
* `declared != enforced` defect facing the other way. Before retiring, prove
* the value has a second road to its consumer.
*
* Consumers measured for THIS producer — two of them, because the array is read
* twice before it reaches the slot:
*
* - `data-table.tsx`, comments stripped, every `col.<key>` read — FOURTEEN:
* `accessorKey`, `width`, `align`, `header`, `className`, `cellClassName`,
* `sortable`, `resizable`, `editable`, `type`, `cell`, `headerIcon`,
* `fitContent`, `wrap`. ⚠️ It was THIRTEEN between objectui#7196 and
* objectui#6650, which added the `wrap` read this producer now feeds; it
* said fourteen before #7196 re-derived it: