@pnkx-lib/ui 1.9.178 → 1.9.180

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