wizzard-stepper-react 1.7.0 → 1.7.2

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/dist/index.cjs CHANGED
@@ -1,954 +1 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
21
-
22
- // src/index.ts
23
- var index_exports = {};
24
- __export(index_exports, {
25
- LocalStorageAdapter: () => LocalStorageAdapter,
26
- MemoryAdapter: () => MemoryAdapter,
27
- WizardProvider: () => WizardProvider,
28
- WizardStepRenderer: () => WizardStepRenderer,
29
- WizardStore: () => WizardStore,
30
- YupAdapter: () => YupAdapter,
31
- ZodAdapter: () => ZodAdapter,
32
- createWizardFactory: () => createWizardFactory,
33
- getByPath: () => getByPath,
34
- setByPath: () => setByPath,
35
- shallowEqual: () => shallowEqual,
36
- toPath: () => toPath,
37
- useWizard: () => useWizard,
38
- useWizardActions: () => useWizardActions,
39
- useWizardContext: () => useWizardContext,
40
- useWizardError: () => useWizardError,
41
- useWizardSelector: () => useWizardSelector,
42
- useWizardState: () => useWizardState,
43
- useWizardValue: () => useWizardValue
44
- });
45
- module.exports = __toCommonJS(index_exports);
46
-
47
- // src/context/WizardContext.tsx
48
- var import_react = require("react");
49
-
50
- // src/adapters/persistence/MemoryAdapter.ts
51
- var MemoryAdapter = class {
52
- constructor() {
53
- __publicField(this, "storage", {});
54
- }
55
- saveStep(stepId, data) {
56
- this.storage[stepId] = data;
57
- }
58
- getStep(stepId) {
59
- return this.storage[stepId];
60
- }
61
- clear() {
62
- this.storage = {};
63
- }
64
- };
65
-
66
- // src/utils/data.ts
67
- var pathCache = /* @__PURE__ */ new Map();
68
- function toPath(path) {
69
- if (!path) return [];
70
- if (pathCache.has(path)) {
71
- return pathCache.get(path);
72
- }
73
- let keys;
74
- if (path.includes("[")) {
75
- keys = path.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
76
- } else {
77
- keys = path.split(".").filter(Boolean);
78
- }
79
- pathCache.set(path, keys);
80
- return keys;
81
- }
82
- function getByPath(obj, path, defaultValue) {
83
- if (!path || obj === void 0 || obj === null) return defaultValue ?? obj;
84
- if (!path.includes(".") && !path.includes("[")) {
85
- const val = obj[path];
86
- return val !== void 0 ? val : defaultValue;
87
- }
88
- const keys = toPath(path);
89
- let result = obj;
90
- for (let i = 0; i < keys.length; i++) {
91
- if (result === void 0 || result === null) return defaultValue;
92
- result = result[keys[i]];
93
- }
94
- return result !== void 0 ? result : defaultValue;
95
- }
96
- function setByPath(obj, path, value) {
97
- if (!path) return value;
98
- if (!path.includes(".") && !path.includes("[")) {
99
- if (Array.isArray(obj)) {
100
- const copy = [...obj];
101
- copy[path] = value;
102
- return copy;
103
- }
104
- return { ...obj, [path]: value };
105
- }
106
- const keys = toPath(path);
107
- if (keys.length === 0) return value;
108
- const root = Array.isArray(obj) ? [...obj] : { ...obj };
109
- let current = root;
110
- for (let i = 0; i < keys.length - 1; i++) {
111
- const key = keys[i];
112
- const nextKey = keys[i + 1];
113
- const existing = current[key];
114
- let nextLevel;
115
- if (existing && typeof existing === "object") {
116
- nextLevel = Array.isArray(existing) ? [...existing] : { ...existing };
117
- } else {
118
- const isNumeric = /^\d+$/.test(nextKey);
119
- nextLevel = isNumeric ? [] : {};
120
- }
121
- current[key] = nextLevel;
122
- current = nextLevel;
123
- }
124
- const lastKey = keys[keys.length - 1];
125
- current[lastKey] = value;
126
- return root;
127
- }
128
- function shallowEqual(a, b) {
129
- if (Object.is(a, b)) return true;
130
- if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) {
131
- return false;
132
- }
133
- const keysA = Object.keys(a);
134
- const keysB = Object.keys(b);
135
- if (keysA.length !== keysB.length) return false;
136
- for (let i = 0; i < keysA.length; i++) {
137
- const key = keysA[i];
138
- if (!Object.prototype.hasOwnProperty.call(b, key) || !Object.is(a[key], b[key])) {
139
- return false;
140
- }
141
- }
142
- return true;
143
- }
144
-
145
- // src/context/WizardContext.tsx
146
- var import_jsx_runtime = require("react/jsx-runtime");
147
- var WizardStateContext = (0, import_react.createContext)(
148
- void 0
149
- );
150
- var WizardActionsContext = (0, import_react.createContext)(
151
- void 0
152
- );
153
- var WizardStore = class {
154
- constructor(initialData) {
155
- __publicField(this, "state");
156
- __publicField(this, "listeners", /* @__PURE__ */ new Set());
157
- __publicField(this, "errorsMap", /* @__PURE__ */ new Map());
158
- __publicField(this, "subscribe", (listener) => {
159
- this.listeners.add(listener);
160
- return () => this.listeners.delete(listener);
161
- });
162
- this.state = {
163
- data: initialData,
164
- errors: {}
165
- };
166
- }
167
- getSnapshot() {
168
- return this.state;
169
- }
170
- update(newData) {
171
- this.state = { ...this.state, data: newData };
172
- this.notify();
173
- }
174
- // Sync internal Map to external Object (for backward compat)
175
- syncErrors() {
176
- const newErrorsObj = {};
177
- for (const [stepId, fieldErrors] of this.errorsMap.entries()) {
178
- if (fieldErrors.size > 0) {
179
- newErrorsObj[stepId] = Object.fromEntries(fieldErrors);
180
- }
181
- }
182
- this.state = { ...this.state, errors: newErrorsObj };
183
- this.notify();
184
- }
185
- // Update from Object (Legacy/State setter)
186
- updateErrors(newErrors) {
187
- this.errorsMap.clear();
188
- for (const [stepId, fieldErrors] of Object.entries(newErrors)) {
189
- const stepMap = /* @__PURE__ */ new Map();
190
- for (const [field, msg] of Object.entries(fieldErrors)) {
191
- stepMap.set(field, msg);
192
- }
193
- if (stepMap.size > 0) this.errorsMap.set(stepId, stepMap);
194
- }
195
- this.state = { ...this.state, errors: newErrors };
196
- this.notify();
197
- }
198
- // Optimize: Update Step Errors directly (O(1) Map updated, then Sync)
199
- setStepErrors(stepId, errors) {
200
- if (!errors || Object.keys(errors).length === 0) {
201
- if (this.errorsMap.has(stepId)) {
202
- this.errorsMap.delete(stepId);
203
- this.syncErrors();
204
- return true;
205
- }
206
- return false;
207
- }
208
- const stepMap = /* @__PURE__ */ new Map();
209
- for (const [field, msg] of Object.entries(errors)) {
210
- stepMap.set(field, msg);
211
- }
212
- this.errorsMap.set(stepId, stepMap);
213
- this.syncErrors();
214
- return true;
215
- }
216
- // Fast Delete (O(1))
217
- deleteError(stepId, path) {
218
- const stepErrors = this.errorsMap.get(stepId);
219
- if (!stepErrors) return false;
220
- if (stepErrors.has(path)) {
221
- stepErrors.delete(path);
222
- if (stepErrors.size === 0) {
223
- this.errorsMap.delete(stepId);
224
- }
225
- this.syncErrors();
226
- return true;
227
- }
228
- return false;
229
- }
230
- notify() {
231
- this.listeners.forEach((l) => l());
232
- }
233
- };
234
- function WizardProvider({
235
- config,
236
- initialData,
237
- initialStepId,
238
- children
239
- }) {
240
- const [currentStepId, setCurrentStepId] = (0, import_react.useState)("");
241
- const currentStepIdRef = (0, import_react.useRef)(currentStepId);
242
- (0, import_react.useEffect)(() => {
243
- currentStepIdRef.current = currentStepId;
244
- }, [currentStepId]);
245
- const [visitedSteps, setVisitedSteps] = (0, import_react.useState)(/* @__PURE__ */ new Set());
246
- const [completedSteps, setCompletedSteps] = (0, import_react.useState)(/* @__PURE__ */ new Set());
247
- const [errorSteps, setErrorSteps] = (0, import_react.useState)(/* @__PURE__ */ new Set());
248
- const [, setAllErrorsState] = (0, import_react.useState)({});
249
- const [isLoading, setIsLoading] = (0, import_react.useState)(true);
250
- const [isPending, startTransition] = (0, import_react.useTransition)();
251
- const storeRef = (0, import_react.useRef)(new WizardStore(initialData || {}));
252
- const persistenceAdapter = (0, import_react.useMemo)(() => {
253
- return config.persistence?.adapter || new MemoryAdapter();
254
- }, [config.persistence?.adapter]);
255
- const persistenceMode = config.persistence?.mode || "onStepChange";
256
- const stepsMap = (0, import_react.useMemo)(() => {
257
- const map = /* @__PURE__ */ new Map();
258
- config.steps.forEach((step) => map.set(step.id, step));
259
- return map;
260
- }, [config.steps]);
261
- const lastActiveStepsRef = (0, import_react.useRef)([]);
262
- const activeSteps = (0, import_react.useSyncExternalStore)(
263
- storeRef.current.subscribe,
264
- (0, import_react.useCallback)(() => {
265
- const currentData = storeRef.current.getSnapshot().data;
266
- const nextActiveSteps = config.steps.filter((step) => {
267
- if (step.condition) {
268
- return step.condition(currentData);
269
- }
270
- return true;
271
- });
272
- const prevIds = lastActiveStepsRef.current.map((s) => s.id).join(".");
273
- const nextIds = nextActiveSteps.map((s) => s.id).join(".");
274
- if (prevIds === nextIds && lastActiveStepsRef.current.length > 0) {
275
- return lastActiveStepsRef.current;
276
- }
277
- lastActiveStepsRef.current = nextActiveSteps;
278
- return nextActiveSteps;
279
- }, [config.steps])
280
- );
281
- const activeStepsIndexMap = (0, import_react.useMemo)(() => {
282
- const map = /* @__PURE__ */ new Map();
283
- activeSteps.forEach((s, i) => map.set(s.id, i));
284
- return map;
285
- }, [activeSteps]);
286
- (0, import_react.useEffect)(() => {
287
- if (!currentStepId && activeSteps.length > 0) {
288
- if (initialStepId) {
289
- const target = activeSteps.find((s) => s.id === initialStepId);
290
- if (target) {
291
- setCurrentStepId(target.id);
292
- } else {
293
- setCurrentStepId(activeSteps[0].id);
294
- }
295
- } else {
296
- setCurrentStepId(activeSteps[0].id);
297
- }
298
- setIsLoading(false);
299
- }
300
- }, [activeSteps, currentStepId, initialStepId]);
301
- const stateRef = (0, import_react.useRef)({
302
- config,
303
- stepsMap,
304
- activeSteps,
305
- activeStepsIndexMap,
306
- visitedSteps,
307
- completedSteps,
308
- persistenceMode,
309
- persistenceAdapter,
310
- currentStepId
311
- });
312
- stateRef.current = {
313
- config,
314
- stepsMap,
315
- activeSteps,
316
- activeStepsIndexMap,
317
- visitedSteps,
318
- completedSteps,
319
- persistenceMode,
320
- persistenceAdapter,
321
- currentStepId
322
- };
323
- const currentStep = (0, import_react.useMemo)(
324
- () => stepsMap.get(currentStepId) || null,
325
- [stepsMap, currentStepId]
326
- );
327
- const currentStepIndex = (0, import_react.useMemo)(
328
- () => activeStepsIndexMap.get(currentStepId) ?? -1,
329
- [activeStepsIndexMap, currentStepId]
330
- );
331
- const isFirstStep = currentStepIndex === 0;
332
- const isLastStep = currentStepIndex === activeSteps.length - 1;
333
- const META_KEY = "__wizzard_meta__";
334
- const hydrate = (0, import_react.useCallback)(() => {
335
- setIsLoading(true);
336
- const { persistenceAdapter: persistenceAdapter2, config: config2 } = stateRef.current;
337
- const metaFn = persistenceAdapter2.getStep(META_KEY);
338
- if (metaFn) {
339
- if (metaFn.currentStepId) setCurrentStepId(metaFn.currentStepId);
340
- if (metaFn.visited) setVisitedSteps(new Set(metaFn.visited));
341
- if (metaFn.completed) setCompletedSteps(new Set(metaFn.completed));
342
- }
343
- const loadedData = {};
344
- config2.steps.forEach((step) => {
345
- const stepData = persistenceAdapter2.getStep(step.id);
346
- if (stepData) {
347
- Object.assign(loadedData, stepData);
348
- }
349
- });
350
- if (Object.keys(loadedData).length > 0) {
351
- const currentData = storeRef.current.getSnapshot().data;
352
- const newData = { ...currentData, ...loadedData };
353
- storeRef.current.update(newData);
354
- }
355
- setIsLoading(false);
356
- }, []);
357
- (0, import_react.useEffect)(() => {
358
- hydrate();
359
- }, [hydrate]);
360
- const saveData = (0, import_react.useCallback)(
361
- (mode, stepId, data) => {
362
- const { stepsMap: stepsMap2, persistenceAdapter: persistenceAdapter2, persistenceMode: globalMode } = stateRef.current;
363
- const stepConfig = stepsMap2.get(stepId);
364
- const stepAdapter = stepConfig?.persistenceAdapter;
365
- const stepMode = stepConfig?.persistenceMode;
366
- const adapterToUse = stepAdapter || persistenceAdapter2;
367
- const modeToUse = stepMode || globalMode;
368
- if (mode === modeToUse || mode === "manual") {
369
- adapterToUse.saveStep(stepId, data);
370
- }
371
- },
372
- []
373
- );
374
- const validationTimeoutRef = (0, import_react.useRef)(
375
- null
376
- );
377
- const validateStep = (0, import_react.useCallback)(
378
- async (stepId, data) => {
379
- const { stepsMap: stepsMap2 } = stateRef.current;
380
- const step = stepsMap2.get(stepId);
381
- if (!step || !step.validationAdapter) {
382
- return true;
383
- }
384
- const result = await step.validationAdapter.validate(data);
385
- if (result.isValid) {
386
- const changed = storeRef.current.setStepErrors(stepId, null);
387
- if (changed) {
388
- setAllErrorsState(storeRef.current.getSnapshot().errors);
389
- setErrorSteps((prev) => {
390
- const next = new Set(prev);
391
- next.delete(stepId);
392
- return next;
393
- });
394
- }
395
- return true;
396
- } else {
397
- storeRef.current.setStepErrors(stepId, result.errors || null);
398
- setAllErrorsState(storeRef.current.getSnapshot().errors);
399
- setErrorSteps((prev) => {
400
- const next = new Set(prev);
401
- next.add(stepId);
402
- return next;
403
- });
404
- return false;
405
- }
406
- },
407
- []
408
- );
409
- const setStepData = (0, import_react.useCallback)(
410
- (stepId, data) => {
411
- const { persistenceMode: persistenceMode2 } = stateRef.current;
412
- const prevData = storeRef.current.getSnapshot().data;
413
- const newData = { ...prevData, ...data };
414
- storeRef.current.update(newData);
415
- const stepConfig = stateRef.current.stepsMap.get(stepId);
416
- const effectiveMode = stepConfig?.persistenceMode || persistenceMode2;
417
- if (effectiveMode === "onChange") {
418
- saveData("onChange", stepId, newData);
419
- }
420
- },
421
- [saveData]
422
- );
423
- const setData = (0, import_react.useCallback)(
424
- (path, value, options) => {
425
- const { persistenceMode: persistenceMode2, stepsMap: stepsMap2 } = stateRef.current;
426
- const prevData = storeRef.current.getSnapshot().data;
427
- const currentValue = getByPath(prevData, path);
428
- if (currentValue === value) return;
429
- const newData = setByPath(prevData, path, value);
430
- storeRef.current.update(newData);
431
- const activeStepId = stateRef.current.currentStepId;
432
- const stepConfig = stepsMap2.get(activeStepId);
433
- if (activeStepId) {
434
- const wasDeleted = storeRef.current.deleteError(activeStepId, path);
435
- if (wasDeleted) {
436
- if (!storeRef.current.errorsMap.has(activeStepId)) {
437
- setErrorSteps((prev) => {
438
- const next = new Set(prev);
439
- next.delete(activeStepId);
440
- return next;
441
- });
442
- }
443
- }
444
- }
445
- if (activeStepId && storeRef.current.getSnapshot().errors[activeStepId]) {
446
- startTransition(() => {
447
- setAllErrorsState(storeRef.current.getSnapshot().errors);
448
- });
449
- }
450
- const { config: config2 } = stateRef.current;
451
- const mode = stepConfig?.validationMode ?? config2.validationMode ?? "onStepChange";
452
- if (mode === "onChange") {
453
- if (options?.debounceValidation) {
454
- if (validationTimeoutRef.current)
455
- clearTimeout(validationTimeoutRef.current);
456
- validationTimeoutRef.current = setTimeout(() => {
457
- try {
458
- if (activeStepId) {
459
- validateStep(activeStepId, newData).catch((err) => {
460
- console.error("[Wizard] Debounced validation failed:", err);
461
- });
462
- }
463
- } catch (e) {
464
- console.error("[Wizard] Error starting validation:", e);
465
- }
466
- }, options.debounceValidation);
467
- } else {
468
- if (activeStepId) validateStep(activeStepId, newData);
469
- }
470
- }
471
- const effectivePersistenceMode = stepConfig?.persistenceMode ?? persistenceMode2;
472
- if (effectivePersistenceMode === "onChange" && activeStepId) {
473
- saveData("onChange", activeStepId, newData);
474
- }
475
- },
476
- [saveData, validateStep]
477
- );
478
- const updateData = (0, import_react.useCallback)(
479
- (data, options) => {
480
- const { config: config2 } = stateRef.current;
481
- const prevData = storeRef.current.getSnapshot().data;
482
- const newData = options?.replace ? data : { ...prevData, ...data };
483
- storeRef.current.update(newData);
484
- if (options?.persist) {
485
- config2.steps.forEach((step) => {
486
- saveData("manual", step.id, newData);
487
- });
488
- }
489
- },
490
- [saveData]
491
- );
492
- const getData = (0, import_react.useCallback)((path, defaultValue) => {
493
- return getByPath(storeRef.current.getSnapshot().data, path, defaultValue);
494
- }, []);
495
- const handleStepChange = (0, import_react.useCallback)(
496
- (field, value) => {
497
- const { currentStepId: currentStepId2 } = stateRef.current;
498
- if (!currentStepId2) return;
499
- setData(field, value);
500
- },
501
- [setData]
502
- );
503
- const validateAll = (0, import_react.useCallback)(async () => {
504
- const { activeSteps: activeSteps2 } = stateRef.current;
505
- const currentData = storeRef.current.getSnapshot().data;
506
- const validationResults = await Promise.all(
507
- activeSteps2.map((step) => validateStep(step.id, currentData))
508
- );
509
- const isValid = validationResults.every(Boolean);
510
- const finalErrors = storeRef.current.getSnapshot().errors;
511
- return { isValid, errors: finalErrors };
512
- }, [validateStep]);
513
- const goToStep = (0, import_react.useCallback)(
514
- async (stepId) => {
515
- const {
516
- activeStepsIndexMap: activeStepsIndexMap2,
517
- currentStepId: currentStepId2,
518
- config: config2,
519
- persistenceMode: persistenceMode2,
520
- visitedSteps: visitedSteps2,
521
- completedSteps: completedSteps2,
522
- persistenceAdapter: persistenceAdapter2,
523
- stepsMap: stepsMap2
524
- } = stateRef.current;
525
- const targetIndex = activeStepsIndexMap2.get(stepId) ?? -1;
526
- if (targetIndex === -1) return false;
527
- const currentData = storeRef.current.getSnapshot().data;
528
- const currentStepIndex2 = activeStepsIndexMap2.get(currentStepId2) ?? -1;
529
- const currentStep2 = stepsMap2.get(currentStepId2);
530
- if (targetIndex > currentStepIndex2) {
531
- const shouldValidate = currentStep2?.autoValidate ?? config2.autoValidate ?? false;
532
- if (shouldValidate && currentStepId2) {
533
- const isValid = await validateStep(currentStepId2, currentData);
534
- if (!isValid) return false;
535
- }
536
- }
537
- if (currentStep2 && currentStepId2) {
538
- const effectivePersistenceMode = currentStep2.persistenceMode ?? persistenceMode2;
539
- if (effectivePersistenceMode === "onStepChange") {
540
- saveData("onStepChange", currentStepId2, currentData);
541
- }
542
- }
543
- const nextVisited = new Set(visitedSteps2);
544
- if (currentStepId2) nextVisited.add(currentStepId2);
545
- setVisitedSteps(nextVisited);
546
- setCurrentStepId(stepId);
547
- if (persistenceMode2 !== "manual") {
548
- persistenceAdapter2.saveStep(META_KEY, {
549
- currentStepId: stepId,
550
- visited: Array.from(nextVisited),
551
- completed: Array.from(completedSteps2)
552
- });
553
- }
554
- if (config2.onStepChange) {
555
- config2.onStepChange(currentStepId2 || null, stepId, currentData);
556
- }
557
- window.scrollTo(0, 0);
558
- return true;
559
- },
560
- [saveData, validateStep]
561
- );
562
- const goToNextStep = (0, import_react.useCallback)(async () => {
563
- const { activeSteps: activeSteps2, activeStepsIndexMap: activeStepsIndexMap2, currentStepId: currentStepId2, completedSteps: completedSteps2, persistenceMode: persistenceMode2 } = stateRef.current;
564
- const currentStepIndex2 = activeStepsIndexMap2.get(currentStepId2) ?? -1;
565
- if (currentStepIndex2 === -1 || currentStepIndex2 === activeSteps2.length - 1) return;
566
- const nextStep = activeSteps2[currentStepIndex2 + 1];
567
- if (nextStep) {
568
- const success = await goToStep(nextStep.id);
569
- if (success) {
570
- const nextCompleted = new Set(completedSteps2).add(currentStepId2);
571
- setCompletedSteps(nextCompleted);
572
- if (persistenceMode2 !== "manual") {
573
- persistenceAdapter.saveStep(META_KEY, {
574
- currentStepId: nextStep.id,
575
- visited: Array.from(new Set(visitedSteps).add(currentStepId2)),
576
- completed: Array.from(nextCompleted)
577
- });
578
- }
579
- }
580
- }
581
- }, [goToStep]);
582
- const goToPrevStep = (0, import_react.useCallback)(() => {
583
- const { activeSteps: activeSteps2, activeStepsIndexMap: activeStepsIndexMap2, currentStepId: currentStepId2 } = stateRef.current;
584
- const currentStepIndex2 = activeStepsIndexMap2.get(currentStepId2) ?? -1;
585
- if (currentStepIndex2 <= 0) return;
586
- const prevStep = activeSteps2[currentStepIndex2 - 1];
587
- if (prevStep) {
588
- goToStep(prevStep.id);
589
- }
590
- }, [goToStep]);
591
- const clearStorage = (0, import_react.useCallback)(() => {
592
- stateRef.current.persistenceAdapter.clear();
593
- }, []);
594
- const save = (0, import_react.useCallback)(
595
- (stepIds) => {
596
- const { config: config2, currentStepId: currentStepId2 } = stateRef.current;
597
- const data = storeRef.current.getSnapshot().data;
598
- if (stepIds === true) {
599
- config2.steps.forEach((step) => {
600
- saveData("manual", step.id, data);
601
- });
602
- return;
603
- }
604
- if (!stepIds) {
605
- if (currentStepId2) {
606
- saveData("manual", currentStepId2, data);
607
- }
608
- return;
609
- }
610
- const ids = Array.isArray(stepIds) ? stepIds : [stepIds];
611
- ids.forEach((id) => {
612
- saveData("manual", id, data);
613
- });
614
- },
615
- [saveData]
616
- );
617
- const stateValue = (0, import_react.useMemo)(
618
- () => ({
619
- currentStep,
620
- currentStepIndex,
621
- isFirstStep,
622
- isLastStep,
623
- isLoading,
624
- isPending,
625
- activeSteps,
626
- visitedSteps,
627
- completedSteps,
628
- errorSteps,
629
- store: storeRef.current
630
- }),
631
- [
632
- currentStep,
633
- currentStepIndex,
634
- isFirstStep,
635
- isLastStep,
636
- isLoading,
637
- isPending,
638
- activeSteps,
639
- visitedSteps,
640
- completedSteps,
641
- errorSteps
642
- ]
643
- );
644
- const actionsValue = (0, import_react.useMemo)(
645
- () => ({
646
- goToNextStep,
647
- goToPrevStep,
648
- goToStep,
649
- setStepData,
650
- handleStepChange,
651
- validateStep: (sid) => validateStep(sid, storeRef.current.getSnapshot().data),
652
- validateAll,
653
- save,
654
- clearStorage,
655
- setData,
656
- updateData,
657
- getData
658
- }),
659
- [
660
- goToNextStep,
661
- goToPrevStep,
662
- goToStep,
663
- setStepData,
664
- handleStepChange,
665
- validateStep,
666
- validateAll,
667
- save,
668
- clearStorage,
669
- setData,
670
- updateData,
671
- getData
672
- ]
673
- );
674
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WizardStateContext.Provider, { value: stateValue, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WizardActionsContext.Provider, { value: actionsValue, children }) });
675
- }
676
- function useWizardState() {
677
- const context = (0, import_react.useContext)(WizardStateContext);
678
- if (!context) {
679
- throw new Error("useWizardState must be used within a WizardProvider");
680
- }
681
- return context;
682
- }
683
- function useWizardValue(path, options) {
684
- const { store } = useWizardState();
685
- const lastStateRef = (0, import_react.useRef)(null);
686
- const lastValueRef = (0, import_react.useRef)(null);
687
- const isEqual = options?.isEqual || Object.is;
688
- const getSnapshot = (0, import_react.useCallback)(() => {
689
- const fullState = store.getSnapshot();
690
- const data = fullState.data;
691
- if (data === lastStateRef.current) {
692
- return lastValueRef.current;
693
- }
694
- const value = getByPath(data, path);
695
- if (lastValueRef.current !== void 0 && isEqual(lastValueRef.current, value)) {
696
- lastStateRef.current = data;
697
- return lastValueRef.current;
698
- }
699
- lastStateRef.current = data;
700
- lastValueRef.current = value;
701
- return value;
702
- }, [store, path, isEqual]);
703
- return (0, import_react.useSyncExternalStore)(store.subscribe, getSnapshot);
704
- }
705
- function useWizardError(path) {
706
- const { store } = useWizardState();
707
- const lastStateRef = (0, import_react.useRef)(null);
708
- const lastValueRef = (0, import_react.useRef)(null);
709
- const getSnapshot = (0, import_react.useCallback)(() => {
710
- const fullState = store.getSnapshot();
711
- const errors = fullState.errors;
712
- if (errors === lastStateRef.current) {
713
- return lastValueRef.current;
714
- }
715
- let foundError;
716
- Object.values(errors).forEach((stepErrors) => {
717
- const typedStepErrors = stepErrors;
718
- if (typedStepErrors[path]) foundError = typedStepErrors[path];
719
- });
720
- lastStateRef.current = errors;
721
- lastValueRef.current = foundError;
722
- return foundError;
723
- }, [store, path]);
724
- return (0, import_react.useSyncExternalStore)(store.subscribe, getSnapshot);
725
- }
726
- function useWizardSelector(selector, options) {
727
- const { store } = useWizardState();
728
- const lastStateRef = (0, import_react.useRef)(null);
729
- const lastResultRef = (0, import_react.useRef)(null);
730
- const isEqual = options?.isEqual || Object.is;
731
- const getSnapshot = (0, import_react.useCallback)(() => {
732
- const fullState = store.getSnapshot();
733
- if (fullState === lastStateRef.current) {
734
- return lastResultRef.current;
735
- }
736
- const result = selector(fullState.data);
737
- if (lastResultRef.current !== null && isEqual(lastResultRef.current, result)) {
738
- lastStateRef.current = fullState;
739
- return lastResultRef.current;
740
- }
741
- lastStateRef.current = fullState;
742
- lastResultRef.current = result;
743
- return result;
744
- }, [store, selector, isEqual]);
745
- return (0, import_react.useSyncExternalStore)(store.subscribe, getSnapshot);
746
- }
747
- function useWizardActions() {
748
- const context = (0, import_react.useContext)(WizardActionsContext);
749
- if (!context) {
750
- throw new Error("useWizardActions must be used within a WizardProvider");
751
- }
752
- return context;
753
- }
754
- function useWizardContext() {
755
- const state = useWizardState();
756
- const actions = useWizardActions();
757
- const wizardData = useWizardSelector((s) => s);
758
- const allErrors = (0, import_react.useSyncExternalStore)(state.store.subscribe, () => state.store.getSnapshot().errors);
759
- return (0, import_react.useMemo)(
760
- () => ({
761
- ...state,
762
- ...actions,
763
- wizardData,
764
- allErrors
765
- }),
766
- [state, actions, wizardData, allErrors]
767
- );
768
- }
769
-
770
- // src/components/WizardStepRenderer.tsx
771
- var import_react2 = require("react");
772
- var import_jsx_runtime2 = require("react/jsx-runtime");
773
- var WizardStepRenderer = ({
774
- wrapper: Wrapper
775
- }) => {
776
- const { currentStep } = useWizardContext();
777
- const StepComponent = (0, import_react2.useMemo)(() => {
778
- if (!currentStep?.component) return null;
779
- return currentStep.component;
780
- }, [currentStep]);
781
- if (!currentStep || !StepComponent) {
782
- return null;
783
- }
784
- const content = /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(StepComponent, {});
785
- if (Wrapper) {
786
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Wrapper, { children: content }, currentStep.id);
787
- }
788
- return content;
789
- };
790
-
791
- // src/hooks/useWizard.ts
792
- var useWizard = () => {
793
- return useWizardContext();
794
- };
795
-
796
- // src/factory.tsx
797
- var import_jsx_runtime3 = require("react/jsx-runtime");
798
- function createWizardFactory() {
799
- const WizardProvider2 = ({
800
- config,
801
- initialData,
802
- children
803
- }) => {
804
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
805
- WizardProvider,
806
- {
807
- config,
808
- initialData,
809
- children
810
- }
811
- );
812
- };
813
- const useWizard2 = () => {
814
- return useWizard();
815
- };
816
- const useWizardContext2 = () => {
817
- return useWizardContext();
818
- };
819
- const useWizardValue2 = (path, options) => {
820
- return useWizardValue(path, options);
821
- };
822
- const useWizardSelector2 = (selector, options) => {
823
- return useWizardSelector(selector, options);
824
- };
825
- const useWizardError2 = (path) => {
826
- return useWizardError(path);
827
- };
828
- const useWizardActions2 = () => {
829
- return useWizardActions();
830
- };
831
- const useWizardState2 = () => {
832
- return useWizardState();
833
- };
834
- const createStep = (config) => config;
835
- return {
836
- WizardProvider: WizardProvider2,
837
- useWizard: useWizard2,
838
- useWizardContext: useWizardContext2,
839
- useWizardValue: useWizardValue2,
840
- useWizardSelector: useWizardSelector2,
841
- useWizardError: useWizardError2,
842
- useWizardActions: useWizardActions2,
843
- useWizardState: useWizardState2,
844
- createStep
845
- };
846
- }
847
-
848
- // src/adapters/persistence/LocalStorageAdapter.ts
849
- var LocalStorageAdapter = class {
850
- constructor(prefix = "wizard_") {
851
- __publicField(this, "prefix");
852
- this.prefix = prefix;
853
- }
854
- getKey(stepId) {
855
- return `${this.prefix}${stepId}`;
856
- }
857
- saveStep(stepId, data) {
858
- if (typeof window === "undefined") return;
859
- try {
860
- localStorage.setItem(this.getKey(stepId), JSON.stringify(data));
861
- } catch (error) {
862
- console.warn("LocalStorageAdapter: Failed to save step", error);
863
- }
864
- }
865
- getStep(stepId) {
866
- if (typeof window === "undefined") return void 0;
867
- try {
868
- const item = localStorage.getItem(this.getKey(stepId));
869
- return item ? JSON.parse(item) : void 0;
870
- } catch (error) {
871
- console.warn("LocalStorageAdapter: Failed to get step", error);
872
- return void 0;
873
- }
874
- }
875
- clear() {
876
- if (typeof window === "undefined") return;
877
- Object.keys(localStorage).forEach((key) => {
878
- if (key.startsWith(this.prefix)) {
879
- localStorage.removeItem(key);
880
- }
881
- });
882
- }
883
- };
884
-
885
- // src/adapters/validation/ZodAdapter.ts
886
- var ZodAdapter = class {
887
- constructor(schema) {
888
- __publicField(this, "schema");
889
- this.schema = schema;
890
- }
891
- async validate(data) {
892
- const result = await this.schema.safeParseAsync(data);
893
- if (result.success) {
894
- return { isValid: true };
895
- }
896
- const errors = {};
897
- if (result.error) {
898
- result.error.issues.forEach((err) => {
899
- const path = err.path.join(".");
900
- errors[path] = err.message;
901
- });
902
- }
903
- return { isValid: false, errors };
904
- }
905
- };
906
-
907
- // src/adapters/validation/YupAdapter.ts
908
- var YupAdapter = class {
909
- constructor(schema) {
910
- __publicField(this, "schema");
911
- this.schema = schema;
912
- }
913
- async validate(data) {
914
- try {
915
- await this.schema.validate(data, { abortEarly: false });
916
- return { isValid: true };
917
- } catch (err) {
918
- if (err && typeof err === "object" && "inner" in err) {
919
- const yupError = err;
920
- const errors = {};
921
- yupError.inner.forEach((error) => {
922
- if (error.path) {
923
- errors[error.path] = error.message;
924
- }
925
- });
926
- return { isValid: false, errors };
927
- }
928
- throw err;
929
- }
930
- }
931
- };
932
- // Annotate the CommonJS export names for ESM import in node:
933
- 0 && (module.exports = {
934
- LocalStorageAdapter,
935
- MemoryAdapter,
936
- WizardProvider,
937
- WizardStepRenderer,
938
- WizardStore,
939
- YupAdapter,
940
- ZodAdapter,
941
- createWizardFactory,
942
- getByPath,
943
- setByPath,
944
- shallowEqual,
945
- toPath,
946
- useWizard,
947
- useWizardActions,
948
- useWizardContext,
949
- useWizardError,
950
- useWizardSelector,
951
- useWizardState,
952
- useWizardValue
953
- });
954
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";var Y=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var Ne=(t,e,r)=>e in t?Y(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Fe=(t,e)=>{for(var r in e)Y(t,r,{get:e[r],enumerable:!0})},_e=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of je(e))!qe.call(t,s)&&s!==r&&Y(t,s,{get:()=>e[s],enumerable:!(o=Le(e,s))||o.enumerable});return t};var Ke=t=>_e(Y({},"__esModule",{value:!0}),t);var x=(t,e,r)=>Ne(t,typeof e!="symbol"?e+"":e,r);var Ue={};Fe(Ue,{LocalStorageAdapter:()=>de,MemoryAdapter:()=>D,WizardProvider:()=>se,WizardStepRenderer:()=>Ae,WizardStore:()=>U,YupAdapter:()=>ue,ZodAdapter:()=>pe,createWizardFactory:()=>Ve,getByPath:()=>O,setByPath:()=>re,shallowEqual:()=>Ye,toPath:()=>te,useWizard:()=>ce,useWizardActions:()=>J,useWizardContext:()=>M,useWizardError:()=>oe,useWizardSelector:()=>$,useWizardState:()=>E,useWizardValue:()=>ae});module.exports=Ke(Ue);var n=require("react");var D=class{constructor(){x(this,"storage",{})}saveStep(e,r){this.storage[e]=r}getStep(e){return this.storage[e]}clear(){this.storage={}}};var ee=new Map;function te(t){if(!t)return[];if(ee.has(t))return ee.get(t);let e;return t.includes("[")?e=t.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean):e=t.split(".").filter(Boolean),ee.set(t,e),e}function O(t,e,r){if(!e||t===void 0||t===null)return r??t;if(!e.includes(".")&&!e.includes("[")){let d=t[e];return d!==void 0?d:r}let o=te(e),s=t;for(let d=0;d<o.length;d++){if(s==null)return r;s=s[o[d]]}return s!==void 0?s:r}function re(t,e,r){if(!e)return r;if(!e.includes(".")&&!e.includes("[")){if(Array.isArray(t)){let f=[...t];return f[e]=r,f}return{...t,[e]:r}}let o=te(e);if(o.length===0)return r;let s=Array.isArray(t)?[...t]:{...t},d=s;for(let f=0;f<o.length-1;f++){let h=o[f],g=o[f+1],v=d[h],P;v&&typeof v=="object"?P=Array.isArray(v)?[...v]:{...v}:P=/^\d+$/.test(g)?[]:{},d[h]=P,d=P}let T=o[o.length-1];return d[T]=r,s}function Ye(t,e){if(Object.is(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;let r=Object.keys(t),o=Object.keys(e);if(r.length!==o.length)return!1;for(let s=0;s<r.length;s++){let d=r[s];if(!Object.prototype.hasOwnProperty.call(e,d)||!Object.is(t[d],e[d]))return!1}return!0}var ne=require("react/jsx-runtime"),Ee=(0,n.createContext)(void 0),Me=(0,n.createContext)(void 0),U=class{constructor(e){x(this,"state");x(this,"listeners",new Set);x(this,"errorsMap",new Map);x(this,"subscribe",e=>(this.listeners.add(e),()=>this.listeners.delete(e)));this.state={data:e,errors:{}}}getSnapshot(){return this.state}update(e){this.state={...this.state,data:e},this.notify()}syncErrors(){let e={};for(let[r,o]of this.errorsMap.entries())o.size>0&&(e[r]=Object.fromEntries(o));this.state={...this.state,errors:e},this.notify()}updateErrors(e){this.errorsMap.clear();for(let[r,o]of Object.entries(e)){let s=new Map;for(let[d,T]of Object.entries(o))s.set(d,T);s.size>0&&this.errorsMap.set(r,s)}this.state={...this.state,errors:e},this.notify()}setStepErrors(e,r){if(!r||Object.keys(r).length===0)return this.errorsMap.has(e)?(this.errorsMap.delete(e),this.syncErrors(),!0):!1;let o=new Map;for(let[s,d]of Object.entries(r))o.set(s,d);return this.errorsMap.set(e,o),this.syncErrors(),!0}deleteError(e,r){let o=this.errorsMap.get(e);return o&&o.has(r)?(o.delete(r),o.size===0&&this.errorsMap.delete(e),this.syncErrors(),!0):!1}notify(){this.listeners.forEach(e=>e())}};function se({config:t,initialData:e,initialStepId:r,children:o}){let[s,d]=(0,n.useState)(""),T=(0,n.useRef)(s);(0,n.useEffect)(()=>{T.current=s},[s]);let[f,h]=(0,n.useState)(new Set),[g,v]=(0,n.useState)(new Set),[P,B]=(0,n.useState)(new Set),[,Z]=(0,n.useState)({}),[le,G]=(0,n.useState)(!0),[Se,De]=(0,n.useTransition)(),S=(0,n.useRef)(new U(e||{})),H=(0,n.useMemo)(()=>t.persistence?.adapter||new D,[t.persistence?.adapter]),fe=t.persistence?.mode||"onStepChange",L=(0,n.useMemo)(()=>{let a=new Map;return t.steps.forEach(c=>a.set(c.id,c)),a},[t.steps]),j=(0,n.useRef)([]),z=(0,n.useSyncExternalStore)(S.current.subscribe,(0,n.useCallback)(()=>{let a=S.current.getSnapshot().data,c=t.steps.filter(p=>p.condition?p.condition(a):!0),i=j.current.map(p=>p.id).join("."),u=c.map(p=>p.id).join(".");return i===u&&j.current.length>0?j.current:(j.current=c,c)},[t.steps])),q=(0,n.useMemo)(()=>{let a=new Map;return z.forEach((c,i)=>a.set(c.id,i)),a},[z]);(0,n.useEffect)(()=>{if(!s&&z.length>0){if(r){let a=z.find(c=>c.id===r);d(a?a.id:z[0].id)}else d(z[0].id);G(!1)}},[z,s,r]);let I=(0,n.useRef)({config:t,stepsMap:L,activeSteps:z,activeStepsIndexMap:q,visitedSteps:f,completedSteps:g,persistenceMode:fe,persistenceAdapter:H,currentStepId:s});I.current={config:t,stepsMap:L,activeSteps:z,activeStepsIndexMap:q,visitedSteps:f,completedSteps:g,persistenceMode:fe,persistenceAdapter:H,currentStepId:s};let ge=(0,n.useMemo)(()=>L.get(s)||null,[L,s]),N=(0,n.useMemo)(()=>q.get(s)??-1,[q,s]),me=N===0,he=N===z.length-1,Q="__wizzard_meta__",Ie=(0,n.useCallback)(()=>{G(!0);let{persistenceAdapter:a,config:c}=I.current,i=a.getStep(Q);i&&(i.currentStepId&&d(i.currentStepId),i.visited&&h(new Set(i.visited)),i.completed&&v(new Set(i.completed)));let u={};if(c.steps.forEach(p=>{let l=a.getStep(p.id);l&&Object.assign(u,l)}),Object.keys(u).length>0){let l={...S.current.getSnapshot().data,...u};S.current.update(l)}G(!1)},[]);(0,n.useEffect)(()=>{Ie()},[Ie]);let W=(0,n.useCallback)((a,c,i)=>{let{stepsMap:u,persistenceAdapter:p,persistenceMode:l}=I.current,y=u.get(c),w=y?.persistenceAdapter,m=y?.persistenceMode;(a===(m||l)||a==="manual")&&(w||p).saveStep(c,i)},[]),X=(0,n.useRef)(null),b=(0,n.useCallback)(async(a,c)=>{let{stepsMap:i}=I.current,u=i.get(a);if(!u||!u.validationAdapter)return!0;let p=await u.validationAdapter.validate(c);return p.isValid?(S.current.setStepErrors(a,null)&&(Z(S.current.getSnapshot().errors),B(y=>{let w=new Set(y);return w.delete(a),w})),!0):(S.current.setStepErrors(a,p.errors||null),Z(S.current.getSnapshot().errors),B(l=>{let y=new Set(l);return y.add(a),y}),!1)},[]),ye=(0,n.useCallback)((a,c)=>{let{persistenceMode:i}=I.current,p={...S.current.getSnapshot().data,...c};S.current.update(p),(I.current.stepsMap.get(a)?.persistenceMode||i)==="onChange"&&W("onChange",a,p)},[W]),F=(0,n.useCallback)((a,c,i)=>{let{persistenceMode:u,stepsMap:p}=I.current,l=S.current.getSnapshot().data;if(O(l,a)===c)return;let w=re(l,a,c);S.current.update(w);let m=I.current.currentStepId,A=p.get(m);m&&S.current.deleteError(m,a)&&(S.current.errorsMap.has(m)||B(_=>{let K=new Set(_);return K.delete(m),K})),m&&S.current.getSnapshot().errors[m]&&De(()=>{Z(S.current.getSnapshot().errors)});let{config:V}=I.current;(A?.validationMode??V.validationMode??"onStepChange")==="onChange"&&(i?.debounceValidation?(X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{try{m&&b(m,w).catch(C=>{console.error("[Wizard] Debounced validation failed:",C)})}catch(C){console.error("[Wizard] Error starting validation:",C)}},i.debounceValidation)):m&&b(m,w)),(A?.persistenceMode??u)==="onChange"&&m&&W("onChange",m,w)},[W,b]),Te=(0,n.useCallback)((a,c)=>{let{config:i}=I.current,u=S.current.getSnapshot().data,p=c?.replace?a:{...u,...a};S.current.update(p),c?.persist&&i.steps.forEach(l=>{W("manual",l.id,p)})},[W]),ve=(0,n.useCallback)((a,c)=>O(S.current.getSnapshot().data,a,c),[]),xe=(0,n.useCallback)((a,c)=>{let{currentStepId:i}=I.current;i&&F(a,c)},[F]),ze=(0,n.useCallback)(async()=>{let{activeSteps:a}=I.current,c=S.current.getSnapshot().data,u=(await Promise.all(a.map(l=>b(l.id,c)))).every(Boolean),p=S.current.getSnapshot().errors;return{isValid:u,errors:p}},[b]),R=(0,n.useCallback)(async a=>{let{activeStepsIndexMap:c,currentStepId:i,config:u,persistenceMode:p,visitedSteps:l,completedSteps:y,persistenceAdapter:w,stepsMap:m}=I.current,A=c.get(a)??-1;if(A===-1)return!1;let V=S.current.getSnapshot().data,Ce=c.get(i)??-1,k=m.get(i);if(A>Ce){let _=k?.autoValidate??u.autoValidate??!1,K=k?.validationMode??u.validationMode??"onStepChange";if((_||K==="onStepChange")&&i&&!await b(i,V))return!1}k&&i&&(k.persistenceMode??p)==="onStepChange"&&W("onStepChange",i,V);let C=new Set(l);return i&&C.add(i),h(C),d(a),p!=="manual"&&w.saveStep(Q,{currentStepId:a,visited:Array.from(C),completed:Array.from(y)}),u.onStepChange&&u.onStepChange(i||null,a,V),window.scrollTo(0,0),!0},[W,b]),We=(0,n.useCallback)(async()=>{let{activeSteps:a,activeStepsIndexMap:c,currentStepId:i,completedSteps:u,persistenceMode:p}=I.current,l=c.get(i)??-1;if(l===-1||l===a.length-1)return;let y=a[l+1];if(y&&await R(y.id)){let m=new Set(u).add(i);v(m),p!=="manual"&&H.saveStep(Q,{currentStepId:y.id,visited:Array.from(new Set(f).add(i)),completed:Array.from(m)})}},[R]),we=(0,n.useCallback)(()=>{let{activeSteps:a,activeStepsIndexMap:c,currentStepId:i}=I.current,u=c.get(i)??-1;if(u<=0)return;let p=a[u-1];p&&R(p.id)},[R]),Pe=(0,n.useCallback)(()=>{I.current.persistenceAdapter.clear()},[]),be=(0,n.useCallback)(a=>{let{config:c,currentStepId:i}=I.current,u=S.current.getSnapshot().data;if(a===!0){c.steps.forEach(l=>{W("manual",l.id,u)});return}if(!a){i&&W("manual",i,u);return}(Array.isArray(a)?a:[a]).forEach(l=>{W("manual",l,u)})},[W]),Oe=(0,n.useMemo)(()=>({currentStep:ge,currentStepIndex:N,isFirstStep:me,isLastStep:he,isLoading:le,isPending:Se,activeSteps:z,visitedSteps:f,completedSteps:g,errorSteps:P,store:S.current}),[ge,N,me,he,le,Se,z,f,g,P]),Be=(0,n.useMemo)(()=>({goToNextStep:We,goToPrevStep:we,goToStep:R,setStepData:ye,handleStepChange:xe,validateStep:a=>b(a,S.current.getSnapshot().data),validateAll:ze,save:be,clearStorage:Pe,setData:F,updateData:Te,getData:ve}),[We,we,R,ye,xe,b,ze,be,Pe,F,Te,ve]);return(0,ne.jsx)(Ee.Provider,{value:Oe,children:(0,ne.jsx)(Me.Provider,{value:Be,children:o})})}function E(){let t=(0,n.useContext)(Ee);if(!t)throw new Error("useWizardState must be used within a WizardProvider");return t}function ae(t,e){let{store:r}=E(),o=(0,n.useRef)(null),s=(0,n.useRef)(null),d=e?.isEqual||Object.is,T=(0,n.useCallback)(()=>{let h=r.getSnapshot().data;if(h===o.current)return s.current;let g=O(h,t);return s.current!==void 0&&d(s.current,g)?(o.current=h,s.current):(o.current=h,s.current=g,g)},[r,t,d]);return(0,n.useSyncExternalStore)(r.subscribe,T)}function oe(t){let{store:e}=E(),r=(0,n.useRef)(null),o=(0,n.useRef)(null),s=(0,n.useCallback)(()=>{let T=e.getSnapshot().errors;if(T===r.current)return o.current;let f;return Object.values(T).forEach(h=>{let g=h;g[t]&&(f=g[t])}),r.current=T,o.current=f,f},[e,t]);return(0,n.useSyncExternalStore)(e.subscribe,s)}function $(t,e){let{store:r}=E(),o=(0,n.useRef)(null),s=(0,n.useRef)(null),d=e?.isEqual||Object.is,T=(0,n.useCallback)(()=>{let f=r.getSnapshot();if(f===o.current)return s.current;let h=t(f.data);return s.current!==null&&d(s.current,h)?(o.current=f,s.current):(o.current=f,s.current=h,h)},[r,t,d]);return(0,n.useSyncExternalStore)(r.subscribe,T)}function J(){let t=(0,n.useContext)(Me);if(!t)throw new Error("useWizardActions must be used within a WizardProvider");return t}function M(){let t=E(),e=J(),r=$(s=>s),o=(0,n.useSyncExternalStore)(t.store.subscribe,()=>t.store.getSnapshot().errors);return(0,n.useMemo)(()=>({...t,...e,wizardData:r,allErrors:o}),[t,e,r,o])}var Re=require("react");var ie=require("react/jsx-runtime"),Ae=({wrapper:t})=>{let{currentStep:e}=M(),r=(0,Re.useMemo)(()=>e?.component?e.component:null,[e]);if(!e||!r)return null;let o=(0,ie.jsx)(r,{});return t?(0,ie.jsx)(t,{children:o},e.id):o};var ce=()=>M();var ke=require("react/jsx-runtime");function Ve(){return{WizardProvider:({config:g,initialData:v,children:P})=>(0,ke.jsx)(se,{config:g,initialData:v,children:P}),useWizard:()=>ce(),useWizardContext:()=>M(),useWizardValue:(g,v)=>ae(g,v),useWizardSelector:(g,v)=>$(g,v),useWizardError:g=>oe(g),useWizardActions:()=>J(),useWizardState:()=>E(),createStep:g=>g}}var de=class{constructor(e="wizard_"){x(this,"prefix");this.prefix=e}getKey(e){return`${this.prefix}${e}`}saveStep(e,r){if(!(typeof window>"u"))try{localStorage.setItem(this.getKey(e),JSON.stringify(r))}catch(o){console.warn("LocalStorageAdapter: Failed to save step",o)}}getStep(e){if(!(typeof window>"u"))try{let r=localStorage.getItem(this.getKey(e));return r?JSON.parse(r):void 0}catch(r){console.warn("LocalStorageAdapter: Failed to get step",r);return}}clear(){typeof window>"u"||Object.keys(localStorage).forEach(e=>{e.startsWith(this.prefix)&&localStorage.removeItem(e)})}};var pe=class{constructor(e){x(this,"schema");this.schema=e}async validate(e){let r=await this.schema.safeParseAsync(e);if(r.success)return{isValid:!0};let o={};return r.error&&r.error.issues.forEach(s=>{let d=s.path.join(".");o[d]=s.message}),{isValid:!1,errors:o}}};var ue=class{constructor(e){x(this,"schema");this.schema=e}async validate(e){try{return await this.schema.validate(e,{abortEarly:!1}),{isValid:!0}}catch(r){if(r&&typeof r=="object"&&"inner"in r){let o=r,s={};return o.inner.forEach(d=>{d.path&&(s[d.path]=d.message)}),{isValid:!1,errors:s}}throw r}}};0&&(module.exports={LocalStorageAdapter,MemoryAdapter,WizardProvider,WizardStepRenderer,WizardStore,YupAdapter,ZodAdapter,createWizardFactory,getByPath,setByPath,shallowEqual,toPath,useWizard,useWizardActions,useWizardContext,useWizardError,useWizardSelector,useWizardState,useWizardValue});