react-simple-formkit 2.1.9 → 2.2.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/README.md +11 -5
- package/dist/react-simple-formkit.js +4 -4
- package/dist/react-simple-formkit.mjs +345 -344
- package/dist/react-simple-formkit.umd.js +4 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -189,10 +189,13 @@ return (
|
|
|
189
189
|
|
|
190
190
|
State updates only when observed via `watch()`, `useWatch()`, `subscribe()`, or by tracking changes through the Form component's `onChange`, `onBlur` callbacks. You can watch Values, Form States, Field States, and Errors through the same interface.
|
|
191
191
|
|
|
192
|
-
-
|
|
193
|
-
-
|
|
194
|
-
-
|
|
195
|
-
-
|
|
192
|
+
- [watch(name)](#watch) will trigger a re-render at the form level.
|
|
193
|
+
- [useWatch({ name })](#usewatch) will trigger a re-render only in the component where it is called.
|
|
194
|
+
- [actions.subscribe(name, callback)](#subscribe) is just a handler callback that is called when watched values change.
|
|
195
|
+
- [onChange](#form) is just a handler callback that is called when field values change.
|
|
196
|
+
- [onBlur](#form) is just a handler callback that is called when field blurred.
|
|
197
|
+
- [actions.subscribeChange(callback)](#useform) subscribe onChange callback instead of passing `onChange` in [Form](#form) component.
|
|
198
|
+
- [actions.subscribeBlur(callback)](#useform) subscribe onBlur callback instead of passing `onBlur` in [Form](#form) component.
|
|
196
199
|
|
|
197
200
|
> **Rule\*:** By default, onBlur works automatically for uncontrolled fields. However, for controlled fields, you must explicitly pass the onBlur prop when rendering the field. For captured fields, use actions.triggerFieldBlur(fieldName) to manually trigger the onBlur event.
|
|
198
201
|
|
|
@@ -358,7 +361,7 @@ return (
|
|
|
358
361
|
<Form control={control} onChange={console.log}>
|
|
359
362
|
<input name="input1" />
|
|
360
363
|
{input1Error && <span className="error-message">{input1Error}</span>}
|
|
361
|
-
<button type="button" onClick={() => actions.setError("
|
|
364
|
+
<button type="button" onClick={() => actions.setError("input1", "This is error message")}>
|
|
362
365
|
Set Error
|
|
363
366
|
</button>
|
|
364
367
|
<button type="submit" disabled={!isDirty}>
|
|
@@ -397,6 +400,8 @@ Return:
|
|
|
397
400
|
- `actions.resetField()`: `(name: String) => void`
|
|
398
401
|
- `actions.clearError()`: `(name: String | Array) => void`
|
|
399
402
|
- `actions.clearErrors()`: `() => void`
|
|
403
|
+
- `actions.subscribeChange()`: `(callback) => unsubscribe: Function()`
|
|
404
|
+
- `actions.subscribeBlur()`: `(callback) => unsubscribe: Function()`
|
|
400
405
|
- `actions.getNumberFields()`: `() => Array`
|
|
401
406
|
- `actions.getDefaultValues()`: `() => Object`
|
|
402
407
|
|
|
@@ -407,6 +412,7 @@ Generic props:
|
|
|
407
412
|
- `control`: received from useForm()
|
|
408
413
|
- `onSubmit`: `(currentValues) => {}` called when the form is submitted via a button with `type='submit'`
|
|
409
414
|
- `onChange`: `(name, value, currentValues) => {}` called when any field value changes
|
|
415
|
+
- `onBlur`: `(name, value, currentValues) => {}` called when any field blurred
|
|
410
416
|
|
|
411
417
|
## Controller
|
|
412
418
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react");var ue={exports:{}},ee={};/**
|
|
2
2
|
* @license React
|
|
3
3
|
* react-jsx-runtime.production.js
|
|
4
4
|
*
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* This source code is licensed under the MIT license found in the
|
|
8
8
|
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var
|
|
9
|
+
*/var le;function Re(){if(le)return ee;le=1;var n=Symbol.for("react.transitional.element"),o=Symbol.for("react.fragment");function l(g,E,h){var i=null;if(h!==void 0&&(i=""+h),E.key!==void 0&&(i=""+E.key),"key"in E){h={};for(var C in E)C!=="key"&&(h[C]=E[C])}else h=E;return E=h.ref,{$$typeof:n,type:g,key:i,ref:E!==void 0?E:null,props:h}}return ee.Fragment=o,ee.jsx=l,ee.jsxs=l,ee}var re={};/**
|
|
10
10
|
* @license React
|
|
11
11
|
* react-jsx-runtime.development.js
|
|
12
12
|
*
|
|
@@ -14,9 +14,9 @@
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var
|
|
17
|
+
*/var ie;function ke(){return ie||(ie=1,process.env.NODE_ENV!=="production"&&function(){function n(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===G?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case d:return"Fragment";case Y:return"Profiler";case A:return"StrictMode";case te:return"Suspense";case se:return"SuspenseList";case j:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case b:return"Portal";case q:return(e.displayName||"Context")+".Provider";case W:return(e._context.displayName||"Context")+".Consumer";case J:var u=e.render;return e=e.displayName,e||(e=u.displayName||u.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ne:return u=e.displayName||null,u!==null?u:n(e.type)||"Memo";case z:u=e._payload,e=e._init;try{return n(e(u))}catch{}}return null}function o(e){return""+e}function l(e){try{o(e);var u=!1}catch{u=!0}if(u){u=console;var R=u.error,y=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return R.call(u,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",y),o(e)}}function g(e){if(e===d)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===z)return"<...>";try{var u=n(e);return u?"<"+u+">":"<...>"}catch{return"<...>"}}function E(){var e=N.A;return e===null?null:e.getOwner()}function h(){return Error("react-stack-top-frame")}function i(e){if(M.call(e,"key")){var u=Object.getOwnPropertyDescriptor(e,"key").get;if(u&&u.isReactWarning)return!1}return e.key!==void 0}function C(e,u){function R(){H||(H=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",u))}R.isReactWarning=!0,Object.defineProperty(e,"key",{get:R,configurable:!0})}function v(){var e=n(this.type);return X[e]||(X[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function T(e,u,R,y,O,w,B,I){return R=w.ref,e={$$typeof:a,type:e,key:u,props:w,_owner:O},(R!==void 0?R:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:v}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:B}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:I}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function c(e,u,R,y,O,w,B,I){var p=u.children;if(p!==void 0)if(y)if(V(p)){for(y=0;y<p.length;y++)m(p[y]);Object.freeze&&Object.freeze(p)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else m(p);if(M.call(u,"key")){p=n(e);var x=Object.keys(u).filter(function(oe){return oe!=="key"});y=0<x.length?"{key: someKey, "+x.join(": ..., ")+": ...}":"{key: someKey}",Q[p+y]||(x=0<x.length?"{"+x.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
18
18
|
let props = %s;
|
|
19
19
|
<%s {...props} />
|
|
20
20
|
React keys must be passed directly to JSX without using spread:
|
|
21
21
|
let props = %s;
|
|
22
|
-
<%s key={someKey} {...props} />`,p,k,P,k),Z[k+p]=!0)}if(k=null,R!==void 0&&(l(R),k=""+R),E(u)&&(l(u.key),k=""+u.key),"key"in u){R={};for(var Q in u)Q!=="key"&&(R[Q]=u[Q])}else R=u;return k&&y(R,typeof e=="function"?e.displayName||e.name||"Unknown":e),T(e,k,w,O,b(),R,Y,I)}function d(e){typeof e=="object"&&e!==null&&e.$$typeof===a&&e._store&&(e._store.validated=1)}var f=s,a=Symbol.for("react.transitional.element"),i=Symbol.for("react.portal"),m=Symbol.for("react.fragment"),A=Symbol.for("react.strict_mode"),$=Symbol.for("react.profiler"),D=Symbol.for("react.consumer"),U=Symbol.for("react.context"),q=Symbol.for("react.forward_ref"),te=Symbol.for("react.suspense"),se=Symbol.for("react.suspense_list"),ne=Symbol.for("react.memo"),J=Symbol.for("react.lazy"),j=Symbol.for("react.activity"),z=Symbol.for("react.client.reference"),x=f.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W=Object.prototype.hasOwnProperty,N=Array.isArray,V=console.createTask?console.createTask:function(){return null};f={"react-stack-bottom-frame":function(e){return e()}};var G,H={},X=f["react-stack-bottom-frame"].bind(f,h)(),C=V(g(h)),Z={};re.Fragment=m,re.jsx=function(e,u,R,p,O){var w=1e4>x.recentlyCreatedOwnerStacks++;return c(e,u,R,!1,p,O,w?Error("react-stack-top-frame"):X,w?V(g(e)):C)},re.jsxs=function(e,u,R,p,O){var w=1e4>x.recentlyCreatedOwnerStacks++;return c(e,u,R,!0,p,O,w?Error("react-stack-top-frame"):X,w?V(g(e)):C)}}()),re}var le;function he(){return le||(le=1,process.env.NODE_ENV==="production"?oe.exports=Ee():oe.exports=ge()),oe.exports}var ie=he();const S=()=>{},be=s.createContext({ref:null,watch:S,actions:{reset:S,resetField:S,setValue:S,getValues:S,getErrors:S,getFieldStates:S,getFormStates:S,setError:S,clearError:S,clearErrors:S,checkValidity:S,getNumberFields:S,getFieldValidity:S,getDefaultValues:S,setFieldState:S,resetFieldState:S,getControlledFields:S},registerController:S,registerHookWatcher:S,lastReloadedAt:S,loadFormValues:S,getWatchValue:S,channels:{}}),ue=()=>s.useContext(be),Re=({id:n,control:o,method:l,action:g,children:b,onSubmit:h=()=>{},onInput:E=()=>{},onChange:y=()=>{},onBlur:v=()=>{},onReset:T=()=>{},numberFields:c=[],className:d,...f})=>(s.useEffect(()=>{const a=o.channels.subscribe("onChange",y),i=o.channels.subscribe("onBlur",v);return()=>{a(),i()}},[]),ie.jsx(be.Provider,{value:o,children:ie.jsx("form",{id:n,ref:o.ref,action:g,method:l,className:d,onInput:E,onSubmit:a=>{l||a.preventDefault();const i=o.loadFormValues();h(i)},onChange:a=>{const i=a.target.name;o.actions.getControlledFields().has(i)||o.actions.setValue(i,a.target.value)},onBlur:a=>{const i=a.target.name;if(o.actions.getControlledFields().has(i))return;const m=a.target.value;o.channels.publish("onBlur",i,m,o.actions.getValues())},onReset:a=>{o.actions.reset(),T(a)},...f,children:b},o.lastReloadedAt)})),de=({control:n,name:o,compute:l})=>{const{getWatchValue:g,registerHookWatcher:b}=n||ue(),h=g({name:o,compute:l}),[E,y]=s.useState(h);return s.useEffect(()=>{const v=b({name:o,compute:l,value:E,setValue:y});return()=>v.forEach(T=>T())},[]),E},me=({name:n,defaultValue:o})=>{const{actions:l,registerController:g,channels:b}=ue(),h=s.useRef(),E=l.getDefaultValues()[n]||o,[y,v]=s.useState(E),T=de({name:`fieldStates.${n}.customState`}),c=s.useCallback(a=>{l.setFieldState(n,"customState",a)},[]),d=s.useCallback((a,{shouldDirty:i=!0,shouldOnChange:m=!0}={})=>{v(a),l.setValue(n,a,{shouldDirty:i,shouldOnChange:m})},[l.setValue]),f=s.useCallback(()=>{b.publish("onBlur",n,y,l.getValues())},[]);return s.useEffect(()=>g(n,v),[]),{ref:h,name:n,defaultValue:E,value:y,onChange:d,onBlur:f,customState:T,setCustomState:c}},ke=({name:n,defaultValue:o,render:l=({ref:g,name:b,defaultValue:h,value:E,onChange:y,onBlur:v,customState:T,setCustomState:c})=>null})=>{const g=me({name:n,defaultValue:o});return l(g)},Se=["errors","fieldStates","formState"],L=n=>Se.some(o=>n.startsWith(o))?n:"values."+n,Ce=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"],fe=n=>{typeof n.setCustomValidity=="function"&&n.setCustomValidity("");let o=n.validity,l=Ce.find(g=>o[g]);if(l)return{type:l,message:n.validationMessage}};class ye{constructor(){this.events=new Map}getEvents(){return this.events}subscribe(o,l){return this.events.has(o)||this.events.set(o,new Set),this.events.get(o).add(l),()=>{var g;return(g=this.events.get(o))==null?void 0:g.delete(l)}}publish(o,...l){const g=this.events.get(o);g&&g.forEach(b=>b(...l)),this.events.forEach((b,h)=>{o.includes(h)&&b.forEach(E=>E(...l))})}reset(){this.events.clear()}}const ve=()=>{const n=s.useRef(new ye),o=s.useCallback((b,...h)=>{n.current.publish(b,...h)},[]),l=s.useCallback((b,h)=>n.current.subscribe(b,h),[]),g=s.useCallback(()=>{n.current.reset()},[]);return{publish:o,subscribe:l,reset:g}},pe=()=>{const[n,o]=s.useState(),l=s.useCallback(()=>o(new Date().toString()),[]);return[n,l]},Fe=()=>{const[,n]=s.useState({});return s.useCallback(()=>n({}),[])},Te=({channels:n,getValues:o,getErrors:l,getFieldStates:g,getFormState:b})=>{const h=Fe(),E=s.useCallback(({name:c,compute:d})=>{if(typeof d=="function")return d(o());if(Array.isArray(c)){const f={};return c.forEach(a=>{f[a]=E({name:a})}),f}return c.split(".").reduce((f,a)=>f&&f[a]!==void 0?f[a]:void 0,{...o(),errors:{...l()},formState:{...b()},fieldStates:{...g()}})},[]),y=s.useCallback(c=>{if(!c)return n.subscribe("values",()=>h()),o();if(typeof c=="string"){const d=L(c);return n.subscribe(d,()=>h()),E({name:c})}if(Array.isArray(c)){const d={};return c.forEach(f=>{const a=L(f);n.subscribe(a,()=>h()),d[f]=E({name:f})}),{...d}}throw new Error("Parameters of watch must be string or array of string")},[]),v=s.useCallback(({name:c,compute:d,value:f,setValue:a})=>{if(typeof d=="function")return[n.subscribe("values",()=>{const m=E({compute:d});a(m)})];if(!c)return[n.subscribe("values",()=>{a(o())})];if(typeof c=="string"){const i=L(c);return[n.subscribe(i,()=>{const A=E({name:c});a(A)})]}if(Array.isArray(c)){const i=E({name:c}),m=[];return c.forEach(A=>{const $=L(A),D=n.subscribe($,()=>{const U=E({name:A});i[A]=U,a({...i})});m.push(D)}),m}throw new Error("Parameters of name must be string or array of string or compute must be a function")},[]),T=s.useCallback((c,d)=>{if(!c)return n.subscribe("values",d);if(typeof c=="string"){const f=L(c);return n.subscribe(f,d)}if(Array.isArray(c)){const f={},a=[];return c.forEach(i=>{const m=L(i),A=n.subscribe(m,()=>{f[i]=E({name:i}),d({...f})});a.push(A)}),a}throw new Error("Parameters of name must be string or array of string")},[n]);return{watch:y,registerHookWatcher:v,getWatchValue:E,subscribe:T}},_e=[],we={},Ae=({numberFields:n=_e,defaultValues:o=we,shouldUnRegister:l=!1,shouldConvertNumber:g=!1}={})=>{const[b,h]=pe(),E=s.useRef(),y=s.useRef(!1),v=s.useRef(!1),T=s.useRef(n),c=s.useRef(new Map),d=s.useRef({}),f=s.useRef({}),a=s.useRef(o),i=s.useRef(o),m=ve(),A=s.useCallback(()=>{f.current=Object.keys(i.current).reduce((r,t)=>({...r,[t]:{isError:!1,isDirty:!1,isTouched:!1,customState:null}}),{})},[]),$=s.useCallback((r={})=>{i.current={...i.current,...r},a.current={...i.current},c.current.forEach((t,F)=>{t(i.current[F])}),y.current=!1,d.current={},T.current=n,c.current=new Map,m.reset(),A(),n.length>0&&(g=!0),h()},[]),D=s.useCallback(()=>{const r=Object.fromEntries(new FormData(E.current));return c.current.forEach((F,_)=>{r[_]=a.current[_]}),g&&T.current.forEach(F=>r.hasOwnProperty(F)&&(r[F]=Number(r[F])||0)),r},[]),U=s.useCallback(()=>!!Object.values(W()).find(r=>r.isDirty),[]),q=s.useCallback(()=>!!Object.values(x()).find(r=>!!r),[]),te=s.useCallback(r=>fe(r.target),[]),se=s.useCallback(()=>i.current,[]),ne=s.useCallback(()=>T.current,[]),J=s.useCallback(()=>c.current,[]),j=s.useCallback((r,t)=>t?Array.isArray(t)?t.map(F=>r[F]):r[t]:{...r},[]),z=s.useCallback(r=>j(a.current,r),[j]),x=s.useCallback(r=>j(d.current,r),[j]),W=s.useCallback(r=>j(f.current,r),[j]),N=s.useCallback(r=>j({isDirty:y.current,isError:v.current,errorFields:Object.keys(d.current).filter(t=>!!d.current[t]),dirtyFields:Object.keys(f.current).filter(t=>f.current[t].isDirty),touchedFields:Object.keys(f.current).filter(t=>f.current[t].isTouched)},r),[j]),{watch:V,registerHookWatcher:G,getWatchValue:H,subscribe:X}=Te({channels:m,getValues:z,getErrors:x,getFieldStates:W,getFormState:N}),C=s.useCallback((r,t,F)=>{const _=f.current[r];_[t]!==F&&(f.current[r]={..._,[t]:F},m.publish(`fieldStates.${r}.${t}`,F),t==="isError"&&m.publish("formState.errorFields",N("errorFields")),t==="isDirty"&&m.publish("formState.dirtyFields",N("dirtyFields")),t==="isTouched"&&m.publish("formState.touchedFields",N("touchedFields")))},[]),Z=s.useCallback(r=>{C(r,"isError",!1),C(r,"isDirty",!1),C(r,"isTouched",!1),C(r,"customState",null)},[C]),e=s.useCallback((r,t)=>{if(d.current[r]===t)return;d.current[r]=t,C(r,"isError",!!t),m.publish(`errors.${r}`,t);const _=q();v.current!==_&&(v.current=_,m.publish("formState.isError",_))},[C]),u=s.useCallback(r=>{if(!d.current[r])return;d.current[r]=null,C(r,"isError",!1),m.publish(`errors.${r}`,null);const t=q();v.current!==t&&(v.current=t,m.publish("formState.isError",t))},[C]),R=s.useCallback(()=>{if(Object.keys(d.current)===0)return;Object.keys(d.current).forEach(t=>u(t)),d.current={};const r=q();v.current!==r&&(v.current=r,m.publish("formState.isError",r))},[]),p=s.useCallback(r=>{const t=fe(r.target);t?e(r.target.name,t):u(r.target.name)},[e,u]),O=s.useCallback((r,t,{shouldDirty:F=!0,shouldOnChange:_=!0}={})=>{if(t===a.current[r])return;g&&T.current.includes(r)&&(t=Number(t)||void 0),C(r,"isTouched",!0);const K=t!==i.current[r];F&&f.current[r].isDirty!==K&&C(r,"isDirty",K);const M=U();y.current!==M&&(y.current=M,m.publish("formState.isDirty",M)),a.current[r]=t;const B=c.current.get(r);B&&B(t),m.publish(`values.${r}`,t,{shouldDirty:F,shouldOnChange:_}),_&&m.publish("onChange",r,t,a.current)},[C]),w=s.useCallback((r,t)=>(c.current.set(r,t),()=>{l&&c.current.delete(r)}),[]),Y=s.useCallback((r,{keepError:t,keepDirty:F,keepTouched:_,keepCustomState:K,defaultValue:M})=>{const B=c.current.get(r);if(!B)throw new Error(`Cannot reset "${r}" because it's uncontrolled field`);i.current[r]=M,a.current[r]=M,B&&B(M),t||u(r),F||C(r,"isDirty",!1),_||C(r,"isTouched",!1),K||C(r,"customState",null)},[u,C]),I=s.useCallback((r,t=k.getValues(r))=>{m.publish("onBlur",r,t,k.getValues())},[]),k=s.useMemo(()=>({subscribe:X,reset:$,resetField:Y,setValue:O,getValues:z,getErrors:x,getFieldStates:W,getFormState:N,setError:e,clearError:u,clearErrors:R,checkValidity:p,getNumberFields:ne,getFieldValidity:te,getDefaultValues:se,setFieldState:C,triggerFieldBlur:I,resetFieldState:Z,getControlledFields:J}),[X,$,Y,O,z,x,W,N,e,u,R,p,ne,te,se,C,Z,I,J]),P=s.useMemo(()=>({ref:E,watch:V,actions:k,registerController:w,registerHookWatcher:G,lastReloadedAt:b,loadFormValues:D,getWatchValue:H,channels:m}),[E,V,k,w,G,b,D,H,m]),Q=s.useMemo(()=>({control:P,actions:k,watch:V}),[b,P,k,V]);return s.useLayoutEffect(()=>{if([...E.current.querySelectorAll("[name]")].forEach(t=>{!t.defaultValue&&i.current[t.name]&&(t.defaultValue=i.current[t.name]),t.type==="number"&&!T.current.includes(t.name)&&T.current.push(t.name)}),E.current){const t=D();a.current={...t},i.current={...t}}},[b]),s.useLayoutEffect(()=>{A()},[]),Q};exports.Controller=ke;exports.Form=Re;exports.useController=me;exports.useForm=Ae;exports.useFormContext=ue;exports.useWatch=de;
|
|
22
|
+
<%s key={someKey} {...props} />`,y,p,x,p),Q[p+y]=!0)}if(p=null,R!==void 0&&(l(R),p=""+R),i(u)&&(l(u.key),p=""+u.key),"key"in u){R={};for(var P in u)P!=="key"&&(R[P]=u[P])}else R=u;return p&&C(R,typeof e=="function"?e.displayName||e.name||"Unknown":e),T(e,p,w,O,E(),R,B,I)}function m(e){typeof e=="object"&&e!==null&&e.$$typeof===a&&e._store&&(e._store.validated=1)}var f=t,a=Symbol.for("react.transitional.element"),b=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),A=Symbol.for("react.strict_mode"),Y=Symbol.for("react.profiler"),W=Symbol.for("react.consumer"),q=Symbol.for("react.context"),J=Symbol.for("react.forward_ref"),te=Symbol.for("react.suspense"),se=Symbol.for("react.suspense_list"),ne=Symbol.for("react.memo"),z=Symbol.for("react.lazy"),j=Symbol.for("react.activity"),G=Symbol.for("react.client.reference"),N=f.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,M=Object.prototype.hasOwnProperty,V=Array.isArray,D=console.createTask?console.createTask:function(){return null};f={"react-stack-bottom-frame":function(e){return e()}};var H,X={},Z=f["react-stack-bottom-frame"].bind(f,h)(),S=D(g(h)),Q={};re.Fragment=d,re.jsx=function(e,u,R,y,O){var w=1e4>N.recentlyCreatedOwnerStacks++;return c(e,u,R,!1,y,O,w?Error("react-stack-top-frame"):Z,w?D(g(e)):S)},re.jsxs=function(e,u,R,y,O){var w=1e4>N.recentlyCreatedOwnerStacks++;return c(e,u,R,!0,y,O,w?Error("react-stack-top-frame"):Z,w?D(g(e)):S)}}()),re}var fe;function Se(){return fe||(fe=1,process.env.NODE_ENV==="production"?ue.exports=Re():ue.exports=ke()),ue.exports}var be=Se();const k=()=>{},me=t.createContext({ref:null,watch:k,actions:{reset:k,resetField:k,setValue:k,getValues:k,getErrors:k,getFieldStates:k,getFormStates:k,setError:k,clearError:k,clearErrors:k,checkValidity:k,getNumberFields:k,getFieldValidity:k,getDefaultValues:k,setFieldState:k,resetFieldState:k,getControlledFields:k},registerController:k,registerHookWatcher:k,lastReloadedAt:k,loadFormValues:k,getWatchValue:k,channels:{}}),ce=()=>t.useContext(me),Ce=({id:n,control:o,method:l,action:g,children:E,onSubmit:h=()=>{},onInput:i=()=>{},onChange:C=()=>{},onBlur:v=()=>{},onReset:T=()=>{},numberFields:c=[],className:m,...f})=>(t.useEffect(()=>{const a=o.channels.subscribe("onChange",C),b=o.channels.subscribe("onBlur",v);return()=>{a(),b()}},[]),be.jsx(me.Provider,{value:o,children:be.jsx("form",{id:n,ref:o.ref,action:g,method:l,className:m,onInput:i,onSubmit:a=>{l||a.preventDefault();const b=o.loadFormValues();h(b)},onChange:a=>{const b=a.target.name;o.actions.getControlledFields().has(b)||o.actions.setValue(b,a.target.value)},onBlur:a=>{const b=a.target.name;if(o.actions.getControlledFields().has(b))return;const d=a.target.value;o.channels.publish("onBlur",b,d,o.actions.getValues())},onReset:a=>{o.actions.reset(),T(a)},...f,children:E},o.lastReloadedAt)})),Ee=({control:n,name:o,compute:l})=>{const{getWatchValue:g,registerHookWatcher:E}=n||ce(),h=g({name:o,compute:l}),[i,C]=t.useState(h);return t.useEffect(()=>{const v=E({name:o,compute:l,value:i,setValue:C});return()=>v.forEach(T=>T())},[]),i},ge=({name:n,defaultValue:o})=>{const{actions:l,registerController:g,channels:E}=ce(),h=t.useRef(),i=l.getDefaultValues()[n]||o||"",[C,v]=t.useState(i),T=Ee({name:`fieldStates.${n}.customState`}),c=t.useCallback(a=>{l.setFieldState(n,"customState",a)},[]),m=t.useCallback((a,{shouldDirty:b=!0,shouldOnChange:d=!0}={})=>{v(a),l.setValue(n,a,{shouldDirty:b,shouldOnChange:d})},[l.setValue]),f=t.useCallback(()=>{E.publish("onBlur",n,C,l.getValues())},[]);return t.useEffect(()=>g(n,v),[]),{ref:h,name:n,defaultValue:i,value:C,onChange:m,onBlur:f,customState:T,setCustomState:c}},ve=({name:n,defaultValue:o,render:l=({ref:g,name:E,defaultValue:h,value:i,onChange:C,onBlur:v,customState:T,setCustomState:c})=>null})=>{const g=ge({name:n,defaultValue:o});return l(g)},ye=["errors","fieldStates","formState"],U=n=>ye.some(o=>n.startsWith(o))?n:"values."+n,pe=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"],de=n=>{typeof n.setCustomValidity=="function"&&n.setCustomValidity("");let o=n.validity,l=pe.find(g=>o[g]);if(l)return{type:l,message:n.validationMessage}};class Fe{constructor(){this.events=new Map}getEvents(){return this.events}subscribe(o,l){return this.events.has(o)||this.events.set(o,new Set),this.events.get(o).add(l),()=>{var g;return(g=this.events.get(o))==null?void 0:g.delete(l)}}publish(o,...l){const g=this.events.get(o);g&&g.forEach(E=>E(...l)),this.events.forEach((E,h)=>{h!==o&&o.includes(h)&&E.forEach(i=>i(...l))})}reset(){this.events.clear()}}const Te=()=>{const n=t.useRef(new Fe),o=t.useCallback((h,...i)=>{n.current.publish(h,...i)},[]),l=t.useCallback((h,i)=>n.current.subscribe(h,i),[]),g=t.useCallback(()=>n.current.getEvents(),[]),E=t.useCallback(()=>{n.current.reset()},[]);return{publish:o,subscribe:l,reset:E,getEvents:g}},_e=()=>{const[n,o]=t.useState(),l=t.useCallback(()=>o(new Date().toString()),[]);return[n,l]},we=()=>{const[,n]=t.useState({});return t.useCallback(()=>n({}),[])},Ae=({channels:n,getValues:o,getErrors:l,getFieldStates:g,getFormState:E})=>{const h=we(),i=t.useCallback(({name:c,compute:m})=>{if(typeof m=="function")return m(o());if(Array.isArray(c)){const f={};return c.forEach(a=>{f[a]=i({name:a})}),f}return c.split(".").reduce((f,a)=>f&&f[a]!==void 0?f[a]:void 0,{...o(),errors:{...l()},formState:{...E()},fieldStates:{...g()}})},[]),C=t.useCallback(c=>{if(!c)return n.subscribe("values",()=>h()),o();if(typeof c=="string"){const m=U(c);return n.subscribe(m,()=>h()),i({name:c})}if(Array.isArray(c)){const m={};return c.forEach(f=>{const a=U(f);n.subscribe(a,()=>h()),m[f]=i({name:f})}),{...m}}throw new Error("Parameters of watch must be string or array of string")},[]),v=t.useCallback(({name:c,compute:m,value:f,setValue:a})=>{if(typeof m=="function")return[n.subscribe("values",()=>{const d=i({compute:m});a(d)})];if(!c)return[n.subscribe("values",()=>{a(o())})];if(typeof c=="string"){const b=U(c);return[n.subscribe(b,()=>{const A=i({name:c});a(A)})]}if(Array.isArray(c)){const b=i({name:c}),d=[];return c.forEach(A=>{const Y=U(A),W=n.subscribe(Y,()=>{const q=i({name:A});b[A]=q,a({...b})});d.push(W)}),d}throw new Error("Parameters of name must be string or array of string or compute must be a function")},[]),T=t.useCallback((c,m)=>{if(!c)return n.subscribe("values",m);if(typeof c=="string"){const f=U(c);return n.subscribe(f,m)}if(Array.isArray(c)){const f={},a=[];return c.forEach(b=>{const d=U(b),A=n.subscribe(d,()=>{f[b]=i({name:b}),m({...f})});a.push(A)}),a}throw new Error("Parameters of name must be string or array of string")},[n]);return{watch:C,registerHookWatcher:v,getWatchValue:i,subscribe:T}},ae={isError:!1,isDirty:!1,isTouched:!1,customState:null},Oe=[],je={},Pe=({numberFields:n=Oe,defaultValues:o=je,shouldUnRegister:l=!1,shouldConvertNumber:g=!1}={})=>{const[E,h]=_e(),i=t.useRef(),C=t.useRef(!1),v=t.useRef(!1),T=t.useRef(n),c=t.useRef(new Map),m=t.useRef({}),f=t.useRef({}),a=t.useRef({...o}),b=t.useRef({...o}),d=Te(),A=t.useCallback(()=>{f.current=Object.keys(b.current).reduce((r,s)=>({...r,[s]:{...ae}}),{})},[]),Y=t.useCallback((r={})=>{b.current={...b.current,...r},a.current={...b.current},c.current.forEach((s,F)=>{s(b.current[F])}),C.current=!1,m.current={},T.current=n,c.current=new Map,d.reset(),A(),n.length>0&&(g=!0),h()},[]),W=t.useCallback(()=>{const r=Object.fromEntries(new FormData(i.current));return c.current.forEach((F,_)=>{r[_]=a.current[_]}),g&&T.current.forEach(F=>r.hasOwnProperty(F)&&(r[F]=Number(r[F])||0)),r},[]),q=t.useCallback(()=>!!Object.values(M()).find(r=>r.isDirty),[]),J=t.useCallback(()=>!!Object.values(N()).find(r=>!!r),[]),te=t.useCallback(r=>de(r.target),[]),se=t.useCallback(()=>b.current,[]),ne=t.useCallback(()=>T.current,[]),z=t.useCallback(()=>c.current,[]),j=t.useCallback((r,s)=>s?Array.isArray(s)?s.map(F=>r[F]):r[s]:{...r},[]),G=t.useCallback(r=>j(a.current,r),[j]),N=t.useCallback(r=>j(m.current,r),[j]),M=t.useCallback(r=>j(f.current,r),[j]),V=t.useCallback(r=>j({isDirty:C.current,isError:v.current,errorFields:Object.keys(m.current).filter(s=>!!m.current[s]),dirtyFields:Object.keys(f.current).filter(s=>f.current[s].isDirty),touchedFields:Object.keys(f.current).filter(s=>f.current[s].isTouched)},r),[j]),{watch:D,registerHookWatcher:H,getWatchValue:X,subscribe:Z}=Ae({channels:d,getValues:G,getErrors:N,getFieldStates:M,getFormState:V}),S=t.useCallback((r,s,F)=>{const _=f.current[r]||{...ae};_[s]!==F&&(f.current[r]={..._,[s]:F},d.publish(`fieldStates.${r}.${s}`,F),s==="isError"&&d.publish("formState.errorFields",V("errorFields")),s==="isDirty"&&d.publish("formState.dirtyFields",V("dirtyFields")),s==="isTouched"&&d.publish("formState.touchedFields",V("touchedFields")))},[]),Q=t.useCallback(r=>{S(r,"isError",!1),S(r,"isDirty",!1),S(r,"isTouched",!1),S(r,"customState",null)},[S]),e=t.useCallback((r,s)=>{if(m.current[r]===s)return;m.current[r]=s,S(r,"isError",!!s),d.publish(`errors.${r}`,s);const _=J();v.current!==_&&(v.current=_,d.publish("formState.isError",_))},[S]),u=t.useCallback(r=>{if(!m.current[r])return;m.current[r]=null,S(r,"isError",!1),d.publish(`errors.${r}`,null);const s=J();v.current!==s&&(v.current=s,d.publish("formState.isError",s))},[S]),R=t.useCallback(()=>{if(Object.keys(m.current)===0)return;Object.keys(m.current).forEach(s=>u(s)),m.current={};const r=J();v.current!==r&&(v.current=r,d.publish("formState.isError",r))},[]),y=t.useCallback(r=>{const s=de(r.target);s?e(r.target.name,s):u(r.target.name)},[e,u]),O=t.useCallback((r,s,{shouldDirty:F=!0,shouldOnChange:_=!0}={})=>{if(s===a.current[r])return;g&&T.current.includes(r)&&(s=Number(s)||void 0),S(r,"isTouched",!0);const K=s!==b.current[r];F&&f.current[r].isDirty!==K&&S(r,"isDirty",K);const $=q();C.current!==$&&(C.current=$,d.publish("formState.isDirty",$)),a.current[r]=s;const L=c.current.get(r);L&&L(s),d.publish(`values.${r}`,s,{shouldDirty:F,shouldOnChange:_}),_&&d.publish("onChange",r,s,a.current)},[S]),w=t.useCallback((r,s)=>(c.current.set(r,s),f.current[r]={...ae},()=>{l&&c.current.delete(r)}),[]),B=t.useCallback((r,{keepError:s,keepDirty:F,keepTouched:_,keepCustomState:K,defaultValue:$})=>{const L=c.current.get(r);if(!L)throw new Error(`Cannot reset "${r}" because it's uncontrolled field`);b.current[r]=$,a.current[r]=$,L&&L($),s||u(r),F||S(r,"isDirty",!1),_||S(r,"isTouched",!1),K||S(r,"customState",null)},[u,S]),I=t.useCallback((r,s=P.getValues(r))=>{d.publish("onBlur",r,s,P.getValues())},[]),p=t.useCallback(r=>d.subscribe("onChange",r),[]),x=t.useCallback(r=>d.subscribe("onBlur",r),[]),P=t.useMemo(()=>({subscribe:Z,reset:Y,resetField:B,setValue:O,getValues:G,getErrors:N,getFieldStates:M,getFormState:V,setError:e,clearError:u,clearErrors:R,checkValidity:y,getNumberFields:ne,getFieldValidity:te,getDefaultValues:se,setFieldState:S,triggerFieldBlur:I,resetFieldState:Q,getControlledFields:z,subscribeChange:p,subscribeBlur:x}),[Z,Y,B,O,G,N,M,V,e,u,R,y,ne,te,se,S,Q,I,z,p,x]),oe=t.useMemo(()=>({ref:i,watch:D,actions:P,registerController:w,registerHookWatcher:H,lastReloadedAt:E,loadFormValues:W,getWatchValue:X,channels:d}),[i,D,P,w,H,E,W,X,d]),he=t.useMemo(()=>({control:oe,actions:P,watch:D}),[E,oe,P,D]);return t.useLayoutEffect(()=>{if([...i.current.querySelectorAll("[name]")].forEach(s=>{!s.defaultValue&&!c.current.has(s.name)&&b.current[s.name]&&(s.defaultValue=b.current[s.name]),s.type==="number"&&!T.current.includes(s.name)&&T.current.push(s.name)}),i.current){const s=W();a.current={...s},b.current={...s}}},[E]),t.useLayoutEffect(()=>{A()},[]),he};exports.Controller=ve;exports.Form=Ce;exports.useController=ge;exports.useForm=Pe;exports.useFormContext=ce;exports.useWatch=Ee;
|