@connect-soft/form-generator 1.0.0-alpha

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