Repository navigation
Expand file tree
/
Copy pathModalForm.tsx
More file actions
1511 lines (1432 loc) · 70.2 KB
/
Copy pathModalForm.tsx
File metadata and controls
1511 lines (1432 loc) · 70.2 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.
*/
/**
* ModalForm Component
*
* A form variant that renders inside a Dialog (modal) overlay.
* Aligns with @objectstack/spec FormView type: 'modal'
*/
import React, { Suspense, startTransition, useState, useCallback, useEffect, useMemo, useId, useRef } from 'react';
import type { FormField, FormSchema, DataSource, ObjectFormSchema, ObjectFormSection } from '@object-ui/types';
import {
Dialog,
MobileDialogContent,
DIALOG_VIEWPORT_GUTTER,
DialogHeader,
DialogTitle,
DialogDescription,
Skeleton,
Button,
cn,
AlertDialog,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
RecordTopBarButton,
toast,
FormSectionNavContext,
} from '@object-ui/components';
import { Loader2, Maximize2, Minimize2 } from 'lucide-react';
import { MasterDetailForm } from './MasterDetailForm';
import { SchemaRenderer, useSafeFieldLabel, usePreviewMode } from '@object-ui/react';
import { createSafeTranslation, useLocalization } from '@object-ui/i18n';
import { buildSectionFields as buildSectionFieldsShared } from './sectionFields';
import { buildFlatFields } from './flatFields';
import { isRecordReadOutstanding } from './recordReadGate';
import {
applyAutoColSpan,
applyAutoLayout,
filterAutoGeneratedFields,
filterSystemFields,
inferColumns,
inferModalSize,
dialogUndeclaredColumns,
sectionedFormColumns,
sectionedGridLayout,
CONTAINER_GRID_COLS,
UNDECLARED_SECTION_COLUMNS,
} from './autoLayout';
import { deriveFieldGroupSections, projectSectionDivider, resolveSectionCollapse } from './fieldGroups';
import { resolveSectionGroupReferences } from './sectionGroups';
import {
sanitizeFormData,
dirtyEditPayload,
snapshotLoadedRecord,
advanceLoadedRecord,
type LoadedRecordSnapshot,
} from './sanitize';
import { closedForRecord, closedFormAffordance, fieldWriteGate, gateFormFields } from './fieldWriteGate';
import { RecordFieldAccessForForm } from './recordFieldAccess';
import { ClosedAffordanceNotice } from './closedAffordanceNotice';
import { seedCreateValues } from './schemaDefaults';
import { createWritePayload } from './writePayload';
import { resolveInitialRecord } from './initialRecord';
import { usePermissions } from '@object-ui/permissions';
import { useOccSave } from './occSave';
import {
NO_LOAD_FAILURES,
RecordNotFoundError,
RecordNotFoundState,
beginLoadRun,
shownLoadFailure,
type LoadFailures,
type LoadRunSeq,
} from './loadFailure';
import { hasInlineFieldSource, noSubmitTargetError } from './submitTarget';
import { useRecordInvalidation } from './recordInvalidation';
import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate';
import { useInitialFieldFocus } from './initialFieldFocus';
import { FormSectionNav, useFormSectionNav } from './FormSectionNav';
import { FormDirtyReportContext } from './formDirtyReport';
import { useModalFormMaximized } from './modalMaximize';
// Localized strings for the unsaved-changes guard and, since objectui#11039,
// the form's own chrome (the default submit and cancel labels and the
// load-failure heading — the same keys and values as `formChrome.ts`). Falls
// back to English when no i18n provider is mounted (createSafeTranslation
// handles that).
const useDiscardTranslation = createSafeTranslation(
{
'form.discardTitle': 'Discard changes?',
'form.discardMessage': 'You have unsaved changes. If you close this form now, your edits will be lost.',
// The dialog's `sr-only` accessible description, used when the form
// declares no `description` (objectui#4024). It rides this table rather
// than a bare `useObjectTranslation` so a provider-less host announces the
// English sentence instead of a raw key — the #4514 trap, and the reason
// this factory exists.
'form.dialogDescriptionFallback': 'Complete the form fields, then submit or cancel.',
// The sr-only description of a master-detail dialog with no `description`
// of its own (objectui#11071).
'form.masterDetail.editorDescription': 'Enter the record and its line items, then save.',
'form.keepEditing': 'Keep editing',
'form.discard': 'Discard',
'form.create': 'Create',
'form.update': 'Update',
'common.cancel': 'Cancel',
// The footer's declared Reset button (objectstack#27247).
'common.reset': 'Reset',
'form.errorLoading': 'Error loading form',
// The heading of the fields no declared field group claims
// (`deriveFieldGroupSections`' trailing bucket).
'common.ungroupedSection': 'Other',
// The header's maximize / restore switch: the record drawer's own pair of
// keys and labels (objectstack-ai/objectstack#34604).
'detail.maximize': 'Maximize',
'detail.restoreSize': 'Restore size',
},
'form.discardTitle',
);
export interface ModalFormSectionConfig {
name?: string;
label?: string;
description?: string;
columns?: 1 | 2 | 3 | 4;
/**
* The same three entry shapes as `ObjectFormSection.fields`, by reference:
* a field name, the form view's `{ field, … }` entry, or an inline
* `FormField` (objectui#11615).
*/
fields: NonNullable<ObjectFormSection['fields']>;
/**
* Whether the section can be collapsed — spec `FormSection.collapsible`.
* `collapsed: true` implies it (objectui#9780). The control lives on the
* section's divider row, so a section with neither `label` nor
* `description` cannot carry one: it renders open and is reported
* (objectui#9849, director ruling letter E). Stacked layout only — the
* `tabbed` content layout draws tabs, which do not collapse.
*/
collapsible?: boolean;
/** Whether the section starts collapsed — spec `FormSection.collapsed`. Same rules as `collapsible`. */
collapsed?: boolean;
/**
* ADR-0089 `FormSection.visibleWhen` — conditional visibility for the
* section's divider HEADER, evaluated by the form renderer with the canonical
* engine and the host predicate scope (#6010/#6111). Fails OPEN.
*/
visibleWhen?: string | { dialect?: string; source: string };
/**
* The fault direction of {@link visibleWhen}, by reference to
* `ObjectFormSection.visibleWhenFault` (objectui#13055): `'hidden'` (a field
* group's predicate) hides the section when it cannot be evaluated.
*/
visibleWhenFault?: ObjectFormSection['visibleWhenFault'];
/** Custom CSS class for the section's header row (stacked layout). */
className?: string;
/**
* Custom CSS class for the section's field grid. Applied to the section's tab
* panel in the `tabbed` layout; in the stacked layout every section shares one
* grid inside the single form (#2959), so there is none to override.
*/
gridClassName?: string;
}
export interface ModalFormSchema {
type: 'object-form';
formType: 'modal';
objectName: string;
mode: 'create' | 'edit' | 'view';
/** Record ID (for edit/view modes). A string, per the one record-id rule on `DataSource` (objectui#9511) — `ObjectForm` builds this schema from the authorable `ObjectFormSchema.recordId`, which is a string, and `findOne` takes a string. */
recordId?: string;
title?: string;
description?: string;
sections?: ModalFormSectionConfig[];
/** Internal content layout (ADR-0050, objectstack-ai/objectstack#1890): 'tabbed' renders sections as
* tabs inside the modal, so "modal + tabbed" composes. Default stacks them. */
contentLayout?: 'simple' | 'tabbed';
/**
* The `tabbed` content layout's initially active tab (a section name) and
* tab strip position, as the spec's `FormView.defaultTab` / `tabPosition`
* declare them (objectstack-ai/objectstack#26843). Read by the tabbed arm
* only, the subforms arm included.
*/
defaultTab?: string;
tabPosition?: 'top' | 'bottom' | 'left' | 'right';
fields?: string[];
customFields?: FormField[];
/**
* Whether the modal is open.
* @default true
*/
open?: boolean;
/**
* Callback when open state changes.
*/
onOpenChange?: (open: boolean) => void;
/**
* Modal dialog size.
* @default 'default'
*/
modalSize?: 'sm' | 'default' | 'lg' | 'xl' | 'full';
/**
* Whether the dialog draws its close (X) button. Only an explicit `false`
* hides it (objectui#11061); both dialog arms (the flat form and the
* `subforms` master-detail form) pass it to `MobileDialogContent`'s
* `showCloseButton`. Hidden, the form is still dismissable: Escape (and a
* backdrop click) still reach `onOpenChange(false)`, as does the Cancel
* action when it is shown.
* @default true
*/
modalCloseButton?: boolean;
/**
* Guard against *accidentally* discarding unsaved input. When the form has
* unsaved changes, an accidental close (backdrop click, Escape, or the X
* button) first asks the user to confirm. The explicit Cancel button is an
* intentional discard and always closes immediately. Set to `false` to drop
* the confirmation entirely.
* @default true
*/
confirmOnDiscard?: boolean;
// Common form props
showSubmit?: boolean;
submitText?: string;
showCancel?: boolean;
cancelText?: string;
/** The Reset button in the footer: restores the opening values, no save (objectstack#27247). */
showReset?: boolean;
initialValues?: Record<string, any>;
initialData?: Record<string, any>;
readOnly?: boolean;
layout?: 'vertical' | 'horizontal';
columns?: number;
/**
* Override persistence — the seam a host uses to own the write. Declared as
* `ObjectFormSchema['submitHandler']` rather than restated, so this variant
* and the canonical key `ObjectForm` forwards can never drift apart.
* When supplied, the form validates and hands the collected values
* to this handler INSTEAD of calling `dataSource.create` /
* `dataSource.update`; the returned record is passed on to `onSuccess`.
* In `edit` mode, for a record this form read itself, it hands over what it
* would have written: the fields that differ from that read, or the full
* sanitized payload when nothing changed (objectui#10156; the whole rule is
* on `ObjectFormSchema['submitHandler']`).
*
* `MasterDetailForm` supplies it to route the parent AND its child
* collections through one atomic `batchTransaction` (#2679 / ADR-0034
* item 4). A renderer that does not read it writes the parent on its own and
* escapes that transaction — objectui#6176.
*/
submitHandler?: ObjectFormSchema['submitHandler'];
onSuccess?: (data: any) => void | Promise<void>;
onError?: (error: Error) => void;
onCancel?: () => void;
className?: string;
/** Inline child collections — renders the modal as an atomic master-detail
* form. Each entry needs only `childObject` (FK + columns derived). */
subforms?: Array<{
childObject: string;
relationshipField?: string;
columns?: any[];
amountField?: string;
totalField?: string;
title?: string;
addLabel?: string;
minRows?: number;
maxRows?: number;
}>;
}
export interface ModalFormProps {
schema: ModalFormSchema;
dataSource?: DataSource;
className?: string;
/**
* A lock on the edited record that the host reads and the record's field
* projection leaves out: `'approval'` while a pending approval locks it
* (objectstack#27138). The dialog then draws the record read-only, says
* why, and offers no Save, as it does for a row the server answers
* `writable: false`. Read on an `edit` form with a `recordId` only.
*/
lockedBy?: 'approval';
}
/**
* Size class map for the dialog content.
*
* Uses `sm:` prefix so that `tailwind-merge` correctly resolves the conflict
* with MobileDialogContent's base `sm:max-w-lg` class. On mobile (< sm) the
* dialog is already full-screen, so max-width only matters at sm+ breakpoints.
*
* The bounded wide sizes, `lg` and `xl`, also read the shared
* {@link DIALOG_VIEWPORT_GUTTER} (objectui#12593, promoted to one export by
* objectui#12603): 1rem from the window edge at every width from `sm` up.
* `sm` (384px) and `default` (512px) never reach the edge at or above 640px,
* and `full` keeps its own `95vw`, so none of the three reads it.
*/
const modalSizeClasses: Record<string, string> = {
sm: 'sm:max-w-sm',
default: 'sm:max-w-lg',
lg: `sm:max-w-2xl ${DIALOG_VIEWPORT_GUTTER}`,
xl: `sm:max-w-5xl ${DIALOG_VIEWPORT_GUTTER}`,
full: 'sm:max-w-[95vw] sm:w-full',
};
/**
* The least grid the dialog draws where the author declared no `columns`
* (objectui#12521): two from the container's `@md` tier up, one below it, so
* the phone sheet keeps its single column. A field-heavy form draws more —
* three in a bounded dialog, four in a `full` one — by
* `dialogUndeclaredColumns` (objectstack-ai/objectstack#34607), whose
* docblock carries the rule and the measured tier.
*
* Every undeclared count rides the spec's own `columns` / `colSpan` path, so
* every field takes one cell — fields of one kind share one width — while a
* wide kind (`isWideFieldType`: textarea, rich text, markdown, html, an inline
* `grid`) and a `span: 'full'` field take the whole row. Line items never
* reach this grid: they arrive as `subforms`, which the master-detail arm
* below lays out across the dialog.
*
* It applies to a flat form with no `columns`, and to a SECTION that declares
* no `columns` — the object's `fieldGroups` among them — through the one
* sectioned-form rule, `sectionedGridLayout`, handed the dialog's count: an
* undeclared section density is the renderer's choice, and a declared one —
* `1` included — is drawn as written (the section-`columns` fork on
* objectui#12521, ruled 6204264665).
*
* The count is dialog-only on purpose: a sectioned page form keeps
* `UNDECLARED_SECTION_COLUMNS`, and a flat page form, a drawer and the detail
* view keep `inferColumns`, which they mirror between them.
*/
const DIALOG_DEFAULT_COLUMNS = UNDECLARED_SECTION_COLUMNS;
/** Clamp an authored column count into the 1–4 grid keys; anything else reads as not authored. */
const clampColumns = (n: unknown): number | undefined =>
typeof n === 'number' && n > 0 ? Math.min(Math.floor(n), 4) : undefined;
/**
* An `edit` form for a stored record answers its field locks from that record
* (objectstack#26594) — see `recordFieldAccess.tsx`.
*/
export const ModalForm: React.FC<ModalFormProps> = ({ schema, lockedBy, ...rest }) => (
<RecordFieldAccessForForm schema={schema} dataSource={rest.dataSource} lockedBy={lockedBy}>
{/* `schema=` by name, so the handler-key census follows the document into the body. */}
<ModalFormBody schema={schema} {...rest} />
</RecordFieldAccessForForm>
);
const ModalFormBody: React.FC<ModalFormProps> = ({
schema,
dataSource,
className,
}) => {
const { fieldLabel, sectionLabel } = useSafeFieldLabel();
const { t } = useDiscardTranslation();
// The heading of the trailing ungrouped-fields bucket (`deriveFieldGroupSections`).
const ungroupedLabel = t('common.ungroupedSection');
// Upload-in-flight gate (objectui#10166): Save is refused, disabled and
// EXPLAINED while a file/image widget below is still uploading.
const uploadGate = useUploadGate();
// The section navigation between the header and the scrolling body
// (objectstack#34605): the form reports its visible sections, the dialog
// draws them where they stay in view while the body scrolls.
const sectionNav = useFormSectionNav();
const drawsSectionNav = (sectionNav.items?.length ?? 0) >= 2;
const previewMode = usePreviewMode();
const perms = usePermissions();
// ADR-0144 D8 rule 4 — the organization currency a record-currency code
// field opens on in create mode.
const { currency: homeCurrency } = useLocalization();
const [objectSchema, setObjectSchema] = useState<any>(null);
const [formData, setFormData] = useState<Record<string, any>>({});
// The ONE field-gate step every layout draws through (`gateFormFields`,
// objectui#10612): FLS drops non-readable fields and disables non-editable
// ones (`80c54122e`; fail-open when no PermissionProvider is mounted), and
// the ADR-0092 D4 managed-object lock disables every field when the object's
// affordance for the mode is closed — before objectui#10612 a managed object
// drew live inputs here.
const gateFields = useCallback(
(fields: FormField[]): FormField[] =>
gateFormFields(fields, {
perms,
objectName: schema.objectName,
mode: schema.mode,
objectSchema,
// The persisted record a `state_machine` select narrows by (#25933).
previousValues: schema.mode === 'edit' && schema.recordId ? formData : undefined,
// The values a create form opens with, which stay offered (#27763).
openingValues: formData,
}) as FormField[],
[perms, schema.objectName, schema.mode, schema.recordId, objectSchema, formData],
);
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 = useRef<LoadRunSeq>({ schema: 0, record: 0 });
const error = shownLoadFailure(loadFailures);
const [isSubmitting, setIsSubmitting] = useState(false);
// Unsaved-changes guard. `isDirty` is fed up from the inner form renderer via
// onDirtyChange; `discardOpen` controls the confirm dialog shown when the user
// tries to close a dirty form.
const [isDirty, setIsDirty] = useState(false);
const [discardOpen, setDiscardOpen] = useState(false);
// Per-section LIVE collapse state, keyed like the divider rows. Unseeded on
// purpose: an untoggled section falls back to its declared `collapsed`
// inside `resolveSectionCollapse`, the one reader of that member — the same
// shape as ObjectForm's grouped layout and DrawerForm (objectui#9849).
const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({});
// objectui#13246 — a section toggle is a TRANSITION. Opening a group draws
// its field widgets, which are `React.lazy`, so the first time a type is
// drawn the render suspends. As an ordinary update that suspension hid the
// drawn body behind `ModalFormBodyPending` — the header the user had just
// pressed included — and a browser drops focus from an element it stops
// rendering, so the dialog's focus scope ended up holding it. As a
// transition React keeps the drawn body on screen until the group's rows can
// be drawn: the header keeps focus, and the next Tab reaches the group's
// first field.
const setSectionCollapsed = (key: string, next: boolean) =>
startTransition(() => setCollapsedSections((prev) => ({ ...prev, [key]: next })));
// OCC-guarded edit save + its conflict dialog (see occSave.tsx).
const { saveWithOcc, conflictDialog } = useOccSave();
// Whether the pending close came from the explicit Cancel button (so we fire
// schema.onCancel) versus a backdrop/Escape/X dismissal (which historically
// did not). Kept in a ref so it survives the confirm round-trip.
const cancelIntentRef = useRef(false);
const confirmOnDiscard = schema.confirmOnDiscard !== false;
const isOpen = schema.open !== false;
// `modalCloseButton` (objectui#11061): only an explicit `false` hides the
// dialog's X; unset and `true` keep it.
const showCloseButton = schema.modalCloseButton !== false;
// Stable form id for linking the external submit button to the form element
const formId = useId();
// objectui#13130 — the dialog opens on its first editable field, not on its
// Close button: the body loads after the content mounts, so Radix's own
// first-tabbable pick found only Close. See `initialFieldFocus.ts`.
const initialFieldFocus = useInitialFieldFocus();
// `form.sections[].group` (objectui#11542): a section that points `group` at
// one of the object's `fieldGroups` becomes the section that group declares,
// through the ONE resolver `ObjectForm`'s `withGroups` uses, so no assembly
// rule lives here. `ObjectForm` resolves above its routing fork, but the
// console's record dialog and an action-opened modal mount THIS component
// directly with the form view's sections as authored, so the dialog resolves
// its own. Resolved once, above both content layouts (tabbed and stacked),
// against the object schema this form already loads; while it loads the
// form shows its skeleton. Returns `schema.sections` itself when no section
// uses `group` — which includes every section list `ObjectForm` hands over,
// already resolved — so no other modal takes a new path. Every resolved
// member still goes through `gateFields` below, like an enumerated one.
const resolvedSections = useMemo(
() =>
resolveSectionGroupReferences(schema.sections as ObjectFormSection[] | undefined, {
objectName: schema.objectName,
formType: schema.formType,
objectDef: objectSchema,
resolvable: typeof dataSource?.getObjectSchema === 'function',
}) as ModalFormSectionConfig[] | undefined,
[schema.sections, schema.objectName, schema.formType, objectSchema, dataSource],
);
// The fields a flat or field-group layout draws: system fields dropped, and
// in create mode the server-computed ones too — what `applyAutoLayout`
// filters (it filters again; the filters are idempotent). `customFields` is
// already merged into `formFields` (objectui#10073).
const layoutPool = useMemo(() => {
const fs = filterSystemFields(formFields, objectSchema);
return schema.mode === 'create' ? filterAutoGeneratedFields(fs, objectSchema) : fs;
}, [formFields, objectSchema, schema.mode]);
// Field-group fallback (object-designer metadata): when the caller passes no
// explicit sections, honor the object's declared `fieldGroups` the same way
// ObjectForm's simple path does — one section per group, with flat-path
// auto-layout parity (system/auto-generated fields filtered, the dialog's
// undeclared count, wide fields spanning the row). An explicit curated
// `sections` list from a form view always wins over this fallback. The
// groups carry no `columns` of their own: the arm that draws them reads the
// form's declared count, else the dialog's (objectstack-ai/objectstack#34607).
const derivedSections = useMemo(() => {
// `customFields` does NOT switch the fallback off (objectui#10073): the
// members are merged into `formFields` above, and ObjectForm derives its
// groups over that same merged pool.
if (schema.sections?.length) return null;
const sections = deriveFieldGroupSections(layoutPool, (objectSchema as any)?.fieldGroups, ungroupedLabel);
// A member's definition reaches a group's body through `buildSectionFields`,
// the route an explicit section's takes (objectui#10254).
return sections ? (sections as ModalFormSectionConfig[]) : null;
}, [schema.sections, layoutPool, objectSchema, ungroupedLabel]);
const effectiveSections = resolvedSections?.length ? resolvedSections : (derivedSections ?? undefined);
// How many fields the dialog lays out — the input to its size and to its
// undeclared column count.
const layoutFieldCount = effectiveSections?.length
? effectiveSections.reduce((n, s) => n + (Array.isArray(s.fields) ? s.fields.length : 0), 0)
: layoutPool.length;
// The header's maximize switch (objectstack-ai/objectstack#34604):
// maximized, the dialog is `full` whatever its authored or inferred size,
// and every reader of the size below — the width class and the undeclared
// column count — reads that effective size.
const { maximized, toggleMaximized } = useModalFormMaximized(schema.objectName);
// The dialog's size when the author declared none (objectui#12521): bounded
// — `lg` or `xl`, never `full` — and chosen from the declared grid and the
// field count, so a short form is not stretched across a wide dialog. An
// authored `modalSize` (including `'full'`) is used as written. An
// undeclared grid is at least `DIALOG_DEFAULT_COLUMNS` wide whatever the
// size, so the size reads that floor and never the count it then bounds
// (objectstack-ai/objectstack#34607).
const effectiveModalSize = useMemo(() => {
if (maximized) return 'full';
if (schema.modalSize) return schema.modalSize;
const columns = effectiveSections?.length
? sectionedFormColumns(schema.columns, effectiveSections.map((s) => s.columns), DIALOG_DEFAULT_COLUMNS)
: (clampColumns(schema.columns) ?? DIALOG_DEFAULT_COLUMNS);
return inferModalSize(Math.min(columns, inferColumns(layoutFieldCount)));
}, [maximized, schema.modalSize, schema.columns, effectiveSections, layoutFieldCount]);
// The count an undeclared form or section draws in THIS dialog
// (objectstack-ai/objectstack#34607): from the field count, bounded by the
// dialog's size — `dialogUndeclaredColumns`.
const undeclaredColumns = dialogUndeclaredColumns(layoutFieldCount, effectiveModalSize);
// Compute auto-layout for flat fields (no sections). A form that declares no
// `columns` lays out at the dialog's undeclared count through the same
// explicit-columns route an authored `columns` takes, so `applyAutoLayout`
// never runs the page's inference here.
const flatColumns = schema.columns ?? undeclaredColumns;
const autoLayoutResult = useMemo(() => {
if (effectiveSections?.length) return null;
return applyAutoLayout(formFields, objectSchema, flatColumns, schema.mode);
}, [formFields, objectSchema, flatColumns, schema.mode, effectiveSections]);
const sizeClass = modalSizeClasses[effectiveModalSize] || modalSizeClasses.default;
// The content's height: a phone sheet is always the whole screen; from `sm`
// up the dialog grows with its body to a `90vh` cap, and maximized it fills
// `95dvh` — the height counterpart of the `full` size's `95vw` — so its body
// scroller, not the page, scrolls a long form.
const heightClass = maximized
? 'h-[100dvh] sm:h-[95dvh] sm:max-h-[95dvh]'
: 'h-[100dvh] sm:h-auto sm:max-h-[90vh]';
// Fetch object schema
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 (the record read's `cancelled` below, applied here).
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');
const fetchSchema = async () => {
if (!dataSource) {
setLoading(false);
return;
}
try {
const data = await dataSource.getObjectSchema(schema.objectName);
if (cancelled) return;
setObjectSchema(data);
run.commit();
} catch (err) {
if (cancelled) return;
run.fail(err);
setLoading(false);
}
};
fetchSchema();
return () => { cancelled = true; };
}, [schema.objectName, dataSource]);
// The record whose data `formData` currently holds. The fetch effect reads it
// to tell a genuine record SWAP from a re-run of its own making —
// `initialData`/`initialValues` are objects callers commonly rebuild every
// render, and flashing the loading state for those would thrash.
const loadedRecordIdRef = useRef<string | number | undefined>(undefined);
// The record itself as read — the baseline an edit save diffs against, so
// only the fields that changed are written (objectui#10156). Kept apart from
// `formData`, which seeds the form and supplies the OCC token: advancing it
// after a save would reseed the one and move the other. Set by the `findOne`
// below and nowhere else, so a caller-supplied record is never a baseline.
const loadedRecordRef = useRef<LoadedRecordSnapshot | null>(null);
// objectui#10715 — the data-invalidation bus, read the way the default arm
// reads it (the rule is stated once in `recordInvalidation.ts`): a change to
// this record, to its object or to `'*'` re-reads the record IN PLACE through
// the effect below while the form is pristine, and is held while it is dirty.
// `isDirty` stays this modal's close guard; the bus hears the same channel.
const { refetch: recordRefetch, onDirtyChange: onBusDirtyChange, saved: recordSaved } =
useRecordInvalidation(schema.objectName, schema.recordId, !!schema.recordId && schema.mode !== 'create');
const handleDirtyChange = useCallback((dirty: boolean) => {
setIsDirty(dirty);
onBusDirtyChange(dirty);
}, [onBusDirtyChange]);
// Fetch initial data
useEffect(() => {
// A `recordId` change re-enters this effect with the form still MOUNTED on
// the previous record, which needs handling on two fronts (pinned by
// recordSwapLoading.test.tsx):
// - go back to the loading state, so record A's values are not left on
// screen AND EDITABLE while B is in flight, to be swapped underneath in
// place when it lands. Anything typed there read as A's on screen but
// would have been submitted against B.
// - ignore a response that is no longer the one being awaited, so two
// overlapping reads land in REQUEST order, not completion order.
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 fetchData = async () => {
if (schema.mode === 'create' || !schema.recordId) {
// Seeded from something other than a read: no baseline to diff against.
loadedRecordRef.current = null;
// No persisted record to show, so the object's declared static
// `defaultValue`s are the form's opening values (#4047) — caller-
// supplied initial values still win. See `schemaDefaults` for why
// runtime defaults (`NOW()`, `current_user`, CEL envelopes) are left
// to the server and why option-level `default` is not read here.
setFormData(seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId: perms.userId, homeCurrency }));
// Not a read, so no earlier record read's failure describes the form.
run.commit();
setLoading(false);
return;
}
if (!dataSource) {
loadedRecordRef.current = null;
setFormData(resolveInitialRecord(schema));
// Not a read either.
run.commit();
setLoading(false);
return;
}
// Only a change of RECORD hides the form. Hiding it UNMOUNTS the inner
// renderer, which is the only thing that reports dirtiness — it cannot
// emit a final `onDirtyChange(false)` on its way out, so clear the flag
// here or the close/unload guards stay armed for input that belongs to a
// record no longer on screen.
if (loadedRecordIdRef.current !== schema.recordId) {
setLoading(true);
setIsDirty(false);
}
try {
const data = await dataSource.findOne(schema.objectName, schema.recordId);
if (cancelled) return;
// `findOne` answers `null` for a record that does not exist: there is
// nothing to edit, so the read failed, and the form is not seeded.
if (data == null) {
run.fail(new RecordNotFoundError(schema.objectName, schema.recordId));
return;
}
loadedRecordIdRef.current = schema.recordId;
loadedRecordRef.current = snapshotLoadedRecord(schema, data);
setFormData(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;
run.fail(err);
} finally {
if (!cancelled) setLoading(false);
}
};
// A bus re-read (objectui#10715, `recordRefetch` below) re-runs this
// effect for the record already on screen: it lands IN PLACE, since the
// loading branch above is keyed on a change of record, and a re-read a
// later run has superseded commits nothing, as above.
if (objectSchema || !dataSource) {
fetchData();
}
return () => { cancelled = true; };
}, [objectSchema, schema.mode, schema.recordId, schema.initialData, schema.initialValues, dataSource, schema.objectName, recordRefetch]);
// Build form fields from section config
const buildSectionFields = useCallback(
(section: ModalFormSectionConfig): FormField[] =>
buildSectionFieldsShared(section as any, {
objectSchema,
objectName: schema.objectName,
readOnly: schema.readOnly,
mode: schema.mode,
// Feeds the "no persisted record" test that decides whether a runtime
// `defaultValue` excuses a field from `required` (#4069).
recordId: schema.recordId,
fieldLabel,
// A member naming a section's field is that field's definition, as it
// is in ObjectForm's merged pool — for explicit and derived sections
// alike (objectui#10254; the explicit path used to regenerate every
// named field from the object schema and drop the member).
customFields: schema.customFields,
}),
[objectSchema, schema.readOnly, schema.mode, schema.recordId, schema.objectName, schema.customFields, fieldLabel],
);
// Build fields from flat field list (when no sections)
useEffect(() => {
if (!objectSchema && dataSource) return;
// Ending the loading state here is only this effect's call when no record
// read is outstanding (objectui#10659, the gate objectui#10190 gave the
// drawer). Ended unconditionally, it painted an editable form while the
// first read was in flight, and the landing record discarded what had been
// typed — see `isRecordReadOutstanding`.
const recordReadOutstanding = isRecordReadOutstanding({
mode: schema.mode,
recordId: schema.recordId,
dataSource,
loadedRecordId: loadedRecordIdRef.current,
});
const endLoading = () => {
if (!recordReadOutstanding) setLoading(false);
};
if (schema.sections?.length) {
endLoading();
return;
}
// `customFields` MERGES over the generated set, as it does on ObjectForm's
// default arm (objectui#10073 — it used to REPLACE it here). With no
// object metadata the members are the whole field source.
if (!objectSchema && !schema.customFields?.length) return;
// ONE builder, shared with DrawerForm (objectui#4755) — the ADR-0036 rules
// and `group` this path carries now reach both containers from a single
// mapping instead of a hand-copied second loop.
setFormFields(
buildFlatFields({
fields: schema.fields as any,
objectSchema,
objectName: schema.objectName,
readOnly: schema.readOnly,
mode: schema.mode,
recordId: schema.recordId,
fieldLabel,
customFields: schema.customFields,
}),
);
endLoading();
}, [objectSchema, schema.fields, schema.customFields, schema.sections, schema.readOnly, schema.mode, dataSource]);
// Handle form submission
const handleSubmit = useCallback(async (data: Record<string, any>) => {
// An upload is still in flight (objectui#10166). Saving now writes the
// record WITHOUT the attachment and reports success. The footer's Save is
// disabled and labelled for this, so reaching here means a keyboard submit
// — refuse it with the same sentence the notice shows.
if (uploadGate.uploading) {
toast.error(uploadGate.reason);
return;
}
setIsSubmitting(true);
try {
// No submit TARGET: a declared `submitHandler` owns the write and needs no
// adapter of its own (objectui#6176's seam), so only a form with NEITHER it
// nor a `dataSource` is target-less. The one target-less form that is still
// legitimate is the inline-fields collector, whose `onSuccess` IS the write.
// This arm used to be `if (!dataSource)` alone: it confirmed EVERY
// adapter-less submit, bypassing a declared host seam and persisting
// nothing (objectui#6300). See `submitTarget.ts` for the whole rule.
if (!dataSource && !schema.submitHandler && hasInlineFieldSource(schema)) {
if (schema.onSuccess) {
await schema.onSuccess(data);
}
// Close modal on success
schema.onOpenChange?.(false);
return data;
}
let result;
// FLS defence-in-depth, inside the ONE outbound filter: react-hook-form
// retains state for unmounted/disabled fields, so the gate above is not
// enough on its own — but the verdict is the same resolver's, adapted by
// `fieldWriteGate` rather than copied here (`80c54122e`).
const canEdit = fieldWriteGate(perms, schema.objectName, schema.mode);
const payload = sanitizeFormData(data, objectSchema, { canEdit });
// Omit the fields the producer owns (#4069) — see
// `omitServerResolvedDefaults` for why an empty key is not the same as
// no key at insert time. Create only: on an edit form a cleared column is
// a real removal. An EDIT writes only the fields that differ from the
// record this form read (objectui#10156; `dirtyEditPayload` holds the
// rule, and sends whatever it cannot settle) — the owner included when
// the user changed it, which is why it is handed the values as well
// (objectui#12205). Computed ONCE (after the FLS strip above) so every
// persistence route below — the host-owned seam included — writes the
// identical payload.
//
// A CREATE writes the owner only when the user picked one against the
// values this form opened with — `formData`, which on a create is the
// seed and nothing else (objectui#12359; `createOwnerPayload` holds the
// rule). A seeded owner left alone is not a pick and is not sent; the
// server judges a pick, and its refusal is this form's error below. On a
// permission-set grant it writes the package of the holder the user
// picked the same way (objectstack#32770): `createWritePayload` is the
// record form's create step, so every key a create adds back reaches
// this form too.
const owner = { values: data, objectSchema, canEdit };
const writePayload = schema.mode === 'create'
? createWritePayload(payload, formData, schema.objectName, owner, objectSchema)
: dirtyEditPayload(payload, loadedRecordRef.current, schema, owner);
if (schema.submitHandler) {
// The host owns persistence (e.g. MasterDetailForm batching the parent
// + its child collections into ONE atomic transaction). The form
// validates and hands the values over; it does NOT create/update
// itself. Same seam and same precedence as SimpleObjectForm — every
// renderer `ObjectForm` routes to must check it FIRST, or a declared
// host-owned write silently becomes an independent one (objectui#6176).
result = await schema.submitHandler(writePayload);
} else if (!dataSource) {
// No route left: no host seam and no adapter. Refuse instead of reporting
// success — the `catch` below hands this to `schema.onError` and rethrows.
throw noSubmitTargetError();
} else if (schema.mode === 'create') {
result = await dataSource.create(schema.objectName, writePayload);
} else if (schema.mode === 'edit' && schema.recordId) {
// OCC-guarded: sends `ifMatch` from the record we read; a 409 asks the
// user to keep editing (modal stays open, draft intact) or overwrite.
const outcome = await saveWithOcc({
dataSource,
objectName: schema.objectName,
recordId: schema.recordId,
payload: writePayload,
baseRecord: formData,
});
if (outcome.status === 'cancelled') return;
result = outcome.result;
}
// The write landed: a save from this still-open modal diffs against the
// record as it now stands, not as first read.
loadedRecordRef.current = advanceLoadedRecord(loadedRecordRef.current, schema, writePayload);
// objectui#10715 — and what the form shows is what the server holds: a
// bus change held while it was dirty (its own write's echo included) is
// replayed now rather than behind input that is no longer unsaved.
recordSaved();
if (schema.onSuccess) {
await schema.onSuccess(result);
}
// Close modal on success
schema.onOpenChange?.(false);
return result;
} catch (err) {
if (schema.onError) {
schema.onError(err as Error);
}
throw err;
} finally {
setIsSubmitting(false);
}
}, [schema, dataSource, objectSchema, perms, saveWithOcc, formData, uploadGate.uploading, uploadGate.reason, recordSaved]);
// Actually close the modal, firing onCancel only when the close originated
// from the explicit Cancel button.
const finalizeClose = useCallback(() => {
setDiscardOpen(false);
if (cancelIntentRef.current) {
cancelIntentRef.current = false;
schema.onCancel?.();
}
schema.onOpenChange?.(false);
}, [schema]);
// Attempt to close. With unsaved changes, intercept and ask for confirmation
// instead of discarding the user's input. `viaCancel` marks the Cancel button.
const attemptClose = useCallback((viaCancel: boolean) => {
cancelIntentRef.current = viaCancel;
if (confirmOnDiscard && isDirty) {
setDiscardOpen(true);
} else {
finalizeClose();
}
}, [confirmOnDiscard, isDirty, finalizeClose]);
// Browser-native "leave site?" prompt on tab close / reload while the form
// is dirty. The in-app guard above only covers Radix close paths (backdrop,
// Escape, the X) — a refresh bypasses them all and the input is gone.
useEffect(() => {
if (!isOpen || !isDirty || !confirmOnDiscard) return;
const handler = (e: BeforeUnloadEvent) => {
e.preventDefault();
// Required for Chrome to actually show the prompt.
e.returnValue = '';
};
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [isOpen, isDirty, confirmOnDiscard]);
// The explicit Cancel button is an *intentional* discard, so it closes
// immediately — no "Discard changes?" prompt. The unsaved-changes guard only
// intercepts *accidental* closes (backdrop click, Escape, the X), which Radix
// routes through onOpenChange below. (attemptClose stays for that path.)
const handleCancel = useCallback(() => {
cancelIntentRef.current = true;
finalizeClose();
}, [finalizeClose]);
// `vertical | horizontal` on the declared face; the fold that mapped any
// other value to `vertical` was retired with `inline` / `grid`
// (objectui#11168 slice 3, objectui#7759 group C).
const formLayout = schema.layout ?? 'vertical';
// Build base form schema
// Actions are hidden inside the form renderer — we render them in a sticky footer instead
// objectui#11000 — the form-wide lock's reason, read once for the notice
// above the fields and for Save: a record that refuses the update itself
// (objectstack#27138) takes no edit, so the dialog offers no Save on it.
const closedAffordance = closedFormAffordance({
perms,
objectName: schema.objectName,
mode: schema.mode,
objectSchema,
});
const showSubmit = schema.showSubmit !== false && schema.mode !== 'view' && !closedForRecord(closedAffordance);
const showCancel = schema.showCancel !== false;
const showReset = schema.showReset === true && schema.mode !== 'view' && !closedForRecord(closedAffordance);
const submitLabel = schema.submitText || (schema.mode === 'create' ? t('form.create') : t('form.update'));
const cancelLabel = schema.cancelText || t('common.cancel');
// Typed as the child `form` node it is (objectui#11354), and so is every node
// `renderContent` builds from it: each is a `FormSchema` const before it
// reaches `SchemaRenderer`. `SchemaRenderer`'s `schema` slot is `BaseSchema`,
// so a literal written inline there was checked against `BaseSchema`, not
// against the `FormSchema` the `form` renderer reads.
const baseFormSchema: FormSchema = {
type: 'form',
objectName: schema.objectName,
layout: formLayout,
defaultValues: formData,
// The persisted record, for `previous`-scoped field rules and the
// read-only submit strip (objectui#3484). Edit mode only: `formData` is
// the raw `findOne` read there, while in create mode it is authored
// seed values and there is no prior row to speak of.
previousValues: schema.mode === 'edit' && schema.recordId ? formData : undefined,
submitLabel,
cancelLabel,
showSubmit,
showCancel,
onSubmit: handleSubmit,
onCancel: handleCancel,
onDirtyChange: handleDirtyChange, // Feed unsaved-changes state up to the close guard and the bus gate
showActions: false, // Hide actions — rendered in sticky footer
id: formId, // Link external submit button via form attribute
};
const renderContent = () => {
if (error instanceof RecordNotFoundError) {
return <RecordNotFoundState testId="modal-form-record-not-found" />;
}
if (error) {
return (
<div className="p-4 border border-red-300 bg-red-50 rounded-md">
<h3 className="text-red-800 font-semibold">{t('form.errorLoading')}</h3>
<p className="text-red-600 text-sm mt-1">{error.message}</p>
</div>
);
}
if (loading) {
return (
<div className="space-y-4" data-testid="modal-form-skeleton">
{[1, 2, 3].map((i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-10 w-full" />
</div>
))}
</div>
);
}
// Explicit sections layout (curated form view) — ONE form for ALL sections.
//