-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcontainers.tsx
More file actions
1360 lines (1303 loc) · 56.1 KB
/
Copy pathcontainers.tsx
File metadata and controls
1360 lines (1303 loc) · 56.1 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.
*
* Spec-aligned container renderers for the `page:*` component namespace.
* Backs the Page-as-root record detail page model (Salesforce Lightning
* Record Page parity).
*
* Maps `packages/spec/src/ui/component.zod.ts` props:
* - PageTabsProps -> page:tabs
* - PageCardProps -> page:card
* - PageAccordionProps -> page:accordion
* - PageHeaderProps -> page:header
* - page:footer / page:sidebar / page:section thin wrappers
*/
import React from 'react';
import { ComponentRegistry, ExpressionEvaluator, getRecordDisplayName } from '@object-ui/core';
import { useRecordContext, useAction, useCapabilityGate, usePredicateScope, usePageVariables, useInlineEdit } from '@object-ui/react';
import { renderChildren, cn } from '../../lib/utils';
import { LazyIcon } from '../../lib/lazy-icon';
import { RelatedCountStore, useRelatedCountVersion } from '../../hooks/related-count-store';
import { useIsMobile } from '../../hooks/use-mobile';
import {
Tabs,
TabsList,
TabsTrigger,
TabsContent,
Card,
CardHeader,
CardTitle,
CardContent,
CardFooter,
Accordion,
AccordionItem,
AccordionTrigger,
AccordionContent,
Separator,
Button,
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
} from '../../ui';
import { RecordTitleChip } from '../../custom/RecordTitleChip';
import { useObjectLabel, useSafeFieldLabel, useObjectTranslation, pickLocalized } from '@object-ui/i18n';
import { MoreHorizontal } from 'lucide-react';
/**
* Pull the standard designer-passthrough props off a renderer's `props`.
* Every page:* renderer must forward these so the Studio designer overlay
* can still target the rendered element.
*/
const splitDesignerProps = (props: Record<string, any>) => {
const {
'data-obj-id': dataObjId,
'data-obj-type': dataObjType,
style,
...rest
} = props || {};
return {
designer: { 'data-obj-id': dataObjId, 'data-obj-type': dataObjType, style },
rest,
};
};
/** Pick a value for I18nLabelSchema (string or { default, ... } shape). */
const labelText = (label: any): string => {
if (label == null) return '';
if (typeof label === 'string') return label;
if (typeof label === 'object') return label.default || label.value || '';
return String(label);
};
/**
* Lightweight built-in translation for well-known English tab/accordion
* labels used by Lightning-style record pages (Details / Related /
* Activity / History / Notes / Files / Tasks / Events / Attachments /
* Chatter / Discussion). Keeps `@object-ui/components` free of an i18n
* dependency while closing the gap between custom Page schemas (often
* authored in English) and the localised default detail view.
*
* Authors can always override by passing a localised `label` (string or
* `{ default, zh-CN, ... }` shape) directly in their schema; the map is
* only consulted when the input matches a known English token.
*/
const KNOWN_LABEL_DICT: Record<string, Record<string, string>> = {
'zh-CN': {
Details: '详情',
Related: '相关',
Activity: '活动',
History: '历史',
Notes: '备注',
Files: '文件',
Tasks: '任务',
'Open Tasks': '待办任务',
'Closed Tasks': '已完成任务',
Events: '日程',
Attachments: '附件',
Chatter: '讨论',
Discussion: '讨论',
Comments: '评论',
Overview: '概览',
Summary: '摘要',
Quotes: '报价单',
Products: '产品',
Contacts: '联系人',
Accounts: '客户',
Leads: '线索',
Opportunities: '商机',
Cases: '服务案例',
Campaigns: '营销活动',
Approvals: '审批',
Documents: '文档',
Emails: '邮件',
Calls: '通话',
Meetings: '会议',
},
'zh-TW': {
Details: '詳情',
Related: '相關',
Activity: '活動',
History: '歷史',
Notes: '備註',
Files: '檔案',
Tasks: '任務',
'Open Tasks': '待辦任務',
'Closed Tasks': '已完成任務',
Events: '行程',
Attachments: '附件',
Chatter: '討論',
Discussion: '討論',
Comments: '評論',
Overview: '概覽',
Summary: '摘要',
Quotes: '報價單',
Products: '產品',
Contacts: '聯絡人',
Accounts: '客戶',
Leads: '線索',
Opportunities: '商機',
Cases: '服務案例',
Campaigns: '行銷活動',
Approvals: '審批',
Documents: '文件',
Emails: '郵件',
Calls: '通話',
Meetings: '會議',
},
};
/**
* `locale` is passed in rather than re-detected. Both call sites already
* resolve it from `useObjectTranslation().language`; this function used to
* call `detectLocale()` and read `document.documentElement.lang` on its own,
* so the tab label and the chrome around it could render from two different
* language sources — they desync the moment the user switches language
* in-app, because the DOM attribute and the i18n instance update
* independently (objectui#2871).
*/
const translateLabel = (text: string, locale: string): string => {
if (!text) return text;
// Match `zh-CN`, `zh-TW`, then base `zh` → `zh-CN`.
const exact = KNOWN_LABEL_DICT[locale];
const base = locale.split('-')[0];
const fallback = base === 'zh' ? KNOWN_LABEL_DICT['zh-CN'] : undefined;
const dict = exact || fallback;
if (!dict) return text;
// Direct hit on the full string.
if (dict[text] !== undefined) return dict[text];
// Try splitting on " & " / " 和 " / " and " separators so labels like
// "Notes & Attachments" translate piece-wise to "备注 & 附件" without
// requiring every concrete combination to be enumerated in the dict.
const sepRe = /\s*(?:&|and|和)\s*/i;
if (sepRe.test(text)) {
const parts = text.split(sepRe);
const allKnown = parts.every((p) => dict[p.trim()] !== undefined);
if (allKnown) {
const sep = locale.startsWith('zh') ? '与' : ' & ';
return parts.map((p) => dict[p.trim()]).join(sep);
}
}
return text;
};
/**
* Replace `{field.path}` tokens in a template against the given data object.
* Missing fields collapse to an empty string. The result is trimmed and
* whitespace-collapsed so partial misses don't leave gaping holes.
*
* When `objectSchema` and `fieldOptionLabel` are supplied, a token that
* resolves to a select-field value gets routed through the i18n option
* label dictionary — so `subtitle: "{industry} · {type}"` renders as
* "科技 · 客户" rather than the raw enum values "technology · customer".
*/
const interpolate = (
template: string,
data: any,
objectSchema?: any,
fieldOptionLabel?: (objectName: string, fieldName: string, value: string, fallback: string) => string,
objectName?: string,
): string => {
if (!template || typeof template !== 'string') return template || '';
if (!template.includes('{')) return template;
const out = template.replace(/\{([a-zA-Z0-9_.]+)\}/g, (_m, path: string) => {
const v = path.split('.').reduce<any>((acc, seg) => (acc == null ? acc : acc[seg]), data);
if (v == null) return '';
// Skip object/array values rather than letting `String(v)` produce a
// useless "[object Object]" — this happens when a token resolves to a
// related record (e.g. `{account}` on an opportunity). Authors who want
// a field of the related record should use a deeper path
// (e.g. `{account.name}`).
if (typeof v === 'object') return '';
const raw = String(v);
// Route enum values through i18n so subtitle templates render
// translated option labels instead of raw machine-readable values.
// Only the first path segment is treated as a field name (deeper
// paths reach into related records and have their own translation
// surfaces).
if (objectSchema?.fields && fieldOptionLabel && objectName && !path.includes('.')) {
const fieldDef: any = Array.isArray(objectSchema.fields)
? objectSchema.fields.find((f: any) => f?.name === path)
: objectSchema.fields[path];
const options: any[] | undefined = fieldDef?.options;
if (Array.isArray(options)) {
const match = options.find((opt: any) => String(opt?.value ?? opt) === raw);
const fallback = match?.label ? String(match.label) : raw;
return fieldOptionLabel(objectName, path, raw, fallback);
}
}
return raw;
});
return out.replace(/\s+/g, ' ').trim();
};
// ---------------------------------------------------------------------------
// page:tabs
// ---------------------------------------------------------------------------
interface PageTabsItem {
label: any;
/**
* Stable, semantic tab identity (e.g. `details`, `related:<childObject>`) —
* used as the Radix value and as the URL token for `?tab=` sync
* (objectui#2257). Falls back to an index-derived value when absent, which
* is NOT stable across item-list changes; synthesized pages always set it.
*/
value?: string;
icon?: string;
/**
* Optional badge value rendered after the label (e.g. related-list count).
* Numbers >= 1000 are shortened to `1.2k`-style.
*/
count?: number | string;
/**
* Conditional tab (framework#2606): CEL predicate — when it evaluates FALSE
* the whole tab (header + panel) is omitted from the strip. Canonical
* ADR-0089 key only; the deprecated `visibility`/`visibleOn` aliases are
* not read on this surface. Accepts a bare CEL string or the normalized
* `{ dialect, source }` Expression envelope the spec emits at parse.
*/
visibleWhen?: string | boolean | { dialect?: string; source?: string };
children: any[];
}
const formatTabCount = (v: number | string): string => {
const n = typeof v === 'number' ? v : Number(v);
if (!Number.isFinite(n)) return String(v);
if (n >= 10000) return `${Math.round(n / 1000)}k`;
if (n >= 1000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`;
return String(n);
};
/**
* Walk a tab's children (depth-first) and return the first
* `record:related_list` schema node found. Used to auto-derive a count
* for the tab badge when the spec author didn't supply one explicitly.
*/
/**
* Walk a tab's children (depth-first) and collect every `record:related_list`
* schema node. Used to auto-derive a count for the tab badge when the spec
* author didn't supply one explicitly. Multiple lists are summed (Salesforce
* "Related" tab convention).
*/
const collectRelatedLists = (nodes: any, acc: any[] = []): any[] => {
if (!nodes) return acc;
const list = Array.isArray(nodes) ? nodes : [nodes];
for (const n of list) {
if (!n || typeof n !== 'object') continue;
if (n.type === 'record:related_list' || n.type === 'record_related_list') {
acc.push(n);
continue; // Don't descend into a related_list's own subtree.
}
const candidates = [
n.children,
n.properties?.children,
n.properties?.items,
n.body,
n.items,
];
for (const c of candidates) {
if (c) collectRelatedLists(c, acc);
}
}
return acc;
};
const PageTabsRenderer: React.FC<any> = ({ schema, className, ...props }) => {
const { designer } = splitDesignerProps(props);
const { language } = useObjectTranslation();
const rawItems: PageTabsItem[] = schema?.items || [];
// Tab visual style lives at `properties.type` ('line'|'card'|'pill') — the
// outer `schema.type` is always 'page:tabs' (the component dispatch key).
const type: 'line' | 'card' | 'pill' = schema?.properties?.type || schema?.tabStyle || 'line';
const position: 'top' | 'left' = schema?.position || 'top';
const isVertical = position === 'left';
// Auto-derive tab counts from any `record:related_list` descendant of
// each tab. The fetch is a `limit:1` find so we only consume the `total`
// — cheap relative to the eventual list render the user gets when they
// open the tab. Spec authors that pass `count` explicitly win.
//
// Counts are kept in a module-scoped store (`RelatedCountStore`) so:
// - sibling tab strips on the same record don't re-probe identical keys
// - bulk mutations elsewhere in the app (delete, create, save) can
// `RelatedCountStore.invalidate(objectName, parentId)` and every
// subscriber updates with no parent re-render.
const ctx = useRecordContext();
const parentId = ctx?.data?.id;
const ds: any = ctx?.dataSource;
// Conditional tabs (framework#2606): an item-level `visibleWhen` CEL
// predicate removes the ENTIRE tab (header + panel) when FALSE — unlike a
// child component's own `visibleWhen`, which hides only the panel content
// and leaves an empty tab header behind. Same binding environment as
// page-component `visibleWhen`: record fields (bare and via `record.` /
// `data.`), `user`/`current_user`, and page state as `page.<var>` — so tabs
// appear/disappear live as page variables change. Canonical key only
// (ADR-0089): the deprecated `visibility`/`visibleOn` aliases are not read
// on this new surface.
const predicateScope = usePredicateScope();
const { variables: pageVariables } = usePageVariables();
const recordData: any = ctx?.data;
const isItemVisible = (it: PageTabsItem): boolean => {
if (it?.visibleWhen === undefined || it?.visibleWhen === null) return true;
const evaluator = new ExpressionEvaluator({
...(recordData && typeof recordData === 'object' ? recordData : {}),
...predicateScope,
current_user: (predicateScope as any)?.user,
record: recordData,
data: recordData,
page: pageVariables,
});
// evaluateCondition is fail-open (unparseable predicate → visible) — the
// same semantics SchemaRenderer applies to component-level `visibleWhen`.
return evaluator.evaluateCondition(it.visibleWhen);
};
const visibleFlags = rawItems.map(isItemVisible);
// Keep the filtered array's identity stable while visibility is unchanged
// (usePageVariables returns a fresh object per render outside a Page), so
// the count-probe memo/effect below don't re-walk on unrelated renders.
const visibleKey = visibleFlags.join(',');
const items = React.useMemo(
() => rawItems.filter((_, i) => visibleFlags[i]),
// eslint-disable-next-line react-hooks/exhaustive-deps
[rawItems, visibleKey],
);
// Subscribe to the store version so badges re-render on invalidation /
// remote count updates, and RE-PROBE freshly-invalidated keys (#2269): the
// version is a dep of the probe effect below, so an invalidation (deleted
// cache entries) triggers a refetch instead of leaving the badge stale.
const countsVersion = useRelatedCountVersion();
// Snapshot which tabs (index → derived (objectName, relationshipField))
// need a count probe. Cached per items reference so we don't re-walk on
// every render.
const probeTargets = React.useMemo(() => {
const out = new Map<number, Array<{ objectName: string; relationshipField?: string }>>();
items.forEach((it, idx) => {
if (it.count !== undefined && it.count !== null && it.count !== '') return;
const lists = collectRelatedLists((it as any).children);
const probes: Array<{ objectName: string; relationshipField?: string }> = [];
for (const rl of lists) {
const objectName: string | undefined = rl?.properties?.objectName || rl?.objectName;
if (!objectName) continue;
const relationshipField: string | undefined =
rl?.properties?.relationshipField || rl?.relationshipField;
probes.push({ objectName, relationshipField });
}
if (probes.length > 0) out.set(idx, probes);
});
return out;
}, [items]);
React.useEffect(() => {
if (!ds || typeof ds.find !== 'function') return;
if (probeTargets.size === 0) return;
let cancelled = false;
for (const probes of probeTargets.values()) {
for (const probe of probes) {
// RelatedCountStore.fetch is internally deduplicated, so concurrent
// mounts of multiple tab strips don't generate redundant requests.
void RelatedCountStore.fetch(
(object, query) => ds.find(object, query),
probe.objectName,
probe.relationshipField,
parentId,
).catch(() => 0);
if (cancelled) return;
}
}
return () => {
cancelled = true;
};
}, [ds, probeTargets, parentId, countsVersion]);
// Compute the displayed count by reading the store for every probe target.
// useRelatedCountVersion above subscribed us to changes, so any store update —
// whether from this effect or from an external invalidate — re-renders.
const computeCount = (idx: number): number | undefined => {
const probes = probeTargets.get(idx);
if (!probes || probes.length === 0) return undefined;
let sum = 0;
let seenAny = false;
for (const p of probes) {
const v = RelatedCountStore.get(p.objectName, p.relationshipField, parentId);
if (v !== undefined) {
sum += v;
seenAny = true;
}
}
return seenAny ? sum : undefined;
};
// Prefer an item's own STABLE `value` (semantic keys like `details` /
// `related:<child>`, emitted by buildDefaultTabs — objectui#2257); fall back
// to the index-derived value for authored schemas that don't declare one.
// Stable values are what make the active tab URL-addressable: an index
// value would silently point at a different tab when the item list changes.
const itemsWithValue = items.map((it, idx) => ({
...it,
value: typeof (it as any).value === 'string' && (it as any).value !== '' ? (it as any).value : `tab-${idx}`,
// pickLocalized first (honours `{ en, zh }` / `{ default }`); translateLabel
// then maps any plain-English well-known token (Details/Related/…) to the locale.
labelStr: translateLabel(pickLocalized(it.label, language), language),
// Explicit spec count wins; otherwise fall back to the derived probe.
count: it.count !== undefined && it.count !== null && it.count !== ''
? it.count
: computeCount(idx),
}));
// Host-provided initial tab (e.g. app-shell restoring `?tab=` — the active
// tab is state that must SURVIVE this component remounting, so it cannot
// live only in Radix's internal uncontrolled state). Honored only when it
// names an actual tab; otherwise the first tab wins as before.
const requestedDefault: string | undefined = (schema as any)?.defaultTab;
const defaultValue =
(requestedDefault && itemsWithValue.some((it) => it.value === requestedDefault)
? requestedDefault
: undefined) ?? itemsWithValue[0]?.value;
// Host callback on tab switch (app-shell writes `?tab=` with replace).
const onTabChange: ((value: string) => void) | undefined = (schema as any)?.onTabChange;
// Controlled active tab so a CONDITIONAL tab can vanish under the user
// (framework#2606): when the active tab's `visibleWhen` flips FALSE (a page
// variable or record change), fall back to the first visible tab instead of
// leaving Radix pointing at a value with no trigger/panel — a blank content
// area. The user's own selection is kept whenever it is still visible, and
// restored semantics for `?tab=` (`defaultTab`) are unchanged.
const [selectedValue, setSelectedValue] = React.useState<string | undefined>(defaultValue);
const activeValue =
(selectedValue && itemsWithValue.some((it) => it.value === selectedValue)
? selectedValue
: undefined) ?? itemsWithValue[0]?.value ?? '';
const listClass = cn(
isVertical && 'flex-col h-auto items-stretch p-1',
type === 'card' && 'bg-transparent gap-1',
type === 'pill' && 'bg-muted rounded-full p-1 gap-1',
// 'line' is the default: an anchored, underline-style strip. The Shadcn
// primitive defaults to a pill-card look (bg-muted, rounded-md) that
// floats unmoored on long record pages — override it so the strip reads
// as a section anchor with a bottom border + per-trigger underline.
type === 'line' && !isVertical && 'h-auto rounded-none bg-transparent p-0 gap-4 border-b border-border w-full justify-start',
// Pin the horizontal tab strip to the top of the scroll container so
// users keep their bearings on long record pages. Skipped for vertical
// layouts where the strip is a sidebar, not a header.
!isVertical && 'sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60',
);
const triggerClass = () => cn(
isVertical && 'justify-start',
type === 'card' && 'data-[state=active]:bg-background data-[state=active]:border data-[state=active]:shadow-sm rounded-md',
type === 'pill' && 'rounded-full data-[state=active]:bg-background',
type === 'line' && !isVertical && 'rounded-none border-b-2 border-transparent bg-transparent px-1 pb-2.5 -mb-px shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:text-foreground',
);
return (
<Tabs
value={activeValue}
onValueChange={(v) => {
setSelectedValue(v);
onTabChange?.(v);
}}
orientation={isVertical ? 'vertical' : 'horizontal'}
className={cn(className, isVertical && 'flex gap-4 w-full')}
{...designer}
>
{/* Hide the tab strip entirely when there's only one tab — a single
pill labelled "Details" is visual clutter rather than an
affordance. Authors who want the strip even at length 1 can pass
`properties.alwaysShowStrip: true`. */}
{(itemsWithValue.length > 1 || schema?.properties?.alwaysShowStrip === true) && (
<TabsList className={listClass}>
{itemsWithValue.map((item) => (
<TabsTrigger key={item.value} value={item.value} className={triggerClass()}>
{item.icon && (
<LazyIcon
name={item.icon}
className="mr-1.5 h-3.5 w-3.5 shrink-0 opacity-70"
aria-hidden
/>
)}
<span>{item.labelStr}</span>
{item.count !== undefined && item.count !== null && item.count !== '' && Number(item.count) > 0 && (
<span
className="ml-1.5 inline-flex h-4 min-w-[1rem] items-center justify-center rounded-full bg-muted px-1 text-[10px] font-medium leading-none text-muted-foreground"
aria-label={`${formatTabCount(item.count)} items`}
>
{formatTabCount(item.count)}
</span>
)}
</TabsTrigger>
))}
</TabsList>
)}
{itemsWithValue.map((item) => (
<TabsContent
key={item.value}
value={item.value}
className={cn(
itemsWithValue.length > 1 ? 'mt-3' : 'mt-0',
isVertical && 'mt-0 flex-1',
)}
>
{renderChildren(item.children)}
</TabsContent>
))}
</Tabs>
);
};
ComponentRegistry.register('tabs', PageTabsRenderer, {
namespace: 'page',
skipFallback: true,
label: 'Page Tabs',
category: 'layout',
isContainer: true,
});
// ---------------------------------------------------------------------------
// page:card
// ---------------------------------------------------------------------------
const PageCardRenderer: React.FC<any> = ({ schema, className, ...props }) => {
const { designer } = splitDesignerProps(props);
const { language } = useObjectTranslation();
// Resolve the title via pickLocalized so inline-i18n shapes (`{ en, zh }`)
// render in the active locale. `labelText` only understands `{ default, value }`
// and would silently blank an `{ en, zh }` title — e.g. the Cloud Pricing
// page's per-plan name + price headings vanished in both locales.
const title = pickLocalized(schema?.title, language);
const bordered = schema?.bordered !== false;
// Accept `children` as well as `body` — every other container (grid/flex/
// section/tabs) renders `children`, so authors expect it to work here too.
// `body` kept first for back-compat with existing card schemas.
const body = schema?.body ?? schema?.children;
const footer = schema?.footer;
return (
<Card
className={cn(className, !bordered && 'border-0 shadow-none bg-transparent')}
{...designer}
>
{title && (
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
)}
{body && <CardContent>{renderChildren(body)}</CardContent>}
{footer && <CardFooter className="flex justify-between">{renderChildren(footer)}</CardFooter>}
</Card>
);
};
ComponentRegistry.register('card', PageCardRenderer, {
namespace: 'page',
skipFallback: true,
label: 'Page Card',
category: 'layout',
isContainer: true,
});
// ---------------------------------------------------------------------------
// page:accordion
// ---------------------------------------------------------------------------
interface PageAccordionItem {
label: any;
icon?: string;
collapsed?: boolean;
children: any[];
}
const PageAccordionRenderer: React.FC<any> = ({ schema, className, ...props }) => {
const { designer } = splitDesignerProps(props);
const { language } = useObjectTranslation();
const items: PageAccordionItem[] = schema?.items || [];
const allowMultiple = !!schema?.allowMultiple;
// Variants:
// - `flush` (default): no per-item border. Lets the inner content (e.g.
// a `record:related_list` Card) provide its own containment so the
// accordion doesn't fight with nested visuals.
// - `card`: legacy bordered look. Authors opt in by setting
// `variant: 'card'` (or `properties.variant: 'card'`) on the schema.
const variant: 'flush' | 'card' =
schema?.variant ?? schema?.properties?.variant ?? 'flush';
const itemClass = variant === 'flush' ? 'border-b last:border-b-0' : undefined;
const itemsWithValue = items.map((it, idx) => ({
...it,
value: `panel-${idx}`,
labelStr: translateLabel(pickLocalized(it.label, language), language),
}));
const defaultOpen = itemsWithValue
.filter((it) => it.collapsed === false)
.map((it) => it.value);
// Radix Accordion has separate single/multiple variants; render the right
// one without trying to share a generic prop bag.
const commonChildren = itemsWithValue.map((item) => (
<AccordionItem key={item.value} value={item.value} className={itemClass}>
<AccordionTrigger className="text-sm font-semibold tracking-tight hover:no-underline">
{item.labelStr}
</AccordionTrigger>
<AccordionContent>{renderChildren(item.children)}</AccordionContent>
</AccordionItem>
));
if (allowMultiple) {
return (
<Accordion
type="multiple"
defaultValue={defaultOpen}
className={className}
{...designer}
>
{commonChildren}
</Accordion>
);
}
return (
<Accordion
type="single"
collapsible
defaultValue={defaultOpen[0]}
className={className}
{...designer}
>
{commonChildren}
</Accordion>
);
};
ComponentRegistry.register('accordion', PageAccordionRenderer, {
namespace: 'page',
skipFallback: true,
label: 'Page Accordion',
category: 'layout',
isContainer: true,
});
// ---------------------------------------------------------------------------
// page:section — thin wrapper used inside regions for grouping children.
// ---------------------------------------------------------------------------
const PageSectionRenderer: React.FC<any> = ({ schema, className, ...props }) => {
const { designer } = splitDesignerProps(props);
return (
<section
className={cn('space-y-4', className)}
{...designer}
>
{renderChildren(schema?.children || schema?.body)}
</section>
);
};
ComponentRegistry.register('section', PageSectionRenderer, {
namespace: 'page',
skipFallback: true,
label: 'Page Section',
category: 'layout',
isContainer: true,
});
// ---------------------------------------------------------------------------
// page:header — title row + optional subtitle + breadcrumb/action slots.
// Action ids are intentionally not resolved here; that will land alongside
// the upcoming `record:quick_actions` renderer.
// ---------------------------------------------------------------------------
/**
* Strip dangling connectors that survive when a `titleFormat` interpolates
* with one side empty — e.g. `{number} - {name}` becomes `CTR-0001 -` when
* `name` is blank. Removes a trailing/leading hyphen / middle-dot / colon /
* slash / pipe (optionally surrounded by whitespace) and collapses
* adjacent whitespace into a single space. Idempotent.
*
* Exported for unit tests.
*/
export function cleanupTitleSeparators(s: string): string {
if (!s) return s;
let out = s;
// Repeatedly trim trailing connectors. Loop so chains like " - · " all peel.
for (let i = 0; i < 4; i += 1) {
const next = out.replace(/[\s\u00A0]*[-·:|/–—][\s\u00A0]*$/u, '').trimEnd();
if (next === out) break;
out = next;
}
for (let i = 0; i < 4; i += 1) {
const next = out.replace(/^[\s\u00A0]*[-·:|/–—][\s\u00A0]*/u, '').trimStart();
if (next === out) break;
out = next;
}
// Collapse double-separators in the middle (rare, but happens when the
// middle field of a 3-part format is empty: "A - - B" -> "A - B").
out = out.replace(/([-·:|/–—])[\s\u00A0]*\1/gu, '$1');
// Collapse runs of whitespace.
out = out.replace(/[\s\u00A0]+/g, ' ').trim();
return out;
}
/**
* One-time diagnostics for header-action `visible` / `hidden` predicates
* (#2358). Both warn-once per (action, predicate) pair so re-renders don't
* spam the console, mirroring ActionEngine's `warnHiddenPredicate` (#2183).
*/
const _warnedHeaderPredicates = new Set<string>();
/** Warn when a predicate THREW — the action is fail-closed hidden. */
function warnHeaderActionPredicate(name: unknown, source: string, err: unknown): void {
const key = `throw::${String(name)}::${source}`;
if (_warnedHeaderPredicates.has(key)) return;
_warnedHeaderPredicates.add(key);
const msg = err instanceof Error ? err.message : String(err);
console.warn(
`[page:header] action "${String(name)}" hidden: its predicate threw — ${msg}. ` +
`Predicate: ${source}. Header-action predicates evaluate against ` +
`{ record, user, os.user, ctx.user, app, features, <record fields> }.`,
);
}
/**
* Warn when a predicate references `record.<field>` keys that are absent from
* the loaded record payload (#2358 trap 3): the server strips `hidden: true`
* fields from detail payloads, so such a predicate silently resolves to
* `undefined` and fail-closed hides the action with no error to catch. A key
* that is present-but-null does NOT trigger this (legitimately empty field).
* Skipped while the record is empty/loading to avoid false positives.
*/
function warnMissingRecordFields(name: unknown, source: string, record: unknown): void {
if (!record || typeof record !== 'object' || Object.keys(record as object).length === 0) return;
const re = /\brecord\.([A-Za-z_][A-Za-z0-9_]*)/g;
const missing: string[] = [];
for (let m = re.exec(source); m; m = re.exec(source)) {
if (!(m[1] in (record as Record<string, unknown>)) && !missing.includes(m[1])) missing.push(m[1]);
}
if (missing.length === 0) return;
const key = `missing::${String(name)}::${source}`;
if (_warnedHeaderPredicates.has(key)) return;
_warnedHeaderPredicates.add(key);
console.warn(
`[page:header] action "${String(name)}" predicate references record field(s) ` +
`not present in the record payload: ${missing.join(', ')}. Predicate: ${source}. ` +
`Hidden (hidden: true) fields are stripped from detail payloads server-side, ` +
`so a predicate gating on one may evaluate to a hide-by-default verdict.`,
);
}
const PageHeaderRenderer: React.FC<any> = ({ schema, className, ...props }) => {
const { designer } = splitDesignerProps(props);
const ctx = useRecordContext();
// Record-level inline-edit session (objectui#2572 item 4): while a shared
// inline draft is active, header actions flagged `disableDuringInlineEdit`
// (the host's Edit CTA) grey out so the classic form-edit surface can't be
// stacked on top of the live draft — two competing edit sessions with no
// reconciliation. `useInlineEdit` is null outside an InlineEditProvider
// (non-record pages), which leaves everything enabled.
const inlineEditing = !!useInlineEdit()?.editing;
// Ambient host scope (signed-in user / app / features), fed by app-shell's
// ExpressionProvider. Needed so header-action `visible` CEL predicates can
// gate on `ctx.user.*` (e.g. sys_environment "Change Plan (admin)" →
// `ctx.user.isPlatformAdmin == true`). Without it the action-visibility
// evalCtx below only had record fields, so every `ctx.user`-gated header
// action was silently filtered out.
const predicateScope = usePredicateScope();
const { execute } = useAction();
// [ADR-0066 D4 / framework#3923] Shared capability gate — see filterAction.
const mayInvoke = useCapabilityGate();
const isMobile = useIsMobile();
const { objectLabel: tObjectLabel, actionLabel: tActionLabel } = useObjectLabel();
const { fieldOptionLabel } = useSafeFieldLabel();
const { language } = useObjectTranslation();
// Spec bridge may either inline `properties.*` onto the node or preserve
// the raw bag (see record:quick_actions for the same pattern). Read from
// both so a `{ properties: { title } }` schema is rendered correctly.
const titleSrc = schema?.title ?? schema?.properties?.title;
const subtitleSrc = schema?.subtitle ?? schema?.properties?.subtitle;
const headerObjectSchema: any = (ctx as any)?.objectSchema;
const headerObjectName: string | undefined = ctx?.objectName || headerObjectSchema?.name;
const explicitTitle = interpolate(
pickLocalized(titleSrc, language),
ctx?.data,
headerObjectSchema,
fieldOptionLabel,
headerObjectName,
);
const subtitle = interpolate(
pickLocalized(subtitleSrc, language),
ctx?.data,
headerObjectSchema,
fieldOptionLabel,
headerObjectName,
);
const breadcrumb = (schema?.breadcrumb ?? schema?.properties?.breadcrumb) !== false;
// Schema-level opt-outs let authors keep the historic "bare h1" header
// when they don't want a record chip (e.g. a non-record landing page).
const disableRecordChrome =
schema?.recordChrome === false || schema?.properties?.recordChrome === false;
const showStar = schema?.showStar !== false && schema?.properties?.showStar !== false;
const showCopyId = schema?.showCopyId !== false && schema?.properties?.showCopyId !== false;
// Inline header actions — authored pages embed action buttons directly on
// `page:header.actions` (or `.properties.actions`). Custom CRM record
// detail pages (lead → Convert Lead, opportunity → Mark Won/Lost, …)
// rely on this slot. Without this rendering they would silently disappear.
const rawHeaderActions = schema?.actions ?? schema?.properties?.actions;
// System actions (Edit / Share / Delete) injected by the host via
// `RecordContext.headerSystemActions`. Appended AFTER authored actions
// and deduplicated by `name` so the host can always supply them
// regardless of whether the page schema is authored (full Lightning) or
// synthesised. Authored pages may opt out by omitting them at the host
// or by adding a name-clashing action of their own.
const hostSystemActions = (ctx as any)?.headerSystemActions as any[] | undefined;
const headerActions = React.useMemo<any[]>(() => {
const recordData: any = ctx?.data;
// Spread record fields as top-level bindings so author-friendly CEL like
// `status == "active"` or `is_default != true` resolves directly. Without
// this, bare identifiers fall through to the JS global scope and silently
// resolve to e.g. `window.status` (empty string), causing every action
// with a `visible` expression to be filtered out.
// Carry the ambient host scope (user / app / features) and expose the
// canonical `ctx.*` namespace so `ctx.user.isPlatformAdmin`-style
// predicates resolve — alongside the record fields spread for bare
// `status`/`is_default` CEL.
const scopeUser = (predicateScope as any)?.user;
const evalCtx = {
...(recordData && typeof recordData === 'object' ? recordData : {}),
record: recordData,
data: recordData,
user: scopeUser,
// Server-CEL-parity identity alias (#2358 trap 1): the spec's canonical
// CEL identity scope is `os.user.*`, so a predicate authored against the
// server dialect resolves here too instead of throwing (fail-closed).
os: (predicateScope as any)?.os ?? { user: scopeUser },
ctx: {
user: scopeUser,
record: recordData,
data: recordData,
app: (predicateScope as any)?.app,
features: (predicateScope as any)?.features,
},
};
const evaluator = new ExpressionEvaluator(evalCtx);
// Fail-closed BUT diagnosable (#2358): a throwing `visible`/`hidden`
// predicate still hides the action, but now warns once (action name +
// predicate + reason) instead of silently swallowing the error — a
// predicate that throws is almost always an authoring bug (wrong scope
// variable, bare field reference), not a real precondition.
const evalExpr = (src: string, actionName: unknown): any => {
try {
return evaluator.evaluateExpression(src);
} catch (err) {
warnHeaderActionPredicate(actionName, src, err);
return undefined;
}
};
const filterAction = (a: any): boolean => {
// [ADR-0066 D4 / framework#3923] Capability gate — the UI half of the
// dual-surface `requiredPermissions` contract.
//
// `page:header` filters its own actions rather than going through
// `ActionEngine.getActionsForLocation`, so the engine's gate never ran on
// the ONE surface `record_header` / `record_more` actions live on: a
// button declaring a capability nobody holds rendered, and only the
// server's 403 stopped it — and only for platform action routes, never
// for a `type: 'api'` action pointed at a custom endpoint. Same rule as
// the engine, so the two surfaces can't disagree: hide unless the caller
// holds ALL declared capabilities.
//
// Fail-OPEN when the caller's capabilities are unknown (no
// ActionProvider user, no host predicate scope) — unknown is not denied,
// and hiding on missing data is the worse regression.
if (!mayInvoke(a?.requiredPermissions)) return false;
// Location filter — when `locations` is declared, require record_header
// or record_more (the latter renders in the header's ⋯ overflow menu —
// see renderHeaderActions; #2358 trap 2). Missing/empty `locations`
// defaults to "show here" since the action is inlined on the header
// itself.
if (Array.isArray(a?.locations) && a.locations.length > 0) {
if (!a.locations.includes('record_header') && !a.locations.includes('record_more')) {
return false;
}
}
// Boolean / expression visibility — supports both `visible: false`,
// `visible: 'record.status == "open"'` and the structured shape
// `visible: { dialect: 'cel', source: '…' }` used by spec authors.
const v = a?.visible;
if (v !== undefined && v !== null) {
if (typeof v === 'boolean') {
if (!v) return false;
} else {
const src =
typeof v === 'string'
? v
: (v && typeof v === 'object' && typeof (v as any).source === 'string')
? (v as any).source
: null;
if (src) {
warnMissingRecordFields(a?.name, src, recordData);
const result = evalExpr(src, a?.name);
// On evaluation error (undefined), hide the action rather than
// risk surfacing a destructive button in the wrong state.
if (!result) return false;
}
}
}
// `hidden` is the mirror image — when truthy, skip.
const h = a?.hidden;
if (h !== undefined && h !== null) {
if (typeof h === 'boolean') {
if (h) return false;
} else {
const src =
typeof h === 'string'
? h
: (h && typeof h === 'object' && typeof (h as any).source === 'string')
? (h as any).source
: null;
if (src) {
warnMissingRecordFields(a?.name, src, recordData);
const result = evalExpr(src, a?.name);
if (result) return false;
}
}
}
return true;
};
const authored = Array.isArray(rawHeaderActions)
? rawHeaderActions.filter(filterAction)
: [];
const system = Array.isArray(hostSystemActions)
? hostSystemActions.filter(filterAction)
: [];
// Dedupe by `name` — authored wins.
const seen = new Set<string>();
const out: any[] = [];
for (const a of [...authored, ...system]) {
const key = (a?.name || a?.id || '') as string;
if (key && seen.has(key)) continue;
if (key) seen.add(key);
out.push(a);
}
// Order the merged list before the inline/overflow split — the same rule
// action:bar applies (objectui#2339):
// 1. `order` ascending (unset = 0; lower = more prominent)
// 2. `variant === 'primary'` as a tie-break within equal order
// 3. original registration order (stable) for the remaining ties
// This is what lets metadata declare which actions claim the inline
// button slots vs. the `⋯` overflow menu (objectui#2361).
const needsOrdering = out.some(
(a) => a?.order !== undefined || a?.variant === 'primary',
);