-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathModalForm.tsx
More file actions
869 lines (802 loc) · 33 KB
/
Copy pathModalForm.tsx
File metadata and controls
869 lines (802 loc) · 33 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
/**
* 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, { useState, useCallback, useEffect, useMemo, useId, useRef } from 'react';
import type { FormField, DataSource } from '@object-ui/types';
import {
Dialog,
MobileDialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
Skeleton,
Button,
cn,
AlertDialog,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
} from '@object-ui/components';
import { Loader2 } from 'lucide-react';
import { MasterDetailForm } from './MasterDetailForm';
import { SchemaRenderer, useSafeFieldLabel, usePreviewMode } from '@object-ui/react';
import { createSafeTranslation } from '@object-ui/i18n';
import { mapFieldTypeToFormType, buildValidationRules } from '@object-ui/fields';
import { buildSectionFields as buildSectionFieldsShared } from './sectionFields';
import {
applyAutoColSpan,
applyAutoLayout,
filterAutoGeneratedFields,
filterSystemFields,
inferColumns,
inferModalSize,
CONTAINER_GRID_COLS,
} from './autoLayout';
import { deriveFieldGroupSections } from './fieldGroups';
import { sanitizeFormData } from './sanitize';
import { usePermissions } from '@object-ui/permissions';
// Localized strings for the unsaved-changes guard. 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.',
'form.keepEditing': 'Keep editing',
'form.discard': 'Discard',
},
'form.discardTitle',
);
export interface ModalFormSectionConfig {
name?: string;
label?: string;
description?: string;
columns?: 1 | 2 | 3 | 4;
fields: (string | FormField)[];
/** 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';
recordId?: string | number;
title?: string;
description?: string;
sections?: ModalFormSectionConfig[];
/** Internal content layout (ADR-0050, #1890): 'tabbed' renders sections as
* tabs inside the modal, so "modal + tabbed" composes. Default stacks them. */
contentLayout?: 'simple' | 'tabbed';
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 to show a close button in the header.
* @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;
initialValues?: Record<string, any>;
initialData?: Record<string, any>;
readOnly?: boolean;
layout?: 'vertical' | 'horizontal';
columns?: number;
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;
}
/**
* 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.
*/
const modalSizeClasses: Record<string, string> = {
sm: 'sm:max-w-sm',
default: 'sm:max-w-lg',
lg: 'sm:max-w-2xl',
xl: 'sm:max-w-5xl',
full: 'sm:max-w-[95vw] sm:w-full',
};
export const ModalForm: React.FC<ModalFormProps> = ({
schema,
dataSource,
className,
}) => {
const { fieldLabel, sectionLabel } = useSafeFieldLabel();
const { t } = useDiscardTranslation();
const previewMode = usePreviewMode();
const perms = usePermissions();
// FLS gate: drop non-readable fields, disable non-editable ones.
// Fail-open when no PermissionProvider mounted (perms.isLoaded false).
const applyFieldPerms = useCallback(
(fields: FormField[]): FormField[] => {
if (!perms?.isLoaded) return fields;
const out: FormField[] = [];
for (const f of fields) {
if (!f?.name) { out.push(f); continue; }
const canRead = perms.checkField(schema.objectName, f.name, 'read');
if (!canRead) continue;
const canWrite = perms.checkField(schema.objectName, f.name, 'write');
if (!canWrite && schema.mode !== 'view') {
out.push({ ...f, readOnly: true, disabled: true });
} else {
out.push(f);
}
}
return out;
},
[perms, schema.objectName, schema.mode],
);
const [objectSchema, setObjectSchema] = useState<any>(null);
const [formFields, setFormFields] = useState<FormField[]>([]);
const [formData, setFormData] = useState<Record<string, any>>({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
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);
// 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;
// Stable form id for linking the external submit button to the form element
const formId = useId();
// 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, columns
// inferred from field count, wide fields spanning the row). An explicit
// curated `sections` list from a form view always wins over this fallback.
const derivedSections = useMemo(() => {
if (schema.sections?.length || schema.customFields?.length) return null;
let fs = filterSystemFields(formFields, objectSchema);
if (schema.mode === 'create') fs = filterAutoGeneratedFields(fs, objectSchema);
const sections = deriveFieldGroupSections(fs, (objectSchema as any)?.fieldGroups);
if (!sections) return null;
const columns = (schema.columns && schema.columns > 0
? Math.min(Math.floor(schema.columns), 4)
: inferColumns(fs.length)) as 1 | 2 | 3 | 4;
return sections.map((s) => ({ ...s, columns })) as ModalFormSectionConfig[];
}, [schema.sections, schema.customFields, schema.columns, schema.mode, formFields, objectSchema]);
const effectiveSections = schema.sections?.length ? schema.sections : (derivedSections ?? undefined);
// Compute auto-layout for flat fields (no sections) to determine inferred columns
const autoLayoutResult = useMemo(() => {
if (effectiveSections?.length || schema.customFields?.length) return null;
return applyAutoLayout(formFields, objectSchema, schema.columns, schema.mode);
}, [formFields, objectSchema, schema.columns, schema.mode, effectiveSections, schema.customFields]);
// Auto-upgrade modal size when auto-layout infers multi-column and user hasn't set modalSize
const effectiveModalSize = useMemo(() => {
if (schema.modalSize) return schema.modalSize;
if (autoLayoutResult?.columns && autoLayoutResult.columns > 1) {
return inferModalSize(autoLayoutResult.columns);
}
// Auto-upgrade for sections: use the max columns across all sections
if (effectiveSections?.length) {
const maxCols = Math.max(...effectiveSections.map(s => Number(s.columns) || 1));
if (maxCols > 1) return inferModalSize(maxCols);
}
return 'default';
}, [schema.modalSize, autoLayoutResult, effectiveSections]);
const sizeClass = modalSizeClasses[effectiveModalSize] || modalSizeClasses.default;
// Fetch object schema
useEffect(() => {
const fetchSchema = async () => {
if (!dataSource) {
setLoading(false);
return;
}
try {
const data = await dataSource.getObjectSchema(schema.objectName);
setObjectSchema(data);
} catch (err) {
setError(err as Error);
setLoading(false);
}
};
fetchSchema();
}, [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);
// 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;
const fetchData = async () => {
if (schema.mode === 'create' || !schema.recordId) {
setFormData(schema.initialData || schema.initialValues || {});
setLoading(false);
return;
}
if (!dataSource) {
setFormData(schema.initialData || schema.initialValues || {});
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;
loadedRecordIdRef.current = schema.recordId;
setFormData(data || {});
} catch (err) {
if (cancelled) return;
setError(err as Error);
} finally {
if (!cancelled) setLoading(false);
}
};
if (objectSchema || !dataSource) {
fetchData();
}
return () => { cancelled = true; };
}, [objectSchema, schema.mode, schema.recordId, schema.initialData, schema.initialValues, dataSource, schema.objectName]);
// 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,
fieldLabel,
}),
[objectSchema, schema.readOnly, schema.mode, schema.objectName, fieldLabel],
);
// Build fields from flat field list (when no sections)
useEffect(() => {
if (!objectSchema && dataSource) return;
if (schema.customFields?.length) {
setFormFields(schema.customFields);
setLoading(false);
return;
}
if (schema.sections?.length) {
setLoading(false);
return;
}
if (!objectSchema) return;
const fieldsToShow = schema.fields || Object.keys(objectSchema.fields || {});
const generated: FormField[] = [];
for (const fieldName of fieldsToShow) {
const name = typeof fieldName === 'string' ? fieldName : (fieldName as any).name;
if (!name) continue;
const field = objectSchema.fields?.[name];
if (!field) continue;
generated.push({
name,
label: fieldLabel(schema.objectName, name, field.label || name),
type: mapFieldTypeToFormType(field.type),
required: field.required || false,
disabled: schema.readOnly || schema.mode === 'view' || field.readonly,
placeholder: field.placeholder,
description: field.help || field.description,
validation: buildValidationRules(field),
field: field,
options: field.options,
multiple: field.multiple,
// Field-level conditional rules (ADR-0036) — resolved reactively by
// the form renderer via the canonical engine (#2212).
visibleWhen: (field as any).visibleWhen,
readonlyWhen: (field as any).readonlyWhen,
requiredWhen: (field as any).requiredWhen,
// Field-group membership (Field.group → object.fieldGroups[].key) —
// read by deriveFieldGroupSections for the fieldGroups fallback.
group: (field as any).group,
});
}
setFormFields(generated);
setLoading(false);
}, [objectSchema, schema.fields, schema.customFields, schema.sections, schema.readOnly, schema.mode, dataSource]);
// Handle form submission
const handleSubmit = useCallback(async (data: Record<string, any>) => {
setIsSubmitting(true);
try {
if (!dataSource) {
if (schema.onSuccess) {
await schema.onSuccess(data);
}
// Close modal on success
schema.onOpenChange?.(false);
return data;
}
let result;
let payload = sanitizeFormData(data, objectSchema);
// FLS defence-in-depth: strip non-editable fields from payload.
// react-hook-form retains state for unmounted/disabled fields; we
// must never trust the client to omit them.
if (perms?.isLoaded) {
const stripped: Record<string, any> = {};
for (const k of Object.keys(payload)) {
if (perms.checkField(schema.objectName, k, 'write')) stripped[k] = payload[k];
}
payload = stripped;
}
if (schema.mode === 'create') {
result = await dataSource.create(schema.objectName, payload);
} else if (schema.mode === 'edit' && schema.recordId) {
result = await dataSource.update(schema.objectName, schema.recordId, payload);
}
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]);
// 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]);
const formLayout = (schema.layout === 'vertical' || schema.layout === 'horizontal')
? schema.layout
: 'vertical';
// Build base form schema
// Actions are hidden inside the form renderer — we render them in a sticky footer instead
const showSubmit = schema.showSubmit !== false && schema.mode !== 'view';
const showCancel = schema.showCancel !== false;
const submitLabel = schema.submitText || (schema.mode === 'create' ? 'Create' : 'Update');
const cancelLabel = schema.cancelText || 'Cancel';
const baseFormSchema = {
type: 'form' as const,
objectName: schema.objectName,
layout: formLayout,
defaultValues: formData,
submitLabel,
cancelLabel,
showSubmit,
showCancel,
onSubmit: handleSubmit,
onCancel: handleCancel,
onDirtyChange: setIsDirty, // Feed unsaved-changes state up to the close guard
showActions: false, // Hide actions — rendered in sticky footer
id: formId, // Link external submit button via form attribute
};
const renderContent = () => {
if (error) {
return (
<div className="p-4 border border-red-300 bg-red-50 rounded-md">
<h3 className="text-red-800 font-semibold">Error loading form</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.
//
// Every section's fields share a single SchemaRenderer, i.e. one
// react-hook-form instance and one <form> element (#2153/#2959). Rendering a
// form PER section broke the modal in two ways: the footer submit button,
// associated by `form={formId}`, can only reach the FIRST form, so section
// 2+ silently dropped everything the user typed; and in the tabbed variant
// Radix unmounted the inactive panel, destroying that tab's form state
// outright. Same single-form pattern as ObjectForm / DrawerForm.
if (schema.sections?.length) {
const sections = schema.sections;
const sectionKey = (sec: ModalFormSectionConfig, i: number) => sec.name || sec.label || String(i);
// Section headers go through the same i18n hook ObjectForm uses, so a
// translated group label wins over the raw metadata label.
const sectionTitle = (sec: ModalFormSectionConfig) =>
sec.name ? sectionLabel(schema.objectName, sec.name, sec.label || sec.name) : sec.label;
// The form is ONE grid. Its width is the explicit form `columns`, else the
// widest section; each section then lays ITS fields out at its own
// declared density within that grid via colSpan (#2578), exactly like the
// full-page sectioned form.
const clampCol = (n: unknown): number | undefined =>
typeof n === 'number' && n > 0 ? Math.min(Math.floor(n), 4) : undefined;
const declaredCols = sections
.map((s) => clampCol(s.columns))
.filter((c): c is number => c != null);
const formColumns = (clampCol(schema.columns)
?? (declaredCols.length ? Math.max(...declaredCols) : 1)) as 1 | 2 | 3 | 4;
const containerFieldClass = CONTAINER_GRID_COLS[formColumns];
// FLS first, so a section whose every field is non-readable drops out
// entirely (header included) instead of leaving an empty group.
const groups = sections
.map((section, index) => {
const body = applyFieldPerms(buildSectionFields(section));
return {
key: sectionKey(section, index),
title: sectionTitle(section),
description: section.description,
className: section.className,
gridClassName: section.gridClassName,
fields: formColumns > 1
? applyAutoColSpan(body, formColumns, clampCol(section.columns))
: body,
};
})
.filter((g) => g.fields.length > 0);
const sharedFormSchema = {
...baseFormSchema,
columns: formColumns,
...(containerFieldClass ? { fieldContainerClass: containerFieldClass } : {}),
};
// ADR-0050 (#1890): a modal can host a tabbed layout — sections render as
// tabs (label on the trigger) instead of a vertical stack, so a modal
// create/edit form composes with `tabbed`. The renderer owns the tab strip
// and panels (`fieldTabs`) so all tabs stay mounted inside the one form.
if (schema.contentLayout === 'tabbed' && groups.length > 1) {
return (
<SchemaRenderer
schema={{
...sharedFormSchema,
fields: groups.flatMap((g) => g.fields),
fieldTabs: groups.map((g, index) => ({
key: g.key,
label: g.title || `Section ${index + 1}`,
description: g.description,
fields: g.fields.map((f) => f.name),
containerClass: g.gridClassName,
})),
}}
/>
);
}
// Stacked sections: a virtual `section-divider` field carries each group's
// header inline. (A per-section Card would need a per-section form, which
// is the defect above; `section.gridClassName` therefore has no per-section
// grid to override here.)
const allFields: FormField[] = [];
groups.forEach((g) => {
if (g.title || g.description) {
allFields.push({
name: `__section_${g.key}`,
label: g.title,
description: g.description,
type: 'section-divider',
colSpan: 4,
className: g.className,
} as any);
}
allFields.push(...g.fields);
});
return <SchemaRenderer schema={{ ...sharedFormSchema, fields: allFields }} />;
}
// Derived field-group sections (object `fieldGroups` metadata) — rendered
// as ONE form with virtual 'section-divider' headers (same pattern as
// DrawerForm), so every group's fields share a single react-hook-form
// instance and the footer submit collects them all.
if (derivedSections?.length) {
const columns = (Number(derivedSections[0]?.columns) || 1) as 1 | 2 | 3 | 4;
const allFields: FormField[] = [];
derivedSections.forEach((section, index) => {
// FLS first, so a group whose every field is non-readable drops its
// header along with its fields.
const body = applyFieldPerms(buildSectionFields(section));
if (!body.length) return;
const title = section.name
? sectionLabel(schema.objectName, section.name, section.label || section.name)
: section.label;
if (title) {
allFields.push({
name: `__section_${section.name || index}`,
label: title,
type: 'section-divider',
} as any);
}
allFields.push(...(columns > 1 ? applyAutoColSpan(body, columns) : body));
});
const groupedContainerClass = CONTAINER_GRID_COLS[columns];
return (
<SchemaRenderer
schema={{
...baseFormSchema,
fields: allFields,
columns,
...(groupedContainerClass ? { fieldContainerClass: groupedContainerClass } : {}),
}}
/>
);
}
// Reuse pre-computed auto-layout result for flat fields
const layoutResult = autoLayoutResult ?? applyAutoLayout(formFields, objectSchema, schema.columns, schema.mode);
// Flat fields layout — use container-query grid classes so the form
// responds to the modal width, not the viewport width.
const containerFieldClass = CONTAINER_GRID_COLS[layoutResult.columns || 1];
return (
<SchemaRenderer
schema={{
...baseFormSchema,
fields: applyFieldPerms(layoutResult.fields),
columns: layoutResult.columns,
...(containerFieldClass ? { fieldContainerClass: containerFieldClass } : {}),
}}
/>
);
};
// Master-detail in a modal: when the schema declares inline child collections,
// render the master-detail form inside the dialog (it owns its own Save/Cancel
// action bar, so the modal footer is suppressed). Persisted atomically.
const subforms = (schema as any).subforms as any[] | undefined;
// Design/preview surfaces render this live on a canvas; a portalled modal Dialog
// would lock the whole editor (Radix sets body pointer-events:none + a focus trap
// while open). Render the form body inline instead — a hard backstop complementing
// the schema-level coercion the preview surfaces apply. (The master-detail line
// items are omitted in preview; the base field layout is what the canvas shows.)
if (previewMode) {
return (
<div className="@container rounded-md border bg-card p-4">
{(schema.title || schema.description) && (
<div className="mb-3 space-y-0.5">
{schema.title && <div className="text-sm font-semibold">{schema.title}</div>}
{schema.description && <p className="text-xs text-muted-foreground">{schema.description}</p>}
</div>
)}
{renderContent()}
</div>
);
}
if (subforms?.length && schema.mode !== 'view') {
return (
<Dialog open={isOpen} onOpenChange={schema.onOpenChange}>
<MobileDialogContent className={cn(sizeClass, 'flex flex-col h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-hidden p-0', className, schema.className)}>
{(schema.title || schema.description) && (
<DialogHeader className="shrink-0 px-4 pt-4 sm:px-6 sm:pt-6 pb-2 border-b">
{schema.title && <DialogTitle>{schema.title}</DialogTitle>}
{schema.description ? (
<DialogDescription>{schema.description}</DialogDescription>
) : (
<DialogDescription className="sr-only">Enter the record and its line items, then save.</DialogDescription>
)}
</DialogHeader>
)}
<div className="@container flex-1 overflow-y-auto px-4 sm:px-6 py-4">
<MasterDetailForm
schema={{
type: 'object-master-detail-form',
objectName: schema.objectName,
mode: schema.mode === 'edit' ? 'edit' : 'create',
recordId: schema.recordId,
fields: schema.fields as any,
sections: schema.sections as any,
// Forward create-mode prefills (e.g. a subtable child's parent
// pre-link, #2604) — MasterDetailForm consumes them the same
// way the flat form path does.
initialValues: schema.initialValues,
initialData: schema.initialData,
submitText: submitLabel,
cancelText: cancelLabel,
details: subforms as any,
onSuccess: async (rec: any) => { await schema.onSuccess?.(rec); schema.onOpenChange?.(false); },
onError: schema.onError,
onCancel: () => schema.onOpenChange?.(false),
}}
dataSource={dataSource}
/>
</div>
</MobileDialogContent>
</Dialog>
);
}
const hasFooter = !loading && !error && (showSubmit || showCancel);
return (
<Dialog
open={isOpen}
onOpenChange={(open) => {
// Radix routes backdrop click, Escape, and the X button all through
// here. Intercept closes so unsaved input isn't silently discarded.
if (open) { schema.onOpenChange?.(true); return; }
attemptClose(false);
}}
>
<MobileDialogContent className={cn(sizeClass, 'flex flex-col h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-hidden p-0', className, schema.className)}>
{(schema.title || schema.description) && (
<DialogHeader className="shrink-0 px-4 pt-4 sm:px-6 sm:pt-6 pb-2 border-b">
{schema.title && <DialogTitle>{schema.title}</DialogTitle>}
{schema.description ? (
<DialogDescription>{schema.description}</DialogDescription>
) : (
<DialogDescription className="sr-only">
Complete the form fields, then submit or cancel.
</DialogDescription>
)}
</DialogHeader>
)}
<div className="@container flex-1 overflow-y-auto px-4 sm:px-6 py-4">
{renderContent()}
</div>
{/* Sticky footer — always visible action buttons */}
{hasFooter && (
<div className="shrink-0 border-t px-4 sm:px-6 py-3 bg-background" data-testid="modal-form-footer">
<div className="flex flex-col sm:flex-row gap-2 sm:justify-end">
{showCancel && (
<Button
type="button"
variant="outline"
onClick={handleCancel}
disabled={isSubmitting}
className="w-full sm:w-auto"
>
{cancelLabel}
</Button>
)}
{showSubmit && (
<Button
type="submit"
form={formId}
disabled={isSubmitting}
className="w-full sm:w-auto"
>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{submitLabel}
</Button>
)}
</div>
</div>
)}
{/* Unsaved-changes guard — rendered INSIDE DialogContent so its portal
inherits the Dialog's Radix layer context (focus scope + dismissable
layer) through React. As a sibling of <Dialog> it had no such
context, so the still-open modal swallowed its button clicks and
"Keep editing" did nothing. Nesting lets Radix stack the two modals
correctly: the alert becomes the topmost layer and its buttons work. */}
<AlertDialog open={discardOpen} onOpenChange={setDiscardOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('form.discardTitle')}</AlertDialogTitle>
<AlertDialogDescription>
{t('form.discardMessage')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => { cancelIntentRef.current = false; }}>
{t('form.keepEditing')}
</AlertDialogCancel>
<AlertDialogAction onClick={finalizeClose}>
{t('form.discard')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</MobileDialogContent>
</Dialog>
);
};
export default ModalForm;