react-hook-form 7.85.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 (43) 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 +128 -82
  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/validateField.d.ts.map +1 -1
  25. package/dist/types/form.d.ts +47 -2
  26. package/dist/types/form.d.ts.map +1 -1
  27. package/dist/useFieldArray.d.ts.map +1 -1
  28. package/dist/useFormContext.d.ts +1 -1
  29. package/dist/useFormContext.d.ts.map +1 -1
  30. package/dist/utils/cloneObject.d.ts.map +1 -1
  31. package/dist/utils/deepEqual.d.ts +1 -1
  32. package/dist/utils/deepEqual.d.ts.map +1 -1
  33. package/dist/utils/flatten.d.ts.map +1 -1
  34. package/dist/utils/has.d.ts +3 -0
  35. package/dist/utils/has.d.ts.map +1 -0
  36. package/dist/utils/json.d.ts +2 -2
  37. package/dist/utils/json.d.ts.map +1 -1
  38. package/package.json +1 -1
  39. package/dist/formStateSubscribe.d.ts.map +0 -1
  40. package/dist/index.react-server.d.ts +0 -3
  41. package/dist/index.react-server.d.ts.map +0 -1
  42. package/dist/react-server.esm.mjs +0 -2367
  43. package/dist/react-server.esm.mjs.map +0 -1
@@ -1,2367 +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) => {
692
- const array = get(ref, name);
693
- !compact(array).length &&
694
- !(array === null || array === void 0 ? void 0 : array.root) &&
695
- unset(ref, name);
696
- };
697
-
698
- var updateFieldArrayRootError = (errors, error, name) => {
699
- const existingErrors = get(errors, name);
700
- const fieldArrayErrors = Array.isArray(existingErrors) ? existingErrors : [];
701
- set(fieldArrayErrors, ROOT_ERROR_TYPE, error[name]);
702
- set(errors, name, fieldArrayErrors);
703
- return errors;
704
- };
705
-
706
- function getValidateError(result, ref, type = 'validate') {
707
- if (isString(result) ||
708
- (Array.isArray(result) && result.every(isString)) ||
709
- (isBoolean(result) && !result)) {
710
- return {
711
- type,
712
- message: isString(result) ? result : '',
713
- ref,
714
- };
715
- }
716
- }
717
-
718
- var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
719
- ? validationData
720
- : {
721
- value: validationData,
722
- message: '',
723
- };
724
-
725
- var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
726
- const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, } = field._f;
727
- const inputValue = get(formValues, name);
728
- if (!mount || disabledFieldNames.has(name)) {
729
- return {};
730
- }
731
- const inputRef = refs ? refs[0] : ref;
732
- const setCustomValidity = (message) => {
733
- if (shouldUseNativeValidation && inputRef.reportValidity) {
734
- const validityMessage = isBoolean(message) ? '' : message || '';
735
- if (refs) {
736
- refs.forEach((ref) => ref.setCustomValidity(validityMessage));
737
- }
738
- else {
739
- inputRef.setCustomValidity(validityMessage);
740
- }
741
- inputRef.reportValidity();
742
- }
743
- };
744
- const error = {};
745
- const isRadio = isRadioInput(ref);
746
- const isCheckBox = isCheckBoxInput(ref);
747
- const isRadioOrCheckbox = isRadio || isCheckBox;
748
- const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
749
- isUndefined(ref.value) &&
750
- isUndefined(inputValue)) ||
751
- (isHTMLElement(ref) && ref.value === '') ||
752
- inputValue === '' ||
753
- (Array.isArray(inputValue) && !inputValue.length);
754
- const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
755
- const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
756
- const message = exceedMax ? maxLengthMessage : minLengthMessage;
757
- error[name] = {
758
- type: exceedMax ? maxType : minType,
759
- message,
760
- ref,
761
- ...appendErrorsCurry(exceedMax ? maxType : minType, message),
762
- };
763
- };
764
- if (isFieldArray
765
- ? !Array.isArray(inputValue) || !inputValue.length
766
- : required &&
767
- ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
768
- (isBoolean(inputValue) && !inputValue) ||
769
- (isCheckBox && !getCheckboxValue(refs).isValid) ||
770
- (isRadio && !getRadioValue(refs).isValid))) {
771
- const { value, message } = isString(required)
772
- ? { value: !!required, message: required }
773
- : getValueAndMessage(required);
774
- if (value) {
775
- error[name] = {
776
- type: INPUT_VALIDATION_RULES.required,
777
- message,
778
- ref: inputRef,
779
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
780
- };
781
- if (!validateAllFieldCriteria) {
782
- setCustomValidity(message);
783
- return error;
784
- }
785
- }
786
- }
787
- if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
788
- let exceedMax;
789
- let exceedMin;
790
- const maxOutput = getValueAndMessage(max);
791
- const minOutput = getValueAndMessage(min);
792
- if (!isNullOrUndefined(inputValue) &&
793
- !isDateObject(inputValue) &&
794
- !isNaN(inputValue)) {
795
- const valueNumber = ref.valueAsNumber ||
796
- (inputValue ? +inputValue : inputValue);
797
- if (!isNullOrUndefined(maxOutput.value)) {
798
- exceedMax = valueNumber > maxOutput.value;
799
- }
800
- if (!isNullOrUndefined(minOutput.value)) {
801
- exceedMin = valueNumber < minOutput.value;
802
- }
803
- }
804
- else {
805
- const valueDate = ref.valueAsDate || new Date(inputValue);
806
- const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
807
- const isTime = ref.type == 'time';
808
- const isWeek = ref.type == 'week';
809
- if (isString(maxOutput.value) && inputValue) {
810
- exceedMax = isTime
811
- ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
812
- : isWeek
813
- ? inputValue > maxOutput.value
814
- : valueDate > new Date(maxOutput.value);
815
- }
816
- if (isString(minOutput.value) && inputValue) {
817
- exceedMin = isTime
818
- ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
819
- : isWeek
820
- ? inputValue < minOutput.value
821
- : valueDate < new Date(minOutput.value);
822
- }
823
- }
824
- if (exceedMax || exceedMin) {
825
- getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
826
- if (!validateAllFieldCriteria) {
827
- setCustomValidity(error[name].message);
828
- return error;
829
- }
830
- }
831
- }
832
- if ((maxLength || minLength) &&
833
- !isEmpty &&
834
- (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
835
- const maxLengthOutput = getValueAndMessage(maxLength);
836
- const minLengthOutput = getValueAndMessage(minLength);
837
- const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
838
- inputValue.length > +maxLengthOutput.value;
839
- const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
840
- inputValue.length < +minLengthOutput.value;
841
- if (exceedMax || exceedMin) {
842
- getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
843
- if (!validateAllFieldCriteria) {
844
- setCustomValidity(error[name].message);
845
- return error;
846
- }
847
- }
848
- }
849
- if (pattern && !isEmpty && isString(inputValue)) {
850
- const { value: patternValue, message } = getValueAndMessage(pattern);
851
- if (isRegex(patternValue) && !inputValue.match(patternValue)) {
852
- error[name] = {
853
- type: INPUT_VALIDATION_RULES.pattern,
854
- message,
855
- ref,
856
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
857
- };
858
- if (!validateAllFieldCriteria) {
859
- setCustomValidity(message);
860
- return error;
861
- }
862
- }
863
- }
864
- if (validate) {
865
- if (isFunction(validate)) {
866
- const result = await validate(inputValue, formValues);
867
- const validateError = getValidateError(result, inputRef);
868
- if (validateError) {
869
- error[name] = {
870
- ...validateError,
871
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
872
- };
873
- if (!validateAllFieldCriteria) {
874
- setCustomValidity(validateError.message);
875
- return error;
876
- }
877
- }
878
- }
879
- else if (isObject(validate)) {
880
- let validationResult = {};
881
- for (const key in validate) {
882
- if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
883
- break;
884
- }
885
- const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
886
- if (validateError) {
887
- validationResult = {
888
- ...validateError,
889
- ...appendErrorsCurry(key, validateError.message),
890
- };
891
- setCustomValidity(validateError.message);
892
- if (validateAllFieldCriteria) {
893
- error[name] = validationResult;
894
- }
895
- }
896
- }
897
- if (!isEmptyObject(validationResult)) {
898
- error[name] = {
899
- ref: inputRef,
900
- ...validationResult,
901
- };
902
- if (!validateAllFieldCriteria) {
903
- return error;
904
- }
905
- }
906
- }
907
- }
908
- setCustomValidity(true);
909
- return error;
910
- };
911
-
912
- const defaultOptions = {
913
- mode: VALIDATION_MODE.onSubmit,
914
- reValidateMode: VALIDATION_MODE.onChange,
915
- shouldFocusError: true,
916
- };
917
- const FORM_ERROR_TYPE = 'form';
918
- const updateDirtyFields = (dirtyFields, nextDirtyFields) => {
919
- for (const key in dirtyFields) {
920
- if (!(key in nextDirtyFields)) {
921
- delete dirtyFields[key];
922
- }
923
- }
924
- Object.assign(dirtyFields, nextDirtyFields);
925
- };
926
- const DEFAULT_FORM_STATE = {
927
- submitCount: 0,
928
- isDirty: false,
929
- isReady: false,
930
- isValidating: false,
931
- isSubmitted: false,
932
- isSubmitting: false,
933
- isSubmitSuccessful: false,
934
- isValid: false,
935
- touchedFields: {},
936
- dirtyFields: {},
937
- validatingFields: {},
938
- };
939
- function createFormControl(props = {}) {
940
- let _options = {
941
- ...defaultOptions,
942
- ...props,
943
- };
944
- let _formState = {
945
- ...cloneObject(DEFAULT_FORM_STATE),
946
- isLoading: isFunction(_options.defaultValues),
947
- errors: _options.errors || {},
948
- disabled: _options.disabled || false,
949
- };
950
- let _fields = {};
951
- let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
952
- ? cloneObject(_options.defaultValues || _options.values) || {}
953
- : {};
954
- let _formValues = _options.shouldUnregister
955
- ? {}
956
- : cloneObject(_defaultValues);
957
- let _state = {
958
- action: false,
959
- actionArrayLengths: new Map(),
960
- mount: false,
961
- watch: false,
962
- keepIsValid: false,
963
- };
964
- let _names = {
965
- mount: new Set(),
966
- disabled: new Set(),
967
- unMount: new Set(),
968
- array: new Set(),
969
- watch: new Set(),
970
- registerName: new Set(),
971
- };
972
- const delayErrorCallbacks = {};
973
- const timers = {};
974
- let _valuesSubscriberCount = 0;
975
- let _validationModeBeforeSubmit = getValidationModes(_options.mode);
976
- let _validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
977
- const defaultProxyFormState = {
978
- isDirty: false,
979
- dirtyFields: false,
980
- validatingFields: false,
981
- touchedFields: false,
982
- isValidating: false,
983
- isValid: false,
984
- errors: false,
985
- };
986
- const _proxyFormState = {
987
- ...defaultProxyFormState,
988
- };
989
- let _proxySubscribeFormState = {
990
- ..._proxyFormState,
991
- };
992
- const _subjects = {
993
- array: createSubject(),
994
- state: createSubject(),
995
- };
996
- let _setValidCallId = 0;
997
- const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
998
- const debounce = (name, callback) => (wait) => {
999
- clearTimeout(timers[name]);
1000
- timers[name] = setTimeout(callback, wait);
1001
- };
1002
- const _setValid = async (shouldUpdateValid) => {
1003
- if (_state.keepIsValid) {
1004
- return;
1005
- }
1006
- if (!_options.disabled &&
1007
- (_proxyFormState.isValid ||
1008
- _proxySubscribeFormState.isValid ||
1009
- shouldUpdateValid)) {
1010
- const callId = ++_setValidCallId;
1011
- let isValid;
1012
- if (_options.resolver) {
1013
- isValid = isEmptyObject((await _runSchema()).errors);
1014
- callId === _setValidCallId && _updateIsValidating();
1015
- }
1016
- else {
1017
- isValid = await executeBuiltInValidation({
1018
- fields: _fields,
1019
- onlyCheckValid: true,
1020
- eventType: EVENTS.VALID,
1021
- });
1022
- }
1023
- if (callId === _setValidCallId && isValid !== _formState.isValid) {
1024
- _subjects.state.next({
1025
- isValid,
1026
- });
1027
- }
1028
- }
1029
- };
1030
- const _updateIsValidating = (names, isValidating) => {
1031
- if (!_options.disabled &&
1032
- (_proxyFormState.isValidating ||
1033
- _proxyFormState.validatingFields ||
1034
- _proxySubscribeFormState.isValidating ||
1035
- _proxySubscribeFormState.validatingFields)) {
1036
- (names || Array.from(_names.mount)).forEach((name) => {
1037
- if (name) {
1038
- isValidating
1039
- ? set(_formState.validatingFields, name, isValidating)
1040
- : unset(_formState.validatingFields, name);
1041
- }
1042
- });
1043
- _subjects.state.next({
1044
- validatingFields: _formState.validatingFields,
1045
- isValidating: !isEmptyObject(_formState.validatingFields),
1046
- });
1047
- }
1048
- };
1049
- const _updateDirtyFields = () => {
1050
- _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues, undefined, _fields);
1051
- };
1052
- const _setFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1053
- if (args && method && !_options.disabled) {
1054
- _state.action = true;
1055
- if (!_state.actionArrayLengths.has(name)) {
1056
- const preActionFields = get(_fields, name);
1057
- _state.actionArrayLengths.set(name, Array.isArray(preActionFields) ? preActionFields.length : 0);
1058
- }
1059
- if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1060
- const fieldValues = method(get(_fields, name), args.argA, args.argB);
1061
- shouldSetValues && set(_fields, name, fieldValues);
1062
- }
1063
- if (shouldUpdateFieldsAndState &&
1064
- Array.isArray(get(_formState.errors, name))) {
1065
- const fieldArrayErrors = get(_formState.errors, name);
1066
- const rootError = fieldArrayErrors.root;
1067
- const errors = method(fieldArrayErrors, args.argA, args.argB) || fieldArrayErrors;
1068
- if (rootError) {
1069
- errors.root = rootError;
1070
- }
1071
- shouldSetValues && set(_formState.errors, name, errors);
1072
- unsetEmptyArray(_formState.errors, name);
1073
- }
1074
- if ((_proxyFormState.touchedFields ||
1075
- _proxySubscribeFormState.touchedFields) &&
1076
- shouldUpdateFieldsAndState &&
1077
- Array.isArray(get(_formState.touchedFields, name))) {
1078
- const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1079
- shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1080
- }
1081
- if (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) {
1082
- _updateDirtyFields();
1083
- }
1084
- _subjects.state.next({
1085
- name,
1086
- isDirty: _getDirty(name, values),
1087
- dirtyFields: _formState.dirtyFields,
1088
- errors: _formState.errors,
1089
- isValid: _formState.isValid,
1090
- });
1091
- }
1092
- else {
1093
- set(_formValues, name, values);
1094
- }
1095
- };
1096
- const updateErrors = (name, error) => {
1097
- set(_formState.errors, name, error);
1098
- _formState.errors = { ..._formState.errors };
1099
- _subjects.state.next({
1100
- errors: _formState.errors,
1101
- });
1102
- };
1103
- const _setErrors = (errors) => {
1104
- _formState.errors = errors;
1105
- _subjects.state.next({
1106
- errors: _formState.errors,
1107
- isValid: false,
1108
- });
1109
- };
1110
- const hasExplicitNullIntermediate = (name) => {
1111
- const segments = isKey(name) ? [name] : stringToPath(name);
1112
- let formValues = _formValues;
1113
- let defaultValues = _defaultValues;
1114
- for (let i = 0; i < segments.length - 1; i++) {
1115
- const key = segments[i];
1116
- formValues = isNullOrUndefined(formValues) ? formValues : formValues[key];
1117
- defaultValues = isNullOrUndefined(defaultValues)
1118
- ? defaultValues
1119
- : defaultValues[key];
1120
- if (formValues === null && defaultValues !== null) {
1121
- return true;
1122
- }
1123
- }
1124
- return false;
1125
- };
1126
- const isStaleArrayIndex = (name) => {
1127
- if (!_state.actionArrayLengths.size) {
1128
- return false;
1129
- }
1130
- const segments = isKey(name) ? [name] : stringToPath(name);
1131
- let node = _formValues;
1132
- let path = '';
1133
- let ownerDepth = -1;
1134
- let ownerPreActionLength = 0;
1135
- for (let i = 0; i < segments.length; i++) {
1136
- if (isNullOrUndefined(node)) {
1137
- return false;
1138
- }
1139
- const key = segments[i];
1140
- path = path ? `${path}.${key}` : key;
1141
- if (Array.isArray(node) && +key >= node.length) {
1142
- return ownerDepth === -1
1143
- ? false
1144
- : i === ownerDepth
1145
- ? +key < ownerPreActionLength
1146
- : true;
1147
- }
1148
- if (_state.actionArrayLengths.has(path)) {
1149
- ownerDepth = i + 1;
1150
- ownerPreActionLength = _state.actionArrayLengths.get(path);
1151
- }
1152
- node = node[key];
1153
- }
1154
- return false;
1155
- };
1156
- const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1157
- const field = get(_fields, name);
1158
- if (field) {
1159
- if (hasExplicitNullIntermediate(name) || isStaleArrayIndex(name)) {
1160
- return;
1161
- }
1162
- const wasUnsetInFormValues = isUndefined(get(_formValues, name));
1163
- const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1164
- isUndefined(defaultValue) ||
1165
- (ref && ref.defaultChecked) ||
1166
- shouldSkipSetValueAs
1167
- ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
1168
- : setFieldValue(name, defaultValue);
1169
- if (_state.mount && !_state.action) {
1170
- _setValid();
1171
- if (wasUnsetInFormValues &&
1172
- _formState.isDirty &&
1173
- (_proxyFormState.isDirty || _proxySubscribeFormState.isDirty)) {
1174
- const isDirty = _getDirty();
1175
- if (!isDirty) {
1176
- _formState.isDirty = false;
1177
- _subjects.state.next({ ..._formState });
1178
- }
1179
- }
1180
- if (props.shouldUnregister &&
1181
- wasUnsetInFormValues &&
1182
- !isUndefined(get(_formValues, name)) &&
1183
- isWatched(name, _names)) {
1184
- _state.watch = true;
1185
- }
1186
- }
1187
- }
1188
- };
1189
- const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1190
- let shouldUpdateField = false;
1191
- let isPreviousDirty = false;
1192
- const output = {
1193
- name,
1194
- };
1195
- // an explicit programmatic update (e.g. setValue with shouldDirty: true)
1196
- // opts into dirty tracking even when the form is disabled
1197
- if (!_options.disabled || shouldDirty === true) {
1198
- if (!isBlurEvent || shouldDirty) {
1199
- const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
1200
- if (_proxyFormState.isDirty || _proxySubscribeFormState.isDirty) {
1201
- isPreviousDirty = _formState.isDirty;
1202
- _formState.isDirty = output.isDirty =
1203
- !isCurrentFieldPristine || _getDirty();
1204
- shouldUpdateField = isPreviousDirty !== output.isDirty;
1205
- }
1206
- isPreviousDirty = !!get(_formState.dirtyFields, name);
1207
- if (isCurrentFieldPristine !== _formState.isDirty) {
1208
- updateDirtyFields(_formState.dirtyFields, getDirtyFields(_defaultValues, _formValues, undefined, _fields));
1209
- }
1210
- else {
1211
- isCurrentFieldPristine
1212
- ? unset(_formState.dirtyFields, name)
1213
- : set(_formState.dirtyFields, name, true);
1214
- }
1215
- output.dirtyFields = _formState.dirtyFields;
1216
- shouldUpdateField =
1217
- shouldUpdateField ||
1218
- ((_proxyFormState.dirtyFields ||
1219
- _proxySubscribeFormState.dirtyFields) &&
1220
- isPreviousDirty !== !isCurrentFieldPristine);
1221
- }
1222
- if (isBlurEvent) {
1223
- const isPreviousFieldTouched = get(_formState.touchedFields, name);
1224
- if (!isPreviousFieldTouched) {
1225
- set(_formState.touchedFields, name, isBlurEvent);
1226
- output.touchedFields = _formState.touchedFields;
1227
- shouldUpdateField =
1228
- shouldUpdateField ||
1229
- ((_proxyFormState.touchedFields ||
1230
- _proxySubscribeFormState.touchedFields) &&
1231
- isPreviousFieldTouched !== isBlurEvent);
1232
- }
1233
- }
1234
- shouldUpdateField && shouldRender && _subjects.state.next(output);
1235
- }
1236
- return shouldUpdateField ? output : {};
1237
- };
1238
- const shouldRenderByError = (name, isValid, error, fieldState) => {
1239
- const previousFieldError = get(_formState.errors, name);
1240
- const shouldUpdateValid = (_proxyFormState.isValid || _proxySubscribeFormState.isValid) &&
1241
- isBoolean(isValid) &&
1242
- _formState.isValid !== isValid;
1243
- if (_options.delayError && error) {
1244
- delayErrorCallbacks[name] = debounce(name, () => updateErrors(name, error));
1245
- delayErrorCallbacks[name](_options.delayError);
1246
- }
1247
- else {
1248
- clearTimeout(timers[name]);
1249
- delete delayErrorCallbacks[name];
1250
- error
1251
- ? set(_formState.errors, name, error)
1252
- : unset(_formState.errors, name);
1253
- _formState.errors = { ..._formState.errors };
1254
- }
1255
- if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
1256
- !isEmptyObject(fieldState) ||
1257
- shouldUpdateValid) {
1258
- const updatedFormState = {
1259
- ...fieldState,
1260
- ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
1261
- errors: _formState.errors,
1262
- name,
1263
- };
1264
- _formState = {
1265
- ..._formState,
1266
- ...updatedFormState,
1267
- };
1268
- _subjects.state.next(updatedFormState);
1269
- }
1270
- };
1271
- const _runSchema = async (name) => {
1272
- _updateIsValidating(name, true);
1273
- return await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1274
- };
1275
- const executeSchemaAndUpdateState = async (names) => {
1276
- const { errors } = await _runSchema(names);
1277
- _updateIsValidating(names);
1278
- if (names) {
1279
- for (const name of names) {
1280
- const error = get(errors, name);
1281
- error
1282
- ? _names.array.has(name) &&
1283
- isObject(error) &&
1284
- !Object.keys(error).some((key) => !Number.isNaN(Number(key)))
1285
- ? updateFieldArrayRootError(_formState.errors, { [name]: error }, name)
1286
- : set(_formState.errors, name, error)
1287
- : unset(_formState.errors, name);
1288
- }
1289
- _formState.errors = { ..._formState.errors };
1290
- }
1291
- else {
1292
- _formState.errors = errors;
1293
- }
1294
- return errors;
1295
- };
1296
- const validateForm = async ({ name, eventType, }) => {
1297
- if (props.validate) {
1298
- const result = await props.validate({
1299
- formValues: _formValues,
1300
- formState: _formState,
1301
- name,
1302
- eventType,
1303
- });
1304
- if (isObject(result)) {
1305
- for (const key in result) {
1306
- const error = result[key];
1307
- if (error) {
1308
- setError(`${FORM_ERROR_TYPE}.${key}`, {
1309
- message: isString(error.message) ? error.message : '',
1310
- type: error.type || INPUT_VALIDATION_RULES.validate,
1311
- });
1312
- }
1313
- }
1314
- }
1315
- else if (isString(result) || !result) {
1316
- setError(FORM_ERROR_TYPE, {
1317
- message: result || '',
1318
- type: INPUT_VALIDATION_RULES.validate,
1319
- });
1320
- }
1321
- else {
1322
- clearErrors(FORM_ERROR_TYPE);
1323
- }
1324
- return result;
1325
- }
1326
- return true;
1327
- };
1328
- const executeBuiltInValidation = async ({ fields, onlyCheckValid, name, eventType, context = {
1329
- valid: true,
1330
- runRootValidation: false,
1331
- }, }) => {
1332
- if (props.validate) {
1333
- context.runRootValidation = true;
1334
- const result = await validateForm({
1335
- name,
1336
- eventType,
1337
- });
1338
- if (!result) {
1339
- context.valid = false;
1340
- if (onlyCheckValid) {
1341
- return context.valid;
1342
- }
1343
- }
1344
- }
1345
- for (const name in fields) {
1346
- const field = fields[name];
1347
- if (field) {
1348
- const { _f, ...fieldValue } = field;
1349
- if (_f) {
1350
- const isFieldArrayRoot = _names.array.has(_f.name);
1351
- const isPromiseFunction = field._f && hasPromiseValidation(field._f);
1352
- const shouldTrackIsValidatingState = _proxyFormState.validatingFields ||
1353
- _proxyFormState.isValidating ||
1354
- _proxySubscribeFormState.validatingFields ||
1355
- _proxySubscribeFormState.isValidating;
1356
- if (isPromiseFunction && shouldTrackIsValidatingState) {
1357
- _updateIsValidating([_f.name], true);
1358
- }
1359
- const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !onlyCheckValid, isFieldArrayRoot);
1360
- if (isPromiseFunction && shouldTrackIsValidatingState) {
1361
- _updateIsValidating([_f.name]);
1362
- }
1363
- if (fieldError[_f.name]) {
1364
- context.valid = false;
1365
- if (onlyCheckValid) {
1366
- break;
1367
- }
1368
- }
1369
- !onlyCheckValid &&
1370
- (get(fieldError, _f.name)
1371
- ? isFieldArrayRoot
1372
- ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
1373
- : set(_formState.errors, _f.name, fieldError[_f.name])
1374
- : unset(_formState.errors, _f.name));
1375
- if (props.shouldUseNativeValidation && fieldError[_f.name]) {
1376
- break;
1377
- }
1378
- }
1379
- !isEmptyObject(fieldValue) &&
1380
- (await executeBuiltInValidation({
1381
- context,
1382
- onlyCheckValid,
1383
- fields: fieldValue,
1384
- name: name,
1385
- eventType,
1386
- }));
1387
- }
1388
- }
1389
- return context.valid;
1390
- };
1391
- const _removeUnmounted = () => {
1392
- for (const name of _names.unMount) {
1393
- const field = get(_fields, name);
1394
- field &&
1395
- (field._f.refs
1396
- ? field._f.refs.every((ref) => !live(ref))
1397
- : !live(field._f.ref)) &&
1398
- unregister(name);
1399
- }
1400
- _names.unMount = new Set();
1401
- };
1402
- const _getDirty = (name, data) => (name && data && set(_formValues, name, data),
1403
- !deepEqual(_state.mount ? _formValues : _defaultValues, _defaultValues));
1404
- const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1405
- ...(_state.mount
1406
- ? _formValues
1407
- : isUndefined(defaultValue) || isString(names)
1408
- ? _defaultValues
1409
- : defaultValue),
1410
- }, isGlobal, defaultValue);
1411
- const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : []));
1412
- const setFieldValue = (name, value, options = {}, skipClone = false, skipRender = false, skipValueRender = false) => {
1413
- const field = get(_fields, name);
1414
- let fieldValue = value;
1415
- if (field) {
1416
- const fieldReference = field._f;
1417
- if (fieldReference) {
1418
- !fieldReference.disabled &&
1419
- set(_formValues, name, getFieldValueAs(value, fieldReference));
1420
- fieldValue =
1421
- isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
1422
- ? ''
1423
- : value;
1424
- if (isMultipleSelect(fieldReference.ref)) {
1425
- [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
1426
- }
1427
- else if (fieldReference.refs) {
1428
- if (isCheckBoxInput(fieldReference.ref)) {
1429
- fieldReference.refs.forEach((checkboxRef) => {
1430
- if (!checkboxRef.defaultChecked || !checkboxRef.disabled) {
1431
- if (Array.isArray(fieldValue)) {
1432
- checkboxRef.checked = !!fieldValue.find((data) => data === checkboxRef.value);
1433
- }
1434
- else {
1435
- checkboxRef.checked =
1436
- fieldValue === checkboxRef.value || !!fieldValue;
1437
- }
1438
- }
1439
- });
1440
- }
1441
- else {
1442
- fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
1443
- }
1444
- }
1445
- else if (isFileInput(fieldReference.ref)) {
1446
- fieldReference.ref.value = '';
1447
- }
1448
- else {
1449
- fieldReference.ref.value = fieldValue;
1450
- if (!fieldReference.ref.type && !skipRender && !skipValueRender) {
1451
- _subjects.state.next({
1452
- name,
1453
- values: skipClone ? _formValues : cloneObject(_formValues),
1454
- });
1455
- }
1456
- }
1457
- }
1458
- }
1459
- (options.shouldDirty || options.shouldTouch) &&
1460
- updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, !skipRender);
1461
- options.shouldValidate &&
1462
- trigger(name, {
1463
- delayError: options.delayError,
1464
- });
1465
- };
1466
- const setFieldValues = (name, value, options, skipClone = false, skipRender = false, skipValueRender = false) => {
1467
- if (_names.array.has(name)) {
1468
- _subjects.array.next({
1469
- name,
1470
- values: skipClone ? _formValues : cloneObject(_formValues),
1471
- });
1472
- }
1473
- for (const fieldKey in value) {
1474
- if (!value.hasOwnProperty(fieldKey)) {
1475
- return;
1476
- }
1477
- const fieldValue = value[fieldKey];
1478
- const fieldName = name + '.' + fieldKey;
1479
- const field = get(_fields, fieldName);
1480
- (_names.array.has(name) ||
1481
- isObject(fieldValue) ||
1482
- (field && !field._f)) &&
1483
- !isDateObject(fieldValue)
1484
- ? setFieldValues(fieldName, fieldValue, options, skipClone, skipRender, skipValueRender)
1485
- : setFieldValue(fieldName, fieldValue, options, skipClone, skipRender, skipValueRender);
1486
- }
1487
- };
1488
- const _setValue = (name, value, options, skipClone, skipStateEmit = false) => {
1489
- const field = get(_fields, name);
1490
- const isFieldArray = _names.array.has(name);
1491
- const cloneValue = skipClone ? value : cloneObject(value);
1492
- const previousValue = get(_formValues, name);
1493
- const isValueUnchanged = deepEqual(previousValue, cloneValue);
1494
- if (!isValueUnchanged) {
1495
- set(_formValues, name, cloneValue);
1496
- }
1497
- if (isFieldArray) {
1498
- _subjects.array.next({
1499
- name,
1500
- values: skipClone ? _formValues : cloneObject(_formValues),
1501
- });
1502
- if ((_proxyFormState.isDirty ||
1503
- _proxyFormState.dirtyFields ||
1504
- _proxySubscribeFormState.isDirty ||
1505
- _proxySubscribeFormState.dirtyFields) &&
1506
- options.shouldDirty) {
1507
- _updateDirtyFields();
1508
- if (!skipStateEmit) {
1509
- _subjects.state.next({
1510
- name,
1511
- dirtyFields: _formState.dirtyFields,
1512
- isDirty: _getDirty(name, cloneValue),
1513
- });
1514
- }
1515
- }
1516
- }
1517
- else {
1518
- const isEmpty = (Array.isArray(cloneValue) && !cloneValue.length) ||
1519
- isEmptyObject(cloneValue);
1520
- const skipValueRender = !isValueUnchanged && !skipStateEmit;
1521
- if (!field || field._f || isNullOrUndefined(cloneValue) || isEmpty) {
1522
- setFieldValue(name, cloneValue, options, skipClone, skipStateEmit, skipValueRender);
1523
- }
1524
- else {
1525
- setFieldValues(name, cloneValue, options, skipClone, skipStateEmit, skipValueRender);
1526
- }
1527
- }
1528
- if (!isValueUnchanged && !skipStateEmit) {
1529
- const watched = isWatched(name, _names);
1530
- const values = skipClone ? _formValues : cloneObject(_formValues);
1531
- _subjects.state.next({
1532
- ...(watched && _formState),
1533
- name: _state.mount || watched ? name : undefined,
1534
- values,
1535
- });
1536
- }
1537
- };
1538
- const setValue = (name, value, options = {}) => _setValue(name, value, options, false);
1539
- const setValues = (formValues, options = {}) => {
1540
- const updatedFormValues = isFunction(formValues)
1541
- ? formValues(_formValues)
1542
- : formValues;
1543
- if (!deepEqual(_formValues, updatedFormValues)) {
1544
- _formValues = {
1545
- ..._formValues,
1546
- ...updatedFormValues,
1547
- };
1548
- const flattenedUpdates = flatten(updatedFormValues);
1549
- for (const fieldName of _names.mount) {
1550
- if (fieldName in flattenedUpdates) {
1551
- _setValue(fieldName, flattenedUpdates[fieldName], options, true, true);
1552
- }
1553
- }
1554
- _subjects.state.next({
1555
- ..._formState,
1556
- name: undefined,
1557
- type: undefined,
1558
- ...(_valuesSubscriberCount ? { values: _formValues } : {}),
1559
- });
1560
- if (options.shouldValidate) {
1561
- _setValid();
1562
- }
1563
- }
1564
- };
1565
- const onChange = async (event) => {
1566
- _state.mount = true;
1567
- const target = event.target;
1568
- let name = target.name;
1569
- let isFieldValueUpdated = true;
1570
- const field = get(_fields, name);
1571
- const _updateIsFieldValueUpdated = (fieldValue) => {
1572
- isFieldValueUpdated =
1573
- Number.isNaN(fieldValue) ||
1574
- (isDateObject(fieldValue) && isNaN(fieldValue.getTime())) ||
1575
- deepEqual(fieldValue, get(_formValues, name, fieldValue));
1576
- };
1577
- if (field) {
1578
- let error;
1579
- let isValid;
1580
- const fieldValue = target.type
1581
- ? getFieldValue(field._f)
1582
- : getEventValue(event);
1583
- const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1584
- const hasNoValidationEffect = !hasValidation(field._f) &&
1585
- !props.validate &&
1586
- !_options.resolver &&
1587
- !get(_formState.errors, name) &&
1588
- !field._f.deps;
1589
- const shouldSkipValidation = hasNoValidationEffect ||
1590
- skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, _validationModeAfterSubmit, _validationModeBeforeSubmit);
1591
- const watched = isWatched(name, _names, isBlurEvent);
1592
- set(_formValues, name, fieldValue);
1593
- if (isBlurEvent) {
1594
- if (!target || !target.readOnly) {
1595
- field._f.onBlur && field._f.onBlur(event);
1596
- const pendingDelayError = delayErrorCallbacks[name];
1597
- pendingDelayError && pendingDelayError(0);
1598
- }
1599
- }
1600
- else if (field._f.onChange) {
1601
- field._f.onChange(event);
1602
- }
1603
- const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent);
1604
- const shouldRender = !isEmptyObject(fieldState) || watched;
1605
- !isBlurEvent &&
1606
- _subjects.state.next({
1607
- name,
1608
- type: event.type,
1609
- ...(_valuesSubscriberCount
1610
- ? { values: cloneObject(_formValues) }
1611
- : {}),
1612
- });
1613
- if (shouldSkipValidation) {
1614
- if ((!hasNoValidationEffect || !_formState.isValid) &&
1615
- (_proxyFormState.isValid || _proxySubscribeFormState.isValid)) {
1616
- if (_options.mode === 'onBlur') {
1617
- if (isBlurEvent) {
1618
- _setValid();
1619
- }
1620
- }
1621
- else if (!isBlurEvent) {
1622
- _setValid();
1623
- }
1624
- }
1625
- return (shouldRender &&
1626
- _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
1627
- }
1628
- if (!_options.resolver && props.validate) {
1629
- await validateForm({
1630
- name: name,
1631
- eventType: event.type,
1632
- });
1633
- }
1634
- !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1635
- if (_options.resolver) {
1636
- const { errors } = await _runSchema([name]);
1637
- _updateIsValidating([name]);
1638
- _updateIsFieldValueUpdated(fieldValue);
1639
- if (!isFieldValueUpdated) {
1640
- !isEmptyObject(fieldState) && _subjects.state.next(fieldState);
1641
- return;
1642
- }
1643
- const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1644
- const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1645
- error = errorLookupResult.error;
1646
- name = errorLookupResult.name;
1647
- isValid = isEmptyObject(errors);
1648
- }
1649
- else {
1650
- _updateIsValidating([name], true);
1651
- error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1652
- _updateIsValidating([name]);
1653
- _updateIsFieldValueUpdated(fieldValue);
1654
- if (isFieldValueUpdated) {
1655
- if (error) {
1656
- isValid = false;
1657
- }
1658
- else if (_proxyFormState.isValid ||
1659
- _proxySubscribeFormState.isValid) {
1660
- isValid = await executeBuiltInValidation({
1661
- fields: _fields,
1662
- onlyCheckValid: true,
1663
- name: name,
1664
- eventType: event.type,
1665
- });
1666
- }
1667
- }
1668
- }
1669
- if (isFieldValueUpdated) {
1670
- field._f.deps &&
1671
- (!Array.isArray(field._f.deps) || field._f.deps.length > 0) &&
1672
- trigger(field._f.deps);
1673
- shouldRenderByError(name, isValid, error, fieldState);
1674
- }
1675
- }
1676
- };
1677
- const _focusInput = (ref, key) => {
1678
- if (get(_formState.errors, key) && ref.focus) {
1679
- ref.focus();
1680
- return 1;
1681
- }
1682
- return;
1683
- };
1684
- const trigger = async (name, options = {}) => {
1685
- let isValid;
1686
- let validationResult;
1687
- const fieldNames = convertToArrayPayload(name);
1688
- if (_options.resolver) {
1689
- const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1690
- isValid = isEmptyObject(errors);
1691
- validationResult = name
1692
- ? !fieldNames.some((name) => get(errors, name))
1693
- : isValid;
1694
- }
1695
- else if (name) {
1696
- validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1697
- const field = get(_fields, fieldName);
1698
- return await executeBuiltInValidation({
1699
- fields: field && field._f ? { [fieldName]: field } : field,
1700
- eventType: EVENTS.TRIGGER,
1701
- });
1702
- }))).every(Boolean);
1703
- !(!validationResult && !_formState.isValid) && _setValid();
1704
- }
1705
- else {
1706
- validationResult = isValid = await executeBuiltInValidation({
1707
- fields: _fields,
1708
- name,
1709
- eventType: EVENTS.TRIGGER,
1710
- });
1711
- }
1712
- if (options.delayError && _options.delayError && isString(name)) {
1713
- const error = get(_formState.errors, name);
1714
- if (error) {
1715
- unset(_formState.errors, name);
1716
- delayErrorCallbacks[name] = debounce(name, () => updateErrors(name, error));
1717
- delayErrorCallbacks[name](_options.delayError);
1718
- }
1719
- else {
1720
- clearTimeout(timers[name]);
1721
- delete delayErrorCallbacks[name];
1722
- }
1723
- }
1724
- _subjects.state.next({
1725
- ...(!isString(name) ||
1726
- ((_proxyFormState.isValid || _proxySubscribeFormState.isValid) &&
1727
- isValid !== _formState.isValid)
1728
- ? {}
1729
- : { name }),
1730
- ...(_options.resolver || !name ? { isValid } : {}),
1731
- errors: _formState.errors,
1732
- });
1733
- options.shouldFocus &&
1734
- !validationResult &&
1735
- iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
1736
- return validationResult;
1737
- };
1738
- const getValues = (fieldNames, config) => {
1739
- let values = {
1740
- ...(_state.mount ? _formValues : _defaultValues),
1741
- };
1742
- if (config) {
1743
- values = extractFormValues(config.dirtyFields ? _formState.dirtyFields : _formState.touchedFields, values);
1744
- }
1745
- return isUndefined(fieldNames)
1746
- ? values
1747
- : isString(fieldNames)
1748
- ? get(values, fieldNames)
1749
- : fieldNames.map((name) => get(values, name));
1750
- };
1751
- const getFieldState = (name, formState) => ({
1752
- invalid: !!get((formState || _formState).errors, name),
1753
- isDirty: !!get((formState || _formState).dirtyFields, name),
1754
- error: get((formState || _formState).errors, name),
1755
- isValidating: !!get(_formState.validatingFields, name),
1756
- isTouched: !!get((formState || _formState).touchedFields, name),
1757
- });
1758
- const clearErrors = (name) => {
1759
- const names = name ? convertToArrayPayload(name) : undefined;
1760
- names === null || names === void 0 ? void 0 : names.forEach((inputName) => unset(_formState.errors, inputName));
1761
- if (names) {
1762
- names.forEach((inputName) => {
1763
- _subjects.state.next({
1764
- name: inputName,
1765
- errors: _formState.errors,
1766
- });
1767
- });
1768
- }
1769
- else {
1770
- _formState.errors = {};
1771
- _subjects.state.next({
1772
- errors: _formState.errors,
1773
- });
1774
- }
1775
- };
1776
- const setError = (name, error, options) => {
1777
- const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1778
- const currentError = get(_formState.errors, name) || {};
1779
- const { ref: currentRef, message, type, ...restOfErrorTree } = currentError;
1780
- set(_formState.errors, name, {
1781
- ...restOfErrorTree,
1782
- ...error,
1783
- ref,
1784
- });
1785
- _subjects.state.next({
1786
- name,
1787
- errors: _formState.errors,
1788
- isValid: false,
1789
- });
1790
- options && options.shouldFocus && ref && ref.focus && ref.focus();
1791
- };
1792
- const watch = (name, defaultValue) => {
1793
- if (isFunction(name)) {
1794
- _valuesSubscriberCount++;
1795
- const { unsubscribe } = _subjects.state.subscribe({
1796
- next: (payload) => 'values' in payload &&
1797
- name(payload.values || _getWatch(undefined, defaultValue), payload),
1798
- });
1799
- let called = false;
1800
- return {
1801
- unsubscribe: () => {
1802
- if (called) {
1803
- return;
1804
- }
1805
- called = true;
1806
- _valuesSubscriberCount--;
1807
- unsubscribe();
1808
- },
1809
- };
1810
- }
1811
- return _getWatch(name, defaultValue, true);
1812
- };
1813
- const _subscribe = (props) => {
1814
- var _a;
1815
- const needsValues = !!((_a = props.formState) === null || _a === void 0 ? void 0 : _a.values);
1816
- if (needsValues) {
1817
- _valuesSubscriberCount++;
1818
- }
1819
- const { unsubscribe } = _subjects.state.subscribe({
1820
- next: (formState) => {
1821
- if (shouldSubscribeByName(props.name, formState.name, props.exact) &&
1822
- shouldRenderFormState(formState, props.formState || _proxyFormState, _setFormState, props.reRenderRoot)) {
1823
- const snapshot = { ..._formValues };
1824
- props.callback({
1825
- values: snapshot,
1826
- ..._formState,
1827
- ...formState,
1828
- defaultValues: _defaultValues,
1829
- });
1830
- }
1831
- },
1832
- });
1833
- if (!needsValues) {
1834
- return unsubscribe;
1835
- }
1836
- let called = false;
1837
- return () => {
1838
- if (called) {
1839
- return;
1840
- }
1841
- called = true;
1842
- _valuesSubscriberCount--;
1843
- unsubscribe();
1844
- };
1845
- };
1846
- const subscribe = (props) => {
1847
- _state.mount = true;
1848
- _proxySubscribeFormState = {
1849
- ..._proxySubscribeFormState,
1850
- ...props.formState,
1851
- };
1852
- return _subscribe({
1853
- ...props,
1854
- formState: {
1855
- ...defaultProxyFormState,
1856
- ...props.formState,
1857
- },
1858
- });
1859
- };
1860
- const unregister = (name, options = {}) => {
1861
- for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1862
- _names.mount.delete(fieldName);
1863
- _names.array.delete(fieldName);
1864
- if (!options.keepValue) {
1865
- unset(_fields, fieldName);
1866
- unset(_formValues, fieldName);
1867
- }
1868
- !options.keepError && unset(_formState.errors, fieldName);
1869
- !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1870
- !options.keepTouched && unset(_formState.touchedFields, fieldName);
1871
- !options.keepIsValidating &&
1872
- unset(_formState.validatingFields, fieldName);
1873
- !_options.shouldUnregister &&
1874
- !options.keepDefaultValue &&
1875
- unset(_defaultValues, fieldName);
1876
- }
1877
- _subjects.state.next({
1878
- values: cloneObject(_formValues),
1879
- });
1880
- _subjects.state.next({
1881
- ..._formState,
1882
- ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
1883
- });
1884
- !options.keepIsValid && _setValid();
1885
- };
1886
- const _setDisabledField = ({ disabled, name, }) => {
1887
- if ((isBoolean(disabled) && _state.mount) ||
1888
- !!disabled ||
1889
- _names.disabled.has(name)) {
1890
- const wasDisabled = _names.disabled.has(name);
1891
- const isDisabled = !!disabled;
1892
- const disabledStateChanged = wasDisabled !== isDisabled;
1893
- disabled ? _names.disabled.add(name) : _names.disabled.delete(name);
1894
- disabledStateChanged && _state.mount && !_state.action && _setValid();
1895
- }
1896
- };
1897
- const register = (name, options = {}) => {
1898
- let field = get(_fields, name);
1899
- const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled);
1900
- const shouldRevalidateRemount = !_names.registerName.has(name) && field && field._f && !field._f.mount;
1901
- set(_fields, name, {
1902
- ...(field || {}),
1903
- _f: {
1904
- ...(field && field._f ? field._f : { ref: { name } }),
1905
- name,
1906
- mount: true,
1907
- ...options,
1908
- },
1909
- });
1910
- _names.mount.add(name);
1911
- if (field && !shouldRevalidateRemount) {
1912
- _setDisabledField({
1913
- disabled: isBoolean(options.disabled)
1914
- ? options.disabled
1915
- : _options.disabled,
1916
- name,
1917
- });
1918
- }
1919
- else {
1920
- updateValidAndValue(name, true, options.value);
1921
- }
1922
- return {
1923
- ...(disabledIsDefined
1924
- ? { disabled: options.disabled || _options.disabled }
1925
- : {}),
1926
- ...(_options.progressive
1927
- ? {
1928
- required: !!options.required,
1929
- min: getRuleValue(options.min),
1930
- max: getRuleValue(options.max),
1931
- minLength: getRuleValue(options.minLength),
1932
- maxLength: getRuleValue(options.maxLength),
1933
- pattern: getRuleValue(options.pattern),
1934
- }
1935
- : {}),
1936
- name,
1937
- onChange,
1938
- onBlur: onChange,
1939
- ref: (ref) => {
1940
- if (ref) {
1941
- _names.registerName.add(name);
1942
- register(name, options);
1943
- _names.registerName.delete(name);
1944
- field = get(_fields, name);
1945
- const fieldRef = isUndefined(ref.value)
1946
- ? ref.querySelectorAll
1947
- ? ref.querySelectorAll('input,select,textarea')[0] || ref
1948
- : ref
1949
- : ref;
1950
- const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1951
- const refs = field._f.refs || [];
1952
- if (radioOrCheckbox
1953
- ? refs.find((option) => option === fieldRef)
1954
- : fieldRef === field._f.ref) {
1955
- return;
1956
- }
1957
- const newField = {
1958
- ...field._f,
1959
- };
1960
- if (radioOrCheckbox) {
1961
- newField.refs = [
1962
- ...refs.filter(live),
1963
- fieldRef,
1964
- ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
1965
- ];
1966
- newField.ref = { type: fieldRef.type, name };
1967
- }
1968
- else {
1969
- newField.ref = fieldRef;
1970
- delete newField.refs;
1971
- }
1972
- set(_fields, name, {
1973
- _f: newField,
1974
- });
1975
- updateValidAndValue(name, false, undefined, fieldRef);
1976
- }
1977
- else {
1978
- field = get(_fields, name, {});
1979
- if (field._f) {
1980
- field._f.mount = false;
1981
- }
1982
- (_options.shouldUnregister || options.shouldUnregister) &&
1983
- !(isNameInFieldArray(_names.array, name) && _state.action) &&
1984
- _names.unMount.add(name);
1985
- }
1986
- },
1987
- };
1988
- };
1989
- const _focusError = () => _options.shouldFocusError &&
1990
- !_options.shouldUseNativeValidation &&
1991
- iterateFieldsByAction(_fields, _focusInput, _names.mount);
1992
- const _disableForm = (disabled) => {
1993
- if (isBoolean(disabled)) {
1994
- _subjects.state.next({ disabled });
1995
- iterateFieldsByAction(_fields, (ref, name) => {
1996
- const currentField = get(_fields, name);
1997
- if (currentField) {
1998
- ref.disabled = currentField._f.disabled || disabled;
1999
- if (Array.isArray(currentField._f.refs)) {
2000
- currentField._f.refs.forEach((inputRef) => {
2001
- inputRef.disabled = currentField._f.disabled || disabled;
2002
- });
2003
- }
2004
- }
2005
- }, 0, false);
2006
- }
2007
- };
2008
- const handleSubmit = (onValid, onInvalid) => async (e) => {
2009
- let result = undefined;
2010
- let onValidError = undefined;
2011
- if (e) {
2012
- e.preventDefault && e.preventDefault();
2013
- e.persist &&
2014
- e.persist();
2015
- }
2016
- let fieldValues = cloneObject(_formValues);
2017
- _subjects.state.next({
2018
- isSubmitting: true,
2019
- });
2020
- if (_options.resolver) {
2021
- const { errors, values } = await _runSchema();
2022
- _updateIsValidating();
2023
- _formState.errors = errors;
2024
- fieldValues = cloneObject(values);
2025
- }
2026
- else {
2027
- await executeBuiltInValidation({
2028
- fields: _fields,
2029
- eventType: EVENTS.SUBMIT,
2030
- });
2031
- }
2032
- if (_names.disabled.size) {
2033
- for (const name of _names.disabled) {
2034
- unset(fieldValues, name);
2035
- }
2036
- }
2037
- unset(_formState.errors, ROOT_ERROR_TYPE);
2038
- if (isEmptyObject(_formState.errors)) {
2039
- _subjects.state.next({
2040
- errors: {},
2041
- });
2042
- try {
2043
- result = await onValid(fieldValues, e);
2044
- }
2045
- catch (error) {
2046
- onValidError = error;
2047
- }
2048
- }
2049
- else {
2050
- if (onInvalid) {
2051
- await onInvalid({ ..._formState.errors }, e);
2052
- }
2053
- _focusError();
2054
- setTimeout(_focusError);
2055
- }
2056
- _subjects.state.next({
2057
- isSubmitted: true,
2058
- isSubmitting: false,
2059
- isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
2060
- submitCount: _formState.submitCount + 1,
2061
- errors: _formState.errors,
2062
- });
2063
- if (onValidError) {
2064
- throw onValidError;
2065
- }
2066
- return result;
2067
- };
2068
- const resetField = (name, options = {}) => {
2069
- if (get(_fields, name)) {
2070
- if (isUndefined(options.defaultValue)) {
2071
- setValue(name, cloneObject(get(_defaultValues, name)));
2072
- }
2073
- else {
2074
- setValue(name, options.defaultValue);
2075
- set(_defaultValues, name, cloneObject(options.defaultValue));
2076
- }
2077
- if (!options.keepTouched) {
2078
- unset(_formState.touchedFields, name);
2079
- }
2080
- if (!options.keepDirty) {
2081
- unset(_formState.dirtyFields, name);
2082
- _formState.isDirty = options.defaultValue
2083
- ? _getDirty(name, cloneObject(get(_defaultValues, name)))
2084
- : _getDirty();
2085
- }
2086
- if (!options.keepError) {
2087
- unset(_formState.errors, name);
2088
- _proxyFormState.isValid && _setValid();
2089
- }
2090
- _subjects.state.next({ ..._formState });
2091
- }
2092
- };
2093
- const _reset = (formValues, keepStateOptions = {}) => {
2094
- const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
2095
- const cloneUpdatedValues = cloneObject(updatedValues);
2096
- const isEmptyResetValues = isEmptyObject(formValues);
2097
- const values = cloneUpdatedValues;
2098
- const fieldRefs = _fields;
2099
- if (!keepStateOptions.keepDefaultValues) {
2100
- _defaultValues = updatedValues;
2101
- }
2102
- if (!keepStateOptions.keepValues) {
2103
- if (keepStateOptions.keepDirtyValues) {
2104
- const fieldsToCheck = new Set([
2105
- ..._names.mount,
2106
- ...collectDirtyFieldNames(getDirtyFields(_defaultValues, _formValues, undefined, fieldRefs), _formState.dirtyFields),
2107
- ]);
2108
- for (const fieldName of Array.from(fieldsToCheck)) {
2109
- const isDirty = get(_formState.dirtyFields, fieldName);
2110
- const existingValue = get(_formValues, fieldName);
2111
- const newValue = get(values, fieldName);
2112
- if (isDirty && !isUndefined(existingValue)) {
2113
- set(values, fieldName, existingValue);
2114
- }
2115
- else if (!isDirty && !isUndefined(newValue)) {
2116
- setValue(fieldName, newValue);
2117
- }
2118
- }
2119
- }
2120
- else {
2121
- if (isWeb && isUndefined(formValues)) {
2122
- for (const name of _names.mount) {
2123
- const field = get(_fields, name);
2124
- if (field && field._f) {
2125
- const fieldReference = Array.isArray(field._f.refs)
2126
- ? field._f.refs[0]
2127
- : field._f.ref;
2128
- if (isHTMLElement(fieldReference)) {
2129
- const form = fieldReference.closest('form');
2130
- if (form) {
2131
- form.reset();
2132
- break;
2133
- }
2134
- }
2135
- }
2136
- }
2137
- }
2138
- if (keepStateOptions.keepFieldsRef) {
2139
- for (const fieldName of _names.mount) {
2140
- setValue(fieldName, get(values, fieldName));
2141
- }
2142
- }
2143
- else {
2144
- _fields = {};
2145
- }
2146
- }
2147
- if (_options.shouldUnregister) {
2148
- _formValues = keepStateOptions.keepDefaultValues
2149
- ? cloneObject(_defaultValues)
2150
- : {};
2151
- if (keepStateOptions.keepFieldsRef) {
2152
- for (const fieldName of _names.mount) {
2153
- set(_formValues, fieldName, get(values, fieldName));
2154
- }
2155
- }
2156
- }
2157
- else {
2158
- _formValues = cloneObject(values);
2159
- }
2160
- _subjects.array.next({
2161
- values: { ...values },
2162
- });
2163
- _subjects.state.next({
2164
- name: undefined,
2165
- type: undefined,
2166
- values: { ...values },
2167
- });
2168
- }
2169
- _names = {
2170
- mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(),
2171
- unMount: new Set(),
2172
- array: new Set(),
2173
- registerName: new Set(),
2174
- disabled: new Set(),
2175
- watch: new Set(),
2176
- watchAll: false,
2177
- focus: '',
2178
- };
2179
- _state.mount =
2180
- !_proxyFormState.isValid ||
2181
- !!keepStateOptions.keepIsValid ||
2182
- !!keepStateOptions.keepDirtyValues ||
2183
- (!_options.shouldUnregister && !isEmptyObject(values));
2184
- _state.watch = !!_options.shouldUnregister;
2185
- _state.keepIsValid = !!keepStateOptions.keepIsValid;
2186
- _state.action = false;
2187
- _state.actionArrayLengths.clear();
2188
- if (!keepStateOptions.keepErrors) {
2189
- _formState.errors = {};
2190
- }
2191
- _subjects.state.next({
2192
- submitCount: keepStateOptions.keepSubmitCount
2193
- ? _formState.submitCount
2194
- : 0,
2195
- isDirty: isEmptyResetValues
2196
- ? false
2197
- : keepStateOptions.keepDirty
2198
- ? _formState.isDirty
2199
- : keepStateOptions.keepValues
2200
- ? _getDirty()
2201
- : !!(keepStateOptions.keepDefaultValues &&
2202
- !deepEqual(formValues, _defaultValues)),
2203
- isSubmitted: keepStateOptions.keepIsSubmitted
2204
- ? _formState.isSubmitted
2205
- : false,
2206
- dirtyFields: isEmptyResetValues
2207
- ? {}
2208
- : keepStateOptions.keepDirtyValues
2209
- ? keepStateOptions.keepDefaultValues && _formValues
2210
- ? getDirtyFields(_defaultValues, _formValues, undefined, fieldRefs)
2211
- : _formState.dirtyFields
2212
- : keepStateOptions.keepDefaultValues && formValues
2213
- ? getDirtyFields(_defaultValues, formValues, undefined, fieldRefs)
2214
- : keepStateOptions.keepDirty
2215
- ? _formState.dirtyFields
2216
- : {},
2217
- touchedFields: keepStateOptions.keepTouched
2218
- ? _formState.touchedFields
2219
- : {},
2220
- errors: keepStateOptions.keepErrors ? _formState.errors : {},
2221
- isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful
2222
- ? _formState.isSubmitSuccessful
2223
- : false,
2224
- isSubmitting: false,
2225
- defaultValues: _defaultValues,
2226
- });
2227
- };
2228
- const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
2229
- ? formValues(_formValues)
2230
- : formValues, { ..._options.resetOptions, ...keepStateOptions });
2231
- const setFocus = (name, options = {}) => {
2232
- const field = get(_fields, name);
2233
- const fieldReference = field && field._f;
2234
- if (fieldReference) {
2235
- const fieldRef = fieldReference.refs
2236
- ? fieldReference.refs[0]
2237
- : fieldReference.ref;
2238
- if (fieldRef.focus) {
2239
- setTimeout(() => {
2240
- fieldRef.focus();
2241
- options.shouldSelect &&
2242
- isFunction(fieldRef.select) &&
2243
- fieldRef.select();
2244
- });
2245
- }
2246
- }
2247
- };
2248
- const _setFormState = (updatedFormState) => {
2249
- // `name`, `type`, and `values` describe the event that produced this
2250
- // update, not the form's persisted state (they aren't part of
2251
- // `FormState`). Merging them in would leak a stale `name`/`type` from
2252
- // one event into a later, unrelated notification that doesn't specify
2253
- // its own.
2254
- const { name, type, values, ...formState } = updatedFormState;
2255
- _formState = {
2256
- ..._formState,
2257
- ...formState,
2258
- };
2259
- };
2260
- _subjects.state.subscribe({ next: _setFormState });
2261
- const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
2262
- _options.defaultValues().then((values) => {
2263
- reset(values, _options.resetOptions);
2264
- _subjects.state.next({
2265
- isLoading: false,
2266
- });
2267
- });
2268
- const resetDefaultValues = (values, options = {}) => {
2269
- _defaultValues = cloneObject(values);
2270
- if (!options.keepDirty) {
2271
- const newDirtyFields = getDirtyFields(_defaultValues, _formValues, undefined, _fields);
2272
- _formState.dirtyFields = newDirtyFields;
2273
- _formState.isDirty = !isEmptyObject(newDirtyFields);
2274
- }
2275
- if (!options.keepIsValid) {
2276
- _setValid();
2277
- }
2278
- _subjects.state.next({
2279
- ..._formState,
2280
- defaultValues: _defaultValues,
2281
- });
2282
- };
2283
- const methods = {
2284
- control: {
2285
- register,
2286
- unregister,
2287
- getFieldState,
2288
- handleSubmit,
2289
- setError,
2290
- _subscribe,
2291
- _runSchema,
2292
- _updateIsValidating,
2293
- _focusError,
2294
- _getWatch,
2295
- _getDirty,
2296
- _setValid,
2297
- _setFieldArray,
2298
- _setDisabledField,
2299
- _setErrors,
2300
- _getFieldArray,
2301
- _reset,
2302
- _resetDefaultValues,
2303
- _removeUnmounted,
2304
- _disableForm,
2305
- _subjects,
2306
- _proxyFormState,
2307
- get _fields() {
2308
- return _fields;
2309
- },
2310
- get _formValues() {
2311
- return _formValues;
2312
- },
2313
- get _state() {
2314
- return _state;
2315
- },
2316
- set _state(value) {
2317
- _state = value;
2318
- },
2319
- get _defaultValues() {
2320
- return _defaultValues;
2321
- },
2322
- get _names() {
2323
- return _names;
2324
- },
2325
- set _names(value) {
2326
- _names = value;
2327
- },
2328
- get _formState() {
2329
- return _formState;
2330
- },
2331
- get _options() {
2332
- return _options;
2333
- },
2334
- set _options(value) {
2335
- _options = {
2336
- ..._options,
2337
- ...value,
2338
- };
2339
- _validationModeBeforeSubmit = getValidationModes(_options.mode);
2340
- _validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
2341
- },
2342
- },
2343
- subscribe,
2344
- trigger,
2345
- register,
2346
- handleSubmit,
2347
- watch,
2348
- setValue,
2349
- setValues,
2350
- getValues,
2351
- reset,
2352
- resetField,
2353
- resetDefaultValues,
2354
- clearErrors,
2355
- unregister,
2356
- setError,
2357
- setFocus,
2358
- getFieldState,
2359
- };
2360
- return {
2361
- ...methods,
2362
- formControl: methods,
2363
- };
2364
- }
2365
-
2366
- export { appendErrors, createFormControl, get, set };
2367
- //# sourceMappingURL=react-server.esm.mjs.map