-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSplitForm.tsx
More file actions
311 lines (279 loc) · 9.72 KB
/
Copy pathSplitForm.tsx
File metadata and controls
311 lines (279 loc) · 9.72 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
/**
* 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'
*/
import React, { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import type { FormField, DataSource } from '@object-ui/types';
import {
ResizablePanelGroup,
ResizablePanel,
ResizableHandle,
cn,
} from '@object-ui/components';
import { FormSection } from './FormSection';
import { SchemaRenderer, useSafeFieldLabel } from '@object-ui/react';
import { buildSectionFields as buildSectionFieldsShared } from './sectionFields';
import { sectionFormLayout } 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 Card wrapper. */
className?: string;
/** Custom CSS class for the section's field grid. */
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;
// 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]);
// Collect all fields for a unified form submission
const allFields: FormField[] = useMemo(
() => schema.sections.flatMap(section => buildSectionFields(section)),
[schema.sections, buildSectionFields]
);
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>
);
}
// Build base form schema for SchemaRenderer
const baseFormSchema = {
type: 'form' as const,
objectName: schema.objectName,
layout: 'vertical' as const,
defaultValues: formData,
onSubmit: handleSubmit,
onCancel: handleCancel,
};
const renderSections = (sections: SplitFormSectionConfig[], showButtons: boolean) => (
<div className="space-y-6 p-4">
{sections.map((section, index) => (
<FormSection
key={section.name || section.label || index}
label={section.label}
description={section.description}
columns={1}
className={section.className}
gridClassName={section.gridClassName}
>
<SchemaRenderer
schema={{
...baseFormSchema,
// Multi-column lives on the field container inside the form, not
// as a grid wrapped around the whole form (which leaves the extra
// columns empty). See sectionFormLayout.
...sectionFormLayout(buildSectionFields(section), section.columns || 1),
showSubmit: showButtons && schema.showSubmit !== false && schema.mode !== 'view',
showCancel: showButtons && schema.showCancel !== false,
submitLabel: schema.submitText || (schema.mode === 'create' ? 'Create' : 'Update'),
cancelLabel: schema.cancelText,
}}
/>
</FormSection>
))}
</div>
);
return (
<div className={cn('w-full', className, schema.className)}>
<ResizablePanelGroup orientation={direction as 'horizontal' | 'vertical'} className="min-h-[300px] rounded-lg border">
{/* Left / Top Panel */}
<ResizablePanel defaultSize={panelSize} minSize={20}>
{renderSections(leftSections, rightSections.length === 0)}
</ResizablePanel>
{rightSections.length > 0 && (
<>
<ResizableHandle withHandle={schema.splitResizable !== false} />
{/* Right / Bottom Panel */}
<ResizablePanel defaultSize={100 - panelSize} minSize={20}>
{renderSections(rightSections, true)}
</ResizablePanel>
</>
)}
</ResizablePanelGroup>
</div>
);
};
export default SplitForm;