@frollo/frollo-web-ui 7.0.1 → 8.0.1

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 (172) hide show
  1. package/cjs/index.js +34629 -34457
  2. package/esm/_rollupPluginBabelHelpers-DpC_oIQV.js +2566 -0
  3. package/esm/{check-94a5917a.js → check--YD4Ts6g.js} +4 -4
  4. package/esm/fw-accordion.js +27 -26
  5. package/esm/fw-animations.js +23 -26
  6. package/esm/fw-bar-chart.js +15289 -19
  7. package/esm/{fw-button-c8502414.js → fw-button-4QLZlu0U.js} +44 -44
  8. package/esm/fw-button.js +5 -10
  9. package/esm/{fw-card-1b6a67fe.js → fw-card-bsYbpPmW.js} +12 -12
  10. package/esm/fw-card.js +1 -1
  11. package/esm/fw-checkbox.js +23 -32
  12. package/esm/fw-date-picker.js +134 -80
  13. package/esm/fw-drawer.js +32 -35
  14. package/esm/fw-dropdown-nLtzu2fS.js +277 -0
  15. package/esm/fw-dropdown.js +7 -15
  16. package/esm/fw-form.js +1 -1
  17. package/esm/fw-image-DOgM8i8X.js +200 -0
  18. package/esm/fw-image.js +5 -21
  19. package/esm/{fw-input-8969b226.js → fw-input-Qiy53nRk.js} +61 -53
  20. package/esm/fw-input.js +6 -19
  21. package/esm/fw-loading-bar-DThRjdw1.js +22 -0
  22. package/esm/{fw-loading-spinner-72d70258.js → fw-loading-spinner-Dn52RI5h.js} +1 -1
  23. package/esm/fw-loading.js +3 -7
  24. package/esm/fw-modal.js +93 -56
  25. package/esm/fw-navigation-menu.js +15 -20
  26. package/esm/fw-popover.js +39 -375
  27. package/esm/fw-progress-bar.js +8 -11
  28. package/esm/fw-provider-list.js +41 -84
  29. package/esm/fw-sidebar-menu.js +33 -24
  30. package/esm/{fw-table-row-23f78218.js → fw-table-row-DkZaaMmE.js} +15 -301
  31. package/esm/fw-table.js +6 -16
  32. package/esm/fw-tabs.js +21 -103
  33. package/esm/{fw-tag-ac28200a.js → fw-tag-CPp1P480.js} +29 -20
  34. package/esm/fw-tag.js +7 -12
  35. package/esm/fw-toast.js +22 -37
  36. package/esm/fw-transactions-card.js +14 -30
  37. package/esm/index-CUPvK0Aa.js +586 -0
  38. package/esm/index.js +66 -228
  39. package/esm/vee-validate.esm-3ptvCDR1.js +4071 -0
  40. package/frollo-web-ui.esm.js +34401 -34647
  41. package/icons/chart-line-up.svg +3 -0
  42. package/icons/icons.stories.ts +24 -29
  43. package/icons/index.ts +5 -1
  44. package/icons/sack-dollar.svg +3 -0
  45. package/icons/xmark.svg +2 -2
  46. package/index.d.ts +2815 -2573
  47. package/package.json +75 -73
  48. package/styles/tailwind.scss +6 -0
  49. package/types/components/fw-accordion/fw-accordion.vue.d.ts +128 -128
  50. package/types/components/fw-accordion/index.d.ts +2 -2
  51. package/types/components/fw-accordion/index.types.d.ts +10 -10
  52. package/types/components/fw-animations/fw-email-pulse.vue.d.ts +24 -24
  53. package/types/components/fw-animations/fw-loading-spinner.vue.d.ts +2 -2
  54. package/types/components/fw-animations/fw-success-pulse.vue.d.ts +24 -24
  55. package/types/components/fw-animations/index.d.ts +4 -4
  56. package/types/components/fw-bar-chart/fw-bar-chart.vue.d.ts +83 -83
  57. package/types/components/fw-bar-chart/index.d.ts +2 -2
  58. package/types/components/fw-bar-chart/index.types.d.ts +11 -11
  59. package/types/components/fw-button/fw-button.vue.d.ts +190 -176
  60. package/types/components/fw-button/index.d.ts +2 -2
  61. package/types/components/fw-button/index.types.d.ts +27 -26
  62. package/types/components/fw-card/fw-card.vue.d.ts +82 -82
  63. package/types/components/fw-card/index.d.ts +2 -2
  64. package/types/components/fw-card/index.types.d.ts +8 -8
  65. package/types/components/fw-checkbox/fw-checkbox.vue.d.ts +108 -108
  66. package/types/components/fw-checkbox/index.d.ts +2 -2
  67. package/types/components/fw-checkbox/index.types.d.ts +9 -9
  68. package/types/components/fw-date-picker/fw-date-picker.vue.d.ts +249 -177
  69. package/types/components/fw-date-picker/index.d.ts +2 -2
  70. package/types/components/fw-date-picker/index.types.d.ts +21 -16
  71. package/types/components/fw-drawer/fw-drawer.vue.d.ts +165 -165
  72. package/types/components/fw-drawer/index.d.ts +2 -2
  73. package/types/components/fw-drawer/index.types.d.ts +13 -13
  74. package/types/components/fw-dropdown/fw-dropdown.vue.d.ts +154 -130
  75. package/types/components/fw-dropdown/index.d.ts +2 -2
  76. package/types/components/fw-dropdown/index.types.d.ts +16 -13
  77. package/types/components/fw-form/index.d.ts +2 -2
  78. package/types/components/fw-image/fw-image.vue.d.ts +103 -84
  79. package/types/components/fw-image/index.d.ts +2 -2
  80. package/types/components/fw-image/index.types.d.ts +9 -8
  81. package/types/components/fw-input/fw-input.vue.d.ts +214 -197
  82. package/types/components/fw-input/index.d.ts +2 -2
  83. package/types/components/fw-input/index.types.d.ts +18 -16
  84. package/types/components/fw-loading/fw-loading-bar.vue.d.ts +2 -2
  85. package/types/components/fw-loading/fw-loading-card.vue.d.ts +2 -2
  86. package/types/components/fw-loading/fw-loading-table.vue.d.ts +25 -25
  87. package/types/components/fw-loading/index.d.ts +4 -4
  88. package/types/components/fw-modal/fw-modal.vue.d.ts +229 -175
  89. package/types/components/fw-modal/index.d.ts +2 -2
  90. package/types/components/fw-modal/index.types.d.ts +18 -14
  91. package/types/components/fw-navigation-menu/fw-navigation-menu.vue.d.ts +57 -57
  92. package/types/components/fw-navigation-menu/index.d.ts +2 -2
  93. package/types/components/fw-navigation-menu/index.types.d.ts +7 -7
  94. package/types/components/fw-popover/fw-popover.vue.d.ts +157 -157
  95. package/types/components/fw-popover/index.d.ts +2 -2
  96. package/types/components/fw-popover/index.types.d.ts +11 -11
  97. package/types/components/fw-progress-bar/fw-progress-bar.vue.d.ts +52 -52
  98. package/types/components/fw-progress-bar/index.d.ts +2 -2
  99. package/types/components/fw-progress-bar/index.types.d.ts +5 -5
  100. package/types/components/fw-provider-list/fw-provider-list.vue.d.ts +100 -100
  101. package/types/components/fw-provider-list/index.d.ts +2 -2
  102. package/types/components/fw-provider-list/index.types.d.ts +11 -11
  103. package/types/components/fw-sidebar-menu/fw-sidebar-menu.vue.d.ts +88 -72
  104. package/types/components/fw-sidebar-menu/index.d.ts +2 -2
  105. package/types/components/fw-sidebar-menu/index.types.d.ts +9 -8
  106. package/types/components/fw-table/fw-table-head.vue.d.ts +2 -2
  107. package/types/components/fw-table/fw-table-row.vue.d.ts +2 -2
  108. package/types/components/fw-table/fw-table.vue.d.ts +71 -71
  109. package/types/components/fw-table/index.d.ts +4 -4
  110. package/types/components/fw-table/index.types.d.ts +16 -16
  111. package/types/components/fw-tabs/fw-tab.vue.d.ts +24 -32
  112. package/types/components/fw-tabs/fw-tabs.vue.d.ts +24 -24
  113. package/types/components/fw-tabs/index.d.ts +3 -3
  114. package/types/components/fw-tabs/index.types.d.ts +8 -0
  115. package/types/components/fw-tag/fw-tag.vue.d.ts +80 -70
  116. package/types/components/fw-tag/index.d.ts +2 -2
  117. package/types/components/fw-tag/index.types.d.ts +18 -18
  118. package/types/components/fw-toast/fw-toast.vue.d.ts +121 -121
  119. package/types/components/fw-toast/index.d.ts +2 -2
  120. package/types/components/fw-toast/index.types.d.ts +13 -13
  121. package/types/components/fw-transactions-card/fw-transactions-card.vue.d.ts +58 -58
  122. package/types/components/fw-transactions-card/index.d.ts +2 -2
  123. package/types/components/fw-transactions-card/index.types.d.ts +6 -6
  124. package/types/components/index.d.ts +24 -24
  125. package/types/components/index.types.d.ts +21 -20
  126. package/types/directives/index.d.ts +2 -2
  127. package/types/directives/lazy-loader.d.ts +3 -3
  128. package/types/helpers/get-root-colours.d.ts +17 -17
  129. package/types/icons/index.d.ts +43 -41
  130. package/types/index-types.esm.d.ts +6 -6
  131. package/types/index.browser-umd.d.ts +2 -1
  132. package/types/index.d.ts +3 -3
  133. package/types/index.esm.d.ts +5 -5
  134. package/types/services/index.d.ts +2 -2
  135. package/types/services/modal.d.ts +9 -9
  136. package/types/services/toast.d.ts +9 -9
  137. package/web-components/index.js +19670 -19720
  138. package/esm/add-to-unscopables-ee05b58f.js +0 -25
  139. package/esm/array-iteration-8267bf22.js +0 -92
  140. package/esm/array-method-has-species-support-6c675094.js +0 -23
  141. package/esm/array-method-is-strict-d313436f.js +0 -14
  142. package/esm/array-species-create-1c67e297.js +0 -97
  143. package/esm/classof-d44bf093.js +0 -42
  144. package/esm/create-property-eb329361.js +0 -14
  145. package/esm/defineProperty-b85f2e0f.js +0 -42
  146. package/esm/does-not-exceed-safe-integer-de37ce28.js +0 -11
  147. package/esm/es.array.concat-99b85557.js +0 -69
  148. package/esm/es.array.find-1ded15d5.js +0 -28
  149. package/esm/es.array.includes-08e25019.js +0 -27
  150. package/esm/es.array.map-c56ebffd.js +0 -22
  151. package/esm/es.date.to-string-15eb9936.js +0 -23
  152. package/esm/es.function.name-6cafd747.js +0 -29
  153. package/esm/es.number.constructor-fb16fe05.js +0 -204
  154. package/esm/es.object.to-string-4b07c4d1.js +0 -24
  155. package/esm/es.string.includes-061e8272.js +0 -66
  156. package/esm/es.string.iterator-25db8cd2.js +0 -469
  157. package/esm/export-10c4adbc.js +0 -95
  158. package/esm/function-apply-e17cf65b.js +0 -14
  159. package/esm/fw-dropdown-6856e66e.js +0 -224
  160. package/esm/fw-image-aca2c61d.js +0 -296
  161. package/esm/fw-loading-bar-f5ca605c.js +0 -22
  162. package/esm/index-6758f755.js +0 -15797
  163. package/esm/index-bced3b35.js +0 -560
  164. package/esm/is-forced-7cb3ee8f.js +0 -927
  165. package/esm/object-create-51bf02dc.js +0 -125
  166. package/esm/regexp-flags-c09864e5.js +0 -50
  167. package/esm/vee-validate.esm-a17a23c3.js +0 -3192
  168. package/esm/web.timers-e406c8e6.js +0 -72
  169. /package/esm/{get-root-colours-865a52ba.js → get-root-colours-DYEoJPEb.js} +0 -0
  170. /package/esm/{index-0c5cae4f.js → index-BVcOAKar.js} +0 -0
  171. /package/esm/{style-inject.es-1f59c1d0.js → style-inject.es-tgCJW-Cu.js} +0 -0
  172. /package/esm/{uniqueId-fe08534a.js → uniqueId-DK6xzFd8.js} +0 -0
@@ -1,3192 +0,0 @@
1
- import { getCurrentInstance, inject, warn as warn$1, ref, unref, computed, reactive, watch, nextTick, onUnmounted, onMounted, provide, isRef, onBeforeUnmount, defineComponent, toRef, resolveDynamicComponent, h, markRaw, watchEffect, readonly } from 'vue';
2
-
3
- function getDevtoolsGlobalHook() {
4
- return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
5
- }
6
- function getTarget() {
7
- // @ts-ignore
8
- return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
9
- ? window
10
- : typeof global !== 'undefined'
11
- ? global
12
- : {};
13
- }
14
- const isProxyAvailable = typeof Proxy === 'function';
15
-
16
- const HOOK_SETUP = 'devtools-plugin:setup';
17
- const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
18
-
19
- let supported;
20
- let perf;
21
- function isPerformanceSupported() {
22
- var _a;
23
- if (supported !== undefined) {
24
- return supported;
25
- }
26
- if (typeof window !== 'undefined' && window.performance) {
27
- supported = true;
28
- perf = window.performance;
29
- }
30
- else if (typeof global !== 'undefined' && ((_a = global.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
31
- supported = true;
32
- perf = global.perf_hooks.performance;
33
- }
34
- else {
35
- supported = false;
36
- }
37
- return supported;
38
- }
39
- function now() {
40
- return isPerformanceSupported() ? perf.now() : Date.now();
41
- }
42
-
43
- class ApiProxy {
44
- constructor(plugin, hook) {
45
- this.target = null;
46
- this.targetQueue = [];
47
- this.onQueue = [];
48
- this.plugin = plugin;
49
- this.hook = hook;
50
- const defaultSettings = {};
51
- if (plugin.settings) {
52
- for (const id in plugin.settings) {
53
- const item = plugin.settings[id];
54
- defaultSettings[id] = item.defaultValue;
55
- }
56
- }
57
- const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
58
- let currentSettings = Object.assign({}, defaultSettings);
59
- try {
60
- const raw = localStorage.getItem(localSettingsSaveId);
61
- const data = JSON.parse(raw);
62
- Object.assign(currentSettings, data);
63
- }
64
- catch (e) {
65
- // noop
66
- }
67
- this.fallbacks = {
68
- getSettings() {
69
- return currentSettings;
70
- },
71
- setSettings(value) {
72
- try {
73
- localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
74
- }
75
- catch (e) {
76
- // noop
77
- }
78
- currentSettings = value;
79
- },
80
- now() {
81
- return now();
82
- },
83
- };
84
- if (hook) {
85
- hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
86
- if (pluginId === this.plugin.id) {
87
- this.fallbacks.setSettings(value);
88
- }
89
- });
90
- }
91
- this.proxiedOn = new Proxy({}, {
92
- get: (_target, prop) => {
93
- if (this.target) {
94
- return this.target.on[prop];
95
- }
96
- else {
97
- return (...args) => {
98
- this.onQueue.push({
99
- method: prop,
100
- args,
101
- });
102
- };
103
- }
104
- },
105
- });
106
- this.proxiedTarget = new Proxy({}, {
107
- get: (_target, prop) => {
108
- if (this.target) {
109
- return this.target[prop];
110
- }
111
- else if (prop === 'on') {
112
- return this.proxiedOn;
113
- }
114
- else if (Object.keys(this.fallbacks).includes(prop)) {
115
- return (...args) => {
116
- this.targetQueue.push({
117
- method: prop,
118
- args,
119
- resolve: () => { },
120
- });
121
- return this.fallbacks[prop](...args);
122
- };
123
- }
124
- else {
125
- return (...args) => {
126
- return new Promise(resolve => {
127
- this.targetQueue.push({
128
- method: prop,
129
- args,
130
- resolve,
131
- });
132
- });
133
- };
134
- }
135
- },
136
- });
137
- }
138
- async setRealTarget(target) {
139
- this.target = target;
140
- for (const item of this.onQueue) {
141
- this.target.on[item.method](...item.args);
142
- }
143
- for (const item of this.targetQueue) {
144
- item.resolve(await this.target[item.method](...item.args));
145
- }
146
- }
147
- }
148
-
149
- function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
150
- const descriptor = pluginDescriptor;
151
- const target = getTarget();
152
- const hook = getDevtoolsGlobalHook();
153
- const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
154
- if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
155
- hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
156
- }
157
- else {
158
- const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
159
- const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
160
- list.push({
161
- pluginDescriptor: descriptor,
162
- setupFn,
163
- proxy,
164
- });
165
- if (proxy)
166
- setupFn(proxy.proxiedTarget);
167
- }
168
- }
169
-
170
- /**
171
- * vee-validate v4.5.11
172
- * (c) 2022 Abdelrahman Awad
173
- * @license MIT
174
- */
175
-
176
- function isCallable(fn) {
177
- return typeof fn === 'function';
178
- }
179
- function isNullOrUndefined(value) {
180
- return value === null || value === undefined;
181
- }
182
- const isObject = (obj) => obj !== null && !!obj && typeof obj === 'object' && !Array.isArray(obj);
183
- function isIndex(value) {
184
- return Number(value) >= 0;
185
- }
186
- function toNumber(value) {
187
- const n = parseFloat(value);
188
- return isNaN(n) ? value : n;
189
- }
190
-
191
- const RULES = {};
192
- /**
193
- * Adds a custom validator to the list of validation rules.
194
- */
195
- function defineRule(id, validator) {
196
- // makes sure new rules are properly formatted.
197
- guardExtend(id, validator);
198
- RULES[id] = validator;
199
- }
200
- /**
201
- * Gets an already defined rule
202
- */
203
- function resolveRule(id) {
204
- return RULES[id];
205
- }
206
- /**
207
- * Guards from extension violations.
208
- */
209
- function guardExtend(id, validator) {
210
- if (isCallable(validator)) {
211
- return;
212
- }
213
- throw new Error(`Extension Error: The validator '${id}' must be a function.`);
214
- }
215
-
216
- const FormContextKey = Symbol('vee-validate-form');
217
- const FieldContextKey = Symbol('vee-validate-field-instance');
218
- const IS_ABSENT = Symbol('Default empty value');
219
-
220
- function isLocator(value) {
221
- return isCallable(value) && !!value.__locatorRef;
222
- }
223
- /**
224
- * Checks if an tag name is a native HTML tag and not a Vue component
225
- */
226
- function isHTMLTag(tag) {
227
- return ['input', 'textarea', 'select'].includes(tag);
228
- }
229
- /**
230
- * Checks if an input is of type file
231
- */
232
- function isFileInputNode(tag, attrs) {
233
- return isHTMLTag(tag) && attrs.type === 'file';
234
- }
235
- function isYupValidator(value) {
236
- return !!value && isCallable(value.validate);
237
- }
238
- function hasCheckedAttr(type) {
239
- return type === 'checkbox' || type === 'radio';
240
- }
241
- function isContainerValue(value) {
242
- return isObject(value) || Array.isArray(value);
243
- }
244
- /**
245
- * True if the value is an empty object or array
246
- */
247
- function isEmptyContainer(value) {
248
- if (Array.isArray(value)) {
249
- return value.length === 0;
250
- }
251
- return isObject(value) && Object.keys(value).length === 0;
252
- }
253
- /**
254
- * Checks if the path opted out of nested fields using `[fieldName]` syntax
255
- */
256
- function isNotNestedPath(path) {
257
- return /^\[.+\]$/i.test(path);
258
- }
259
- /**
260
- * Checks if an element is a native HTML5 multi-select input element
261
- */
262
- function isNativeMultiSelect(el) {
263
- return isNativeSelect(el) && el.multiple;
264
- }
265
- /**
266
- * Checks if an element is a native HTML5 select input element
267
- */
268
- function isNativeSelect(el) {
269
- return el.tagName === 'SELECT';
270
- }
271
- /**
272
- * Checks if a tag name with attrs object will render a native multi-select element
273
- */
274
- function isNativeMultiSelectNode(tag, attrs) {
275
- // The falsy value array is the values that Vue won't add the `multiple` prop if it has one of these values
276
- const hasTruthyBindingValue = ![false, null, undefined, 0].includes(attrs.multiple) && !Number.isNaN(attrs.multiple);
277
- return tag === 'select' && 'multiple' in attrs && hasTruthyBindingValue;
278
- }
279
- /**
280
- * Checks if a node should have a `:value` binding or not
281
- *
282
- * These nodes should not have a value binding
283
- * For files, because they are not reactive
284
- * For multi-selects because the value binding will reset the value
285
- */
286
- function shouldHaveValueBinding(tag, attrs) {
287
- return isNativeMultiSelectNode(tag, attrs) || isFileInputNode(tag, attrs);
288
- }
289
- function isFormSubmitEvent(evt) {
290
- return isEvent(evt) && evt.target && 'submit' in evt.target;
291
- }
292
- function isEvent(evt) {
293
- if (!evt) {
294
- return false;
295
- }
296
- if (typeof Event !== 'undefined' && isCallable(Event) && evt instanceof Event) {
297
- return true;
298
- }
299
- // this is for IE and Cypress #3161
300
- /* istanbul ignore next */
301
- if (evt && evt.srcElement) {
302
- return true;
303
- }
304
- return false;
305
- }
306
- function isPropPresent(obj, prop) {
307
- return prop in obj && obj[prop] !== IS_ABSENT;
308
- }
309
-
310
- function cleanupNonNestedPath(path) {
311
- if (isNotNestedPath(path)) {
312
- return path.replace(/\[|\]/gi, '');
313
- }
314
- return path;
315
- }
316
- function getFromPath(object, path, fallback) {
317
- if (!object) {
318
- return fallback;
319
- }
320
- if (isNotNestedPath(path)) {
321
- return object[cleanupNonNestedPath(path)];
322
- }
323
- const resolvedValue = (path || '')
324
- .split(/\.|\[(\d+)\]/)
325
- .filter(Boolean)
326
- .reduce((acc, propKey) => {
327
- if (isContainerValue(acc) && propKey in acc) {
328
- return acc[propKey];
329
- }
330
- return fallback;
331
- }, object);
332
- return resolvedValue;
333
- }
334
- /**
335
- * Sets a nested property value in a path, creates the path properties if it doesn't exist
336
- */
337
- function setInPath(object, path, value) {
338
- if (isNotNestedPath(path)) {
339
- object[cleanupNonNestedPath(path)] = value;
340
- return;
341
- }
342
- const keys = path.split(/\.|\[(\d+)\]/).filter(Boolean);
343
- let acc = object;
344
- for (let i = 0; i < keys.length; i++) {
345
- // Last key, set it
346
- if (i === keys.length - 1) {
347
- acc[keys[i]] = value;
348
- return;
349
- }
350
- // Key does not exist, create a container for it
351
- if (!(keys[i] in acc) || isNullOrUndefined(acc[keys[i]])) {
352
- // container can be either an object or an array depending on the next key if it exists
353
- acc[keys[i]] = isIndex(keys[i + 1]) ? [] : {};
354
- }
355
- acc = acc[keys[i]];
356
- }
357
- }
358
- function unset(object, key) {
359
- if (Array.isArray(object) && isIndex(key)) {
360
- object.splice(Number(key), 1);
361
- return;
362
- }
363
- if (isObject(object)) {
364
- delete object[key];
365
- }
366
- }
367
- /**
368
- * Removes a nested property from object
369
- */
370
- function unsetPath(object, path) {
371
- if (isNotNestedPath(path)) {
372
- delete object[cleanupNonNestedPath(path)];
373
- return;
374
- }
375
- const keys = path.split(/\.|\[(\d+)\]/).filter(Boolean);
376
- let acc = object;
377
- for (let i = 0; i < keys.length; i++) {
378
- // Last key, unset it
379
- if (i === keys.length - 1) {
380
- unset(acc, keys[i]);
381
- break;
382
- }
383
- // Key does not exist, exit
384
- if (!(keys[i] in acc) || isNullOrUndefined(acc[keys[i]])) {
385
- break;
386
- }
387
- acc = acc[keys[i]];
388
- }
389
- const pathValues = keys.map((_, idx) => {
390
- return getFromPath(object, keys.slice(0, idx).join('.'));
391
- });
392
- for (let i = pathValues.length - 1; i >= 0; i--) {
393
- if (!isEmptyContainer(pathValues[i])) {
394
- continue;
395
- }
396
- if (i === 0) {
397
- unset(object, keys[0]);
398
- continue;
399
- }
400
- unset(pathValues[i - 1], keys[i - 1]);
401
- }
402
- }
403
- /**
404
- * A typed version of Object.keys
405
- */
406
- function keysOf(record) {
407
- return Object.keys(record);
408
- }
409
- // Uses same component provide as its own injections
410
- // Due to changes in https://github.com/vuejs/vue-next/pull/2424
411
- function injectWithSelf(symbol, def = undefined) {
412
- const vm = getCurrentInstance();
413
- return (vm === null || vm === void 0 ? void 0 : vm.provides[symbol]) || inject(symbol, def);
414
- }
415
- function warn(message) {
416
- warn$1(`[vee-validate]: ${message}`);
417
- }
418
- /**
419
- * Ensures we deal with a singular field value
420
- */
421
- function normalizeField(field) {
422
- if (Array.isArray(field)) {
423
- return field[0];
424
- }
425
- return field;
426
- }
427
- function resolveNextCheckboxValue(currentValue, checkedValue, uncheckedValue) {
428
- if (Array.isArray(currentValue)) {
429
- const newVal = [...currentValue];
430
- const idx = newVal.indexOf(checkedValue);
431
- idx >= 0 ? newVal.splice(idx, 1) : newVal.push(checkedValue);
432
- return newVal;
433
- }
434
- return currentValue === checkedValue ? uncheckedValue : checkedValue;
435
- }
436
- /**
437
- * Creates a throttled function that only invokes the provided function (`func`) at most once per within a given number of milliseconds
438
- * (`limit`)
439
- */
440
- function throttle(func, limit) {
441
- let inThrottle;
442
- let lastResult;
443
- return function (...args) {
444
- // eslint-disable-next-line @typescript-eslint/no-this-alias
445
- const context = this;
446
- if (!inThrottle) {
447
- inThrottle = true;
448
- setTimeout(() => (inThrottle = false), limit);
449
- lastResult = func.apply(context, args);
450
- }
451
- return lastResult;
452
- };
453
- }
454
- function debounceAsync(inner, ms = 0) {
455
- let timer = null;
456
- let resolves = [];
457
- return function (...args) {
458
- // Run the function after a certain amount of time
459
- if (timer) {
460
- window.clearTimeout(timer);
461
- }
462
- timer = window.setTimeout(() => {
463
- // Get the result of the inner function, then apply it to the resolve function of
464
- // each promise that has been created since the last time the inner function was run
465
- const result = inner(...args);
466
- resolves.forEach(r => r(result));
467
- resolves = [];
468
- }, ms);
469
- return new Promise(resolve => resolves.push(resolve));
470
- };
471
- }
472
-
473
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
474
- const normalizeChildren = (tag, context, slotProps) => {
475
- if (!context.slots.default) {
476
- return context.slots.default;
477
- }
478
- if (typeof tag === 'string' || !tag) {
479
- return context.slots.default(slotProps());
480
- }
481
- return {
482
- default: () => { var _a, _b; return (_b = (_a = context.slots).default) === null || _b === void 0 ? void 0 : _b.call(_a, slotProps()); },
483
- };
484
- };
485
- /**
486
- * Vue adds a `_value` prop at the moment on the input elements to store the REAL value on them, real values are different than the `value` attribute
487
- * as they do not get casted to strings unlike `el.value` which preserves user-code behavior
488
- */
489
- function getBoundValue(el) {
490
- if (hasValueBinding(el)) {
491
- return el._value;
492
- }
493
- return undefined;
494
- }
495
- /**
496
- * Vue adds a `_value` prop at the moment on the input elements to store the REAL value on them, real values are different than the `value` attribute
497
- * as they do not get casted to strings unlike `el.value` which preserves user-code behavior
498
- */
499
- function hasValueBinding(el) {
500
- return '_value' in el;
501
- }
502
-
503
- function normalizeEventValue(value) {
504
- if (!isEvent(value)) {
505
- return value;
506
- }
507
- const input = value.target;
508
- // Vue sets the current bound value on `_value` prop
509
- // for checkboxes it it should fetch the value binding type as is (boolean instead of string)
510
- if (hasCheckedAttr(input.type) && hasValueBinding(input)) {
511
- return getBoundValue(input);
512
- }
513
- if (input.type === 'file' && input.files) {
514
- return Array.from(input.files);
515
- }
516
- if (isNativeMultiSelect(input)) {
517
- return Array.from(input.options)
518
- .filter(opt => opt.selected && !opt.disabled)
519
- .map(getBoundValue);
520
- }
521
- // makes sure we get the actual `option` bound value
522
- // #3440
523
- if (isNativeSelect(input)) {
524
- const selectedOption = Array.from(input.options).find(opt => opt.selected);
525
- return selectedOption ? getBoundValue(selectedOption) : input.value;
526
- }
527
- return input.value;
528
- }
529
-
530
- /**
531
- * Normalizes the given rules expression.
532
- */
533
- function normalizeRules(rules) {
534
- const acc = {};
535
- Object.defineProperty(acc, '_$$isNormalized', {
536
- value: true,
537
- writable: false,
538
- enumerable: false,
539
- configurable: false,
540
- });
541
- if (!rules) {
542
- return acc;
543
- }
544
- // Object is already normalized, skip.
545
- if (isObject(rules) && rules._$$isNormalized) {
546
- return rules;
547
- }
548
- if (isObject(rules)) {
549
- return Object.keys(rules).reduce((prev, curr) => {
550
- const params = normalizeParams(rules[curr]);
551
- if (rules[curr] !== false) {
552
- prev[curr] = buildParams(params);
553
- }
554
- return prev;
555
- }, acc);
556
- }
557
- /* istanbul ignore if */
558
- if (typeof rules !== 'string') {
559
- return acc;
560
- }
561
- return rules.split('|').reduce((prev, rule) => {
562
- const parsedRule = parseRule(rule);
563
- if (!parsedRule.name) {
564
- return prev;
565
- }
566
- prev[parsedRule.name] = buildParams(parsedRule.params);
567
- return prev;
568
- }, acc);
569
- }
570
- /**
571
- * Normalizes a rule param.
572
- */
573
- function normalizeParams(params) {
574
- if (params === true) {
575
- return [];
576
- }
577
- if (Array.isArray(params)) {
578
- return params;
579
- }
580
- if (isObject(params)) {
581
- return params;
582
- }
583
- return [params];
584
- }
585
- function buildParams(provided) {
586
- const mapValueToLocator = (value) => {
587
- // A target param using interpolation
588
- if (typeof value === 'string' && value[0] === '@') {
589
- return createLocator(value.slice(1));
590
- }
591
- return value;
592
- };
593
- if (Array.isArray(provided)) {
594
- return provided.map(mapValueToLocator);
595
- }
596
- // #3073
597
- if (provided instanceof RegExp) {
598
- return [provided];
599
- }
600
- return Object.keys(provided).reduce((prev, key) => {
601
- prev[key] = mapValueToLocator(provided[key]);
602
- return prev;
603
- }, {});
604
- }
605
- /**
606
- * Parses a rule string expression.
607
- */
608
- const parseRule = (rule) => {
609
- let params = [];
610
- const name = rule.split(':')[0];
611
- if (rule.includes(':')) {
612
- params = rule.split(':').slice(1).join(':').split(',');
613
- }
614
- return { name, params };
615
- };
616
- function createLocator(value) {
617
- const locator = (crossTable) => {
618
- const val = getFromPath(crossTable, value) || crossTable[value];
619
- return val;
620
- };
621
- locator.__locatorRef = value;
622
- return locator;
623
- }
624
- function extractLocators(params) {
625
- if (Array.isArray(params)) {
626
- return params.filter(isLocator);
627
- }
628
- return keysOf(params)
629
- .filter(key => isLocator(params[key]))
630
- .map(key => params[key]);
631
- }
632
-
633
- const DEFAULT_CONFIG = {
634
- generateMessage: ({ field }) => `${field} is not valid.`,
635
- bails: true,
636
- validateOnBlur: true,
637
- validateOnChange: true,
638
- validateOnInput: false,
639
- validateOnModelUpdate: true,
640
- };
641
- let currentConfig = Object.assign({}, DEFAULT_CONFIG);
642
- const getConfig = () => currentConfig;
643
- const setConfig = (newConf) => {
644
- currentConfig = Object.assign(Object.assign({}, currentConfig), newConf);
645
- };
646
- const configure = setConfig;
647
-
648
- /**
649
- * Validates a value against the rules.
650
- */
651
- async function validate(value, rules, options = {}) {
652
- const shouldBail = options === null || options === void 0 ? void 0 : options.bails;
653
- const field = {
654
- name: (options === null || options === void 0 ? void 0 : options.name) || '{field}',
655
- rules,
656
- bails: shouldBail !== null && shouldBail !== void 0 ? shouldBail : true,
657
- formData: (options === null || options === void 0 ? void 0 : options.values) || {},
658
- };
659
- const result = await _validate(field, value);
660
- const errors = result.errors;
661
- return {
662
- errors,
663
- valid: !errors.length,
664
- };
665
- }
666
- /**
667
- * Starts the validation process.
668
- */
669
- async function _validate(field, value) {
670
- if (isYupValidator(field.rules)) {
671
- return validateFieldWithYup(value, field.rules, { bails: field.bails });
672
- }
673
- // if a generic function or chain of generic functions
674
- if (isCallable(field.rules) || Array.isArray(field.rules)) {
675
- const ctx = {
676
- field: field.name,
677
- form: field.formData,
678
- value: value,
679
- };
680
- // Normalize the pipeline
681
- const pipeline = Array.isArray(field.rules) ? field.rules : [field.rules];
682
- const length = pipeline.length;
683
- const errors = [];
684
- for (let i = 0; i < length; i++) {
685
- const rule = pipeline[i];
686
- const result = await rule(value, ctx);
687
- const isValid = typeof result !== 'string' && result;
688
- if (isValid) {
689
- continue;
690
- }
691
- const message = typeof result === 'string' ? result : _generateFieldError(ctx);
692
- errors.push(message);
693
- if (field.bails) {
694
- return {
695
- errors,
696
- };
697
- }
698
- }
699
- return {
700
- errors,
701
- };
702
- }
703
- const normalizedContext = Object.assign(Object.assign({}, field), { rules: normalizeRules(field.rules) });
704
- const errors = [];
705
- const rulesKeys = Object.keys(normalizedContext.rules);
706
- const length = rulesKeys.length;
707
- for (let i = 0; i < length; i++) {
708
- const rule = rulesKeys[i];
709
- const result = await _test(normalizedContext, value, {
710
- name: rule,
711
- params: normalizedContext.rules[rule],
712
- });
713
- if (result.error) {
714
- errors.push(result.error);
715
- if (field.bails) {
716
- return {
717
- errors,
718
- };
719
- }
720
- }
721
- }
722
- return {
723
- errors,
724
- };
725
- }
726
- /**
727
- * Handles yup validation
728
- */
729
- async function validateFieldWithYup(value, validator, opts) {
730
- var _a;
731
- const errors = await validator
732
- .validate(value, {
733
- abortEarly: (_a = opts.bails) !== null && _a !== void 0 ? _a : true,
734
- })
735
- .then(() => [])
736
- .catch((err) => {
737
- // Yup errors have a name prop one them.
738
- // https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string
739
- if (err.name === 'ValidationError') {
740
- return err.errors;
741
- }
742
- // re-throw the error so we don't hide it
743
- throw err;
744
- });
745
- return {
746
- errors,
747
- };
748
- }
749
- /**
750
- * Tests a single input value against a rule.
751
- */
752
- async function _test(field, value, rule) {
753
- const validator = resolveRule(rule.name);
754
- if (!validator) {
755
- throw new Error(`No such validator '${rule.name}' exists.`);
756
- }
757
- const params = fillTargetValues(rule.params, field.formData);
758
- const ctx = {
759
- field: field.name,
760
- value,
761
- form: field.formData,
762
- rule: Object.assign(Object.assign({}, rule), { params }),
763
- };
764
- const result = await validator(value, params, ctx);
765
- if (typeof result === 'string') {
766
- return {
767
- error: result,
768
- };
769
- }
770
- return {
771
- error: result ? undefined : _generateFieldError(ctx),
772
- };
773
- }
774
- /**
775
- * Generates error messages.
776
- */
777
- function _generateFieldError(fieldCtx) {
778
- const message = getConfig().generateMessage;
779
- if (!message) {
780
- return 'Field is invalid';
781
- }
782
- return message(fieldCtx);
783
- }
784
- function fillTargetValues(params, crossTable) {
785
- const normalize = (value) => {
786
- if (isLocator(value)) {
787
- return value(crossTable);
788
- }
789
- return value;
790
- };
791
- if (Array.isArray(params)) {
792
- return params.map(normalize);
793
- }
794
- return Object.keys(params).reduce((acc, param) => {
795
- acc[param] = normalize(params[param]);
796
- return acc;
797
- }, {});
798
- }
799
- async function validateYupSchema(schema, values) {
800
- const errorObjects = await schema
801
- .validate(values, { abortEarly: false })
802
- .then(() => [])
803
- .catch((err) => {
804
- // Yup errors have a name prop one them.
805
- // https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string
806
- if (err.name !== 'ValidationError') {
807
- throw err;
808
- }
809
- // list of aggregated errors
810
- return err.inner || [];
811
- });
812
- const results = {};
813
- const errors = {};
814
- for (const error of errorObjects) {
815
- const messages = error.errors;
816
- results[error.path] = { valid: !messages.length, errors: messages };
817
- if (messages.length) {
818
- errors[error.path] = messages[0];
819
- }
820
- }
821
- return {
822
- valid: !errorObjects.length,
823
- results,
824
- errors,
825
- };
826
- }
827
- async function validateObjectSchema(schema, values, opts) {
828
- const paths = keysOf(schema);
829
- const validations = paths.map(async (path) => {
830
- var _a, _b, _c;
831
- const fieldResult = await validate(getFromPath(values, path), schema[path], {
832
- name: ((_a = opts === null || opts === void 0 ? void 0 : opts.names) === null || _a === void 0 ? void 0 : _a[path]) || path,
833
- values: values,
834
- bails: (_c = (_b = opts === null || opts === void 0 ? void 0 : opts.bailsMap) === null || _b === void 0 ? void 0 : _b[path]) !== null && _c !== void 0 ? _c : true,
835
- });
836
- return Object.assign(Object.assign({}, fieldResult), { path });
837
- });
838
- let isAllValid = true;
839
- const validationResults = await Promise.all(validations);
840
- const results = {};
841
- const errors = {};
842
- for (const result of validationResults) {
843
- results[result.path] = {
844
- valid: result.valid,
845
- errors: result.errors,
846
- };
847
- if (!result.valid) {
848
- isAllValid = false;
849
- errors[result.path] = result.errors[0];
850
- }
851
- }
852
- return {
853
- valid: isAllValid,
854
- results,
855
- errors,
856
- };
857
- }
858
-
859
- function set(obj, key, val) {
860
- if (typeof val.value === 'object') val.value = klona(val.value);
861
- if (!val.enumerable || val.get || val.set || !val.configurable || !val.writable || key === '__proto__') {
862
- Object.defineProperty(obj, key, val);
863
- } else obj[key] = val.value;
864
- }
865
-
866
- function klona(x) {
867
- if (typeof x !== 'object') return x;
868
-
869
- var i=0, k, list, tmp, str=Object.prototype.toString.call(x);
870
-
871
- if (str === '[object Object]') {
872
- tmp = Object.create(x.__proto__ || null);
873
- } else if (str === '[object Array]') {
874
- tmp = Array(x.length);
875
- } else if (str === '[object Set]') {
876
- tmp = new Set;
877
- x.forEach(function (val) {
878
- tmp.add(klona(val));
879
- });
880
- } else if (str === '[object Map]') {
881
- tmp = new Map;
882
- x.forEach(function (val, key) {
883
- tmp.set(klona(key), klona(val));
884
- });
885
- } else if (str === '[object Date]') {
886
- tmp = new Date(+x);
887
- } else if (str === '[object RegExp]') {
888
- tmp = new RegExp(x.source, x.flags);
889
- } else if (str === '[object DataView]') {
890
- tmp = new x.constructor( klona(x.buffer) );
891
- } else if (str === '[object ArrayBuffer]') {
892
- tmp = x.slice(0);
893
- } else if (str.slice(-6) === 'Array]') {
894
- // ArrayBuffer.isView(x)
895
- // ~> `new` bcuz `Buffer.slice` => ref
896
- tmp = new x.constructor(x);
897
- }
898
-
899
- if (tmp) {
900
- for (list=Object.getOwnPropertySymbols(x); i < list.length; i++) {
901
- set(tmp, list[i], Object.getOwnPropertyDescriptor(x, list[i]));
902
- }
903
-
904
- for (i=0, list=Object.getOwnPropertyNames(x); i < list.length; i++) {
905
- if (Object.hasOwnProperty.call(tmp, k=list[i]) && tmp[k] === x[k]) continue;
906
- set(tmp, k, Object.getOwnPropertyDescriptor(x, k));
907
- }
908
- }
909
-
910
- return tmp || x;
911
- }
912
-
913
- var es6 = function equal(a, b) {
914
- if (a === b) return true;
915
-
916
- if (a && b && typeof a == 'object' && typeof b == 'object') {
917
- if (a.constructor !== b.constructor) return false;
918
-
919
- var length, i, keys;
920
- if (Array.isArray(a)) {
921
- length = a.length;
922
- if (length != b.length) return false;
923
- for (i = length; i-- !== 0;)
924
- if (!equal(a[i], b[i])) return false;
925
- return true;
926
- }
927
-
928
-
929
- if ((a instanceof Map) && (b instanceof Map)) {
930
- if (a.size !== b.size) return false;
931
- for (i of a.entries())
932
- if (!b.has(i[0])) return false;
933
- for (i of a.entries())
934
- if (!equal(i[1], b.get(i[0]))) return false;
935
- return true;
936
- }
937
-
938
- if ((a instanceof Set) && (b instanceof Set)) {
939
- if (a.size !== b.size) return false;
940
- for (i of a.entries())
941
- if (!b.has(i[0])) return false;
942
- return true;
943
- }
944
-
945
- if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
946
- length = a.length;
947
- if (length != b.length) return false;
948
- for (i = length; i-- !== 0;)
949
- if (a[i] !== b[i]) return false;
950
- return true;
951
- }
952
-
953
-
954
- if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
955
- if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
956
- if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
957
-
958
- keys = Object.keys(a);
959
- length = keys.length;
960
- if (length !== Object.keys(b).length) return false;
961
-
962
- for (i = length; i-- !== 0;)
963
- if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
964
-
965
- for (i = length; i-- !== 0;) {
966
- var key = keys[i];
967
-
968
- if (!equal(a[key], b[key])) return false;
969
- }
970
-
971
- return true;
972
- }
973
-
974
- // true if both NaN, false otherwise
975
- return a!==a && b!==b;
976
- };
977
-
978
- let ID_COUNTER = 0;
979
- function useFieldState(path, init) {
980
- const { value, initialValue, setInitialValue } = _useFieldValue(path, init.modelValue, !init.standalone);
981
- const { errorMessage, errors, setErrors } = _useFieldErrors(path, !init.standalone);
982
- const meta = _useFieldMeta(value, initialValue, errors);
983
- const id = ID_COUNTER >= Number.MAX_SAFE_INTEGER ? 0 : ++ID_COUNTER;
984
- function setState(state) {
985
- var _a;
986
- if ('value' in state) {
987
- value.value = state.value;
988
- }
989
- if ('errors' in state) {
990
- setErrors(state.errors);
991
- }
992
- if ('touched' in state) {
993
- meta.touched = (_a = state.touched) !== null && _a !== void 0 ? _a : meta.touched;
994
- }
995
- if ('initialValue' in state) {
996
- setInitialValue(state.initialValue);
997
- }
998
- }
999
- return {
1000
- id,
1001
- path,
1002
- value,
1003
- initialValue,
1004
- meta,
1005
- errors,
1006
- errorMessage,
1007
- setState,
1008
- };
1009
- }
1010
- /**
1011
- * Creates the field value and resolves the initial value
1012
- */
1013
- function _useFieldValue(path, modelValue, shouldInjectForm) {
1014
- const form = shouldInjectForm ? injectWithSelf(FormContextKey, undefined) : undefined;
1015
- const modelRef = ref(unref(modelValue));
1016
- function resolveInitialValue() {
1017
- if (!form) {
1018
- return unref(modelRef);
1019
- }
1020
- return getFromPath(form.meta.value.initialValues, unref(path), unref(modelRef));
1021
- }
1022
- function setInitialValue(value) {
1023
- if (!form) {
1024
- modelRef.value = value;
1025
- return;
1026
- }
1027
- form.setFieldInitialValue(unref(path), value);
1028
- }
1029
- const initialValue = computed(resolveInitialValue);
1030
- // if no form is associated, use a regular ref.
1031
- if (!form) {
1032
- const value = ref(resolveInitialValue());
1033
- return {
1034
- value,
1035
- initialValue,
1036
- setInitialValue,
1037
- };
1038
- }
1039
- // to set the initial value, first check if there is a current value, if there is then use it.
1040
- // otherwise use the configured initial value if it exists.
1041
- // prioritize model value over form values
1042
- // #3429
1043
- const currentValue = modelValue ? unref(modelValue) : getFromPath(form.values, unref(path), unref(initialValue));
1044
- form.stageInitialValue(unref(path), currentValue);
1045
- // otherwise use a computed setter that triggers the `setFieldValue`
1046
- const value = computed({
1047
- get() {
1048
- return getFromPath(form.values, unref(path));
1049
- },
1050
- set(newVal) {
1051
- form.setFieldValue(unref(path), newVal);
1052
- },
1053
- });
1054
- return {
1055
- value,
1056
- initialValue,
1057
- setInitialValue,
1058
- };
1059
- }
1060
- /**
1061
- * Creates meta flags state and some associated effects with them
1062
- */
1063
- function _useFieldMeta(currentValue, initialValue, errors) {
1064
- const meta = reactive({
1065
- touched: false,
1066
- pending: false,
1067
- valid: true,
1068
- validated: !!unref(errors).length,
1069
- initialValue: computed(() => unref(initialValue)),
1070
- dirty: computed(() => {
1071
- return !es6(unref(currentValue), unref(initialValue));
1072
- }),
1073
- });
1074
- watch(errors, value => {
1075
- meta.valid = !value.length;
1076
- }, {
1077
- immediate: true,
1078
- flush: 'sync',
1079
- });
1080
- return meta;
1081
- }
1082
- /**
1083
- * Creates the error message state for the field state
1084
- */
1085
- function _useFieldErrors(path, shouldInjectForm) {
1086
- const form = shouldInjectForm ? injectWithSelf(FormContextKey, undefined) : undefined;
1087
- function normalizeErrors(messages) {
1088
- if (!messages) {
1089
- return [];
1090
- }
1091
- return Array.isArray(messages) ? messages : [messages];
1092
- }
1093
- if (!form) {
1094
- const errors = ref([]);
1095
- return {
1096
- errors,
1097
- errorMessage: computed(() => errors.value[0]),
1098
- setErrors: (messages) => {
1099
- errors.value = normalizeErrors(messages);
1100
- },
1101
- };
1102
- }
1103
- const errors = computed(() => form.errorBag.value[unref(path)] || []);
1104
- return {
1105
- errors,
1106
- errorMessage: computed(() => errors.value[0]),
1107
- setErrors: (messages) => {
1108
- form.setFieldErrorBag(unref(path), normalizeErrors(messages));
1109
- },
1110
- };
1111
- }
1112
-
1113
- function installDevtoolsPlugin(app) {
1114
- if (("production" !== 'production')) {
1115
- setupDevtoolsPlugin({
1116
- id: 'vee-validate-devtools-plugin',
1117
- label: 'VeeValidate Plugin',
1118
- packageName: 'vee-validate',
1119
- homepage: 'https://vee-validate.logaretm.com/v4',
1120
- app,
1121
- logo: 'https://vee-validate.logaretm.com/v4/logo.png',
1122
- }, setupApiHooks);
1123
- }
1124
- }
1125
- const DEVTOOLS_FORMS = {};
1126
- const DEVTOOLS_FIELDS = {};
1127
- let API;
1128
- const refreshInspector = throttle(() => {
1129
- setTimeout(async () => {
1130
- await nextTick();
1131
- API === null || API === void 0 ? void 0 : API.sendInspectorState(INSPECTOR_ID);
1132
- API === null || API === void 0 ? void 0 : API.sendInspectorTree(INSPECTOR_ID);
1133
- }, 100);
1134
- }, 100);
1135
- function registerFormWithDevTools(form) {
1136
- const vm = getCurrentInstance();
1137
- if (!API) {
1138
- const app = vm === null || vm === void 0 ? void 0 : vm.appContext.app;
1139
- if (!app) {
1140
- return;
1141
- }
1142
- installDevtoolsPlugin(app);
1143
- }
1144
- DEVTOOLS_FORMS[form.formId] = Object.assign({}, form);
1145
- DEVTOOLS_FORMS[form.formId]._vm = vm;
1146
- onUnmounted(() => {
1147
- delete DEVTOOLS_FORMS[form.formId];
1148
- refreshInspector();
1149
- });
1150
- refreshInspector();
1151
- }
1152
- function registerSingleFieldWithDevtools(field) {
1153
- const vm = getCurrentInstance();
1154
- if (!API) {
1155
- const app = vm === null || vm === void 0 ? void 0 : vm.appContext.app;
1156
- if (!app) {
1157
- return;
1158
- }
1159
- installDevtoolsPlugin(app);
1160
- }
1161
- DEVTOOLS_FIELDS[field.id] = Object.assign({}, field);
1162
- DEVTOOLS_FIELDS[field.id]._vm = vm;
1163
- onUnmounted(() => {
1164
- delete DEVTOOLS_FIELDS[field.id];
1165
- refreshInspector();
1166
- });
1167
- refreshInspector();
1168
- }
1169
- const INSPECTOR_ID = 'vee-validate-inspector';
1170
- const COLORS = {
1171
- error: 0xbd4b4b,
1172
- success: 0x06d77b,
1173
- unknown: 0x54436b,
1174
- white: 0xffffff,
1175
- black: 0x000000,
1176
- blue: 0x035397,
1177
- purple: 0xb980f0,
1178
- orange: 0xf5a962,
1179
- gray: 0xbbbfca,
1180
- };
1181
- let SELECTED_NODE = null;
1182
- function setupApiHooks(api) {
1183
- API = api;
1184
- api.addInspector({
1185
- id: INSPECTOR_ID,
1186
- icon: 'rule',
1187
- label: 'vee-validate',
1188
- noSelectionText: 'Select a vee-validate node to inspect',
1189
- actions: [
1190
- {
1191
- icon: 'done_outline',
1192
- tooltip: 'Validate selected item',
1193
- action: async () => {
1194
- if (!SELECTED_NODE) {
1195
- console.error('There is not a valid selected vee-validate node or component');
1196
- return;
1197
- }
1198
- const result = await SELECTED_NODE.validate();
1199
- console.log(result);
1200
- },
1201
- },
1202
- {
1203
- icon: 'delete_sweep',
1204
- tooltip: 'Clear validation state of the selected item',
1205
- action: () => {
1206
- if (!SELECTED_NODE) {
1207
- console.error('There is not a valid selected vee-validate node or component');
1208
- return;
1209
- }
1210
- if ('id' in SELECTED_NODE) {
1211
- SELECTED_NODE.resetField();
1212
- return;
1213
- }
1214
- SELECTED_NODE.resetForm();
1215
- },
1216
- },
1217
- ],
1218
- });
1219
- api.on.getInspectorTree(payload => {
1220
- if (payload.inspectorId !== INSPECTOR_ID) {
1221
- return;
1222
- }
1223
- const forms = Object.values(DEVTOOLS_FORMS);
1224
- const fields = Object.values(DEVTOOLS_FIELDS);
1225
- payload.rootNodes = [
1226
- ...forms.map(mapFormForDevtoolsInspector),
1227
- ...fields.map(field => mapFieldForDevtoolsInspector(field)),
1228
- ];
1229
- });
1230
- api.on.getInspectorState((payload, ctx) => {
1231
- if (payload.inspectorId !== INSPECTOR_ID || ctx.currentTab !== `custom-inspector:${INSPECTOR_ID}`) {
1232
- return;
1233
- }
1234
- const { form, field, type } = decodeNodeId(payload.nodeId);
1235
- if (form && type === 'form') {
1236
- payload.state = buildFormState(form);
1237
- SELECTED_NODE = form;
1238
- return;
1239
- }
1240
- if (field && type === 'field') {
1241
- payload.state = buildFieldState(field);
1242
- SELECTED_NODE = field;
1243
- return;
1244
- }
1245
- SELECTED_NODE = null;
1246
- });
1247
- }
1248
- function mapFormForDevtoolsInspector(form) {
1249
- const { textColor, bgColor } = getTagTheme(form);
1250
- const formTreeNodes = {};
1251
- Object.values(form.fieldsByPath.value).forEach(field => {
1252
- const fieldInstance = Array.isArray(field) ? field[0] : field;
1253
- if (!fieldInstance) {
1254
- return;
1255
- }
1256
- setInPath(formTreeNodes, unref(fieldInstance.name), mapFieldForDevtoolsInspector(fieldInstance, form));
1257
- });
1258
- function buildFormTree(tree, path = []) {
1259
- const key = [...path].pop();
1260
- if ('id' in tree) {
1261
- return Object.assign(Object.assign({}, tree), { label: key || tree.label });
1262
- }
1263
- if (isObject(tree)) {
1264
- return {
1265
- id: `${path.join('.')}`,
1266
- label: key || '',
1267
- children: Object.keys(tree).map(key => buildFormTree(tree[key], [...path, key])),
1268
- };
1269
- }
1270
- if (Array.isArray(tree)) {
1271
- return {
1272
- id: `${path.join('.')}`,
1273
- label: `${key}[]`,
1274
- children: tree.map((c, idx) => buildFormTree(c, [...path, String(idx)])),
1275
- };
1276
- }
1277
- return { id: '', label: '', children: [] };
1278
- }
1279
- const { children } = buildFormTree(formTreeNodes);
1280
- return {
1281
- id: encodeNodeId(form),
1282
- label: 'Form',
1283
- children,
1284
- tags: [
1285
- {
1286
- label: 'Form',
1287
- textColor,
1288
- backgroundColor: bgColor,
1289
- },
1290
- {
1291
- label: `${Object.keys(form.fieldsByPath.value).length} fields`,
1292
- textColor: COLORS.white,
1293
- backgroundColor: COLORS.unknown,
1294
- },
1295
- ],
1296
- };
1297
- }
1298
- function mapFieldForDevtoolsInspector(field, form) {
1299
- const fieldInstance = normalizeField(field);
1300
- const { textColor, bgColor } = getTagTheme(fieldInstance);
1301
- const isGroup = Array.isArray(field) && field.length > 1;
1302
- return {
1303
- id: encodeNodeId(form, fieldInstance, !isGroup),
1304
- label: unref(fieldInstance.name),
1305
- children: Array.isArray(field) ? field.map(fieldItem => mapFieldForDevtoolsInspector(fieldItem, form)) : undefined,
1306
- tags: [
1307
- isGroup
1308
- ? undefined
1309
- : {
1310
- label: 'Field',
1311
- textColor,
1312
- backgroundColor: bgColor,
1313
- },
1314
- !form
1315
- ? {
1316
- label: 'Standalone',
1317
- textColor: COLORS.black,
1318
- backgroundColor: COLORS.gray,
1319
- }
1320
- : undefined,
1321
- !isGroup && fieldInstance.type === 'checkbox'
1322
- ? {
1323
- label: 'Checkbox',
1324
- textColor: COLORS.white,
1325
- backgroundColor: COLORS.blue,
1326
- }
1327
- : undefined,
1328
- !isGroup && fieldInstance.type === 'radio'
1329
- ? {
1330
- label: 'Radio',
1331
- textColor: COLORS.white,
1332
- backgroundColor: COLORS.purple,
1333
- }
1334
- : undefined,
1335
- isGroup
1336
- ? {
1337
- label: 'Group',
1338
- textColor: COLORS.black,
1339
- backgroundColor: COLORS.orange,
1340
- }
1341
- : undefined,
1342
- ].filter(Boolean),
1343
- };
1344
- }
1345
- function encodeNodeId(form, field, encodeIndex = true) {
1346
- const fieldPath = form ? unref(field === null || field === void 0 ? void 0 : field.name) : field === null || field === void 0 ? void 0 : field.id;
1347
- const fieldGroup = fieldPath ? form === null || form === void 0 ? void 0 : form.fieldsByPath.value[fieldPath] : undefined;
1348
- let idx;
1349
- if (encodeIndex && field && Array.isArray(fieldGroup)) {
1350
- idx = fieldGroup.indexOf(field);
1351
- }
1352
- const idObject = { f: form === null || form === void 0 ? void 0 : form.formId, ff: fieldPath, idx, type: field ? 'field' : 'form' };
1353
- return btoa(JSON.stringify(idObject));
1354
- }
1355
- function decodeNodeId(nodeId) {
1356
- try {
1357
- const idObject = JSON.parse(atob(nodeId));
1358
- const form = DEVTOOLS_FORMS[idObject.f];
1359
- if (!form && idObject.ff) {
1360
- const field = DEVTOOLS_FIELDS[idObject.ff];
1361
- if (!field) {
1362
- return {};
1363
- }
1364
- return {
1365
- type: idObject.type,
1366
- field,
1367
- };
1368
- }
1369
- if (!form) {
1370
- return {};
1371
- }
1372
- const fieldGroup = form.fieldsByPath.value[idObject.ff];
1373
- return {
1374
- type: idObject.type,
1375
- form,
1376
- field: Array.isArray(fieldGroup) ? fieldGroup[idObject.idx || 0] : fieldGroup,
1377
- };
1378
- }
1379
- catch (err) {
1380
- // console.error(`Devtools: [vee-validate] Failed to parse node id ${nodeId}`);
1381
- }
1382
- return {};
1383
- }
1384
- function buildFieldState(field) {
1385
- const { errors, meta, value } = field;
1386
- return {
1387
- 'Field state': [
1388
- { key: 'errors', value: errors.value },
1389
- {
1390
- key: 'initialValue',
1391
- value: meta.initialValue,
1392
- },
1393
- {
1394
- key: 'currentValue',
1395
- value: value.value,
1396
- },
1397
- {
1398
- key: 'touched',
1399
- value: meta.touched,
1400
- },
1401
- {
1402
- key: 'dirty',
1403
- value: meta.dirty,
1404
- },
1405
- {
1406
- key: 'valid',
1407
- value: meta.valid,
1408
- },
1409
- ],
1410
- };
1411
- }
1412
- function buildFormState(form) {
1413
- const { errorBag, meta, values, isSubmitting, submitCount } = form;
1414
- return {
1415
- 'Form state': [
1416
- {
1417
- key: 'submitCount',
1418
- value: submitCount.value,
1419
- },
1420
- {
1421
- key: 'isSubmitting',
1422
- value: isSubmitting.value,
1423
- },
1424
- {
1425
- key: 'touched',
1426
- value: meta.value.touched,
1427
- },
1428
- {
1429
- key: 'dirty',
1430
- value: meta.value.dirty,
1431
- },
1432
- {
1433
- key: 'valid',
1434
- value: meta.value.valid,
1435
- },
1436
- {
1437
- key: 'initialValues',
1438
- value: meta.value.initialValues,
1439
- },
1440
- {
1441
- key: 'currentValues',
1442
- value: values,
1443
- },
1444
- {
1445
- key: 'errors',
1446
- value: keysOf(errorBag.value).reduce((acc, key) => {
1447
- var _a;
1448
- const message = (_a = errorBag.value[key]) === null || _a === void 0 ? void 0 : _a[0];
1449
- if (message) {
1450
- acc[key] = message;
1451
- }
1452
- return acc;
1453
- }, {}),
1454
- },
1455
- ],
1456
- };
1457
- }
1458
- /**
1459
- * Resolves the tag color based on the form state
1460
- */
1461
- function getTagTheme(fieldOrForm) {
1462
- // const fallbackColors = {
1463
- // bgColor: COLORS.unknown,
1464
- // textColor: COLORS.white,
1465
- // };
1466
- const isValid = 'id' in fieldOrForm ? fieldOrForm.meta.valid : fieldOrForm.meta.value.valid;
1467
- return {
1468
- bgColor: isValid ? COLORS.success : COLORS.error,
1469
- textColor: isValid ? COLORS.black : COLORS.white,
1470
- };
1471
- }
1472
-
1473
- /**
1474
- * Creates a field composite.
1475
- */
1476
- function useField(name, rules, opts) {
1477
- if (hasCheckedAttr(opts === null || opts === void 0 ? void 0 : opts.type)) {
1478
- return useCheckboxField(name, rules, opts);
1479
- }
1480
- return _useField(name, rules, opts);
1481
- }
1482
- function _useField(name, rules, opts) {
1483
- const { initialValue: modelValue, validateOnMount, bails, type, checkedValue, label, validateOnValueUpdate, uncheckedValue, standalone, } = normalizeOptions(unref(name), opts);
1484
- const form = !standalone ? injectWithSelf(FormContextKey) : undefined;
1485
- // a flag indicating if the field is about to be removed/unmounted.
1486
- let markedForRemoval = false;
1487
- const { id, value, initialValue, meta, setState, errors, errorMessage } = useFieldState(name, {
1488
- modelValue,
1489
- standalone,
1490
- });
1491
- /**
1492
- * Handles common onBlur meta update
1493
- */
1494
- const handleBlur = () => {
1495
- meta.touched = true;
1496
- };
1497
- const normalizedRules = computed(() => {
1498
- let rulesValue = unref(rules);
1499
- const schema = unref(form === null || form === void 0 ? void 0 : form.schema);
1500
- if (schema && !isYupValidator(schema)) {
1501
- rulesValue = extractRuleFromSchema(schema, unref(name)) || rulesValue;
1502
- }
1503
- if (isYupValidator(rulesValue) || isCallable(rulesValue) || Array.isArray(rulesValue)) {
1504
- return rulesValue;
1505
- }
1506
- return normalizeRules(rulesValue);
1507
- });
1508
- async function validateCurrentValue(mode) {
1509
- var _a, _b;
1510
- if (form === null || form === void 0 ? void 0 : form.validateSchema) {
1511
- return (_a = (await form.validateSchema(mode)).results[unref(name)]) !== null && _a !== void 0 ? _a : { valid: true, errors: [] };
1512
- }
1513
- return validate(value.value, normalizedRules.value, {
1514
- name: unref(label) || unref(name),
1515
- values: (_b = form === null || form === void 0 ? void 0 : form.values) !== null && _b !== void 0 ? _b : {},
1516
- bails,
1517
- });
1518
- }
1519
- async function validateWithStateMutation() {
1520
- meta.pending = true;
1521
- meta.validated = true;
1522
- const result = await validateCurrentValue('validated-only');
1523
- if (markedForRemoval) {
1524
- result.valid = true;
1525
- result.errors = [];
1526
- }
1527
- setState({ errors: result.errors });
1528
- meta.pending = false;
1529
- return result;
1530
- }
1531
- async function validateValidStateOnly() {
1532
- const result = await validateCurrentValue('silent');
1533
- if (markedForRemoval) {
1534
- result.valid = true;
1535
- }
1536
- meta.valid = result.valid;
1537
- return result;
1538
- }
1539
- function validate$1(opts) {
1540
- if (!(opts === null || opts === void 0 ? void 0 : opts.mode) || (opts === null || opts === void 0 ? void 0 : opts.mode) === 'force') {
1541
- return validateWithStateMutation();
1542
- }
1543
- if ((opts === null || opts === void 0 ? void 0 : opts.mode) === 'validated-only') {
1544
- return validateWithStateMutation();
1545
- }
1546
- return validateValidStateOnly();
1547
- }
1548
- // Common input/change event handler
1549
- const handleChange = (e, shouldValidate = true) => {
1550
- const newValue = normalizeEventValue(e);
1551
- value.value = newValue;
1552
- if (!validateOnValueUpdate && shouldValidate) {
1553
- validateWithStateMutation();
1554
- }
1555
- };
1556
- // Runs the initial validation
1557
- onMounted(() => {
1558
- if (validateOnMount) {
1559
- return validateWithStateMutation();
1560
- }
1561
- // validate self initially if no form was handling this
1562
- // forms should have their own initial silent validation run to make things more efficient
1563
- if (!form || !form.validateSchema) {
1564
- validateValidStateOnly();
1565
- }
1566
- });
1567
- function setTouched(isTouched) {
1568
- meta.touched = isTouched;
1569
- }
1570
- let unwatchValue;
1571
- function watchValue() {
1572
- unwatchValue = watch(value, validateOnValueUpdate ? validateWithStateMutation : validateValidStateOnly, {
1573
- deep: true,
1574
- });
1575
- }
1576
- watchValue();
1577
- function resetField(state) {
1578
- var _a;
1579
- unwatchValue === null || unwatchValue === void 0 ? void 0 : unwatchValue();
1580
- const newValue = state && 'value' in state ? state.value : initialValue.value;
1581
- setState({
1582
- value: klona(newValue),
1583
- initialValue: klona(newValue),
1584
- touched: (_a = state === null || state === void 0 ? void 0 : state.touched) !== null && _a !== void 0 ? _a : false,
1585
- errors: (state === null || state === void 0 ? void 0 : state.errors) || [],
1586
- });
1587
- meta.pending = false;
1588
- meta.validated = false;
1589
- validateValidStateOnly();
1590
- // need to watch at next tick to avoid triggering the value watcher
1591
- nextTick(() => {
1592
- watchValue();
1593
- });
1594
- }
1595
- function setValue(newValue) {
1596
- value.value = newValue;
1597
- }
1598
- function setErrors(errors) {
1599
- setState({ errors: Array.isArray(errors) ? errors : [errors] });
1600
- }
1601
- const field = {
1602
- id,
1603
- name,
1604
- label,
1605
- value,
1606
- meta,
1607
- errors,
1608
- errorMessage,
1609
- type,
1610
- checkedValue,
1611
- uncheckedValue,
1612
- bails,
1613
- resetField,
1614
- handleReset: () => resetField(),
1615
- validate: validate$1,
1616
- handleChange,
1617
- handleBlur,
1618
- setState,
1619
- setTouched,
1620
- setErrors,
1621
- setValue,
1622
- };
1623
- provide(FieldContextKey, field);
1624
- if (isRef(rules) && typeof unref(rules) !== 'function') {
1625
- watch(rules, (value, oldValue) => {
1626
- if (es6(value, oldValue)) {
1627
- return;
1628
- }
1629
- meta.validated ? validateWithStateMutation() : validateValidStateOnly();
1630
- }, {
1631
- deep: true,
1632
- });
1633
- }
1634
- if (("production" !== 'production')) {
1635
- field._vm = getCurrentInstance();
1636
- watch(() => (Object.assign(Object.assign({ errors: errors.value }, meta), { value: value.value })), refreshInspector, {
1637
- deep: true,
1638
- });
1639
- if (!form) {
1640
- registerSingleFieldWithDevtools(field);
1641
- }
1642
- }
1643
- // if no associated form return the field API immediately
1644
- if (!form) {
1645
- return field;
1646
- }
1647
- // associate the field with the given form
1648
- form.register(field);
1649
- onBeforeUnmount(() => {
1650
- markedForRemoval = true;
1651
- form.unregister(field);
1652
- });
1653
- // extract cross-field dependencies in a computed prop
1654
- const dependencies = computed(() => {
1655
- const rulesVal = normalizedRules.value;
1656
- // is falsy, a function schema or a yup schema
1657
- if (!rulesVal || isCallable(rulesVal) || isYupValidator(rulesVal) || Array.isArray(rulesVal)) {
1658
- return {};
1659
- }
1660
- return Object.keys(rulesVal).reduce((acc, rule) => {
1661
- const deps = extractLocators(rulesVal[rule])
1662
- .map((dep) => dep.__locatorRef)
1663
- .reduce((depAcc, depName) => {
1664
- const depValue = getFromPath(form.values, depName) || form.values[depName];
1665
- if (depValue !== undefined) {
1666
- depAcc[depName] = depValue;
1667
- }
1668
- return depAcc;
1669
- }, {});
1670
- Object.assign(acc, deps);
1671
- return acc;
1672
- }, {});
1673
- });
1674
- // Adds a watcher that runs the validation whenever field dependencies change
1675
- watch(dependencies, (deps, oldDeps) => {
1676
- // Skip if no dependencies or if the field wasn't manipulated
1677
- if (!Object.keys(deps).length) {
1678
- return;
1679
- }
1680
- const shouldValidate = !es6(deps, oldDeps);
1681
- if (shouldValidate) {
1682
- meta.validated ? validateWithStateMutation() : validateValidStateOnly();
1683
- }
1684
- });
1685
- return field;
1686
- }
1687
- /**
1688
- * Normalizes partial field options to include the full options
1689
- */
1690
- function normalizeOptions(name, opts) {
1691
- const defaults = () => ({
1692
- initialValue: undefined,
1693
- validateOnMount: false,
1694
- bails: true,
1695
- rules: '',
1696
- label: name,
1697
- validateOnValueUpdate: true,
1698
- standalone: false,
1699
- });
1700
- if (!opts) {
1701
- return defaults();
1702
- }
1703
- // TODO: Deprecate this in next major release
1704
- const checkedValue = 'valueProp' in opts ? opts.valueProp : opts.checkedValue;
1705
- return Object.assign(Object.assign(Object.assign({}, defaults()), (opts || {})), { checkedValue });
1706
- }
1707
- /**
1708
- * Extracts the validation rules from a schema
1709
- */
1710
- function extractRuleFromSchema(schema, fieldName) {
1711
- // no schema at all
1712
- if (!schema) {
1713
- return undefined;
1714
- }
1715
- // there is a key on the schema object for this field
1716
- return schema[fieldName];
1717
- }
1718
- function useCheckboxField(name, rules, opts) {
1719
- const form = !(opts === null || opts === void 0 ? void 0 : opts.standalone) ? injectWithSelf(FormContextKey) : undefined;
1720
- const checkedValue = opts === null || opts === void 0 ? void 0 : opts.checkedValue;
1721
- const uncheckedValue = opts === null || opts === void 0 ? void 0 : opts.uncheckedValue;
1722
- function patchCheckboxApi(field) {
1723
- const handleChange = field.handleChange;
1724
- const checked = computed(() => {
1725
- const currentValue = unref(field.value);
1726
- const checkedVal = unref(checkedValue);
1727
- return Array.isArray(currentValue) ? currentValue.includes(checkedVal) : checkedVal === currentValue;
1728
- });
1729
- function handleCheckboxChange(e, shouldValidate = true) {
1730
- var _a, _b;
1731
- if (checked.value === ((_b = (_a = e) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.checked)) {
1732
- return;
1733
- }
1734
- let newValue = normalizeEventValue(e);
1735
- // Single checkbox field without a form to toggle it's value
1736
- if (!form) {
1737
- newValue = resolveNextCheckboxValue(unref(field.value), unref(checkedValue), unref(uncheckedValue));
1738
- }
1739
- handleChange(newValue, shouldValidate);
1740
- }
1741
- onBeforeUnmount(() => {
1742
- // toggles the checkbox value if it was checked
1743
- if (checked.value) {
1744
- handleCheckboxChange(unref(checkedValue), false);
1745
- }
1746
- });
1747
- return Object.assign(Object.assign({}, field), { checked,
1748
- checkedValue,
1749
- uncheckedValue, handleChange: handleCheckboxChange });
1750
- }
1751
- return patchCheckboxApi(_useField(name, rules, opts));
1752
- }
1753
-
1754
- const FieldImpl = defineComponent({
1755
- name: 'Field',
1756
- inheritAttrs: false,
1757
- props: {
1758
- as: {
1759
- type: [String, Object],
1760
- default: undefined,
1761
- },
1762
- name: {
1763
- type: String,
1764
- required: true,
1765
- },
1766
- rules: {
1767
- type: [Object, String, Function],
1768
- default: undefined,
1769
- },
1770
- validateOnMount: {
1771
- type: Boolean,
1772
- default: false,
1773
- },
1774
- validateOnBlur: {
1775
- type: Boolean,
1776
- default: undefined,
1777
- },
1778
- validateOnChange: {
1779
- type: Boolean,
1780
- default: undefined,
1781
- },
1782
- validateOnInput: {
1783
- type: Boolean,
1784
- default: undefined,
1785
- },
1786
- validateOnModelUpdate: {
1787
- type: Boolean,
1788
- default: undefined,
1789
- },
1790
- bails: {
1791
- type: Boolean,
1792
- default: () => getConfig().bails,
1793
- },
1794
- label: {
1795
- type: String,
1796
- default: undefined,
1797
- },
1798
- uncheckedValue: {
1799
- type: null,
1800
- default: undefined,
1801
- },
1802
- modelValue: {
1803
- type: null,
1804
- default: IS_ABSENT,
1805
- },
1806
- modelModifiers: {
1807
- type: null,
1808
- default: () => ({}),
1809
- },
1810
- 'onUpdate:modelValue': {
1811
- type: null,
1812
- default: undefined,
1813
- },
1814
- standalone: {
1815
- type: Boolean,
1816
- default: false,
1817
- },
1818
- },
1819
- setup(props, ctx) {
1820
- const rules = toRef(props, 'rules');
1821
- const name = toRef(props, 'name');
1822
- const label = toRef(props, 'label');
1823
- const uncheckedValue = toRef(props, 'uncheckedValue');
1824
- const hasModelEvents = isPropPresent(props, 'onUpdate:modelValue');
1825
- const { errors, value, errorMessage, validate: validateField, handleChange, handleBlur, setTouched, resetField, handleReset, meta, checked, setErrors, } = useField(name, rules, {
1826
- validateOnMount: props.validateOnMount,
1827
- bails: props.bails,
1828
- standalone: props.standalone,
1829
- type: ctx.attrs.type,
1830
- initialValue: resolveInitialValue(props, ctx),
1831
- // Only for checkboxes and radio buttons
1832
- checkedValue: ctx.attrs.value,
1833
- uncheckedValue,
1834
- label,
1835
- validateOnValueUpdate: false,
1836
- });
1837
- // If there is a v-model applied on the component we need to emit the `update:modelValue` whenever the value binding changes
1838
- const onChangeHandler = hasModelEvents
1839
- ? function handleChangeWithModel(e, shouldValidate = true) {
1840
- handleChange(e, shouldValidate);
1841
- ctx.emit('update:modelValue', value.value);
1842
- }
1843
- : handleChange;
1844
- const handleInput = (e) => {
1845
- if (!hasCheckedAttr(ctx.attrs.type)) {
1846
- value.value = normalizeEventValue(e);
1847
- }
1848
- };
1849
- const onInputHandler = hasModelEvents
1850
- ? function handleInputWithModel(e) {
1851
- handleInput(e);
1852
- ctx.emit('update:modelValue', value.value);
1853
- }
1854
- : handleInput;
1855
- const fieldProps = computed(() => {
1856
- const { validateOnInput, validateOnChange, validateOnBlur, validateOnModelUpdate } = resolveValidationTriggers(props);
1857
- const baseOnBlur = [handleBlur, ctx.attrs.onBlur, validateOnBlur ? validateField : undefined].filter(Boolean);
1858
- const baseOnInput = [(e) => onChangeHandler(e, validateOnInput), ctx.attrs.onInput].filter(Boolean);
1859
- const baseOnChange = [(e) => onChangeHandler(e, validateOnChange), ctx.attrs.onChange].filter(Boolean);
1860
- const attrs = {
1861
- name: props.name,
1862
- onBlur: baseOnBlur,
1863
- onInput: baseOnInput,
1864
- onChange: baseOnChange,
1865
- };
1866
- attrs['onUpdate:modelValue'] = e => onChangeHandler(e, validateOnModelUpdate);
1867
- if (hasCheckedAttr(ctx.attrs.type) && checked) {
1868
- attrs.checked = checked.value;
1869
- }
1870
- else {
1871
- attrs.value = value.value;
1872
- }
1873
- const tag = resolveTag(props, ctx);
1874
- if (shouldHaveValueBinding(tag, ctx.attrs)) {
1875
- delete attrs.value;
1876
- }
1877
- return attrs;
1878
- });
1879
- const modelValue = toRef(props, 'modelValue');
1880
- watch(modelValue, newModelValue => {
1881
- // Don't attempt to sync absent values
1882
- if (newModelValue === IS_ABSENT && value.value === undefined) {
1883
- return;
1884
- }
1885
- if (newModelValue !== applyModifiers(value.value, props.modelModifiers)) {
1886
- value.value = newModelValue === IS_ABSENT ? undefined : newModelValue;
1887
- validateField();
1888
- }
1889
- });
1890
- function slotProps() {
1891
- return {
1892
- field: fieldProps.value,
1893
- value: value.value,
1894
- meta,
1895
- errors: errors.value,
1896
- errorMessage: errorMessage.value,
1897
- validate: validateField,
1898
- resetField,
1899
- handleChange: onChangeHandler,
1900
- handleInput: onInputHandler,
1901
- handleReset,
1902
- handleBlur,
1903
- setTouched,
1904
- setErrors,
1905
- };
1906
- }
1907
- ctx.expose({
1908
- setErrors,
1909
- setTouched,
1910
- reset: resetField,
1911
- validate: validateField,
1912
- handleChange,
1913
- });
1914
- return () => {
1915
- const tag = resolveDynamicComponent(resolveTag(props, ctx));
1916
- const children = normalizeChildren(tag, ctx, slotProps);
1917
- if (tag) {
1918
- return h(tag, Object.assign(Object.assign({}, ctx.attrs), fieldProps.value), children);
1919
- }
1920
- return children;
1921
- };
1922
- },
1923
- });
1924
- function resolveTag(props, ctx) {
1925
- let tag = props.as || '';
1926
- if (!props.as && !ctx.slots.default) {
1927
- tag = 'input';
1928
- }
1929
- return tag;
1930
- }
1931
- function resolveValidationTriggers(props) {
1932
- var _a, _b, _c, _d;
1933
- const { validateOnInput, validateOnChange, validateOnBlur, validateOnModelUpdate } = getConfig();
1934
- return {
1935
- validateOnInput: (_a = props.validateOnInput) !== null && _a !== void 0 ? _a : validateOnInput,
1936
- validateOnChange: (_b = props.validateOnChange) !== null && _b !== void 0 ? _b : validateOnChange,
1937
- validateOnBlur: (_c = props.validateOnBlur) !== null && _c !== void 0 ? _c : validateOnBlur,
1938
- validateOnModelUpdate: (_d = props.validateOnModelUpdate) !== null && _d !== void 0 ? _d : validateOnModelUpdate,
1939
- };
1940
- }
1941
- function applyModifiers(value, modifiers) {
1942
- if (modifiers.number) {
1943
- return toNumber(value);
1944
- }
1945
- return value;
1946
- }
1947
- function resolveInitialValue(props, ctx) {
1948
- // Gets the initial value either from `value` prop/attr or `v-model` binding (modelValue)
1949
- // For checkboxes and radio buttons it will always be the model value not the `value` attribute
1950
- if (!hasCheckedAttr(ctx.attrs.type)) {
1951
- return isPropPresent(props, 'modelValue') ? props.modelValue : ctx.attrs.value;
1952
- }
1953
- return isPropPresent(props, 'modelValue') ? props.modelValue : undefined;
1954
- }
1955
- const Field = FieldImpl;
1956
-
1957
- let FORM_COUNTER = 0;
1958
- function useForm(opts) {
1959
- const formId = FORM_COUNTER++;
1960
- // Prevents fields from double resetting their values, which causes checkboxes to toggle their initial value
1961
- // TODO: This won't be needed if we centralize all the state inside the `form` for form inputs
1962
- let RESET_LOCK = false;
1963
- // A lookup containing fields or field groups
1964
- const fieldsByPath = ref({});
1965
- // If the form is currently submitting
1966
- const isSubmitting = ref(false);
1967
- // The number of times the user tried to submit the form
1968
- const submitCount = ref(0);
1969
- // dictionary for field arrays to receive various signals like reset
1970
- const fieldArraysLookup = {};
1971
- // a private ref for all form values
1972
- const formValues = reactive(klona(unref(opts === null || opts === void 0 ? void 0 : opts.initialValues) || {}));
1973
- // the source of errors for the form fields
1974
- const { errorBag, setErrorBag, setFieldErrorBag } = useErrorBag(opts === null || opts === void 0 ? void 0 : opts.initialErrors);
1975
- // Gets the first error of each field
1976
- const errors = computed(() => {
1977
- return keysOf(errorBag.value).reduce((acc, key) => {
1978
- const bag = errorBag.value[key];
1979
- if (bag && bag.length) {
1980
- acc[key] = bag[0];
1981
- }
1982
- return acc;
1983
- }, {});
1984
- });
1985
- function getFirstFieldAtPath(path) {
1986
- const fieldOrGroup = fieldsByPath.value[path];
1987
- return Array.isArray(fieldOrGroup) ? fieldOrGroup[0] : fieldOrGroup;
1988
- }
1989
- function fieldExists(path) {
1990
- return !!fieldsByPath.value[path];
1991
- }
1992
- /**
1993
- * Holds a computed reference to all fields names and labels
1994
- */
1995
- const fieldNames = computed(() => {
1996
- return keysOf(fieldsByPath.value).reduce((names, path) => {
1997
- const field = getFirstFieldAtPath(path);
1998
- if (field) {
1999
- names[path] = unref(field.label || field.name) || '';
2000
- }
2001
- return names;
2002
- }, {});
2003
- });
2004
- const fieldBailsMap = computed(() => {
2005
- return keysOf(fieldsByPath.value).reduce((map, path) => {
2006
- var _a;
2007
- const field = getFirstFieldAtPath(path);
2008
- if (field) {
2009
- map[path] = (_a = field.bails) !== null && _a !== void 0 ? _a : true;
2010
- }
2011
- return map;
2012
- }, {});
2013
- });
2014
- // mutable non-reactive reference to initial errors
2015
- // we need this to process initial errors then unset them
2016
- const initialErrors = Object.assign({}, ((opts === null || opts === void 0 ? void 0 : opts.initialErrors) || {}));
2017
- // initial form values
2018
- const { initialValues, originalInitialValues, setInitialValues } = useFormInitialValues(fieldsByPath, formValues, opts === null || opts === void 0 ? void 0 : opts.initialValues);
2019
- // form meta aggregations
2020
- const meta = useFormMeta(fieldsByPath, formValues, initialValues, errors);
2021
- const schema = opts === null || opts === void 0 ? void 0 : opts.validationSchema;
2022
- const formCtx = {
2023
- formId,
2024
- fieldsByPath,
2025
- values: formValues,
2026
- errorBag,
2027
- errors,
2028
- schema,
2029
- submitCount,
2030
- meta,
2031
- isSubmitting,
2032
- fieldArraysLookup,
2033
- validateSchema: unref(schema) ? validateSchema : undefined,
2034
- validate,
2035
- register: registerField,
2036
- unregister: unregisterField,
2037
- setFieldErrorBag,
2038
- validateField,
2039
- setFieldValue,
2040
- setValues,
2041
- setErrors,
2042
- setFieldError,
2043
- setFieldTouched,
2044
- setTouched,
2045
- resetForm,
2046
- handleSubmit,
2047
- stageInitialValue,
2048
- unsetInitialValue,
2049
- setFieldInitialValue,
2050
- };
2051
- function isFieldGroup(fieldOrGroup) {
2052
- return Array.isArray(fieldOrGroup);
2053
- }
2054
- function applyFieldMutation(fieldOrGroup, mutation) {
2055
- if (Array.isArray(fieldOrGroup)) {
2056
- return fieldOrGroup.forEach(mutation);
2057
- }
2058
- return mutation(fieldOrGroup);
2059
- }
2060
- function mutateAllFields(mutation) {
2061
- Object.values(fieldsByPath.value).forEach(field => {
2062
- if (!field) {
2063
- return;
2064
- }
2065
- // avoid resetting the field values, because they should've been reset already.
2066
- applyFieldMutation(field, mutation);
2067
- });
2068
- }
2069
- /**
2070
- * Manually sets an error message on a specific field
2071
- */
2072
- function setFieldError(field, message) {
2073
- setFieldErrorBag(field, message);
2074
- }
2075
- /**
2076
- * Sets errors for the fields specified in the object
2077
- */
2078
- function setErrors(fields) {
2079
- setErrorBag(fields);
2080
- }
2081
- /**
2082
- * Sets a single field value
2083
- */
2084
- function setFieldValue(field, value, { force } = { force: false }) {
2085
- var _a;
2086
- const fieldInstance = fieldsByPath.value[field];
2087
- const clonedValue = klona(value);
2088
- // field wasn't found, create a virtual field as a placeholder
2089
- if (!fieldInstance) {
2090
- setInPath(formValues, field, clonedValue);
2091
- return;
2092
- }
2093
- if (isFieldGroup(fieldInstance) && ((_a = fieldInstance[0]) === null || _a === void 0 ? void 0 : _a.type) === 'checkbox' && !Array.isArray(value)) {
2094
- // Multiple checkboxes, and only one of them got updated
2095
- const newValue = klona(resolveNextCheckboxValue(getFromPath(formValues, field) || [], value, undefined));
2096
- setInPath(formValues, field, newValue);
2097
- return;
2098
- }
2099
- let newValue = value;
2100
- // Single Checkbox: toggles the field value unless the field is being reset then force it
2101
- if (!isFieldGroup(fieldInstance) && fieldInstance.type === 'checkbox' && !force && !RESET_LOCK) {
2102
- newValue = klona(resolveNextCheckboxValue(getFromPath(formValues, field), value, unref(fieldInstance.uncheckedValue)));
2103
- }
2104
- setInPath(formValues, field, newValue);
2105
- }
2106
- /**
2107
- * Sets multiple fields values
2108
- */
2109
- function setValues(fields) {
2110
- // clean up old values
2111
- keysOf(formValues).forEach(key => {
2112
- delete formValues[key];
2113
- });
2114
- // set up new values
2115
- keysOf(fields).forEach(path => {
2116
- setFieldValue(path, fields[path]);
2117
- });
2118
- // regenerate the arrays when the form values change
2119
- Object.values(fieldArraysLookup).forEach(f => f && f.reset());
2120
- }
2121
- /**
2122
- * Sets the touched meta state on a field
2123
- */
2124
- function setFieldTouched(field, isTouched) {
2125
- const fieldInstance = fieldsByPath.value[field];
2126
- if (fieldInstance) {
2127
- applyFieldMutation(fieldInstance, f => f.setTouched(isTouched));
2128
- }
2129
- }
2130
- /**
2131
- * Sets the touched meta state on multiple fields
2132
- */
2133
- function setTouched(fields) {
2134
- keysOf(fields).forEach(field => {
2135
- setFieldTouched(field, !!fields[field]);
2136
- });
2137
- }
2138
- /**
2139
- * Resets all fields
2140
- */
2141
- function resetForm(state) {
2142
- RESET_LOCK = true;
2143
- // set initial values if provided
2144
- if (state === null || state === void 0 ? void 0 : state.values) {
2145
- setInitialValues(state.values);
2146
- setValues(state === null || state === void 0 ? void 0 : state.values);
2147
- }
2148
- else {
2149
- // clean up the initial values back to the original
2150
- setInitialValues(originalInitialValues.value);
2151
- // otherwise clean the current values
2152
- setValues(originalInitialValues.value);
2153
- }
2154
- // avoid resetting the field values, because they should've been reset already.
2155
- mutateAllFields(f => f.resetField());
2156
- if (state === null || state === void 0 ? void 0 : state.touched) {
2157
- setTouched(state.touched);
2158
- }
2159
- setErrors((state === null || state === void 0 ? void 0 : state.errors) || {});
2160
- submitCount.value = (state === null || state === void 0 ? void 0 : state.submitCount) || 0;
2161
- nextTick(() => {
2162
- RESET_LOCK = false;
2163
- });
2164
- }
2165
- function insertFieldAtPath(field, path) {
2166
- const rawField = markRaw(field);
2167
- const fieldPath = path;
2168
- // first field at that path
2169
- if (!fieldsByPath.value[fieldPath]) {
2170
- fieldsByPath.value[fieldPath] = rawField;
2171
- return;
2172
- }
2173
- const fieldAtPath = fieldsByPath.value[fieldPath];
2174
- if (fieldAtPath && !Array.isArray(fieldAtPath)) {
2175
- fieldsByPath.value[fieldPath] = [fieldAtPath];
2176
- }
2177
- // add the new array to that path
2178
- fieldsByPath.value[fieldPath] = [...fieldsByPath.value[fieldPath], rawField];
2179
- }
2180
- function removeFieldFromPath(field, path) {
2181
- const fieldPath = path;
2182
- const fieldAtPath = fieldsByPath.value[fieldPath];
2183
- if (!fieldAtPath) {
2184
- return;
2185
- }
2186
- // same field at path
2187
- if (!isFieldGroup(fieldAtPath) && field.id === fieldAtPath.id) {
2188
- delete fieldsByPath.value[fieldPath];
2189
- return;
2190
- }
2191
- if (isFieldGroup(fieldAtPath)) {
2192
- const idx = fieldAtPath.findIndex(f => f.id === field.id);
2193
- if (idx === -1) {
2194
- return;
2195
- }
2196
- fieldAtPath.splice(idx, 1);
2197
- if (fieldAtPath.length === 1) {
2198
- fieldsByPath.value[fieldPath] = fieldAtPath[0];
2199
- return;
2200
- }
2201
- if (!fieldAtPath.length) {
2202
- delete fieldsByPath.value[fieldPath];
2203
- }
2204
- }
2205
- }
2206
- function registerField(field) {
2207
- const fieldPath = unref(field.name);
2208
- insertFieldAtPath(field, fieldPath);
2209
- if (isRef(field.name)) {
2210
- // ensures when a field's name was already taken that it preserves its same value
2211
- // necessary for fields generated by loops
2212
- watch(field.name, async (newPath, oldPath) => {
2213
- // cache the value
2214
- await nextTick();
2215
- removeFieldFromPath(field, oldPath);
2216
- insertFieldAtPath(field, newPath);
2217
- // re-validate if either path had errors before
2218
- if (errors.value[oldPath] || errors.value[newPath]) {
2219
- // clear up both paths errors
2220
- setFieldError(oldPath, undefined);
2221
- validateField(newPath);
2222
- }
2223
- // clean up the old path if no other field is sharing that name
2224
- // #3325
2225
- await nextTick();
2226
- if (!fieldExists(oldPath)) {
2227
- unsetPath(formValues, oldPath);
2228
- }
2229
- });
2230
- }
2231
- // if field already had errors (initial errors) that's not user-set, validate it again to ensure state is correct
2232
- // the difference being that `initialErrors` will contain the error message while other errors (pre-validated schema) won't have them as initial errors
2233
- // #3342
2234
- const initialErrorMessage = unref(field.errorMessage);
2235
- if (initialErrorMessage && (initialErrors === null || initialErrors === void 0 ? void 0 : initialErrors[fieldPath]) !== initialErrorMessage) {
2236
- validateField(fieldPath);
2237
- }
2238
- // marks the initial error as "consumed" so it won't be matched later with same non-initial error
2239
- delete initialErrors[fieldPath];
2240
- }
2241
- function unregisterField(field) {
2242
- const fieldName = unref(field.name);
2243
- removeFieldFromPath(field, fieldName);
2244
- nextTick(() => {
2245
- // clears a field error on unmounted
2246
- // we wait till next tick to make sure if the field is completely removed and doesn't have any siblings like checkboxes
2247
- // #3384
2248
- if (!fieldExists(fieldName)) {
2249
- setFieldError(fieldName, undefined);
2250
- unsetPath(formValues, fieldName);
2251
- }
2252
- });
2253
- }
2254
- async function validate(opts) {
2255
- mutateAllFields(f => (f.meta.validated = true));
2256
- if (formCtx.validateSchema) {
2257
- return formCtx.validateSchema((opts === null || opts === void 0 ? void 0 : opts.mode) || 'force');
2258
- }
2259
- // No schema, each field is responsible to validate itself
2260
- const validations = await Promise.all(Object.values(fieldsByPath.value).map(field => {
2261
- const fieldInstance = Array.isArray(field) ? field[0] : field;
2262
- if (!fieldInstance) {
2263
- return Promise.resolve({ key: '', valid: true, errors: [] });
2264
- }
2265
- return fieldInstance.validate(opts).then((result) => {
2266
- return {
2267
- key: unref(fieldInstance.name),
2268
- valid: result.valid,
2269
- errors: result.errors,
2270
- };
2271
- });
2272
- }));
2273
- const results = {};
2274
- const errors = {};
2275
- for (const validation of validations) {
2276
- results[validation.key] = {
2277
- valid: validation.valid,
2278
- errors: validation.errors,
2279
- };
2280
- if (validation.errors.length) {
2281
- errors[validation.key] = validation.errors[0];
2282
- }
2283
- }
2284
- return {
2285
- valid: validations.every(r => r.valid),
2286
- results,
2287
- errors,
2288
- };
2289
- }
2290
- async function validateField(field) {
2291
- const fieldInstance = fieldsByPath.value[field];
2292
- if (!fieldInstance) {
2293
- warn$1(`field with name ${field} was not found`);
2294
- return Promise.resolve({ errors: [], valid: true });
2295
- }
2296
- if (Array.isArray(fieldInstance)) {
2297
- return fieldInstance.map(f => f.validate())[0];
2298
- }
2299
- return fieldInstance.validate();
2300
- }
2301
- function handleSubmit(fn, onValidationError) {
2302
- return function submissionHandler(e) {
2303
- if (e instanceof Event) {
2304
- e.preventDefault();
2305
- e.stopPropagation();
2306
- }
2307
- // Touch all fields
2308
- setTouched(keysOf(fieldsByPath.value).reduce((acc, field) => {
2309
- acc[field] = true;
2310
- return acc;
2311
- }, {}));
2312
- isSubmitting.value = true;
2313
- submitCount.value++;
2314
- return validate()
2315
- .then(result => {
2316
- if (result.valid && typeof fn === 'function') {
2317
- return fn(klona(formValues), {
2318
- evt: e,
2319
- setErrors,
2320
- setFieldError,
2321
- setTouched,
2322
- setFieldTouched,
2323
- setValues,
2324
- setFieldValue,
2325
- resetForm,
2326
- });
2327
- }
2328
- if (!result.valid && typeof onValidationError === 'function') {
2329
- onValidationError({
2330
- values: klona(formValues),
2331
- evt: e,
2332
- errors: result.errors,
2333
- results: result.results,
2334
- });
2335
- }
2336
- })
2337
- .then(returnVal => {
2338
- isSubmitting.value = false;
2339
- return returnVal;
2340
- }, err => {
2341
- isSubmitting.value = false;
2342
- // re-throw the err so it doesn't go silent
2343
- throw err;
2344
- });
2345
- };
2346
- }
2347
- function setFieldInitialValue(path, value) {
2348
- setInPath(initialValues.value, path, klona(value));
2349
- }
2350
- function unsetInitialValue(path) {
2351
- unsetPath(initialValues.value, path);
2352
- }
2353
- /**
2354
- * Sneaky function to set initial field values
2355
- */
2356
- function stageInitialValue(path, value) {
2357
- setInPath(formValues, path, value);
2358
- setFieldInitialValue(path, value);
2359
- }
2360
- async function _validateSchema() {
2361
- const schemaValue = unref(schema);
2362
- if (!schemaValue) {
2363
- return { valid: true, results: {}, errors: {} };
2364
- }
2365
- const formResult = isYupValidator(schemaValue)
2366
- ? await validateYupSchema(schemaValue, formValues)
2367
- : await validateObjectSchema(schemaValue, formValues, {
2368
- names: fieldNames.value,
2369
- bailsMap: fieldBailsMap.value,
2370
- });
2371
- return formResult;
2372
- }
2373
- /**
2374
- * Batches validation runs in 5ms batches
2375
- */
2376
- const debouncedSchemaValidation = debounceAsync(_validateSchema, 5);
2377
- async function validateSchema(mode) {
2378
- const formResult = await debouncedSchemaValidation();
2379
- // fields by id lookup
2380
- const fieldsById = formCtx.fieldsByPath.value || {};
2381
- // errors fields names, we need it to also check if custom errors are updated
2382
- const currentErrorsPaths = keysOf(formCtx.errorBag.value);
2383
- // collect all the keys from the schema and all fields
2384
- // this ensures we have a complete keymap of all the fields
2385
- const paths = [
2386
- ...new Set([...keysOf(formResult.results), ...keysOf(fieldsById), ...currentErrorsPaths]),
2387
- ];
2388
- // aggregates the paths into a single result object while applying the results on the fields
2389
- return paths.reduce((validation, path) => {
2390
- const field = fieldsById[path];
2391
- const messages = (formResult.results[path] || { errors: [] }).errors;
2392
- const fieldResult = {
2393
- errors: messages,
2394
- valid: !messages.length,
2395
- };
2396
- validation.results[path] = fieldResult;
2397
- if (!fieldResult.valid) {
2398
- validation.errors[path] = fieldResult.errors[0];
2399
- }
2400
- // field not rendered
2401
- if (!field) {
2402
- setFieldError(path, messages);
2403
- return validation;
2404
- }
2405
- // always update the valid flag regardless of the mode
2406
- applyFieldMutation(field, f => (f.meta.valid = fieldResult.valid));
2407
- if (mode === 'silent') {
2408
- return validation;
2409
- }
2410
- const wasValidated = Array.isArray(field) ? field.some(f => f.meta.validated) : field.meta.validated;
2411
- if (mode === 'validated-only' && !wasValidated) {
2412
- return validation;
2413
- }
2414
- applyFieldMutation(field, f => f.setState({ errors: fieldResult.errors }));
2415
- return validation;
2416
- }, { valid: formResult.valid, results: {}, errors: {} });
2417
- }
2418
- const submitForm = handleSubmit((_, { evt }) => {
2419
- if (isFormSubmitEvent(evt)) {
2420
- evt.target.submit();
2421
- }
2422
- });
2423
- // Trigger initial validation
2424
- onMounted(() => {
2425
- if (opts === null || opts === void 0 ? void 0 : opts.initialErrors) {
2426
- setErrors(opts.initialErrors);
2427
- }
2428
- if (opts === null || opts === void 0 ? void 0 : opts.initialTouched) {
2429
- setTouched(opts.initialTouched);
2430
- }
2431
- // if validate on mount was enabled
2432
- if (opts === null || opts === void 0 ? void 0 : opts.validateOnMount) {
2433
- validate();
2434
- return;
2435
- }
2436
- // otherwise run initial silent validation through schema if available
2437
- // the useField should skip their own silent validation if a yup schema is present
2438
- if (formCtx.validateSchema) {
2439
- formCtx.validateSchema('silent');
2440
- }
2441
- });
2442
- if (isRef(schema)) {
2443
- watch(schema, () => {
2444
- var _a;
2445
- (_a = formCtx.validateSchema) === null || _a === void 0 ? void 0 : _a.call(formCtx, 'validated-only');
2446
- });
2447
- }
2448
- // Provide injections
2449
- provide(FormContextKey, formCtx);
2450
- if (("production" !== 'production')) {
2451
- registerFormWithDevTools(formCtx);
2452
- watch(() => (Object.assign(Object.assign({ errors: errorBag.value }, meta.value), { values: formValues, isSubmitting: isSubmitting.value, submitCount: submitCount.value })), refreshInspector, {
2453
- deep: true,
2454
- });
2455
- }
2456
- return {
2457
- errors,
2458
- meta,
2459
- values: formValues,
2460
- isSubmitting,
2461
- submitCount,
2462
- validate,
2463
- validateField,
2464
- handleReset: () => resetForm(),
2465
- resetForm,
2466
- handleSubmit,
2467
- submitForm,
2468
- setFieldError,
2469
- setErrors,
2470
- setFieldValue,
2471
- setValues,
2472
- setFieldTouched,
2473
- setTouched,
2474
- };
2475
- }
2476
- /**
2477
- * Manages form meta aggregation
2478
- */
2479
- function useFormMeta(fieldsByPath, currentValues, initialValues, errors) {
2480
- const MERGE_STRATEGIES = {
2481
- touched: 'some',
2482
- pending: 'some',
2483
- valid: 'every',
2484
- };
2485
- const isDirty = computed(() => {
2486
- return !es6(currentValues, unref(initialValues));
2487
- });
2488
- function calculateFlags() {
2489
- const fields = Object.values(fieldsByPath.value).flat(1).filter(Boolean);
2490
- return keysOf(MERGE_STRATEGIES).reduce((acc, flag) => {
2491
- const mergeMethod = MERGE_STRATEGIES[flag];
2492
- acc[flag] = fields[mergeMethod](field => field.meta[flag]);
2493
- return acc;
2494
- }, {});
2495
- }
2496
- const flags = reactive(calculateFlags());
2497
- watchEffect(() => {
2498
- const value = calculateFlags();
2499
- flags.touched = value.touched;
2500
- flags.valid = value.valid;
2501
- flags.pending = value.pending;
2502
- });
2503
- return computed(() => {
2504
- return Object.assign(Object.assign({ initialValues: unref(initialValues) }, flags), { valid: flags.valid && !keysOf(errors.value).length, dirty: isDirty.value });
2505
- });
2506
- }
2507
- /**
2508
- * Manages the initial values prop
2509
- */
2510
- function useFormInitialValues(fields, formValues, providedValues) {
2511
- // these are the mutable initial values as the fields are mounted/unmounted
2512
- const initialValues = ref(klona(unref(providedValues)) || {});
2513
- // these are the original initial value as provided by the user initially, they don't keep track of conditional fields
2514
- // this is important because some conditional fields will overwrite the initial values for other fields who had the same name
2515
- // like array fields, any push/insert operation will overwrite the initial values because they "create new fields"
2516
- // so these are the values that the reset function should use
2517
- // these only change when the user explicitly chanegs the initial values or when the user resets them with new values.
2518
- const originalInitialValues = ref(klona(unref(providedValues)) || {});
2519
- function setInitialValues(values, updateFields = false) {
2520
- initialValues.value = klona(values);
2521
- originalInitialValues.value = klona(values);
2522
- if (!updateFields) {
2523
- return;
2524
- }
2525
- // update the pristine non-touched fields
2526
- // those are excluded because it's unlikely you want to change the form values using initial values
2527
- // we mostly watch them for API population or newly inserted fields
2528
- // if the user API is taking too much time before user interaction they should consider disabling or hiding their inputs until the values are ready
2529
- keysOf(fields.value).forEach(fieldPath => {
2530
- const field = fields.value[fieldPath];
2531
- const wasTouched = Array.isArray(field) ? field.some(f => f.meta.touched) : field === null || field === void 0 ? void 0 : field.meta.touched;
2532
- if (!field || wasTouched) {
2533
- return;
2534
- }
2535
- const newValue = getFromPath(initialValues.value, fieldPath);
2536
- setInPath(formValues, fieldPath, klona(newValue));
2537
- });
2538
- }
2539
- if (isRef(providedValues)) {
2540
- watch(providedValues, value => {
2541
- setInitialValues(value, true);
2542
- }, {
2543
- deep: true,
2544
- });
2545
- }
2546
- return {
2547
- initialValues,
2548
- originalInitialValues,
2549
- setInitialValues,
2550
- };
2551
- }
2552
- function useErrorBag(initialErrors) {
2553
- const errorBag = ref({});
2554
- function normalizeErrorItem(message) {
2555
- return Array.isArray(message) ? message : message ? [message] : [];
2556
- }
2557
- /**
2558
- * Manually sets an error message on a specific field
2559
- */
2560
- function setFieldErrorBag(field, message) {
2561
- if (!message) {
2562
- delete errorBag.value[field];
2563
- return;
2564
- }
2565
- errorBag.value[field] = normalizeErrorItem(message);
2566
- }
2567
- /**
2568
- * Sets errors for the fields specified in the object
2569
- */
2570
- function setErrorBag(fields) {
2571
- errorBag.value = keysOf(fields).reduce((acc, key) => {
2572
- const message = fields[key];
2573
- if (message) {
2574
- acc[key] = normalizeErrorItem(message);
2575
- }
2576
- return acc;
2577
- }, {});
2578
- }
2579
- if (initialErrors) {
2580
- setErrorBag(initialErrors);
2581
- }
2582
- return {
2583
- errorBag,
2584
- setErrorBag,
2585
- setFieldErrorBag,
2586
- };
2587
- }
2588
-
2589
- const FormImpl = defineComponent({
2590
- name: 'Form',
2591
- inheritAttrs: false,
2592
- props: {
2593
- as: {
2594
- type: String,
2595
- default: 'form',
2596
- },
2597
- validationSchema: {
2598
- type: Object,
2599
- default: undefined,
2600
- },
2601
- initialValues: {
2602
- type: Object,
2603
- default: undefined,
2604
- },
2605
- initialErrors: {
2606
- type: Object,
2607
- default: undefined,
2608
- },
2609
- initialTouched: {
2610
- type: Object,
2611
- default: undefined,
2612
- },
2613
- validateOnMount: {
2614
- type: Boolean,
2615
- default: false,
2616
- },
2617
- onSubmit: {
2618
- type: Function,
2619
- default: undefined,
2620
- },
2621
- onInvalidSubmit: {
2622
- type: Function,
2623
- default: undefined,
2624
- },
2625
- },
2626
- setup(props, ctx) {
2627
- const initialValues = toRef(props, 'initialValues');
2628
- const validationSchema = toRef(props, 'validationSchema');
2629
- const { errors, values, meta, isSubmitting, submitCount, validate, validateField, handleReset, resetForm, handleSubmit, submitForm, setErrors, setFieldError, setFieldValue, setValues, setFieldTouched, setTouched, } = useForm({
2630
- validationSchema: validationSchema.value ? validationSchema : undefined,
2631
- initialValues,
2632
- initialErrors: props.initialErrors,
2633
- initialTouched: props.initialTouched,
2634
- validateOnMount: props.validateOnMount,
2635
- });
2636
- const onSubmit = props.onSubmit ? handleSubmit(props.onSubmit, props.onInvalidSubmit) : submitForm;
2637
- function handleFormReset(e) {
2638
- if (isEvent(e)) {
2639
- // Prevent default form reset behavior
2640
- e.preventDefault();
2641
- }
2642
- handleReset();
2643
- if (typeof ctx.attrs.onReset === 'function') {
2644
- ctx.attrs.onReset();
2645
- }
2646
- }
2647
- function handleScopedSlotSubmit(evt, onSubmit) {
2648
- const onSuccess = typeof evt === 'function' && !onSubmit ? evt : onSubmit;
2649
- return handleSubmit(onSuccess, props.onInvalidSubmit)(evt);
2650
- }
2651
- function slotProps() {
2652
- return {
2653
- meta: meta.value,
2654
- errors: errors.value,
2655
- values: values,
2656
- isSubmitting: isSubmitting.value,
2657
- submitCount: submitCount.value,
2658
- validate,
2659
- validateField,
2660
- handleSubmit: handleScopedSlotSubmit,
2661
- handleReset,
2662
- submitForm,
2663
- setErrors,
2664
- setFieldError,
2665
- setFieldValue,
2666
- setValues,
2667
- setFieldTouched,
2668
- setTouched,
2669
- resetForm,
2670
- };
2671
- }
2672
- // expose these functions and methods as part of public API
2673
- ctx.expose({
2674
- setFieldError,
2675
- setErrors,
2676
- setFieldValue,
2677
- setValues,
2678
- setFieldTouched,
2679
- setTouched,
2680
- resetForm,
2681
- validate,
2682
- validateField,
2683
- });
2684
- return function renderForm() {
2685
- // avoid resolving the form component as itself
2686
- const tag = props.as === 'form' ? props.as : resolveDynamicComponent(props.as);
2687
- const children = normalizeChildren(tag, ctx, slotProps);
2688
- if (!props.as) {
2689
- return children;
2690
- }
2691
- // Attributes to add on a native `form` tag
2692
- const formAttrs = props.as === 'form'
2693
- ? {
2694
- // Disables native validation as vee-validate will handle it.
2695
- novalidate: true,
2696
- }
2697
- : {};
2698
- return h(tag, Object.assign(Object.assign(Object.assign({}, formAttrs), ctx.attrs), { onSubmit, onReset: handleFormReset }), children);
2699
- };
2700
- },
2701
- });
2702
- const Form = FormImpl;
2703
-
2704
- let FIELD_ARRAY_COUNTER = 0;
2705
- function useFieldArray(arrayPath) {
2706
- const id = FIELD_ARRAY_COUNTER++;
2707
- const form = injectWithSelf(FormContextKey, undefined);
2708
- const fields = ref([]);
2709
- // eslint-disable-next-line @typescript-eslint/no-empty-function
2710
- const noOp = () => { };
2711
- const noOpApi = {
2712
- fields: readonly(fields),
2713
- remove: noOp,
2714
- push: noOp,
2715
- swap: noOp,
2716
- insert: noOp,
2717
- update: noOp,
2718
- replace: noOp,
2719
- prepend: noOp,
2720
- };
2721
- if (!form) {
2722
- warn('FieldArray requires being a child of `<Form/>` or `useForm` being called before it. Array fields may not work correctly');
2723
- return noOpApi;
2724
- }
2725
- if (!unref(arrayPath)) {
2726
- warn('FieldArray requires a field path to be provided, did you forget to pass the `name` prop?');
2727
- return noOpApi;
2728
- }
2729
- let entryCounter = 0;
2730
- function initFields() {
2731
- const currentValues = getFromPath(form === null || form === void 0 ? void 0 : form.values, unref(arrayPath), []);
2732
- fields.value = currentValues.map(createEntry);
2733
- updateEntryFlags();
2734
- }
2735
- initFields();
2736
- function updateEntryFlags() {
2737
- const fieldsLength = fields.value.length;
2738
- for (let i = 0; i < fieldsLength; i++) {
2739
- const entry = fields.value[i];
2740
- entry.isFirst = i === 0;
2741
- entry.isLast = i === fieldsLength - 1;
2742
- }
2743
- }
2744
- function createEntry(value) {
2745
- const key = entryCounter++;
2746
- const entry = {
2747
- key,
2748
- value: computed(() => {
2749
- const currentValues = getFromPath(form === null || form === void 0 ? void 0 : form.values, unref(arrayPath), []);
2750
- const idx = fields.value.findIndex(e => e.key === key);
2751
- return idx === -1 ? value : currentValues[idx];
2752
- }),
2753
- isFirst: false,
2754
- isLast: false,
2755
- };
2756
- return entry;
2757
- }
2758
- function remove(idx) {
2759
- const pathName = unref(arrayPath);
2760
- const pathValue = getFromPath(form === null || form === void 0 ? void 0 : form.values, pathName);
2761
- if (!pathValue || !Array.isArray(pathValue)) {
2762
- return;
2763
- }
2764
- const newValue = [...pathValue];
2765
- newValue.splice(idx, 1);
2766
- form === null || form === void 0 ? void 0 : form.unsetInitialValue(pathName + `[${idx}]`);
2767
- form === null || form === void 0 ? void 0 : form.setFieldValue(pathName, newValue);
2768
- fields.value.splice(idx, 1);
2769
- updateEntryFlags();
2770
- }
2771
- function push(value) {
2772
- const pathName = unref(arrayPath);
2773
- const pathValue = getFromPath(form === null || form === void 0 ? void 0 : form.values, pathName);
2774
- const normalizedPathValue = isNullOrUndefined(pathValue) ? [] : pathValue;
2775
- if (!Array.isArray(normalizedPathValue)) {
2776
- return;
2777
- }
2778
- const newValue = [...normalizedPathValue];
2779
- newValue.push(value);
2780
- form === null || form === void 0 ? void 0 : form.stageInitialValue(pathName + `[${newValue.length - 1}]`, value);
2781
- form === null || form === void 0 ? void 0 : form.setFieldValue(pathName, newValue);
2782
- fields.value.push(createEntry(value));
2783
- updateEntryFlags();
2784
- }
2785
- function swap(indexA, indexB) {
2786
- const pathName = unref(arrayPath);
2787
- const pathValue = getFromPath(form === null || form === void 0 ? void 0 : form.values, pathName);
2788
- if (!Array.isArray(pathValue) || !(indexA in pathValue) || !(indexB in pathValue)) {
2789
- return;
2790
- }
2791
- const newValue = [...pathValue];
2792
- const newFields = [...fields.value];
2793
- // the old switcheroo
2794
- const temp = newValue[indexA];
2795
- newValue[indexA] = newValue[indexB];
2796
- newValue[indexB] = temp;
2797
- const tempEntry = newFields[indexA];
2798
- newFields[indexA] = newFields[indexB];
2799
- newFields[indexB] = tempEntry;
2800
- form === null || form === void 0 ? void 0 : form.setFieldValue(pathName, newValue);
2801
- fields.value = newFields;
2802
- updateEntryFlags();
2803
- }
2804
- function insert(idx, value) {
2805
- const pathName = unref(arrayPath);
2806
- const pathValue = getFromPath(form === null || form === void 0 ? void 0 : form.values, pathName);
2807
- if (!Array.isArray(pathValue) || pathValue.length < idx) {
2808
- return;
2809
- }
2810
- const newValue = [...pathValue];
2811
- const newFields = [...fields.value];
2812
- newValue.splice(idx, 0, value);
2813
- newFields.splice(idx, 0, createEntry(value));
2814
- form === null || form === void 0 ? void 0 : form.setFieldValue(pathName, newValue);
2815
- fields.value = newFields;
2816
- updateEntryFlags();
2817
- }
2818
- function replace(arr) {
2819
- const pathName = unref(arrayPath);
2820
- form === null || form === void 0 ? void 0 : form.setFieldValue(pathName, arr);
2821
- initFields();
2822
- }
2823
- function update(idx, value) {
2824
- const pathName = unref(arrayPath);
2825
- const pathValue = getFromPath(form === null || form === void 0 ? void 0 : form.values, pathName);
2826
- if (!Array.isArray(pathValue) || pathValue.length - 1 < idx) {
2827
- return;
2828
- }
2829
- form === null || form === void 0 ? void 0 : form.setFieldValue(`${pathName}[${idx}]`, value);
2830
- }
2831
- function prepend(value) {
2832
- const pathName = unref(arrayPath);
2833
- const pathValue = getFromPath(form === null || form === void 0 ? void 0 : form.values, pathName);
2834
- const normalizedPathValue = isNullOrUndefined(pathValue) ? [] : pathValue;
2835
- if (!Array.isArray(normalizedPathValue)) {
2836
- return;
2837
- }
2838
- const newValue = [value, ...normalizedPathValue];
2839
- form === null || form === void 0 ? void 0 : form.stageInitialValue(pathName + `[${newValue.length - 1}]`, value);
2840
- form === null || form === void 0 ? void 0 : form.setFieldValue(pathName, newValue);
2841
- fields.value.unshift(createEntry(value));
2842
- updateEntryFlags();
2843
- }
2844
- form.fieldArraysLookup[id] = {
2845
- reset: initFields,
2846
- };
2847
- onBeforeUnmount(() => {
2848
- delete form.fieldArraysLookup[id];
2849
- });
2850
- return {
2851
- fields: readonly(fields),
2852
- remove,
2853
- push,
2854
- swap,
2855
- insert,
2856
- update,
2857
- replace,
2858
- prepend,
2859
- };
2860
- }
2861
-
2862
- const FieldArrayImpl = defineComponent({
2863
- name: 'FieldArray',
2864
- inheritAttrs: false,
2865
- props: {
2866
- name: {
2867
- type: String,
2868
- required: true,
2869
- },
2870
- },
2871
- setup(props, ctx) {
2872
- const { push, remove, swap, insert, replace, update, prepend, fields } = useFieldArray(toRef(props, 'name'));
2873
- function slotProps() {
2874
- return {
2875
- fields: fields.value,
2876
- push,
2877
- remove,
2878
- swap,
2879
- insert,
2880
- update,
2881
- replace,
2882
- prepend,
2883
- };
2884
- }
2885
- ctx.expose({
2886
- push,
2887
- remove,
2888
- swap,
2889
- insert,
2890
- update,
2891
- replace,
2892
- prepend,
2893
- });
2894
- return () => {
2895
- const children = normalizeChildren(undefined, ctx, slotProps);
2896
- return children;
2897
- };
2898
- },
2899
- });
2900
- const FieldArray = FieldArrayImpl;
2901
-
2902
- const ErrorMessageImpl = defineComponent({
2903
- name: 'ErrorMessage',
2904
- props: {
2905
- as: {
2906
- type: String,
2907
- default: undefined,
2908
- },
2909
- name: {
2910
- type: String,
2911
- required: true,
2912
- },
2913
- },
2914
- setup(props, ctx) {
2915
- const form = inject(FormContextKey, undefined);
2916
- const message = computed(() => {
2917
- return form === null || form === void 0 ? void 0 : form.errors.value[props.name];
2918
- });
2919
- function slotProps() {
2920
- return {
2921
- message: message.value,
2922
- };
2923
- }
2924
- return () => {
2925
- // Renders nothing if there are no messages
2926
- if (!message.value) {
2927
- return undefined;
2928
- }
2929
- const tag = (props.as ? resolveDynamicComponent(props.as) : props.as);
2930
- const children = normalizeChildren(tag, ctx, slotProps);
2931
- const attrs = Object.assign({ role: 'alert' }, ctx.attrs);
2932
- // If no tag was specified and there are children
2933
- // render the slot as is without wrapping it
2934
- if (!tag && (Array.isArray(children) || !children) && (children === null || children === void 0 ? void 0 : children.length)) {
2935
- return children;
2936
- }
2937
- // If no children in slot
2938
- // render whatever specified and fallback to a <span> with the message in it's contents
2939
- if ((Array.isArray(children) || !children) && !(children === null || children === void 0 ? void 0 : children.length)) {
2940
- return h(tag || 'span', attrs, message.value);
2941
- }
2942
- return h(tag, attrs, children);
2943
- };
2944
- },
2945
- });
2946
- const ErrorMessage = ErrorMessageImpl;
2947
-
2948
- function useResetForm() {
2949
- const form = injectWithSelf(FormContextKey);
2950
- if (!form) {
2951
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
2952
- }
2953
- return function resetForm(state) {
2954
- if (!form) {
2955
- return;
2956
- }
2957
- return form.resetForm(state);
2958
- };
2959
- }
2960
-
2961
- /**
2962
- * If a field is dirty or not
2963
- */
2964
- function useIsFieldDirty(path) {
2965
- const form = injectWithSelf(FormContextKey);
2966
- let field = path ? undefined : inject(FieldContextKey);
2967
- return computed(() => {
2968
- if (path) {
2969
- field = normalizeField(form === null || form === void 0 ? void 0 : form.fieldsByPath.value[unref(path)]);
2970
- }
2971
- if (!field) {
2972
- warn(`field with name ${unref(path)} was not found`);
2973
- return false;
2974
- }
2975
- return field.meta.dirty;
2976
- });
2977
- }
2978
-
2979
- /**
2980
- * If a field is touched or not
2981
- */
2982
- function useIsFieldTouched(path) {
2983
- const form = injectWithSelf(FormContextKey);
2984
- let field = path ? undefined : inject(FieldContextKey);
2985
- return computed(() => {
2986
- if (path) {
2987
- field = normalizeField(form === null || form === void 0 ? void 0 : form.fieldsByPath.value[unref(path)]);
2988
- }
2989
- if (!field) {
2990
- warn(`field with name ${unref(path)} was not found`);
2991
- return false;
2992
- }
2993
- return field.meta.touched;
2994
- });
2995
- }
2996
-
2997
- /**
2998
- * If a field is validated and is valid
2999
- */
3000
- function useIsFieldValid(path) {
3001
- const form = injectWithSelf(FormContextKey);
3002
- let field = path ? undefined : inject(FieldContextKey);
3003
- return computed(() => {
3004
- if (path) {
3005
- field = normalizeField(form === null || form === void 0 ? void 0 : form.fieldsByPath.value[unref(path)]);
3006
- }
3007
- if (!field) {
3008
- warn(`field with name ${unref(path)} was not found`);
3009
- return false;
3010
- }
3011
- return field.meta.valid;
3012
- });
3013
- }
3014
-
3015
- /**
3016
- * If the form is submitting or not
3017
- */
3018
- function useIsSubmitting() {
3019
- const form = injectWithSelf(FormContextKey);
3020
- if (!form) {
3021
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3022
- }
3023
- return computed(() => {
3024
- var _a;
3025
- return (_a = form === null || form === void 0 ? void 0 : form.isSubmitting.value) !== null && _a !== void 0 ? _a : false;
3026
- });
3027
- }
3028
-
3029
- /**
3030
- * Validates a single field
3031
- */
3032
- function useValidateField(path) {
3033
- const form = injectWithSelf(FormContextKey);
3034
- let field = path ? undefined : inject(FieldContextKey);
3035
- return function validateField() {
3036
- if (path) {
3037
- field = normalizeField(form === null || form === void 0 ? void 0 : form.fieldsByPath.value[unref(path)]);
3038
- }
3039
- if (!field) {
3040
- warn(`field with name ${unref(path)} was not found`);
3041
- return Promise.resolve({
3042
- errors: [],
3043
- valid: true,
3044
- });
3045
- }
3046
- return field.validate();
3047
- };
3048
- }
3049
-
3050
- /**
3051
- * If the form is dirty or not
3052
- */
3053
- function useIsFormDirty() {
3054
- const form = injectWithSelf(FormContextKey);
3055
- if (!form) {
3056
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3057
- }
3058
- return computed(() => {
3059
- var _a;
3060
- return (_a = form === null || form === void 0 ? void 0 : form.meta.value.dirty) !== null && _a !== void 0 ? _a : false;
3061
- });
3062
- }
3063
-
3064
- /**
3065
- * If the form is touched or not
3066
- */
3067
- function useIsFormTouched() {
3068
- const form = injectWithSelf(FormContextKey);
3069
- if (!form) {
3070
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3071
- }
3072
- return computed(() => {
3073
- var _a;
3074
- return (_a = form === null || form === void 0 ? void 0 : form.meta.value.touched) !== null && _a !== void 0 ? _a : false;
3075
- });
3076
- }
3077
-
3078
- /**
3079
- * If the form has been validated and is valid
3080
- */
3081
- function useIsFormValid() {
3082
- const form = injectWithSelf(FormContextKey);
3083
- if (!form) {
3084
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3085
- }
3086
- return computed(() => {
3087
- var _a;
3088
- return (_a = form === null || form === void 0 ? void 0 : form.meta.value.valid) !== null && _a !== void 0 ? _a : false;
3089
- });
3090
- }
3091
-
3092
- /**
3093
- * Validate multiple fields
3094
- */
3095
- function useValidateForm() {
3096
- const form = injectWithSelf(FormContextKey);
3097
- if (!form) {
3098
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3099
- }
3100
- return function validateField() {
3101
- if (!form) {
3102
- return Promise.resolve({ results: {}, errors: {}, valid: true });
3103
- }
3104
- return form.validate();
3105
- };
3106
- }
3107
-
3108
- /**
3109
- * The number of form's submission count
3110
- */
3111
- function useSubmitCount() {
3112
- const form = injectWithSelf(FormContextKey);
3113
- if (!form) {
3114
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3115
- }
3116
- return computed(() => {
3117
- var _a;
3118
- return (_a = form === null || form === void 0 ? void 0 : form.submitCount.value) !== null && _a !== void 0 ? _a : 0;
3119
- });
3120
- }
3121
-
3122
- /**
3123
- * Gives access to a field's current value
3124
- */
3125
- function useFieldValue(path) {
3126
- const form = injectWithSelf(FormContextKey);
3127
- // We don't want to use self injected context as it doesn't make sense
3128
- const field = path ? undefined : inject(FieldContextKey);
3129
- return computed(() => {
3130
- if (path) {
3131
- return getFromPath(form === null || form === void 0 ? void 0 : form.values, unref(path));
3132
- }
3133
- return unref(field === null || field === void 0 ? void 0 : field.value);
3134
- });
3135
- }
3136
-
3137
- /**
3138
- * Gives access to a form's values
3139
- */
3140
- function useFormValues() {
3141
- const form = injectWithSelf(FormContextKey);
3142
- if (!form) {
3143
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3144
- }
3145
- return computed(() => {
3146
- return (form === null || form === void 0 ? void 0 : form.values) || {};
3147
- });
3148
- }
3149
-
3150
- /**
3151
- * Gives access to all form errors
3152
- */
3153
- function useFormErrors() {
3154
- const form = injectWithSelf(FormContextKey);
3155
- if (!form) {
3156
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3157
- }
3158
- return computed(() => {
3159
- return ((form === null || form === void 0 ? void 0 : form.errors.value) || {});
3160
- });
3161
- }
3162
-
3163
- /**
3164
- * Gives access to a single field error
3165
- */
3166
- function useFieldError(path) {
3167
- const form = injectWithSelf(FormContextKey);
3168
- // We don't want to use self injected context as it doesn't make sense
3169
- const field = path ? undefined : inject(FieldContextKey);
3170
- return computed(() => {
3171
- if (path) {
3172
- return form === null || form === void 0 ? void 0 : form.errors.value[unref(path)];
3173
- }
3174
- return field === null || field === void 0 ? void 0 : field.errorMessage.value;
3175
- });
3176
- }
3177
-
3178
- function useSubmitForm(cb) {
3179
- const form = injectWithSelf(FormContextKey);
3180
- if (!form) {
3181
- warn('No vee-validate <Form /> or `useForm` was detected in the component tree');
3182
- }
3183
- const onSubmit = form ? form.handleSubmit(cb) : undefined;
3184
- return function submitForm(e) {
3185
- if (!onSubmit) {
3186
- return;
3187
- }
3188
- return onSubmit(e);
3189
- };
3190
- }
3191
-
3192
- export { Form as F, Field as a, useField as u };