@classytic/pos-ui 0.1.0
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 +38 -0
- package/dist/components/CartSidebar.js +222 -0
- package/dist/components/PosTopBar.js +156 -0
- package/dist/components/PrinterSettingsDialog.js +163 -0
- package/dist/components/ReceiptReprintDialog.js +182 -0
- package/dist/dashboard/components/CustomerLookupDialog.js +120 -0
- package/dist/dashboard/components/CustomerQuickAddDialog.js +101 -0
- package/dist/dashboard/components/ManagerAuthDialog.js +77 -0
- package/dist/dashboard/components/ProductCard.js +98 -0
- package/dist/dashboard/components/ProductsPanel.js +119 -0
- package/dist/dashboard/components/SplitPaymentPanel.js +131 -0
- package/dist/dashboard/components/VariantSelectorDialog.js +150 -0
- package/dist/dashboard/components/cart/AddChargeDialog.js +99 -0
- package/dist/dashboard/components/cart/CartItems.js +103 -0
- package/dist/dashboard/components/cart/CartSummary.js +73 -0
- package/dist/dashboard/components/cart/CustomerSection.js +127 -0
- package/dist/dashboard/components/cart/DiscountSection.js +50 -0
- package/dist/dashboard/components/cart/PointsRedemptionSection.js +58 -0
- package/dist/hardware/context.d.ts +15 -0
- package/dist/hardware/context.js +33 -0
- package/dist/hardware/index.d.ts +7 -0
- package/dist/hardware/index.js +7 -0
- package/dist/hardware/ports.d.ts +116 -0
- package/dist/hardware/tauri-adapter.d.ts +7 -0
- package/dist/hardware/tauri-adapter.js +77 -0
- package/dist/hardware/use-printer-availability.d.ts +12 -0
- package/dist/hardware/use-printer-availability.js +50 -0
- package/dist/hardware/use-printer-config.d.ts +16 -0
- package/dist/hardware/use-printer-config.js +62 -0
- package/dist/hardware/web-adapter.d.ts +15 -0
- package/dist/hardware/web-adapter.js +80 -0
- package/dist/hooks/useManagerAuth.js +83 -0
- package/dist/hooks/usePosCart.js +142 -0
- package/dist/hooks/usePosCustomer.js +192 -0
- package/dist/hooks/usePosMultiOrder.js +48 -0
- package/dist/hooks/usePosPayment.js +194 -0
- package/dist/lib/cn.js +12 -0
- package/dist/lib/loyalty.js +30 -0
- package/dist/lib/money.js +41 -0
- package/dist/node_modules/react-hook-form/dist/index.esm.js +1661 -0
- package/dist/runtime/auth-port.d.ts +46 -0
- package/dist/runtime/auth-port.js +21 -0
- package/dist/runtime/branch-port.d.ts +38 -0
- package/dist/runtime/branch-port.js +26 -0
- package/dist/runtime/config.d.ts +24 -0
- package/dist/runtime/config.js +21 -0
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/index.js +5 -0
- package/dist/screens/OrderHistoryDrawer.js +245 -0
- package/dist/screens/ParkedOrdersDrawer.js +128 -0
- package/dist/screens/PaymentScreen.js +397 -0
- package/dist/screens/ProductScreen.js +322 -0
- package/dist/screens/ReceiptScreen.js +288 -0
- package/dist/screens/ShiftCloseScreen.js +365 -0
- package/dist/screens/ShiftOpenScreen.js +176 -0
- package/dist/shell/index.d.ts +8 -0
- package/dist/shell/index.js +5 -0
- package/dist/shell/pos-shell.d.ts +23 -0
- package/dist/shell/pos-shell.js +132 -0
- package/dist/state/pos-context.js +33 -0
- package/dist/state/pos-state.js +70 -0
- package/dist/utils/customer-display.js +35 -0
- package/dist/utils/pos-helpers.js +242 -0
- package/package.json +92 -0
- package/styles.css +19 -0
|
@@ -0,0 +1,1661 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
|
|
3
|
+
//#region node_modules/react-hook-form/dist/index.esm.mjs
|
|
4
|
+
var isCheckBoxInput = (element) => element.type === "checkbox";
|
|
5
|
+
var isDateObject = (value) => value instanceof Date;
|
|
6
|
+
var isNullOrUndefined = (value) => value == null;
|
|
7
|
+
const isObjectType = (value) => typeof value === "object";
|
|
8
|
+
var isObject = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !isDateObject(value);
|
|
9
|
+
var getEventValue = (event) => isObject(event) && event.target ? isCheckBoxInput(event.target) ? event.target.checked : event.target.value : event;
|
|
10
|
+
var isNameInFieldArray = (names, name) => name.split(".").some((part, index, arr) => !isNaN(Number(part)) && names.has(arr.slice(0, index).join(".")));
|
|
11
|
+
var isPlainObject = (tempObject) => {
|
|
12
|
+
const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
|
|
13
|
+
return isObject(prototypeCopy) && prototypeCopy.hasOwnProperty("isPrototypeOf");
|
|
14
|
+
};
|
|
15
|
+
var isWeb = typeof window !== "undefined" && typeof window.HTMLElement !== "undefined" && typeof document !== "undefined";
|
|
16
|
+
function cloneObject(data) {
|
|
17
|
+
if (data instanceof Date) return new Date(data);
|
|
18
|
+
const isFileListInstance = typeof FileList !== "undefined" && data instanceof FileList;
|
|
19
|
+
if (isWeb && (data instanceof Blob || isFileListInstance)) return data;
|
|
20
|
+
const isArray = Array.isArray(data);
|
|
21
|
+
if (!isArray && !(isObject(data) && isPlainObject(data))) return data;
|
|
22
|
+
const copy = isArray ? [] : Object.create(Object.getPrototypeOf(data));
|
|
23
|
+
for (const key in data) if (Object.prototype.hasOwnProperty.call(data, key)) copy[key] = cloneObject(data[key]);
|
|
24
|
+
return copy;
|
|
25
|
+
}
|
|
26
|
+
const EVENTS = {
|
|
27
|
+
BLUR: "blur",
|
|
28
|
+
FOCUS_OUT: "focusout",
|
|
29
|
+
CHANGE: "change",
|
|
30
|
+
SUBMIT: "submit",
|
|
31
|
+
TRIGGER: "trigger",
|
|
32
|
+
VALID: "valid"
|
|
33
|
+
};
|
|
34
|
+
const VALIDATION_MODE = {
|
|
35
|
+
onBlur: "onBlur",
|
|
36
|
+
onChange: "onChange",
|
|
37
|
+
onSubmit: "onSubmit",
|
|
38
|
+
onTouched: "onTouched",
|
|
39
|
+
all: "all"
|
|
40
|
+
};
|
|
41
|
+
const INPUT_VALIDATION_RULES = {
|
|
42
|
+
max: "max",
|
|
43
|
+
min: "min",
|
|
44
|
+
maxLength: "maxLength",
|
|
45
|
+
minLength: "minLength",
|
|
46
|
+
pattern: "pattern",
|
|
47
|
+
required: "required",
|
|
48
|
+
validate: "validate"
|
|
49
|
+
};
|
|
50
|
+
const ROOT_ERROR_TYPE = "root";
|
|
51
|
+
const PROTOTYPE_KEYWORDS = [
|
|
52
|
+
"__proto__",
|
|
53
|
+
"constructor",
|
|
54
|
+
"prototype"
|
|
55
|
+
];
|
|
56
|
+
const IS_KEY_RE = /^\w*$/;
|
|
57
|
+
var isKey = (value) => IS_KEY_RE.test(value);
|
|
58
|
+
var isUndefined = (val) => val === void 0;
|
|
59
|
+
const FIELD_PATH_RE = /[.[\]'"]/;
|
|
60
|
+
var stringToPath = (input) => input.split(FIELD_PATH_RE).filter(Boolean);
|
|
61
|
+
var get = (object, path, defaultValue) => {
|
|
62
|
+
if (!path || !isObject(object)) return defaultValue;
|
|
63
|
+
const paths = isKey(path) ? [path] : stringToPath(path);
|
|
64
|
+
if (paths.some((key) => PROTOTYPE_KEYWORDS.includes(key))) return defaultValue;
|
|
65
|
+
const result = paths.reduce((result, key) => {
|
|
66
|
+
return isNullOrUndefined(result) ? void 0 : result[key];
|
|
67
|
+
}, object);
|
|
68
|
+
return isUndefined(result) || result === object ? isUndefined(object[path]) ? defaultValue : object[path] : result;
|
|
69
|
+
};
|
|
70
|
+
var isBoolean = (value) => typeof value === "boolean";
|
|
71
|
+
var isFunction = (value) => typeof value === "function";
|
|
72
|
+
var set = (object, path, value) => {
|
|
73
|
+
let index = -1;
|
|
74
|
+
const tempPath = isKey(path) ? [path] : stringToPath(path);
|
|
75
|
+
const length = tempPath.length;
|
|
76
|
+
const lastIndex = length - 1;
|
|
77
|
+
while (++index < length) {
|
|
78
|
+
const key = tempPath[index];
|
|
79
|
+
let newValue = value;
|
|
80
|
+
if (index !== lastIndex) {
|
|
81
|
+
const objValue = object[key];
|
|
82
|
+
newValue = isObject(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index + 1]) ? [] : {};
|
|
83
|
+
}
|
|
84
|
+
if (PROTOTYPE_KEYWORDS.includes(key)) return;
|
|
85
|
+
object[key] = newValue;
|
|
86
|
+
object = object[key];
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Separate context for `control` to prevent unnecessary rerenders.
|
|
91
|
+
* Internal hooks that only need control use this instead of full form context.
|
|
92
|
+
*/
|
|
93
|
+
const HookFormControlContext = React.createContext(null);
|
|
94
|
+
HookFormControlContext.displayName = "HookFormControlContext";
|
|
95
|
+
var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
|
|
96
|
+
const result = {};
|
|
97
|
+
for (const key in formState) Object.defineProperty(result, key, { get: () => {
|
|
98
|
+
const _key = key;
|
|
99
|
+
if (control._proxyFormState[_key] !== VALIDATION_MODE.all) control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
|
|
100
|
+
localProxyFormState && (localProxyFormState[_key] = true);
|
|
101
|
+
return formState[_key];
|
|
102
|
+
} });
|
|
103
|
+
return result;
|
|
104
|
+
};
|
|
105
|
+
const useIsomorphicLayoutEffect = isWeb ? React.useLayoutEffect : React.useEffect;
|
|
106
|
+
var isString = (value) => typeof value === "string";
|
|
107
|
+
var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
|
|
108
|
+
if (isString(names)) {
|
|
109
|
+
isGlobal && _names.watch.add(names);
|
|
110
|
+
return get(formValues, names, defaultValue);
|
|
111
|
+
}
|
|
112
|
+
if (Array.isArray(names)) return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
|
|
113
|
+
isGlobal && (_names.watchAll = true);
|
|
114
|
+
return formValues;
|
|
115
|
+
};
|
|
116
|
+
var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
|
|
117
|
+
const isEmptyObjectWithCustomPrototype = (object, keys) => keys.length === 0 && !Array.isArray(object) && !isPlainObject(object);
|
|
118
|
+
function deepEqual(object1, object2, visited = /* @__PURE__ */ new WeakMap()) {
|
|
119
|
+
if (object1 === object2) return true;
|
|
120
|
+
if (isPrimitive(object1) || isPrimitive(object2)) return Object.is(object1, object2);
|
|
121
|
+
if (isDateObject(object1) && isDateObject(object2)) return Object.is(object1.getTime(), object2.getTime());
|
|
122
|
+
const keys1 = Object.keys(object1);
|
|
123
|
+
const keys2 = Object.keys(object2);
|
|
124
|
+
if (keys1.length !== keys2.length) return false;
|
|
125
|
+
if (isEmptyObjectWithCustomPrototype(object1, keys1) || isEmptyObjectWithCustomPrototype(object2, keys2)) return Object.is(object1, object2);
|
|
126
|
+
if (!keys1.length && Array.isArray(object1) !== Array.isArray(object2)) return false;
|
|
127
|
+
const visitedPairs = visited.get(object1);
|
|
128
|
+
if (visitedPairs && visitedPairs.has(object2)) return true;
|
|
129
|
+
if (visitedPairs) visitedPairs.add(object2);
|
|
130
|
+
else {
|
|
131
|
+
const ws = /* @__PURE__ */ new WeakSet();
|
|
132
|
+
ws.add(object2);
|
|
133
|
+
visited.set(object1, ws);
|
|
134
|
+
}
|
|
135
|
+
for (const key of keys1) {
|
|
136
|
+
const val1 = object1[key];
|
|
137
|
+
if (!(key in object2)) return false;
|
|
138
|
+
if (key !== "ref") {
|
|
139
|
+
const val2 = object2[key];
|
|
140
|
+
if (isDateObject(val1) && isDateObject(val2) || (isObject(val1) || Array.isArray(val1)) && (isObject(val2) || Array.isArray(val2)) ? !deepEqual(val1, val2, visited) : !Object.is(val1, val2)) return false;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
const HookFormContext = React.createContext(null);
|
|
146
|
+
HookFormContext.displayName = "HookFormContext";
|
|
147
|
+
var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria ? {
|
|
148
|
+
...errors[name],
|
|
149
|
+
types: {
|
|
150
|
+
...errors[name] && errors[name].types ? errors[name].types : {},
|
|
151
|
+
[type]: message || true
|
|
152
|
+
}
|
|
153
|
+
} : {};
|
|
154
|
+
var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
|
|
155
|
+
var convertToArrayPayload = (value) => Array.isArray(value) ? value : [value];
|
|
156
|
+
var createSubject = () => {
|
|
157
|
+
let _observers = [];
|
|
158
|
+
const next = (value) => {
|
|
159
|
+
for (const observer of _observers) observer.next && observer.next(value);
|
|
160
|
+
};
|
|
161
|
+
const subscribe = (observer) => {
|
|
162
|
+
_observers.push(observer);
|
|
163
|
+
return { unsubscribe: () => {
|
|
164
|
+
_observers = _observers.filter((o) => o !== observer);
|
|
165
|
+
} };
|
|
166
|
+
};
|
|
167
|
+
const unsubscribe = () => {
|
|
168
|
+
_observers = [];
|
|
169
|
+
};
|
|
170
|
+
return {
|
|
171
|
+
get observers() {
|
|
172
|
+
return _observers;
|
|
173
|
+
},
|
|
174
|
+
next,
|
|
175
|
+
subscribe,
|
|
176
|
+
unsubscribe
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
function extractFormValues(fieldsState, formValues) {
|
|
180
|
+
const values = {};
|
|
181
|
+
for (const key in fieldsState) if (fieldsState.hasOwnProperty(key)) {
|
|
182
|
+
const fieldState = fieldsState[key];
|
|
183
|
+
const fieldValue = formValues[key];
|
|
184
|
+
if (fieldState && isObject(fieldState) && fieldValue) {
|
|
185
|
+
const nestedFieldsState = extractFormValues(fieldState, fieldValue);
|
|
186
|
+
if (isObject(nestedFieldsState)) values[key] = nestedFieldsState;
|
|
187
|
+
} else if (fieldsState[key]) values[key] = fieldValue;
|
|
188
|
+
}
|
|
189
|
+
return values;
|
|
190
|
+
}
|
|
191
|
+
var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
|
|
192
|
+
var isFileInput = (element) => element.type === "file";
|
|
193
|
+
var isHTMLElement = (value) => {
|
|
194
|
+
if (!isWeb) return false;
|
|
195
|
+
const owner = value ? value.ownerDocument : 0;
|
|
196
|
+
return value instanceof (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement);
|
|
197
|
+
};
|
|
198
|
+
var isMultipleSelect = (element) => element.type === `select-multiple`;
|
|
199
|
+
var isRadioInput = (element) => element.type === "radio";
|
|
200
|
+
var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
|
|
201
|
+
var live = (ref) => isHTMLElement(ref) && ref.isConnected;
|
|
202
|
+
function baseGet(object, updatePath) {
|
|
203
|
+
const length = updatePath.slice(0, -1).length;
|
|
204
|
+
let index = 0;
|
|
205
|
+
while (index < length) {
|
|
206
|
+
if (isNullOrUndefined(object)) {
|
|
207
|
+
object = void 0;
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
object = object[updatePath[index]];
|
|
211
|
+
index++;
|
|
212
|
+
}
|
|
213
|
+
return object;
|
|
214
|
+
}
|
|
215
|
+
function isEmptyArray(obj) {
|
|
216
|
+
for (const key in obj) if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) return false;
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
function unset(object, path) {
|
|
220
|
+
if (isString(path) && Object.prototype.hasOwnProperty.call(object, path)) {
|
|
221
|
+
delete object[path];
|
|
222
|
+
return object;
|
|
223
|
+
}
|
|
224
|
+
const paths = Array.isArray(path) ? path : isKey(path) ? [path] : stringToPath(path);
|
|
225
|
+
const childObject = paths.length === 1 ? object : baseGet(object, paths);
|
|
226
|
+
const index = paths.length - 1;
|
|
227
|
+
const key = paths[index];
|
|
228
|
+
if (childObject) delete childObject[key];
|
|
229
|
+
if (index !== 0 && (isObject(childObject) && isEmptyObject(childObject) || Array.isArray(childObject) && isEmptyArray(childObject))) unset(object, paths.slice(0, -1));
|
|
230
|
+
return object;
|
|
231
|
+
}
|
|
232
|
+
var objectHasFunction = (data) => {
|
|
233
|
+
for (const key in data) if (isFunction(data[key])) return true;
|
|
234
|
+
return false;
|
|
235
|
+
};
|
|
236
|
+
function isTraversable(value) {
|
|
237
|
+
return Array.isArray(value) || isObject(value) && !objectHasFunction(value);
|
|
238
|
+
}
|
|
239
|
+
function markFieldsDirty(data, fields = {}) {
|
|
240
|
+
for (const key in data) {
|
|
241
|
+
const value = data[key];
|
|
242
|
+
if (isTraversable(value)) {
|
|
243
|
+
fields[key] = Array.isArray(value) ? [] : {};
|
|
244
|
+
markFieldsDirty(value, fields[key]);
|
|
245
|
+
} else if (!isUndefined(value)) fields[key] = true;
|
|
246
|
+
}
|
|
247
|
+
return fields;
|
|
248
|
+
}
|
|
249
|
+
function pruneDirtyFields(value) {
|
|
250
|
+
if (value === false) return;
|
|
251
|
+
if (value === true) return true;
|
|
252
|
+
if (Array.isArray(value)) {
|
|
253
|
+
const result = value.map((value) => pruneDirtyFields(value));
|
|
254
|
+
return result.some((value) => value !== void 0) ? result : void 0;
|
|
255
|
+
}
|
|
256
|
+
if (isObject(value)) {
|
|
257
|
+
const result = {};
|
|
258
|
+
for (const key in value) {
|
|
259
|
+
const pruned = pruneDirtyFields(value[key]);
|
|
260
|
+
if (!isUndefined(pruned)) result[key] = pruned;
|
|
261
|
+
}
|
|
262
|
+
return Object.keys(result).length ? result : void 0;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
function getDirtyFields(data, formValues, dirtyFieldsFromValues) {
|
|
266
|
+
if (!dirtyFieldsFromValues) dirtyFieldsFromValues = markFieldsDirty(formValues);
|
|
267
|
+
for (const key in data) {
|
|
268
|
+
const value = data[key];
|
|
269
|
+
if (isTraversable(value)) if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) dirtyFieldsFromValues[key] = markFieldsDirty(value, Array.isArray(value) ? [] : {});
|
|
270
|
+
else getDirtyFields(value, isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
|
|
271
|
+
else {
|
|
272
|
+
const formValue = formValues[key];
|
|
273
|
+
dirtyFieldsFromValues[key] = !deepEqual(value, formValue);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return pruneDirtyFields(dirtyFieldsFromValues) || {};
|
|
277
|
+
}
|
|
278
|
+
const defaultResult = {
|
|
279
|
+
value: false,
|
|
280
|
+
isValid: false
|
|
281
|
+
};
|
|
282
|
+
const validResult = {
|
|
283
|
+
value: true,
|
|
284
|
+
isValid: true
|
|
285
|
+
};
|
|
286
|
+
var getCheckboxValue = (options) => {
|
|
287
|
+
if (Array.isArray(options)) {
|
|
288
|
+
if (options.length > 1) {
|
|
289
|
+
const values = options.filter((option) => option && option.checked && !option.disabled).map((option) => option.value);
|
|
290
|
+
return {
|
|
291
|
+
value: values,
|
|
292
|
+
isValid: !!values.length
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
return options[0].checked && !options[0].disabled ? options[0].attributes && !isUndefined(options[0].attributes.value) ? isUndefined(options[0].value) || options[0].value === "" ? validResult : {
|
|
296
|
+
value: options[0].value,
|
|
297
|
+
isValid: true
|
|
298
|
+
} : validResult : defaultResult;
|
|
299
|
+
}
|
|
300
|
+
return defaultResult;
|
|
301
|
+
};
|
|
302
|
+
var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value) ? value : valueAsNumber ? value === "" ? NaN : value ? +value : value : valueAsDate && isString(value) ? new Date(value) : setValueAs ? setValueAs(value) : value;
|
|
303
|
+
const defaultReturn = {
|
|
304
|
+
isValid: false,
|
|
305
|
+
value: null
|
|
306
|
+
};
|
|
307
|
+
var getRadioValue = (options) => Array.isArray(options) ? options.reduce((previous, option) => option && option.checked && !option.disabled ? {
|
|
308
|
+
isValid: true,
|
|
309
|
+
value: option.value
|
|
310
|
+
} : previous, defaultReturn) : defaultReturn;
|
|
311
|
+
function getFieldValue(_f) {
|
|
312
|
+
const ref = _f.ref;
|
|
313
|
+
if (isFileInput(ref)) return ref.files;
|
|
314
|
+
if (isRadioInput(ref)) return getRadioValue(_f.refs).value;
|
|
315
|
+
if (isMultipleSelect(ref)) return [...ref.selectedOptions].map(({ value }) => value);
|
|
316
|
+
if (isCheckBoxInput(ref)) return getCheckboxValue(_f.refs).value;
|
|
317
|
+
return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
|
|
318
|
+
}
|
|
319
|
+
var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
|
|
320
|
+
const fields = {};
|
|
321
|
+
for (const name of fieldsNames) {
|
|
322
|
+
const field = get(_fields, name);
|
|
323
|
+
field && set(fields, name, field._f);
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
criteriaMode,
|
|
327
|
+
names: [...fieldsNames],
|
|
328
|
+
fields,
|
|
329
|
+
shouldUseNativeValidation
|
|
330
|
+
};
|
|
331
|
+
};
|
|
332
|
+
var isRegex = (value) => value instanceof RegExp;
|
|
333
|
+
var getRuleValue = (rule) => isUndefined(rule) ? rule : isRegex(rule) ? rule.source : isObject(rule) ? isRegex(rule.value) ? rule.value.source : rule.value : rule;
|
|
334
|
+
var getValidationModes = (mode) => ({
|
|
335
|
+
isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
|
|
336
|
+
isOnBlur: mode === VALIDATION_MODE.onBlur,
|
|
337
|
+
isOnChange: mode === VALIDATION_MODE.onChange,
|
|
338
|
+
isOnAll: mode === VALIDATION_MODE.all,
|
|
339
|
+
isOnTouch: mode === VALIDATION_MODE.onTouched
|
|
340
|
+
});
|
|
341
|
+
const ASYNC_FUNCTION = "AsyncFunction";
|
|
342
|
+
var hasPromiseValidation = (fieldReference) => {
|
|
343
|
+
if (!fieldReference || !fieldReference.validate) return false;
|
|
344
|
+
if (isFunction(fieldReference.validate)) return fieldReference.validate.constructor.name === ASYNC_FUNCTION;
|
|
345
|
+
if (isObject(fieldReference.validate)) {
|
|
346
|
+
for (const key in fieldReference.validate) if (fieldReference.validate[key].constructor.name === ASYNC_FUNCTION) return true;
|
|
347
|
+
}
|
|
348
|
+
return false;
|
|
349
|
+
};
|
|
350
|
+
var hasValidation = (options) => options.mount && (options.required || options.min || options.max || options.maxLength || options.minLength || options.pattern || options.validate);
|
|
351
|
+
var isWatched = (name, _names, isBlurEvent) => {
|
|
352
|
+
if (isBlurEvent) return false;
|
|
353
|
+
if (_names.watchAll || _names.watch.has(name)) return true;
|
|
354
|
+
for (const watchName of _names.watch) if (name.startsWith(watchName) && name.charAt(watchName.length) === ".") return true;
|
|
355
|
+
return false;
|
|
356
|
+
};
|
|
357
|
+
const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
|
|
358
|
+
for (const key of fieldsNames || Object.keys(fields)) {
|
|
359
|
+
const field = get(fields, key);
|
|
360
|
+
if (field) {
|
|
361
|
+
const { _f, ...currentField } = field;
|
|
362
|
+
if (_f) {
|
|
363
|
+
if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) return true;
|
|
364
|
+
else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) return true;
|
|
365
|
+
else if (iterateFieldsByAction(currentField, action)) break;
|
|
366
|
+
} else if (isObject(currentField)) {
|
|
367
|
+
if (iterateFieldsByAction(currentField, action)) break;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
function schemaErrorLookup(errors, _fields, name) {
|
|
373
|
+
const error = get(errors, name);
|
|
374
|
+
if (error || isKey(name)) return {
|
|
375
|
+
error,
|
|
376
|
+
name
|
|
377
|
+
};
|
|
378
|
+
const names = name.split(".");
|
|
379
|
+
while (names.length) {
|
|
380
|
+
const fieldName = names.join(".");
|
|
381
|
+
const field = get(_fields, fieldName);
|
|
382
|
+
const foundError = get(errors, fieldName);
|
|
383
|
+
if (field && !Array.isArray(field) && name !== fieldName) return { name };
|
|
384
|
+
if (foundError && foundError.type) return {
|
|
385
|
+
name: fieldName,
|
|
386
|
+
error: foundError
|
|
387
|
+
};
|
|
388
|
+
if (foundError && foundError.root && foundError.root.type) return {
|
|
389
|
+
name: `${fieldName}.root`,
|
|
390
|
+
error: foundError.root
|
|
391
|
+
};
|
|
392
|
+
names.pop();
|
|
393
|
+
}
|
|
394
|
+
return { name };
|
|
395
|
+
}
|
|
396
|
+
var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
|
|
397
|
+
updateFormState(formStateData);
|
|
398
|
+
const { name, ...formState } = formStateData;
|
|
399
|
+
const keys = Object.keys(formState);
|
|
400
|
+
return !keys.length || isRoot && keys.length >= Object.keys(_proxyFormState).length || keys.find((key) => _proxyFormState[key] === (!isRoot || VALIDATION_MODE.all));
|
|
401
|
+
};
|
|
402
|
+
var shouldSubscribeByName = (name, signalName, exact) => !name || !signalName || name === signalName || convertToArrayPayload(name).some((currentName) => currentName && (exact ? currentName === signalName : currentName.startsWith(signalName) || signalName.startsWith(currentName)));
|
|
403
|
+
var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
|
|
404
|
+
if (mode.isOnAll) return false;
|
|
405
|
+
else if (!isSubmitted && mode.isOnTouch) return !(isTouched || isBlurEvent);
|
|
406
|
+
else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) return !isBlurEvent;
|
|
407
|
+
else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) return isBlurEvent;
|
|
408
|
+
return true;
|
|
409
|
+
};
|
|
410
|
+
var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
|
|
411
|
+
var updateFieldArrayRootError = (errors, error, name) => {
|
|
412
|
+
const existingErrors = get(errors, name);
|
|
413
|
+
const fieldArrayErrors = Array.isArray(existingErrors) ? existingErrors : [];
|
|
414
|
+
set(fieldArrayErrors, ROOT_ERROR_TYPE, error[name]);
|
|
415
|
+
set(errors, name, fieldArrayErrors);
|
|
416
|
+
return errors;
|
|
417
|
+
};
|
|
418
|
+
function getValidateError(result, ref, type = "validate") {
|
|
419
|
+
if (isString(result) || Array.isArray(result) && result.every(isString) || isBoolean(result) && !result) return {
|
|
420
|
+
type,
|
|
421
|
+
message: isString(result) ? result : "",
|
|
422
|
+
ref
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData) ? validationData : {
|
|
426
|
+
value: validationData,
|
|
427
|
+
message: ""
|
|
428
|
+
};
|
|
429
|
+
var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
|
|
430
|
+
const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount } = field._f;
|
|
431
|
+
const inputValue = get(formValues, name);
|
|
432
|
+
if (!mount || disabledFieldNames.has(name)) return {};
|
|
433
|
+
const inputRef = refs ? refs[0] : ref;
|
|
434
|
+
const setCustomValidity = (message) => {
|
|
435
|
+
if (shouldUseNativeValidation && inputRef.reportValidity) {
|
|
436
|
+
const validityMessage = isBoolean(message) ? "" : message || "";
|
|
437
|
+
if (refs) refs.forEach((ref) => ref.setCustomValidity(validityMessage));
|
|
438
|
+
else inputRef.setCustomValidity(validityMessage);
|
|
439
|
+
inputRef.reportValidity();
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
const error = {};
|
|
443
|
+
const isRadio = isRadioInput(ref);
|
|
444
|
+
const isCheckBox = isCheckBoxInput(ref);
|
|
445
|
+
const isRadioOrCheckbox = isRadio || isCheckBox;
|
|
446
|
+
const isEmpty = (valueAsNumber || isFileInput(ref)) && isUndefined(ref.value) && isUndefined(inputValue) || isHTMLElement(ref) && ref.value === "" || inputValue === "" || Array.isArray(inputValue) && !inputValue.length;
|
|
447
|
+
const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
|
|
448
|
+
const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
|
|
449
|
+
const message = exceedMax ? maxLengthMessage : minLengthMessage;
|
|
450
|
+
error[name] = {
|
|
451
|
+
type: exceedMax ? maxType : minType,
|
|
452
|
+
message,
|
|
453
|
+
ref,
|
|
454
|
+
...appendErrorsCurry(exceedMax ? maxType : minType, message)
|
|
455
|
+
};
|
|
456
|
+
};
|
|
457
|
+
if (isFieldArray ? !Array.isArray(inputValue) || !inputValue.length : required && (!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue)) || isBoolean(inputValue) && !inputValue || isCheckBox && !getCheckboxValue(refs).isValid || isRadio && !getRadioValue(refs).isValid)) {
|
|
458
|
+
const { value, message } = isString(required) ? {
|
|
459
|
+
value: !!required,
|
|
460
|
+
message: required
|
|
461
|
+
} : getValueAndMessage(required);
|
|
462
|
+
if (value) {
|
|
463
|
+
error[name] = {
|
|
464
|
+
type: INPUT_VALIDATION_RULES.required,
|
|
465
|
+
message,
|
|
466
|
+
ref: inputRef,
|
|
467
|
+
...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message)
|
|
468
|
+
};
|
|
469
|
+
if (!validateAllFieldCriteria) {
|
|
470
|
+
setCustomValidity(message);
|
|
471
|
+
return error;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
|
|
476
|
+
let exceedMax;
|
|
477
|
+
let exceedMin;
|
|
478
|
+
const maxOutput = getValueAndMessage(max);
|
|
479
|
+
const minOutput = getValueAndMessage(min);
|
|
480
|
+
if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
|
|
481
|
+
const valueNumber = ref.valueAsNumber || (inputValue ? +inputValue : inputValue);
|
|
482
|
+
if (!isNullOrUndefined(maxOutput.value)) exceedMax = valueNumber > maxOutput.value;
|
|
483
|
+
if (!isNullOrUndefined(minOutput.value)) exceedMin = valueNumber < minOutput.value;
|
|
484
|
+
} else {
|
|
485
|
+
const valueDate = ref.valueAsDate || new Date(inputValue);
|
|
486
|
+
const convertTimeToDate = (time) => /* @__PURE__ */ new Date((/* @__PURE__ */ new Date()).toDateString() + " " + time);
|
|
487
|
+
const isTime = ref.type == "time";
|
|
488
|
+
const isWeek = ref.type == "week";
|
|
489
|
+
if (isString(maxOutput.value) && inputValue) exceedMax = isTime ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value) : isWeek ? inputValue > maxOutput.value : valueDate > new Date(maxOutput.value);
|
|
490
|
+
if (isString(minOutput.value) && inputValue) exceedMin = isTime ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value) : isWeek ? inputValue < minOutput.value : valueDate < new Date(minOutput.value);
|
|
491
|
+
}
|
|
492
|
+
if (exceedMax || exceedMin) {
|
|
493
|
+
getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
|
|
494
|
+
if (!validateAllFieldCriteria) {
|
|
495
|
+
setCustomValidity(error[name].message);
|
|
496
|
+
return error;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if ((maxLength || minLength) && !isEmpty && (isString(inputValue) || isFieldArray && Array.isArray(inputValue))) {
|
|
501
|
+
const maxLengthOutput = getValueAndMessage(maxLength);
|
|
502
|
+
const minLengthOutput = getValueAndMessage(minLength);
|
|
503
|
+
const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > +maxLengthOutput.value;
|
|
504
|
+
const exceedMin = !isNullOrUndefined(minLengthOutput.value) && inputValue.length < +minLengthOutput.value;
|
|
505
|
+
if (exceedMax || exceedMin) {
|
|
506
|
+
getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
|
|
507
|
+
if (!validateAllFieldCriteria) {
|
|
508
|
+
setCustomValidity(error[name].message);
|
|
509
|
+
return error;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (pattern && !isEmpty && isString(inputValue)) {
|
|
514
|
+
const { value: patternValue, message } = getValueAndMessage(pattern);
|
|
515
|
+
if (isRegex(patternValue) && !inputValue.match(patternValue)) {
|
|
516
|
+
error[name] = {
|
|
517
|
+
type: INPUT_VALIDATION_RULES.pattern,
|
|
518
|
+
message,
|
|
519
|
+
ref,
|
|
520
|
+
...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message)
|
|
521
|
+
};
|
|
522
|
+
if (!validateAllFieldCriteria) {
|
|
523
|
+
setCustomValidity(message);
|
|
524
|
+
return error;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
if (validate) {
|
|
529
|
+
if (isFunction(validate)) {
|
|
530
|
+
const validateError = getValidateError(await validate(inputValue, formValues), inputRef);
|
|
531
|
+
if (validateError) {
|
|
532
|
+
error[name] = {
|
|
533
|
+
...validateError,
|
|
534
|
+
...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message)
|
|
535
|
+
};
|
|
536
|
+
if (!validateAllFieldCriteria) {
|
|
537
|
+
setCustomValidity(validateError.message);
|
|
538
|
+
return error;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
} else if (isObject(validate)) {
|
|
542
|
+
let validationResult = {};
|
|
543
|
+
for (const key in validate) {
|
|
544
|
+
if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) break;
|
|
545
|
+
const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
|
|
546
|
+
if (validateError) {
|
|
547
|
+
validationResult = {
|
|
548
|
+
...validateError,
|
|
549
|
+
...appendErrorsCurry(key, validateError.message)
|
|
550
|
+
};
|
|
551
|
+
setCustomValidity(validateError.message);
|
|
552
|
+
if (validateAllFieldCriteria) error[name] = validationResult;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (!isEmptyObject(validationResult)) {
|
|
556
|
+
error[name] = {
|
|
557
|
+
ref: inputRef,
|
|
558
|
+
...validationResult
|
|
559
|
+
};
|
|
560
|
+
if (!validateAllFieldCriteria) return error;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
setCustomValidity(true);
|
|
565
|
+
return error;
|
|
566
|
+
};
|
|
567
|
+
const defaultOptions = {
|
|
568
|
+
mode: VALIDATION_MODE.onSubmit,
|
|
569
|
+
reValidateMode: VALIDATION_MODE.onChange,
|
|
570
|
+
shouldFocusError: true
|
|
571
|
+
};
|
|
572
|
+
const FORM_ERROR_TYPE = "form";
|
|
573
|
+
const DEFAULT_FORM_STATE = {
|
|
574
|
+
submitCount: 0,
|
|
575
|
+
isDirty: false,
|
|
576
|
+
isReady: false,
|
|
577
|
+
isValidating: false,
|
|
578
|
+
isSubmitted: false,
|
|
579
|
+
isSubmitting: false,
|
|
580
|
+
isSubmitSuccessful: false,
|
|
581
|
+
isValid: false,
|
|
582
|
+
touchedFields: {},
|
|
583
|
+
dirtyFields: {},
|
|
584
|
+
validatingFields: {}
|
|
585
|
+
};
|
|
586
|
+
function createFormControl(props = {}) {
|
|
587
|
+
let _options = {
|
|
588
|
+
...defaultOptions,
|
|
589
|
+
...props
|
|
590
|
+
};
|
|
591
|
+
let _formState = {
|
|
592
|
+
...cloneObject(DEFAULT_FORM_STATE),
|
|
593
|
+
isLoading: isFunction(_options.defaultValues),
|
|
594
|
+
errors: _options.errors || {},
|
|
595
|
+
disabled: _options.disabled || false
|
|
596
|
+
};
|
|
597
|
+
let _fields = {};
|
|
598
|
+
let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values) ? cloneObject(_options.defaultValues || _options.values) || {} : {};
|
|
599
|
+
let _formValues = _options.shouldUnregister ? {} : cloneObject(_defaultValues);
|
|
600
|
+
let _state = {
|
|
601
|
+
action: false,
|
|
602
|
+
mount: false,
|
|
603
|
+
watch: false,
|
|
604
|
+
keepIsValid: false
|
|
605
|
+
};
|
|
606
|
+
let _names = {
|
|
607
|
+
mount: /* @__PURE__ */ new Set(),
|
|
608
|
+
disabled: /* @__PURE__ */ new Set(),
|
|
609
|
+
unMount: /* @__PURE__ */ new Set(),
|
|
610
|
+
array: /* @__PURE__ */ new Set(),
|
|
611
|
+
watch: /* @__PURE__ */ new Set(),
|
|
612
|
+
registerName: /* @__PURE__ */ new Set()
|
|
613
|
+
};
|
|
614
|
+
let delayErrorCallback;
|
|
615
|
+
let timer = 0;
|
|
616
|
+
let _valuesSubscriberCount = 0;
|
|
617
|
+
let _validationModeBeforeSubmit = getValidationModes(_options.mode);
|
|
618
|
+
let _validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
|
|
619
|
+
const defaultProxyFormState = {
|
|
620
|
+
isDirty: false,
|
|
621
|
+
dirtyFields: false,
|
|
622
|
+
validatingFields: false,
|
|
623
|
+
touchedFields: false,
|
|
624
|
+
isValidating: false,
|
|
625
|
+
isValid: false,
|
|
626
|
+
errors: false
|
|
627
|
+
};
|
|
628
|
+
const _proxyFormState = { ...defaultProxyFormState };
|
|
629
|
+
let _proxySubscribeFormState = { ..._proxyFormState };
|
|
630
|
+
const _subjects = {
|
|
631
|
+
array: createSubject(),
|
|
632
|
+
state: createSubject()
|
|
633
|
+
};
|
|
634
|
+
const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
|
|
635
|
+
const debounce = (callback) => (wait) => {
|
|
636
|
+
clearTimeout(timer);
|
|
637
|
+
timer = setTimeout(callback, wait);
|
|
638
|
+
};
|
|
639
|
+
const _setValid = async (shouldUpdateValid) => {
|
|
640
|
+
if (_state.keepIsValid) return;
|
|
641
|
+
if (!_options.disabled && (_proxyFormState.isValid || _proxySubscribeFormState.isValid || shouldUpdateValid)) {
|
|
642
|
+
let isValid;
|
|
643
|
+
if (_options.resolver) {
|
|
644
|
+
isValid = isEmptyObject((await _runSchema()).errors);
|
|
645
|
+
_updateIsValidating();
|
|
646
|
+
} else isValid = await executeBuiltInValidation({
|
|
647
|
+
fields: _fields,
|
|
648
|
+
onlyCheckValid: true,
|
|
649
|
+
eventType: EVENTS.VALID
|
|
650
|
+
});
|
|
651
|
+
if (isValid !== _formState.isValid) _subjects.state.next({ isValid });
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
const _updateIsValidating = (names, isValidating) => {
|
|
655
|
+
if (!_options.disabled && (_proxyFormState.isValidating || _proxyFormState.validatingFields || _proxySubscribeFormState.isValidating || _proxySubscribeFormState.validatingFields)) {
|
|
656
|
+
(names || Array.from(_names.mount)).forEach((name) => {
|
|
657
|
+
if (name) isValidating ? set(_formState.validatingFields, name, isValidating) : unset(_formState.validatingFields, name);
|
|
658
|
+
});
|
|
659
|
+
_subjects.state.next({
|
|
660
|
+
validatingFields: _formState.validatingFields,
|
|
661
|
+
isValidating: !isEmptyObject(_formState.validatingFields)
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
const _updateDirtyFields = () => {
|
|
666
|
+
_formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
|
|
667
|
+
};
|
|
668
|
+
const _setFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
|
|
669
|
+
if (args && method && !_options.disabled) {
|
|
670
|
+
_state.action = true;
|
|
671
|
+
if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
|
|
672
|
+
const fieldValues = method(get(_fields, name), args.argA, args.argB);
|
|
673
|
+
shouldSetValues && set(_fields, name, fieldValues);
|
|
674
|
+
}
|
|
675
|
+
if (shouldUpdateFieldsAndState && Array.isArray(get(_formState.errors, name))) {
|
|
676
|
+
const errors = method(get(_formState.errors, name), args.argA, args.argB);
|
|
677
|
+
shouldSetValues && set(_formState.errors, name, errors);
|
|
678
|
+
unsetEmptyArray(_formState.errors, name);
|
|
679
|
+
}
|
|
680
|
+
if ((_proxyFormState.touchedFields || _proxySubscribeFormState.touchedFields) && shouldUpdateFieldsAndState && Array.isArray(get(_formState.touchedFields, name))) {
|
|
681
|
+
const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
|
|
682
|
+
shouldSetValues && set(_formState.touchedFields, name, touchedFields);
|
|
683
|
+
}
|
|
684
|
+
if (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) _updateDirtyFields();
|
|
685
|
+
_subjects.state.next({
|
|
686
|
+
name,
|
|
687
|
+
isDirty: _getDirty(name, values),
|
|
688
|
+
dirtyFields: _formState.dirtyFields,
|
|
689
|
+
errors: _formState.errors,
|
|
690
|
+
isValid: _formState.isValid
|
|
691
|
+
});
|
|
692
|
+
} else set(_formValues, name, values);
|
|
693
|
+
};
|
|
694
|
+
const updateErrors = (name, error) => {
|
|
695
|
+
set(_formState.errors, name, error);
|
|
696
|
+
_formState.errors = { ..._formState.errors };
|
|
697
|
+
_subjects.state.next({ errors: _formState.errors });
|
|
698
|
+
};
|
|
699
|
+
const _setErrors = (errors) => {
|
|
700
|
+
_formState.errors = errors;
|
|
701
|
+
_subjects.state.next({
|
|
702
|
+
errors: _formState.errors,
|
|
703
|
+
isValid: false
|
|
704
|
+
});
|
|
705
|
+
};
|
|
706
|
+
const hasExplicitNullIntermediate = (name) => {
|
|
707
|
+
const segments = isKey(name) ? [name] : stringToPath(name);
|
|
708
|
+
let formValues = _formValues;
|
|
709
|
+
let defaultValues = _defaultValues;
|
|
710
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
711
|
+
const key = segments[i];
|
|
712
|
+
formValues = isNullOrUndefined(formValues) ? formValues : formValues[key];
|
|
713
|
+
defaultValues = isNullOrUndefined(defaultValues) ? defaultValues : defaultValues[key];
|
|
714
|
+
if (formValues === null && defaultValues !== null) return true;
|
|
715
|
+
}
|
|
716
|
+
return false;
|
|
717
|
+
};
|
|
718
|
+
const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
|
|
719
|
+
const field = get(_fields, name);
|
|
720
|
+
if (field) {
|
|
721
|
+
if (hasExplicitNullIntermediate(name)) return;
|
|
722
|
+
const wasUnsetInFormValues = isUndefined(get(_formValues, name));
|
|
723
|
+
const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
|
|
724
|
+
isUndefined(defaultValue) || ref && ref.defaultChecked || shouldSkipSetValueAs ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) : setFieldValue(name, defaultValue);
|
|
725
|
+
if (_state.mount && !_state.action) {
|
|
726
|
+
_setValid();
|
|
727
|
+
if (wasUnsetInFormValues && _formState.isDirty && (_proxyFormState.isDirty || _proxySubscribeFormState.isDirty)) {
|
|
728
|
+
if (!_getDirty()) {
|
|
729
|
+
_formState.isDirty = false;
|
|
730
|
+
_subjects.state.next({ ..._formState });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
if (props.shouldUnregister && wasUnsetInFormValues && !isUndefined(get(_formValues, name)) && isWatched(name, _names)) _state.watch = true;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
|
|
738
|
+
let shouldUpdateField = false;
|
|
739
|
+
let isPreviousDirty = false;
|
|
740
|
+
const output = { name };
|
|
741
|
+
if (!_options.disabled) {
|
|
742
|
+
if (!isBlurEvent || shouldDirty) {
|
|
743
|
+
const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
|
|
744
|
+
if (_proxyFormState.isDirty || _proxySubscribeFormState.isDirty) {
|
|
745
|
+
isPreviousDirty = _formState.isDirty;
|
|
746
|
+
_formState.isDirty = output.isDirty = !isCurrentFieldPristine || _getDirty();
|
|
747
|
+
shouldUpdateField = isPreviousDirty !== output.isDirty;
|
|
748
|
+
}
|
|
749
|
+
isPreviousDirty = !!get(_formState.dirtyFields, name);
|
|
750
|
+
if (isCurrentFieldPristine !== _formState.isDirty) _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
|
|
751
|
+
else isCurrentFieldPristine ? unset(_formState.dirtyFields, name) : set(_formState.dirtyFields, name, true);
|
|
752
|
+
output.dirtyFields = _formState.dirtyFields;
|
|
753
|
+
shouldUpdateField = shouldUpdateField || (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) && isPreviousDirty !== !isCurrentFieldPristine;
|
|
754
|
+
}
|
|
755
|
+
if (isBlurEvent) {
|
|
756
|
+
const isPreviousFieldTouched = get(_formState.touchedFields, name);
|
|
757
|
+
if (!isPreviousFieldTouched) {
|
|
758
|
+
set(_formState.touchedFields, name, isBlurEvent);
|
|
759
|
+
output.touchedFields = _formState.touchedFields;
|
|
760
|
+
shouldUpdateField = shouldUpdateField || (_proxyFormState.touchedFields || _proxySubscribeFormState.touchedFields) && isPreviousFieldTouched !== isBlurEvent;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
shouldUpdateField && shouldRender && _subjects.state.next(output);
|
|
764
|
+
}
|
|
765
|
+
return shouldUpdateField ? output : {};
|
|
766
|
+
};
|
|
767
|
+
const shouldRenderByError = (name, isValid, error, fieldState) => {
|
|
768
|
+
const previousFieldError = get(_formState.errors, name);
|
|
769
|
+
const shouldUpdateValid = (_proxyFormState.isValid || _proxySubscribeFormState.isValid) && isBoolean(isValid) && _formState.isValid !== isValid;
|
|
770
|
+
if (_options.delayError && error) {
|
|
771
|
+
delayErrorCallback = debounce(() => updateErrors(name, error));
|
|
772
|
+
delayErrorCallback(_options.delayError);
|
|
773
|
+
} else {
|
|
774
|
+
clearTimeout(timer);
|
|
775
|
+
delayErrorCallback = null;
|
|
776
|
+
error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
|
|
777
|
+
_formState.errors = { ..._formState.errors };
|
|
778
|
+
}
|
|
779
|
+
if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) || !isEmptyObject(fieldState) || shouldUpdateValid) {
|
|
780
|
+
const updatedFormState = {
|
|
781
|
+
...fieldState,
|
|
782
|
+
...shouldUpdateValid && isBoolean(isValid) ? { isValid } : {},
|
|
783
|
+
errors: _formState.errors,
|
|
784
|
+
name
|
|
785
|
+
};
|
|
786
|
+
_formState = {
|
|
787
|
+
..._formState,
|
|
788
|
+
...updatedFormState
|
|
789
|
+
};
|
|
790
|
+
_subjects.state.next(updatedFormState);
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
const _runSchema = async (name) => {
|
|
794
|
+
_updateIsValidating(name, true);
|
|
795
|
+
return await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
|
|
796
|
+
};
|
|
797
|
+
const executeSchemaAndUpdateState = async (names) => {
|
|
798
|
+
const { errors } = await _runSchema(names);
|
|
799
|
+
_updateIsValidating(names);
|
|
800
|
+
if (names) {
|
|
801
|
+
for (const name of names) {
|
|
802
|
+
const error = get(errors, name);
|
|
803
|
+
error ? _names.array.has(name) && isObject(error) && !Object.keys(error).some((key) => !Number.isNaN(Number(key))) ? updateFieldArrayRootError(_formState.errors, { [name]: error }, name) : set(_formState.errors, name, error) : unset(_formState.errors, name);
|
|
804
|
+
}
|
|
805
|
+
_formState.errors = { ..._formState.errors };
|
|
806
|
+
} else _formState.errors = errors;
|
|
807
|
+
return errors;
|
|
808
|
+
};
|
|
809
|
+
const validateForm = async ({ name, eventType }) => {
|
|
810
|
+
if (props.validate) {
|
|
811
|
+
const result = await props.validate({
|
|
812
|
+
formValues: _formValues,
|
|
813
|
+
formState: _formState,
|
|
814
|
+
name,
|
|
815
|
+
eventType
|
|
816
|
+
});
|
|
817
|
+
if (isObject(result)) for (const key in result) {
|
|
818
|
+
const error = result[key];
|
|
819
|
+
if (error) setError(`${FORM_ERROR_TYPE}.${key}`, {
|
|
820
|
+
message: isString(error.message) ? error.message : "",
|
|
821
|
+
type: error.type || INPUT_VALIDATION_RULES.validate
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
else if (isString(result) || !result) setError(FORM_ERROR_TYPE, {
|
|
825
|
+
message: result || "",
|
|
826
|
+
type: INPUT_VALIDATION_RULES.validate
|
|
827
|
+
});
|
|
828
|
+
else clearErrors(FORM_ERROR_TYPE);
|
|
829
|
+
return result;
|
|
830
|
+
}
|
|
831
|
+
return true;
|
|
832
|
+
};
|
|
833
|
+
const executeBuiltInValidation = async ({ fields, onlyCheckValid, name, eventType, context = {
|
|
834
|
+
valid: true,
|
|
835
|
+
runRootValidation: false
|
|
836
|
+
} }) => {
|
|
837
|
+
if (props.validate) {
|
|
838
|
+
context.runRootValidation = true;
|
|
839
|
+
if (!await validateForm({
|
|
840
|
+
name,
|
|
841
|
+
eventType
|
|
842
|
+
})) {
|
|
843
|
+
context.valid = false;
|
|
844
|
+
if (onlyCheckValid) return context.valid;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
for (const name in fields) {
|
|
848
|
+
const field = fields[name];
|
|
849
|
+
if (field) {
|
|
850
|
+
const { _f, ...fieldValue } = field;
|
|
851
|
+
if (_f) {
|
|
852
|
+
const isFieldArrayRoot = _names.array.has(_f.name);
|
|
853
|
+
const isPromiseFunction = field._f && hasPromiseValidation(field._f);
|
|
854
|
+
const shouldTrackIsValidatingState = _proxyFormState.validatingFields || _proxyFormState.isValidating || _proxySubscribeFormState.validatingFields || _proxySubscribeFormState.isValidating;
|
|
855
|
+
if (isPromiseFunction && shouldTrackIsValidatingState) _updateIsValidating([_f.name], true);
|
|
856
|
+
const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !onlyCheckValid, isFieldArrayRoot);
|
|
857
|
+
if (isPromiseFunction && shouldTrackIsValidatingState) _updateIsValidating([_f.name]);
|
|
858
|
+
if (fieldError[_f.name]) {
|
|
859
|
+
context.valid = false;
|
|
860
|
+
if (onlyCheckValid) break;
|
|
861
|
+
}
|
|
862
|
+
!onlyCheckValid && (get(fieldError, _f.name) ? isFieldArrayRoot ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name) : set(_formState.errors, _f.name, fieldError[_f.name]) : unset(_formState.errors, _f.name));
|
|
863
|
+
if (props.shouldUseNativeValidation && fieldError[_f.name]) break;
|
|
864
|
+
}
|
|
865
|
+
!isEmptyObject(fieldValue) && await executeBuiltInValidation({
|
|
866
|
+
context,
|
|
867
|
+
onlyCheckValid,
|
|
868
|
+
fields: fieldValue,
|
|
869
|
+
name,
|
|
870
|
+
eventType
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return context.valid;
|
|
875
|
+
};
|
|
876
|
+
const _removeUnmounted = () => {
|
|
877
|
+
for (const name of _names.unMount) {
|
|
878
|
+
const field = get(_fields, name);
|
|
879
|
+
field && (field._f.refs ? field._f.refs.every((ref) => !live(ref)) : !live(field._f.ref)) && unregister(name);
|
|
880
|
+
}
|
|
881
|
+
_names.unMount = /* @__PURE__ */ new Set();
|
|
882
|
+
};
|
|
883
|
+
const _getDirty = (name, data) => !_options.disabled && (name && data && set(_formValues, name, data), !deepEqual(_state.mount ? _formValues : _defaultValues, _defaultValues));
|
|
884
|
+
const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, { ..._state.mount ? _formValues : isUndefined(defaultValue) ? _defaultValues : isString(names) ? { [names]: defaultValue } : defaultValue }, isGlobal, defaultValue);
|
|
885
|
+
const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : []));
|
|
886
|
+
const setFieldValue = (name, value, options = {}, skipClone = false, skipRender = false) => {
|
|
887
|
+
const field = get(_fields, name);
|
|
888
|
+
let fieldValue = value;
|
|
889
|
+
if (field) {
|
|
890
|
+
const fieldReference = field._f;
|
|
891
|
+
if (fieldReference) {
|
|
892
|
+
!fieldReference.disabled && set(_formValues, name, getFieldValueAs(value, fieldReference));
|
|
893
|
+
fieldValue = isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ? "" : value;
|
|
894
|
+
if (isMultipleSelect(fieldReference.ref)) [...fieldReference.ref.options].forEach((optionRef) => optionRef.selected = fieldValue.includes(optionRef.value));
|
|
895
|
+
else if (fieldReference.refs) if (isCheckBoxInput(fieldReference.ref)) fieldReference.refs.forEach((checkboxRef) => {
|
|
896
|
+
if (!checkboxRef.defaultChecked || !checkboxRef.disabled) if (Array.isArray(fieldValue)) checkboxRef.checked = !!fieldValue.find((data) => data === checkboxRef.value);
|
|
897
|
+
else checkboxRef.checked = fieldValue === checkboxRef.value || !!fieldValue;
|
|
898
|
+
});
|
|
899
|
+
else fieldReference.refs.forEach((radioRef) => radioRef.checked = radioRef.value === fieldValue);
|
|
900
|
+
else if (isFileInput(fieldReference.ref)) fieldReference.ref.value = "";
|
|
901
|
+
else {
|
|
902
|
+
fieldReference.ref.value = fieldValue;
|
|
903
|
+
if (!fieldReference.ref.type && !skipRender) _subjects.state.next({
|
|
904
|
+
name,
|
|
905
|
+
values: skipClone ? _formValues : cloneObject(_formValues)
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
(options.shouldDirty || options.shouldTouch) && updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, !skipRender);
|
|
911
|
+
options.shouldValidate && trigger(name);
|
|
912
|
+
};
|
|
913
|
+
const setFieldValues = (name, value, options, skipClone = false, skipRender = false) => {
|
|
914
|
+
for (const fieldKey in value) {
|
|
915
|
+
if (!value.hasOwnProperty(fieldKey)) return;
|
|
916
|
+
const fieldValue = value[fieldKey];
|
|
917
|
+
const fieldName = name + "." + fieldKey;
|
|
918
|
+
const field = get(_fields, fieldName);
|
|
919
|
+
(_names.array.has(name) || isObject(fieldValue) || field && !field._f) && !isDateObject(fieldValue) ? setFieldValues(fieldName, fieldValue, options, skipClone, skipRender) : setFieldValue(fieldName, fieldValue, options, skipClone, skipRender);
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
const _setValue = (name, value, options, skipClone, skipStateEmit = false) => {
|
|
923
|
+
const field = get(_fields, name);
|
|
924
|
+
const isFieldArray = _names.array.has(name);
|
|
925
|
+
const cloneValue = skipClone ? value : cloneObject(value);
|
|
926
|
+
const isValueUnchanged = deepEqual(get(_formValues, name), cloneValue);
|
|
927
|
+
if (!isValueUnchanged) set(_formValues, name, cloneValue);
|
|
928
|
+
if (isFieldArray) {
|
|
929
|
+
_subjects.array.next({
|
|
930
|
+
name,
|
|
931
|
+
values: skipClone ? _formValues : cloneObject(_formValues)
|
|
932
|
+
});
|
|
933
|
+
if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields || _proxySubscribeFormState.isDirty || _proxySubscribeFormState.dirtyFields) && options.shouldDirty) {
|
|
934
|
+
_updateDirtyFields();
|
|
935
|
+
if (!skipStateEmit) _subjects.state.next({
|
|
936
|
+
name,
|
|
937
|
+
dirtyFields: _formState.dirtyFields,
|
|
938
|
+
isDirty: _getDirty(name, cloneValue)
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
} else {
|
|
942
|
+
const isEmpty = Array.isArray(cloneValue) && !cloneValue.length || isEmptyObject(cloneValue);
|
|
943
|
+
if (!field || field._f || isNullOrUndefined(cloneValue) || isEmpty) setFieldValue(name, cloneValue, options, skipClone, skipStateEmit);
|
|
944
|
+
else setFieldValues(name, cloneValue, options, skipClone, skipStateEmit);
|
|
945
|
+
}
|
|
946
|
+
if (!isValueUnchanged && !skipStateEmit) {
|
|
947
|
+
const watched = isWatched(name, _names);
|
|
948
|
+
const values = skipClone ? _formValues : cloneObject(_formValues);
|
|
949
|
+
_subjects.state.next({
|
|
950
|
+
...watched && _formState,
|
|
951
|
+
name: _state.mount || watched ? name : void 0,
|
|
952
|
+
values
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
const setValue = (name, value, options = {}) => _setValue(name, value, options, false);
|
|
957
|
+
const setValues = (formValues, options = {}) => {
|
|
958
|
+
const updatedFormValues = isFunction(formValues) ? formValues(_formValues) : formValues;
|
|
959
|
+
if (!deepEqual(_formValues, updatedFormValues)) {
|
|
960
|
+
_formValues = {
|
|
961
|
+
..._formValues,
|
|
962
|
+
...updatedFormValues
|
|
963
|
+
};
|
|
964
|
+
for (const fieldName of _names.mount) _setValue(fieldName, get(updatedFormValues, fieldName), options, true, true);
|
|
965
|
+
_subjects.state.next({
|
|
966
|
+
..._formState,
|
|
967
|
+
name: void 0,
|
|
968
|
+
type: void 0,
|
|
969
|
+
..._valuesSubscriberCount ? { values: _formValues } : {}
|
|
970
|
+
});
|
|
971
|
+
if (options.shouldValidate) _setValid();
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
const onChange = async (event) => {
|
|
975
|
+
_state.mount = true;
|
|
976
|
+
const target = event.target;
|
|
977
|
+
let name = target.name;
|
|
978
|
+
let isFieldValueUpdated = true;
|
|
979
|
+
const field = get(_fields, name);
|
|
980
|
+
const _updateIsFieldValueUpdated = (fieldValue) => {
|
|
981
|
+
isFieldValueUpdated = Number.isNaN(fieldValue) || isDateObject(fieldValue) && isNaN(fieldValue.getTime()) || deepEqual(fieldValue, get(_formValues, name, fieldValue));
|
|
982
|
+
};
|
|
983
|
+
if (field) {
|
|
984
|
+
let error;
|
|
985
|
+
let isValid;
|
|
986
|
+
const fieldValue = target.type ? getFieldValue(field._f) : getEventValue(event);
|
|
987
|
+
const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
|
|
988
|
+
const hasNoValidationEffect = !hasValidation(field._f) && !props.validate && !_options.resolver && !get(_formState.errors, name) && !field._f.deps;
|
|
989
|
+
const shouldSkipValidation = hasNoValidationEffect || skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, _validationModeAfterSubmit, _validationModeBeforeSubmit);
|
|
990
|
+
const watched = isWatched(name, _names, isBlurEvent);
|
|
991
|
+
set(_formValues, name, fieldValue);
|
|
992
|
+
if (isBlurEvent) {
|
|
993
|
+
if (!target || !target.readOnly) {
|
|
994
|
+
field._f.onBlur && field._f.onBlur(event);
|
|
995
|
+
delayErrorCallback && delayErrorCallback(0);
|
|
996
|
+
}
|
|
997
|
+
} else if (field._f.onChange) field._f.onChange(event);
|
|
998
|
+
const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent);
|
|
999
|
+
const shouldRender = !isEmptyObject(fieldState) || watched;
|
|
1000
|
+
!isBlurEvent && _subjects.state.next({
|
|
1001
|
+
name,
|
|
1002
|
+
type: event.type,
|
|
1003
|
+
..._valuesSubscriberCount ? { values: cloneObject(_formValues) } : {}
|
|
1004
|
+
});
|
|
1005
|
+
if (shouldSkipValidation) {
|
|
1006
|
+
if ((!hasNoValidationEffect || !_formState.isValid) && (_proxyFormState.isValid || _proxySubscribeFormState.isValid)) {
|
|
1007
|
+
if (_options.mode === "onBlur") {
|
|
1008
|
+
if (isBlurEvent) _setValid();
|
|
1009
|
+
} else if (!isBlurEvent) _setValid();
|
|
1010
|
+
}
|
|
1011
|
+
return shouldRender && _subjects.state.next({
|
|
1012
|
+
name,
|
|
1013
|
+
...watched ? {} : fieldState
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
if (!_options.resolver && props.validate) await validateForm({
|
|
1017
|
+
name,
|
|
1018
|
+
eventType: event.type
|
|
1019
|
+
});
|
|
1020
|
+
!isBlurEvent && watched && _subjects.state.next({ ..._formState });
|
|
1021
|
+
if (_options.resolver) {
|
|
1022
|
+
const { errors } = await _runSchema([name]);
|
|
1023
|
+
_updateIsValidating([name]);
|
|
1024
|
+
_updateIsFieldValueUpdated(fieldValue);
|
|
1025
|
+
if (!isFieldValueUpdated) {
|
|
1026
|
+
!isEmptyObject(fieldState) && _subjects.state.next(fieldState);
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
|
|
1030
|
+
const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
|
|
1031
|
+
error = errorLookupResult.error;
|
|
1032
|
+
name = errorLookupResult.name;
|
|
1033
|
+
isValid = isEmptyObject(errors);
|
|
1034
|
+
} else {
|
|
1035
|
+
_updateIsValidating([name], true);
|
|
1036
|
+
error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
|
|
1037
|
+
_updateIsValidating([name]);
|
|
1038
|
+
_updateIsFieldValueUpdated(fieldValue);
|
|
1039
|
+
if (isFieldValueUpdated) {
|
|
1040
|
+
if (error) isValid = false;
|
|
1041
|
+
else if (_proxyFormState.isValid || _proxySubscribeFormState.isValid) isValid = await executeBuiltInValidation({
|
|
1042
|
+
fields: _fields,
|
|
1043
|
+
onlyCheckValid: true,
|
|
1044
|
+
name,
|
|
1045
|
+
eventType: event.type
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
if (isFieldValueUpdated) {
|
|
1050
|
+
field._f.deps && (!Array.isArray(field._f.deps) || field._f.deps.length > 0) && trigger(field._f.deps);
|
|
1051
|
+
shouldRenderByError(name, isValid, error, fieldState);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
const _focusInput = (ref, key) => {
|
|
1056
|
+
if (get(_formState.errors, key) && ref.focus) {
|
|
1057
|
+
ref.focus();
|
|
1058
|
+
return 1;
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
const trigger = async (name, options = {}) => {
|
|
1062
|
+
let isValid;
|
|
1063
|
+
let validationResult;
|
|
1064
|
+
const fieldNames = convertToArrayPayload(name);
|
|
1065
|
+
if (_options.resolver) {
|
|
1066
|
+
const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
|
|
1067
|
+
isValid = isEmptyObject(errors);
|
|
1068
|
+
validationResult = name ? !fieldNames.some((name) => get(errors, name)) : isValid;
|
|
1069
|
+
} else if (name) {
|
|
1070
|
+
validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
|
|
1071
|
+
const field = get(_fields, fieldName);
|
|
1072
|
+
return await executeBuiltInValidation({
|
|
1073
|
+
fields: field && field._f ? { [fieldName]: field } : field,
|
|
1074
|
+
eventType: EVENTS.TRIGGER
|
|
1075
|
+
});
|
|
1076
|
+
}))).every(Boolean);
|
|
1077
|
+
!(!validationResult && !_formState.isValid) && _setValid();
|
|
1078
|
+
} else validationResult = isValid = await executeBuiltInValidation({
|
|
1079
|
+
fields: _fields,
|
|
1080
|
+
name,
|
|
1081
|
+
eventType: EVENTS.TRIGGER
|
|
1082
|
+
});
|
|
1083
|
+
_subjects.state.next({
|
|
1084
|
+
...!isString(name) || (_proxyFormState.isValid || _proxySubscribeFormState.isValid) && isValid !== _formState.isValid ? {} : { name },
|
|
1085
|
+
..._options.resolver || !name ? { isValid } : {},
|
|
1086
|
+
errors: _formState.errors
|
|
1087
|
+
});
|
|
1088
|
+
options.shouldFocus && !validationResult && iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
|
|
1089
|
+
return validationResult;
|
|
1090
|
+
};
|
|
1091
|
+
const getValues = (fieldNames, config) => {
|
|
1092
|
+
let values = { ..._state.mount ? _formValues : _defaultValues };
|
|
1093
|
+
if (config) values = extractFormValues(config.dirtyFields ? _formState.dirtyFields : _formState.touchedFields, values);
|
|
1094
|
+
return isUndefined(fieldNames) ? values : isString(fieldNames) ? get(values, fieldNames) : fieldNames.map((name) => get(values, name));
|
|
1095
|
+
};
|
|
1096
|
+
const getFieldState = (name, formState) => ({
|
|
1097
|
+
invalid: !!get((formState || _formState).errors, name),
|
|
1098
|
+
isDirty: !!get((formState || _formState).dirtyFields, name),
|
|
1099
|
+
error: get((formState || _formState).errors, name),
|
|
1100
|
+
isValidating: !!get(_formState.validatingFields, name),
|
|
1101
|
+
isTouched: !!get((formState || _formState).touchedFields, name)
|
|
1102
|
+
});
|
|
1103
|
+
const clearErrors = (name) => {
|
|
1104
|
+
const names = name ? convertToArrayPayload(name) : void 0;
|
|
1105
|
+
names === null || names === void 0 || names.forEach((inputName) => unset(_formState.errors, inputName));
|
|
1106
|
+
if (names) names.forEach((inputName) => {
|
|
1107
|
+
_subjects.state.next({
|
|
1108
|
+
name: inputName,
|
|
1109
|
+
errors: _formState.errors
|
|
1110
|
+
});
|
|
1111
|
+
});
|
|
1112
|
+
else _subjects.state.next({ errors: {} });
|
|
1113
|
+
};
|
|
1114
|
+
const setError = (name, error, options) => {
|
|
1115
|
+
const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
|
|
1116
|
+
const { ref: currentRef, message, type, ...restOfErrorTree } = get(_formState.errors, name) || {};
|
|
1117
|
+
set(_formState.errors, name, {
|
|
1118
|
+
...restOfErrorTree,
|
|
1119
|
+
...error,
|
|
1120
|
+
ref
|
|
1121
|
+
});
|
|
1122
|
+
_subjects.state.next({
|
|
1123
|
+
name,
|
|
1124
|
+
errors: _formState.errors,
|
|
1125
|
+
isValid: false
|
|
1126
|
+
});
|
|
1127
|
+
options && options.shouldFocus && ref && ref.focus && ref.focus();
|
|
1128
|
+
};
|
|
1129
|
+
const watch = (name, defaultValue) => {
|
|
1130
|
+
if (isFunction(name)) {
|
|
1131
|
+
_valuesSubscriberCount++;
|
|
1132
|
+
const { unsubscribe } = _subjects.state.subscribe({ next: (payload) => "values" in payload && name(payload.values || _getWatch(void 0, defaultValue), payload) });
|
|
1133
|
+
let called = false;
|
|
1134
|
+
return { unsubscribe: () => {
|
|
1135
|
+
if (called) return;
|
|
1136
|
+
called = true;
|
|
1137
|
+
_valuesSubscriberCount--;
|
|
1138
|
+
unsubscribe();
|
|
1139
|
+
} };
|
|
1140
|
+
}
|
|
1141
|
+
return _getWatch(name, defaultValue, true);
|
|
1142
|
+
};
|
|
1143
|
+
const _subscribe = (props) => {
|
|
1144
|
+
var _a;
|
|
1145
|
+
const needsValues = !!((_a = props.formState) === null || _a === void 0 ? void 0 : _a.values);
|
|
1146
|
+
if (needsValues) _valuesSubscriberCount++;
|
|
1147
|
+
const { unsubscribe } = _subjects.state.subscribe({ next: (formState) => {
|
|
1148
|
+
if (shouldSubscribeByName(props.name, formState.name, props.exact) && shouldRenderFormState(formState, props.formState || _proxyFormState, _setFormState, props.reRenderRoot)) {
|
|
1149
|
+
const snapshot = { ..._formValues };
|
|
1150
|
+
props.callback({
|
|
1151
|
+
values: snapshot,
|
|
1152
|
+
..._formState,
|
|
1153
|
+
...formState,
|
|
1154
|
+
defaultValues: _defaultValues
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
} });
|
|
1158
|
+
if (!needsValues) return unsubscribe;
|
|
1159
|
+
let called = false;
|
|
1160
|
+
return () => {
|
|
1161
|
+
if (called) return;
|
|
1162
|
+
called = true;
|
|
1163
|
+
_valuesSubscriberCount--;
|
|
1164
|
+
unsubscribe();
|
|
1165
|
+
};
|
|
1166
|
+
};
|
|
1167
|
+
const subscribe = (props) => {
|
|
1168
|
+
_state.mount = true;
|
|
1169
|
+
_proxySubscribeFormState = {
|
|
1170
|
+
..._proxySubscribeFormState,
|
|
1171
|
+
...props.formState
|
|
1172
|
+
};
|
|
1173
|
+
return _subscribe({
|
|
1174
|
+
...props,
|
|
1175
|
+
formState: {
|
|
1176
|
+
...defaultProxyFormState,
|
|
1177
|
+
...props.formState
|
|
1178
|
+
}
|
|
1179
|
+
});
|
|
1180
|
+
};
|
|
1181
|
+
const unregister = (name, options = {}) => {
|
|
1182
|
+
for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
|
|
1183
|
+
_names.mount.delete(fieldName);
|
|
1184
|
+
_names.array.delete(fieldName);
|
|
1185
|
+
if (!options.keepValue) {
|
|
1186
|
+
unset(_fields, fieldName);
|
|
1187
|
+
unset(_formValues, fieldName);
|
|
1188
|
+
}
|
|
1189
|
+
!options.keepError && unset(_formState.errors, fieldName);
|
|
1190
|
+
!options.keepDirty && unset(_formState.dirtyFields, fieldName);
|
|
1191
|
+
!options.keepTouched && unset(_formState.touchedFields, fieldName);
|
|
1192
|
+
!options.keepIsValidating && unset(_formState.validatingFields, fieldName);
|
|
1193
|
+
!_options.shouldUnregister && !options.keepDefaultValue && unset(_defaultValues, fieldName);
|
|
1194
|
+
}
|
|
1195
|
+
_subjects.state.next({ values: cloneObject(_formValues) });
|
|
1196
|
+
_subjects.state.next({
|
|
1197
|
+
..._formState,
|
|
1198
|
+
...!options.keepDirty ? {} : { isDirty: _getDirty() }
|
|
1199
|
+
});
|
|
1200
|
+
!options.keepIsValid && _setValid();
|
|
1201
|
+
};
|
|
1202
|
+
const _setDisabledField = ({ disabled, name }) => {
|
|
1203
|
+
if (isBoolean(disabled) && _state.mount || !!disabled || _names.disabled.has(name)) {
|
|
1204
|
+
const disabledStateChanged = _names.disabled.has(name) !== !!disabled;
|
|
1205
|
+
disabled ? _names.disabled.add(name) : _names.disabled.delete(name);
|
|
1206
|
+
disabledStateChanged && _state.mount && !_state.action && _setValid();
|
|
1207
|
+
}
|
|
1208
|
+
};
|
|
1209
|
+
const register = (name, options = {}) => {
|
|
1210
|
+
let field = get(_fields, name);
|
|
1211
|
+
const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled);
|
|
1212
|
+
const shouldRevalidateRemount = !_names.registerName.has(name) && field && field._f && !field._f.mount;
|
|
1213
|
+
set(_fields, name, {
|
|
1214
|
+
...field || {},
|
|
1215
|
+
_f: {
|
|
1216
|
+
...field && field._f ? field._f : { ref: { name } },
|
|
1217
|
+
name,
|
|
1218
|
+
mount: true,
|
|
1219
|
+
...options
|
|
1220
|
+
}
|
|
1221
|
+
});
|
|
1222
|
+
_names.mount.add(name);
|
|
1223
|
+
if (field && !shouldRevalidateRemount) _setDisabledField({
|
|
1224
|
+
disabled: isBoolean(options.disabled) ? options.disabled : _options.disabled,
|
|
1225
|
+
name
|
|
1226
|
+
});
|
|
1227
|
+
else updateValidAndValue(name, true, options.value);
|
|
1228
|
+
return {
|
|
1229
|
+
...disabledIsDefined ? { disabled: options.disabled || _options.disabled } : {},
|
|
1230
|
+
..._options.progressive ? {
|
|
1231
|
+
required: !!options.required,
|
|
1232
|
+
min: getRuleValue(options.min),
|
|
1233
|
+
max: getRuleValue(options.max),
|
|
1234
|
+
minLength: getRuleValue(options.minLength),
|
|
1235
|
+
maxLength: getRuleValue(options.maxLength),
|
|
1236
|
+
pattern: getRuleValue(options.pattern)
|
|
1237
|
+
} : {},
|
|
1238
|
+
name,
|
|
1239
|
+
onChange,
|
|
1240
|
+
onBlur: onChange,
|
|
1241
|
+
ref: (ref) => {
|
|
1242
|
+
if (ref) {
|
|
1243
|
+
_names.registerName.add(name);
|
|
1244
|
+
register(name, options);
|
|
1245
|
+
_names.registerName.delete(name);
|
|
1246
|
+
field = get(_fields, name);
|
|
1247
|
+
const fieldRef = isUndefined(ref.value) ? ref.querySelectorAll ? ref.querySelectorAll("input,select,textarea")[0] || ref : ref : ref;
|
|
1248
|
+
const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
|
|
1249
|
+
const refs = field._f.refs || [];
|
|
1250
|
+
if (radioOrCheckbox ? refs.find((option) => option === fieldRef) : fieldRef === field._f.ref) return;
|
|
1251
|
+
set(_fields, name, { _f: {
|
|
1252
|
+
...field._f,
|
|
1253
|
+
...radioOrCheckbox ? {
|
|
1254
|
+
refs: [
|
|
1255
|
+
...refs.filter(live),
|
|
1256
|
+
fieldRef,
|
|
1257
|
+
...Array.isArray(get(_defaultValues, name)) ? [{}] : []
|
|
1258
|
+
],
|
|
1259
|
+
ref: {
|
|
1260
|
+
type: fieldRef.type,
|
|
1261
|
+
name
|
|
1262
|
+
}
|
|
1263
|
+
} : { ref: fieldRef }
|
|
1264
|
+
} });
|
|
1265
|
+
updateValidAndValue(name, false, void 0, fieldRef);
|
|
1266
|
+
} else {
|
|
1267
|
+
field = get(_fields, name, {});
|
|
1268
|
+
if (field._f) field._f.mount = false;
|
|
1269
|
+
(_options.shouldUnregister || options.shouldUnregister) && !(isNameInFieldArray(_names.array, name) && _state.action) && _names.unMount.add(name);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
};
|
|
1274
|
+
const _focusError = () => _options.shouldFocusError && !_options.shouldUseNativeValidation && iterateFieldsByAction(_fields, _focusInput, _names.mount);
|
|
1275
|
+
const _disableForm = (disabled) => {
|
|
1276
|
+
if (isBoolean(disabled)) {
|
|
1277
|
+
_subjects.state.next({ disabled });
|
|
1278
|
+
iterateFieldsByAction(_fields, (ref, name) => {
|
|
1279
|
+
const currentField = get(_fields, name);
|
|
1280
|
+
if (currentField) {
|
|
1281
|
+
ref.disabled = currentField._f.disabled || disabled;
|
|
1282
|
+
if (Array.isArray(currentField._f.refs)) currentField._f.refs.forEach((inputRef) => {
|
|
1283
|
+
inputRef.disabled = currentField._f.disabled || disabled;
|
|
1284
|
+
});
|
|
1285
|
+
}
|
|
1286
|
+
}, 0, false);
|
|
1287
|
+
}
|
|
1288
|
+
};
|
|
1289
|
+
const handleSubmit = (onValid, onInvalid) => async (e) => {
|
|
1290
|
+
let onValidError = void 0;
|
|
1291
|
+
if (e) {
|
|
1292
|
+
e.preventDefault && e.preventDefault();
|
|
1293
|
+
e.persist && e.persist();
|
|
1294
|
+
}
|
|
1295
|
+
let fieldValues = cloneObject(_formValues);
|
|
1296
|
+
_subjects.state.next({ isSubmitting: true });
|
|
1297
|
+
if (_options.resolver) {
|
|
1298
|
+
const { errors, values } = await _runSchema();
|
|
1299
|
+
_updateIsValidating();
|
|
1300
|
+
_formState.errors = errors;
|
|
1301
|
+
fieldValues = cloneObject(values);
|
|
1302
|
+
} else await executeBuiltInValidation({
|
|
1303
|
+
fields: _fields,
|
|
1304
|
+
eventType: EVENTS.SUBMIT
|
|
1305
|
+
});
|
|
1306
|
+
if (_names.disabled.size) for (const name of _names.disabled) unset(fieldValues, name);
|
|
1307
|
+
unset(_formState.errors, ROOT_ERROR_TYPE);
|
|
1308
|
+
if (isEmptyObject(_formState.errors)) {
|
|
1309
|
+
_subjects.state.next({ errors: {} });
|
|
1310
|
+
try {
|
|
1311
|
+
await onValid(fieldValues, e);
|
|
1312
|
+
} catch (error) {
|
|
1313
|
+
onValidError = error;
|
|
1314
|
+
}
|
|
1315
|
+
} else {
|
|
1316
|
+
if (onInvalid) await onInvalid({ ..._formState.errors }, e);
|
|
1317
|
+
_focusError();
|
|
1318
|
+
setTimeout(_focusError);
|
|
1319
|
+
}
|
|
1320
|
+
_subjects.state.next({
|
|
1321
|
+
isSubmitted: true,
|
|
1322
|
+
isSubmitting: false,
|
|
1323
|
+
isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
|
|
1324
|
+
submitCount: _formState.submitCount + 1,
|
|
1325
|
+
errors: _formState.errors
|
|
1326
|
+
});
|
|
1327
|
+
if (onValidError) throw onValidError;
|
|
1328
|
+
};
|
|
1329
|
+
const resetField = (name, options = {}) => {
|
|
1330
|
+
if (get(_fields, name)) {
|
|
1331
|
+
if (isUndefined(options.defaultValue)) setValue(name, cloneObject(get(_defaultValues, name)));
|
|
1332
|
+
else {
|
|
1333
|
+
setValue(name, options.defaultValue);
|
|
1334
|
+
set(_defaultValues, name, cloneObject(options.defaultValue));
|
|
1335
|
+
}
|
|
1336
|
+
if (!options.keepTouched) unset(_formState.touchedFields, name);
|
|
1337
|
+
if (!options.keepDirty) {
|
|
1338
|
+
unset(_formState.dirtyFields, name);
|
|
1339
|
+
_formState.isDirty = options.defaultValue ? _getDirty(name, cloneObject(get(_defaultValues, name))) : _getDirty();
|
|
1340
|
+
}
|
|
1341
|
+
if (!options.keepError) {
|
|
1342
|
+
unset(_formState.errors, name);
|
|
1343
|
+
_proxyFormState.isValid && _setValid();
|
|
1344
|
+
}
|
|
1345
|
+
_subjects.state.next({ ..._formState });
|
|
1346
|
+
}
|
|
1347
|
+
};
|
|
1348
|
+
const _reset = (formValues, keepStateOptions = {}) => {
|
|
1349
|
+
const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
|
|
1350
|
+
const cloneUpdatedValues = cloneObject(updatedValues);
|
|
1351
|
+
const isEmptyResetValues = isEmptyObject(formValues);
|
|
1352
|
+
const values = cloneUpdatedValues;
|
|
1353
|
+
if (!keepStateOptions.keepDefaultValues) _defaultValues = updatedValues;
|
|
1354
|
+
if (!keepStateOptions.keepValues) {
|
|
1355
|
+
if (keepStateOptions.keepDirtyValues) {
|
|
1356
|
+
const fieldsToCheck = /* @__PURE__ */ new Set([..._names.mount, ...Object.keys(getDirtyFields(_defaultValues, _formValues))]);
|
|
1357
|
+
for (const fieldName of Array.from(fieldsToCheck)) {
|
|
1358
|
+
const isDirty = get(_formState.dirtyFields, fieldName);
|
|
1359
|
+
const existingValue = get(_formValues, fieldName);
|
|
1360
|
+
const newValue = get(values, fieldName);
|
|
1361
|
+
if (isDirty && !isUndefined(existingValue)) set(values, fieldName, existingValue);
|
|
1362
|
+
else if (!isDirty && !isUndefined(newValue)) setValue(fieldName, newValue);
|
|
1363
|
+
}
|
|
1364
|
+
} else {
|
|
1365
|
+
if (isWeb && isUndefined(formValues)) for (const name of _names.mount) {
|
|
1366
|
+
const field = get(_fields, name);
|
|
1367
|
+
if (field && field._f) {
|
|
1368
|
+
const fieldReference = Array.isArray(field._f.refs) ? field._f.refs[0] : field._f.ref;
|
|
1369
|
+
if (isHTMLElement(fieldReference)) {
|
|
1370
|
+
const form = fieldReference.closest("form");
|
|
1371
|
+
if (form) {
|
|
1372
|
+
form.reset();
|
|
1373
|
+
break;
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
if (keepStateOptions.keepFieldsRef) for (const fieldName of _names.mount) setValue(fieldName, get(values, fieldName));
|
|
1379
|
+
else _fields = {};
|
|
1380
|
+
}
|
|
1381
|
+
if (_options.shouldUnregister) {
|
|
1382
|
+
_formValues = keepStateOptions.keepDefaultValues ? cloneObject(_defaultValues) : {};
|
|
1383
|
+
if (keepStateOptions.keepFieldsRef) for (const fieldName of _names.mount) set(_formValues, fieldName, get(values, fieldName));
|
|
1384
|
+
} else _formValues = cloneObject(values);
|
|
1385
|
+
_subjects.array.next({ values: { ...values } });
|
|
1386
|
+
_subjects.state.next({ values: { ...values } });
|
|
1387
|
+
}
|
|
1388
|
+
_names = {
|
|
1389
|
+
mount: keepStateOptions.keepDirtyValues ? _names.mount : /* @__PURE__ */ new Set(),
|
|
1390
|
+
unMount: /* @__PURE__ */ new Set(),
|
|
1391
|
+
array: /* @__PURE__ */ new Set(),
|
|
1392
|
+
registerName: /* @__PURE__ */ new Set(),
|
|
1393
|
+
disabled: /* @__PURE__ */ new Set(),
|
|
1394
|
+
watch: /* @__PURE__ */ new Set(),
|
|
1395
|
+
watchAll: false,
|
|
1396
|
+
focus: ""
|
|
1397
|
+
};
|
|
1398
|
+
_state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid || !!keepStateOptions.keepDirtyValues || !_options.shouldUnregister && !isEmptyObject(values);
|
|
1399
|
+
_state.watch = !!_options.shouldUnregister;
|
|
1400
|
+
_state.keepIsValid = !!keepStateOptions.keepIsValid;
|
|
1401
|
+
_state.action = false;
|
|
1402
|
+
if (!keepStateOptions.keepErrors) _formState.errors = {};
|
|
1403
|
+
_subjects.state.next({
|
|
1404
|
+
submitCount: keepStateOptions.keepSubmitCount ? _formState.submitCount : 0,
|
|
1405
|
+
isDirty: isEmptyResetValues ? false : keepStateOptions.keepDirty ? _formState.isDirty : keepStateOptions.keepValues ? _getDirty() : !!(keepStateOptions.keepDefaultValues && !deepEqual(formValues, _defaultValues)),
|
|
1406
|
+
isSubmitted: keepStateOptions.keepIsSubmitted ? _formState.isSubmitted : false,
|
|
1407
|
+
dirtyFields: isEmptyResetValues ? {} : keepStateOptions.keepDirtyValues ? keepStateOptions.keepDefaultValues && _formValues ? getDirtyFields(_defaultValues, _formValues) : _formState.dirtyFields : keepStateOptions.keepDefaultValues && formValues ? getDirtyFields(_defaultValues, formValues) : keepStateOptions.keepDirty ? _formState.dirtyFields : {},
|
|
1408
|
+
touchedFields: keepStateOptions.keepTouched ? _formState.touchedFields : {},
|
|
1409
|
+
errors: keepStateOptions.keepErrors ? _formState.errors : {},
|
|
1410
|
+
isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful ? _formState.isSubmitSuccessful : false,
|
|
1411
|
+
isSubmitting: false,
|
|
1412
|
+
defaultValues: _defaultValues
|
|
1413
|
+
});
|
|
1414
|
+
};
|
|
1415
|
+
const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues) ? formValues(_formValues) : formValues, {
|
|
1416
|
+
..._options.resetOptions,
|
|
1417
|
+
...keepStateOptions
|
|
1418
|
+
});
|
|
1419
|
+
const setFocus = (name, options = {}) => {
|
|
1420
|
+
const field = get(_fields, name);
|
|
1421
|
+
const fieldReference = field && field._f;
|
|
1422
|
+
if (fieldReference) {
|
|
1423
|
+
const fieldRef = fieldReference.refs ? fieldReference.refs[0] : fieldReference.ref;
|
|
1424
|
+
if (fieldRef.focus) setTimeout(() => {
|
|
1425
|
+
fieldRef.focus();
|
|
1426
|
+
options.shouldSelect && isFunction(fieldRef.select) && fieldRef.select();
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
const _setFormState = (updatedFormState) => {
|
|
1431
|
+
_formState = {
|
|
1432
|
+
..._formState,
|
|
1433
|
+
...updatedFormState
|
|
1434
|
+
};
|
|
1435
|
+
};
|
|
1436
|
+
const _resetDefaultValues = () => isFunction(_options.defaultValues) && _options.defaultValues().then((values) => {
|
|
1437
|
+
reset(values, _options.resetOptions);
|
|
1438
|
+
_subjects.state.next({ isLoading: false });
|
|
1439
|
+
});
|
|
1440
|
+
const resetDefaultValues = (values, options = {}) => {
|
|
1441
|
+
_defaultValues = cloneObject(values);
|
|
1442
|
+
if (!options.keepDirty) {
|
|
1443
|
+
const newDirtyFields = getDirtyFields(_defaultValues, _formValues);
|
|
1444
|
+
_formState.dirtyFields = newDirtyFields;
|
|
1445
|
+
_formState.isDirty = !isEmptyObject(newDirtyFields);
|
|
1446
|
+
}
|
|
1447
|
+
if (!options.keepIsValid) _setValid();
|
|
1448
|
+
_subjects.state.next({
|
|
1449
|
+
..._formState,
|
|
1450
|
+
defaultValues: _defaultValues
|
|
1451
|
+
});
|
|
1452
|
+
};
|
|
1453
|
+
const methods = {
|
|
1454
|
+
control: {
|
|
1455
|
+
register,
|
|
1456
|
+
unregister,
|
|
1457
|
+
getFieldState,
|
|
1458
|
+
handleSubmit,
|
|
1459
|
+
setError,
|
|
1460
|
+
_subscribe,
|
|
1461
|
+
_runSchema,
|
|
1462
|
+
_updateIsValidating,
|
|
1463
|
+
_focusError,
|
|
1464
|
+
_getWatch,
|
|
1465
|
+
_getDirty,
|
|
1466
|
+
_setValid,
|
|
1467
|
+
_setFieldArray,
|
|
1468
|
+
_setDisabledField,
|
|
1469
|
+
_setErrors,
|
|
1470
|
+
_getFieldArray,
|
|
1471
|
+
_reset,
|
|
1472
|
+
_resetDefaultValues,
|
|
1473
|
+
_removeUnmounted,
|
|
1474
|
+
_disableForm,
|
|
1475
|
+
_subjects,
|
|
1476
|
+
_proxyFormState,
|
|
1477
|
+
get _fields() {
|
|
1478
|
+
return _fields;
|
|
1479
|
+
},
|
|
1480
|
+
get _formValues() {
|
|
1481
|
+
return _formValues;
|
|
1482
|
+
},
|
|
1483
|
+
get _state() {
|
|
1484
|
+
return _state;
|
|
1485
|
+
},
|
|
1486
|
+
set _state(value) {
|
|
1487
|
+
_state = value;
|
|
1488
|
+
},
|
|
1489
|
+
get _defaultValues() {
|
|
1490
|
+
return _defaultValues;
|
|
1491
|
+
},
|
|
1492
|
+
get _names() {
|
|
1493
|
+
return _names;
|
|
1494
|
+
},
|
|
1495
|
+
set _names(value) {
|
|
1496
|
+
_names = value;
|
|
1497
|
+
},
|
|
1498
|
+
get _formState() {
|
|
1499
|
+
return _formState;
|
|
1500
|
+
},
|
|
1501
|
+
get _options() {
|
|
1502
|
+
return _options;
|
|
1503
|
+
},
|
|
1504
|
+
set _options(value) {
|
|
1505
|
+
_options = {
|
|
1506
|
+
..._options,
|
|
1507
|
+
...value
|
|
1508
|
+
};
|
|
1509
|
+
_validationModeBeforeSubmit = getValidationModes(_options.mode);
|
|
1510
|
+
_validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
|
|
1511
|
+
}
|
|
1512
|
+
},
|
|
1513
|
+
subscribe,
|
|
1514
|
+
trigger,
|
|
1515
|
+
register,
|
|
1516
|
+
handleSubmit,
|
|
1517
|
+
watch,
|
|
1518
|
+
setValue,
|
|
1519
|
+
setValues,
|
|
1520
|
+
getValues,
|
|
1521
|
+
reset,
|
|
1522
|
+
resetField,
|
|
1523
|
+
resetDefaultValues,
|
|
1524
|
+
clearErrors,
|
|
1525
|
+
unregister,
|
|
1526
|
+
setError,
|
|
1527
|
+
setFocus,
|
|
1528
|
+
getFieldState
|
|
1529
|
+
};
|
|
1530
|
+
return {
|
|
1531
|
+
...methods,
|
|
1532
|
+
formControl: methods
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
1535
|
+
/**
|
|
1536
|
+
* Custom hook to manage the entire form.
|
|
1537
|
+
*
|
|
1538
|
+
* @remarks
|
|
1539
|
+
* [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
|
|
1540
|
+
*
|
|
1541
|
+
* @param props - form configuration and validation parameters.
|
|
1542
|
+
*
|
|
1543
|
+
* @returns methods - individual functions to manage the form state. {@link UseFormReturn}
|
|
1544
|
+
*
|
|
1545
|
+
* @example
|
|
1546
|
+
* ```tsx
|
|
1547
|
+
* function App() {
|
|
1548
|
+
* const { register, handleSubmit, watch, formState: { errors } } = useForm();
|
|
1549
|
+
* const onSubmit = data => console.log(data);
|
|
1550
|
+
*
|
|
1551
|
+
* console.log(watch("example"));
|
|
1552
|
+
*
|
|
1553
|
+
* return (
|
|
1554
|
+
* <form onSubmit={handleSubmit(onSubmit)}>
|
|
1555
|
+
* <input defaultValue="test" {...register("example")} />
|
|
1556
|
+
* <input {...register("exampleRequired", { required: true })} />
|
|
1557
|
+
* {errors.exampleRequired && <span>This field is required</span>}
|
|
1558
|
+
* <button>Submit</button>
|
|
1559
|
+
* </form>
|
|
1560
|
+
* );
|
|
1561
|
+
* }
|
|
1562
|
+
* ```
|
|
1563
|
+
*/
|
|
1564
|
+
function useForm(props = {}) {
|
|
1565
|
+
const _formControl = React.useRef(void 0);
|
|
1566
|
+
const _values = React.useRef(void 0);
|
|
1567
|
+
const _formControlProp = React.useRef(props.formControl);
|
|
1568
|
+
const [formState, updateFormState] = React.useState(() => ({
|
|
1569
|
+
...cloneObject(DEFAULT_FORM_STATE),
|
|
1570
|
+
isLoading: isFunction(props.defaultValues),
|
|
1571
|
+
errors: props.errors || {},
|
|
1572
|
+
disabled: props.disabled || false,
|
|
1573
|
+
defaultValues: isFunction(props.defaultValues) ? void 0 : props.defaultValues
|
|
1574
|
+
}));
|
|
1575
|
+
if (!_formControl.current || props.formControl && _formControlProp.current !== props.formControl) {
|
|
1576
|
+
_formControlProp.current = props.formControl;
|
|
1577
|
+
if (props.formControl) {
|
|
1578
|
+
_formControl.current = {
|
|
1579
|
+
...props.formControl,
|
|
1580
|
+
formState
|
|
1581
|
+
};
|
|
1582
|
+
if (props.defaultValues && !isFunction(props.defaultValues)) props.formControl.reset(props.defaultValues, props.resetOptions);
|
|
1583
|
+
} else {
|
|
1584
|
+
const { formControl, ...rest } = createFormControl(props);
|
|
1585
|
+
_formControl.current = {
|
|
1586
|
+
...rest,
|
|
1587
|
+
formState
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
const control = _formControl.current.control;
|
|
1592
|
+
control._options = props;
|
|
1593
|
+
useIsomorphicLayoutEffect(() => {
|
|
1594
|
+
const sub = control._subscribe({
|
|
1595
|
+
formState: control._proxyFormState,
|
|
1596
|
+
callback: () => updateFormState({
|
|
1597
|
+
...control._formState,
|
|
1598
|
+
defaultValues: control._defaultValues
|
|
1599
|
+
}),
|
|
1600
|
+
reRenderRoot: true
|
|
1601
|
+
});
|
|
1602
|
+
updateFormState((data) => ({
|
|
1603
|
+
...data,
|
|
1604
|
+
isReady: true
|
|
1605
|
+
}));
|
|
1606
|
+
control._formState.isReady = true;
|
|
1607
|
+
return sub;
|
|
1608
|
+
}, [control]);
|
|
1609
|
+
React.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
|
|
1610
|
+
React.useEffect(() => {
|
|
1611
|
+
if (props.mode) control._options.mode = props.mode;
|
|
1612
|
+
if (props.reValidateMode) control._options.reValidateMode = props.reValidateMode;
|
|
1613
|
+
}, [
|
|
1614
|
+
control,
|
|
1615
|
+
props.mode,
|
|
1616
|
+
props.reValidateMode
|
|
1617
|
+
]);
|
|
1618
|
+
React.useEffect(() => {
|
|
1619
|
+
if (props.errors) {
|
|
1620
|
+
control._setErrors(props.errors);
|
|
1621
|
+
control._focusError();
|
|
1622
|
+
}
|
|
1623
|
+
}, [control, props.errors]);
|
|
1624
|
+
React.useEffect(() => {
|
|
1625
|
+
props.shouldUnregister && control._subjects.state.next({ values: control._getWatch() });
|
|
1626
|
+
}, [control, props.shouldUnregister]);
|
|
1627
|
+
React.useEffect(() => {
|
|
1628
|
+
if (control._proxyFormState.isDirty) {
|
|
1629
|
+
const isDirty = control._getDirty();
|
|
1630
|
+
if (isDirty !== formState.isDirty) control._subjects.state.next({ isDirty });
|
|
1631
|
+
}
|
|
1632
|
+
}, [control, formState.isDirty]);
|
|
1633
|
+
React.useEffect(() => {
|
|
1634
|
+
var _a;
|
|
1635
|
+
if (props.values && !deepEqual(props.values, _values.current)) {
|
|
1636
|
+
control._reset(props.values, {
|
|
1637
|
+
keepFieldsRef: true,
|
|
1638
|
+
...control._options.resetOptions
|
|
1639
|
+
});
|
|
1640
|
+
if (!((_a = control._options.resetOptions) === null || _a === void 0 ? void 0 : _a.keepIsValid)) control._setValid();
|
|
1641
|
+
_values.current = props.values;
|
|
1642
|
+
updateFormState((state) => ({ ...state }));
|
|
1643
|
+
} else control._resetDefaultValues();
|
|
1644
|
+
}, [control, props.values]);
|
|
1645
|
+
React.useEffect(() => {
|
|
1646
|
+
if (!control._state.mount) {
|
|
1647
|
+
control._setValid();
|
|
1648
|
+
control._state.mount = true;
|
|
1649
|
+
}
|
|
1650
|
+
if (control._state.watch) {
|
|
1651
|
+
control._state.watch = false;
|
|
1652
|
+
control._subjects.state.next({ ...control._formState });
|
|
1653
|
+
}
|
|
1654
|
+
control._removeUnmounted();
|
|
1655
|
+
});
|
|
1656
|
+
_formControl.current.formState = React.useMemo(() => getProxyFormState(formState, control), [control, formState]);
|
|
1657
|
+
return _formControl.current;
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
//#endregion
|
|
1661
|
+
export { appendErrors, createFormControl, get, set, useForm };
|