Repository navigation
Expand file tree
/
Copy pathObjectForm.tsx
More file actions
1949 lines (1849 loc) · 97.5 KB
/
Copy pathObjectForm.tsx
File metadata and controls
1949 lines (1849 loc) · 97.5 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.
*/
/**
* ObjectForm Component
*
* A smart form component that generates forms from ObjectQL object schemas.
* It automatically creates form fields based on object metadata.
*/
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import type { ObjectFormSchema, FormField, FormSchema, DataSource } from '@object-ui/types';
import { SchemaRenderer, useSafeFieldLabel } from '@object-ui/react';
import { pickLocalized, useObjectTranslation, useLocalization } from '@object-ui/i18n';
import { useRecordInvalidation } from './recordInvalidation';
import { mapFieldTypeToFormType, buildValidationRules, formatFileSize, fieldHelpText } from '@object-ui/fields';
import { useIsMobile, toast } from '@object-ui/components';
import { resolveSuccessNavigate } from './successBehavior';
import { resolveSubmitRedirect, submitRedirectScope } from './submitRedirect';
import {
useSubmitRedirectNavigation,
type PendingSubmitRedirect,
} from './submitRedirectNavigation';
import { usePermissions } from '@object-ui/permissions';
import { sectionPredicateUnsupportedWarning } from './sectionPredicateDiagnostic';
import {
warnUnresolvedTopLevelField,
warnSectionMemberExcludedByFields,
buildSectionFields,
sectionEntryName,
type SectionFieldsContext,
} from './sectionFields';
import { TabbedForm } from './TabbedForm';
import { WizardForm } from './WizardForm';
import { useFormChromeTranslation } from './formChrome';
import { MasterDetailForm } from './MasterDetailForm';
import {
applyAutoLayout,
filterAutoGeneratedFields,
filterSystemFields,
sectionedGridLayout,
} from './autoLayout';
import { deriveFieldGroupSections, projectSectionDivider, resolveSectionCollapse, type FormFieldWithGroup } from './fieldGroups';
import { mergeCustomFields } from './customFieldsMerge';
import { hasSectionGroupReference, resolveSectionGroupReferences } from './sectionGroups';
import {
snapshotLoadedRecord,
advanceLoadedRecord,
type LoadedRecordSnapshot,
} from './sanitize';
import { formWritePayload } from './writePayload';
import { applyFieldPermissions, closedFormAffordance, fieldWriteGate, gateFormFields } from './fieldWriteGate';
import { RecordFieldAccessForForm } from './recordFieldAccess';
import { ClosedAffordanceNotice } from './closedAffordanceNotice';
import { resolveInitialRecord } from './initialRecord';
import { hasInlineFieldSource, isInlineFieldDef, noSubmitTargetError } from './submitTarget';
import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate';
import {
schemaDefaultValues,
isCreateFormMode,
isRequiredInForm,
} from './schemaDefaults';
import { useOccSave } from './occSave';
import {
NO_LOAD_FAILURES,
beginLoadRun,
shownLoadFailure,
type LoadFailures,
type LoadRunSeq,
} from './loadFailure';
/**
* Props of the `ObjectForm` React component.
*
* Renamed off the bare `ObjectFormProps` (objectui#4650): from 17.0.0
* `@objectstack/spec/ui` owns that name, where it is the AUTHORED props
* document of the `object-form` element — `z.input<typeof
* ObjectFormPropsSchema>`, i.e. serialisable authoring keys only. This is the
* RENDERER's props: a live `dataSource`, submit/cancel callbacks and imperative
* handles, 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 `ObjectFormProps` as a deprecated alias of this type, so no
* importer breaks. Tripwire: `__tests__/spec-symbol-4650.test.ts`.
*/
export interface ObjectFormComponentProps {
/**
* The schema configuration for the form
*/
schema: ObjectFormSchema;
/**
* Data source (ObjectQL or ObjectStack adapter)
* Optional when using inline field definitions (customFields or fields array with field objects)
*/
dataSource?: DataSource;
/**
* Additional CSS class
*/
className?: string;
}
/**
* Fold the structured, spec-aligned `buttons`/`defaults` surface
* (`@objectstack/spec` FormViewSchema; framework#1894 / objectstack-ai/objectstack#2998) down onto the
* flat renderer props ObjectForm and its variants read
* (`showSubmit`/`submitText`/`showCancel`/`cancelText`/`initialValues`). This is the objectui-side consumer of those spec keys — it
* is what lets them flip `experimental → live` in the spec liveness ledger.
*
* Spec is the authored surface, but an explicitly-set flat key still wins so
* existing metadata that authored the deprecated flat keys is unchanged.
* Returns the input untouched when neither structured key is present (the
* common case), so there is no allocation on the hot path.
*/
function foldFormButtons(schema: ObjectFormComponentProps['schema']): ObjectFormComponentProps['schema'] {
const buttons = (schema as { buttons?: ObjectFormSchema['buttons'] }).buttons;
const defaults = (schema as { defaults?: Record<string, any> }).defaults;
if (!buttons && !defaults) return schema;
const s = schema as Record<string, any>;
const out: Record<string, any> = { ...s };
if (buttons?.submit?.show !== undefined && s.showSubmit === undefined) out.showSubmit = buttons.submit.show;
if (buttons?.submit?.label != null && s.submitText === undefined) out.submitText = buttons.submit.label;
if (buttons?.cancel?.show !== undefined && s.showCancel === undefined) out.showCancel = buttons.cancel.show;
if (buttons?.cancel?.label != null && s.cancelText === undefined) out.cancelText = buttons.cancel.label;
if (defaults && s.initialValues === undefined) out.initialValues = defaults;
return out as ObjectFormComponentProps['schema'];
}
/**
* The seven members `ComponentPropsMap['object-form']` in `@objectstack/spec`
* declares as `I18nLabel`: a plain string or an inline per-locale map such as
* `{ en: 'Save order', 'zh-CN': '保存订单' }` (objectui#10993).
*/
const OBJECT_FORM_LABEL_KEYS = [
'title',
'description',
'submitText',
'cancelText',
'nextText',
'prevText',
'successMessage',
] as const;
type ObjectFormLabelKey = (typeof OBJECT_FORM_LABEL_KEYS)[number];
/**
* `ObjectFormSchema` as every presentation below reads it: the seven
* `I18nLabel` members already resolved to a string. A homomorphic mapped type
* rather than `Omit`, because `BaseSchema`'s index signature made `Omit`
* collapse to that signature and drop every declared member (until
* objectui#8347 removed it).
*/
type LocalizedObjectFormSchema = {
[K in keyof ObjectFormSchema]: K extends ObjectFormLabelKey ? string : ObjectFormSchema[K];
};
/**
* Resolve the seven `I18nLabel` members against the active UI language — the
* source `ObjectMetricWidget` and `MasterDetailForm` resolve their own
* `I18nLabel` members against — before any presentation reads them.
*
* Read raw, a map was a React child in every presentation that renders one
* (`submitText` / `cancelText` on the form's buttons, `nextText` / `prevText`
* on the wizard's, `title` / `description` as the drawer and modal headings)
* and threw "Objects are not valid as a React child", taking the whole form
* down; `successMessage` went into the success toast.
*
* Only the map arm is touched: a string, or any value that is not an object,
* is handed on exactly as authored. A map with no usable entry resolves to
* `undefined`, so each presentation's own default ('Create', 'Cancel', 'Next',
* …) shows. Returns its input untouched when no member is a map, so there is
* no allocation on the hot path.
*/
function localizeFormLabels(
schema: ObjectFormComponentProps['schema'],
language: string,
): LocalizedObjectFormSchema {
let out: Record<string, unknown> | null = null;
for (const key of OBJECT_FORM_LABEL_KEYS) {
const value: unknown = schema[key];
if (value === null || typeof value !== 'object') continue;
out ??= { ...schema };
out[key] = pickLocalized(value, language) || undefined;
}
return (out ?? schema) as LocalizedObjectFormSchema;
}
/**
* ObjectForm Component
*
* Renders a form for an ObjectQL object with automatic schema integration.
*
* @example
* ```tsx
* <ObjectForm
* schema={{
* type: 'object-form',
* objectName: 'users',
* mode: 'create',
* fields: ['name', 'email', 'status']
* }}
* dataSource={dataSource}
* />
* ```
*/
/**
* An `edit` form for a stored record answers its field locks from that record
* (objectstack#26594) — see `recordFieldAccess.tsx`.
*/
export const ObjectForm: React.FC<ObjectFormComponentProps> = ({ schema, ...rest }) => (
<RecordFieldAccessForForm schema={schema} dataSource={rest.dataSource}>
{/* `schema=` by name, so the handler-key census follows the document into the body. */}
<ObjectFormBody schema={schema} {...rest} />
</RecordFieldAccessForForm>
);
/**
* The schema every layout reads, prepared ONCE above the layout fork: the
* structured `buttons` / `defaults` folded onto the flat keys, the seven
* `I18nLabel` members resolved, legacy `groups` normalised to `sections`,
* field-level permissions applied and `{ group }` sections resolved — plus the
* section-label translator every section map uses.
*
* A hook of its own because two renderers prepare the same schema: this file's
* `ObjectForm` (the `simple` / `tabbed` / `wizard` layouts) and
* `ObjectFormContainer`, which supplies the drawer or modal container an
* `object-form` block asks for with `formType` (ADR-0050 Decision 4 — the
* container is the caller's, never the form's).
*/
export function usePreparedFormSchema(
rawSchema: ObjectFormComponentProps['schema'],
dataSource: ObjectFormComponentProps['dataSource'],
) {
const perms = usePermissions();
// ── `sections[].group` — the ADR-0085 §5 REFERENCE form (objectui#7051) ───
//
// A section may point `group` at one of the object's declared `fieldGroups`
// instead of enumerating members (`@objectstack/spec` 17.3.0,
// objectstack#13855). Resolving it needs the OBJECT definition, and this
// preparation — unlike the layout bodies it feeds — has never loaded one.
//
// It is resolved HERE, above the routing, on purpose: every variant's
// `sections` prop is rebuilt key by key in the maps below, so a `group` left
// in place would be dropped before any container could see it, and each
// container would need its own copy of the resolution. One site above the
// fork is what makes "one assembler" true for all six layouts at once —
// including `simple`, whose section loop read `section.fields.map(...)`
// unguarded and threw `Cannot read properties of undefined (reading 'map')`
// on a spec-legal `{ group }` section, blanking the WHOLE form (measured on
// this file at `origin/main`; the other five silently dropped the section
// instead, because `buildSectionFields` spells the same read `?? []`).
//
// The load is gated on an authored `group` being present, so a form that
// does not use the reference form issues no request and takes no new path.
const needsGroupLayout = hasSectionGroupReference((rawSchema as any)?.sections);
const canResolveGroups = typeof (dataSource as any)?.getObjectSchema === 'function';
const [groupObjectDef, setGroupObjectDef] = useState<any>(null);
useEffect(() => {
if (!needsGroupLayout || !canResolveGroups) return;
let alive = true;
Promise.resolve((dataSource as any).getObjectSchema(rawSchema.objectName))
.then((def: any) => { if (alive) setGroupObjectDef(def ?? null); })
// A failed load leaves the references unresolved (their sections render
// empty). It is deliberately NOT reported as a dangling reference: the
// body below owns the load error for the object, and claiming the group
// does not exist would be a second, wrong diagnosis of one failure.
.catch(() => { if (alive) setGroupObjectDef(null); });
return () => { alive = false; };
}, [needsGroupLayout, canResolveGroups, dataSource, rawSchema.objectName]);
// The UI language the seven `I18nLabel` members resolve against — see
// `localizeFormLabels` (objectui#10993).
const { language } = useObjectTranslation();
// Apply field-level permissions to the entire schema (sections + flat
// fields) BEFORE dispatching to any variant. This way all variants
// (Tabbed/Wizard/Simple here, Drawer/Modal through `ObjectFormContainer`)
// transparently honour FLS.
// Fail-open when no provider mounted (perms.isLoaded false).
const schema = useMemo<LocalizedObjectFormSchema>(() => {
// framework#1894 / objectstack-ai/objectstack#2998 (ADR-0078): the authored @objectstack/spec
// FormViewSchema carries the structured `buttons.{submit,cancel}.
// {show,label}` + `defaults` surface (`buttons.reset` retired, #27153), but this renderer historically read
// only the flat `showSubmit`/`submitText`/…/`initialValues`. Fold the
// structured shape down onto those flat props FIRST so every downstream
// read (and every variant we dispatch `schema` into) sees it. An
// explicitly-set flat key still wins (deprecated back-compat).
//
// objectui#10993: the seven `I18nLabel` members are resolved HERE, above the
// `formType` fork, for the reason `sections[].group` is resolved above it:
// every presentation reads them, so one site covers all of them. Folded
// first, so a `buttons.*.label` lands on the flat key before it resolves.
const folded = localizeFormLabels(foldFormButtons(rawSchema), language);
// #2545: spec FormViewSchema defines `groups` as a legacy alias of
// `sections`, and this renderer only ever consumes `sections` — normalize
// so groups-only metadata actually renders (it used to be silently
// ignored). Legacy shape maps `title`→`label`, `defaultCollapsed`→`collapsed`.
const legacyGroups = (folded as any).groups;
const base: LocalizedObjectFormSchema =
!folded.sections?.length && Array.isArray(legacyGroups) && legacyGroups.length
? {
...folded,
sections: legacyGroups.map((g: any) => ({
label: g.title ?? g.label,
description: g.description,
collapsible: g.collapsible,
collapsed: g.defaultCollapsed ?? g.collapsed,
fields: g.fields ?? [],
})),
}
: folded;
/**
* Resolve every `{ group }` section into the section that group declares.
*
* Returns its input UNCHANGED — same array reference — when no section
* uses the reference form, so this memo cannot perturb any existing form.
*/
const withGroups = (s: LocalizedObjectFormSchema) => {
const resolved = resolveSectionGroupReferences(s.sections as any, {
objectName: s.objectName,
formType: s.formType,
objectDef: groupObjectDef,
resolvable: canResolveGroups,
});
return resolved === (s.sections as any) ? s : { ...s, sections: resolved as any };
};
if (!perms?.isLoaded) return withGroups(base);
// ONE render gate, shared with `ModalForm` and `DrawerForm` — see
// `fieldWriteGate.ts` for why the copy each container used to carry is the
// defect rather than the style (`80c54122e`).
const filterArr = (arr?: any[]) =>
applyFieldPermissions(arr, { perms, objectName: base.objectName, mode: base.mode });
return withGroups({
...base,
fields: filterArr(base.fields as any[]),
sections: base.sections?.map((s: any) => ({
...s,
fields: filterArr(s.fields),
})),
} as LocalizedObjectFormSchema);
}, [rawSchema, perms, groupObjectDef, canResolveGroups, language]);
const { sectionLabel } = useSafeFieldLabel();
const tSec = (s: any) =>
s?.name ? sectionLabel(schema.objectName, s.name, s.label || s.name) : s?.label;
return { schema, tSec };
}
const ObjectFormBody: React.FC<ObjectFormComponentProps> = ({
schema: rawSchema,
dataSource,
}) => {
const { schema, tSec } = usePreparedFormSchema(rawSchema, dataSource);
// Master-detail: when the schema declares inline child collections, render as
// a master-detail form (parent fields + child grids, persisted atomically).
// This lets a plain form view become master-detail by config — no bespoke
// page. Skipped in view mode (read-only detail uses related lists instead).
// A drawer or modal container never reaches here: `ObjectFormContainer`
// hands it to DrawerForm/ModalForm, which host the master-detail form INSIDE
// their envelope.
const routesToMasterDetail = !!(schema as any).subforms?.length && schema.mode !== 'view';
// ── objectui#6237 diagnostic, now scoped to the ONE arm still inert ────────
// The interim diagnostic ruled on 2026-08-29 covered `tabbed` AND `wizard`,
// the two routes that dropped an authored section `visibleWhen`. The tabbed
// arm now HONOURS it (the map below copies the key, `TabbedForm` puts it on
// the tab it synthesises, and the renderer evaluates it), so warning about it
// would be a false alarm about a working feature — the same boundary the four
// control rows of the diagnostic's pin defend. `wizard` stays inert by
// DESIGN, not by omission: a step predicate is a different contract, not a
// port (see `WizardStepConfig`), so its gap is still reported rather than
// silently dropped.
//
// Deliberately NOT reported for the master-detail branch: that branch re-enters
// `ObjectForm` through `MasterDetailForm`'s parent schema, which is where the
// real layout is decided (a master-detail `wizard` parent renders `simple`,
// which DOES honour the predicate). Reporting here as well would double-report
// the tabbed parent and false-report the wizard one.
const inertPredicateLayout = !routesToMasterDetail && schema.formType === 'wizard'
? schema.formType
: null;
// Joined to a string on purpose: the effect's deps must be primitives, or a
// fresh array identity each render would re-report on every keystroke.
const inertPredicateSections = (schema.sections ?? [])
.filter((s: any) => s?.visibleWhen != null)
.map((s: any) => s?.name || s?.label || '(unnamed)')
.join(', ');
useEffect(() => {
if (!inertPredicateLayout || !inertPredicateSections) return;
console.warn(sectionPredicateUnsupportedWarning(inertPredicateLayout, inertPredicateSections));
}, [inertPredicateLayout, inertPredicateSections]);
if (routesToMasterDetail) {
return (
<MasterDetailForm
schema={{
type: 'object-master-detail-form',
objectName: schema.objectName,
mode: schema.mode === 'edit' ? 'edit' : 'create',
recordId: schema.recordId,
// Forward prefilled header values so create-mode wizards (e.g. lead
// conversion) seed the parent fields, not just plain forms.
initialValues: (schema as any).initialValues,
initialData: (schema as any).initialData,
formType: schema.formType === 'tabbed' ? 'tabbed' : 'simple',
// objectstack-ai/objectstack#26843 — the tabbed header's opening tab
// and strip position, and the field layout, which this rebuild
// dropped before the header form could read them.
defaultTab: schema.defaultTab,
tabPosition: schema.tabPosition,
layout: schema.layout,
sections: schema.sections as any,
fields: schema.fields as any,
title: schema.title,
submitText: schema.submitText,
cancelText: schema.cancelText,
// Forward the host's submit-visibility so a non-persisting preview
// can hide the master-detail Save bar (it owns the only Save here).
showSubmit: (schema as any).showSubmit,
details: (schema as any).subforms,
onSuccess: schema.onSuccess,
onError: schema.onError,
// The master-detail action bar draws Cancel only when handed an
// `onCancel`, so a hidden cancel button is no handler
// (objectstack-ai/objectstack#26843).
onCancel: schema.showCancel === false ? undefined : schema.onCancel,
className: schema.className,
}}
dataSource={dataSource}
/>
);
}
// Route to specialized form variant based on formType
if (schema.formType === 'tabbed' && schema.sections?.length) {
return (
<TabbedForm
schema={{
...schema,
formType: 'tabbed',
sections: schema.sections.map(s => ({
name: s.name,
label: tSec(s),
description: s.description,
columns: s.columns,
// `?? []` because `ObjectFormSection.fields` is OPTIONAL since objectui#7051
// — `group` is the other way a section declares its members. A `{ group }`
// section has already been resolved into one carrying `fields` before this
// map runs (and an unresolvable one into `fields: []`), so this default is
// reached only by a programmatic caller sending a section with neither,
// which the spec door refuses. These per-layout config types stay
// `fields`-required on purpose: they are the programmatic React-mount
// shapes, not the authorable surface, and the reference form is resolved
// above them.
fields: s.fields ?? [],
// ADR-0089 section predicate (objectui#6237) — key-by-key rebuild,
// so an uncopied key is silently dropped before TabbedForm ever
// sees it, exactly as it was on this route until this card. The
// drawer/modal maps (`ObjectFormContainer`) have carried it since
// #6111; this is the tabbed arm joining them.
//
// Read WITHOUT an `as any` cast on purpose, unlike those two:
// `ObjectFormSection.visibleWhen` is declared, so the compiler is
// able to catch a rename here. Through a cast it would keep
// compiling and silently copy `undefined` — the exact silent-drop
// failure this line exists to fix.
visibleWhen: s.visibleWhen,
visibleWhenFault: s.visibleWhenFault,
// ⛔ `className` / `gridClassName` are DELIBERATELY not copied here
// or at any of the six sibling sites below — objectstack#13626,
// maintainer ruling 2026-09-01 (director decision batch C):
// "retire the reads".
//
// The two keys sit on the SDUI-only side of the authorable
// boundary: `@objectstack/spec` deliberately does NOT declare them
// on the form-view/section surface (see the "Deliberately NOT
// declared" note in its `component.zod.ts`), and the
// authorable-surface ledger carries no entry for them. They were
// nevertheless reached off the parsed view through `as any` — the
// boundary declared on one side and crossed on the other.
//
// Declaring them instead was weighed and NOT adopted: it would
// formally invite free Tailwind strings into authored metadata,
// the exact class the boundary exists to keep out — and per
// ADR-0065 / ADR-0080 (rev. 2026-06-30) utility classNames in
// runtime metadata are never scanned by the build-time Tailwind,
// so they silently produce no CSS. If per-view styling becomes a
// real product need it gets an explicit controlled token surface,
// not two leaked keys.
//
// ⚠️ `ObjectFormSection` (this repo's own `@object-ui/types`) no
// longer declares either key (objectui#7200), so an uncast
// `className: s.className` fails to compile here. A CAST read —
// the shape the seven retired sites had — still would, and JSON
// metadata carries whatever an author wrote. The omission is
// therefore pinned behaviourally, not by a source grep —
// `__tests__/sectionStyleKeysRetired-13626.test.tsx`.
})),
defaultTab: schema.defaultTab,
tabPosition: schema.tabPosition,
}}
dataSource={dataSource}
className={schema.className}
/>
);
}
if (schema.formType === 'wizard' && schema.sections?.length) {
return (
<WizardForm
schema={{
...schema,
formType: 'wizard',
// Key-by-key rebuild into `WizardStepConfig`, the wizard's OWN step
// shape: `visibleWhen` / `collapsible` / `collapsed` are deliberately
// not copied — wizard steps carry no predicate slot and do not
// collapse (objectui#6237 split; upgraded to a spec-door parse
// refusal by objectstack#13622 D2, ruled 2026-08-31, so authored
// metadata carrying them never reaches this map). The predicate drop
// is additionally reported above for the callers the spec door
// cannot see (programmatic SDUI, pre-tightening metadata).
sections: schema.sections.map(s => ({
name: s.name,
label: tSec(s),
description: s.description,
columns: s.columns,
// `?? []` — see the tabbed arm above (objectui#7051).
fields: s.fields ?? [],
// `className` / `gridClassName`: deliberately not copied — see the
// tabbed arm above (objectstack#13626, ruled 2026-09-01).
})),
allowSkip: schema.allowSkip,
showStepIndicator: schema.showStepIndicator,
nextText: schema.nextText,
prevText: schema.prevText,
onStepChange: schema.onStepChange,
}}
dataSource={dataSource}
className={schema.className}
/>
);
}
// Default: simple form
return <SimpleObjectForm schema={schema} dataSource={dataSource} />;
};
/**
* SimpleObjectForm — default form variant with auto-generated fields from ObjectQL schema.
*/
/**
* A simple form's opening values: the seeded defaults (empty on an edit),
* overlaid with the record the form holds or the caller supplied. The form
* renders these, and a create save judges a picked owner against them
* (objectui#12359).
*/
function formOpeningValues(
schemaDefaults: Record<string, unknown>,
initialData: Record<string, unknown> | null | undefined,
): Record<string, unknown> {
return { ...schemaDefaults, ...(initialData ?? {}) };
}
const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource?: DataSource }> = ({
schema,
dataSource,
}) => {
const { fieldLabel, sectionLabel } = useSafeFieldLabel();
// The form's own feedback chrome — the default success toast and
// confirmation, the loading line, the load-failure heading and the default
// submit label — in the session locale (objectui#11039). See `formChrome.ts`.
const { t } = useFormChromeTranslation();
const isMobile = useIsMobile();
// Upload-in-flight gate (objectui#10166). Owns the aggregated "is any
// file/image widget below me still uploading" answer, the Save label while it
// is true, and the sentence that says why. See `uploadGate.tsx`.
const uploadGate = useUploadGate();
// Field-level permission gate. When the consumer hasn't mounted a
// PermissionProvider / MePermissionsProvider, `usePermissions` returns
// a permissive default (isLoaded:false, checkField always true) so we
// remain backward-compatible.
const perms = usePermissions();
const [objectSchema, setObjectSchema] = useState<any>(null);
// The hint under a field the caller may read but not write, in the session
// locale (objectui#11071). A string rather than `t` in the dependency list
// below: it changes when the language does and at no other time.
const deniedDescription = t('form.deniedDescription');
// The same reason for the file-size hint's sentence (objectui#12156): the
// field builder below interpolates the size into it, and this string, not
// `t`, is what its dependency list carries. It changes when the language, or
// that language's late-arriving catalogue, does.
const maxFileSizeSentence = t('form.maxFileSize', { size: '' });
const [initialData, setInitialData] = useState<any>(null);
// The persisted record, for `previous`-scoped field rules and the read-only
// submit strip (objectui#3484). Edit mode only, and WITHOUT the schema
// defaults folded in below: `previous` must be the row as the server last
// stored it, not "the row plus what a blank column would default to". It is
// also the from-state a `state_machine` select narrows by (#25933).
const previousValues =
schema.mode === 'edit' && schema.recordId && initialData && typeof initialData === 'object'
? (initialData as Record<string, any>)
: undefined;
// objectui#11000 — why `gateFields` locked every field, when the lock is the
// form-wide one: the affordance for the mode is closed. Rendered above the
// fields by `ClosedAffordanceNotice`.
const closedAffordance = closedFormAffordance({
perms,
objectName: schema.objectName,
mode: schema.mode,
objectSchema,
});
const closedAffordanceNotice = (
<ClosedAffordanceNotice
affordance={closedAffordance}
objectName={schema.objectName}
objectSchema={objectSchema}
/>
);
const [formFields, setFormFields] = useState<FormField[]>([]);
const [loading, setLoading] = useState(true);
// objectui#10682 — the load error, kept per read (the object schema and the
// record), each written only by the current run of its read and cleared when
// a later run of that read commits: see `loadFailure.ts`. `error` is what
// the error screen reports.
const [loadFailures, setLoadFailures] = useState<LoadFailures>(NO_LOAD_FAILURES);
const loadRunSeqRef = React.useRef<LoadRunSeq>({ schema: 0, record: 0 });
const error = shownLoadFailure(loadFailures);
// Terminal state for `submitBehavior: { kind: 'thank-you' | 'next-record' }`
// — without it the form stayed mounted and fully filled after a successful
// submit, with nothing disabling re-submission (a second click created a
// second record).
//
// `refusal` carries the second fact a REFUSED `redirect` destination has to
// report (objectui#4989): the write succeeded — hence the confirmation this
// state already renders — but the authored destination is out of contract, so
// nothing was navigated to and the author needs the reason. It rides on this
// state rather than on `error` because `error` is the load/submit FAILURE
// channel and a refused destination is not a failed submit; putting it there
// would tell the submitter their record was lost.
const [submitted, setSubmitted] = useState<
{ title?: string; message?: string; refusal?: string } | null
>(null);
// The accepted destination of a `submitBehavior: { kind: 'redirect' }` submit,
// together with the delay declared for it, held from the moment the write
// succeeds until the wait below elapses (objectui#5033).
//
// The wait used to be a bare `setTimeout` armed inside the submit handler:
// nothing stored the handle and nothing cleared it, so for the whole of
// `delayMs` a full-page navigation was pending that OUTLIVED this component. A
// submitter who dismissed the modal/drawer variant, followed an in-app link, or
// whose host re-keyed the subtree was pulled away from wherever they had gone.
// Recording the destination here hands the wait to the effect below, which owns
// it for exactly as long as this component is mounted.
//
// The delay travels WITH the destination rather than being re-read from
// `schema.submitBehavior` at wait time: the value honoured is the one declared
// when the write was accepted, so a host re-rendering with a different
// `delayMs` mid-wait cannot restart the pause under the submitter.
const [pendingRedirect, setPendingRedirect] = useState<PendingSubmitRedirect | null>(null);
// The delayed leg of a `redirect` submit behaviour.
//
// `delayMs` semantics are unchanged: the pause is what makes the confirmation
// readable, and an unset value still means "go now" (a zero timer, exactly as
// the in-handler version scheduled it). The one thing that changed is who owns
// the wait — unmounting cancels it instead of leaving it to fire into a page
// the submitter has left.
//
// WHERE the wait lands is `submitRedirectNavigation.ts`'s question: the host's
// injected navigate when one was supplied (so a mounted host's basename is
// applied — objectui#4989 defect 4), else the `window.location.assign` this
// arm has always done. The wizard consumes the same hook, so a wizard and a
// flat form cannot travel to one authored destination differently.
useSubmitRedirectNavigation(pendingRedirect);
// OCC-guarded edit save + its conflict dialog (see occSave.tsx).
const { saveWithOcc, conflictDialog } = useOccSave();
// The record this form READ for the record it edits — the baseline an edit
// save diffs against, so only the fields that changed are written
// (objectui#10156). A ref, not state: only the save path reads it, and
// nothing renders from it. Set by the `findOne` below and nowhere else, so a
// caller-supplied record (inline fields, `initialData`) never becomes a
// baseline and its save keeps sending every field. `initialData` itself is
// left alone: it seeds the form and supplies the OCC token, and advancing it
// after a save would reseed the one and move the other.
const loadedRecordRef = React.useRef<LoadedRecordSnapshot | null>(null);
// Check if using inline fields (fields defined as objects, not just names)
const hasInlineFields = schema.customFields && schema.customFields.length > 0;
// objectui#11615 — the members-only field source as the five other layouts
// answer it (`hasInlineFieldSource`): `customFields` (limb a, which is
// `hasInlineFields` above), or sections whose EVERY entry is self-describing
// (limb b), which this arm now draws whatever its field pool holds. With no
// adapter such a form has nothing to read: it opens on the caller's record,
// and its `onSuccess` is the write (the carve-out in `handleSubmit`).
const hasInlineSource = hasInlineFieldSource(schema);
// Initialize with inline data if provided
useEffect(() => {
if (hasInlineFields) {
setInitialData(resolveInitialRecord(schema));
// objectui#9778: inline members no longer short-circuit the metadata
// read — they MERGE over it — so the loading flag can only drop here
// when nothing is going to be fetched. Dropping it unconditionally put
// an empty `<form>` on screen for the duration of `getObjectSchema`.
// The metadata branch's own tail (`willFetchData`) clears it otherwise.
if (!(schema.objectName && dataSource)) {
setLoading(false);
}
}
}, [hasInlineFields, schema.initialData, schema.initialValues, schema.objectName, dataSource]);
// Fetch object schema from ObjectQL/ObjectStack (inline members merge OVER it)
useEffect(() => {
// objectui#10712 — a read an `objectName` or data-source change has
// superseded commits nothing: not the schema, and not the `loading` release
// the current read owns. Otherwise it could land last and draw the current
// object's record against the previous object's fields.
let cancelled = false;
// objectui#10682 — this run's writes to the schema read's failure; a newer
// run of this effect makes them no-ops.
const run = beginLoadRun(loadRunSeqRef, setLoadFailures, 'schema');
// The field source when no object metadata is reachable: an object with no
// fields, over which the authored members are the whole set.
const inlineOnlySchema = {
name: schema.objectName,
fields: {} as Record<string, any>,
};
const fetchObjectSchema = async () => {
try {
if (!dataSource) {
throw new Error('DataSource is required when using ObjectQL schema fetching (inline fields not provided)');
}
const schemaData = await dataSource.getObjectSchema(schema.objectName);
if (cancelled) return;
if (!schemaData) {
throw new Error(`No schema found for object "${schema.objectName}"`);
}
setObjectSchema(schemaData);
run.commit();
} catch (err) {
if (cancelled) return;
// objectui#9778: for the inline path the metadata is an OVERLAY, not a
// prerequisite. A form that renders its authored members today must not
// become an error panel because the adapter cannot describe the object —
// fall back to the members-only source the registration promises for the
// no-data-source case.
if (hasInlineFields) {
setObjectSchema(inlineOnlySchema);
run.commit();
setLoading(false);
return;
}
run.fail(err);
setLoading(false);
}
};
// objectui#9778: inline members are "merged over the set generated from
// object metadata" (the registered description of `customFields`), so the
// fetch is no longer skipped when they are present — without the generated
// set there is nothing to merge over and the merge lookup further down
// stays the dead code objectui#8071 measured. The members-only schema is
// what the registration's second sentence describes ("with inline
// definitions and no data source, this becomes the only field source"), so
// it is now the FALLBACK rather than the inline path's fixed answer.
//
// objectui#11615: sections of self-describing entries are the other
// members-only source (`hasInlineSource`), so they take the same fallback —
// which is what lets the record effect below seed such a form.
if (schema.objectName && dataSource) {
fetchObjectSchema();
} else if (hasInlineSource) {
setObjectSchema(inlineOnlySchema);
run.commit();
} else {
// No objectName or dataSource and no inline fields — cannot proceed
setLoading(false);
}
return () => { cancelled = true; };
}, [schema.objectName, dataSource, hasInlineFields, hasInlineSource]);
// objectui#10572 — the data-invalidation bus (`notifyDataChanged` from
// `@object-ui/react`), read for the record this form READS (edit/view mode,
// no inline fields). The rule — which changes move it, the pristine gate, the
// held re-read replayed on save or revert — is stated once in
// `recordInvalidation.ts` and shared with the five other layouts
// (objectui#10715). Dirtiness is read from the form renderer's existing
// `onDirtyChange` channel; nothing new is declared on any schema.
const readsRecord = !!schema.recordId && schema.mode !== 'create' && !hasInlineFields;
const { refetch: recordRefetch, onDirtyChange: handleDirtyChange, saved: recordSaved } =
useRecordInvalidation(schema.objectName, schema.recordId, readsRecord);
// The `recordRefetch` value the fetch effect last ran for — a run that moved
// it is a re-read IN PLACE and must not enter the loading branch.
const appliedRecordRefetchRef = React.useRef(0);
// Fetch initial data for edit/view modes (skip if using inline data)
useEffect(() => {
const inPlace = recordRefetch !== appliedRecordRefetchRef.current;
appliedRecordRefetchRef.current = recordRefetch;
// objectui#10712 — a read a newer run has superseded (another `recordId`,
// say, while it was in flight) commits nothing: not the values, not the
// baseline, and not the `loading` release the current run owns. Otherwise
// the answer for the previous record could land last and be shown under
// the new one. The shape the four other sectioned layouts already use
// (recordSwapLoading.test.tsx).
let cancelled = false;
// objectui#10682 — this run's writes to the record read's failure; a newer
// run of this effect makes them no-ops.
const run = beginLoadRun(loadRunSeqRef, setLoadFailures, 'record');
const fetchInitialData = async () => {
if (!schema.recordId || schema.mode === 'create') {
// Seeded from something other than a read: no baseline to diff against.
loadedRecordRef.current = null;
setInitialData(resolveInitialRecord(schema));
// Not a read, so no earlier record read's failure describes the form.
run.commit();
setLoading(false);
return;
}
// Skip fetching if using inline data
if (hasInlineFields) {
return;
}
if (!dataSource) {
if (hasInlineSource) {
// objectui#11615 — sections of self-describing entries with no
// adapter: a self-contained collector with nothing to read, so it
// opens on the caller's record, as the five other layouts open the
// same form. Not a read, so no baseline.
loadedRecordRef.current = null;
setInitialData(resolveInitialRecord(schema));
run.commit();
setLoading(false);
return;
}
run.fail(new Error('DataSource is required for fetching record data (inline data not provided)'));
setLoading(false);
return;
}
// A bus re-read keeps the form mounted (objectui#10572): the loading
// branch would unmount it and drop the fields' own UI state.
if (!inPlace) setLoading(true);
try {
const data = await dataSource.findOne(schema.objectName, schema.recordId);
if (cancelled) return;
// Tagged with the object and record it was read for, so a save that
// runs against a different one finds no baseline and sends everything.
loadedRecordRef.current = snapshotLoadedRecord(schema, data);
setInitialData(data);
// The record on screen is the one this run read, so an earlier record
// read's failure no longer describes it. A schema failure stays: this
// read says nothing about the object's fields.
run.commit();
} catch (err) {
if (cancelled) return;
console.error('Failed to fetch record:', err);
// A failed background re-read (the bus above) is reported like any
// other: the form has no silent mode, so the last good values stay in
// state but are not drawn, and the next re-read that succeeds takes the
// screen back.
run.fail(err);
} finally {
if (!cancelled) setLoading(false);
}
};
if (objectSchema && !hasInlineFields) {
fetchInitialData();
}
return () => { cancelled = true; };
}, [schema.objectName, schema.recordId, schema.mode, schema.initialValues, schema.initialData, dataSource, objectSchema, hasInlineFields, hasInlineSource, recordRefetch]);
// FormField `visibleOn` (spec FormFieldSchema CEL expression) is consumed
// directly by the form renderer via the canonical engine — it accepts both
// the bare-string and `{ dialect, source }` wire shapes (#2212). Fields are
// passed through verbatim; the previous normalization attached a
// `visible(formData)` closure backed by the legacy `evaluateCondition`
// matcher, which is not a CEL evaluator and was never called downstream.
const normalizeVisibility = useCallback((f: any): any => f, []);
// Generate form fields from object schema, with inline members merged over it
//
// objectui#9778 — `customFields` MERGES, it does not replace. The registered
// description of the member ("Field definitions merged over the set generated
// from object metadata. With inline definitions and no data source, this
// becomes the only field source.") is the contract, and the per-member merge
// (now `mergeCustomFields`, objectui#10073) was written for it — but a
// non-empty `customFields` used to return from here with
// `setFormFields(schema.customFields.map(normalizeVisibility))` BEFORE the
// generated set existed, so that lookup only ever ran over an empty array.
// The three directions the merge now takes, one case each in
// `objectFormCustomFieldsMembers-8071.test.tsx`:
// override — a member naming a declared field replaces that field's
// generated definition, in the generated set's position;
// keep — a declared field no member names still renders;
// append — a member naming a field the metadata never declares is added
// after the generated set, in authored order.
// With no data source the generated set is empty, so the members remain the
// only field source (the registration's second sentence) — unchanged. The
// drawer and modal arms resolve their members through the same helper, pinned
// per arm by `drawerModalCustomFieldsMerge-10073.test.tsx`.
useEffect(() => {
if (!objectSchema) return;
// ⛔ No managed-object lock here (ADR-0092 D4). This generator used to
// stamp it on the fields it generates, so only this arm drew it — and an
// inline member replacing a generated field escaped it. The lock now runs
// in `gateFormFields`, the one step every layout draws its resolved fields
// through, with field-level security (objectui#10612).
// Determine which fields to include
const fieldsToShow = schema.fields || Object.keys(objectSchema.fields || {});
// Support object format for fields in schema (legacy/compat)
const fieldNames = Array.isArray(fieldsToShow)
? fieldsToShow
: Object.keys(fieldsToShow);
const resolved: Array<{ name: string; entry: (typeof fieldNames)[number] }> = [];
fieldNames.forEach((fieldName) => {
// If fieldsToShow is an array of strings, fieldName is the string
// If fieldsToShow is array of objects (unlikely but possible in some formats), we need to extract name
const name = typeof fieldName === 'string' ? fieldName : (fieldName as any).name;
if (!name) {
// objectui#8738 route 1: a member that resolves to no name (most
// commonly the spec `FormFieldSchema` object, identity key `field`,
// that IS legal in `sections[].fields`) used to vanish here without a
// word. Warn, don't accept — see `warnUnresolvedTopLevelField`.
warnUnresolvedTopLevelField(fieldName, schema.objectName);
return;
}
resolved.push({ name, entry: fieldName });
});
// The generated half of the merge: `undefined` for a name the object does
// not declare, which `mergeCustomFields` then draws only if a member names
// it. Field-level permissions are enforced downstream by `gateFields`
// (the real per-caller gate via `perms.checkField`); the schema itself
// carries no per-caller permission bits (objectstack#3661).
const generateField = (name: string, index: number): FormField | undefined => {
const fieldName = resolved[index].entry;
const field = objectSchema.fields?.[name];
if (field) {
// Auto-generate field from schema
const formField: FormFieldWithGroup = {
name: name,
label: fieldLabel(schema.objectName, name, field.label || fieldName),
// (type, multiple) decides the widget, not the type alone: a `select`
// declared `multiple: true` renders the multi-value chip picker, whose
// label must be associated by IDREF — a fact declared per WIDGET, so
// the widget id has to carry the arity (objectui#3986).
type: mapFieldTypeToFormType(field.type, { multiple: field.multiple }),
// Mode-aware: a CREATE form does not enforce `required` on a field
// whose `defaultValue` is a runtime instruction the server resolves
// at insert (#4069). The control is left empty on purpose so the
// server resolves it — refusing the submit would leave the user with
// nothing sensible to type.
required: isRequiredInForm(field, isCreateFormMode(schema)),
disabled: schema.readOnly || schema.mode === 'view' || field.readonly,
placeholder: field.placeholder,
// The help line under the control: the spec's `inlineHelpText`,
// else `description`, through the one read `fromObjectSchema`
// shares (`fieldHelpText`, objectui#12213). A file or image field's
// size hint is appended to it below.
description: fieldHelpText(field),
validation: buildValidationRules(field),
// Field-level CEL conditional rules (B2). Carried through verbatim so
// the form renderer evaluates them reactively via the canonical
// engine (same dialect the server enforces). Undefined when absent.
visibleWhen: field.visibleWhen,
readonlyWhen: field.readonlyWhen,
requiredWhen: field.requiredWhen,
// Field-group membership (Field.group → object.fieldGroups[].key).
// Carried through so the form can auto-derive sections from the
// object's declared field groups when no explicit sections are given.
group: field.group,
// Important: Pass the original field metadata so widgets can access properties like precision, currency, etc.
field: field,
// A per-field widget override. `form.tsx` resolves `widget || type`, so this makes the
// auto-generated (no-form-view) form honor the override just like the
// authored-section path already does (sectionFields.ts).
widget: (field as any).widget,
};