react-simple-formkit 2.4.7 → 2.4.8
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 +27 -23
- package/dist/react-simple-formkit.js +1 -22
- package/dist/react-simple-formkit.mjs +382 -661
- package/dist/react-simple-formkit.umd.js +1 -22
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
[](https://github.com/huynguyen294/react-simple-formkit/blob/main/LICENSE)
|
|
6
6
|
[](https://www.npmjs.com/package/react-simple-formkit)
|
|
7
7
|
|
|
8
|
-
A
|
|
8
|
+
A flexible toolkit for building your own form management system in React.
|
|
9
|
+
Unlike traditional form libraries that provide a rigid, all-in-one solution, React Simple FormKit gives you a powerful **kit** of primitives — unified state observation (via `watch`, `useWatch`, `subscribe`), unlimited custom states, and high-performance uncontrolled-first architecture — so you can build a form system that fits your project, without adapting your project to the library.
|
|
9
10
|
|
|
10
11
|
# Table of Contents
|
|
11
12
|
|
|
@@ -13,6 +14,7 @@ A lightweight library for managing forms as uncontrolled. State updates only whe
|
|
|
13
14
|
- [Highlights](#highlights)
|
|
14
15
|
- [Features](#features)
|
|
15
16
|
- [Core concepts](#core-concepts)
|
|
17
|
+
- [State Model](#state-model)
|
|
16
18
|
- [Input Field Modes](#input-field-modes)
|
|
17
19
|
- [Watching for updates](#watching-for-updates)
|
|
18
20
|
- [The Power of watch (Unified Observation)](#the-power-of-watch-unified-observation)
|
|
@@ -69,7 +71,7 @@ return (
|
|
|
69
71
|
|
|
70
72
|
# Highlights
|
|
71
73
|
|
|
72
|
-
- 🪶 **Lightweight** — ~
|
|
74
|
+
- 🪶 **Lightweight** — ~15KB, zero dependencies, supports React 17, 18, and 19
|
|
73
75
|
- 📦 **Easy data collection** — Automatically collects all input values including nested objects, just by using the `name` attribute
|
|
74
76
|
- 📊 **Comprehensive state management** — Track isDirty, isTouched, errors at both form level and individual field level
|
|
75
77
|
- 🧠 **Unified Observation** — One `watch()` API for values, errors, formState, and fieldStates using dot-notation syntax
|
|
@@ -125,6 +127,18 @@ All three use the same unified dot-notation name format to observe values, error
|
|
|
125
127
|
|
|
126
128
|
# Core concepts
|
|
127
129
|
|
|
130
|
+
## State Model
|
|
131
|
+
|
|
132
|
+
React Simple FormKit consolidates common form states into **4 core objects**:
|
|
133
|
+
| Object | Description |
|
|
134
|
+
|:-------|:------------|
|
|
135
|
+
| **Values** | Stores the current value of each field |
|
|
136
|
+
| **FieldStates** | Stores per-field state: `isDirty`, `isTouched`, `error`, plus unlimited custom states (`hidden`, `disabled`, `validating`, ...) via `actions.setFieldState(name, prop, value)` |
|
|
137
|
+
| **FormState** | Stores form-level state: `isDirty`, `isError`, `dirtyFields`, `touchedFields`, `errorFields`, plus unlimited custom states (`isSubmitting`, `isValidating`, ...) via `actions.setFormState(prop, value)` |
|
|
138
|
+
| **Errors** | Stores validation errors per field, settable via `actions.setError(name, message)` |
|
|
139
|
+
|
|
140
|
+
The library provides **3 methods** to observe these states — `watch`, `useWatch`, and `subscribe` — each suited to different use cases. All three share the same unified name format and can observe any of the 4 state objects above. See [The Power of watch](#the-power-of-watch-unified-observation) for details.
|
|
141
|
+
|
|
128
142
|
## Input Field Modes
|
|
129
143
|
|
|
130
144
|
### 1. `Uncontrolled`:
|
|
@@ -274,8 +288,6 @@ const { actions } = useForm();
|
|
|
274
288
|
console.log(actions.getValues());
|
|
275
289
|
```
|
|
276
290
|
|
|
277
|
-
> **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
|
|
278
|
-
|
|
279
291
|
## Set value
|
|
280
292
|
|
|
281
293
|
actions.setValue() can help to control value of a field. But that field must be controlled by Controller.
|
|
@@ -360,8 +372,6 @@ console.log(actions.getFormState("custom.hello"));
|
|
|
360
372
|
console.log(actions.getFormState(["isDirty", "isError"]));
|
|
361
373
|
```
|
|
362
374
|
|
|
363
|
-
> **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
|
|
364
|
-
|
|
365
375
|
# Managing field states
|
|
366
376
|
|
|
367
377
|
## Set field states
|
|
@@ -386,8 +396,6 @@ console.log(actions.getFieldStates("fieldStates.fieldName.hidden"))
|
|
|
386
396
|
console.log(actions.getFieldStates(["fieldStates.fieldName.isDirty", "fieldStates.fieldName.isError"]))
|
|
387
397
|
```
|
|
388
398
|
|
|
389
|
-
> **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
|
|
390
|
-
|
|
391
399
|
# Managing errors
|
|
392
400
|
|
|
393
401
|
## Get field error
|
|
@@ -401,8 +409,6 @@ const { actions } = useForm();
|
|
|
401
409
|
console.log(actions.getErrors());
|
|
402
410
|
```
|
|
403
411
|
|
|
404
|
-
> **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
|
|
405
|
-
|
|
406
412
|
## Set field error
|
|
407
413
|
|
|
408
414
|
```jsx
|
|
@@ -523,23 +529,21 @@ Return:
|
|
|
523
529
|
- `actions.getErrors()`: `(name?: String | Array) => Object` [Example](#managing-errors)
|
|
524
530
|
- `actions.getFormState()`: `(name?: String | Array) => Object` [Example](#managing-form-state)
|
|
525
531
|
- `actions.getFieldStates()`: `(name?: String | Array) => Object` [Example](#managing-field-states)
|
|
526
|
-
- `actions.
|
|
527
|
-
- `actions.
|
|
528
|
-
- `actions.
|
|
529
|
-
- `actions.
|
|
530
|
-
- `actions.
|
|
531
|
-
- `actions.
|
|
532
|
-
- `actions.
|
|
533
|
-
- `actions.clearError()`: `(name: String | Array) => void`
|
|
532
|
+
- `actions.setFormState(property, value)`: `(property: String, value: Any) => void`
|
|
533
|
+
- `actions.setValue(name, value, options)`: `(name: String, value: Any, options?: { shouldDirty?: Boolean, shouldTouched?: Boolean }) => void` [Example](#set-value)
|
|
534
|
+
- `actions.setError(name, error)`: `(name: String, error: Any) => void` [Example](#set-field-error)
|
|
535
|
+
- `actions.setFieldState(name, property, value)`: `(name: String, property: String, value: Any) => void` [Example](#set-field-states)
|
|
536
|
+
- `actions.resetFieldState(name)`: `(name: String) => void`
|
|
537
|
+
- `actions.resetField(name)`: `(name: String) => void`
|
|
538
|
+
- `actions.clearError(name)`: `(name: String | Array) => void`
|
|
534
539
|
- `actions.clearErrors()`: `() => void`
|
|
535
|
-
- `actions.
|
|
536
|
-
- `actions.subscribeBlur()`: `(callback) => unsubscribe: Function()`
|
|
537
|
-
- `actions.getNumberFields()`: `() => Array`
|
|
538
|
-
- `actions.getDefaultValues()`: `() => Object`
|
|
540
|
+
- `actions.addGroups(name)`: `(name: String | Array) => void` [Example](#registering)
|
|
539
541
|
- `actions.trigger(name, options)`: `(name: String | Array, options?: {bubble?: Boolean, trickle?: Boolean}) => void` trigger watchers (e.g. `watch`, `useWatch`, `subscribe`) re-update values if needed.
|
|
540
542
|
- `bubble`: `Boolean`. If true, it will trigger all parent events (e.g. trigger "address.line1" will trigger watch("address"), watch()).
|
|
541
543
|
- `trickle`: `Boolean`. If true, it will trigger all child events (e.g. trigger "address" will trigger watch("address.line1"), watch("address.line2"), etc.).
|
|
542
|
-
- `actions.
|
|
544
|
+
- `actions.triggerFieldBlur `(name: String, value?: Any) => void`. Used to trigger the blur event for a field manually.
|
|
545
|
+
- `actions.getDefaultValues()`: `() => Object`
|
|
546
|
+
- `actions.getNumberFields()`: `() => Array`
|
|
543
547
|
|
|
544
548
|
## Form
|
|
545
549
|
|
|
@@ -1,22 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react");var ae={exports:{}},ee={};/**
|
|
2
|
-
* @license React
|
|
3
|
-
* react-jsx-runtime.production.js
|
|
4
|
-
*
|
|
5
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
6
|
-
*
|
|
7
|
-
* This source code is licensed under the MIT license found in the
|
|
8
|
-
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var ge;function Ae(){if(ge)return ee;ge=1;var o=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function c(f,a,d){var u=null;if(d!==void 0&&(u=""+d),a.key!==void 0&&(u=""+a.key),"key"in a){d={};for(var h in a)h!=="key"&&(d[h]=a[h])}else d=a;return a=d.ref,{$$typeof:o,type:f,key:u,ref:a!==void 0?a:null,props:d}}return ee.Fragment=t,ee.jsx=c,ee.jsxs=c,ee}var re={};/**
|
|
10
|
-
* @license React
|
|
11
|
-
* react-jsx-runtime.development.js
|
|
12
|
-
*
|
|
13
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
14
|
-
*
|
|
15
|
-
* This source code is licensed under the MIT license found in the
|
|
16
|
-
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var he;function _e(){return he||(he=1,process.env.NODE_ENV!=="production"&&function(){function o(r){if(r==null)return null;if(typeof r=="function")return r.$$typeof===te?null:r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case v:return"Fragment";case S:return"Profiler";case w:return"StrictMode";case x:return"Suspense";case q:return"SuspenseList";case k:return"Activity"}if(typeof r=="object")switch(typeof r.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),r.$$typeof){case p:return"Portal";case A:return(r.displayName||"Context")+".Provider";case T:return(r._context.displayName||"Context")+".Consumer";case P:var g=r.render;return r=r.displayName,r||(r=g.displayName||g.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case z:return g=r.displayName||null,g!==null?g:o(r.type)||"Memo";case G:g=r._payload,r=r._init;try{return o(r(g))}catch{}}return null}function t(r){return""+r}function c(r){try{t(r);var g=!1}catch{g=!0}if(g){g=console;var F=g.error,j=typeof Symbol=="function"&&Symbol.toStringTag&&r[Symbol.toStringTag]||r.constructor.name||"Object";return F.call(g,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",j),t(r)}}function f(r){if(r===v)return"<>";if(typeof r=="object"&&r!==null&&r.$$typeof===G)return"<...>";try{var g=o(r);return g?"<"+g+">":"<...>"}catch{return"<...>"}}function a(){var r=Z.A;return r===null?null:r.getOwner()}function d(){return Error("react-stack-top-frame")}function u(r){if(se.call(r,"key")){var g=Object.getOwnPropertyDescriptor(r,"key").get;if(g&&g.isReactWarning)return!1}return r.key!==void 0}function h(r,g){function F(){J||(J=!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)",g))}F.isReactWarning=!0,Object.defineProperty(r,"key",{get:F,configurable:!0})}function E(){var r=o(this.type);return ne[r]||(ne[r]=!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.")),r=this.props.ref,r!==void 0?r:null}function C(r,g,F,j,Y,I,X,K){return F=I.ref,r={$$typeof:_,type:r,key:g,props:I,_owner:Y},(F!==void 0?F:null)!==null?Object.defineProperty(r,"ref",{enumerable:!1,get:E}):Object.defineProperty(r,"ref",{enumerable:!1,value:null}),r._store={},Object.defineProperty(r._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(r,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(r,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:X}),Object.defineProperty(r,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:K}),Object.freeze&&(Object.freeze(r.props),Object.freeze(r)),r}function m(r,g,F,j,Y,I,X,K){var O=g.children;if(O!==void 0)if(j)if(le(O)){for(j=0;j<O.length;j++)l(O[j]);Object.freeze&&Object.freeze(O)}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 l(O);if(se.call(g,"key")){O=o(r);var L=Object.keys(g).filter(function(ie){return ie!=="key"});j=0<L.length?"{key: someKey, "+L.join(": ..., ")+": ...}":"{key: someKey}",ue[O+j]||(L=0<L.length?"{"+L.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
18
|
-
let props = %s;
|
|
19
|
-
<%s {...props} />
|
|
20
|
-
React keys must be passed directly to JSX without using spread:
|
|
21
|
-
let props = %s;
|
|
22
|
-
<%s key={someKey} {...props} />`,j,O,L,O),ue[O+j]=!0)}if(O=null,F!==void 0&&(c(F),O=""+F),u(g)&&(c(g.key),O=""+g.key),"key"in g){F={};for(var Q in g)Q!=="key"&&(F[Q]=g[Q])}else F=g;return O&&h(F,typeof r=="function"?r.displayName||r.name||"Unknown":r),C(r,O,I,Y,a(),F,X,K)}function l(r){typeof r=="object"&&r!==null&&r.$$typeof===_&&r._store&&(r._store.validated=1)}var R=n,_=Symbol.for("react.transitional.element"),p=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),w=Symbol.for("react.strict_mode"),S=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),A=Symbol.for("react.context"),P=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),q=Symbol.for("react.suspense_list"),z=Symbol.for("react.memo"),G=Symbol.for("react.lazy"),k=Symbol.for("react.activity"),te=Symbol.for("react.client.reference"),Z=R.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,se=Object.prototype.hasOwnProperty,le=Array.isArray,H=console.createTask?console.createTask:function(){return null};R={"react-stack-bottom-frame":function(r){return r()}};var J,ne={},W=R["react-stack-bottom-frame"].bind(R,d)(),oe=H(f(d)),ue={};re.Fragment=v,re.jsx=function(r,g,F,j,Y){var I=1e4>Z.recentlyCreatedOwnerStacks++;return m(r,g,F,!1,j,Y,I?Error("react-stack-top-frame"):W,I?H(f(r)):oe)},re.jsxs=function(r,g,F,j,Y){var I=1e4>Z.recentlyCreatedOwnerStacks++;return m(r,g,F,!0,j,Y,I?Error("react-stack-top-frame"):W,I?H(f(r)):oe)}}()),re}var Ee;function Oe(){return Ee||(Ee=1,process.env.NODE_ENV==="production"?ae.exports=Ae():ae.exports=_e()),ae.exports}var me=Oe();const y=()=>{},ve=n.createContext({ref:null,watch:y,actions:{subscribe:y,reset:y,trigger:y,reload:y,resetField:y,setValue:y,getValues:y,getErrors:y,getFieldStates:y,getFormState:y,setError:y,clearError:y,clearErrors:y,checkValidity:y,getFieldValidity:y,getDefaultValues:y,setFieldState:y,triggerFieldBlur:y,resetFieldState:y,getControlledFields:y,setFormState:y,getEvents:y,getWatchEvents:y,addGroups:y},registerController:y,registerHookWatcher:y,lastReloadedAt:y,loadFormValues:y,getWatchValue:y,channels:{}}),be=()=>n.useContext(ve),je=({id:o,control:t,method:c,action:f,children:a,onChange:d,onBlur:u,onSubmit:h=()=>{},onInput:E=()=>{},onReset:C=()=>{},numberFields:m=[],className:l,...R})=>{const _=n.useCallback(p=>{t.ref&&(t.ref.current=p,t.ref.current&&t.initForm())},[t]);return n.useEffect(()=>{let p=()=>{},v=()=>{};return d&&(p=t.channels.subscribe("onChange",d)),u&&(v=t.channels.subscribe("onBlur",u)),()=>{p(),v()}},[t.lastReloadedAt]),me.jsx(ve.Provider,{value:t,children:me.jsx("form",{id:o,ref:_,action:f,method:c,className:l,onInput:E,onSubmit:p=>{c||p.preventDefault();const v=t.loadFormValues();h(v)},onChange:p=>{const v=p.target.name;!v||t.actions.getControlledFields().has(v)||t.actions.setValue(v,p.target.value)},onBlur:p=>{const v=p.target.name;if(!v||t.actions.getControlledFields().has(v))return;const w=p.target.value;t.channels.publish("onBlur",v,w,t.actions.getValues()),t.triggerBlurWatchers(v)},onReset:p=>{t.actions.reset(),C(p)},...R,children:a},t.lastReloadedAt)})},de={isDirty:!1,isTouched:!1,error:null},Re={lastReset:null,isDirty:!1,isError:!1,errorFields:[],dirtyFields:[],touchedFields:[]},we={},Pe=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"],D=(o={},t="")=>t.split(".").reduce((c,f)=>c&&c[f]!==void 0?c[f]:void 0,o),M=(o={},t="",c)=>{const f=Array.isArray(o)?[...o]:{...o};let a=f;const d=t.split(".");return d.forEach((u,h)=>{h<d.length-1?(a[u]||(a[u]=/^\d+$/.test(d[h+1])?[]:{}),Array.isArray(a[u])?a[u]=[...a[u]]:a[u]={...a[u]},a=a[u]):a[u]=c}),f},Se=o=>{let t=Array.isArray(o)?[...o]:{...o};return Object.keys(t).forEach(c=>{if(c.includes(".")){const f=D(t,c);t=M(t,c,f||""),delete t[c]}}),t},$e=["errors","fieldStates","formState"],U=o=>$e.some(t=>o.startsWith(t))?o:"values."+o,Ce=o=>{typeof o.setCustomValidity=="function"&&o.setCustomValidity("");let t=o.validity,c=Pe.find(f=>t[f]);if(c)return{type:c,message:o.validationMessage}},ye=(o=new Set,t={},c="")=>Object.keys(t||{}).reduce((f,a)=>{const d=(t||{})[a];return o.has(c+a)?[...f,...ye(o,d,c+a+".")]:d!=null&&d.isDirty?[...f,c+a]:f},[]),ke=(o=new Set,t={},c="")=>Object.keys(t||{}).reduce((f,a)=>{const d=(t||{})[a];return o.has(c+a)?[...f,...ke(o,d,c+a+".")]:d!=null&&d.isTouched?[...f,c+a]:f},[]),pe=(o=new Set,t={},c="")=>Object.keys(t||{}).reduce((f,a)=>{const d=(t||{})[a];return o.has(c+a)?[...f,...pe(o,d,c+a+".")]:d?[...f,c+a]:f},[]),Fe=({control:o,name:t,compute:c,mode:f})=>{const{getWatchValue:a,registerHookWatcher:d}=o||be(),u=a({name:t,compute:c}),[h,E]=n.useState(u);return n.useEffect(()=>d({name:t,compute:c,value:h,setValue:E,mode:f}),[]),h},Te=({control:o,name:t,defaultValue:c,shouldUnRegister:f})=>{const{actions:a,registerController:d,channels:u,getWatchValue:h,triggerBlurWatchers:E}=o||be(),C=n.useRef(),m=n.useRef(),l=D(a.getDefaultValues(),t)||c||"",R=Fe({name:t})??l,[_,p]=n.useState({}),v=n.useCallback((S,{shouldDirty:T=!0,shouldOnChange:A=!0}={})=>{var x;let P=S;((x=S==null?void 0:S.target)==null?void 0:x.value)!==void 0&&(P=S.target.value),a.setValue(t,P,{shouldDirty:T,shouldOnChange:A})},[a.setValue]),w=n.useCallback(S=>{const T=a.getValues(),A=S??D(T,t);u.publish("onBlur",t,A,T),E(t)},[]);return n.useEffect(()=>{const S=d(t,{shouldUnRegister:f});return()=>{S&&S(),m.current&&m.current()}},[f,t]),new Proxy({ref:C,name:t,defaultValue:l,value:R,onChange:v,onBlur:w,fieldState:_},{get(S,T,A){return typeof T=="string"&&T==="fieldState"&&(m.current&&m.current(),m.current=a.subscribe(`fieldStates.${t}`,()=>{p(h({name:`fieldStates.${t}`}))})),Reflect.get(S,T,A)}})},Ne=({name:o,control:t,shouldUnRegister:c,defaultValue:f,render:a=({ref:d,name:u,defaultValue:h,value:E,onChange:C,onBlur:m,fieldState:l})=>null})=>{const d=Te({name:o,defaultValue:f,shouldUnRegister:c,control:t});return a(d)},De=()=>{const[o,t]=n.useState(),c=n.useCallback(()=>t(new Date().toString()),[]);return[o,c]},xe=()=>{const[,o]=n.useState({});return n.useCallback(()=>o({}),[])},We=({channels:o,getWatchValue:t})=>{const c=xe(),f=n.useCallback((u,h="onChange")=>{if(!u)return o.subscribeWatch("values",()=>c()),t();if(typeof u=="string"){let E=U(u);h==="onBlur"&&(E=`blur.${E}`),o.subscribeWatch(E,(C,m)=>{C!==m&&c()})}return Array.isArray(u)&&u.forEach(E=>{let C=U(E);h==="onBlur"&&(C=`blur.${C}`),o.subscribeWatch(C,(m,l)=>{m!==l&&c()})}),t({name:u})},[]),a=n.useCallback(({name:u,compute:h,setValue:E,mode:C="onChange"})=>{if(typeof h=="function")return o.subscribe("values",()=>{const l=t({compute:h});E(l)});if(!u)return o.subscribe("values",()=>{E(t())});if(typeof u=="string"){let m=U(u);return C==="onBlur"&&(m=`blur.${m}`),o.subscribe(m,()=>{const R=t({name:u});E(R)})}if(Array.isArray(u)){const m=[];return u.forEach(l=>{let R=U(l);C==="onBlur"&&(R=`blur.${R}`);const _=o.subscribe(R,()=>{const p=t({name:u});E(p)});m.push(_)}),()=>m.forEach(l=>l())}throw new Error("Parameters of name must be string or array of string or compute must be a function")},[]),d=n.useCallback((u,h,E="onChange")=>{if(!u)return o.subscribe("values",()=>h(t()));if(["onChange","onBlur"].includes(u))return o.subscribe(u,h);if(typeof u=="string"){let C=U(u);return E==="onBlur"&&(C=`blur.${C}`),o.subscribe(C,()=>h(t({name:u})))}if(Array.isArray(u)){const C=[];return u.forEach(m=>{let l=U(m);E==="onBlur"&&(l=`blur.${l}`);const R=o.subscribe(l,()=>{h(t({name:u}))});C.push(R)}),()=>C.forEach(m=>m())}throw new Error("Parameters of name must be string or array of string")},[]);return{watch:f,registerHookWatcher:a,getWatchValue:t,subscribe:d}},Be=({getWatchValue:o})=>{const t=n.useRef(new Map),c=n.useRef(new Map),f=n.useCallback(()=>c.current,[]),a=n.useCallback(()=>t.current,[]),d=n.useCallback(()=>{t.current.clear(),c.current.clear()},[]),u=l=>l.replace("values.","").replace("values",""),h=n.useCallback((l,...R)=>{const _=l.split(".");_.forEach((p,v)=>{const w=_.slice(0,_.length-v).join("."),S=t.current.get(w),T=c.current.get(w);if(v>0){const A=R[0],P=o({name:u(w)});R=[M(P,l.replace(w,""),A)]}S&&S.forEach(A=>A(...R)),T&&T.forEach(A=>A(...R))})},[]),E=n.useCallback((l,{trickle:R=!1,bubble:_=!1})=>{const p=l.split(".");let v=[o({name:u(l)})];p.forEach((w,S)=>{const T=p.slice(0,p.length-S).join("."),A=t.current.get(T),P=c.current.get(T);if(S>0&&_){const x=v[0],q=o({name:u(T)});v=[M(q,l.replace(T,""),x)]}A&&(S===0||_)&&A.forEach(x=>x(...v)),P&&(S===0||_)&&P.forEach(x=>x(...v))}),R&&(t.current.forEach((w,S)=>{S.startsWith(l)&&w.forEach(T=>T(o({name:u(S)})))}),c.current.forEach((w,S)=>{S.startsWith(l)&&w.forEach(T=>T(o({name:u(S)})))}))},[]),C=n.useCallback((l,R)=>(t.current.has(l)||t.current.set(l,new Set),t.current.get(l).add(R),()=>{var _;return(_=t.current.get(l))==null?void 0:_.delete(R)}),[]),m=n.useCallback((l,R)=>{c.current.has(l)||(c.current.set(l,new Set),c.current.get(l).add(R))},[]);return{reset:d,publish:h,subscribe:C,subscribeWatch:m,getEvents:a,getWatchEvents:f,trigger:E}},Ie=({defaultValues:o=we,shouldUnRegister:t=!1,groups:c=[]}={})=>{const[f,a]=De(),d=n.useRef(),u=n.useRef({}),h=n.useRef({}),E=n.useRef({...Re}),C=n.useRef({...o}),m=n.useRef({...o}),l=n.useRef(new Set),R=n.useRef(new Set(c)),_=n.useCallback((e,s=m.current)=>Object.keys(s).reduce((i,b)=>{if(typeof s[b]=="object")return{...i,[b]:_(e,s[b])};const $={...e?{}:h.current[b]||{},...de};return{...i,[b]:$}},{}),[]),p=n.useCallback((e={},{clearCustomFormStates:s=!1,clearCustomFieldStates:i=!1,groups:b=R.current}={})=>{u.current={},m.current={...m.current,...e},C.current={...m.current},l.current=new Set,R.current=new Set(b),E.current={...s?{}:E.current,...Re},h.current=_(i),k.reset(),a()},[]),v=n.useCallback(()=>{let e=Object.fromEntries(new FormData(d.current));l.current.forEach(i=>{e=M(e,i,D(C.current,i))});let s={...C.current,...e};return Se(s)},[]),w=n.useCallback(e=>Ce(e.target),[]),S=n.useCallback(()=>m.current,[]),T=n.useCallback(()=>l.current,[]),A=n.useCallback((e,s)=>s?Array.isArray(s)?s.reduce((i,b)=>({...i,[b]:D(e,b)}),{}):D(e,s):{...e},[]),P=n.useCallback(e=>A(C.current,e),[A]),x=n.useCallback(e=>A(u.current,e),[A]),q=n.useCallback(e=>A(h.current,e),[A]),z=n.useCallback(e=>A({...E.current,lastReset:f},e),[f]),G=n.useCallback(({name:e,compute:s}={})=>!e&&!s||e==="values"?P():typeof s=="function"?s(P()):Array.isArray(e)?e.reduce((i,b)=>({...i,[b]:G({name:b})}),{}):D({...C.current,errors:u.current,fieldStates:h.current,formState:z()},e),[]),k=Be({getWatchValue:G}),{watch:te,registerHookWatcher:Z,subscribe:se}=We({getWatchValue:G,channels:k}),le=n.useCallback((e,s)=>{typeof s=="function"&&(s=s(z(e)));const i=E.current,b=D(i,e);b!==s&&(E.current=M(E.current,e,s),k.publish(`formState.${e}`,s,b))},[]),H=n.useCallback((e,s)=>{typeof s=="function"&&(s=s(x(e))),W(e,"error",s)},[]),J=n.useCallback(e=>{W(e,"error",null)},[]),ne=n.useCallback(()=>{E.current.isError&&Object.keys(u.current).forEach(e=>J(e))},[]),W=n.useCallback((e,s,i)=>{try{if(typeof i=="function"&&(i=i(q(e))),R.current.has(e))if(typeof i=="object"&&i!==null){Object.keys(i).forEach(N=>{W(`${e}.${N}`,s,i[N])});return}else return console.error(`Cannot set primitive value for nested parent field "${e}". Please set value for its children or provide an object.`);const b=D(h.current,e)||{...de},$=D(b,s);if($!==i){if(h.current=M(h.current,`${e}.${s}`,i),k.publish(`fieldStates.${e}.${s}`,i,$),s==="error"){const N=D(u.current,e),B=i||null;N!==B&&(u.current=M(u.current,e,B),k.publish(`errors.${e}`,B,N));const V=pe(R.current,u.current);E.current.errorFields=V,k.publish("formState.errorFields",V);const ce=V.length>0;if(E.current.isError!==ce){const fe=E.current.isError;E.current.isError=ce,k.publish("formState.isError",ce,fe)}}if(s==="isDirty"){const N=ye(R.current,h.current);E.current.dirtyFields=N,k.publish("formState.dirtyFields",N);const B=N.length>0;if(E.current.isDirty!==B){const V=E.current.isDirty;E.current.isDirty=B,k.publish("formState.isDirty",B,V)}}if(s==="isTouched"){const N=ke(R.current,h.current);E.current.touchedFields=N,k.publish("formState.touchedFields",N)}}}catch(b){console.log(b)}},[]),oe=n.useCallback(e=>{W(e,"isDirty",!1),W(e,"isTouched",!1),W(e,"error",null)},[]),ue=n.useCallback(e=>{const s=Ce(e.target);s?H(e.target.name,s):J(e.target.name)},[]),r=n.useCallback((e,s,{shouldDirty:i=!0,shouldOnChange:b=!0}={})=>{if(typeof s=="function"&&(s=s(P(e))),R.current.has(e)){typeof s=="object"&&s!==null?Object.keys(s).forEach(B=>{r(`${e}.${B}`,s[B],{shouldDirty:i,shouldOnChange:b})}):console.error(`Cannot set primitive value for nested parent field "${e}". Please set value for its children or provide an object.`);return}const $=D(C.current,e);if(s===$)return;if(C.current=M(C.current,e,s),k.publish(`values.${e}`,s,$),e.includes(".")){const B=e.split("."),V=B.findIndex((ce,fe)=>!R.current.has(B.slice(0,fe+1).join(".")));V!==-1&&(e=B.slice(0,V+1).join("."))}s&&W(e,"isTouched",!0);const N=s!==(D(m.current,e)||"");i&&W(e,"isDirty",N),b&&k.publish("onChange",e,s,$)},[]),g=n.useCallback(e=>{const s=e.split(".");let i="";s.forEach((b,$)=>{$<s.length-1&&(i=i?`${i}.${b}`:b,R.current.add(i))})},[]),F=n.useCallback(e=>{Array.isArray(e)?e.forEach(s=>g(s+".")):g(e+".")},[]),j=n.useCallback((e="",{shouldUnRegister:s=t}={})=>e?(l.current.add(e),h.current=M(h.current,e,{...de}),e.includes(".")&&g(e),()=>{s&&(r(e,void 0,{shouldDirty:!1,shouldOnChange:!1}),l.current.delete(e))}):console.error("Controller must have a name"),[]),Y=n.useCallback((e,{keepError:s,keepDirty:i,keepTouched:b,defaultValue:$})=>{if(!l.current.has(e))throw new Error(`Cannot reset "${e}" because it's uncontrolled field`);m.current=M(m.current,e,$),C.current=M(C.current,e,$),k.publish(`values.${e}`,$),s||J(e),i||W(e,"isDirty",!1),b||W(e,"isTouched",!1)},[]),I=n.useCallback((e,{bubble:s,trickle:i}={})=>{if(!e){k.trigger("values",{bubble:s,trickle:i??!0}),k.trigger("blur.values",{bubble:s,trickle:i??!0});return}if(!Array.isArray(e)){const b=U(e);k.trigger(b,{bubble:s,trickle:i}),k.trigger(`blur.${b}`,{bubble:s,trickle:i});return}e.forEach(b=>{const $=U(b);k.trigger($,{bubble:s,trickle:i}),k.trigger(`blur.${$}`,{bubble:s,trickle:i})})},[]),X=n.useCallback(e=>{k.publish(`blur.values.${e}`,P(e)),k.publish(`blur.errors.${e}`,x(e));const s=q(e);Object.keys(s||{}).forEach(b=>{k.publish(`blur.fieldStates.${e}.${b}`,s[b])});const i=z();Object.keys(i||{}).forEach(b=>{k.publish(`blur.formState.${b}`,i[b])})},[]),K=n.useCallback((e,s=P(e))=>{k.publish("onBlur",e,s,P()),X(e)},[]),O=n.useMemo(()=>({subscribe:se,reset:p,trigger:I,reload:a,resetField:Y,setValue:r,getValues:P,getErrors:x,getFieldStates:q,getFormState:z,setError:H,clearError:J,clearErrors:ne,checkValidity:ue,getFieldValidity:w,getDefaultValues:S,setFieldState:W,triggerFieldBlur:K,resetFieldState:oe,getControlledFields:T,setFormState:le,getEvents:k.getEvents,getWatchEvents:k.getWatchEvents,addGroups:F}),[f]),L=n.useCallback(()=>{[...d.current.querySelectorAll("[name]")].forEach(i=>{const b=i.name||"";b.includes(".")&&g(b),!i.defaultValue&&!l.current.has(b)&&D(m.current,b)&&(i.defaultValue=D(m.current,b))});const s=v();C.current={...s},m.current={...s}},[]),Q=n.useMemo(()=>({ref:d,watch:te,actions:O,initForm:L,registerController:j,registerHookWatcher:Z,lastReloadedAt:f,loadFormValues:v,getWatchValue:G,triggerBlurWatchers:X,channels:k}),[f]),ie=n.useMemo(()=>({control:Q,actions:O,watch:te}),[f]);return n.useLayoutEffect(()=>{d.current&&L()},[f]),n.useLayoutEffect(()=>{h.current=_(!1)},[]),ie};exports.Controller=Ne;exports.Form=je;exports.restoreFromDotNotation=Se;exports.useController=Te;exports.useForm=Ie;exports.useFormContext=be;exports.useWatch=Fe;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("react/jsx-runtime"),s=require("react"),F=()=>{},tr=s.createContext({ref:null,watch:F,actions:{subscribe:F,reset:F,trigger:F,reload:F,resetField:F,setValue:F,getValues:F,getErrors:F,getFieldStates:F,getFormState:F,setError:F,clearError:F,clearErrors:F,checkValidity:F,getFieldValidity:F,getDefaultValues:F,setFieldState:F,triggerFieldBlur:F,resetFieldState:F,getControlledFields:F,setFormState:F,getEvents:F,getWatchEvents:F,addGroups:F},registerController:F,registerHookWatcher:F,lastReloadedAt:F,loadFormValues:F,getWatchValue:F,channels:{}}),U=()=>s.useContext(tr),vr=({id:n,control:t,method:c,action:f,children:l,onChange:h,onBlur:u,onSubmit:b=()=>{},onInput:d=()=>{},onReset:C=()=>{},numberFields:g=[],className:i,...E})=>{const $=s.useCallback(k=>{t.ref&&(t.ref.current=k,t.ref.current&&t.initForm())},[t]);return s.useEffect(()=>{let k=()=>{},v=()=>{};return h&&(k=t.channels.subscribe("onChange",h)),u&&(v=t.channels.subscribe("onBlur",u)),()=>{k(),v()}},[t.lastReloadedAt]),Y.jsx(tr.Provider,{value:t,children:Y.jsx("form",{id:n,ref:$,action:f,method:c,className:i,onInput:d,onSubmit:k=>{c||k.preventDefault();const v=t.loadFormValues();b(v)},onChange:k=>{const v=k.target.name;!v||t.actions.getControlledFields().has(v)||t.actions.setValue(v,k.target.value)},onBlur:k=>{const v=k.target.name;if(!v||t.actions.getControlledFields().has(v))return;const p=k.target.value;t.channels.publish("onBlur",v,p,t.actions.getValues()),t.triggerBlurWatchers(v)},onReset:k=>{t.actions.reset(),C(k)},...E,children:l},t.lastReloadedAt)})},_={isDirty:!1,isTouched:!1,error:null},Z={lastReset:null,isDirty:!1,isError:!1,errorFields:[],dirtyFields:[],touchedFields:[]},kr={},mr=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"],A=(n={},t="")=>t.split(".").reduce((c,f)=>c&&c[f]!==void 0?c[f]:void 0,n),N=(n={},t="",c)=>{const f=Array.isArray(n)?[...n]:{...n};let l=f;const h=t.split(".");return h.forEach((u,b)=>{b<h.length-1?(l[u]||(l[u]=/^\d+$/.test(h[b+1])?[]:{}),Array.isArray(l[u])?l[u]=[...l[u]]:l[u]={...l[u]},l=l[u]):l[u]=c}),f},er=n=>{let t=Array.isArray(n)?[...n]:{...n};return Object.keys(t).forEach(c=>{if(c.includes(".")){const f=A(t,c);t=N(t,c,f||""),delete t[c]}}),t},Rr=["errors","fieldStates","formState"],P=n=>Rr.some(t=>n.startsWith(t))?n:"values."+n,rr=n=>{typeof n.setCustomValidity=="function"&&n.setCustomValidity("");let t=n.validity,c=mr.find(f=>t[f]);if(c)return{type:c,message:n.validationMessage}},sr=(n=new Set,t={},c="")=>Object.keys(t||{}).reduce((f,l)=>{const h=(t||{})[l];return n.has(c+l)?[...f,...sr(n,h,c+l+".")]:h!=null&&h.isDirty?[...f,c+l]:f},[]),nr=(n=new Set,t={},c="")=>Object.keys(t||{}).reduce((f,l)=>{const h=(t||{})[l];return n.has(c+l)?[...f,...nr(n,h,c+l+".")]:h!=null&&h.isTouched?[...f,c+l]:f},[]),ur=(n=new Set,t={},c="")=>Object.keys(t||{}).reduce((f,l)=>{const h=(t||{})[l];return n.has(c+l)?[...f,...ur(n,h,c+l+".")]:h?[...f,c+l]:f},[]),cr=({control:n,name:t,compute:c,mode:f})=>{const{getWatchValue:l,registerHookWatcher:h}=n||U(),u=l({name:t,compute:c}),[b,d]=s.useState(u);return s.useEffect(()=>h({name:t,compute:c,value:b,setValue:d,mode:f}),[]),b},or=({control:n,name:t,defaultValue:c,shouldUnRegister:f})=>{const{actions:l,registerController:h,channels:u,getWatchValue:b,triggerBlurWatchers:d}=n||U(),C=s.useRef(),g=s.useRef(),i=A(l.getDefaultValues(),t)||c||"",E=cr({name:t})??i,[$,k]=s.useState({}),v=s.useCallback((y,{shouldDirty:m=!0,shouldOnChange:R=!0}={})=>{var O;let B=y;((O=y==null?void 0:y.target)==null?void 0:O.value)!==void 0&&(B=y.target.value),l.setValue(t,B,{shouldDirty:m,shouldOnChange:R})},[l.setValue]),p=s.useCallback(y=>{const m=l.getValues(),R=y??A(m,t);u.publish("onBlur",t,R,m),d(t)},[]);return s.useEffect(()=>{const y=h(t,{shouldUnRegister:f});return()=>{y&&y(),g.current&&g.current()}},[f,t]),new Proxy({ref:C,name:t,defaultValue:i,value:E,onChange:v,onBlur:p,fieldState:$},{get(y,m,R){return typeof m=="string"&&m==="fieldState"&&(g.current&&g.current(),g.current=l.subscribe(`fieldStates.${t}`,()=>{k(b({name:`fieldStates.${t}`}))})),Reflect.get(y,m,R)}})},$r=({name:n,control:t,shouldUnRegister:c,defaultValue:f,render:l=({ref:h,name:u,defaultValue:b,value:d,onChange:C,onBlur:g,fieldState:i})=>null})=>{const h=or({name:n,defaultValue:f,shouldUnRegister:c,control:t});return l(h)},Dr=()=>{const[n,t]=s.useState(),c=s.useCallback(()=>t(new Date().toString()),[]);return[n,c]},Ar=()=>{const[,n]=s.useState({});return s.useCallback(()=>n({}),[])},pr=({channels:n,getWatchValue:t})=>{const c=Ar(),f=s.useCallback((u,b="onChange")=>{if(!u)return n.subscribeWatch("values",()=>c()),t();if(typeof u=="string"){let d=P(u);b==="onBlur"&&(d=`blur.${d}`),n.subscribeWatch(d,(C,g)=>{C!==g&&c()})}return Array.isArray(u)&&u.forEach(d=>{let C=P(d);b==="onBlur"&&(C=`blur.${C}`),n.subscribeWatch(C,(g,i)=>{g!==i&&c()})}),t({name:u})},[]),l=s.useCallback(({name:u,compute:b,setValue:d,mode:C="onChange"})=>{if(typeof b=="function")return n.subscribe("values",()=>{const i=t({compute:b});d(i)});if(!u)return n.subscribe("values",()=>{d(t())});if(typeof u=="string"){let g=P(u);return C==="onBlur"&&(g=`blur.${g}`),n.subscribe(g,()=>{const E=t({name:u});d(E)})}if(Array.isArray(u)){const g=[];return u.forEach(i=>{let E=P(i);C==="onBlur"&&(E=`blur.${E}`);const $=n.subscribe(E,()=>{const k=t({name:u});d(k)});g.push($)}),()=>g.forEach(i=>i())}throw new Error("Parameters of name must be string or array of string or compute must be a function")},[]),h=s.useCallback((u,b,d="onChange")=>{if(!u)return n.subscribe("values",()=>b(t()));if(["onChange","onBlur"].includes(u))return n.subscribe(u,b);if(typeof u=="string"){let C=P(u);return d==="onBlur"&&(C=`blur.${C}`),n.subscribe(C,()=>b(t({name:u})))}if(Array.isArray(u)){const C=[];return u.forEach(g=>{let i=P(g);d==="onBlur"&&(i=`blur.${i}`);const E=n.subscribe(i,()=>{b(t({name:u}))});C.push(E)}),()=>C.forEach(g=>g())}throw new Error("Parameters of name must be string or array of string")},[]);return{watch:f,registerHookWatcher:l,getWatchValue:t,subscribe:h}},Br=({getWatchValue:n})=>{const t=s.useRef(new Map),c=s.useRef(new Map),f=s.useCallback(()=>c.current,[]),l=s.useCallback(()=>t.current,[]),h=s.useCallback(()=>{t.current.clear(),c.current.clear()},[]),u=i=>i.replace("values.","").replace("values",""),b=s.useCallback((i,...E)=>{const $=i.split(".");$.forEach((k,v)=>{const p=$.slice(0,$.length-v).join("."),y=t.current.get(p),m=c.current.get(p);if(v>0){const R=E[0],B=n({name:u(p)});E=[N(B,i.replace(p,""),R)]}y&&y.forEach(R=>R(...E)),m&&m.forEach(R=>R(...E))})},[]),d=s.useCallback((i,{trickle:E=!1,bubble:$=!1})=>{const k=i.split(".");let v=[n({name:u(i)})];k.forEach((p,y)=>{const m=k.slice(0,k.length-y).join("."),R=t.current.get(m),B=c.current.get(m);if(y>0&&$){const O=v[0],T=n({name:u(m)});v=[N(T,i.replace(m,""),O)]}R&&(y===0||$)&&R.forEach(O=>O(...v)),B&&(y===0||$)&&B.forEach(O=>O(...v))}),E&&(t.current.forEach((p,y)=>{y.startsWith(i)&&p.forEach(m=>m(n({name:u(y)})))}),c.current.forEach((p,y)=>{y.startsWith(i)&&p.forEach(m=>m(n({name:u(y)})))}))},[]),C=s.useCallback((i,E)=>(t.current.has(i)||t.current.set(i,new Set),t.current.get(i).add(E),()=>{var $;return($=t.current.get(i))==null?void 0:$.delete(E)}),[]),g=s.useCallback((i,E)=>{c.current.has(i)||(c.current.set(i,new Set),c.current.get(i).add(E))},[]);return{reset:h,publish:b,subscribe:C,subscribeWatch:g,getEvents:l,getWatchEvents:f,trigger:d}},jr=({defaultValues:n=kr,shouldUnRegister:t=!1,groups:c=[]}={})=>{const[f,l]=Dr(),h=s.useRef(),u=s.useRef({}),b=s.useRef({}),d=s.useRef({...Z}),C=s.useRef({...n}),g=s.useRef({...n}),i=s.useRef(new Set),E=s.useRef(new Set(c)),$=s.useCallback((r,e=g.current)=>Object.keys(e).reduce((o,a)=>{if(typeof e[a]=="object")return{...o,[a]:$(r,e[a])};const D={...r?{}:b.current[a]||{},..._};return{...o,[a]:D}},{}),[]),k=s.useCallback((r={},{clearCustomFormStates:e=!1,clearCustomFieldStates:o=!1,groups:a=E.current}={})=>{u.current={},g.current={...g.current,...r},C.current={...g.current},i.current=new Set,E.current=new Set(a),d.current={...e?{}:d.current,...Z},b.current=$(o),S.reset(),l()},[]),v=s.useCallback(()=>{let r=Object.fromEntries(new FormData(h.current));i.current.forEach(o=>{r=N(r,o,A(C.current,o))});let e={...C.current,...r};return er(e)},[]),p=s.useCallback(r=>rr(r.target),[]),y=s.useCallback(()=>g.current,[]),m=s.useCallback(()=>i.current,[]),R=s.useCallback((r,e)=>e?Array.isArray(e)?e.reduce((o,a)=>({...o,[a]:A(r,a)}),{}):A(r,e):r,[]),B=s.useCallback(r=>R(C.current,r),[R]),O=s.useCallback(r=>R(u.current,r),[R]),T=s.useCallback(r=>R(b.current,r),[R]),I=s.useCallback(r=>R({...d.current,lastReset:f},r),[f]),G=s.useCallback(({name:r,compute:e}={})=>!r&&!e||r==="values"?B():typeof e=="function"?e(B()):Array.isArray(r)?r.reduce((o,a)=>({...o,[a]:G({name:a})}),{}):A({...C.current,errors:u.current,fieldStates:b.current,formState:I()},r),[]),S=Br({getWatchValue:G}),{watch:x,registerHookWatcher:ir,subscribe:ar}=pr({getWatchValue:G,channels:S}),lr=s.useCallback((r,e)=>{typeof e=="function"&&(e=e(I(r)));const o=d.current,a=A(o,r);a!==e&&(d.current=N(d.current,r,e),S.publish(`formState.${r}`,e,a))},[]),z=s.useCallback((r,e)=>{typeof e=="function"&&(e=e(O(r))),W(r,"error",e)},[]),H=s.useCallback(r=>{W(r,"error",null)},[]),fr=s.useCallback(()=>{d.current.isError&&Object.keys(u.current).forEach(r=>H(r))},[]),W=s.useCallback((r,e,o)=>{try{if(typeof o=="function"&&(o=o(T(r))),E.current.has(r))if(typeof o=="object"&&o!==null){Object.keys(o).forEach(j=>{W(`${r}.${j}`,e,o[j])});return}else return console.error(`Cannot set primitive value for nested parent field "${r}". Please set value for its children or provide an object.`);const a=A(b.current,r)||{..._},D=A(a,e);if(D!==o){if(b.current=N(b.current,`${r}.${e}`,o),S.publish(`fieldStates.${r}.${e}`,o,D),e==="error"){const j=A(u.current,r),w=o||null;j!==w&&(u.current=N(u.current,r,w),S.publish(`errors.${r}`,w,j));const M=ur(E.current,u.current);d.current.errorFields=M,S.publish("formState.errorFields",M);const K=M.length>0;if(d.current.isError!==K){const V=d.current.isError;d.current.isError=K,S.publish("formState.isError",K,V)}}if(e==="isDirty"){const j=sr(E.current,b.current);d.current.dirtyFields=j,S.publish("formState.dirtyFields",j);const w=j.length>0;if(d.current.isDirty!==w){const M=d.current.isDirty;d.current.isDirty=w,S.publish("formState.isDirty",w,M)}}if(e==="isTouched"){const j=nr(E.current,b.current);d.current.touchedFields=j,S.publish("formState.touchedFields",j)}}}catch(a){console.log(a)}},[]),dr=s.useCallback(r=>{W(r,"isDirty",!1),W(r,"isTouched",!1),W(r,"error",null)},[]),gr=s.useCallback(r=>{const e=rr(r.target);e?z(r.target.name,e):H(r.target.name)},[]),L=s.useCallback((r,e,{shouldDirty:o=!0,shouldOnChange:a=!0}={})=>{if(typeof e=="function"&&(e=e(B(r))),E.current.has(r)){typeof e=="object"&&e!==null?Object.keys(e).forEach(w=>{L(`${r}.${w}`,e[w],{shouldDirty:o,shouldOnChange:a})}):console.error(`Cannot set primitive value for nested parent field "${r}". Please set value for its children or provide an object.`);return}const D=A(C.current,r);if(e===D)return;if(C.current=N(C.current,r,e),S.publish(`values.${r}`,e,D),r.includes(".")){const w=r.split("."),M=w.findIndex((K,V)=>!E.current.has(w.slice(0,V+1).join(".")));M!==-1&&(r=w.slice(0,M+1).join("."))}e&&W(r,"isTouched",!0);const j=e!==(A(g.current,r)||"");o&&W(r,"isDirty",j),a&&S.publish("onChange",r,e,D)},[]),q=s.useCallback(r=>{const e=r.split(".");let o="";e.forEach((a,D)=>{D<e.length-1&&(o=o?`${o}.${a}`:a,E.current.add(o))})},[]),br=s.useCallback(r=>{Array.isArray(r)?r.forEach(e=>q(e+".")):q(r+".")},[]),hr=s.useCallback((r="",{shouldUnRegister:e=t}={})=>r?(i.current.add(r),b.current=N(b.current,r,{..._}),r.includes(".")&&q(r),()=>{e&&(L(r,void 0,{shouldDirty:!1,shouldOnChange:!1}),i.current.delete(r))}):console.error("Controller must have a name"),[]),Cr=s.useCallback((r,{keepError:e,keepDirty:o,keepTouched:a,defaultValue:D}={})=>{if(!i.current.has(r))throw new Error(`Cannot reset "${r}" because it's uncontrolled field`);D===void 0&&(D=A(g.current,r)),g.current=N(g.current,r,D),C.current=N(C.current,r,D),S.publish(`values.${r}`,D),e||H(r),o||W(r,"isDirty",!1),a||W(r,"isTouched",!1)},[]),Er=s.useCallback((r,{bubble:e,trickle:o}={})=>{if(!r){S.trigger("values",{bubble:e,trickle:o??!0}),S.trigger("blur.values",{bubble:e,trickle:o??!0});return}if(!Array.isArray(r)){const a=P(r);S.trigger(a,{bubble:e,trickle:o}),S.trigger(`blur.${a}`,{bubble:e,trickle:o});return}r.forEach(a=>{const D=P(a);S.trigger(D,{bubble:e,trickle:o}),S.trigger(`blur.${D}`,{bubble:e,trickle:o})})},[]),J=s.useCallback(r=>{S.publish(`blur.values.${r}`,B(r)),S.publish(`blur.errors.${r}`,O(r));const e=T(r);Object.keys(e||{}).forEach(a=>{S.publish(`blur.fieldStates.${r}.${a}`,e[a])});const o=I();Object.keys(o||{}).forEach(a=>{S.publish(`blur.formState.${a}`,o[a])})},[]),Fr=s.useCallback((r,e=B(r))=>{S.publish("onBlur",r,e,B()),J(r)},[]),Q=s.useMemo(()=>({subscribe:ar,reset:k,trigger:Er,reload:l,resetField:Cr,setValue:L,getValues:B,getErrors:O,getFieldStates:T,getFormState:I,setError:z,clearError:H,clearErrors:fr,checkValidity:gr,getFieldValidity:p,getDefaultValues:y,setFieldState:W,triggerFieldBlur:Fr,resetFieldState:dr,getControlledFields:m,setFormState:lr,getEvents:S.getEvents,getWatchEvents:S.getWatchEvents,addGroups:br}),[f]),X=s.useCallback(()=>{[...h.current.querySelectorAll("[name]")].forEach(o=>{const a=o.name||"";a.includes(".")&&q(a),!o.defaultValue&&!i.current.has(a)&&A(g.current,a)&&(o.defaultValue=A(g.current,a))});const e=v();C.current={...e},g.current={...e}},[]),yr=s.useMemo(()=>({ref:h,watch:x,actions:Q,initForm:X,registerController:hr,registerHookWatcher:ir,lastReloadedAt:f,loadFormValues:v,getWatchValue:G,triggerBlurWatchers:J,channels:S}),[f]),Sr=s.useMemo(()=>({control:yr,actions:Q,watch:x}),[f]);return s.useLayoutEffect(()=>{h.current&&X()},[f]),s.useEffect(()=>{b.current=$(!1)},[]),Sr};exports.Controller=$r;exports.Form=vr;exports.restoreFromDotNotation=er;exports.useController=or;exports.useForm=jr;exports.useFormContext=U;exports.useWatch=cr;
|