@frollo/frollo-web-ui 0.0.9 → 0.0.12

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