react-hook-form 7.43.6 → 7.43.8

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