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