notform 4.0.1 → 4.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1256 +1 @@
1
- import { computed, createBlock, createCommentVNode, createElementBlock, createTextVNode, defineComponent, getCurrentScope, mergeProps, normalizeProps, onScopeDispose, openBlock, reactive, readonly, ref, renderSlot, resolveDynamicComponent, shallowReactive, shallowRef, toDisplayString, toRaw, toValue, triggerRef, watch, withCtx, withModifiers } from "vue";
2
- import { dequal } from "dequal";
3
- import { klona } from "klona";
4
- import { getProperty, parsePath, setProperty } from "dot-prop";
5
- // src/components/array-field.vue
6
- var array_field_default = /* @__PURE__ */ defineComponent({
7
- inheritAttrs: false,
8
- __name: "array-field",
9
- props: { arrayField: {
10
- type: Object,
11
- required: true
12
- } },
13
- setup(__props) {
14
- /** `props.arrayField` is the field created by `form.arrayField('some.path')`. */
15
- const props = __props;
16
- return (_ctx, _cache) => {
17
- return renderSlot(_ctx.$slots, "default", mergeProps({ arrayField: props.arrayField }, _ctx.$attrs));
18
- };
19
- }
20
- });
21
- // src/components/field-error.vue
22
- var field_error_default = /* @__PURE__ */ defineComponent({
23
- inheritAttrs: false,
24
- __name: "field-error",
25
- props: {
26
- as: {
27
- type: null,
28
- required: false,
29
- default: "span"
30
- },
31
- errors: {
32
- type: [Array, Object],
33
- required: true
34
- }
35
- },
36
- setup(__props) {
37
- const props = __props;
38
- const message = computed(() => {
39
- if (Array.isArray(props.errors)) return props.errors[0]?.message;
40
- return props.errors?.errors?.[0]?.message;
41
- });
42
- return (_ctx, _cache) => {
43
- return message.value ? (openBlock(), createBlock(resolveDynamicComponent(props.as), normalizeProps(mergeProps({ key: 0 }, _ctx.$attrs)), {
44
- default: withCtx(() => [renderSlot(_ctx.$slots, "default", { message: message.value }, () => [createTextVNode(toDisplayString(message.value), 1)])]),
45
- _: 3
46
- }, 16)) : createCommentVNode("v-if", true);
47
- };
48
- }
49
- });
50
- // src/components/field.vue
51
- var field_default = /* @__PURE__ */ defineComponent({
52
- inheritAttrs: false,
53
- __name: "field",
54
- props: { field: {
55
- type: Object,
56
- required: true
57
- } },
58
- setup(__props) {
59
- /** `props.field` is the field created by `form.field('some.path')`, or an array item. */
60
- const props = __props;
61
- return (_ctx, _cache) => {
62
- return renderSlot(_ctx.$slots, "default", mergeProps({ field: props.field }, _ctx.$attrs));
63
- };
64
- }
65
- });
66
- // src/components/form.vue
67
- var form_default = /* @__PURE__ */ defineComponent({
68
- inheritAttrs: false,
69
- __name: "form",
70
- props: { form: {
71
- type: Object,
72
- required: true
73
- } },
74
- setup(__props) {
75
- /** `props.form` is the form returned by `useForm()`. */
76
- const props = __props;
77
- return (_ctx, _cache) => {
78
- return openBlock(), createElementBlock("form", mergeProps(_ctx.$attrs, {
79
- onSubmit: _cache[0] || (_cache[0] = (...args) => props.form.submit && props.form.submit(...args)),
80
- onReset: _cache[1] || (_cache[1] = withModifiers((...args) => props.form.reset && props.form.reset(...args), ["prevent"]))
81
- }), [renderSlot(_ctx.$slots, "default")], 16);
82
- };
83
- }
84
- });
85
- // src/utils/path.ts
86
- /**
87
- * @file
88
- * Everything that reads, writes, splits or compares paths lives here, so the
89
- * rest of the code never touches the path library (dot-prop) directly.
90
- *
91
- * - PATH dot-notation text, e.g. 'address.city' or 'tags.0'
92
- * - SEGMENTS the same location split into steps, e.g. ['address', 'city'] or ['tags', 0]
93
- */
94
- /**
95
- * Reads a path step as an array index.
96
- * @param segment A path step: `0`, `'0'`, `{ key: 0 }`, ...
97
- * @returns The index, or `undefined` if the step is not a non-negative integer.
98
- * @example
99
- * getSegmentIndex('2') // 2
100
- * getSegmentIndex('name') // undefined
101
- */
102
- function getSegmentIndex(segment) {
103
- const key = getSegmentKey(segment);
104
- if (typeof key === "number") return Number.isSafeInteger(key) && key >= 0 ? key : void 0;
105
- return typeof key === "string" && /^(?:0|[1-9]\d*)$/.test(key) ? Number(key) : void 0;
106
- }
107
- /**
108
- * Reads the key out of a path step, whether it is bare or wrapped.
109
- * @param segment A path step: `'email'`, `0`, or `{ key: 'email' }`.
110
- * @returns The plain key.
111
- * @example
112
- * getSegmentKey({ key: 'email' }) // 'email'
113
- */
114
- function getSegmentKey(segment) {
115
- if (typeof segment === "object" && segment !== null && "key" in segment) return segment.key;
116
- return segment;
117
- }
118
- /**
119
- * Reads the value at a dot-notation path.
120
- * @param source The object to read from.
121
- * @param path Dot-notation path, e.g. `'tags.0'`.
122
- * @returns The value, or `undefined` if any step is missing.
123
- */
124
- function getValueAtPath(source, path) {
125
- return getProperty(source, path);
126
- }
127
- /**
128
- * Checks whether a path sits at, or below, a parent path.
129
- * @param segments The path being tested.
130
- * @param parentSegments The path it should start with.
131
- * @returns `true` if `segments` equals `parentSegments` or is nested deeper.
132
- * @example
133
- * isPathInside(['user', 'name'], ['user']) // true
134
- * isPathInside(['user'], ['user']) // true
135
- * isPathInside(['user'], ['user', 'name']) // false
136
- */
137
- function isPathInside(segments, parentSegments) {
138
- if (segments.length < parentSegments.length) return false;
139
- return parentSegments.every((parentSegment, index) => {
140
- return isSameSegment(segments[index], parentSegment);
141
- });
142
- }
143
- /**
144
- * Checks whether two paths point at exactly the same place.
145
- * @param firstSegments The first path (e.g. an issue's `path`).
146
- * @param secondSegments The second path.
147
- * @returns `true` if both exist, have the same length, and every step matches.
148
- * @remarks A missing path means "the whole form", so it never equals anything, not even another missing path.
149
- * @example
150
- * isSamePath(['tags', 0], ['tags', '0']) // true
151
- * isSamePath(undefined, undefined) // false
152
- */
153
- function isSamePath(firstSegments, secondSegments) {
154
- if (!firstSegments || !secondSegments || firstSegments.length !== secondSegments.length) return false;
155
- return firstSegments.every((segment, index) => {
156
- return isSameSegment(segment, secondSegments[index]);
157
- });
158
- }
159
- /**
160
- * Checks whether two path steps are the same key.
161
- *
162
- * `0` equals `'0'` because schema libraries disagree on whether array indexes
163
- * are numbers or strings. Wrapped keys (`{ key }`) are unwrapped first.
164
- * @param firstSegment The first step.
165
- * @param secondSegment The second step.
166
- * @returns `true` if both steps refer to the same key.
167
- */
168
- function isSameSegment(firstSegment, secondSegment) {
169
- const firstKey = getSegmentKey(firstSegment);
170
- const secondKey = getSegmentKey(secondSegment);
171
- if (typeof firstKey === "number" && typeof secondKey === "string") return Number.isSafeInteger(firstKey) && String(firstKey) === secondKey;
172
- if (typeof firstKey === "string" && typeof secondKey === "number") return Number.isSafeInteger(secondKey) && firstKey === String(secondKey);
173
- return firstKey === secondKey;
174
- }
175
- /**
176
- * Appends one step to a path.
177
- * @param parentPath The parent path. An empty string means the form root.
178
- * @param key The step to append (property name or array index).
179
- * @returns The combined path.
180
- * @example
181
- * joinPath('tags', 1) // 'tags.1'
182
- * joinPath('', 'name') // 'name'
183
- */
184
- function joinPath(parentPath, key) {
185
- return parentPath === "" ? String(key) : `${parentPath}.${key}`;
186
- }
187
- /**
188
- * Writes a value at a dot-notation path, creating missing steps.
189
- * @param target The object to write into (modified in place).
190
- * @param path Dot-notation path, e.g. `'address.city'`.
191
- * @param value The value to write.
192
- */
193
- function setValueAtPath(target, path, value) {
194
- setProperty(target, path, value);
195
- }
196
- /**
197
- * Splits a dot-notation path into its steps.
198
- * @param path Dot-notation path, e.g. `'tags.0.name'`.
199
- * @returns The steps, e.g. `['tags', '0', 'name']` (indexes may be strings or numbers).
200
- */
201
- function splitPath(path) {
202
- return parsePath(path);
203
- }
204
- // src/utils/validation-issue.ts
205
- /** Message used when something was thrown that carries no readable text. */
206
- const FALLBACK_VALIDATION_ERROR_MESSAGE = "Validation failed";
207
- /**
208
- * Turns anything thrown during validation into a regular issue, so a crashing
209
- * schema shows up as a form error instead of an unhandled exception.
210
- * @param error Whatever was thrown.
211
- * @param path Dot-notation path of the field being validated. Leave out for a form-level error.
212
- * @returns An issue carrying the error's message.
213
- * @example
214
- * createValidationIssueFromError(new Error('Down'), 'email') // { message: 'Down', path: ['email'] }
215
- */
216
- function createValidationIssueFromError(error, path) {
217
- const message = getErrorMessage(error);
218
- return path ? {
219
- message,
220
- path: splitPath(path)
221
- } : { message };
222
- }
223
- /**
224
- * Re-points an issue that lives inside an array after the array was mutated.
225
- * @param issue The issue to adjust.
226
- * @param arraySegments Path of the mutated array.
227
- * @param mapIndex Translates an item's old index to its new one.
228
- * @returns The same issue when it is unaffected, a copy with the new index when the
229
- * item moved, or `undefined` when the item no longer exists.
230
- */
231
- function remapIssueIndex(issue, arraySegments, mapIndex) {
232
- const { path } = issue;
233
- if (!path || path.length <= arraySegments.length || !isPathInside(path, arraySegments)) return issue;
234
- const oldIndex = getSegmentIndex(path[arraySegments.length]);
235
- if (oldIndex === void 0) return issue;
236
- const newIndex = mapIndex(oldIndex);
237
- if (newIndex === void 0) return;
238
- if (newIndex === oldIndex) return issue;
239
- return {
240
- ...issue,
241
- path: [
242
- ...path.slice(0, arraySegments.length),
243
- newIndex,
244
- ...path.slice(arraySegments.length + 1)
245
- ]
246
- };
247
- }
248
- /**
249
- * Extracts readable text from a thrown value.
250
- * @param error Whatever was thrown.
251
- * @returns The `Error` message, the string itself, or a generic fallback.
252
- */
253
- function getErrorMessage(error) {
254
- if (error instanceof Error) return error.message;
255
- if (typeof error === "string") return error;
256
- return FALLBACK_VALIDATION_ERROR_MESSAGE;
257
- }
258
- // src/utils/validation-scope.ts
259
- /**
260
- * Checks whether a new run makes an older run pointless.
261
- *
262
- * A field run only writes the errors of its own path, so it only replaces an
263
- * older run of that same path. A whole-form run writes everything, so it
264
- * replaces any older run.
265
- * @param coveringScope Scope of the new run.
266
- * @param coveredScope Scope of the older run.
267
- * @returns `true` if the older run's result would be overwritten anyway.
268
- */
269
- function doesScopeCover(coveringScope, coveredScope) {
270
- if (coveringScope.type === "form") return true;
271
- return coveredScope.type === "field" && isSamePath(coveringScope.segments, coveredScope.segments);
272
- }
273
- /**
274
- * Builds the scope of a validation run.
275
- * @param path Dot-notation field path. Leave out to cover the whole form.
276
- * @returns A field scope when `path` is given, otherwise a whole-form scope.
277
- * @example
278
- * getValidationScope('tags.0') // { segments: ['tags', '0'], type: 'field' }
279
- */
280
- function getValidationScope(path) {
281
- if (path === void 0) return { type: "form" };
282
- return {
283
- segments: splitPath(path),
284
- type: "field"
285
- };
286
- }
287
- /**
288
- * Checks whether a running validation concerns a field, for `isValidating` flags.
289
- * A field counts as validating while the whole form, the field itself, or any
290
- * field nested inside it is being validated.
291
- * @param runScope Scope of the running validation.
292
- * @param fieldSegments Path of the field being asked about.
293
- * @returns `true` if the run concerns the field.
294
- */
295
- function isFieldAffectedByScope(runScope, fieldSegments) {
296
- if (runScope.type === "form") return true;
297
- return isPathInside(runScope.segments, fieldSegments);
298
- }
299
- // src/utils/array.ts
300
- /**
301
- * Forces an index into `0..max` (inclusive). `NaN` becomes `0`, `Infinity` becomes `max`.
302
- * @param index The requested index.
303
- * @param max The highest allowed index.
304
- * @returns The clamped integer index.
305
- */
306
- function clampIndex(index, max) {
307
- return Math.min(Math.max(Math.trunc(index) || 0, 0), max);
308
- }
309
- /**
310
- * Maps indexes after an item was replaced in place: the replaced item is gone, the rest stay.
311
- * @param at Index of the replaced item.
312
- * @returns The mapper.
313
- */
314
- function createDiscardMapper(at) {
315
- return (index) => {
316
- return index === at ? void 0 : index;
317
- };
318
- }
319
- /**
320
- * Maps indexes after an item was inserted: everything from `at` on shifts up by one.
321
- * @param at Index the new item was inserted at.
322
- * @returns The mapper.
323
- */
324
- function createInsertMapper(at) {
325
- return (index) => {
326
- return index >= at ? index + 1 : index;
327
- };
328
- }
329
- /**
330
- * Maps indexes after an item moved from `from` to `to`.
331
- * @param from Index the item left.
332
- * @param to Index the item landed on.
333
- * @returns The mapper.
334
- */
335
- function createMoveMapper(from, to) {
336
- return (index) => {
337
- if (index === from) return to;
338
- if (from < to && index > from && index <= to) return index - 1;
339
- if (from > to && index >= to && index < from) return index + 1;
340
- return index;
341
- };
342
- }
343
- /**
344
- * Maps indexes after an item was removed: the removed item is gone, later ones shift down by one.
345
- * @param at Index of the removed item.
346
- * @returns The mapper.
347
- */
348
- function createRemoveMapper(at) {
349
- return (index) => {
350
- if (index === at) return;
351
- return index > at ? index - 1 : index;
352
- };
353
- }
354
- /**
355
- * Maps indexes after two items traded places.
356
- * @param indexA Index of the first item.
357
- * @param indexB Index of the second item.
358
- * @returns The mapper.
359
- */
360
- function createSwapMapper(indexA, indexB) {
361
- return (index) => {
362
- if (index === indexA) return indexB;
363
- return index === indexB ? indexA : index;
364
- };
365
- }
366
- /**
367
- * Checks that an index points at an existing item.
368
- * @param index The index to test.
369
- * @param length The length of the list.
370
- * @returns `true` for an integer in `0..length - 1`.
371
- */
372
- function isIndexInRange(index, length) {
373
- return Number.isSafeInteger(index) && index >= 0 && index < length;
374
- }
375
- /**
376
- * Moves one item inside a list, in place. Both indexes must be in range.
377
- * @param list The list to change.
378
- * @param from Current index of the item.
379
- * @param to Index the item should end up at.
380
- */
381
- function moveListItem(list, from, to) {
382
- const [item] = list.splice(from, 1);
383
- list.splice(to, 0, item);
384
- }
385
- /**
386
- * Swaps two items of a list, in place. Both indexes must be in range.
387
- * @param list The list to change.
388
- * @param indexA Index of the first item.
389
- * @param indexB Index of the second item.
390
- */
391
- function swapListItems(list, indexA, indexB) {
392
- const first = list[indexA];
393
- list[indexA] = list[indexB];
394
- list[indexB] = first;
395
- }
396
- // src/utils/id.ts
397
- let lastIssuedNumber = 0;
398
- /**
399
- * Creates the unique, stable identity of a field.
400
- *
401
- * The number in the description is a debugging aid only; always compare ids by reference.
402
- * @param kind What the id is for.
403
- * @returns A new symbol, e.g. `notform.field.3`.
404
- */
405
- function createFieldId(kind) {
406
- lastIssuedNumber += 1;
407
- return Symbol(`notform.${kind}.${lastIssuedNumber}`);
408
- }
409
- // src/utils/debounce.ts
410
- /**
411
- * Cleans up a debounce delay so it is always safe to hand to `setTimeout`.
412
- * @param delayInMilliseconds The delay requested by the user, if any.
413
- * @returns `undefined` when no delay was given; otherwise the delay clamped to
414
- * `0` or more (negative, `NaN` and `Infinity` all become `0`).
415
- * @example
416
- * normalizeDebounce(undefined) // undefined
417
- * normalizeDebounce(-50) // 0
418
- */
419
- function normalizeDebounce(delayInMilliseconds) {
420
- if (delayInMilliseconds === void 0) return;
421
- return Number.isFinite(delayInMilliseconds) ? Math.max(0, delayInMilliseconds) : 0;
422
- }
423
- // src/factories/create-field.ts
424
- /**
425
- * Creates a field: a small reactive handle bound to one value inside a form.
426
- * @template TValue - Type of the value the field holds.
427
- * @param host The form the field belongs to.
428
- * @param options Identity, path source and behavior.
429
- * @returns The field instance and its teardown.
430
- * @remarks Internal. Use `form.field(path)`, which caches the result.
431
- */
432
- function createField(host, options) {
433
- const { dispose, parts } = createFieldState(host, options);
434
- return {
435
- dispose,
436
- instance: reactive(parts)
437
- };
438
- }
439
- /**
440
- * Builds the state every kind of field shares (plain field, array field, array item).
441
- *
442
- * The field owns no data: `model` reads and writes straight into the form's values,
443
- * and the path is resolved on every read, so the field stays correct when it moves.
444
- * @template TValue - Type of the value the field holds.
445
- * @param host The form the field belongs to.
446
- * @param options Identity, path source and behavior.
447
- * @returns `parts`, the raw members (computed refs and functions) to wrap in `reactive()`, `dispose`,
448
- * and `isDisposed`. A disposed field is inert: events, writes and validation do nothing.
449
- */
450
- function createFieldState(host, options) {
451
- const id = options.id ?? createFieldId("field");
452
- const config = resolveFieldConfig(options.config);
453
- let isDisposed = false;
454
- let lastKnownPath = "";
455
- /** Current path. Frozen at its last value once the field is disposed. */
456
- const path = computed(() => {
457
- if (!isDisposed) lastKnownPath = options.getPath();
458
- return lastKnownPath;
459
- });
460
- /** Two-way link to the form's value at `path`. */
461
- const model = computed({
462
- get: () => {
463
- return host.getValue(path.value);
464
- },
465
- set: (value) => {
466
- if (!isDisposed) host.setValue(path.value, value);
467
- }
468
- });
469
- const isDirty = computed(() => {
470
- return !dequal(model.value, host.getInitialValue(path.value));
471
- });
472
- const isTouched = computed(() => {
473
- return host.isFieldTouched(id);
474
- });
475
- const errors = computed(() => {
476
- return host.getFieldErrors(path.value);
477
- });
478
- const isValid = computed(() => {
479
- return errors.value.length === 0;
480
- });
481
- const isValidating = computed(() => {
482
- return host.isFieldValidating(path.value);
483
- });
484
- function validate() {
485
- if (isDisposed) return Promise.resolve({ value: void 0 });
486
- host.cancelFieldTask(id);
487
- return host.validateField(path.value);
488
- }
489
- /**
490
- * Validates in response to `change` / `input`, honouring `validateOn`, the mode and the debounce.
491
- * @param event The event that fired.
492
- */
493
- function validateOnEvent(event) {
494
- if (isDisposed) return;
495
- if (!(config.validateOn[event] || config.validationMode === "eager" && errors.value.length > 0)) return;
496
- if (config.debounce) {
497
- host.scheduleFieldTask(id, config.debounce, () => {
498
- validate();
499
- });
500
- return;
501
- }
502
- validate();
503
- }
504
- function onBlur() {
505
- if (isDisposed) return;
506
- host.touchField(id);
507
- if (config.validateOn.blur) validate();
508
- }
509
- function onChange() {
510
- validateOnEvent("change");
511
- }
512
- function onInput() {
513
- validateOnEvent("input");
514
- }
515
- function dispose() {
516
- if (isDisposed) return;
517
- if (lastKnownPath === "") lastKnownPath = options.getPath();
518
- isDisposed = true;
519
- host.cancelFieldTask(id);
520
- host.untouchField(id);
521
- }
522
- return {
523
- dispose,
524
- isDisposed: () => {
525
- return isDisposed;
526
- },
527
- parts: {
528
- errors,
529
- events: {
530
- onBlur,
531
- onChange,
532
- onInput
533
- },
534
- id,
535
- isDirty,
536
- isTouched,
537
- isValid,
538
- isValidating,
539
- model,
540
- path,
541
- validate
542
- }
543
- };
544
- }
545
- /**
546
- * Merges the user's config over the defaults.
547
- * @param config The config passed to `form.field()`.
548
- * @returns A complete config (blur and change validate, input does not; eager mode).
549
- */
550
- function resolveFieldConfig(config) {
551
- return {
552
- debounce: normalizeDebounce(config?.debounce),
553
- validateOn: {
554
- blur: config?.validateOn?.blur ?? true,
555
- change: config?.validateOn?.change ?? true,
556
- input: config?.validateOn?.input ?? false
557
- },
558
- validationMode: config?.validationMode ?? "eager"
559
- };
560
- }
561
- // src/factories/create-array-field.ts
562
- /**
563
- * Creates an array field: a field for the array itself, plus one stable identity
564
- * per item and the mutations that keep values, ids and errors in step.
565
- *
566
- * Bookkeeping lives in one place: `ids`, a list parallel to the array.
567
- * - Every mutation edits the array, `ids` and the form's errors together.
568
- * - If the array is changed behind our back, `ids` is reconciled by length the next
569
- * time it is read (new ids at the end, extra ids dropped). On form reset all ids are renewed.
570
- * - Once the field is disposed (its item was removed) it is inert: mutations do nothing and
571
- * `items` is empty, so a stale handle can never write into the item that took its place.
572
- * @template TItem - Type of one array item.
573
- * @param host The form the field belongs to.
574
- * @param options Path source, behavior and the scope factory for nested fields.
575
- * @returns The array field instance and its teardown.
576
- * @remarks Internal. Use `form.arrayField(path)`, which caches the result.
577
- */
578
- function createArrayField(host, options) {
579
- const base = createFieldState(host, {
580
- config: options.config,
581
- getPath: options.getPath,
582
- id: createFieldId("array-field")
583
- });
584
- const arrayPath = base.parts.path;
585
- /** One id per array item, same order as the array. Mutated in place; `triggerRef` announces changes. */
586
- const ids = shallowRef([]);
587
- /** Item fields by id, created on demand. */
588
- const itemNodes = /* @__PURE__ */ new Map();
589
- /** The form's reset count when `ids` was last in sync. */
590
- let seenResetCount = host.getResetCount();
591
- /**
592
- * Reads the array this field points at.
593
- * @returns The reactive array, or `undefined` if the value is missing or not an array.
594
- */
595
- function readArray() {
596
- const value = host.getValue(arrayPath.value);
597
- return Array.isArray(value) ? value : void 0;
598
- }
599
- /**
600
- * Reads the array, creating an empty one if the value is missing.
601
- * @returns The reactive array.
602
- * @throws If an array cannot be created at the path.
603
- */
604
- function ensureArray() {
605
- const existing = readArray();
606
- if (existing) return existing;
607
- host.setValue(arrayPath.value, []);
608
- const created = readArray();
609
- if (!created) throw new TypeError(`[notform] Cannot create an array at "${arrayPath.value}"`);
610
- return created;
611
- }
612
- /**
613
- * Tears down item fields whose ids left the list.
614
- * @param removedIds The ids that were removed.
615
- * @param isDeferred Run the teardown in a microtask. Needed when called while a computed is
616
- * evaluating, because teardown writes reactive state (the touched set).
617
- */
618
- function releaseItems(removedIds, isDeferred) {
619
- for (const removedId of removedIds) {
620
- const node = itemNodes.get(removedId);
621
- if (!node) continue;
622
- itemNodes.delete(removedId);
623
- if (isDeferred) queueMicrotask(node.dispose);
624
- else node.dispose();
625
- }
626
- }
627
- /**
628
- * Brings `ids` in line with the array, then returns it.
629
- * @returns The id list (same length as the array).
630
- */
631
- function syncIds() {
632
- const list = ids.value;
633
- if (base.isDisposed()) return list;
634
- const resetCount = host.getResetCount();
635
- if (resetCount !== seenResetCount) {
636
- seenResetCount = resetCount;
637
- releaseItems(list.splice(0), true);
638
- }
639
- const length = readArray()?.length ?? 0;
640
- while (list.length < length) list.push(createFieldId("array-item"));
641
- if (list.length > length) releaseItems(list.splice(length), true);
642
- return list;
643
- }
644
- /** Announces a finished mutation: refreshes `items` and validates per the field's config. */
645
- function commit() {
646
- triggerRef(ids);
647
- base.parts.events.onChange();
648
- }
649
- function insert(index, value) {
650
- if (base.isDisposed()) return;
651
- const list = syncIds();
652
- const array = ensureArray();
653
- const at = clampIndex(index, list.length);
654
- list.splice(at, 0, createFieldId("array-item"));
655
- array.splice(at, 0, cloneValue(value));
656
- host.remapArrayErrors(arrayPath.value, createInsertMapper(at));
657
- commit();
658
- }
659
- function append(value) {
660
- insert(syncIds().length, value);
661
- }
662
- function prepend(value) {
663
- insert(0, value);
664
- }
665
- function remove(index) {
666
- const list = syncIds();
667
- if (base.isDisposed() || !isIndexInRange(index, list.length)) return;
668
- releaseItems(list.splice(index, 1), false);
669
- ensureArray().splice(index, 1);
670
- host.remapArrayErrors(arrayPath.value, createRemoveMapper(index));
671
- commit();
672
- }
673
- function move(from, to) {
674
- const list = syncIds();
675
- if (from === to || base.isDisposed() || !isIndexInRange(from, list.length) || !isIndexInRange(to, list.length)) return;
676
- moveListItem(list, from, to);
677
- moveListItem(ensureArray(), from, to);
678
- host.remapArrayErrors(arrayPath.value, createMoveMapper(from, to));
679
- commit();
680
- }
681
- function swap(indexA, indexB) {
682
- const list = syncIds();
683
- if (indexA === indexB || base.isDisposed() || !isIndexInRange(indexA, list.length) || !isIndexInRange(indexB, list.length)) return;
684
- swapListItems(list, indexA, indexB);
685
- swapListItems(ensureArray(), indexA, indexB);
686
- host.remapArrayErrors(arrayPath.value, createSwapMapper(indexA, indexB));
687
- commit();
688
- }
689
- function update(index, value) {
690
- if (base.isDisposed() || !isIndexInRange(index, syncIds().length)) return;
691
- ensureArray()[index] = cloneValue(value);
692
- host.remapArrayErrors(arrayPath.value, createDiscardMapper(index));
693
- commit();
694
- }
695
- /**
696
- * Creates the field of one array item.
697
- * @param id The item's id.
698
- * @returns The item instance and its teardown.
699
- */
700
- function createItemNode(id) {
701
- let lastIndex = ids.value.indexOf(id);
702
- /** Position of the item. Keeps its last value once the item is gone, so its path never turns into `-1`. */
703
- const index = computed(() => {
704
- const currentIndex = syncIds().indexOf(id);
705
- if (currentIndex !== -1) lastIndex = currentIndex;
706
- return lastIndex;
707
- });
708
- const getItemPath = () => {
709
- return joinPath(arrayPath.value, index.value);
710
- };
711
- const scope = options.createScope(getItemPath);
712
- const state = createFieldState(host, {
713
- config: options.config,
714
- getPath: getItemPath,
715
- id
716
- });
717
- return {
718
- dispose: () => {
719
- scope.dispose();
720
- state.dispose();
721
- },
722
- instance: reactive({
723
- ...state.parts,
724
- arrayField: scope.arrayField,
725
- field: scope.field,
726
- index
727
- })
728
- };
729
- }
730
- /**
731
- * Gets or creates the field of the item with this id.
732
- * @param id The item's id.
733
- * @returns The cached item instance.
734
- */
735
- function getItem(id) {
736
- let node = itemNodes.get(id);
737
- if (!node) {
738
- node = createItemNode(id);
739
- itemNodes.set(id, node);
740
- }
741
- return node.instance;
742
- }
743
- const items = computed(() => {
744
- return base.isDisposed() ? [] : syncIds().map((id) => {
745
- return getItem(id);
746
- });
747
- });
748
- function dispose() {
749
- for (const node of itemNodes.values()) node.dispose();
750
- itemNodes.clear();
751
- base.dispose();
752
- }
753
- return {
754
- dispose,
755
- instance: reactive({
756
- ...base.parts,
757
- append,
758
- insert,
759
- items,
760
- move,
761
- prepend,
762
- remove,
763
- swap,
764
- update
765
- })
766
- };
767
- }
768
- /**
769
- * Deep-copies a value on its way in, so two items never share one object.
770
- * @param value The value to copy.
771
- * @returns The copy.
772
- */
773
- function cloneValue(value) {
774
- return klona(toRaw(value));
775
- }
776
- // src/factories/create-field-scope.ts
777
- /**
778
- * Creates a scope: the place that creates fields under a base path and keeps
779
- * one instance per relative path.
780
- *
781
- * Caching is what gives fields a stable identity. A template may call
782
- * `form.field('name')` on every render and always gets the same field, so its
783
- * id, touched state and pending validation survive re-renders.
784
- * @param host The form the fields belong to.
785
- * @param getBasePath Returns the base path. The form root uses `() => ''`; an array item
786
- * uses its own current path, so nested fields follow the item when it moves.
787
- * @returns The scope. After `dispose()`, fields it still hands out are inert.
788
- */
789
- function createFieldScope(host, getBasePath) {
790
- const nodes = /* @__PURE__ */ new Map();
791
- let isDisposed = false;
792
- function field(path, config) {
793
- const key = `field:${path}`;
794
- let node = nodes.get(key);
795
- if (!node) {
796
- node = createField(host, {
797
- config,
798
- getPath: () => {
799
- return joinPath(getBasePath(), path);
800
- }
801
- });
802
- nodes.set(key, node);
803
- if (isDisposed) node.dispose();
804
- }
805
- return node.instance;
806
- }
807
- function arrayField(path, config) {
808
- const key = `array:${path}`;
809
- let node = nodes.get(key);
810
- if (!node) {
811
- node = createArrayField(host, {
812
- config,
813
- createScope: (getItemPath) => {
814
- return createFieldScope(host, getItemPath);
815
- },
816
- getPath: () => {
817
- return joinPath(getBasePath(), path);
818
- }
819
- });
820
- nodes.set(key, node);
821
- if (isDisposed) node.dispose();
822
- }
823
- return node.instance;
824
- }
825
- function dispose() {
826
- isDisposed = true;
827
- for (const node of nodes.values()) node.dispose();
828
- nodes.clear();
829
- }
830
- return {
831
- arrayField,
832
- dispose,
833
- field
834
- };
835
- }
836
- // src/factories/create-validation-run-registry.ts
837
- /**
838
- * Creates a tracker for validations that are currently running.
839
- *
840
- * Validation is async, so a second one can start before the first finishes.
841
- * The registry marks the older run stale, so its result is dropped instead of
842
- * overwriting fresher data.
843
- * @returns Functions to start a run, finish a run, and invalidate every run.
844
- * @remarks One registry per form.
845
- * @example
846
- * const run = runs.startRun('field', 'email')
847
- * // ... await validation ...
848
- * if (!run.isStale) {
849
- * applyResult()
850
- * }
851
- * runs.finishRun(run)
852
- */
853
- function createValidationRunRegistry() {
854
- /** Id of the most recently started run. Only ever goes up. */
855
- let latestRunId = 0;
856
- /** Runs that started but have not finished, keyed by run id. */
857
- const activeRuns = reactive(/* @__PURE__ */ new Map());
858
- /**
859
- * Registers a run and marks the older runs it replaces as stale.
860
- *
861
- * A run replaces another when its result would overwrite it (see `doesScopeCover`).
862
- * A running submit is never replaced by a non-submit run: a field check or a
863
- * manual `validate()` must not cancel a submit in progress.
864
- * @param origin What started the run.
865
- * @param path Dot-notation field path. Leave out for a whole-form run.
866
- * @returns The new run. Check `run.isStale` after awaiting.
867
- */
868
- function startRun(origin, path) {
869
- const newRun = {
870
- id: ++latestRunId,
871
- isStale: false,
872
- origin,
873
- scope: getValidationScope(path)
874
- };
875
- for (const [activeRunId, activeRun] of activeRuns) {
876
- if (origin !== "submit" && activeRun.origin === "submit" || !doesScopeCover(newRun.scope, activeRun.scope)) continue;
877
- activeRun.isStale = true;
878
- activeRuns.delete(activeRunId);
879
- }
880
- activeRuns.set(newRun.id, newRun);
881
- return newRun;
882
- }
883
- /**
884
- * Removes a run from the active list, whether it succeeded, failed or went stale. Safe to call twice.
885
- * @param run The run returned by `startRun`.
886
- */
887
- function finishRun(run) {
888
- activeRuns.delete(run.id);
889
- }
890
- /** Marks every active run stale and empties the list (form reset, value change, schema change). */
891
- function markAllRunsStale() {
892
- for (const run of activeRuns.values()) run.isStale = true;
893
- activeRuns.clear();
894
- }
895
- return {
896
- activeRuns: readonly(activeRuns),
897
- finishRun,
898
- markAllRunsStale,
899
- startRun
900
- };
901
- }
902
- // src/factories/create-form.ts
903
- /**
904
- * Builds a complete reactive form: values, errors, validation, submit handling,
905
- * and the registry that gives every field a stable identity.
906
- *
907
- * Single source of truth:
908
- * - values live in `values`; fields only point at them by path;
909
- * - errors live in `errors` as the schema reports them (by path); array mutations re-point them;
910
- * - touched state lives in `touchedFields`, keyed by field id, so it survives reordering;
911
- * - pending debounced validations live in `fieldTasks`, keyed by field id.
912
- * @template TSchema - The schema describing the form's data (must be an object schema).
913
- * @param config Schema, starting values/errors, and the submit handler.
914
- * @returns The full reactive form.
915
- * @remarks Internal building block. Prefer the `useForm` composable.
916
- */
917
- function createForm(config) {
918
- const initialValues = shallowRef(klona(toRaw(config.initialValues ?? {})));
919
- const initialErrors = shallowRef(klona(toRaw(config.initialErrors ?? [])));
920
- /** Live form data (a separate copy of the initial values). */
921
- const values = reactive(klona(initialValues.value));
922
- /** Live validation errors (a separate copy of the initial errors). */
923
- const errors = reactive(klona(initialErrors.value));
924
- /** Ids of the fields that were blurred. */
925
- const touchedFields = shallowReactive(/* @__PURE__ */ new Set());
926
- /** Debounced validations waiting to fire, by field id. */
927
- const fieldTasks = /* @__PURE__ */ new Map();
928
- const isSubmitting = ref(false);
929
- const submitCount = ref(0);
930
- const resetCount = ref(0);
931
- const isSubmitted = computed(() => {
932
- return submitCount.value > 0;
933
- });
934
- const isTouched = computed(() => {
935
- return isSubmitted.value || touchedFields.size > 0;
936
- });
937
- const isDirty = computed(() => {
938
- return !dequal(values, initialValues.value);
939
- });
940
- const isValid = computed(() => {
941
- return errors.length === 0;
942
- });
943
- function touchField(id) {
944
- touchedFields.add(id);
945
- }
946
- function untouchField(id) {
947
- touchedFields.delete(id);
948
- }
949
- function isFieldTouched(id) {
950
- return isSubmitted.value || touchedFields.has(id);
951
- }
952
- function cancelFieldTask(id) {
953
- const timer = fieldTasks.get(id);
954
- if (timer === void 0) return;
955
- clearTimeout(timer);
956
- fieldTasks.delete(id);
957
- }
958
- function cancelAllFieldTasks() {
959
- for (const timer of fieldTasks.values()) clearTimeout(timer);
960
- fieldTasks.clear();
961
- }
962
- function scheduleFieldTask(id, delay, task) {
963
- cancelFieldTask(id);
964
- fieldTasks.set(id, setTimeout(() => {
965
- fieldTasks.delete(id);
966
- task();
967
- }, delay));
968
- }
969
- /** Tracks running validations so outdated results can be discarded. */
970
- const validationRuns = createValidationRunRegistry();
971
- /**
972
- * Increases every time a submit starts. A submit loop keeps going only while its own
973
- * attempt id is still the latest, so bumping this elsewhere cancels the submit in progress.
974
- */
975
- let latestSubmitAttemptId = 0;
976
- const isValidating = computed(() => {
977
- return validationRuns.activeRuns.size > 0;
978
- });
979
- /**
980
- * Validates a snapshot of the current values against the schema.
981
- * @returns The schema result (`{ value }` or `{ issues }`), sync or async.
982
- */
983
- function validateAgainstSchema() {
984
- const schema = toValue(config.schema);
985
- const valuesSnapshot = klona(toRaw(values));
986
- return schema["~standard"].validate(valuesSnapshot);
987
- }
988
- /**
989
- * Runs one validation and reports whether it was replaced meanwhile.
990
- * Never throws: a crashing schema becomes a normal issue.
991
- * @param origin What started this validation.
992
- * @param path Dot-notation field path. Leave out for a whole-form run.
993
- * @returns The schema result and whether it went stale.
994
- */
995
- async function runValidation(origin, path) {
996
- const run = validationRuns.startRun(origin, path);
997
- try {
998
- let result;
999
- try {
1000
- result = await validateAgainstSchema();
1001
- } catch (error) {
1002
- result = { issues: [createValidationIssueFromError(error, path)] };
1003
- }
1004
- return {
1005
- isStale: run.isStale,
1006
- result
1007
- };
1008
- } finally {
1009
- validationRuns.finishRun(run);
1010
- }
1011
- }
1012
- watch(() => {
1013
- return toValue(config.schema);
1014
- }, () => {
1015
- validationRuns.markAllRunsStale();
1016
- }, { flush: "sync" });
1017
- watch(values, () => {
1018
- validationRuns.markAllRunsStale();
1019
- }, {
1020
- deep: true,
1021
- flush: "sync"
1022
- });
1023
- function getValue(path) {
1024
- return getValueAtPath(values, path);
1025
- }
1026
- function setValue(path, value) {
1027
- setValueAtPath(values, path, value);
1028
- }
1029
- function replaceErrors(nextErrors) {
1030
- errors.splice(0, errors.length, ...nextErrors);
1031
- }
1032
- function clearErrors() {
1033
- errors.length = 0;
1034
- }
1035
- function getFieldErrors(path) {
1036
- const targetPath = splitPath(path);
1037
- return errors.filter((error) => {
1038
- return isSamePath(error.path, targetPath);
1039
- });
1040
- }
1041
- /**
1042
- * Replaces the errors sitting exactly at a path. Leaves the other errors alone.
1043
- * @param segments The path whose errors are replaced.
1044
- * @param nextIssues The new errors for that path.
1045
- */
1046
- function replaceErrorsAt(segments, nextIssues) {
1047
- const keptErrors = errors.filter((error) => {
1048
- return !isSamePath(error.path, segments);
1049
- });
1050
- if (keptErrors.length === errors.length && nextIssues.length === 0) return;
1051
- replaceErrors([...keptErrors, ...nextIssues]);
1052
- }
1053
- function setError(error) {
1054
- if (error.path) replaceErrorsAt(error.path, [error]);
1055
- else errors.push(error);
1056
- }
1057
- /**
1058
- * Re-points the errors inside an array after it was mutated, so each error stays with its item.
1059
- * @param arrayPath Path of the mutated array.
1060
- * @param mapIndex Translates an item's old index to its new one (`undefined` drops the error).
1061
- */
1062
- function remapArrayErrors(arrayPath, mapIndex) {
1063
- const arraySegments = splitPath(arrayPath);
1064
- const remappedErrors = [];
1065
- let hasChanged = false;
1066
- for (const error of errors) {
1067
- const remapped = remapIssueIndex(error, arraySegments, mapIndex);
1068
- if (remapped !== error) hasChanged = true;
1069
- if (remapped) remappedErrors.push(remapped);
1070
- }
1071
- if (hasChanged) replaceErrors(remappedErrors);
1072
- }
1073
- function isFieldValidating(path) {
1074
- const fieldSegments = splitPath(path);
1075
- for (const activeRun of validationRuns.activeRuns.values()) if (isFieldAffectedByScope(activeRun.scope, fieldSegments)) return true;
1076
- return false;
1077
- }
1078
- /**
1079
- * Validates a single field and updates only that field's errors.
1080
- * The whole form is checked against the schema, but only issues sitting exactly at `path` are kept.
1081
- * @param path Dot-notation path to the field.
1082
- * @returns `{ issues }` if the field is invalid, otherwise `{ value }` with its current input value.
1083
- * A result made obsolete by a newer run is returned, but the errors are left untouched.
1084
- */
1085
- async function validateField(path) {
1086
- const { isStale, result } = await runValidation("field", path);
1087
- const fieldSegments = splitPath(path);
1088
- const fieldIssues = (result.issues ?? []).filter((issue) => {
1089
- return isSamePath(issue.path, fieldSegments);
1090
- });
1091
- if (!isStale) replaceErrorsAt(fieldSegments, fieldIssues);
1092
- return fieldIssues.length > 0 ? { issues: fieldIssues } : { value: getValue(path) };
1093
- }
1094
- /**
1095
- * Validates the whole form and replaces all errors with the outcome.
1096
- * @returns The schema result. If a newer validation replaced this one, errors are left untouched.
1097
- */
1098
- async function validate() {
1099
- const { isStale, result } = await runValidation("form");
1100
- if (!isStale) replaceErrors(result.issues ? [...result.issues] : []);
1101
- return result;
1102
- }
1103
- /**
1104
- * Validates the whole form and, if valid, calls `config.onSubmit` with the parsed data.
1105
- *
1106
- * - Ignored while a submit is already running.
1107
- * - If validation is replaced mid-flight (the user kept typing), it is simply run again.
1108
- * - On failure, errors are shown and `onSubmit` is not called.
1109
- * @param event Browser submit event; its default page reload is prevented.
1110
- * @throws Whatever `config.onSubmit` throws (after `isSubmitting` has been reset).
1111
- */
1112
- async function submit(event) {
1113
- event?.preventDefault();
1114
- if (isSubmitting.value) return;
1115
- isSubmitting.value = true;
1116
- submitCount.value++;
1117
- const thisSubmitAttemptId = ++latestSubmitAttemptId;
1118
- try {
1119
- while (thisSubmitAttemptId === latestSubmitAttemptId) {
1120
- const { isStale, result } = await runValidation("submit");
1121
- if (thisSubmitAttemptId !== latestSubmitAttemptId) return;
1122
- if (isStale) continue;
1123
- if (result.issues) {
1124
- replaceErrors([...result.issues]);
1125
- return;
1126
- }
1127
- clearErrors();
1128
- await config.onSubmit?.(result.value);
1129
- return;
1130
- }
1131
- } finally {
1132
- if (thisSubmitAttemptId === latestSubmitAttemptId) isSubmitting.value = false;
1133
- }
1134
- }
1135
- function reset(nextValues, nextErrors) {
1136
- const freshValues = isEvent(nextValues) ? void 0 : nextValues;
1137
- validationRuns.markAllRunsStale();
1138
- cancelAllFieldTasks();
1139
- latestSubmitAttemptId++;
1140
- isSubmitting.value = false;
1141
- if (freshValues !== void 0) initialValues.value = klona(toRaw(freshValues));
1142
- if (nextErrors !== void 0) initialErrors.value = klona(toRaw(nextErrors));
1143
- replaceRecordContents(values, klona(initialValues.value));
1144
- replaceErrors(klona(initialErrors.value));
1145
- touchedFields.clear();
1146
- submitCount.value = 0;
1147
- resetCount.value++;
1148
- }
1149
- /** The root scope: `form.field(path)` and `form.arrayField(path)` live here. */
1150
- const rootScope = createFieldScope({
1151
- cancelFieldTask,
1152
- getFieldErrors,
1153
- getInitialValue: (path) => {
1154
- return getValueAtPath(initialValues.value, path);
1155
- },
1156
- getResetCount: () => {
1157
- return resetCount.value;
1158
- },
1159
- getValue,
1160
- isFieldTouched,
1161
- isFieldValidating,
1162
- remapArrayErrors,
1163
- scheduleFieldTask,
1164
- setValue,
1165
- touchField,
1166
- untouchField,
1167
- validateField
1168
- }, () => {
1169
- return "";
1170
- });
1171
- if (getCurrentScope()) onScopeDispose(() => {
1172
- validationRuns.markAllRunsStale();
1173
- cancelAllFieldTasks();
1174
- rootScope.dispose();
1175
- });
1176
- return reactive({
1177
- arrayField: rootScope.arrayField,
1178
- clearErrors,
1179
- errors,
1180
- field: rootScope.field,
1181
- getFieldErrors,
1182
- getValue,
1183
- initialErrors,
1184
- initialValues,
1185
- isDirty,
1186
- isFieldValidating,
1187
- isSubmitted,
1188
- isSubmitting,
1189
- isTouched,
1190
- isValid,
1191
- isValidating,
1192
- replaceErrors,
1193
- reset,
1194
- resetCount,
1195
- setError,
1196
- setValue,
1197
- submit,
1198
- submitCount,
1199
- validate,
1200
- validateField,
1201
- values
1202
- });
1203
- }
1204
- /**
1205
- * Tells an event apart from starting values.
1206
- * @param value The first argument given to `reset`.
1207
- * @returns `true` if it is a DOM event.
1208
- */
1209
- function isEvent(value) {
1210
- return typeof Event !== "undefined" && value instanceof Event;
1211
- }
1212
- /**
1213
- * Empties a reactive record and refills it, keeping the same object identity.
1214
- * @param target The record to replace the contents of.
1215
- * @param source The new contents.
1216
- */
1217
- function replaceRecordContents(target, source) {
1218
- for (const key of Object.keys(target)) delete target[key];
1219
- Object.assign(target, source);
1220
- }
1221
- // src/composables/use-form.ts
1222
- /**
1223
- * Creates a reactive, schema-validated form. Call it inside `setup()`, so its
1224
- * watchers and pending timers are cleaned up when the component unmounts.
1225
- * @template TSchema - A Standard Schema (Zod, Valibot, ArkType, ...) describing the form's data. Must be an object schema.
1226
- * @param config The schema, optional starting values/errors, and an optional submit handler.
1227
- * @returns The form. Pass it to `<Form :form />` and use `form.field(path)` / `form.arrayField(path)` to create fields.
1228
- * @example
1229
- * ```vue
1230
- * <script setup lang="ts">
1231
- * import { z } from 'zod'
1232
- * import { Field, Form, useForm } from 'notform'
1233
- *
1234
- * const form = useForm({
1235
- * schema: z.object({ email: z.email() }),
1236
- * initialValues: { email: '' },
1237
- * onSubmit: async (data) => {
1238
- * await api.signUp(data) // `data` is the validated output
1239
- * },
1240
- * })
1241
- * <\/script>
1242
- *
1243
- * <template>
1244
- * <Form :form>
1245
- * <Field v-slot="{ field }" :field="form.field('email')">
1246
- * <input v-model="field.model" v-bind="field.events" type="email">
1247
- * </Field>
1248
- * <button type="submit" :disabled="form.isSubmitting">Sign up</button>
1249
- * </Form>
1250
- * </template>
1251
- * ```
1252
- */
1253
- function useForm(config) {
1254
- return createForm(config);
1255
- }
1256
- export { array_field_default as ArrayField, field_default as Field, field_error_default as FieldError, form_default as Form, useForm };
1
+ import{computed as e,createBlock as t,createCommentVNode as n,createElementBlock as r,createTextVNode as i,defineComponent as a,getCurrentScope as o,mergeProps as s,normalizeProps as c,onScopeDispose as l,openBlock as u,reactive as d,readonly as f,ref as p,renderSlot as m,resolveDynamicComponent as h,shallowReactive as g,shallowRef as _,toDisplayString as v,toRaw as y,toValue as b,triggerRef as ee,watch as x,withCtx as S,withModifiers as C}from"vue";import{dequal as w}from"dequal";import{klona as T}from"klona";import{getProperty as E,parsePath as D,setProperty as O}from"dot-prop";var k=/* @__PURE__ */ a({inheritAttrs:!1,__name:`array-field`,props:{arrayField:{type:Object,required:!0}},setup(e){let t=e;return(e,n)=>m(e.$slots,`default`,s({arrayField:t.arrayField},e.$attrs))}}),A=/* @__PURE__ */ a({inheritAttrs:!1,__name:`field-error`,props:{as:{type:null,required:!1,default:`span`},errors:{type:[Array,Object],required:!0}},setup(r){let a=r,o=e(()=>Array.isArray(a.errors)?a.errors[0]?.message:a.errors?.errors?.[0]?.message);return(e,r)=>o.value?(u(),t(h(a.as),c(s({key:0},e.$attrs)),{default:S(()=>[m(e.$slots,`default`,{message:o.value},()=>[i(v(o.value),1)])]),_:3},16)):n(`v-if`,!0)}}),j=/* @__PURE__ */ a({inheritAttrs:!1,__name:`field`,props:{field:{type:Object,required:!0}},setup(e){let t=e;return(e,n)=>m(e.$slots,`default`,s({field:t.field},e.$attrs))}}),M=/* @__PURE__ */ a({inheritAttrs:!1,__name:`form`,props:{form:{type:Object,required:!0}},setup(e){let t=e;return(e,n)=>(u(),r(`form`,s(e.$attrs,{onSubmit:n[0]||=(...e)=>t.form.submit&&t.form.submit(...e),onReset:n[1]||=C((...e)=>t.form.reset&&t.form.reset(...e),[`prevent`])}),[m(e.$slots,`default`)],16))}});function te(e){let t=N(e);return typeof t==`number`?Number.isSafeInteger(t)&&t>=0?t:void 0:typeof t==`string`&&/^(?:0|[1-9]\d*)$/.test(t)?Number(t):void 0}function N(e){return typeof e==`object`&&e&&`key`in e?e.key:e}function P(e,t){return E(e,t)}function F(e,t){return e.length<t.length?!1:t.every((t,n)=>L(e[n],t))}function I(e,t){return!e||!t||e.length!==t.length?!1:e.every((e,n)=>L(e,t[n]))}function L(e,t){let n=N(e),r=N(t);return typeof n==`number`&&typeof r==`string`?Number.isSafeInteger(n)&&String(n)===r:typeof n==`string`&&typeof r==`number`?Number.isSafeInteger(r)&&n===String(r):n===r}function R(e,t){return e===``?String(t):`${e}.${t}`}function ne(e,t,n){O(e,t,n)}function z(e){return D(e)}function re(e,t){let n=B(e);return t?{message:n,path:z(t)}:{message:n}}function ie(e,t,n){let{path:r}=e;if(!r||r.length<=t.length||!F(r,t))return e;let i=te(r[t.length]);if(i===void 0)return e;let a=n(i);if(a!==void 0)return a===i?e:{...e,path:[...r.slice(0,t.length),a,...r.slice(t.length+1)]}}function B(e){return e instanceof Error?e.message:typeof e==`string`?e:`Validation failed`}function V(e,t){return e.type===`form`||t.type===`field`&&I(e.segments,t.segments)}function H(e){return e===void 0?{type:`form`}:{segments:z(e),type:`field`}}function ae(e,t){return e.type===`form`||F(e.segments,t)}function U(e,t){return Math.min(Math.max(Math.trunc(e)||0,0),t)}function W(e){return t=>t===e?void 0:t}function G(e){return t=>t>=e?t+1:t}function K(e,t){return n=>n===e?t:e<t&&n>e&&n<=t?n-1:e>t&&n>=t&&n<e?n+1:n}function q(e){return t=>{if(t!==e)return t>e?t-1:t}}function J(e,t){return n=>n===e?t:n===t?e:n}function Y(e,t){return Number.isSafeInteger(e)&&e>=0&&e<t}function X(e,t,n){let[r]=e.splice(t,1);e.splice(n,0,r)}function Z(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}let oe=0;function Q(e){return oe+=1,Symbol(`notform.${e}.${oe}`)}function se(e){if(e!==void 0)return Number.isFinite(e)?Math.max(0,e):0}function ce(e,t){let{dispose:n,parts:r}=$(e,t);return{dispose:n,instance:d(r)}}function $(t,n){let r=n.id??Q(`field`),i=le(n.config),a=!1,o=``,s=e(()=>(a||(o=n.getPath()),o)),c=e({get:()=>t.getValue(s.value),set:e=>{a||t.setValue(s.value,e)}}),l=e(()=>!w(c.value,t.getInitialValue(s.value))),u=e(()=>t.isFieldTouched(r)),d=e(()=>t.getFieldErrors(s.value)),f=e(()=>d.value.length===0),p=e(()=>t.isFieldValidating(s.value));function m(){return a?Promise.resolve({value:void 0}):(t.cancelFieldTask(r),t.validateField(s.value))}function h(e){a||(i.validateOn[e]||i.validationMode===`eager`&&d.value.length>0)&&(i.debounce?t.scheduleFieldTask(r,i.debounce,()=>{m()}):m())}function g(){a||(t.touchField(r),i.validateOn.blur&&m())}function _(){h(`change`)}function v(){h(`input`)}function y(){a||(o===``&&(o=n.getPath()),a=!0,t.cancelFieldTask(r),t.untouchField(r))}return{dispose:y,isDisposed:()=>a,parts:{errors:d,events:{onBlur:g,onChange:_,onInput:v},id:r,isDirty:l,isTouched:u,isValid:f,isValidating:p,model:c,path:s,validate:m}}}function le(e){return{debounce:se(e?.debounce),validateOn:{blur:e?.validateOn?.blur??!0,change:e?.validateOn?.change??!0,input:e?.validateOn?.input??!1},validationMode:e?.validationMode??`eager`}}function ue(t,n){let r=$(t,{config:n.config,getPath:n.getPath,id:Q(`array-field`)}),i=r.parts.path,a=_([]),o=/* @__PURE__ */ new Map,s=t.getResetCount();function c(){let e=t.getValue(i.value);return Array.isArray(e)?e:void 0}function l(){let e=c();if(e)return e;t.setValue(i.value,[]);let n=c();if(!n)throw TypeError(`[notform] Cannot create an array at "${i.value}"`);return n}function u(e,t){for(let n of e){let e=o.get(n);e&&(o.delete(n),t?queueMicrotask(e.dispose):e.dispose())}}function f(){let e=a.value;if(r.isDisposed())return e;let n=t.getResetCount();n!==s&&(s=n,u(e.splice(0),!0));let i=c()?.length??0;for(;e.length<i;)e.push(Q(`array-item`));return e.length>i&&u(e.splice(i),!0),e}function p(){ee(a),r.parts.events.onChange()}function m(e,n){if(r.isDisposed())return;let a=f(),o=l(),s=U(e,a.length);a.splice(s,0,Q(`array-item`)),o.splice(s,0,de(n)),t.remapArrayErrors(i.value,G(s)),p()}function h(e){m(f().length,e)}function g(e){m(0,e)}function v(e){let n=f();!r.isDisposed()&&Y(e,n.length)&&(u(n.splice(e,1),!1),l().splice(e,1),t.remapArrayErrors(i.value,q(e)),p())}function y(e,n){let a=f();e!==n&&!r.isDisposed()&&Y(e,a.length)&&Y(n,a.length)&&(X(a,e,n),X(l(),e,n),t.remapArrayErrors(i.value,K(e,n)),p())}function b(e,n){let a=f();e!==n&&!r.isDisposed()&&Y(e,a.length)&&Y(n,a.length)&&(Z(a,e,n),Z(l(),e,n),t.remapArrayErrors(i.value,J(e,n)),p())}function x(e,n){!r.isDisposed()&&Y(e,f().length)&&(l()[e]=de(n),t.remapArrayErrors(i.value,W(e)),p())}function S(r){let o=a.value.indexOf(r),s=e(()=>{let e=f().indexOf(r);return e!==-1&&(o=e),o}),c=()=>R(i.value,s.value),l=n.createScope(c),u=$(t,{config:n.config,getPath:c,id:r});return{dispose:()=>{l.dispose(),u.dispose()},instance:d({...u.parts,arrayField:l.arrayField,field:l.field,index:s})}}function C(e){let t=o.get(e);return t||(t=S(e),o.set(e,t)),t.instance}let w=e(()=>r.isDisposed()?[]:f().map(e=>C(e)));function T(){for(let e of o.values())e.dispose();o.clear(),r.dispose()}return{dispose:T,instance:d({...r.parts,append:h,insert:m,items:w,move:y,prepend:g,remove:v,swap:b,update:x})}}function de(e){return T(y(e))}function fe(e,t){let n=/* @__PURE__ */ new Map,r=!1;function i(i,a){let o=`field:${i}`,s=n.get(o);return s||(s=ce(e,{config:a,getPath:()=>R(t(),i)}),n.set(o,s),r&&s.dispose()),s.instance}function a(i,a){let o=`array:${i}`,s=n.get(o);return s||(s=ue(e,{config:a,createScope:t=>fe(e,t),getPath:()=>R(t(),i)}),n.set(o,s),r&&s.dispose()),s.instance}function o(){r=!0;for(let e of n.values())e.dispose();n.clear()}return{arrayField:a,dispose:o,field:i}}function pe(){let e=0,t=d(/* @__PURE__ */ new Map);function n(n,r){let i={id:++e,isStale:!1,origin:n,scope:H(r)};for(let[e,r]of t)n!==`submit`&&r.origin===`submit`||!V(i.scope,r.scope)||(r.isStale=!0,t.delete(e));return t.set(i.id,i),i}function r(e){t.delete(e.id)}function i(){for(let e of t.values())e.isStale=!0;t.clear()}return{activeRuns:f(t),finishRun:r,markAllRunsStale:i,startRun:n}}function me(t){let n=_(T(y(t.initialValues??{}))),r=_(T(y(t.initialErrors??[]))),i=d(T(n.value)),a=d(T(r.value)),s=g(/* @__PURE__ */ new Set),c=/* @__PURE__ */ new Map,u=p(!1),f=p(0),m=p(0),h=e(()=>f.value>0),v=e(()=>h.value||s.size>0),ee=e(()=>!w(i,n.value)),S=e(()=>a.length===0);function C(e){s.add(e)}function E(e){s.delete(e)}function D(e){return h.value||s.has(e)}function O(e){let t=c.get(e);t!==void 0&&(clearTimeout(t),c.delete(e))}function k(){for(let e of c.values())clearTimeout(e);c.clear()}function A(e,t,n){O(e),c.set(e,setTimeout(()=>{c.delete(e),n()},t))}let j=pe(),M=0,te=e(()=>j.activeRuns.size>0);function N(){let e=b(t.schema),n=T(y(i));return e[`~standard`].validate(n)}async function F(e,t){let n=j.startRun(e,t);try{let e;try{e=await N()}catch(n){e={issues:[re(n,t)]}}return{isStale:n.isStale,result:e}}finally{j.finishRun(n)}}x(()=>b(t.schema),()=>{j.markAllRunsStale()},{flush:`sync`}),x(i,()=>{j.markAllRunsStale()},{deep:!0,flush:`sync`});function L(e){return P(i,e)}function R(e,t){ne(i,e,t)}function B(e){a.splice(0,a.length,...e)}function V(){a.length=0}function H(e){let t=z(e);return a.filter(e=>I(e.path,t))}function U(e,t){let n=a.filter(t=>!I(t.path,e));(n.length!==a.length||t.length!==0)&&B([...n,...t])}function W(e){e.path?U(e.path,[e]):a.push(e)}function G(e,t){let n=z(e),r=[],i=!1;for(let e of a){let a=ie(e,n,t);a!==e&&(i=!0),a&&r.push(a)}i&&B(r)}function K(e){let t=z(e);for(let e of j.activeRuns.values())if(ae(e.scope,t))return!0;return!1}async function q(e){let{isStale:t,result:n}=await F(`field`,e),r=z(e),i=(n.issues??[]).filter(e=>I(e.path,r));return t||U(r,i),i.length>0?{issues:i}:{value:L(e)}}async function J(){let{isStale:e,result:t}=await F(`form`);return e||B(t.issues?[...t.issues]:[]),t}async function Y(e){if(e?.preventDefault(),u.value)return;u.value=!0,f.value++;let n=++M;try{for(;n===M;){let{isStale:e,result:r}=await F(`submit`);if(n!==M)return;if(!e){if(r.issues){B([...r.issues]);return}V(),await t.onSubmit?.(r.value);return}}}finally{n===M&&(u.value=!1)}}function X(e,t){let a=he(e)?void 0:e;j.markAllRunsStale(),k(),M++,u.value=!1,a!==void 0&&(n.value=T(y(a))),t!==void 0&&(r.value=T(y(t))),ge(i,T(n.value)),B(T(r.value)),s.clear(),f.value=0,m.value++}let Z=fe({cancelFieldTask:O,getFieldErrors:H,getInitialValue:e=>P(n.value,e),getResetCount:()=>m.value,getValue:L,isFieldTouched:D,isFieldValidating:K,remapArrayErrors:G,scheduleFieldTask:A,setValue:R,touchField:C,untouchField:E,validateField:q},()=>``);return o()&&l(()=>{j.markAllRunsStale(),k(),Z.dispose()}),d({arrayField:Z.arrayField,clearErrors:V,errors:a,field:Z.field,getFieldErrors:H,getValue:L,initialErrors:r,initialValues:n,isDirty:ee,isFieldValidating:K,isSubmitted:h,isSubmitting:u,isTouched:v,isValid:S,isValidating:te,replaceErrors:B,reset:X,resetCount:m,setError:W,setValue:R,submit:Y,submitCount:f,validate:J,validateField:q,values:i})}function he(e){return typeof Event<`u`&&e instanceof Event}function ge(e,t){for(let t of Object.keys(e))delete e[t];Object.assign(e,t)}function _e(e){return me(e)}export{k as ArrayField,j as Field,A as FieldError,M as Form,_e as useForm};