-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSplitForm.tsx
More file actions
352 lines (321 loc) · 12.1 KB
/
Copy pathSplitForm.tsx
File metadata and controls
352 lines (321 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/**
* 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.
*/
/**
* SplitForm Component
*
* A form variant that displays sections in a resizable split-panel layout.
* The first section renders in the left/top panel, remaining sections in the right/bottom panel.
* Aligns with @objectstack/spec FormView type: 'split'
*
* Both panels are ONE form (#2153). The panel group is a layout the form
* renderer owns via `FormSchema.fieldPanes`, so a single `<form>` /
* react-hook-form instance spans the divider. Rendering a form per panel — per
* SECTION, in fact — meant an action bar submitted only its own section and
* silently dropped everything typed on the other side, and a field condition
* could not see across the split at all.
*/
import React, { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import type { FormField, DataSource } from '@object-ui/types';
import { cn } from '@object-ui/components';
import { SchemaRenderer, useSafeFieldLabel } from '@object-ui/react';
import { buildSectionFields as buildSectionFieldsShared } from './sectionFields';
import { applyAutoColSpan, containerGridColsFor } from './autoLayout';
export interface SplitFormSectionConfig {
name?: string;
label?: string;
description?: string;
columns?: 1 | 2 | 3 | 4;
fields: (string | FormField)[];
/** Custom CSS class for the section's header row. */
className?: string;
/**
* Custom CSS class for the section's field grid. Applied to the panel's grid
* when that panel holds this section alone (the common case — the first
* section owns the left/top panel); a panel stacking several sections shares
* one grid inside the single form (#2153), so there is none to override.
*/
gridClassName?: string;
}
export interface SplitFormSchema {
type: 'object-form';
formType: 'split';
objectName: string;
mode: 'create' | 'edit' | 'view';
recordId?: string | number;
sections: SplitFormSectionConfig[];
/**
* Split direction.
* @default 'horizontal'
*/
splitDirection?: 'horizontal' | 'vertical';
/**
* Size of the first panel (percentage 1-99).
* @default 50
*/
splitSize?: number;
/**
* Whether panels can be resized.
* @default true
*/
splitResizable?: boolean;
/**
* Grid width for the whole form (1–4). Aligns with @objectstack/spec
* FormView.columns and OUTRANKS the per-section `columns`, which say how a
* section fills the grid rather than how wide it is. Omitted = the widest
* section's density.
*/
columns?: number;
// Common form props
showSubmit?: boolean;
submitText?: string;
showCancel?: boolean;
cancelText?: string;
initialValues?: Record<string, any>;
initialData?: Record<string, any>;
readOnly?: boolean;
onSuccess?: (data: any) => void | Promise<void>;
onError?: (error: Error) => void;
onCancel?: () => void;
className?: string;
}
export interface SplitFormProps {
schema: SplitFormSchema;
dataSource?: DataSource;
className?: string;
}
export const SplitForm: React.FC<SplitFormProps> = ({
schema,
dataSource,
className,
}) => {
const { fieldLabel } = useSafeFieldLabel();
const [objectSchema, setObjectSchema] = useState<any>(null);
const [formData, setFormData] = useState<Record<string, any>>({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
// 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.
if (loadedRecordIdRef.current !== schema.recordId) setLoading(true);
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: SplitFormSectionConfig): FormField[] =>
buildSectionFieldsShared(section as any, {
objectSchema,
objectName: schema.objectName,
readOnly: schema.readOnly,
mode: schema.mode,
fieldLabel,
}),
[objectSchema, schema.readOnly, schema.mode, schema.objectName, fieldLabel],
);
// Handle form submission
const handleSubmit = useCallback(async (data: Record<string, any>) => {
if (!dataSource) {
if (schema.onSuccess) {
await schema.onSuccess(data);
}
return data;
}
try {
let result;
if (schema.mode === 'create') {
result = await dataSource.create(schema.objectName, data);
} else if (schema.mode === 'edit' && schema.recordId) {
result = await dataSource.update(schema.objectName, schema.recordId, data);
}
if (schema.onSuccess) {
await schema.onSuccess(result);
}
return result;
} catch (err) {
if (schema.onError) {
schema.onError(err as Error);
}
throw err;
}
}, [schema, dataSource]);
// Handle cancel
const handleCancel = useCallback(() => {
if (schema.onCancel) {
schema.onCancel();
}
}, [schema]);
// Split sections: first section in panel 1, rest in panel 2
const leftSections = useMemo(() => schema.sections.slice(0, 1), [schema.sections]);
const rightSections = useMemo(() => schema.sections.slice(1), [schema.sections]);
const direction = schema.splitDirection || 'horizontal';
const panelSize = schema.splitSize || 50;
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="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>
);
}
// The form is ONE grid; each section then lays ITS fields out at its own
// declared density within that grid via colSpan (#2578) — the same arrangement
// the stacked/tabbed sectioned forms use. The grid lives on the FIELD
// container inside the form, never wrapped around the form (that leaves the
// extra columns permanently empty, #2128).
//
// Grid width: the form view's own `columns` first (spec FormView.columns),
// else the widest section. Same precedence ObjectForm's simple path and
// ModalForm use, so one piece of metadata lays out the same in every host.
const clampCol = (n: unknown): number | undefined =>
typeof n === 'number' && n > 0 ? Math.min(Math.floor(n), 4) : undefined;
const declaredCols = schema.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 = containerGridColsFor(formColumns);
/**
* One panel's field list: each section contributes an inline `section-divider`
* header row followed by its fields. A per-section Card would need a
* per-section form, which is the defect above.
*/
const paneFields = (sections: SplitFormSectionConfig[], paneKey: string): FormField[] => {
const out: FormField[] = [];
sections.forEach((section, index) => {
const body = buildSectionFields(section);
if (!body.length) return;
if (section.label || section.description) {
out.push({
name: `__section_${section.name || `${paneKey}_${index}`}`,
label: section.label,
description: section.description,
type: 'section-divider',
colSpan: 4,
className: section.className,
} as any);
}
out.push(
...(formColumns > 1
? applyAutoColSpan(body, formColumns, clampCol(section.columns))
: body),
);
});
return out;
};
// A pane holding exactly one section can still honour that section's
// `gridClassName` — it owns the panel's grid outright.
const panes = [
{ key: 'primary', sections: leftSections, defaultSize: panelSize },
{ key: 'secondary', sections: rightSections, defaultSize: 100 - panelSize },
]
.map((pane) => ({
...pane,
fields: paneFields(pane.sections, pane.key),
containerClass: pane.sections.length === 1 ? pane.sections[0].gridClassName : undefined,
}))
.filter((pane) => pane.fields.length > 0);
return (
<div className={cn('w-full @container', className, schema.className)}>
<SchemaRenderer
schema={{
type: 'form' as const,
objectName: schema.objectName,
// Every pane's fields, in one list, for the one form instance. The
// panes below claim them back by name for layout only.
fields: panes.flatMap((pane) => pane.fields),
columns: formColumns,
...(containerFieldClass ? { fieldContainerClass: containerFieldClass } : {}),
layout: 'vertical' as const,
defaultValues: formData,
submitLabel: schema.submitText || (schema.mode === 'create' ? 'Create' : 'Update'),
cancelLabel: schema.cancelText,
showSubmit: schema.showSubmit !== false && schema.mode !== 'view',
showCancel: schema.showCancel !== false,
onSubmit: handleSubmit,
onCancel: handleCancel,
// A single pane is not a split — the renderer then falls back to a
// plain field list rather than a one-panel resizable group.
fieldPanes: panes.map((pane) => ({
key: pane.key,
fields: pane.fields.map((f) => f.name),
defaultSize: pane.defaultSize,
...(pane.containerClass ? { containerClass: pane.containerClass } : {}),
})),
fieldPanesOrientation: direction,
fieldPanesResizable: schema.splitResizable !== false,
}}
/>
</div>
);
};
export default SplitForm;