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