@baseplate-dev/plugin-auth 0.6.10 → 0.6.11

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