warqadui 0.0.8 → 0.0.10

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