-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathWizardForm.tsx
More file actions
751 lines (687 loc) · 26.7 KB
/
Copy pathWizardForm.tsx
File metadata and controls
751 lines (687 loc) · 26.7 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
/**
* 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 { AlertCircle, Check, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';
import { resolveFieldRuleState } from '@object-ui/core';
import { createSafeTranslation } from '@object-ui/i18n';
import { FormSection } from './FormSection';
import { SchemaRenderer, useSafeFieldLabel } from '@object-ui/react';
import { buildSectionFields as buildSectionFieldsShared } from './sectionFields';
import { applyAutoColSpan, containerGridColsFor } from './autoLayout';
import { resolveSuccessNavigate, isSameOriginUrl, type SubmitBehavior } from './successBehavior';
import type { FormSectionConfig } from './TabbedForm';
// Falls back to English when no i18n provider is mounted.
const useWizardTranslation = createSafeTranslation(
{
'wizard.missingRequired': 'Please complete the required fields: {{fields}}',
},
'wizard.missingRequired',
);
/** Empty for the purposes of a required check: '' / null / undefined / []. */
const isEmptyValue = (v: unknown): boolean =>
v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0);
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).
*
* This is navigation freedom, NOT an exemption from the object's rules: the
* final submit still checks every step's required fields and sends the user
* back to the first step that has one outstanding (#2959's validation half —
* react-hook-form only validates the fields currently mounted, so a step
* nobody opened used to reach the server unvalidated).
* @default false
*/
allowSkip?: boolean;
/**
* Grid width for each step (1–4). Aligns with @objectstack/spec
* FormView.columns and OUTRANKS the per-step `columns`, which says how densely
* that step fills the grid. Omitted = the step's own `columns`, else 1.
*/
columns?: number;
/**
* 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 { t } = useWizardTranslation();
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);
// Steps the final submit found an outstanding required field on, so their
// indicator can say so — a rejection on a step the user is not looking at is
// otherwise invisible and the submit just appears to do nothing.
const [invalidSteps, setInvalidSteps] = useState<Set<number>>(new Set());
// 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]);
/**
* Required fields the record does not satisfy, grouped by the STEP that
* declares them.
*
* react-hook-form only validates the fields currently MOUNTED, and a wizard
* mounts one step at a time. Sequential navigation is safe (Next validates the
* step you are leaving), but `allowSkip` jumps straight to any step — so a
* required field on a step nobody opened was never registered, never
* validated, and simply absent from the create payload, with nothing on screen
* saying so. The final submit therefore re-checks the WHOLE declared field set
* here.
*
* Uses the canonical rule engine (`resolveFieldRuleState`), the same one the
* form renderer and the server's rule-validator use, so a conditionally
* required/hidden field gets the same verdict from all three rather than a
* second, divergent dialect.
*/
const missingRequiredByStep = useCallback(
(record: Record<string, any>): Map<number, string[]> => {
const out = new Map<number, string[]>();
schema.sections.forEach((section, index) => {
for (const field of buildSectionFields(section)) {
const name = field?.name;
if (!name || (field as any).hidden === true) continue;
const state = resolveFieldRuleState(
{
visibleWhen: (field as any).visibleWhen,
readonlyWhen: (field as any).readonlyWhen,
requiredWhen: (field as any).requiredWhen,
},
record,
{ required: !!field.required, readonly: (field as any).readonly === true },
);
// A hidden or read-only field is not the user's to fill in.
if (!state.visible || state.readonly || !state.required) continue;
if (!isEmptyValue(record[name])) continue;
out.set(index, [...(out.get(index) ?? []), (field as any).label || name]);
}
});
return out;
},
[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));
// This step just cleared its own validation, so drop any marker it carried.
setInvalidSteps(prev => {
if (!prev.has(currentStep)) return prev;
const next = new Set(prev);
next.delete(currentStep);
return next;
});
if (isLastStep) {
// Gate the submit on the FULL field set, not just this step's (see
// missingRequiredByStep) — then point the user at the first step that is
// short something, instead of letting the server answer with a 400 that
// names fields the user cannot even see.
const missing = missingRequiredByStep(mergedData);
if (missing.size > 0) {
setInvalidSteps(new Set(missing.keys()));
const labels = [...missing.values()].flat();
const MAX = 3;
toast.error(
t('wizard.missingRequired', {
fields: labels.slice(0, MAX).join(', ') + (labels.length > MAX ? '…' : ''),
}),
);
goToStep(Math.min(...missing.keys()));
return;
}
setInvalidSteps(new Set());
// 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, missingRequiredByStep, t]);
// 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];
const clampCol = (n: unknown): number | undefined =>
typeof n === 'number' && n > 0 ? Math.min(Math.floor(n), 4) : undefined;
const stepGridColumns = clampCol(schema.columns) ?? clampCol(currentSection?.columns) ?? 1;
const stepFieldContainerClass = containerGridColsFor(stepGridColumns);
return (
// `@container`: the step's field grid is sized with container queries
// (`@md:grid-cols-2` …), which need a container ancestor to resolve against —
// without one the classes are inert and a multi-column step silently stayed
// single-column. Same wrapper TabbedForm / SplitForm carry.
<div className={cn('w-full @container', 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;
// The last submit found a required field outstanding on this step.
const hasError = invalidSteps.has(index);
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}
data-testid={`wizard-step:${section.name || index}`}
data-error={hasError || undefined}
>
{/* 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',
// An outstanding required field outranks the completed
// tick: the step needs attention, whatever else it is.
hasError && 'border-2 border-destructive bg-background text-destructive',
!hasError && isCompleted && 'bg-primary text-primary-foreground',
!hasError && isActive && !isCompleted && 'border-2 border-primary bg-background text-primary',
!hasError && !isActive && !isCompleted && 'border-2 border-muted bg-background text-muted-foreground'
)}
>
{hasError ? (
<AlertCircle className="h-3 w-3 sm:h-4 sm:w-4" aria-hidden />
) : 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(
hasError
? 'text-destructive'
: 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).
//
// Grid width: the form view's own `columns` first (spec
// FormView.columns — it was being dropped, so a view that
// declared 3 columns rendered single-column here while the same
// metadata gave 3 in a modal), else this step's own `columns`.
// Unlike the tabbed/split hosts there is no widest-section
// fallback: wizard steps never share a viewport, so there is no
// shared grid to size, and each step keeps its authored width.
fields: stepGridColumns > 1
? applyAutoColSpan(currentSectionFields, stepGridColumns, clampCol(currentSection.columns))
: currentSectionFields,
columns: stepGridColumns,
...(stepFieldContainerClass ? { fieldContainerClass: stepFieldContainerClass } : {}),
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;