react-hook-form 7.43.6 → 7.43.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/__tests__/controller.server.test.d.ts +1 -1
  2. package/dist/__tests__/controller.test.d.ts +1 -1
  3. package/dist/__tests__/logic/validateField.test.d.ts +1 -1
  4. package/dist/__tests__/type.test.d.ts +1 -1
  5. package/dist/__tests__/useController.test.d.ts +1 -1
  6. package/dist/__tests__/useFieldArray/append.test.d.ts +1 -1
  7. package/dist/__tests__/useFieldArray/focus.test.d.ts +1 -1
  8. package/dist/__tests__/useFieldArray/insert.test.d.ts +1 -1
  9. package/dist/__tests__/useFieldArray/move.test.d.ts +1 -1
  10. package/dist/__tests__/useFieldArray/prepend.test.d.ts +1 -1
  11. package/dist/__tests__/useFieldArray/remove.test.d.ts +1 -1
  12. package/dist/__tests__/useFieldArray/replace.test.d.ts +1 -1
  13. package/dist/__tests__/useFieldArray/swap.test.d.ts +1 -1
  14. package/dist/__tests__/useFieldArray/update.test.d.ts +1 -1
  15. package/dist/__tests__/useFieldArray.test.d.ts +1 -1
  16. package/dist/__tests__/useForm/clearErrors.test.d.ts +1 -1
  17. package/dist/__tests__/useForm/formState.test.d.ts +1 -1
  18. package/dist/__tests__/useForm/getFieldState.test.d.ts +1 -1
  19. package/dist/__tests__/useForm/getValues.test.d.ts +1 -1
  20. package/dist/__tests__/useForm/handleSubmit.test.d.ts +1 -1
  21. package/dist/__tests__/useForm/register.test.d.ts +1 -1
  22. package/dist/__tests__/useForm/reset.test.d.ts +1 -1
  23. package/dist/__tests__/useForm/resetField.test.d.ts +1 -1
  24. package/dist/__tests__/useForm/resolver.test.d.ts +1 -1
  25. package/dist/__tests__/useForm/setError.test.d.ts +1 -1
  26. package/dist/__tests__/useForm/setValue.test.d.ts +1 -1
  27. package/dist/__tests__/useForm/trigger.test.d.ts +1 -1
  28. package/dist/__tests__/useForm/unregister.test.d.ts +1 -1
  29. package/dist/__tests__/useForm/watch.test.d.ts +1 -1
  30. package/dist/__tests__/useForm.server.test.d.ts +1 -1
  31. package/dist/__tests__/useForm.test.d.ts +1 -1
  32. package/dist/__tests__/useFormContext.server.test.d.ts +1 -1
  33. package/dist/__tests__/useFormContext.test.d.ts +1 -1
  34. package/dist/__tests__/useFormState.test.d.ts +1 -1
  35. package/dist/__tests__/useWatch.test.d.ts +1 -1
  36. package/dist/__typetest__/__fixtures__/index.d.ts +4 -4
  37. package/dist/__typetest__/__fixtures__/pathString.d.ts +3 -3
  38. package/dist/__typetest__/__fixtures__/traversable.d.ts +13 -13
  39. package/dist/__typetest__/__fixtures__/tuple.d.ts +14 -14
  40. package/dist/__typetest__/__fixtures__/type.d.ts +11 -11
  41. package/dist/__typetest__/errors.test-d.d.ts +1 -1
  42. package/dist/__typetest__/form.test-d.d.ts +1 -1
  43. package/dist/__typetest__/path/common.test-d.d.ts +1 -1
  44. package/dist/__typetest__/path/eager.test-d.d.ts +1 -1
  45. package/dist/__typetest__/util.test-d.d.ts +1 -1
  46. package/dist/constants.d.ts +16 -16
  47. package/dist/controller.d.ts +46 -46
  48. package/dist/controller.d.ts.map +1 -1
  49. package/dist/index.cjs.js +1 -1
  50. package/dist/index.cjs.js.map +1 -1
  51. package/dist/index.d.ts +10 -10
  52. package/dist/index.esm.mjs +2174 -2174
  53. package/dist/index.esm.mjs.map +1 -1
  54. package/dist/index.umd.js +1 -1
  55. package/dist/index.umd.js.map +1 -1
  56. package/dist/logic/appendErrors.d.ts +3 -3
  57. package/dist/logic/createFormControl.d.ts +25 -25
  58. package/dist/logic/focusFieldBy.d.ts +3 -3
  59. package/dist/logic/generateId.d.ts +2 -2
  60. package/dist/logic/generateWatchOutput.d.ts +3 -3
  61. package/dist/logic/getCheckboxValue.d.ts +6 -6
  62. package/dist/logic/getDirtyFields.d.ts +2 -2
  63. package/dist/logic/getEventValue.d.ts +2 -2
  64. package/dist/logic/getFieldValue.d.ts +2 -2
  65. package/dist/logic/getFieldValueAs.d.ts +3 -3
  66. package/dist/logic/getFocusFieldName.d.ts +3 -3
  67. package/dist/logic/getNodeParentName.d.ts +2 -2
  68. package/dist/logic/getProxyFormState.d.ts +3 -3
  69. package/dist/logic/getRadioValue.d.ts +6 -6
  70. package/dist/logic/getResolverOptions.d.ts +13 -13
  71. package/dist/logic/getRuleValue.d.ts +3 -3
  72. package/dist/logic/getValidateError.d.ts +2 -2
  73. package/dist/logic/getValidationModes.d.ts +9 -9
  74. package/dist/logic/getValueAndMessage.d.ts +6 -6
  75. package/dist/logic/hasValidation.d.ts +3 -3
  76. package/dist/logic/index.d.ts +2 -2
  77. package/dist/logic/isNameInFieldArray.d.ts +3 -3
  78. package/dist/logic/isWatched.d.ts +3 -3
  79. package/dist/logic/schemaErrorLookup.d.ts +5 -5
  80. package/dist/logic/shouldRenderFormState.d.ts +5 -5
  81. package/dist/logic/shouldSubscribeByName.d.ts +2 -2
  82. package/dist/logic/skipValidation.d.ts +11 -11
  83. package/dist/logic/unsetEmptyArray.d.ts +2 -2
  84. package/dist/logic/updateFieldArrayRootError.d.ts +3 -3
  85. package/dist/logic/validateField.d.ts +3 -3
  86. package/dist/types/controller.d.ts +56 -56
  87. package/dist/types/errors.d.ts +35 -35
  88. package/dist/types/events.d.ts +1 -1
  89. package/dist/types/fieldArray.d.ts +194 -194
  90. package/dist/types/fields.d.ts +28 -28
  91. package/dist/types/form.d.ts +627 -627
  92. package/dist/types/index.d.ts +10 -10
  93. package/dist/types/path/common.d.ts +315 -315
  94. package/dist/types/path/eager.d.ts +120 -120
  95. package/dist/types/path/index.d.ts +3 -3
  96. package/dist/types/resolvers.d.ts +19 -19
  97. package/dist/types/utils.d.ts +70 -70
  98. package/dist/types/validator.d.ts +38 -38
  99. package/dist/useController.d.ts +26 -26
  100. package/dist/useFieldArray.d.ts +39 -39
  101. package/dist/useForm.d.ts +31 -31
  102. package/dist/useFormContext.d.ts +64 -64
  103. package/dist/useFormContext.d.ts.map +1 -1
  104. package/dist/useFormState.d.ts +33 -33
  105. package/dist/useSubscribe.d.ts +8 -8
  106. package/dist/useWatch.d.ts +99 -99
  107. package/dist/utils/append.d.ts +1 -1
  108. package/dist/utils/cloneObject.d.ts +1 -1
  109. package/dist/utils/compact.d.ts +2 -2
  110. package/dist/utils/convertToArrayPayload.d.ts +2 -2
  111. package/dist/utils/createSubject.d.ts +13 -13
  112. package/dist/utils/deepEqual.d.ts +1 -1
  113. package/dist/utils/deepMerge.d.ts +1 -1
  114. package/dist/utils/fillBooleanArray.d.ts +2 -2
  115. package/dist/utils/fillEmptyArray.d.ts +2 -2
  116. package/dist/utils/get.d.ts +2 -2
  117. package/dist/utils/index.d.ts +3 -3
  118. package/dist/utils/insert.d.ts +2 -2
  119. package/dist/utils/isBoolean.d.ts +2 -2
  120. package/dist/utils/isCheckBoxInput.d.ts +3 -3
  121. package/dist/utils/isDateObject.d.ts +2 -2
  122. package/dist/utils/isEmptyObject.d.ts +3 -3
  123. package/dist/utils/isFileInput.d.ts +3 -3
  124. package/dist/utils/isFunction.d.ts +2 -2
  125. package/dist/utils/isHTMLElement.d.ts +2 -2
  126. package/dist/utils/isKey.d.ts +2 -2
  127. package/dist/utils/isMessage.d.ts +2 -2
  128. package/dist/utils/isMultipleSelect.d.ts +3 -3
  129. package/dist/utils/isNullOrUndefined.d.ts +2 -2
  130. package/dist/utils/isObject.d.ts +3 -3
  131. package/dist/utils/isPlainObject.d.ts +2 -2
  132. package/dist/utils/isPrimitive.d.ts +3 -3
  133. package/dist/utils/isRadioInput.d.ts +3 -3
  134. package/dist/utils/isRadioOrCheckbox.d.ts +3 -3
  135. package/dist/utils/isRegex.d.ts +2 -2
  136. package/dist/utils/isSelectInput.d.ts +3 -3
  137. package/dist/utils/isString.d.ts +2 -2
  138. package/dist/utils/isUndefined.d.ts +2 -2
  139. package/dist/utils/isWeb.d.ts +2 -2
  140. package/dist/utils/live.d.ts +3 -3
  141. package/dist/utils/move.d.ts +2 -2
  142. package/dist/utils/objectHasFunction.d.ts +2 -2
  143. package/dist/utils/omit.d.ts +2 -2
  144. package/dist/utils/prepend.d.ts +1 -1
  145. package/dist/utils/remove.d.ts +2 -2
  146. package/dist/utils/set.d.ts +2 -2
  147. package/dist/utils/sleep.d.ts +1 -1
  148. package/dist/utils/stringToPath.d.ts +2 -2
  149. package/dist/utils/swap.d.ts +2 -2
  150. package/dist/utils/unset.d.ts +1 -1
  151. package/dist/utils/update.d.ts +2 -2
  152. package/package.json +8 -8
@@ -6,594 +6,594 @@ var isDateObject = (value) => value instanceof Date;
6
6
 
7
7
  var isNullOrUndefined = (value) => value == null;
8
8
 
9
- const isObjectType = (value) => typeof value === 'object';
10
- var isObject = (value) => !isNullOrUndefined(value) &&
11
- !Array.isArray(value) &&
12
- isObjectType(value) &&
9
+ const isObjectType = (value) => typeof value === 'object';
10
+ var isObject = (value) => !isNullOrUndefined(value) &&
11
+ !Array.isArray(value) &&
12
+ isObjectType(value) &&
13
13
  !isDateObject(value);
14
14
 
15
- var getEventValue = (event) => isObject(event) && event.target
16
- ? isCheckBoxInput(event.target)
17
- ? event.target.checked
18
- : event.target.value
15
+ var getEventValue = (event) => isObject(event) && event.target
16
+ ? isCheckBoxInput(event.target)
17
+ ? event.target.checked
18
+ : event.target.value
19
19
  : event;
20
20
 
21
21
  var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
22
22
 
23
23
  var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
24
24
 
25
- var isPlainObject = (tempObject) => {
26
- const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
27
- return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
25
+ var isPlainObject = (tempObject) => {
26
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
27
+ return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
28
28
  };
29
29
 
30
- var isWeb = typeof window !== 'undefined' &&
31
- typeof window.HTMLElement !== 'undefined' &&
30
+ var isWeb = typeof window !== 'undefined' &&
31
+ typeof window.HTMLElement !== 'undefined' &&
32
32
  typeof document !== 'undefined';
33
33
 
34
- function cloneObject(data) {
35
- let copy;
36
- const isArray = Array.isArray(data);
37
- if (data instanceof Date) {
38
- copy = new Date(data);
39
- }
40
- else if (data instanceof Set) {
41
- copy = new Set(data);
42
- }
43
- else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) &&
44
- (isArray || isObject(data))) {
45
- copy = isArray ? [] : {};
46
- if (!Array.isArray(data) && !isPlainObject(data)) {
47
- copy = data;
48
- }
49
- else {
50
- for (const key in data) {
51
- copy[key] = cloneObject(data[key]);
52
- }
53
- }
54
- }
55
- else {
56
- return data;
57
- }
58
- return copy;
34
+ function cloneObject(data) {
35
+ let copy;
36
+ const isArray = Array.isArray(data);
37
+ if (data instanceof Date) {
38
+ copy = new Date(data);
39
+ }
40
+ else if (data instanceof Set) {
41
+ copy = new Set(data);
42
+ }
43
+ else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) &&
44
+ (isArray || isObject(data))) {
45
+ copy = isArray ? [] : {};
46
+ if (!Array.isArray(data) && !isPlainObject(data)) {
47
+ copy = data;
48
+ }
49
+ else {
50
+ for (const key in data) {
51
+ copy[key] = cloneObject(data[key]);
52
+ }
53
+ }
54
+ }
55
+ else {
56
+ return data;
57
+ }
58
+ return copy;
59
59
  }
60
60
 
61
61
  var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
62
62
 
63
63
  var isUndefined = (val) => val === undefined;
64
64
 
65
- var get = (obj, path, defaultValue) => {
66
- if (!path || !isObject(obj)) {
67
- return defaultValue;
68
- }
69
- const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], obj);
70
- return isUndefined(result) || result === obj
71
- ? isUndefined(obj[path])
72
- ? defaultValue
73
- : obj[path]
74
- : result;
65
+ var get = (obj, path, defaultValue) => {
66
+ if (!path || !isObject(obj)) {
67
+ return defaultValue;
68
+ }
69
+ const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], obj);
70
+ return isUndefined(result) || result === obj
71
+ ? isUndefined(obj[path])
72
+ ? defaultValue
73
+ : obj[path]
74
+ : result;
75
75
  };
76
76
 
77
- const EVENTS = {
78
- BLUR: 'blur',
79
- FOCUS_OUT: 'focusout',
80
- CHANGE: 'change',
81
- };
82
- const VALIDATION_MODE = {
83
- onBlur: 'onBlur',
84
- onChange: 'onChange',
85
- onSubmit: 'onSubmit',
86
- onTouched: 'onTouched',
87
- all: 'all',
88
- };
89
- const INPUT_VALIDATION_RULES = {
90
- max: 'max',
91
- min: 'min',
92
- maxLength: 'maxLength',
93
- minLength: 'minLength',
94
- pattern: 'pattern',
95
- required: 'required',
96
- validate: 'validate',
77
+ const EVENTS = {
78
+ BLUR: 'blur',
79
+ FOCUS_OUT: 'focusout',
80
+ CHANGE: 'change',
81
+ };
82
+ const VALIDATION_MODE = {
83
+ onBlur: 'onBlur',
84
+ onChange: 'onChange',
85
+ onSubmit: 'onSubmit',
86
+ onTouched: 'onTouched',
87
+ all: 'all',
88
+ };
89
+ const INPUT_VALIDATION_RULES = {
90
+ max: 'max',
91
+ min: 'min',
92
+ maxLength: 'maxLength',
93
+ minLength: 'minLength',
94
+ pattern: 'pattern',
95
+ required: 'required',
96
+ validate: 'validate',
97
97
  };
98
98
 
99
- const HookFormContext = React.createContext(null);
100
- /**
101
- * 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}.
102
- *
103
- * @remarks
104
- * [API](https://react-hook-form.com/api/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
105
- *
106
- * @returns return all useForm methods
107
- *
108
- * @example
109
- * ```tsx
110
- * function App() {
111
- * const methods = useForm();
112
- * const onSubmit = data => console.log(data);
113
- *
114
- * return (
115
- * <FormProvider {...methods} >
116
- * <form onSubmit={methods.handleSubmit(onSubmit)}>
117
- * <NestedInput />
118
- * <input type="submit" />
119
- * </form>
120
- * </FormProvider>
121
- * );
122
- * }
123
- *
124
- * function NestedInput() {
125
- * const { register } = useFormContext(); // retrieve all hook methods
126
- * return <input {...register("test")} />;
127
- * }
128
- * ```
129
- */
130
- const useFormContext = () => React.useContext(HookFormContext);
131
- /**
132
- * A provider component that propagates the `useForm` methods to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useFormContext}.
133
- *
134
- * @remarks
135
- * [API](https://react-hook-form.com/api/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
136
- *
137
- * @param props - all useFrom methods
138
- *
139
- * @example
140
- * ```tsx
141
- * function App() {
142
- * const methods = useForm();
143
- * const onSubmit = data => console.log(data);
144
- *
145
- * return (
146
- * <FormProvider {...methods} >
147
- * <form onSubmit={methods.handleSubmit(onSubmit)}>
148
- * <NestedInput />
149
- * <input type="submit" />
150
- * </form>
151
- * </FormProvider>
152
- * );
153
- * }
154
- *
155
- * function NestedInput() {
156
- * const { register } = useFormContext(); // retrieve all hook methods
157
- * return <input {...register("test")} />;
158
- * }
159
- * ```
160
- */
161
- const FormProvider = (props) => {
162
- const { children, ...data } = props;
163
- return (React.createElement(HookFormContext.Provider, { value: data }, children));
99
+ const HookFormContext = React.createContext(null);
100
+ /**
101
+ * 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}.
102
+ *
103
+ * @remarks
104
+ * [API](https://react-hook-form.com/api/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
105
+ *
106
+ * @returns return all useForm methods
107
+ *
108
+ * @example
109
+ * ```tsx
110
+ * function App() {
111
+ * const methods = useForm();
112
+ * const onSubmit = data => console.log(data);
113
+ *
114
+ * return (
115
+ * <FormProvider {...methods} >
116
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
117
+ * <NestedInput />
118
+ * <input type="submit" />
119
+ * </form>
120
+ * </FormProvider>
121
+ * );
122
+ * }
123
+ *
124
+ * function NestedInput() {
125
+ * const { register } = useFormContext(); // retrieve all hook methods
126
+ * return <input {...register("test")} />;
127
+ * }
128
+ * ```
129
+ */
130
+ const useFormContext = () => React.useContext(HookFormContext);
131
+ /**
132
+ * A provider component that propagates the `useForm` methods to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useFormContext}.
133
+ *
134
+ * @remarks
135
+ * [API](https://react-hook-form.com/api/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
136
+ *
137
+ * @param props - all useFrom methods
138
+ *
139
+ * @example
140
+ * ```tsx
141
+ * function App() {
142
+ * const methods = useForm();
143
+ * const onSubmit = data => console.log(data);
144
+ *
145
+ * return (
146
+ * <FormProvider {...methods} >
147
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
148
+ * <NestedInput />
149
+ * <input type="submit" />
150
+ * </form>
151
+ * </FormProvider>
152
+ * );
153
+ * }
154
+ *
155
+ * function NestedInput() {
156
+ * const { register } = useFormContext(); // retrieve all hook methods
157
+ * return <input {...register("test")} />;
158
+ * }
159
+ * ```
160
+ */
161
+ const FormProvider = (props) => {
162
+ const { children, ...data } = props;
163
+ return (React.createElement(HookFormContext.Provider, { value: data }, children));
164
164
  };
165
165
 
166
- var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
167
- const result = {
168
- defaultValues: control._defaultValues,
169
- };
170
- for (const key in formState) {
171
- Object.defineProperty(result, key, {
172
- get: () => {
173
- const _key = key;
174
- if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
175
- control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
176
- }
177
- localProxyFormState && (localProxyFormState[_key] = true);
178
- return formState[_key];
179
- },
180
- });
181
- }
182
- return result;
166
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
167
+ const result = {
168
+ defaultValues: control._defaultValues,
169
+ };
170
+ for (const key in formState) {
171
+ Object.defineProperty(result, key, {
172
+ get: () => {
173
+ const _key = key;
174
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
175
+ control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
176
+ }
177
+ localProxyFormState && (localProxyFormState[_key] = true);
178
+ return formState[_key];
179
+ },
180
+ });
181
+ }
182
+ return result;
183
183
  };
184
184
 
185
185
  var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
186
186
 
187
- var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
188
- updateFormState(formStateData);
189
- const { name, ...formState } = formStateData;
190
- return (isEmptyObject(formState) ||
191
- Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
192
- Object.keys(formState).find((key) => _proxyFormState[key] ===
193
- (!isRoot || VALIDATION_MODE.all)));
187
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
188
+ updateFormState(formStateData);
189
+ const { name, ...formState } = formStateData;
190
+ return (isEmptyObject(formState) ||
191
+ Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
192
+ Object.keys(formState).find((key) => _proxyFormState[key] ===
193
+ (!isRoot || VALIDATION_MODE.all)));
194
194
  };
195
195
 
196
196
  var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
197
197
 
198
- var shouldSubscribeByName = (name, signalName, exact) => exact && signalName
199
- ? name === signalName
200
- : !name ||
201
- !signalName ||
202
- name === signalName ||
203
- convertToArrayPayload(name).some((currentName) => currentName &&
204
- (currentName.startsWith(signalName) ||
198
+ var shouldSubscribeByName = (name, signalName, exact) => exact && signalName
199
+ ? name === signalName
200
+ : !name ||
201
+ !signalName ||
202
+ name === signalName ||
203
+ convertToArrayPayload(name).some((currentName) => currentName &&
204
+ (currentName.startsWith(signalName) ||
205
205
  signalName.startsWith(currentName)));
206
206
 
207
- function useSubscribe(props) {
208
- const _props = React.useRef(props);
209
- _props.current = props;
210
- React.useEffect(() => {
211
- const subscription = !props.disabled &&
212
- _props.current.subject &&
213
- _props.current.subject.subscribe({
214
- next: _props.current.next,
215
- });
216
- return () => {
217
- subscription && subscription.unsubscribe();
218
- };
219
- }, [props.disabled]);
207
+ function useSubscribe(props) {
208
+ const _props = React.useRef(props);
209
+ _props.current = props;
210
+ React.useEffect(() => {
211
+ const subscription = !props.disabled &&
212
+ _props.current.subject &&
213
+ _props.current.subject.subscribe({
214
+ next: _props.current.next,
215
+ });
216
+ return () => {
217
+ subscription && subscription.unsubscribe();
218
+ };
219
+ }, [props.disabled]);
220
220
  }
221
221
 
222
- /**
223
- * 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.
224
- *
225
- * @remarks
226
- * [API](https://react-hook-form.com/api/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
227
- *
228
- * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
229
- *
230
- * @example
231
- * ```tsx
232
- * function App() {
233
- * const { register, handleSubmit, control } = useForm({
234
- * defaultValues: {
235
- * firstName: "firstName"
236
- * }});
237
- * const { dirtyFields } = useFormState({
238
- * control
239
- * });
240
- * const onSubmit = (data) => console.log(data);
241
- *
242
- * return (
243
- * <form onSubmit={handleSubmit(onSubmit)}>
244
- * <input {...register("firstName")} placeholder="First Name" />
245
- * {dirtyFields.firstName && <p>Field is dirty.</p>}
246
- * <input type="submit" />
247
- * </form>
248
- * );
249
- * }
250
- * ```
251
- */
252
- function useFormState(props) {
253
- const methods = useFormContext();
254
- const { control = methods.control, disabled, name, exact } = props || {};
255
- const [formState, updateFormState] = React.useState(control._formState);
256
- const _mounted = React.useRef(true);
257
- const _localProxyFormState = React.useRef({
258
- isDirty: false,
259
- isLoading: false,
260
- dirtyFields: false,
261
- touchedFields: false,
262
- isValidating: false,
263
- isValid: false,
264
- errors: false,
265
- });
266
- const _name = React.useRef(name);
267
- _name.current = name;
268
- useSubscribe({
269
- disabled,
270
- next: (value) => _mounted.current &&
271
- shouldSubscribeByName(_name.current, value.name, exact) &&
272
- shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
273
- updateFormState({
274
- ...control._formState,
275
- ...value,
276
- }),
277
- subject: control._subjects.state,
278
- });
279
- React.useEffect(() => {
280
- _mounted.current = true;
281
- const isDirty = control._proxyFormState.isDirty && control._getDirty();
282
- if (isDirty !== control._formState.isDirty) {
283
- control._subjects.state.next({
284
- isDirty,
285
- });
286
- }
287
- _localProxyFormState.current.isValid && control._updateValid(true);
288
- return () => {
289
- _mounted.current = false;
290
- };
291
- }, [control]);
292
- return getProxyFormState(formState, control, _localProxyFormState.current, false);
222
+ /**
223
+ * 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.
224
+ *
225
+ * @remarks
226
+ * [API](https://react-hook-form.com/api/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
227
+ *
228
+ * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
229
+ *
230
+ * @example
231
+ * ```tsx
232
+ * function App() {
233
+ * const { register, handleSubmit, control } = useForm({
234
+ * defaultValues: {
235
+ * firstName: "firstName"
236
+ * }});
237
+ * const { dirtyFields } = useFormState({
238
+ * control
239
+ * });
240
+ * const onSubmit = (data) => console.log(data);
241
+ *
242
+ * return (
243
+ * <form onSubmit={handleSubmit(onSubmit)}>
244
+ * <input {...register("firstName")} placeholder="First Name" />
245
+ * {dirtyFields.firstName && <p>Field is dirty.</p>}
246
+ * <input type="submit" />
247
+ * </form>
248
+ * );
249
+ * }
250
+ * ```
251
+ */
252
+ function useFormState(props) {
253
+ const methods = useFormContext();
254
+ const { control = methods.control, disabled, name, exact } = props || {};
255
+ const [formState, updateFormState] = React.useState(control._formState);
256
+ const _mounted = React.useRef(true);
257
+ const _localProxyFormState = React.useRef({
258
+ isDirty: false,
259
+ isLoading: false,
260
+ dirtyFields: false,
261
+ touchedFields: false,
262
+ isValidating: false,
263
+ isValid: false,
264
+ errors: false,
265
+ });
266
+ const _name = React.useRef(name);
267
+ _name.current = name;
268
+ useSubscribe({
269
+ disabled,
270
+ next: (value) => _mounted.current &&
271
+ shouldSubscribeByName(_name.current, value.name, exact) &&
272
+ shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
273
+ updateFormState({
274
+ ...control._formState,
275
+ ...value,
276
+ }),
277
+ subject: control._subjects.state,
278
+ });
279
+ React.useEffect(() => {
280
+ _mounted.current = true;
281
+ const isDirty = control._proxyFormState.isDirty && control._getDirty();
282
+ if (isDirty !== control._formState.isDirty) {
283
+ control._subjects.state.next({
284
+ isDirty,
285
+ });
286
+ }
287
+ _localProxyFormState.current.isValid && control._updateValid(true);
288
+ return () => {
289
+ _mounted.current = false;
290
+ };
291
+ }, [control]);
292
+ return getProxyFormState(formState, control, _localProxyFormState.current, false);
293
293
  }
294
294
 
295
295
  var isString = (value) => typeof value === 'string';
296
296
 
297
- var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
298
- if (isString(names)) {
299
- isGlobal && _names.watch.add(names);
300
- return get(formValues, names, defaultValue);
301
- }
302
- if (Array.isArray(names)) {
303
- return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
304
- }
305
- isGlobal && (_names.watchAll = true);
306
- return formValues;
297
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
298
+ if (isString(names)) {
299
+ isGlobal && _names.watch.add(names);
300
+ return get(formValues, names, defaultValue);
301
+ }
302
+ if (Array.isArray(names)) {
303
+ return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
304
+ }
305
+ isGlobal && (_names.watchAll = true);
306
+ return formValues;
307
307
  };
308
308
 
309
- /**
310
- * Custom hook to subscribe to field change and isolate re-rendering at the component level.
311
- *
312
- * @remarks
313
- *
314
- * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
315
- *
316
- * @example
317
- * ```tsx
318
- * const { watch } = useForm();
319
- * const values = useWatch({
320
- * name: "fieldName"
321
- * control,
322
- * })
323
- * ```
324
- */
325
- function useWatch(props) {
326
- const methods = useFormContext();
327
- const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};
328
- const _name = React.useRef(name);
329
- _name.current = name;
330
- useSubscribe({
331
- disabled,
332
- subject: control._subjects.values,
333
- next: (formState) => {
334
- if (shouldSubscribeByName(_name.current, formState.name, exact)) {
335
- updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
336
- }
337
- },
338
- });
339
- const [value, updateValue] = React.useState(control._getWatch(name, defaultValue));
340
- React.useEffect(() => control._removeUnmounted());
341
- return value;
309
+ /**
310
+ * Custom hook to subscribe to field change and isolate re-rendering at the component level.
311
+ *
312
+ * @remarks
313
+ *
314
+ * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
315
+ *
316
+ * @example
317
+ * ```tsx
318
+ * const { watch } = useForm();
319
+ * const values = useWatch({
320
+ * name: "fieldName"
321
+ * control,
322
+ * })
323
+ * ```
324
+ */
325
+ function useWatch(props) {
326
+ const methods = useFormContext();
327
+ const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};
328
+ const _name = React.useRef(name);
329
+ _name.current = name;
330
+ useSubscribe({
331
+ disabled,
332
+ subject: control._subjects.values,
333
+ next: (formState) => {
334
+ if (shouldSubscribeByName(_name.current, formState.name, exact)) {
335
+ updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
336
+ }
337
+ },
338
+ });
339
+ const [value, updateValue] = React.useState(control._getWatch(name, defaultValue));
340
+ React.useEffect(() => control._removeUnmounted());
341
+ return value;
342
342
  }
343
343
 
344
344
  var isKey = (value) => /^\w*$/.test(value);
345
345
 
346
346
  var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
347
347
 
348
- function set(object, path, value) {
349
- let index = -1;
350
- const tempPath = isKey(path) ? [path] : stringToPath(path);
351
- const length = tempPath.length;
352
- const lastIndex = length - 1;
353
- while (++index < length) {
354
- const key = tempPath[index];
355
- let newValue = value;
356
- if (index !== lastIndex) {
357
- const objValue = object[key];
358
- newValue =
359
- isObject(objValue) || Array.isArray(objValue)
360
- ? objValue
361
- : !isNaN(+tempPath[index + 1])
362
- ? []
363
- : {};
364
- }
365
- object[key] = newValue;
366
- object = object[key];
367
- }
368
- return object;
348
+ function set(object, path, value) {
349
+ let index = -1;
350
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
351
+ const length = tempPath.length;
352
+ const lastIndex = length - 1;
353
+ while (++index < length) {
354
+ const key = tempPath[index];
355
+ let newValue = value;
356
+ if (index !== lastIndex) {
357
+ const objValue = object[key];
358
+ newValue =
359
+ isObject(objValue) || Array.isArray(objValue)
360
+ ? objValue
361
+ : !isNaN(+tempPath[index + 1])
362
+ ? []
363
+ : {};
364
+ }
365
+ object[key] = newValue;
366
+ object = object[key];
367
+ }
368
+ return object;
369
369
  }
370
370
 
371
- /**
372
- * 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.
373
- *
374
- * @remarks
375
- * [API](https://react-hook-form.com/api/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
376
- *
377
- * @param props - the path name to the form field value, and validation rules.
378
- *
379
- * @returns field properties, field and form state. {@link UseControllerReturn}
380
- *
381
- * @example
382
- * ```tsx
383
- * function Input(props) {
384
- * const { field, fieldState, formState } = useController(props);
385
- * return (
386
- * <div>
387
- * <input {...field} placeholder={props.name} />
388
- * <p>{fieldState.isTouched && "Touched"}</p>
389
- * <p>{formState.isSubmitted ? "submitted" : ""}</p>
390
- * </div>
391
- * );
392
- * }
393
- * ```
394
- */
395
- function useController(props) {
396
- const methods = useFormContext();
397
- const { name, control = methods.control, shouldUnregister } = props;
398
- const isArrayField = isNameInFieldArray(control._names.array, name);
399
- const value = useWatch({
400
- control,
401
- name,
402
- defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
403
- exact: true,
404
- });
405
- const formState = useFormState({
406
- control,
407
- name,
408
- });
409
- const _registerProps = React.useRef(control.register(name, {
410
- ...props.rules,
411
- value,
412
- }));
413
- React.useEffect(() => {
414
- const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
415
- const updateMounted = (name, value) => {
416
- const field = get(control._fields, name);
417
- if (field) {
418
- field._f.mount = value;
419
- }
420
- };
421
- updateMounted(name, true);
422
- if (_shouldUnregisterField) {
423
- const value = cloneObject(get(control._options.defaultValues, name));
424
- set(control._defaultValues, name, value);
425
- if (isUndefined(get(control._formValues, name))) {
426
- set(control._formValues, name, value);
427
- }
428
- }
429
- return () => {
430
- (isArrayField
431
- ? _shouldUnregisterField && !control._state.action
432
- : _shouldUnregisterField)
433
- ? control.unregister(name)
434
- : updateMounted(name, false);
435
- };
436
- }, [name, control, isArrayField, shouldUnregister]);
437
- return {
438
- field: {
439
- name,
440
- value,
441
- onChange: React.useCallback((event) => _registerProps.current.onChange({
442
- target: {
443
- value: getEventValue(event),
444
- name: name,
445
- },
446
- type: EVENTS.CHANGE,
447
- }), [name]),
448
- onBlur: React.useCallback(() => _registerProps.current.onBlur({
449
- target: {
450
- value: get(control._formValues, name),
451
- name: name,
452
- },
453
- type: EVENTS.BLUR,
454
- }), [name, control]),
455
- ref: (elm) => {
456
- const field = get(control._fields, name);
457
- if (field && elm) {
458
- field._f.ref = {
459
- focus: () => elm.focus(),
460
- select: () => elm.select(),
461
- setCustomValidity: (message) => elm.setCustomValidity(message),
462
- reportValidity: () => elm.reportValidity(),
463
- };
464
- }
465
- },
466
- },
467
- formState,
468
- fieldState: Object.defineProperties({}, {
469
- invalid: {
470
- enumerable: true,
471
- get: () => !!get(formState.errors, name),
472
- },
473
- isDirty: {
474
- enumerable: true,
475
- get: () => !!get(formState.dirtyFields, name),
476
- },
477
- isTouched: {
478
- enumerable: true,
479
- get: () => !!get(formState.touchedFields, name),
480
- },
481
- error: {
482
- enumerable: true,
483
- get: () => get(formState.errors, name),
484
- },
485
- }),
486
- };
371
+ /**
372
+ * 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.
373
+ *
374
+ * @remarks
375
+ * [API](https://react-hook-form.com/api/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
376
+ *
377
+ * @param props - the path name to the form field value, and validation rules.
378
+ *
379
+ * @returns field properties, field and form state. {@link UseControllerReturn}
380
+ *
381
+ * @example
382
+ * ```tsx
383
+ * function Input(props) {
384
+ * const { field, fieldState, formState } = useController(props);
385
+ * return (
386
+ * <div>
387
+ * <input {...field} placeholder={props.name} />
388
+ * <p>{fieldState.isTouched && "Touched"}</p>
389
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
390
+ * </div>
391
+ * );
392
+ * }
393
+ * ```
394
+ */
395
+ function useController(props) {
396
+ const methods = useFormContext();
397
+ const { name, control = methods.control, shouldUnregister } = props;
398
+ const isArrayField = isNameInFieldArray(control._names.array, name);
399
+ const value = useWatch({
400
+ control,
401
+ name,
402
+ defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
403
+ exact: true,
404
+ });
405
+ const formState = useFormState({
406
+ control,
407
+ name,
408
+ });
409
+ const _registerProps = React.useRef(control.register(name, {
410
+ ...props.rules,
411
+ value,
412
+ }));
413
+ React.useEffect(() => {
414
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
415
+ const updateMounted = (name, value) => {
416
+ const field = get(control._fields, name);
417
+ if (field) {
418
+ field._f.mount = value;
419
+ }
420
+ };
421
+ updateMounted(name, true);
422
+ if (_shouldUnregisterField) {
423
+ const value = cloneObject(get(control._options.defaultValues, name));
424
+ set(control._defaultValues, name, value);
425
+ if (isUndefined(get(control._formValues, name))) {
426
+ set(control._formValues, name, value);
427
+ }
428
+ }
429
+ return () => {
430
+ (isArrayField
431
+ ? _shouldUnregisterField && !control._state.action
432
+ : _shouldUnregisterField)
433
+ ? control.unregister(name)
434
+ : updateMounted(name, false);
435
+ };
436
+ }, [name, control, isArrayField, shouldUnregister]);
437
+ return {
438
+ field: {
439
+ name,
440
+ value,
441
+ onChange: React.useCallback((event) => _registerProps.current.onChange({
442
+ target: {
443
+ value: getEventValue(event),
444
+ name: name,
445
+ },
446
+ type: EVENTS.CHANGE,
447
+ }), [name]),
448
+ onBlur: React.useCallback(() => _registerProps.current.onBlur({
449
+ target: {
450
+ value: get(control._formValues, name),
451
+ name: name,
452
+ },
453
+ type: EVENTS.BLUR,
454
+ }), [name, control]),
455
+ ref: (elm) => {
456
+ const field = get(control._fields, name);
457
+ if (field && elm) {
458
+ field._f.ref = {
459
+ focus: () => elm.focus(),
460
+ select: () => elm.select(),
461
+ setCustomValidity: (message) => elm.setCustomValidity(message),
462
+ reportValidity: () => elm.reportValidity(),
463
+ };
464
+ }
465
+ },
466
+ },
467
+ formState,
468
+ fieldState: Object.defineProperties({}, {
469
+ invalid: {
470
+ enumerable: true,
471
+ get: () => !!get(formState.errors, name),
472
+ },
473
+ isDirty: {
474
+ enumerable: true,
475
+ get: () => !!get(formState.dirtyFields, name),
476
+ },
477
+ isTouched: {
478
+ enumerable: true,
479
+ get: () => !!get(formState.touchedFields, name),
480
+ },
481
+ error: {
482
+ enumerable: true,
483
+ get: () => get(formState.errors, name),
484
+ },
485
+ }),
486
+ };
487
487
  }
488
488
 
489
- /**
490
- * Component based on `useController` hook to work with controlled component.
491
- *
492
- * @remarks
493
- * [API](https://react-hook-form.com/api/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
494
- *
495
- * @param props - the path name to the form field value, and validation rules.
496
- *
497
- * @returns provide field handler functions, field and form state.
498
- *
499
- * @example
500
- * ```tsx
501
- * function App() {
502
- * const { control } = useForm<FormValues>({
503
- * defaultValues: {
504
- * test: ""
505
- * }
506
- * });
507
- *
508
- * return (
509
- * <form>
510
- * <Controller
511
- * control={control}
512
- * name="test"
513
- * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
514
- * <>
515
- * <input
516
- * onChange={onChange} // send value to hook form
517
- * onBlur={onBlur} // notify when input is touched
518
- * value={value} // return updated value
519
- * ref={ref} // set ref for focus management
520
- * />
521
- * <p>{formState.isSubmitted ? "submitted" : ""}</p>
522
- * <p>{fieldState.isTouched ? "touched" : ""}</p>
523
- * </>
524
- * )}
525
- * />
526
- * </form>
527
- * );
528
- * }
529
- * ```
530
- */
489
+ /**
490
+ * Component based on `useController` hook to work with controlled component.
491
+ *
492
+ * @remarks
493
+ * [API](https://react-hook-form.com/api/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
494
+ *
495
+ * @param props - the path name to the form field value, and validation rules.
496
+ *
497
+ * @returns provide field handler functions, field and form state.
498
+ *
499
+ * @example
500
+ * ```tsx
501
+ * function App() {
502
+ * const { control } = useForm<FormValues>({
503
+ * defaultValues: {
504
+ * test: ""
505
+ * }
506
+ * });
507
+ *
508
+ * return (
509
+ * <form>
510
+ * <Controller
511
+ * control={control}
512
+ * name="test"
513
+ * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
514
+ * <>
515
+ * <input
516
+ * onChange={onChange} // send value to hook form
517
+ * onBlur={onBlur} // notify when input is touched
518
+ * value={value} // return updated value
519
+ * ref={ref} // set ref for focus management
520
+ * />
521
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
522
+ * <p>{fieldState.isTouched ? "touched" : ""}</p>
523
+ * </>
524
+ * )}
525
+ * />
526
+ * </form>
527
+ * );
528
+ * }
529
+ * ```
530
+ */
531
531
  const Controller = (props) => props.render(useController(props));
532
532
 
533
- var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
534
- ? {
535
- ...errors[name],
536
- types: {
537
- ...(errors[name] && errors[name].types ? errors[name].types : {}),
538
- [type]: message || true,
539
- },
540
- }
533
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
534
+ ? {
535
+ ...errors[name],
536
+ types: {
537
+ ...(errors[name] && errors[name].types ? errors[name].types : {}),
538
+ [type]: message || true,
539
+ },
540
+ }
541
541
  : {};
542
542
 
543
- const focusFieldBy = (fields, callback, fieldsNames) => {
544
- for (const key of fieldsNames || Object.keys(fields)) {
545
- const field = get(fields, key);
546
- if (field) {
547
- const { _f, ...currentField } = field;
548
- if (_f && callback(_f.name)) {
549
- if (_f.ref.focus) {
550
- _f.ref.focus();
551
- break;
552
- }
553
- else if (_f.refs && _f.refs[0].focus) {
554
- _f.refs[0].focus();
555
- break;
556
- }
557
- }
558
- else if (isObject(currentField)) {
559
- focusFieldBy(currentField, callback);
560
- }
561
- }
562
- }
543
+ const focusFieldBy = (fields, callback, fieldsNames) => {
544
+ for (const key of fieldsNames || Object.keys(fields)) {
545
+ const field = get(fields, key);
546
+ if (field) {
547
+ const { _f, ...currentField } = field;
548
+ if (_f && callback(_f.name)) {
549
+ if (_f.ref.focus) {
550
+ _f.ref.focus();
551
+ break;
552
+ }
553
+ else if (_f.refs && _f.refs[0].focus) {
554
+ _f.refs[0].focus();
555
+ break;
556
+ }
557
+ }
558
+ else if (isObject(currentField)) {
559
+ focusFieldBy(currentField, callback);
560
+ }
561
+ }
562
+ }
563
563
  };
564
564
 
565
- var generateId = () => {
566
- const d = typeof performance === 'undefined' ? Date.now() : performance.now() * 1000;
567
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
568
- const r = (Math.random() * 16 + d) % 16 | 0;
569
- return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);
570
- });
565
+ var generateId = () => {
566
+ const d = typeof performance === 'undefined' ? Date.now() : performance.now() * 1000;
567
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
568
+ const r = (Math.random() * 16 + d) % 16 | 0;
569
+ return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);
570
+ });
571
571
  };
572
572
 
573
- var getFocusFieldName = (name, index, options = {}) => options.shouldFocus || isUndefined(options.shouldFocus)
574
- ? options.focusName ||
575
- `${name}.${isUndefined(options.focusIndex) ? index : options.focusIndex}.`
573
+ var getFocusFieldName = (name, index, options = {}) => options.shouldFocus || isUndefined(options.shouldFocus)
574
+ ? options.focusName ||
575
+ `${name}.${isUndefined(options.focusIndex) ? index : options.focusIndex}.`
576
576
  : '';
577
577
 
578
- var getValidationModes = (mode) => ({
579
- isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
580
- isOnBlur: mode === VALIDATION_MODE.onBlur,
581
- isOnChange: mode === VALIDATION_MODE.onChange,
582
- isOnAll: mode === VALIDATION_MODE.all,
583
- isOnTouch: mode === VALIDATION_MODE.onTouched,
578
+ var getValidationModes = (mode) => ({
579
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
580
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
581
+ isOnChange: mode === VALIDATION_MODE.onChange,
582
+ isOnAll: mode === VALIDATION_MODE.all,
583
+ isOnTouch: mode === VALIDATION_MODE.onTouched,
584
584
  });
585
585
 
586
- var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
587
- (_names.watchAll ||
588
- _names.watch.has(name) ||
589
- [..._names.watch].some((watchName) => name.startsWith(watchName) &&
586
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
587
+ (_names.watchAll ||
588
+ _names.watch.has(name) ||
589
+ [..._names.watch].some((watchName) => name.startsWith(watchName) &&
590
590
  /^\.\w+/.test(name.slice(watchName.length))));
591
591
 
592
- var updateFieldArrayRootError = (errors, error, name) => {
593
- const fieldArrayErrors = compact(get(errors, name));
594
- set(fieldArrayErrors, 'root', error[name]);
595
- set(errors, name, fieldArrayErrors);
596
- return errors;
592
+ var updateFieldArrayRootError = (errors, error, name) => {
593
+ const fieldArrayErrors = compact(get(errors, name));
594
+ set(fieldArrayErrors, 'root', error[name]);
595
+ set(errors, name, fieldArrayErrors);
596
+ return errors;
597
597
  };
598
598
 
599
599
  var isBoolean = (value) => typeof value === 'boolean';
@@ -602,13 +602,13 @@ var isFileInput = (element) => element.type === 'file';
602
602
 
603
603
  var isFunction = (value) => typeof value === 'function';
604
604
 
605
- var isHTMLElement = (value) => {
606
- if (!isWeb) {
607
- return false;
608
- }
609
- const owner = value ? value.ownerDocument : 0;
610
- return (value instanceof
611
- (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
605
+ var isHTMLElement = (value) => {
606
+ if (!isWeb) {
607
+ return false;
608
+ }
609
+ const owner = value ? value.ownerDocument : 0;
610
+ return (value instanceof
611
+ (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
612
612
  };
613
613
 
614
614
  var isMessage = (value) => isString(value);
@@ -617,602 +617,602 @@ var isRadioInput = (element) => element.type === 'radio';
617
617
 
618
618
  var isRegex = (value) => value instanceof RegExp;
619
619
 
620
- const defaultResult = {
621
- value: false,
622
- isValid: false,
623
- };
624
- const validResult = { value: true, isValid: true };
625
- var getCheckboxValue = (options) => {
626
- if (Array.isArray(options)) {
627
- if (options.length > 1) {
628
- const values = options
629
- .filter((option) => option && option.checked && !option.disabled)
630
- .map((option) => option.value);
631
- return { value: values, isValid: !!values.length };
632
- }
633
- return options[0].checked && !options[0].disabled
634
- ? // @ts-expect-error expected to work in the browser
635
- options[0].attributes && !isUndefined(options[0].attributes.value)
636
- ? isUndefined(options[0].value) || options[0].value === ''
637
- ? validResult
638
- : { value: options[0].value, isValid: true }
639
- : validResult
640
- : defaultResult;
641
- }
642
- return defaultResult;
620
+ const defaultResult = {
621
+ value: false,
622
+ isValid: false,
623
+ };
624
+ const validResult = { value: true, isValid: true };
625
+ var getCheckboxValue = (options) => {
626
+ if (Array.isArray(options)) {
627
+ if (options.length > 1) {
628
+ const values = options
629
+ .filter((option) => option && option.checked && !option.disabled)
630
+ .map((option) => option.value);
631
+ return { value: values, isValid: !!values.length };
632
+ }
633
+ return options[0].checked && !options[0].disabled
634
+ ? // @ts-expect-error expected to work in the browser
635
+ options[0].attributes && !isUndefined(options[0].attributes.value)
636
+ ? isUndefined(options[0].value) || options[0].value === ''
637
+ ? validResult
638
+ : { value: options[0].value, isValid: true }
639
+ : validResult
640
+ : defaultResult;
641
+ }
642
+ return defaultResult;
643
643
  };
644
644
 
645
- const defaultReturn = {
646
- isValid: false,
647
- value: null,
648
- };
649
- var getRadioValue = (options) => Array.isArray(options)
650
- ? options.reduce((previous, option) => option && option.checked && !option.disabled
651
- ? {
652
- isValid: true,
653
- value: option.value,
654
- }
655
- : previous, defaultReturn)
645
+ const defaultReturn = {
646
+ isValid: false,
647
+ value: null,
648
+ };
649
+ var getRadioValue = (options) => Array.isArray(options)
650
+ ? options.reduce((previous, option) => option && option.checked && !option.disabled
651
+ ? {
652
+ isValid: true,
653
+ value: option.value,
654
+ }
655
+ : previous, defaultReturn)
656
656
  : defaultReturn;
657
657
 
658
- function getValidateError(result, ref, type = 'validate') {
659
- if (isMessage(result) ||
660
- (Array.isArray(result) && result.every(isMessage)) ||
661
- (isBoolean(result) && !result)) {
662
- return {
663
- type,
664
- message: isMessage(result) ? result : '',
665
- ref,
666
- };
667
- }
658
+ function getValidateError(result, ref, type = 'validate') {
659
+ if (isMessage(result) ||
660
+ (Array.isArray(result) && result.every(isMessage)) ||
661
+ (isBoolean(result) && !result)) {
662
+ return {
663
+ type,
664
+ message: isMessage(result) ? result : '',
665
+ ref,
666
+ };
667
+ }
668
668
  }
669
669
 
670
- var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
671
- ? validationData
672
- : {
673
- value: validationData,
674
- message: '',
670
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
671
+ ? validationData
672
+ : {
673
+ value: validationData,
674
+ message: '',
675
675
  };
676
676
 
677
- var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
678
- const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled, } = field._f;
679
- const inputValue = get(formValues, name);
680
- if (!mount || disabled) {
681
- return {};
682
- }
683
- const inputRef = refs ? refs[0] : ref;
684
- const setCustomValidity = (message) => {
685
- if (shouldUseNativeValidation && inputRef.reportValidity) {
686
- inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
687
- inputRef.reportValidity();
688
- }
689
- };
690
- const error = {};
691
- const isRadio = isRadioInput(ref);
692
- const isCheckBox = isCheckBoxInput(ref);
693
- const isRadioOrCheckbox = isRadio || isCheckBox;
694
- const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
695
- isUndefined(ref.value) &&
696
- isUndefined(inputValue)) ||
697
- (isHTMLElement(ref) && ref.value === '') ||
698
- inputValue === '' ||
699
- (Array.isArray(inputValue) && !inputValue.length);
700
- const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
701
- const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
702
- const message = exceedMax ? maxLengthMessage : minLengthMessage;
703
- error[name] = {
704
- type: exceedMax ? maxType : minType,
705
- message,
706
- ref,
707
- ...appendErrorsCurry(exceedMax ? maxType : minType, message),
708
- };
709
- };
710
- if (isFieldArray
711
- ? !Array.isArray(inputValue) || !inputValue.length
712
- : required &&
713
- ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
714
- (isBoolean(inputValue) && !inputValue) ||
715
- (isCheckBox && !getCheckboxValue(refs).isValid) ||
716
- (isRadio && !getRadioValue(refs).isValid))) {
717
- const { value, message } = isMessage(required)
718
- ? { value: !!required, message: required }
719
- : getValueAndMessage(required);
720
- if (value) {
721
- error[name] = {
722
- type: INPUT_VALIDATION_RULES.required,
723
- message,
724
- ref: inputRef,
725
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
726
- };
727
- if (!validateAllFieldCriteria) {
728
- setCustomValidity(message);
729
- return error;
730
- }
731
- }
732
- }
733
- if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
734
- let exceedMax;
735
- let exceedMin;
736
- const maxOutput = getValueAndMessage(max);
737
- const minOutput = getValueAndMessage(min);
738
- if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
739
- const valueNumber = ref.valueAsNumber ||
740
- (inputValue ? +inputValue : inputValue);
741
- if (!isNullOrUndefined(maxOutput.value)) {
742
- exceedMax = valueNumber > maxOutput.value;
743
- }
744
- if (!isNullOrUndefined(minOutput.value)) {
745
- exceedMin = valueNumber < minOutput.value;
746
- }
747
- }
748
- else {
749
- const valueDate = ref.valueAsDate || new Date(inputValue);
750
- const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
751
- const isTime = ref.type == 'time';
752
- const isWeek = ref.type == 'week';
753
- if (isString(maxOutput.value) && inputValue) {
754
- exceedMax = isTime
755
- ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
756
- : isWeek
757
- ? inputValue > maxOutput.value
758
- : valueDate > new Date(maxOutput.value);
759
- }
760
- if (isString(minOutput.value) && inputValue) {
761
- exceedMin = isTime
762
- ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
763
- : isWeek
764
- ? inputValue < minOutput.value
765
- : valueDate < new Date(minOutput.value);
766
- }
767
- }
768
- if (exceedMax || exceedMin) {
769
- getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
770
- if (!validateAllFieldCriteria) {
771
- setCustomValidity(error[name].message);
772
- return error;
773
- }
774
- }
775
- }
776
- if ((maxLength || minLength) &&
777
- !isEmpty &&
778
- (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
779
- const maxLengthOutput = getValueAndMessage(maxLength);
780
- const minLengthOutput = getValueAndMessage(minLength);
781
- const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
782
- inputValue.length > maxLengthOutput.value;
783
- const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
784
- inputValue.length < minLengthOutput.value;
785
- if (exceedMax || exceedMin) {
786
- getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
787
- if (!validateAllFieldCriteria) {
788
- setCustomValidity(error[name].message);
789
- return error;
790
- }
791
- }
792
- }
793
- if (pattern && !isEmpty && isString(inputValue)) {
794
- const { value: patternValue, message } = getValueAndMessage(pattern);
795
- if (isRegex(patternValue) && !inputValue.match(patternValue)) {
796
- error[name] = {
797
- type: INPUT_VALIDATION_RULES.pattern,
798
- message,
799
- ref,
800
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
801
- };
802
- if (!validateAllFieldCriteria) {
803
- setCustomValidity(message);
804
- return error;
805
- }
806
- }
807
- }
808
- if (validate) {
809
- if (isFunction(validate)) {
810
- const result = await validate(inputValue, formValues);
811
- const validateError = getValidateError(result, inputRef);
812
- if (validateError) {
813
- error[name] = {
814
- ...validateError,
815
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
816
- };
817
- if (!validateAllFieldCriteria) {
818
- setCustomValidity(validateError.message);
819
- return error;
820
- }
821
- }
822
- }
823
- else if (isObject(validate)) {
824
- let validationResult = {};
825
- for (const key in validate) {
826
- if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
827
- break;
828
- }
829
- const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
830
- if (validateError) {
831
- validationResult = {
832
- ...validateError,
833
- ...appendErrorsCurry(key, validateError.message),
834
- };
835
- setCustomValidity(validateError.message);
836
- if (validateAllFieldCriteria) {
837
- error[name] = validationResult;
838
- }
839
- }
840
- }
841
- if (!isEmptyObject(validationResult)) {
842
- error[name] = {
843
- ref: inputRef,
844
- ...validationResult,
845
- };
846
- if (!validateAllFieldCriteria) {
847
- return error;
848
- }
849
- }
850
- }
851
- }
852
- setCustomValidity(true);
853
- return error;
677
+ var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
678
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled, } = field._f;
679
+ const inputValue = get(formValues, name);
680
+ if (!mount || disabled) {
681
+ return {};
682
+ }
683
+ const inputRef = refs ? refs[0] : ref;
684
+ const setCustomValidity = (message) => {
685
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
686
+ inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
687
+ inputRef.reportValidity();
688
+ }
689
+ };
690
+ const error = {};
691
+ const isRadio = isRadioInput(ref);
692
+ const isCheckBox = isCheckBoxInput(ref);
693
+ const isRadioOrCheckbox = isRadio || isCheckBox;
694
+ const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
695
+ isUndefined(ref.value) &&
696
+ isUndefined(inputValue)) ||
697
+ (isHTMLElement(ref) && ref.value === '') ||
698
+ inputValue === '' ||
699
+ (Array.isArray(inputValue) && !inputValue.length);
700
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
701
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
702
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
703
+ error[name] = {
704
+ type: exceedMax ? maxType : minType,
705
+ message,
706
+ ref,
707
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message),
708
+ };
709
+ };
710
+ if (isFieldArray
711
+ ? !Array.isArray(inputValue) || !inputValue.length
712
+ : required &&
713
+ ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
714
+ (isBoolean(inputValue) && !inputValue) ||
715
+ (isCheckBox && !getCheckboxValue(refs).isValid) ||
716
+ (isRadio && !getRadioValue(refs).isValid))) {
717
+ const { value, message } = isMessage(required)
718
+ ? { value: !!required, message: required }
719
+ : getValueAndMessage(required);
720
+ if (value) {
721
+ error[name] = {
722
+ type: INPUT_VALIDATION_RULES.required,
723
+ message,
724
+ ref: inputRef,
725
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
726
+ };
727
+ if (!validateAllFieldCriteria) {
728
+ setCustomValidity(message);
729
+ return error;
730
+ }
731
+ }
732
+ }
733
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
734
+ let exceedMax;
735
+ let exceedMin;
736
+ const maxOutput = getValueAndMessage(max);
737
+ const minOutput = getValueAndMessage(min);
738
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
739
+ const valueNumber = ref.valueAsNumber ||
740
+ (inputValue ? +inputValue : inputValue);
741
+ if (!isNullOrUndefined(maxOutput.value)) {
742
+ exceedMax = valueNumber > maxOutput.value;
743
+ }
744
+ if (!isNullOrUndefined(minOutput.value)) {
745
+ exceedMin = valueNumber < minOutput.value;
746
+ }
747
+ }
748
+ else {
749
+ const valueDate = ref.valueAsDate || new Date(inputValue);
750
+ const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
751
+ const isTime = ref.type == 'time';
752
+ const isWeek = ref.type == 'week';
753
+ if (isString(maxOutput.value) && inputValue) {
754
+ exceedMax = isTime
755
+ ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
756
+ : isWeek
757
+ ? inputValue > maxOutput.value
758
+ : valueDate > new Date(maxOutput.value);
759
+ }
760
+ if (isString(minOutput.value) && inputValue) {
761
+ exceedMin = isTime
762
+ ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
763
+ : isWeek
764
+ ? inputValue < minOutput.value
765
+ : valueDate < new Date(minOutput.value);
766
+ }
767
+ }
768
+ if (exceedMax || exceedMin) {
769
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
770
+ if (!validateAllFieldCriteria) {
771
+ setCustomValidity(error[name].message);
772
+ return error;
773
+ }
774
+ }
775
+ }
776
+ if ((maxLength || minLength) &&
777
+ !isEmpty &&
778
+ (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
779
+ const maxLengthOutput = getValueAndMessage(maxLength);
780
+ const minLengthOutput = getValueAndMessage(minLength);
781
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
782
+ inputValue.length > +maxLengthOutput.value;
783
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
784
+ inputValue.length < +minLengthOutput.value;
785
+ if (exceedMax || exceedMin) {
786
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
787
+ if (!validateAllFieldCriteria) {
788
+ setCustomValidity(error[name].message);
789
+ return error;
790
+ }
791
+ }
792
+ }
793
+ if (pattern && !isEmpty && isString(inputValue)) {
794
+ const { value: patternValue, message } = getValueAndMessage(pattern);
795
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
796
+ error[name] = {
797
+ type: INPUT_VALIDATION_RULES.pattern,
798
+ message,
799
+ ref,
800
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
801
+ };
802
+ if (!validateAllFieldCriteria) {
803
+ setCustomValidity(message);
804
+ return error;
805
+ }
806
+ }
807
+ }
808
+ if (validate) {
809
+ if (isFunction(validate)) {
810
+ const result = await validate(inputValue, formValues);
811
+ const validateError = getValidateError(result, inputRef);
812
+ if (validateError) {
813
+ error[name] = {
814
+ ...validateError,
815
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
816
+ };
817
+ if (!validateAllFieldCriteria) {
818
+ setCustomValidity(validateError.message);
819
+ return error;
820
+ }
821
+ }
822
+ }
823
+ else if (isObject(validate)) {
824
+ let validationResult = {};
825
+ for (const key in validate) {
826
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
827
+ break;
828
+ }
829
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
830
+ if (validateError) {
831
+ validationResult = {
832
+ ...validateError,
833
+ ...appendErrorsCurry(key, validateError.message),
834
+ };
835
+ setCustomValidity(validateError.message);
836
+ if (validateAllFieldCriteria) {
837
+ error[name] = validationResult;
838
+ }
839
+ }
840
+ }
841
+ if (!isEmptyObject(validationResult)) {
842
+ error[name] = {
843
+ ref: inputRef,
844
+ ...validationResult,
845
+ };
846
+ if (!validateAllFieldCriteria) {
847
+ return error;
848
+ }
849
+ }
850
+ }
851
+ }
852
+ setCustomValidity(true);
853
+ return error;
854
854
  };
855
855
 
856
- function append(data, value) {
857
- return [...data, ...convertToArrayPayload(value)];
856
+ function append(data, value) {
857
+ return [...data, ...convertToArrayPayload(value)];
858
858
  }
859
859
 
860
860
  var fillEmptyArray = (value) => Array.isArray(value) ? value.map(() => undefined) : undefined;
861
861
 
862
- function insert(data, index, value) {
863
- return [
864
- ...data.slice(0, index),
865
- ...convertToArrayPayload(value),
866
- ...data.slice(index),
867
- ];
862
+ function insert(data, index, value) {
863
+ return [
864
+ ...data.slice(0, index),
865
+ ...convertToArrayPayload(value),
866
+ ...data.slice(index),
867
+ ];
868
868
  }
869
869
 
870
- var moveArrayAt = (data, from, to) => {
871
- if (!Array.isArray(data)) {
872
- return [];
873
- }
874
- if (isUndefined(data[to])) {
875
- data[to] = undefined;
876
- }
877
- data.splice(to, 0, data.splice(from, 1)[0]);
878
- return data;
870
+ var moveArrayAt = (data, from, to) => {
871
+ if (!Array.isArray(data)) {
872
+ return [];
873
+ }
874
+ if (isUndefined(data[to])) {
875
+ data[to] = undefined;
876
+ }
877
+ data.splice(to, 0, data.splice(from, 1)[0]);
878
+ return data;
879
879
  };
880
880
 
881
- function prepend(data, value) {
882
- return [...convertToArrayPayload(value), ...convertToArrayPayload(data)];
881
+ function prepend(data, value) {
882
+ return [...convertToArrayPayload(value), ...convertToArrayPayload(data)];
883
883
  }
884
884
 
885
- function removeAtIndexes(data, indexes) {
886
- let i = 0;
887
- const temp = [...data];
888
- for (const index of indexes) {
889
- temp.splice(index - i, 1);
890
- i++;
891
- }
892
- return compact(temp).length ? temp : [];
893
- }
894
- var removeArrayAt = (data, index) => isUndefined(index)
895
- ? []
885
+ function removeAtIndexes(data, indexes) {
886
+ let i = 0;
887
+ const temp = [...data];
888
+ for (const index of indexes) {
889
+ temp.splice(index - i, 1);
890
+ i++;
891
+ }
892
+ return compact(temp).length ? temp : [];
893
+ }
894
+ var removeArrayAt = (data, index) => isUndefined(index)
895
+ ? []
896
896
  : removeAtIndexes(data, convertToArrayPayload(index).sort((a, b) => a - b));
897
897
 
898
- var swapArrayAt = (data, indexA, indexB) => {
899
- data[indexA] = [data[indexB], (data[indexB] = data[indexA])][0];
898
+ var swapArrayAt = (data, indexA, indexB) => {
899
+ data[indexA] = [data[indexB], (data[indexB] = data[indexA])][0];
900
900
  };
901
901
 
902
- function baseGet(object, updatePath) {
903
- const length = updatePath.slice(0, -1).length;
904
- let index = 0;
905
- while (index < length) {
906
- object = isUndefined(object) ? index++ : object[updatePath[index++]];
907
- }
908
- return object;
909
- }
910
- function isEmptyArray(obj) {
911
- for (const key in obj) {
912
- if (!isUndefined(obj[key])) {
913
- return false;
914
- }
915
- }
916
- return true;
917
- }
918
- function unset(object, path) {
919
- const paths = Array.isArray(path)
920
- ? path
921
- : isKey(path)
922
- ? [path]
923
- : stringToPath(path);
924
- const childObject = paths.length === 1 ? object : baseGet(object, paths);
925
- const index = paths.length - 1;
926
- const key = paths[index];
927
- if (childObject) {
928
- delete childObject[key];
929
- }
930
- if (index !== 0 &&
931
- ((isObject(childObject) && isEmptyObject(childObject)) ||
932
- (Array.isArray(childObject) && isEmptyArray(childObject)))) {
933
- unset(object, paths.slice(0, -1));
934
- }
935
- return object;
902
+ function baseGet(object, updatePath) {
903
+ const length = updatePath.slice(0, -1).length;
904
+ let index = 0;
905
+ while (index < length) {
906
+ object = isUndefined(object) ? index++ : object[updatePath[index++]];
907
+ }
908
+ return object;
909
+ }
910
+ function isEmptyArray(obj) {
911
+ for (const key in obj) {
912
+ if (!isUndefined(obj[key])) {
913
+ return false;
914
+ }
915
+ }
916
+ return true;
917
+ }
918
+ function unset(object, path) {
919
+ const paths = Array.isArray(path)
920
+ ? path
921
+ : isKey(path)
922
+ ? [path]
923
+ : stringToPath(path);
924
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
925
+ const index = paths.length - 1;
926
+ const key = paths[index];
927
+ if (childObject) {
928
+ delete childObject[key];
929
+ }
930
+ if (index !== 0 &&
931
+ ((isObject(childObject) && isEmptyObject(childObject)) ||
932
+ (Array.isArray(childObject) && isEmptyArray(childObject)))) {
933
+ unset(object, paths.slice(0, -1));
934
+ }
935
+ return object;
936
936
  }
937
937
 
938
- var updateAt = (fieldValues, index, value) => {
939
- fieldValues[index] = value;
940
- return fieldValues;
938
+ var updateAt = (fieldValues, index, value) => {
939
+ fieldValues[index] = value;
940
+ return fieldValues;
941
941
  };
942
942
 
943
- /**
944
- * 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)
945
- *
946
- * @remarks
947
- * [API](https://react-hook-form.com/api/usefieldarray) • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn)
948
- *
949
- * @param props - useFieldArray props
950
- *
951
- * @returns methods - functions to manipulate with the Field Arrays (dynamic inputs) {@link UseFieldArrayReturn}
952
- *
953
- * @example
954
- * ```tsx
955
- * function App() {
956
- * const { register, control, handleSubmit, reset, trigger, setError } = useForm({
957
- * defaultValues: {
958
- * test: []
959
- * }
960
- * });
961
- * const { fields, append } = useFieldArray({
962
- * control,
963
- * name: "test"
964
- * });
965
- *
966
- * return (
967
- * <form onSubmit={handleSubmit(data => console.log(data))}>
968
- * {fields.map((item, index) => (
969
- * <input key={item.id} {...register(`test.${index}.firstName`)} />
970
- * ))}
971
- * <button type="button" onClick={() => append({ firstName: "bill" })}>
972
- * append
973
- * </button>
974
- * <input type="submit" />
975
- * </form>
976
- * );
977
- * }
978
- * ```
979
- */
980
- function useFieldArray(props) {
981
- const methods = useFormContext();
982
- const { control = methods.control, name, keyName = 'id', shouldUnregister, } = props;
983
- const [fields, setFields] = React.useState(control._getFieldArray(name));
984
- const ids = React.useRef(control._getFieldArray(name).map(generateId));
985
- const _fieldIds = React.useRef(fields);
986
- const _name = React.useRef(name);
987
- const _actioned = React.useRef(false);
988
- _name.current = name;
989
- _fieldIds.current = fields;
990
- control._names.array.add(name);
991
- props.rules &&
992
- control.register(name, props.rules);
993
- useSubscribe({
994
- next: ({ values, name: fieldArrayName, }) => {
995
- if (fieldArrayName === _name.current || !fieldArrayName) {
996
- const fieldValues = get(values, _name.current);
997
- if (Array.isArray(fieldValues)) {
998
- setFields(fieldValues);
999
- ids.current = fieldValues.map(generateId);
1000
- }
1001
- }
1002
- },
1003
- subject: control._subjects.array,
1004
- });
1005
- const updateValues = React.useCallback((updatedFieldArrayValues) => {
1006
- _actioned.current = true;
1007
- control._updateFieldArray(name, updatedFieldArrayValues);
1008
- }, [control, name]);
1009
- const append$1 = (value, options) => {
1010
- const appendValue = convertToArrayPayload(cloneObject(value));
1011
- const updatedFieldArrayValues = append(control._getFieldArray(name), appendValue);
1012
- control._names.focus = getFocusFieldName(name, updatedFieldArrayValues.length - 1, options);
1013
- ids.current = append(ids.current, appendValue.map(generateId));
1014
- updateValues(updatedFieldArrayValues);
1015
- setFields(updatedFieldArrayValues);
1016
- control._updateFieldArray(name, updatedFieldArrayValues, append, {
1017
- argA: fillEmptyArray(value),
1018
- });
1019
- };
1020
- const prepend$1 = (value, options) => {
1021
- const prependValue = convertToArrayPayload(cloneObject(value));
1022
- const updatedFieldArrayValues = prepend(control._getFieldArray(name), prependValue);
1023
- control._names.focus = getFocusFieldName(name, 0, options);
1024
- ids.current = prepend(ids.current, prependValue.map(generateId));
1025
- updateValues(updatedFieldArrayValues);
1026
- setFields(updatedFieldArrayValues);
1027
- control._updateFieldArray(name, updatedFieldArrayValues, prepend, {
1028
- argA: fillEmptyArray(value),
1029
- });
1030
- };
1031
- const remove = (index) => {
1032
- const updatedFieldArrayValues = removeArrayAt(control._getFieldArray(name), index);
1033
- ids.current = removeArrayAt(ids.current, index);
1034
- updateValues(updatedFieldArrayValues);
1035
- setFields(updatedFieldArrayValues);
1036
- control._updateFieldArray(name, updatedFieldArrayValues, removeArrayAt, {
1037
- argA: index,
1038
- });
1039
- };
1040
- const insert$1 = (index, value, options) => {
1041
- const insertValue = convertToArrayPayload(cloneObject(value));
1042
- const updatedFieldArrayValues = insert(control._getFieldArray(name), index, insertValue);
1043
- control._names.focus = getFocusFieldName(name, index, options);
1044
- ids.current = insert(ids.current, index, insertValue.map(generateId));
1045
- updateValues(updatedFieldArrayValues);
1046
- setFields(updatedFieldArrayValues);
1047
- control._updateFieldArray(name, updatedFieldArrayValues, insert, {
1048
- argA: index,
1049
- argB: fillEmptyArray(value),
1050
- });
1051
- };
1052
- const swap = (indexA, indexB) => {
1053
- const updatedFieldArrayValues = control._getFieldArray(name);
1054
- swapArrayAt(updatedFieldArrayValues, indexA, indexB);
1055
- swapArrayAt(ids.current, indexA, indexB);
1056
- updateValues(updatedFieldArrayValues);
1057
- setFields(updatedFieldArrayValues);
1058
- control._updateFieldArray(name, updatedFieldArrayValues, swapArrayAt, {
1059
- argA: indexA,
1060
- argB: indexB,
1061
- }, false);
1062
- };
1063
- const move = (from, to) => {
1064
- const updatedFieldArrayValues = control._getFieldArray(name);
1065
- moveArrayAt(updatedFieldArrayValues, from, to);
1066
- moveArrayAt(ids.current, from, to);
1067
- updateValues(updatedFieldArrayValues);
1068
- setFields(updatedFieldArrayValues);
1069
- control._updateFieldArray(name, updatedFieldArrayValues, moveArrayAt, {
1070
- argA: from,
1071
- argB: to,
1072
- }, false);
1073
- };
1074
- const update = (index, value) => {
1075
- const updateValue = cloneObject(value);
1076
- const updatedFieldArrayValues = updateAt(control._getFieldArray(name), index, updateValue);
1077
- ids.current = [...updatedFieldArrayValues].map((item, i) => !item || i === index ? generateId() : ids.current[i]);
1078
- updateValues(updatedFieldArrayValues);
1079
- setFields([...updatedFieldArrayValues]);
1080
- control._updateFieldArray(name, updatedFieldArrayValues, updateAt, {
1081
- argA: index,
1082
- argB: updateValue,
1083
- }, true, false);
1084
- };
1085
- const replace = (value) => {
1086
- const updatedFieldArrayValues = convertToArrayPayload(cloneObject(value));
1087
- ids.current = updatedFieldArrayValues.map(generateId);
1088
- updateValues([...updatedFieldArrayValues]);
1089
- setFields([...updatedFieldArrayValues]);
1090
- control._updateFieldArray(name, [...updatedFieldArrayValues], (data) => data, {}, true, false);
1091
- };
1092
- React.useEffect(() => {
1093
- control._state.action = false;
1094
- isWatched(name, control._names) &&
1095
- control._subjects.state.next({
1096
- ...control._formState,
1097
- });
1098
- if (_actioned.current &&
1099
- (!getValidationModes(control._options.mode).isOnSubmit ||
1100
- control._formState.isSubmitted)) {
1101
- if (control._options.resolver) {
1102
- control._executeSchema([name]).then((result) => {
1103
- const error = get(result.errors, name);
1104
- const existingError = get(control._formState.errors, name);
1105
- if (existingError ? !error && existingError.type : error && error.type) {
1106
- error
1107
- ? set(control._formState.errors, name, error)
1108
- : unset(control._formState.errors, name);
1109
- control._subjects.state.next({
1110
- errors: control._formState.errors,
1111
- });
1112
- }
1113
- });
1114
- }
1115
- else {
1116
- const field = get(control._fields, name);
1117
- if (field && field._f) {
1118
- validateField(field, control._formValues, control._options.criteriaMode === VALIDATION_MODE.all, control._options.shouldUseNativeValidation, true).then((error) => !isEmptyObject(error) &&
1119
- control._subjects.state.next({
1120
- errors: updateFieldArrayRootError(control._formState.errors, error, name),
1121
- }));
1122
- }
1123
- }
1124
- }
1125
- control._subjects.values.next({
1126
- name,
1127
- values: { ...control._formValues },
1128
- });
1129
- control._names.focus &&
1130
- focusFieldBy(control._fields, (key) => !!key && key.startsWith(control._names.focus || ''));
1131
- control._names.focus = '';
1132
- control._updateValid();
1133
- }, [fields, name, control]);
1134
- React.useEffect(() => {
1135
- !get(control._formValues, name) && control._updateFieldArray(name);
1136
- return () => {
1137
- (control._options.shouldUnregister || shouldUnregister) &&
1138
- control.unregister(name);
1139
- };
1140
- }, [name, control, keyName, shouldUnregister]);
1141
- return {
1142
- swap: React.useCallback(swap, [updateValues, name, control]),
1143
- move: React.useCallback(move, [updateValues, name, control]),
1144
- prepend: React.useCallback(prepend$1, [updateValues, name, control]),
1145
- append: React.useCallback(append$1, [updateValues, name, control]),
1146
- remove: React.useCallback(remove, [updateValues, name, control]),
1147
- insert: React.useCallback(insert$1, [updateValues, name, control]),
1148
- update: React.useCallback(update, [updateValues, name, control]),
1149
- replace: React.useCallback(replace, [updateValues, name, control]),
1150
- fields: React.useMemo(() => fields.map((field, index) => ({
1151
- ...field,
1152
- [keyName]: ids.current[index] || generateId(),
1153
- })), [fields, keyName]),
1154
- };
943
+ /**
944
+ * 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)
945
+ *
946
+ * @remarks
947
+ * [API](https://react-hook-form.com/api/usefieldarray) • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn)
948
+ *
949
+ * @param props - useFieldArray props
950
+ *
951
+ * @returns methods - functions to manipulate with the Field Arrays (dynamic inputs) {@link UseFieldArrayReturn}
952
+ *
953
+ * @example
954
+ * ```tsx
955
+ * function App() {
956
+ * const { register, control, handleSubmit, reset, trigger, setError } = useForm({
957
+ * defaultValues: {
958
+ * test: []
959
+ * }
960
+ * });
961
+ * const { fields, append } = useFieldArray({
962
+ * control,
963
+ * name: "test"
964
+ * });
965
+ *
966
+ * return (
967
+ * <form onSubmit={handleSubmit(data => console.log(data))}>
968
+ * {fields.map((item, index) => (
969
+ * <input key={item.id} {...register(`test.${index}.firstName`)} />
970
+ * ))}
971
+ * <button type="button" onClick={() => append({ firstName: "bill" })}>
972
+ * append
973
+ * </button>
974
+ * <input type="submit" />
975
+ * </form>
976
+ * );
977
+ * }
978
+ * ```
979
+ */
980
+ function useFieldArray(props) {
981
+ const methods = useFormContext();
982
+ const { control = methods.control, name, keyName = 'id', shouldUnregister, } = props;
983
+ const [fields, setFields] = React.useState(control._getFieldArray(name));
984
+ const ids = React.useRef(control._getFieldArray(name).map(generateId));
985
+ const _fieldIds = React.useRef(fields);
986
+ const _name = React.useRef(name);
987
+ const _actioned = React.useRef(false);
988
+ _name.current = name;
989
+ _fieldIds.current = fields;
990
+ control._names.array.add(name);
991
+ props.rules &&
992
+ control.register(name, props.rules);
993
+ useSubscribe({
994
+ next: ({ values, name: fieldArrayName, }) => {
995
+ if (fieldArrayName === _name.current || !fieldArrayName) {
996
+ const fieldValues = get(values, _name.current);
997
+ if (Array.isArray(fieldValues)) {
998
+ setFields(fieldValues);
999
+ ids.current = fieldValues.map(generateId);
1000
+ }
1001
+ }
1002
+ },
1003
+ subject: control._subjects.array,
1004
+ });
1005
+ const updateValues = React.useCallback((updatedFieldArrayValues) => {
1006
+ _actioned.current = true;
1007
+ control._updateFieldArray(name, updatedFieldArrayValues);
1008
+ }, [control, name]);
1009
+ const append$1 = (value, options) => {
1010
+ const appendValue = convertToArrayPayload(cloneObject(value));
1011
+ const updatedFieldArrayValues = append(control._getFieldArray(name), appendValue);
1012
+ control._names.focus = getFocusFieldName(name, updatedFieldArrayValues.length - 1, options);
1013
+ ids.current = append(ids.current, appendValue.map(generateId));
1014
+ updateValues(updatedFieldArrayValues);
1015
+ setFields(updatedFieldArrayValues);
1016
+ control._updateFieldArray(name, updatedFieldArrayValues, append, {
1017
+ argA: fillEmptyArray(value),
1018
+ });
1019
+ };
1020
+ const prepend$1 = (value, options) => {
1021
+ const prependValue = convertToArrayPayload(cloneObject(value));
1022
+ const updatedFieldArrayValues = prepend(control._getFieldArray(name), prependValue);
1023
+ control._names.focus = getFocusFieldName(name, 0, options);
1024
+ ids.current = prepend(ids.current, prependValue.map(generateId));
1025
+ updateValues(updatedFieldArrayValues);
1026
+ setFields(updatedFieldArrayValues);
1027
+ control._updateFieldArray(name, updatedFieldArrayValues, prepend, {
1028
+ argA: fillEmptyArray(value),
1029
+ });
1030
+ };
1031
+ const remove = (index) => {
1032
+ const updatedFieldArrayValues = removeArrayAt(control._getFieldArray(name), index);
1033
+ ids.current = removeArrayAt(ids.current, index);
1034
+ updateValues(updatedFieldArrayValues);
1035
+ setFields(updatedFieldArrayValues);
1036
+ control._updateFieldArray(name, updatedFieldArrayValues, removeArrayAt, {
1037
+ argA: index,
1038
+ });
1039
+ };
1040
+ const insert$1 = (index, value, options) => {
1041
+ const insertValue = convertToArrayPayload(cloneObject(value));
1042
+ const updatedFieldArrayValues = insert(control._getFieldArray(name), index, insertValue);
1043
+ control._names.focus = getFocusFieldName(name, index, options);
1044
+ ids.current = insert(ids.current, index, insertValue.map(generateId));
1045
+ updateValues(updatedFieldArrayValues);
1046
+ setFields(updatedFieldArrayValues);
1047
+ control._updateFieldArray(name, updatedFieldArrayValues, insert, {
1048
+ argA: index,
1049
+ argB: fillEmptyArray(value),
1050
+ });
1051
+ };
1052
+ const swap = (indexA, indexB) => {
1053
+ const updatedFieldArrayValues = control._getFieldArray(name);
1054
+ swapArrayAt(updatedFieldArrayValues, indexA, indexB);
1055
+ swapArrayAt(ids.current, indexA, indexB);
1056
+ updateValues(updatedFieldArrayValues);
1057
+ setFields(updatedFieldArrayValues);
1058
+ control._updateFieldArray(name, updatedFieldArrayValues, swapArrayAt, {
1059
+ argA: indexA,
1060
+ argB: indexB,
1061
+ }, false);
1062
+ };
1063
+ const move = (from, to) => {
1064
+ const updatedFieldArrayValues = control._getFieldArray(name);
1065
+ moveArrayAt(updatedFieldArrayValues, from, to);
1066
+ moveArrayAt(ids.current, from, to);
1067
+ updateValues(updatedFieldArrayValues);
1068
+ setFields(updatedFieldArrayValues);
1069
+ control._updateFieldArray(name, updatedFieldArrayValues, moveArrayAt, {
1070
+ argA: from,
1071
+ argB: to,
1072
+ }, false);
1073
+ };
1074
+ const update = (index, value) => {
1075
+ const updateValue = cloneObject(value);
1076
+ const updatedFieldArrayValues = updateAt(control._getFieldArray(name), index, updateValue);
1077
+ ids.current = [...updatedFieldArrayValues].map((item, i) => !item || i === index ? generateId() : ids.current[i]);
1078
+ updateValues(updatedFieldArrayValues);
1079
+ setFields([...updatedFieldArrayValues]);
1080
+ control._updateFieldArray(name, updatedFieldArrayValues, updateAt, {
1081
+ argA: index,
1082
+ argB: updateValue,
1083
+ }, true, false);
1084
+ };
1085
+ const replace = (value) => {
1086
+ const updatedFieldArrayValues = convertToArrayPayload(cloneObject(value));
1087
+ ids.current = updatedFieldArrayValues.map(generateId);
1088
+ updateValues([...updatedFieldArrayValues]);
1089
+ setFields([...updatedFieldArrayValues]);
1090
+ control._updateFieldArray(name, [...updatedFieldArrayValues], (data) => data, {}, true, false);
1091
+ };
1092
+ React.useEffect(() => {
1093
+ control._state.action = false;
1094
+ isWatched(name, control._names) &&
1095
+ control._subjects.state.next({
1096
+ ...control._formState,
1097
+ });
1098
+ if (_actioned.current &&
1099
+ (!getValidationModes(control._options.mode).isOnSubmit ||
1100
+ control._formState.isSubmitted)) {
1101
+ if (control._options.resolver) {
1102
+ control._executeSchema([name]).then((result) => {
1103
+ const error = get(result.errors, name);
1104
+ const existingError = get(control._formState.errors, name);
1105
+ if (existingError ? !error && existingError.type : error && error.type) {
1106
+ error
1107
+ ? set(control._formState.errors, name, error)
1108
+ : unset(control._formState.errors, name);
1109
+ control._subjects.state.next({
1110
+ errors: control._formState.errors,
1111
+ });
1112
+ }
1113
+ });
1114
+ }
1115
+ else {
1116
+ const field = get(control._fields, name);
1117
+ if (field && field._f) {
1118
+ validateField(field, control._formValues, control._options.criteriaMode === VALIDATION_MODE.all, control._options.shouldUseNativeValidation, true).then((error) => !isEmptyObject(error) &&
1119
+ control._subjects.state.next({
1120
+ errors: updateFieldArrayRootError(control._formState.errors, error, name),
1121
+ }));
1122
+ }
1123
+ }
1124
+ }
1125
+ control._subjects.values.next({
1126
+ name,
1127
+ values: { ...control._formValues },
1128
+ });
1129
+ control._names.focus &&
1130
+ focusFieldBy(control._fields, (key) => !!key && key.startsWith(control._names.focus || ''));
1131
+ control._names.focus = '';
1132
+ control._updateValid();
1133
+ }, [fields, name, control]);
1134
+ React.useEffect(() => {
1135
+ !get(control._formValues, name) && control._updateFieldArray(name);
1136
+ return () => {
1137
+ (control._options.shouldUnregister || shouldUnregister) &&
1138
+ control.unregister(name);
1139
+ };
1140
+ }, [name, control, keyName, shouldUnregister]);
1141
+ return {
1142
+ swap: React.useCallback(swap, [updateValues, name, control]),
1143
+ move: React.useCallback(move, [updateValues, name, control]),
1144
+ prepend: React.useCallback(prepend$1, [updateValues, name, control]),
1145
+ append: React.useCallback(append$1, [updateValues, name, control]),
1146
+ remove: React.useCallback(remove, [updateValues, name, control]),
1147
+ insert: React.useCallback(insert$1, [updateValues, name, control]),
1148
+ update: React.useCallback(update, [updateValues, name, control]),
1149
+ replace: React.useCallback(replace, [updateValues, name, control]),
1150
+ fields: React.useMemo(() => fields.map((field, index) => ({
1151
+ ...field,
1152
+ [keyName]: ids.current[index] || generateId(),
1153
+ })), [fields, keyName]),
1154
+ };
1155
1155
  }
1156
1156
 
1157
- function createSubject() {
1158
- let _observers = [];
1159
- const next = (value) => {
1160
- for (const observer of _observers) {
1161
- observer.next && observer.next(value);
1162
- }
1163
- };
1164
- const subscribe = (observer) => {
1165
- _observers.push(observer);
1166
- return {
1167
- unsubscribe: () => {
1168
- _observers = _observers.filter((o) => o !== observer);
1169
- },
1170
- };
1171
- };
1172
- const unsubscribe = () => {
1173
- _observers = [];
1174
- };
1175
- return {
1176
- get observers() {
1177
- return _observers;
1178
- },
1179
- next,
1180
- subscribe,
1181
- unsubscribe,
1182
- };
1157
+ function createSubject() {
1158
+ let _observers = [];
1159
+ const next = (value) => {
1160
+ for (const observer of _observers) {
1161
+ observer.next && observer.next(value);
1162
+ }
1163
+ };
1164
+ const subscribe = (observer) => {
1165
+ _observers.push(observer);
1166
+ return {
1167
+ unsubscribe: () => {
1168
+ _observers = _observers.filter((o) => o !== observer);
1169
+ },
1170
+ };
1171
+ };
1172
+ const unsubscribe = () => {
1173
+ _observers = [];
1174
+ };
1175
+ return {
1176
+ get observers() {
1177
+ return _observers;
1178
+ },
1179
+ next,
1180
+ subscribe,
1181
+ unsubscribe,
1182
+ };
1183
1183
  }
1184
1184
 
1185
1185
  var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
1186
1186
 
1187
- function deepEqual(object1, object2) {
1188
- if (isPrimitive(object1) || isPrimitive(object2)) {
1189
- return object1 === object2;
1190
- }
1191
- if (isDateObject(object1) && isDateObject(object2)) {
1192
- return object1.getTime() === object2.getTime();
1193
- }
1194
- const keys1 = Object.keys(object1);
1195
- const keys2 = Object.keys(object2);
1196
- if (keys1.length !== keys2.length) {
1197
- return false;
1198
- }
1199
- for (const key of keys1) {
1200
- const val1 = object1[key];
1201
- if (!keys2.includes(key)) {
1202
- return false;
1203
- }
1204
- if (key !== 'ref') {
1205
- const val2 = object2[key];
1206
- if ((isDateObject(val1) && isDateObject(val2)) ||
1207
- (isObject(val1) && isObject(val2)) ||
1208
- (Array.isArray(val1) && Array.isArray(val2))
1209
- ? !deepEqual(val1, val2)
1210
- : val1 !== val2) {
1211
- return false;
1212
- }
1213
- }
1214
- }
1215
- return true;
1187
+ function deepEqual(object1, object2) {
1188
+ if (isPrimitive(object1) || isPrimitive(object2)) {
1189
+ return object1 === object2;
1190
+ }
1191
+ if (isDateObject(object1) && isDateObject(object2)) {
1192
+ return object1.getTime() === object2.getTime();
1193
+ }
1194
+ const keys1 = Object.keys(object1);
1195
+ const keys2 = Object.keys(object2);
1196
+ if (keys1.length !== keys2.length) {
1197
+ return false;
1198
+ }
1199
+ for (const key of keys1) {
1200
+ const val1 = object1[key];
1201
+ if (!keys2.includes(key)) {
1202
+ return false;
1203
+ }
1204
+ if (key !== 'ref') {
1205
+ const val2 = object2[key];
1206
+ if ((isDateObject(val1) && isDateObject(val2)) ||
1207
+ (isObject(val1) && isObject(val2)) ||
1208
+ (Array.isArray(val1) && Array.isArray(val2))
1209
+ ? !deepEqual(val1, val2)
1210
+ : val1 !== val2) {
1211
+ return false;
1212
+ }
1213
+ }
1214
+ }
1215
+ return true;
1216
1216
  }
1217
1217
 
1218
1218
  var isMultipleSelect = (element) => element.type === `select-multiple`;
@@ -1221,1111 +1221,1111 @@ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
1221
1221
 
1222
1222
  var live = (ref) => isHTMLElement(ref) && ref.isConnected;
1223
1223
 
1224
- var objectHasFunction = (data) => {
1225
- for (const key in data) {
1226
- if (isFunction(data[key])) {
1227
- return true;
1228
- }
1229
- }
1230
- return false;
1224
+ var objectHasFunction = (data) => {
1225
+ for (const key in data) {
1226
+ if (isFunction(data[key])) {
1227
+ return true;
1228
+ }
1229
+ }
1230
+ return false;
1231
1231
  };
1232
1232
 
1233
- function markFieldsDirty(data, fields = {}) {
1234
- const isParentNodeArray = Array.isArray(data);
1235
- if (isObject(data) || isParentNodeArray) {
1236
- for (const key in data) {
1237
- if (Array.isArray(data[key]) ||
1238
- (isObject(data[key]) && !objectHasFunction(data[key]))) {
1239
- fields[key] = Array.isArray(data[key]) ? [] : {};
1240
- markFieldsDirty(data[key], fields[key]);
1241
- }
1242
- else if (!isNullOrUndefined(data[key])) {
1243
- fields[key] = true;
1244
- }
1245
- }
1246
- }
1247
- return fields;
1248
- }
1249
- function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
1250
- const isParentNodeArray = Array.isArray(data);
1251
- if (isObject(data) || isParentNodeArray) {
1252
- for (const key in data) {
1253
- if (Array.isArray(data[key]) ||
1254
- (isObject(data[key]) && !objectHasFunction(data[key]))) {
1255
- if (isUndefined(formValues) ||
1256
- isPrimitive(dirtyFieldsFromValues[key])) {
1257
- dirtyFieldsFromValues[key] = Array.isArray(data[key])
1258
- ? markFieldsDirty(data[key], [])
1259
- : { ...markFieldsDirty(data[key]) };
1260
- }
1261
- else {
1262
- getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1263
- }
1264
- }
1265
- else {
1266
- dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
1267
- }
1268
- }
1269
- }
1270
- return dirtyFieldsFromValues;
1271
- }
1233
+ function markFieldsDirty(data, fields = {}) {
1234
+ const isParentNodeArray = Array.isArray(data);
1235
+ if (isObject(data) || isParentNodeArray) {
1236
+ for (const key in data) {
1237
+ if (Array.isArray(data[key]) ||
1238
+ (isObject(data[key]) && !objectHasFunction(data[key]))) {
1239
+ fields[key] = Array.isArray(data[key]) ? [] : {};
1240
+ markFieldsDirty(data[key], fields[key]);
1241
+ }
1242
+ else if (!isNullOrUndefined(data[key])) {
1243
+ fields[key] = true;
1244
+ }
1245
+ }
1246
+ }
1247
+ return fields;
1248
+ }
1249
+ function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
1250
+ const isParentNodeArray = Array.isArray(data);
1251
+ if (isObject(data) || isParentNodeArray) {
1252
+ for (const key in data) {
1253
+ if (Array.isArray(data[key]) ||
1254
+ (isObject(data[key]) && !objectHasFunction(data[key]))) {
1255
+ if (isUndefined(formValues) ||
1256
+ isPrimitive(dirtyFieldsFromValues[key])) {
1257
+ dirtyFieldsFromValues[key] = Array.isArray(data[key])
1258
+ ? markFieldsDirty(data[key], [])
1259
+ : { ...markFieldsDirty(data[key]) };
1260
+ }
1261
+ else {
1262
+ getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1263
+ }
1264
+ }
1265
+ else {
1266
+ dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
1267
+ }
1268
+ }
1269
+ }
1270
+ return dirtyFieldsFromValues;
1271
+ }
1272
1272
  var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
1273
1273
 
1274
- var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
1275
- ? value
1276
- : valueAsNumber
1277
- ? value === ''
1278
- ? NaN
1279
- : value
1280
- ? +value
1281
- : value
1282
- : valueAsDate && isString(value)
1283
- ? new Date(value)
1284
- : setValueAs
1285
- ? setValueAs(value)
1274
+ var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
1275
+ ? value
1276
+ : valueAsNumber
1277
+ ? value === ''
1278
+ ? NaN
1279
+ : value
1280
+ ? +value
1281
+ : value
1282
+ : valueAsDate && isString(value)
1283
+ ? new Date(value)
1284
+ : setValueAs
1285
+ ? setValueAs(value)
1286
1286
  : value;
1287
1287
 
1288
- function getFieldValue(_f) {
1289
- const ref = _f.ref;
1290
- if (_f.refs ? _f.refs.every((ref) => ref.disabled) : ref.disabled) {
1291
- return;
1292
- }
1293
- if (isFileInput(ref)) {
1294
- return ref.files;
1295
- }
1296
- if (isRadioInput(ref)) {
1297
- return getRadioValue(_f.refs).value;
1298
- }
1299
- if (isMultipleSelect(ref)) {
1300
- return [...ref.selectedOptions].map(({ value }) => value);
1301
- }
1302
- if (isCheckBoxInput(ref)) {
1303
- return getCheckboxValue(_f.refs).value;
1304
- }
1305
- return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1288
+ function getFieldValue(_f) {
1289
+ const ref = _f.ref;
1290
+ if (_f.refs ? _f.refs.every((ref) => ref.disabled) : ref.disabled) {
1291
+ return;
1292
+ }
1293
+ if (isFileInput(ref)) {
1294
+ return ref.files;
1295
+ }
1296
+ if (isRadioInput(ref)) {
1297
+ return getRadioValue(_f.refs).value;
1298
+ }
1299
+ if (isMultipleSelect(ref)) {
1300
+ return [...ref.selectedOptions].map(({ value }) => value);
1301
+ }
1302
+ if (isCheckBoxInput(ref)) {
1303
+ return getCheckboxValue(_f.refs).value;
1304
+ }
1305
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1306
1306
  }
1307
1307
 
1308
- var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1309
- const fields = {};
1310
- for (const name of fieldsNames) {
1311
- const field = get(_fields, name);
1312
- field && set(fields, name, field._f);
1313
- }
1314
- return {
1315
- criteriaMode,
1316
- names: [...fieldsNames],
1317
- fields,
1318
- shouldUseNativeValidation,
1319
- };
1308
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1309
+ const fields = {};
1310
+ for (const name of fieldsNames) {
1311
+ const field = get(_fields, name);
1312
+ field && set(fields, name, field._f);
1313
+ }
1314
+ return {
1315
+ criteriaMode,
1316
+ names: [...fieldsNames],
1317
+ fields,
1318
+ shouldUseNativeValidation,
1319
+ };
1320
1320
  };
1321
1321
 
1322
- var getRuleValue = (rule) => isUndefined(rule)
1323
- ? rule
1324
- : isRegex(rule)
1325
- ? rule.source
1326
- : isObject(rule)
1327
- ? isRegex(rule.value)
1328
- ? rule.value.source
1329
- : rule.value
1322
+ var getRuleValue = (rule) => isUndefined(rule)
1323
+ ? rule
1324
+ : isRegex(rule)
1325
+ ? rule.source
1326
+ : isObject(rule)
1327
+ ? isRegex(rule.value)
1328
+ ? rule.value.source
1329
+ : rule.value
1330
1330
  : rule;
1331
1331
 
1332
- var hasValidation = (options) => options.mount &&
1333
- (options.required ||
1334
- options.min ||
1335
- options.max ||
1336
- options.maxLength ||
1337
- options.minLength ||
1338
- options.pattern ||
1332
+ var hasValidation = (options) => options.mount &&
1333
+ (options.required ||
1334
+ options.min ||
1335
+ options.max ||
1336
+ options.maxLength ||
1337
+ options.minLength ||
1338
+ options.pattern ||
1339
1339
  options.validate);
1340
1340
 
1341
- function schemaErrorLookup(errors, _fields, name) {
1342
- const error = get(errors, name);
1343
- if (error || isKey(name)) {
1344
- return {
1345
- error,
1346
- name,
1347
- };
1348
- }
1349
- const names = name.split('.');
1350
- while (names.length) {
1351
- const fieldName = names.join('.');
1352
- const field = get(_fields, fieldName);
1353
- const foundError = get(errors, fieldName);
1354
- if (field && !Array.isArray(field) && name !== fieldName) {
1355
- return { name };
1356
- }
1357
- if (foundError && foundError.type) {
1358
- return {
1359
- name: fieldName,
1360
- error: foundError,
1361
- };
1362
- }
1363
- names.pop();
1364
- }
1365
- return {
1366
- name,
1367
- };
1341
+ function schemaErrorLookup(errors, _fields, name) {
1342
+ const error = get(errors, name);
1343
+ if (error || isKey(name)) {
1344
+ return {
1345
+ error,
1346
+ name,
1347
+ };
1348
+ }
1349
+ const names = name.split('.');
1350
+ while (names.length) {
1351
+ const fieldName = names.join('.');
1352
+ const field = get(_fields, fieldName);
1353
+ const foundError = get(errors, fieldName);
1354
+ if (field && !Array.isArray(field) && name !== fieldName) {
1355
+ return { name };
1356
+ }
1357
+ if (foundError && foundError.type) {
1358
+ return {
1359
+ name: fieldName,
1360
+ error: foundError,
1361
+ };
1362
+ }
1363
+ names.pop();
1364
+ }
1365
+ return {
1366
+ name,
1367
+ };
1368
1368
  }
1369
1369
 
1370
- var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1371
- if (mode.isOnAll) {
1372
- return false;
1373
- }
1374
- else if (!isSubmitted && mode.isOnTouch) {
1375
- return !(isTouched || isBlurEvent);
1376
- }
1377
- else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
1378
- return !isBlurEvent;
1379
- }
1380
- else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
1381
- return isBlurEvent;
1382
- }
1383
- return true;
1370
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1371
+ if (mode.isOnAll) {
1372
+ return false;
1373
+ }
1374
+ else if (!isSubmitted && mode.isOnTouch) {
1375
+ return !(isTouched || isBlurEvent);
1376
+ }
1377
+ else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
1378
+ return !isBlurEvent;
1379
+ }
1380
+ else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
1381
+ return isBlurEvent;
1382
+ }
1383
+ return true;
1384
1384
  };
1385
1385
 
1386
1386
  var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
1387
1387
 
1388
- const defaultOptions = {
1389
- mode: VALIDATION_MODE.onSubmit,
1390
- reValidateMode: VALIDATION_MODE.onChange,
1391
- shouldFocusError: true,
1392
- };
1393
- function createFormControl(props = {}, flushRootRender) {
1394
- let _options = {
1395
- ...defaultOptions,
1396
- ...props,
1397
- };
1398
- let _formState = {
1399
- submitCount: 0,
1400
- isDirty: false,
1401
- isLoading: isFunction(_options.defaultValues),
1402
- isValidating: false,
1403
- isSubmitted: false,
1404
- isSubmitting: false,
1405
- isSubmitSuccessful: false,
1406
- isValid: false,
1407
- touchedFields: {},
1408
- dirtyFields: {},
1409
- errors: {},
1410
- };
1411
- let _fields = {};
1412
- let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
1413
- ? cloneObject(_options.defaultValues || _options.values) || {}
1414
- : {};
1415
- let _formValues = _options.shouldUnregister
1416
- ? {}
1417
- : cloneObject(_defaultValues);
1418
- let _state = {
1419
- action: false,
1420
- mount: false,
1421
- watch: false,
1422
- };
1423
- let _names = {
1424
- mount: new Set(),
1425
- unMount: new Set(),
1426
- array: new Set(),
1427
- watch: new Set(),
1428
- };
1429
- let delayErrorCallback;
1430
- let timer = 0;
1431
- const _proxyFormState = {
1432
- isDirty: false,
1433
- dirtyFields: false,
1434
- touchedFields: false,
1435
- isValidating: false,
1436
- isValid: false,
1437
- errors: false,
1438
- };
1439
- const _subjects = {
1440
- values: createSubject(),
1441
- array: createSubject(),
1442
- state: createSubject(),
1443
- };
1444
- const shouldCaptureDirtyFields = props.resetOptions && props.resetOptions.keepDirtyValues;
1445
- const validationModeBeforeSubmit = getValidationModes(_options.mode);
1446
- const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
1447
- const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1448
- const debounce = (callback) => (wait) => {
1449
- clearTimeout(timer);
1450
- timer = setTimeout(callback, wait);
1451
- };
1452
- const _updateValid = async (shouldUpdateValid) => {
1453
- if (_proxyFormState.isValid || shouldUpdateValid) {
1454
- const isValid = _options.resolver
1455
- ? isEmptyObject((await _executeSchema()).errors)
1456
- : await executeBuiltInValidation(_fields, true);
1457
- if (isValid !== _formState.isValid) {
1458
- _subjects.state.next({
1459
- isValid,
1460
- });
1461
- }
1462
- }
1463
- };
1464
- const _updateIsValidating = (value) => _proxyFormState.isValidating &&
1465
- _subjects.state.next({
1466
- isValidating: value,
1467
- });
1468
- const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1469
- if (args && method) {
1470
- _state.action = true;
1471
- if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1472
- const fieldValues = method(get(_fields, name), args.argA, args.argB);
1473
- shouldSetValues && set(_fields, name, fieldValues);
1474
- }
1475
- if (shouldUpdateFieldsAndState &&
1476
- Array.isArray(get(_formState.errors, name))) {
1477
- const errors = method(get(_formState.errors, name), args.argA, args.argB);
1478
- shouldSetValues && set(_formState.errors, name, errors);
1479
- unsetEmptyArray(_formState.errors, name);
1480
- }
1481
- if (_proxyFormState.touchedFields &&
1482
- shouldUpdateFieldsAndState &&
1483
- Array.isArray(get(_formState.touchedFields, name))) {
1484
- const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1485
- shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1486
- }
1487
- if (_proxyFormState.dirtyFields) {
1488
- _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1489
- }
1490
- _subjects.state.next({
1491
- name,
1492
- isDirty: _getDirty(name, values),
1493
- dirtyFields: _formState.dirtyFields,
1494
- errors: _formState.errors,
1495
- isValid: _formState.isValid,
1496
- });
1497
- }
1498
- else {
1499
- set(_formValues, name, values);
1500
- }
1501
- };
1502
- const updateErrors = (name, error) => {
1503
- set(_formState.errors, name, error);
1504
- _subjects.state.next({
1505
- errors: _formState.errors,
1506
- });
1507
- };
1508
- const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1509
- const field = get(_fields, name);
1510
- if (field) {
1511
- const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1512
- isUndefined(defaultValue) ||
1513
- (ref && ref.defaultChecked) ||
1514
- shouldSkipSetValueAs
1515
- ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
1516
- : setFieldValue(name, defaultValue);
1517
- _state.mount && _updateValid();
1518
- }
1519
- };
1520
- const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1521
- let shouldUpdateField = false;
1522
- let isPreviousDirty = false;
1523
- const output = {
1524
- name,
1525
- };
1526
- if (!isBlurEvent || shouldDirty) {
1527
- if (_proxyFormState.isDirty) {
1528
- isPreviousDirty = _formState.isDirty;
1529
- _formState.isDirty = output.isDirty = _getDirty();
1530
- shouldUpdateField = isPreviousDirty !== output.isDirty;
1531
- }
1532
- const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
1533
- isPreviousDirty = get(_formState.dirtyFields, name);
1534
- isCurrentFieldPristine
1535
- ? unset(_formState.dirtyFields, name)
1536
- : set(_formState.dirtyFields, name, true);
1537
- output.dirtyFields = _formState.dirtyFields;
1538
- shouldUpdateField =
1539
- shouldUpdateField ||
1540
- (_proxyFormState.dirtyFields &&
1541
- isPreviousDirty !== !isCurrentFieldPristine);
1542
- }
1543
- if (isBlurEvent) {
1544
- const isPreviousFieldTouched = get(_formState.touchedFields, name);
1545
- if (!isPreviousFieldTouched) {
1546
- set(_formState.touchedFields, name, isBlurEvent);
1547
- output.touchedFields = _formState.touchedFields;
1548
- shouldUpdateField =
1549
- shouldUpdateField ||
1550
- (_proxyFormState.touchedFields &&
1551
- isPreviousFieldTouched !== isBlurEvent);
1552
- }
1553
- }
1554
- shouldUpdateField && shouldRender && _subjects.state.next(output);
1555
- return shouldUpdateField ? output : {};
1556
- };
1557
- const shouldRenderByError = (name, isValid, error, fieldState) => {
1558
- const previousFieldError = get(_formState.errors, name);
1559
- const shouldUpdateValid = _proxyFormState.isValid &&
1560
- isBoolean(isValid) &&
1561
- _formState.isValid !== isValid;
1562
- if (props.delayError && error) {
1563
- delayErrorCallback = debounce(() => updateErrors(name, error));
1564
- delayErrorCallback(props.delayError);
1565
- }
1566
- else {
1567
- clearTimeout(timer);
1568
- delayErrorCallback = null;
1569
- error
1570
- ? set(_formState.errors, name, error)
1571
- : unset(_formState.errors, name);
1572
- }
1573
- if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
1574
- !isEmptyObject(fieldState) ||
1575
- shouldUpdateValid) {
1576
- const updatedFormState = {
1577
- ...fieldState,
1578
- ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
1579
- errors: _formState.errors,
1580
- name,
1581
- };
1582
- _formState = {
1583
- ..._formState,
1584
- ...updatedFormState,
1585
- };
1586
- _subjects.state.next(updatedFormState);
1587
- }
1588
- _updateIsValidating(false);
1589
- };
1590
- const _executeSchema = async (name) => _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1591
- const executeSchemaAndUpdateState = async (names) => {
1592
- const { errors } = await _executeSchema();
1593
- if (names) {
1594
- for (const name of names) {
1595
- const error = get(errors, name);
1596
- error
1597
- ? set(_formState.errors, name, error)
1598
- : unset(_formState.errors, name);
1599
- }
1600
- }
1601
- else {
1602
- _formState.errors = errors;
1603
- }
1604
- return errors;
1605
- };
1606
- const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
1607
- valid: true,
1608
- }) => {
1609
- for (const name in fields) {
1610
- const field = fields[name];
1611
- if (field) {
1612
- const { _f, ...fieldValue } = field;
1613
- if (_f) {
1614
- const isFieldArrayRoot = _names.array.has(_f.name);
1615
- const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
1616
- if (fieldError[_f.name]) {
1617
- context.valid = false;
1618
- if (shouldOnlyCheckValid) {
1619
- break;
1620
- }
1621
- }
1622
- !shouldOnlyCheckValid &&
1623
- (get(fieldError, _f.name)
1624
- ? isFieldArrayRoot
1625
- ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
1626
- : set(_formState.errors, _f.name, fieldError[_f.name])
1627
- : unset(_formState.errors, _f.name));
1628
- }
1629
- fieldValue &&
1630
- (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
1631
- }
1632
- }
1633
- return context.valid;
1634
- };
1635
- const _removeUnmounted = () => {
1636
- for (const name of _names.unMount) {
1637
- const field = get(_fields, name);
1638
- field &&
1639
- (field._f.refs
1640
- ? field._f.refs.every((ref) => !live(ref))
1641
- : !live(field._f.ref)) &&
1642
- unregister(name);
1643
- }
1644
- _names.unMount = new Set();
1645
- };
1646
- const _getDirty = (name, data) => (name && data && set(_formValues, name, data),
1647
- !deepEqual(getValues(), _defaultValues));
1648
- const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1649
- ...(_state.mount
1650
- ? _formValues
1651
- : isUndefined(defaultValue)
1652
- ? _defaultValues
1653
- : isString(names)
1654
- ? { [names]: defaultValue }
1655
- : defaultValue),
1656
- }, isGlobal, defaultValue);
1657
- const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
1658
- const setFieldValue = (name, value, options = {}) => {
1659
- const field = get(_fields, name);
1660
- let fieldValue = value;
1661
- if (field) {
1662
- const fieldReference = field._f;
1663
- if (fieldReference) {
1664
- !fieldReference.disabled &&
1665
- set(_formValues, name, getFieldValueAs(value, fieldReference));
1666
- fieldValue =
1667
- isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
1668
- ? ''
1669
- : value;
1670
- if (isMultipleSelect(fieldReference.ref)) {
1671
- [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
1672
- }
1673
- else if (fieldReference.refs) {
1674
- if (isCheckBoxInput(fieldReference.ref)) {
1675
- fieldReference.refs.length > 1
1676
- ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&
1677
- (checkboxRef.checked = Array.isArray(fieldValue)
1678
- ? !!fieldValue.find((data) => data === checkboxRef.value)
1679
- : fieldValue === checkboxRef.value))
1680
- : fieldReference.refs[0] &&
1681
- (fieldReference.refs[0].checked = !!fieldValue);
1682
- }
1683
- else {
1684
- fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
1685
- }
1686
- }
1687
- else if (isFileInput(fieldReference.ref)) {
1688
- fieldReference.ref.value = '';
1689
- }
1690
- else {
1691
- fieldReference.ref.value = fieldValue;
1692
- if (!fieldReference.ref.type) {
1693
- _subjects.values.next({
1694
- name,
1695
- values: { ..._formValues },
1696
- });
1697
- }
1698
- }
1699
- }
1700
- }
1701
- (options.shouldDirty || options.shouldTouch) &&
1702
- updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
1703
- options.shouldValidate && trigger(name);
1704
- };
1705
- const setValues = (name, value, options) => {
1706
- for (const fieldKey in value) {
1707
- const fieldValue = value[fieldKey];
1708
- const fieldName = `${name}.${fieldKey}`;
1709
- const field = get(_fields, fieldName);
1710
- (_names.array.has(name) ||
1711
- !isPrimitive(fieldValue) ||
1712
- (field && !field._f)) &&
1713
- !isDateObject(fieldValue)
1714
- ? setValues(fieldName, fieldValue, options)
1715
- : setFieldValue(fieldName, fieldValue, options);
1716
- }
1717
- };
1718
- const setValue = (name, value, options = {}) => {
1719
- const field = get(_fields, name);
1720
- const isFieldArray = _names.array.has(name);
1721
- const cloneValue = cloneObject(value);
1722
- set(_formValues, name, cloneValue);
1723
- if (isFieldArray) {
1724
- _subjects.array.next({
1725
- name,
1726
- values: { ..._formValues },
1727
- });
1728
- if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
1729
- options.shouldDirty) {
1730
- _subjects.state.next({
1731
- name,
1732
- dirtyFields: getDirtyFields(_defaultValues, _formValues),
1733
- isDirty: _getDirty(name, cloneValue),
1734
- });
1735
- }
1736
- }
1737
- else {
1738
- field && !field._f && !isNullOrUndefined(cloneValue)
1739
- ? setValues(name, cloneValue, options)
1740
- : setFieldValue(name, cloneValue, options);
1741
- }
1742
- isWatched(name, _names) && _subjects.state.next({ ..._formState });
1743
- _subjects.values.next({
1744
- name,
1745
- values: { ..._formValues },
1746
- });
1747
- !_state.mount && flushRootRender();
1748
- };
1749
- const onChange = async (event) => {
1750
- const target = event.target;
1751
- let name = target.name;
1752
- let isFieldValueUpdated = true;
1753
- const field = get(_fields, name);
1754
- const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
1755
- if (field) {
1756
- let error;
1757
- let isValid;
1758
- const fieldValue = getCurrentFieldValue();
1759
- const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1760
- const shouldSkipValidation = (!hasValidation(field._f) &&
1761
- !_options.resolver &&
1762
- !get(_formState.errors, name) &&
1763
- !field._f.deps) ||
1764
- skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1765
- const watched = isWatched(name, _names, isBlurEvent);
1766
- set(_formValues, name, fieldValue);
1767
- if (isBlurEvent) {
1768
- field._f.onBlur && field._f.onBlur(event);
1769
- delayErrorCallback && delayErrorCallback(0);
1770
- }
1771
- else if (field._f.onChange) {
1772
- field._f.onChange(event);
1773
- }
1774
- const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
1775
- const shouldRender = !isEmptyObject(fieldState) || watched;
1776
- !isBlurEvent &&
1777
- _subjects.values.next({
1778
- name,
1779
- type: event.type,
1780
- values: { ..._formValues },
1781
- });
1782
- if (shouldSkipValidation) {
1783
- _proxyFormState.isValid && _updateValid();
1784
- return (shouldRender &&
1785
- _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
1786
- }
1787
- !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1788
- _updateIsValidating(true);
1789
- if (_options.resolver) {
1790
- const { errors } = await _executeSchema([name]);
1791
- const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1792
- const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1793
- error = errorLookupResult.error;
1794
- name = errorLookupResult.name;
1795
- isValid = isEmptyObject(errors);
1796
- }
1797
- else {
1798
- error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1799
- isFieldValueUpdated = fieldValue === get(_formValues, name, fieldValue);
1800
- if (isFieldValueUpdated) {
1801
- if (error) {
1802
- isValid = false;
1803
- }
1804
- else if (_proxyFormState.isValid) {
1805
- isValid = await executeBuiltInValidation(_fields, true);
1806
- }
1807
- }
1808
- }
1809
- if (isFieldValueUpdated) {
1810
- field._f.deps &&
1811
- trigger(field._f.deps);
1812
- shouldRenderByError(name, isValid, error, fieldState);
1813
- }
1814
- }
1815
- };
1816
- const trigger = async (name, options = {}) => {
1817
- let isValid;
1818
- let validationResult;
1819
- const fieldNames = convertToArrayPayload(name);
1820
- _updateIsValidating(true);
1821
- if (_options.resolver) {
1822
- const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1823
- isValid = isEmptyObject(errors);
1824
- validationResult = name
1825
- ? !fieldNames.some((name) => get(errors, name))
1826
- : isValid;
1827
- }
1828
- else if (name) {
1829
- validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1830
- const field = get(_fields, fieldName);
1831
- return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1832
- }))).every(Boolean);
1833
- !(!validationResult && !_formState.isValid) && _updateValid();
1834
- }
1835
- else {
1836
- validationResult = isValid = await executeBuiltInValidation(_fields);
1837
- }
1838
- _subjects.state.next({
1839
- ...(!isString(name) ||
1840
- (_proxyFormState.isValid && isValid !== _formState.isValid)
1841
- ? {}
1842
- : { name }),
1843
- ...(_options.resolver || !name ? { isValid } : {}),
1844
- errors: _formState.errors,
1845
- isValidating: false,
1846
- });
1847
- options.shouldFocus &&
1848
- !validationResult &&
1849
- focusFieldBy(_fields, (key) => key && get(_formState.errors, key), name ? fieldNames : _names.mount);
1850
- return validationResult;
1851
- };
1852
- const getValues = (fieldNames) => {
1853
- const values = {
1854
- ..._defaultValues,
1855
- ...(_state.mount ? _formValues : {}),
1856
- };
1857
- return isUndefined(fieldNames)
1858
- ? values
1859
- : isString(fieldNames)
1860
- ? get(values, fieldNames)
1861
- : fieldNames.map((name) => get(values, name));
1862
- };
1863
- const getFieldState = (name, formState) => ({
1864
- invalid: !!get((formState || _formState).errors, name),
1865
- isDirty: !!get((formState || _formState).dirtyFields, name),
1866
- isTouched: !!get((formState || _formState).touchedFields, name),
1867
- error: get((formState || _formState).errors, name),
1868
- });
1869
- const clearErrors = (name) => {
1870
- name &&
1871
- convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1872
- _subjects.state.next({
1873
- errors: name ? _formState.errors : {},
1874
- });
1875
- };
1876
- const setError = (name, error, options) => {
1877
- const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1878
- set(_formState.errors, name, {
1879
- ...error,
1880
- ref,
1881
- });
1882
- _subjects.state.next({
1883
- name,
1884
- errors: _formState.errors,
1885
- isValid: false,
1886
- });
1887
- options && options.shouldFocus && ref && ref.focus && ref.focus();
1888
- };
1889
- const watch = (name, defaultValue) => isFunction(name)
1890
- ? _subjects.values.subscribe({
1891
- next: (payload) => name(_getWatch(undefined, defaultValue), payload),
1892
- })
1893
- : _getWatch(name, defaultValue, true);
1894
- const unregister = (name, options = {}) => {
1895
- for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1896
- _names.mount.delete(fieldName);
1897
- _names.array.delete(fieldName);
1898
- if (get(_fields, fieldName)) {
1899
- if (!options.keepValue) {
1900
- unset(_fields, fieldName);
1901
- unset(_formValues, fieldName);
1902
- }
1903
- !options.keepError && unset(_formState.errors, fieldName);
1904
- !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1905
- !options.keepTouched && unset(_formState.touchedFields, fieldName);
1906
- !_options.shouldUnregister &&
1907
- !options.keepDefaultValue &&
1908
- unset(_defaultValues, fieldName);
1909
- }
1910
- }
1911
- _subjects.values.next({
1912
- values: { ..._formValues },
1913
- });
1914
- _subjects.state.next({
1915
- ..._formState,
1916
- ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
1917
- });
1918
- !options.keepIsValid && _updateValid();
1919
- };
1920
- const register = (name, options = {}) => {
1921
- let field = get(_fields, name);
1922
- const disabledIsDefined = isBoolean(options.disabled);
1923
- set(_fields, name, {
1924
- ...(field || {}),
1925
- _f: {
1926
- ...(field && field._f ? field._f : { ref: { name } }),
1927
- name,
1928
- mount: true,
1929
- ...options,
1930
- },
1931
- });
1932
- _names.mount.add(name);
1933
- field
1934
- ? disabledIsDefined &&
1935
- set(_formValues, name, options.disabled
1936
- ? undefined
1937
- : get(_formValues, name, getFieldValue(field._f)))
1938
- : updateValidAndValue(name, true, options.value);
1939
- return {
1940
- ...(disabledIsDefined ? { disabled: options.disabled } : {}),
1941
- ...(_options.shouldUseNativeValidation
1942
- ? {
1943
- required: !!options.required,
1944
- min: getRuleValue(options.min),
1945
- max: getRuleValue(options.max),
1946
- minLength: getRuleValue(options.minLength),
1947
- maxLength: getRuleValue(options.maxLength),
1948
- pattern: getRuleValue(options.pattern),
1949
- }
1950
- : {}),
1951
- name,
1952
- onChange,
1953
- onBlur: onChange,
1954
- ref: (ref) => {
1955
- if (ref) {
1956
- register(name, options);
1957
- field = get(_fields, name);
1958
- const fieldRef = isUndefined(ref.value)
1959
- ? ref.querySelectorAll
1960
- ? ref.querySelectorAll('input,select,textarea')[0] || ref
1961
- : ref
1962
- : ref;
1963
- const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1964
- const refs = field._f.refs || [];
1965
- if (radioOrCheckbox
1966
- ? refs.find((option) => option === fieldRef)
1967
- : fieldRef === field._f.ref) {
1968
- return;
1969
- }
1970
- set(_fields, name, {
1971
- _f: {
1972
- ...field._f,
1973
- ...(radioOrCheckbox
1974
- ? {
1975
- refs: [
1976
- ...refs.filter(live),
1977
- fieldRef,
1978
- ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
1979
- ],
1980
- ref: { type: fieldRef.type, name },
1981
- }
1982
- : { ref: fieldRef }),
1983
- },
1984
- });
1985
- updateValidAndValue(name, false, undefined, fieldRef);
1986
- }
1987
- else {
1988
- field = get(_fields, name, {});
1989
- if (field._f) {
1990
- field._f.mount = false;
1991
- }
1992
- (_options.shouldUnregister || options.shouldUnregister) &&
1993
- !(isNameInFieldArray(_names.array, name) && _state.action) &&
1994
- _names.unMount.add(name);
1995
- }
1996
- },
1997
- };
1998
- };
1999
- const _focusError = () => _options.shouldFocusError &&
2000
- focusFieldBy(_fields, (key) => key && get(_formState.errors, key), _names.mount);
2001
- const handleSubmit = (onValid, onInvalid) => async (e) => {
2002
- if (e) {
2003
- e.preventDefault && e.preventDefault();
2004
- e.persist && e.persist();
2005
- }
2006
- let fieldValues = cloneObject(_formValues);
2007
- _subjects.state.next({
2008
- isSubmitting: true,
2009
- });
2010
- if (_options.resolver) {
2011
- const { errors, values } = await _executeSchema();
2012
- _formState.errors = errors;
2013
- fieldValues = values;
2014
- }
2015
- else {
2016
- await executeBuiltInValidation(_fields);
2017
- }
2018
- unset(_formState.errors, 'root');
2019
- if (isEmptyObject(_formState.errors)) {
2020
- _subjects.state.next({
2021
- errors: {},
2022
- });
2023
- await onValid(fieldValues, e);
2024
- }
2025
- else {
2026
- if (onInvalid) {
2027
- await onInvalid({ ..._formState.errors }, e);
2028
- }
2029
- _focusError();
2030
- setTimeout(_focusError);
2031
- }
2032
- _subjects.state.next({
2033
- isSubmitted: true,
2034
- isSubmitting: false,
2035
- isSubmitSuccessful: isEmptyObject(_formState.errors),
2036
- submitCount: _formState.submitCount + 1,
2037
- errors: _formState.errors,
2038
- });
2039
- };
2040
- const resetField = (name, options = {}) => {
2041
- if (get(_fields, name)) {
2042
- if (isUndefined(options.defaultValue)) {
2043
- setValue(name, get(_defaultValues, name));
2044
- }
2045
- else {
2046
- setValue(name, options.defaultValue);
2047
- set(_defaultValues, name, options.defaultValue);
2048
- }
2049
- if (!options.keepTouched) {
2050
- unset(_formState.touchedFields, name);
2051
- }
2052
- if (!options.keepDirty) {
2053
- unset(_formState.dirtyFields, name);
2054
- _formState.isDirty = options.defaultValue
2055
- ? _getDirty(name, get(_defaultValues, name))
2056
- : _getDirty();
2057
- }
2058
- if (!options.keepError) {
2059
- unset(_formState.errors, name);
2060
- _proxyFormState.isValid && _updateValid();
2061
- }
2062
- _subjects.state.next({ ..._formState });
2063
- }
2064
- };
2065
- const _reset = (formValues, keepStateOptions = {}) => {
2066
- const updatedValues = formValues || _defaultValues;
2067
- const cloneUpdatedValues = cloneObject(updatedValues);
2068
- const values = formValues && !isEmptyObject(formValues)
2069
- ? cloneUpdatedValues
2070
- : _defaultValues;
2071
- if (!keepStateOptions.keepDefaultValues) {
2072
- _defaultValues = updatedValues;
2073
- }
2074
- if (!keepStateOptions.keepValues) {
2075
- if (keepStateOptions.keepDirtyValues || shouldCaptureDirtyFields) {
2076
- for (const fieldName of _names.mount) {
2077
- get(_formState.dirtyFields, fieldName)
2078
- ? set(values, fieldName, get(_formValues, fieldName))
2079
- : setValue(fieldName, get(values, fieldName));
2080
- }
2081
- }
2082
- else {
2083
- if (isWeb && isUndefined(formValues)) {
2084
- for (const name of _names.mount) {
2085
- const field = get(_fields, name);
2086
- if (field && field._f) {
2087
- const fieldReference = Array.isArray(field._f.refs)
2088
- ? field._f.refs[0]
2089
- : field._f.ref;
2090
- if (isHTMLElement(fieldReference)) {
2091
- const form = fieldReference.closest('form');
2092
- if (form) {
2093
- form.reset();
2094
- break;
2095
- }
2096
- }
2097
- }
2098
- }
2099
- }
2100
- _fields = {};
2101
- }
2102
- _formValues = props.shouldUnregister
2103
- ? keepStateOptions.keepDefaultValues
2104
- ? cloneObject(_defaultValues)
2105
- : {}
2106
- : cloneUpdatedValues;
2107
- _subjects.array.next({
2108
- values: { ...values },
2109
- });
2110
- _subjects.values.next({
2111
- values: { ...values },
2112
- });
2113
- }
2114
- _names = {
2115
- mount: new Set(),
2116
- unMount: new Set(),
2117
- array: new Set(),
2118
- watch: new Set(),
2119
- watchAll: false,
2120
- focus: '',
2121
- };
2122
- !_state.mount && flushRootRender();
2123
- _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
2124
- _state.watch = !!props.shouldUnregister;
2125
- _subjects.state.next({
2126
- submitCount: keepStateOptions.keepSubmitCount
2127
- ? _formState.submitCount
2128
- : 0,
2129
- isDirty: keepStateOptions.keepDirty
2130
- ? _formState.isDirty
2131
- : !!(keepStateOptions.keepDefaultValues &&
2132
- !deepEqual(formValues, _defaultValues)),
2133
- isSubmitted: keepStateOptions.keepIsSubmitted
2134
- ? _formState.isSubmitted
2135
- : false,
2136
- dirtyFields: keepStateOptions.keepDirtyValues
2137
- ? _formState.dirtyFields
2138
- : keepStateOptions.keepDefaultValues && formValues
2139
- ? getDirtyFields(_defaultValues, formValues)
2140
- : {},
2141
- touchedFields: keepStateOptions.keepTouched
2142
- ? _formState.touchedFields
2143
- : {},
2144
- errors: keepStateOptions.keepErrors ? _formState.errors : {},
2145
- isSubmitting: false,
2146
- isSubmitSuccessful: false,
2147
- });
2148
- };
2149
- const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
2150
- ? formValues(_formValues)
2151
- : formValues, keepStateOptions);
2152
- const setFocus = (name, options = {}) => {
2153
- const field = get(_fields, name);
2154
- const fieldReference = field && field._f;
2155
- if (fieldReference) {
2156
- const fieldRef = fieldReference.refs
2157
- ? fieldReference.refs[0]
2158
- : fieldReference.ref;
2159
- if (fieldRef.focus) {
2160
- fieldRef.focus();
2161
- options.shouldSelect && fieldRef.select();
2162
- }
2163
- }
2164
- };
2165
- const _updateFormState = (updatedFormState) => {
2166
- _formState = {
2167
- ..._formState,
2168
- ...updatedFormState,
2169
- };
2170
- };
2171
- if (isFunction(_options.defaultValues)) {
2172
- _options.defaultValues().then((values) => {
2173
- reset(values, _options.resetOptions);
2174
- _subjects.state.next({
2175
- isLoading: false,
2176
- });
2177
- });
2178
- }
2179
- return {
2180
- control: {
2181
- register,
2182
- unregister,
2183
- getFieldState,
2184
- _executeSchema,
2185
- _getWatch,
2186
- _getDirty,
2187
- _updateValid,
2188
- _removeUnmounted,
2189
- _updateFieldArray,
2190
- _getFieldArray,
2191
- _reset,
2192
- _updateFormState,
2193
- _subjects,
2194
- _proxyFormState,
2195
- get _fields() {
2196
- return _fields;
2197
- },
2198
- get _formValues() {
2199
- return _formValues;
2200
- },
2201
- get _state() {
2202
- return _state;
2203
- },
2204
- set _state(value) {
2205
- _state = value;
2206
- },
2207
- get _defaultValues() {
2208
- return _defaultValues;
2209
- },
2210
- get _names() {
2211
- return _names;
2212
- },
2213
- set _names(value) {
2214
- _names = value;
2215
- },
2216
- get _formState() {
2217
- return _formState;
2218
- },
2219
- set _formState(value) {
2220
- _formState = value;
2221
- },
2222
- get _options() {
2223
- return _options;
2224
- },
2225
- set _options(value) {
2226
- _options = {
2227
- ..._options,
2228
- ...value,
2229
- };
2230
- },
2231
- },
2232
- trigger,
2233
- register,
2234
- handleSubmit,
2235
- watch,
2236
- setValue,
2237
- getValues,
2238
- reset,
2239
- resetField,
2240
- clearErrors,
2241
- unregister,
2242
- setError,
2243
- setFocus,
2244
- getFieldState,
2245
- };
1388
+ const defaultOptions = {
1389
+ mode: VALIDATION_MODE.onSubmit,
1390
+ reValidateMode: VALIDATION_MODE.onChange,
1391
+ shouldFocusError: true,
1392
+ };
1393
+ function createFormControl(props = {}, flushRootRender) {
1394
+ let _options = {
1395
+ ...defaultOptions,
1396
+ ...props,
1397
+ };
1398
+ let _formState = {
1399
+ submitCount: 0,
1400
+ isDirty: false,
1401
+ isLoading: isFunction(_options.defaultValues),
1402
+ isValidating: false,
1403
+ isSubmitted: false,
1404
+ isSubmitting: false,
1405
+ isSubmitSuccessful: false,
1406
+ isValid: false,
1407
+ touchedFields: {},
1408
+ dirtyFields: {},
1409
+ errors: {},
1410
+ };
1411
+ let _fields = {};
1412
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
1413
+ ? cloneObject(_options.defaultValues || _options.values) || {}
1414
+ : {};
1415
+ let _formValues = _options.shouldUnregister
1416
+ ? {}
1417
+ : cloneObject(_defaultValues);
1418
+ let _state = {
1419
+ action: false,
1420
+ mount: false,
1421
+ watch: false,
1422
+ };
1423
+ let _names = {
1424
+ mount: new Set(),
1425
+ unMount: new Set(),
1426
+ array: new Set(),
1427
+ watch: new Set(),
1428
+ };
1429
+ let delayErrorCallback;
1430
+ let timer = 0;
1431
+ const _proxyFormState = {
1432
+ isDirty: false,
1433
+ dirtyFields: false,
1434
+ touchedFields: false,
1435
+ isValidating: false,
1436
+ isValid: false,
1437
+ errors: false,
1438
+ };
1439
+ const _subjects = {
1440
+ values: createSubject(),
1441
+ array: createSubject(),
1442
+ state: createSubject(),
1443
+ };
1444
+ const shouldCaptureDirtyFields = props.resetOptions && props.resetOptions.keepDirtyValues;
1445
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
1446
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
1447
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1448
+ const debounce = (callback) => (wait) => {
1449
+ clearTimeout(timer);
1450
+ timer = setTimeout(callback, wait);
1451
+ };
1452
+ const _updateValid = async (shouldUpdateValid) => {
1453
+ if (_proxyFormState.isValid || shouldUpdateValid) {
1454
+ const isValid = _options.resolver
1455
+ ? isEmptyObject((await _executeSchema()).errors)
1456
+ : await executeBuiltInValidation(_fields, true);
1457
+ if (isValid !== _formState.isValid) {
1458
+ _subjects.state.next({
1459
+ isValid,
1460
+ });
1461
+ }
1462
+ }
1463
+ };
1464
+ const _updateIsValidating = (value) => _proxyFormState.isValidating &&
1465
+ _subjects.state.next({
1466
+ isValidating: value,
1467
+ });
1468
+ const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1469
+ if (args && method) {
1470
+ _state.action = true;
1471
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1472
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
1473
+ shouldSetValues && set(_fields, name, fieldValues);
1474
+ }
1475
+ if (shouldUpdateFieldsAndState &&
1476
+ Array.isArray(get(_formState.errors, name))) {
1477
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
1478
+ shouldSetValues && set(_formState.errors, name, errors);
1479
+ unsetEmptyArray(_formState.errors, name);
1480
+ }
1481
+ if (_proxyFormState.touchedFields &&
1482
+ shouldUpdateFieldsAndState &&
1483
+ Array.isArray(get(_formState.touchedFields, name))) {
1484
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1485
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1486
+ }
1487
+ if (_proxyFormState.dirtyFields) {
1488
+ _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1489
+ }
1490
+ _subjects.state.next({
1491
+ name,
1492
+ isDirty: _getDirty(name, values),
1493
+ dirtyFields: _formState.dirtyFields,
1494
+ errors: _formState.errors,
1495
+ isValid: _formState.isValid,
1496
+ });
1497
+ }
1498
+ else {
1499
+ set(_formValues, name, values);
1500
+ }
1501
+ };
1502
+ const updateErrors = (name, error) => {
1503
+ set(_formState.errors, name, error);
1504
+ _subjects.state.next({
1505
+ errors: _formState.errors,
1506
+ });
1507
+ };
1508
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1509
+ const field = get(_fields, name);
1510
+ if (field) {
1511
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1512
+ isUndefined(defaultValue) ||
1513
+ (ref && ref.defaultChecked) ||
1514
+ shouldSkipSetValueAs
1515
+ ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
1516
+ : setFieldValue(name, defaultValue);
1517
+ _state.mount && _updateValid();
1518
+ }
1519
+ };
1520
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1521
+ let shouldUpdateField = false;
1522
+ let isPreviousDirty = false;
1523
+ const output = {
1524
+ name,
1525
+ };
1526
+ if (!isBlurEvent || shouldDirty) {
1527
+ if (_proxyFormState.isDirty) {
1528
+ isPreviousDirty = _formState.isDirty;
1529
+ _formState.isDirty = output.isDirty = _getDirty();
1530
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
1531
+ }
1532
+ const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
1533
+ isPreviousDirty = get(_formState.dirtyFields, name);
1534
+ isCurrentFieldPristine
1535
+ ? unset(_formState.dirtyFields, name)
1536
+ : set(_formState.dirtyFields, name, true);
1537
+ output.dirtyFields = _formState.dirtyFields;
1538
+ shouldUpdateField =
1539
+ shouldUpdateField ||
1540
+ (_proxyFormState.dirtyFields &&
1541
+ isPreviousDirty !== !isCurrentFieldPristine);
1542
+ }
1543
+ if (isBlurEvent) {
1544
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
1545
+ if (!isPreviousFieldTouched) {
1546
+ set(_formState.touchedFields, name, isBlurEvent);
1547
+ output.touchedFields = _formState.touchedFields;
1548
+ shouldUpdateField =
1549
+ shouldUpdateField ||
1550
+ (_proxyFormState.touchedFields &&
1551
+ isPreviousFieldTouched !== isBlurEvent);
1552
+ }
1553
+ }
1554
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
1555
+ return shouldUpdateField ? output : {};
1556
+ };
1557
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
1558
+ const previousFieldError = get(_formState.errors, name);
1559
+ const shouldUpdateValid = _proxyFormState.isValid &&
1560
+ isBoolean(isValid) &&
1561
+ _formState.isValid !== isValid;
1562
+ if (props.delayError && error) {
1563
+ delayErrorCallback = debounce(() => updateErrors(name, error));
1564
+ delayErrorCallback(props.delayError);
1565
+ }
1566
+ else {
1567
+ clearTimeout(timer);
1568
+ delayErrorCallback = null;
1569
+ error
1570
+ ? set(_formState.errors, name, error)
1571
+ : unset(_formState.errors, name);
1572
+ }
1573
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
1574
+ !isEmptyObject(fieldState) ||
1575
+ shouldUpdateValid) {
1576
+ const updatedFormState = {
1577
+ ...fieldState,
1578
+ ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
1579
+ errors: _formState.errors,
1580
+ name,
1581
+ };
1582
+ _formState = {
1583
+ ..._formState,
1584
+ ...updatedFormState,
1585
+ };
1586
+ _subjects.state.next(updatedFormState);
1587
+ }
1588
+ _updateIsValidating(false);
1589
+ };
1590
+ const _executeSchema = async (name) => _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1591
+ const executeSchemaAndUpdateState = async (names) => {
1592
+ const { errors } = await _executeSchema();
1593
+ if (names) {
1594
+ for (const name of names) {
1595
+ const error = get(errors, name);
1596
+ error
1597
+ ? set(_formState.errors, name, error)
1598
+ : unset(_formState.errors, name);
1599
+ }
1600
+ }
1601
+ else {
1602
+ _formState.errors = errors;
1603
+ }
1604
+ return errors;
1605
+ };
1606
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
1607
+ valid: true,
1608
+ }) => {
1609
+ for (const name in fields) {
1610
+ const field = fields[name];
1611
+ if (field) {
1612
+ const { _f, ...fieldValue } = field;
1613
+ if (_f) {
1614
+ const isFieldArrayRoot = _names.array.has(_f.name);
1615
+ const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
1616
+ if (fieldError[_f.name]) {
1617
+ context.valid = false;
1618
+ if (shouldOnlyCheckValid) {
1619
+ break;
1620
+ }
1621
+ }
1622
+ !shouldOnlyCheckValid &&
1623
+ (get(fieldError, _f.name)
1624
+ ? isFieldArrayRoot
1625
+ ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
1626
+ : set(_formState.errors, _f.name, fieldError[_f.name])
1627
+ : unset(_formState.errors, _f.name));
1628
+ }
1629
+ fieldValue &&
1630
+ (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
1631
+ }
1632
+ }
1633
+ return context.valid;
1634
+ };
1635
+ const _removeUnmounted = () => {
1636
+ for (const name of _names.unMount) {
1637
+ const field = get(_fields, name);
1638
+ field &&
1639
+ (field._f.refs
1640
+ ? field._f.refs.every((ref) => !live(ref))
1641
+ : !live(field._f.ref)) &&
1642
+ unregister(name);
1643
+ }
1644
+ _names.unMount = new Set();
1645
+ };
1646
+ const _getDirty = (name, data) => (name && data && set(_formValues, name, data),
1647
+ !deepEqual(getValues(), _defaultValues));
1648
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1649
+ ...(_state.mount
1650
+ ? _formValues
1651
+ : isUndefined(defaultValue)
1652
+ ? _defaultValues
1653
+ : isString(names)
1654
+ ? { [names]: defaultValue }
1655
+ : defaultValue),
1656
+ }, isGlobal, defaultValue);
1657
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
1658
+ const setFieldValue = (name, value, options = {}) => {
1659
+ const field = get(_fields, name);
1660
+ let fieldValue = value;
1661
+ if (field) {
1662
+ const fieldReference = field._f;
1663
+ if (fieldReference) {
1664
+ !fieldReference.disabled &&
1665
+ set(_formValues, name, getFieldValueAs(value, fieldReference));
1666
+ fieldValue =
1667
+ isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
1668
+ ? ''
1669
+ : value;
1670
+ if (isMultipleSelect(fieldReference.ref)) {
1671
+ [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
1672
+ }
1673
+ else if (fieldReference.refs) {
1674
+ if (isCheckBoxInput(fieldReference.ref)) {
1675
+ fieldReference.refs.length > 1
1676
+ ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&
1677
+ (checkboxRef.checked = Array.isArray(fieldValue)
1678
+ ? !!fieldValue.find((data) => data === checkboxRef.value)
1679
+ : fieldValue === checkboxRef.value))
1680
+ : fieldReference.refs[0] &&
1681
+ (fieldReference.refs[0].checked = !!fieldValue);
1682
+ }
1683
+ else {
1684
+ fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
1685
+ }
1686
+ }
1687
+ else if (isFileInput(fieldReference.ref)) {
1688
+ fieldReference.ref.value = '';
1689
+ }
1690
+ else {
1691
+ fieldReference.ref.value = fieldValue;
1692
+ if (!fieldReference.ref.type) {
1693
+ _subjects.values.next({
1694
+ name,
1695
+ values: { ..._formValues },
1696
+ });
1697
+ }
1698
+ }
1699
+ }
1700
+ }
1701
+ (options.shouldDirty || options.shouldTouch) &&
1702
+ updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
1703
+ options.shouldValidate && trigger(name);
1704
+ };
1705
+ const setValues = (name, value, options) => {
1706
+ for (const fieldKey in value) {
1707
+ const fieldValue = value[fieldKey];
1708
+ const fieldName = `${name}.${fieldKey}`;
1709
+ const field = get(_fields, fieldName);
1710
+ (_names.array.has(name) ||
1711
+ !isPrimitive(fieldValue) ||
1712
+ (field && !field._f)) &&
1713
+ !isDateObject(fieldValue)
1714
+ ? setValues(fieldName, fieldValue, options)
1715
+ : setFieldValue(fieldName, fieldValue, options);
1716
+ }
1717
+ };
1718
+ const setValue = (name, value, options = {}) => {
1719
+ const field = get(_fields, name);
1720
+ const isFieldArray = _names.array.has(name);
1721
+ const cloneValue = cloneObject(value);
1722
+ set(_formValues, name, cloneValue);
1723
+ if (isFieldArray) {
1724
+ _subjects.array.next({
1725
+ name,
1726
+ values: { ..._formValues },
1727
+ });
1728
+ if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
1729
+ options.shouldDirty) {
1730
+ _subjects.state.next({
1731
+ name,
1732
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
1733
+ isDirty: _getDirty(name, cloneValue),
1734
+ });
1735
+ }
1736
+ }
1737
+ else {
1738
+ field && !field._f && !isNullOrUndefined(cloneValue)
1739
+ ? setValues(name, cloneValue, options)
1740
+ : setFieldValue(name, cloneValue, options);
1741
+ }
1742
+ isWatched(name, _names) && _subjects.state.next({ ..._formState });
1743
+ _subjects.values.next({
1744
+ name,
1745
+ values: { ..._formValues },
1746
+ });
1747
+ !_state.mount && flushRootRender();
1748
+ };
1749
+ const onChange = async (event) => {
1750
+ const target = event.target;
1751
+ let name = target.name;
1752
+ let isFieldValueUpdated = true;
1753
+ const field = get(_fields, name);
1754
+ const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
1755
+ if (field) {
1756
+ let error;
1757
+ let isValid;
1758
+ const fieldValue = getCurrentFieldValue();
1759
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1760
+ const shouldSkipValidation = (!hasValidation(field._f) &&
1761
+ !_options.resolver &&
1762
+ !get(_formState.errors, name) &&
1763
+ !field._f.deps) ||
1764
+ skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1765
+ const watched = isWatched(name, _names, isBlurEvent);
1766
+ set(_formValues, name, fieldValue);
1767
+ if (isBlurEvent) {
1768
+ field._f.onBlur && field._f.onBlur(event);
1769
+ delayErrorCallback && delayErrorCallback(0);
1770
+ }
1771
+ else if (field._f.onChange) {
1772
+ field._f.onChange(event);
1773
+ }
1774
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
1775
+ const shouldRender = !isEmptyObject(fieldState) || watched;
1776
+ !isBlurEvent &&
1777
+ _subjects.values.next({
1778
+ name,
1779
+ type: event.type,
1780
+ values: { ..._formValues },
1781
+ });
1782
+ if (shouldSkipValidation) {
1783
+ _proxyFormState.isValid && _updateValid();
1784
+ return (shouldRender &&
1785
+ _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
1786
+ }
1787
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1788
+ _updateIsValidating(true);
1789
+ if (_options.resolver) {
1790
+ const { errors } = await _executeSchema([name]);
1791
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1792
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1793
+ error = errorLookupResult.error;
1794
+ name = errorLookupResult.name;
1795
+ isValid = isEmptyObject(errors);
1796
+ }
1797
+ else {
1798
+ error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1799
+ isFieldValueUpdated =
1800
+ isNaN(fieldValue) ||
1801
+ fieldValue === get(_formValues, name, fieldValue);
1802
+ if (isFieldValueUpdated) {
1803
+ if (error) {
1804
+ isValid = false;
1805
+ }
1806
+ else if (_proxyFormState.isValid) {
1807
+ isValid = await executeBuiltInValidation(_fields, true);
1808
+ }
1809
+ }
1810
+ }
1811
+ if (isFieldValueUpdated) {
1812
+ field._f.deps &&
1813
+ trigger(field._f.deps);
1814
+ shouldRenderByError(name, isValid, error, fieldState);
1815
+ }
1816
+ }
1817
+ };
1818
+ const trigger = async (name, options = {}) => {
1819
+ let isValid;
1820
+ let validationResult;
1821
+ const fieldNames = convertToArrayPayload(name);
1822
+ _updateIsValidating(true);
1823
+ if (_options.resolver) {
1824
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1825
+ isValid = isEmptyObject(errors);
1826
+ validationResult = name
1827
+ ? !fieldNames.some((name) => get(errors, name))
1828
+ : isValid;
1829
+ }
1830
+ else if (name) {
1831
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1832
+ const field = get(_fields, fieldName);
1833
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1834
+ }))).every(Boolean);
1835
+ !(!validationResult && !_formState.isValid) && _updateValid();
1836
+ }
1837
+ else {
1838
+ validationResult = isValid = await executeBuiltInValidation(_fields);
1839
+ }
1840
+ _subjects.state.next({
1841
+ ...(!isString(name) ||
1842
+ (_proxyFormState.isValid && isValid !== _formState.isValid)
1843
+ ? {}
1844
+ : { name }),
1845
+ ...(_options.resolver || !name ? { isValid } : {}),
1846
+ errors: _formState.errors,
1847
+ isValidating: false,
1848
+ });
1849
+ options.shouldFocus &&
1850
+ !validationResult &&
1851
+ focusFieldBy(_fields, (key) => key && get(_formState.errors, key), name ? fieldNames : _names.mount);
1852
+ return validationResult;
1853
+ };
1854
+ const getValues = (fieldNames) => {
1855
+ const values = {
1856
+ ..._defaultValues,
1857
+ ...(_state.mount ? _formValues : {}),
1858
+ };
1859
+ return isUndefined(fieldNames)
1860
+ ? values
1861
+ : isString(fieldNames)
1862
+ ? get(values, fieldNames)
1863
+ : fieldNames.map((name) => get(values, name));
1864
+ };
1865
+ const getFieldState = (name, formState) => ({
1866
+ invalid: !!get((formState || _formState).errors, name),
1867
+ isDirty: !!get((formState || _formState).dirtyFields, name),
1868
+ isTouched: !!get((formState || _formState).touchedFields, name),
1869
+ error: get((formState || _formState).errors, name),
1870
+ });
1871
+ const clearErrors = (name) => {
1872
+ name &&
1873
+ convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1874
+ _subjects.state.next({
1875
+ errors: name ? _formState.errors : {},
1876
+ });
1877
+ };
1878
+ const setError = (name, error, options) => {
1879
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1880
+ set(_formState.errors, name, {
1881
+ ...error,
1882
+ ref,
1883
+ });
1884
+ _subjects.state.next({
1885
+ name,
1886
+ errors: _formState.errors,
1887
+ isValid: false,
1888
+ });
1889
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
1890
+ };
1891
+ const watch = (name, defaultValue) => isFunction(name)
1892
+ ? _subjects.values.subscribe({
1893
+ next: (payload) => name(_getWatch(undefined, defaultValue), payload),
1894
+ })
1895
+ : _getWatch(name, defaultValue, true);
1896
+ const unregister = (name, options = {}) => {
1897
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1898
+ _names.mount.delete(fieldName);
1899
+ _names.array.delete(fieldName);
1900
+ if (!options.keepValue) {
1901
+ unset(_fields, fieldName);
1902
+ unset(_formValues, fieldName);
1903
+ }
1904
+ !options.keepError && unset(_formState.errors, fieldName);
1905
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1906
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
1907
+ !_options.shouldUnregister &&
1908
+ !options.keepDefaultValue &&
1909
+ unset(_defaultValues, fieldName);
1910
+ }
1911
+ _subjects.values.next({
1912
+ values: { ..._formValues },
1913
+ });
1914
+ _subjects.state.next({
1915
+ ..._formState,
1916
+ ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
1917
+ });
1918
+ !options.keepIsValid && _updateValid();
1919
+ };
1920
+ const register = (name, options = {}) => {
1921
+ let field = get(_fields, name);
1922
+ const disabledIsDefined = isBoolean(options.disabled);
1923
+ set(_fields, name, {
1924
+ ...(field || {}),
1925
+ _f: {
1926
+ ...(field && field._f ? field._f : { ref: { name } }),
1927
+ name,
1928
+ mount: true,
1929
+ ...options,
1930
+ },
1931
+ });
1932
+ _names.mount.add(name);
1933
+ field
1934
+ ? disabledIsDefined &&
1935
+ set(_formValues, name, options.disabled
1936
+ ? undefined
1937
+ : get(_formValues, name, getFieldValue(field._f)))
1938
+ : updateValidAndValue(name, true, options.value);
1939
+ return {
1940
+ ...(disabledIsDefined ? { disabled: options.disabled } : {}),
1941
+ ...(_options.shouldUseNativeValidation
1942
+ ? {
1943
+ required: !!options.required,
1944
+ min: getRuleValue(options.min),
1945
+ max: getRuleValue(options.max),
1946
+ minLength: getRuleValue(options.minLength),
1947
+ maxLength: getRuleValue(options.maxLength),
1948
+ pattern: getRuleValue(options.pattern),
1949
+ }
1950
+ : {}),
1951
+ name,
1952
+ onChange,
1953
+ onBlur: onChange,
1954
+ ref: (ref) => {
1955
+ if (ref) {
1956
+ register(name, options);
1957
+ field = get(_fields, name);
1958
+ const fieldRef = isUndefined(ref.value)
1959
+ ? ref.querySelectorAll
1960
+ ? ref.querySelectorAll('input,select,textarea')[0] || ref
1961
+ : ref
1962
+ : ref;
1963
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1964
+ const refs = field._f.refs || [];
1965
+ if (radioOrCheckbox
1966
+ ? refs.find((option) => option === fieldRef)
1967
+ : fieldRef === field._f.ref) {
1968
+ return;
1969
+ }
1970
+ set(_fields, name, {
1971
+ _f: {
1972
+ ...field._f,
1973
+ ...(radioOrCheckbox
1974
+ ? {
1975
+ refs: [
1976
+ ...refs.filter(live),
1977
+ fieldRef,
1978
+ ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
1979
+ ],
1980
+ ref: { type: fieldRef.type, name },
1981
+ }
1982
+ : { ref: fieldRef }),
1983
+ },
1984
+ });
1985
+ updateValidAndValue(name, false, undefined, fieldRef);
1986
+ }
1987
+ else {
1988
+ field = get(_fields, name, {});
1989
+ if (field._f) {
1990
+ field._f.mount = false;
1991
+ }
1992
+ (_options.shouldUnregister || options.shouldUnregister) &&
1993
+ !(isNameInFieldArray(_names.array, name) && _state.action) &&
1994
+ _names.unMount.add(name);
1995
+ }
1996
+ },
1997
+ };
1998
+ };
1999
+ const _focusError = () => _options.shouldFocusError &&
2000
+ focusFieldBy(_fields, (key) => key && get(_formState.errors, key), _names.mount);
2001
+ const handleSubmit = (onValid, onInvalid) => async (e) => {
2002
+ if (e) {
2003
+ e.preventDefault && e.preventDefault();
2004
+ e.persist && e.persist();
2005
+ }
2006
+ let fieldValues = cloneObject(_formValues);
2007
+ _subjects.state.next({
2008
+ isSubmitting: true,
2009
+ });
2010
+ if (_options.resolver) {
2011
+ const { errors, values } = await _executeSchema();
2012
+ _formState.errors = errors;
2013
+ fieldValues = values;
2014
+ }
2015
+ else {
2016
+ await executeBuiltInValidation(_fields);
2017
+ }
2018
+ unset(_formState.errors, 'root');
2019
+ if (isEmptyObject(_formState.errors)) {
2020
+ _subjects.state.next({
2021
+ errors: {},
2022
+ });
2023
+ await onValid(fieldValues, e);
2024
+ }
2025
+ else {
2026
+ if (onInvalid) {
2027
+ await onInvalid({ ..._formState.errors }, e);
2028
+ }
2029
+ _focusError();
2030
+ setTimeout(_focusError);
2031
+ }
2032
+ _subjects.state.next({
2033
+ isSubmitted: true,
2034
+ isSubmitting: false,
2035
+ isSubmitSuccessful: isEmptyObject(_formState.errors),
2036
+ submitCount: _formState.submitCount + 1,
2037
+ errors: _formState.errors,
2038
+ });
2039
+ };
2040
+ const resetField = (name, options = {}) => {
2041
+ if (get(_fields, name)) {
2042
+ if (isUndefined(options.defaultValue)) {
2043
+ setValue(name, get(_defaultValues, name));
2044
+ }
2045
+ else {
2046
+ setValue(name, options.defaultValue);
2047
+ set(_defaultValues, name, options.defaultValue);
2048
+ }
2049
+ if (!options.keepTouched) {
2050
+ unset(_formState.touchedFields, name);
2051
+ }
2052
+ if (!options.keepDirty) {
2053
+ unset(_formState.dirtyFields, name);
2054
+ _formState.isDirty = options.defaultValue
2055
+ ? _getDirty(name, get(_defaultValues, name))
2056
+ : _getDirty();
2057
+ }
2058
+ if (!options.keepError) {
2059
+ unset(_formState.errors, name);
2060
+ _proxyFormState.isValid && _updateValid();
2061
+ }
2062
+ _subjects.state.next({ ..._formState });
2063
+ }
2064
+ };
2065
+ const _reset = (formValues, keepStateOptions = {}) => {
2066
+ const updatedValues = formValues || _defaultValues;
2067
+ const cloneUpdatedValues = cloneObject(updatedValues);
2068
+ const values = formValues && !isEmptyObject(formValues)
2069
+ ? cloneUpdatedValues
2070
+ : _defaultValues;
2071
+ if (!keepStateOptions.keepDefaultValues) {
2072
+ _defaultValues = updatedValues;
2073
+ }
2074
+ if (!keepStateOptions.keepValues) {
2075
+ if (keepStateOptions.keepDirtyValues || shouldCaptureDirtyFields) {
2076
+ for (const fieldName of _names.mount) {
2077
+ get(_formState.dirtyFields, fieldName)
2078
+ ? set(values, fieldName, get(_formValues, fieldName))
2079
+ : setValue(fieldName, get(values, fieldName));
2080
+ }
2081
+ }
2082
+ else {
2083
+ if (isWeb && isUndefined(formValues)) {
2084
+ for (const name of _names.mount) {
2085
+ const field = get(_fields, name);
2086
+ if (field && field._f) {
2087
+ const fieldReference = Array.isArray(field._f.refs)
2088
+ ? field._f.refs[0]
2089
+ : field._f.ref;
2090
+ if (isHTMLElement(fieldReference)) {
2091
+ const form = fieldReference.closest('form');
2092
+ if (form) {
2093
+ form.reset();
2094
+ break;
2095
+ }
2096
+ }
2097
+ }
2098
+ }
2099
+ }
2100
+ _fields = {};
2101
+ }
2102
+ _formValues = props.shouldUnregister
2103
+ ? keepStateOptions.keepDefaultValues
2104
+ ? cloneObject(_defaultValues)
2105
+ : {}
2106
+ : cloneUpdatedValues;
2107
+ _subjects.array.next({
2108
+ values: { ...values },
2109
+ });
2110
+ _subjects.values.next({
2111
+ values: { ...values },
2112
+ });
2113
+ }
2114
+ _names = {
2115
+ mount: new Set(),
2116
+ unMount: new Set(),
2117
+ array: new Set(),
2118
+ watch: new Set(),
2119
+ watchAll: false,
2120
+ focus: '',
2121
+ };
2122
+ !_state.mount && flushRootRender();
2123
+ _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
2124
+ _state.watch = !!props.shouldUnregister;
2125
+ _subjects.state.next({
2126
+ submitCount: keepStateOptions.keepSubmitCount
2127
+ ? _formState.submitCount
2128
+ : 0,
2129
+ isDirty: keepStateOptions.keepDirty
2130
+ ? _formState.isDirty
2131
+ : !!(keepStateOptions.keepDefaultValues &&
2132
+ !deepEqual(formValues, _defaultValues)),
2133
+ isSubmitted: keepStateOptions.keepIsSubmitted
2134
+ ? _formState.isSubmitted
2135
+ : false,
2136
+ dirtyFields: keepStateOptions.keepDirtyValues
2137
+ ? _formState.dirtyFields
2138
+ : keepStateOptions.keepDefaultValues && formValues
2139
+ ? getDirtyFields(_defaultValues, formValues)
2140
+ : {},
2141
+ touchedFields: keepStateOptions.keepTouched
2142
+ ? _formState.touchedFields
2143
+ : {},
2144
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
2145
+ isSubmitting: false,
2146
+ isSubmitSuccessful: false,
2147
+ });
2148
+ };
2149
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
2150
+ ? formValues(_formValues)
2151
+ : formValues, keepStateOptions);
2152
+ const setFocus = (name, options = {}) => {
2153
+ const field = get(_fields, name);
2154
+ const fieldReference = field && field._f;
2155
+ if (fieldReference) {
2156
+ const fieldRef = fieldReference.refs
2157
+ ? fieldReference.refs[0]
2158
+ : fieldReference.ref;
2159
+ if (fieldRef.focus) {
2160
+ fieldRef.focus();
2161
+ options.shouldSelect && fieldRef.select();
2162
+ }
2163
+ }
2164
+ };
2165
+ const _updateFormState = (updatedFormState) => {
2166
+ _formState = {
2167
+ ..._formState,
2168
+ ...updatedFormState,
2169
+ };
2170
+ };
2171
+ if (isFunction(_options.defaultValues)) {
2172
+ _options.defaultValues().then((values) => {
2173
+ reset(values, _options.resetOptions);
2174
+ _subjects.state.next({
2175
+ isLoading: false,
2176
+ });
2177
+ });
2178
+ }
2179
+ return {
2180
+ control: {
2181
+ register,
2182
+ unregister,
2183
+ getFieldState,
2184
+ _executeSchema,
2185
+ _getWatch,
2186
+ _getDirty,
2187
+ _updateValid,
2188
+ _removeUnmounted,
2189
+ _updateFieldArray,
2190
+ _getFieldArray,
2191
+ _reset,
2192
+ _updateFormState,
2193
+ _subjects,
2194
+ _proxyFormState,
2195
+ get _fields() {
2196
+ return _fields;
2197
+ },
2198
+ get _formValues() {
2199
+ return _formValues;
2200
+ },
2201
+ get _state() {
2202
+ return _state;
2203
+ },
2204
+ set _state(value) {
2205
+ _state = value;
2206
+ },
2207
+ get _defaultValues() {
2208
+ return _defaultValues;
2209
+ },
2210
+ get _names() {
2211
+ return _names;
2212
+ },
2213
+ set _names(value) {
2214
+ _names = value;
2215
+ },
2216
+ get _formState() {
2217
+ return _formState;
2218
+ },
2219
+ set _formState(value) {
2220
+ _formState = value;
2221
+ },
2222
+ get _options() {
2223
+ return _options;
2224
+ },
2225
+ set _options(value) {
2226
+ _options = {
2227
+ ..._options,
2228
+ ...value,
2229
+ };
2230
+ },
2231
+ },
2232
+ trigger,
2233
+ register,
2234
+ handleSubmit,
2235
+ watch,
2236
+ setValue,
2237
+ getValues,
2238
+ reset,
2239
+ resetField,
2240
+ clearErrors,
2241
+ unregister,
2242
+ setError,
2243
+ setFocus,
2244
+ getFieldState,
2245
+ };
2246
2246
  }
2247
2247
 
2248
- /**
2249
- * Custom hook to manage the entire form.
2250
- *
2251
- * @remarks
2252
- * [API](https://react-hook-form.com/api/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2253
- *
2254
- * @param props - form configuration and validation parameters.
2255
- *
2256
- * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2257
- *
2258
- * @example
2259
- * ```tsx
2260
- * function App() {
2261
- * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2262
- * const onSubmit = data => console.log(data);
2263
- *
2264
- * console.log(watch("example"));
2265
- *
2266
- * return (
2267
- * <form onSubmit={handleSubmit(onSubmit)}>
2268
- * <input defaultValue="test" {...register("example")} />
2269
- * <input {...register("exampleRequired", { required: true })} />
2270
- * {errors.exampleRequired && <span>This field is required</span>}
2271
- * <input type="submit" />
2272
- * </form>
2273
- * );
2274
- * }
2275
- * ```
2276
- */
2277
- function useForm(props = {}) {
2278
- const _formControl = React.useRef();
2279
- const [formState, updateFormState] = React.useState({
2280
- isDirty: false,
2281
- isValidating: false,
2282
- isLoading: isFunction(props.defaultValues),
2283
- isSubmitted: false,
2284
- isSubmitting: false,
2285
- isSubmitSuccessful: false,
2286
- isValid: false,
2287
- submitCount: 0,
2288
- dirtyFields: {},
2289
- touchedFields: {},
2290
- errors: {},
2291
- defaultValues: isFunction(props.defaultValues)
2292
- ? undefined
2293
- : props.defaultValues,
2294
- });
2295
- if (!_formControl.current) {
2296
- _formControl.current = {
2297
- ...createFormControl(props, () => updateFormState((formState) => ({ ...formState }))),
2298
- formState,
2299
- };
2300
- }
2301
- const control = _formControl.current.control;
2302
- control._options = props;
2303
- useSubscribe({
2304
- subject: control._subjects.state,
2305
- next: (value) => {
2306
- if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
2307
- updateFormState({ ...control._formState });
2308
- }
2309
- },
2310
- });
2311
- React.useEffect(() => {
2312
- if (props.values && !deepEqual(props.values, control._defaultValues)) {
2313
- control._reset(props.values, control._options.resetOptions);
2314
- }
2315
- }, [props.values, control]);
2316
- React.useEffect(() => {
2317
- if (!control._state.mount) {
2318
- control._updateValid();
2319
- control._state.mount = true;
2320
- }
2321
- if (control._state.watch) {
2322
- control._state.watch = false;
2323
- control._subjects.state.next({ ...control._formState });
2324
- }
2325
- control._removeUnmounted();
2326
- });
2327
- _formControl.current.formState = getProxyFormState(formState, control);
2328
- return _formControl.current;
2248
+ /**
2249
+ * Custom hook to manage the entire form.
2250
+ *
2251
+ * @remarks
2252
+ * [API](https://react-hook-form.com/api/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2253
+ *
2254
+ * @param props - form configuration and validation parameters.
2255
+ *
2256
+ * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2257
+ *
2258
+ * @example
2259
+ * ```tsx
2260
+ * function App() {
2261
+ * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2262
+ * const onSubmit = data => console.log(data);
2263
+ *
2264
+ * console.log(watch("example"));
2265
+ *
2266
+ * return (
2267
+ * <form onSubmit={handleSubmit(onSubmit)}>
2268
+ * <input defaultValue="test" {...register("example")} />
2269
+ * <input {...register("exampleRequired", { required: true })} />
2270
+ * {errors.exampleRequired && <span>This field is required</span>}
2271
+ * <input type="submit" />
2272
+ * </form>
2273
+ * );
2274
+ * }
2275
+ * ```
2276
+ */
2277
+ function useForm(props = {}) {
2278
+ const _formControl = React.useRef();
2279
+ const [formState, updateFormState] = React.useState({
2280
+ isDirty: false,
2281
+ isValidating: false,
2282
+ isLoading: isFunction(props.defaultValues),
2283
+ isSubmitted: false,
2284
+ isSubmitting: false,
2285
+ isSubmitSuccessful: false,
2286
+ isValid: false,
2287
+ submitCount: 0,
2288
+ dirtyFields: {},
2289
+ touchedFields: {},
2290
+ errors: {},
2291
+ defaultValues: isFunction(props.defaultValues)
2292
+ ? undefined
2293
+ : props.defaultValues,
2294
+ });
2295
+ if (!_formControl.current) {
2296
+ _formControl.current = {
2297
+ ...createFormControl(props, () => updateFormState((formState) => ({ ...formState }))),
2298
+ formState,
2299
+ };
2300
+ }
2301
+ const control = _formControl.current.control;
2302
+ control._options = props;
2303
+ useSubscribe({
2304
+ subject: control._subjects.state,
2305
+ next: (value) => {
2306
+ if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
2307
+ updateFormState({ ...control._formState });
2308
+ }
2309
+ },
2310
+ });
2311
+ React.useEffect(() => {
2312
+ if (props.values && !deepEqual(props.values, control._defaultValues)) {
2313
+ control._reset(props.values, control._options.resetOptions);
2314
+ }
2315
+ }, [props.values, control]);
2316
+ React.useEffect(() => {
2317
+ if (!control._state.mount) {
2318
+ control._updateValid();
2319
+ control._state.mount = true;
2320
+ }
2321
+ if (control._state.watch) {
2322
+ control._state.watch = false;
2323
+ control._subjects.state.next({ ...control._formState });
2324
+ }
2325
+ control._removeUnmounted();
2326
+ });
2327
+ _formControl.current.formState = getProxyFormState(formState, control);
2328
+ return _formControl.current;
2329
2329
  }
2330
2330
 
2331
2331
  export { Controller, FormProvider, appendErrors, get, set, useController, useFieldArray, useForm, useFormContext, useFormState, useWatch };