@grafana/plugin-ui 0.15.0 → 0.16.0-dsconfig.a155abe

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