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