-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathTabbedForm.tsx
More file actions
400 lines (350 loc) · 11.2 KB
/
Copy pathTabbedForm.tsx
File metadata and controls
400 lines (350 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/**
* 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.
*/
/**
* TabbedForm Component
*
* A form component that organizes sections into tabs.
* Aligns with @objectstack/spec FormView type: 'tabbed'
*/
import React, { useState, useCallback, 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 FormSectionConfig {
/**
* Section identifier (used as tab value)
*/
name?: string;
/**
* Section label (used as tab trigger text)
*/
label?: string;
/**
* Section description
*/
description?: string;
/**
* Number of columns in the section
* @default 1
*/
columns?: 1 | 2 | 3 | 4;
/**
* Field names or configurations in this section
*/
fields: (string | FormField)[];
/**
* Custom CSS class for the section's Card wrapper.
*
* Unused in the tabbed layout: all tabs share ONE form (#2959), so a tab's
* panel has no per-section Card to carry it.
*/
className?: string;
/**
* Custom CSS class for the section's field grid — applied to this tab's panel
* grid (overrides the shared column classes).
*/
gridClassName?: string;
}
export interface TabbedFormSchema {
type: 'object-form';
formType: 'tabbed';
/**
* Object name for ObjectQL schema lookup
*/
objectName: string;
/**
* Form mode
*/
mode: 'create' | 'edit' | 'view';
/**
* Record ID (for edit/view modes)
*/
recordId?: string | number;
/**
* Tab sections configuration
*/
sections: FormSectionConfig[];
/**
* Default active tab (section name)
*/
defaultTab?: string;
/**
* Tab position
* @default 'top'
*/
tabPosition?: 'top' | 'bottom' | 'left' | 'right';
/**
* Show submit button
* @default true
*/
showSubmit?: boolean;
/**
* Submit button text
*/
submitText?: string;
/**
* Show cancel button
* @default true
*/
showCancel?: boolean;
/**
* Cancel button text
*/
cancelText?: string;
/**
* Initial values
*/
initialValues?: Record<string, any>;
/**
* Initial data (alias for initialValues)
*/
initialData?: Record<string, any>;
/**
* Read-only mode
*/
readOnly?: boolean;
/**
* Callbacks
*/
onSuccess?: (data: any) => void | Promise<void>;
onError?: (error: Error) => void;
onCancel?: () => void;
/**
* CSS class
*/
className?: string;
}
export interface TabbedFormProps {
schema: TabbedFormSchema;
dataSource?: DataSource;
className?: string;
}
/**
* TabbedForm Component
*
* Renders a form with sections organized as tabs.
*
* @example
* ```tsx
* <TabbedForm
* schema={{
* type: 'object-form',
* formType: 'tabbed',
* objectName: 'contacts',
* mode: 'create',
* sections: [
* { label: 'Basic Info', fields: ['firstName', 'lastName', 'email'] },
* { label: 'Address', fields: ['street', 'city', 'country'] },
* ]
* }}
* dataSource={dataSource}
* />
* ```
*/
export const TabbedForm: React.FC<TabbedFormProps> = ({
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);
// Which tab opens first. The live tab state belongs to the form renderer from
// here on — it owns the panels, so only it can jump to the tab holding a
// rejected field on a failed submit (#2959).
const initialTab =
schema.defaultTab || schema.sections[0]?.name || schema.sections[0]?.label || 'tab-0';
// Fetch object schema
React.useEffect(() => {
const fetchSchema = async () => {
if (!dataSource) {
setLoading(false);
return;
}
try {
const schemaData = await dataSource.getObjectSchema(schema.objectName);
setObjectSchema(schemaData);
} catch (err) {
setError(err as Error);
}
};
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 for edit/view modes
React.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 || !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: FormSectionConfig): 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]);
// Generate tab value
const getTabValue = (section: FormSectionConfig, index: number): string => {
return section.name || section.label || `tab-${index}`;
};
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>
);
}
// ONE form for ALL tabs (#2959). A SchemaRenderer per tab gave each tab its
// own react-hook-form instance, and Radix unmounted the inactive panel — so
// every tab the user left behind lost its input and only the visible tab's
// fields reached the submit payload. The renderer now owns the tab strip and
// panels (`fieldTabs`): all panels stay mounted inside a single <form>, which
// is also what lets cross-tab conditions and validation see every field.
//
// Multi-column stays on the field container INSIDE the form: each tab's fields
// carry their own colSpan against the shared grid (sectionFormLayout parity),
// never a grid wrapped around the form — that would leave the extra columns
// empty (#2128).
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 = declaredCols.length ? Math.max(...declaredCols) : 1;
const containerFieldClass = containerGridColsFor(formColumns);
const tabGroups = schema.sections.map((section, index) => {
const body = buildSectionFields(section);
return {
key: getTabValue(section, index),
label: section.label || `Tab ${index + 1}`,
description: section.description,
containerClass: section.gridClassName,
fields: formColumns > 1
? applyAutoColSpan(body, formColumns, clampCol(section.columns))
: body,
};
});
const allFields: FormField[] = tabGroups.flatMap((g) => g.fields);
return (
<div className={cn('w-full @container', className, schema.className)}>
<SchemaRenderer
schema={{
type: 'form' as const,
objectName: schema.objectName,
fields: allFields,
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,
fieldTabs: tabGroups.map((g) => ({
key: g.key,
label: g.label,
description: g.description,
fields: g.fields.map((f) => f.name),
containerClass: g.containerClass,
})),
defaultFieldTab: initialTab,
fieldTabsPosition: schema.tabPosition || 'top',
}}
/>
</div>
);
};
export default TabbedForm;