@connect-soft/form-generator 1.0.0 → 1.1.0-alpha10

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.
Files changed (34) hide show
  1. package/README.md +956 -188
  2. package/dist/index.js +4400 -0
  3. package/dist/index.js.map +1 -0
  4. package/dist/index.mjs +4329 -0
  5. package/dist/index.mjs.map +1 -0
  6. package/dist/types/components/form/array-field-renderer.d.ts +39 -0
  7. package/dist/types/components/form/array-field-renderer.d.ts.map +1 -0
  8. package/dist/types/components/form/create-template-fields.d.ts +3 -0
  9. package/dist/types/components/form/create-template-fields.d.ts.map +1 -0
  10. package/dist/types/components/form/field-renderer.d.ts +7 -0
  11. package/dist/types/components/form/field-renderer.d.ts.map +1 -0
  12. package/dist/types/components/form/fields-context.d.ts +26 -0
  13. package/dist/types/components/form/fields-context.d.ts.map +1 -0
  14. package/dist/types/components/form/form-generator-typed.d.ts +47 -0
  15. package/dist/types/components/form/form-generator-typed.d.ts.map +1 -0
  16. package/dist/types/components/form/form-generator.d.ts +51 -0
  17. package/dist/types/components/form/form-generator.d.ts.map +1 -0
  18. package/dist/types/components/form/form-utils.d.ts +47 -0
  19. package/dist/types/components/form/form-utils.d.ts.map +1 -0
  20. package/dist/types/components/form/index.d.ts +7 -0
  21. package/dist/types/components/form/index.d.ts.map +1 -0
  22. package/dist/types/index.d.ts +22 -0
  23. package/dist/types/index.d.ts.map +1 -0
  24. package/dist/types/lib/field-registry.d.ts +74 -0
  25. package/dist/types/lib/field-registry.d.ts.map +1 -0
  26. package/dist/types/lib/field-types.d.ts +151 -0
  27. package/dist/types/lib/field-types.d.ts.map +1 -0
  28. package/dist/types/lib/index.d.ts +7 -0
  29. package/dist/types/lib/index.d.ts.map +1 -0
  30. package/dist/types/lib/template-types.d.ts +55 -0
  31. package/dist/types/lib/template-types.d.ts.map +1 -0
  32. package/dist/types/setupTests.d.ts +2 -0
  33. package/dist/types/setupTests.d.ts.map +1 -0
  34. package/package.json +40 -131
package/dist/index.mjs ADDED
@@ -0,0 +1,4329 @@
1
+ import { jsx, jsxs, Fragment as Fragment$1 } from 'react/jsx-runtime';
2
+ import React, { createElement, Fragment, memo, useCallback, useContext, createContext, useRef, useMemo, useImperativeHandle } from 'react';
3
+ import * as n$1 from 'zod/v4/core';
4
+ import { c } from 'react/compiler-runtime';
5
+ import { z } from 'zod';
6
+ export { z } from 'zod';
7
+
8
+ var isCheckBoxInput = (element) => element.type === 'checkbox';
9
+
10
+ var isDateObject = (value) => value instanceof Date;
11
+
12
+ var isNullOrUndefined = (value) => value == null;
13
+
14
+ const isObjectType = (value) => typeof value === 'object';
15
+ var isObject = (value) => !isNullOrUndefined(value) &&
16
+ !Array.isArray(value) &&
17
+ isObjectType(value) &&
18
+ !isDateObject(value);
19
+
20
+ var getEventValue = (event) => isObject(event) && event.target
21
+ ? isCheckBoxInput(event.target)
22
+ ? event.target.checked
23
+ : event.target.value
24
+ : event;
25
+
26
+ var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
27
+
28
+ var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
29
+
30
+ var isPlainObject = (tempObject) => {
31
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
32
+ return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
33
+ };
34
+
35
+ var isWeb = typeof window !== 'undefined' &&
36
+ typeof window.HTMLElement !== 'undefined' &&
37
+ typeof document !== 'undefined';
38
+
39
+ function cloneObject(data) {
40
+ if (data instanceof Date) {
41
+ return new Date(data);
42
+ }
43
+ const isFileListInstance = typeof FileList !== 'undefined' && data instanceof FileList;
44
+ if (isWeb && (data instanceof Blob || isFileListInstance)) {
45
+ return data;
46
+ }
47
+ const isArray = Array.isArray(data);
48
+ if (!isArray && !(isObject(data) && isPlainObject(data))) {
49
+ return data;
50
+ }
51
+ const copy = isArray ? [] : Object.create(Object.getPrototypeOf(data));
52
+ for (const key in data) {
53
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
54
+ copy[key] = cloneObject(data[key]);
55
+ }
56
+ }
57
+ return copy;
58
+ }
59
+
60
+ var isKey = (value) => /^\w*$/.test(value);
61
+
62
+ var isUndefined = (val) => val === undefined;
63
+
64
+ var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
65
+
66
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
67
+
68
+ var get = (object, path, defaultValue) => {
69
+ if (!path || !isObject(object)) {
70
+ return defaultValue;
71
+ }
72
+ const result = (isKey(path) ? [path] : stringToPath(path)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);
73
+ return isUndefined(result) || result === object
74
+ ? isUndefined(object[path])
75
+ ? defaultValue
76
+ : object[path]
77
+ : result;
78
+ };
79
+
80
+ var isBoolean = (value) => typeof value === 'boolean';
81
+
82
+ var isFunction = (value) => typeof value === 'function';
83
+
84
+ var set = (object, path, value) => {
85
+ let index = -1;
86
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
87
+ const length = tempPath.length;
88
+ const lastIndex = length - 1;
89
+ while (++index < length) {
90
+ const key = tempPath[index];
91
+ let newValue = value;
92
+ if (index !== lastIndex) {
93
+ const objValue = object[key];
94
+ newValue =
95
+ isObject(objValue) || Array.isArray(objValue)
96
+ ? objValue
97
+ : !isNaN(+tempPath[index + 1])
98
+ ? []
99
+ : {};
100
+ }
101
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
102
+ return;
103
+ }
104
+ object[key] = newValue;
105
+ object = object[key];
106
+ }
107
+ };
108
+
109
+ const EVENTS = {
110
+ BLUR: 'blur',
111
+ FOCUS_OUT: 'focusout',
112
+ CHANGE: 'change',
113
+ };
114
+ const VALIDATION_MODE = {
115
+ onBlur: 'onBlur',
116
+ onChange: 'onChange',
117
+ onSubmit: 'onSubmit',
118
+ onTouched: 'onTouched',
119
+ all: 'all',
120
+ };
121
+ const INPUT_VALIDATION_RULES = {
122
+ max: 'max',
123
+ min: 'min',
124
+ maxLength: 'maxLength',
125
+ minLength: 'minLength',
126
+ pattern: 'pattern',
127
+ required: 'required',
128
+ validate: 'validate',
129
+ };
130
+
131
+ const HookFormContext = React.createContext(null);
132
+ HookFormContext.displayName = 'HookFormContext';
133
+ /**
134
+ * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
135
+ *
136
+ * @remarks
137
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
138
+ *
139
+ * @returns return all useForm methods
140
+ *
141
+ * @example
142
+ * ```tsx
143
+ * function App() {
144
+ * const methods = useForm();
145
+ * const onSubmit = data => console.log(data);
146
+ *
147
+ * return (
148
+ * <FormProvider {...methods} >
149
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
150
+ * <NestedInput />
151
+ * <input type="submit" />
152
+ * </form>
153
+ * </FormProvider>
154
+ * );
155
+ * }
156
+ *
157
+ * function NestedInput() {
158
+ * const { register } = useFormContext(); // retrieve all hook methods
159
+ * return <input {...register("test")} />;
160
+ * }
161
+ * ```
162
+ */
163
+ const useFormContext = () => React.useContext(HookFormContext);
164
+ /**
165
+ * A provider component that propagates the `useForm` methods to all children components via [React Context](https://react.dev/reference/react/useContext) API. To be used with {@link useFormContext}.
166
+ *
167
+ * @remarks
168
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
169
+ *
170
+ * @param props - all useForm methods
171
+ *
172
+ * @example
173
+ * ```tsx
174
+ * function App() {
175
+ * const methods = useForm();
176
+ * const onSubmit = data => console.log(data);
177
+ *
178
+ * return (
179
+ * <FormProvider {...methods} >
180
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
181
+ * <NestedInput />
182
+ * <input type="submit" />
183
+ * </form>
184
+ * </FormProvider>
185
+ * );
186
+ * }
187
+ *
188
+ * function NestedInput() {
189
+ * const { register } = useFormContext(); // retrieve all hook methods
190
+ * return <input {...register("test")} />;
191
+ * }
192
+ * ```
193
+ */
194
+ const FormProvider = (props) => {
195
+ const { children, ...data } = props;
196
+ return (React.createElement(HookFormContext.Provider, { value: data }, children));
197
+ };
198
+
199
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
200
+ const result = {
201
+ defaultValues: control._defaultValues,
202
+ };
203
+ for (const key in formState) {
204
+ Object.defineProperty(result, key, {
205
+ get: () => {
206
+ const _key = key;
207
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
208
+ control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
209
+ }
210
+ localProxyFormState && (localProxyFormState[_key] = true);
211
+ return formState[_key];
212
+ },
213
+ });
214
+ }
215
+ return result;
216
+ };
217
+
218
+ const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
219
+
220
+ /**
221
+ * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
222
+ *
223
+ * @remarks
224
+ * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
225
+ *
226
+ * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
227
+ *
228
+ * @example
229
+ * ```tsx
230
+ * function App() {
231
+ * const { register, handleSubmit, control } = useForm({
232
+ * defaultValues: {
233
+ * firstName: "firstName"
234
+ * }});
235
+ * const { dirtyFields } = useFormState({
236
+ * control
237
+ * });
238
+ * const onSubmit = (data) => console.log(data);
239
+ *
240
+ * return (
241
+ * <form onSubmit={handleSubmit(onSubmit)}>
242
+ * <input {...register("firstName")} placeholder="First Name" />
243
+ * {dirtyFields.firstName && <p>Field is dirty.</p>}
244
+ * <input type="submit" />
245
+ * </form>
246
+ * );
247
+ * }
248
+ * ```
249
+ */
250
+ function useFormState(props) {
251
+ const methods = useFormContext();
252
+ const { control = methods.control, disabled, name, exact } = props || {};
253
+ const [formState, updateFormState] = React.useState(control._formState);
254
+ const _localProxyFormState = React.useRef({
255
+ isDirty: false,
256
+ isLoading: false,
257
+ dirtyFields: false,
258
+ touchedFields: false,
259
+ validatingFields: false,
260
+ isValidating: false,
261
+ isValid: false,
262
+ errors: false,
263
+ });
264
+ useIsomorphicLayoutEffect(() => control._subscribe({
265
+ name,
266
+ formState: _localProxyFormState.current,
267
+ exact,
268
+ callback: (formState) => {
269
+ !disabled &&
270
+ updateFormState({
271
+ ...control._formState,
272
+ ...formState,
273
+ });
274
+ },
275
+ }), [name, disabled, exact]);
276
+ React.useEffect(() => {
277
+ _localProxyFormState.current.isValid && control._setValid(true);
278
+ }, [control]);
279
+ return React.useMemo(() => getProxyFormState(formState, control, _localProxyFormState.current, false), [formState, control]);
280
+ }
281
+
282
+ var isString = (value) => typeof value === 'string';
283
+
284
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
285
+ if (isString(names)) {
286
+ isGlobal && _names.watch.add(names);
287
+ return get(formValues, names, defaultValue);
288
+ }
289
+ if (Array.isArray(names)) {
290
+ return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName),
291
+ get(formValues, fieldName)));
292
+ }
293
+ isGlobal && (_names.watchAll = true);
294
+ return formValues;
295
+ };
296
+
297
+ var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
298
+
299
+ function deepEqual(object1, object2, _internal_visited = new WeakSet()) {
300
+ if (isPrimitive(object1) || isPrimitive(object2)) {
301
+ return Object.is(object1, object2);
302
+ }
303
+ if (isDateObject(object1) && isDateObject(object2)) {
304
+ return Object.is(object1.getTime(), object2.getTime());
305
+ }
306
+ const keys1 = Object.keys(object1);
307
+ const keys2 = Object.keys(object2);
308
+ if (keys1.length !== keys2.length) {
309
+ return false;
310
+ }
311
+ if (_internal_visited.has(object1) || _internal_visited.has(object2)) {
312
+ return true;
313
+ }
314
+ _internal_visited.add(object1);
315
+ _internal_visited.add(object2);
316
+ for (const key of keys1) {
317
+ const val1 = object1[key];
318
+ if (!keys2.includes(key)) {
319
+ return false;
320
+ }
321
+ if (key !== 'ref') {
322
+ const val2 = object2[key];
323
+ if ((isDateObject(val1) && isDateObject(val2)) ||
324
+ (isObject(val1) && isObject(val2)) ||
325
+ (Array.isArray(val1) && Array.isArray(val2))
326
+ ? !deepEqual(val1, val2, _internal_visited)
327
+ : !Object.is(val1, val2)) {
328
+ return false;
329
+ }
330
+ }
331
+ }
332
+ return true;
333
+ }
334
+
335
+ /**
336
+ * Custom hook to subscribe to field change and isolate re-rendering at the component level.
337
+ *
338
+ * @remarks
339
+ *
340
+ * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
341
+ *
342
+ * @example
343
+ * ```tsx
344
+ * const { control } = useForm();
345
+ * const values = useWatch({
346
+ * name: "fieldName"
347
+ * control,
348
+ * })
349
+ * ```
350
+ */
351
+ function useWatch(props) {
352
+ const methods = useFormContext();
353
+ const { control = methods.control, name, defaultValue, disabled, exact, compute, } = props || {};
354
+ const _defaultValue = React.useRef(defaultValue);
355
+ const _compute = React.useRef(compute);
356
+ const _computeFormValues = React.useRef(undefined);
357
+ const _prevControl = React.useRef(control);
358
+ const _prevName = React.useRef(name);
359
+ _compute.current = compute;
360
+ const [value, updateValue] = React.useState(() => {
361
+ const defaultValue = control._getWatch(name, _defaultValue.current);
362
+ return _compute.current ? _compute.current(defaultValue) : defaultValue;
363
+ });
364
+ const getCurrentOutput = React.useCallback((values) => {
365
+ const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current);
366
+ return _compute.current ? _compute.current(formValues) : formValues;
367
+ }, [control._formValues, control._names, name]);
368
+ const refreshValue = React.useCallback((values) => {
369
+ if (!disabled) {
370
+ const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current);
371
+ if (_compute.current) {
372
+ const computedFormValues = _compute.current(formValues);
373
+ if (!deepEqual(computedFormValues, _computeFormValues.current)) {
374
+ updateValue(computedFormValues);
375
+ _computeFormValues.current = computedFormValues;
376
+ }
377
+ }
378
+ else {
379
+ updateValue(formValues);
380
+ }
381
+ }
382
+ }, [control._formValues, control._names, disabled, name]);
383
+ useIsomorphicLayoutEffect(() => {
384
+ if (_prevControl.current !== control ||
385
+ !deepEqual(_prevName.current, name)) {
386
+ _prevControl.current = control;
387
+ _prevName.current = name;
388
+ refreshValue();
389
+ }
390
+ return control._subscribe({
391
+ name,
392
+ formState: {
393
+ values: true,
394
+ },
395
+ exact,
396
+ callback: (formState) => {
397
+ refreshValue(formState.values);
398
+ },
399
+ });
400
+ }, [control, exact, name, refreshValue]);
401
+ React.useEffect(() => control._removeUnmounted());
402
+ // If name or control changed for this render, synchronously reflect the
403
+ // latest value so callers (like useController) see the correct value
404
+ // immediately on the same render.
405
+ // Optimize: Check control reference first before expensive deepEqual
406
+ const controlChanged = _prevControl.current !== control;
407
+ const prevName = _prevName.current;
408
+ // Cache the computed output to avoid duplicate calls within the same render
409
+ // We include shouldReturnImmediate in deps to ensure proper recomputation
410
+ const computedOutput = React.useMemo(() => {
411
+ if (disabled) {
412
+ return null;
413
+ }
414
+ const nameChanged = !controlChanged && !deepEqual(prevName, name);
415
+ const shouldReturnImmediate = controlChanged || nameChanged;
416
+ return shouldReturnImmediate ? getCurrentOutput() : null;
417
+ }, [disabled, controlChanged, name, prevName, getCurrentOutput]);
418
+ return computedOutput !== null ? computedOutput : value;
419
+ }
420
+
421
+ /**
422
+ * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
423
+ *
424
+ * @remarks
425
+ * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
426
+ *
427
+ * @param props - the path name to the form field value, and validation rules.
428
+ *
429
+ * @returns field properties, field and form state. {@link UseControllerReturn}
430
+ *
431
+ * @example
432
+ * ```tsx
433
+ * function Input(props) {
434
+ * const { field, fieldState, formState } = useController(props);
435
+ * return (
436
+ * <div>
437
+ * <input {...field} placeholder={props.name} />
438
+ * <p>{fieldState.isTouched && "Touched"}</p>
439
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
440
+ * </div>
441
+ * );
442
+ * }
443
+ * ```
444
+ */
445
+ function useController(props) {
446
+ const methods = useFormContext();
447
+ const { name, disabled, control = methods.control, shouldUnregister, defaultValue, exact = true, } = props;
448
+ const isArrayField = isNameInFieldArray(control._names.array, name);
449
+ const defaultValueMemo = React.useMemo(() => get(control._formValues, name, get(control._defaultValues, name, defaultValue)), [control, name, defaultValue]);
450
+ const value = useWatch({
451
+ control,
452
+ name,
453
+ defaultValue: defaultValueMemo,
454
+ exact,
455
+ });
456
+ const formState = useFormState({
457
+ control,
458
+ name,
459
+ exact,
460
+ });
461
+ const _props = React.useRef(props);
462
+ const _previousNameRef = React.useRef(undefined);
463
+ const _registerProps = React.useRef(control.register(name, {
464
+ ...props.rules,
465
+ value,
466
+ ...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}),
467
+ }));
468
+ _props.current = props;
469
+ const fieldState = React.useMemo(() => Object.defineProperties({}, {
470
+ invalid: {
471
+ enumerable: true,
472
+ get: () => !!get(formState.errors, name),
473
+ },
474
+ isDirty: {
475
+ enumerable: true,
476
+ get: () => !!get(formState.dirtyFields, name),
477
+ },
478
+ isTouched: {
479
+ enumerable: true,
480
+ get: () => !!get(formState.touchedFields, name),
481
+ },
482
+ isValidating: {
483
+ enumerable: true,
484
+ get: () => !!get(formState.validatingFields, name),
485
+ },
486
+ error: {
487
+ enumerable: true,
488
+ get: () => get(formState.errors, name),
489
+ },
490
+ }), [formState, name]);
491
+ const onChange = React.useCallback((event) => _registerProps.current.onChange({
492
+ target: {
493
+ value: getEventValue(event),
494
+ name: name,
495
+ },
496
+ type: EVENTS.CHANGE,
497
+ }), [name]);
498
+ const onBlur = React.useCallback(() => _registerProps.current.onBlur({
499
+ target: {
500
+ value: get(control._formValues, name),
501
+ name: name,
502
+ },
503
+ type: EVENTS.BLUR,
504
+ }), [name, control._formValues]);
505
+ const ref = React.useCallback((elm) => {
506
+ const field = get(control._fields, name);
507
+ if (field && field._f && elm) {
508
+ field._f.ref = {
509
+ focus: () => isFunction(elm.focus) && elm.focus(),
510
+ select: () => isFunction(elm.select) && elm.select(),
511
+ setCustomValidity: (message) => isFunction(elm.setCustomValidity) && elm.setCustomValidity(message),
512
+ reportValidity: () => isFunction(elm.reportValidity) && elm.reportValidity(),
513
+ };
514
+ }
515
+ }, [control._fields, name]);
516
+ const field = React.useMemo(() => ({
517
+ name,
518
+ value,
519
+ ...(isBoolean(disabled) || formState.disabled
520
+ ? { disabled: formState.disabled || disabled }
521
+ : {}),
522
+ onChange,
523
+ onBlur,
524
+ ref,
525
+ }), [name, disabled, formState.disabled, onChange, onBlur, ref, value]);
526
+ React.useEffect(() => {
527
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
528
+ const previousName = _previousNameRef.current;
529
+ if (previousName && previousName !== name && !isArrayField) {
530
+ control.unregister(previousName);
531
+ }
532
+ control.register(name, {
533
+ ..._props.current.rules,
534
+ ...(isBoolean(_props.current.disabled)
535
+ ? { disabled: _props.current.disabled }
536
+ : {}),
537
+ });
538
+ const updateMounted = (name, value) => {
539
+ const field = get(control._fields, name);
540
+ if (field && field._f) {
541
+ field._f.mount = value;
542
+ }
543
+ };
544
+ updateMounted(name, true);
545
+ if (_shouldUnregisterField) {
546
+ const value = cloneObject(get(control._options.defaultValues, name, _props.current.defaultValue));
547
+ set(control._defaultValues, name, value);
548
+ if (isUndefined(get(control._formValues, name))) {
549
+ set(control._formValues, name, value);
550
+ }
551
+ }
552
+ !isArrayField && control.register(name);
553
+ _previousNameRef.current = name;
554
+ return () => {
555
+ (isArrayField
556
+ ? _shouldUnregisterField && !control._state.action
557
+ : _shouldUnregisterField)
558
+ ? control.unregister(name)
559
+ : updateMounted(name, false);
560
+ };
561
+ }, [name, control, isArrayField, shouldUnregister]);
562
+ React.useEffect(() => {
563
+ control._setDisabledField({
564
+ disabled,
565
+ name,
566
+ });
567
+ }, [disabled, name, control]);
568
+ return React.useMemo(() => ({
569
+ field,
570
+ formState,
571
+ fieldState,
572
+ }), [field, formState, fieldState]);
573
+ }
574
+
575
+ /**
576
+ * Component based on `useController` hook to work with controlled component.
577
+ *
578
+ * @remarks
579
+ * [API](https://react-hook-form.com/docs/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
580
+ *
581
+ * @param props - the path name to the form field value, and validation rules.
582
+ *
583
+ * @returns provide field handler functions, field and form state.
584
+ *
585
+ * @example
586
+ * ```tsx
587
+ * function App() {
588
+ * const { control } = useForm<FormValues>({
589
+ * defaultValues: {
590
+ * test: ""
591
+ * }
592
+ * });
593
+ *
594
+ * return (
595
+ * <form>
596
+ * <Controller
597
+ * control={control}
598
+ * name="test"
599
+ * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
600
+ * <>
601
+ * <input
602
+ * onChange={onChange} // send value to hook form
603
+ * onBlur={onBlur} // notify when input is touched
604
+ * value={value} // return updated value
605
+ * ref={ref} // set ref for focus management
606
+ * />
607
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
608
+ * <p>{fieldState.isTouched ? "touched" : ""}</p>
609
+ * </>
610
+ * )}
611
+ * />
612
+ * </form>
613
+ * );
614
+ * }
615
+ * ```
616
+ */
617
+ const Controller = (props) => props.render(useController(props));
618
+
619
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
620
+ ? {
621
+ ...errors[name],
622
+ types: {
623
+ ...(errors[name] && errors[name].types ? errors[name].types : {}),
624
+ [type]: message || true,
625
+ },
626
+ }
627
+ : {};
628
+
629
+ var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
630
+
631
+ var createSubject = () => {
632
+ let _observers = [];
633
+ const next = (value) => {
634
+ for (const observer of _observers) {
635
+ observer.next && observer.next(value);
636
+ }
637
+ };
638
+ const subscribe = (observer) => {
639
+ _observers.push(observer);
640
+ return {
641
+ unsubscribe: () => {
642
+ _observers = _observers.filter((o) => o !== observer);
643
+ },
644
+ };
645
+ };
646
+ const unsubscribe = () => {
647
+ _observers = [];
648
+ };
649
+ return {
650
+ get observers() {
651
+ return _observers;
652
+ },
653
+ next,
654
+ subscribe,
655
+ unsubscribe,
656
+ };
657
+ };
658
+
659
+ function extractFormValues(fieldsState, formValues) {
660
+ const values = {};
661
+ for (const key in fieldsState) {
662
+ if (fieldsState.hasOwnProperty(key)) {
663
+ const fieldState = fieldsState[key];
664
+ const fieldValue = formValues[key];
665
+ if (fieldState && isObject(fieldState) && fieldValue) {
666
+ const nestedFieldsState = extractFormValues(fieldState, fieldValue);
667
+ if (isObject(nestedFieldsState)) {
668
+ values[key] = nestedFieldsState;
669
+ }
670
+ }
671
+ else if (fieldsState[key]) {
672
+ values[key] = fieldValue;
673
+ }
674
+ }
675
+ }
676
+ return values;
677
+ }
678
+
679
+ var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
680
+
681
+ var isFileInput = (element) => element.type === 'file';
682
+
683
+ var isHTMLElement = (value) => {
684
+ if (!isWeb) {
685
+ return false;
686
+ }
687
+ const owner = value ? value.ownerDocument : 0;
688
+ return (value instanceof
689
+ (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
690
+ };
691
+
692
+ var isMultipleSelect = (element) => element.type === `select-multiple`;
693
+
694
+ var isRadioInput = (element) => element.type === 'radio';
695
+
696
+ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
697
+
698
+ var live = (ref) => isHTMLElement(ref) && ref.isConnected;
699
+
700
+ function baseGet(object, updatePath) {
701
+ const length = updatePath.slice(0, -1).length;
702
+ let index = 0;
703
+ while (index < length) {
704
+ object = isUndefined(object) ? index++ : object[updatePath[index++]];
705
+ }
706
+ return object;
707
+ }
708
+ function isEmptyArray(obj) {
709
+ for (const key in obj) {
710
+ if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
711
+ return false;
712
+ }
713
+ }
714
+ return true;
715
+ }
716
+ function unset(object, path) {
717
+ const paths = Array.isArray(path)
718
+ ? path
719
+ : isKey(path)
720
+ ? [path]
721
+ : stringToPath(path);
722
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
723
+ const index = paths.length - 1;
724
+ const key = paths[index];
725
+ if (childObject) {
726
+ delete childObject[key];
727
+ }
728
+ if (index !== 0 &&
729
+ ((isObject(childObject) && isEmptyObject(childObject)) ||
730
+ (Array.isArray(childObject) && isEmptyArray(childObject)))) {
731
+ unset(object, paths.slice(0, -1));
732
+ }
733
+ return object;
734
+ }
735
+
736
+ var objectHasFunction = (data) => {
737
+ for (const key in data) {
738
+ if (isFunction(data[key])) {
739
+ return true;
740
+ }
741
+ }
742
+ return false;
743
+ };
744
+
745
+ function isTraversable(value) {
746
+ return Array.isArray(value) || (isObject(value) && !objectHasFunction(value));
747
+ }
748
+ function markFieldsDirty(data, fields = {}) {
749
+ for (const key in data) {
750
+ const value = data[key];
751
+ if (isTraversable(value)) {
752
+ fields[key] = Array.isArray(value) ? [] : {};
753
+ markFieldsDirty(value, fields[key]);
754
+ }
755
+ else if (!isUndefined(value)) {
756
+ fields[key] = true;
757
+ }
758
+ }
759
+ return fields;
760
+ }
761
+ function getDirtyFields(data, formValues, dirtyFieldsFromValues) {
762
+ if (!dirtyFieldsFromValues) {
763
+ dirtyFieldsFromValues = markFieldsDirty(formValues);
764
+ }
765
+ for (const key in data) {
766
+ const value = data[key];
767
+ if (isTraversable(value)) {
768
+ if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) {
769
+ dirtyFieldsFromValues[key] = markFieldsDirty(value, Array.isArray(value) ? [] : {});
770
+ }
771
+ else {
772
+ getDirtyFields(value, isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
773
+ }
774
+ }
775
+ else {
776
+ const formValue = formValues[key];
777
+ dirtyFieldsFromValues[key] = !deepEqual(value, formValue);
778
+ }
779
+ }
780
+ return dirtyFieldsFromValues;
781
+ }
782
+
783
+ const defaultResult = {
784
+ value: false,
785
+ isValid: false,
786
+ };
787
+ const validResult = { value: true, isValid: true };
788
+ var getCheckboxValue = (options) => {
789
+ if (Array.isArray(options)) {
790
+ if (options.length > 1) {
791
+ const values = options
792
+ .filter((option) => option && option.checked && !option.disabled)
793
+ .map((option) => option.value);
794
+ return { value: values, isValid: !!values.length };
795
+ }
796
+ return options[0].checked && !options[0].disabled
797
+ ? // @ts-expect-error expected to work in the browser
798
+ options[0].attributes && !isUndefined(options[0].attributes.value)
799
+ ? isUndefined(options[0].value) || options[0].value === ''
800
+ ? validResult
801
+ : { value: options[0].value, isValid: true }
802
+ : validResult
803
+ : defaultResult;
804
+ }
805
+ return defaultResult;
806
+ };
807
+
808
+ var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
809
+ ? value
810
+ : valueAsNumber
811
+ ? value === ''
812
+ ? NaN
813
+ : value
814
+ ? +value
815
+ : value
816
+ : valueAsDate && isString(value)
817
+ ? new Date(value)
818
+ : setValueAs
819
+ ? setValueAs(value)
820
+ : value;
821
+
822
+ const defaultReturn = {
823
+ isValid: false,
824
+ value: null,
825
+ };
826
+ var getRadioValue = (options) => Array.isArray(options)
827
+ ? options.reduce((previous, option) => option && option.checked && !option.disabled
828
+ ? {
829
+ isValid: true,
830
+ value: option.value,
831
+ }
832
+ : previous, defaultReturn)
833
+ : defaultReturn;
834
+
835
+ function getFieldValue(_f) {
836
+ const ref = _f.ref;
837
+ if (isFileInput(ref)) {
838
+ return ref.files;
839
+ }
840
+ if (isRadioInput(ref)) {
841
+ return getRadioValue(_f.refs).value;
842
+ }
843
+ if (isMultipleSelect(ref)) {
844
+ return [...ref.selectedOptions].map(({ value }) => value);
845
+ }
846
+ if (isCheckBoxInput(ref)) {
847
+ return getCheckboxValue(_f.refs).value;
848
+ }
849
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
850
+ }
851
+
852
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
853
+ const fields = {};
854
+ for (const name of fieldsNames) {
855
+ const field = get(_fields, name);
856
+ field && set(fields, name, field._f);
857
+ }
858
+ return {
859
+ criteriaMode,
860
+ names: [...fieldsNames],
861
+ fields,
862
+ shouldUseNativeValidation,
863
+ };
864
+ };
865
+
866
+ var isRegex = (value) => value instanceof RegExp;
867
+
868
+ var getRuleValue = (rule) => isUndefined(rule)
869
+ ? rule
870
+ : isRegex(rule)
871
+ ? rule.source
872
+ : isObject(rule)
873
+ ? isRegex(rule.value)
874
+ ? rule.value.source
875
+ : rule.value
876
+ : rule;
877
+
878
+ var getValidationModes = (mode) => ({
879
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
880
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
881
+ isOnChange: mode === VALIDATION_MODE.onChange,
882
+ isOnAll: mode === VALIDATION_MODE.all,
883
+ isOnTouch: mode === VALIDATION_MODE.onTouched,
884
+ });
885
+
886
+ const ASYNC_FUNCTION = 'AsyncFunction';
887
+ var hasPromiseValidation = (fieldReference) => !!fieldReference &&
888
+ !!fieldReference.validate &&
889
+ !!((isFunction(fieldReference.validate) &&
890
+ fieldReference.validate.constructor.name === ASYNC_FUNCTION) ||
891
+ (isObject(fieldReference.validate) &&
892
+ Object.values(fieldReference.validate).find((validateFunction) => validateFunction.constructor.name === ASYNC_FUNCTION)));
893
+
894
+ var hasValidation = (options) => options.mount &&
895
+ (options.required ||
896
+ options.min ||
897
+ options.max ||
898
+ options.maxLength ||
899
+ options.minLength ||
900
+ options.pattern ||
901
+ options.validate);
902
+
903
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
904
+ (_names.watchAll ||
905
+ _names.watch.has(name) ||
906
+ [..._names.watch].some((watchName) => name.startsWith(watchName) &&
907
+ /^\.\w+/.test(name.slice(watchName.length))));
908
+
909
+ const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
910
+ for (const key of fieldsNames || Object.keys(fields)) {
911
+ const field = get(fields, key);
912
+ if (field) {
913
+ const { _f, ...currentField } = field;
914
+ if (_f) {
915
+ if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
916
+ return true;
917
+ }
918
+ else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
919
+ return true;
920
+ }
921
+ else {
922
+ if (iterateFieldsByAction(currentField, action)) {
923
+ break;
924
+ }
925
+ }
926
+ }
927
+ else if (isObject(currentField)) {
928
+ if (iterateFieldsByAction(currentField, action)) {
929
+ break;
930
+ }
931
+ }
932
+ }
933
+ }
934
+ return;
935
+ };
936
+
937
+ function schemaErrorLookup(errors, _fields, name) {
938
+ const error = get(errors, name);
939
+ if (error || isKey(name)) {
940
+ return {
941
+ error,
942
+ name,
943
+ };
944
+ }
945
+ const names = name.split('.');
946
+ while (names.length) {
947
+ const fieldName = names.join('.');
948
+ const field = get(_fields, fieldName);
949
+ const foundError = get(errors, fieldName);
950
+ if (field && !Array.isArray(field) && name !== fieldName) {
951
+ return { name };
952
+ }
953
+ if (foundError && foundError.type) {
954
+ return {
955
+ name: fieldName,
956
+ error: foundError,
957
+ };
958
+ }
959
+ if (foundError && foundError.root && foundError.root.type) {
960
+ return {
961
+ name: `${fieldName}.root`,
962
+ error: foundError.root,
963
+ };
964
+ }
965
+ names.pop();
966
+ }
967
+ return {
968
+ name,
969
+ };
970
+ }
971
+
972
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
973
+ updateFormState(formStateData);
974
+ const { name, ...formState } = formStateData;
975
+ return (isEmptyObject(formState) ||
976
+ Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
977
+ Object.keys(formState).find((key) => _proxyFormState[key] ===
978
+ (!isRoot || VALIDATION_MODE.all)));
979
+ };
980
+
981
+ var shouldSubscribeByName = (name, signalName, exact) => !name ||
982
+ !signalName ||
983
+ name === signalName ||
984
+ convertToArrayPayload(name).some((currentName) => currentName &&
985
+ (exact
986
+ ? currentName === signalName
987
+ : currentName.startsWith(signalName) ||
988
+ signalName.startsWith(currentName)));
989
+
990
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
991
+ if (mode.isOnAll) {
992
+ return false;
993
+ }
994
+ else if (!isSubmitted && mode.isOnTouch) {
995
+ return !(isTouched || isBlurEvent);
996
+ }
997
+ else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
998
+ return !isBlurEvent;
999
+ }
1000
+ else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
1001
+ return isBlurEvent;
1002
+ }
1003
+ return true;
1004
+ };
1005
+
1006
+ var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
1007
+
1008
+ var updateFieldArrayRootError = (errors, error, name) => {
1009
+ const fieldArrayErrors = convertToArrayPayload(get(errors, name));
1010
+ set(fieldArrayErrors, 'root', error[name]);
1011
+ set(errors, name, fieldArrayErrors);
1012
+ return errors;
1013
+ };
1014
+
1015
+ function getValidateError(result, ref, type = 'validate') {
1016
+ if (isString(result) ||
1017
+ (Array.isArray(result) && result.every(isString)) ||
1018
+ (isBoolean(result) && !result)) {
1019
+ return {
1020
+ type,
1021
+ message: isString(result) ? result : '',
1022
+ ref,
1023
+ };
1024
+ }
1025
+ }
1026
+
1027
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
1028
+ ? validationData
1029
+ : {
1030
+ value: validationData,
1031
+ message: '',
1032
+ };
1033
+
1034
+ var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
1035
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, } = field._f;
1036
+ const inputValue = get(formValues, name);
1037
+ if (!mount || disabledFieldNames.has(name)) {
1038
+ return {};
1039
+ }
1040
+ const inputRef = refs ? refs[0] : ref;
1041
+ const setCustomValidity = (message) => {
1042
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
1043
+ inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
1044
+ inputRef.reportValidity();
1045
+ }
1046
+ };
1047
+ const error = {};
1048
+ const isRadio = isRadioInput(ref);
1049
+ const isCheckBox = isCheckBoxInput(ref);
1050
+ const isRadioOrCheckbox = isRadio || isCheckBox;
1051
+ const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
1052
+ isUndefined(ref.value) &&
1053
+ isUndefined(inputValue)) ||
1054
+ (isHTMLElement(ref) && ref.value === '') ||
1055
+ inputValue === '' ||
1056
+ (Array.isArray(inputValue) && !inputValue.length);
1057
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
1058
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
1059
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
1060
+ error[name] = {
1061
+ type: exceedMax ? maxType : minType,
1062
+ message,
1063
+ ref,
1064
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message),
1065
+ };
1066
+ };
1067
+ if (isFieldArray
1068
+ ? !Array.isArray(inputValue) || !inputValue.length
1069
+ : required &&
1070
+ ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
1071
+ (isBoolean(inputValue) && !inputValue) ||
1072
+ (isCheckBox && !getCheckboxValue(refs).isValid) ||
1073
+ (isRadio && !getRadioValue(refs).isValid))) {
1074
+ const { value, message } = isString(required)
1075
+ ? { value: !!required, message: required }
1076
+ : getValueAndMessage(required);
1077
+ if (value) {
1078
+ error[name] = {
1079
+ type: INPUT_VALIDATION_RULES.required,
1080
+ message,
1081
+ ref: inputRef,
1082
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
1083
+ };
1084
+ if (!validateAllFieldCriteria) {
1085
+ setCustomValidity(message);
1086
+ return error;
1087
+ }
1088
+ }
1089
+ }
1090
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
1091
+ let exceedMax;
1092
+ let exceedMin;
1093
+ const maxOutput = getValueAndMessage(max);
1094
+ const minOutput = getValueAndMessage(min);
1095
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
1096
+ const valueNumber = ref.valueAsNumber ||
1097
+ (inputValue ? +inputValue : inputValue);
1098
+ if (!isNullOrUndefined(maxOutput.value)) {
1099
+ exceedMax = valueNumber > maxOutput.value;
1100
+ }
1101
+ if (!isNullOrUndefined(minOutput.value)) {
1102
+ exceedMin = valueNumber < minOutput.value;
1103
+ }
1104
+ }
1105
+ else {
1106
+ const valueDate = ref.valueAsDate || new Date(inputValue);
1107
+ const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
1108
+ const isTime = ref.type == 'time';
1109
+ const isWeek = ref.type == 'week';
1110
+ if (isString(maxOutput.value) && inputValue) {
1111
+ exceedMax = isTime
1112
+ ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
1113
+ : isWeek
1114
+ ? inputValue > maxOutput.value
1115
+ : valueDate > new Date(maxOutput.value);
1116
+ }
1117
+ if (isString(minOutput.value) && inputValue) {
1118
+ exceedMin = isTime
1119
+ ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
1120
+ : isWeek
1121
+ ? inputValue < minOutput.value
1122
+ : valueDate < new Date(minOutput.value);
1123
+ }
1124
+ }
1125
+ if (exceedMax || exceedMin) {
1126
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
1127
+ if (!validateAllFieldCriteria) {
1128
+ setCustomValidity(error[name].message);
1129
+ return error;
1130
+ }
1131
+ }
1132
+ }
1133
+ if ((maxLength || minLength) &&
1134
+ !isEmpty &&
1135
+ (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
1136
+ const maxLengthOutput = getValueAndMessage(maxLength);
1137
+ const minLengthOutput = getValueAndMessage(minLength);
1138
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
1139
+ inputValue.length > +maxLengthOutput.value;
1140
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
1141
+ inputValue.length < +minLengthOutput.value;
1142
+ if (exceedMax || exceedMin) {
1143
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
1144
+ if (!validateAllFieldCriteria) {
1145
+ setCustomValidity(error[name].message);
1146
+ return error;
1147
+ }
1148
+ }
1149
+ }
1150
+ if (pattern && !isEmpty && isString(inputValue)) {
1151
+ const { value: patternValue, message } = getValueAndMessage(pattern);
1152
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
1153
+ error[name] = {
1154
+ type: INPUT_VALIDATION_RULES.pattern,
1155
+ message,
1156
+ ref,
1157
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
1158
+ };
1159
+ if (!validateAllFieldCriteria) {
1160
+ setCustomValidity(message);
1161
+ return error;
1162
+ }
1163
+ }
1164
+ }
1165
+ if (validate) {
1166
+ if (isFunction(validate)) {
1167
+ const result = await validate(inputValue, formValues);
1168
+ const validateError = getValidateError(result, inputRef);
1169
+ if (validateError) {
1170
+ error[name] = {
1171
+ ...validateError,
1172
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
1173
+ };
1174
+ if (!validateAllFieldCriteria) {
1175
+ setCustomValidity(validateError.message);
1176
+ return error;
1177
+ }
1178
+ }
1179
+ }
1180
+ else if (isObject(validate)) {
1181
+ let validationResult = {};
1182
+ for (const key in validate) {
1183
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
1184
+ break;
1185
+ }
1186
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
1187
+ if (validateError) {
1188
+ validationResult = {
1189
+ ...validateError,
1190
+ ...appendErrorsCurry(key, validateError.message),
1191
+ };
1192
+ setCustomValidity(validateError.message);
1193
+ if (validateAllFieldCriteria) {
1194
+ error[name] = validationResult;
1195
+ }
1196
+ }
1197
+ }
1198
+ if (!isEmptyObject(validationResult)) {
1199
+ error[name] = {
1200
+ ref: inputRef,
1201
+ ...validationResult,
1202
+ };
1203
+ if (!validateAllFieldCriteria) {
1204
+ return error;
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ setCustomValidity(true);
1210
+ return error;
1211
+ };
1212
+
1213
+ const defaultOptions = {
1214
+ mode: VALIDATION_MODE.onSubmit,
1215
+ reValidateMode: VALIDATION_MODE.onChange,
1216
+ shouldFocusError: true,
1217
+ };
1218
+ function createFormControl(props = {}) {
1219
+ let _options = {
1220
+ ...defaultOptions,
1221
+ ...props,
1222
+ };
1223
+ let _formState = {
1224
+ submitCount: 0,
1225
+ isDirty: false,
1226
+ isReady: false,
1227
+ isLoading: isFunction(_options.defaultValues),
1228
+ isValidating: false,
1229
+ isSubmitted: false,
1230
+ isSubmitting: false,
1231
+ isSubmitSuccessful: false,
1232
+ isValid: false,
1233
+ touchedFields: {},
1234
+ dirtyFields: {},
1235
+ validatingFields: {},
1236
+ errors: _options.errors || {},
1237
+ disabled: _options.disabled || false,
1238
+ };
1239
+ let _fields = {};
1240
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
1241
+ ? cloneObject(_options.defaultValues || _options.values) || {}
1242
+ : {};
1243
+ let _formValues = _options.shouldUnregister
1244
+ ? {}
1245
+ : cloneObject(_defaultValues);
1246
+ let _state = {
1247
+ action: false,
1248
+ mount: false,
1249
+ watch: false,
1250
+ keepIsValid: false,
1251
+ };
1252
+ let _names = {
1253
+ mount: new Set(),
1254
+ disabled: new Set(),
1255
+ unMount: new Set(),
1256
+ array: new Set(),
1257
+ watch: new Set(),
1258
+ };
1259
+ let delayErrorCallback;
1260
+ let timer = 0;
1261
+ const defaultProxyFormState = {
1262
+ isDirty: false,
1263
+ dirtyFields: false,
1264
+ validatingFields: false,
1265
+ touchedFields: false,
1266
+ isValidating: false,
1267
+ isValid: false,
1268
+ errors: false,
1269
+ };
1270
+ const _proxyFormState = {
1271
+ ...defaultProxyFormState,
1272
+ };
1273
+ let _proxySubscribeFormState = {
1274
+ ..._proxyFormState,
1275
+ };
1276
+ const _subjects = {
1277
+ array: createSubject(),
1278
+ state: createSubject(),
1279
+ };
1280
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1281
+ const debounce = (callback) => (wait) => {
1282
+ clearTimeout(timer);
1283
+ timer = setTimeout(callback, wait);
1284
+ };
1285
+ const _setValid = async (shouldUpdateValid) => {
1286
+ if (_state.keepIsValid) {
1287
+ return;
1288
+ }
1289
+ if (!_options.disabled &&
1290
+ (_proxyFormState.isValid ||
1291
+ _proxySubscribeFormState.isValid ||
1292
+ shouldUpdateValid)) {
1293
+ let isValid;
1294
+ if (_options.resolver) {
1295
+ isValid = isEmptyObject((await _runSchema()).errors);
1296
+ _updateIsValidating();
1297
+ }
1298
+ else {
1299
+ isValid = await executeBuiltInValidation(_fields, true);
1300
+ }
1301
+ if (isValid !== _formState.isValid) {
1302
+ _subjects.state.next({
1303
+ isValid,
1304
+ });
1305
+ }
1306
+ }
1307
+ };
1308
+ const _updateIsValidating = (names, isValidating) => {
1309
+ if (!_options.disabled &&
1310
+ (_proxyFormState.isValidating ||
1311
+ _proxyFormState.validatingFields ||
1312
+ _proxySubscribeFormState.isValidating ||
1313
+ _proxySubscribeFormState.validatingFields)) {
1314
+ (names || Array.from(_names.mount)).forEach((name) => {
1315
+ if (name) {
1316
+ isValidating
1317
+ ? set(_formState.validatingFields, name, isValidating)
1318
+ : unset(_formState.validatingFields, name);
1319
+ }
1320
+ });
1321
+ _subjects.state.next({
1322
+ validatingFields: _formState.validatingFields,
1323
+ isValidating: !isEmptyObject(_formState.validatingFields),
1324
+ });
1325
+ }
1326
+ };
1327
+ const _setFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1328
+ if (args && method && !_options.disabled) {
1329
+ _state.action = true;
1330
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1331
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
1332
+ shouldSetValues && set(_fields, name, fieldValues);
1333
+ }
1334
+ if (shouldUpdateFieldsAndState &&
1335
+ Array.isArray(get(_formState.errors, name))) {
1336
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
1337
+ shouldSetValues && set(_formState.errors, name, errors);
1338
+ unsetEmptyArray(_formState.errors, name);
1339
+ }
1340
+ if ((_proxyFormState.touchedFields ||
1341
+ _proxySubscribeFormState.touchedFields) &&
1342
+ shouldUpdateFieldsAndState &&
1343
+ Array.isArray(get(_formState.touchedFields, name))) {
1344
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1345
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1346
+ }
1347
+ if (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) {
1348
+ _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1349
+ }
1350
+ _subjects.state.next({
1351
+ name,
1352
+ isDirty: _getDirty(name, values),
1353
+ dirtyFields: _formState.dirtyFields,
1354
+ errors: _formState.errors,
1355
+ isValid: _formState.isValid,
1356
+ });
1357
+ }
1358
+ else {
1359
+ set(_formValues, name, values);
1360
+ }
1361
+ };
1362
+ const updateErrors = (name, error) => {
1363
+ set(_formState.errors, name, error);
1364
+ _subjects.state.next({
1365
+ errors: _formState.errors,
1366
+ });
1367
+ };
1368
+ const _setErrors = (errors) => {
1369
+ _formState.errors = errors;
1370
+ _subjects.state.next({
1371
+ errors: _formState.errors,
1372
+ isValid: false,
1373
+ });
1374
+ };
1375
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1376
+ const field = get(_fields, name);
1377
+ if (field) {
1378
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1379
+ isUndefined(defaultValue) ||
1380
+ (ref && ref.defaultChecked) ||
1381
+ shouldSkipSetValueAs
1382
+ ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
1383
+ : setFieldValue(name, defaultValue);
1384
+ _state.mount && !_state.action && _setValid();
1385
+ }
1386
+ };
1387
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1388
+ let shouldUpdateField = false;
1389
+ let isPreviousDirty = false;
1390
+ const output = {
1391
+ name,
1392
+ };
1393
+ if (!_options.disabled) {
1394
+ if (!isBlurEvent || shouldDirty) {
1395
+ if (_proxyFormState.isDirty || _proxySubscribeFormState.isDirty) {
1396
+ isPreviousDirty = _formState.isDirty;
1397
+ _formState.isDirty = output.isDirty = _getDirty();
1398
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
1399
+ }
1400
+ const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
1401
+ isPreviousDirty = !!get(_formState.dirtyFields, name);
1402
+ isCurrentFieldPristine
1403
+ ? unset(_formState.dirtyFields, name)
1404
+ : set(_formState.dirtyFields, name, true);
1405
+ output.dirtyFields = _formState.dirtyFields;
1406
+ shouldUpdateField =
1407
+ shouldUpdateField ||
1408
+ ((_proxyFormState.dirtyFields ||
1409
+ _proxySubscribeFormState.dirtyFields) &&
1410
+ isPreviousDirty !== !isCurrentFieldPristine);
1411
+ }
1412
+ if (isBlurEvent) {
1413
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
1414
+ if (!isPreviousFieldTouched) {
1415
+ set(_formState.touchedFields, name, isBlurEvent);
1416
+ output.touchedFields = _formState.touchedFields;
1417
+ shouldUpdateField =
1418
+ shouldUpdateField ||
1419
+ ((_proxyFormState.touchedFields ||
1420
+ _proxySubscribeFormState.touchedFields) &&
1421
+ isPreviousFieldTouched !== isBlurEvent);
1422
+ }
1423
+ }
1424
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
1425
+ }
1426
+ return shouldUpdateField ? output : {};
1427
+ };
1428
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
1429
+ const previousFieldError = get(_formState.errors, name);
1430
+ const shouldUpdateValid = (_proxyFormState.isValid || _proxySubscribeFormState.isValid) &&
1431
+ isBoolean(isValid) &&
1432
+ _formState.isValid !== isValid;
1433
+ if (_options.delayError && error) {
1434
+ delayErrorCallback = debounce(() => updateErrors(name, error));
1435
+ delayErrorCallback(_options.delayError);
1436
+ }
1437
+ else {
1438
+ clearTimeout(timer);
1439
+ delayErrorCallback = null;
1440
+ error
1441
+ ? set(_formState.errors, name, error)
1442
+ : unset(_formState.errors, name);
1443
+ }
1444
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
1445
+ !isEmptyObject(fieldState) ||
1446
+ shouldUpdateValid) {
1447
+ const updatedFormState = {
1448
+ ...fieldState,
1449
+ ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
1450
+ errors: _formState.errors,
1451
+ name,
1452
+ };
1453
+ _formState = {
1454
+ ..._formState,
1455
+ ...updatedFormState,
1456
+ };
1457
+ _subjects.state.next(updatedFormState);
1458
+ }
1459
+ };
1460
+ const _runSchema = async (name) => {
1461
+ _updateIsValidating(name, true);
1462
+ const result = await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1463
+ return result;
1464
+ };
1465
+ const executeSchemaAndUpdateState = async (names) => {
1466
+ const { errors } = await _runSchema(names);
1467
+ _updateIsValidating(names);
1468
+ if (names) {
1469
+ for (const name of names) {
1470
+ const error = get(errors, name);
1471
+ error
1472
+ ? set(_formState.errors, name, error)
1473
+ : unset(_formState.errors, name);
1474
+ }
1475
+ }
1476
+ else {
1477
+ _formState.errors = errors;
1478
+ }
1479
+ return errors;
1480
+ };
1481
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
1482
+ valid: true,
1483
+ }) => {
1484
+ for (const name in fields) {
1485
+ const field = fields[name];
1486
+ if (field) {
1487
+ const { _f, ...fieldValue } = field;
1488
+ if (_f) {
1489
+ const isFieldArrayRoot = _names.array.has(_f.name);
1490
+ const isPromiseFunction = field._f && hasPromiseValidation(field._f);
1491
+ if (isPromiseFunction && _proxyFormState.validatingFields) {
1492
+ _updateIsValidating([_f.name], true);
1493
+ }
1494
+ const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
1495
+ if (isPromiseFunction && _proxyFormState.validatingFields) {
1496
+ _updateIsValidating([_f.name]);
1497
+ }
1498
+ if (fieldError[_f.name]) {
1499
+ context.valid = false;
1500
+ if (shouldOnlyCheckValid || props.shouldUseNativeValidation) {
1501
+ break;
1502
+ }
1503
+ }
1504
+ !shouldOnlyCheckValid &&
1505
+ (get(fieldError, _f.name)
1506
+ ? isFieldArrayRoot
1507
+ ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
1508
+ : set(_formState.errors, _f.name, fieldError[_f.name])
1509
+ : unset(_formState.errors, _f.name));
1510
+ }
1511
+ !isEmptyObject(fieldValue) &&
1512
+ (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
1513
+ }
1514
+ }
1515
+ return context.valid;
1516
+ };
1517
+ const _removeUnmounted = () => {
1518
+ for (const name of _names.unMount) {
1519
+ const field = get(_fields, name);
1520
+ field &&
1521
+ (field._f.refs
1522
+ ? field._f.refs.every((ref) => !live(ref))
1523
+ : !live(field._f.ref)) &&
1524
+ unregister(name);
1525
+ }
1526
+ _names.unMount = new Set();
1527
+ };
1528
+ const _getDirty = (name, data) => !_options.disabled &&
1529
+ (name && data && set(_formValues, name, data),
1530
+ !deepEqual(getValues(), _defaultValues));
1531
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1532
+ ...(_state.mount
1533
+ ? _formValues
1534
+ : isUndefined(defaultValue)
1535
+ ? _defaultValues
1536
+ : isString(names)
1537
+ ? { [names]: defaultValue }
1538
+ : defaultValue),
1539
+ }, isGlobal, defaultValue);
1540
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : []));
1541
+ const setFieldValue = (name, value, options = {}) => {
1542
+ const field = get(_fields, name);
1543
+ let fieldValue = value;
1544
+ if (field) {
1545
+ const fieldReference = field._f;
1546
+ if (fieldReference) {
1547
+ !fieldReference.disabled &&
1548
+ set(_formValues, name, getFieldValueAs(value, fieldReference));
1549
+ fieldValue =
1550
+ isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
1551
+ ? ''
1552
+ : value;
1553
+ if (isMultipleSelect(fieldReference.ref)) {
1554
+ [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
1555
+ }
1556
+ else if (fieldReference.refs) {
1557
+ if (isCheckBoxInput(fieldReference.ref)) {
1558
+ fieldReference.refs.forEach((checkboxRef) => {
1559
+ if (!checkboxRef.defaultChecked || !checkboxRef.disabled) {
1560
+ if (Array.isArray(fieldValue)) {
1561
+ checkboxRef.checked = !!fieldValue.find((data) => data === checkboxRef.value);
1562
+ }
1563
+ else {
1564
+ checkboxRef.checked =
1565
+ fieldValue === checkboxRef.value || !!fieldValue;
1566
+ }
1567
+ }
1568
+ });
1569
+ }
1570
+ else {
1571
+ fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
1572
+ }
1573
+ }
1574
+ else if (isFileInput(fieldReference.ref)) {
1575
+ fieldReference.ref.value = '';
1576
+ }
1577
+ else {
1578
+ fieldReference.ref.value = fieldValue;
1579
+ if (!fieldReference.ref.type) {
1580
+ _subjects.state.next({
1581
+ name,
1582
+ values: cloneObject(_formValues),
1583
+ });
1584
+ }
1585
+ }
1586
+ }
1587
+ }
1588
+ (options.shouldDirty || options.shouldTouch) &&
1589
+ updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
1590
+ options.shouldValidate && trigger(name);
1591
+ };
1592
+ const setValues = (name, value, options) => {
1593
+ for (const fieldKey in value) {
1594
+ if (!value.hasOwnProperty(fieldKey)) {
1595
+ return;
1596
+ }
1597
+ const fieldValue = value[fieldKey];
1598
+ const fieldName = name + '.' + fieldKey;
1599
+ const field = get(_fields, fieldName);
1600
+ (_names.array.has(name) ||
1601
+ isObject(fieldValue) ||
1602
+ (field && !field._f)) &&
1603
+ !isDateObject(fieldValue)
1604
+ ? setValues(fieldName, fieldValue, options)
1605
+ : setFieldValue(fieldName, fieldValue, options);
1606
+ }
1607
+ };
1608
+ const setValue = (name, value, options = {}) => {
1609
+ const field = get(_fields, name);
1610
+ const isFieldArray = _names.array.has(name);
1611
+ const cloneValue = cloneObject(value);
1612
+ set(_formValues, name, cloneValue);
1613
+ if (isFieldArray) {
1614
+ _subjects.array.next({
1615
+ name,
1616
+ values: cloneObject(_formValues),
1617
+ });
1618
+ if ((_proxyFormState.isDirty ||
1619
+ _proxyFormState.dirtyFields ||
1620
+ _proxySubscribeFormState.isDirty ||
1621
+ _proxySubscribeFormState.dirtyFields) &&
1622
+ options.shouldDirty) {
1623
+ _subjects.state.next({
1624
+ name,
1625
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
1626
+ isDirty: _getDirty(name, cloneValue),
1627
+ });
1628
+ }
1629
+ }
1630
+ else {
1631
+ field && !field._f && !isNullOrUndefined(cloneValue)
1632
+ ? setValues(name, cloneValue, options)
1633
+ : setFieldValue(name, cloneValue, options);
1634
+ }
1635
+ if (isWatched(name, _names)) {
1636
+ _subjects.state.next({
1637
+ ..._formState,
1638
+ name,
1639
+ values: cloneObject(_formValues),
1640
+ });
1641
+ }
1642
+ else {
1643
+ _subjects.state.next({
1644
+ name: _state.mount ? name : undefined,
1645
+ values: cloneObject(_formValues),
1646
+ });
1647
+ }
1648
+ };
1649
+ const onChange = async (event) => {
1650
+ _state.mount = true;
1651
+ const target = event.target;
1652
+ let name = target.name;
1653
+ let isFieldValueUpdated = true;
1654
+ const field = get(_fields, name);
1655
+ const _updateIsFieldValueUpdated = (fieldValue) => {
1656
+ isFieldValueUpdated =
1657
+ Number.isNaN(fieldValue) ||
1658
+ (isDateObject(fieldValue) && isNaN(fieldValue.getTime())) ||
1659
+ deepEqual(fieldValue, get(_formValues, name, fieldValue));
1660
+ };
1661
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
1662
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
1663
+ if (field) {
1664
+ let error;
1665
+ let isValid;
1666
+ const fieldValue = target.type
1667
+ ? getFieldValue(field._f)
1668
+ : getEventValue(event);
1669
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1670
+ const shouldSkipValidation = (!hasValidation(field._f) &&
1671
+ !_options.resolver &&
1672
+ !get(_formState.errors, name) &&
1673
+ !field._f.deps) ||
1674
+ skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1675
+ const watched = isWatched(name, _names, isBlurEvent);
1676
+ set(_formValues, name, fieldValue);
1677
+ if (isBlurEvent) {
1678
+ if (!target || !target.readOnly) {
1679
+ field._f.onBlur && field._f.onBlur(event);
1680
+ delayErrorCallback && delayErrorCallback(0);
1681
+ }
1682
+ }
1683
+ else if (field._f.onChange) {
1684
+ field._f.onChange(event);
1685
+ }
1686
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent);
1687
+ const shouldRender = !isEmptyObject(fieldState) || watched;
1688
+ !isBlurEvent &&
1689
+ _subjects.state.next({
1690
+ name,
1691
+ type: event.type,
1692
+ values: cloneObject(_formValues),
1693
+ });
1694
+ if (shouldSkipValidation) {
1695
+ if (_proxyFormState.isValid || _proxySubscribeFormState.isValid) {
1696
+ if (_options.mode === 'onBlur') {
1697
+ if (isBlurEvent) {
1698
+ _setValid();
1699
+ }
1700
+ }
1701
+ else if (!isBlurEvent) {
1702
+ _setValid();
1703
+ }
1704
+ }
1705
+ return (shouldRender &&
1706
+ _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
1707
+ }
1708
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1709
+ if (_options.resolver) {
1710
+ const { errors } = await _runSchema([name]);
1711
+ _updateIsValidating([name]);
1712
+ _updateIsFieldValueUpdated(fieldValue);
1713
+ if (isFieldValueUpdated) {
1714
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1715
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1716
+ error = errorLookupResult.error;
1717
+ name = errorLookupResult.name;
1718
+ isValid = isEmptyObject(errors);
1719
+ }
1720
+ }
1721
+ else {
1722
+ _updateIsValidating([name], true);
1723
+ error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1724
+ _updateIsValidating([name]);
1725
+ _updateIsFieldValueUpdated(fieldValue);
1726
+ if (isFieldValueUpdated) {
1727
+ if (error) {
1728
+ isValid = false;
1729
+ }
1730
+ else if (_proxyFormState.isValid ||
1731
+ _proxySubscribeFormState.isValid) {
1732
+ isValid = await executeBuiltInValidation(_fields, true);
1733
+ }
1734
+ }
1735
+ }
1736
+ if (isFieldValueUpdated) {
1737
+ field._f.deps &&
1738
+ (!Array.isArray(field._f.deps) || field._f.deps.length > 0) &&
1739
+ trigger(field._f.deps);
1740
+ shouldRenderByError(name, isValid, error, fieldState);
1741
+ }
1742
+ }
1743
+ };
1744
+ const _focusInput = (ref, key) => {
1745
+ if (get(_formState.errors, key) && ref.focus) {
1746
+ ref.focus();
1747
+ return 1;
1748
+ }
1749
+ return;
1750
+ };
1751
+ const trigger = async (name, options = {}) => {
1752
+ let isValid;
1753
+ let validationResult;
1754
+ const fieldNames = convertToArrayPayload(name);
1755
+ if (_options.resolver) {
1756
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1757
+ isValid = isEmptyObject(errors);
1758
+ validationResult = name
1759
+ ? !fieldNames.some((name) => get(errors, name))
1760
+ : isValid;
1761
+ }
1762
+ else if (name) {
1763
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1764
+ const field = get(_fields, fieldName);
1765
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1766
+ }))).every(Boolean);
1767
+ !(!validationResult && !_formState.isValid) && _setValid();
1768
+ }
1769
+ else {
1770
+ validationResult = isValid = await executeBuiltInValidation(_fields);
1771
+ }
1772
+ _subjects.state.next({
1773
+ ...(!isString(name) ||
1774
+ ((_proxyFormState.isValid || _proxySubscribeFormState.isValid) &&
1775
+ isValid !== _formState.isValid)
1776
+ ? {}
1777
+ : { name }),
1778
+ ...(_options.resolver || !name ? { isValid } : {}),
1779
+ errors: _formState.errors,
1780
+ });
1781
+ options.shouldFocus &&
1782
+ !validationResult &&
1783
+ iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
1784
+ return validationResult;
1785
+ };
1786
+ const getValues = (fieldNames, config) => {
1787
+ let values = {
1788
+ ...(_state.mount ? _formValues : _defaultValues),
1789
+ };
1790
+ if (config) {
1791
+ values = extractFormValues(config.dirtyFields ? _formState.dirtyFields : _formState.touchedFields, values);
1792
+ }
1793
+ return isUndefined(fieldNames)
1794
+ ? values
1795
+ : isString(fieldNames)
1796
+ ? get(values, fieldNames)
1797
+ : fieldNames.map((name) => get(values, name));
1798
+ };
1799
+ const getFieldState = (name, formState) => ({
1800
+ invalid: !!get((formState || _formState).errors, name),
1801
+ isDirty: !!get((formState || _formState).dirtyFields, name),
1802
+ error: get((formState || _formState).errors, name),
1803
+ isValidating: !!get(_formState.validatingFields, name),
1804
+ isTouched: !!get((formState || _formState).touchedFields, name),
1805
+ });
1806
+ const clearErrors = (name) => {
1807
+ name &&
1808
+ convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1809
+ _subjects.state.next({
1810
+ errors: name ? _formState.errors : {},
1811
+ });
1812
+ };
1813
+ const setError = (name, error, options) => {
1814
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1815
+ const currentError = get(_formState.errors, name) || {};
1816
+ // Don't override existing error messages elsewhere in the object tree.
1817
+ const { ref: currentRef, message, type, ...restOfErrorTree } = currentError;
1818
+ set(_formState.errors, name, {
1819
+ ...restOfErrorTree,
1820
+ ...error,
1821
+ ref,
1822
+ });
1823
+ _subjects.state.next({
1824
+ name,
1825
+ errors: _formState.errors,
1826
+ isValid: false,
1827
+ });
1828
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
1829
+ };
1830
+ const watch = (name, defaultValue) => isFunction(name)
1831
+ ? _subjects.state.subscribe({
1832
+ next: (payload) => 'values' in payload &&
1833
+ name(_getWatch(undefined, defaultValue), payload),
1834
+ })
1835
+ : _getWatch(name, defaultValue, true);
1836
+ const _subscribe = (props) => _subjects.state.subscribe({
1837
+ next: (formState) => {
1838
+ if (shouldSubscribeByName(props.name, formState.name, props.exact) &&
1839
+ shouldRenderFormState(formState, props.formState || _proxyFormState, _setFormState, props.reRenderRoot)) {
1840
+ props.callback({
1841
+ values: { ..._formValues },
1842
+ ..._formState,
1843
+ ...formState,
1844
+ defaultValues: _defaultValues,
1845
+ });
1846
+ }
1847
+ },
1848
+ }).unsubscribe;
1849
+ const subscribe = (props) => {
1850
+ _state.mount = true;
1851
+ _proxySubscribeFormState = {
1852
+ ..._proxySubscribeFormState,
1853
+ ...props.formState,
1854
+ };
1855
+ return _subscribe({
1856
+ ...props,
1857
+ formState: {
1858
+ ...defaultProxyFormState,
1859
+ ...props.formState,
1860
+ },
1861
+ });
1862
+ };
1863
+ const unregister = (name, options = {}) => {
1864
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1865
+ _names.mount.delete(fieldName);
1866
+ _names.array.delete(fieldName);
1867
+ if (!options.keepValue) {
1868
+ unset(_fields, fieldName);
1869
+ unset(_formValues, fieldName);
1870
+ }
1871
+ !options.keepError && unset(_formState.errors, fieldName);
1872
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1873
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
1874
+ !options.keepIsValidating &&
1875
+ unset(_formState.validatingFields, fieldName);
1876
+ !_options.shouldUnregister &&
1877
+ !options.keepDefaultValue &&
1878
+ unset(_defaultValues, fieldName);
1879
+ }
1880
+ _subjects.state.next({
1881
+ values: cloneObject(_formValues),
1882
+ });
1883
+ _subjects.state.next({
1884
+ ..._formState,
1885
+ ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
1886
+ });
1887
+ !options.keepIsValid && _setValid();
1888
+ };
1889
+ const _setDisabledField = ({ disabled, name, }) => {
1890
+ if ((isBoolean(disabled) && _state.mount) ||
1891
+ !!disabled ||
1892
+ _names.disabled.has(name)) {
1893
+ disabled ? _names.disabled.add(name) : _names.disabled.delete(name);
1894
+ }
1895
+ };
1896
+ const register = (name, options = {}) => {
1897
+ let field = get(_fields, name);
1898
+ const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled);
1899
+ set(_fields, name, {
1900
+ ...(field || {}),
1901
+ _f: {
1902
+ ...(field && field._f ? field._f : { ref: { name } }),
1903
+ name,
1904
+ mount: true,
1905
+ ...options,
1906
+ },
1907
+ });
1908
+ _names.mount.add(name);
1909
+ if (field) {
1910
+ _setDisabledField({
1911
+ disabled: isBoolean(options.disabled)
1912
+ ? options.disabled
1913
+ : _options.disabled,
1914
+ name,
1915
+ });
1916
+ }
1917
+ else {
1918
+ updateValidAndValue(name, true, options.value);
1919
+ }
1920
+ return {
1921
+ ...(disabledIsDefined
1922
+ ? { disabled: options.disabled || _options.disabled }
1923
+ : {}),
1924
+ ...(_options.progressive
1925
+ ? {
1926
+ required: !!options.required,
1927
+ min: getRuleValue(options.min),
1928
+ max: getRuleValue(options.max),
1929
+ minLength: getRuleValue(options.minLength),
1930
+ maxLength: getRuleValue(options.maxLength),
1931
+ pattern: getRuleValue(options.pattern),
1932
+ }
1933
+ : {}),
1934
+ name,
1935
+ onChange,
1936
+ onBlur: onChange,
1937
+ ref: (ref) => {
1938
+ if (ref) {
1939
+ register(name, options);
1940
+ field = get(_fields, name);
1941
+ const fieldRef = isUndefined(ref.value)
1942
+ ? ref.querySelectorAll
1943
+ ? ref.querySelectorAll('input,select,textarea')[0] || ref
1944
+ : ref
1945
+ : ref;
1946
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1947
+ const refs = field._f.refs || [];
1948
+ if (radioOrCheckbox
1949
+ ? refs.find((option) => option === fieldRef)
1950
+ : fieldRef === field._f.ref) {
1951
+ return;
1952
+ }
1953
+ set(_fields, name, {
1954
+ _f: {
1955
+ ...field._f,
1956
+ ...(radioOrCheckbox
1957
+ ? {
1958
+ refs: [
1959
+ ...refs.filter(live),
1960
+ fieldRef,
1961
+ ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
1962
+ ],
1963
+ ref: { type: fieldRef.type, name },
1964
+ }
1965
+ : { ref: fieldRef }),
1966
+ },
1967
+ });
1968
+ updateValidAndValue(name, false, undefined, fieldRef);
1969
+ }
1970
+ else {
1971
+ field = get(_fields, name, {});
1972
+ if (field._f) {
1973
+ field._f.mount = false;
1974
+ }
1975
+ (_options.shouldUnregister || options.shouldUnregister) &&
1976
+ !(isNameInFieldArray(_names.array, name) && _state.action) &&
1977
+ _names.unMount.add(name);
1978
+ }
1979
+ },
1980
+ };
1981
+ };
1982
+ const _focusError = () => _options.shouldFocusError &&
1983
+ iterateFieldsByAction(_fields, _focusInput, _names.mount);
1984
+ const _disableForm = (disabled) => {
1985
+ if (isBoolean(disabled)) {
1986
+ _subjects.state.next({ disabled });
1987
+ iterateFieldsByAction(_fields, (ref, name) => {
1988
+ const currentField = get(_fields, name);
1989
+ if (currentField) {
1990
+ ref.disabled = currentField._f.disabled || disabled;
1991
+ if (Array.isArray(currentField._f.refs)) {
1992
+ currentField._f.refs.forEach((inputRef) => {
1993
+ inputRef.disabled = currentField._f.disabled || disabled;
1994
+ });
1995
+ }
1996
+ }
1997
+ }, 0, false);
1998
+ }
1999
+ };
2000
+ const handleSubmit = (onValid, onInvalid) => async (e) => {
2001
+ let onValidError = undefined;
2002
+ if (e) {
2003
+ e.preventDefault && e.preventDefault();
2004
+ e.persist &&
2005
+ e.persist();
2006
+ }
2007
+ let fieldValues = cloneObject(_formValues);
2008
+ _subjects.state.next({
2009
+ isSubmitting: true,
2010
+ });
2011
+ if (_options.resolver) {
2012
+ const { errors, values } = await _runSchema();
2013
+ _updateIsValidating();
2014
+ _formState.errors = errors;
2015
+ fieldValues = cloneObject(values);
2016
+ }
2017
+ else {
2018
+ await executeBuiltInValidation(_fields);
2019
+ }
2020
+ if (_names.disabled.size) {
2021
+ for (const name of _names.disabled) {
2022
+ unset(fieldValues, name);
2023
+ }
2024
+ }
2025
+ unset(_formState.errors, 'root');
2026
+ if (isEmptyObject(_formState.errors)) {
2027
+ _subjects.state.next({
2028
+ errors: {},
2029
+ });
2030
+ try {
2031
+ await onValid(fieldValues, e);
2032
+ }
2033
+ catch (error) {
2034
+ onValidError = error;
2035
+ }
2036
+ }
2037
+ else {
2038
+ if (onInvalid) {
2039
+ await onInvalid({ ..._formState.errors }, e);
2040
+ }
2041
+ _focusError();
2042
+ setTimeout(_focusError);
2043
+ }
2044
+ _subjects.state.next({
2045
+ isSubmitted: true,
2046
+ isSubmitting: false,
2047
+ isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
2048
+ submitCount: _formState.submitCount + 1,
2049
+ errors: _formState.errors,
2050
+ });
2051
+ if (onValidError) {
2052
+ throw onValidError;
2053
+ }
2054
+ };
2055
+ const resetField = (name, options = {}) => {
2056
+ if (get(_fields, name)) {
2057
+ if (isUndefined(options.defaultValue)) {
2058
+ setValue(name, cloneObject(get(_defaultValues, name)));
2059
+ }
2060
+ else {
2061
+ setValue(name, options.defaultValue);
2062
+ set(_defaultValues, name, cloneObject(options.defaultValue));
2063
+ }
2064
+ if (!options.keepTouched) {
2065
+ unset(_formState.touchedFields, name);
2066
+ }
2067
+ if (!options.keepDirty) {
2068
+ unset(_formState.dirtyFields, name);
2069
+ _formState.isDirty = options.defaultValue
2070
+ ? _getDirty(name, cloneObject(get(_defaultValues, name)))
2071
+ : _getDirty();
2072
+ }
2073
+ if (!options.keepError) {
2074
+ unset(_formState.errors, name);
2075
+ _proxyFormState.isValid && _setValid();
2076
+ }
2077
+ _subjects.state.next({ ..._formState });
2078
+ }
2079
+ };
2080
+ const _reset = (formValues, keepStateOptions = {}) => {
2081
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
2082
+ const cloneUpdatedValues = cloneObject(updatedValues);
2083
+ const isEmptyResetValues = isEmptyObject(formValues);
2084
+ const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;
2085
+ if (!keepStateOptions.keepDefaultValues) {
2086
+ _defaultValues = updatedValues;
2087
+ }
2088
+ if (!keepStateOptions.keepValues) {
2089
+ if (keepStateOptions.keepDirtyValues) {
2090
+ const fieldsToCheck = new Set([
2091
+ ..._names.mount,
2092
+ ...Object.keys(getDirtyFields(_defaultValues, _formValues)),
2093
+ ]);
2094
+ for (const fieldName of Array.from(fieldsToCheck)) {
2095
+ const isDirty = get(_formState.dirtyFields, fieldName);
2096
+ const existingValue = get(_formValues, fieldName);
2097
+ const newValue = get(values, fieldName);
2098
+ if (isDirty && !isUndefined(existingValue)) {
2099
+ set(values, fieldName, existingValue);
2100
+ }
2101
+ else if (!isDirty && !isUndefined(newValue)) {
2102
+ setValue(fieldName, newValue);
2103
+ }
2104
+ }
2105
+ }
2106
+ else {
2107
+ if (isWeb && isUndefined(formValues)) {
2108
+ for (const name of _names.mount) {
2109
+ const field = get(_fields, name);
2110
+ if (field && field._f) {
2111
+ const fieldReference = Array.isArray(field._f.refs)
2112
+ ? field._f.refs[0]
2113
+ : field._f.ref;
2114
+ if (isHTMLElement(fieldReference)) {
2115
+ const form = fieldReference.closest('form');
2116
+ if (form) {
2117
+ form.reset();
2118
+ break;
2119
+ }
2120
+ }
2121
+ }
2122
+ }
2123
+ }
2124
+ if (keepStateOptions.keepFieldsRef) {
2125
+ for (const fieldName of _names.mount) {
2126
+ setValue(fieldName, get(values, fieldName));
2127
+ }
2128
+ }
2129
+ else {
2130
+ _fields = {};
2131
+ }
2132
+ }
2133
+ _formValues = _options.shouldUnregister
2134
+ ? keepStateOptions.keepDefaultValues
2135
+ ? cloneObject(_defaultValues)
2136
+ : {}
2137
+ : cloneObject(values);
2138
+ _subjects.array.next({
2139
+ values: { ...values },
2140
+ });
2141
+ _subjects.state.next({
2142
+ values: { ...values },
2143
+ });
2144
+ }
2145
+ _names = {
2146
+ mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(),
2147
+ unMount: new Set(),
2148
+ array: new Set(),
2149
+ disabled: new Set(),
2150
+ watch: new Set(),
2151
+ watchAll: false,
2152
+ focus: '',
2153
+ };
2154
+ _state.mount =
2155
+ !_proxyFormState.isValid ||
2156
+ !!keepStateOptions.keepIsValid ||
2157
+ !!keepStateOptions.keepDirtyValues ||
2158
+ (!_options.shouldUnregister && !isEmptyObject(values));
2159
+ _state.watch = !!_options.shouldUnregister;
2160
+ _state.keepIsValid = !!keepStateOptions.keepIsValid;
2161
+ _state.action = false;
2162
+ // Clear errors synchronously to prevent validation errors on subsequent submissions
2163
+ // This fixes the issue where form.reset() causes validation errors on subsequent
2164
+ // submissions in Next.js 16 with Server Actions
2165
+ if (!keepStateOptions.keepErrors) {
2166
+ _formState.errors = {};
2167
+ }
2168
+ _subjects.state.next({
2169
+ submitCount: keepStateOptions.keepSubmitCount
2170
+ ? _formState.submitCount
2171
+ : 0,
2172
+ isDirty: isEmptyResetValues
2173
+ ? false
2174
+ : keepStateOptions.keepDirty
2175
+ ? _formState.isDirty
2176
+ : !!(keepStateOptions.keepDefaultValues &&
2177
+ !deepEqual(formValues, _defaultValues)),
2178
+ isSubmitted: keepStateOptions.keepIsSubmitted
2179
+ ? _formState.isSubmitted
2180
+ : false,
2181
+ dirtyFields: isEmptyResetValues
2182
+ ? {}
2183
+ : keepStateOptions.keepDirtyValues
2184
+ ? keepStateOptions.keepDefaultValues && _formValues
2185
+ ? getDirtyFields(_defaultValues, _formValues)
2186
+ : _formState.dirtyFields
2187
+ : keepStateOptions.keepDefaultValues && formValues
2188
+ ? getDirtyFields(_defaultValues, formValues)
2189
+ : keepStateOptions.keepDirty
2190
+ ? _formState.dirtyFields
2191
+ : {},
2192
+ touchedFields: keepStateOptions.keepTouched
2193
+ ? _formState.touchedFields
2194
+ : {},
2195
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
2196
+ isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful
2197
+ ? _formState.isSubmitSuccessful
2198
+ : false,
2199
+ isSubmitting: false,
2200
+ defaultValues: _defaultValues,
2201
+ });
2202
+ };
2203
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
2204
+ ? formValues(_formValues)
2205
+ : formValues, { ..._options.resetOptions, ...keepStateOptions });
2206
+ const setFocus = (name, options = {}) => {
2207
+ const field = get(_fields, name);
2208
+ const fieldReference = field && field._f;
2209
+ if (fieldReference) {
2210
+ const fieldRef = fieldReference.refs
2211
+ ? fieldReference.refs[0]
2212
+ : fieldReference.ref;
2213
+ if (fieldRef.focus) {
2214
+ // Use setTimeout to ensure focus happens after any pending state updates
2215
+ // This fixes the issue where setFocus doesn't work immediately after setError
2216
+ setTimeout(() => {
2217
+ fieldRef.focus();
2218
+ options.shouldSelect &&
2219
+ isFunction(fieldRef.select) &&
2220
+ fieldRef.select();
2221
+ });
2222
+ }
2223
+ }
2224
+ };
2225
+ const _setFormState = (updatedFormState) => {
2226
+ _formState = {
2227
+ ..._formState,
2228
+ ...updatedFormState,
2229
+ };
2230
+ };
2231
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
2232
+ _options.defaultValues().then((values) => {
2233
+ reset(values, _options.resetOptions);
2234
+ _subjects.state.next({
2235
+ isLoading: false,
2236
+ });
2237
+ });
2238
+ const methods = {
2239
+ control: {
2240
+ register,
2241
+ unregister,
2242
+ getFieldState,
2243
+ handleSubmit,
2244
+ setError,
2245
+ _subscribe,
2246
+ _runSchema,
2247
+ _updateIsValidating,
2248
+ _focusError,
2249
+ _getWatch,
2250
+ _getDirty,
2251
+ _setValid,
2252
+ _setFieldArray,
2253
+ _setDisabledField,
2254
+ _setErrors,
2255
+ _getFieldArray,
2256
+ _reset,
2257
+ _resetDefaultValues,
2258
+ _removeUnmounted,
2259
+ _disableForm,
2260
+ _subjects,
2261
+ _proxyFormState,
2262
+ get _fields() {
2263
+ return _fields;
2264
+ },
2265
+ get _formValues() {
2266
+ return _formValues;
2267
+ },
2268
+ get _state() {
2269
+ return _state;
2270
+ },
2271
+ set _state(value) {
2272
+ _state = value;
2273
+ },
2274
+ get _defaultValues() {
2275
+ return _defaultValues;
2276
+ },
2277
+ get _names() {
2278
+ return _names;
2279
+ },
2280
+ set _names(value) {
2281
+ _names = value;
2282
+ },
2283
+ get _formState() {
2284
+ return _formState;
2285
+ },
2286
+ get _options() {
2287
+ return _options;
2288
+ },
2289
+ set _options(value) {
2290
+ _options = {
2291
+ ..._options,
2292
+ ...value,
2293
+ };
2294
+ },
2295
+ },
2296
+ subscribe,
2297
+ trigger,
2298
+ register,
2299
+ handleSubmit,
2300
+ watch,
2301
+ setValue,
2302
+ getValues,
2303
+ reset,
2304
+ resetField,
2305
+ clearErrors,
2306
+ unregister,
2307
+ setError,
2308
+ setFocus,
2309
+ getFieldState,
2310
+ };
2311
+ return {
2312
+ ...methods,
2313
+ formControl: methods,
2314
+ };
2315
+ }
2316
+
2317
+ var generateId = () => {
2318
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) {
2319
+ return crypto.randomUUID();
2320
+ }
2321
+ const d = typeof performance === 'undefined' ? Date.now() : performance.now() * 1000;
2322
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
2323
+ const r = ((Math.random() * 16 + d) % 16) | 0;
2324
+ return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);
2325
+ });
2326
+ };
2327
+
2328
+ var getFocusFieldName = (name, index, options = {}) => options.shouldFocus || isUndefined(options.shouldFocus)
2329
+ ? options.focusName ||
2330
+ `${name}.${isUndefined(options.focusIndex) ? index : options.focusIndex}.`
2331
+ : '';
2332
+
2333
+ var appendAt = (data, value) => [
2334
+ ...data,
2335
+ ...convertToArrayPayload(value),
2336
+ ];
2337
+
2338
+ var fillEmptyArray = (value) => Array.isArray(value) ? value.map(() => undefined) : undefined;
2339
+
2340
+ function insert(data, index, value) {
2341
+ return [
2342
+ ...data.slice(0, index),
2343
+ ...convertToArrayPayload(value),
2344
+ ...data.slice(index),
2345
+ ];
2346
+ }
2347
+
2348
+ var moveArrayAt = (data, from, to) => {
2349
+ if (!Array.isArray(data)) {
2350
+ return [];
2351
+ }
2352
+ if (isUndefined(data[to])) {
2353
+ data[to] = undefined;
2354
+ }
2355
+ data.splice(to, 0, data.splice(from, 1)[0]);
2356
+ return data;
2357
+ };
2358
+
2359
+ var prependAt = (data, value) => [
2360
+ ...convertToArrayPayload(value),
2361
+ ...convertToArrayPayload(data),
2362
+ ];
2363
+
2364
+ function removeAtIndexes(data, indexes) {
2365
+ let i = 0;
2366
+ const temp = [...data];
2367
+ for (const index of indexes) {
2368
+ temp.splice(index - i, 1);
2369
+ i++;
2370
+ }
2371
+ return compact(temp).length ? temp : [];
2372
+ }
2373
+ var removeArrayAt = (data, index) => isUndefined(index)
2374
+ ? []
2375
+ : removeAtIndexes(data, convertToArrayPayload(index).sort((a, b) => a - b));
2376
+
2377
+ var swapArrayAt = (data, indexA, indexB) => {
2378
+ [data[indexA], data[indexB]] = [data[indexB], data[indexA]];
2379
+ };
2380
+
2381
+ var updateAt = (fieldValues, index, value) => {
2382
+ fieldValues[index] = value;
2383
+ return fieldValues;
2384
+ };
2385
+
2386
+ /**
2387
+ * A custom hook that exposes convenient methods to perform operations with a list of dynamic inputs that need to be appended, updated, removed etc. • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn) • [Video](https://youtu.be/4MrbfGSFY2A)
2388
+ *
2389
+ * @remarks
2390
+ * [API](https://react-hook-form.com/docs/usefieldarray) • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn)
2391
+ *
2392
+ * @param props - useFieldArray props
2393
+ *
2394
+ * @returns methods - functions to manipulate with the Field Arrays (dynamic inputs) {@link UseFieldArrayReturn}
2395
+ *
2396
+ * @example
2397
+ * ```tsx
2398
+ * function App() {
2399
+ * const { register, control, handleSubmit, reset, trigger, setError } = useForm({
2400
+ * defaultValues: {
2401
+ * test: []
2402
+ * }
2403
+ * });
2404
+ * const { fields, append } = useFieldArray({
2405
+ * control,
2406
+ * name: "test"
2407
+ * });
2408
+ *
2409
+ * return (
2410
+ * <form onSubmit={handleSubmit(data => console.log(data))}>
2411
+ * {fields.map((item, index) => (
2412
+ * <input key={item.id} {...register(`test.${index}.firstName`)} />
2413
+ * ))}
2414
+ * <button type="button" onClick={() => append({ firstName: "bill" })}>
2415
+ * append
2416
+ * </button>
2417
+ * <input type="submit" />
2418
+ * </form>
2419
+ * );
2420
+ * }
2421
+ * ```
2422
+ */
2423
+ function useFieldArray(props) {
2424
+ const methods = useFormContext();
2425
+ const { control = methods.control, name, keyName = 'id', shouldUnregister, rules, } = props;
2426
+ const [fields, setFields] = React.useState(control._getFieldArray(name));
2427
+ const ids = React.useRef(control._getFieldArray(name).map(generateId));
2428
+ const _actioned = React.useRef(false);
2429
+ control._names.array.add(name);
2430
+ React.useMemo(() => rules &&
2431
+ fields.length >= 0 &&
2432
+ control.register(name, rules), [control, name, fields.length, rules]);
2433
+ useIsomorphicLayoutEffect(() => control._subjects.array.subscribe({
2434
+ next: ({ values, name: fieldArrayName, }) => {
2435
+ if (fieldArrayName === name || !fieldArrayName) {
2436
+ const fieldValues = get(values, name);
2437
+ if (Array.isArray(fieldValues)) {
2438
+ setFields(fieldValues);
2439
+ ids.current = fieldValues.map(generateId);
2440
+ }
2441
+ }
2442
+ },
2443
+ }).unsubscribe, [control, name]);
2444
+ const updateValues = React.useCallback((updatedFieldArrayValues) => {
2445
+ _actioned.current = true;
2446
+ control._setFieldArray(name, updatedFieldArrayValues);
2447
+ }, [control, name]);
2448
+ const append = (value, options) => {
2449
+ const appendValue = convertToArrayPayload(cloneObject(value));
2450
+ const updatedFieldArrayValues = appendAt(control._getFieldArray(name), appendValue);
2451
+ control._names.focus = getFocusFieldName(name, updatedFieldArrayValues.length - 1, options);
2452
+ ids.current = appendAt(ids.current, appendValue.map(generateId));
2453
+ updateValues(updatedFieldArrayValues);
2454
+ setFields(updatedFieldArrayValues);
2455
+ control._setFieldArray(name, updatedFieldArrayValues, appendAt, {
2456
+ argA: fillEmptyArray(value),
2457
+ });
2458
+ };
2459
+ const prepend = (value, options) => {
2460
+ const prependValue = convertToArrayPayload(cloneObject(value));
2461
+ const updatedFieldArrayValues = prependAt(control._getFieldArray(name), prependValue);
2462
+ control._names.focus = getFocusFieldName(name, 0, options);
2463
+ ids.current = prependAt(ids.current, prependValue.map(generateId));
2464
+ updateValues(updatedFieldArrayValues);
2465
+ setFields(updatedFieldArrayValues);
2466
+ control._setFieldArray(name, updatedFieldArrayValues, prependAt, {
2467
+ argA: fillEmptyArray(value),
2468
+ });
2469
+ };
2470
+ const remove = (index) => {
2471
+ const updatedFieldArrayValues = removeArrayAt(control._getFieldArray(name), index);
2472
+ ids.current = removeArrayAt(ids.current, index);
2473
+ updateValues(updatedFieldArrayValues);
2474
+ setFields(updatedFieldArrayValues);
2475
+ !Array.isArray(get(control._fields, name)) &&
2476
+ set(control._fields, name, undefined);
2477
+ control._setFieldArray(name, updatedFieldArrayValues, removeArrayAt, {
2478
+ argA: index,
2479
+ });
2480
+ };
2481
+ const insert$1 = (index, value, options) => {
2482
+ const insertValue = convertToArrayPayload(cloneObject(value));
2483
+ const updatedFieldArrayValues = insert(control._getFieldArray(name), index, insertValue);
2484
+ control._names.focus = getFocusFieldName(name, index, options);
2485
+ ids.current = insert(ids.current, index, insertValue.map(generateId));
2486
+ updateValues(updatedFieldArrayValues);
2487
+ setFields(updatedFieldArrayValues);
2488
+ control._setFieldArray(name, updatedFieldArrayValues, insert, {
2489
+ argA: index,
2490
+ argB: fillEmptyArray(value),
2491
+ });
2492
+ };
2493
+ const swap = (indexA, indexB) => {
2494
+ const updatedFieldArrayValues = control._getFieldArray(name);
2495
+ swapArrayAt(updatedFieldArrayValues, indexA, indexB);
2496
+ swapArrayAt(ids.current, indexA, indexB);
2497
+ updateValues(updatedFieldArrayValues);
2498
+ setFields(updatedFieldArrayValues);
2499
+ control._setFieldArray(name, updatedFieldArrayValues, swapArrayAt, {
2500
+ argA: indexA,
2501
+ argB: indexB,
2502
+ }, false);
2503
+ };
2504
+ const move = (from, to) => {
2505
+ const updatedFieldArrayValues = control._getFieldArray(name);
2506
+ moveArrayAt(updatedFieldArrayValues, from, to);
2507
+ moveArrayAt(ids.current, from, to);
2508
+ updateValues(updatedFieldArrayValues);
2509
+ setFields(updatedFieldArrayValues);
2510
+ control._setFieldArray(name, updatedFieldArrayValues, moveArrayAt, {
2511
+ argA: from,
2512
+ argB: to,
2513
+ }, false);
2514
+ };
2515
+ const update = (index, value) => {
2516
+ const updateValue = cloneObject(value);
2517
+ const updatedFieldArrayValues = updateAt(control._getFieldArray(name), index, updateValue);
2518
+ ids.current = [...updatedFieldArrayValues].map((item, i) => !item || i === index ? generateId() : ids.current[i]);
2519
+ updateValues(updatedFieldArrayValues);
2520
+ setFields([...updatedFieldArrayValues]);
2521
+ control._setFieldArray(name, updatedFieldArrayValues, updateAt, {
2522
+ argA: index,
2523
+ argB: updateValue,
2524
+ }, true, false);
2525
+ };
2526
+ const replace = (value) => {
2527
+ const updatedFieldArrayValues = convertToArrayPayload(cloneObject(value));
2528
+ ids.current = updatedFieldArrayValues.map(generateId);
2529
+ updateValues([...updatedFieldArrayValues]);
2530
+ setFields([...updatedFieldArrayValues]);
2531
+ control._setFieldArray(name, [...updatedFieldArrayValues], (data) => data, {}, true, false);
2532
+ };
2533
+ React.useEffect(() => {
2534
+ control._state.action = false;
2535
+ isWatched(name, control._names) &&
2536
+ control._subjects.state.next({
2537
+ ...control._formState,
2538
+ });
2539
+ if (_actioned.current &&
2540
+ (!getValidationModes(control._options.mode).isOnSubmit ||
2541
+ control._formState.isSubmitted) &&
2542
+ !getValidationModes(control._options.reValidateMode).isOnSubmit) {
2543
+ if (control._options.resolver) {
2544
+ control._runSchema([name]).then((result) => {
2545
+ control._updateIsValidating([name]);
2546
+ const error = get(result.errors, name);
2547
+ const existingError = get(control._formState.errors, name);
2548
+ if (existingError
2549
+ ? (!error && existingError.type) ||
2550
+ (error &&
2551
+ (existingError.type !== error.type ||
2552
+ existingError.message !== error.message))
2553
+ : error && error.type) {
2554
+ error
2555
+ ? set(control._formState.errors, name, error)
2556
+ : unset(control._formState.errors, name);
2557
+ control._subjects.state.next({
2558
+ errors: control._formState.errors,
2559
+ });
2560
+ }
2561
+ });
2562
+ }
2563
+ else {
2564
+ const field = get(control._fields, name);
2565
+ if (field &&
2566
+ field._f &&
2567
+ !(getValidationModes(control._options.reValidateMode).isOnSubmit &&
2568
+ getValidationModes(control._options.mode).isOnSubmit)) {
2569
+ validateField(field, control._names.disabled, control._formValues, control._options.criteriaMode === VALIDATION_MODE.all, control._options.shouldUseNativeValidation, true).then((error) => !isEmptyObject(error) &&
2570
+ control._subjects.state.next({
2571
+ errors: updateFieldArrayRootError(control._formState.errors, error, name),
2572
+ }));
2573
+ }
2574
+ }
2575
+ }
2576
+ control._subjects.state.next({
2577
+ name,
2578
+ values: cloneObject(control._formValues),
2579
+ });
2580
+ control._names.focus &&
2581
+ iterateFieldsByAction(control._fields, (ref, key) => {
2582
+ if (control._names.focus &&
2583
+ key.startsWith(control._names.focus) &&
2584
+ ref.focus) {
2585
+ ref.focus();
2586
+ return 1;
2587
+ }
2588
+ return;
2589
+ });
2590
+ control._names.focus = '';
2591
+ control._setValid();
2592
+ _actioned.current = false;
2593
+ }, [fields, name, control]);
2594
+ React.useEffect(() => {
2595
+ !get(control._formValues, name) && control._setFieldArray(name);
2596
+ return () => {
2597
+ const updateMounted = (name, value) => {
2598
+ const field = get(control._fields, name);
2599
+ if (field && field._f) {
2600
+ field._f.mount = value;
2601
+ }
2602
+ };
2603
+ control._options.shouldUnregister || shouldUnregister
2604
+ ? control.unregister(name)
2605
+ : updateMounted(name, false);
2606
+ };
2607
+ }, [name, control, keyName, shouldUnregister]);
2608
+ return {
2609
+ swap: React.useCallback(swap, [updateValues, name, control]),
2610
+ move: React.useCallback(move, [updateValues, name, control]),
2611
+ prepend: React.useCallback(prepend, [updateValues, name, control]),
2612
+ append: React.useCallback(append, [updateValues, name, control]),
2613
+ remove: React.useCallback(remove, [updateValues, name, control]),
2614
+ insert: React.useCallback(insert$1, [updateValues, name, control]),
2615
+ update: React.useCallback(update, [updateValues, name, control]),
2616
+ replace: React.useCallback(replace, [updateValues, name, control]),
2617
+ fields: React.useMemo(() => fields.map((field, index) => ({
2618
+ ...field,
2619
+ [keyName]: ids.current[index] || generateId(),
2620
+ })), [fields, keyName]),
2621
+ };
2622
+ }
2623
+
2624
+ /**
2625
+ * Custom hook to manage the entire form.
2626
+ *
2627
+ * @remarks
2628
+ * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2629
+ *
2630
+ * @param props - form configuration and validation parameters.
2631
+ *
2632
+ * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2633
+ *
2634
+ * @example
2635
+ * ```tsx
2636
+ * function App() {
2637
+ * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2638
+ * const onSubmit = data => console.log(data);
2639
+ *
2640
+ * console.log(watch("example"));
2641
+ *
2642
+ * return (
2643
+ * <form onSubmit={handleSubmit(onSubmit)}>
2644
+ * <input defaultValue="test" {...register("example")} />
2645
+ * <input {...register("exampleRequired", { required: true })} />
2646
+ * {errors.exampleRequired && <span>This field is required</span>}
2647
+ * <button>Submit</button>
2648
+ * </form>
2649
+ * );
2650
+ * }
2651
+ * ```
2652
+ */
2653
+ function useForm(props = {}) {
2654
+ const _formControl = React.useRef(undefined);
2655
+ const _values = React.useRef(undefined);
2656
+ const [formState, updateFormState] = React.useState({
2657
+ isDirty: false,
2658
+ isValidating: false,
2659
+ isLoading: isFunction(props.defaultValues),
2660
+ isSubmitted: false,
2661
+ isSubmitting: false,
2662
+ isSubmitSuccessful: false,
2663
+ isValid: false,
2664
+ submitCount: 0,
2665
+ dirtyFields: {},
2666
+ touchedFields: {},
2667
+ validatingFields: {},
2668
+ errors: props.errors || {},
2669
+ disabled: props.disabled || false,
2670
+ isReady: false,
2671
+ defaultValues: isFunction(props.defaultValues)
2672
+ ? undefined
2673
+ : props.defaultValues,
2674
+ });
2675
+ if (!_formControl.current) {
2676
+ if (props.formControl) {
2677
+ _formControl.current = {
2678
+ ...props.formControl,
2679
+ formState,
2680
+ };
2681
+ if (props.defaultValues && !isFunction(props.defaultValues)) {
2682
+ props.formControl.reset(props.defaultValues, props.resetOptions);
2683
+ }
2684
+ }
2685
+ else {
2686
+ const { formControl, ...rest } = createFormControl(props);
2687
+ _formControl.current = {
2688
+ ...rest,
2689
+ formState,
2690
+ };
2691
+ }
2692
+ }
2693
+ const control = _formControl.current.control;
2694
+ control._options = props;
2695
+ useIsomorphicLayoutEffect(() => {
2696
+ const sub = control._subscribe({
2697
+ formState: control._proxyFormState,
2698
+ callback: () => updateFormState({ ...control._formState }),
2699
+ reRenderRoot: true,
2700
+ });
2701
+ updateFormState((data) => ({
2702
+ ...data,
2703
+ isReady: true,
2704
+ }));
2705
+ control._formState.isReady = true;
2706
+ return sub;
2707
+ }, [control]);
2708
+ React.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
2709
+ React.useEffect(() => {
2710
+ if (props.mode) {
2711
+ control._options.mode = props.mode;
2712
+ }
2713
+ if (props.reValidateMode) {
2714
+ control._options.reValidateMode = props.reValidateMode;
2715
+ }
2716
+ }, [control, props.mode, props.reValidateMode]);
2717
+ React.useEffect(() => {
2718
+ if (props.errors) {
2719
+ control._setErrors(props.errors);
2720
+ control._focusError();
2721
+ }
2722
+ }, [control, props.errors]);
2723
+ React.useEffect(() => {
2724
+ props.shouldUnregister &&
2725
+ control._subjects.state.next({
2726
+ values: control._getWatch(),
2727
+ });
2728
+ }, [control, props.shouldUnregister]);
2729
+ React.useEffect(() => {
2730
+ if (control._proxyFormState.isDirty) {
2731
+ const isDirty = control._getDirty();
2732
+ if (isDirty !== formState.isDirty) {
2733
+ control._subjects.state.next({
2734
+ isDirty,
2735
+ });
2736
+ }
2737
+ }
2738
+ }, [control, formState.isDirty]);
2739
+ React.useEffect(() => {
2740
+ var _a;
2741
+ if (props.values && !deepEqual(props.values, _values.current)) {
2742
+ control._reset(props.values, {
2743
+ keepFieldsRef: true,
2744
+ ...control._options.resetOptions,
2745
+ });
2746
+ if (!((_a = control._options.resetOptions) === null || _a === void 0 ? void 0 : _a.keepIsValid)) {
2747
+ control._setValid();
2748
+ }
2749
+ _values.current = props.values;
2750
+ updateFormState((state) => ({ ...state }));
2751
+ }
2752
+ else {
2753
+ control._resetDefaultValues();
2754
+ }
2755
+ }, [control, props.values]);
2756
+ React.useEffect(() => {
2757
+ if (!control._state.mount) {
2758
+ control._setValid();
2759
+ control._state.mount = true;
2760
+ }
2761
+ if (control._state.watch) {
2762
+ control._state.watch = false;
2763
+ control._subjects.state.next({ ...control._formState });
2764
+ }
2765
+ control._removeUnmounted();
2766
+ });
2767
+ _formControl.current.formState = getProxyFormState(formState, control);
2768
+ return _formControl.current;
2769
+ }
2770
+
2771
+ const r=(t,r,o)=>{if(t&&"reportValidity"in t){const s=get(o,r);t.setCustomValidity(s&&s.message||""),t.reportValidity();}},o=(e,t)=>{for(const o in t.fields){const s=t.fields[o];s&&s.ref&&"reportValidity"in s.ref?r(s.ref,o,e):s&&s.refs&&s.refs.forEach(t=>r(t,o,e));}},s$1=(r,s)=>{s.shouldUseNativeValidation&&o(r,s);const n={};for(const o in r){const f=get(s.fields,o),c=Object.assign(r[o]||{},{ref:f&&f.ref});if(i$1(s.names||Object.keys(r),o)){const r=Object.assign({},get(n,o));set(r,"root",c),set(n,o,r);}else set(n,o,c);}return n},i$1=(e,t)=>{const r=n(t);return e.some(e=>n(e).match(`^${r}\\.\\d+`))};function n(e){return e.replace(/\]|\[/g,"")}
2772
+
2773
+ function t(r,e){try{var o=r();}catch(r){return e(r)}return o&&o.then?o.then(void 0,e):o}function s(r,e){for(var n={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("unionErrors"in t){var u=t.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code};}else n[a]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[t.code];n[a]=appendErrors(a,e,n,s,f?[].concat(f,t.message):t.message);}r.shift();}return n}function i(r,e){for(var n={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("invalid_union"===t.code&&t.errors.length>0){var u=t.errors[0][0];n[a]={message:u.message,type:u.code};}else n[a]={message:i,type:s};if("invalid_union"===t.code&&t.errors.forEach(function(e){return e.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[t.code];n[a]=appendErrors(a,e,n,s,f?[].concat(f,t.message):t.message);}r.shift();}return n}function a(o$1,a,u){if(void 0===u&&(u={}),function(r){return "_def"in r&&"object"==typeof r._def&&"typeName"in r._def}(o$1))return function(n,i,c){try{return Promise.resolve(t(function(){return Promise.resolve(o$1["sync"===u.mode?"parse":"parseAsync"](n,a)).then(function(e){return c.shouldUseNativeValidation&&o({},c),{errors:{},values:u.raw?Object.assign({},n):e}})},function(r){if(function(r){return Array.isArray(null==r?void 0:r.issues)}(r))return {values:{},errors:s$1(s(r.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw r}))}catch(r){return Promise.reject(r)}};if(function(r){return "_zod"in r&&"object"==typeof r._zod}(o$1))return function(s,c,f){try{return Promise.resolve(t(function(){return Promise.resolve(("sync"===u.mode?n$1.parse:n$1.parseAsync)(o$1,s,a)).then(function(e){return f.shouldUseNativeValidation&&o({},f),{errors:{},values:u.raw?Object.assign({},s):e}})},function(r){if(function(r){return r instanceof n$1.$ZodError}(r))return {values:{},errors:s$1(i(r.issues,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)};throw r}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")}
2774
+
2775
+ function isArrayField(field) {
2776
+ return field.type === 'array' && 'fields' in field;
2777
+ }
2778
+ function createField(field) {
2779
+ return field;
2780
+ }
2781
+ function createArrayField(field) {
2782
+ return {
2783
+ ...field,
2784
+ type: 'array'
2785
+ };
2786
+ }
2787
+ function strictFields(fields) {
2788
+ return fields;
2789
+ }
2790
+ function validateFieldType(type, registeredTypes) {
2791
+ if (!registeredTypes.includes(type) && type !== 'array') {
2792
+ throw new Error(`Unregistered field type: "${type}". ` + `Registered types: ${registeredTypes.join(', ')}. ` + `Use registerField("${type}", YourComponent) to register it.`);
2793
+ }
2794
+ return type;
2795
+ }
2796
+ function validateFieldTypes(fields, registeredTypes, options = {}) {
2797
+ const {
2798
+ throwOnError = false,
2799
+ warn = true
2800
+ } = options;
2801
+ const invalidTypes = [];
2802
+ const checkField = field => {
2803
+ if (field.type === 'array' && 'fields' in field) {
2804
+ field.fields.forEach(checkField);
2805
+ } else if (!registeredTypes.includes(field.type) && field.type !== 'array') {
2806
+ invalidTypes.push(field.type);
2807
+ }
2808
+ };
2809
+ fields.forEach(checkField);
2810
+ if (invalidTypes.length > 0) {
2811
+ const uniqueInvalid = [...new Set(invalidTypes)];
2812
+ const message = `Unregistered field type(s): ${uniqueInvalid.map(t => `"${t}"`).join(', ')}. ` + `Registered types: ${registeredTypes.join(', ')}. ` + 'Register custom types with registerField() or use module augmentation for TypeScript support.';
2813
+ if (throwOnError) {
2814
+ throw new Error(message);
2815
+ } else if (warn && typeof console !== 'undefined') {
2816
+ console.warn(`[FormGenerator] ${message}`);
2817
+ }
2818
+ }
2819
+ return fields;
2820
+ }
2821
+
2822
+ const fieldRegistry = new Map();
2823
+ const componentRegistry = {};
2824
+ const defaultFormComponents = {
2825
+ SubmitButton: ({
2826
+ className,
2827
+ children,
2828
+ disabled,
2829
+ isSubmitting
2830
+ }) => /*#__PURE__*/createElement('button', {
2831
+ type: 'submit',
2832
+ className: className !== null && className !== void 0 ? className : 'form-submit',
2833
+ disabled: disabled || isSubmitting
2834
+ }, isSubmitting ? 'Submitting...' : children),
2835
+ FieldWrapper: ({
2836
+ children
2837
+ }) => /*#__PURE__*/createElement(Fragment, null, children),
2838
+ FieldsWrapper: ({
2839
+ children
2840
+ }) => /*#__PURE__*/createElement(Fragment, null, children)
2841
+ };
2842
+ const htmlInputTypes = {
2843
+ text: 'text',
2844
+ email: 'email',
2845
+ password: 'password',
2846
+ number: 'number',
2847
+ tel: 'tel',
2848
+ url: 'url',
2849
+ search: 'search',
2850
+ date: 'date',
2851
+ time: 'time',
2852
+ datetime: 'datetime-local',
2853
+ month: 'month',
2854
+ week: 'week',
2855
+ color: 'color',
2856
+ range: 'range',
2857
+ file: 'file',
2858
+ hidden: 'hidden'
2859
+ };
2860
+ function createDefaultFieldComponent(type) {
2861
+ const inputType = htmlInputTypes[type];
2862
+ if (inputType) {
2863
+ const InputComponent = function DefaultInput({
2864
+ field,
2865
+ formField,
2866
+ fieldState
2867
+ }) {
2868
+ var _a;
2869
+ const f = field;
2870
+ return /*#__PURE__*/createElement('input', {
2871
+ 'type': inputType,
2872
+ 'aria-invalid': fieldState.invalid,
2873
+ 'required': field.required,
2874
+ 'placeholder': f.placeholder,
2875
+ 'disabled': field.disabled,
2876
+ 'className': (_a = field.className) !== null && _a !== void 0 ? _a : `form-field form-field-${type}`,
2877
+ 'ref': formField.ref,
2878
+ 'value': formField.value,
2879
+ 'onChange': formField.onChange,
2880
+ 'onBlur': formField.onBlur,
2881
+ 'name': field.name,
2882
+ 'autoComplete': field.name,
2883
+ 'id': field.name
2884
+ });
2885
+ };
2886
+ return InputComponent;
2887
+ }
2888
+ if (type === 'textarea') {
2889
+ const TextareaComponent = function DefaultTextarea({
2890
+ field,
2891
+ formField
2892
+ }) {
2893
+ var _a, _b;
2894
+ const f = field;
2895
+ return /*#__PURE__*/createElement('textarea', {
2896
+ ...formField,
2897
+ placeholder: f.placeholder,
2898
+ disabled: field.disabled,
2899
+ rows: (_a = f.rows) !== null && _a !== void 0 ? _a : 3,
2900
+ className: (_b = field.className) !== null && _b !== void 0 ? _b : 'form-field form-field-textarea'
2901
+ });
2902
+ };
2903
+ return TextareaComponent;
2904
+ }
2905
+ if (type === 'select') {
2906
+ const SelectComponent = function DefaultSelect({
2907
+ field,
2908
+ formField
2909
+ }) {
2910
+ var _a, _b, _c;
2911
+ const f = field;
2912
+ const options = (_a = f.options) !== null && _a !== void 0 ? _a : [];
2913
+ return /*#__PURE__*/createElement('select', {
2914
+ ...formField,
2915
+ disabled: field.disabled,
2916
+ className: (_b = field.className) !== null && _b !== void 0 ? _b : 'form-field form-field-select'
2917
+ }, /*#__PURE__*/createElement('option', {
2918
+ value: ''
2919
+ }, (_c = f.placeholder) !== null && _c !== void 0 ? _c : 'Select...'), options.map(opt => /*#__PURE__*/createElement('option', {
2920
+ key: opt.value,
2921
+ value: opt.value
2922
+ }, opt.label)));
2923
+ };
2924
+ return SelectComponent;
2925
+ }
2926
+ if (type === 'checkbox') {
2927
+ const CheckboxComponent = function DefaultCheckbox({
2928
+ field,
2929
+ formField
2930
+ }) {
2931
+ var _a;
2932
+ return /*#__PURE__*/createElement('input', {
2933
+ type: 'checkbox',
2934
+ ...formField,
2935
+ checked: !!formField.value,
2936
+ onChange: e => formField.onChange(e.target.checked),
2937
+ disabled: field.disabled,
2938
+ className: (_a = field.className) !== null && _a !== void 0 ? _a : 'form-field form-field-checkbox'
2939
+ });
2940
+ };
2941
+ return CheckboxComponent;
2942
+ }
2943
+ if (type === 'radio') {
2944
+ const RadioComponent = function DefaultRadio({
2945
+ field,
2946
+ formField
2947
+ }) {
2948
+ var _a, _b;
2949
+ const f = field;
2950
+ const options = (_a = f.options) !== null && _a !== void 0 ? _a : [];
2951
+ return /*#__PURE__*/createElement('div', {
2952
+ className: (_b = field.className) !== null && _b !== void 0 ? _b : 'form-field form-field-radio-group'
2953
+ }, options.map(opt => /*#__PURE__*/createElement('label', {
2954
+ key: opt.value,
2955
+ className: 'form-radio-option'
2956
+ }, /*#__PURE__*/createElement('input', {
2957
+ type: 'radio',
2958
+ name: formField.name,
2959
+ value: opt.value,
2960
+ checked: formField.value === opt.value,
2961
+ onChange: () => formField.onChange(opt.value),
2962
+ disabled: field.disabled
2963
+ }), opt.label)));
2964
+ };
2965
+ return RadioComponent;
2966
+ }
2967
+ const FallbackComponent = function DefaultFallback({
2968
+ field,
2969
+ formField
2970
+ }) {
2971
+ var _a;
2972
+ const f = field;
2973
+ return /*#__PURE__*/createElement('input', {
2974
+ type: 'text',
2975
+ ...formField,
2976
+ placeholder: f.placeholder,
2977
+ disabled: field.disabled,
2978
+ className: (_a = field.className) !== null && _a !== void 0 ? _a : 'form-field'
2979
+ });
2980
+ };
2981
+ return FallbackComponent;
2982
+ }
2983
+ function registerField(type, component, options = {}) {
2984
+ fieldRegistry.set(type, {
2985
+ component,
2986
+ options
2987
+ });
2988
+ }
2989
+ function registerFields(fields) {
2990
+ Object.entries(fields).forEach(([type, definition]) => {
2991
+ var _a;
2992
+ if (typeof definition === 'function') {
2993
+ fieldRegistry.set(type, {
2994
+ component: definition,
2995
+ options: {}
2996
+ });
2997
+ } else {
2998
+ fieldRegistry.set(type, {
2999
+ component: definition.component,
3000
+ options: (_a = definition.options) !== null && _a !== void 0 ? _a : {}
3001
+ });
3002
+ }
3003
+ });
3004
+ }
3005
+ function getFieldComponent(type) {
3006
+ var _a;
3007
+ const registered = (_a = fieldRegistry.get(type)) === null || _a === void 0 ? void 0 : _a.component;
3008
+ if (registered) {
3009
+ return registered;
3010
+ }
3011
+ return createDefaultFieldComponent(type);
3012
+ }
3013
+ function getFieldValidator(type) {
3014
+ var _a;
3015
+ return (_a = fieldRegistry.get(type)) === null || _a === void 0 ? void 0 : _a.options.validator;
3016
+ }
3017
+ function hasFieldType(type) {
3018
+ return fieldRegistry.has(type);
3019
+ }
3020
+ function unregisterField(type) {
3021
+ return fieldRegistry.delete(type);
3022
+ }
3023
+ function getRegisteredFieldTypes() {
3024
+ return Array.from(fieldRegistry.keys());
3025
+ }
3026
+ function registerFormComponents(components) {
3027
+ Object.keys(components).forEach(key => {
3028
+ componentRegistry[key] = components[key];
3029
+ });
3030
+ }
3031
+ function registerFormComponent(name, component) {
3032
+ componentRegistry[name] = component;
3033
+ }
3034
+ function getFormComponent(name) {
3035
+ var _a;
3036
+ return (_a = componentRegistry[name]) !== null && _a !== void 0 ? _a : defaultFormComponents[name];
3037
+ }
3038
+ function hasFormComponent(name) {
3039
+ return name in componentRegistry;
3040
+ }
3041
+ function getFormComponents() {
3042
+ return {
3043
+ ...componentRegistry
3044
+ };
3045
+ }
3046
+ function clearFieldRegistry() {
3047
+ fieldRegistry.clear();
3048
+ }
3049
+ function clearFormComponentRegistry() {
3050
+ Object.keys(componentRegistry).forEach(key => {
3051
+ delete componentRegistry[key];
3052
+ });
3053
+ }
3054
+ function resetFormComponentRegistry() {
3055
+ clearFormComponentRegistry();
3056
+ Object.assign(componentRegistry, defaultFormComponents);
3057
+ }
3058
+ function clearAllRegistries() {
3059
+ clearFieldRegistry();
3060
+ clearFormComponentRegistry();
3061
+ }
3062
+
3063
+ const FieldRenderer = /*#__PURE__*/memo(t0 => {
3064
+ const $ = c(5);
3065
+ const {
3066
+ field,
3067
+ namePrefix
3068
+ } = t0;
3069
+ const form = useFormContext();
3070
+ if (field.hidden) {
3071
+ return null;
3072
+ }
3073
+ if (!field.name) {
3074
+ console.error(`Field is missing required "name" property. Field type: "${field.type}". ` + "Every field must have a unique name for form state management.");
3075
+ return null;
3076
+ }
3077
+ let t1;
3078
+ let t2;
3079
+ if ($[0] !== field || $[1] !== form || $[2] !== namePrefix) {
3080
+ t2 = Symbol.for("react.early_return_sentinel");
3081
+ bb0: {
3082
+ const FieldComponent = getFieldComponent(field.type);
3083
+ if (!FieldComponent) {
3084
+ console.warn(`No component registered for field type "${field.type}". ` + `Use registerField('${field.type}', Component) to register one.`);
3085
+ t2 = null;
3086
+ break bb0;
3087
+ }
3088
+ const fieldName = namePrefix ? `${namePrefix}.${field.name}` : field.name;
3089
+ t1 = jsx(Controller, {
3090
+ control: form.control,
3091
+ name: fieldName,
3092
+ render: t3 => {
3093
+ const {
3094
+ field: formField,
3095
+ fieldState
3096
+ } = t3;
3097
+ return jsx(FieldComponent, {
3098
+ field: {
3099
+ ...field,
3100
+ name: fieldName
3101
+ },
3102
+ formField,
3103
+ fieldState: {
3104
+ invalid: fieldState.invalid,
3105
+ error: fieldState.error,
3106
+ isDirty: fieldState.isDirty,
3107
+ isTouched: fieldState.isTouched
3108
+ }
3109
+ });
3110
+ }
3111
+ });
3112
+ }
3113
+ $[0] = field;
3114
+ $[1] = form;
3115
+ $[2] = namePrefix;
3116
+ $[3] = t1;
3117
+ $[4] = t2;
3118
+ } else {
3119
+ t1 = $[3];
3120
+ t2 = $[4];
3121
+ }
3122
+ if (t2 !== Symbol.for("react.early_return_sentinel")) {
3123
+ return t2;
3124
+ }
3125
+ return t1;
3126
+ });
3127
+ FieldRenderer.displayName = 'FieldRenderer';
3128
+
3129
+ function useArrayField(field) {
3130
+ const {
3131
+ control
3132
+ } = useFormContext();
3133
+ const fieldArray = useFieldArray({
3134
+ control,
3135
+ name: field.name
3136
+ });
3137
+ const {
3138
+ fields: items,
3139
+ append,
3140
+ prepend,
3141
+ remove,
3142
+ move,
3143
+ swap,
3144
+ insert
3145
+ } = fieldArray;
3146
+ const buildEmptyItem = useCallback(() => {
3147
+ const item = {};
3148
+ field.fields.forEach(f => {
3149
+ var _a;
3150
+ item[f.name] = (_a = f.defaultValue) !== null && _a !== void 0 ? _a : '';
3151
+ });
3152
+ return item;
3153
+ }, [field.fields]);
3154
+ const handleAppend = useCallback(() => {
3155
+ append(buildEmptyItem());
3156
+ }, [append, buildEmptyItem]);
3157
+ const handleAppendWith = useCallback(values => {
3158
+ append(values);
3159
+ }, [append]);
3160
+ const handlePrepend = useCallback(() => {
3161
+ prepend(buildEmptyItem());
3162
+ }, [prepend, buildEmptyItem]);
3163
+ const handleInsert = useCallback((index, values_0) => {
3164
+ insert(index, values_0 !== null && values_0 !== void 0 ? values_0 : buildEmptyItem());
3165
+ }, [insert, buildEmptyItem]);
3166
+ const canAppend = field.maxItems === undefined || items.length < field.maxItems;
3167
+ const canRemove = field.minItems === undefined || items.length > field.minItems;
3168
+ const renderField = useCallback((index_0, fieldName) => {
3169
+ const childField = field.fields.find(f_0 => f_0.name === fieldName);
3170
+ if (!childField) {
3171
+ console.warn(`Field "${fieldName}" not found in array field "${field.name}"`);
3172
+ return jsx(Fragment$1, {});
3173
+ }
3174
+ return jsx(FieldRenderer, {
3175
+ field: childField,
3176
+ namePrefix: `${field.name}.${index_0}`
3177
+ }, `${field.name}.${index_0}.${fieldName}`);
3178
+ }, [field]);
3179
+ const renderItem = useCallback(index_1 => {
3180
+ const result = {};
3181
+ field.fields.forEach(childField_0 => {
3182
+ result[childField_0.name] = jsx(FieldRenderer, {
3183
+ field: childField_0,
3184
+ namePrefix: `${field.name}.${index_1}`
3185
+ }, `${field.name}.${index_1}.${childField_0.name}`);
3186
+ });
3187
+ return result;
3188
+ }, [field]);
3189
+ return {
3190
+ fieldArray,
3191
+ append: handleAppend,
3192
+ appendWith: handleAppendWith,
3193
+ prepend: handlePrepend,
3194
+ remove,
3195
+ move,
3196
+ swap,
3197
+ insert: handleInsert,
3198
+ field,
3199
+ items: items.map((item_0, index_2) => ({
3200
+ id: item_0.id,
3201
+ index: index_2
3202
+ })),
3203
+ canAppend,
3204
+ canRemove,
3205
+ renderField,
3206
+ renderItem
3207
+ };
3208
+ }
3209
+ const ArrayFieldRenderer = /*#__PURE__*/memo(t0 => {
3210
+ const $ = c(28);
3211
+ const {
3212
+ field,
3213
+ children
3214
+ } = t0;
3215
+ const {
3216
+ items,
3217
+ append,
3218
+ remove,
3219
+ move,
3220
+ canAppend,
3221
+ renderItem,
3222
+ field: arrayField
3223
+ } = useArrayField(field);
3224
+ if (field.hidden) {
3225
+ return null;
3226
+ }
3227
+ if (!children) {
3228
+ let t1;
3229
+ if ($[0] !== append || $[1] !== canAppend || $[2] !== field.className || $[3] !== field.description || $[4] !== field.label || $[5] !== items || $[6] !== renderItem) {
3230
+ let t2;
3231
+ if ($[8] !== renderItem) {
3232
+ t2 = t3 => {
3233
+ const {
3234
+ id,
3235
+ index
3236
+ } = t3;
3237
+ return jsx("div", {
3238
+ "data-array-item-index": index,
3239
+ children: Object.values(renderItem(index))
3240
+ }, id);
3241
+ };
3242
+ $[8] = renderItem;
3243
+ $[9] = t2;
3244
+ } else {
3245
+ t2 = $[9];
3246
+ }
3247
+ t1 = jsxs("div", {
3248
+ className: field.className,
3249
+ children: [field.label && jsx("label", {
3250
+ children: field.label
3251
+ }), field.description && jsx("p", {
3252
+ children: field.description
3253
+ }), items.map(t2), canAppend && jsx("button", {
3254
+ type: "button",
3255
+ onClick: append,
3256
+ children: "Add Item"
3257
+ })]
3258
+ });
3259
+ $[0] = append;
3260
+ $[1] = canAppend;
3261
+ $[2] = field.className;
3262
+ $[3] = field.description;
3263
+ $[4] = field.label;
3264
+ $[5] = items;
3265
+ $[6] = renderItem;
3266
+ $[7] = t1;
3267
+ } else {
3268
+ t1 = $[7];
3269
+ }
3270
+ return t1;
3271
+ }
3272
+ let t1;
3273
+ if ($[10] !== arrayField || $[11] !== children || $[12] !== field.className || $[13] !== field.description || $[14] !== field.label || $[15] !== field.name || $[16] !== items || $[17] !== move || $[18] !== remove || $[19] !== renderItem) {
3274
+ let t2;
3275
+ if ($[21] !== arrayField || $[22] !== children || $[23] !== field.name || $[24] !== move || $[25] !== remove || $[26] !== renderItem) {
3276
+ t2 = t3 => {
3277
+ const {
3278
+ id: id_0,
3279
+ index: index_0
3280
+ } = t3;
3281
+ return children({
3282
+ index: index_0,
3283
+ id: id_0,
3284
+ remove: () => remove(index_0),
3285
+ move: toIndex => move(index_0, toIndex),
3286
+ fields: renderItem(index_0),
3287
+ fieldNames: arrayField.fields.map(_temp),
3288
+ namePrefix: `${field.name}.${index_0}`
3289
+ });
3290
+ };
3291
+ $[21] = arrayField;
3292
+ $[22] = children;
3293
+ $[23] = field.name;
3294
+ $[24] = move;
3295
+ $[25] = remove;
3296
+ $[26] = renderItem;
3297
+ $[27] = t2;
3298
+ } else {
3299
+ t2 = $[27];
3300
+ }
3301
+ t1 = jsxs("div", {
3302
+ className: field.className,
3303
+ children: [field.label && jsx("label", {
3304
+ children: field.label
3305
+ }), field.description && jsx("p", {
3306
+ children: field.description
3307
+ }), items.map(t2)]
3308
+ });
3309
+ $[10] = arrayField;
3310
+ $[11] = children;
3311
+ $[12] = field.className;
3312
+ $[13] = field.description;
3313
+ $[14] = field.label;
3314
+ $[15] = field.name;
3315
+ $[16] = items;
3316
+ $[17] = move;
3317
+ $[18] = remove;
3318
+ $[19] = renderItem;
3319
+ $[20] = t1;
3320
+ } else {
3321
+ t1 = $[20];
3322
+ }
3323
+ return t1;
3324
+ });
3325
+ ArrayFieldRenderer.displayName = 'ArrayFieldRenderer';
3326
+ function _temp(f) {
3327
+ return f.name;
3328
+ }
3329
+
3330
+ const RESERVED_PROPS = new Set(['all', 'remaining', 'names', 'has', 'render']);
3331
+ function createTemplateFields(fieldEntries) {
3332
+ const accessedFields = new Set();
3333
+ const handler = {
3334
+ get(_, prop) {
3335
+ if (typeof prop === 'symbol') {
3336
+ return undefined;
3337
+ }
3338
+ if (prop === 'all') {
3339
+ return Array.from(fieldEntries.values()).map(entry => entry.element);
3340
+ }
3341
+ if (prop === 'remaining') {
3342
+ return Array.from(fieldEntries.entries()).filter(([name]) => !accessedFields.has(name)).map(([, entry]) => entry.element);
3343
+ }
3344
+ if (prop === 'names') {
3345
+ return Array.from(fieldEntries.keys());
3346
+ }
3347
+ if (prop === 'has') {
3348
+ return name => fieldEntries.has(name);
3349
+ }
3350
+ if (prop === 'render') {
3351
+ return (...names) => {
3352
+ return names.filter(name => fieldEntries.has(name)).map(name => {
3353
+ accessedFields.add(name);
3354
+ return fieldEntries.get(name).element;
3355
+ });
3356
+ };
3357
+ }
3358
+ if (fieldEntries.has(prop)) {
3359
+ accessedFields.add(prop);
3360
+ return fieldEntries.get(prop).element;
3361
+ }
3362
+ return undefined;
3363
+ },
3364
+ has(_, prop) {
3365
+ if (typeof prop === 'symbol') {
3366
+ return false;
3367
+ }
3368
+ return RESERVED_PROPS.has(prop) || fieldEntries.has(prop);
3369
+ },
3370
+ ownKeys() {
3371
+ return [...RESERVED_PROPS, ...fieldEntries.keys()];
3372
+ },
3373
+ getOwnPropertyDescriptor(_, prop) {
3374
+ if (typeof prop === 'symbol') {
3375
+ return undefined;
3376
+ }
3377
+ if (RESERVED_PROPS.has(prop) || fieldEntries.has(prop)) {
3378
+ return {
3379
+ configurable: true,
3380
+ enumerable: true,
3381
+ value: this.get(_, prop, {})
3382
+ };
3383
+ }
3384
+ return undefined;
3385
+ }
3386
+ };
3387
+ return new Proxy({}, handler);
3388
+ }
3389
+
3390
+ const FieldsContext = /*#__PURE__*/createContext(null);
3391
+ function FieldsProvider(t0) {
3392
+ const $ = c(9);
3393
+ const {
3394
+ children,
3395
+ fields,
3396
+ namePrefix
3397
+ } = t0;
3398
+ let map;
3399
+ if ($[0] !== fields || $[1] !== namePrefix) {
3400
+ map = new Map();
3401
+ const addFields = (items, prefix) => {
3402
+ items.forEach(item => {
3403
+ if ("fields" in item && Array.isArray(item.fields)) {
3404
+ const arrayPrefix = prefix ? `${prefix}.${item.name}` : item.name;
3405
+ addFields(item.fields, arrayPrefix);
3406
+ } else {
3407
+ const fieldName = prefix ? `${prefix}.${item.name}` : item.name;
3408
+ map.set(fieldName, item);
3409
+ if (prefix) {
3410
+ map.set(item.name, item);
3411
+ }
3412
+ }
3413
+ });
3414
+ };
3415
+ addFields(fields, namePrefix);
3416
+ $[0] = fields;
3417
+ $[1] = namePrefix;
3418
+ $[2] = map;
3419
+ } else {
3420
+ map = $[2];
3421
+ }
3422
+ const fieldsMap = map;
3423
+ let t1;
3424
+ if ($[3] !== fieldsMap || $[4] !== namePrefix) {
3425
+ t1 = {
3426
+ fields: fieldsMap,
3427
+ namePrefix
3428
+ };
3429
+ $[3] = fieldsMap;
3430
+ $[4] = namePrefix;
3431
+ $[5] = t1;
3432
+ } else {
3433
+ t1 = $[5];
3434
+ }
3435
+ const value = t1;
3436
+ let t2;
3437
+ if ($[6] !== children || $[7] !== value) {
3438
+ t2 = jsx(FieldsContext.Provider, {
3439
+ value,
3440
+ children
3441
+ });
3442
+ $[6] = children;
3443
+ $[7] = value;
3444
+ $[8] = t2;
3445
+ } else {
3446
+ t2 = $[8];
3447
+ }
3448
+ return t2;
3449
+ }
3450
+ function useFieldProps(name) {
3451
+ const $ = c(23);
3452
+ const context = useContext(FieldsContext);
3453
+ const form = useFormContext();
3454
+ if (!context) {
3455
+ throw new Error("useFieldProps must be used within FormGenerator or FieldsProvider");
3456
+ }
3457
+ if (!form) {
3458
+ throw new Error("useFieldProps must be used within a FormProvider context");
3459
+ }
3460
+ const {
3461
+ fields,
3462
+ namePrefix
3463
+ } = context;
3464
+ const fullName = namePrefix ? `${namePrefix}.${name}` : name;
3465
+ let t0;
3466
+ if ($[0] !== fields || $[1] !== fullName || $[2] !== name) {
3467
+ t0 = fields.get(fullName) || fields.get(name);
3468
+ $[0] = fields;
3469
+ $[1] = fullName;
3470
+ $[2] = name;
3471
+ $[3] = t0;
3472
+ } else {
3473
+ t0 = $[3];
3474
+ }
3475
+ const field = t0;
3476
+ if (!field) {
3477
+ throw new Error(`Field "${name}" not found in form fields. ` + `Available fields: ${Array.from(fields.keys()).join(", ")}`);
3478
+ }
3479
+ let t1;
3480
+ if ($[4] !== form.control || $[5] !== fullName) {
3481
+ t1 = {
3482
+ control: form.control,
3483
+ name: fullName
3484
+ };
3485
+ $[4] = form.control;
3486
+ $[5] = fullName;
3487
+ $[6] = t1;
3488
+ } else {
3489
+ t1 = $[6];
3490
+ }
3491
+ const {
3492
+ field: controllerField,
3493
+ fieldState
3494
+ } = useController(t1);
3495
+ let t2;
3496
+ if ($[7] !== field || $[8] !== fullName) {
3497
+ t2 = {
3498
+ ...field,
3499
+ name: fullName
3500
+ };
3501
+ $[7] = field;
3502
+ $[8] = fullName;
3503
+ $[9] = t2;
3504
+ } else {
3505
+ t2 = $[9];
3506
+ }
3507
+ let t3;
3508
+ if ($[10] !== fieldState.error || $[11] !== fieldState.invalid || $[12] !== fieldState.isDirty || $[13] !== fieldState.isTouched) {
3509
+ t3 = {
3510
+ invalid: fieldState.invalid,
3511
+ error: fieldState.error,
3512
+ isDirty: fieldState.isDirty,
3513
+ isTouched: fieldState.isTouched
3514
+ };
3515
+ $[10] = fieldState.error;
3516
+ $[11] = fieldState.invalid;
3517
+ $[12] = fieldState.isDirty;
3518
+ $[13] = fieldState.isTouched;
3519
+ $[14] = t3;
3520
+ } else {
3521
+ t3 = $[14];
3522
+ }
3523
+ let t4;
3524
+ if ($[15] !== controllerField.name || $[16] !== controllerField.onBlur || $[17] !== controllerField.onChange || $[18] !== controllerField.ref || $[19] !== controllerField.value || $[20] !== t2 || $[21] !== t3) {
3525
+ t4 = {
3526
+ name: controllerField.name,
3527
+ value: controllerField.value,
3528
+ onChange: controllerField.onChange,
3529
+ onBlur: controllerField.onBlur,
3530
+ ref: controllerField.ref,
3531
+ field: t2,
3532
+ fieldState: t3
3533
+ };
3534
+ $[15] = controllerField.name;
3535
+ $[16] = controllerField.onBlur;
3536
+ $[17] = controllerField.onChange;
3537
+ $[18] = controllerField.ref;
3538
+ $[19] = controllerField.value;
3539
+ $[20] = t2;
3540
+ $[21] = t3;
3541
+ $[22] = t4;
3542
+ } else {
3543
+ t4 = $[22];
3544
+ }
3545
+ return t4;
3546
+ }
3547
+ function useFieldsContext() {
3548
+ return useContext(FieldsContext);
3549
+ }
3550
+
3551
+ function isSchemaRequired(schema) {
3552
+ return !schema.isOptional() && !schema.isNullable();
3553
+ }
3554
+ function unwrapSchema(schema) {
3555
+ let current = schema;
3556
+ while (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {
3557
+ current = current.unwrap();
3558
+ }
3559
+ if (current instanceof z.ZodDefault) {
3560
+ current = current._def.innerType;
3561
+ }
3562
+ return current;
3563
+ }
3564
+ function getSchemaTypeName(schema) {
3565
+ const unwrapped = unwrapSchema(schema);
3566
+ if (unwrapped instanceof z.ZodString) return 'string';
3567
+ if (unwrapped instanceof z.ZodNumber) return 'number';
3568
+ if (unwrapped instanceof z.ZodBoolean) return 'boolean';
3569
+ if (unwrapped instanceof z.ZodDate) return 'date';
3570
+ if (unwrapped instanceof z.ZodArray) return 'array';
3571
+ if (unwrapped instanceof z.ZodObject) return 'object';
3572
+ if (unwrapped instanceof z.ZodEnum) return 'enum';
3573
+ return 'unknown';
3574
+ }
3575
+ function getCheckDef(check) {
3576
+ var _a;
3577
+ if ((_a = check._zod) === null || _a === void 0 ? void 0 : _a.def) {
3578
+ const def = check._zod.def;
3579
+ return {
3580
+ type: def.check,
3581
+ value: def.value,
3582
+ minimum: def.minimum,
3583
+ maximum: def.maximum,
3584
+ length: def.length,
3585
+ regex: def.pattern || def.regex,
3586
+ format: def.format,
3587
+ inclusive: def.inclusive
3588
+ };
3589
+ }
3590
+ if (check.kind) {
3591
+ return {
3592
+ type: check.kind,
3593
+ value: check.value,
3594
+ regex: check.regex
3595
+ };
3596
+ }
3597
+ return null;
3598
+ }
3599
+ function getNumberConstraints(schema) {
3600
+ const unwrapped = unwrapSchema(schema);
3601
+ if (!(unwrapped instanceof z.ZodNumber)) {
3602
+ return {};
3603
+ }
3604
+ const constraints = {};
3605
+ const checks = unwrapped._def.checks;
3606
+ if (checks) {
3607
+ for (const check of checks) {
3608
+ const def = getCheckDef(check);
3609
+ if (!def) continue;
3610
+ if (def.type === 'greater_than' || def.type === 'min') {
3611
+ constraints.min = def.value;
3612
+ } else if (def.type === 'less_than' || def.type === 'max') {
3613
+ constraints.max = def.value;
3614
+ } else if (def.type === 'multiple_of' || def.type === 'multipleOf') {
3615
+ constraints.step = def.value;
3616
+ } else if (def.type === 'number_format' && (def.format === 'safeint' || def.format === 'int')) {
3617
+ constraints.step = 1;
3618
+ } else if (def.type === 'int' || def.type === 'integer') {
3619
+ constraints.step = 1;
3620
+ }
3621
+ }
3622
+ }
3623
+ return constraints;
3624
+ }
3625
+ function getStringConstraints(schema) {
3626
+ const unwrapped = unwrapSchema(schema);
3627
+ if (!(unwrapped instanceof z.ZodString)) {
3628
+ return {};
3629
+ }
3630
+ const constraints = {};
3631
+ const checks = unwrapped._def.checks;
3632
+ if (checks) {
3633
+ for (const check of checks) {
3634
+ const def = getCheckDef(check);
3635
+ if (!def) continue;
3636
+ if (def.type === 'min_length' && def.minimum !== undefined) {
3637
+ constraints.minLength = def.minimum;
3638
+ } else if (def.type === 'min' && def.value !== undefined) {
3639
+ constraints.minLength = def.value;
3640
+ } else if (def.type === 'max_length' && def.maximum !== undefined) {
3641
+ constraints.maxLength = def.maximum;
3642
+ } else if (def.type === 'max' && def.value !== undefined) {
3643
+ constraints.maxLength = def.value;
3644
+ } else if (def.type === 'length_equals' && def.length !== undefined) {
3645
+ constraints.minLength = def.length;
3646
+ constraints.maxLength = def.length;
3647
+ } else if (def.type === 'length' && def.value !== undefined) {
3648
+ constraints.minLength = def.value;
3649
+ constraints.maxLength = def.value;
3650
+ } else if (def.type === 'string_format' && def.regex) {
3651
+ constraints.pattern = def.regex.source;
3652
+ } else if (def.type === 'regex' && def.regex) {
3653
+ constraints.pattern = def.regex.source;
3654
+ }
3655
+ }
3656
+ }
3657
+ return constraints;
3658
+ }
3659
+ function getDateConstraints(schema) {
3660
+ const unwrapped = unwrapSchema(schema);
3661
+ if (!(unwrapped instanceof z.ZodDate)) {
3662
+ return {};
3663
+ }
3664
+ const constraints = {};
3665
+ const checks = unwrapped._def.checks;
3666
+ if (checks) {
3667
+ for (const check of checks) {
3668
+ const def = getCheckDef(check);
3669
+ if (!def) continue;
3670
+ if (def.type === 'greater_than' || def.type === 'min') {
3671
+ const value = def.value;
3672
+ constraints.min = value instanceof Date ? value : new Date(value);
3673
+ } else if (def.type === 'less_than' || def.type === 'max') {
3674
+ const value = def.value;
3675
+ constraints.max = value instanceof Date ? value : new Date(value);
3676
+ }
3677
+ }
3678
+ }
3679
+ return constraints;
3680
+ }
3681
+ function getSchemaRequirements(schema) {
3682
+ const result = {};
3683
+ const shape = schema.shape;
3684
+ for (const key in shape) {
3685
+ result[key] = isSchemaRequired(shape[key]);
3686
+ }
3687
+ return result;
3688
+ }
3689
+ function analyzeSchema(schema) {
3690
+ const shape = schema.shape;
3691
+ return Object.entries(shape).map(([name, fieldSchema]) => {
3692
+ const type = getSchemaTypeName(fieldSchema);
3693
+ const info = {
3694
+ name,
3695
+ required: isSchemaRequired(fieldSchema),
3696
+ type,
3697
+ schema: fieldSchema
3698
+ };
3699
+ if (type === 'number') {
3700
+ const constraints = getNumberConstraints(fieldSchema);
3701
+ if (constraints.min !== undefined) info.min = constraints.min;
3702
+ if (constraints.max !== undefined) info.max = constraints.max;
3703
+ if (constraints.step !== undefined) info.step = constraints.step;
3704
+ } else if (type === 'string') {
3705
+ const constraints = getStringConstraints(fieldSchema);
3706
+ if (constraints.minLength !== undefined) info.minLength = constraints.minLength;
3707
+ if (constraints.maxLength !== undefined) info.maxLength = constraints.maxLength;
3708
+ if (constraints.pattern !== undefined) info.pattern = constraints.pattern;
3709
+ } else if (type === 'date') {
3710
+ const constraints = getDateConstraints(fieldSchema);
3711
+ if (constraints.min !== undefined) info.minDate = constraints.min;
3712
+ if (constraints.max !== undefined) info.maxDate = constraints.max;
3713
+ }
3714
+ return info;
3715
+ });
3716
+ }
3717
+ function mergeSchemaRequirements(schema, fields) {
3718
+ const requirements = getSchemaRequirements(schema);
3719
+ return fields.map(field => {
3720
+ const schemaRequired = requirements[field.name];
3721
+ if (schemaRequired !== undefined) {
3722
+ return {
3723
+ ...field,
3724
+ required: schemaRequired
3725
+ };
3726
+ }
3727
+ return field;
3728
+ });
3729
+ }
3730
+ function mergeSchemaConstraints(schema, fields) {
3731
+ const fieldInfoMap = new Map();
3732
+ analyzeSchema(schema).forEach(info => {
3733
+ fieldInfoMap.set(info.name, info);
3734
+ });
3735
+ return fields.map(field => {
3736
+ const schemaInfo = fieldInfoMap.get(field.name);
3737
+ if (!schemaInfo) {
3738
+ return field;
3739
+ }
3740
+ const merged = {
3741
+ ...field,
3742
+ required: schemaInfo.required
3743
+ };
3744
+ if (schemaInfo.type === 'number') {
3745
+ if (schemaInfo.min !== undefined) {
3746
+ merged.min = schemaInfo.min;
3747
+ }
3748
+ if (schemaInfo.max !== undefined) {
3749
+ merged.max = schemaInfo.max;
3750
+ }
3751
+ if (schemaInfo.step !== undefined) {
3752
+ merged.step = schemaInfo.step;
3753
+ }
3754
+ }
3755
+ if (schemaInfo.type === 'string') {
3756
+ if (schemaInfo.minLength !== undefined) {
3757
+ merged.minLength = schemaInfo.minLength;
3758
+ }
3759
+ if (schemaInfo.maxLength !== undefined) {
3760
+ merged.maxLength = schemaInfo.maxLength;
3761
+ }
3762
+ if (schemaInfo.pattern !== undefined) {
3763
+ merged.pattern = schemaInfo.pattern;
3764
+ }
3765
+ }
3766
+ if (schemaInfo.type === 'date') {
3767
+ if (schemaInfo.minDate !== undefined) {
3768
+ merged.min = schemaInfo.minDate.toISOString().split('T')[0];
3769
+ }
3770
+ if (schemaInfo.maxDate !== undefined) {
3771
+ merged.max = schemaInfo.maxDate.toISOString().split('T')[0];
3772
+ }
3773
+ }
3774
+ return merged;
3775
+ });
3776
+ }
3777
+ function deepMerge(target, source) {
3778
+ const result = {
3779
+ ...target
3780
+ };
3781
+ for (const key of Object.keys(source)) {
3782
+ if (source[key] !== null && typeof source[key] === 'object' && !Array.isArray(source[key]) && target[key] !== null && typeof target[key] === 'object' && !Array.isArray(target[key])) {
3783
+ result[key] = deepMerge(target[key], source[key]);
3784
+ } else {
3785
+ result[key] = source[key];
3786
+ }
3787
+ }
3788
+ return result;
3789
+ }
3790
+ function stringValidator(field) {
3791
+ return field.required ? z.string().min(1, 'Field is required') : z.string();
3792
+ }
3793
+ const defaultValidators = {
3794
+ text: stringValidator,
3795
+ textarea: stringValidator,
3796
+ email: field => field.required ? z.email() : z.email().optional(),
3797
+ password: stringValidator,
3798
+ url: field => field.required ? z.url() : z.url().optional(),
3799
+ tel: stringValidator,
3800
+ number: field => {
3801
+ let schema = z.coerce.number();
3802
+ const numberField = field;
3803
+ if (numberField.min !== undefined) schema = schema.min(numberField.min);
3804
+ if (numberField.max !== undefined) schema = schema.max(numberField.max);
3805
+ return schema;
3806
+ },
3807
+ checkbox: () => z.coerce.boolean(),
3808
+ switch: () => z.coerce.boolean(),
3809
+ select: field => field.required ? z.string().min(1) : z.string(),
3810
+ radio: field => field.required ? z.string().min(1) : z.string(),
3811
+ date: () => z.coerce.date(),
3812
+ datetime: () => z.coerce.date(),
3813
+ time: stringValidator,
3814
+ file: () => z.any(),
3815
+ hidden: () => z.any()
3816
+ };
3817
+ function getValidatorForField(field) {
3818
+ if (field.validation) {
3819
+ return field.validation;
3820
+ }
3821
+ const registeredValidator = getFieldValidator(field.type);
3822
+ if (registeredValidator) {
3823
+ return registeredValidator(field);
3824
+ }
3825
+ const defaultValidator = defaultValidators[field.type];
3826
+ if (defaultValidator) {
3827
+ return defaultValidator(field);
3828
+ }
3829
+ return z.any();
3830
+ }
3831
+ function buildArrayItemSchema(arrayField) {
3832
+ const itemShape = {};
3833
+ for (const field of arrayField.fields) {
3834
+ const validator = getValidatorForField(field);
3835
+ itemShape[field.name] = field.required ? validator : validator.optional();
3836
+ }
3837
+ return z.object(itemShape);
3838
+ }
3839
+ function buildSchema(fields) {
3840
+ const shape = {};
3841
+ for (const field of fields) {
3842
+ if (isArrayField(field)) {
3843
+ let arraySchema = z.array(buildArrayItemSchema(field));
3844
+ if (field.minItems !== undefined) {
3845
+ arraySchema = arraySchema.min(field.minItems);
3846
+ }
3847
+ if (field.maxItems !== undefined) {
3848
+ arraySchema = arraySchema.max(field.maxItems);
3849
+ }
3850
+ shape[field.name] = arraySchema;
3851
+ } else {
3852
+ const validator = getValidatorForField(field);
3853
+ shape[field.name] = field.required ? validator : validator.optional();
3854
+ }
3855
+ }
3856
+ return z.object(shape);
3857
+ }
3858
+ function buildArrayItemDefaults(arrayField) {
3859
+ var _a;
3860
+ const item = {};
3861
+ for (const field of arrayField.fields) {
3862
+ item[field.name] = (_a = field.defaultValue) !== null && _a !== void 0 ? _a : '';
3863
+ }
3864
+ return item;
3865
+ }
3866
+ function buildDefaultValues(fields) {
3867
+ var _a;
3868
+ const values = {};
3869
+ for (const field of fields) {
3870
+ if (isArrayField(field)) {
3871
+ if (field.defaultValue && field.defaultValue.length > 0) {
3872
+ values[field.name] = field.defaultValue;
3873
+ } else if (field.minItems && field.minItems > 0) {
3874
+ values[field.name] = Array.from({
3875
+ length: field.minItems
3876
+ }, () => buildArrayItemDefaults(field));
3877
+ } else {
3878
+ values[field.name] = [];
3879
+ }
3880
+ } else {
3881
+ values[field.name] = (_a = field.defaultValue) !== null && _a !== void 0 ? _a : '';
3882
+ }
3883
+ }
3884
+ return values;
3885
+ }
3886
+
3887
+ function FormGenerator(props) {
3888
+ const {
3889
+ fields,
3890
+ defaultValues,
3891
+ className,
3892
+ submitText = 'Submit',
3893
+ disabled,
3894
+ mode = 'onChange',
3895
+ title,
3896
+ description,
3897
+ showReset = false,
3898
+ resetText = 'Reset',
3899
+ children,
3900
+ ref,
3901
+ validateTypes
3902
+ } = props;
3903
+ const onSubmit = props.onSubmit;
3904
+ const formRef = useRef(null);
3905
+ useMemo(() => {
3906
+ if (validateTypes) {
3907
+ const registeredTypes = getRegisteredFieldTypes();
3908
+ const options = typeof validateTypes === 'object' ? validateTypes : {
3909
+ throwOnError: false,
3910
+ warn: true
3911
+ };
3912
+ validateFieldTypes(fields, registeredTypes, options);
3913
+ }
3914
+ }, [fields, validateTypes]);
3915
+ const schema = useMemo(() => buildSchema(fields), [fields]);
3916
+ const mergedDefaultValues = useMemo(() => {
3917
+ const builtDefaults = buildDefaultValues(fields);
3918
+ return defaultValues ? deepMerge(builtDefaults, defaultValues) : builtDefaults;
3919
+ }, [fields, defaultValues]);
3920
+ const form = useForm({
3921
+ resolver: a(schema),
3922
+ defaultValues: mergedDefaultValues,
3923
+ mode
3924
+ });
3925
+ const handleSubmit = form.handleSubmit(async data => {
3926
+ const context = {
3927
+ isDirty: form.formState.isDirty,
3928
+ dirtyFields: form.formState.dirtyFields,
3929
+ isValid: form.formState.isValid,
3930
+ errors: form.formState.errors,
3931
+ touchedFields: form.formState.touchedFields,
3932
+ isSubmitting: form.formState.isSubmitting,
3933
+ submitCount: form.formState.submitCount,
3934
+ defaultValues: mergedDefaultValues,
3935
+ form: form
3936
+ };
3937
+ await onSubmit(data, context);
3938
+ });
3939
+ const handleReset = useCallback(() => {
3940
+ form.reset(mergedDefaultValues);
3941
+ }, [form, mergedDefaultValues]);
3942
+ useImperativeHandle(ref, () => ({
3943
+ setValues: values => {
3944
+ Object.entries(values).forEach(([key, value]) => {
3945
+ form.setValue(key, value, {
3946
+ shouldValidate: true,
3947
+ shouldDirty: true
3948
+ });
3949
+ });
3950
+ },
3951
+ getValues: () => form.getValues(),
3952
+ reset: values_0 => {
3953
+ if (values_0) {
3954
+ form.reset(deepMerge(mergedDefaultValues, values_0));
3955
+ } else {
3956
+ form.reset(mergedDefaultValues);
3957
+ }
3958
+ },
3959
+ submit: async () => {
3960
+ await handleSubmit();
3961
+ },
3962
+ clearErrors: () => form.clearErrors(),
3963
+ setError: (name, error) => form.setError(name, error),
3964
+ isValid: () => form.formState.isValid,
3965
+ isDirty: () => form.formState.isDirty,
3966
+ form: form
3967
+ }), [form, handleSubmit, mergedDefaultValues]);
3968
+ const SubmitButton = getFormComponent('SubmitButton');
3969
+ const FieldWrapper = getFormComponent('FieldWrapper');
3970
+ const FieldsWrapper = getFormComponent('FieldsWrapper');
3971
+ const {
3972
+ regularFields,
3973
+ arrayFields
3974
+ } = useMemo(() => {
3975
+ const regular = [];
3976
+ const arrays = [];
3977
+ fields.forEach(field => {
3978
+ if (isArrayField(field)) {
3979
+ arrays.push(field);
3980
+ } else {
3981
+ regular.push(field);
3982
+ }
3983
+ });
3984
+ return {
3985
+ regularFields: regular,
3986
+ arrayFields: arrays
3987
+ };
3988
+ }, [fields]);
3989
+ const fieldEntries = useMemo(() => {
3990
+ const entries = new Map();
3991
+ regularFields.forEach((field_0, index) => {
3992
+ if (!field_0.hidden) {
3993
+ const element = jsx(FieldWrapper, {
3994
+ name: field_0.name,
3995
+ type: field_0.type,
3996
+ className: field_0.className,
3997
+ children: jsx(FieldRenderer, {
3998
+ field: field_0
3999
+ })
4000
+ }, field_0.name || `field-${index}`);
4001
+ entries.set(field_0.name, {
4002
+ field: field_0,
4003
+ element,
4004
+ accessed: false
4005
+ });
4006
+ }
4007
+ });
4008
+ return entries;
4009
+ }, [regularFields, FieldWrapper]);
4010
+ const templateFields = useMemo(() => createTemplateFields(fieldEntries), [fieldEntries]);
4011
+ const buttons = useMemo(() => {
4012
+ const result = {
4013
+ submit: jsx(SubmitButton, {
4014
+ disabled: disabled || form.formState.isSubmitting,
4015
+ isSubmitting: form.formState.isSubmitting,
4016
+ children: submitText
4017
+ }, "submit")
4018
+ };
4019
+ if (showReset) {
4020
+ result.reset = jsx("button", {
4021
+ type: "button",
4022
+ onClick: handleReset,
4023
+ disabled: disabled,
4024
+ children: resetText
4025
+ }, "reset");
4026
+ }
4027
+ return result;
4028
+ }, [SubmitButton, disabled, form.formState.isSubmitting, submitText, showReset, resetText, handleReset]);
4029
+ const renderField = useCallback((field_1, options_0) => {
4030
+ return jsx(FieldRenderer, {
4031
+ field: field_1,
4032
+ namePrefix: options_0 === null || options_0 === void 0 ? void 0 : options_0.namePrefix
4033
+ });
4034
+ }, []);
4035
+ if (!children) {
4036
+ return jsx(FormProvider, {
4037
+ ...form,
4038
+ children: jsx(FieldsProvider, {
4039
+ fields: fields,
4040
+ children: jsxs("form", {
4041
+ ref: formRef,
4042
+ onSubmit: handleSubmit,
4043
+ className: className,
4044
+ children: [jsxs(FieldsWrapper, {
4045
+ children: [regularFields.map((field_2, index_0) => jsx(FieldWrapper, {
4046
+ name: field_2.name,
4047
+ type: field_2.type,
4048
+ className: field_2.className,
4049
+ children: jsx(FieldRenderer, {
4050
+ field: field_2
4051
+ })
4052
+ }, field_2.name || `field-${index_0}`)), arrayFields.map(arrayField => jsx(FieldWrapper, {
4053
+ name: arrayField.name,
4054
+ type: "array",
4055
+ className: arrayField.className,
4056
+ children: jsx(ArrayFieldRenderer, {
4057
+ field: arrayField
4058
+ })
4059
+ }, arrayField.name))]
4060
+ }), jsx(SubmitButton, {
4061
+ disabled: disabled || form.formState.isSubmitting,
4062
+ isSubmitting: form.formState.isSubmitting,
4063
+ children: submitText
4064
+ })]
4065
+ })
4066
+ })
4067
+ });
4068
+ }
4069
+ const renderProps = {
4070
+ fields: templateFields,
4071
+ arrays: Object.fromEntries(arrayFields.map(arrayField_0 => [arrayField_0.name, {
4072
+ field: arrayField_0
4073
+ }])),
4074
+ buttons,
4075
+ title,
4076
+ description,
4077
+ form: form,
4078
+ isSubmitting: form.formState.isSubmitting,
4079
+ isValid: form.formState.isValid,
4080
+ isDirty: form.formState.isDirty,
4081
+ renderField,
4082
+ FieldWrapper,
4083
+ FieldsWrapper
4084
+ };
4085
+ const renderFn = children;
4086
+ return jsx(FormProvider, {
4087
+ ...form,
4088
+ children: jsx(FieldsProvider, {
4089
+ fields: fields,
4090
+ children: jsx("form", {
4091
+ ref: formRef,
4092
+ onSubmit: handleSubmit,
4093
+ className: className,
4094
+ children: renderFn(renderProps)
4095
+ })
4096
+ })
4097
+ });
4098
+ }
4099
+
4100
+ function typedField() {
4101
+ return field => field;
4102
+ }
4103
+ function typedFields(fields) {
4104
+ return fields;
4105
+ }
4106
+ function StrictFormGenerator(props) {
4107
+ const {
4108
+ schema,
4109
+ fields,
4110
+ onSubmit,
4111
+ defaultValues,
4112
+ className,
4113
+ submitText = 'Submit',
4114
+ disabled,
4115
+ mode = 'onChange',
4116
+ title,
4117
+ description,
4118
+ showReset = false,
4119
+ resetText = 'Reset',
4120
+ children,
4121
+ ref,
4122
+ validateTypes
4123
+ } = props;
4124
+ const formRef = useRef(null);
4125
+ const fieldsWithRequirements = useMemo(() => {
4126
+ if (schema && typeof schema === 'object' && 'shape' in schema) {
4127
+ return mergeSchemaConstraints(schema, fields);
4128
+ }
4129
+ return fields;
4130
+ }, [schema, fields]);
4131
+ useMemo(() => {
4132
+ if (validateTypes) {
4133
+ const registeredTypes = getRegisteredFieldTypes();
4134
+ const options = typeof validateTypes === 'object' ? validateTypes : {
4135
+ throwOnError: false,
4136
+ warn: true
4137
+ };
4138
+ validateFieldTypes(fieldsWithRequirements, registeredTypes, options);
4139
+ }
4140
+ }, [fieldsWithRequirements, validateTypes]);
4141
+ const mergedDefaultValues = useMemo(() => {
4142
+ const builtDefaults = buildDefaultValues(fieldsWithRequirements);
4143
+ return defaultValues ? deepMerge(builtDefaults, defaultValues) : builtDefaults;
4144
+ }, [fieldsWithRequirements, defaultValues]);
4145
+ const form = useForm({
4146
+ resolver: a(schema),
4147
+ defaultValues: mergedDefaultValues,
4148
+ mode
4149
+ });
4150
+ const handleSubmit = form.handleSubmit(async data => {
4151
+ const context = {
4152
+ isDirty: form.formState.isDirty,
4153
+ dirtyFields: form.formState.dirtyFields,
4154
+ isValid: form.formState.isValid,
4155
+ errors: form.formState.errors,
4156
+ touchedFields: form.formState.touchedFields,
4157
+ isSubmitting: form.formState.isSubmitting,
4158
+ submitCount: form.formState.submitCount,
4159
+ defaultValues: mergedDefaultValues,
4160
+ form: form
4161
+ };
4162
+ await onSubmit(data, context);
4163
+ });
4164
+ const handleReset = useCallback(() => {
4165
+ form.reset(mergedDefaultValues);
4166
+ }, [form, mergedDefaultValues]);
4167
+ useImperativeHandle(ref, () => ({
4168
+ setValues: values => {
4169
+ Object.entries(values).forEach(([key, value]) => {
4170
+ form.setValue(key, value, {
4171
+ shouldValidate: true,
4172
+ shouldDirty: true
4173
+ });
4174
+ });
4175
+ },
4176
+ getValues: () => form.getValues(),
4177
+ reset: values_0 => {
4178
+ if (values_0) {
4179
+ form.reset(deepMerge(mergedDefaultValues, values_0));
4180
+ } else {
4181
+ form.reset(mergedDefaultValues);
4182
+ }
4183
+ },
4184
+ submit: async () => {
4185
+ await handleSubmit();
4186
+ },
4187
+ clearErrors: () => form.clearErrors(),
4188
+ setError: (name, error) => form.setError(name, error),
4189
+ isValid: () => form.formState.isValid,
4190
+ isDirty: () => form.formState.isDirty,
4191
+ form: form
4192
+ }), [form, handleSubmit, mergedDefaultValues]);
4193
+ const SubmitButton = getFormComponent('SubmitButton');
4194
+ const FieldWrapper = getFormComponent('FieldWrapper');
4195
+ const FieldsWrapper = getFormComponent('FieldsWrapper');
4196
+ const {
4197
+ regularFields,
4198
+ arrayFields
4199
+ } = useMemo(() => {
4200
+ const regular = [];
4201
+ const arrays = [];
4202
+ fieldsWithRequirements.forEach(field => {
4203
+ if (isArrayField(field)) {
4204
+ arrays.push(field);
4205
+ } else {
4206
+ regular.push(field);
4207
+ }
4208
+ });
4209
+ return {
4210
+ regularFields: regular,
4211
+ arrayFields: arrays
4212
+ };
4213
+ }, [fieldsWithRequirements]);
4214
+ const fieldEntries = useMemo(() => {
4215
+ const entries = new Map();
4216
+ regularFields.forEach((field_0, index) => {
4217
+ if (!field_0.hidden) {
4218
+ const element = jsx(FieldWrapper, {
4219
+ name: field_0.name,
4220
+ type: field_0.type,
4221
+ className: field_0.className,
4222
+ children: jsx(FieldRenderer, {
4223
+ field: field_0
4224
+ })
4225
+ }, field_0.name || `field-${index}`);
4226
+ entries.set(field_0.name, {
4227
+ field: field_0,
4228
+ element,
4229
+ accessed: false
4230
+ });
4231
+ }
4232
+ });
4233
+ return entries;
4234
+ }, [regularFields, FieldWrapper]);
4235
+ const templateFields = useMemo(() => createTemplateFields(fieldEntries), [fieldEntries]);
4236
+ const buttons = useMemo(() => {
4237
+ const result = {
4238
+ submit: jsx(SubmitButton, {
4239
+ disabled: disabled || form.formState.isSubmitting,
4240
+ isSubmitting: form.formState.isSubmitting,
4241
+ children: submitText
4242
+ }, "submit")
4243
+ };
4244
+ if (showReset) {
4245
+ result.reset = jsx("button", {
4246
+ type: "button",
4247
+ onClick: handleReset,
4248
+ disabled: disabled,
4249
+ children: resetText
4250
+ }, "reset");
4251
+ }
4252
+ return result;
4253
+ }, [SubmitButton, disabled, form.formState.isSubmitting, submitText, showReset, resetText, handleReset]);
4254
+ const renderField = useCallback((field_1, options_0) => {
4255
+ return jsx(FieldRenderer, {
4256
+ field: field_1,
4257
+ namePrefix: options_0 === null || options_0 === void 0 ? void 0 : options_0.namePrefix
4258
+ });
4259
+ }, []);
4260
+ if (!children) {
4261
+ return jsx(FormProvider, {
4262
+ ...form,
4263
+ children: jsx(FieldsProvider, {
4264
+ fields: fieldsWithRequirements,
4265
+ children: jsxs("form", {
4266
+ ref: formRef,
4267
+ onSubmit: handleSubmit,
4268
+ className: className,
4269
+ children: [jsxs(FieldsWrapper, {
4270
+ children: [regularFields.map((field_2, index_0) => jsx(FieldWrapper, {
4271
+ name: field_2.name,
4272
+ type: field_2.type,
4273
+ className: field_2.className,
4274
+ children: jsx(FieldRenderer, {
4275
+ field: field_2
4276
+ })
4277
+ }, field_2.name || `field-${index_0}`)), arrayFields.map(arrayField => jsx(FieldWrapper, {
4278
+ name: arrayField.name,
4279
+ type: "array",
4280
+ className: arrayField.className,
4281
+ children: jsx(ArrayFieldRenderer, {
4282
+ field: arrayField
4283
+ })
4284
+ }, arrayField.name))]
4285
+ }), jsx(SubmitButton, {
4286
+ disabled: disabled || form.formState.isSubmitting,
4287
+ isSubmitting: form.formState.isSubmitting,
4288
+ children: submitText
4289
+ })]
4290
+ })
4291
+ })
4292
+ });
4293
+ }
4294
+ const renderProps = {
4295
+ fields: templateFields,
4296
+ arrays: Object.fromEntries(arrayFields.map(arrayField_0 => [arrayField_0.name, {
4297
+ field: arrayField_0
4298
+ }])),
4299
+ buttons,
4300
+ title,
4301
+ description,
4302
+ form: form,
4303
+ isSubmitting: form.formState.isSubmitting,
4304
+ isValid: form.formState.isValid,
4305
+ isDirty: form.formState.isDirty,
4306
+ renderField,
4307
+ FieldWrapper,
4308
+ FieldsWrapper
4309
+ };
4310
+ const renderFn = children;
4311
+ return jsx(FormProvider, {
4312
+ ...form,
4313
+ children: jsx(FieldsProvider, {
4314
+ fields: fieldsWithRequirements,
4315
+ children: jsx("form", {
4316
+ ref: formRef,
4317
+ onSubmit: handleSubmit,
4318
+ className: className,
4319
+ children: renderFn(renderProps)
4320
+ })
4321
+ })
4322
+ });
4323
+ }
4324
+ function createFieldFactory(_schema) {
4325
+ return field => field;
4326
+ }
4327
+
4328
+ export { ArrayFieldRenderer, Controller, FieldRenderer, FieldsProvider, FormGenerator, FormProvider, StrictFormGenerator, analyzeSchema, clearAllRegistries, clearFieldRegistry, clearFormComponentRegistry, createArrayField, createField, createFieldFactory, getDateConstraints, getFieldComponent, getFormComponent, getFormComponents, getNumberConstraints, getRegisteredFieldTypes, getSchemaRequirements, getSchemaTypeName, getStringConstraints, hasFieldType, hasFormComponent, isArrayField, isSchemaRequired, mergeSchemaConstraints, mergeSchemaRequirements, registerField, registerFields, registerFormComponent, registerFormComponents, resetFormComponentRegistry, strictFields, typedField, typedFields, unregisterField, unwrapSchema, useArrayField, useFieldArray, useFieldProps, useFieldsContext, useForm, useFormContext, useWatch, validateFieldType, validateFieldTypes };
4329
+ //# sourceMappingURL=index.mjs.map