@bombillazo/rhf-plus 7.56.1-plus.0

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