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