wizzard-stepper-react 2.0.0 → 2.0.1
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 +1 -1
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var q=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Be=(a,e,t)=>e in a?q(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var Le=(a,e)=>{for(var t in e)q(a,t,{get:e[t],enumerable:!0})},Ne=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Oe(e))!Ve.call(a,s)&&s!==t&&q(a,s,{get:()=>e[s],enumerable:!(i=De(e,s))||i.enumerable});return a};var Fe=a=>Ne(q({},"__esModule",{value:!0}),a);var I=(a,e,t)=>Be(a,typeof e!="symbol"?e+"":e,t);var Ye={};Le(Ye,{LocalStorageAdapter:()=>pe,MemoryAdapter:()=>N,WizardDevTools:()=>Re,WizardProvider:()=>ie,WizardStepRenderer:()=>ze,YupAdapter:()=>ue,ZodAdapter:()=>le,createWizardFactory:()=>We,devToolsMiddleware:()=>Pe,getByPath:()=>C,loggerMiddleware:()=>Ae,setByPath:()=>V,shallowEqual:()=>je,toPath:()=>ne,useWizard:()=>ce,useWizardActions:()=>X,useWizardContext:()=>P,useWizardError:()=>de,useWizardSelector:()=>F,useWizardState:()=>J,useWizardValue:()=>oe});module.exports=Fe(Ye);var d=require("react");var ae=new Map;function ne(a){if(!a)return[];if(ae.has(a))return ae.get(a);let e;return a.includes("[")?e=a.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean):e=a.split(".").filter(Boolean),ae.set(a,e),e}function C(a,e,t){if(!e||a===void 0||a===null)return t??a;if(!e.includes(".")&&!e.includes("[")){let l=a[e];return l!==void 0?l:t}let i=ne(e),s=a;for(let l=0;l<i.length;l++){if(s==null)return t;s=s[i[l]]}return s!==void 0?s:t}function V(a,e,t){if(!e)return t;if(!e.includes(".")&&!e.includes("[")){if(Array.isArray(a)){let u=[...a];return u[e]=t,u}return{...a,[e]:t}}let i=ne(e);if(i.length===0)return t;let s=Array.isArray(a)?[...a]:{...a},l=s;for(let u=0;u<i.length-1;u++){let h=i[u],x=i[u+1],S=l[h],m;S&&typeof S=="object"?m=Array.isArray(S)?[...S]:{...S}:m=/^\d+$/.test(x)?[]:{},l[h]=m,l=m}let r=i[i.length-1];return l[r]=t,s}function je(a,e){if(Object.is(a,e))return!0;if(typeof a!="object"||a===null||typeof e!="object"||e===null)return!1;let t=Object.keys(a),i=Object.keys(e);if(t.length!==i.length)return!1;for(let s=0;s<t.length;s++){let l=t[s];if(!Object.prototype.hasOwnProperty.call(e,l)||!Object.is(a[l],e[l]))return!1}return!0}var K=class{constructor(e,t=[]){I(this,"initialData");I(this,"dirtyFields",new Set);I(this,"state");I(this,"listeners",new Set);I(this,"actionListeners",new Set);I(this,"errorsMap",new Map);I(this,"middlewareChain");I(this,"getSnapshot",()=>this.state);I(this,"subscribe",e=>(this.listeners.add(e),()=>this.listeners.delete(e)));this.initialData=JSON.parse(JSON.stringify(e)),this.state={data:e,errors:{},isDirty:!1,dirtyFields:this.dirtyFields,visitedSteps:new Set,completedSteps:new Set,errorSteps:new Set,currentStep:null,currentStepId:"",currentStepIndex:0,isFirstStep:!0,isLastStep:!1,isLoading:!0,isPending:!1,isBusy:!1,activeSteps:[],history:[],busySteps:new Set,progress:0,activeStepsCount:0,breadcrumbs:[],config:{}},this.middlewareChain=this.setupMiddlewares(t)}subscribeToActions(e){return this.actionListeners.add(e),()=>this.actionListeners.delete(e)}notifyActions(e){this.actionListeners.forEach(t=>t(e))}setupMiddlewares(e){let t={getState:()=>this.state.data,getSnapshot:()=>this.getSnapshot(),dispatch:s=>this.dispatch(s)};return e.map(s=>s(t)).reduceRight((s,l)=>l(s),this.internalDispatch.bind(this))}dispatch(e){this.middlewareChain(e)}internalDispatch(e){switch(this.notifyActions(e),e.type){case"INIT":this.initialData=JSON.parse(JSON.stringify(e.payload.data));let t=e.payload.config.steps.filter(i=>!i.condition);this.state={...this.state,data:e.payload.data,config:e.payload.config,activeSteps:t,activeStepsCount:t.length},this.notify();break;case"SET_CURRENT_STEP_ID":this.state={...this.state,currentStepId:e.payload.stepId},this.notify();break;case"SET_HISTORY":this.state={...this.state,history:e.payload.history},this.notify();break;case"SET_ACTIVE_STEPS":this.state={...this.state,activeSteps:e.payload.steps,activeStepsCount:e.payload.steps.length},this.notify();break;case"SET_DATA":this.updateDataByPath(e.payload.path,e.payload.value,e.payload.options);break;case"UPDATE_DATA":this.updateBulkData(e.payload.data,e.payload.options);break;case"GO_TO_STEP":break;case"VALIDATE_START":break;case"VALIDATE_END":break;case"SET_STEP_ERRORS":this.setStepErrors(e.payload.stepId,e.payload.errors);break;case"RESET":this.setInitialData(e.payload.data);break;case"SET_ERROR_STEPS":this.state={...this.state,errorSteps:e.payload.steps};break}this.syncDerivedState(),this.notify()}updateDataByPath(e,t,i){let s=V(this.state.data,e,t);s!==this.state.data&&this.update(s,e)}updateBulkData(e,t){let i;t?.replace?i=e:(i=JSON.parse(JSON.stringify(this.state.data)),Object.assign(i,e)),this.update(i,Object.keys(e))}update(e,t){t&&(Array.isArray(t)?t:[t]).forEach(s=>{let l=C(this.initialData,s),r=C(e,s);JSON.stringify(l)!==JSON.stringify(r)?this.dirtyFields.add(s):this.dirtyFields.delete(s)}),this.state={...this.state,data:e,isDirty:this.dirtyFields.size>0,dirtyFields:new Set(this.dirtyFields)},this.notify()}updateMeta(e){this.state={...this.state,...e},this.syncDerivedState(),this.notify()}syncDerivedState(){let{activeSteps:e,currentStepId:t,visitedSteps:i,completedSteps:s,errorSteps:l}=this.state,r=Math.max(0,e.findIndex(x=>x.id===t)),u=e[r]||null,h=e.map(x=>{let S="upcoming";return x.id===t?S="current":l.has(x.id)?S="error":s.has(x.id)?S="completed":i.has(x.id)&&(S="visited"),{id:x.id,label:x.label,status:S}});this.state={...this.state,currentStep:u,currentStepIndex:r,isFirstStep:r===0,isLastStep:e.length>0&&r===e.length-1,progress:e.length>0?Math.round((r+1)/e.length*100):0,breadcrumbs:h}}setInitialData(e){this.initialData=JSON.parse(JSON.stringify(e)),this.dirtyFields.clear(),this.state={...this.state,data:e,isDirty:!1,dirtyFields:new Set},this.notify()}syncErrors(){let e={};for(let[t,i]of this.errorsMap.entries())i.size>0&&(e[t]=Object.fromEntries(i));this.state={...this.state,errors:e},this.notify()}updateErrors(e){this.errorsMap.clear();for(let[t,i]of Object.entries(e)){let s=new Map;for(let[l,r]of Object.entries(i))s.set(l,r);s.size>0&&this.errorsMap.set(t,s)}this.state={...this.state,errors:e},this.notify()}setStepErrors(e,t){if(!t||Object.keys(t).length===0)return this.errorsMap.has(e)?(this.errorsMap.delete(e),this.syncErrors(),!0):!1;let i=new Map;for(let[s,l]of Object.entries(t))i.set(s,l);return this.errorsMap.set(e,i),this.syncErrors(),!0}deleteError(e,t){let i=this.errorsMap.get(e);return i&&i.has(t)?(i.delete(t),i.size===0&&this.errorsMap.delete(e),this.syncErrors(),!0):!1}notify(){this.listeners.forEach(e=>e())}};var N=class{constructor(){I(this,"storage",{})}saveStep(e,t){this.storage[e]=t}getStep(e){return this.storage[e]}clear(){this.storage={}}};var $=require("react/jsx-runtime"),be=(0,d.createContext)(void 0),Ee=(0,d.createContext)(void 0),j=(0,d.createContext)(void 0);function ie({config:a,initialData:e,initialStepId:t,children:i}){let[s,l]=(0,d.useState)(a),r=(0,d.useRef)(new K(e||{},a.middlewares)),u=(0,d.useRef)(!1),h=(0,d.useMemo)(()=>s.persistence?.adapter||new N,[s.persistence?.adapter]),x=s.persistence?.mode||"onStepChange",S="__wizzard_meta__",m=(0,d.useSyncExternalStore)(n=>r.current.subscribe(n),()=>r.current.getSnapshot()),{activeSteps:b,currentStepId:H,history:Se,visitedSteps:fe,completedSteps:ye,data:ge,errors:{}}=m,M=(0,d.useMemo)(()=>{let n=new Map;return s.steps.forEach(p=>n.set(p.id,p)),n},[s.steps]);(0,d.useEffect)(()=>{l(a)},[a]);let he=(0,d.useMemo)(()=>{let n=new Map;return b.forEach((p,o)=>n.set(p.id,o)),n},[b]),W=(0,d.useRef)({config:s,stepsMap:M,activeSteps:b,activeStepsIndexMap:he,visitedSteps:fe,completedSteps:ye,persistenceMode:x,persistenceAdapter:h,currentStepId:H,history:Se});(0,d.useEffect)(()=>{W.current={config:s,stepsMap:M,activeSteps:b,activeStepsIndexMap:he,visitedSteps:fe,completedSteps:ye,persistenceMode:x,persistenceAdapter:h,currentStepId:H,history:Se}});let D=(0,d.useCallback)((n,p)=>{s.analytics?.onEvent(n,p)},[s.analytics]),z=(0,d.useCallback)((n,p,o)=>{let{stepsMap:y,persistenceAdapter:f,persistenceMode:g}=W.current,E=y.get(p),v=E?.persistenceAdapter||f,T=E?.persistenceMode||g;(n===T||n==="manual")&&v.saveStep(p,o)},[]),_=(0,d.useCallback)(async n=>{r.current.updateMeta({isBusy:!0});try{return(await Promise.all(s.steps.map(async o=>{if(!o.condition)return{step:o,ok:!0};let y=new Set(r.current.getSnapshot().busySteps);y.add(o.id),r.current.updateMeta({busySteps:y,isBusy:!0});try{let f=o.condition(n||{},r.current.getSnapshot()),g=f instanceof Promise?await f:f;return{step:o,ok:g}}catch(f){return console.error(`[Wizard] Condition failed for ${o.id}:`,f),{step:o,ok:!1}}finally{let f=r.current.getSnapshot(),g=new Set(f.busySteps);g.delete(o.id),r.current.updateMeta({busySteps:g,isBusy:g.size>0})}}))).filter(o=>o.ok).map(o=>o.step)}finally{r.current.getSnapshot().busySteps.size===0&&r.current.updateMeta({isBusy:!1})}},[s.steps]),w=(0,d.useCallback)(async(n,p)=>{let o=M.get(n);if(!o||!o.validationAdapter)return!0;r.current.dispatch({type:"VALIDATE_START",payload:{stepId:n}});let y=new Set(r.current.getSnapshot().busySteps);y.add(n),r.current.updateMeta({busySteps:y,isBusy:!0});try{let f=await o.validationAdapter.validate(p);if(f.isValid){r.current.setStepErrors(n,null);let g=new Set(r.current.getSnapshot().errorSteps);return g.delete(n),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:g}}),!0}else{r.current.setStepErrors(n,f.errors||null),D("validation_error",{stepId:n,errors:f.errors,timestamp:Date.now()});let g=new Set(r.current.getSnapshot().errorSteps);return g.add(n),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:g}}),!1}}finally{let f=new Set(r.current.getSnapshot().busySteps);f.delete(n),r.current.updateMeta({busySteps:f,isBusy:f.size>0}),r.current.dispatch({type:"VALIDATE_END",payload:{stepId:n,result:{isValid:!0}}})}},[M,D]),O=(0,d.useCallback)(async(n,p)=>{let{currentStepId:o,config:y,persistenceMode:f,persistenceAdapter:g,stepsMap:E}=W.current,v=r.current.getSnapshot().data,T=y.steps,R=T.findIndex(A=>A.id===o),L=T.findIndex(A=>A.id===n);if(L>R&&o){let A=E.get(o);if((A?.autoValidate??y.autoValidate??!!A?.validationAdapter)&&!await w(o,v))return!1}r.current.updateMeta({isBusy:!0});try{if(!(p||await _(v)).find(se=>se.id===n))return!1;let U=E.get(o);if(U?.beforeLeave){let se=r.current.getSnapshot(),Me=L>R?"next":"prev";if(await U.beforeLeave(v,Me,se)===!1)return!1}o&&(U?.persistenceMode||f)==="onStepChange"&&z("onStepChange",o,v);let te=r.current.getSnapshot(),re=new Set(te.visitedSteps);o&&re.add(o),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:re}}),r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n}});let ve=[...te.history,n];return r.current.dispatch({type:"SET_HISTORY",payload:{history:ve}}),f!=="manual"&&g.saveStep(S,{currentStepId:n,visited:Array.from(re),completed:Array.from(te.completedSteps),history:ve}),y.onStepChange&&y.onStepChange(o||null,n,v),D("step_change",{from:o||null,to:n,timestamp:Date.now()}),window.scrollTo(0,0),!0}finally{r.current.updateMeta({isBusy:!1})}},[_,w,z,D]),Te=(0,d.useCallback)(async()=>{let{currentStepId:n}=W.current;if(!n)return;let p=r.current.getSnapshot().data,o=M.get(n);if((o?.autoValidate??s.autoValidate??!!o?.validationAdapter)&&!await w(n,p))return;let f=await _(p),g=f.findIndex(E=>E.id===n);if(g!==-1&&g<f.length-1){let E=f[g+1].id;if(await O(E,f)){let T=new Set(r.current.getSnapshot().completedSteps);T.add(n),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:T}})}}},[O,_,w,M]),me=(0,d.useCallback)(()=>{let{currentStepId:n,activeSteps:p,activeStepsIndexMap:o}=W.current,y=o.get(n)??-1;y>0&&O(p[y-1].id)},[O]),ee=(0,d.useCallback)((n,p,o)=>{let{persistenceMode:y,stepsMap:f,currentStepId:g}=W.current,E=r.current.getSnapshot().data;if(C(E,n)===p)return;let v=V(E,n,p);if(s.steps.forEach(T=>{if(T.dependsOn?.some(R=>n===R||n.startsWith(R+"."))){let R=new Set(r.current.getSnapshot().completedSteps);R.delete(T.id)&&r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:R}});let L=new Set(r.current.getSnapshot().visitedSteps);L.delete(T.id)&&r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:L}}),T.clearData&&(typeof T.clearData=="function"?v={...v,...T.clearData(v)}:(Array.isArray(T.clearData)?T.clearData:[T.clearData]).forEach(A=>{v=V(v,A,void 0)}))}}),r.current.dispatch({type:"SET_DATA",payload:{path:n,value:p,options:o}}),g){r.current.deleteError(g,n);let T=f.get(g);(T?.validationMode||s.validationMode||"onStepChange")==="onChange"&&w(g,v),(T?.persistenceMode||y)==="onChange"&&z("onChange",g,v)}},[s,w,z]),Ie=(0,d.useCallback)((n,p)=>{let o=r.current.getSnapshot().data,y=p?.replace?n:{...o,...n};r.current.update(y,Object.keys(n)),p?.persist&&s.steps.forEach(f=>z("manual",f.id,y))},[s.steps,z]),xe=(0,d.useCallback)(()=>{if(r.current.setInitialData(e||{}),r.current.update(e||{}),r.current.updateErrors({}),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:new Set}}),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:new Set}}),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:new Set}}),b.length>0){let n=b[0].id;r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n}}),r.current.dispatch({type:"SET_HISTORY",payload:{history:[n]}})}else r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:""}}),r.current.dispatch({type:"SET_HISTORY",payload:{history:[]}});h.clear(),D("wizard_reset",{data:e})},[e,b,h,D]),Ce=(0,d.useMemo)(()=>({...m,config:s}),[m,s]),_e=(0,d.useMemo)(()=>({goToNextStep:Te,goToPrevStep:me,goToStep:O,setStepData:(n,p)=>{let o={...r.current.getSnapshot().data,...p};r.current.update(o,Object.keys(p))},handleStepChange:(n,p)=>{W.current.currentStepId&&ee(n,p)},validateStep:n=>w(n,r.current.getSnapshot().data),validateAll:async()=>{r.current.updateMeta({isBusy:!0});let n=r.current.getSnapshot().data,p=await _(n),o=await Promise.all(p.map(y=>w(y.id,n)));return r.current.updateMeta({isBusy:!1}),{isValid:o.every(Boolean),errors:r.current.getSnapshot().errors}},save:n=>{let p=r.current.getSnapshot().data;n===!0?s.steps.forEach(o=>z("manual",o.id,p)):n?(Array.isArray(n)?n:[n]).forEach(o=>z("manual",o,p)):W.current.currentStepId&&z("manual",W.current.currentStepId,p)},clearStorage:()=>h.clear(),reset:xe,setData:ee,updateData:Ie,getData:(n,p)=>C(r.current.getSnapshot().data,n,p),updateConfig:n=>l(p=>({...p,...n}))}),[Te,me,O,w,xe,ee,Ie,h,s.steps,z]);return(0,d.useEffect)(()=>{u.current?r.current.updateMeta({config:s}):(r.current.dispatch({type:"INIT",payload:{data:e||{},config:s}}),u.current=!0)},[e,s]),(0,d.useEffect)(()=>{let n=!0;return(async()=>{let o=await _(ge);n&&r.current.dispatch({type:"SET_ACTIVE_STEPS",payload:{steps:o}})})(),()=>{n=!1}},[ge,_]),(0,d.useEffect)(()=>{let n=h.getStep(S);n&&(n.currentStepId&&r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n.currentStepId}}),n.visited&&r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:new Set(n.visited)}}),n.completed&&r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:new Set(n.completed)}}),n.history&&r.current.dispatch({type:"SET_HISTORY",payload:{history:n.history}}));let p=r.current.getSnapshot(),o=p.activeSteps;if(!H&&o.length>0){let y=t&&o.some(f=>f.id===t)?t:o[0].id;r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:y}}),p.history.length===0&&r.current.dispatch({type:"SET_HISTORY",payload:{history:[y]}}),r.current.updateMeta({isLoading:!1})}},[b,t,H,h]),(0,$.jsx)(j.Provider,{value:r.current,children:(0,$.jsx)(be.Provider,{value:Ce,children:(0,$.jsx)(Ee.Provider,{value:_e,children:i})})})}function J(){let a=(0,d.useContext)(be);if(!a)throw new Error("useWizardState must be used within a WizardProvider");return a}function oe(a,e){let t=(0,d.useContext)(j);if(!t)throw new Error("useWizardValue must be used within a WizardProvider");let i=(0,d.useRef)(null),s=(0,d.useRef)(null),l=(0,d.useCallback)(()=>{let r=t.getSnapshot().data;if(r===i.current)return s.current;let u=C(r,a);return s.current!==void 0&&(e?.isEqual||Object.is)(s.current,u)?(i.current=r,s.current):(i.current=r,s.current=u,u)},[t,a,e?.isEqual]);return(0,d.useSyncExternalStore)(t.subscribe,l)}function de(a){let e=(0,d.useContext)(j);if(!e)throw new Error("useWizardError must be used within a WizardProvider");let t=(0,d.useCallback)(()=>{let i=e.getSnapshot().errors;for(let[s,l]of Object.entries(i)){let r=l;if(r[a])return r[a];if(a.startsWith(s+".")&&r[s])return r[s];let u=a.split(".").pop();if(u&&r[u])return r[u]}},[e,a]);return(0,d.useSyncExternalStore)(e.subscribe,t)}function F(a,e){let t=(0,d.useContext)(j);if(!t)throw new Error("useWizardSelector must be used within a WizardProvider");let i=(0,d.useRef)(null),s=(0,d.useRef)(null),l=(0,d.useCallback)(()=>{let r=t.getSnapshot();if(r===i.current)return s.current;let u=a(r);return s.current!==null&&(e?.isEqual||Object.is)(s.current,u)?(i.current=r,s.current):(i.current=r,s.current=u,u)},[t,a,e?.isEqual]);return(0,d.useSyncExternalStore)(t.subscribe,l)}function X(){let a=(0,d.useContext)(Ee);if(!a)throw new Error("useWizardActions must be used within a WizardProvider");return a}function P(){let a=J(),e=X(),t=(0,d.useContext)(j),i=F(h=>h.data),s=F(h=>h.errors),{data:l,errors:r,...u}=a;return(0,d.useMemo)(()=>({...u,...e,wizardData:i,allErrors:s,data:i,errors:s,store:t}),[u,e,i,s,t])}var G=require("react");var Z=require("react/jsx-runtime"),ze=({wrapper:a,fallback:e=null})=>{let{currentStep:t}=P(),i=(0,G.useMemo)(()=>t?.component?t.component:null,[t]);if(!t||!i)return null;let s=(0,Z.jsx)(G.Suspense,{fallback:e,children:(0,Z.jsx)(i,{})});return a?(0,Z.jsx)(a,{children:s},t.id):s};var ce=()=>P();var we=require("react/jsx-runtime");function We(){return{WizardProvider:({config:S,initialData:m,children:b})=>(0,we.jsx)(ie,{config:S,initialData:m,children:b}),useWizard:()=>ce(),useWizardContext:()=>P(),useWizardValue:(S,m)=>oe(S,m),useWizardSelector:(S,m)=>F(S,m),useWizardError:S=>de(S),useWizardActions:()=>X(),useWizardState:()=>J(),useBreadcrumbs:()=>J().breadcrumbs,createStep:S=>S}}var pe=class{constructor(e="wizard_"){I(this,"prefix");this.prefix=e}getKey(e){return`${this.prefix}${e}`}saveStep(e,t){if(!(typeof window>"u"))try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch(i){console.warn("LocalStorageAdapter: Failed to save step",i)}}getStep(e){if(!(typeof window>"u"))try{let t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):void 0}catch(t){console.warn("LocalStorageAdapter: Failed to get step",t);return}}clear(){typeof window>"u"||Object.keys(localStorage).forEach(e=>{e.startsWith(this.prefix)&&localStorage.removeItem(e)})}};var le=class{constructor(e){I(this,"schema");this.schema=e}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return{isValid:!0};let i={};return t.error&&t.error.issues.forEach(s=>{let l=s.path.join(".");i[l]=s.message}),{isValid:!1,errors:i}}};var ue=class{constructor(e){I(this,"schema");this.schema=e}async validate(e){try{return await this.schema.validate(e,{abortEarly:!1}),{isValid:!0}}catch(t){if(t&&typeof t=="object"&&"inner"in t){let i=t,s={};return i.inner.forEach(l=>{l.path&&(s[l.path]=l.message)}),{isValid:!1,errors:s}}throw t}}};var Ae=a=>e=>t=>{console.group(`Wizard Action: ${t.type}`),console.log("Action payload:",t.payload),console.log("State before:",a.getSnapshot());let i=e(t);return console.log("State after:",a.getSnapshot()),console.groupEnd(),i};var Pe=a=>{if(typeof window>"u"||!window.__REDUX_DEVTOOLS_EXTENSION__)return t=>i=>t(i);let e=window.__REDUX_DEVTOOLS_EXTENSION__.connect({name:"Wizard Stepper React"});return e.init(a.getSnapshot()),t=>i=>{let s=t(i);return e.send(i,a.getSnapshot()),s}};var k=require("react");var c=require("react/jsx-runtime");function Re(){let[a,e]=(0,k.useState)(!1),[t,i]=(0,k.useState)("state"),{wizardData:s,allErrors:l,store:r,...u}=P(),[h,x]=(0,k.useState)([]);return(0,k.useEffect)(()=>r?r.subscribeToActions(m=>{x(b=>[{timestamp:Date.now(),action:m,state:r.getSnapshot()},...b].slice(0,50))}):void 0,[r]),a?(0,c.jsxs)("div",{style:{position:"fixed",bottom:"20px",right:"20px",width:"400px",height:"500px",backgroundColor:"rgba(15, 23, 42, 0.9)",backdropFilter:"blur(12px)",borderRadius:"16px",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"0 10px 40px rgba(0,0,0,0.5)",zIndex:9999,display:"flex",flexDirection:"column",color:"#e2e8f0",fontFamily:"Inter, sans-serif",overflow:"hidden"},children:[(0,c.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",display:"flex",justifyContent:"space-between",alignItems:"center",background:"rgba(255, 255, 255, 0.03)"},children:[(0,c.jsx)("span",{style:{fontWeight:600,fontSize:"14px"},children:"Wizard DevTools"}),(0,c.jsx)("button",{onClick:()=>e(!1),style:{background:"none",border:"none",color:"#94a3b8",cursor:"pointer",fontSize:"18px"},children:"\xD7"})]}),(0,c.jsx)("div",{style:{display:"flex",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",background:"rgba(255, 255, 255, 0.02)"},children:["state","actions","errors"].map(S=>(0,c.jsx)("button",{onClick:()=>i(S),style:{flex:1,padding:"10px",background:t===S?"rgba(37, 99, 235, 0.2)":"none",border:"none",color:t===S?"#60a5fa":"#94a3b8",borderBottom:t===S?"2px solid #3b82f6":"none",cursor:"pointer",fontSize:"12px",textTransform:"capitalize",fontWeight:t===S?600:400},children:S},S))}),(0,c.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"16px",fontSize:"12px"},children:[t==="state"&&(0,c.jsxs)("div",{children:[(0,c.jsxs)(Q,{title:"Navigation",children:[(0,c.jsx)(B,{label:"Current Step",value:u.currentStepId}),(0,c.jsx)(B,{label:"Index",value:u.currentStepIndex}),(0,c.jsx)(B,{label:"Progress",value:`${u.progress}%`}),(0,c.jsx)(B,{label:"Total Steps",value:u.activeStepsCount}),(0,c.jsx)(B,{label:"Is Loading",value:String(u.isLoading)}),(0,c.jsx)(B,{label:"Is Busy",value:String(u.isBusy)})]}),(0,c.jsx)(Q,{title:"History",children:(0,c.jsx)("div",{style:{color:"#94a3b8"},children:u.history.join(" \u2192 ")||"Empty"})}),(0,c.jsx)(Q,{title:"Data",children:(0,c.jsx)(Y,{data:s})}),(0,c.jsx)(Q,{title:"Meta",children:(0,c.jsx)(Y,{data:{visited:Array.from(u.visitedSteps),completed:Array.from(u.completedSteps),busy:Array.from(u.busySteps)}})})]}),t==="errors"&&(0,c.jsx)("div",{children:Object.keys(l).length===0?(0,c.jsx)("div",{style:{color:"#94a3b8",textAlign:"center",marginTop:"20px"},children:"No active errors"}):(0,c.jsx)(Y,{data:l})}),t==="actions"&&(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:h.length===0?(0,c.jsx)("div",{style:{color:"#94a3b8",textAlign:"center",marginTop:"20px"},children:"No actions recorded yet"}):h.map((S,m)=>(0,c.jsx)(Je,{log:S},S.timestamp+m))})]}),(0,c.jsxs)("div",{style:{padding:"8px 16px",fontSize:"10px",color:"#64748b",borderTop:"1px solid rgba(255, 255, 255, 0.1)",background:"rgba(255, 255, 255, 0.02)",display:"flex",justifyContent:"space-between"},children:[(0,c.jsxs)("span",{children:["v",globalThis.process?.env?.VERSION||"2.0.0"]}),(0,c.jsx)("span",{children:"Strict Mode: Active"})]})]}):(0,c.jsx)("button",{onClick:()=>e(!0),style:{position:"fixed",bottom:"20px",right:"20px",zIndex:9999,padding:"10px 15px",borderRadius:"50px",background:"rgba(37, 99, 235, 0.9)",color:"white",border:"none",boxShadow:"0 4px 15px rgba(0,0,0,0.2)",cursor:"pointer",fontWeight:"bold",fontSize:"12px",backdropFilter:"blur(5px)"},children:"Wizard DevTools"})}var Je=({log:a})=>{let[e,t]=(0,k.useState)(!1),i=new Date(a.timestamp).toLocaleTimeString();return(0,c.jsxs)("div",{style:{background:"rgba(255, 255, 255, 0.05)",borderRadius:"8px",overflow:"hidden",border:"1px solid rgba(255, 255, 255, 0.05)"},children:[(0,c.jsxs)("div",{onClick:()=>t(!e),style:{padding:"8px 12px",display:"flex",justifyContent:"space-between",cursor:"pointer",alignItems:"center"},children:[(0,c.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[(0,c.jsx)("span",{style:{color:"#64748b",fontSize:"10px"},children:i}),(0,c.jsx)("span",{style:{color:"#60a5fa",fontWeight:600},children:a.action.type})]}),(0,c.jsx)("span",{style:{color:"#475569",transform:e?"rotate(180deg)":"none",transition:"transform 0.2s"},children:"\u25BE"})]}),e&&(0,c.jsxs)("div",{style:{padding:"0 12px 12px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.05)"},children:[(0,c.jsxs)("div",{style:{marginTop:"8px"},children:[(0,c.jsx)("div",{style:{color:"#94a3b8",marginBottom:"4px",fontSize:"10px"},children:"Payload:"}),(0,c.jsx)(Y,{data:a.action.payload})]}),(0,c.jsxs)("div",{style:{marginTop:"8px"},children:[(0,c.jsx)("div",{style:{color:"#94a3b8",marginBottom:"4px",fontSize:"10px"},children:"State after:"}),(0,c.jsx)(Y,{data:a.state})]})]})]})},Q=({title:a,children:e})=>(0,c.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,c.jsx)("h4",{style:{margin:"0 0 8px 0",color:"#3b82f6",fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.05em"},children:a}),e]}),B=({label:a,value:e})=>(0,c.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"4px"},children:[(0,c.jsxs)("span",{style:{color:"#94a3b8"},children:[a,":"]}),(0,c.jsx)("span",{style:{color:"#f8fafc",fontWeight:500},children:e})]}),Y=({data:a})=>(0,c.jsx)("pre",{style:{background:"rgba(0, 0, 0, 0.3)",padding:"10px",borderRadius:"8px",overflowX:"auto",color:"#60a5fa",border:"1px solid rgba(255, 255, 255, 0.05)",margin:0},children:JSON.stringify(a,(t,i)=>i instanceof Set?Array.from(i):i,2)});0&&(module.exports={LocalStorageAdapter,MemoryAdapter,WizardDevTools,WizardProvider,WizardStepRenderer,YupAdapter,ZodAdapter,createWizardFactory,devToolsMiddleware,getByPath,loggerMiddleware,setByPath,shallowEqual,toPath,useWizard,useWizardActions,useWizardContext,useWizardError,useWizardSelector,useWizardState,useWizardValue});
|
|
1
|
+
"use strict";var Z=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var je=(s,e,t)=>e in s?Z(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Je=(s,e)=>{for(var t in e)Z(s,t,{get:e[t],enumerable:!0})},Ye=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ne(e))!Fe.call(s,a)&&a!==t&&Z(s,a,{get:()=>e[a],enumerable:!(i=Le(e,a))||i.enumerable});return s};var He=s=>Ye(Z({},"__esModule",{value:!0}),s);var v=(s,e,t)=>je(s,typeof e!="symbol"?e+"":e,t);var $e={};Je($e,{LocalStorageAdapter:()=>Se,MemoryAdapter:()=>j,WizardDevTools:()=>De,WizardProvider:()=>ce,WizardStepRenderer:()=>Ae,YupAdapter:()=>ye,ZodAdapter:()=>fe,createWizardFactory:()=>Ce,devToolsMiddleware:()=>ke,getByPath:()=>A,loggerMiddleware:()=>Re,setByPath:()=>O,shallowEqual:()=>Ue,toPath:()=>de,useWizard:()=>ue,useWizardActions:()=>ee,useWizardContext:()=>C,useWizardError:()=>le,useWizardSelector:()=>J,useWizardState:()=>H,useWizardValue:()=>pe});module.exports=He($e);var o=require("react");var oe=new Map;function de(s){if(!s)return[];if(oe.has(s))return oe.get(s);let e;return s.includes("[")?e=s.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean):e=s.split(".").filter(Boolean),oe.set(s,e),e}function A(s,e,t){if(!e||s===void 0||s===null)return t??s;if(!e.includes(".")&&!e.includes("[")){let p=s[e];return p!==void 0?p:t}let i=de(e),a=s;for(let p=0;p<i.length;p++){if(a==null)return t;a=a[i[p]]}return a!==void 0?a:t}function O(s,e,t){if(!e)return t;if(!e.includes(".")&&!e.includes("[")){if(Array.isArray(s)){let u=[...s];return u[e]=t,u}return{...s,[e]:t}}let i=de(e);if(i.length===0)return t;let a=Array.isArray(s)?[...s]:{...s},p=a;for(let u=0;u<i.length-1;u++){let m=i[u],b=i[u+1],f=p[m],I;f&&typeof f=="object"?I=Array.isArray(f)?[...f]:{...f}:I=/^\d+$/.test(b)?[]:{},p[m]=I,p=I}let r=i[i.length-1];return p[r]=t,a}function Ue(s,e){if(Object.is(s,e))return!0;if(typeof s!="object"||s===null||typeof e!="object"||e===null)return!1;let t=Object.keys(s),i=Object.keys(e);if(t.length!==i.length)return!1;for(let a=0;a<t.length;a++){let p=t[a];if(!Object.prototype.hasOwnProperty.call(e,p)||!Object.is(s[p],e[p]))return!1}return!0}var G=class{constructor(e,t=[]){v(this,"initialData");v(this,"dirtyFields",new Set);v(this,"state");v(this,"listeners",new Set);v(this,"actionListeners",new Set);v(this,"errorsMap",new Map);v(this,"middlewareChain");v(this,"getSnapshot",()=>this.state);v(this,"subscribe",e=>(this.listeners.add(e),()=>this.listeners.delete(e)));this.initialData=JSON.parse(JSON.stringify(e)),this.state={data:e,errors:{},isDirty:!1,dirtyFields:this.dirtyFields,visitedSteps:new Set,completedSteps:new Set,errorSteps:new Set,currentStep:null,currentStepId:"",currentStepIndex:0,isFirstStep:!0,isLastStep:!1,isLoading:!0,isPending:!1,isBusy:!1,activeSteps:[],history:[],busySteps:new Set,progress:0,activeStepsCount:0,breadcrumbs:[],config:{}},this.middlewareChain=this.setupMiddlewares(t)}subscribeToActions(e){return this.actionListeners.add(e),()=>this.actionListeners.delete(e)}notifyActions(e){this.actionListeners.forEach(t=>t(e))}setupMiddlewares(e){let t={getState:()=>this.state.data,getSnapshot:()=>this.getSnapshot(),dispatch:a=>this.dispatch(a)};return e.map(a=>a(t)).reduceRight((a,p)=>p(a),this.internalDispatch.bind(this))}dispatch(e){this.middlewareChain(e)}internalDispatch(e){switch(this.notifyActions(e),e.type){case"INIT":this.initialData=JSON.parse(JSON.stringify(e.payload.data));let t=e.payload.config.steps.filter(i=>!i.condition);this.state={...this.state,data:e.payload.data,config:e.payload.config,activeSteps:t,activeStepsCount:t.length},this.notify();break;case"SET_CURRENT_STEP_ID":this.state={...this.state,currentStepId:e.payload.stepId},this.notify();break;case"SET_HISTORY":this.state={...this.state,history:e.payload.history},this.notify();break;case"SET_ACTIVE_STEPS":this.state={...this.state,activeSteps:e.payload.steps,activeStepsCount:e.payload.steps.length},this.notify();break;case"SET_DATA":this.updateDataByPath(e.payload.path,e.payload.value,e.payload.options);break;case"UPDATE_DATA":this.updateBulkData(e.payload.data,e.payload.options);break;case"GO_TO_STEP":this.state={...this.state,currentStepId:e.payload.to};break;case"VALIDATE_START":this.state.busySteps.add(e.payload.stepId),this.state={...this.state,busySteps:new Set(this.state.busySteps)};break;case"VALIDATE_END":this.state.busySteps.delete(e.payload.stepId),this.state={...this.state,busySteps:new Set(this.state.busySteps)},e.payload.result.errors&&this.setStepErrors(e.payload.stepId,e.payload.result.errors);break;case"SET_STEP_ERRORS":this.setStepErrors(e.payload.stepId,e.payload.errors);break;case"RESET":this.setInitialData(e.payload.data);break;case"SET_ERROR_STEPS":this.state={...this.state,errorSteps:e.payload.steps};break;case"SET_VISITED_STEPS":this.state={...this.state,visitedSteps:e.payload.steps};break;case"SET_COMPLETED_STEPS":this.state={...this.state,completedSteps:e.payload.steps};break}this.syncDerivedState(),this.notify()}updateDataByPath(e,t,i){let a=O(this.state.data,e,t);a!==this.state.data&&this.update(a,e)}updateBulkData(e,t){let i;t?.replace?i=e:(i=JSON.parse(JSON.stringify(this.state.data)),Object.assign(i,e)),this.update(i,Object.keys(e))}update(e,t){t&&(Array.isArray(t)?t:[t]).forEach(a=>{let p=A(this.initialData,a),r=A(e,a);JSON.stringify(p)!==JSON.stringify(r)?this.dirtyFields.add(a):this.dirtyFields.delete(a)}),this.state={...this.state,data:e,isDirty:this.dirtyFields.size>0,dirtyFields:new Set(this.dirtyFields)},this.notify()}updateMeta(e){this.state={...this.state,...e},this.syncDerivedState(),this.notify()}syncDerivedState(){let{activeSteps:e,currentStepId:t,visitedSteps:i,completedSteps:a,errorSteps:p}=this.state,r=Math.max(0,e.findIndex(b=>b.id===t)),u=e[r]||null,m=e.map(b=>{let f="upcoming";return b.id===t?f="current":p.has(b.id)?f="error":a.has(b.id)?f="completed":i.has(b.id)&&(f="visited"),{id:b.id,label:b.label,status:f}});this.state={...this.state,currentStep:u,currentStepIndex:r,isFirstStep:r===0,isLastStep:e.length>0&&r===e.length-1,progress:e.length>0?Math.round((r+1)/e.length*100):0,breadcrumbs:m}}setInitialData(e){this.initialData=JSON.parse(JSON.stringify(e)),this.dirtyFields.clear(),this.state={...this.state,data:e,isDirty:!1,dirtyFields:new Set},this.notify()}syncErrors(){let e={};for(let[t,i]of this.errorsMap.entries())i.size>0&&(e[t]=Object.fromEntries(i));this.state={...this.state,errors:e},this.notify()}updateErrors(e){this.errorsMap.clear();for(let[t,i]of Object.entries(e)){let a=new Map;for(let[p,r]of Object.entries(i))a.set(p,r);a.size>0&&this.errorsMap.set(t,a)}this.state={...this.state,errors:e},this.notify()}setStepErrors(e,t){if(!t||Object.keys(t).length===0)return this.errorsMap.has(e)?(this.errorsMap.delete(e),this.syncErrors(),!0):!1;let i=new Map;for(let[a,p]of Object.entries(t))i.set(a,p);return this.errorsMap.set(e,i),this.syncErrors(),!0}deleteError(e,t){let i=this.errorsMap.get(e);return i&&i.has(t)?(i.delete(t),i.size===0&&this.errorsMap.delete(e),this.syncErrors(),!0):!1}notify(){this.listeners.forEach(e=>e())}};var j=class{constructor(){v(this,"storage",{})}saveStep(e,t){this.storage[e]=t}getStep(e){return this.storage[e]}clear(){this.storage={}}};var Q=require("react/jsx-runtime"),We=(0,o.createContext)(void 0),Pe=(0,o.createContext)(void 0),Y=(0,o.createContext)(void 0);function ce({config:s,initialData:e,initialStepId:t,children:i}){let[a,p]=(0,o.useState)(s),r=(0,o.useRef)(null);r.current||(r.current=new G(e||{},s.middlewares));let u=(0,o.useRef)(!1),m=(0,o.useMemo)(()=>a.persistence?.adapter||new j,[a.persistence?.adapter]),b=a.persistence?.mode||"onStepChange",f="__wizzard_meta__",I=(0,o.useSyncExternalStore)(n=>r.current.subscribe(n),()=>r.current.getSnapshot()),{activeSteps:E,currentStepId:q,history:he,visitedSteps:ge,completedSteps:Te,data:me,errors:{}}=I,D=(0,o.useMemo)(()=>{let n=new Map;return a.steps.forEach(l=>n.set(l.id,l)),n},[a.steps]);(0,o.useEffect)(()=>{p(s)},[s]);let Ie=(0,o.useMemo)(()=>{let n=new Map;return E.forEach((l,d)=>n.set(l.id,d)),n},[E]),W=(0,o.useRef)({config:a,stepsMap:D,activeSteps:E,activeStepsIndexMap:Ie,visitedSteps:ge,completedSteps:Te,persistenceMode:b,persistenceAdapter:m,currentStepId:q,history:he}),xe=(0,o.useRef)(new Map),N=(0,o.useRef)(null);(0,o.useEffect)(()=>{W.current={config:a,stepsMap:D,activeSteps:E,activeStepsIndexMap:Ie,visitedSteps:ge,completedSteps:Te,persistenceMode:b,persistenceAdapter:m,currentStepId:q,history:he}}),(0,o.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let M=(0,o.useCallback)((n,l)=>{a.analytics?.onEvent(n,l)},[a.analytics]),w=(0,o.useCallback)((n,l,d)=>{let{stepsMap:y,persistenceAdapter:S,persistenceMode:h}=W.current,g=y.get(l),x=g?.persistenceAdapter||S,T=g?.persistenceMode||h;(n===T||n==="manual")&&x.saveStep(l,d)},[]),_=(0,o.useCallback)(async n=>{r.current.updateMeta({isBusy:!0});try{return(await Promise.all(a.steps.map(async d=>{if(!d.condition)return{step:d,ok:!0};if(d.conditionDependsOn){let S=d.conditionDependsOn.map(g=>A(n,g)),h=xe.current.get(d.id);if(h&&h.depsValues.length===S.length&&h.depsValues.every((g,x)=>g===S[x]))return{step:d,ok:h.result};try{let g=d.condition(n||{},r.current.getSnapshot()),x=g instanceof Promise?await g:g;return xe.current.set(d.id,{result:x,depsValues:S}),{step:d,ok:x}}catch(g){return console.error(`[Wizard] Condition failed for ${d.id}:`,g),{step:d,ok:!1}}}let y=new Set(r.current.getSnapshot().busySteps);y.add(d.id),r.current.updateMeta({busySteps:y,isBusy:!0});try{let S=d.condition(n||{},r.current.getSnapshot()),h=S instanceof Promise?await S:S;return{step:d,ok:h}}catch(S){return console.error(`[Wizard] Condition failed for ${d.id}:`,S),{step:d,ok:!1}}finally{let S=r.current.getSnapshot(),h=new Set(S.busySteps);h.delete(d.id),r.current.updateMeta({busySteps:h,isBusy:h.size>0})}}))).filter(d=>d.ok).map(d=>d.step)}finally{r.current.getSnapshot().busySteps.size===0&&r.current.updateMeta({isBusy:!1})}},[a.steps]),P=(0,o.useCallback)(async(n,l)=>{let d=D.get(n);if(!d||!d.validationAdapter)return!0;r.current.dispatch({type:"VALIDATE_START",payload:{stepId:n}});let y=new Set(r.current.getSnapshot().busySteps);y.add(n),r.current.updateMeta({busySteps:y,isBusy:!0});try{let S=await d.validationAdapter.validate(l);if(S.isValid){r.current.setStepErrors(n,null);let h=new Set(r.current.getSnapshot().errorSteps);return h.delete(n),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:h}}),!0}else{r.current.setStepErrors(n,S.errors||null),M("validation_error",{stepId:n,errors:S.errors,timestamp:Date.now()});let h=new Set(r.current.getSnapshot().errorSteps);h.add(n),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:h}});let g=new Set(r.current.getSnapshot().completedSteps);return g.has(n)&&(g.delete(n),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:g}})),!1}}finally{let S=new Set(r.current.getSnapshot().busySteps);S.delete(n),r.current.updateMeta({busySteps:S,isBusy:S.size>0}),r.current.dispatch({type:"VALIDATE_END",payload:{stepId:n,result:{isValid:!0}}})}},[D,M]),V=(0,o.useCallback)(async(n,l,d={validate:!0})=>{let{currentStepId:y,config:S,persistenceMode:h,persistenceAdapter:g,stepsMap:x}=W.current,T=r.current.getSnapshot().data,z=S.steps,F=z.findIndex(R=>R.id===y),$=z.findIndex(R=>R.id===n);if($>F&&y&&d.validate){let R=x.get(y);if((R?.autoValidate??S.autoValidate??!!R?.validationAdapter)&&!await P(y,T))return!1}r.current.updateMeta({isBusy:!0});try{if(!(l||await _(T)).find(ie=>ie.id===n))return!1;let K=x.get(y);if(K?.beforeLeave){let ie=r.current.getSnapshot(),Be=$>F?"next":"prev";if(await K.beforeLeave(T,Be,ie)===!1)return!1}y&&(K?.persistenceMode||h)==="onStepChange"&&w("onStepChange",y,T);let ne=r.current.getSnapshot(),X=new Set(ne.visitedSteps);y&&X.add(y),X.add(n),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:X}}),r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n}});let we=[...ne.history,n];return r.current.dispatch({type:"SET_HISTORY",payload:{history:we}}),h!=="manual"&&g.saveStep(f,{currentStepId:n,visited:Array.from(X),completed:Array.from(ne.completedSteps),history:we}),S.onStepChange&&S.onStepChange(y||null,n,T),M("step_change",{from:y||null,to:n,timestamp:Date.now()}),window.scrollTo(0,0),!0}finally{r.current.updateMeta({isBusy:!1})}},[_,P,w,M]),ve=(0,o.useCallback)(async()=>{let{currentStepId:n}=W.current;if(!n)return;let l=r.current.getSnapshot().data,d=D.get(n);if((d?.autoValidate??a.autoValidate??!!d?.validationAdapter)&&!await P(n,l))return;let S=await _(l),h=S.findIndex(g=>g.id===n);if(h!==-1&&h<S.length-1){let g=S[h+1].id;if(await V(g,S,{validate:!1})){let T=r.current.getSnapshot();if(!T.errorSteps.has(n)){let z=new Set(T.completedSteps);z.add(n),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:z}})}}}},[V,_,P,D]),be=(0,o.useCallback)(()=>{let{currentStepId:n,activeSteps:l,activeStepsIndexMap:d}=W.current,y=d.get(n)??-1;y>0&&V(l[y-1].id)},[V]),ae=(0,o.useCallback)((n,l,d)=>{let{persistenceMode:y,stepsMap:S,currentStepId:h}=W.current,g=r.current.getSnapshot().data;if(A(g,n)===l)return;let x=O(g,n,l);if(a.steps.forEach(T=>{if(T.dependsOn?.some(z=>n===z||n.startsWith(z+"."))){let z=new Set(r.current.getSnapshot().completedSteps);z.delete(T.id)&&r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:z}});let F=new Set(r.current.getSnapshot().visitedSteps);F.delete(T.id)&&r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:F}}),T.clearData&&(typeof T.clearData=="function"?x={...x,...T.clearData(x)}:(Array.isArray(T.clearData)?T.clearData:[T.clearData]).forEach($=>{x=O(x,$,void 0)}))}}),r.current.dispatch({type:"SET_DATA",payload:{path:n,value:l,options:d}}),h){r.current.deleteError(h,n);let T=S.get(h);if((T?.validationMode||a.validationMode||"onStepChange")==="onChange"){let z=d?.debounceValidation??a.validationDebounceTime??300;N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{P(h,x)},z)}(T?.persistenceMode||y)==="onChange"&&w("onChange",h,x)}},[a,P,w]),Ee=(0,o.useCallback)((n,l)=>{let d=r.current.getSnapshot().data,y=l?.replace?n:{...d,...n};r.current.update(y,Object.keys(n)),l?.persist&&a.steps.forEach(S=>w("manual",S.id,y))},[a.steps,w]),ze=(0,o.useCallback)(()=>{if(r.current.setInitialData(e||{}),r.current.update(e||{}),r.current.updateErrors({}),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:new Set}}),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:new Set}}),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:new Set}}),E.length>0){let n=E[0].id;r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n}}),r.current.dispatch({type:"SET_HISTORY",payload:{history:[n]}})}else r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:""}}),r.current.dispatch({type:"SET_HISTORY",payload:{history:[]}});m.clear(),M("wizard_reset",{data:e})},[e,E,m,M]),Me=(0,o.useMemo)(()=>({...I,config:a}),[I,a]),Ve=(0,o.useMemo)(()=>({goToNextStep:ve,goToPrevStep:be,goToStep:V,setStepData:(n,l)=>{let d={...r.current.getSnapshot().data,...l};r.current.update(d,Object.keys(l))},handleStepChange:(n,l)=>{W.current.currentStepId&&ae(n,l)},validateStep:n=>P(n,r.current.getSnapshot().data),validateAll:async()=>{r.current.updateMeta({isBusy:!0});let n=r.current.getSnapshot().data,l=await _(n),d=await Promise.all(l.map(y=>P(y.id,n)));return r.current.updateMeta({isBusy:!1}),{isValid:d.every(Boolean),errors:r.current.getSnapshot().errors}},save:n=>{let l=r.current.getSnapshot().data;n===!0?a.steps.forEach(d=>w("manual",d.id,l)):n?(Array.isArray(n)?n:[n]).forEach(d=>w("manual",d,l)):W.current.currentStepId&&w("manual",W.current.currentStepId,l)},clearStorage:()=>m.clear(),reset:ze,setData:ae,updateData:Ee,getData:(n,l)=>A(r.current.getSnapshot().data,n,l),updateConfig:n=>p(l=>({...l,...n}))}),[ve,be,V,P,ze,ae,Ee,m,a.steps,w]);return(0,o.useEffect)(()=>{u.current?r.current.updateMeta({config:a}):(r.current.dispatch({type:"INIT",payload:{data:e||{},config:a}}),u.current=!0)},[e,a]),(0,o.useEffect)(()=>{let n=!0,l=setTimeout(async()=>{let d=await _(me);n&&r.current.dispatch({type:"SET_ACTIVE_STEPS",payload:{steps:d}})},200);return()=>{n=!1,clearTimeout(l)}},[me,_]),(0,o.useEffect)(()=>{let n=m.getStep(f);n&&(n.currentStepId&&r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n.currentStepId}}),n.visited&&r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:new Set(n.visited)}}),n.completed&&r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:new Set(n.completed)}}),n.history&&r.current.dispatch({type:"SET_HISTORY",payload:{history:n.history}}));let l=r.current.getSnapshot(),d=l.activeSteps;if(!q&&d.length>0){let y=t&&d.some(h=>h.id===t)?t:d[0].id;r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:y}}),l.history.length===0&&r.current.dispatch({type:"SET_HISTORY",payload:{history:[y]}});let S=new Set(r.current.getSnapshot().visitedSteps);S.has(y)||(S.add(y),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:S}})),r.current.updateMeta({isLoading:!1})}},[E,t,q,m]),(0,Q.jsx)(Y.Provider,{value:r.current,children:(0,Q.jsx)(We.Provider,{value:Me,children:(0,Q.jsx)(Pe.Provider,{value:Ve,children:i})})})}function H(){let s=(0,o.useContext)(We);if(!s)throw new Error("useWizardState must be used within a WizardProvider");return s}function pe(s,e){let t=(0,o.useContext)(Y);if(!t)throw new Error("useWizardValue must be used within a WizardProvider");let i=(0,o.useRef)(null),a=(0,o.useRef)(null),p=(0,o.useCallback)(()=>{let r=t.getSnapshot().data;if(r===i.current)return a.current;let u=A(r,s);return a.current!==void 0&&(e?.isEqual||Object.is)(a.current,u)?(i.current=r,a.current):(i.current=r,a.current=u,u)},[t,s,e?.isEqual]);return(0,o.useSyncExternalStore)(t.subscribe,p)}function le(s){let e=(0,o.useContext)(Y);if(!e)throw new Error("useWizardError must be used within a WizardProvider");let t=(0,o.useCallback)(()=>{let i=e.getSnapshot().errors;for(let[a,p]of Object.entries(i)){let r=p;if(r[s])return r[s];if(s.startsWith(a+".")&&r[a])return r[a];let u=s.split(".").pop();if(u&&r[u])return r[u]}},[e,s]);return(0,o.useSyncExternalStore)(e.subscribe,t)}function J(s,e){let t=(0,o.useContext)(Y);if(!t)throw new Error("useWizardSelector must be used within a WizardProvider");let i=(0,o.useRef)(null),a=(0,o.useRef)(null),p=(0,o.useCallback)(()=>{let r=t.getSnapshot();if(r===i.current)return a.current;let u=s(r);return a.current!==null&&(e?.isEqual||Object.is)(a.current,u)?(i.current=r,a.current):(i.current=r,a.current=u,u)},[t,s,e?.isEqual]);return(0,o.useSyncExternalStore)(t.subscribe,p)}function ee(){let s=(0,o.useContext)(Pe);if(!s)throw new Error("useWizardActions must be used within a WizardProvider");return s}function C(){let s=H(),e=ee(),t=(0,o.useContext)(Y),i=J(m=>m.data),a=J(m=>m.errors),{data:p,errors:r,...u}=s;return(0,o.useMemo)(()=>({...u,...e,wizardData:i,allErrors:a,data:i,errors:a,store:t}),[u,e,i,a,t])}var re=require("react");var te=require("react/jsx-runtime"),Ae=({wrapper:s,fallback:e=null})=>{let{currentStep:t}=C(),i=(0,re.useMemo)(()=>t?.component?t.component:null,[t]);if(!t||!i)return null;let a=(0,te.jsx)(re.Suspense,{fallback:e,children:(0,te.jsx)(i,{})});return s?(0,te.jsx)(s,{children:a},t.id):a};var ue=()=>C();var _e=require("react/jsx-runtime");function Ce(){return{WizardProvider:({config:f,initialData:I,children:E})=>(0,_e.jsx)(ce,{config:f,initialData:I,children:E}),useWizard:()=>ue(),useWizardContext:()=>C(),useWizardValue:(f,I)=>pe(f,I),useWizardSelector:(f,I)=>J(f,I),useWizardError:f=>le(f),useWizardActions:()=>ee(),useWizardState:()=>H(),useBreadcrumbs:()=>H().breadcrumbs,createStep:f=>f}}var Se=class{constructor(e="wizard_"){v(this,"prefix");this.prefix=e}getKey(e){return`${this.prefix}${e}`}saveStep(e,t){if(!(typeof window>"u"))try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch(i){console.warn("LocalStorageAdapter: Failed to save step",i)}}getStep(e){if(!(typeof window>"u"))try{let t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):void 0}catch(t){console.warn("LocalStorageAdapter: Failed to get step",t);return}}clear(){typeof window>"u"||Object.keys(localStorage).forEach(e=>{e.startsWith(this.prefix)&&localStorage.removeItem(e)})}};var fe=class{constructor(e){v(this,"schema");this.schema=e}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return{isValid:!0};let i={};return t.error&&t.error.issues.forEach(a=>{let p=a.path.join(".");i[p]=a.message}),{isValid:!1,errors:i}}};var ye=class{constructor(e){v(this,"schema");this.schema=e}async validate(e){try{return await this.schema.validate(e,{abortEarly:!1}),{isValid:!0}}catch(t){if(t&&typeof t=="object"&&"inner"in t){let i=t,a={};return i.inner.forEach(p=>{p.path&&(a[p.path]=p.message)}),{isValid:!1,errors:a}}throw t}}};var Re=s=>e=>t=>{console.group(`Wizard Action: ${t.type}`),console.log("Action payload:",t.payload),console.log("State before:",s.getSnapshot());let i=e(t);return console.log("State after:",s.getSnapshot()),console.groupEnd(),i};var B=s=>{if(s instanceof Set)return Array.from(s);if(s instanceof Map)return Object.fromEntries(s);if(typeof s=="function")return"[Function]";if(Array.isArray(s))return s.map(B);if(typeof s=="object"&&s!==null){if("steps"in s&&Array.isArray(s.steps)&&"persistence"in s)return{...s,steps:s.steps.map(t=>({id:t.id,label:t.label,condition:t.condition?"[Function]":void 0,component:t.component?"[Component]":void 0,...t}))};let e={};for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=B(s[t]));return e}return s},ke=s=>{if(typeof window>"u"||!window.__REDUX_DEVTOOLS_EXTENSION__)return t=>i=>t(i);let e=window.__REDUX_DEVTOOLS_EXTENSION__.connect({name:"Wizard Stepper React",features:{pause:!0,lock:!0,persist:!0,export:!0,import:"custom",jump:!0,skip:!0,reorder:!0,dispatch:!0,test:!0}});return e.init(B(s.getSnapshot())),t=>i=>{let a=t(i),p=s.getSnapshot(),r=B(p),u=B(i);return e.send(u,r),a}};var k=require("react");var c=require("react/jsx-runtime");function De(){let[s,e]=(0,k.useState)(!1),[t,i]=(0,k.useState)("state"),{wizardData:a,allErrors:p,store:r,...u}=C(),[m,b]=(0,k.useState)([]);return(0,k.useEffect)(()=>r?r.subscribeToActions(I=>{b(E=>[{timestamp:Date.now(),action:I,state:r.getSnapshot()},...E].slice(0,50))}):void 0,[r]),s?(0,c.jsxs)("div",{style:{position:"fixed",bottom:"20px",right:"20px",width:"400px",height:"500px",backgroundColor:"rgba(15, 23, 42, 0.9)",backdropFilter:"blur(12px)",borderRadius:"16px",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"0 10px 40px rgba(0,0,0,0.5)",zIndex:9999,display:"flex",flexDirection:"column",color:"#e2e8f0",fontFamily:"Inter, sans-serif",overflow:"hidden"},children:[(0,c.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",display:"flex",justifyContent:"space-between",alignItems:"center",background:"rgba(255, 255, 255, 0.03)"},children:[(0,c.jsx)("span",{style:{fontWeight:600,fontSize:"14px"},children:"Wizard DevTools"}),(0,c.jsx)("button",{onClick:()=>e(!1),style:{background:"none",border:"none",color:"#94a3b8",cursor:"pointer",fontSize:"18px"},children:"\xD7"})]}),(0,c.jsx)("div",{style:{display:"flex",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",background:"rgba(255, 255, 255, 0.02)"},children:["state","actions","errors"].map(f=>(0,c.jsx)("button",{onClick:()=>i(f),style:{flex:1,padding:"10px",background:t===f?"rgba(37, 99, 235, 0.2)":"none",border:"none",color:t===f?"#60a5fa":"#94a3b8",borderBottom:t===f?"2px solid #3b82f6":"none",cursor:"pointer",fontSize:"12px",textTransform:"capitalize",fontWeight:t===f?600:400},children:f},f))}),(0,c.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"16px",fontSize:"12px"},children:[t==="state"&&(0,c.jsxs)("div",{children:[(0,c.jsxs)(se,{title:"Navigation",children:[(0,c.jsx)(L,{label:"Current Step",value:u.currentStepId}),(0,c.jsx)(L,{label:"Index",value:u.currentStepIndex}),(0,c.jsx)(L,{label:"Progress",value:`${u.progress}%`}),(0,c.jsx)(L,{label:"Total Steps",value:u.activeStepsCount}),(0,c.jsx)(L,{label:"Is Loading",value:String(u.isLoading)}),(0,c.jsx)(L,{label:"Is Busy",value:String(u.isBusy)})]}),(0,c.jsx)(se,{title:"History",children:(0,c.jsx)("div",{style:{color:"#94a3b8"},children:u.history.join(" \u2192 ")||"Empty"})}),(0,c.jsx)(se,{title:"Data",children:(0,c.jsx)(U,{data:a})}),(0,c.jsx)(se,{title:"Meta",children:(0,c.jsx)(U,{data:{visited:Array.from(u.visitedSteps),completed:Array.from(u.completedSteps),busy:Array.from(u.busySteps)}})})]}),t==="errors"&&(0,c.jsx)("div",{children:Object.keys(p).length===0?(0,c.jsx)("div",{style:{color:"#94a3b8",textAlign:"center",marginTop:"20px"},children:"No active errors"}):(0,c.jsx)(U,{data:p})}),t==="actions"&&(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:m.length===0?(0,c.jsx)("div",{style:{color:"#94a3b8",textAlign:"center",marginTop:"20px"},children:"No actions recorded yet"}):m.map((f,I)=>(0,c.jsx)(qe,{log:f},f.timestamp+I))})]}),(0,c.jsxs)("div",{style:{padding:"8px 16px",fontSize:"10px",color:"#64748b",borderTop:"1px solid rgba(255, 255, 255, 0.1)",background:"rgba(255, 255, 255, 0.02)",display:"flex",justifyContent:"space-between"},children:[(0,c.jsxs)("span",{children:["v",globalThis.process?.env?.VERSION||"2.0.0"]}),(0,c.jsx)("span",{children:"Strict Mode: Active"})]})]}):(0,c.jsx)("button",{onClick:()=>e(!0),style:{position:"fixed",bottom:"20px",right:"20px",zIndex:9999,padding:"10px 15px",borderRadius:"50px",background:"rgba(37, 99, 235, 0.9)",color:"white",border:"none",boxShadow:"0 4px 15px rgba(0,0,0,0.2)",cursor:"pointer",fontWeight:"bold",fontSize:"12px",backdropFilter:"blur(5px)"},children:"Wizard DevTools"})}var qe=({log:s})=>{let[e,t]=(0,k.useState)(!1),i=new Date(s.timestamp).toLocaleTimeString();return(0,c.jsxs)("div",{style:{background:"rgba(255, 255, 255, 0.05)",borderRadius:"8px",overflow:"hidden",border:"1px solid rgba(255, 255, 255, 0.05)"},children:[(0,c.jsxs)("div",{onClick:()=>t(!e),style:{padding:"8px 12px",display:"flex",justifyContent:"space-between",cursor:"pointer",alignItems:"center"},children:[(0,c.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[(0,c.jsx)("span",{style:{color:"#64748b",fontSize:"10px"},children:i}),(0,c.jsx)("span",{style:{color:"#60a5fa",fontWeight:600},children:s.action.type})]}),(0,c.jsx)("span",{style:{color:"#475569",transform:e?"rotate(180deg)":"none",transition:"transform 0.2s"},children:"\u25BE"})]}),e&&(0,c.jsxs)("div",{style:{padding:"0 12px 12px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.05)"},children:[(0,c.jsxs)("div",{style:{marginTop:"8px"},children:[(0,c.jsx)("div",{style:{color:"#94a3b8",marginBottom:"4px",fontSize:"10px"},children:"Payload:"}),(0,c.jsx)(U,{data:s.action.payload})]}),(0,c.jsxs)("div",{style:{marginTop:"8px"},children:[(0,c.jsx)("div",{style:{color:"#94a3b8",marginBottom:"4px",fontSize:"10px"},children:"State after:"}),(0,c.jsx)(U,{data:s.state})]})]})]})},se=({title:s,children:e})=>(0,c.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,c.jsx)("h4",{style:{margin:"0 0 8px 0",color:"#3b82f6",fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.05em"},children:s}),e]}),L=({label:s,value:e})=>(0,c.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"4px"},children:[(0,c.jsxs)("span",{style:{color:"#94a3b8"},children:[s,":"]}),(0,c.jsx)("span",{style:{color:"#f8fafc",fontWeight:500},children:e})]}),U=({data:s})=>(0,c.jsx)("pre",{style:{background:"rgba(0, 0, 0, 0.3)",padding:"10px",borderRadius:"8px",overflowX:"auto",color:"#60a5fa",border:"1px solid rgba(255, 255, 255, 0.05)",margin:0},children:JSON.stringify(s,(t,i)=>i instanceof Set?Array.from(i):i,2)});0&&(module.exports={LocalStorageAdapter,MemoryAdapter,WizardDevTools,WizardProvider,WizardStepRenderer,YupAdapter,ZodAdapter,createWizardFactory,devToolsMiddleware,getByPath,loggerMiddleware,setByPath,shallowEqual,toPath,useWizard,useWizardActions,useWizardContext,useWizardError,useWizardSelector,useWizardState,useWizardValue});
|
package/dist/index.d.cts
CHANGED
|
@@ -126,6 +126,11 @@ interface IStepConfig<TStepData = unknown, StepId extends string = string> {
|
|
|
126
126
|
* Default: false (step is hidden until condition is resolved)
|
|
127
127
|
*/
|
|
128
128
|
showWhilePending?: boolean;
|
|
129
|
+
/**
|
|
130
|
+
* Optimization: Array of paths that this step's condition depends on.
|
|
131
|
+
* If provided, the condition will only be re-evaluated when these paths change.
|
|
132
|
+
*/
|
|
133
|
+
conditionDependsOn?: string[];
|
|
129
134
|
/**
|
|
130
135
|
* Guard function called before leaving the step.
|
|
131
136
|
* Return false or throw to prevent navigation.
|
|
@@ -194,6 +199,10 @@ interface IWizardConfig<T = unknown, StepId extends string = string> {
|
|
|
194
199
|
* Default validation mode for all steps (default: 'onChange')
|
|
195
200
|
*/
|
|
196
201
|
validationMode?: ValidationMode;
|
|
202
|
+
/**
|
|
203
|
+
* Debounce time in ms for validation when mode is 'onChange' (default: 300)
|
|
204
|
+
*/
|
|
205
|
+
validationDebounceTime?: number;
|
|
197
206
|
/**
|
|
198
207
|
* Persistence configuration
|
|
199
208
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -126,6 +126,11 @@ interface IStepConfig<TStepData = unknown, StepId extends string = string> {
|
|
|
126
126
|
* Default: false (step is hidden until condition is resolved)
|
|
127
127
|
*/
|
|
128
128
|
showWhilePending?: boolean;
|
|
129
|
+
/**
|
|
130
|
+
* Optimization: Array of paths that this step's condition depends on.
|
|
131
|
+
* If provided, the condition will only be re-evaluated when these paths change.
|
|
132
|
+
*/
|
|
133
|
+
conditionDependsOn?: string[];
|
|
129
134
|
/**
|
|
130
135
|
* Guard function called before leaving the step.
|
|
131
136
|
* Return false or throw to prevent navigation.
|
|
@@ -194,6 +199,10 @@ interface IWizardConfig<T = unknown, StepId extends string = string> {
|
|
|
194
199
|
* Default validation mode for all steps (default: 'onChange')
|
|
195
200
|
*/
|
|
196
201
|
validationMode?: ValidationMode;
|
|
202
|
+
/**
|
|
203
|
+
* Debounce time in ms for validation when mode is 'onChange' (default: 300)
|
|
204
|
+
*/
|
|
205
|
+
validationDebounceTime?: number;
|
|
197
206
|
/**
|
|
198
207
|
* Persistence configuration
|
|
199
208
|
*/
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Me=Object.defineProperty;var De=(n,e,t)=>e in n?Me(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var m=(n,e,t)=>De(n,typeof e!="symbol"?e+"":e,t);import{createContext as oe,useContext as L,useEffect as J,useMemo as B,useState as Oe,useCallback as z,useSyncExternalStore as Z,useRef as M}from"react";var ne=new Map;function Ie(n){if(!n)return[];if(ne.has(n))return ne.get(n);let e;return n.includes("[")?e=n.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean):e=n.split(".").filter(Boolean),ne.set(n,e),e}function k(n,e,t){if(!e||n===void 0||n===null)return t??n;if(!e.includes(".")&&!e.includes("[")){let c=n[e];return c!==void 0?c:t}let i=Ie(e),s=n;for(let c=0;c<i.length;c++){if(s==null)return t;s=s[i[c]]}return s!==void 0?s:t}function j(n,e,t){if(!e)return t;if(!e.includes(".")&&!e.includes("[")){if(Array.isArray(n)){let p=[...n];return p[e]=t,p}return{...n,[e]:t}}let i=Ie(e);if(i.length===0)return t;let s=Array.isArray(n)?[...n]:{...n},c=s;for(let p=0;p<i.length-1;p++){let g=i[p],I=i[p+1],l=c[g],T;l&&typeof l=="object"?T=Array.isArray(l)?[...l]:{...l}:T=/^\d+$/.test(I)?[]:{},c[g]=T,c=T}let r=i[i.length-1];return c[r]=t,s}function $e(n,e){if(Object.is(n,e))return!0;if(typeof n!="object"||n===null||typeof e!="object"||e===null)return!1;let t=Object.keys(n),i=Object.keys(e);if(t.length!==i.length)return!1;for(let s=0;s<t.length;s++){let c=t[s];if(!Object.prototype.hasOwnProperty.call(e,c)||!Object.is(n[c],e[c]))return!1}return!0}var K=class{constructor(e,t=[]){m(this,"initialData");m(this,"dirtyFields",new Set);m(this,"state");m(this,"listeners",new Set);m(this,"actionListeners",new Set);m(this,"errorsMap",new Map);m(this,"middlewareChain");m(this,"getSnapshot",()=>this.state);m(this,"subscribe",e=>(this.listeners.add(e),()=>this.listeners.delete(e)));this.initialData=JSON.parse(JSON.stringify(e)),this.state={data:e,errors:{},isDirty:!1,dirtyFields:this.dirtyFields,visitedSteps:new Set,completedSteps:new Set,errorSteps:new Set,currentStep:null,currentStepId:"",currentStepIndex:0,isFirstStep:!0,isLastStep:!1,isLoading:!0,isPending:!1,isBusy:!1,activeSteps:[],history:[],busySteps:new Set,progress:0,activeStepsCount:0,breadcrumbs:[],config:{}},this.middlewareChain=this.setupMiddlewares(t)}subscribeToActions(e){return this.actionListeners.add(e),()=>this.actionListeners.delete(e)}notifyActions(e){this.actionListeners.forEach(t=>t(e))}setupMiddlewares(e){let t={getState:()=>this.state.data,getSnapshot:()=>this.getSnapshot(),dispatch:s=>this.dispatch(s)};return e.map(s=>s(t)).reduceRight((s,c)=>c(s),this.internalDispatch.bind(this))}dispatch(e){this.middlewareChain(e)}internalDispatch(e){switch(this.notifyActions(e),e.type){case"INIT":this.initialData=JSON.parse(JSON.stringify(e.payload.data));let t=e.payload.config.steps.filter(i=>!i.condition);this.state={...this.state,data:e.payload.data,config:e.payload.config,activeSteps:t,activeStepsCount:t.length},this.notify();break;case"SET_CURRENT_STEP_ID":this.state={...this.state,currentStepId:e.payload.stepId},this.notify();break;case"SET_HISTORY":this.state={...this.state,history:e.payload.history},this.notify();break;case"SET_ACTIVE_STEPS":this.state={...this.state,activeSteps:e.payload.steps,activeStepsCount:e.payload.steps.length},this.notify();break;case"SET_DATA":this.updateDataByPath(e.payload.path,e.payload.value,e.payload.options);break;case"UPDATE_DATA":this.updateBulkData(e.payload.data,e.payload.options);break;case"GO_TO_STEP":break;case"VALIDATE_START":break;case"VALIDATE_END":break;case"SET_STEP_ERRORS":this.setStepErrors(e.payload.stepId,e.payload.errors);break;case"RESET":this.setInitialData(e.payload.data);break;case"SET_ERROR_STEPS":this.state={...this.state,errorSteps:e.payload.steps};break}this.syncDerivedState(),this.notify()}updateDataByPath(e,t,i){let s=j(this.state.data,e,t);s!==this.state.data&&this.update(s,e)}updateBulkData(e,t){let i;t?.replace?i=e:(i=JSON.parse(JSON.stringify(this.state.data)),Object.assign(i,e)),this.update(i,Object.keys(e))}update(e,t){t&&(Array.isArray(t)?t:[t]).forEach(s=>{let c=k(this.initialData,s),r=k(e,s);JSON.stringify(c)!==JSON.stringify(r)?this.dirtyFields.add(s):this.dirtyFields.delete(s)}),this.state={...this.state,data:e,isDirty:this.dirtyFields.size>0,dirtyFields:new Set(this.dirtyFields)},this.notify()}updateMeta(e){this.state={...this.state,...e},this.syncDerivedState(),this.notify()}syncDerivedState(){let{activeSteps:e,currentStepId:t,visitedSteps:i,completedSteps:s,errorSteps:c}=this.state,r=Math.max(0,e.findIndex(I=>I.id===t)),p=e[r]||null,g=e.map(I=>{let l="upcoming";return I.id===t?l="current":c.has(I.id)?l="error":s.has(I.id)?l="completed":i.has(I.id)&&(l="visited"),{id:I.id,label:I.label,status:l}});this.state={...this.state,currentStep:p,currentStepIndex:r,isFirstStep:r===0,isLastStep:e.length>0&&r===e.length-1,progress:e.length>0?Math.round((r+1)/e.length*100):0,breadcrumbs:g}}setInitialData(e){this.initialData=JSON.parse(JSON.stringify(e)),this.dirtyFields.clear(),this.state={...this.state,data:e,isDirty:!1,dirtyFields:new Set},this.notify()}syncErrors(){let e={};for(let[t,i]of this.errorsMap.entries())i.size>0&&(e[t]=Object.fromEntries(i));this.state={...this.state,errors:e},this.notify()}updateErrors(e){this.errorsMap.clear();for(let[t,i]of Object.entries(e)){let s=new Map;for(let[c,r]of Object.entries(i))s.set(c,r);s.size>0&&this.errorsMap.set(t,s)}this.state={...this.state,errors:e},this.notify()}setStepErrors(e,t){if(!t||Object.keys(t).length===0)return this.errorsMap.has(e)?(this.errorsMap.delete(e),this.syncErrors(),!0):!1;let i=new Map;for(let[s,c]of Object.entries(t))i.set(s,c);return this.errorsMap.set(e,i),this.syncErrors(),!0}deleteError(e,t){let i=this.errorsMap.get(e);return i&&i.has(t)?(i.delete(t),i.size===0&&this.errorsMap.delete(e),this.syncErrors(),!0):!1}notify(){this.listeners.forEach(e=>e())}};var $=class{constructor(){m(this,"storage",{})}saveStep(e,t){this.storage[e]=t}getStep(e){return this.storage[e]}clear(){this.storage={}}};import{jsx as ie}from"react/jsx-runtime";var xe=oe(void 0),ve=oe(void 0),Y=oe(void 0);function be({config:n,initialData:e,initialStepId:t,children:i}){let[s,c]=Oe(n),r=M(new K(e||{},n.middlewares)),p=M(!1),g=B(()=>s.persistence?.adapter||new $,[s.persistence?.adapter]),I=s.persistence?.mode||"onStepChange",l="__wizzard_meta__",T=Z(a=>r.current.subscribe(a),()=>r.current.getSnapshot()),{activeSteps:b,currentStepId:U,history:pe,visitedSteps:le,completedSteps:ue,data:Se,errors:{}}=T,D=B(()=>{let a=new Map;return s.steps.forEach(d=>a.set(d.id,d)),a},[s.steps]);J(()=>{c(n)},[n]);let fe=B(()=>{let a=new Map;return b.forEach((d,o)=>a.set(d.id,o)),a},[b]),w=M({config:s,stepsMap:D,activeSteps:b,activeStepsIndexMap:fe,visitedSteps:le,completedSteps:ue,persistenceMode:I,persistenceAdapter:g,currentStepId:U,history:pe});J(()=>{w.current={config:s,stepsMap:D,activeSteps:b,activeStepsIndexMap:fe,visitedSteps:le,completedSteps:ue,persistenceMode:I,persistenceAdapter:g,currentStepId:U,history:pe}});let O=z((a,d)=>{s.analytics?.onEvent(a,d)},[s.analytics]),W=z((a,d,o)=>{let{stepsMap:f,persistenceAdapter:S,persistenceMode:y}=w.current,E=f.get(d),x=E?.persistenceAdapter||S,h=E?.persistenceMode||y;(a===h||a==="manual")&&x.saveStep(d,o)},[]),_=z(async a=>{r.current.updateMeta({isBusy:!0});try{return(await Promise.all(s.steps.map(async o=>{if(!o.condition)return{step:o,ok:!0};let f=new Set(r.current.getSnapshot().busySteps);f.add(o.id),r.current.updateMeta({busySteps:f,isBusy:!0});try{let S=o.condition(a||{},r.current.getSnapshot()),y=S instanceof Promise?await S:S;return{step:o,ok:y}}catch(S){return console.error(`[Wizard] Condition failed for ${o.id}:`,S),{step:o,ok:!1}}finally{let S=r.current.getSnapshot(),y=new Set(S.busySteps);y.delete(o.id),r.current.updateMeta({busySteps:y,isBusy:y.size>0})}}))).filter(o=>o.ok).map(o=>o.step)}finally{r.current.getSnapshot().busySteps.size===0&&r.current.updateMeta({isBusy:!1})}},[s.steps]),A=z(async(a,d)=>{let o=D.get(a);if(!o||!o.validationAdapter)return!0;r.current.dispatch({type:"VALIDATE_START",payload:{stepId:a}});let f=new Set(r.current.getSnapshot().busySteps);f.add(a),r.current.updateMeta({busySteps:f,isBusy:!0});try{let S=await o.validationAdapter.validate(d);if(S.isValid){r.current.setStepErrors(a,null);let y=new Set(r.current.getSnapshot().errorSteps);return y.delete(a),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:y}}),!0}else{r.current.setStepErrors(a,S.errors||null),O("validation_error",{stepId:a,errors:S.errors,timestamp:Date.now()});let y=new Set(r.current.getSnapshot().errorSteps);return y.add(a),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:y}}),!1}}finally{let S=new Set(r.current.getSnapshot().busySteps);S.delete(a),r.current.updateMeta({busySteps:S,isBusy:S.size>0}),r.current.dispatch({type:"VALIDATE_END",payload:{stepId:a,result:{isValid:!0}}})}},[D,O]),V=z(async(a,d)=>{let{currentStepId:o,config:f,persistenceMode:S,persistenceAdapter:y,stepsMap:E}=w.current,x=r.current.getSnapshot().data,h=f.steps,R=h.findIndex(P=>P.id===o),F=h.findIndex(P=>P.id===a);if(F>R&&o){let P=E.get(o);if((P?.autoValidate??f.autoValidate??!!P?.validationAdapter)&&!await A(o,x))return!1}r.current.updateMeta({isBusy:!0});try{if(!(d||await _(x)).find(ae=>ae.id===a))return!1;let q=E.get(o);if(q?.beforeLeave){let ae=r.current.getSnapshot(),ke=F>R?"next":"prev";if(await q.beforeLeave(x,ke,ae)===!1)return!1}o&&(q?.persistenceMode||S)==="onStepChange"&&W("onStepChange",o,x);let re=r.current.getSnapshot(),se=new Set(re.visitedSteps);o&&se.add(o),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:se}}),r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:a}});let me=[...re.history,a];return r.current.dispatch({type:"SET_HISTORY",payload:{history:me}}),S!=="manual"&&y.saveStep(l,{currentStepId:a,visited:Array.from(se),completed:Array.from(re.completedSteps),history:me}),f.onStepChange&&f.onStepChange(o||null,a,x),O("step_change",{from:o||null,to:a,timestamp:Date.now()}),window.scrollTo(0,0),!0}finally{r.current.updateMeta({isBusy:!1})}},[_,A,W,O]),ye=z(async()=>{let{currentStepId:a}=w.current;if(!a)return;let d=r.current.getSnapshot().data,o=D.get(a);if((o?.autoValidate??s.autoValidate??!!o?.validationAdapter)&&!await A(a,d))return;let S=await _(d),y=S.findIndex(E=>E.id===a);if(y!==-1&&y<S.length-1){let E=S[y+1].id;if(await V(E,S)){let h=new Set(r.current.getSnapshot().completedSteps);h.add(a),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:h}})}}},[V,_,A,D]),ge=z(()=>{let{currentStepId:a,activeSteps:d,activeStepsIndexMap:o}=w.current,f=o.get(a)??-1;f>0&&V(d[f-1].id)},[V]),te=z((a,d,o)=>{let{persistenceMode:f,stepsMap:S,currentStepId:y}=w.current,E=r.current.getSnapshot().data;if(k(E,a)===d)return;let x=j(E,a,d);if(s.steps.forEach(h=>{if(h.dependsOn?.some(R=>a===R||a.startsWith(R+"."))){let R=new Set(r.current.getSnapshot().completedSteps);R.delete(h.id)&&r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:R}});let F=new Set(r.current.getSnapshot().visitedSteps);F.delete(h.id)&&r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:F}}),h.clearData&&(typeof h.clearData=="function"?x={...x,...h.clearData(x)}:(Array.isArray(h.clearData)?h.clearData:[h.clearData]).forEach(P=>{x=j(x,P,void 0)}))}}),r.current.dispatch({type:"SET_DATA",payload:{path:a,value:d,options:o}}),y){r.current.deleteError(y,a);let h=S.get(y);(h?.validationMode||s.validationMode||"onStepChange")==="onChange"&&A(y,x),(h?.persistenceMode||f)==="onChange"&&W("onChange",y,x)}},[s,A,W]),he=z((a,d)=>{let o=r.current.getSnapshot().data,f=d?.replace?a:{...o,...a};r.current.update(f,Object.keys(a)),d?.persist&&s.steps.forEach(S=>W("manual",S.id,f))},[s.steps,W]),Te=z(()=>{if(r.current.setInitialData(e||{}),r.current.update(e||{}),r.current.updateErrors({}),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:new Set}}),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:new Set}}),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:new Set}}),b.length>0){let a=b[0].id;r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:a}}),r.current.dispatch({type:"SET_HISTORY",payload:{history:[a]}})}else r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:""}}),r.current.dispatch({type:"SET_HISTORY",payload:{history:[]}});g.clear(),O("wizard_reset",{data:e})},[e,b,g,O]),Re=B(()=>({...T,config:s}),[T,s]),Ce=B(()=>({goToNextStep:ye,goToPrevStep:ge,goToStep:V,setStepData:(a,d)=>{let o={...r.current.getSnapshot().data,...d};r.current.update(o,Object.keys(d))},handleStepChange:(a,d)=>{w.current.currentStepId&&te(a,d)},validateStep:a=>A(a,r.current.getSnapshot().data),validateAll:async()=>{r.current.updateMeta({isBusy:!0});let a=r.current.getSnapshot().data,d=await _(a),o=await Promise.all(d.map(f=>A(f.id,a)));return r.current.updateMeta({isBusy:!1}),{isValid:o.every(Boolean),errors:r.current.getSnapshot().errors}},save:a=>{let d=r.current.getSnapshot().data;a===!0?s.steps.forEach(o=>W("manual",o.id,d)):a?(Array.isArray(a)?a:[a]).forEach(o=>W("manual",o,d)):w.current.currentStepId&&W("manual",w.current.currentStepId,d)},clearStorage:()=>g.clear(),reset:Te,setData:te,updateData:he,getData:(a,d)=>k(r.current.getSnapshot().data,a,d),updateConfig:a=>c(d=>({...d,...a}))}),[ye,ge,V,A,Te,te,he,g,s.steps,W]);return J(()=>{p.current?r.current.updateMeta({config:s}):(r.current.dispatch({type:"INIT",payload:{data:e||{},config:s}}),p.current=!0)},[e,s]),J(()=>{let a=!0;return(async()=>{let o=await _(Se);a&&r.current.dispatch({type:"SET_ACTIVE_STEPS",payload:{steps:o}})})(),()=>{a=!1}},[Se,_]),J(()=>{let a=g.getStep(l);a&&(a.currentStepId&&r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:a.currentStepId}}),a.visited&&r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:new Set(a.visited)}}),a.completed&&r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:new Set(a.completed)}}),a.history&&r.current.dispatch({type:"SET_HISTORY",payload:{history:a.history}}));let d=r.current.getSnapshot(),o=d.activeSteps;if(!U&&o.length>0){let f=t&&o.some(S=>S.id===t)?t:o[0].id;r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:f}}),d.history.length===0&&r.current.dispatch({type:"SET_HISTORY",payload:{history:[f]}}),r.current.updateMeta({isLoading:!1})}},[b,t,U,g]),ie(Y.Provider,{value:r.current,children:ie(xe.Provider,{value:Re,children:ie(ve.Provider,{value:Ce,children:i})})})}function G(){let n=L(xe);if(!n)throw new Error("useWizardState must be used within a WizardProvider");return n}function Ee(n,e){let t=L(Y);if(!t)throw new Error("useWizardValue must be used within a WizardProvider");let i=M(null),s=M(null),c=z(()=>{let r=t.getSnapshot().data;if(r===i.current)return s.current;let p=k(r,n);return s.current!==void 0&&(e?.isEqual||Object.is)(s.current,p)?(i.current=r,s.current):(i.current=r,s.current=p,p)},[t,n,e?.isEqual]);return Z(t.subscribe,c)}function ze(n){let e=L(Y);if(!e)throw new Error("useWizardError must be used within a WizardProvider");let t=z(()=>{let i=e.getSnapshot().errors;for(let[s,c]of Object.entries(i)){let r=c;if(r[n])return r[n];if(n.startsWith(s+".")&&r[s])return r[s];let p=n.split(".").pop();if(p&&r[p])return r[p]}},[e,n]);return Z(e.subscribe,t)}function X(n,e){let t=L(Y);if(!t)throw new Error("useWizardSelector must be used within a WizardProvider");let i=M(null),s=M(null),c=z(()=>{let r=t.getSnapshot();if(r===i.current)return s.current;let p=n(r);return s.current!==null&&(e?.isEqual||Object.is)(s.current,p)?(i.current=r,s.current):(i.current=r,s.current=p,p)},[t,n,e?.isEqual]);return Z(t.subscribe,c)}function de(){let n=L(ve);if(!n)throw new Error("useWizardActions must be used within a WizardProvider");return n}function C(){let n=G(),e=de(),t=L(Y),i=X(g=>g.data),s=X(g=>g.errors),{data:c,errors:r,...p}=n;return B(()=>({...p,...e,wizardData:i,allErrors:s,data:i,errors:s,store:t}),[p,e,i,s,t])}import{useMemo as Ve,Suspense as Be}from"react";import{jsx as ce}from"react/jsx-runtime";var Le=({wrapper:n,fallback:e=null})=>{let{currentStep:t}=C(),i=Ve(()=>t?.component?t.component:null,[t]);if(!t||!i)return null;let s=ce(Be,{fallback:e,children:ce(i,{})});return n?ce(n,{children:s},t.id):s};var We=()=>C();import{jsx as Fe}from"react/jsx-runtime";function Ne(){return{WizardProvider:({config:l,initialData:T,children:b})=>Fe(be,{config:l,initialData:T,children:b}),useWizard:()=>We(),useWizardContext:()=>C(),useWizardValue:(l,T)=>Ee(l,T),useWizardSelector:(l,T)=>X(l,T),useWizardError:l=>ze(l),useWizardActions:()=>de(),useWizardState:()=>G(),useBreadcrumbs:()=>G().breadcrumbs,createStep:l=>l}}var we=class{constructor(e="wizard_"){m(this,"prefix");this.prefix=e}getKey(e){return`${this.prefix}${e}`}saveStep(e,t){if(!(typeof window>"u"))try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch(i){console.warn("LocalStorageAdapter: Failed to save step",i)}}getStep(e){if(!(typeof window>"u"))try{let t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):void 0}catch(t){console.warn("LocalStorageAdapter: Failed to get step",t);return}}clear(){typeof window>"u"||Object.keys(localStorage).forEach(e=>{e.startsWith(this.prefix)&&localStorage.removeItem(e)})}};var Ae=class{constructor(e){m(this,"schema");this.schema=e}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return{isValid:!0};let i={};return t.error&&t.error.issues.forEach(s=>{let c=s.path.join(".");i[c]=s.message}),{isValid:!1,errors:i}}};var Pe=class{constructor(e){m(this,"schema");this.schema=e}async validate(e){try{return await this.schema.validate(e,{abortEarly:!1}),{isValid:!0}}catch(t){if(t&&typeof t=="object"&&"inner"in t){let i=t,s={};return i.inner.forEach(c=>{c.path&&(s[c.path]=c.message)}),{isValid:!1,errors:s}}throw t}}};var je=n=>e=>t=>{console.group(`Wizard Action: ${t.type}`),console.log("Action payload:",t.payload),console.log("State before:",n.getSnapshot());let i=e(t);return console.log("State after:",n.getSnapshot()),console.groupEnd(),i};var Je=n=>{if(typeof window>"u"||!window.__REDUX_DEVTOOLS_EXTENSION__)return t=>i=>t(i);let e=window.__REDUX_DEVTOOLS_EXTENSION__.connect({name:"Wizard Stepper React"});return e.init(n.getSnapshot()),t=>i=>{let s=t(i);return e.send(i,n.getSnapshot()),s}};import{useState as ee,useEffect as Ye}from"react";import{jsx as u,jsxs as v}from"react/jsx-runtime";function He(){let[n,e]=ee(!1),[t,i]=ee("state"),{wizardData:s,allErrors:c,store:r,...p}=C(),[g,I]=ee([]);return Ye(()=>r?r.subscribeToActions(T=>{I(b=>[{timestamp:Date.now(),action:T,state:r.getSnapshot()},...b].slice(0,50))}):void 0,[r]),n?v("div",{style:{position:"fixed",bottom:"20px",right:"20px",width:"400px",height:"500px",backgroundColor:"rgba(15, 23, 42, 0.9)",backdropFilter:"blur(12px)",borderRadius:"16px",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"0 10px 40px rgba(0,0,0,0.5)",zIndex:9999,display:"flex",flexDirection:"column",color:"#e2e8f0",fontFamily:"Inter, sans-serif",overflow:"hidden"},children:[v("div",{style:{padding:"12px 16px",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",display:"flex",justifyContent:"space-between",alignItems:"center",background:"rgba(255, 255, 255, 0.03)"},children:[u("span",{style:{fontWeight:600,fontSize:"14px"},children:"Wizard DevTools"}),u("button",{onClick:()=>e(!1),style:{background:"none",border:"none",color:"#94a3b8",cursor:"pointer",fontSize:"18px"},children:"\xD7"})]}),u("div",{style:{display:"flex",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",background:"rgba(255, 255, 255, 0.02)"},children:["state","actions","errors"].map(l=>u("button",{onClick:()=>i(l),style:{flex:1,padding:"10px",background:t===l?"rgba(37, 99, 235, 0.2)":"none",border:"none",color:t===l?"#60a5fa":"#94a3b8",borderBottom:t===l?"2px solid #3b82f6":"none",cursor:"pointer",fontSize:"12px",textTransform:"capitalize",fontWeight:t===l?600:400},children:l},l))}),v("div",{style:{flex:1,overflowY:"auto",padding:"16px",fontSize:"12px"},children:[t==="state"&&v("div",{children:[v(Q,{title:"Navigation",children:[u(N,{label:"Current Step",value:p.currentStepId}),u(N,{label:"Index",value:p.currentStepIndex}),u(N,{label:"Progress",value:`${p.progress}%`}),u(N,{label:"Total Steps",value:p.activeStepsCount}),u(N,{label:"Is Loading",value:String(p.isLoading)}),u(N,{label:"Is Busy",value:String(p.isBusy)})]}),u(Q,{title:"History",children:u("div",{style:{color:"#94a3b8"},children:p.history.join(" \u2192 ")||"Empty"})}),u(Q,{title:"Data",children:u(H,{data:s})}),u(Q,{title:"Meta",children:u(H,{data:{visited:Array.from(p.visitedSteps),completed:Array.from(p.completedSteps),busy:Array.from(p.busySteps)}})})]}),t==="errors"&&u("div",{children:Object.keys(c).length===0?u("div",{style:{color:"#94a3b8",textAlign:"center",marginTop:"20px"},children:"No active errors"}):u(H,{data:c})}),t==="actions"&&u("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:g.length===0?u("div",{style:{color:"#94a3b8",textAlign:"center",marginTop:"20px"},children:"No actions recorded yet"}):g.map((l,T)=>u(Ue,{log:l},l.timestamp+T))})]}),v("div",{style:{padding:"8px 16px",fontSize:"10px",color:"#64748b",borderTop:"1px solid rgba(255, 255, 255, 0.1)",background:"rgba(255, 255, 255, 0.02)",display:"flex",justifyContent:"space-between"},children:[v("span",{children:["v",globalThis.process?.env?.VERSION||"2.0.0"]}),u("span",{children:"Strict Mode: Active"})]})]}):u("button",{onClick:()=>e(!0),style:{position:"fixed",bottom:"20px",right:"20px",zIndex:9999,padding:"10px 15px",borderRadius:"50px",background:"rgba(37, 99, 235, 0.9)",color:"white",border:"none",boxShadow:"0 4px 15px rgba(0,0,0,0.2)",cursor:"pointer",fontWeight:"bold",fontSize:"12px",backdropFilter:"blur(5px)"},children:"Wizard DevTools"})}var Ue=({log:n})=>{let[e,t]=ee(!1),i=new Date(n.timestamp).toLocaleTimeString();return v("div",{style:{background:"rgba(255, 255, 255, 0.05)",borderRadius:"8px",overflow:"hidden",border:"1px solid rgba(255, 255, 255, 0.05)"},children:[v("div",{onClick:()=>t(!e),style:{padding:"8px 12px",display:"flex",justifyContent:"space-between",cursor:"pointer",alignItems:"center"},children:[v("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[u("span",{style:{color:"#64748b",fontSize:"10px"},children:i}),u("span",{style:{color:"#60a5fa",fontWeight:600},children:n.action.type})]}),u("span",{style:{color:"#475569",transform:e?"rotate(180deg)":"none",transition:"transform 0.2s"},children:"\u25BE"})]}),e&&v("div",{style:{padding:"0 12px 12px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.05)"},children:[v("div",{style:{marginTop:"8px"},children:[u("div",{style:{color:"#94a3b8",marginBottom:"4px",fontSize:"10px"},children:"Payload:"}),u(H,{data:n.action.payload})]}),v("div",{style:{marginTop:"8px"},children:[u("div",{style:{color:"#94a3b8",marginBottom:"4px",fontSize:"10px"},children:"State after:"}),u(H,{data:n.state})]})]})]})},Q=({title:n,children:e})=>v("div",{style:{marginBottom:"20px"},children:[u("h4",{style:{margin:"0 0 8px 0",color:"#3b82f6",fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.05em"},children:n}),e]}),N=({label:n,value:e})=>v("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"4px"},children:[v("span",{style:{color:"#94a3b8"},children:[n,":"]}),u("span",{style:{color:"#f8fafc",fontWeight:500},children:e})]}),H=({data:n})=>u("pre",{style:{background:"rgba(0, 0, 0, 0.3)",padding:"10px",borderRadius:"8px",overflowX:"auto",color:"#60a5fa",border:"1px solid rgba(255, 255, 255, 0.05)",margin:0},children:JSON.stringify(n,(t,i)=>i instanceof Set?Array.from(i):i,2)});export{we as LocalStorageAdapter,$ as MemoryAdapter,He as WizardDevTools,be as WizardProvider,Le as WizardStepRenderer,Pe as YupAdapter,Ae as ZodAdapter,Ne as createWizardFactory,Je as devToolsMiddleware,k as getByPath,je as loggerMiddleware,j as setByPath,$e as shallowEqual,Ie as toPath,We as useWizard,de as useWizardActions,C as useWizardContext,ze as useWizardError,X as useWizardSelector,G as useWizardState,Ee as useWizardValue};
|
|
1
|
+
var Be=Object.defineProperty;var Le=(s,e,t)=>e in s?Be(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var x=(s,e,t)=>Le(s,typeof e!="symbol"?e+"":e,t);import{createContext as pe,useContext as N,useEffect as B,useMemo as L,useState as Ne,useCallback as w,useSyncExternalStore as te,useRef as C}from"react";var de=new Map;function Ee(s){if(!s)return[];if(de.has(s))return de.get(s);let e;return s.includes("[")?e=s.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean):e=s.split(".").filter(Boolean),de.set(s,e),e}function _(s,e,t){if(!e||s===void 0||s===null)return t??s;if(!e.includes(".")&&!e.includes("[")){let d=s[e];return d!==void 0?d:t}let i=Ee(e),a=s;for(let d=0;d<i.length;d++){if(a==null)return t;a=a[i[d]]}return a!==void 0?a:t}function H(s,e,t){if(!e)return t;if(!e.includes(".")&&!e.includes("[")){if(Array.isArray(s)){let p=[...s];return p[e]=t,p}return{...s,[e]:t}}let i=Ee(e);if(i.length===0)return t;let a=Array.isArray(s)?[...s]:{...s},d=a;for(let p=0;p<i.length-1;p++){let T=i[p],v=i[p+1],u=d[T],m;u&&typeof u=="object"?m=Array.isArray(u)?[...u]:{...u}:m=/^\d+$/.test(v)?[]:{},d[T]=m,d=m}let r=i[i.length-1];return d[r]=t,a}function Qe(s,e){if(Object.is(s,e))return!0;if(typeof s!="object"||s===null||typeof e!="object"||e===null)return!1;let t=Object.keys(s),i=Object.keys(e);if(t.length!==i.length)return!1;for(let a=0;a<t.length;a++){let d=t[a];if(!Object.prototype.hasOwnProperty.call(e,d)||!Object.is(s[d],e[d]))return!1}return!0}var G=class{constructor(e,t=[]){x(this,"initialData");x(this,"dirtyFields",new Set);x(this,"state");x(this,"listeners",new Set);x(this,"actionListeners",new Set);x(this,"errorsMap",new Map);x(this,"middlewareChain");x(this,"getSnapshot",()=>this.state);x(this,"subscribe",e=>(this.listeners.add(e),()=>this.listeners.delete(e)));this.initialData=JSON.parse(JSON.stringify(e)),this.state={data:e,errors:{},isDirty:!1,dirtyFields:this.dirtyFields,visitedSteps:new Set,completedSteps:new Set,errorSteps:new Set,currentStep:null,currentStepId:"",currentStepIndex:0,isFirstStep:!0,isLastStep:!1,isLoading:!0,isPending:!1,isBusy:!1,activeSteps:[],history:[],busySteps:new Set,progress:0,activeStepsCount:0,breadcrumbs:[],config:{}},this.middlewareChain=this.setupMiddlewares(t)}subscribeToActions(e){return this.actionListeners.add(e),()=>this.actionListeners.delete(e)}notifyActions(e){this.actionListeners.forEach(t=>t(e))}setupMiddlewares(e){let t={getState:()=>this.state.data,getSnapshot:()=>this.getSnapshot(),dispatch:a=>this.dispatch(a)};return e.map(a=>a(t)).reduceRight((a,d)=>d(a),this.internalDispatch.bind(this))}dispatch(e){this.middlewareChain(e)}internalDispatch(e){switch(this.notifyActions(e),e.type){case"INIT":this.initialData=JSON.parse(JSON.stringify(e.payload.data));let t=e.payload.config.steps.filter(i=>!i.condition);this.state={...this.state,data:e.payload.data,config:e.payload.config,activeSteps:t,activeStepsCount:t.length},this.notify();break;case"SET_CURRENT_STEP_ID":this.state={...this.state,currentStepId:e.payload.stepId},this.notify();break;case"SET_HISTORY":this.state={...this.state,history:e.payload.history},this.notify();break;case"SET_ACTIVE_STEPS":this.state={...this.state,activeSteps:e.payload.steps,activeStepsCount:e.payload.steps.length},this.notify();break;case"SET_DATA":this.updateDataByPath(e.payload.path,e.payload.value,e.payload.options);break;case"UPDATE_DATA":this.updateBulkData(e.payload.data,e.payload.options);break;case"GO_TO_STEP":this.state={...this.state,currentStepId:e.payload.to};break;case"VALIDATE_START":this.state.busySteps.add(e.payload.stepId),this.state={...this.state,busySteps:new Set(this.state.busySteps)};break;case"VALIDATE_END":this.state.busySteps.delete(e.payload.stepId),this.state={...this.state,busySteps:new Set(this.state.busySteps)},e.payload.result.errors&&this.setStepErrors(e.payload.stepId,e.payload.result.errors);break;case"SET_STEP_ERRORS":this.setStepErrors(e.payload.stepId,e.payload.errors);break;case"RESET":this.setInitialData(e.payload.data);break;case"SET_ERROR_STEPS":this.state={...this.state,errorSteps:e.payload.steps};break;case"SET_VISITED_STEPS":this.state={...this.state,visitedSteps:e.payload.steps};break;case"SET_COMPLETED_STEPS":this.state={...this.state,completedSteps:e.payload.steps};break}this.syncDerivedState(),this.notify()}updateDataByPath(e,t,i){let a=H(this.state.data,e,t);a!==this.state.data&&this.update(a,e)}updateBulkData(e,t){let i;t?.replace?i=e:(i=JSON.parse(JSON.stringify(this.state.data)),Object.assign(i,e)),this.update(i,Object.keys(e))}update(e,t){t&&(Array.isArray(t)?t:[t]).forEach(a=>{let d=_(this.initialData,a),r=_(e,a);JSON.stringify(d)!==JSON.stringify(r)?this.dirtyFields.add(a):this.dirtyFields.delete(a)}),this.state={...this.state,data:e,isDirty:this.dirtyFields.size>0,dirtyFields:new Set(this.dirtyFields)},this.notify()}updateMeta(e){this.state={...this.state,...e},this.syncDerivedState(),this.notify()}syncDerivedState(){let{activeSteps:e,currentStepId:t,visitedSteps:i,completedSteps:a,errorSteps:d}=this.state,r=Math.max(0,e.findIndex(v=>v.id===t)),p=e[r]||null,T=e.map(v=>{let u="upcoming";return v.id===t?u="current":d.has(v.id)?u="error":a.has(v.id)?u="completed":i.has(v.id)&&(u="visited"),{id:v.id,label:v.label,status:u}});this.state={...this.state,currentStep:p,currentStepIndex:r,isFirstStep:r===0,isLastStep:e.length>0&&r===e.length-1,progress:e.length>0?Math.round((r+1)/e.length*100):0,breadcrumbs:T}}setInitialData(e){this.initialData=JSON.parse(JSON.stringify(e)),this.dirtyFields.clear(),this.state={...this.state,data:e,isDirty:!1,dirtyFields:new Set},this.notify()}syncErrors(){let e={};for(let[t,i]of this.errorsMap.entries())i.size>0&&(e[t]=Object.fromEntries(i));this.state={...this.state,errors:e},this.notify()}updateErrors(e){this.errorsMap.clear();for(let[t,i]of Object.entries(e)){let a=new Map;for(let[d,r]of Object.entries(i))a.set(d,r);a.size>0&&this.errorsMap.set(t,a)}this.state={...this.state,errors:e},this.notify()}setStepErrors(e,t){if(!t||Object.keys(t).length===0)return this.errorsMap.has(e)?(this.errorsMap.delete(e),this.syncErrors(),!0):!1;let i=new Map;for(let[a,d]of Object.entries(t))i.set(a,d);return this.errorsMap.set(e,i),this.syncErrors(),!0}deleteError(e,t){let i=this.errorsMap.get(e);return i&&i.has(t)?(i.delete(t),i.size===0&&this.errorsMap.delete(e),this.syncErrors(),!0):!1}notify(){this.listeners.forEach(e=>e())}};var Q=class{constructor(){x(this,"storage",{})}saveStep(e,t){this.storage[e]=t}getStep(e){return this.storage[e]}clear(){this.storage={}}};import{jsx as ce}from"react/jsx-runtime";var ze=pe(void 0),we=pe(void 0),U=pe(void 0);function We({config:s,initialData:e,initialStepId:t,children:i}){let[a,d]=Ne(s),r=C(null);r.current||(r.current=new G(e||{},s.middlewares));let p=C(!1),T=L(()=>a.persistence?.adapter||new Q,[a.persistence?.adapter]),v=a.persistence?.mode||"onStepChange",u="__wizzard_meta__",m=te(n=>r.current.subscribe(n),()=>r.current.getSnapshot()),{activeSteps:E,currentStepId:$,history:Se,visitedSteps:fe,completedSteps:ye,data:he,errors:{}}=m,M=L(()=>{let n=new Map;return a.steps.forEach(c=>n.set(c.id,c)),n},[a.steps]);B(()=>{d(s)},[s]);let ge=L(()=>{let n=new Map;return E.forEach((c,o)=>n.set(c.id,o)),n},[E]),P=C({config:a,stepsMap:M,activeSteps:E,activeStepsIndexMap:ge,visitedSteps:fe,completedSteps:ye,persistenceMode:v,persistenceAdapter:T,currentStepId:$,history:Se}),Te=C(new Map),J=C(null);B(()=>{P.current={config:a,stepsMap:M,activeSteps:E,activeStepsIndexMap:ge,visitedSteps:fe,completedSteps:ye,persistenceMode:v,persistenceAdapter:T,currentStepId:$,history:Se}}),B(()=>()=>{J.current&&clearTimeout(J.current)},[]);let V=w((n,c)=>{a.analytics?.onEvent(n,c)},[a.analytics]),W=w((n,c,o)=>{let{stepsMap:S,persistenceAdapter:l,persistenceMode:y}=P.current,h=S.get(c),I=h?.persistenceAdapter||l,g=h?.persistenceMode||y;(n===g||n==="manual")&&I.saveStep(c,o)},[]),k=w(async n=>{r.current.updateMeta({isBusy:!0});try{return(await Promise.all(a.steps.map(async o=>{if(!o.condition)return{step:o,ok:!0};if(o.conditionDependsOn){let l=o.conditionDependsOn.map(h=>_(n,h)),y=Te.current.get(o.id);if(y&&y.depsValues.length===l.length&&y.depsValues.every((h,I)=>h===l[I]))return{step:o,ok:y.result};try{let h=o.condition(n||{},r.current.getSnapshot()),I=h instanceof Promise?await h:h;return Te.current.set(o.id,{result:I,depsValues:l}),{step:o,ok:I}}catch(h){return console.error(`[Wizard] Condition failed for ${o.id}:`,h),{step:o,ok:!1}}}let S=new Set(r.current.getSnapshot().busySteps);S.add(o.id),r.current.updateMeta({busySteps:S,isBusy:!0});try{let l=o.condition(n||{},r.current.getSnapshot()),y=l instanceof Promise?await l:l;return{step:o,ok:y}}catch(l){return console.error(`[Wizard] Condition failed for ${o.id}:`,l),{step:o,ok:!1}}finally{let l=r.current.getSnapshot(),y=new Set(l.busySteps);y.delete(o.id),r.current.updateMeta({busySteps:y,isBusy:y.size>0})}}))).filter(o=>o.ok).map(o=>o.step)}finally{r.current.getSnapshot().busySteps.size===0&&r.current.updateMeta({isBusy:!1})}},[a.steps]),A=w(async(n,c)=>{let o=M.get(n);if(!o||!o.validationAdapter)return!0;r.current.dispatch({type:"VALIDATE_START",payload:{stepId:n}});let S=new Set(r.current.getSnapshot().busySteps);S.add(n),r.current.updateMeta({busySteps:S,isBusy:!0});try{let l=await o.validationAdapter.validate(c);if(l.isValid){r.current.setStepErrors(n,null);let y=new Set(r.current.getSnapshot().errorSteps);return y.delete(n),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:y}}),!0}else{r.current.setStepErrors(n,l.errors||null),V("validation_error",{stepId:n,errors:l.errors,timestamp:Date.now()});let y=new Set(r.current.getSnapshot().errorSteps);y.add(n),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:y}});let h=new Set(r.current.getSnapshot().completedSteps);return h.has(n)&&(h.delete(n),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:h}})),!1}}finally{let l=new Set(r.current.getSnapshot().busySteps);l.delete(n),r.current.updateMeta({busySteps:l,isBusy:l.size>0}),r.current.dispatch({type:"VALIDATE_END",payload:{stepId:n,result:{isValid:!0}}})}},[M,V]),O=w(async(n,c,o={validate:!0})=>{let{currentStepId:S,config:l,persistenceMode:y,persistenceAdapter:h,stepsMap:I}=P.current,g=r.current.getSnapshot().data,z=l.steps,Y=z.findIndex(D=>D.id===S),K=z.findIndex(D=>D.id===n);if(K>Y&&S&&o.validate){let D=I.get(S);if((D?.autoValidate??l.autoValidate??!!D?.validationAdapter)&&!await A(S,g))return!1}r.current.updateMeta({isBusy:!0});try{if(!(c||await k(g)).find(oe=>oe.id===n))return!1;let X=I.get(S);if(X?.beforeLeave){let oe=r.current.getSnapshot(),Oe=K>Y?"next":"prev";if(await X.beforeLeave(g,Oe,oe)===!1)return!1}S&&(X?.persistenceMode||y)==="onStepChange"&&W("onStepChange",S,g);let ie=r.current.getSnapshot(),Z=new Set(ie.visitedSteps);S&&Z.add(S),Z.add(n),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:Z}}),r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n}});let be=[...ie.history,n];return r.current.dispatch({type:"SET_HISTORY",payload:{history:be}}),y!=="manual"&&h.saveStep(u,{currentStepId:n,visited:Array.from(Z),completed:Array.from(ie.completedSteps),history:be}),l.onStepChange&&l.onStepChange(S||null,n,g),V("step_change",{from:S||null,to:n,timestamp:Date.now()}),window.scrollTo(0,0),!0}finally{r.current.updateMeta({isBusy:!1})}},[k,A,W,V]),me=w(async()=>{let{currentStepId:n}=P.current;if(!n)return;let c=r.current.getSnapshot().data,o=M.get(n);if((o?.autoValidate??a.autoValidate??!!o?.validationAdapter)&&!await A(n,c))return;let l=await k(c),y=l.findIndex(h=>h.id===n);if(y!==-1&&y<l.length-1){let h=l[y+1].id;if(await O(h,l,{validate:!1})){let g=r.current.getSnapshot();if(!g.errorSteps.has(n)){let z=new Set(g.completedSteps);z.add(n),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:z}})}}}},[O,k,A,M]),Ie=w(()=>{let{currentStepId:n,activeSteps:c,activeStepsIndexMap:o}=P.current,S=o.get(n)??-1;S>0&&O(c[S-1].id)},[O]),ne=w((n,c,o)=>{let{persistenceMode:S,stepsMap:l,currentStepId:y}=P.current,h=r.current.getSnapshot().data;if(_(h,n)===c)return;let I=H(h,n,c);if(a.steps.forEach(g=>{if(g.dependsOn?.some(z=>n===z||n.startsWith(z+"."))){let z=new Set(r.current.getSnapshot().completedSteps);z.delete(g.id)&&r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:z}});let Y=new Set(r.current.getSnapshot().visitedSteps);Y.delete(g.id)&&r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:Y}}),g.clearData&&(typeof g.clearData=="function"?I={...I,...g.clearData(I)}:(Array.isArray(g.clearData)?g.clearData:[g.clearData]).forEach(K=>{I=H(I,K,void 0)}))}}),r.current.dispatch({type:"SET_DATA",payload:{path:n,value:c,options:o}}),y){r.current.deleteError(y,n);let g=l.get(y);if((g?.validationMode||a.validationMode||"onStepChange")==="onChange"){let z=o?.debounceValidation??a.validationDebounceTime??300;J.current&&clearTimeout(J.current),J.current=setTimeout(()=>{A(y,I)},z)}(g?.persistenceMode||S)==="onChange"&&W("onChange",y,I)}},[a,A,W]),xe=w((n,c)=>{let o=r.current.getSnapshot().data,S=c?.replace?n:{...o,...n};r.current.update(S,Object.keys(n)),c?.persist&&a.steps.forEach(l=>W("manual",l.id,S))},[a.steps,W]),ve=w(()=>{if(r.current.setInitialData(e||{}),r.current.update(e||{}),r.current.updateErrors({}),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:new Set}}),r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:new Set}}),r.current.dispatch({type:"SET_ERROR_STEPS",payload:{steps:new Set}}),E.length>0){let n=E[0].id;r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n}}),r.current.dispatch({type:"SET_HISTORY",payload:{history:[n]}})}else r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:""}}),r.current.dispatch({type:"SET_HISTORY",payload:{history:[]}});T.clear(),V("wizard_reset",{data:e})},[e,E,T,V]),De=L(()=>({...m,config:a}),[m,a]),Me=L(()=>({goToNextStep:me,goToPrevStep:Ie,goToStep:O,setStepData:(n,c)=>{let o={...r.current.getSnapshot().data,...c};r.current.update(o,Object.keys(c))},handleStepChange:(n,c)=>{P.current.currentStepId&&ne(n,c)},validateStep:n=>A(n,r.current.getSnapshot().data),validateAll:async()=>{r.current.updateMeta({isBusy:!0});let n=r.current.getSnapshot().data,c=await k(n),o=await Promise.all(c.map(S=>A(S.id,n)));return r.current.updateMeta({isBusy:!1}),{isValid:o.every(Boolean),errors:r.current.getSnapshot().errors}},save:n=>{let c=r.current.getSnapshot().data;n===!0?a.steps.forEach(o=>W("manual",o.id,c)):n?(Array.isArray(n)?n:[n]).forEach(o=>W("manual",o,c)):P.current.currentStepId&&W("manual",P.current.currentStepId,c)},clearStorage:()=>T.clear(),reset:ve,setData:ne,updateData:xe,getData:(n,c)=>_(r.current.getSnapshot().data,n,c),updateConfig:n=>d(c=>({...c,...n}))}),[me,Ie,O,A,ve,ne,xe,T,a.steps,W]);return B(()=>{p.current?r.current.updateMeta({config:a}):(r.current.dispatch({type:"INIT",payload:{data:e||{},config:a}}),p.current=!0)},[e,a]),B(()=>{let n=!0,c=setTimeout(async()=>{let o=await k(he);n&&r.current.dispatch({type:"SET_ACTIVE_STEPS",payload:{steps:o}})},200);return()=>{n=!1,clearTimeout(c)}},[he,k]),B(()=>{let n=T.getStep(u);n&&(n.currentStepId&&r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:n.currentStepId}}),n.visited&&r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:new Set(n.visited)}}),n.completed&&r.current.dispatch({type:"SET_COMPLETED_STEPS",payload:{steps:new Set(n.completed)}}),n.history&&r.current.dispatch({type:"SET_HISTORY",payload:{history:n.history}}));let c=r.current.getSnapshot(),o=c.activeSteps;if(!$&&o.length>0){let S=t&&o.some(y=>y.id===t)?t:o[0].id;r.current.dispatch({type:"SET_CURRENT_STEP_ID",payload:{stepId:S}}),c.history.length===0&&r.current.dispatch({type:"SET_HISTORY",payload:{history:[S]}});let l=new Set(r.current.getSnapshot().visitedSteps);l.has(S)||(l.add(S),r.current.dispatch({type:"SET_VISITED_STEPS",payload:{steps:l}})),r.current.updateMeta({isLoading:!1})}},[E,t,$,T]),ce(U.Provider,{value:r.current,children:ce(ze.Provider,{value:De,children:ce(we.Provider,{value:Me,children:i})})})}function re(){let s=N(ze);if(!s)throw new Error("useWizardState must be used within a WizardProvider");return s}function Pe(s,e){let t=N(U);if(!t)throw new Error("useWizardValue must be used within a WizardProvider");let i=C(null),a=C(null),d=w(()=>{let r=t.getSnapshot().data;if(r===i.current)return a.current;let p=_(r,s);return a.current!==void 0&&(e?.isEqual||Object.is)(a.current,p)?(i.current=r,a.current):(i.current=r,a.current=p,p)},[t,s,e?.isEqual]);return te(t.subscribe,d)}function Ae(s){let e=N(U);if(!e)throw new Error("useWizardError must be used within a WizardProvider");let t=w(()=>{let i=e.getSnapshot().errors;for(let[a,d]of Object.entries(i)){let r=d;if(r[s])return r[s];if(s.startsWith(a+".")&&r[a])return r[a];let p=s.split(".").pop();if(p&&r[p])return r[p]}},[e,s]);return te(e.subscribe,t)}function ee(s,e){let t=N(U);if(!t)throw new Error("useWizardSelector must be used within a WizardProvider");let i=C(null),a=C(null),d=w(()=>{let r=t.getSnapshot();if(r===i.current)return a.current;let p=s(r);return a.current!==null&&(e?.isEqual||Object.is)(a.current,p)?(i.current=r,a.current):(i.current=r,a.current=p,p)},[t,s,e?.isEqual]);return te(t.subscribe,d)}function le(){let s=N(we);if(!s)throw new Error("useWizardActions must be used within a WizardProvider");return s}function R(){let s=re(),e=le(),t=N(U),i=ee(T=>T.data),a=ee(T=>T.errors),{data:d,errors:r,...p}=s;return L(()=>({...p,...e,wizardData:i,allErrors:a,data:i,errors:a,store:t}),[p,e,i,a,t])}import{useMemo as Fe,Suspense as je}from"react";import{jsx as ue}from"react/jsx-runtime";var Je=({wrapper:s,fallback:e=null})=>{let{currentStep:t}=R(),i=Fe(()=>t?.component?t.component:null,[t]);if(!t||!i)return null;let a=ue(je,{fallback:e,children:ue(i,{})});return s?ue(s,{children:a},t.id):a};var Ce=()=>R();import{jsx as He}from"react/jsx-runtime";function Ye(){return{WizardProvider:({config:u,initialData:m,children:E})=>He(We,{config:u,initialData:m,children:E}),useWizard:()=>Ce(),useWizardContext:()=>R(),useWizardValue:(u,m)=>Pe(u,m),useWizardSelector:(u,m)=>ee(u,m),useWizardError:u=>Ae(u),useWizardActions:()=>le(),useWizardState:()=>re(),useBreadcrumbs:()=>re().breadcrumbs,createStep:u=>u}}var _e=class{constructor(e="wizard_"){x(this,"prefix");this.prefix=e}getKey(e){return`${this.prefix}${e}`}saveStep(e,t){if(!(typeof window>"u"))try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch(i){console.warn("LocalStorageAdapter: Failed to save step",i)}}getStep(e){if(!(typeof window>"u"))try{let t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):void 0}catch(t){console.warn("LocalStorageAdapter: Failed to get step",t);return}}clear(){typeof window>"u"||Object.keys(localStorage).forEach(e=>{e.startsWith(this.prefix)&&localStorage.removeItem(e)})}};var Re=class{constructor(e){x(this,"schema");this.schema=e}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return{isValid:!0};let i={};return t.error&&t.error.issues.forEach(a=>{let d=a.path.join(".");i[d]=a.message}),{isValid:!1,errors:i}}};var ke=class{constructor(e){x(this,"schema");this.schema=e}async validate(e){try{return await this.schema.validate(e,{abortEarly:!1}),{isValid:!0}}catch(t){if(t&&typeof t=="object"&&"inner"in t){let i=t,a={};return i.inner.forEach(d=>{d.path&&(a[d.path]=d.message)}),{isValid:!1,errors:a}}throw t}}};var Ue=s=>e=>t=>{console.group(`Wizard Action: ${t.type}`),console.log("Action payload:",t.payload),console.log("State before:",s.getSnapshot());let i=e(t);return console.log("State after:",s.getSnapshot()),console.groupEnd(),i};var F=s=>{if(s instanceof Set)return Array.from(s);if(s instanceof Map)return Object.fromEntries(s);if(typeof s=="function")return"[Function]";if(Array.isArray(s))return s.map(F);if(typeof s=="object"&&s!==null){if("steps"in s&&Array.isArray(s.steps)&&"persistence"in s)return{...s,steps:s.steps.map(t=>({id:t.id,label:t.label,condition:t.condition?"[Function]":void 0,component:t.component?"[Component]":void 0,...t}))};let e={};for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=F(s[t]));return e}return s},qe=s=>{if(typeof window>"u"||!window.__REDUX_DEVTOOLS_EXTENSION__)return t=>i=>t(i);let e=window.__REDUX_DEVTOOLS_EXTENSION__.connect({name:"Wizard Stepper React",features:{pause:!0,lock:!0,persist:!0,export:!0,import:"custom",jump:!0,skip:!0,reorder:!0,dispatch:!0,test:!0}});return e.init(F(s.getSnapshot())),t=>i=>{let a=t(i),d=s.getSnapshot(),r=F(d),p=F(i);return e.send(p,r),a}};import{useState as ae,useEffect as $e}from"react";import{jsx as f,jsxs as b}from"react/jsx-runtime";function Ke(){let[s,e]=ae(!1),[t,i]=ae("state"),{wizardData:a,allErrors:d,store:r,...p}=R(),[T,v]=ae([]);return $e(()=>r?r.subscribeToActions(m=>{v(E=>[{timestamp:Date.now(),action:m,state:r.getSnapshot()},...E].slice(0,50))}):void 0,[r]),s?b("div",{style:{position:"fixed",bottom:"20px",right:"20px",width:"400px",height:"500px",backgroundColor:"rgba(15, 23, 42, 0.9)",backdropFilter:"blur(12px)",borderRadius:"16px",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"0 10px 40px rgba(0,0,0,0.5)",zIndex:9999,display:"flex",flexDirection:"column",color:"#e2e8f0",fontFamily:"Inter, sans-serif",overflow:"hidden"},children:[b("div",{style:{padding:"12px 16px",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",display:"flex",justifyContent:"space-between",alignItems:"center",background:"rgba(255, 255, 255, 0.03)"},children:[f("span",{style:{fontWeight:600,fontSize:"14px"},children:"Wizard DevTools"}),f("button",{onClick:()=>e(!1),style:{background:"none",border:"none",color:"#94a3b8",cursor:"pointer",fontSize:"18px"},children:"\xD7"})]}),f("div",{style:{display:"flex",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",background:"rgba(255, 255, 255, 0.02)"},children:["state","actions","errors"].map(u=>f("button",{onClick:()=>i(u),style:{flex:1,padding:"10px",background:t===u?"rgba(37, 99, 235, 0.2)":"none",border:"none",color:t===u?"#60a5fa":"#94a3b8",borderBottom:t===u?"2px solid #3b82f6":"none",cursor:"pointer",fontSize:"12px",textTransform:"capitalize",fontWeight:t===u?600:400},children:u},u))}),b("div",{style:{flex:1,overflowY:"auto",padding:"16px",fontSize:"12px"},children:[t==="state"&&b("div",{children:[b(se,{title:"Navigation",children:[f(j,{label:"Current Step",value:p.currentStepId}),f(j,{label:"Index",value:p.currentStepIndex}),f(j,{label:"Progress",value:`${p.progress}%`}),f(j,{label:"Total Steps",value:p.activeStepsCount}),f(j,{label:"Is Loading",value:String(p.isLoading)}),f(j,{label:"Is Busy",value:String(p.isBusy)})]}),f(se,{title:"History",children:f("div",{style:{color:"#94a3b8"},children:p.history.join(" \u2192 ")||"Empty"})}),f(se,{title:"Data",children:f(q,{data:a})}),f(se,{title:"Meta",children:f(q,{data:{visited:Array.from(p.visitedSteps),completed:Array.from(p.completedSteps),busy:Array.from(p.busySteps)}})})]}),t==="errors"&&f("div",{children:Object.keys(d).length===0?f("div",{style:{color:"#94a3b8",textAlign:"center",marginTop:"20px"},children:"No active errors"}):f(q,{data:d})}),t==="actions"&&f("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:T.length===0?f("div",{style:{color:"#94a3b8",textAlign:"center",marginTop:"20px"},children:"No actions recorded yet"}):T.map((u,m)=>f(Xe,{log:u},u.timestamp+m))})]}),b("div",{style:{padding:"8px 16px",fontSize:"10px",color:"#64748b",borderTop:"1px solid rgba(255, 255, 255, 0.1)",background:"rgba(255, 255, 255, 0.02)",display:"flex",justifyContent:"space-between"},children:[b("span",{children:["v",globalThis.process?.env?.VERSION||"2.0.0"]}),f("span",{children:"Strict Mode: Active"})]})]}):f("button",{onClick:()=>e(!0),style:{position:"fixed",bottom:"20px",right:"20px",zIndex:9999,padding:"10px 15px",borderRadius:"50px",background:"rgba(37, 99, 235, 0.9)",color:"white",border:"none",boxShadow:"0 4px 15px rgba(0,0,0,0.2)",cursor:"pointer",fontWeight:"bold",fontSize:"12px",backdropFilter:"blur(5px)"},children:"Wizard DevTools"})}var Xe=({log:s})=>{let[e,t]=ae(!1),i=new Date(s.timestamp).toLocaleTimeString();return b("div",{style:{background:"rgba(255, 255, 255, 0.05)",borderRadius:"8px",overflow:"hidden",border:"1px solid rgba(255, 255, 255, 0.05)"},children:[b("div",{onClick:()=>t(!e),style:{padding:"8px 12px",display:"flex",justifyContent:"space-between",cursor:"pointer",alignItems:"center"},children:[b("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[f("span",{style:{color:"#64748b",fontSize:"10px"},children:i}),f("span",{style:{color:"#60a5fa",fontWeight:600},children:s.action.type})]}),f("span",{style:{color:"#475569",transform:e?"rotate(180deg)":"none",transition:"transform 0.2s"},children:"\u25BE"})]}),e&&b("div",{style:{padding:"0 12px 12px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.05)"},children:[b("div",{style:{marginTop:"8px"},children:[f("div",{style:{color:"#94a3b8",marginBottom:"4px",fontSize:"10px"},children:"Payload:"}),f(q,{data:s.action.payload})]}),b("div",{style:{marginTop:"8px"},children:[f("div",{style:{color:"#94a3b8",marginBottom:"4px",fontSize:"10px"},children:"State after:"}),f(q,{data:s.state})]})]})]})},se=({title:s,children:e})=>b("div",{style:{marginBottom:"20px"},children:[f("h4",{style:{margin:"0 0 8px 0",color:"#3b82f6",fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.05em"},children:s}),e]}),j=({label:s,value:e})=>b("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"4px"},children:[b("span",{style:{color:"#94a3b8"},children:[s,":"]}),f("span",{style:{color:"#f8fafc",fontWeight:500},children:e})]}),q=({data:s})=>f("pre",{style:{background:"rgba(0, 0, 0, 0.3)",padding:"10px",borderRadius:"8px",overflowX:"auto",color:"#60a5fa",border:"1px solid rgba(255, 255, 255, 0.05)",margin:0},children:JSON.stringify(s,(t,i)=>i instanceof Set?Array.from(i):i,2)});export{_e as LocalStorageAdapter,Q as MemoryAdapter,Ke as WizardDevTools,We as WizardProvider,Je as WizardStepRenderer,ke as YupAdapter,Re as ZodAdapter,Ye as createWizardFactory,qe as devToolsMiddleware,_ as getByPath,Ue as loggerMiddleware,H as setByPath,Qe as shallowEqual,Ee as toPath,Ce as useWizard,le as useWizardActions,R as useWizardContext,Ae as useWizardError,ee as useWizardSelector,re as useWizardState,Pe as useWizardValue};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wizzard-stepper-react",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "A flexible, headless, and strictly typed multi-step wizard library for React.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -92,7 +92,7 @@
|
|
|
92
92
|
"lint": "eslint src/**",
|
|
93
93
|
"test": "vitest",
|
|
94
94
|
"test:run": "vitest run",
|
|
95
|
-
"release": "release-it",
|
|
95
|
+
"release": "release-it --no-npm",
|
|
96
96
|
"commit": "cz"
|
|
97
97
|
}
|
|
98
98
|
}
|