-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathWizardForm.tsx
More file actions
618 lines (559 loc) · 20.1 KB
/
Copy pathWizardForm.tsx
File metadata and controls
618 lines (559 loc) · 20.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
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
/**
* 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.
*/
/**
* WizardForm Component
*
* A multi-step wizard form that guides users through sections step by step.
* Aligns with @objectstack/spec FormView type: 'wizard'
*/
import React, { useState, useCallback, useMemo } from 'react';
import type { FormField, DataSource } from '@object-ui/types';
import { Button, cn, toast } from '@object-ui/components';
import { Check, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';
import { FormSection } from './FormSection';
import { SchemaRenderer, useSafeFieldLabel } from '@object-ui/react';
import { buildSectionFields as buildSectionFieldsShared } from './sectionFields';
import { sectionFormLayout } from './autoLayout';
import { resolveSuccessNavigate, isSameOriginUrl, type SubmitBehavior } from './successBehavior';
import type { FormSectionConfig } from './TabbedForm';
export interface WizardFormSchema {
type: 'object-form';
formType: 'wizard';
/**
* Object name for ObjectQL schema lookup
*/
objectName: string;
/**
* Form mode
*/
mode: 'create' | 'edit' | 'view';
/**
* Record ID (for edit/view modes)
*/
recordId?: string | number;
/**
* Wizard step sections
*/
sections: FormSectionConfig[];
/**
* Allow navigation to any step (not just sequential)
* @default false
*/
allowSkip?: boolean;
/**
* Show step indicators
* @default true
*/
showStepIndicator?: boolean;
/**
* Text for Next button
* @default 'Next'
*/
nextText?: string;
/**
* Text for Previous button
* @default 'Back'
*/
prevText?: string;
/**
* Submit button text (shown on last step)
*/
submitText?: string;
/**
* Declarative success toast text shown when no `onSuccess` handler is given
* (metadata pages cannot pass a function). Falls back to 'Created'/'Saved'.
* Ignored when `submitBehavior` is set.
*/
successMessage?: string;
/** Navigate here after a successful create/update (declarative; metadata
* pages can't pass onSuccess). Supports `{id}`/`{recordId}` interpolation
* from the saved record. Same-origin-guarded. Takes precedence over the toast.
* Ignored when `submitBehavior` is set. */
navigateOnSuccess?: string;
/** Reset the wizard (back to step 1, cleared) after a successful create so the
* user can enter another. Ignored when `navigateOnSuccess` or `submitBehavior`
* is set. */
resetOnSuccess?: boolean;
/**
* Declarative post-submit behavior aligned with `@objectstack/spec`'s
* `FormView.submitBehavior`. When present, takes precedence over
* `successMessage` / `navigateOnSuccess` / `resetOnSuccess`.
*/
submitBehavior?: SubmitBehavior;
/**
* Show cancel button
* @default true
*/
showCancel?: boolean;
/**
* Cancel button text
*/
cancelText?: string;
/**
* Initial values
*/
initialValues?: Record<string, any>;
/**
* Initial data (alias)
*/
initialData?: Record<string, any>;
/**
* Read-only mode
*/
readOnly?: boolean;
/**
* Callbacks
*/
onSuccess?: (data: any) => void | Promise<void>;
onError?: (error: Error) => void;
onCancel?: () => void;
/**
* Called when step changes
*/
onStepChange?: (step: number) => void;
/**
* CSS class
*/
className?: string;
}
export interface WizardFormProps {
schema: WizardFormSchema;
dataSource?: DataSource;
className?: string;
}
/**
* WizardForm Component
*
* Renders a multi-step wizard form with step indicators and navigation.
*
* @example
* ```tsx
* <WizardForm
* schema={{
* type: 'object-form',
* formType: 'wizard',
* objectName: 'users',
* mode: 'create',
* sections: [
* { label: 'Step 1: Personal', fields: ['firstName', 'lastName'] },
* { label: 'Step 2: Contact', fields: ['email', 'phone'] },
* { label: 'Step 3: Review', fields: [] },
* ]
* }}
* dataSource={dataSource}
* />
* ```
*/
export const WizardForm: React.FC<WizardFormProps> = ({
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);
const [currentStep, setCurrentStep] = useState(0);
const [completedSteps, setCompletedSteps] = useState<Set<number>>(new Set());
const [submitting, setSubmitting] = useState(false);
// Terminal state for `submitBehavior: { kind: 'thank-you' | 'next-record' }`.
// Without this the last step's form stayed mounted and fully filled after a
// successful create, with nothing disabling "Create" — a second click fired
// a second create request (duplicate record).
const [submitted, setSubmitted] = useState<{ title?: string; message?: string } | null>(null);
// Stable id for the *inner* step form's <form> element. The wizard's
// Next/Create buttons live in the footer, OUTSIDE that form, and submit it
// natively via `type="submit" form={stepFormId}`. Going through the real
// form submit (rather than calling handleStepSubmit with the wizard's stale
// `formData`) runs the step's validation and collects every entered value
// via RHF `getValues()` — selects, lookups and dates included — so the
// accumulated record actually reaches the server. Without this the create
// POST body was `{}` and the server rejected all required fields.
const stepFormId = React.useId();
// Bumped on resetOnSuccess to force the inner step form to remount fresh
// (it's otherwise reused across steps so back/forward retains values).
const [resetNonce, setResetNonce] = useState(0);
// Seed `formData` only once. The data-loading effect below depends on
// `dataSource`/`objectSchema`, whose identity can churn across renders;
// re-running its create-mode branch would `setFormData({})` mid-wizard and
// wipe everything the user entered on earlier steps (the create POST then
// carried only the final step's fields). This guard makes the seed idempotent.
const seededRef = React.useRef(false);
const totalSteps = schema.sections.length;
const isFirstStep = currentStep === 0;
const isLastStep = currentStep === totalSteps - 1;
// 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]);
// Fetch initial data
React.useEffect(() => {
const fetchData = async () => {
if (schema.mode === 'create' || !schema.recordId || !dataSource) {
if (!seededRef.current) {
setFormData(schema.initialData || schema.initialValues || {});
seededRef.current = true;
}
setLoading(false);
return;
}
try {
const data = await dataSource.findOne(schema.objectName, schema.recordId);
setFormData(data || {});
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
};
if (objectSchema || !dataSource) {
fetchData();
}
}, [objectSchema, schema.mode, schema.recordId, schema.initialData, schema.initialValues, dataSource, schema.objectName]);
// Build section fields from object schema
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],
);
// Current section fields
const currentSectionFields = useMemo(() => {
if (currentStep >= 0 && currentStep < totalSteps) {
return buildSectionFields(schema.sections[currentStep]);
}
return [];
}, [currentStep, totalSteps, schema.sections, buildSectionFields]);
// Handle step data collection (merge partial data into formData)
const handleStepSubmit = useCallback(async (stepData: Record<string, any>) => {
const mergedData = { ...formData, ...stepData };
setFormData(mergedData);
// Mark step as completed
setCompletedSteps(prev => new Set(prev).add(currentStep));
if (isLastStep) {
// Final submission
setSubmitting(true);
try {
if (!dataSource) {
if (schema.onSuccess) {
await schema.onSuccess(mergedData);
}
return mergedData;
}
let result;
if (schema.mode === 'create') {
result = await dataSource.create(schema.objectName, mergedData);
} else if (schema.mode === 'edit' && schema.recordId) {
result = await dataSource.update(schema.objectName, schema.recordId, mergedData);
}
if (schema.onSuccess) {
await schema.onSuccess(result);
} else if (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':
// Back to a fresh step 1 for the next entry.
setFormData({});
setCompletedSteps(new Set());
setCurrentStep(0);
setResetNonce((n) => n + 1);
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) step form with a confirmation
// panel so there's nothing left to resubmit.
setSubmitted({ title: behavior.kind === 'thank-you' ? behavior.title : undefined, message });
break;
}
}
} else {
// Legacy declarative success behaviors for metadata-only wizards.
const nav = resolveSuccessNavigate(schema.navigateOnSuccess, result);
if (nav) {
// Landing on the saved record is the confirmation — no toast needed.
window.location.assign(nav);
return result;
}
toast.success(schema.successMessage || (schema.mode === 'create' ? 'Created' : 'Saved'));
if (schema.resetOnSuccess && schema.mode === 'create') {
// Back to a fresh step 1 for the next entry.
setFormData({});
setCompletedSteps(new Set());
setCurrentStep(0);
setResetNonce((n) => n + 1);
}
}
return result;
} catch (err) {
if (schema.onError) {
schema.onError(err as Error);
}
throw err;
} finally {
setSubmitting(false);
}
} else {
// Move to next step
goToStep(currentStep + 1);
}
}, [formData, currentStep, isLastStep, schema, dataSource]);
// Navigation
const goToStep = useCallback((step: number) => {
if (step >= 0 && step < totalSteps) {
setCurrentStep(step);
if (schema.onStepChange) {
schema.onStepChange(step);
}
}
}, [totalSteps, schema]);
const handlePrev = useCallback(() => {
goToStep(currentStep - 1);
}, [currentStep, goToStep]);
const handleCancel = useCallback(() => {
if (schema.onCancel) {
schema.onCancel();
}
}, [schema]);
const handleStepClick = useCallback((step: number) => {
if (schema.allowSkip || completedSteps.has(step) || step <= currentStep) {
goToStep(step);
}
}, [schema.allowSkip, completedSteps, currentStep, goToStep]);
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>
);
}
if (submitted) {
return (
<div className={cn('w-full', className, schema.className)}>
<div className="rounded-md border bg-card 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>
</div>
);
}
const currentSection = schema.sections[currentStep];
return (
<div className={cn('w-full', className, schema.className)}>
{/* Step Indicator */}
{schema.showStepIndicator !== false && (
<nav aria-label="Progress" className="mb-8">
<ol className="flex items-center">
{schema.sections.map((section, index) => {
const isActive = index === currentStep;
const isCompleted = completedSteps.has(index);
const isClickable = schema.allowSkip || isCompleted || index <= currentStep;
return (
<li
key={index}
className={cn(
'relative flex-1',
index !== totalSteps - 1 && 'pr-8 sm:pr-12'
)}
>
{/* Connector line */}
{index !== totalSteps - 1 && (
<div
className="absolute top-3 sm:top-4 left-6 -right-4 sm:left-10 sm:-right-2 h-0.5"
aria-hidden="true"
>
<div
className={cn(
'h-full',
isCompleted ? 'bg-primary' : 'bg-muted'
)}
/>
</div>
)}
<button
type="button"
className={cn(
'group relative flex items-center',
isClickable ? 'cursor-pointer' : 'cursor-not-allowed'
)}
onClick={() => handleStepClick(index)}
disabled={!isClickable}
>
{/* Step circle - smaller on mobile */}
<span
className={cn(
'flex h-6 w-6 sm:h-8 sm:w-8 items-center justify-center rounded-full text-xs sm:text-sm font-medium transition-colors',
isCompleted && 'bg-primary text-primary-foreground',
isActive && !isCompleted && 'border-2 border-primary bg-background text-primary',
!isActive && !isCompleted && 'border-2 border-muted bg-background text-muted-foreground'
)}
>
{isCompleted ? (
<Check className="h-3 w-3 sm:h-4 sm:w-4" />
) : (
index + 1
)}
</span>
{/* Step label */}
<span className="ml-2 sm:ml-3 text-xs sm:text-sm font-medium hidden sm:block">
<span
className={cn(
isActive ? 'text-foreground' : 'text-muted-foreground'
)}
>
{section.label || `Step ${index + 1}`}
</span>
</span>
</button>
</li>
);
})}
</ol>
</nav>
)}
{/* Current Step Content */}
<div className="min-h-[200px]">
{currentSection && (
<FormSection
label={currentSection.label}
description={currentSection.description}
columns={1}
className={currentSection.className}
gridClassName={currentSection.gridClassName}
>
{currentSectionFields.length > 0 ? (
<SchemaRenderer
key={resetNonce}
schema={{
type: 'form' as const,
objectName: schema.objectName,
id: stepFormId,
// Multi-column on the field container inside the form, not a
// grid around the whole form (which leaves columns empty).
...sectionFormLayout(currentSectionFields, currentSection.columns || 1),
layout: 'vertical' as const,
defaultValues: formData,
showSubmit: false,
showCancel: false,
onSubmit: handleStepSubmit,
}}
/>
) : (
// A step can legitimately have NO inputs — a final "Review"/confirm
// step is the canonical case (this component's own usage example
// ends on `{ label: 'Step 3: Review', fields: [] }`). The footer
// Next/Create buttons submit the step form *natively* by id, so
// that form has to exist even when there is nothing to fill in:
// without it the buttons point at a missing target, the click does
// nothing at all, and a wizard that ends on a review step can never
// be completed. Submitting contributes no new values — the record
// is whatever the earlier steps accumulated in `formData`.
<form
id={stepFormId}
onSubmit={(e) => {
e.preventDefault();
void handleStepSubmit({});
}}
>
<div className="text-center py-8 text-muted-foreground">
No fields configured for this step
</div>
</form>
)}
</FormSection>
)}
</div>
{/* Navigation Buttons */}
<div className="flex items-center justify-between mt-6 pt-4 border-t">
<div>
{schema.showCancel !== false && (
<Button
variant="ghost"
onClick={handleCancel}
>
{schema.cancelText || 'Cancel'}
</Button>
)}
</div>
<div className="flex items-center gap-2">
{/* Step counter */}
<span className="text-sm text-muted-foreground mr-2">
Step {currentStep + 1} of {totalSteps}
</span>
{!isFirstStep && (
<Button
variant="outline"
onClick={handlePrev}
>
<ChevronLeft className="h-4 w-4 mr-1" />
{schema.prevText || 'Back'}
</Button>
)}
{isLastStep ? (
<Button
type="submit"
form={stepFormId}
disabled={submitting || schema.mode === 'view'}
>
{submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />}
{submitting ? 'Submitting...' : (schema.submitText || (schema.mode === 'create' ? 'Create' : 'Update'))}
</Button>
) : (
<Button
type="submit"
form={stepFormId}
>
{schema.nextText || 'Next'}
<ChevronRight className="h-4 w-4 ml-1" />
</Button>
)}
</div>
</div>
</div>
);
};
export default WizardForm;