@lssm/lib.ui-kit 1.11.1 → 1.41.0

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