react-simple-formkit 2.0.4 → 2.1.5
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 +113 -30
- package/dist/react-simple-formkit.js +4 -4
- package/dist/react-simple-formkit.mjs +517 -397
- package/dist/react-simple-formkit.umd.js +4 -4
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -10,6 +10,7 @@ Supports managing forms as uncontrolled. State updates only when watched. Simple
|
|
|
10
10
|
- [Core concepts](#core-concepts)
|
|
11
11
|
- [Modes of input field](#modes-of-input-field)
|
|
12
12
|
- [Watching for updates](#watching-for-updates)
|
|
13
|
+
- [The Power of watch (Unified Observation)](#the-power-of-watch-unified-observation)
|
|
13
14
|
- [Manage values](#manage-values)
|
|
14
15
|
- [Get value](#get-value)
|
|
15
16
|
- [Set value](#set-value)
|
|
@@ -26,6 +27,9 @@ Supports managing forms as uncontrolled. State updates only when watched. Simple
|
|
|
26
27
|
- [Controller](#controller)
|
|
27
28
|
- [useController](#useController)
|
|
28
29
|
- [useWatch](#useWatch)
|
|
30
|
+
- [useFormContext](#useFormContext)
|
|
31
|
+
- [watch](#watch)
|
|
32
|
+
- [subscribe](#subscribe)
|
|
29
33
|
- [Examples](#examples)
|
|
30
34
|
- [Contact](#contact)
|
|
31
35
|
|
|
@@ -45,8 +49,9 @@ Supports managing forms as uncontrolled. State updates only when watched. Simple
|
|
|
45
49
|
- **Optimized for uncontrolled forms**: no unnecessary re-renders
|
|
46
50
|
- Comprehensive form management:
|
|
47
51
|
- [Values](#manage-values): get/set values, defaults, reset, ...
|
|
48
|
-
- [
|
|
49
|
-
- [
|
|
52
|
+
- [Form state](#manage-form-state): isDirty, isError, dirtyFields, touchedFields, errorFields, ...
|
|
53
|
+
- [Field states](#manage-field-states): isDirty, isTouched, isError, custom states, ...
|
|
54
|
+
- [Errors](#manage-errors): form errors, field errors, ...
|
|
50
55
|
|
|
51
56
|
# Quick start
|
|
52
57
|
|
|
@@ -135,6 +140,8 @@ Example:
|
|
|
135
140
|
</LocalizationProvider>
|
|
136
141
|
```
|
|
137
142
|
|
|
143
|
+
### `Full Example`
|
|
144
|
+
|
|
138
145
|
```
|
|
139
146
|
const { control, actions } = useForm();
|
|
140
147
|
|
|
@@ -176,28 +183,45 @@ return (
|
|
|
176
183
|
)
|
|
177
184
|
```
|
|
178
185
|
|
|
179
|
-
> **
|
|
186
|
+
> **Rule\*:** All fields in the form must follow one of the three modes above to ensure the form works correctly
|
|
180
187
|
|
|
181
188
|
## Watching for updates
|
|
182
189
|
|
|
183
|
-
State updates only when observed via `watch()
|
|
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.
|
|
184
191
|
|
|
185
192
|
- `watch()` will trigger a re-render at the form level.
|
|
186
193
|
- `useWatch()` will trigger a re-render only in the component where it is called.
|
|
187
194
|
- `onChange` is just a handler callback that is called when field values change.
|
|
195
|
+
- `onBlur` is just a handler callback that is called when field blurred.
|
|
196
|
+
|
|
197
|
+
> **Rule\*:** onBlur works for uncontrolled fields by default. But for controlled fields, you need to use onBlur when rendering a field. For captured fields, you need to use `actions.triggerFieldBlur(fieldName)` to trigger onBlur event.
|
|
198
|
+
|
|
199
|
+
### The Power of watch (Unified Observation)
|
|
200
|
+
|
|
201
|
+
The `watch` function (and `useWatch`, `subscribe`) is the "brain" of your form. Instead of having multiple hooks for different states, you can observe anything in the form using a unified dot-notation syntax:
|
|
202
|
+
|
|
203
|
+
| Target | Syntax Example | Description |
|
|
204
|
+
| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------- |
|
|
205
|
+
| **All Values** | `watch()` | Observe every field value in the form. |
|
|
206
|
+
| **Specific Value** | `watch("email")` | Observe changes for a specific field. |
|
|
207
|
+
| **Form State** | `watch("formState")` <br/> `watch("formState.isDirty")` <br/> `watch("formState.isError")` <br/> `watch("formState.dirtyFields")` <br/> `watch("formState.touchedFields")` <br/> `watch("formState.errorFields")` | Track if the form has been modified. |
|
|
208
|
+
| **Field States** | `watch("fieldStates")` <br/> `watch("fieldStates.email")` <br/> `watch("fieldStates.email.isDirty")` <br/> `watch("fieldStates.email.isTouched")` <br/> `watch("fieldStates.email.isError")` <br/> `watch("fieldStates.email.customState")` <br/> | Monitor if a field has been interacted with. |
|
|
209
|
+
| **Errors** | `watch("errors")` <br/> `watch("errors.email")` <br/> | Get real-time validation error messages. |
|
|
210
|
+
| **Multiple values** | `watch(["email", "errors.email", "fieldStates.email", "formState.isDirty"])` <br/> | Get real-time validation error messages. |
|
|
211
|
+
|
|
212
|
+
> **💡Why it matters\*:** This unified approach ensures you only need to learn one API to track the entire lifecycle of your form.
|
|
188
213
|
|
|
189
214
|
# Manage values
|
|
190
215
|
|
|
191
216
|
## Get value
|
|
192
217
|
|
|
193
218
|
```
|
|
194
|
-
// watch
|
|
195
219
|
const fieldName = watch("fieldName")
|
|
196
220
|
const fieldName2 = watch("fieldName2")
|
|
197
221
|
// Or
|
|
198
222
|
const { fieldName2, fieldName } = watch(["fieldName", "fieldName2"])
|
|
199
223
|
// Or
|
|
200
|
-
const values = watch(
|
|
224
|
+
const values = watch()
|
|
201
225
|
|
|
202
226
|
// useWatch
|
|
203
227
|
useWatch({ name: "fieldName" })
|
|
@@ -209,6 +233,8 @@ const { actions } = useForm()
|
|
|
209
233
|
console.log(actions.getValues())
|
|
210
234
|
```
|
|
211
235
|
|
|
236
|
+
> **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
|
|
237
|
+
|
|
212
238
|
## Set value
|
|
213
239
|
|
|
214
240
|
actions.setValue() can help to control value of a field. But that field must be controlled by Controller.
|
|
@@ -267,24 +293,43 @@ return (
|
|
|
267
293
|
);
|
|
268
294
|
```
|
|
269
295
|
|
|
270
|
-
# Manage
|
|
296
|
+
# Manage form state
|
|
297
|
+
|
|
298
|
+
## Get form states
|
|
299
|
+
|
|
300
|
+
```
|
|
301
|
+
const isFormDirty = watch("formState.isDirty")
|
|
302
|
+
const isFormError = watch("formState.isError")
|
|
303
|
+
const dirtyFields = watch("formState.dirtyFields")
|
|
304
|
+
const touchedFields = watch("formState.touchedFields")
|
|
305
|
+
const errorFields = watch("formState.errorFields")
|
|
306
|
+
// actions.getFormState()
|
|
307
|
+
const { actions } = useForm()
|
|
308
|
+
console.log(actions.getFormState())
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
> **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
|
|
312
|
+
|
|
313
|
+
# Manage field states
|
|
271
314
|
|
|
272
315
|
## Get field states
|
|
273
316
|
|
|
274
317
|
```
|
|
275
|
-
// watch() or useWatch()
|
|
276
|
-
const isFormDirty = watch("isDirty")
|
|
277
318
|
const { fieldName: {...}, fieldName2: {...} } = watch("fieldStates")
|
|
278
319
|
const { isDirty, isTouched } = watch("fieldStates.fieldName")
|
|
279
320
|
const isFieldDirty = watch("fieldStates.fieldName.isDirty")
|
|
280
321
|
const fieldCustomState = watch("fieldStates.fieldName.customState")
|
|
322
|
+
// actions.getFieldStates()
|
|
323
|
+
const { actions } = useForm()
|
|
324
|
+
console.log(actions.getFieldStates())
|
|
281
325
|
```
|
|
282
326
|
|
|
327
|
+
> **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
|
|
328
|
+
|
|
283
329
|
## Set field states
|
|
284
330
|
|
|
285
331
|
```
|
|
286
|
-
actions.
|
|
287
|
-
// This will trigger re-render at watch(), useWatch() and render function in Controller
|
|
332
|
+
actions.setFieldState('fieldName', 'customState', { hello: "world" })
|
|
288
333
|
```
|
|
289
334
|
|
|
290
335
|
# Manage errors
|
|
@@ -292,12 +337,16 @@ actions.setFieldStateProperty('fieldName', 'customState', { hello: "world" })
|
|
|
292
337
|
## Get field error
|
|
293
338
|
|
|
294
339
|
```
|
|
295
|
-
|
|
296
|
-
const isFormError = watch("isError")
|
|
297
|
-
const fieldError = watch("errors.fieldName")
|
|
340
|
+
const isFormError = watch("formState.isError")
|
|
298
341
|
const { fieldName, fieldName2 } = watch("errors")
|
|
342
|
+
const fieldError = watch("errors.fieldName")
|
|
343
|
+
// actions.getErrors()
|
|
344
|
+
const { actions } = useForm()
|
|
345
|
+
console.log(actions.getErrors())
|
|
299
346
|
```
|
|
300
347
|
|
|
348
|
+
> **Note\*:** watch(), useWatch(), and subscribe() share the same name format.
|
|
349
|
+
|
|
301
350
|
## Set field error
|
|
302
351
|
|
|
303
352
|
```
|
|
@@ -335,15 +384,21 @@ Return:
|
|
|
335
384
|
- `control`: contains methods and utilities to control the form.
|
|
336
385
|
- `watch(name)`: `Function` [Example](#manage-values)
|
|
337
386
|
- `actions` is an object that contains utilities
|
|
338
|
-
- `actions.reset()`: [Example](#default-values-and-reset)
|
|
339
|
-
- `actions.getValues()`: [Example](#manage-values)
|
|
340
|
-
- `actions.
|
|
341
|
-
- `actions.
|
|
342
|
-
- `actions.
|
|
343
|
-
- `actions.
|
|
344
|
-
- `actions.
|
|
345
|
-
- `actions.
|
|
346
|
-
- `actions.
|
|
387
|
+
- `actions.reset()`: `(newDefaultValues?: Object) => void` [Example](#default-values-and-reset)
|
|
388
|
+
- `actions.getValues()`: `(name?: String | Array) => Object` [Example](#manage-values)
|
|
389
|
+
- `actions.getErrors()`: `(name?: String | Array) => Object` [Example](#manage-errors)
|
|
390
|
+
- `actions.getFormState()`: `(name?: String | Array) => Object` [Example](#manage-form-state)
|
|
391
|
+
- `actions.getFieldStates()`: `(name?: String | Array) => Object` [Example](#manage-field-states)
|
|
392
|
+
- `actions.setValue()`: `(name: String, value: Any, options?: { shouldDirty?: Boolean, shouldTouched?: Boolean }) => void` [Example](#set-value)
|
|
393
|
+
- `actions.setError()`: `(name: String, error: Any) => void` [Example](#set-field-error)
|
|
394
|
+
- `actions.setFieldState()`: `(name: String, property: String, value: Any) => void` [Example](#set-field-states)
|
|
395
|
+
- `actions.triggerFieldBlur()`: `(name: String, value?: Any) => void`
|
|
396
|
+
- `actions.resetFieldState()`: `(name: String) => void`
|
|
397
|
+
- `actions.resetField()`: `(name: String) => void`
|
|
398
|
+
- `actions.clearError()`: `(name: String | Array) => void`
|
|
399
|
+
- `actions.clearErrors()`: `() => void`
|
|
400
|
+
- `actions.getNumberFields()`: `() => Array`
|
|
401
|
+
- `actions.getDefaultValues()`: `() => Object`
|
|
347
402
|
|
|
348
403
|
## Form
|
|
349
404
|
|
|
@@ -359,9 +414,9 @@ Generic props:
|
|
|
359
414
|
|
|
360
415
|
- `name`
|
|
361
416
|
- `defaultValue`
|
|
362
|
-
- `render({name, value, onChange, customState, setCustomState})`
|
|
417
|
+
- `render({name, value, onChange, onBlur, customState, setCustomState})`
|
|
363
418
|
|
|
364
|
-
## useController
|
|
419
|
+
## useController({ name, defaultValue })
|
|
365
420
|
|
|
366
421
|
Generic props:
|
|
367
422
|
|
|
@@ -370,23 +425,51 @@ Generic props:
|
|
|
370
425
|
|
|
371
426
|
Return: everything in render function above
|
|
372
427
|
|
|
373
|
-
## useWatch
|
|
428
|
+
## useWatch({ name, compute })
|
|
374
429
|
|
|
375
430
|
[Example](#manage-values)
|
|
376
431
|
|
|
377
432
|
Generic props:
|
|
378
433
|
|
|
379
|
-
- `name`: `String | Array
|
|
380
|
-
- compute
|
|
434
|
+
- `name`: `String | Array | undefined`. If undefined, it will return all input values
|
|
435
|
+
- `compute`: `Function` that will calculate from form values and return a value. It will make re-render when the result changes
|
|
436
|
+
|
|
437
|
+
Return:
|
|
438
|
+
|
|
439
|
+
- if compute is passed: the computed value
|
|
440
|
+
- if name is string: value of the field
|
|
441
|
+
- if name is array: object of values of the fields
|
|
442
|
+
- if name is undefined: object of all input values
|
|
381
443
|
|
|
382
|
-
## useFormContext
|
|
444
|
+
## useFormContext()
|
|
383
445
|
|
|
384
446
|
Return:
|
|
385
447
|
|
|
386
448
|
- `watch`
|
|
387
449
|
- `actions`
|
|
388
450
|
|
|
389
|
-
|
|
451
|
+
## watch(name)
|
|
452
|
+
|
|
453
|
+
Arguments:
|
|
454
|
+
|
|
455
|
+
- `name`: `String | Array | undefined`. If undefined, it will return all input values
|
|
456
|
+
|
|
457
|
+
Return:
|
|
458
|
+
|
|
459
|
+
- same with useWatch()
|
|
460
|
+
|
|
461
|
+
## subscribe(name, callback)
|
|
462
|
+
|
|
463
|
+
Arguments:
|
|
464
|
+
|
|
465
|
+
- `name`: `String | Array | undefined`. If undefined, it will return all input values
|
|
466
|
+
- `callback()`: `Function` receive value based on name parameter. Only be called when the value changes
|
|
467
|
+
|
|
468
|
+
Return:
|
|
469
|
+
|
|
470
|
+
- `unregister()`: `Function` that will unregister the callback
|
|
471
|
+
|
|
472
|
+
## Examples
|
|
390
473
|
|
|
391
474
|
- https://codesandbox.io/p/sandbox/react-simple-formkit-examples-rhmhjj
|
|
392
475
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react");var oe={exports:{}},
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react");var oe={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 ae;function Ee(){if(ae)return ee;ae=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 p in b)p!=="key"&&(h[p]=b[p])}else h=b;return b=h.ref,{$$typeof:n,type:g,key:E,ref:b!==void 0?b:null,props:h}}return ee.Fragment=o,ee.jsx=f,ee.jsxs=f,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 ce;function ge(){return ce||(ce=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 $:return"Profiler";case _: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 i:return"Portal";case Y:return(e.displayName||"Context")+".Provider";case D: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 ne: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,F=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.",F),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=x.A;return e===null?null:e.getOwner()}function h(){return Error("react-stack-top-frame")}function E(e){if(W.call(e,"key")){var a=Object.getOwnPropertyDescriptor(e,"key").get;if(a&&a.isReactWarning)return!1}return e.key!==void 0}function p(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 v(){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,F,w,A,I,B){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: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:I}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:B}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function c(e,a,R,F,w,A,I,B){var k=a.children;if(k!==void 0)if(F)if(N(k)){for(F=0;F<k.length;F++)m(k[F]);Object.freeze&&Object.freeze(k)}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(k);if(W.call(a,"key")){k=n(e);var P=Object.keys(a).filter(function(r){return r!=="key"});F=0<P.length?"{key: someKey, "+P.join(": ..., ")+": ...}":"{key: someKey}",Z[k+F]||(P=0<P.length?"{"+P.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} />`,F,k,P,k),Z[k+F]=!0)}if(k=null,R!==void 0&&(f(R),k=""+R),E(a)&&(f(a.key),k=""+a.key),"key"in a){R={};for(var Q in a)Q!=="key"&&(R[Q]=a[Q])}else R=a;return k&&p(R,typeof e=="function"?e.displayName||e.name||"Unknown":e),T(e,k,A,w,b(),R,I,B)}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"),$=Symbol.for("react.profiler"),D=Symbol.for("react.consumer"),Y=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=l.__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};l={"react-stack-bottom-frame":function(e){return e()}};var G,H={},X=l["react-stack-bottom-frame"].bind(l,h)(),C=V(g(h)),Z={};re.Fragment=d,re.jsx=function(e,a,R,F,w){var A=1e4>x.recentlyCreatedOwnerStacks++;return c(e,a,R,!1,F,w,A?Error("react-stack-top-frame"):X,A?V(g(e)):C)},re.jsxs=function(e,a,R,F,w){var A=1e4>x.recentlyCreatedOwnerStacks++;return c(e,a,R,!0,F,w,A?Error("react-stack-top-frame"):X,A?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=()=>{},de=t.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=()=>t.useContext(de),Re=({id:n,control:o,method:f,action:g,children:b,onSubmit:h=()=>{},onInput:E=()=>{},onChange:p=()=>{},onBlur:v=()=>{},onReset:T=()=>{},numberFields:c=[],className:m,...l})=>(t.useEffect(()=>{const u=o.channels.subscribe("onChange",p),i=o.channels.subscribe("onBlur",v);return()=>{u(),i()}},[]),ie.jsx(de.Provider,{value:o,children:ie.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)})),be=({control:n,name:o,compute:f})=>{const{getWatchValue:g,registerHookWatcher:b}=n||ue(),h=g({name:o,compute:f}),[E,p]=t.useState(h);return t.useEffect(()=>{const v=b({name:o,compute:f,value:E,setValue:p});return()=>v.forEach(T=>T())},[]),E},me=({name:n,defaultValue:o})=>{const{actions:f,registerController:g,channels:b}=ue(),h=t.useRef(),E=f.getDefaultValues()[n]||o,[p,v]=t.useState(E),T=be({name:`fieldStates.${n}.customState`}),c=t.useCallback(u=>{f.setFieldState(n,"customState",u)},[]),m=t.useCallback((u,{shouldDirty:i=!0,shouldOnChange:d=!0}={})=>{v(u),f.setValue(n,u,{shouldDirty:i,shouldOnChange:d})},[f.setValue]),l=t.useCallback(()=>{b.publish("onBlur",n,p,f.getValues())},[]);return t.useEffect(()=>g(n,v),[]),{ref:h,name:n,defaultValue:E,value:p,onChange:m,onBlur:l,customState:T,setCustomState:c}},ke=({name:n,defaultValue:o,render:f=({ref:g,name:b,defaultValue:h,value:E,onChange:p,onBlur:v,customState:T,setCustomState:c})=>null})=>{const g=me({name:n,defaultValue:o});return f(g)},Se=["errors","fieldStates","formState"],U=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,f=Ce.find(g=>o[g]);if(f)return{type:f,message:n.validationMessage}};class pe{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 pe),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}},ve=()=>{const[n,o]=t.useState(),f=t.useCallback(()=>o(new Date().toString()),[]);return[n,f]},Fe=()=>{const[,n]=t.useState({});return t.useCallback(()=>n({}),[])},Te=({channels:n,getValues:o,getErrors:f,getFieldStates:g,getFormState:b})=>{const h=Fe(),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()}})},[]),p=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")},[]),v=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 $=U(_),D=n.subscribe($,()=>{const Y=E({name:_});i[_]!==Y&&(i[_]=Y,u({...i}))});d.push(D)}),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:p,registerHookWatcher:v,getWatchValue:E,subscribe:T}},_e=[],Ae={},we=({numberFields:n=_e,defaultValues:o=Ae,shouldUnRegister:f=!1,shouldConvertNumber:g=!1}={})=>{const[b,h]=ve(),E=t.useRef(),p=t.useRef(!1),v=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}}),{})},[]),$=t.useCallback((r={})=>{i.current={...i.current,...r},u.current={...i.current},c.current.forEach((s,y)=>{s(i.current[y])}),p.current=!1,m.current={},T.current=n,c.current=new Map,d.reset(),_(),n.length>0&&(g=!0),h()},[]),D=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},[]),Y=t.useCallback(()=>!!Object.values(W()).find(r=>r.isDirty),[]),q=t.useCallback(()=>!!Object.values(x()).find(r=>!!r),[]),te=t.useCallback(r=>fe(r.target),[]),se=t.useCallback(()=>i.current,[]),ne=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]),x=t.useCallback(r=>j(m.current,r),[j]),W=t.useCallback(r=>j(l.current,r),[j]),N=t.useCallback(r=>j({isDirty:p.current,isError:v.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:V,registerHookWatcher:G,getWatchValue:H,subscribe:X}=Te({channels:d,getValues:z,getErrors:x,getFieldStates:W,getFormState:N}),C=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",N("errorFields")),s==="isDirty"&&d.publish("formState.dirtyFields",N("dirtyFields")),s==="isTouched"&&d.publish("formState.touchedFields",N("touchedFields")))},[]),Z=t.useCallback(r=>{C(r,"isError",!1),C(r,"isDirty",!1),C(r,"isTouched",!1),C(r,"customState",null)},[C]),e=t.useCallback((r,s)=>{if(m.current[r]===s)return;m.current[r]=s,C(r,"isError",!!s),d.publish(`errors.${r}`,s);const O=q();v.current!==O&&(v.current=O,d.publish("formState.isError",O))},[C]),a=t.useCallback(r=>{if(!m.current[r])return;m.current[r]=null,C(r,"isError",!1),d.publish(`errors.${r}`,null);const s=q();v.current!==s&&(v.current=s,d.publish("formState.isError",s))},[C]),R=t.useCallback(()=>{if(Object.keys(m.current)===0)return;m.current={},d.publish("errors",m.current);const r=q();v.current!==r&&(v.current=r,d.publish("formState.isError",r))},[]),F=t.useCallback(r=>{const s=fe(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),C(r,"isTouched",!0);const K=s!==i.current[r];y&&l.current[r].isDirty!==K&&C(r,"isDirty",K);const M=Y();p.current!==M&&(p.current=M,d.publish("formState.isDirty",M)),u.current[r]=s;const L=c.current.get(r);L&&L(s),d.publish(`values.${r}`,s,{shouldDirty:y,shouldOnChange:O}),O&&d.publish("onChange",r,s,u.current)},[C]),A=t.useCallback((r,s)=>(c.current.set(r,s),()=>{f&&c.current.delete(r)}),[]),I=t.useCallback((r,{keepError:s,keepDirty:y,keepTouched:O,keepCustomState:K,defaultValue:M})=>{const L=c.current.get(r);if(!L)throw new Error(`Cannot reset "${r}" because it's uncontrolled field`);i.current[r]=M,u.current[r]=M,L&&L(M),s||a(r),y||C(r,"isDirty",!1),O||C(r,"isTouched",!1),K||C(r,"customState",null)},[a,C]),B=t.useCallback((r,s=k.getValues(r))=>{d.publish("onBlur",r,s,k.getValues())},[]),k=t.useMemo(()=>({subscribe:X,reset:$,resetField:I,setValue:w,getValues:z,getErrors:x,getFieldStates:W,getFormState:N,setError:e,clearError:a,clearErrors:R,checkValidity:F,getNumberFields:ne,getFieldValidity:te,getDefaultValues:se,setFieldState:C,triggerFieldBlur:B,resetFieldState:Z,getControlledFields:J}),[X,$,I,w,z,x,W,N,e,a,R,F,ne,te,se,C,Z,B,J]),P=t.useMemo(()=>({ref:E,watch:V,actions:k,registerController:A,registerHookWatcher:G,lastReloadedAt:b,loadFormValues:D,getWatchValue:H,channels:d}),[E,V,k,A,G,b,D,H,d]),Q=t.useMemo(()=>({control:P,actions:k,watch:V}),[b,P,k,V]);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=D();u.current={...s},i.current={...s}}},[b]),t.useLayoutEffect(()=>{_()},[]),Q};exports.Controller=ke;exports.Form=Re;exports.useController=me;exports.useForm=we;exports.useFormContext=ue;exports.useWatch=be;
|