@wizardkit/react 0.0.0-stage → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +586 -2
- package/dist/index.d.ts +6 -0
- package/dist/index.js +262 -0
- package/dist/use-wizard-granular.d.ts +69 -0
- package/dist/use-wizard.d.ts +168 -0
- package/dist/wizard-provider.d.ts +84 -0
- package/package.json +77 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Georgiy Tsamaladze
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,587 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @wizardkit/react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React integration for the WizardKit state machine. Provides a convenient `useWizard()` hook that connects your wizard definitions to React state.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **React Hook** - Simple `useWizard()` hook for React components
|
|
8
|
+
- **Organized API** - State grouped into logical slices (state, validation, navigation, loading, actions)
|
|
9
|
+
- **Navigation History** - `canGoBack` and `stepHistory` for history-based back navigation
|
|
10
|
+
- **Granular Hooks** - Fine-grained subscriptions with `useWizardData()`, `useWizardNavigation()`, etc.
|
|
11
|
+
- **Optional Provider** - `WizardProvider` for performance optimization in complex UIs
|
|
12
|
+
- **Full Type Safety** - TypeScript generics for your data types
|
|
13
|
+
- **State Management** - Built-in React state handling with zero configuration
|
|
14
|
+
- **Loading States** - Track validation, submission, and navigation
|
|
15
|
+
- **Backwards Compatible** - 100% compatible with existing code
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @wizardkit/core @wizardkit/react
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
import { useWizard } from "@wizardkit/react";
|
|
27
|
+
import { createLinearWizard } from "@wizardkit/core";
|
|
28
|
+
|
|
29
|
+
type SignupData = {
|
|
30
|
+
name: string;
|
|
31
|
+
email: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const wizard = createLinearWizard<SignupData>({
|
|
35
|
+
id: "signup",
|
|
36
|
+
steps: [
|
|
37
|
+
{
|
|
38
|
+
id: "name",
|
|
39
|
+
title: "What's your name?",
|
|
40
|
+
validate: (data) => ({
|
|
41
|
+
valid: Boolean(data.name),
|
|
42
|
+
errors: data.name ? undefined : { name: "Required" },
|
|
43
|
+
}),
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
id: "email",
|
|
47
|
+
title: "What's your email?",
|
|
48
|
+
validate: (data) => ({
|
|
49
|
+
valid: data.email?.includes("@") ?? false,
|
|
50
|
+
errors: data.email?.includes("@")
|
|
51
|
+
? undefined
|
|
52
|
+
: { email: "Invalid email" },
|
|
53
|
+
}),
|
|
54
|
+
},
|
|
55
|
+
],
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
export function SignupForm() {
|
|
59
|
+
const { state, navigation, actions, validation, loading } = useWizard({
|
|
60
|
+
definition: wizard,
|
|
61
|
+
initialData: { name: "", email: "" },
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
return (
|
|
65
|
+
<div>
|
|
66
|
+
<h2>{state.currentStep.meta?.title}</h2>
|
|
67
|
+
|
|
68
|
+
{state.currentStepId === "name" && (
|
|
69
|
+
<input
|
|
70
|
+
value={state.data.name}
|
|
71
|
+
onChange={(e) => actions.updateField("name", e.target.value)}
|
|
72
|
+
placeholder="Name"
|
|
73
|
+
/>
|
|
74
|
+
)}
|
|
75
|
+
|
|
76
|
+
{state.currentStepId === "email" && (
|
|
77
|
+
<input
|
|
78
|
+
value={state.data.email}
|
|
79
|
+
onChange={(e) => actions.updateField("email", e.target.value)}
|
|
80
|
+
placeholder="Email"
|
|
81
|
+
/>
|
|
82
|
+
)}
|
|
83
|
+
|
|
84
|
+
{validation.validationErrors && (
|
|
85
|
+
<ul className="errors">
|
|
86
|
+
{Object.entries(validation.validationErrors).map(([field, error]) => (
|
|
87
|
+
<li key={field}>{error}</li>
|
|
88
|
+
))}
|
|
89
|
+
</ul>
|
|
90
|
+
)}
|
|
91
|
+
|
|
92
|
+
<button
|
|
93
|
+
onClick={() => navigation.goPrevious()}
|
|
94
|
+
disabled={!navigation.canGoPrevious || loading.isNavigating}
|
|
95
|
+
>
|
|
96
|
+
Previous
|
|
97
|
+
</button>
|
|
98
|
+
<button
|
|
99
|
+
onClick={() => navigation.goNext()}
|
|
100
|
+
disabled={loading.isNavigating}
|
|
101
|
+
>
|
|
102
|
+
{/* On the last step goNext() completes the wizard; canGoNext is false there. */}
|
|
103
|
+
{navigation.isLastStep ? "Complete" : "Next"}
|
|
104
|
+
</button>
|
|
105
|
+
</div>
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Core Concepts
|
|
111
|
+
|
|
112
|
+
### useWizard Hook
|
|
113
|
+
|
|
114
|
+
The `useWizard()` hook connects a wizard definition to React state and returns an organized object with state grouped into logical slices:
|
|
115
|
+
|
|
116
|
+
```tsx
|
|
117
|
+
const { state, validation, navigation, loading, actions } = useWizard({
|
|
118
|
+
definition: wizardDefinition,
|
|
119
|
+
initialData: myInitialData,
|
|
120
|
+
context: myContext,
|
|
121
|
+
onComplete: (data) => {
|
|
122
|
+
// Handle completion
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### Organized State Structure
|
|
128
|
+
|
|
129
|
+
The hook returns state grouped into five logical slices for clarity:
|
|
130
|
+
|
|
131
|
+
```tsx
|
|
132
|
+
// State slice - current step and data
|
|
133
|
+
state.currentStepId;
|
|
134
|
+
state.currentStep;
|
|
135
|
+
state.data;
|
|
136
|
+
state.isCompleted;
|
|
137
|
+
|
|
138
|
+
// Validation slice
|
|
139
|
+
validation.isValid;
|
|
140
|
+
validation.validationErrors;
|
|
141
|
+
|
|
142
|
+
// Navigation slice (state + methods)
|
|
143
|
+
navigation.canGoNext;
|
|
144
|
+
navigation.canGoPrevious;
|
|
145
|
+
navigation.canGoBack;
|
|
146
|
+
navigation.isFirstStep;
|
|
147
|
+
navigation.isLastStep;
|
|
148
|
+
navigation.visitedSteps;
|
|
149
|
+
navigation.availableSteps;
|
|
150
|
+
navigation.stepHistory;
|
|
151
|
+
navigation.goNext();
|
|
152
|
+
navigation.goPrevious();
|
|
153
|
+
navigation.goBack(n); // deprecated
|
|
154
|
+
navigation.goTo(stepId); // validates current step first
|
|
155
|
+
navigation.goTo(stepId, options); // with GoToOptions
|
|
156
|
+
navigation.goToStep(stepId); // @deprecated — use goTo() instead
|
|
157
|
+
|
|
158
|
+
// Loading slice
|
|
159
|
+
loading.isValidating;
|
|
160
|
+
loading.isSubmitting;
|
|
161
|
+
loading.isNavigating;
|
|
162
|
+
loading.isLoadingStep; // a lazy step's implementation is loading
|
|
163
|
+
|
|
164
|
+
// Actions slice
|
|
165
|
+
actions.updateField("name", "John");
|
|
166
|
+
actions.updateData((d) => ({ ...d, name: "John" }));
|
|
167
|
+
actions.setData(newData);
|
|
168
|
+
actions.validate();
|
|
169
|
+
actions.validateAll(); // dry-run all enabled steps → ValidationSummary
|
|
170
|
+
actions.canSubmit();
|
|
171
|
+
actions.submit();
|
|
172
|
+
actions.reset();
|
|
173
|
+
actions.cancel(); // onCancel + reset
|
|
174
|
+
actions.serialize(); // / actions.restore(saved)
|
|
175
|
+
actions.preloadStep("documents"); // prefetch a lazy step (never rejects)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Plugins
|
|
179
|
+
|
|
180
|
+
Pass a **reference-stable** `plugins` array (hoist or `useMemo`) — read once at machine creation:
|
|
181
|
+
|
|
182
|
+
```tsx
|
|
183
|
+
const plugins = useMemo(() => [createLoggingPlugin({ level: "info" })], []);
|
|
184
|
+
|
|
185
|
+
useWizard({ definition, initialData, plugins });
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
## Hook API
|
|
189
|
+
|
|
190
|
+
### useWizard Options
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
interface UseWizardOptions<T> {
|
|
194
|
+
definition: WizardDefinition<T>;
|
|
195
|
+
initialData: T;
|
|
196
|
+
context?: WizardContext;
|
|
197
|
+
onStateChange?: (state: WizardState<T>) => void;
|
|
198
|
+
onStepEnter?: (stepId: string, data: T) => void;
|
|
199
|
+
onStepLeave?: (stepId: string, data: T) => void;
|
|
200
|
+
onComplete?: (data: T) => void;
|
|
201
|
+
onCancel?: (data: T) => void | Promise<void>;
|
|
202
|
+
onReset?: () => void;
|
|
203
|
+
onError?: (error: Error) => void;
|
|
204
|
+
plugins?: WizardPlugin<T>[];
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### useWizard Return Value
|
|
209
|
+
|
|
210
|
+
```typescript
|
|
211
|
+
interface UseWizardReturn<T> {
|
|
212
|
+
state: UseWizardState<T>;
|
|
213
|
+
validation: UseWizardValidation;
|
|
214
|
+
navigation: UseWizardNavigation;
|
|
215
|
+
loading: UseWizardLoading;
|
|
216
|
+
actions: UseWizardActions<T>;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
interface UseWizardState<T> {
|
|
220
|
+
currentStepId: string;
|
|
221
|
+
currentStep: WizardStepDefinition<T>;
|
|
222
|
+
data: T;
|
|
223
|
+
isCompleted: boolean;
|
|
224
|
+
stepStatuses: Record<string, StepStatus>;
|
|
225
|
+
progress: WizardProgress;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
interface UseWizardValidation {
|
|
229
|
+
isValid: boolean;
|
|
230
|
+
validationErrors?: Record<string, string>;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
interface UseWizardNavigation {
|
|
234
|
+
canGoNext: boolean;
|
|
235
|
+
canGoPrevious: boolean;
|
|
236
|
+
canGoBack: boolean;
|
|
237
|
+
isFirstStep: boolean;
|
|
238
|
+
isLastStep: boolean;
|
|
239
|
+
visitedSteps: string[];
|
|
240
|
+
availableSteps: string[];
|
|
241
|
+
stepHistory: string[];
|
|
242
|
+
goNext(): Promise<void>;
|
|
243
|
+
goPrevious(): Promise<void>;
|
|
244
|
+
/** @deprecated Use goPrevious() instead */
|
|
245
|
+
goBack(steps?: number): Promise<void>;
|
|
246
|
+
goTo(stepId: string, options?: GoToOptions): Promise<void>;
|
|
247
|
+
/** @deprecated Use goTo(stepId) instead */
|
|
248
|
+
goToStep(stepId: string): Promise<void>;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
interface UseWizardLoading {
|
|
252
|
+
isValidating: boolean;
|
|
253
|
+
isSubmitting: boolean;
|
|
254
|
+
isNavigating: boolean;
|
|
255
|
+
isLoadingStep: boolean; // a lazy step's implementation is loading
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
interface UseWizardActions<T> {
|
|
259
|
+
updateData(updater: (data: T) => T): void;
|
|
260
|
+
setData(data: T): void;
|
|
261
|
+
updateField<K extends keyof T>(field: K, value: T[K]): void;
|
|
262
|
+
validate(): Promise<void>;
|
|
263
|
+
validateAll(options?: { updateStatuses?: boolean }): Promise<ValidationSummary>;
|
|
264
|
+
canSubmit(): Promise<boolean>;
|
|
265
|
+
submit(): Promise<void>;
|
|
266
|
+
reset(data?: T): void;
|
|
267
|
+
cancel(): Promise<void>;
|
|
268
|
+
serialize(): WizardSerializedState<T>;
|
|
269
|
+
restore(state: WizardSerializedState<T>): void;
|
|
270
|
+
preloadStep(stepId: string): Promise<void>; // prefetch a lazy step; never rejects
|
|
271
|
+
}
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
## Granular Hooks (Optional Provider)
|
|
275
|
+
|
|
276
|
+
For performance-critical applications, use `WizardProvider` with granular hooks to subscribe only to relevant state changes:
|
|
277
|
+
|
|
278
|
+
```tsx
|
|
279
|
+
import {
|
|
280
|
+
WizardProvider,
|
|
281
|
+
useWizardData,
|
|
282
|
+
useWizardNavigation,
|
|
283
|
+
useWizardLoading,
|
|
284
|
+
useWizardActions,
|
|
285
|
+
} from "@wizardkit/react";
|
|
286
|
+
|
|
287
|
+
function App() {
|
|
288
|
+
return (
|
|
289
|
+
<WizardProvider definition={wizard} initialData={initialData}>
|
|
290
|
+
<MyWizardForm />
|
|
291
|
+
</WizardProvider>
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function MyWizardForm() {
|
|
296
|
+
// Only re-renders when data changes
|
|
297
|
+
const { data, currentStepId } = useWizardData();
|
|
298
|
+
|
|
299
|
+
// Only re-renders when navigation state changes
|
|
300
|
+
const { isLastStep, goNext } = useWizardNavigation();
|
|
301
|
+
|
|
302
|
+
// Only re-renders when loading flags change
|
|
303
|
+
const { isNavigating } = useWizardLoading();
|
|
304
|
+
|
|
305
|
+
// Always stable - doesn't cause re-renders
|
|
306
|
+
const { updateField } = useWizardActions();
|
|
307
|
+
|
|
308
|
+
return (
|
|
309
|
+
<div>
|
|
310
|
+
<input
|
|
311
|
+
value={data.name}
|
|
312
|
+
onChange={(e) => updateField("name", e.target.value)}
|
|
313
|
+
/>
|
|
314
|
+
{/* On the last step goNext() completes the wizard; canGoNext is false there. */}
|
|
315
|
+
<button onClick={() => goNext()} disabled={isNavigating}>
|
|
316
|
+
{isLastStep ? "Finish" : "Next"}
|
|
317
|
+
</button>
|
|
318
|
+
</div>
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
### Available Granular Hooks
|
|
324
|
+
|
|
325
|
+
- **`useWizardData<T>()`** - Current step ID, step definition, data, completion status
|
|
326
|
+
- **`useWizardNavigation()`** - Navigation state and methods (canGoNext, goNext, etc.)
|
|
327
|
+
- **`useWizardValidation()`** - Validation status and field errors
|
|
328
|
+
- **`useWizardLoading()`** - Loading flags (isValidating, isSubmitting, isNavigating, isLoadingStep)
|
|
329
|
+
- **`useWizardActions<T>()`** - All wizard action methods (updateField, submit, reset, preloadStep, etc.)
|
|
330
|
+
|
|
331
|
+
### When to Use Granular Hooks
|
|
332
|
+
|
|
333
|
+
Use granular hooks when:
|
|
334
|
+
|
|
335
|
+
- Your wizard has many fields and complex components
|
|
336
|
+
- You want to prevent unnecessary re-renders
|
|
337
|
+
- You're optimizing a large or performance-critical form
|
|
338
|
+
- You want fine-grained control over which state changes trigger re-renders
|
|
339
|
+
|
|
340
|
+
**Note:** Granular hooks require `WizardProvider`. For simple wizards, `useWizard()` alone is sufficient.
|
|
341
|
+
|
|
342
|
+
## Common Patterns
|
|
343
|
+
|
|
344
|
+
### Conditional Step Rendering
|
|
345
|
+
|
|
346
|
+
```tsx
|
|
347
|
+
function MyWizard() {
|
|
348
|
+
const { state, navigation, actions, loading } = useWizard({
|
|
349
|
+
definition,
|
|
350
|
+
initialData,
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
return (
|
|
354
|
+
<>
|
|
355
|
+
{state.currentStepId === "personal" && (
|
|
356
|
+
<PersonalStep data={state.data} onUpdate={actions.updateField} />
|
|
357
|
+
)}
|
|
358
|
+
|
|
359
|
+
{state.currentStepId === "contact" && (
|
|
360
|
+
<ContactStep data={state.data} onUpdate={actions.updateField} />
|
|
361
|
+
)}
|
|
362
|
+
|
|
363
|
+
{state.currentStepId === "review" && <ReviewStep data={state.data} />}
|
|
364
|
+
|
|
365
|
+
<button
|
|
366
|
+
onClick={() => navigation.goPrevious()}
|
|
367
|
+
disabled={!navigation.canGoPrevious || loading.isNavigating}
|
|
368
|
+
>
|
|
369
|
+
Back
|
|
370
|
+
</button>
|
|
371
|
+
<button
|
|
372
|
+
onClick={() => navigation.goNext()}
|
|
373
|
+
disabled={loading.isNavigating}
|
|
374
|
+
>
|
|
375
|
+
{/* On the last step goNext() completes the wizard; canGoNext is false there. */}
|
|
376
|
+
{navigation.isLastStep ? "Submit" : "Next"}
|
|
377
|
+
</button>
|
|
378
|
+
</>
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
### With React Hook Form
|
|
384
|
+
|
|
385
|
+
```tsx
|
|
386
|
+
import { useForm } from "react-hook-form";
|
|
387
|
+
import { useWizard } from "@wizardkit/react";
|
|
388
|
+
|
|
389
|
+
function FormWizard() {
|
|
390
|
+
const { register, watch, handleSubmit } = useForm({
|
|
391
|
+
defaultValues: initialData,
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
const { state, navigation, actions, validation } = useWizard({
|
|
395
|
+
definition,
|
|
396
|
+
initialData,
|
|
397
|
+
});
|
|
398
|
+
const formData = watch();
|
|
399
|
+
|
|
400
|
+
const handleNext = async () => {
|
|
401
|
+
await actions.validate();
|
|
402
|
+
if (validation.isValid) {
|
|
403
|
+
actions.setData(formData);
|
|
404
|
+
await navigation.goNext();
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
return (
|
|
409
|
+
<form onSubmit={handleSubmit(handleNext)}>
|
|
410
|
+
{state.currentStepId === "personal" && (
|
|
411
|
+
<>
|
|
412
|
+
<input {...register("name")} />
|
|
413
|
+
<input {...register("email")} />
|
|
414
|
+
</>
|
|
415
|
+
)}
|
|
416
|
+
|
|
417
|
+
<button type="submit">Next</button>
|
|
418
|
+
</form>
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
### With Context (API Client)
|
|
424
|
+
|
|
425
|
+
```tsx
|
|
426
|
+
interface AppContext extends WizardContext {
|
|
427
|
+
api: ApiClient;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const appContext: AppContext = {
|
|
431
|
+
api: new ApiClient(),
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
function Wizard() {
|
|
435
|
+
const { state, navigation, actions } = useWizard({
|
|
436
|
+
definition,
|
|
437
|
+
initialData,
|
|
438
|
+
context: appContext,
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
// Definition can now use appContext in validators and hooks
|
|
442
|
+
}
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
### Persisting Progress
|
|
446
|
+
|
|
447
|
+
```tsx
|
|
448
|
+
function PersistentWizard() {
|
|
449
|
+
const [savedData, setSavedData] = useState(() => {
|
|
450
|
+
const saved = localStorage.getItem("wizard-data");
|
|
451
|
+
return saved ? JSON.parse(saved) : initialData;
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
const wizard = useWizard({
|
|
455
|
+
definition,
|
|
456
|
+
initialData: savedData,
|
|
457
|
+
onStateChange: (state) => {
|
|
458
|
+
localStorage.setItem("wizard-data", JSON.stringify(state.data));
|
|
459
|
+
},
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
return (
|
|
463
|
+
<MyWizardForm
|
|
464
|
+
state={wizard.state}
|
|
465
|
+
actions={wizard.actions}
|
|
466
|
+
navigation={wizard.navigation}
|
|
467
|
+
/>
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
## Best Practices
|
|
473
|
+
|
|
474
|
+
### 1. Define Wizard Outside Component
|
|
475
|
+
|
|
476
|
+
```tsx
|
|
477
|
+
// ✅ Good - defined once
|
|
478
|
+
const wizard = createWizard(/* ... */).build();
|
|
479
|
+
|
|
480
|
+
function MyComponent() {
|
|
481
|
+
const { state, actions, navigation } = useWizard({
|
|
482
|
+
definition: wizard,
|
|
483
|
+
initialData,
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// ❌ Bad - recreated every render
|
|
488
|
+
function MyComponent() {
|
|
489
|
+
const wizard = createWizard(/* ... */).build();
|
|
490
|
+
const { state, actions, navigation } = useWizard({
|
|
491
|
+
definition: wizard,
|
|
492
|
+
initialData,
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
### 2. Use Separate Sub-components
|
|
498
|
+
|
|
499
|
+
```tsx
|
|
500
|
+
// ✅ Good - concerns separated
|
|
501
|
+
function WizardContainer() {
|
|
502
|
+
const wizard = useWizard({ definition, initialData });
|
|
503
|
+
return (
|
|
504
|
+
<>
|
|
505
|
+
<StepRenderer state={wizard.state} actions={wizard.actions} />
|
|
506
|
+
<Navigation navigation={wizard.navigation} loading={wizard.loading} />
|
|
507
|
+
</>
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// ❌ Bad - everything in one component
|
|
512
|
+
function WizardContainer() {
|
|
513
|
+
const wizard = useWizard({ definition, initialData });
|
|
514
|
+
return <div>{/* all UI here */}</div>;
|
|
515
|
+
}
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
### 3. Await Async Operations
|
|
519
|
+
|
|
520
|
+
```tsx
|
|
521
|
+
// ✅ Good - properly awaiting
|
|
522
|
+
const handleNext = async () => {
|
|
523
|
+
await actions.validate();
|
|
524
|
+
if (validation.isValid) {
|
|
525
|
+
await navigation.goNext();
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
// ❌ Bad - not awaiting
|
|
530
|
+
const handleNext = () => {
|
|
531
|
+
actions.validate();
|
|
532
|
+
navigation.goNext();
|
|
533
|
+
};
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
### 4. Handle Loading States
|
|
537
|
+
|
|
538
|
+
```tsx
|
|
539
|
+
// ✅ Good - disable while loading (not on !canGoNext: goNext() finishes the last step)
|
|
540
|
+
<button
|
|
541
|
+
onClick={() => navigation.goNext()}
|
|
542
|
+
disabled={loading.isNavigating}
|
|
543
|
+
>
|
|
544
|
+
{loading.isNavigating
|
|
545
|
+
? "Loading..."
|
|
546
|
+
: navigation.isLastStep
|
|
547
|
+
? "Finish"
|
|
548
|
+
: "Next"}
|
|
549
|
+
</button>
|
|
550
|
+
|
|
551
|
+
// ❌ Bad - no feedback to user
|
|
552
|
+
<button onClick={() => navigation.goNext()}>Next</button>
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
### 5. Use TypeScript
|
|
556
|
+
|
|
557
|
+
```tsx
|
|
558
|
+
// ✅ Good - full type safety
|
|
559
|
+
type MyData = { name: string; email: string };
|
|
560
|
+
const { state, actions, navigation } = useWizard<MyData>({
|
|
561
|
+
definition,
|
|
562
|
+
initialData: { name: "", email: "" },
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
// ❌ Bad - no type safety
|
|
566
|
+
const { state, actions, navigation } = useWizard({ definition, initialData });
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
## Documentation
|
|
570
|
+
|
|
571
|
+
For more details, see:
|
|
572
|
+
|
|
573
|
+
- [React Integration Guide](https://wizardkit.dev/guide/react-integration) - Deep dive into React-specific features
|
|
574
|
+
- [Getting Started](https://wizardkit.dev/guide/getting-started) - Quick introduction
|
|
575
|
+
- [Core Concepts](https://wizardkit.dev/guide/core-concepts) - Understand the fundamentals
|
|
576
|
+
- [API Reference](https://wizardkit.dev/guide/api/react) - Complete API documentation
|
|
577
|
+
|
|
578
|
+
## Peer Dependencies
|
|
579
|
+
|
|
580
|
+
- React 18.0+ or React 19
|
|
581
|
+
|
|
582
|
+
**React 18 and StrictMode.** In development, React 18's `<StrictMode>` renders a component twice on mount and discards the first render together with its refs. The wizard machine created by that discarded render is never destroyed, so each plugin's `onInit` runs one extra time without a matching `destroy()`. This happens only in development under StrictMode: production builds and React 19 are not affected. The built-in plugins re-seed themselves on every `onInit`, so they are safe; a custom plugin that acquires a resource in `onInit` (a timer, a listener, a connection) should be idempotent on React 18.
|
|
583
|
+
- React-DOM 18.0+ or 19
|
|
584
|
+
|
|
585
|
+
## License
|
|
586
|
+
|
|
587
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type { WizardProgress, WizardSerializedState, } from '@wizardkit/core';
|
|
2
|
+
export { WizardRestoreError } from '@wizardkit/core';
|
|
3
|
+
export { type LoadingState, type NavigationState, type StateSnapshot, type SubscriptionChannel, type ValidationState, WizardStateManager, } from '@wizardkit/state';
|
|
4
|
+
export { type CancelFn, type CanSubmitFn, type ResetFn, type RestoreFn, type SerializeFn, type SetDataFn, type SubmitFn, type UpdateDataFn, type UpdateFieldFn, type UseWizardActions, type UseWizardLoading, type UseWizardNavigation, type UseWizardOptions, type UseWizardReturn, type UseWizardState, type UseWizardValidation, useWizard, type ValidateAllFn, type ValidateFn, } from './use-wizard';
|
|
5
|
+
export { useWizardActions, useWizardData, useWizardField, useWizardLoading, useWizardNavigation, useWizardValidation, } from './use-wizard-granular';
|
|
6
|
+
export { useWizardProviderContext, WizardProvider, type WizardProviderProps, } from './wizard-provider';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { WizardRestoreError as e } from "@wizardkit/core";
|
|
2
|
+
import { WizardStateManager as t, createMachineAndManager as n, createWizardActions as r } from "@wizardkit/state";
|
|
3
|
+
import { createContext as i, useCallback as a, useContext as o, useEffect as s, useMemo as c, useRef as l, useState as u, useSyncExternalStore as d } from "react";
|
|
4
|
+
import { jsx as f } from "react/jsx-runtime";
|
|
5
|
+
//#region src/use-wizard.tsx
|
|
6
|
+
function p(e) {
|
|
7
|
+
return {
|
|
8
|
+
goNext: e.goNext,
|
|
9
|
+
goPrevious: e.goPrevious,
|
|
10
|
+
goBack: e.goBack,
|
|
11
|
+
goTo: e.goTo,
|
|
12
|
+
goToStep: e.goToStep
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
function m(e) {
|
|
16
|
+
return {
|
|
17
|
+
updateData: e.updateData,
|
|
18
|
+
setData: e.setData,
|
|
19
|
+
updateField: e.updateField,
|
|
20
|
+
validate: e.validate,
|
|
21
|
+
validateAll: e.validateAll,
|
|
22
|
+
canSubmit: e.canSubmit,
|
|
23
|
+
submit: e.submit,
|
|
24
|
+
reset: e.reset,
|
|
25
|
+
cancel: e.cancel,
|
|
26
|
+
serialize: e.serialize,
|
|
27
|
+
restore: e.restore,
|
|
28
|
+
preloadStep: e.preloadStep
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function h(e) {
|
|
32
|
+
let { definition: t, initialData: i, context: o = {}, onStateChange: f, onStepEnter: h, onStepLeave: g, onComplete: _, onCancel: v, onReset: y, onError: b, onDataChange: x, plugins: S } = e, C = l({
|
|
33
|
+
onStateChange: f,
|
|
34
|
+
onStepEnter: h,
|
|
35
|
+
onStepLeave: g,
|
|
36
|
+
onComplete: _,
|
|
37
|
+
onCancel: v,
|
|
38
|
+
onReset: y,
|
|
39
|
+
onError: b,
|
|
40
|
+
onDataChange: x
|
|
41
|
+
});
|
|
42
|
+
C.current = {
|
|
43
|
+
onStateChange: f,
|
|
44
|
+
onStepEnter: h,
|
|
45
|
+
onStepLeave: g,
|
|
46
|
+
onComplete: _,
|
|
47
|
+
onCancel: v,
|
|
48
|
+
onReset: y,
|
|
49
|
+
onError: b,
|
|
50
|
+
onDataChange: x
|
|
51
|
+
};
|
|
52
|
+
let w = l(i), T = l(o), E = l(t), D = l(S), O = l(null);
|
|
53
|
+
(O.current === null || O.current.isDestroyed) && (O.current = n({
|
|
54
|
+
definition: E.current,
|
|
55
|
+
context: T.current,
|
|
56
|
+
initialData: w.current,
|
|
57
|
+
getCallbacks: () => C.current,
|
|
58
|
+
plugins: D.current
|
|
59
|
+
}).manager);
|
|
60
|
+
let [, k] = u(0), A = O.current;
|
|
61
|
+
s(() => () => {
|
|
62
|
+
A.destroy(), O.current === A && (O.current = null, k((e) => e + 1));
|
|
63
|
+
}, [A]);
|
|
64
|
+
let j = d(a((e) => A.subscribe(e, "state"), [A]), a(() => A.getStateSnapshot(), [A]), a(() => A.getStateSnapshot(), [A])), M = d(a((e) => A.subscribe(e, "navigation"), [A]), a(() => A.getNavigationSnapshot(), [A]), a(() => A.getNavigationSnapshot(), [A])), N = d(a((e) => A.subscribe(e, "validation"), [A]), a(() => A.getValidationSnapshot(), [A]), a(() => A.getValidationSnapshot(), [A])), P = d(a((e) => A.subscribe(e, "loading"), [A]), a(() => A.getLoadingSnapshot(), [A]), a(() => A.getLoadingSnapshot(), [A])), F = a((e) => {
|
|
65
|
+
C.current.onError?.(e instanceof Error ? e : Error(String(e)));
|
|
66
|
+
}, []), I = c(() => r(A, F), [A, F]), L = c(() => ({
|
|
67
|
+
currentStepId: j.currentStepId,
|
|
68
|
+
currentStep: j.currentStep,
|
|
69
|
+
data: j.data,
|
|
70
|
+
isCompleted: j.isCompleted,
|
|
71
|
+
stepStatuses: j.stepStatuses,
|
|
72
|
+
progress: j.progress
|
|
73
|
+
}), [
|
|
74
|
+
j.currentStepId,
|
|
75
|
+
j.currentStep,
|
|
76
|
+
j.data,
|
|
77
|
+
j.isCompleted,
|
|
78
|
+
j.stepStatuses,
|
|
79
|
+
j.progress
|
|
80
|
+
]), R = c(() => ({
|
|
81
|
+
isValid: N.isValid,
|
|
82
|
+
validationErrors: N.validationErrors
|
|
83
|
+
}), [N.isValid, N.validationErrors]), z = c(() => ({
|
|
84
|
+
canGoNext: M.canGoNext,
|
|
85
|
+
canGoPrevious: M.canGoPrevious,
|
|
86
|
+
canGoBack: M.canGoBack,
|
|
87
|
+
isFirstStep: M.isFirstStep,
|
|
88
|
+
isLastStep: M.isLastStep,
|
|
89
|
+
visitedSteps: M.visitedSteps,
|
|
90
|
+
availableSteps: M.availableSteps,
|
|
91
|
+
stepHistory: M.stepHistory,
|
|
92
|
+
...p(I)
|
|
93
|
+
}), [
|
|
94
|
+
M.canGoNext,
|
|
95
|
+
M.canGoPrevious,
|
|
96
|
+
M.canGoBack,
|
|
97
|
+
M.isFirstStep,
|
|
98
|
+
M.isLastStep,
|
|
99
|
+
M.visitedSteps,
|
|
100
|
+
M.availableSteps,
|
|
101
|
+
M.stepHistory,
|
|
102
|
+
I
|
|
103
|
+
]), B = c(() => ({
|
|
104
|
+
isValidating: P.isValidating,
|
|
105
|
+
isSubmitting: P.isSubmitting,
|
|
106
|
+
isNavigating: P.isNavigating,
|
|
107
|
+
isLoadingStep: P.isLoadingStep
|
|
108
|
+
}), [
|
|
109
|
+
P.isValidating,
|
|
110
|
+
P.isSubmitting,
|
|
111
|
+
P.isNavigating,
|
|
112
|
+
P.isLoadingStep
|
|
113
|
+
]), V = c(() => m(I), [I]);
|
|
114
|
+
return c(() => ({
|
|
115
|
+
state: L,
|
|
116
|
+
validation: R,
|
|
117
|
+
navigation: z,
|
|
118
|
+
loading: B,
|
|
119
|
+
actions: V
|
|
120
|
+
}), [
|
|
121
|
+
L,
|
|
122
|
+
R,
|
|
123
|
+
z,
|
|
124
|
+
B,
|
|
125
|
+
V
|
|
126
|
+
]);
|
|
127
|
+
}
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/wizard-provider.tsx
|
|
130
|
+
var g = i(null);
|
|
131
|
+
function _({ definition: e, initialData: t, context: i = {}, onStateChange: o, onStepEnter: p, onStepLeave: m, onComplete: h, onCancel: _, onReset: v, onError: y, onDataChange: b, plugins: x, children: S }) {
|
|
132
|
+
let C = l({
|
|
133
|
+
onStateChange: o,
|
|
134
|
+
onStepEnter: p,
|
|
135
|
+
onStepLeave: m,
|
|
136
|
+
onComplete: h,
|
|
137
|
+
onCancel: _,
|
|
138
|
+
onReset: v,
|
|
139
|
+
onError: y,
|
|
140
|
+
onDataChange: b
|
|
141
|
+
});
|
|
142
|
+
C.current = {
|
|
143
|
+
onStateChange: o,
|
|
144
|
+
onStepEnter: p,
|
|
145
|
+
onStepLeave: m,
|
|
146
|
+
onComplete: h,
|
|
147
|
+
onCancel: _,
|
|
148
|
+
onReset: v,
|
|
149
|
+
onError: y,
|
|
150
|
+
onDataChange: b
|
|
151
|
+
};
|
|
152
|
+
let w = l(t), T = l(i), E = l(e), D = l(x), O = a((e) => {
|
|
153
|
+
C.current.onError?.(e instanceof Error ? e : Error(String(e)));
|
|
154
|
+
}, []), k = l(null);
|
|
155
|
+
(k.current === null || k.current.isDestroyed) && (k.current = n({
|
|
156
|
+
definition: E.current,
|
|
157
|
+
context: T.current,
|
|
158
|
+
initialData: w.current,
|
|
159
|
+
getCallbacks: () => C.current,
|
|
160
|
+
plugins: D.current
|
|
161
|
+
}).manager);
|
|
162
|
+
let [, A] = u(0), j = k.current;
|
|
163
|
+
d(a((e) => j.subscribe(e, "all"), [j]), a(() => j.isDestroyed, [j]), a(() => j.isDestroyed, [j])), s(() => () => {
|
|
164
|
+
j.destroy(), k.current === j && (k.current = null, A((e) => e + 1));
|
|
165
|
+
}, [j]);
|
|
166
|
+
let M = c(() => r(j, O), [j, O]), N = c(() => ({
|
|
167
|
+
manager: j,
|
|
168
|
+
initialData: w.current,
|
|
169
|
+
actions: M
|
|
170
|
+
}), [j, M]);
|
|
171
|
+
return /* @__PURE__ */ f(g.Provider, {
|
|
172
|
+
value: N,
|
|
173
|
+
children: S
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
function v() {
|
|
177
|
+
return y();
|
|
178
|
+
}
|
|
179
|
+
function y() {
|
|
180
|
+
let e = o(g);
|
|
181
|
+
if (!e) throw Error("useWizardProviderContext must be used within <WizardProvider>");
|
|
182
|
+
return e;
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/use-wizard-granular.tsx
|
|
186
|
+
function b() {
|
|
187
|
+
let { manager: e } = v(), t = d(a((t) => e.subscribe(t, "state"), [e]), a(() => e.getStateSnapshot(), [e]), a(() => e.getStateSnapshot(), [e]));
|
|
188
|
+
return c(() => ({
|
|
189
|
+
currentStepId: t.currentStepId,
|
|
190
|
+
currentStep: t.currentStep,
|
|
191
|
+
data: t.data,
|
|
192
|
+
isCompleted: t.isCompleted,
|
|
193
|
+
stepStatuses: t.stepStatuses,
|
|
194
|
+
progress: t.progress
|
|
195
|
+
}), [
|
|
196
|
+
t.currentStepId,
|
|
197
|
+
t.currentStep,
|
|
198
|
+
t.data,
|
|
199
|
+
t.isCompleted,
|
|
200
|
+
t.stepStatuses,
|
|
201
|
+
t.progress
|
|
202
|
+
]);
|
|
203
|
+
}
|
|
204
|
+
function x() {
|
|
205
|
+
let { manager: e, actions: t } = y(), n = d(a((t) => e.subscribe(t, "navigation"), [e]), a(() => e.getNavigationSnapshot(), [e]), a(() => e.getNavigationSnapshot(), [e]));
|
|
206
|
+
return c(() => ({
|
|
207
|
+
canGoNext: n.canGoNext,
|
|
208
|
+
canGoPrevious: n.canGoPrevious,
|
|
209
|
+
canGoBack: n.canGoBack,
|
|
210
|
+
isFirstStep: n.isFirstStep,
|
|
211
|
+
isLastStep: n.isLastStep,
|
|
212
|
+
visitedSteps: n.visitedSteps,
|
|
213
|
+
availableSteps: n.availableSteps,
|
|
214
|
+
stepHistory: n.stepHistory,
|
|
215
|
+
...p(t)
|
|
216
|
+
}), [
|
|
217
|
+
n.canGoNext,
|
|
218
|
+
n.canGoPrevious,
|
|
219
|
+
n.canGoBack,
|
|
220
|
+
n.isFirstStep,
|
|
221
|
+
n.isLastStep,
|
|
222
|
+
n.visitedSteps,
|
|
223
|
+
n.availableSteps,
|
|
224
|
+
n.stepHistory,
|
|
225
|
+
t
|
|
226
|
+
]);
|
|
227
|
+
}
|
|
228
|
+
function S() {
|
|
229
|
+
let { manager: e } = v(), t = d(a((t) => e.subscribe(t, "validation"), [e]), a(() => e.getValidationSnapshot(), [e]), a(() => e.getValidationSnapshot(), [e]));
|
|
230
|
+
return c(() => ({
|
|
231
|
+
isValid: t.isValid,
|
|
232
|
+
validationErrors: t.validationErrors
|
|
233
|
+
}), [t.isValid, t.validationErrors]);
|
|
234
|
+
}
|
|
235
|
+
function C() {
|
|
236
|
+
let { manager: e } = v(), t = d(a((t) => e.subscribe(t, "loading"), [e]), a(() => e.getLoadingSnapshot(), [e]), a(() => e.getLoadingSnapshot(), [e]));
|
|
237
|
+
return c(() => ({
|
|
238
|
+
isValidating: t.isValidating,
|
|
239
|
+
isSubmitting: t.isSubmitting,
|
|
240
|
+
isNavigating: t.isNavigating,
|
|
241
|
+
isLoadingStep: t.isLoadingStep
|
|
242
|
+
}), [
|
|
243
|
+
t.isValidating,
|
|
244
|
+
t.isSubmitting,
|
|
245
|
+
t.isNavigating,
|
|
246
|
+
t.isLoadingStep
|
|
247
|
+
]);
|
|
248
|
+
}
|
|
249
|
+
function w() {
|
|
250
|
+
let { actions: e } = y();
|
|
251
|
+
return c(() => m(e), [e]);
|
|
252
|
+
}
|
|
253
|
+
function T(e, t) {
|
|
254
|
+
if (t === void 0) {
|
|
255
|
+
let t = e, { data: n } = b(), { updateField: r } = w(), i = a((e) => r(t, e), [r, t]);
|
|
256
|
+
return [n[t], i];
|
|
257
|
+
}
|
|
258
|
+
let n = e, r = t, i = a((e) => n.actions.updateField(r, e), [n, r]);
|
|
259
|
+
return [n.state.data[r], i];
|
|
260
|
+
}
|
|
261
|
+
//#endregion
|
|
262
|
+
export { _ as WizardProvider, e as WizardRestoreError, t as WizardStateManager, h as useWizard, w as useWizardActions, b as useWizardData, T as useWizardField, C as useWizardLoading, x as useWizardNavigation, v as useWizardProviderContext, S as useWizardValidation };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { WizardData } from '@wizardkit/core';
|
|
2
|
+
import { UseWizardActions, UseWizardLoading, UseWizardNavigation, UseWizardReturn, UseWizardState, UseWizardValidation } from './use-wizard';
|
|
3
|
+
/**
|
|
4
|
+
* Hook for wizard data state
|
|
5
|
+
* Only re-renders when data or current step changes (subscribes to 'state' channel)
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```tsx
|
|
9
|
+
* const { data, currentStepId, currentStep } = useWizardData<MyFormData>();
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function useWizardData<T extends WizardData>(): UseWizardState<T>;
|
|
13
|
+
/**
|
|
14
|
+
* Hook for navigation state and methods
|
|
15
|
+
* Only re-renders when navigation state changes (subscribes to 'navigation' channel)
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* const { canGoNext, goNext, canGoPrevious, goPrevious } = useWizardNavigation();
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function useWizardNavigation(): UseWizardNavigation;
|
|
23
|
+
/**
|
|
24
|
+
* Hook for validation state
|
|
25
|
+
* Only re-renders when validation state changes (subscribes to 'validation' channel)
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```tsx
|
|
29
|
+
* const { isValid, validationErrors } = useWizardValidation();
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function useWizardValidation(): UseWizardValidation;
|
|
33
|
+
/**
|
|
34
|
+
* Hook for loading states
|
|
35
|
+
* Only re-renders when loading states change (subscribes to 'loading' channel)
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```tsx
|
|
39
|
+
* const { isValidating, isSubmitting, isNavigating, isLoadingStep } = useWizardLoading();
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function useWizardLoading(): UseWizardLoading;
|
|
43
|
+
/**
|
|
44
|
+
* Hook for wizard actions
|
|
45
|
+
* Does not subscribe to any channel - actions are stable references
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```tsx
|
|
49
|
+
* const { updateField, submit, reset } = useWizardActions<MyFormData>();
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare function useWizardActions<T extends WizardData>(): UseWizardActions<T>;
|
|
53
|
+
/**
|
|
54
|
+
* Controlled-input binding for a single wizard field.
|
|
55
|
+
* Returns a `[value, setValue]` tuple. React has no two-way-binding primitive,
|
|
56
|
+
* so this is the analogue of Vue's `useWizardField` (which returns a WritableComputedRef).
|
|
57
|
+
*
|
|
58
|
+
* Provider mode (inside <WizardProvider>):
|
|
59
|
+
* const [name, setName] = useWizardField<MyData, "name">("name");
|
|
60
|
+
* Direct mode (with a useWizard() return):
|
|
61
|
+
* const wizard = useWizard({ definition, initialData });
|
|
62
|
+
* const [name, setName] = useWizardField(wizard, "name");
|
|
63
|
+
*
|
|
64
|
+
* Hooks-rules caveat: a single call site must not switch between the two styles
|
|
65
|
+
* across renders (the provider-mode branch calls hooks). Pick one style per call
|
|
66
|
+
* site — the same contract Vue's `useWizardField` carries.
|
|
67
|
+
*/
|
|
68
|
+
export declare function useWizardField<T extends WizardData, K extends keyof T>(field: K): [T[K], (value: T[K]) => void];
|
|
69
|
+
export declare function useWizardField<T extends WizardData, K extends keyof T>(wizard: UseWizardReturn<T>, field: K): [T[K], (value: T[K]) => void];
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { GoToOptions, StepId, StepStatus, ValidationSummary, WizardContext, WizardData, WizardDefinition, WizardPlugin, WizardProgress, WizardSerializedState, WizardState, WizardStepDefinition } from '@wizardkit/core';
|
|
2
|
+
import { WizardBindingActions } from '@wizardkit/state';
|
|
3
|
+
/**
|
|
4
|
+
* React hook options
|
|
5
|
+
*/
|
|
6
|
+
export interface UseWizardOptions<T extends WizardData> {
|
|
7
|
+
/**
|
|
8
|
+
* Read ONCE at mount and captured — NOT reactive. Changing this prop after the
|
|
9
|
+
* first render has no effect (the machine is created once). To reconfigure,
|
|
10
|
+
* remount the hook with a new `key`.
|
|
11
|
+
*/
|
|
12
|
+
definition: WizardDefinition<T>;
|
|
13
|
+
/**
|
|
14
|
+
* Read ONCE at mount and captured — NOT reactive. Changing this prop after the
|
|
15
|
+
* first render has no effect (the machine is created once). To reconfigure,
|
|
16
|
+
* remount the hook with a new `key`.
|
|
17
|
+
*/
|
|
18
|
+
initialData: T;
|
|
19
|
+
/**
|
|
20
|
+
* Read ONCE at mount and captured — NOT reactive. Changing this prop after the
|
|
21
|
+
* first render has no effect (the machine is created once). To reconfigure,
|
|
22
|
+
* remount the hook with a new `key`.
|
|
23
|
+
*/
|
|
24
|
+
context?: WizardContext;
|
|
25
|
+
onStateChange?: (state: WizardState<T>) => void;
|
|
26
|
+
onStepEnter?: (stepId: StepId, data: T) => void;
|
|
27
|
+
onStepLeave?: (stepId: StepId, data: T) => void;
|
|
28
|
+
onComplete?: (data: T) => void;
|
|
29
|
+
onCancel?: (data: T) => void | Promise<void>;
|
|
30
|
+
onReset?: () => void;
|
|
31
|
+
onError?: (error: Error) => void;
|
|
32
|
+
onDataChange?: (prevData: T, nextData: T, changedFields: (keyof T)[]) => void;
|
|
33
|
+
/**
|
|
34
|
+
* Plugins registered once at machine creation (reference-stable — read once,
|
|
35
|
+
* NOT reactive). Define them outside render or memoize them.
|
|
36
|
+
*
|
|
37
|
+
* `onInit` may run for a manager that is later discarded/recreated under React
|
|
38
|
+
* StrictMode or concurrent rendering, so `onInit` must be idempotent and any
|
|
39
|
+
* resource it acquires must be released in `destroy()`.
|
|
40
|
+
*/
|
|
41
|
+
plugins?: WizardPlugin<T>[];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* State slice - current step and data
|
|
45
|
+
*/
|
|
46
|
+
export interface UseWizardState<T extends WizardData> {
|
|
47
|
+
currentStepId: StepId;
|
|
48
|
+
currentStep: WizardStepDefinition<T>;
|
|
49
|
+
data: T;
|
|
50
|
+
isCompleted: boolean;
|
|
51
|
+
stepStatuses: Record<StepId, StepStatus>;
|
|
52
|
+
progress: WizardProgress;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Validation slice - validation state and errors
|
|
56
|
+
*/
|
|
57
|
+
export interface UseWizardValidation {
|
|
58
|
+
isValid: boolean;
|
|
59
|
+
validationErrors?: Record<string, string>;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Navigation slice - step navigation capabilities
|
|
63
|
+
*/
|
|
64
|
+
export interface UseWizardNavigationState {
|
|
65
|
+
canGoNext: boolean;
|
|
66
|
+
canGoPrevious: boolean;
|
|
67
|
+
canGoBack: boolean;
|
|
68
|
+
isFirstStep: boolean;
|
|
69
|
+
isLastStep: boolean;
|
|
70
|
+
visitedSteps: StepId[];
|
|
71
|
+
availableSteps: StepId[];
|
|
72
|
+
stepHistory: StepId[];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Navigation slice - step navigation methods
|
|
76
|
+
*/
|
|
77
|
+
export interface UseWizardNavigationActions {
|
|
78
|
+
goNext: () => Promise<void>;
|
|
79
|
+
goPrevious: () => Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* @deprecated Use `goPrevious()` instead. `goBack(1)` is equivalent;
|
|
82
|
+
* for multiple steps call `goPrevious()` repeatedly.
|
|
83
|
+
*/
|
|
84
|
+
goBack: (steps?: number) => Promise<void>;
|
|
85
|
+
goTo: (stepId: StepId, options?: GoToOptions) => Promise<void>;
|
|
86
|
+
/** @deprecated Use goTo(stepId) instead */
|
|
87
|
+
goToStep: (stepId: StepId) => Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
export type UseWizardNavigation = UseWizardNavigationState & UseWizardNavigationActions;
|
|
90
|
+
/**
|
|
91
|
+
* Loading slice - async operation states
|
|
92
|
+
*/
|
|
93
|
+
export interface UseWizardLoading {
|
|
94
|
+
isValidating: boolean;
|
|
95
|
+
isSubmitting: boolean;
|
|
96
|
+
isNavigating: boolean;
|
|
97
|
+
/** A lazy step implementation is loading (WIZ-013). */
|
|
98
|
+
isLoadingStep: boolean;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Helper types for individual wizard actions
|
|
102
|
+
*/
|
|
103
|
+
export type UpdateDataFn<T extends WizardData> = (updater: (data: T) => T) => void;
|
|
104
|
+
export type SetDataFn<T extends WizardData> = (data: T) => void;
|
|
105
|
+
export type UpdateFieldFn<T extends WizardData> = <K extends keyof T>(field: K, value: T[K]) => void;
|
|
106
|
+
export type ValidateFn = () => Promise<void>;
|
|
107
|
+
export type ValidateAllFn = (options?: {
|
|
108
|
+
updateStatuses?: boolean;
|
|
109
|
+
}) => Promise<ValidationSummary>;
|
|
110
|
+
export type CanSubmitFn = () => Promise<boolean>;
|
|
111
|
+
export type SubmitFn = () => Promise<void>;
|
|
112
|
+
export type ResetFn<T extends WizardData> = (data?: T) => void;
|
|
113
|
+
export type CancelFn = () => Promise<void>;
|
|
114
|
+
export type SerializeFn<T extends WizardData> = () => WizardSerializedState<T>;
|
|
115
|
+
export type RestoreFn<T extends WizardData> = (state: WizardSerializedState<T>) => void;
|
|
116
|
+
/**
|
|
117
|
+
* Actions slice - data mutations and validation
|
|
118
|
+
*/
|
|
119
|
+
export interface UseWizardActions<T extends WizardData> {
|
|
120
|
+
updateData: UpdateDataFn<T>;
|
|
121
|
+
setData: SetDataFn<T>;
|
|
122
|
+
updateField: UpdateFieldFn<T>;
|
|
123
|
+
validate: ValidateFn;
|
|
124
|
+
validateAll: ValidateAllFn;
|
|
125
|
+
canSubmit: CanSubmitFn;
|
|
126
|
+
submit: SubmitFn;
|
|
127
|
+
/**
|
|
128
|
+
* Resets to the initial step. `reset(data)` also makes `data` the new reset
|
|
129
|
+
* baseline, so a later `reset()` (or `cancel()`) restores `data` rather than
|
|
130
|
+
* the original `initialData`.
|
|
131
|
+
*/
|
|
132
|
+
reset: ResetFn<T>;
|
|
133
|
+
cancel: CancelFn;
|
|
134
|
+
serialize: SerializeFn<T>;
|
|
135
|
+
restore: RestoreFn<T>;
|
|
136
|
+
/**
|
|
137
|
+
* Loads a lazy step's implementation ahead of navigation (WIZ-013).
|
|
138
|
+
* Never rejects: meant for fire-and-forget hover/focus handlers; failures
|
|
139
|
+
* are reported by the navigation that needs the step.
|
|
140
|
+
*/
|
|
141
|
+
preloadStep: (stepId: StepId) => Promise<void>;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Complete wizard return value with organized concerns
|
|
145
|
+
*/
|
|
146
|
+
export interface UseWizardReturn<T extends WizardData> {
|
|
147
|
+
state: UseWizardState<T>;
|
|
148
|
+
validation: UseWizardValidation;
|
|
149
|
+
navigation: UseWizardNavigation;
|
|
150
|
+
loading: UseWizardLoading;
|
|
151
|
+
actions: UseWizardActions<T>;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Picks the navigation methods out of a shared action set. Explicit (no spread)
|
|
155
|
+
* so the slice never carries the data actions. Package-internal.
|
|
156
|
+
*/
|
|
157
|
+
export declare function pickNavigationActions<T extends WizardData>(actions: WizardBindingActions<T>): UseWizardNavigationActions;
|
|
158
|
+
/**
|
|
159
|
+
* Picks the data/validation/lifecycle methods out of a shared action set.
|
|
160
|
+
* Explicit (no spread) so the slice never carries the navigation methods.
|
|
161
|
+
* Package-internal.
|
|
162
|
+
*/
|
|
163
|
+
export declare function pickDataActions<T extends WizardData>(actions: WizardBindingActions<T>): UseWizardActions<T>;
|
|
164
|
+
/**
|
|
165
|
+
* React hook for wizard state management using useSyncExternalStore
|
|
166
|
+
* Returns organized state slices with fine-grained re-renders via channel subscriptions
|
|
167
|
+
*/
|
|
168
|
+
export declare function useWizard<T extends WizardData>(options: UseWizardOptions<T>): UseWizardReturn<T>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { StepId, WizardContext as WizardCoreContext, WizardData, WizardDefinition, WizardPlugin, WizardState } from '@wizardkit/core';
|
|
2
|
+
import { WizardBindingActions, WizardStateManager } from '@wizardkit/state';
|
|
3
|
+
import { ReactNode } from 'react';
|
|
4
|
+
/**
|
|
5
|
+
* Context for granular hooks - holds the WizardStateManager for fine-grained subscriptions.
|
|
6
|
+
*
|
|
7
|
+
* `initialData` is the prop captured at mount. It is kept for compatibility only:
|
|
8
|
+
* `reset()` no longer reads it (the machine owns the reset baseline).
|
|
9
|
+
*/
|
|
10
|
+
interface WizardProviderContextValue<T extends WizardData> {
|
|
11
|
+
manager: WizardStateManager<T>;
|
|
12
|
+
initialData: T;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The shape actually stored in the context. `actions` is the provider's single
|
|
16
|
+
* action set (built once per manager by `createWizardActions`), shared by the
|
|
17
|
+
* granular `useWizardNavigation` / `useWizardActions` hooks so every consumer
|
|
18
|
+
* gets the same stable identities and the same reference-counted loading flags.
|
|
19
|
+
* Its `reset`/`restore` report failures to this provider's current `onError`.
|
|
20
|
+
*
|
|
21
|
+
* Deliberately kept OFF `WizardProviderContextValue` — that is the return type of the
|
|
22
|
+
* exported `useWizardProviderContext()`, so widening it would widen the package's public
|
|
23
|
+
* type surface. `useWizardInternalContext` is not re-exported from `src/index.ts` and the
|
|
24
|
+
* package's `exports` map has no deep-import entry, so this stays internal.
|
|
25
|
+
*/
|
|
26
|
+
interface WizardProviderInternalContextValue<T extends WizardData> extends WizardProviderContextValue<T> {
|
|
27
|
+
actions: WizardBindingActions<T>;
|
|
28
|
+
}
|
|
29
|
+
export interface WizardProviderProps<T extends WizardData> {
|
|
30
|
+
/**
|
|
31
|
+
* Read ONCE at mount and captured — NOT reactive. Changing this prop after the
|
|
32
|
+
* first render has no effect (the machine is created once). To reconfigure,
|
|
33
|
+
* remount the provider with a new `key`.
|
|
34
|
+
*/
|
|
35
|
+
definition: WizardDefinition<T>;
|
|
36
|
+
/**
|
|
37
|
+
* Read ONCE at mount and captured — NOT reactive. Changing this prop after the
|
|
38
|
+
* first render has no effect (the machine is created once). To reconfigure,
|
|
39
|
+
* remount the provider with a new `key`.
|
|
40
|
+
*/
|
|
41
|
+
initialData: T;
|
|
42
|
+
/**
|
|
43
|
+
* Read ONCE at mount and captured — NOT reactive. Changing this prop after the
|
|
44
|
+
* first render has no effect (the machine is created once). To reconfigure,
|
|
45
|
+
* remount the provider with a new `key`.
|
|
46
|
+
*/
|
|
47
|
+
context?: WizardCoreContext;
|
|
48
|
+
onStateChange?: (state: WizardState<T>) => void;
|
|
49
|
+
onStepEnter?: (stepId: StepId, data: T) => void;
|
|
50
|
+
onStepLeave?: (stepId: StepId, data: T) => void;
|
|
51
|
+
onComplete?: (data: T) => void;
|
|
52
|
+
onCancel?: (data: T) => void | Promise<void>;
|
|
53
|
+
onReset?: () => void;
|
|
54
|
+
onError?: (error: Error) => void;
|
|
55
|
+
onDataChange?: (prevData: T, nextData: T, changedFields: (keyof T)[]) => void;
|
|
56
|
+
/**
|
|
57
|
+
* Plugins registered once at machine creation (reference-stable — read once,
|
|
58
|
+
* NOT reactive). Define them outside render or memoize them.
|
|
59
|
+
*
|
|
60
|
+
* `onInit` may run for a manager that is later discarded/recreated under React
|
|
61
|
+
* StrictMode or concurrent rendering, so `onInit` must be idempotent and any
|
|
62
|
+
* resource it acquires must be released in `destroy()`.
|
|
63
|
+
*/
|
|
64
|
+
plugins?: WizardPlugin<T>[];
|
|
65
|
+
children: ReactNode;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Provider for fine-grained subscriptions via granular hooks
|
|
69
|
+
* Exposes a shared WizardStateManager instance for channel-based subscriptions
|
|
70
|
+
*/
|
|
71
|
+
export declare function WizardProvider<T extends WizardData>({ definition, initialData, context, onStateChange, onStepEnter, onStepLeave, onComplete, onCancel, onReset, onError, onDataChange, plugins, children, }: WizardProviderProps<T>): import("react").JSX.Element;
|
|
72
|
+
/**
|
|
73
|
+
* Get wizard provider context (internal use for granular hooks)
|
|
74
|
+
* @throws {Error} if used outside of WizardProvider
|
|
75
|
+
*/
|
|
76
|
+
export declare function useWizardProviderContext<T extends WizardData>(): WizardProviderContextValue<T>;
|
|
77
|
+
/**
|
|
78
|
+
* Same context, widened with the provider-owned `actions`. Package-internal: it is
|
|
79
|
+
* NOT re-exported from `src/index.ts`, so the public surface stays
|
|
80
|
+
* `useWizardProviderContext()`'s narrower `WizardProviderContextValue`.
|
|
81
|
+
* @throws {Error} if used outside of WizardProvider
|
|
82
|
+
*/
|
|
83
|
+
export declare function useWizardInternalContext<T extends WizardData>(): WizardProviderInternalContextValue<T>;
|
|
84
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,80 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wizardkit/react",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.13.0",
|
|
4
|
+
"description": "Headless multi-step form and wizard hooks for React. Type-safe useWizard with conditional steps, validation and navigation history, powered by WizardKit.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"wizard",
|
|
7
|
+
"multi-step-form",
|
|
8
|
+
"multistep",
|
|
9
|
+
"stepper",
|
|
10
|
+
"form-wizard",
|
|
11
|
+
"onboarding",
|
|
12
|
+
"state-machine",
|
|
13
|
+
"headless",
|
|
14
|
+
"typescript",
|
|
15
|
+
"react",
|
|
16
|
+
"react-hooks",
|
|
17
|
+
"hook",
|
|
18
|
+
"use-wizard",
|
|
19
|
+
"react-wizard",
|
|
20
|
+
"react-stepper"
|
|
21
|
+
],
|
|
22
|
+
"homepage": "https://wizardkit.dev/guide/react-integration",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/gooonzick/wizard/issues"
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"main": "./dist/index.js",
|
|
29
|
+
"module": "./dist/index.js",
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"import": "./dist/index.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"README.md"
|
|
40
|
+
],
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"react": "^18.0.0 || ^19.0.0",
|
|
43
|
+
"react-dom": "^18.0.0 || ^19.0.0"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"@wizardkit/core": "1.13.0",
|
|
47
|
+
"@wizardkit/state": "1.13.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@biomejs/biome": "^2.5.3",
|
|
51
|
+
"@testing-library/react": "^16.3.2",
|
|
52
|
+
"@types/node": "^26.1.1",
|
|
53
|
+
"@types/react": "^19.2.17",
|
|
54
|
+
"@vitejs/plugin-react": "^6.0.3",
|
|
55
|
+
"@vitest/coverage-v8": "^4.1.10",
|
|
56
|
+
"jsdom": "^29.1.1",
|
|
57
|
+
"react": "^19.2.7",
|
|
58
|
+
"react-dom": "^19.2.7",
|
|
59
|
+
"typescript": "^6.0.3",
|
|
60
|
+
"vite": "^8.1.4",
|
|
61
|
+
"vite-plugin-dts": "^5.0.3",
|
|
62
|
+
"vitest": "^4.1.10"
|
|
63
|
+
},
|
|
64
|
+
"repository": {
|
|
65
|
+
"type": "git",
|
|
66
|
+
"url": "https://github.com/gooonzick/wizard",
|
|
67
|
+
"directory": "packages/react"
|
|
68
|
+
},
|
|
69
|
+
"publishConfig": {
|
|
70
|
+
"access": "public"
|
|
71
|
+
},
|
|
72
|
+
"scripts": {
|
|
73
|
+
"build": "vite build",
|
|
74
|
+
"typecheck": "tsc --build --verbose",
|
|
75
|
+
"test": "vitest --run",
|
|
76
|
+
"test:watch": "vitest --watch",
|
|
77
|
+
"lint": "biome check .",
|
|
78
|
+
"lint:fix": "biome check . --write"
|
|
79
|
+
}
|
|
6
80
|
}
|