@evervault/react-native 2.5.1 → 2.6.1

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