@icap-ethiopia/esm-ethiohri-intake 1.0.0-pre.9 → 1.0.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 (95) hide show
  1. package/LICENSE +400 -400
  2. package/README.md +46 -46
  3. package/dist/main.js +4914 -1
  4. package/dist/main.js.map +1 -1
  5. package/dist/node_modules_dayjs_dayjs_min_js.js +14 -0
  6. package/dist/node_modules_dayjs_dayjs_min_js.js.map +1 -0
  7. package/dist/openmrs-esm-ethio-template-app.js +4696 -1
  8. package/dist/openmrs-esm-ethio-template-app.js.buildmanifest.json +233 -249
  9. package/dist/openmrs-esm-ethio-template-app.js.map +1 -1
  10. package/dist/routes.json +1 -1
  11. package/dist/src_forms_family-information_tsx.js +934 -0
  12. package/dist/src_forms_family-information_tsx.js.map +1 -0
  13. package/dist/src_forms_intake-a-form_tsx.js +2367 -0
  14. package/dist/src_forms_intake-a-form_tsx.js.map +1 -0
  15. package/dist/src_forms_intake-b-form_tsx.js +2684 -0
  16. package/dist/src_forms_intake-b-form_tsx.js.map +1 -0
  17. package/dist/src_forms_intake-form_scss-src_forms_hooks_createEncounter_ts-src_forms_hooks_defaultValuesFr-54076e.js +2871 -0
  18. package/dist/src_forms_intake-form_scss-src_forms_hooks_createEncounter_ts-src_forms_hooks_defaultValuesFr-54076e.js.map +1 -0
  19. package/dist/src_forms_phdp-form_tsx.js +470 -0
  20. package/dist/src_forms_phdp-form_tsx.js.map +1 -0
  21. package/dist/src_index_ts.js +255 -0
  22. package/dist/src_index_ts.js.map +1 -0
  23. package/dist/src_intake_index_tsx.js +2738 -0
  24. package/dist/src_intake_index_tsx.js.map +1 -0
  25. package/dist/src_root_component_tsx.js +615 -0
  26. package/dist/src_root_component_tsx.js.map +1 -0
  27. package/dist/src_utils_Delete-Encounter_modal_tsx.js +396 -0
  28. package/dist/src_utils_Delete-Encounter_modal_tsx.js.map +1 -0
  29. package/dist/translations_am_json.js +14 -0
  30. package/dist/translations_en_json.js +14 -0
  31. package/dist/translations_es_json.js +14 -0
  32. package/dist/translations_fr_json.js +14 -0
  33. package/dist/translations_he_json.js +14 -0
  34. package/dist/translations_km_json.js +14 -0
  35. package/dist/vendors-node_modules_carbon_react_es_index_js-node_modules_swr_dist_core_index_mjs.js +132608 -0
  36. package/dist/vendors-node_modules_carbon_react_es_index_js-node_modules_swr_dist_core_index_mjs.js.map +1 -0
  37. package/dist/vendors-node_modules_openmrs_esm-framework_src_internal_ts.js +35952 -0
  38. package/dist/vendors-node_modules_openmrs_esm-framework_src_internal_ts.js.map +1 -0
  39. package/dist/vendors-node_modules_openmrs_esm-patient-common-lib_src_index_ts-node_modules_openmrs_esm-pat-24e5c8.js +4695 -0
  40. package/dist/vendors-node_modules_openmrs_esm-patient-common-lib_src_index_ts-node_modules_openmrs_esm-pat-24e5c8.js.map +1 -0
  41. package/dist/vendors-node_modules_openmrs_node_modules_css-loader_dist_runtime_api_js-node_modules_openmrs-205702.js +3059 -0
  42. package/dist/vendors-node_modules_openmrs_node_modules_css-loader_dist_runtime_api_js-node_modules_openmrs-205702.js.map +1 -0
  43. package/dist/vendors-node_modules_react-i18next_dist_es_index_js.js +1424 -0
  44. package/dist/vendors-node_modules_react-i18next_dist_es_index_js.js.map +1 -0
  45. package/dist/vendors-node_modules_react-router-dom_dist_index_js.js +6574 -0
  46. package/dist/vendors-node_modules_react-router-dom_dist_index_js.js.map +1 -0
  47. package/dist/vendors-node_modules_react_index_js.js +2770 -0
  48. package/dist/vendors-node_modules_react_index_js.js.map +1 -0
  49. package/package.json +121 -121
  50. package/src/index.ts +34 -34
  51. package/dist/151.js +0 -2
  52. package/dist/151.js.LICENSE.txt +0 -3
  53. package/dist/151.js.map +0 -1
  54. package/dist/159.js +0 -1
  55. package/dist/159.js.map +0 -1
  56. package/dist/197.js +0 -1
  57. package/dist/222.js +0 -2
  58. package/dist/222.js.LICENSE.txt +0 -5
  59. package/dist/222.js.map +0 -1
  60. package/dist/282.js +0 -2
  61. package/dist/282.js.LICENSE.txt +0 -32
  62. package/dist/282.js.map +0 -1
  63. package/dist/300.js +0 -1
  64. package/dist/319.js +0 -1
  65. package/dist/319.js.map +0 -1
  66. package/dist/335.js +0 -1
  67. package/dist/353.js +0 -1
  68. package/dist/353.js.map +0 -1
  69. package/dist/404.js +0 -2
  70. package/dist/404.js.LICENSE.txt +0 -45
  71. package/dist/404.js.map +0 -1
  72. package/dist/410.js +0 -1
  73. package/dist/410.js.map +0 -1
  74. package/dist/475.js +0 -1
  75. package/dist/475.js.map +0 -1
  76. package/dist/540.js +0 -2
  77. package/dist/540.js.LICENSE.txt +0 -9
  78. package/dist/540.js.map +0 -1
  79. package/dist/55.js +0 -1
  80. package/dist/652.js +0 -1
  81. package/dist/692.js +0 -1
  82. package/dist/692.js.map +0 -1
  83. package/dist/712.js +0 -1
  84. package/dist/712.js.map +0 -1
  85. package/dist/912.js +0 -1
  86. package/dist/912.js.map +0 -1
  87. package/dist/917.js +0 -1
  88. package/dist/917.js.map +0 -1
  89. package/dist/937.js +0 -1
  90. package/dist/937.js.map +0 -1
  91. package/dist/940.js +0 -1
  92. package/dist/940.js.map +0 -1
  93. package/dist/979.js +0 -1
  94. package/dist/979.js.map +0 -1
  95. package/dist/99.js +0 -1
@@ -0,0 +1,3059 @@
1
+ "use strict";
2
+ (globalThis["webpackChunk_icap_ethiopia_esm_ethiohri_intake"] = globalThis["webpackChunk_icap_ethiopia_esm_ethiohri_intake"] || []).push([["vendors-node_modules_openmrs_node_modules_css-loader_dist_runtime_api_js-node_modules_openmrs-205702"],{
3
+
4
+ /***/ "./node_modules/openmrs/node_modules/css-loader/dist/runtime/api.js":
5
+ /*!**************************************************************************!*\
6
+ !*** ./node_modules/openmrs/node_modules/css-loader/dist/runtime/api.js ***!
7
+ \**************************************************************************/
8
+ /***/ ((module) => {
9
+
10
+
11
+
12
+ /*
13
+ MIT License http://www.opensource.org/licenses/mit-license.php
14
+ Author Tobias Koppers @sokra
15
+ */
16
+ // css base code, injected by the css-loader
17
+ // eslint-disable-next-line func-names
18
+ module.exports = function (cssWithMappingToString) {
19
+ var list = []; // return the list of modules as css string
20
+
21
+ list.toString = function toString() {
22
+ return this.map(function (item) {
23
+ var content = cssWithMappingToString(item);
24
+
25
+ if (item[2]) {
26
+ return "@media ".concat(item[2], " {").concat(content, "}");
27
+ }
28
+
29
+ return content;
30
+ }).join("");
31
+ }; // import a list of modules into the list
32
+ // eslint-disable-next-line func-names
33
+
34
+
35
+ list.i = function (modules, mediaQuery, dedupe) {
36
+ if (typeof modules === "string") {
37
+ // eslint-disable-next-line no-param-reassign
38
+ modules = [[null, modules, ""]];
39
+ }
40
+
41
+ var alreadyImportedModules = {};
42
+
43
+ if (dedupe) {
44
+ for (var i = 0; i < this.length; i++) {
45
+ // eslint-disable-next-line prefer-destructuring
46
+ var id = this[i][0];
47
+
48
+ if (id != null) {
49
+ alreadyImportedModules[id] = true;
50
+ }
51
+ }
52
+ }
53
+
54
+ for (var _i = 0; _i < modules.length; _i++) {
55
+ var item = [].concat(modules[_i]);
56
+
57
+ if (dedupe && alreadyImportedModules[item[0]]) {
58
+ // eslint-disable-next-line no-continue
59
+ continue;
60
+ }
61
+
62
+ if (mediaQuery) {
63
+ if (!item[2]) {
64
+ item[2] = mediaQuery;
65
+ } else {
66
+ item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
67
+ }
68
+ }
69
+
70
+ list.push(item);
71
+ }
72
+ };
73
+
74
+ return list;
75
+ };
76
+
77
+ /***/ }),
78
+
79
+ /***/ "./node_modules/openmrs/node_modules/css-loader/dist/runtime/cssWithMappingToString.js":
80
+ /*!*********************************************************************************************!*\
81
+ !*** ./node_modules/openmrs/node_modules/css-loader/dist/runtime/cssWithMappingToString.js ***!
82
+ \*********************************************************************************************/
83
+ /***/ ((module) => {
84
+
85
+
86
+
87
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
88
+
89
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
90
+
91
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
92
+
93
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
94
+
95
+ function _iterableToArrayLimit(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
96
+
97
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
98
+
99
+ module.exports = function cssWithMappingToString(item) {
100
+ var _item = _slicedToArray(item, 4),
101
+ content = _item[1],
102
+ cssMapping = _item[3];
103
+
104
+ if (!cssMapping) {
105
+ return content;
106
+ }
107
+
108
+ if (typeof btoa === "function") {
109
+ // eslint-disable-next-line no-undef
110
+ var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping))));
111
+ var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
112
+ var sourceMapping = "/*# ".concat(data, " */");
113
+ var sourceURLs = cssMapping.sources.map(function (source) {
114
+ return "/*# sourceURL=".concat(cssMapping.sourceRoot || "").concat(source, " */");
115
+ });
116
+ return [content].concat(sourceURLs).concat([sourceMapping]).join("\n");
117
+ }
118
+
119
+ return [content].join("\n");
120
+ };
121
+
122
+ /***/ }),
123
+
124
+ /***/ "./node_modules/openmrs/node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js":
125
+ /*!*************************************************************************************************!*\
126
+ !*** ./node_modules/openmrs/node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***!
127
+ \*************************************************************************************************/
128
+ /***/ ((module) => {
129
+
130
+
131
+
132
+ var stylesInDOM = [];
133
+
134
+ function getIndexByIdentifier(identifier) {
135
+ var result = -1;
136
+
137
+ for (var i = 0; i < stylesInDOM.length; i++) {
138
+ if (stylesInDOM[i].identifier === identifier) {
139
+ result = i;
140
+ break;
141
+ }
142
+ }
143
+
144
+ return result;
145
+ }
146
+
147
+ function modulesToDom(list, options) {
148
+ var idCountMap = {};
149
+ var identifiers = [];
150
+
151
+ for (var i = 0; i < list.length; i++) {
152
+ var item = list[i];
153
+ var id = options.base ? item[0] + options.base : item[0];
154
+ var count = idCountMap[id] || 0;
155
+ var identifier = "".concat(id, " ").concat(count);
156
+ idCountMap[id] = count + 1;
157
+ var indexByIdentifier = getIndexByIdentifier(identifier);
158
+ var obj = {
159
+ css: item[1],
160
+ media: item[2],
161
+ sourceMap: item[3],
162
+ supports: item[4],
163
+ layer: item[5]
164
+ };
165
+
166
+ if (indexByIdentifier !== -1) {
167
+ stylesInDOM[indexByIdentifier].references++;
168
+ stylesInDOM[indexByIdentifier].updater(obj);
169
+ } else {
170
+ var updater = addElementStyle(obj, options);
171
+ options.byIndex = i;
172
+ stylesInDOM.splice(i, 0, {
173
+ identifier: identifier,
174
+ updater: updater,
175
+ references: 1
176
+ });
177
+ }
178
+
179
+ identifiers.push(identifier);
180
+ }
181
+
182
+ return identifiers;
183
+ }
184
+
185
+ function addElementStyle(obj, options) {
186
+ var api = options.domAPI(options);
187
+ api.update(obj);
188
+
189
+ var updater = function updater(newObj) {
190
+ if (newObj) {
191
+ if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap && newObj.supports === obj.supports && newObj.layer === obj.layer) {
192
+ return;
193
+ }
194
+
195
+ api.update(obj = newObj);
196
+ } else {
197
+ api.remove();
198
+ }
199
+ };
200
+
201
+ return updater;
202
+ }
203
+
204
+ module.exports = function (list, options) {
205
+ options = options || {};
206
+ list = list || [];
207
+ var lastIdentifiers = modulesToDom(list, options);
208
+ return function update(newList) {
209
+ newList = newList || [];
210
+
211
+ for (var i = 0; i < lastIdentifiers.length; i++) {
212
+ var identifier = lastIdentifiers[i];
213
+ var index = getIndexByIdentifier(identifier);
214
+ stylesInDOM[index].references--;
215
+ }
216
+
217
+ var newLastIdentifiers = modulesToDom(newList, options);
218
+
219
+ for (var _i = 0; _i < lastIdentifiers.length; _i++) {
220
+ var _identifier = lastIdentifiers[_i];
221
+
222
+ var _index = getIndexByIdentifier(_identifier);
223
+
224
+ if (stylesInDOM[_index].references === 0) {
225
+ stylesInDOM[_index].updater();
226
+
227
+ stylesInDOM.splice(_index, 1);
228
+ }
229
+ }
230
+
231
+ lastIdentifiers = newLastIdentifiers;
232
+ };
233
+ };
234
+
235
+ /***/ }),
236
+
237
+ /***/ "./node_modules/openmrs/node_modules/style-loader/dist/runtime/insertBySelector.js":
238
+ /*!*****************************************************************************************!*\
239
+ !*** ./node_modules/openmrs/node_modules/style-loader/dist/runtime/insertBySelector.js ***!
240
+ \*****************************************************************************************/
241
+ /***/ ((module) => {
242
+
243
+
244
+
245
+ var memo = {};
246
+ /* istanbul ignore next */
247
+
248
+ function getTarget(target) {
249
+ if (typeof memo[target] === "undefined") {
250
+ var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself
251
+
252
+ if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
253
+ try {
254
+ // This will throw an exception if access to iframe is blocked
255
+ // due to cross-origin restrictions
256
+ styleTarget = styleTarget.contentDocument.head;
257
+ } catch (e) {
258
+ // istanbul ignore next
259
+ styleTarget = null;
260
+ }
261
+ }
262
+
263
+ memo[target] = styleTarget;
264
+ }
265
+
266
+ return memo[target];
267
+ }
268
+ /* istanbul ignore next */
269
+
270
+
271
+ function insertBySelector(insert, style) {
272
+ var target = getTarget(insert);
273
+
274
+ if (!target) {
275
+ throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
276
+ }
277
+
278
+ target.appendChild(style);
279
+ }
280
+
281
+ module.exports = insertBySelector;
282
+
283
+ /***/ }),
284
+
285
+ /***/ "./node_modules/openmrs/node_modules/style-loader/dist/runtime/insertStyleElement.js":
286
+ /*!*******************************************************************************************!*\
287
+ !*** ./node_modules/openmrs/node_modules/style-loader/dist/runtime/insertStyleElement.js ***!
288
+ \*******************************************************************************************/
289
+ /***/ ((module) => {
290
+
291
+
292
+
293
+ /* istanbul ignore next */
294
+ function insertStyleElement(options) {
295
+ var element = document.createElement("style");
296
+ options.setAttributes(element, options.attributes);
297
+ options.insert(element, options.options);
298
+ return element;
299
+ }
300
+
301
+ module.exports = insertStyleElement;
302
+
303
+ /***/ }),
304
+
305
+ /***/ "./node_modules/openmrs/node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js":
306
+ /*!*******************************************************************************************************!*\
307
+ !*** ./node_modules/openmrs/node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js ***!
308
+ \*******************************************************************************************************/
309
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
310
+
311
+
312
+
313
+ /* istanbul ignore next */
314
+ function setAttributesWithoutAttributes(styleElement) {
315
+ var nonce = true ? __webpack_require__.nc : 0;
316
+
317
+ if (nonce) {
318
+ styleElement.setAttribute("nonce", nonce);
319
+ }
320
+ }
321
+
322
+ module.exports = setAttributesWithoutAttributes;
323
+
324
+ /***/ }),
325
+
326
+ /***/ "./node_modules/openmrs/node_modules/style-loader/dist/runtime/styleDomAPI.js":
327
+ /*!************************************************************************************!*\
328
+ !*** ./node_modules/openmrs/node_modules/style-loader/dist/runtime/styleDomAPI.js ***!
329
+ \************************************************************************************/
330
+ /***/ ((module) => {
331
+
332
+
333
+
334
+ /* istanbul ignore next */
335
+ function apply(styleElement, options, obj) {
336
+ var css = "";
337
+
338
+ if (obj.supports) {
339
+ css += "@supports (".concat(obj.supports, ") {");
340
+ }
341
+
342
+ if (obj.media) {
343
+ css += "@media ".concat(obj.media, " {");
344
+ }
345
+
346
+ var needLayer = typeof obj.layer !== "undefined";
347
+
348
+ if (needLayer) {
349
+ css += "@layer".concat(obj.layer.length > 0 ? " ".concat(obj.layer) : "", " {");
350
+ }
351
+
352
+ css += obj.css;
353
+
354
+ if (needLayer) {
355
+ css += "}";
356
+ }
357
+
358
+ if (obj.media) {
359
+ css += "}";
360
+ }
361
+
362
+ if (obj.supports) {
363
+ css += "}";
364
+ }
365
+
366
+ var sourceMap = obj.sourceMap;
367
+
368
+ if (sourceMap && typeof btoa !== "undefined") {
369
+ css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
370
+ } // For old IE
371
+
372
+ /* istanbul ignore if */
373
+
374
+
375
+ options.styleTagTransform(css, styleElement, options.options);
376
+ }
377
+
378
+ function removeStyleElement(styleElement) {
379
+ // istanbul ignore if
380
+ if (styleElement.parentNode === null) {
381
+ return false;
382
+ }
383
+
384
+ styleElement.parentNode.removeChild(styleElement);
385
+ }
386
+ /* istanbul ignore next */
387
+
388
+
389
+ function domAPI(options) {
390
+ var styleElement = options.insertStyleElement(options);
391
+ return {
392
+ update: function update(obj) {
393
+ apply(styleElement, options, obj);
394
+ },
395
+ remove: function remove() {
396
+ removeStyleElement(styleElement);
397
+ }
398
+ };
399
+ }
400
+
401
+ module.exports = domAPI;
402
+
403
+ /***/ }),
404
+
405
+ /***/ "./node_modules/openmrs/node_modules/style-loader/dist/runtime/styleTagTransform.js":
406
+ /*!******************************************************************************************!*\
407
+ !*** ./node_modules/openmrs/node_modules/style-loader/dist/runtime/styleTagTransform.js ***!
408
+ \******************************************************************************************/
409
+ /***/ ((module) => {
410
+
411
+
412
+
413
+ /* istanbul ignore next */
414
+ function styleTagTransform(css, styleElement) {
415
+ if (styleElement.styleSheet) {
416
+ styleElement.styleSheet.cssText = css;
417
+ } else {
418
+ while (styleElement.firstChild) {
419
+ styleElement.removeChild(styleElement.firstChild);
420
+ }
421
+
422
+ styleElement.appendChild(document.createTextNode(css));
423
+ }
424
+ }
425
+
426
+ module.exports = styleTagTransform;
427
+
428
+ /***/ }),
429
+
430
+ /***/ "./node_modules/react-hook-form/dist/index.esm.mjs":
431
+ /*!*********************************************************!*\
432
+ !*** ./node_modules/react-hook-form/dist/index.esm.mjs ***!
433
+ \*********************************************************/
434
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
435
+
436
+ __webpack_require__.r(__webpack_exports__);
437
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
438
+ /* harmony export */ Controller: () => (/* binding */ Controller),
439
+ /* harmony export */ Form: () => (/* binding */ Form),
440
+ /* harmony export */ FormProvider: () => (/* binding */ FormProvider),
441
+ /* harmony export */ appendErrors: () => (/* binding */ appendErrors),
442
+ /* harmony export */ get: () => (/* binding */ get),
443
+ /* harmony export */ set: () => (/* binding */ set),
444
+ /* harmony export */ useController: () => (/* binding */ useController),
445
+ /* harmony export */ useFieldArray: () => (/* binding */ useFieldArray),
446
+ /* harmony export */ useForm: () => (/* binding */ useForm),
447
+ /* harmony export */ useFormContext: () => (/* binding */ useFormContext),
448
+ /* harmony export */ useFormState: () => (/* binding */ useFormState),
449
+ /* harmony export */ useWatch: () => (/* binding */ useWatch)
450
+ /* harmony export */ });
451
+ /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react/react");
452
+
453
+
454
+ var isCheckBoxInput = (element) => element.type === 'checkbox';
455
+
456
+ var isDateObject = (value) => value instanceof Date;
457
+
458
+ var isNullOrUndefined = (value) => value == null;
459
+
460
+ const isObjectType = (value) => typeof value === 'object';
461
+ var isObject = (value) => !isNullOrUndefined(value) &&
462
+ !Array.isArray(value) &&
463
+ isObjectType(value) &&
464
+ !isDateObject(value);
465
+
466
+ var getEventValue = (event) => isObject(event) && event.target
467
+ ? isCheckBoxInput(event.target)
468
+ ? event.target.checked
469
+ : event.target.value
470
+ : event;
471
+
472
+ var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
473
+
474
+ var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
475
+
476
+ var isPlainObject = (tempObject) => {
477
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
478
+ return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
479
+ };
480
+
481
+ var isWeb = typeof window !== 'undefined' &&
482
+ typeof window.HTMLElement !== 'undefined' &&
483
+ typeof document !== 'undefined';
484
+
485
+ function cloneObject(data) {
486
+ let copy;
487
+ const isArray = Array.isArray(data);
488
+ if (data instanceof Date) {
489
+ copy = new Date(data);
490
+ }
491
+ else if (data instanceof Set) {
492
+ copy = new Set(data);
493
+ }
494
+ else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) &&
495
+ (isArray || isObject(data))) {
496
+ copy = isArray ? [] : {};
497
+ if (!isArray && !isPlainObject(data)) {
498
+ copy = data;
499
+ }
500
+ else {
501
+ for (const key in data) {
502
+ if (data.hasOwnProperty(key)) {
503
+ copy[key] = cloneObject(data[key]);
504
+ }
505
+ }
506
+ }
507
+ }
508
+ else {
509
+ return data;
510
+ }
511
+ return copy;
512
+ }
513
+
514
+ var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
515
+
516
+ var isUndefined = (val) => val === undefined;
517
+
518
+ var get = (object, path, defaultValue) => {
519
+ if (!path || !isObject(object)) {
520
+ return defaultValue;
521
+ }
522
+ const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);
523
+ return isUndefined(result) || result === object
524
+ ? isUndefined(object[path])
525
+ ? defaultValue
526
+ : object[path]
527
+ : result;
528
+ };
529
+
530
+ var isBoolean = (value) => typeof value === 'boolean';
531
+
532
+ var isKey = (value) => /^\w*$/.test(value);
533
+
534
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
535
+
536
+ var set = (object, path, value) => {
537
+ let index = -1;
538
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
539
+ const length = tempPath.length;
540
+ const lastIndex = length - 1;
541
+ while (++index < length) {
542
+ const key = tempPath[index];
543
+ let newValue = value;
544
+ if (index !== lastIndex) {
545
+ const objValue = object[key];
546
+ newValue =
547
+ isObject(objValue) || Array.isArray(objValue)
548
+ ? objValue
549
+ : !isNaN(+tempPath[index + 1])
550
+ ? []
551
+ : {};
552
+ }
553
+ if (key === '__proto__') {
554
+ return;
555
+ }
556
+ object[key] = newValue;
557
+ object = object[key];
558
+ }
559
+ return object;
560
+ };
561
+
562
+ const EVENTS = {
563
+ BLUR: 'blur',
564
+ FOCUS_OUT: 'focusout',
565
+ CHANGE: 'change',
566
+ };
567
+ const VALIDATION_MODE = {
568
+ onBlur: 'onBlur',
569
+ onChange: 'onChange',
570
+ onSubmit: 'onSubmit',
571
+ onTouched: 'onTouched',
572
+ all: 'all',
573
+ };
574
+ const INPUT_VALIDATION_RULES = {
575
+ max: 'max',
576
+ min: 'min',
577
+ maxLength: 'maxLength',
578
+ minLength: 'minLength',
579
+ pattern: 'pattern',
580
+ required: 'required',
581
+ validate: 'validate',
582
+ };
583
+
584
+ const HookFormContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
585
+ /**
586
+ * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
587
+ *
588
+ * @remarks
589
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
590
+ *
591
+ * @returns return all useForm methods
592
+ *
593
+ * @example
594
+ * ```tsx
595
+ * function App() {
596
+ * const methods = useForm();
597
+ * const onSubmit = data => console.log(data);
598
+ *
599
+ * return (
600
+ * <FormProvider {...methods} >
601
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
602
+ * <NestedInput />
603
+ * <input type="submit" />
604
+ * </form>
605
+ * </FormProvider>
606
+ * );
607
+ * }
608
+ *
609
+ * function NestedInput() {
610
+ * const { register } = useFormContext(); // retrieve all hook methods
611
+ * return <input {...register("test")} />;
612
+ * }
613
+ * ```
614
+ */
615
+ const useFormContext = () => react__WEBPACK_IMPORTED_MODULE_0__.useContext(HookFormContext);
616
+ /**
617
+ * A provider component that propagates the `useForm` methods to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useFormContext}.
618
+ *
619
+ * @remarks
620
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
621
+ *
622
+ * @param props - all useForm methods
623
+ *
624
+ * @example
625
+ * ```tsx
626
+ * function App() {
627
+ * const methods = useForm();
628
+ * const onSubmit = data => console.log(data);
629
+ *
630
+ * return (
631
+ * <FormProvider {...methods} >
632
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
633
+ * <NestedInput />
634
+ * <input type="submit" />
635
+ * </form>
636
+ * </FormProvider>
637
+ * );
638
+ * }
639
+ *
640
+ * function NestedInput() {
641
+ * const { register } = useFormContext(); // retrieve all hook methods
642
+ * return <input {...register("test")} />;
643
+ * }
644
+ * ```
645
+ */
646
+ const FormProvider = (props) => {
647
+ const { children, ...data } = props;
648
+ return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(HookFormContext.Provider, { value: data }, children));
649
+ };
650
+
651
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
652
+ const result = {
653
+ defaultValues: control._defaultValues,
654
+ };
655
+ for (const key in formState) {
656
+ Object.defineProperty(result, key, {
657
+ get: () => {
658
+ const _key = key;
659
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
660
+ control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
661
+ }
662
+ localProxyFormState && (localProxyFormState[_key] = true);
663
+ return formState[_key];
664
+ },
665
+ });
666
+ }
667
+ return result;
668
+ };
669
+
670
+ var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
671
+
672
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
673
+ updateFormState(formStateData);
674
+ const { name, ...formState } = formStateData;
675
+ return (isEmptyObject(formState) ||
676
+ Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
677
+ Object.keys(formState).find((key) => _proxyFormState[key] ===
678
+ (!isRoot || VALIDATION_MODE.all)));
679
+ };
680
+
681
+ var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
682
+
683
+ var shouldSubscribeByName = (name, signalName, exact) => !name ||
684
+ !signalName ||
685
+ name === signalName ||
686
+ convertToArrayPayload(name).some((currentName) => currentName &&
687
+ (exact
688
+ ? currentName === signalName
689
+ : currentName.startsWith(signalName) ||
690
+ signalName.startsWith(currentName)));
691
+
692
+ function useSubscribe(props) {
693
+ const _props = react__WEBPACK_IMPORTED_MODULE_0__.useRef(props);
694
+ _props.current = props;
695
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
696
+ const subscription = !props.disabled &&
697
+ _props.current.subject &&
698
+ _props.current.subject.subscribe({
699
+ next: _props.current.next,
700
+ });
701
+ return () => {
702
+ subscription && subscription.unsubscribe();
703
+ };
704
+ }, [props.disabled]);
705
+ }
706
+
707
+ /**
708
+ * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
709
+ *
710
+ * @remarks
711
+ * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
712
+ *
713
+ * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
714
+ *
715
+ * @example
716
+ * ```tsx
717
+ * function App() {
718
+ * const { register, handleSubmit, control } = useForm({
719
+ * defaultValues: {
720
+ * firstName: "firstName"
721
+ * }});
722
+ * const { dirtyFields } = useFormState({
723
+ * control
724
+ * });
725
+ * const onSubmit = (data) => console.log(data);
726
+ *
727
+ * return (
728
+ * <form onSubmit={handleSubmit(onSubmit)}>
729
+ * <input {...register("firstName")} placeholder="First Name" />
730
+ * {dirtyFields.firstName && <p>Field is dirty.</p>}
731
+ * <input type="submit" />
732
+ * </form>
733
+ * );
734
+ * }
735
+ * ```
736
+ */
737
+ function useFormState(props) {
738
+ const methods = useFormContext();
739
+ const { control = methods.control, disabled, name, exact } = props || {};
740
+ const [formState, updateFormState] = react__WEBPACK_IMPORTED_MODULE_0__.useState(control._formState);
741
+ const _mounted = react__WEBPACK_IMPORTED_MODULE_0__.useRef(true);
742
+ const _localProxyFormState = react__WEBPACK_IMPORTED_MODULE_0__.useRef({
743
+ isDirty: false,
744
+ isLoading: false,
745
+ dirtyFields: false,
746
+ touchedFields: false,
747
+ validatingFields: false,
748
+ isValidating: false,
749
+ isValid: false,
750
+ errors: false,
751
+ });
752
+ const _name = react__WEBPACK_IMPORTED_MODULE_0__.useRef(name);
753
+ _name.current = name;
754
+ useSubscribe({
755
+ disabled,
756
+ next: (value) => _mounted.current &&
757
+ shouldSubscribeByName(_name.current, value.name, exact) &&
758
+ shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
759
+ updateFormState({
760
+ ...control._formState,
761
+ ...value,
762
+ }),
763
+ subject: control._subjects.state,
764
+ });
765
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
766
+ _mounted.current = true;
767
+ _localProxyFormState.current.isValid && control._updateValid(true);
768
+ return () => {
769
+ _mounted.current = false;
770
+ };
771
+ }, [control]);
772
+ return getProxyFormState(formState, control, _localProxyFormState.current, false);
773
+ }
774
+
775
+ var isString = (value) => typeof value === 'string';
776
+
777
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
778
+ if (isString(names)) {
779
+ isGlobal && _names.watch.add(names);
780
+ return get(formValues, names, defaultValue);
781
+ }
782
+ if (Array.isArray(names)) {
783
+ return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
784
+ }
785
+ isGlobal && (_names.watchAll = true);
786
+ return formValues;
787
+ };
788
+
789
+ /**
790
+ * Custom hook to subscribe to field change and isolate re-rendering at the component level.
791
+ *
792
+ * @remarks
793
+ *
794
+ * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
795
+ *
796
+ * @example
797
+ * ```tsx
798
+ * const { control } = useForm();
799
+ * const values = useWatch({
800
+ * name: "fieldName"
801
+ * control,
802
+ * })
803
+ * ```
804
+ */
805
+ function useWatch(props) {
806
+ const methods = useFormContext();
807
+ const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};
808
+ const _name = react__WEBPACK_IMPORTED_MODULE_0__.useRef(name);
809
+ _name.current = name;
810
+ useSubscribe({
811
+ disabled,
812
+ subject: control._subjects.values,
813
+ next: (formState) => {
814
+ if (shouldSubscribeByName(_name.current, formState.name, exact)) {
815
+ updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
816
+ }
817
+ },
818
+ });
819
+ const [value, updateValue] = react__WEBPACK_IMPORTED_MODULE_0__.useState(control._getWatch(name, defaultValue));
820
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => control._removeUnmounted());
821
+ return value;
822
+ }
823
+
824
+ /**
825
+ * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
826
+ *
827
+ * @remarks
828
+ * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
829
+ *
830
+ * @param props - the path name to the form field value, and validation rules.
831
+ *
832
+ * @returns field properties, field and form state. {@link UseControllerReturn}
833
+ *
834
+ * @example
835
+ * ```tsx
836
+ * function Input(props) {
837
+ * const { field, fieldState, formState } = useController(props);
838
+ * return (
839
+ * <div>
840
+ * <input {...field} placeholder={props.name} />
841
+ * <p>{fieldState.isTouched && "Touched"}</p>
842
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
843
+ * </div>
844
+ * );
845
+ * }
846
+ * ```
847
+ */
848
+ function useController(props) {
849
+ const methods = useFormContext();
850
+ const { name, disabled, control = methods.control, shouldUnregister } = props;
851
+ const isArrayField = isNameInFieldArray(control._names.array, name);
852
+ const value = useWatch({
853
+ control,
854
+ name,
855
+ defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
856
+ exact: true,
857
+ });
858
+ const formState = useFormState({
859
+ control,
860
+ name,
861
+ });
862
+ const _registerProps = react__WEBPACK_IMPORTED_MODULE_0__.useRef(control.register(name, {
863
+ ...props.rules,
864
+ value,
865
+ ...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}),
866
+ }));
867
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
868
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
869
+ const updateMounted = (name, value) => {
870
+ const field = get(control._fields, name);
871
+ if (field && field._f) {
872
+ field._f.mount = value;
873
+ }
874
+ };
875
+ updateMounted(name, true);
876
+ if (_shouldUnregisterField) {
877
+ const value = cloneObject(get(control._options.defaultValues, name));
878
+ set(control._defaultValues, name, value);
879
+ if (isUndefined(get(control._formValues, name))) {
880
+ set(control._formValues, name, value);
881
+ }
882
+ }
883
+ return () => {
884
+ (isArrayField
885
+ ? _shouldUnregisterField && !control._state.action
886
+ : _shouldUnregisterField)
887
+ ? control.unregister(name)
888
+ : updateMounted(name, false);
889
+ };
890
+ }, [name, control, isArrayField, shouldUnregister]);
891
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
892
+ if (get(control._fields, name)) {
893
+ control._updateDisabledField({
894
+ disabled,
895
+ fields: control._fields,
896
+ name,
897
+ value: get(control._fields, name)._f.value,
898
+ });
899
+ }
900
+ }, [disabled, name, control]);
901
+ return {
902
+ field: {
903
+ name,
904
+ value,
905
+ ...(isBoolean(disabled) || formState.disabled
906
+ ? { disabled: formState.disabled || disabled }
907
+ : {}),
908
+ onChange: react__WEBPACK_IMPORTED_MODULE_0__.useCallback((event) => _registerProps.current.onChange({
909
+ target: {
910
+ value: getEventValue(event),
911
+ name: name,
912
+ },
913
+ type: EVENTS.CHANGE,
914
+ }), [name]),
915
+ onBlur: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(() => _registerProps.current.onBlur({
916
+ target: {
917
+ value: get(control._formValues, name),
918
+ name: name,
919
+ },
920
+ type: EVENTS.BLUR,
921
+ }), [name, control]),
922
+ ref: (elm) => {
923
+ const field = get(control._fields, name);
924
+ if (field && elm) {
925
+ field._f.ref = {
926
+ focus: () => elm.focus(),
927
+ select: () => elm.select(),
928
+ setCustomValidity: (message) => elm.setCustomValidity(message),
929
+ reportValidity: () => elm.reportValidity(),
930
+ };
931
+ }
932
+ },
933
+ },
934
+ formState,
935
+ fieldState: Object.defineProperties({}, {
936
+ invalid: {
937
+ enumerable: true,
938
+ get: () => !!get(formState.errors, name),
939
+ },
940
+ isDirty: {
941
+ enumerable: true,
942
+ get: () => !!get(formState.dirtyFields, name),
943
+ },
944
+ isTouched: {
945
+ enumerable: true,
946
+ get: () => !!get(formState.touchedFields, name),
947
+ },
948
+ isValidating: {
949
+ enumerable: true,
950
+ get: () => !!get(formState.validatingFields, name),
951
+ },
952
+ error: {
953
+ enumerable: true,
954
+ get: () => get(formState.errors, name),
955
+ },
956
+ }),
957
+ };
958
+ }
959
+
960
+ /**
961
+ * Component based on `useController` hook to work with controlled component.
962
+ *
963
+ * @remarks
964
+ * [API](https://react-hook-form.com/docs/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
965
+ *
966
+ * @param props - the path name to the form field value, and validation rules.
967
+ *
968
+ * @returns provide field handler functions, field and form state.
969
+ *
970
+ * @example
971
+ * ```tsx
972
+ * function App() {
973
+ * const { control } = useForm<FormValues>({
974
+ * defaultValues: {
975
+ * test: ""
976
+ * }
977
+ * });
978
+ *
979
+ * return (
980
+ * <form>
981
+ * <Controller
982
+ * control={control}
983
+ * name="test"
984
+ * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
985
+ * <>
986
+ * <input
987
+ * onChange={onChange} // send value to hook form
988
+ * onBlur={onBlur} // notify when input is touched
989
+ * value={value} // return updated value
990
+ * ref={ref} // set ref for focus management
991
+ * />
992
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
993
+ * <p>{fieldState.isTouched ? "touched" : ""}</p>
994
+ * </>
995
+ * )}
996
+ * />
997
+ * </form>
998
+ * );
999
+ * }
1000
+ * ```
1001
+ */
1002
+ const Controller = (props) => props.render(useController(props));
1003
+
1004
+ const POST_REQUEST = 'post';
1005
+ /**
1006
+ * Form component to manage submission.
1007
+ *
1008
+ * @param props - to setup submission detail. {@link FormProps}
1009
+ *
1010
+ * @returns form component or headless render prop.
1011
+ *
1012
+ * @example
1013
+ * ```tsx
1014
+ * function App() {
1015
+ * const { control, formState: { errors } } = useForm();
1016
+ *
1017
+ * return (
1018
+ * <Form action="/api" control={control}>
1019
+ * <input {...register("name")} />
1020
+ * <p>{errors?.root?.server && 'Server error'}</p>
1021
+ * <button>Submit</button>
1022
+ * </Form>
1023
+ * );
1024
+ * }
1025
+ * ```
1026
+ */
1027
+ function Form(props) {
1028
+ const methods = useFormContext();
1029
+ const [mounted, setMounted] = react__WEBPACK_IMPORTED_MODULE_0__.useState(false);
1030
+ const { control = methods.control, onSubmit, children, action, method = POST_REQUEST, headers, encType, onError, render, onSuccess, validateStatus, ...rest } = props;
1031
+ const submit = async (event) => {
1032
+ let hasError = false;
1033
+ let type = '';
1034
+ await control.handleSubmit(async (data) => {
1035
+ const formData = new FormData();
1036
+ let formDataJson = '';
1037
+ try {
1038
+ formDataJson = JSON.stringify(data);
1039
+ }
1040
+ catch (_a) { }
1041
+ for (const name of control._names.mount) {
1042
+ formData.append(name, get(data, name));
1043
+ }
1044
+ if (onSubmit) {
1045
+ await onSubmit({
1046
+ data,
1047
+ event,
1048
+ method,
1049
+ formData,
1050
+ formDataJson,
1051
+ });
1052
+ }
1053
+ if (action) {
1054
+ try {
1055
+ const shouldStringifySubmissionData = [
1056
+ headers && headers['Content-Type'],
1057
+ encType,
1058
+ ].some((value) => value && value.includes('json'));
1059
+ const response = await fetch(action, {
1060
+ method,
1061
+ headers: {
1062
+ ...headers,
1063
+ ...(encType ? { 'Content-Type': encType } : {}),
1064
+ },
1065
+ body: shouldStringifySubmissionData ? formDataJson : formData,
1066
+ });
1067
+ if (response &&
1068
+ (validateStatus
1069
+ ? !validateStatus(response.status)
1070
+ : response.status < 200 || response.status >= 300)) {
1071
+ hasError = true;
1072
+ onError && onError({ response });
1073
+ type = String(response.status);
1074
+ }
1075
+ else {
1076
+ onSuccess && onSuccess({ response });
1077
+ }
1078
+ }
1079
+ catch (error) {
1080
+ hasError = true;
1081
+ onError && onError({ error });
1082
+ }
1083
+ }
1084
+ })(event);
1085
+ if (hasError && props.control) {
1086
+ props.control._subjects.state.next({
1087
+ isSubmitSuccessful: false,
1088
+ });
1089
+ props.control.setError('root.server', {
1090
+ type,
1091
+ });
1092
+ }
1093
+ };
1094
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
1095
+ setMounted(true);
1096
+ }, []);
1097
+ return render ? (react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, render({
1098
+ submit,
1099
+ }))) : (react__WEBPACK_IMPORTED_MODULE_0__.createElement("form", { noValidate: mounted, action: action, method: method, encType: encType, onSubmit: submit, ...rest }, children));
1100
+ }
1101
+
1102
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
1103
+ ? {
1104
+ ...errors[name],
1105
+ types: {
1106
+ ...(errors[name] && errors[name].types ? errors[name].types : {}),
1107
+ [type]: message || true,
1108
+ },
1109
+ }
1110
+ : {};
1111
+
1112
+ var generateId = () => {
1113
+ const d = typeof performance === 'undefined' ? Date.now() : performance.now() * 1000;
1114
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
1115
+ const r = (Math.random() * 16 + d) % 16 | 0;
1116
+ return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);
1117
+ });
1118
+ };
1119
+
1120
+ var getFocusFieldName = (name, index, options = {}) => options.shouldFocus || isUndefined(options.shouldFocus)
1121
+ ? options.focusName ||
1122
+ `${name}.${isUndefined(options.focusIndex) ? index : options.focusIndex}.`
1123
+ : '';
1124
+
1125
+ var getValidationModes = (mode) => ({
1126
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
1127
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
1128
+ isOnChange: mode === VALIDATION_MODE.onChange,
1129
+ isOnAll: mode === VALIDATION_MODE.all,
1130
+ isOnTouch: mode === VALIDATION_MODE.onTouched,
1131
+ });
1132
+
1133
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
1134
+ (_names.watchAll ||
1135
+ _names.watch.has(name) ||
1136
+ [..._names.watch].some((watchName) => name.startsWith(watchName) &&
1137
+ /^\.\w+/.test(name.slice(watchName.length))));
1138
+
1139
+ const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
1140
+ for (const key of fieldsNames || Object.keys(fields)) {
1141
+ const field = get(fields, key);
1142
+ if (field) {
1143
+ const { _f, ...currentField } = field;
1144
+ if (_f) {
1145
+ if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
1146
+ break;
1147
+ }
1148
+ else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
1149
+ break;
1150
+ }
1151
+ else {
1152
+ iterateFieldsByAction(currentField, action);
1153
+ }
1154
+ }
1155
+ else if (isObject(currentField)) {
1156
+ iterateFieldsByAction(currentField, action);
1157
+ }
1158
+ }
1159
+ }
1160
+ };
1161
+
1162
+ var updateFieldArrayRootError = (errors, error, name) => {
1163
+ const fieldArrayErrors = convertToArrayPayload(get(errors, name));
1164
+ set(fieldArrayErrors, 'root', error[name]);
1165
+ set(errors, name, fieldArrayErrors);
1166
+ return errors;
1167
+ };
1168
+
1169
+ var isFileInput = (element) => element.type === 'file';
1170
+
1171
+ var isFunction = (value) => typeof value === 'function';
1172
+
1173
+ var isHTMLElement = (value) => {
1174
+ if (!isWeb) {
1175
+ return false;
1176
+ }
1177
+ const owner = value ? value.ownerDocument : 0;
1178
+ return (value instanceof
1179
+ (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
1180
+ };
1181
+
1182
+ var isMessage = (value) => isString(value);
1183
+
1184
+ var isRadioInput = (element) => element.type === 'radio';
1185
+
1186
+ var isRegex = (value) => value instanceof RegExp;
1187
+
1188
+ const defaultResult = {
1189
+ value: false,
1190
+ isValid: false,
1191
+ };
1192
+ const validResult = { value: true, isValid: true };
1193
+ var getCheckboxValue = (options) => {
1194
+ if (Array.isArray(options)) {
1195
+ if (options.length > 1) {
1196
+ const values = options
1197
+ .filter((option) => option && option.checked && !option.disabled)
1198
+ .map((option) => option.value);
1199
+ return { value: values, isValid: !!values.length };
1200
+ }
1201
+ return options[0].checked && !options[0].disabled
1202
+ ? // @ts-expect-error expected to work in the browser
1203
+ options[0].attributes && !isUndefined(options[0].attributes.value)
1204
+ ? isUndefined(options[0].value) || options[0].value === ''
1205
+ ? validResult
1206
+ : { value: options[0].value, isValid: true }
1207
+ : validResult
1208
+ : defaultResult;
1209
+ }
1210
+ return defaultResult;
1211
+ };
1212
+
1213
+ const defaultReturn = {
1214
+ isValid: false,
1215
+ value: null,
1216
+ };
1217
+ var getRadioValue = (options) => Array.isArray(options)
1218
+ ? options.reduce((previous, option) => option && option.checked && !option.disabled
1219
+ ? {
1220
+ isValid: true,
1221
+ value: option.value,
1222
+ }
1223
+ : previous, defaultReturn)
1224
+ : defaultReturn;
1225
+
1226
+ function getValidateError(result, ref, type = 'validate') {
1227
+ if (isMessage(result) ||
1228
+ (Array.isArray(result) && result.every(isMessage)) ||
1229
+ (isBoolean(result) && !result)) {
1230
+ return {
1231
+ type,
1232
+ message: isMessage(result) ? result : '',
1233
+ ref,
1234
+ };
1235
+ }
1236
+ }
1237
+
1238
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
1239
+ ? validationData
1240
+ : {
1241
+ value: validationData,
1242
+ message: '',
1243
+ };
1244
+
1245
+ var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
1246
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled, } = field._f;
1247
+ const inputValue = get(formValues, name);
1248
+ if (!mount || disabled) {
1249
+ return {};
1250
+ }
1251
+ const inputRef = refs ? refs[0] : ref;
1252
+ const setCustomValidity = (message) => {
1253
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
1254
+ inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
1255
+ inputRef.reportValidity();
1256
+ }
1257
+ };
1258
+ const error = {};
1259
+ const isRadio = isRadioInput(ref);
1260
+ const isCheckBox = isCheckBoxInput(ref);
1261
+ const isRadioOrCheckbox = isRadio || isCheckBox;
1262
+ const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
1263
+ isUndefined(ref.value) &&
1264
+ isUndefined(inputValue)) ||
1265
+ (isHTMLElement(ref) && ref.value === '') ||
1266
+ inputValue === '' ||
1267
+ (Array.isArray(inputValue) && !inputValue.length);
1268
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
1269
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
1270
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
1271
+ error[name] = {
1272
+ type: exceedMax ? maxType : minType,
1273
+ message,
1274
+ ref,
1275
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message),
1276
+ };
1277
+ };
1278
+ if (isFieldArray
1279
+ ? !Array.isArray(inputValue) || !inputValue.length
1280
+ : required &&
1281
+ ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
1282
+ (isBoolean(inputValue) && !inputValue) ||
1283
+ (isCheckBox && !getCheckboxValue(refs).isValid) ||
1284
+ (isRadio && !getRadioValue(refs).isValid))) {
1285
+ const { value, message } = isMessage(required)
1286
+ ? { value: !!required, message: required }
1287
+ : getValueAndMessage(required);
1288
+ if (value) {
1289
+ error[name] = {
1290
+ type: INPUT_VALIDATION_RULES.required,
1291
+ message,
1292
+ ref: inputRef,
1293
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
1294
+ };
1295
+ if (!validateAllFieldCriteria) {
1296
+ setCustomValidity(message);
1297
+ return error;
1298
+ }
1299
+ }
1300
+ }
1301
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
1302
+ let exceedMax;
1303
+ let exceedMin;
1304
+ const maxOutput = getValueAndMessage(max);
1305
+ const minOutput = getValueAndMessage(min);
1306
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
1307
+ const valueNumber = ref.valueAsNumber ||
1308
+ (inputValue ? +inputValue : inputValue);
1309
+ if (!isNullOrUndefined(maxOutput.value)) {
1310
+ exceedMax = valueNumber > maxOutput.value;
1311
+ }
1312
+ if (!isNullOrUndefined(minOutput.value)) {
1313
+ exceedMin = valueNumber < minOutput.value;
1314
+ }
1315
+ }
1316
+ else {
1317
+ const valueDate = ref.valueAsDate || new Date(inputValue);
1318
+ const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
1319
+ const isTime = ref.type == 'time';
1320
+ const isWeek = ref.type == 'week';
1321
+ if (isString(maxOutput.value) && inputValue) {
1322
+ exceedMax = isTime
1323
+ ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
1324
+ : isWeek
1325
+ ? inputValue > maxOutput.value
1326
+ : valueDate > new Date(maxOutput.value);
1327
+ }
1328
+ if (isString(minOutput.value) && inputValue) {
1329
+ exceedMin = isTime
1330
+ ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
1331
+ : isWeek
1332
+ ? inputValue < minOutput.value
1333
+ : valueDate < new Date(minOutput.value);
1334
+ }
1335
+ }
1336
+ if (exceedMax || exceedMin) {
1337
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
1338
+ if (!validateAllFieldCriteria) {
1339
+ setCustomValidity(error[name].message);
1340
+ return error;
1341
+ }
1342
+ }
1343
+ }
1344
+ if ((maxLength || minLength) &&
1345
+ !isEmpty &&
1346
+ (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
1347
+ const maxLengthOutput = getValueAndMessage(maxLength);
1348
+ const minLengthOutput = getValueAndMessage(minLength);
1349
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
1350
+ inputValue.length > +maxLengthOutput.value;
1351
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
1352
+ inputValue.length < +minLengthOutput.value;
1353
+ if (exceedMax || exceedMin) {
1354
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
1355
+ if (!validateAllFieldCriteria) {
1356
+ setCustomValidity(error[name].message);
1357
+ return error;
1358
+ }
1359
+ }
1360
+ }
1361
+ if (pattern && !isEmpty && isString(inputValue)) {
1362
+ const { value: patternValue, message } = getValueAndMessage(pattern);
1363
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
1364
+ error[name] = {
1365
+ type: INPUT_VALIDATION_RULES.pattern,
1366
+ message,
1367
+ ref,
1368
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
1369
+ };
1370
+ if (!validateAllFieldCriteria) {
1371
+ setCustomValidity(message);
1372
+ return error;
1373
+ }
1374
+ }
1375
+ }
1376
+ if (validate) {
1377
+ if (isFunction(validate)) {
1378
+ const result = await validate(inputValue, formValues);
1379
+ const validateError = getValidateError(result, inputRef);
1380
+ if (validateError) {
1381
+ error[name] = {
1382
+ ...validateError,
1383
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
1384
+ };
1385
+ if (!validateAllFieldCriteria) {
1386
+ setCustomValidity(validateError.message);
1387
+ return error;
1388
+ }
1389
+ }
1390
+ }
1391
+ else if (isObject(validate)) {
1392
+ let validationResult = {};
1393
+ for (const key in validate) {
1394
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
1395
+ break;
1396
+ }
1397
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
1398
+ if (validateError) {
1399
+ validationResult = {
1400
+ ...validateError,
1401
+ ...appendErrorsCurry(key, validateError.message),
1402
+ };
1403
+ setCustomValidity(validateError.message);
1404
+ if (validateAllFieldCriteria) {
1405
+ error[name] = validationResult;
1406
+ }
1407
+ }
1408
+ }
1409
+ if (!isEmptyObject(validationResult)) {
1410
+ error[name] = {
1411
+ ref: inputRef,
1412
+ ...validationResult,
1413
+ };
1414
+ if (!validateAllFieldCriteria) {
1415
+ return error;
1416
+ }
1417
+ }
1418
+ }
1419
+ }
1420
+ setCustomValidity(true);
1421
+ return error;
1422
+ };
1423
+
1424
+ var appendAt = (data, value) => [
1425
+ ...data,
1426
+ ...convertToArrayPayload(value),
1427
+ ];
1428
+
1429
+ var fillEmptyArray = (value) => Array.isArray(value) ? value.map(() => undefined) : undefined;
1430
+
1431
+ function insert(data, index, value) {
1432
+ return [
1433
+ ...data.slice(0, index),
1434
+ ...convertToArrayPayload(value),
1435
+ ...data.slice(index),
1436
+ ];
1437
+ }
1438
+
1439
+ var moveArrayAt = (data, from, to) => {
1440
+ if (!Array.isArray(data)) {
1441
+ return [];
1442
+ }
1443
+ if (isUndefined(data[to])) {
1444
+ data[to] = undefined;
1445
+ }
1446
+ data.splice(to, 0, data.splice(from, 1)[0]);
1447
+ return data;
1448
+ };
1449
+
1450
+ var prependAt = (data, value) => [
1451
+ ...convertToArrayPayload(value),
1452
+ ...convertToArrayPayload(data),
1453
+ ];
1454
+
1455
+ function removeAtIndexes(data, indexes) {
1456
+ let i = 0;
1457
+ const temp = [...data];
1458
+ for (const index of indexes) {
1459
+ temp.splice(index - i, 1);
1460
+ i++;
1461
+ }
1462
+ return compact(temp).length ? temp : [];
1463
+ }
1464
+ var removeArrayAt = (data, index) => isUndefined(index)
1465
+ ? []
1466
+ : removeAtIndexes(data, convertToArrayPayload(index).sort((a, b) => a - b));
1467
+
1468
+ var swapArrayAt = (data, indexA, indexB) => {
1469
+ [data[indexA], data[indexB]] = [data[indexB], data[indexA]];
1470
+ };
1471
+
1472
+ function baseGet(object, updatePath) {
1473
+ const length = updatePath.slice(0, -1).length;
1474
+ let index = 0;
1475
+ while (index < length) {
1476
+ object = isUndefined(object) ? index++ : object[updatePath[index++]];
1477
+ }
1478
+ return object;
1479
+ }
1480
+ function isEmptyArray(obj) {
1481
+ for (const key in obj) {
1482
+ if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
1483
+ return false;
1484
+ }
1485
+ }
1486
+ return true;
1487
+ }
1488
+ function unset(object, path) {
1489
+ const paths = Array.isArray(path)
1490
+ ? path
1491
+ : isKey(path)
1492
+ ? [path]
1493
+ : stringToPath(path);
1494
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
1495
+ const index = paths.length - 1;
1496
+ const key = paths[index];
1497
+ if (childObject) {
1498
+ delete childObject[key];
1499
+ }
1500
+ if (index !== 0 &&
1501
+ ((isObject(childObject) && isEmptyObject(childObject)) ||
1502
+ (Array.isArray(childObject) && isEmptyArray(childObject)))) {
1503
+ unset(object, paths.slice(0, -1));
1504
+ }
1505
+ return object;
1506
+ }
1507
+
1508
+ var updateAt = (fieldValues, index, value) => {
1509
+ fieldValues[index] = value;
1510
+ return fieldValues;
1511
+ };
1512
+
1513
+ /**
1514
+ * A custom hook that exposes convenient methods to perform operations with a list of dynamic inputs that need to be appended, updated, removed etc. • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn) • [Video](https://youtu.be/4MrbfGSFY2A)
1515
+ *
1516
+ * @remarks
1517
+ * [API](https://react-hook-form.com/docs/usefieldarray) • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn)
1518
+ *
1519
+ * @param props - useFieldArray props
1520
+ *
1521
+ * @returns methods - functions to manipulate with the Field Arrays (dynamic inputs) {@link UseFieldArrayReturn}
1522
+ *
1523
+ * @example
1524
+ * ```tsx
1525
+ * function App() {
1526
+ * const { register, control, handleSubmit, reset, trigger, setError } = useForm({
1527
+ * defaultValues: {
1528
+ * test: []
1529
+ * }
1530
+ * });
1531
+ * const { fields, append } = useFieldArray({
1532
+ * control,
1533
+ * name: "test"
1534
+ * });
1535
+ *
1536
+ * return (
1537
+ * <form onSubmit={handleSubmit(data => console.log(data))}>
1538
+ * {fields.map((item, index) => (
1539
+ * <input key={item.id} {...register(`test.${index}.firstName`)} />
1540
+ * ))}
1541
+ * <button type="button" onClick={() => append({ firstName: "bill" })}>
1542
+ * append
1543
+ * </button>
1544
+ * <input type="submit" />
1545
+ * </form>
1546
+ * );
1547
+ * }
1548
+ * ```
1549
+ */
1550
+ function useFieldArray(props) {
1551
+ const methods = useFormContext();
1552
+ const { control = methods.control, name, keyName = 'id', shouldUnregister, } = props;
1553
+ const [fields, setFields] = react__WEBPACK_IMPORTED_MODULE_0__.useState(control._getFieldArray(name));
1554
+ const ids = react__WEBPACK_IMPORTED_MODULE_0__.useRef(control._getFieldArray(name).map(generateId));
1555
+ const _fieldIds = react__WEBPACK_IMPORTED_MODULE_0__.useRef(fields);
1556
+ const _name = react__WEBPACK_IMPORTED_MODULE_0__.useRef(name);
1557
+ const _actioned = react__WEBPACK_IMPORTED_MODULE_0__.useRef(false);
1558
+ _name.current = name;
1559
+ _fieldIds.current = fields;
1560
+ control._names.array.add(name);
1561
+ props.rules &&
1562
+ control.register(name, props.rules);
1563
+ useSubscribe({
1564
+ next: ({ values, name: fieldArrayName, }) => {
1565
+ if (fieldArrayName === _name.current || !fieldArrayName) {
1566
+ const fieldValues = get(values, _name.current);
1567
+ if (Array.isArray(fieldValues)) {
1568
+ setFields(fieldValues);
1569
+ ids.current = fieldValues.map(generateId);
1570
+ }
1571
+ }
1572
+ },
1573
+ subject: control._subjects.array,
1574
+ });
1575
+ const updateValues = react__WEBPACK_IMPORTED_MODULE_0__.useCallback((updatedFieldArrayValues) => {
1576
+ _actioned.current = true;
1577
+ control._updateFieldArray(name, updatedFieldArrayValues);
1578
+ }, [control, name]);
1579
+ const append = (value, options) => {
1580
+ const appendValue = convertToArrayPayload(cloneObject(value));
1581
+ const updatedFieldArrayValues = appendAt(control._getFieldArray(name), appendValue);
1582
+ control._names.focus = getFocusFieldName(name, updatedFieldArrayValues.length - 1, options);
1583
+ ids.current = appendAt(ids.current, appendValue.map(generateId));
1584
+ updateValues(updatedFieldArrayValues);
1585
+ setFields(updatedFieldArrayValues);
1586
+ control._updateFieldArray(name, updatedFieldArrayValues, appendAt, {
1587
+ argA: fillEmptyArray(value),
1588
+ });
1589
+ };
1590
+ const prepend = (value, options) => {
1591
+ const prependValue = convertToArrayPayload(cloneObject(value));
1592
+ const updatedFieldArrayValues = prependAt(control._getFieldArray(name), prependValue);
1593
+ control._names.focus = getFocusFieldName(name, 0, options);
1594
+ ids.current = prependAt(ids.current, prependValue.map(generateId));
1595
+ updateValues(updatedFieldArrayValues);
1596
+ setFields(updatedFieldArrayValues);
1597
+ control._updateFieldArray(name, updatedFieldArrayValues, prependAt, {
1598
+ argA: fillEmptyArray(value),
1599
+ });
1600
+ };
1601
+ const remove = (index) => {
1602
+ const updatedFieldArrayValues = removeArrayAt(control._getFieldArray(name), index);
1603
+ ids.current = removeArrayAt(ids.current, index);
1604
+ updateValues(updatedFieldArrayValues);
1605
+ setFields(updatedFieldArrayValues);
1606
+ control._updateFieldArray(name, updatedFieldArrayValues, removeArrayAt, {
1607
+ argA: index,
1608
+ });
1609
+ };
1610
+ const insert$1 = (index, value, options) => {
1611
+ const insertValue = convertToArrayPayload(cloneObject(value));
1612
+ const updatedFieldArrayValues = insert(control._getFieldArray(name), index, insertValue);
1613
+ control._names.focus = getFocusFieldName(name, index, options);
1614
+ ids.current = insert(ids.current, index, insertValue.map(generateId));
1615
+ updateValues(updatedFieldArrayValues);
1616
+ setFields(updatedFieldArrayValues);
1617
+ control._updateFieldArray(name, updatedFieldArrayValues, insert, {
1618
+ argA: index,
1619
+ argB: fillEmptyArray(value),
1620
+ });
1621
+ };
1622
+ const swap = (indexA, indexB) => {
1623
+ const updatedFieldArrayValues = control._getFieldArray(name);
1624
+ swapArrayAt(updatedFieldArrayValues, indexA, indexB);
1625
+ swapArrayAt(ids.current, indexA, indexB);
1626
+ updateValues(updatedFieldArrayValues);
1627
+ setFields(updatedFieldArrayValues);
1628
+ control._updateFieldArray(name, updatedFieldArrayValues, swapArrayAt, {
1629
+ argA: indexA,
1630
+ argB: indexB,
1631
+ }, false);
1632
+ };
1633
+ const move = (from, to) => {
1634
+ const updatedFieldArrayValues = control._getFieldArray(name);
1635
+ moveArrayAt(updatedFieldArrayValues, from, to);
1636
+ moveArrayAt(ids.current, from, to);
1637
+ updateValues(updatedFieldArrayValues);
1638
+ setFields(updatedFieldArrayValues);
1639
+ control._updateFieldArray(name, updatedFieldArrayValues, moveArrayAt, {
1640
+ argA: from,
1641
+ argB: to,
1642
+ }, false);
1643
+ };
1644
+ const update = (index, value) => {
1645
+ const updateValue = cloneObject(value);
1646
+ const updatedFieldArrayValues = updateAt(control._getFieldArray(name), index, updateValue);
1647
+ ids.current = [...updatedFieldArrayValues].map((item, i) => !item || i === index ? generateId() : ids.current[i]);
1648
+ updateValues(updatedFieldArrayValues);
1649
+ setFields([...updatedFieldArrayValues]);
1650
+ control._updateFieldArray(name, updatedFieldArrayValues, updateAt, {
1651
+ argA: index,
1652
+ argB: updateValue,
1653
+ }, true, false);
1654
+ };
1655
+ const replace = (value) => {
1656
+ const updatedFieldArrayValues = convertToArrayPayload(cloneObject(value));
1657
+ ids.current = updatedFieldArrayValues.map(generateId);
1658
+ updateValues([...updatedFieldArrayValues]);
1659
+ setFields([...updatedFieldArrayValues]);
1660
+ control._updateFieldArray(name, [...updatedFieldArrayValues], (data) => data, {}, true, false);
1661
+ };
1662
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
1663
+ control._state.action = false;
1664
+ isWatched(name, control._names) &&
1665
+ control._subjects.state.next({
1666
+ ...control._formState,
1667
+ });
1668
+ if (_actioned.current &&
1669
+ (!getValidationModes(control._options.mode).isOnSubmit ||
1670
+ control._formState.isSubmitted)) {
1671
+ if (control._options.resolver) {
1672
+ control._executeSchema([name]).then((result) => {
1673
+ const error = get(result.errors, name);
1674
+ const existingError = get(control._formState.errors, name);
1675
+ if (existingError
1676
+ ? (!error && existingError.type) ||
1677
+ (error &&
1678
+ (existingError.type !== error.type ||
1679
+ existingError.message !== error.message))
1680
+ : error && error.type) {
1681
+ error
1682
+ ? set(control._formState.errors, name, error)
1683
+ : unset(control._formState.errors, name);
1684
+ control._subjects.state.next({
1685
+ errors: control._formState.errors,
1686
+ });
1687
+ }
1688
+ });
1689
+ }
1690
+ else {
1691
+ const field = get(control._fields, name);
1692
+ if (field &&
1693
+ field._f &&
1694
+ !(getValidationModes(control._options.reValidateMode).isOnSubmit &&
1695
+ getValidationModes(control._options.mode).isOnSubmit)) {
1696
+ validateField(field, control._formValues, control._options.criteriaMode === VALIDATION_MODE.all, control._options.shouldUseNativeValidation, true).then((error) => !isEmptyObject(error) &&
1697
+ control._subjects.state.next({
1698
+ errors: updateFieldArrayRootError(control._formState.errors, error, name),
1699
+ }));
1700
+ }
1701
+ }
1702
+ }
1703
+ control._subjects.values.next({
1704
+ name,
1705
+ values: { ...control._formValues },
1706
+ });
1707
+ control._names.focus &&
1708
+ iterateFieldsByAction(control._fields, (ref, key) => {
1709
+ if (control._names.focus &&
1710
+ key.startsWith(control._names.focus) &&
1711
+ ref.focus) {
1712
+ ref.focus();
1713
+ return 1;
1714
+ }
1715
+ return;
1716
+ });
1717
+ control._names.focus = '';
1718
+ control._updateValid();
1719
+ _actioned.current = false;
1720
+ }, [fields, name, control]);
1721
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
1722
+ !get(control._formValues, name) && control._updateFieldArray(name);
1723
+ return () => {
1724
+ (control._options.shouldUnregister || shouldUnregister) &&
1725
+ control.unregister(name);
1726
+ };
1727
+ }, [name, control, keyName, shouldUnregister]);
1728
+ return {
1729
+ swap: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(swap, [updateValues, name, control]),
1730
+ move: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(move, [updateValues, name, control]),
1731
+ prepend: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(prepend, [updateValues, name, control]),
1732
+ append: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(append, [updateValues, name, control]),
1733
+ remove: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(remove, [updateValues, name, control]),
1734
+ insert: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(insert$1, [updateValues, name, control]),
1735
+ update: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(update, [updateValues, name, control]),
1736
+ replace: react__WEBPACK_IMPORTED_MODULE_0__.useCallback(replace, [updateValues, name, control]),
1737
+ fields: react__WEBPACK_IMPORTED_MODULE_0__.useMemo(() => fields.map((field, index) => ({
1738
+ ...field,
1739
+ [keyName]: ids.current[index] || generateId(),
1740
+ })), [fields, keyName]),
1741
+ };
1742
+ }
1743
+
1744
+ var createSubject = () => {
1745
+ let _observers = [];
1746
+ const next = (value) => {
1747
+ for (const observer of _observers) {
1748
+ observer.next && observer.next(value);
1749
+ }
1750
+ };
1751
+ const subscribe = (observer) => {
1752
+ _observers.push(observer);
1753
+ return {
1754
+ unsubscribe: () => {
1755
+ _observers = _observers.filter((o) => o !== observer);
1756
+ },
1757
+ };
1758
+ };
1759
+ const unsubscribe = () => {
1760
+ _observers = [];
1761
+ };
1762
+ return {
1763
+ get observers() {
1764
+ return _observers;
1765
+ },
1766
+ next,
1767
+ subscribe,
1768
+ unsubscribe,
1769
+ };
1770
+ };
1771
+
1772
+ var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
1773
+
1774
+ function deepEqual(object1, object2) {
1775
+ if (isPrimitive(object1) || isPrimitive(object2)) {
1776
+ return object1 === object2;
1777
+ }
1778
+ if (isDateObject(object1) && isDateObject(object2)) {
1779
+ return object1.getTime() === object2.getTime();
1780
+ }
1781
+ const keys1 = Object.keys(object1);
1782
+ const keys2 = Object.keys(object2);
1783
+ if (keys1.length !== keys2.length) {
1784
+ return false;
1785
+ }
1786
+ for (const key of keys1) {
1787
+ const val1 = object1[key];
1788
+ if (!keys2.includes(key)) {
1789
+ return false;
1790
+ }
1791
+ if (key !== 'ref') {
1792
+ const val2 = object2[key];
1793
+ if ((isDateObject(val1) && isDateObject(val2)) ||
1794
+ (isObject(val1) && isObject(val2)) ||
1795
+ (Array.isArray(val1) && Array.isArray(val2))
1796
+ ? !deepEqual(val1, val2)
1797
+ : val1 !== val2) {
1798
+ return false;
1799
+ }
1800
+ }
1801
+ }
1802
+ return true;
1803
+ }
1804
+
1805
+ var isMultipleSelect = (element) => element.type === `select-multiple`;
1806
+
1807
+ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
1808
+
1809
+ var live = (ref) => isHTMLElement(ref) && ref.isConnected;
1810
+
1811
+ var objectHasFunction = (data) => {
1812
+ for (const key in data) {
1813
+ if (isFunction(data[key])) {
1814
+ return true;
1815
+ }
1816
+ }
1817
+ return false;
1818
+ };
1819
+
1820
+ function markFieldsDirty(data, fields = {}) {
1821
+ const isParentNodeArray = Array.isArray(data);
1822
+ if (isObject(data) || isParentNodeArray) {
1823
+ for (const key in data) {
1824
+ if (Array.isArray(data[key]) ||
1825
+ (isObject(data[key]) && !objectHasFunction(data[key]))) {
1826
+ fields[key] = Array.isArray(data[key]) ? [] : {};
1827
+ markFieldsDirty(data[key], fields[key]);
1828
+ }
1829
+ else if (!isNullOrUndefined(data[key])) {
1830
+ fields[key] = true;
1831
+ }
1832
+ }
1833
+ }
1834
+ return fields;
1835
+ }
1836
+ function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
1837
+ const isParentNodeArray = Array.isArray(data);
1838
+ if (isObject(data) || isParentNodeArray) {
1839
+ for (const key in data) {
1840
+ if (Array.isArray(data[key]) ||
1841
+ (isObject(data[key]) && !objectHasFunction(data[key]))) {
1842
+ if (isUndefined(formValues) ||
1843
+ isPrimitive(dirtyFieldsFromValues[key])) {
1844
+ dirtyFieldsFromValues[key] = Array.isArray(data[key])
1845
+ ? markFieldsDirty(data[key], [])
1846
+ : { ...markFieldsDirty(data[key]) };
1847
+ }
1848
+ else {
1849
+ getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1850
+ }
1851
+ }
1852
+ else {
1853
+ dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
1854
+ }
1855
+ }
1856
+ }
1857
+ return dirtyFieldsFromValues;
1858
+ }
1859
+ var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
1860
+
1861
+ var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
1862
+ ? value
1863
+ : valueAsNumber
1864
+ ? value === ''
1865
+ ? NaN
1866
+ : value
1867
+ ? +value
1868
+ : value
1869
+ : valueAsDate && isString(value)
1870
+ ? new Date(value)
1871
+ : setValueAs
1872
+ ? setValueAs(value)
1873
+ : value;
1874
+
1875
+ function getFieldValue(_f) {
1876
+ const ref = _f.ref;
1877
+ if (_f.refs ? _f.refs.every((ref) => ref.disabled) : ref.disabled) {
1878
+ return;
1879
+ }
1880
+ if (isFileInput(ref)) {
1881
+ return ref.files;
1882
+ }
1883
+ if (isRadioInput(ref)) {
1884
+ return getRadioValue(_f.refs).value;
1885
+ }
1886
+ if (isMultipleSelect(ref)) {
1887
+ return [...ref.selectedOptions].map(({ value }) => value);
1888
+ }
1889
+ if (isCheckBoxInput(ref)) {
1890
+ return getCheckboxValue(_f.refs).value;
1891
+ }
1892
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1893
+ }
1894
+
1895
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1896
+ const fields = {};
1897
+ for (const name of fieldsNames) {
1898
+ const field = get(_fields, name);
1899
+ field && set(fields, name, field._f);
1900
+ }
1901
+ return {
1902
+ criteriaMode,
1903
+ names: [...fieldsNames],
1904
+ fields,
1905
+ shouldUseNativeValidation,
1906
+ };
1907
+ };
1908
+
1909
+ var getRuleValue = (rule) => isUndefined(rule)
1910
+ ? rule
1911
+ : isRegex(rule)
1912
+ ? rule.source
1913
+ : isObject(rule)
1914
+ ? isRegex(rule.value)
1915
+ ? rule.value.source
1916
+ : rule.value
1917
+ : rule;
1918
+
1919
+ var hasValidation = (options) => options.mount &&
1920
+ (options.required ||
1921
+ options.min ||
1922
+ options.max ||
1923
+ options.maxLength ||
1924
+ options.minLength ||
1925
+ options.pattern ||
1926
+ options.validate);
1927
+
1928
+ function schemaErrorLookup(errors, _fields, name) {
1929
+ const error = get(errors, name);
1930
+ if (error || isKey(name)) {
1931
+ return {
1932
+ error,
1933
+ name,
1934
+ };
1935
+ }
1936
+ const names = name.split('.');
1937
+ while (names.length) {
1938
+ const fieldName = names.join('.');
1939
+ const field = get(_fields, fieldName);
1940
+ const foundError = get(errors, fieldName);
1941
+ if (field && !Array.isArray(field) && name !== fieldName) {
1942
+ return { name };
1943
+ }
1944
+ if (foundError && foundError.type) {
1945
+ return {
1946
+ name: fieldName,
1947
+ error: foundError,
1948
+ };
1949
+ }
1950
+ names.pop();
1951
+ }
1952
+ return {
1953
+ name,
1954
+ };
1955
+ }
1956
+
1957
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1958
+ if (mode.isOnAll) {
1959
+ return false;
1960
+ }
1961
+ else if (!isSubmitted && mode.isOnTouch) {
1962
+ return !(isTouched || isBlurEvent);
1963
+ }
1964
+ else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
1965
+ return !isBlurEvent;
1966
+ }
1967
+ else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
1968
+ return isBlurEvent;
1969
+ }
1970
+ return true;
1971
+ };
1972
+
1973
+ var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
1974
+
1975
+ const defaultOptions = {
1976
+ mode: VALIDATION_MODE.onSubmit,
1977
+ reValidateMode: VALIDATION_MODE.onChange,
1978
+ shouldFocusError: true,
1979
+ };
1980
+ function createFormControl(props = {}) {
1981
+ let _options = {
1982
+ ...defaultOptions,
1983
+ ...props,
1984
+ };
1985
+ let _formState = {
1986
+ submitCount: 0,
1987
+ isDirty: false,
1988
+ isLoading: isFunction(_options.defaultValues),
1989
+ isValidating: false,
1990
+ isSubmitted: false,
1991
+ isSubmitting: false,
1992
+ isSubmitSuccessful: false,
1993
+ isValid: false,
1994
+ touchedFields: {},
1995
+ dirtyFields: {},
1996
+ validatingFields: {},
1997
+ errors: _options.errors || {},
1998
+ disabled: _options.disabled || false,
1999
+ };
2000
+ let _fields = {};
2001
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
2002
+ ? cloneObject(_options.defaultValues || _options.values) || {}
2003
+ : {};
2004
+ let _formValues = _options.shouldUnregister
2005
+ ? {}
2006
+ : cloneObject(_defaultValues);
2007
+ let _state = {
2008
+ action: false,
2009
+ mount: false,
2010
+ watch: false,
2011
+ };
2012
+ let _names = {
2013
+ mount: new Set(),
2014
+ unMount: new Set(),
2015
+ array: new Set(),
2016
+ watch: new Set(),
2017
+ };
2018
+ let delayErrorCallback;
2019
+ let timer = 0;
2020
+ const _proxyFormState = {
2021
+ isDirty: false,
2022
+ dirtyFields: false,
2023
+ validatingFields: false,
2024
+ touchedFields: false,
2025
+ isValidating: false,
2026
+ isValid: false,
2027
+ errors: false,
2028
+ };
2029
+ const _subjects = {
2030
+ values: createSubject(),
2031
+ array: createSubject(),
2032
+ state: createSubject(),
2033
+ };
2034
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
2035
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
2036
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
2037
+ const debounce = (callback) => (wait) => {
2038
+ clearTimeout(timer);
2039
+ timer = setTimeout(callback, wait);
2040
+ };
2041
+ const _updateValid = async (shouldUpdateValid) => {
2042
+ if (_proxyFormState.isValid || shouldUpdateValid) {
2043
+ const isValid = _options.resolver
2044
+ ? isEmptyObject((await _executeSchema()).errors)
2045
+ : await executeBuiltInValidation(_fields, true);
2046
+ if (isValid !== _formState.isValid) {
2047
+ _subjects.state.next({
2048
+ isValid,
2049
+ });
2050
+ }
2051
+ }
2052
+ };
2053
+ const _updateIsValidating = (names, isValidating) => {
2054
+ if (_proxyFormState.isValidating || _proxyFormState.validatingFields) {
2055
+ (names || Array.from(_names.mount)).forEach((name) => {
2056
+ if (name) {
2057
+ isValidating
2058
+ ? set(_formState.validatingFields, name, isValidating)
2059
+ : unset(_formState.validatingFields, name);
2060
+ }
2061
+ });
2062
+ _subjects.state.next({
2063
+ validatingFields: _formState.validatingFields,
2064
+ isValidating: !isEmptyObject(_formState.validatingFields),
2065
+ });
2066
+ }
2067
+ };
2068
+ const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
2069
+ if (args && method) {
2070
+ _state.action = true;
2071
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
2072
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
2073
+ shouldSetValues && set(_fields, name, fieldValues);
2074
+ }
2075
+ if (shouldUpdateFieldsAndState &&
2076
+ Array.isArray(get(_formState.errors, name))) {
2077
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
2078
+ shouldSetValues && set(_formState.errors, name, errors);
2079
+ unsetEmptyArray(_formState.errors, name);
2080
+ }
2081
+ if (_proxyFormState.touchedFields &&
2082
+ shouldUpdateFieldsAndState &&
2083
+ Array.isArray(get(_formState.touchedFields, name))) {
2084
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
2085
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
2086
+ }
2087
+ if (_proxyFormState.dirtyFields) {
2088
+ _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
2089
+ }
2090
+ _subjects.state.next({
2091
+ name,
2092
+ isDirty: _getDirty(name, values),
2093
+ dirtyFields: _formState.dirtyFields,
2094
+ errors: _formState.errors,
2095
+ isValid: _formState.isValid,
2096
+ });
2097
+ }
2098
+ else {
2099
+ set(_formValues, name, values);
2100
+ }
2101
+ };
2102
+ const updateErrors = (name, error) => {
2103
+ set(_formState.errors, name, error);
2104
+ _subjects.state.next({
2105
+ errors: _formState.errors,
2106
+ });
2107
+ };
2108
+ const _setErrors = (errors) => {
2109
+ _formState.errors = errors;
2110
+ _subjects.state.next({
2111
+ errors: _formState.errors,
2112
+ isValid: false,
2113
+ });
2114
+ };
2115
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
2116
+ const field = get(_fields, name);
2117
+ if (field) {
2118
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
2119
+ isUndefined(defaultValue) ||
2120
+ (ref && ref.defaultChecked) ||
2121
+ shouldSkipSetValueAs
2122
+ ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
2123
+ : setFieldValue(name, defaultValue);
2124
+ _state.mount && _updateValid();
2125
+ }
2126
+ };
2127
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
2128
+ let shouldUpdateField = false;
2129
+ let isPreviousDirty = false;
2130
+ const output = {
2131
+ name,
2132
+ };
2133
+ const disabledField = !!(get(_fields, name) &&
2134
+ get(_fields, name)._f &&
2135
+ get(_fields, name)._f.disabled);
2136
+ if (!isBlurEvent || shouldDirty) {
2137
+ if (_proxyFormState.isDirty) {
2138
+ isPreviousDirty = _formState.isDirty;
2139
+ _formState.isDirty = output.isDirty = _getDirty();
2140
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
2141
+ }
2142
+ const isCurrentFieldPristine = disabledField || deepEqual(get(_defaultValues, name), fieldValue);
2143
+ isPreviousDirty = !!(!disabledField && get(_formState.dirtyFields, name));
2144
+ isCurrentFieldPristine || disabledField
2145
+ ? unset(_formState.dirtyFields, name)
2146
+ : set(_formState.dirtyFields, name, true);
2147
+ output.dirtyFields = _formState.dirtyFields;
2148
+ shouldUpdateField =
2149
+ shouldUpdateField ||
2150
+ (_proxyFormState.dirtyFields &&
2151
+ isPreviousDirty !== !isCurrentFieldPristine);
2152
+ }
2153
+ if (isBlurEvent) {
2154
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
2155
+ if (!isPreviousFieldTouched) {
2156
+ set(_formState.touchedFields, name, isBlurEvent);
2157
+ output.touchedFields = _formState.touchedFields;
2158
+ shouldUpdateField =
2159
+ shouldUpdateField ||
2160
+ (_proxyFormState.touchedFields &&
2161
+ isPreviousFieldTouched !== isBlurEvent);
2162
+ }
2163
+ }
2164
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
2165
+ return shouldUpdateField ? output : {};
2166
+ };
2167
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
2168
+ const previousFieldError = get(_formState.errors, name);
2169
+ const shouldUpdateValid = _proxyFormState.isValid &&
2170
+ isBoolean(isValid) &&
2171
+ _formState.isValid !== isValid;
2172
+ if (props.delayError && error) {
2173
+ delayErrorCallback = debounce(() => updateErrors(name, error));
2174
+ delayErrorCallback(props.delayError);
2175
+ }
2176
+ else {
2177
+ clearTimeout(timer);
2178
+ delayErrorCallback = null;
2179
+ error
2180
+ ? set(_formState.errors, name, error)
2181
+ : unset(_formState.errors, name);
2182
+ }
2183
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
2184
+ !isEmptyObject(fieldState) ||
2185
+ shouldUpdateValid) {
2186
+ const updatedFormState = {
2187
+ ...fieldState,
2188
+ ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
2189
+ errors: _formState.errors,
2190
+ name,
2191
+ };
2192
+ _formState = {
2193
+ ..._formState,
2194
+ ...updatedFormState,
2195
+ };
2196
+ _subjects.state.next(updatedFormState);
2197
+ }
2198
+ };
2199
+ const _executeSchema = async (name) => {
2200
+ _updateIsValidating(name, true);
2201
+ const result = await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
2202
+ _updateIsValidating(name);
2203
+ return result;
2204
+ };
2205
+ const executeSchemaAndUpdateState = async (names) => {
2206
+ const { errors } = await _executeSchema(names);
2207
+ if (names) {
2208
+ for (const name of names) {
2209
+ const error = get(errors, name);
2210
+ error
2211
+ ? set(_formState.errors, name, error)
2212
+ : unset(_formState.errors, name);
2213
+ }
2214
+ }
2215
+ else {
2216
+ _formState.errors = errors;
2217
+ }
2218
+ return errors;
2219
+ };
2220
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
2221
+ valid: true,
2222
+ }) => {
2223
+ for (const name in fields) {
2224
+ const field = fields[name];
2225
+ if (field) {
2226
+ const { _f, ...fieldValue } = field;
2227
+ if (_f) {
2228
+ const isFieldArrayRoot = _names.array.has(_f.name);
2229
+ _updateIsValidating([name], true);
2230
+ const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
2231
+ _updateIsValidating([name]);
2232
+ if (fieldError[_f.name]) {
2233
+ context.valid = false;
2234
+ if (shouldOnlyCheckValid) {
2235
+ break;
2236
+ }
2237
+ }
2238
+ !shouldOnlyCheckValid &&
2239
+ (get(fieldError, _f.name)
2240
+ ? isFieldArrayRoot
2241
+ ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
2242
+ : set(_formState.errors, _f.name, fieldError[_f.name])
2243
+ : unset(_formState.errors, _f.name));
2244
+ }
2245
+ fieldValue &&
2246
+ (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
2247
+ }
2248
+ }
2249
+ return context.valid;
2250
+ };
2251
+ const _removeUnmounted = () => {
2252
+ for (const name of _names.unMount) {
2253
+ const field = get(_fields, name);
2254
+ field &&
2255
+ (field._f.refs
2256
+ ? field._f.refs.every((ref) => !live(ref))
2257
+ : !live(field._f.ref)) &&
2258
+ unregister(name);
2259
+ }
2260
+ _names.unMount = new Set();
2261
+ };
2262
+ const _getDirty = (name, data) => (name && data && set(_formValues, name, data),
2263
+ !deepEqual(getValues(), _defaultValues));
2264
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
2265
+ ...(_state.mount
2266
+ ? _formValues
2267
+ : isUndefined(defaultValue)
2268
+ ? _defaultValues
2269
+ : isString(names)
2270
+ ? { [names]: defaultValue }
2271
+ : defaultValue),
2272
+ }, isGlobal, defaultValue);
2273
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
2274
+ const setFieldValue = (name, value, options = {}) => {
2275
+ const field = get(_fields, name);
2276
+ let fieldValue = value;
2277
+ if (field) {
2278
+ const fieldReference = field._f;
2279
+ if (fieldReference) {
2280
+ !fieldReference.disabled &&
2281
+ set(_formValues, name, getFieldValueAs(value, fieldReference));
2282
+ fieldValue =
2283
+ isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
2284
+ ? ''
2285
+ : value;
2286
+ if (isMultipleSelect(fieldReference.ref)) {
2287
+ [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
2288
+ }
2289
+ else if (fieldReference.refs) {
2290
+ if (isCheckBoxInput(fieldReference.ref)) {
2291
+ fieldReference.refs.length > 1
2292
+ ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&
2293
+ (checkboxRef.checked = Array.isArray(fieldValue)
2294
+ ? !!fieldValue.find((data) => data === checkboxRef.value)
2295
+ : fieldValue === checkboxRef.value))
2296
+ : fieldReference.refs[0] &&
2297
+ (fieldReference.refs[0].checked = !!fieldValue);
2298
+ }
2299
+ else {
2300
+ fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
2301
+ }
2302
+ }
2303
+ else if (isFileInput(fieldReference.ref)) {
2304
+ fieldReference.ref.value = '';
2305
+ }
2306
+ else {
2307
+ fieldReference.ref.value = fieldValue;
2308
+ if (!fieldReference.ref.type) {
2309
+ _subjects.values.next({
2310
+ name,
2311
+ values: { ..._formValues },
2312
+ });
2313
+ }
2314
+ }
2315
+ }
2316
+ }
2317
+ (options.shouldDirty || options.shouldTouch) &&
2318
+ updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
2319
+ options.shouldValidate && trigger(name);
2320
+ };
2321
+ const setValues = (name, value, options) => {
2322
+ for (const fieldKey in value) {
2323
+ const fieldValue = value[fieldKey];
2324
+ const fieldName = `${name}.${fieldKey}`;
2325
+ const field = get(_fields, fieldName);
2326
+ (_names.array.has(name) ||
2327
+ !isPrimitive(fieldValue) ||
2328
+ (field && !field._f)) &&
2329
+ !isDateObject(fieldValue)
2330
+ ? setValues(fieldName, fieldValue, options)
2331
+ : setFieldValue(fieldName, fieldValue, options);
2332
+ }
2333
+ };
2334
+ const setValue = (name, value, options = {}) => {
2335
+ const field = get(_fields, name);
2336
+ const isFieldArray = _names.array.has(name);
2337
+ const cloneValue = cloneObject(value);
2338
+ set(_formValues, name, cloneValue);
2339
+ if (isFieldArray) {
2340
+ _subjects.array.next({
2341
+ name,
2342
+ values: { ..._formValues },
2343
+ });
2344
+ if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
2345
+ options.shouldDirty) {
2346
+ _subjects.state.next({
2347
+ name,
2348
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
2349
+ isDirty: _getDirty(name, cloneValue),
2350
+ });
2351
+ }
2352
+ }
2353
+ else {
2354
+ field && !field._f && !isNullOrUndefined(cloneValue)
2355
+ ? setValues(name, cloneValue, options)
2356
+ : setFieldValue(name, cloneValue, options);
2357
+ }
2358
+ isWatched(name, _names) && _subjects.state.next({ ..._formState });
2359
+ _subjects.values.next({
2360
+ name: _state.mount ? name : undefined,
2361
+ values: { ..._formValues },
2362
+ });
2363
+ };
2364
+ const onChange = async (event) => {
2365
+ _state.mount = true;
2366
+ const target = event.target;
2367
+ let name = target.name;
2368
+ let isFieldValueUpdated = true;
2369
+ const field = get(_fields, name);
2370
+ const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
2371
+ const _updateIsFieldValueUpdated = (fieldValue) => {
2372
+ isFieldValueUpdated =
2373
+ Number.isNaN(fieldValue) ||
2374
+ fieldValue === get(_formValues, name, fieldValue);
2375
+ };
2376
+ if (field) {
2377
+ let error;
2378
+ let isValid;
2379
+ const fieldValue = getCurrentFieldValue();
2380
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
2381
+ const shouldSkipValidation = (!hasValidation(field._f) &&
2382
+ !_options.resolver &&
2383
+ !get(_formState.errors, name) &&
2384
+ !field._f.deps) ||
2385
+ skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
2386
+ const watched = isWatched(name, _names, isBlurEvent);
2387
+ set(_formValues, name, fieldValue);
2388
+ if (isBlurEvent) {
2389
+ field._f.onBlur && field._f.onBlur(event);
2390
+ delayErrorCallback && delayErrorCallback(0);
2391
+ }
2392
+ else if (field._f.onChange) {
2393
+ field._f.onChange(event);
2394
+ }
2395
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
2396
+ const shouldRender = !isEmptyObject(fieldState) || watched;
2397
+ !isBlurEvent &&
2398
+ _subjects.values.next({
2399
+ name,
2400
+ type: event.type,
2401
+ values: { ..._formValues },
2402
+ });
2403
+ if (shouldSkipValidation) {
2404
+ _proxyFormState.isValid && _updateValid();
2405
+ return (shouldRender &&
2406
+ _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
2407
+ }
2408
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
2409
+ if (_options.resolver) {
2410
+ const { errors } = await _executeSchema([name]);
2411
+ _updateIsFieldValueUpdated(fieldValue);
2412
+ if (isFieldValueUpdated) {
2413
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
2414
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
2415
+ error = errorLookupResult.error;
2416
+ name = errorLookupResult.name;
2417
+ isValid = isEmptyObject(errors);
2418
+ }
2419
+ }
2420
+ else {
2421
+ _updateIsValidating([name], true);
2422
+ error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
2423
+ _updateIsValidating([name]);
2424
+ _updateIsFieldValueUpdated(fieldValue);
2425
+ if (isFieldValueUpdated) {
2426
+ if (error) {
2427
+ isValid = false;
2428
+ }
2429
+ else if (_proxyFormState.isValid) {
2430
+ isValid = await executeBuiltInValidation(_fields, true);
2431
+ }
2432
+ }
2433
+ }
2434
+ if (isFieldValueUpdated) {
2435
+ field._f.deps &&
2436
+ trigger(field._f.deps);
2437
+ shouldRenderByError(name, isValid, error, fieldState);
2438
+ }
2439
+ }
2440
+ };
2441
+ const _focusInput = (ref, key) => {
2442
+ if (get(_formState.errors, key) && ref.focus) {
2443
+ ref.focus();
2444
+ return 1;
2445
+ }
2446
+ return;
2447
+ };
2448
+ const trigger = async (name, options = {}) => {
2449
+ let isValid;
2450
+ let validationResult;
2451
+ const fieldNames = convertToArrayPayload(name);
2452
+ if (_options.resolver) {
2453
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
2454
+ isValid = isEmptyObject(errors);
2455
+ validationResult = name
2456
+ ? !fieldNames.some((name) => get(errors, name))
2457
+ : isValid;
2458
+ }
2459
+ else if (name) {
2460
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
2461
+ const field = get(_fields, fieldName);
2462
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
2463
+ }))).every(Boolean);
2464
+ !(!validationResult && !_formState.isValid) && _updateValid();
2465
+ }
2466
+ else {
2467
+ validationResult = isValid = await executeBuiltInValidation(_fields);
2468
+ }
2469
+ _subjects.state.next({
2470
+ ...(!isString(name) ||
2471
+ (_proxyFormState.isValid && isValid !== _formState.isValid)
2472
+ ? {}
2473
+ : { name }),
2474
+ ...(_options.resolver || !name ? { isValid } : {}),
2475
+ errors: _formState.errors,
2476
+ });
2477
+ options.shouldFocus &&
2478
+ !validationResult &&
2479
+ iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
2480
+ return validationResult;
2481
+ };
2482
+ const getValues = (fieldNames) => {
2483
+ const values = {
2484
+ ...(_state.mount ? _formValues : _defaultValues),
2485
+ };
2486
+ return isUndefined(fieldNames)
2487
+ ? values
2488
+ : isString(fieldNames)
2489
+ ? get(values, fieldNames)
2490
+ : fieldNames.map((name) => get(values, name));
2491
+ };
2492
+ const getFieldState = (name, formState) => ({
2493
+ invalid: !!get((formState || _formState).errors, name),
2494
+ isDirty: !!get((formState || _formState).dirtyFields, name),
2495
+ error: get((formState || _formState).errors, name),
2496
+ isValidating: !!get(_formState.validatingFields, name),
2497
+ isTouched: !!get((formState || _formState).touchedFields, name),
2498
+ });
2499
+ const clearErrors = (name) => {
2500
+ name &&
2501
+ convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
2502
+ _subjects.state.next({
2503
+ errors: name ? _formState.errors : {},
2504
+ });
2505
+ };
2506
+ const setError = (name, error, options) => {
2507
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
2508
+ const currentError = get(_formState.errors, name) || {};
2509
+ // Don't override existing error messages elsewhere in the object tree.
2510
+ const { ref: currentRef, message, type, ...restOfErrorTree } = currentError;
2511
+ set(_formState.errors, name, {
2512
+ ...restOfErrorTree,
2513
+ ...error,
2514
+ ref,
2515
+ });
2516
+ _subjects.state.next({
2517
+ name,
2518
+ errors: _formState.errors,
2519
+ isValid: false,
2520
+ });
2521
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
2522
+ };
2523
+ const watch = (name, defaultValue) => isFunction(name)
2524
+ ? _subjects.values.subscribe({
2525
+ next: (payload) => name(_getWatch(undefined, defaultValue), payload),
2526
+ })
2527
+ : _getWatch(name, defaultValue, true);
2528
+ const unregister = (name, options = {}) => {
2529
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
2530
+ _names.mount.delete(fieldName);
2531
+ _names.array.delete(fieldName);
2532
+ if (!options.keepValue) {
2533
+ unset(_fields, fieldName);
2534
+ unset(_formValues, fieldName);
2535
+ }
2536
+ !options.keepError && unset(_formState.errors, fieldName);
2537
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
2538
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
2539
+ !options.keepIsValidating &&
2540
+ unset(_formState.validatingFields, fieldName);
2541
+ !_options.shouldUnregister &&
2542
+ !options.keepDefaultValue &&
2543
+ unset(_defaultValues, fieldName);
2544
+ }
2545
+ _subjects.values.next({
2546
+ values: { ..._formValues },
2547
+ });
2548
+ _subjects.state.next({
2549
+ ..._formState,
2550
+ ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
2551
+ });
2552
+ !options.keepIsValid && _updateValid();
2553
+ };
2554
+ const _updateDisabledField = ({ disabled, name, field, fields, value, }) => {
2555
+ if ((isBoolean(disabled) && _state.mount) || !!disabled) {
2556
+ const inputValue = disabled
2557
+ ? undefined
2558
+ : isUndefined(value)
2559
+ ? getFieldValue(field ? field._f : get(fields, name)._f)
2560
+ : value;
2561
+ set(_formValues, name, inputValue);
2562
+ updateTouchAndDirty(name, inputValue, false, false, true);
2563
+ }
2564
+ };
2565
+ const register = (name, options = {}) => {
2566
+ let field = get(_fields, name);
2567
+ const disabledIsDefined = isBoolean(options.disabled);
2568
+ set(_fields, name, {
2569
+ ...(field || {}),
2570
+ _f: {
2571
+ ...(field && field._f ? field._f : { ref: { name } }),
2572
+ name,
2573
+ mount: true,
2574
+ ...options,
2575
+ },
2576
+ });
2577
+ _names.mount.add(name);
2578
+ if (field) {
2579
+ _updateDisabledField({
2580
+ field,
2581
+ disabled: options.disabled,
2582
+ name,
2583
+ value: options.value,
2584
+ });
2585
+ }
2586
+ else {
2587
+ updateValidAndValue(name, true, options.value);
2588
+ }
2589
+ return {
2590
+ ...(disabledIsDefined ? { disabled: options.disabled } : {}),
2591
+ ...(_options.progressive
2592
+ ? {
2593
+ required: !!options.required,
2594
+ min: getRuleValue(options.min),
2595
+ max: getRuleValue(options.max),
2596
+ minLength: getRuleValue(options.minLength),
2597
+ maxLength: getRuleValue(options.maxLength),
2598
+ pattern: getRuleValue(options.pattern),
2599
+ }
2600
+ : {}),
2601
+ name,
2602
+ onChange,
2603
+ onBlur: onChange,
2604
+ ref: (ref) => {
2605
+ if (ref) {
2606
+ register(name, options);
2607
+ field = get(_fields, name);
2608
+ const fieldRef = isUndefined(ref.value)
2609
+ ? ref.querySelectorAll
2610
+ ? ref.querySelectorAll('input,select,textarea')[0] || ref
2611
+ : ref
2612
+ : ref;
2613
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
2614
+ const refs = field._f.refs || [];
2615
+ if (radioOrCheckbox
2616
+ ? refs.find((option) => option === fieldRef)
2617
+ : fieldRef === field._f.ref) {
2618
+ return;
2619
+ }
2620
+ set(_fields, name, {
2621
+ _f: {
2622
+ ...field._f,
2623
+ ...(radioOrCheckbox
2624
+ ? {
2625
+ refs: [
2626
+ ...refs.filter(live),
2627
+ fieldRef,
2628
+ ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
2629
+ ],
2630
+ ref: { type: fieldRef.type, name },
2631
+ }
2632
+ : { ref: fieldRef }),
2633
+ },
2634
+ });
2635
+ updateValidAndValue(name, false, undefined, fieldRef);
2636
+ }
2637
+ else {
2638
+ field = get(_fields, name, {});
2639
+ if (field._f) {
2640
+ field._f.mount = false;
2641
+ }
2642
+ (_options.shouldUnregister || options.shouldUnregister) &&
2643
+ !(isNameInFieldArray(_names.array, name) && _state.action) &&
2644
+ _names.unMount.add(name);
2645
+ }
2646
+ },
2647
+ };
2648
+ };
2649
+ const _focusError = () => _options.shouldFocusError &&
2650
+ iterateFieldsByAction(_fields, _focusInput, _names.mount);
2651
+ const _disableForm = (disabled) => {
2652
+ if (isBoolean(disabled)) {
2653
+ _subjects.state.next({ disabled });
2654
+ iterateFieldsByAction(_fields, (ref, name) => {
2655
+ const currentField = get(_fields, name);
2656
+ if (currentField) {
2657
+ ref.disabled = currentField._f.disabled || disabled;
2658
+ if (Array.isArray(currentField._f.refs)) {
2659
+ currentField._f.refs.forEach((inputRef) => {
2660
+ inputRef.disabled = currentField._f.disabled || disabled;
2661
+ });
2662
+ }
2663
+ }
2664
+ }, 0, false);
2665
+ }
2666
+ };
2667
+ const handleSubmit = (onValid, onInvalid) => async (e) => {
2668
+ let onValidError = undefined;
2669
+ if (e) {
2670
+ e.preventDefault && e.preventDefault();
2671
+ e.persist && e.persist();
2672
+ }
2673
+ let fieldValues = cloneObject(_formValues);
2674
+ _subjects.state.next({
2675
+ isSubmitting: true,
2676
+ });
2677
+ if (_options.resolver) {
2678
+ const { errors, values } = await _executeSchema();
2679
+ _formState.errors = errors;
2680
+ fieldValues = values;
2681
+ }
2682
+ else {
2683
+ await executeBuiltInValidation(_fields);
2684
+ }
2685
+ unset(_formState.errors, 'root');
2686
+ if (isEmptyObject(_formState.errors)) {
2687
+ _subjects.state.next({
2688
+ errors: {},
2689
+ });
2690
+ try {
2691
+ await onValid(fieldValues, e);
2692
+ }
2693
+ catch (error) {
2694
+ onValidError = error;
2695
+ }
2696
+ }
2697
+ else {
2698
+ if (onInvalid) {
2699
+ await onInvalid({ ..._formState.errors }, e);
2700
+ }
2701
+ _focusError();
2702
+ setTimeout(_focusError);
2703
+ }
2704
+ _subjects.state.next({
2705
+ isSubmitted: true,
2706
+ isSubmitting: false,
2707
+ isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
2708
+ submitCount: _formState.submitCount + 1,
2709
+ errors: _formState.errors,
2710
+ });
2711
+ if (onValidError) {
2712
+ throw onValidError;
2713
+ }
2714
+ };
2715
+ const resetField = (name, options = {}) => {
2716
+ if (get(_fields, name)) {
2717
+ if (isUndefined(options.defaultValue)) {
2718
+ setValue(name, cloneObject(get(_defaultValues, name)));
2719
+ }
2720
+ else {
2721
+ setValue(name, options.defaultValue);
2722
+ set(_defaultValues, name, cloneObject(options.defaultValue));
2723
+ }
2724
+ if (!options.keepTouched) {
2725
+ unset(_formState.touchedFields, name);
2726
+ }
2727
+ if (!options.keepDirty) {
2728
+ unset(_formState.dirtyFields, name);
2729
+ _formState.isDirty = options.defaultValue
2730
+ ? _getDirty(name, cloneObject(get(_defaultValues, name)))
2731
+ : _getDirty();
2732
+ }
2733
+ if (!options.keepError) {
2734
+ unset(_formState.errors, name);
2735
+ _proxyFormState.isValid && _updateValid();
2736
+ }
2737
+ _subjects.state.next({ ..._formState });
2738
+ }
2739
+ };
2740
+ const _reset = (formValues, keepStateOptions = {}) => {
2741
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
2742
+ const cloneUpdatedValues = cloneObject(updatedValues);
2743
+ const isEmptyResetValues = isEmptyObject(formValues);
2744
+ const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;
2745
+ if (!keepStateOptions.keepDefaultValues) {
2746
+ _defaultValues = updatedValues;
2747
+ }
2748
+ if (!keepStateOptions.keepValues) {
2749
+ if (keepStateOptions.keepDirtyValues) {
2750
+ for (const fieldName of _names.mount) {
2751
+ get(_formState.dirtyFields, fieldName)
2752
+ ? set(values, fieldName, get(_formValues, fieldName))
2753
+ : setValue(fieldName, get(values, fieldName));
2754
+ }
2755
+ }
2756
+ else {
2757
+ if (isWeb && isUndefined(formValues)) {
2758
+ for (const name of _names.mount) {
2759
+ const field = get(_fields, name);
2760
+ if (field && field._f) {
2761
+ const fieldReference = Array.isArray(field._f.refs)
2762
+ ? field._f.refs[0]
2763
+ : field._f.ref;
2764
+ if (isHTMLElement(fieldReference)) {
2765
+ const form = fieldReference.closest('form');
2766
+ if (form) {
2767
+ form.reset();
2768
+ break;
2769
+ }
2770
+ }
2771
+ }
2772
+ }
2773
+ }
2774
+ _fields = {};
2775
+ }
2776
+ _formValues = props.shouldUnregister
2777
+ ? keepStateOptions.keepDefaultValues
2778
+ ? cloneObject(_defaultValues)
2779
+ : {}
2780
+ : cloneObject(values);
2781
+ _subjects.array.next({
2782
+ values: { ...values },
2783
+ });
2784
+ _subjects.values.next({
2785
+ values: { ...values },
2786
+ });
2787
+ }
2788
+ _names = {
2789
+ mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(),
2790
+ unMount: new Set(),
2791
+ array: new Set(),
2792
+ watch: new Set(),
2793
+ watchAll: false,
2794
+ focus: '',
2795
+ };
2796
+ _state.mount =
2797
+ !_proxyFormState.isValid ||
2798
+ !!keepStateOptions.keepIsValid ||
2799
+ !!keepStateOptions.keepDirtyValues;
2800
+ _state.watch = !!props.shouldUnregister;
2801
+ _subjects.state.next({
2802
+ submitCount: keepStateOptions.keepSubmitCount
2803
+ ? _formState.submitCount
2804
+ : 0,
2805
+ isDirty: isEmptyResetValues
2806
+ ? false
2807
+ : keepStateOptions.keepDirty
2808
+ ? _formState.isDirty
2809
+ : !!(keepStateOptions.keepDefaultValues &&
2810
+ !deepEqual(formValues, _defaultValues)),
2811
+ isSubmitted: keepStateOptions.keepIsSubmitted
2812
+ ? _formState.isSubmitted
2813
+ : false,
2814
+ dirtyFields: isEmptyResetValues
2815
+ ? {}
2816
+ : keepStateOptions.keepDirtyValues
2817
+ ? keepStateOptions.keepDefaultValues && _formValues
2818
+ ? getDirtyFields(_defaultValues, _formValues)
2819
+ : _formState.dirtyFields
2820
+ : keepStateOptions.keepDefaultValues && formValues
2821
+ ? getDirtyFields(_defaultValues, formValues)
2822
+ : keepStateOptions.keepDirty
2823
+ ? _formState.dirtyFields
2824
+ : {},
2825
+ touchedFields: keepStateOptions.keepTouched
2826
+ ? _formState.touchedFields
2827
+ : {},
2828
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
2829
+ isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful
2830
+ ? _formState.isSubmitSuccessful
2831
+ : false,
2832
+ isSubmitting: false,
2833
+ });
2834
+ };
2835
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
2836
+ ? formValues(_formValues)
2837
+ : formValues, keepStateOptions);
2838
+ const setFocus = (name, options = {}) => {
2839
+ const field = get(_fields, name);
2840
+ const fieldReference = field && field._f;
2841
+ if (fieldReference) {
2842
+ const fieldRef = fieldReference.refs
2843
+ ? fieldReference.refs[0]
2844
+ : fieldReference.ref;
2845
+ if (fieldRef.focus) {
2846
+ fieldRef.focus();
2847
+ options.shouldSelect && fieldRef.select();
2848
+ }
2849
+ }
2850
+ };
2851
+ const _updateFormState = (updatedFormState) => {
2852
+ _formState = {
2853
+ ..._formState,
2854
+ ...updatedFormState,
2855
+ };
2856
+ };
2857
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
2858
+ _options.defaultValues().then((values) => {
2859
+ reset(values, _options.resetOptions);
2860
+ _subjects.state.next({
2861
+ isLoading: false,
2862
+ });
2863
+ });
2864
+ return {
2865
+ control: {
2866
+ register,
2867
+ unregister,
2868
+ getFieldState,
2869
+ handleSubmit,
2870
+ setError,
2871
+ _executeSchema,
2872
+ _getWatch,
2873
+ _getDirty,
2874
+ _updateValid,
2875
+ _removeUnmounted,
2876
+ _updateFieldArray,
2877
+ _updateDisabledField,
2878
+ _getFieldArray,
2879
+ _reset,
2880
+ _resetDefaultValues,
2881
+ _updateFormState,
2882
+ _disableForm,
2883
+ _subjects,
2884
+ _proxyFormState,
2885
+ _setErrors,
2886
+ get _fields() {
2887
+ return _fields;
2888
+ },
2889
+ get _formValues() {
2890
+ return _formValues;
2891
+ },
2892
+ get _state() {
2893
+ return _state;
2894
+ },
2895
+ set _state(value) {
2896
+ _state = value;
2897
+ },
2898
+ get _defaultValues() {
2899
+ return _defaultValues;
2900
+ },
2901
+ get _names() {
2902
+ return _names;
2903
+ },
2904
+ set _names(value) {
2905
+ _names = value;
2906
+ },
2907
+ get _formState() {
2908
+ return _formState;
2909
+ },
2910
+ set _formState(value) {
2911
+ _formState = value;
2912
+ },
2913
+ get _options() {
2914
+ return _options;
2915
+ },
2916
+ set _options(value) {
2917
+ _options = {
2918
+ ..._options,
2919
+ ...value,
2920
+ };
2921
+ },
2922
+ },
2923
+ trigger,
2924
+ register,
2925
+ handleSubmit,
2926
+ watch,
2927
+ setValue,
2928
+ getValues,
2929
+ reset,
2930
+ resetField,
2931
+ clearErrors,
2932
+ unregister,
2933
+ setError,
2934
+ setFocus,
2935
+ getFieldState,
2936
+ };
2937
+ }
2938
+
2939
+ /**
2940
+ * Custom hook to manage the entire form.
2941
+ *
2942
+ * @remarks
2943
+ * [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)
2944
+ *
2945
+ * @param props - form configuration and validation parameters.
2946
+ *
2947
+ * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2948
+ *
2949
+ * @example
2950
+ * ```tsx
2951
+ * function App() {
2952
+ * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2953
+ * const onSubmit = data => console.log(data);
2954
+ *
2955
+ * console.log(watch("example"));
2956
+ *
2957
+ * return (
2958
+ * <form onSubmit={handleSubmit(onSubmit)}>
2959
+ * <input defaultValue="test" {...register("example")} />
2960
+ * <input {...register("exampleRequired", { required: true })} />
2961
+ * {errors.exampleRequired && <span>This field is required</span>}
2962
+ * <button>Submit</button>
2963
+ * </form>
2964
+ * );
2965
+ * }
2966
+ * ```
2967
+ */
2968
+ function useForm(props = {}) {
2969
+ const _formControl = react__WEBPACK_IMPORTED_MODULE_0__.useRef();
2970
+ const _values = react__WEBPACK_IMPORTED_MODULE_0__.useRef();
2971
+ const [formState, updateFormState] = react__WEBPACK_IMPORTED_MODULE_0__.useState({
2972
+ isDirty: false,
2973
+ isValidating: false,
2974
+ isLoading: isFunction(props.defaultValues),
2975
+ isSubmitted: false,
2976
+ isSubmitting: false,
2977
+ isSubmitSuccessful: false,
2978
+ isValid: false,
2979
+ submitCount: 0,
2980
+ dirtyFields: {},
2981
+ touchedFields: {},
2982
+ validatingFields: {},
2983
+ errors: props.errors || {},
2984
+ disabled: props.disabled || false,
2985
+ defaultValues: isFunction(props.defaultValues)
2986
+ ? undefined
2987
+ : props.defaultValues,
2988
+ });
2989
+ if (!_formControl.current) {
2990
+ _formControl.current = {
2991
+ ...createFormControl(props),
2992
+ formState,
2993
+ };
2994
+ }
2995
+ const control = _formControl.current.control;
2996
+ control._options = props;
2997
+ useSubscribe({
2998
+ subject: control._subjects.state,
2999
+ next: (value) => {
3000
+ if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
3001
+ updateFormState({ ...control._formState });
3002
+ }
3003
+ },
3004
+ });
3005
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
3006
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
3007
+ if (control._proxyFormState.isDirty) {
3008
+ const isDirty = control._getDirty();
3009
+ if (isDirty !== formState.isDirty) {
3010
+ control._subjects.state.next({
3011
+ isDirty,
3012
+ });
3013
+ }
3014
+ }
3015
+ }, [control, formState.isDirty]);
3016
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
3017
+ if (props.values && !deepEqual(props.values, _values.current)) {
3018
+ control._reset(props.values, control._options.resetOptions);
3019
+ _values.current = props.values;
3020
+ updateFormState((state) => ({ ...state }));
3021
+ }
3022
+ else {
3023
+ control._resetDefaultValues();
3024
+ }
3025
+ }, [props.values, control]);
3026
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
3027
+ if (props.errors) {
3028
+ control._setErrors(props.errors);
3029
+ }
3030
+ }, [props.errors, control]);
3031
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
3032
+ if (!control._state.mount) {
3033
+ control._updateValid();
3034
+ control._state.mount = true;
3035
+ }
3036
+ if (control._state.watch) {
3037
+ control._state.watch = false;
3038
+ control._subjects.state.next({ ...control._formState });
3039
+ }
3040
+ control._removeUnmounted();
3041
+ });
3042
+ react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => {
3043
+ props.shouldUnregister &&
3044
+ control._subjects.values.next({
3045
+ values: control._getWatch(),
3046
+ });
3047
+ }, [props.shouldUnregister, control]);
3048
+ _formControl.current.formState = getProxyFormState(formState, control);
3049
+ return _formControl.current;
3050
+ }
3051
+
3052
+
3053
+ //# sourceMappingURL=index.esm.mjs.map
3054
+
3055
+
3056
+ /***/ })
3057
+
3058
+ }]);
3059
+ //# sourceMappingURL=vendors-node_modules_openmrs_node_modules_css-loader_dist_runtime_api_js-node_modules_openmrs-205702.js.map