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