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