UNPKG

react-zod-form

Version:

Simple form validation and values transformation.

3 lines (2 loc) 5.16 kB
import{z as e}from"zod";import{useState as t,useEffect as r,useMemo as s,useRef as n}from"react";class i extends Error{constructor(e){super("Unreachable code reached with these details: "+JSON.stringify(e)),this.name=i.name}}let o="This target is not FormFieldElement (HTMLInputElement | HTMLTextAreaElement | RadioNodeList).";class a{#e;get listeners(){return this.#e}listenersOf(e){return this.callbacks[e]?.size??0}on(e,t){this.callbacks[e]??=new Set,this.callbacks[e]?.add(t),this.#e++}off(e,t){this.callbacks[e]?.delete(t),this.#e--}emit(e,...t){let r=this.callbacks[e];if(null!=r)for(let e of r)e(...t)}constructor(){this.callbacks={},this.#e=0}}function l(e){if(e instanceof HTMLInputElement){if(u(e.value))return"true"===e.value.toLowerCase();if("radio"===e.type||"checkbox"===e.type)return"ok"===e.value?e.checked:f(e.value);if(e.files){let t=[...e.files];return e.multiple?t:t[0]}}if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return 0===e.value.length?"":f(e.value);if(e instanceof RadioNodeList){let t=function(e){let t=!0,r=[];for(let s of e)s instanceof HTMLInputElement&&("radio"!==s.type&&(t=!1),!1===s.checked)||"value"in s==!1||r.push(String(s.value));return t?e.value:r}(e);return t instanceof Array?t.map(f):f(t)}throw new i([e,typeof e])}function u(e){return["true","false"].includes(e.toLowerCase())}function c(e){return!!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof RadioNodeList)}function f(e){return isNaN(Number(e))?u(e)?"true"===e.toLowerCase():e:Number(e)}class h{static set(e,t,r){let s=t.split("."),n=s.pop();null!=n&&(s.reduce((e,t)=>e[t]??={},e)[n]=r)}static get(e,t){return String(t).split(".").reduce((e,t)=>e?.[t],e)}}class d{static getFieldName(e){if(e instanceof RadioNodeList){let t=e[0];if("name"in t)return String(t.name);throw Error("Unacceptable RadioNodeList")}return e.name}static getCurrentFieldName(e){let t=e.target??e.currentTarget;if(!c(t))throw TypeError(o);return this.getFieldName(t)}static getValue(e,t,r=!0){let s=e.currentTarget.elements.namedItem(t);if(!c(s))throw TypeError(o);return{name:this.getFieldName(s),value:r?l(s):s.value}}static getAllValues(e,t,r=!0){let s=e.currentTarget.elements,n={};for(let e of t){let t=s.namedItem(String(e));if(!c(t))continue;let i=this.getFieldName(t),o=r?l(t):t.value;h.set(n,i,o)}return n}}class m{constructor(t,r){this.shape=t,this.options=r,this.events=new a,this.object=e.object(t),this.fieldNames=this.getShapeFlatKeys(t),this.fields=this.shapeToFields()}parseCurrentField(e){let t=d.getCurrentFieldName(e);if(""!==t)return this.parseField(e,t)}parseField(t,r){let{name:s,value:n}=d.getValue(t,r,!this.options?.noTransform);try{if(!this.fieldNames.includes(r))return;let t=(function t(r,s){let n=s.shift();if(null==n)throw new i(["currentPath",n]);let o=r.shape[n];if(o instanceof e.ZodOptional){let r=o.unwrap();if(r instanceof e.ZodObject)return t(r,s)}return o instanceof e.ZodObject?t(o,s):o})(this.object,r.split(".")).parse(n,{path:[r]});return this.events.emit("parsed",r),{name:s,value:t}}catch(e){this.emitError(e)}}emitError(t){if(0===this.events.listenersOf("error")||!(t instanceof e.ZodError))throw t;this.events.emit("error",t)}parseAllFields(e){let t=d.getAllValues(e,this.fieldNames,!this.options?.noTransform);try{let e=this.object.parse(t);return this.events.emit("parsedAll"),e}catch(e){this.emitError(e)}}safeParseAllFields(e){let t=d.getAllValues(e,this.fieldNames,!this.options?.noTransform),r=this.object.safeParse(t);return r.success?this.events.emit("parsedAll"):this.events.emit("error",r.error),r}shapeToFields(){let e={};for(let t of this.fieldNames)h.set(e,t,t);return e}getShapeFlatKeys(t,r){return Object.entries(t).reduce((t,[s,n])=>{let i=(r?r+".":"")+s;if(n instanceof e.ZodOptional){let r=n.unwrap();if(r instanceof e.ZodObject)return[...t,...this.getShapeFlatKeys(r.shape,i)]}return n instanceof e.ZodObject?[...t,...this.getShapeFlatKeys(n.shape,i)]:[...t,i]},[])}on(e,t){return this.events.on(e,t),()=>{this.events.off(e,t)}}}function p(e){let[n,i]=t([]);function o(e){i(t=>[...t,...e.issues])}function a(e){i(t=>t.filter(t=>t.path.join(".")!==e))}function l(){i([])}r(()=>e.on("parsed",a),[e]),r(()=>e.on("parsedAll",l),[e]),r(()=>e.on("error",o),[e]);let u=s(()=>{let e={};for(let t of n)h.set(e,t.path.join("."),t.message);return e},[e,n]);return{reportError:o,clearError:l,issues:n,fieldIssues:u,getIssues:function(e){return n.filter(t=>t.path.includes(e))},setIssues:i,addIssue:function(e,t){let r={path:e,code:"custom",message:t};i(e=>[...e,r])},removeIssue:function(...e){let t=e.toString();i(e=>e.filter(e=>e.path.toString()!==t))},addIssues:function(e,t){let r=t.map(t=>({path:e,code:"custom",message:t}));i(e=>[...e,...r])}}}function g(e,r){let s=n(r),[i,o]=t(r),[a,l]=t(!1);function u(){return JSON.stringify(s.current)!==JSON.stringify(i)}return{observe:function(e){s.current={...s.current,...e},l(u())},setDefault:function(e){o(e)},checkIfDirty:u,isDirty:a}}function v(e){return"string"==typeof e?u(e)?"true"===e.toLowerCase():!!Number(e):!!e}export{m as default,v as toBoolean,g as useZodFormDirty,p as useZodFormIssues}; //# sourceMappingURL=index.js.map