-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathObjectForm.tsx
More file actions
1049 lines (963 loc) · 41.3 KB
/
Copy pathObjectForm.tsx
File metadata and controls
1049 lines (963 loc) · 41.3 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 { mapFieldTypeToFormType, buildValidationRules, formatFileSize } from '@object-ui/fields';
import { useIsMobile, toast } from '@object-ui/components';
import { resolveCrudAffordances } from '@object-ui/core';
import { resolveSuccessNavigate, isSameOriginUrl } from './successBehavior';
import { usePermissions } from '@object-ui/permissions';
import { TabbedForm } from './TabbedForm';
import { WizardForm } from './WizardForm';
import { SplitForm } from './SplitForm';
import { DrawerForm } from './DrawerForm';
import { ModalForm } from './ModalForm';
import { MasterDetailForm } from './MasterDetailForm';
import {
applyAutoLayout,
applyAutoColSpan,
containerGridColsFor,
filterAutoGeneratedFields,
filterSystemFields,
inferColumns,
} from './autoLayout';
import { deriveFieldGroupSections } from './fieldGroups';
import { sanitizeFormData } from './sanitize';
export interface ObjectFormProps {
/**
* 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;
}
/**
* 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}
* />
* ```
*/
export const ObjectForm: React.FC<ObjectFormProps> = ({
schema: rawSchema,
dataSource,
}) => {
const perms = usePermissions();
// Apply field-level permissions to the entire schema (sections + flat
// fields) BEFORE dispatching to any variant. This way all variants
// (Tabbed/Wizard/Split/Drawer/Modal/Simple) transparently honour FLS.
// Fail-open when no provider mounted (perms.isLoaded false).
const schema = useMemo<ObjectFormProps['schema']>(() => {
// #2545: spec FormViewSchema defines `groups` as a legacy alias of
// `sections`, and this renderer only ever consumes `sections` — normalize
// FIRST so groups-only metadata actually renders (it used to be silently
// ignored). Legacy shape maps `title`→`label`, `defaultCollapsed`→`collapsed`.
const legacyGroups = (rawSchema as any).groups;
const base: ObjectFormProps['schema'] =
!rawSchema.sections?.length && Array.isArray(legacyGroups) && legacyGroups.length
? {
...rawSchema,
sections: legacyGroups.map((g: any) => ({
label: g.title ?? g.label,
description: g.description,
collapsible: g.collapsible,
collapsed: g.defaultCollapsed ?? g.collapsed,
fields: g.fields ?? [],
})),
}
: rawSchema;
if (!perms?.isLoaded) return base;
const gateField = (f: any) => {
if (!f?.name) return f;
const canRead = perms.checkField(base.objectName, f.name, 'read');
if (!canRead) return null;
const canWrite = perms.checkField(base.objectName, f.name, 'write');
if (!canWrite && base.mode !== 'view') {
return { ...f, readOnly: true, disabled: true };
}
return f;
};
const filterArr = (arr?: any[]) =>
Array.isArray(arr) ? arr.map(gateField).filter(Boolean) : arr;
return {
...base,
fields: filterArr(base.fields as any[]),
sections: base.sections?.map((s: any) => ({
...s,
fields: filterArr(s.fields),
})),
} as ObjectFormProps['schema'];
}, [rawSchema, perms]);
const { sectionLabel } = useSafeFieldLabel();
const tSec = (s: any) =>
s?.name ? sectionLabel(schema.objectName, s.name, s.label || s.name) : s?.label;
// 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).
// For drawer/modal formTypes we fall through to DrawerForm/ModalForm, which
// host the master-detail form INSIDE their envelope.
if ((schema as any).subforms?.length && schema.mode !== 'view'
&& schema.formType !== 'drawer' && schema.formType !== 'modal') {
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',
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,
onCancel: 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,
fields: s.fields,
className: (s as any).className,
gridClassName: (s as any).gridClassName,
})),
defaultTab: schema.defaultTab,
tabPosition: schema.tabPosition,
}}
dataSource={dataSource}
className={schema.className}
/>
);
}
if (schema.formType === 'wizard' && schema.sections?.length) {
return (
<WizardForm
schema={{
...schema,
formType: 'wizard',
sections: schema.sections.map(s => ({
name: s.name,
label: tSec(s),
description: s.description,
columns: s.columns,
fields: s.fields,
className: (s as any).className,
gridClassName: (s as any).gridClassName,
})),
allowSkip: schema.allowSkip,
showStepIndicator: schema.showStepIndicator,
nextText: schema.nextText,
prevText: schema.prevText,
onStepChange: schema.onStepChange,
}}
dataSource={dataSource}
className={schema.className}
/>
);
}
if (schema.formType === 'split' && schema.sections?.length) {
return (
<SplitForm
schema={{
...schema,
formType: 'split',
sections: schema.sections.map(s => ({
name: s.name,
label: tSec(s),
description: s.description,
columns: s.columns,
fields: s.fields,
className: (s as any).className,
gridClassName: (s as any).gridClassName,
})),
splitDirection: schema.splitDirection,
splitSize: schema.splitSize,
splitResizable: schema.splitResizable,
}}
dataSource={dataSource}
className={schema.className}
/>
);
}
if (schema.formType === 'drawer') {
const { layout: _layout, ...drawerRest } = schema;
const drawerLayout = (schema.layout === 'vertical' || schema.layout === 'horizontal') ? schema.layout : undefined;
return (
<DrawerForm
schema={{
...drawerRest,
layout: drawerLayout,
formType: 'drawer',
sections: schema.sections?.map(s => ({
name: s.name,
label: tSec(s),
description: s.description,
columns: s.columns,
fields: s.fields,
collapsible: (s as any).collapsible,
collapsed: (s as any).collapsed,
className: (s as any).className,
})),
open: schema.open,
onOpenChange: schema.onOpenChange,
drawerSide: schema.drawerSide,
drawerWidth: schema.drawerWidth,
}}
dataSource={dataSource}
className={schema.className}
/>
);
}
if (schema.formType === 'modal') {
const { layout: _layout2, ...modalRest } = schema;
const modalLayout = (schema.layout === 'vertical' || schema.layout === 'horizontal') ? schema.layout : undefined;
return (
<ModalForm
schema={{
...modalRest,
layout: modalLayout,
formType: 'modal',
sections: schema.sections?.map(s => ({
name: s.name,
label: tSec(s),
description: s.description,
columns: s.columns,
fields: s.fields,
className: (s as any).className,
gridClassName: (s as any).gridClassName,
})),
open: schema.open,
onOpenChange: schema.onOpenChange,
modalSize: schema.modalSize,
modalCloseButton: schema.modalCloseButton,
}}
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.
*/
const SimpleObjectForm: React.FC<ObjectFormProps> = ({
schema,
dataSource,
}) => {
const { fieldLabel, sectionLabel } = useSafeFieldLabel();
const isMobile = useIsMobile();
// 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 applyFieldPerms = useCallback(
(fields: FormField[]): FormField[] => {
if (!perms?.isLoaded) return fields;
const out: FormField[] = [];
for (const f of fields) {
const canRead = perms.checkField(schema.objectName, f.name, 'read');
if (!canRead) continue; // omit hidden fields entirely
const canWrite = perms.checkField(schema.objectName, f.name, 'write');
if (!canWrite && schema.mode !== 'view') {
out.push({
...f,
readOnly: true,
disabled: true,
description: f.description ?? 'You do not have edit access to this field.',
});
} else {
out.push(f);
}
}
return out;
},
[perms, schema.objectName, schema.mode],
);
const [objectSchema, setObjectSchema] = useState<any>(null);
const [formFields, setFormFields] = useState<FormField[]>([]);
const [initialData, setInitialData] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
// 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).
const [submitted, setSubmitted] = useState<{ title?: string; message?: string } | null>(null);
// Check if using inline fields (fields defined as objects, not just names)
const hasInlineFields = schema.customFields && schema.customFields.length > 0;
// Initialize with inline data if provided
useEffect(() => {
if (hasInlineFields) {
setInitialData(schema.initialData || schema.initialValues || {});
setLoading(false);
}
}, [hasInlineFields, schema.initialData, schema.initialValues]);
// Fetch object schema from ObjectQL/ObjectStack (skip if using inline fields)
useEffect(() => {
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 (!schemaData) {
throw new Error(`No schema found for object "${schema.objectName}"`);
}
setObjectSchema(schemaData);
} catch (err) {
setError(err as Error);
setLoading(false);
}
};
// Skip fetching if we have inline fields
if (hasInlineFields) {
// Use a minimal schema for inline fields
setObjectSchema({
name: schema.objectName,
fields: {} as Record<string, any>,
});
} else if (schema.objectName && dataSource) {
fetchObjectSchema();
} else if (!hasInlineFields) {
// No objectName or dataSource and no inline fields — cannot proceed
setLoading(false);
}
}, [schema.objectName, dataSource, hasInlineFields]);
// Fetch initial data for edit/view modes (skip if using inline data)
useEffect(() => {
const fetchInitialData = async () => {
if (!schema.recordId || schema.mode === 'create') {
setInitialData(schema.initialData || schema.initialValues || {});
setLoading(false);
return;
}
// Skip fetching if using inline data
if (hasInlineFields) {
return;
}
if (!dataSource) {
setError(new Error('DataSource is required for fetching record data (inline data not provided)'));
setLoading(false);
return;
}
setLoading(true);
try {
const data = await dataSource.findOne(schema.objectName, schema.recordId);
setInitialData(data);
} catch (err) {
console.error('Failed to fetch record:', err);
setError(err as Error);
} finally {
setLoading(false);
}
};
if (objectSchema && !hasInlineFields) {
fetchInitialData();
}
}, [schema.objectName, schema.recordId, schema.mode, schema.initialValues, schema.initialData, dataSource, objectSchema, hasInlineFields]);
// 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 or inline fields
useEffect(() => {
// For inline fields, use them directly
if (hasInlineFields && schema.customFields) {
setFormFields(schema.customFields.map(normalizeVisibility));
setLoading(false);
return;
}
if (!objectSchema) return;
const generatedFields: FormField[] = [];
// Managed-object blanket lock (ADR-0092 D4 / ADR-0103). We disable every
// field when the object's resolved CRUD affordance for the CURRENT mode is
// closed — `edit` for edit mode, `create` for create mode. This routes
// through the SAME shared `resolveCrudAffordances` policy the detail
// (`isObjectInlineEditable`) and grid surfaces use, instead of re-deriving
// the bucket lock here: `platform` and admin-editable `config` resolve open;
// engine-owned `system` / `append-only` / `better-auth` resolve closed
// unless the object OPENED per-record writing via `userActions.{edit,create}`
// (e.g. sys_user opens `edit` for its profile fields). When open, the lock
// lifts and each field's own `readonly` flag decides. The server-side write
// guard remains the real boundary; this is UX only.
const affordances = resolveCrudAffordances(objectSchema as any);
const modeAffordanceOpen =
schema.mode === 'edit'
? affordances.edit
: schema.mode === 'create'
? affordances.create
: true; // view mode disables fields elsewhere — never double-lock here
const managedBlanketLock = !modeAffordanceOpen;
// 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);
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) return;
const field = objectSchema.fields?.[name];
if (!field && !hasInlineFields) return; // Skip if not found in object definition unless inline
// Check field-level permissions for create/edit modes
const hasWritePermission = !field?.permissions || field?.permissions.write !== false;
if (schema.mode !== 'view' && !hasWritePermission) return; // Skip fields without write permission
// Check if there's a custom field configuration
const customField = schema.customFields?.find(f => f.name === name);
if (customField) {
generatedFields.push(normalizeVisibility(customField));
} else if (field) {
// Auto-generate field from schema
const formField: FormField = {
name: name,
label: fieldLabel(schema.objectName, name, field.label || fieldName),
type: mapFieldTypeToFormType(field.type),
required: field.required || false,
disabled: schema.readOnly || schema.mode === 'view' || field.readonly || managedBlanketLock,
placeholder: field.placeholder,
description: field.help || field.description,
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.conditionalRequired,
// 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 (e.g. capability-multiselect stamped onto
// sys_permission_set.system_permissions by MetadataProvider, ADR-0056
// P2). `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,
};
// Add field-specific properties
if (field.type === 'select' || field.type === 'lookup' || field.type === 'master_detail') {
formField.options = field.options || [];
formField.multiple = field.multiple;
}
if (field.type === 'number' || field.type === 'currency' || field.type === 'percent') {
formField.inputType = 'number';
formField.min = field.min;
formField.max = field.max;
formField.step = field.precision ? Math.pow(10, -field.precision) : undefined;
}
if (field.type === 'date') {
formField.inputType = 'date';
}
if (field.type === 'datetime') {
formField.inputType = 'datetime-local';
}
if (field.type === 'text' || field.type === 'textarea' || field.type === 'markdown' || field.type === 'html') {
formField.maxLength = field.max_length;
formField.minLength = field.min_length;
}
if (field.type === 'file' || field.type === 'image') {
formField.inputType = 'file';
formField.multiple = field.multiple;
formField.accept = field.accept ? field.accept.join(',') : undefined;
// Add validation hints for file size and dimensions
if (field.max_size) {
const sizeHint = `Max size: ${formatFileSize(field.max_size)}`;
formField.description = formField.description
? `${formField.description} (${sizeHint})`
: sizeHint;
}
}
if (field.type === 'email') {
formField.inputType = 'email';
}
if (field.type === 'phone') {
formField.inputType = 'tel';
}
if (field.type === 'url') {
formField.inputType = 'url';
}
if (field.type === 'password') {
formField.inputType = 'password';
}
if (field.type === 'time') {
formField.inputType = 'time';
}
// Read-only fields for computed types
if (field.type === 'formula' || field.type === 'summary' || field.type === 'auto_number') {
formField.disabled = true;
}
// Conditional visibility (legacy snake_case `visible_on`) — carry it
// as `visibleOn` so the form renderer evaluates it with the canonical
// CEL engine; the old `visible()` closure was never called (#2212).
if (field.visible_on) {
(formField as any).visibleOn = field.visible_on;
}
generatedFields.push(formField);
}
});
setFormFields(generatedFields);
// Only set loading to false if we are not going to fetch data
// This prevents a flash of empty form before data is loaded in edit mode
const willFetchData = !hasInlineFields && (schema.recordId && schema.mode !== 'create' && dataSource);
if (!willFetchData) {
setLoading(false);
}
}, [objectSchema, schema.fields, schema.customFields, schema.readOnly, schema.mode, hasInlineFields, schema.recordId, dataSource]);
// Handle form submission
const handleSubmit = useCallback(async (formData: any, e?: any) => {
// If we receive an event as the first argument, it means the Form renderer passed the event instead of data
// This happens when react-hook-form's handleSubmit is bypassed or configured incorrectly
if (formData && (formData.nativeEvent || formData._reactName === 'onSubmit')) {
console.warn('ObjectForm: Received Event instead of data in handleSubmit! This suggests a Form renderer issue.');
// Proceed defensively - we can't do much if we don't have data, but let's try to not crash
// If we are here, formData is actually the event
if (e === undefined) {
// The event arrived as the first arg; discard it and submit empty data
// rather than the Event object. (`e` is unused beyond this guard.)
formData = {}; // Reset to empty object or we try to submit the Event object
}
}
// For inline fields without a dataSource, just call the success callback
if (hasInlineFields && !dataSource) {
if (schema.onSuccess) {
await schema.onSuccess(formData);
}
return formData;
}
if (!dataSource) {
throw new Error('DataSource is required for form submission (inline mode not configured)');
}
// Strip server-managed and computed / read-only fields from the payload
// before persisting. react-hook-form retains state for unmounted/disabled
// fields (see ModalForm), so an edit form seeded from a full record read
// round-trips computed columns it never rendered — formula/summary/rollup
// values, flattened lookups, id/timestamps — which the server rejects as
// unknown or non-writable fields. Mirrors ModalForm/DrawerForm. For inline
// forms `objectSchema` is a field-less stub, so pass null to strip only the
// server-managed keys rather than dropping every (schema-less) value.
let payload = sanitizeFormData(formData, hasInlineFields ? null : objectSchema);
// FLS defence-in-depth: never trust the client to include a field the user
// lacked edit access to — drop any that fail the write check.
if (perms?.isLoaded && payload && typeof payload === 'object') {
const stripped: Record<string, unknown> = {};
for (const k of Object.keys(payload)) {
if (perms.checkField(schema.objectName, k, 'write')) {
stripped[k] = (payload as Record<string, unknown>)[k];
}
}
payload = stripped;
}
try {
let result;
if (schema.submitHandler) {
// The host owns persistence (e.g. MasterDetailForm batching the parent
// + children into one atomic transaction). The form just validates and
// hands over the values; it does NOT create/update itself.
result = await schema.submitHandler(payload);
} else 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);
} else {
throw new Error('Invalid form mode or missing record ID');
}
// Call success callback if provided, else give default feedback. Skip the
// default when a `submitHandler` owns persistence (e.g. MasterDetailForm
// already toasts) so we never double-confirm.
if (schema.onSuccess) {
await schema.onSuccess(result);
} else if (!schema.submitHandler && schema.submitBehavior) {
const behavior = schema.submitBehavior;
switch (behavior.kind) {
case 'redirect':
if (isSameOriginUrl(behavior.url)) {
setTimeout(() => window.location.assign(behavior.url), behavior.delayMs ?? 0);
}
break;
case 'continue':
// Reset is driven declaratively by `resetOnSubmit` below (mirrors
// `resetOnSuccess`) — nothing imperative to do here.
break;
case 'next-record':
case 'thank-you':
default: {
const message = behavior.kind === 'thank-you' && behavior.message
? behavior.message
: schema.successMessage || (schema.mode === 'create' ? 'Created' : 'Saved');
toast.success(message);
// Replace the (still fully filled) form with a confirmation panel
// so there's nothing left to resubmit.
setSubmitted({ title: behavior.kind === 'thank-you' ? behavior.title : undefined, message });
break;
}
}
} else if (!schema.submitHandler) {
const nav = resolveSuccessNavigate(schema.navigateOnSuccess, result);
if (nav) {
window.location.assign(nav);
return result;
}
toast.success(schema.successMessage || (schema.mode === 'create' ? 'Created' : 'Saved'));
}
return result;
} catch (err) {
console.error('Failed to submit form:', err);
// Call error callback if provided
if (schema.onError) {
schema.onError(err as Error);
}
throw err;
}
}, [schema, dataSource, hasInlineFields, perms, objectSchema]);
// Handle form cancellation
const handleCancel = useCallback(() => {
if (schema.onCancel) {
schema.onCancel();
}
}, [schema]);
// Calculate default values from schema fields
const schemaDefaultValues = React.useMemo(() => {
if (!objectSchema?.fields) return {};
const defaults: Record<string, any> = {};
Object.keys(objectSchema.fields).forEach(key => {
const field = objectSchema.fields[key];
if (field.defaultValue !== undefined) {
defaults[key] = field.defaultValue;
}
});
return defaults;
}, [objectSchema]);
const finalDefaultValues = {
...schemaDefaultValues,
...initialData
};
// Auto-layout parity with the flat path (which runs these inside
// applyAutoLayout): drop platform-managed system fields — and, in create
// mode, server-computed fields — BEFORE deriving field-group sections, so a
// grouped form hides exactly the fields the flat form hides instead of
// leaking created_at / formula columns into the trailing ungrouped bucket.
const groupableFields = React.useMemo(() => {
let fs = filterSystemFields(formFields, objectSchema);
if (schema.mode === 'create') fs = filterAutoGeneratedFields(fs, objectSchema);
return fs;
}, [formFields, objectSchema, schema.mode]);
// Auto-derive sections from the object's declared `fieldGroups` when the
// consumer hasn't supplied explicit sections. This makes field groups laid
// out in the object designer render as sections on the actual form — not just
// in the designer preview. Falls back to a flat form (null) when the object
// declares no groups or no field opts into one.
const fieldGroupSections = React.useMemo(
() =>
schema.sections?.length
? null
: deriveFieldGroupSections(groupableFields, objectSchema?.fieldGroups),
[schema.sections, groupableFields, objectSchema],
);
const effectiveSections = schema.sections?.length ? schema.sections : fieldGroupSections;
// Per-section collapse state for the simple grouped form. Keyed by section
// name/label; an unseeded key falls back to the section's declared `collapsed`
// (so a group declared `collapsed: true` starts closed without pre-seeding).
const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({});
// Render error state
if (error) {
return (
<div className="p-3 sm: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>
);
}
// Render loading state
if (loading) {
return (
<div className="p-4 sm:p-8 text-center">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
<p className="mt-2 text-sm text-gray-600">Loading form...</p>
</div>
);
}
if (submitted) {
return (
<div className="rounded-md border bg-card p-6 sm:p-8 text-center">
<h3 className="text-lg font-semibold">{submitted.title ?? 'Thanks!'}</h3>
{submitted.message && (
<p className="mt-2 text-sm text-muted-foreground">{submitted.message}</p>
)}
</div>
);
}
// Convert to FormSchema
// Note: FormSchema currently only supports 'vertical' and 'horizontal' layouts
// Map 'grid' and 'inline' to 'vertical' as fallback
const formLayout = (schema.layout === 'vertical' || schema.layout === 'horizontal')
? schema.layout
: 'vertical';
// If sections are provided (explicitly, or derived from the object's
// `fieldGroups`) for the simple form, render them as full-width, optionally
// collapsible groups.
//
// All sections share ONE SchemaRenderer / react-hook-form instance: a virtual
// `section-divider` field renders each group's header, and the group's own
// fields follow inline. This is the same single-form pattern DrawerForm uses,
// and it matters for correctness — N separate per-section <form> elements
// would each own isolated form state, so a submit (which only fired the last
// section) silently dropped every other group's edits. One form also lets
// collapse simply hide a group's fields (`hidden: true`) while react-hook-form
// retains their values, and lets cross-section conditions resolve via watch().
if (effectiveSections?.length && (!schema.formType || schema.formType === 'simple')) {
// Derived (fieldGroup) sections were computed from the filtered field list;
// explicit sections keep the authored field selection as-is.
const sourceFields = fieldGroupSections ? groupableFields : formFields;
// #2578: honour per-section `columns`. The form renders as ONE grid (one
// react-hook-form instance); each section lays its OWN fields out at its
// declared density within that grid. Grid width = explicit form `columns`,
// else the widest section, else inferred from field count (the
// fieldGroup-derived path declares no per-section columns and keeps its
// historical inferred multi-column layout).
const clampCol = (n: unknown): number | undefined =>
typeof n === 'number' && n > 0 ? Math.min(Math.floor(n), 4) : undefined;
const declaredSectionCols = effectiveSections
.map(s => clampCol((s as any).columns))
.filter((c): c is number => c != null);
const approxInputs = effectiveSections.reduce(
(n, s) => n + (Array.isArray(s.fields) ? s.fields.length : 0), 0,
);
const formColumns =
clampCol(schema.columns) ??
(declaredSectionCols.length ? Math.max(...declaredSectionCols) : inferColumns(approxInputs));
const groupedFields: FormField[] = [];
effectiveSections.forEach((section, index) => {
// Section field defs may carry a per-field `visibleOn` predicate (spec
// FormFieldSchema, #2212). The filter below matches by name only, so the
// predicate must be merged onto the resolved field or it is silently
// dropped — the form renderer evaluates it with the canonical engine.
const sectionDefByName = new Map<string, any>(
section.fields.map(f => [typeof f === 'string' ? f : ((f as any).field ?? f.name), f]),
);
const sectionFieldNames = Array.from(sectionDefByName.keys());
const sectionFields = applyFieldPerms(sourceFields.filter(f => sectionFieldNames.includes(f.name)))
.map(f => {
const def = sectionDefByName.get(f.name);
if (!def || typeof def !== 'object') return f;
// Carry the section field def's layout/visibility overrides onto the
// resolved field — the name-only filter above would otherwise drop
// them. #2578: `span`/`colSpan` are how a section controls per-field
// width; #2212: `visibleOn`.
const d = def as any;
const merged: any = { ...f };
if (d.visibleOn != null) merged.visibleOn = d.visibleOn;
if (d.colSpan != null) merged.colSpan = d.colSpan;
if (d.span != null) merged.span = d.span;
return merged as FormField;
});
if (sectionFields.length === 0) return;
const sectionKey = section.name || section.label || String(index);
// Untitled trailing bucket (ungrouped fields) renders flat — no divider.
const label = section.name
? sectionLabel(schema.objectName, section.name, section.label || section.name)
: section.label;
const isCollapsed = collapsedSections[sectionKey] ?? (section.collapsed ?? false);
if (label) {
groupedFields.push({
name: `__section_${sectionKey}`,
label,
type: 'section-divider',
colSpan: 4,
collapsible: section.collapsible,
collapsed: isCollapsed,
onToggle: section.collapsible
? () => setCollapsedSections(prev => ({ ...prev, [sectionKey]: !isCollapsed }))
: undefined,
className: (section as any).className,
} as FormField);
}
// #2578: lay THIS section's fields out at its declared column density
// within the shared form grid (span-aware; wide fields still full-row).
const secCols = clampCol((section as any).columns);
const laid = formColumns > 1 ? applyAutoColSpan(sectionFields, formColumns, secCols) : sectionFields;
// Collapsed groups keep their fields registered (values preserved) but
// hidden from the DOM. An untitled bucket is never collapsible.
if (label && isCollapsed) {
groupedFields.push(...laid.map(f => ({ ...f, hidden: true })));
} else {
groupedFields.push(...laid);
}
});
// Per-section colSpan was applied in the loop above — each section at its
// own density within the shared `formColumns` grid. The field grid uses
// container-query classes (with the @container wrapper below), so it tracks
// the form's own width: a grouped form in a wide dialog goes multi-column
// while a narrow drawer stays stacked. Section dividers span the full row.
const laidOutFields = groupedFields;
const fieldContainerClass = containerGridColsFor(formColumns);
return (
<div className="w-full @container">
<SchemaRenderer
schema={{
type: 'form',
objectName: schema.objectName,
fields: laidOutFields,
layout: formLayout,
columns: formColumns,
...(fieldContainerClass ? { fieldContainerClass } : {}),
defaultValues: finalDefaultValues,
showSubmit: schema.showSubmit !== false && schema.mode !== 'view',
showCancel: schema.showCancel !== false,
submitLabel: schema.submitText || (schema.mode === 'create' ? 'Create' : 'Update'),
cancelLabel: schema.cancelText,
onSubmit: handleSubmit,
onCancel: handleCancel,
} as FormSchema}
/>
</div>
);
}
// Apply auto-layout: infer columns and colSpan when not explicitly configured
const hasSections = schema.sections?.length;
const gatedFormFields = applyFieldPerms(formFields);
const autoLayoutResult = !hasSections
? applyAutoLayout(gatedFormFields, objectSchema, schema.columns, schema.mode)
: { fields: gatedFormFields, columns: schema.columns };
// ----- Mobile UX (round 3) -----
// 1) Propagate fullscreen-textarea opt-in to each textarea field so the
// field widget can render its expand affordance + dialog.
const mobileOpts = schema.mobile;
const fieldsWithMobile = mobileOpts?.fullscreenLongText
? autoLayoutResult.fields.map((f) => {
const t = f.type as string | undefined;
const isTextarea = t === 'textarea' || t === 'field:textarea' ||
t === 'string-multiline' || t === 'field:markdown' || t === 'field:html';
return isTextarea ? ({ ...f, mobile_fullscreen: true } as FormField) : f;
})
: autoLayoutResult.fields;
// 2) Auto-stepper: when explicitly enabled, OR when set to 'auto' on a
// long form on a small viewport, route the flat field list through
// WizardForm with one (or a few) fields per step.
const stepperMode = mobileOpts?.stepper;
const stepperMin = mobileOpts?.stepperMinFields ?? 8;
const fieldsPerStep = Math.max(1, mobileOpts?.stepperFieldsPerStep ?? 1);
const wantsStepper =
!schema.formType &&
!hasSections &&
fieldsWithMobile.length >= 2 &&
(
stepperMode === true ||
(stepperMode === 'auto' && isMobile && fieldsWithMobile.length >= stepperMin)
);
if (wantsStepper) {
const visibleFields = fieldsWithMobile;
const syntheticSections = [] as Array<{ name: string; label?: string; fields: FormField[] }>;
for (let i = 0; i < visibleFields.length; i += fieldsPerStep) {
const chunk = visibleFields.slice(i, i + fieldsPerStep);
syntheticSections.push({
name: `step-${Math.floor(i / fieldsPerStep) + 1}`,