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