react-simple-formkit 2.0.4 → 2.1.4

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 CHANGED
@@ -26,6 +26,9 @@ Supports managing forms as uncontrolled. State updates only when watched. Simple
26
26
  - [Controller](#controller)
27
27
  - [useController](#useController)
28
28
  - [useWatch](#useWatch)
29
+ - [useFormContext](#useFormContext)
30
+ - [watch](#watch)
31
+ - [subscribe](#subscribe)
29
32
  - [Examples](#examples)
30
33
  - [Contact](#contact)
31
34
 
@@ -45,8 +48,9 @@ Supports managing forms as uncontrolled. State updates only when watched. Simple
45
48
  - **Optimized for uncontrolled forms**: no unnecessary re-renders
46
49
  - Comprehensive form management:
47
50
  - [Values](#manage-values): get/set values, defaults, reset, ...
48
- - [States](#manage-states): dirty, touched, custom states, ...
49
- - [Errors](#manage-errors): form-level and field-level errors, ...
51
+ - [Form state](#manage-form-state): isDirty, isError, dirtyFields, touchedFields, errorFields, ...
52
+ - [Field states](#manage-field-states): isDirty, isTouched, isError, custom states, ...
53
+ - [Errors](#manage-errors): form errors, field errors, ...
50
54
 
51
55
  # Quick start
52
56
 
@@ -135,6 +139,8 @@ Example:
135
139
  </LocalizationProvider>
136
140
  ```
137
141
 
142
+ ### `Full Example`
143
+
138
144
  ```
139
145
  const { control, actions } = useForm();
140
146
 
@@ -176,11 +182,11 @@ return (
176
182
  )
177
183
  ```
178
184
 
179
- > **Note\*:** All fields in the form must follow one of the three modes above to ensure the form works correctly
185
+ > **Rule\*:** All fields in the form must follow one of the three modes above to ensure the form works correctly
180
186
 
181
187
  ## Watching for updates
182
188
 
183
- State updates only when observed via `watch()` or `useWatch()`, or by tracking changes through the Form component's `onChange` callback.
189
+ State updates only when observed via `watch()`, `useWatch()`, `subscribe()`, or by tracking changes through the Form component's `onChange`, `onBlur` callbacks.
184
190
 
185
191
  - `watch()` will trigger a re-render at the form level.
186
192
  - `useWatch()` will trigger a re-render only in the component where it is called.
@@ -191,13 +197,12 @@ State updates only when observed via `watch()` or `useWatch()`, or by tracking c
191
197
  ## Get value
192
198
 
193
199
  ```
194
- // watch
195
200
  const fieldName = watch("fieldName")
196
201
  const fieldName2 = watch("fieldName2")
197
202
  // Or
198
203
  const { fieldName2, fieldName } = watch(["fieldName", "fieldName2"])
199
204
  // Or
200
- const values = watch("values")
205
+ const values = watch()
201
206
 
202
207
  // useWatch
203
208
  useWatch({ name: "fieldName" })
@@ -209,6 +214,8 @@ const { actions } = useForm()
209
214
  console.log(actions.getValues())
210
215
  ```
211
216
 
217
+ > **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
218
+
212
219
  ## Set value
213
220
 
214
221
  actions.setValue() can help to control value of a field. But that field must be controlled by Controller.
@@ -267,24 +274,43 @@ return (
267
274
  );
268
275
  ```
269
276
 
270
- # Manage states
277
+ # Manage form state
278
+
279
+ ## Get form states
280
+
281
+ ```
282
+ const isFormDirty = watch("formState.isDirty")
283
+ const isFormError = watch("formState.isError")
284
+ const dirtyFields = watch("formState.dirtyFields")
285
+ const touchedFields = watch("formState.touchedFields")
286
+ const errorFields = watch("formState.errorFields")
287
+ // actions.getFormState()
288
+ const { actions } = useForm()
289
+ console.log(actions.getFormState())
290
+ ```
291
+
292
+ > **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
293
+
294
+ # Manage field states
271
295
 
272
296
  ## Get field states
273
297
 
274
298
  ```
275
- // watch() or useWatch()
276
- const isFormDirty = watch("isDirty")
277
299
  const { fieldName: {...}, fieldName2: {...} } = watch("fieldStates")
278
300
  const { isDirty, isTouched } = watch("fieldStates.fieldName")
279
301
  const isFieldDirty = watch("fieldStates.fieldName.isDirty")
280
302
  const fieldCustomState = watch("fieldStates.fieldName.customState")
303
+ // actions.getFieldStates()
304
+ const { actions } = useForm()
305
+ console.log(actions.getFieldStates())
281
306
  ```
282
307
 
308
+ > **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
309
+
283
310
  ## Set field states
284
311
 
285
312
  ```
286
- actions.setFieldStateProperty('fieldName', 'customState', { hello: "world" })
287
- // This will trigger re-render at watch(), useWatch() and render function in Controller
313
+ actions.setFieldState('fieldName', 'customState', { hello: "world" })
288
314
  ```
289
315
 
290
316
  # Manage errors
@@ -292,12 +318,16 @@ actions.setFieldStateProperty('fieldName', 'customState', { hello: "world" })
292
318
  ## Get field error
293
319
 
294
320
  ```
295
- // watch() or useWatch()
296
- const isFormError = watch("isError")
297
- const fieldError = watch("errors.fieldName")
321
+ const isFormError = watch("formState.isError")
298
322
  const { fieldName, fieldName2 } = watch("errors")
323
+ const fieldError = watch("errors.fieldName")
324
+ // actions.getErrors()
325
+ const { actions } = useForm()
326
+ console.log(actions.getErrors())
299
327
  ```
300
328
 
329
+ > **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
330
+
301
331
  ## Set field error
302
332
 
303
333
  ```
@@ -335,15 +365,20 @@ Return:
335
365
  - `control`: contains methods and utilities to control the form.
336
366
  - `watch(name)`: `Function` [Example](#manage-values)
337
367
  - `actions` is an object that contains utilities
338
- - `actions.reset()`: [Example](#default-values-and-reset)
339
- - `actions.getValues()`: [Example](#manage-values)
340
- - `actions.setValue()`: [Example](#set-value)
341
- - `actions.setError()`: [Example](#set-field-error)
342
- - `actions.clearError()`
343
- - `actions.clearErrors()`
344
- - `actions.getNumberFields()`
345
- - `actions.getDefaultValues()`
346
- - `actions.setFieldStateProperty()`: [Example](#set-field-states)
368
+ - `actions.reset()`: `(newDefaultValues?: Object) => void` [Example](#default-values-and-reset)
369
+ - `actions.getValues()`: `(name?: String | Array) => Object` [Example](#manage-values)
370
+ - `actions.getErrors()`: `(name?: String | Array) => Object` [Example](#manage-errors)
371
+ - `actions.getFormState()`: `(name?: String | Array) => Object` [Example](#manage-form-state)
372
+ - `actions.getFieldStates()`: `(name?: String | Array) => Object` [Example](#manage-field-states)
373
+ - `actions.setValue()`: `(name: String, value: Any, options?: { shouldDirty?: Boolean, shouldTouched?: Boolean }) => void` [Example](#set-value)
374
+ - `actions.setError()`: `(name: String, error: Any) => void` [Example](#set-field-error)
375
+ - `actions.setFieldState()`: `(name: String, property: String, value: Any) => void` [Example](#set-field-states)
376
+ - `actions.resetFieldState()`: `(name: String) => void`
377
+ - `actions.resetField()`: `(name: String) => void`
378
+ - `actions.clearError()`: `(name: String | Array) => void`
379
+ - `actions.clearErrors()`: `() => void`
380
+ - `actions.getNumberFields()`: `() => Array`
381
+ - `actions.getDefaultValues()`: `() => Object`
347
382
 
348
383
  ## Form
349
384
 
@@ -359,9 +394,9 @@ Generic props:
359
394
 
360
395
  - `name`
361
396
  - `defaultValue`
362
- - `render({name, value, onChange, customState, setCustomState})`
397
+ - `render({name, value, onChange, onBlur, customState, setCustomState})`
363
398
 
364
- ## useController
399
+ ## useController({ name, defaultValue })
365
400
 
366
401
  Generic props:
367
402
 
@@ -370,23 +405,51 @@ Generic props:
370
405
 
371
406
  Return: everything in render function above
372
407
 
373
- ## useWatch
408
+ ## useWatch({ name, compute })
374
409
 
375
410
  [Example](#manage-values)
376
411
 
377
412
  Generic props:
378
413
 
379
- - `name`: `String | Array`
380
- - compute: `Function` that will calculate from form values and return a value. It will make re-render when the result changes
414
+ - `name`: `String | Array | undefined`. If undefined, it will return all input values
415
+ - `compute`: `Function` that will calculate from form values and return a value. It will make re-render when the result changes
381
416
 
382
- ## useFormContext
417
+ Return:
418
+
419
+ - if compute is passed: the computed value
420
+ - if name is string: value of the field
421
+ - if name is array: object of values of the fields
422
+ - if name is undefined: object of all input values
423
+
424
+ ## useFormContext()
383
425
 
384
426
  Return:
385
427
 
386
428
  - `watch`
387
429
  - `actions`
388
430
 
389
- # Examples
431
+ ## watch(name)
432
+
433
+ Arguments:
434
+
435
+ - `name`: `String | Array | undefined`. If undefined, it will return all input values
436
+
437
+ Return:
438
+
439
+ - same with useWatch()
440
+
441
+ ## subscribe(name, callback)
442
+
443
+ Arguments:
444
+
445
+ - `name`: `String | Array | undefined`. If undefined, it will return all input values
446
+ - `callback()`: `Function` receive value based on name parameter. Only be called when the value changes
447
+
448
+ Return:
449
+
450
+ - `unregister()`: `Function` that will unregister the callback
451
+
452
+ ## Examples
390
453
 
391
454
  - https://codesandbox.io/p/sandbox/react-simple-formkit-examples-rhmhjj
392
455
 
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react");var oe={exports:{}},Z={};/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react");var ne={exports:{}},K={};/**
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 Re;function pe(){if(Re)return Z;Re=1;var u=Symbol.for("react.transitional.element"),c=Symbol.for("react.fragment");function l(m,i,f){var C=null;if(f!==void 0&&(C=""+f),i.key!==void 0&&(C=""+i.key),"key"in i){f={};for(var b in i)b!=="key"&&(f[b]=i[b])}else f=i;return i=f.ref,{$$typeof:u,type:m,key:C,ref:i!==void 0?i:null,props:f}}return Z.Fragment=c,Z.jsx=l,Z.jsxs=l,Z}var Q={};/**
9
+ */var ue;function me(){if(ue)return K;ue=1;var n=Symbol.for("react.transitional.element"),o=Symbol.for("react.fragment");function f(g,b,h){var E=null;if(h!==void 0&&(E=""+h),b.key!==void 0&&(E=""+b.key),"key"in b){h={};for(var C in b)C!=="key"&&(h[C]=b[C])}else h=b;return b=h.ref,{$$typeof:n,type:g,key:E,ref:b!==void 0?b:null,props:h}}return K.Fragment=o,K.jsx=f,K.jsxs=f,K}var ee={};/**
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 ge;function _e(){return ge||(ge=1,process.env.NODE_ENV!=="production"&&function(){function u(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===te?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case P:return"Fragment";case j:return"Profiler";case W:return"StrictMode";case ee:return"Suspense";case re:return"SuspenseList";case V: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 D:return"Portal";case M:return(e.displayName||"Context")+".Provider";case H:return(e._context.displayName||"Context")+".Consumer";case K:var o=e.render;return e=e.displayName,e||(e=o.displayName||o.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ue:return o=e.displayName||null,o!==null?o:u(e.type)||"Memo";case B:o=e._payload,e=e._init;try{return u(e(o))}catch{}}return null}function c(e){return""+e}function l(e){try{c(e);var o=!1}catch{o=!0}if(o){o=console;var a=o.error,g=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return a.call(o,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",g),c(e)}}function m(e){if(e===P)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===B)return"<...>";try{var o=u(e);return o?"<"+o+">":"<...>"}catch{return"<...>"}}function i(){var e=L.A;return e===null?null:e.getOwner()}function f(){return Error("react-stack-top-frame")}function C(e){if(Y.call(e,"key")){var o=Object.getOwnPropertyDescriptor(e,"key").get;if(o&&o.isReactWarning)return!1}return e.key!==void 0}function b(e,o){function a(){O||(O=!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)",o))}a.isReactWarning=!0,Object.defineProperty(e,"key",{get:a,configurable:!0})}function _(){var e=u(this.type);return U[e]||(U[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 A(e,o,a,g,v,p,J,z){return a=p.ref,e={$$typeof:S,type:e,key:o,props:p,_owner:v},(a!==void 0?a:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:_}):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:J}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:z}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function h(e,o,a,g,v,p,J,z){var R=o.children;if(R!==void 0)if(g)if(ne(R)){for(g=0;g<R.length;g++)E(R[g]);Object.freeze&&Object.freeze(R)}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 E(R);if(Y.call(o,"key")){R=u(e);var T=Object.keys(o).filter(function(ae){return ae!=="key"});g=0<T.length?"{key: someKey, "+T.join(": ..., ")+": ...}":"{key: someKey}",I[R+g]||(T=0<T.length?"{"+T.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
17
+ */var ae;function Ee(){return ae||(ae=1,process.env.NODE_ENV!=="production"&&function(){function n(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===z?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case d:return"Fragment";case Y:return"Profiler";case _:return"StrictMode";case re:return"Suspense";case te: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 i:return"Portal";case I:return(e.displayName||"Context")+".Provider";case W:return(e._context.displayName||"Context")+".Consumer";case q:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case se:return a=e.displayName||null,a!==null?a:n(e.type)||"Memo";case J:a=e._payload,e=e._init;try{return n(e(a))}catch{}}return null}function o(e){return""+e}function f(e){try{o(e);var a=!1}catch{a=!0}if(a){a=console;var R=a.error,v=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return R.call(a,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",v),o(e)}}function g(e){if(e===d)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===J)return"<...>";try{var a=n(e);return a?"<"+a+">":"<...>"}catch{return"<...>"}}function b(){var e=P.A;return e===null?null:e.getOwner()}function h(){return Error("react-stack-top-frame")}function E(e){if(M.call(e,"key")){var a=Object.getOwnPropertyDescriptor(e,"key").get;if(a&&a.isReactWarning)return!1}return e.key!==void 0}function C(e,a){function R(){G||(G=!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)",a))}R.isReactWarning=!0,Object.defineProperty(e,"key",{get:R,configurable:!0})}function p(){var e=n(this.type);return H[e]||(H[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,a,R,v,w,A,L,D){return R=A.ref,e={$$typeof:u,type:e,key:a,props:A,_owner:w},(R!==void 0?R:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:p}):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:L}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:D}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function c(e,a,R,v,w,A,L,D){var F=a.children;if(F!==void 0)if(v)if(x(F)){for(v=0;v<F.length;v++)m(F[v]);Object.freeze&&Object.freeze(F)}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(F);if(M.call(a,"key")){F=n(e);var V=Object.keys(a).filter(function(s){return s!=="key"});v=0<V.length?"{key: someKey, "+V.join(": ..., ")+": ...}":"{key: someKey}",Z[F+v]||(V=0<V.length?"{"+V.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} />`,g,R,T,R),I[R+g]=!0)}if(R=null,a!==void 0&&(l(a),R=""+a),C(o)&&(l(o.key),R=""+o.key),"key"in o){a={};for(var G in o)G!=="key"&&(a[G]=o[G])}else a=o;return R&&b(a,typeof e=="function"?e.displayName||e.name||"Unknown":e),A(e,R,p,v,i(),a,J,z)}function E(e){typeof e=="object"&&e!==null&&e.$$typeof===S&&e._store&&(e._store.validated=1)}var d=t,S=Symbol.for("react.transitional.element"),D=Symbol.for("react.portal"),P=Symbol.for("react.fragment"),W=Symbol.for("react.strict_mode"),j=Symbol.for("react.profiler"),H=Symbol.for("react.consumer"),M=Symbol.for("react.context"),K=Symbol.for("react.forward_ref"),ee=Symbol.for("react.suspense"),re=Symbol.for("react.suspense_list"),ue=Symbol.for("react.memo"),B=Symbol.for("react.lazy"),V=Symbol.for("react.activity"),te=Symbol.for("react.client.reference"),L=d.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Y=Object.prototype.hasOwnProperty,ne=Array.isArray,N=console.createTask?console.createTask:function(){return null};d={"react-stack-bottom-frame":function(e){return e()}};var O,U={},q=d["react-stack-bottom-frame"].bind(d,f)(),$=N(m(f)),I={};Q.Fragment=P,Q.jsx=function(e,o,a,g,v){var p=1e4>L.recentlyCreatedOwnerStacks++;return h(e,o,a,!1,g,v,p?Error("react-stack-top-frame"):q,p?N(m(e)):$)},Q.jsxs=function(e,o,a,g,v){var p=1e4>L.recentlyCreatedOwnerStacks++;return h(e,o,a,!0,g,v,p?Error("react-stack-top-frame"):q,p?N(m(e)):$)}}()),Q}var ke;function Te(){return ke||(ke=1,process.env.NODE_ENV==="production"?oe.exports=pe():oe.exports=_e()),oe.exports}var he=Te();const k=()=>{},ye=t.createContext({ref:null,watch:null,actions:{reset:k,setValue:k,getValues:k,setError:k,clearError:k,clearErrors:k,checkValidity:k,getNumberFields:k,getFieldValidity:k,getDefaultValues:k,setFieldStateProperty:k,getControlledFields:k},registerController:k,registerHookWatcher:k,lastReloadedAt:k,registerOnchange:k,loadFormValues:k,getWatchValue:k}),fe=()=>t.useContext(ye),Oe=({id:u,control:c,method:l,action:m,children:i,onSubmit:f=()=>{},onInput:C=()=>{},onChange:b=()=>{},onReset:_=()=>{},numberFields:A=[],className:h,...E})=>(t.useEffect(()=>c.registerOnchange(b),[b]),he.jsx(ye.Provider,{value:c,children:he.jsx("form",{id:u,ref:c.ref,action:m,method:l,className:h,onInput:C,onSubmit:d=>{l||d.preventDefault();const S=c.loadFormValues();f(S)},onChange:d=>{const S=d.target.name;c.actions.getControlledFields()[S]||c.actions.setValue(S,d.target.value)},onReset:d=>{c.actions.reset(),_(d)},...E,children:i},c.lastReloadedAt)})),Ce=({control:u,name:c,compute:l})=>{const{getWatchValue:m,registerHookWatcher:i}=u||fe(),f=m({name:c,compute:l}),[C,b]=t.useState(f);return t.useEffect(()=>i({name:c,compute:l,setValue:b,computeValue:f}),[]),C},ve=({name:u,defaultValue:c})=>{const{actions:l,registerController:m}=fe(),i=t.useRef(),f=l.getDefaultValues()[u]||c,[C,b]=t.useState(f),_=Ce({name:`fieldStates.${u}.customState`}),A=t.useCallback(E=>{l.setFieldStateProperty(u,"customState",E)},[]),h=t.useCallback((E,{shouldDirty:d=!0,shouldOnChange:S=!0}={})=>{l.setValue(u,E,{shouldDirty:d,shouldOnChange:S}),b(E)},[l.setValue]);return t.useEffect(()=>m(u,b),[]),{ref:i,name:u,defaultValue:f,value:C,onChange:h,customState:_,setCustomState:A}},Ae=({name:u,defaultValue:c,render:l=({ref:m,name:i,defaultValue:f,value:C,onChange:b,customState:_,setCustomState:A})=>null})=>{const m=ve({name:u,defaultValue:c});return l(m)},Pe=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"],Se=u=>{typeof u.setCustomValidity=="function"&&u.setCustomValidity("");let c=u.validity;console.log(u.valid);let l=Pe.find(m=>c[m]);if(l)return{type:l,message:u.validationMessage}},je=()=>{const[,u]=t.useState({});return t.useCallback(()=>u({}),[])},Fe=()=>{const[u,c]=t.useState(),l=t.useCallback(()=>c(new Date().toString()),[]);return[u,l]},xe=[],Ve={},Ne=({numberFields:u=xe,defaultValues:c=Ve,shouldUnRegister:l=!1,shouldConvertNumber:m=!1}={})=>{const i=je(),[f,C]=Fe(),b=t.useRef(),_=t.useRef(()=>{}),A=t.useRef(!1),h=t.useRef(c),E=t.useRef(c),d=t.useRef(new Set),S=t.useRef(u),D=t.useRef({}),P=t.useRef([]),W=t.useRef([]),j=t.useRef({}),H=t.useRef(0),M=t.useRef({}),K=t.useCallback(()=>{M.current=Object.keys(E.current).reduce((r,n)=>({...r,[n]:{isDirty:!1,isTouched:!1,customState:null}}),{})},[]),ee=t.useCallback((r={})=>{E.current={...E.current,...r},h.current={...E.current},H.current=0,A.current=!1,j.current={},S.current=u,d.current=new Set,W.current=[],P.current=[],D.current={},K(),u.length>0&&(m=!0),C()},[]),re=t.useCallback(()=>!!Object.values(N()).find(r=>r.isDirty),[]),ue=t.useCallback(()=>!!Object.values(Y()).find(r=>!!r),[]),B=t.useCallback(r=>Se(r.target),[]),V=t.useCallback(r=>r?h.current[r]:h.current,[]),te=t.useCallback(()=>E.current,[]),L=t.useCallback(()=>S.current,[]),Y=t.useCallback(()=>j.current,[]),ne=t.useCallback(()=>D.current,[]),N=t.useCallback(()=>M.current,[]),O=t.useCallback(({name:r,compute:n})=>{var y;if(typeof n=="function")return n(V());if(Array.isArray(r)){const F={};return r.forEach(x=>{F[x]=O({name:x})}),F}if(r==="isDirty")return re();if(r==="isError")return ue();if(r==="values")return{...V()};if(r==="errors")return{...Y()};if(r==="fieldStates")return{...N()};const s=r.split(".");if(s.length>1){const F=s[1];if(s[0]==="errors")return s.length===2?Y()[F]:Y();if(s[0]==="fieldStates"){if(s.length===2)return{...N()[F]};const x=s[2];return(y=N()[F])==null?void 0:y[x]}}return V()[r]},[]),U=r=>{W.current.forEach(n=>{let s;if(typeof n.name=="string"?s=r(n):n.name.forEach(y=>{s||(s=r({...n,name:y}))}),s){const y=O(n);n.setValue(y)}})},q=r=>{const n=({name:s})=>s==="isError"||s==="errors"||(r?s===`errors.${r}`:s.includes("errors"));[...d.current].forEach(s=>{n({name:s})&&i()}),U(n)},$=t.useCallback((r,n)=>{j.current[r]=n,q(r)},[]),I=t.useCallback(r=>{j.current[r]&&(j.current[r]=null,q(r))},[]),e=t.useCallback(()=>{Object.keys(j.current)!==0&&(j.current={},q())},[]),o=t.useCallback(r=>{const n=Se(r.target);n?$(r.target.name,n):I(r.target.name)},[$,I]),a=t.useCallback((r,n,s)=>{const y=M.current[r];if(y[n]!==s){M.current[r]={...y,[n]:s};const x=({name:w})=>w==="fieldStates"||w===`fieldStates.${r}`||w===`fieldStates.${r}.${n}`;if([...d.current].forEach(w=>{x({name:w})&&i()}),n==="customState"){P.current.forEach(({name:w,setValue:se})=>{w.includes(r)&&se(s)});return}U(x)}}),g=t.useCallback((r,n,{shouldDirty:s=!0,shouldOnChange:y=!0}={})=>{m&&S.current.includes(r)&&(n=Number(n)||void 0);const F=h.current[r],x=M.current[r],se=D.current[r];if(a(r,"isTouched",!0),s){const X=n!==E.current[r];x.isDirty!==X&&a(r,"isDirty",X)}const ce=re(),de=A.current,me=n!==F;d.current.has(r)&&me&&i(),d.current.has("values")&&i(),d.current.has("isDirty")&&ce!==de&&i(),h.current[r]=n,se&&se(n),A.current=ce,U(X=>{const{name:le,compute:be,computeValue:Ee}=X;if(be){const ie=be(V());return ie!==Ee&&(X.computeValue=ie),ie!==Ee}if(le==="values")return!0;if(le==="isDirty")return ce!==de;if(le===r)return me}),y&&_.current(r,n,h.current)},[a]),v=t.useCallback(r=>{if(typeof r=="string")return d.current.add(r),O({name:r});if(Array.isArray(r)){const n={};return r.forEach(s=>{d.current.add(s),n[s]=O({name:s})}),n}return O({name:r})},[]),p=t.useCallback((r,n)=>{const s=D.current;return s[r]=n,()=>{l&&(delete s[r],delete h.current[r])}},[]),J=t.useCallback(r=>(_.current=r,()=>_.current=()=>{}),[]),z=t.useCallback(r=>{var s;const n=H.current;return(s=r.name)!=null&&s.includes("customState")?P.current.push({key:n,...r}):W.current.push({key:n,...r}),H.current++,()=>{W.current=W.current.filter(y=>y.key!==n),P.current=P.current.filter(y=>y.key!==n)}},[]),R=t.useCallback(()=>{const r=Object.fromEntries(new FormData(b.current)),n=D.current;return Object.keys(n).map(s=>{r[s]=h.current[s]}),m&&S.current.forEach(s=>r.hasOwnProperty(s)&&(r[s]=Number(r[s])||0)),r},[]),T=t.useMemo(()=>({reset:ee,setValue:g,getValues:V,setError:$,clearError:I,clearErrors:e,checkValidity:o,getNumberFields:L,getFieldValidity:B,getDefaultValues:te,setFieldStateProperty:a,getControlledFields:ne}),[ee,g,V,$,I,e,o,L,B,te,a,ne]),G=t.useMemo(()=>({ref:b,watch:v,actions:T,registerController:p,registerHookWatcher:z,lastReloadedAt:f,registerOnchange:J,loadFormValues:R,getWatchValue:O}),[b,v,T,p,z,f,J,R,O]),ae=t.useMemo(()=>({control:G,actions:T,watch:v}),[f,G,T,v]);return t.useLayoutEffect(()=>{if([...b.current.querySelectorAll("[name]")].forEach(n=>{!n.defaultValue&&E.current[n.name]&&(n.defaultValue=E.current[n.name]),n.type==="number"&&!S.current.includes(n.name)&&S.current.push(n.name)}),b.current){const n=R();h.current={...n},E.current={...n}}},[f]),t.useLayoutEffect(()=>{K()},[]),ae};exports.Controller=Ae;exports.Form=Oe;exports.useController=ve;exports.useForm=Ne;exports.useFormContext=fe;exports.useWatch=Ce;
22
+ <%s key={someKey} {...props} />`,v,F,V,F),Z[F+v]=!0)}if(F=null,R!==void 0&&(f(R),F=""+R),E(a)&&(f(a.key),F=""+a.key),"key"in a){R={};for(var r in a)r!=="key"&&(R[r]=a[r])}else R=a;return F&&C(R,typeof e=="function"?e.displayName||e.name||"Unknown":e),T(e,F,A,w,b(),R,L,D)}function m(e){typeof e=="object"&&e!==null&&e.$$typeof===u&&e._store&&(e._store.validated=1)}var l=t,u=Symbol.for("react.transitional.element"),i=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),Y=Symbol.for("react.profiler"),W=Symbol.for("react.consumer"),I=Symbol.for("react.context"),q=Symbol.for("react.forward_ref"),re=Symbol.for("react.suspense"),te=Symbol.for("react.suspense_list"),se=Symbol.for("react.memo"),J=Symbol.for("react.lazy"),j=Symbol.for("react.activity"),z=Symbol.for("react.client.reference"),P=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,M=Object.prototype.hasOwnProperty,x=Array.isArray,N=console.createTask?console.createTask:function(){return null};l={"react-stack-bottom-frame":function(e){return e()}};var G,H={},X=l["react-stack-bottom-frame"].bind(l,h)(),S=N(g(h)),Z={};ee.Fragment=d,ee.jsx=function(e,a,R,v,w){var A=1e4>P.recentlyCreatedOwnerStacks++;return c(e,a,R,!1,v,w,A?Error("react-stack-top-frame"):X,A?N(g(e)):S)},ee.jsxs=function(e,a,R,v,w){var A=1e4>P.recentlyCreatedOwnerStacks++;return c(e,a,R,!0,v,w,A?Error("react-stack-top-frame"):X,A?N(g(e)):S)}}()),ee}var ce;function ge(){return ce||(ce=1,process.env.NODE_ENV==="production"?ne.exports=me():ne.exports=Ee()),ne.exports}var le=ge();const k=()=>{},fe=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:{}}),oe=()=>t.useContext(fe),he=({id:n,control:o,method:f,action:g,children:b,onSubmit:h=()=>{},onInput:E=()=>{},onChange:C=()=>{},onBlur:p=()=>{},onReset:T=()=>{},numberFields:c=[],className:m,...l})=>(t.useEffect(()=>{const u=o.channels.subscribe("onChange",C),i=o.channels.subscribe("onBlur",p);return()=>{u(),i()}},[]),le.jsx(fe.Provider,{value:o,children:le.jsx("form",{id:n,ref:o.ref,action:g,method:f,className:m,onInput:E,onSubmit:u=>{f||u.preventDefault();const i=o.loadFormValues();h(i)},onChange:u=>{const i=u.target.name;o.actions.getControlledFields().has(i)||o.actions.setValue(i,u.target.value)},onBlur:u=>{const i=u.target.name;if(o.actions.getControlledFields().has(i))return;const d=u.target.value;o.channels.publish("onBlur",i,d,o.actions.getValues())},onReset:u=>{o.actions.reset(),T(u)},...l,children:b},o.lastReloadedAt)})),de=({control:n,name:o,compute:f})=>{const{getWatchValue:g,registerHookWatcher:b}=n||oe(),h=g({name:o,compute:f}),[E,C]=t.useState(h);return t.useEffect(()=>{const p=b({name:o,compute:f,value:E,setValue:C});return()=>p.forEach(T=>T())},[]),E},be=({name:n,defaultValue:o})=>{const{actions:f,registerController:g,channels:b}=oe(),h=t.useRef(),E=f.getDefaultValues()[n]||o,[C,p]=t.useState(E),T=de({name:`fieldStates.${n}.customState`}),c=t.useCallback(u=>{f.setFieldState(n,"customState",u)},[]),m=t.useCallback((u,{shouldDirty:i=!0,shouldOnChange:d=!0}={})=>{p(u),f.setValue(n,u,{shouldDirty:i,shouldOnChange:d})},[f.setValue]),l=t.useCallback(()=>{b.publish("onBlur",n,C,f.getValues())},[]);return t.useEffect(()=>g(n,p),[]),{ref:h,name:n,defaultValue:E,value:C,onChange:m,onBlur:l,customState:T,setCustomState:c}},Re=({name:n,defaultValue:o,render:f=({ref:g,name:b,defaultValue:h,value:E,onChange:C,onBlur:p,customState:T,setCustomState:c})=>null})=>{const g=be({name:n,defaultValue:o});return f(g)},ke=["errors","fieldStates","formState"],U=n=>ke.some(o=>n.startsWith(o))?n:"values."+n,Se=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"],ie=n=>{typeof n.setCustomValidity=="function"&&n.setCustomValidity("");let o=n.validity,f=Se.find(g=>o[g]);if(f)return{type:f,message:n.validationMessage}};class Ce{constructor(){this.events=new Map}getEvents(){return this.events}subscribe(o,f){return this.events.has(o)||this.events.set(o,new Set),this.events.get(o).add(f),()=>{var g;return(g=this.events.get(o))==null?void 0:g.delete(f)}}publish(o,...f){const g=this.events.get(o);g&&g.forEach(b=>b(...f)),this.events.forEach((b,h)=>{o.includes(h)&&b.forEach(E=>E(...f))})}reset(){this.events.clear()}}const ye=()=>{const n=t.useRef(new Ce),o=t.useCallback((b,...h)=>{n.current.publish(b,...h)},[]),f=t.useCallback((b,h)=>n.current.subscribe(b,h),[]),g=t.useCallback(()=>{n.current.reset()},[]);return{publish:o,subscribe:f,reset:g}},pe=()=>{const[n,o]=t.useState(),f=t.useCallback(()=>o(new Date().toString()),[]);return[n,f]},ve=()=>{const[,n]=t.useState({});return t.useCallback(()=>n({}),[])},Fe=({channels:n,getValues:o,getErrors:f,getFieldStates:g,getFormState:b})=>{const h=ve(),E=t.useCallback(({name:c,compute:m})=>{if(typeof m=="function")return m(o());if(Array.isArray(c)){const l={};return c.forEach(u=>{l[u]=E({name:u})}),l}return c.replaceAll(/\[(\d+)\]/g,".$1").split(".").reduce((l,u)=>l&&l[u]!==void 0?l[u]:void 0,{...o(),errors:{...f()},formState:{...b()},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()}),E({name:c})}if(Array.isArray(c)){const m={};return c.forEach(l=>{const u=U(l);n.subscribe(u,()=>{h()}),m[l]=E({name:l})}),m}throw new Error("Parameters of watch must be string or array of string")},[]),p=t.useCallback(({name:c,compute:m,value:l,setValue:u})=>{if(typeof m=="function")return[n.subscribe("values",()=>{const d=E({compute:m});d!==l&&u(d)})];if(c)if(typeof c=="string"){const i=U(c);return[n.subscribe(i,()=>{const _=E({name:c});_!==l&&u(_)})]}else if(Array.isArray(c)){const i=E({name:c}),d=[];return c.forEach(_=>{const Y=U(_),W=n.subscribe(Y,()=>{const I=E({name:_});i[_]!==I&&(i[_]=I,u({...i}))});d.push(W)}),d}else throw new Error("Parameters of name must be string or array of string or compute must be a function");else return[n.subscribe("values",()=>{u(o())})]},[]),T=t.useCallback((c,m)=>{if(typeof c===void 0)return n.subscribe("values",m);if(typeof c=="string"){const l=U(c);return n.subscribe(l,m)}if(Array.isArray(c)){const l={},u=[];return c.forEach(i=>{const d=U(i),_=n.subscribe(d,()=>{l[i]=E({name:i}),m(l)});u.push(_)}),u}},[n]);return{watch:C,registerHookWatcher:p,getWatchValue:E,subscribe:T}},Te=[],_e={},Ae=({numberFields:n=Te,defaultValues:o=_e,shouldUnRegister:f=!1,shouldConvertNumber:g=!1}={})=>{const[b,h]=pe(),E=t.useRef(),C=t.useRef(!1),p=t.useRef(!1),T=t.useRef(n),c=t.useRef(new Map),m=t.useRef({}),l=t.useRef({}),u=t.useRef(o),i=t.useRef(o),d=ye(),_=t.useCallback(()=>{l.current=Object.keys(i.current).reduce((r,s)=>({...r,[s]:{isError:!1,isDirty:!1,isTouched:!1,customState:null}}),{})},[]),Y=t.useCallback((r={})=>{i.current={...i.current,...r},u.current={...i.current},c.current.forEach((s,y)=>{s(i.current[y])}),C.current=!1,m.current={},T.current=n,c.current=new Map,d.reset(),_(),n.length>0&&(g=!0),h()},[]),W=t.useCallback(()=>{const r=Object.fromEntries(new FormData(E.current));return c.current.forEach(y=>{r[y]=u.current[y]}),g&&T.current.forEach(y=>r.hasOwnProperty(y)&&(r[y]=Number(r[y])||0)),r},[]),I=t.useCallback(()=>!!Object.values(M()).find(r=>r.isDirty),[]),q=t.useCallback(()=>!!Object.values(P()).find(r=>!!r),[]),re=t.useCallback(r=>ie(r.target),[]),te=t.useCallback(()=>i.current,[]),se=t.useCallback(()=>T.current,[]),J=t.useCallback(()=>c.current,[]),j=t.useCallback((r,s)=>s?Array.isArray(s)?s.map(y=>r[y]):r[s]:{...r},[]),z=t.useCallback(r=>j(u.current,r),[j]),P=t.useCallback(r=>j(m.current,r),[j]),M=t.useCallback(r=>j(l.current,r),[j]),x=t.useCallback(r=>j({isDirty:C.current,isError:p.current,errorFields:Object.keys(m.current).filter(s=>!!m.current[s]),dirtyFields:Object.keys(l.current).filter(s=>l.current[s].isDirty),touchedFields:Object.keys(l.current).filter(s=>l.current[s].isTouched)},r),[j]),{watch:N,registerHookWatcher:G,getWatchValue:H,subscribe:X}=Fe({channels:d,getValues:z,getErrors:P,getFieldStates:M,getFormState:x}),S=t.useCallback((r,s,y)=>{const O=l.current[r];O[s]!==y&&(l.current[r]={...O,[s]:y},d.publish(`fieldStates.${r}.${s}`,y),s==="isError"&&d.publish("formState.errorFields",x("errorFields")),s==="isDirty"&&d.publish("formState.dirtyFields",x("dirtyFields")),s==="isTouched"&&d.publish("formState.touchedFields",x("touchedFields")))},[]),Z=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 O=q();p.current!==O&&(p.current=O,d.publish("formState.isError",O))},[S]),a=t.useCallback(r=>{if(!m.current[r])return;m.current[r]=null,S(r,"isError",!1),d.publish(`errors.${r}`,null);const s=q();p.current!==s&&(p.current=s,d.publish("formState.isError",s))},[S]),R=t.useCallback(()=>{if(Object.keys(m.current)===0)return;m.current={},d.publish("errors",m.current);const r=q();p.current!==r&&(p.current=r,d.publish("formState.isError",r))},[]),v=t.useCallback(r=>{const s=ie(r.target);s?e(r.target.name,s):a(r.target.name)},[e,a]),w=t.useCallback((r,s,{shouldDirty:y=!0,shouldOnChange:O=!0}={})=>{if(s===u.current[r])return;g&&T.current.includes(r)&&(s=Number(s)||void 0),S(r,"isTouched",!0);const Q=s!==i.current[r];y&&l.current[r].isDirty!==Q&&S(r,"isDirty",Q);const $=I();C.current!==$&&(C.current=$,d.publish("formState.isDirty",$)),u.current[r]=s;const B=c.current.get(r);B&&B(s),d.publish(`values.${r}`,s,{shouldDirty:y,shouldOnChange:O}),O&&d.publish("onChange",r,s,u.current)},[S]),A=t.useCallback((r,s)=>(c.current.set(r,s),()=>{f&&c.current.delete(r)}),[]),L=t.useCallback((r,{keepError:s,keepDirty:y,keepTouched:O,keepCustomState:Q,defaultValue:$})=>{const B=c.current.get(r);if(!B)throw new Error(`Cannot reset "${r}" because it's uncontrolled field`);i.current[r]=$,u.current[r]=$,B&&B($),s||a(r),y||S(r,"isDirty",!1),O||S(r,"isTouched",!1),Q||S(r,"customState",null)},[a,S]),D=t.useMemo(()=>({subscribe:X,reset:Y,resetField:L,setValue:w,getValues:z,getErrors:P,getFieldStates:M,getFormState:x,setError:e,clearError:a,clearErrors:R,checkValidity:v,getNumberFields:se,getFieldValidity:re,getDefaultValues:te,setFieldState:S,resetFieldState:Z,getControlledFields:J}),[X,Y,L,w,z,P,M,x,e,a,R,v,se,re,te,S,Z,J]),F=t.useMemo(()=>({ref:E,watch:N,actions:D,registerController:A,registerHookWatcher:G,lastReloadedAt:b,loadFormValues:W,getWatchValue:H,channels:d}),[E,N,D,A,G,b,W,H,d]),V=t.useMemo(()=>({control:F,actions:D,watch:N}),[b,F,D,N]);return t.useLayoutEffect(()=>{if([...E.current.querySelectorAll("[name]")].forEach(s=>{!s.defaultValue&&i.current[s.name]&&(s.defaultValue=i.current[s.name]),s.type==="number"&&!T.current.includes(s.name)&&T.current.push(s.name)}),E.current){const s=W();u.current={...s},i.current={...s}}},[b]),t.useLayoutEffect(()=>{_()},[]),V};exports.Controller=Re;exports.Form=he;exports.useController=be;exports.useForm=Ae;exports.useFormContext=oe;exports.useWatch=de;