@jfdevelops/react-multi-step-form 1.0.0-alpha.1 → 1.0.0-alpha.3
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 +9 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +552 -609
- package/dist/index.mjs.map +1 -1
- package/dist/types/step-schema.d.ts +16 -6
- package/package.json +10 -5
package/dist/index.cjs
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("react/jsx-runtime"),
|
|
2
|
-
`)}function
|
|
3
|
-
${
|
|
4
|
-
${
|
|
5
|
-
${V(n.errors)}`:s()}),this.createCtxHelper(e);if(typeof e=="object"){const n=Object.keys(e);return d(n.every(a=>r.includes(a)),()=>{const a=N(n,r,t);return a.status==="error"?`${s()}. See errors:
|
|
6
|
-
${V(a.errors)}`:s()}),this.createCtxHelper(n)}throw new Error(`${s()} OR to "all"`)}createStepHelperFnImpl(e){return(t,r)=>{const s=this.createCtx(e);if(typeof t=="function")return()=>t({ctx:s});if(typeof t=="object")return n=>"validator"in t?(d(typeof n=="object","An input is expected since you provided a validator"),G(t.validator,n.data),r({ctx:s,...n})):r({ctx:s});throw new Error(`The first argument must be a function or an object, (was ${typeof t})`)}}}class ve{prefix;includeTimestamp;throwOnError;constructor(e){const{includeTimestamp:t,prefix:r,throwOnError:s}=e??{};this.prefix=r??"MultiStepFormSchema",this.includeTimestamp=t??!1,this.throwOnError=s??!1}wrapValue(e,t){if(e==="[]")return`[${t}]`;if(e==="{}")return`{${t}}`;if(e==="none")return t;throw new Error(`The first argument ${e} is not valid. Valid options include: "[]", "{}", and "none"`)}formatPrefix(e){if(!e)return this.prefix;const{action:t,value:r,wrapWith:s}=e;if(t==="replace")return this.wrapValue(s??"[]",r);const{delimiter:n}=e;return t==="append"?`${this.wrapValue(s?.originalPrefix??"[]",this.prefix)}${n}${this.wrapValue(s?.addedPrefix??"[]",r)}`.trim():t==="prepend"?`${this.wrapValue(s?.addedPrefix??"[]",r)}${n}${this.wrapValue(s?.originalPrefix??"[]",this.prefix)}`.trim():this.prefix}formatMessage(e,t,r){const{includeTimestamp:s=this.includeTimestamp,prefix:n,logLevelOptions:a}=r??{},c=this.formatPrefix(n),y=this.wrapValue(a?.wrapWith??"[]",(a?.level??e).toUpperCase()),p=`${c} ${y} ${t}`;return s?`[${new Date().toISOString()}] ${p}`:p}info(e,t){console.info(this.formatMessage("info",e,t))}warn(e,t){console.warn(this.formatMessage("warn",e,t))}error(e,t){const r=this.formatMessage("error",e,t);if(console.error(r),t?.throw??this.throwOnError)throw new Error(r)}}const Y='"window" in undefined. No storage is available',K="MultiStepForm";class ie{key;store;data;log;isWindowUndefined;constructor(e){const{key:t,data:r,store:s}=e;this.log=new ve({prefix:K}),this.key=t,this.data=r,s?(this.store=s,this.isWindowUndefined=!1):typeof window<"u"?(this.store=window.localStorage,this.isWindowUndefined=!1):(this.isWindowUndefined=!0,this.log.warn(Y))}throwOnEmptyStore(){d(this.store,()=>this.isWindowUndefined?Y:"No storage available")}resolveValue(e){if(typeof e=="object")return e;if(typeof e=="function")return e(this.data);this.log.error(`The updater value must be a function or object. Was a ${typeof e}`,{throw:!0})}hasKey(){return this.store.getItem(this.key)!==null}get(){this.throwOnEmptyStore();const e=this.store.getItem(this.key);if(e)return JSON.parse(e)}remove(){this.throwOnEmptyStore(),this.store.removeItem(this.key)}add(e){this.throwOnEmptyStore();const t=JSON.stringify(this.resolveValue(e));this.store.setItem(this.key,t)}}const ge=["sentence","title","camel","lower","upper","pascal","snake","screaming-snake","flat","kebab"],P="title";function we(o,e){const t=o.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().split(/\s+/).map(r=>r.toLowerCase());switch(e){case"sentence":return t[0].charAt(0).toUpperCase()+t[0].slice(1)+(t.length>1?" "+t.slice(1).join(" "):"");case"title":return t.map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"camel":return t[0]+t.slice(1).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");case"pascal":return t.map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");case"lower":return t.join(" ");case"upper":return t.join(" ").toUpperCase();case"snake":return t.join("_");case"screaming-snake":return t.join("_").toUpperCase();case"kebab":return t.join("-");case"flat":return t.join("");default:return o}}function H(o){return typeof o!="string"?!1:ge.includes(o)}function ue(o,e=P){return H(o)?o:e}const _e=["string","string.phone","string.email","string.time","number","number.counter","date","dateTime","boolean.switch"],Z="string";function Te(o){return typeof o=="string"&&_e.includes(o)}class ce{listeners=new Set;constructor(){this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}}const $e=["string","number","array.string","array.string.untyped"],le=/^step\d+$/i;function Q(o,e){if(typeof o!="object"||o===null)return!1;for(const t of Object.keys(e)){if(!(t in o))return!1;const r=e[t],s=o[t];if(!r(s))return!1}return!0}function X(o,e,t){return o??we(e,t)}function Ee(o){const e={},{fields:t,defaultCasing:r,validateFields:s}=o;for(const[n,a]of Object.entries(t)){d(typeof n=="string",`Each key for the "fields" option must be a string. Key ${n} was a ${typeof n}`),d(typeof a=="object",`The value for key ${n} must be an object. Was ${typeof a}`);const{defaultValue:c,label:y,nameTransformCasing:p,type:l=Z}=a;if(s)e[n]=c;else{const u=p??r;e[n]={...e[n],nameTransformCasing:u,type:l,defaultValue:c,label:X(y,n,u)}}}if(s){const n=G(s,e);d(typeof n=="object",`The result of the validated fields must be an object, was (${typeof n}). This is probably an internal error, so open up an issue about it`),d(!!n,"The result of the validated fields must be defined. This is probably an internal error, so open up an issue about it");for(const[a,c]of Object.entries(n)){const y=t[a];d(y,`No field found in the fields config for "${a}"`);const{label:p,type:l=Z,nameTransformCasing:u}=y,f=u??r;e[a]={...e[a],nameTransformCasing:f,type:l,defaultValue:c,label:X(p,a,f)}}}return e}function fe(o){const e={};d(!!o,"The steps config must be defined",TypeError),d(typeof o=="object",`The steps config must be an object, was (${typeof o})`,TypeError);for(const[t,r]of Object.entries(o)){d(typeof t=="string",`Each key for the step config must be a string. Key "${t}" was ${typeof t} `,TypeError),d(le.test(t),`The key "${t}" isn't formatted properly. Each key in the step config must be the following format: "step{number}"`);const s=t,{fields:n,title:a,nameTransformCasing:c=P,description:y,validateFields:p}=r,l=s.toString().replace("step","");d(n,`Missing fields for step ${l} (${String(s)})`,TypeError),d(typeof n=="object","Fields must be an object",TypeError),d(Object.keys(n).length>0,`The fields config for step ${l} (${String(s)}) is empty. Please add a field`),d(typeof n=="object",`The "fields" property must be an object. Was ${typeof n}`);const u=Ee({defaultCasing:c,fields:n,validateFields:p});e[s]={...e[s],title:a,nameTransformCasing:c,...typeof y=="string"?{description:y}:{},fields:u}}return e}class B extends ce{original;value;steps;defaultNameTransformationCasing;firstStep;lastStep;stepNumbers;storage;constructor(e){super();const{steps:t,nameTransformCasing:r,storage:s}=e;this.defaultNameTransformationCasing=ue(r),this.original=t,this.value=this.enrichValues(fe(this.original)),this.stepNumbers=Object.keys(this.value).map(n=>Number.parseInt(n.replace("step",""))),this.storage=new ie({data:this.value,key:s?.key??K,store:s?.store}),this.firstStep=this.first(),this.lastStep=this.last(),this.steps={first:this.firstStep.step,last:this.lastStep.step,value:this.stepNumbers,as:n=>{if(d(typeof n=="string",`The type of the target transformation type must be a string, was ${typeof n}`),n==="string")return this.stepNumbers.map(a=>`'${a}'`).join(" | ");if(n==="number")return this.stepNumbers.join(" | ");if(n.includes("array.string"))return this.stepNumbers.map(a=>`${a}`);throw new Error(`Transformation type "${n}" is not supported. Available transformations include: ${$e.map(a=>`"${a}"`).join(", ")}`)},isValidStepNumber:n=>this.stepNumbers.includes(n),isValidStepKey:n=>Object.keys(this.value).includes(n)}}getSnapshot(){return this}notify(){for(const e of this.listeners)e({defaultNameTransformationCasing:this.defaultNameTransformationCasing,original:this.original,steps:this.steps,value:this.value})}enrichValues(e,t){for(const[r,s]of Object.entries(e)){const n=Number.parseInt(r.replace("step",""));e={...e,[r]:{...s,update:this.createStepUpdaterFn(n),createHelperFn:this.createStepHelperFn(n),...t?.(n)}}}return e}get(e){return j(this.value)(e)}first(){const e=Math.min(...this.stepNumbers);return this.get({step:e})}last(){const e=Math.max(...this.stepNumbers);return this.get({step:e})}handlePostUpdate(){this.storage.add(this.value),this.notify()}createStepUpdaterFnImpl(e,t,r){const s=this.stepNumbers;d(typeof e=="number",`Type of step must be a number, was ${typeof e}`,TypeError),d(s.includes(e),`The target step ${e} is not valid. Valid steps include "${s.join(", ")}"`);const n=`step${e}`;if(typeof t=="string"){d(this.value[n],`No data found for step ${e}`),d(typeof this.value[n]=="object",`The values for step ${e} is not an object, was ${typeof this.value[n]}`),d(t in this.value[n],`The field ${t} is not a valid field. Valid fields include ${Object.keys(this.value[n]).join(", ")}`),d(typeof r=="object"||typeof r=="function",()=>{let a="";return typeof r!="object"&&(a="an object"),typeof r!="function"&&(a="a function"),`[${String(n)}-${t}]: The updater must be ${a}, was "${typeof r}"`},TypeError),this.value={...this.value,[n]:{...this.value[n],[t]:J(r,this.value[n][t])}},this.handlePostUpdate();return}if(typeof t=="object"||typeof t=="function"){const a=J(t,this.value[n]);d(typeof a=="object",`The updated data must be an object, was ${typeof a}`),this.value={...this.value,[n]:{...this.value[n],...a}},this.handlePostUpdate();return}throw new TypeError(`The second parameter must be one of the following: a specific field to update (string), an object with the updated data, or a function that returns the updated data. It was ${typeof t}`,{cause:t})}createStepUpdaterFn(e){return(t,r)=>{this.createStepUpdaterFnImpl(e,t,r)}}update(e,t,r){this.createStepUpdaterFnImpl(e,t,r)}createStepHelperFnImpl(e){return(t,r)=>{const s=U(this.value,e);if(typeof t=="function")return()=>t({ctx:s});if(typeof t=="object")return n=>"validator"in t?(d(typeof n=="object","An input is expected since you provided a validator"),G(t.validator,n.data),r({ctx:s,...n})):r({ctx:s});throw new Error(`The first argument must be a function or an object, (was ${typeof t})`)}}createStepHelperFn(e){return this.createStepHelperFnImpl([`step${e}`])}createHelperFn(e,t){const{stepData:r,...s}=e;return this.createStepHelperFnImpl(r)(s,t)}static hasData(e,t){return e===null||typeof e!="object"?!1:Q(e,{title:r=>typeof r=="string",fields:r=>{if(r===null||typeof r!="object")return!1;for(const s of Object.keys(r)){if(typeof s!="string"||!(s in r))return!1;const n=r[s];if(n===null||typeof n!="object"||!Q(n,{defaultValue:a=>a!=="undefined"&&a!==null,label:a=>typeof a=="string"||typeof a=="boolean"&&!a,nameTransformCasing:H,type:Te}))return!1}return!0},createHelperFn:r=>typeof r=="function",update:r=>typeof r=="function",nameTransformCasing:H,...t?.optionalKeysToCheck})}}class Oe extends ce{stepHelper;defaultNameTransformationCasing;stepSchema;storage;mountCount=0;constructor(e){super();const{steps:t,nameTransformCasing:r,storage:s}=e;this.defaultNameTransformationCasing=ue(r),this.stepSchema=new B({steps:t,nameTransformCasing:this.defaultNameTransformationCasing}),this.stepHelper=new be(this.stepSchema.value,this.stepSchema.steps.value),this.storage=new ie({key:s?.key??K,data:this.stepSchema.value,store:s?.store}),this.stepSchema.subscribe(()=>{this.notify()})}getSnapshot(){return this}mount(){return this.mountCount++,this.mountCount===1&&this.onMount(),()=>{this.unmount()}}unmount(){this.mountCount=Math.max(0,this.mountCount-1),this.mountCount===0&&this.onUnmount()}isMounted(){return this.mountCount>0}onMount(){}onUnmount(){}notify(){for(const e of this.listeners)e({nameTransformCasing:this.defaultNameTransformationCasing,storage:{key:this.storage.key,store:this.storage.store},steps:this.stepSchema.original})}}function je(o){function e(t){const{children:r,name:s}=t;return r(o(s))}return e}var O;(o=>{o.DEFAULT_FORM_ALIAS="Form";function e(r,s){if(Array.isArray(r)){if(s==="all")return!0;if(typeof s=="object"&&!Array.isArray(s))return Object.keys(s).some(n=>r.includes(n));if(Array.isArray(s))return s.some(n=>r.includes(n))}return!1}o.isFormAvailable=e;function t(r){return s=>R.jsx("form",{id:r,...s})}o.createDefaultForm=t})(O||(O={}));exports.StepSpecificComponent=void 0;(o=>{o.DEFAULT_FORM_INSTANCE_ALIAS="form"})(exports.StepSpecificComponent||(exports.StepSpecificComponent={}));function pe(o,e){d(e in o,`The target step ${e} is not a valid step key`);const t=o[e];d("fields"in t,`No "fields" were found for ${e}`);let r={};for(const[s,n]of Object.entries(t.fields))r={...r,[s]:n.defaultValue};return r}class de extends B{value;constructor(e){const{form:t,...r}=e;super(r),this.value=this.enrichValues(fe(this.original)),this.value=this.enrichValues(this.value,s=>{const n=`step${s}`,a=t?.id??n;return{createComponent:this.createComponentForStep([`step${s}`],{isStepSpecific:!0,defaultId:a,form:t})}})}createFormComponent(e,t){const{render:r,enabledForSteps:s="all",id:n=t}=e,a={id:n,steps:U(this.value,s)};return c=>r(a,c)}createStepSpecificComponentImpl(e,t,r,s={}){return n=>(a=>{const c={};for(const[l,u]of Object.entries(s))if(typeof u=="function")try{const f=u();c[l]=f,typeof console<"u"&&console.debug&&console.debug(`[multi-step-form] Hook "${l}" called successfully`,{result:f!==void 0?"defined":"undefined"})}catch(f){const i=f instanceof Error?f.message:String(f);throw new Error(`[multi-step-form] Error calling hook "${l}" in useFormInstance.render: ${i}
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("react/jsx-runtime"),N=require("react");function ve(o,...e){return()=>String.raw({raw:o},...e)}function h(o,e,t=Error){if(!o){const r=typeof e=="function"?e():ve`${e}`();throw new t(r)}}const I="MultiStepFormSchema";class ae{debug;prefix=I;includeTimestamp=!1;throwOnError=!1;constructor(e){if(this.debug=e?.debug??!1,this.debug&&e?.debug){const{includeTimestamp:t=!1,prefix:r=I,throwOnError:s=!1}=e;this.includeTimestamp=t,this.prefix=typeof r=="string"?r:r(I),this.throwOnError=s}}wrapValue(e,t){if(e==="[]")return`[${t}]`;if(e==="{}")return`{${t}}`;if(e==="none")return t;throw new Error(`The first argument ${e} is not valid. Valid options include: "[]", "{}", and "none"`)}formatPrefix(e){if(!e)return this.prefix;const{action:t,value:r,wrapWith:s}=e;if(t==="replace")return this.wrapValue(s??"[]",r);const{delimiter:n}=e;return t==="append"?`${this.wrapValue(s?.originalPrefix??"[]",this.prefix)}${n}${this.wrapValue(s?.addedPrefix??"[]",r)}`.trim():t==="prepend"?`${this.wrapValue(s?.addedPrefix??"[]",r)}${n}${this.wrapValue(s?.originalPrefix??"[]",this.prefix)}`.trim():this.prefix}formatMessage(e,t,r){const{includeTimestamp:s=this.includeTimestamp,prefix:n,logLevelOptions:i}=r??{},p=this.formatPrefix(n),y=this.wrapValue(i?.wrapWith??"[]",(i?.level??e).toUpperCase()),f=`${p} ${y} ${t}`;return s?`[${new Date().toISOString()}] ${f}`:f}info(e,t){this.debug&&console.info(this.formatMessage("info",e,t))}warn(e,t){this.debug&&console.warn(this.formatMessage("warn",e,t))}error(e,t){if(!this.debug)return;const r=this.formatMessage("error",e,t);if(console.error(r),t?.throw??this.throwOnError)throw new Error(r)}}const B='"window" in undefined. No storage is available',W="MultiStepForm";class ue{key;store;data;log;isWindowUndefined;constructor(e){const{key:t,data:r,store:s}=e;this.log=new ae({prefix:W}),this.key=t,this.data=r,s?(this.store=s,this.isWindowUndefined=!1):typeof window<"u"?(this.store=window.localStorage,this.isWindowUndefined=!1):(this.isWindowUndefined=!0,this.log.warn(B))}throwOnEmptyStore(){h(this.store,()=>this.isWindowUndefined?B:"No storage available")}resolveValue(e){if(typeof e=="object")return e;if(typeof e=="function")return e(this.data);this.log.error(`The updater value must be a function or object. Was a ${typeof e}`,{throw:!0})}hasKey(){return this.store.getItem(this.key)!==null}get(){this.throwOnEmptyStore();const e=this.store.getItem(this.key);if(e)return JSON.parse(e)}remove(){this.throwOnEmptyStore(),this.store.removeItem(this.key)}add(e){this.throwOnEmptyStore();const t=JSON.stringify(this.resolveValue(e));this.store.setItem(this.key,t)}}const _e=["sentence","title","camel","lower","upper","pascal","snake","screaming-snake","flat","kebab"],K="title";function we(o,e){const t=o.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().split(/\s+/).map(r=>r.toLowerCase());switch(e){case"sentence":return t[0].charAt(0).toUpperCase()+t[0].slice(1)+(t.length>1?" "+t.slice(1).join(" "):"");case"title":return t.map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"camel":return t[0]+t.slice(1).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");case"pascal":return t.map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");case"lower":return t.join(" ");case"upper":return t.join(" ").toUpperCase();case"snake":return t.join("_");case"screaming-snake":return t.join("_").toUpperCase();case"kebab":return t.join("-");case"flat":return t.join("");default:return o}}function U(o){return typeof o!="string"?!1:_e.includes(o)}function ce(o,e=K){return U(o)?o:e}const Oe=["string","string.phone","string.email","string.time","number","number.counter","date","dateTime","boolean.switch"],z="string";function Te(o){return typeof o=="string"&&Oe.includes(o)}function le(o,e){const t=o["~standard"].validate(e);if(t instanceof Promise)throw new TypeError("Schema validation must be synchronous",{cause:o});if(t.issues)throw new Error(JSON.stringify(t.issues,null,2));return t.value}class fe{listeners=new Set;constructor(){this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}}function q(o,e,t){const r=[],s=new Set(o),n=t?t.format(o.map(i=>`${i}`)):`[${o.join(", ")}]`;for(let i=0;i<e.length;i++){const p=e[i];s.has(p)||r.push(`Extra element at index ${i}: "${p}" is not in ${n}`)}return e.some(i=>s.has(i))||r.push(`Array must contain at least one valid element from ${n}`),r.length>0?{status:"error",errors:r}:{status:"success"}}function J(o){return o.map((e,t)=>`❌ ${t+1}. ${e}`).join(`
|
|
2
|
+
`)}function V(o){h(o.includes("step"),"Can't extract a valid step number since");const e=o.replace("step","");return h(/^\d+$/.test(e),`Invalid step format: "${o}"`),Number.parseInt(e,10)}function F(o){return function(e){const{step:t}=e,r=`step${t}`,s=o[r];return{step:t,data:s}}}function Y(o,e){return e.reduce((t,r)=>{const s=V(r),{data:n}=F(o)({step:s});for(const[i,p]of Object.entries(n))typeof p=="function"&&i!=="update"||(n[i]=p);return t[r]=n,t},{})}function A(o,e){const t=new Intl.ListFormat("en",{style:"long",type:"disjunction"}),r=Object.keys(o),s=()=>`"stepData" must be set to an array of available steps (${t.format(r)})`;if(e==="all"){let n={};for(const i of r)n={...n,[i]:F(o)({step:V(i)})};return Object.fromEntries(r.map(i=>[i,F(o)({step:V(i)})]))}if(Array.isArray(e))return h(e.every(n=>r.includes(n)),()=>{const n=q(e,r.map(i=>V(i)),t);return n.status==="error"?`${s()}. See errors:
|
|
3
|
+
${J(n.errors)}`:s()}),Y(o,e);if(typeof e=="object"){const n=Object.keys(e);return h(n.every(i=>r.includes(i)),()=>{const i=q(n,r,t);return i.status==="error"?`${s()}. See errors:
|
|
4
|
+
${J(i.errors)}`:s()}),Y(o,n)}throw new Error(`${s()} OR to "all"`)}function Z(o,e){return typeof o=="function"?o(e):o}const Ee=["string","number","array.string","array.string.untyped"],pe=/^step\d+$/i;function Q(o,e){if(typeof o!="object"||o===null)return!1;for(const t of Object.keys(e)){if(!(t in o))return!1;const r=e[t],s=o[t];if(!r(s))return!1}return!0}function X(o,e,t){return o??we(e,t)}function $e(o){const e={},{fields:t,defaultCasing:r,validateFields:s}=o;for(const[n,i]of Object.entries(t)){h(typeof n=="string",`Each key for the "fields" option must be a string. Key ${n} was a ${typeof n}`),h(typeof i=="object",`The value for key ${n} must be an object. Was ${typeof i}`);const{defaultValue:p,label:y,nameTransformCasing:f,type:d=z}=i;if(s)e[n]=p;else{const u=f??r;e[n]={...e[n],nameTransformCasing:u,type:d,defaultValue:p,label:X(y,n,u)}}}if(s){const n=le(s,e);h(typeof n=="object",`The result of the validated fields must be an object, was (${typeof n}). This is probably an internal error, so open up an issue about it`),h(!!n,"The result of the validated fields must be defined. This is probably an internal error, so open up an issue about it");for(const[i,p]of Object.entries(n)){const y=t[i];h(y,`No field found in the fields config for "${i}"`);const{label:f,type:d=z,nameTransformCasing:u}=y,l=u??r;e[i]={...e[i],nameTransformCasing:l,type:d,defaultValue:p,label:X(f,i,l)}}}return e}function de(o){const e={};h(!!o,"The steps config must be defined",TypeError),h(typeof o=="object",`The steps config must be an object, was (${typeof o})`,TypeError);for(const[t,r]of Object.entries(o)){h(typeof t=="string",`Each key for the step config must be a string. Key "${t}" was ${typeof t} `,TypeError),h(pe.test(t),`The key "${t}" isn't formatted properly. Each key in the step config must be the following format: "step{number}"`);const s=t,{fields:n,title:i,nameTransformCasing:p=K,description:y,validateFields:f}=r,d=s.toString().replace("step","");h(n,`Missing fields for step ${d} (${String(s)})`,TypeError),h(typeof n=="object","Fields must be an object",TypeError),h(Object.keys(n).length>0,`The fields config for step ${d} (${String(s)}) is empty. Please add a field`),h(typeof n=="object",`The "fields" property must be an object. Was ${typeof n}`);const u=$e({defaultCasing:p,fields:n,validateFields:f});e[s]={...e[s],title:i,nameTransformCasing:p,...typeof y=="string"?{description:y}:{},fields:u}}return e}class G extends fe{original;value;steps;defaultNameTransformationCasing;firstStep;lastStep;stepNumbers;storage;constructor(e){super();const{steps:t,nameTransformCasing:r,storage:s}=e;this.defaultNameTransformationCasing=ce(r),this.original=t,this.value=this.enrichValues(de(this.original)),this.stepNumbers=Object.keys(this.value).map(n=>Number.parseInt(n.replace("step",""))),this.storage=new ue({data:this.value,key:s?.key??W,store:s?.store}),this.firstStep=this.first(),this.lastStep=this.last(),this.steps={first:this.firstStep.step,last:this.lastStep.step,value:this.stepNumbers,as:n=>{if(h(typeof n=="string",`The type of the target transformation type must be a string, was ${typeof n}`),n==="string")return this.stepNumbers.map(i=>`'${i}'`).join(" | ");if(n==="number")return this.stepNumbers.join(" | ");if(n.includes("array.string"))return this.stepNumbers.map(i=>`${i}`);throw new Error(`Transformation type "${n}" is not supported. Available transformations include: ${Ee.map(i=>`"${i}"`).join(", ")}`)},isValidStepNumber:n=>this.stepNumbers.includes(n),isValidStepKey:n=>Object.keys(this.value).includes(n)}}getSnapshot(){return this}notify(){for(const e of this.listeners)e({defaultNameTransformationCasing:this.defaultNameTransformationCasing,original:this.original,steps:this.steps,value:this.value})}enrichValues(e,t){for(const[r,s]of Object.entries(e)){const n=Number.parseInt(r.replace("step",""));e={...e,[r]:{...s,update:this.createStepUpdaterFn(n),createHelperFn:this.createStepHelperFn(n),...t?.(n)}}}return e}get(e){return F(this.value)(e)}first(){const e=Math.min(...this.stepNumbers);return this.get({step:e})}last(){const e=Math.max(...this.stepNumbers);return this.get({step:e})}handlePostUpdate(){this.storage.add(this.value),this.notify()}createStepUpdaterFnImpl(e,t,r){const s=this.stepNumbers;h(typeof e=="number",`Type of step must be a number, was ${typeof e}`,TypeError),h(s.includes(e),`The target step ${e} is not valid. Valid steps include "${s.join(", ")}"`);const n=`step${e}`;if(typeof t=="string"){h(this.value[n],`No data found for step ${e}`),h(typeof this.value[n]=="object",`The values for step ${e} is not an object, was ${typeof this.value[n]}`),h(t in this.value[n],`The field ${t} is not a valid field. Valid fields include ${Object.keys(this.value[n]).join(", ")}`),this.value={...this.value,[n]:{...this.value[n],[t]:Z(r,this.value[n][t])}},this.handlePostUpdate();return}if(typeof t=="object"||typeof t=="function"){const i=Z(t,this.value[n]);h(typeof i=="object",`The updated data must be an object, was ${typeof i}`),this.value={...this.value,[n]:{...this.value[n],...i}},this.handlePostUpdate();return}throw new TypeError(`The second parameter must be one of the following: a specific field to update (string), an object with the updated data, or a function that returns the updated data. It was ${typeof t}`,{cause:t})}createStepUpdaterFn(e){return(t,r)=>{this.createStepUpdaterFnImpl(e,t,r)}}update(e,t,r){this.createStepUpdaterFnImpl(e,t,r)}createStepHelperFnImpl(e){return(t,r)=>{const s=A(this.value,e);if(typeof t=="function")return()=>t({ctx:s});if(typeof t=="object")return n=>"validator"in t?(h(typeof n=="object","An input is expected since you provided a validator"),le(t.validator,n.data),r({ctx:s,...n})):r({ctx:s});throw new Error(`The first argument must be a function or an object, (was ${typeof t})`)}}createStepHelperFn(e){return this.createStepHelperFnImpl([`step${e}`])}createHelperFn(e,t){const{stepData:r,...s}=e;return this.createStepHelperFnImpl(r)(s,t)}static hasData(e,t){return e===null||typeof e!="object"?!1:Q(e,{title:r=>typeof r=="string",fields:r=>{if(r===null||typeof r!="object")return!1;for(const s of Object.keys(r)){if(typeof s!="string"||!(s in r))return!1;const n=r[s];if(n===null||typeof n!="object"||!Q(n,{defaultValue:i=>i!=="undefined"&&i!==null,label:i=>typeof i=="string"||typeof i=="boolean"&&!i,nameTransformCasing:U,type:Te}))return!1}return!0},createHelperFn:r=>typeof r=="function",update:r=>typeof r=="function",nameTransformCasing:U,...t?.optionalKeysToCheck})}}class Ce extends fe{defaultNameTransformationCasing;stepSchema;storage;mountCount=0;constructor(e){super();const{steps:t,nameTransformCasing:r,storage:s}=e;this.defaultNameTransformationCasing=ce(r),this.stepSchema=new G({steps:t,nameTransformCasing:this.defaultNameTransformationCasing}),this.storage=new ue({key:s?.key??W,data:this.stepSchema.value,store:s?.store}),this.stepSchema.subscribe(()=>{this.notify()})}getSnapshot(){return this}mount(){return this.mountCount++,this.mountCount===1&&this.onMount(),()=>{this.unmount()}}unmount(){this.mountCount=Math.max(0,this.mountCount-1),this.mountCount===0&&this.onUnmount()}isMounted(){return this.mountCount>0}onMount(){}onUnmount(){}notify(){for(const e of this.listeners)e({nameTransformCasing:this.defaultNameTransformationCasing,storage:{key:this.storage.key,store:this.storage.store},steps:this.stepSchema.original})}}function je(o){function e(t){const{children:r,name:s}=t;return r(o(s))}return e}var $;(o=>{o.DEFAULT_FORM_ALIAS="Form";function e(r,s){if(Array.isArray(r)){if(s==="all")return!0;if(typeof s=="object"&&!Array.isArray(s))return Object.keys(s).some(n=>r.includes(n));if(Array.isArray(s))return s.some(n=>r.includes(n))}return!1}o.isFormAvailable=e;function t(r){return s=>R.jsx("form",{id:r,...s})}o.createDefaultForm=t})($||($={}));exports.StepSpecificComponent=void 0;(o=>{o.DEFAULT_FORM_INSTANCE_ALIAS="form"})(exports.StepSpecificComponent||(exports.StepSpecificComponent={}));function he(o,e){h(e in o,`The target step ${e} is not a valid step key`);const t=o[e];h("fields"in t,`No "fields" were found for ${e}`);let r={};for(const[s,n]of Object.entries(t.fields))r={...r,[s]:n.defaultValue};return r}class me extends G{value;constructor(e){const{form:t,...r}=e;super(r),this.value=this.enrichValues(de(this.original)),this.value=this.enrichValues(this.value,s=>{const n=`step${s}`,i=t?.id??n;return{createComponent:this.createComponentForStep([`step${s}`],{isStepSpecific:!0,defaultId:i,form:t})}})}createFormComponent(e,t){const{render:r,enabledForSteps:s="all",id:n=t}=e,i={id:n,steps:A(this.value,s)};return p=>r(i,p)}createStepSpecificComponentImpl(e,t,r,s={}){return n=>(i=>{const p={};for(const[u,l]of Object.entries(s))if(typeof l=="function")try{const a=l();p[u]=a,typeof console<"u"&&console.debug&&console.debug(`[multi-step-form] Hook "${u}" called successfully`,{result:a!==void 0?"defined":"undefined"})}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(`[multi-step-form] Error calling hook "${u}" in useFormInstance.render: ${c}
|
|
7
5
|
|
|
8
6
|
This usually means:
|
|
9
7
|
1. The hook is being called outside of a React component
|
|
10
8
|
2. The hook has invalid dependencies or configuration
|
|
11
9
|
3. There's an error in your hook implementation
|
|
12
10
|
|
|
13
|
-
Original error: ${
|
|
11
|
+
Original error: ${c}`,{cause:a})}else p[u]=l;const{defaultId:y,form:f}=t,{ctx:d}=r;if(f){const{alias:u=$.DEFAULT_FORM_ALIAS,...l}=f,a=l.enabledForSteps??"all",[c]=e;h(this.steps.isValidStepKey(c),`[createComponent]: the target step ${c} is invalid. Note, this error shouldn't appear as the target step should always be valid. If you see this error, please open an issue.`);const m=Number.parseInt(c.replace("step",""));h(!Number.isNaN(m),`[${c}:"createComponent"]: an error occurred while extracting the number`);const S=this.value[c];h("fields"in S,`[${c}:createComponent]: unable to find the "fields" for the current step`),h(typeof S.fields=="object",`[${c}:createComponent]: the "fields" property must be an object, was ${typeof S.fields}`);const _=je(b=>{h(typeof b=="string",()=>{const x=new Intl.ListFormat("en",{style:"long",type:"disjunction"});return`[${c}:Field]: the "name" prop must be a string and a valid field for ${c}. Available fields include ${x.format(Object.keys(S.fields))}`}),h(b in S.fields,`[${c}:Field]: the field "${b}" doesn't exist for the current step`);const{fields:O,update:T}=S,{defaultValue:g,label:v,nameTransformCasing:E,type:ge}=O[b];return{defaultValue:g,label:v,nameTransformCasing:E,type:ge,name:b,onInputChange:x=>T("fields",P=>({...P,[b]:{...P[b],defaultValue:x}}))}});let w={ctx:d,onInputChange:this.createStepUpdaterFn(m),Field:_,...p};return $.isFormAvailable(e,a)&&(w={...w,[u]:this.createFormComponent(l,y)}),n(w,i)}return n({ctx:d,[$.DEFAULT_FORM_ALIAS]:$.createDefaultForm(y)},i)})}createStepSpecificComponentFactory(e,t,r){const s=this.createStepSpecificComponentImpl.bind(this),n=this.createDefaultValues.bind(this),i=this.value;function p(y,f){function d(l){return l?{ctx:{...r,...l}}:{ctx:r}}function u(){return h(typeof y=="function","The first argument must be a function"),s(e,t,d(void 0))(y)}if(typeof y=="object"){const{useFormInstance:l,ctxData:a,debug:c}=y,m=e[0],S=new ae({debug:c,prefix(b){return`${b}-${String(m)}-createComponent`}});S.info("First argument is an object");const{[m]:_,...w}=i;if(h(typeof f=="function","The second argument must be a function"),l){const{render:b,alias:O=exports.StepSpecificComponent.DEFAULT_FORM_INSTANCE_ALIAS}=l,[T]=e,g=n(T),v=a?{...r,...a({ctx:w})}:r,E={ctx:v,defaultValues:g};return s(e,t,v,{[O]:()=>b(E)})(f)}if(a){S.info('Option "ctxData" is defined'),h(typeof a=="function",'Option "ctxData" must be a function');const b=a({ctx:w});S.info(`Addition context is: ${JSON.stringify(b,null,2)}`);const O={...r,...b};return S.info(`Resolved context is: ${JSON.stringify(O,null,2)}`),s(e,t,{ctx:O})(f)}return u()}return u()}return p}createComponentImpl(e,t){const r=A(this.value,e);return t.isStepSpecific?this.createStepSpecificComponentFactory(e,t,r):s=>(n=>s(r,n))}createComponentForStep(e,t){return this.createComponentImpl(e,t)}createComponent(e,t){return this.createComponentImpl(e.stepData,{isStepSpecific:!1})(t)}createDefaultValues(e){return he(this.value,e)}}class ye extends Ce{stepSchema;constructor(e){const{nameTransformCasing:t=K,storage:r,...s}=e;super({nameTransformCasing:t,storage:r,...s}),this.stepSchema=new me({nameTransformCasing:t,...s})}createComponent(e,t){const{stepData:r}=e,s=A(this.stepSchema.value,r);return(n=>t({ctx:s},n))}}function Ve(o){return new ye(o)}var C={exports:{}},L={},j={exports:{}},D={};/**
|
|
14
12
|
* @license React
|
|
15
13
|
* use-sync-external-store-shim.production.js
|
|
16
14
|
*
|
|
@@ -18,7 +16,7 @@ Original error: ${i}`,{cause:f})}else c[l]=u;const{defaultId:y,form:p}=t;if(p){c
|
|
|
18
16
|
*
|
|
19
17
|
* This source code is licensed under the MIT license found in the
|
|
20
18
|
* LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/var ee;function
|
|
19
|
+
*/var ee;function Fe(){if(ee)return D;ee=1;var o=N;function e(u,l){return u===l&&(u!==0||1/u===1/l)||u!==u&&l!==l}var t=typeof Object.is=="function"?Object.is:e,r=o.useState,s=o.useEffect,n=o.useLayoutEffect,i=o.useDebugValue;function p(u,l){var a=l(),c=r({inst:{value:a,getSnapshot:l}}),m=c[0].inst,S=c[1];return n(function(){m.value=a,m.getSnapshot=l,y(m)&&S({inst:m})},[u,a,l]),s(function(){return y(m)&&S({inst:m}),u(function(){y(m)&&S({inst:m})})},[u]),i(a),a}function y(u){var l=u.getSnapshot;u=u.value;try{var a=l();return!t(u,a)}catch{return!0}}function f(u,l){return l()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:p;return D.useSyncExternalStore=o.useSyncExternalStore!==void 0?o.useSyncExternalStore:d,D}var k={};/**
|
|
22
20
|
* @license React
|
|
23
21
|
* use-sync-external-store-shim.development.js
|
|
24
22
|
*
|
|
@@ -26,7 +24,7 @@ Original error: ${i}`,{cause:f})}else c[l]=u;const{defaultId:y,form:p}=t;if(p){c
|
|
|
26
24
|
*
|
|
27
25
|
* This source code is licensed under the MIT license found in the
|
|
28
26
|
* LICENSE file in the root directory of this source tree.
|
|
29
|
-
*/var te;function
|
|
27
|
+
*/var te;function Ae(){return te||(te=1,process.env.NODE_ENV!=="production"&&(function(){function o(a,c){return a===c&&(a!==0||1/a===1/c)||a!==a&&c!==c}function e(a,c){d||s.startTransition===void 0||(d=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var m=c();if(!u){var S=c();n(m,S)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),u=!0)}S=i({inst:{value:m,getSnapshot:c}});var _=S[0].inst,w=S[1];return y(function(){_.value=m,_.getSnapshot=c,t(_)&&w({inst:_})},[a,m,c]),p(function(){return t(_)&&w({inst:_}),a(function(){t(_)&&w({inst:_})})},[a]),f(m),m}function t(a){var c=a.getSnapshot;a=a.value;try{var m=c();return!n(a,m)}catch{return!0}}function r(a,c){return c()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var s=N,n=typeof Object.is=="function"?Object.is:o,i=s.useState,p=s.useEffect,y=s.useLayoutEffect,f=s.useDebugValue,d=!1,u=!1,l=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?r:e;k.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:l,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()),k}var re;function Se(){return re||(re=1,process.env.NODE_ENV==="production"?j.exports=Fe():j.exports=Ae()),j.exports}/**
|
|
30
28
|
* @license React
|
|
31
29
|
* use-sync-external-store-shim/with-selector.production.js
|
|
32
30
|
*
|
|
@@ -34,7 +32,7 @@ Original error: ${i}`,{cause:f})}else c[l]=u;const{defaultId:y,form:p}=t;if(p){c
|
|
|
34
32
|
*
|
|
35
33
|
* This source code is licensed under the MIT license found in the
|
|
36
34
|
* LICENSE file in the root directory of this source tree.
|
|
37
|
-
*/var ne;function Ne(){if(ne)return
|
|
35
|
+
*/var ne;function Ne(){if(ne)return L;ne=1;var o=N,e=Se();function t(f,d){return f===d&&(f!==0||1/f===1/d)||f!==f&&d!==d}var r=typeof Object.is=="function"?Object.is:t,s=e.useSyncExternalStore,n=o.useRef,i=o.useEffect,p=o.useMemo,y=o.useDebugValue;return L.useSyncExternalStoreWithSelector=function(f,d,u,l,a){var c=n(null);if(c.current===null){var m={hasValue:!1,value:null};c.current=m}else m=c.current;c=p(function(){function _(g){if(!w){if(w=!0,b=g,g=l(g),a!==void 0&&m.hasValue){var v=m.value;if(a(v,g))return O=v}return O=g}if(v=O,r(b,g))return v;var E=l(g);return a!==void 0&&a(v,E)?(b=g,v):(b=g,O=E)}var w=!1,b,O,T=u===void 0?null:u;return[function(){return _(d())},T===null?void 0:function(){return _(T())}]},[d,u,l,a]);var S=s(f,c[0],c[1]);return i(function(){m.hasValue=!0,m.value=S},[S]),y(S),S},L}var M={};/**
|
|
38
36
|
* @license React
|
|
39
37
|
* use-sync-external-store-shim/with-selector.development.js
|
|
40
38
|
*
|
|
@@ -42,5 +40,5 @@ Original error: ${i}`,{cause:f})}else c[l]=u;const{defaultId:y,form:p}=t;if(p){c
|
|
|
42
40
|
*
|
|
43
41
|
* This source code is licensed under the MIT license found in the
|
|
44
42
|
* LICENSE file in the root directory of this source tree.
|
|
45
|
-
*/var se;function
|
|
43
|
+
*/var se;function xe(){return se||(se=1,process.env.NODE_ENV!=="production"&&(function(){function o(f,d){return f===d&&(f!==0||1/f===1/d)||f!==f&&d!==d}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=N,t=Se(),r=typeof Object.is=="function"?Object.is:o,s=t.useSyncExternalStore,n=e.useRef,i=e.useEffect,p=e.useMemo,y=e.useDebugValue;M.useSyncExternalStoreWithSelector=function(f,d,u,l,a){var c=n(null);if(c.current===null){var m={hasValue:!1,value:null};c.current=m}else m=c.current;c=p(function(){function _(g){if(!w){if(w=!0,b=g,g=l(g),a!==void 0&&m.hasValue){var v=m.value;if(a(v,g))return O=v}return O=g}if(v=O,r(b,g))return v;var E=l(g);return a!==void 0&&a(v,E)?(b=g,v):(b=g,O=E)}var w=!1,b,O,T=u===void 0?null:u;return[function(){return _(d())},T===null?void 0:function(){return _(T())}]},[d,u,l,a]);var S=s(f,c[0],c[1]);return i(function(){m.hasValue=!0,m.value=S},[S]),y(S),S},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()),M}var oe;function Ie(){return oe||(oe=1,process.env.NODE_ENV==="production"?C.exports=Ne():C.exports=xe()),C.exports}var Le=Ie();function H(o,e){h(typeof e=="string",`The target step must be a string, was ${typeof e}`);const{as:t,isValidStepNumber:r}=o.stepSchema.steps,n=new Intl.ListFormat("en",{type:"disjunction",style:"long"}).format(t("array.string.untyped"));h(pe.test(e),`The target step must match the following format: "step{number}". Available steps are ${n}`);const i=Number.parseInt(e.replace("step",""));return h(r(i),`The step number "${i}" is not a valid step number. Valid step numbers include ${n}`,TypeError),i}function be(o){function e(t){return Le.useSyncExternalStoreWithSelector(o.subscribe,()=>o.getSnapshot(),()=>o.getSnapshot(),r=>{if(typeof t=="object"){const s=H(r,t.targetStep);return r.stepSchema.get({step:s}).data}return typeof t=="function"?t(r):r})}return e}function De(o,e){const t=be(o);return typeof e=="object"||typeof e=="function"?t(e):t()}function ie(o){return function(e){return(t=>e(o,t))}}function ke(o){const e=be(o);function t(p){const{targetStep:y,notFoundMessage:f,isDataGuaranteed:d}=p,u=e({targetStep:y}),l=f?i({targetStep:y},f):a=>R.jsxs("div",{...a,children:["No data found for step ",String(y)]});return d?{data:u,NoCurrentData:l}:G.hasData(u)?{data:u,hasData:!0,NoCurrentData:l}:{data:void 0,hasData:!1,NoCurrentData:l}}function r(p){const y=e(S=>S.stepSchema.steps.value.length),{targetStep:f,maxProgressValue:d=100,totalSteps:u=y,progressTextTransformer:l}=p,a=H(o,f),c=a/u*d,m=l?n({targetStep:f,maxProgressValue:d,totalSteps:u},l):S=>R.jsxs("div",{...S,children:["Step ",a,"/",u]});return{value:c,maxProgressValue:d,ProgressText:m}}function s(p){const f=e(u=>u.storage).get(),d=!!(f&&typeof f=="object"&&Object.keys(f).length>0);return p?p(d):d}function n(p,y){const f=o.getSnapshot().stepSchema.steps.value.length,{targetStep:d,maxProgressValue:u=100,totalSteps:l=f}=p;return ie({targetStep:d,maxProgressValue:u,totalSteps:l})(y)}function i(p,y){return H(o,p.targetStep),ie(p)(y)}return{useMultiStepFormData:e,useCurrentStepData:t,useProgress:r,useCanRestartForm:s,withProgressText:n,withNoStepDataFound:i}}exports.MultiStepFormSchema=ye;exports.MultiStepFormStepSchema=me;exports.createDefaultValues=he;exports.createMultiStepFormContext=ke;exports.createMultiStepFormSchema=Ve;exports.useMultiStepFormData=De;
|
|
46
44
|
//# sourceMappingURL=index.cjs.map
|