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