@vizejs/composable 0.809.0 → 0.810.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.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{use-form-C2JXZ0i7.mjs → use-form-A4j_h14D.mjs} +168 -27
- package/dist/use-form.d.mts +123 -18
- package/dist/use-form.mjs +1 -1
- package/package.json +2 -2
- package/registry/files/form-control-types.ts +260 -0
- package/registry/files/form-dirty.ts +131 -0
- package/registry/files/form-options.ts +156 -0
- package/registry/files/form-path-types.ts +135 -0
- package/registry/files/use-form.ts +102 -449
- package/registry/registry.json +28 -4
|
@@ -1,440 +1,40 @@
|
|
|
1
|
-
import { computed, ref, shallowRef, toRaw, triggerRef } from "vue";
|
|
2
|
-
import type {
|
|
1
|
+
import { computed, ref, shallowRef, toRaw, toValue, triggerRef } from "vue";
|
|
2
|
+
import type { Ref } from "vue";
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { dirtyFieldsOf, valuesEqual, valuesKeepingDirty } from "./form-dirty.ts";
|
|
5
|
+
import { readPath, writePath } from "./form-value-paths.ts";
|
|
5
6
|
import { tryOnScopeDispose } from "./scope.ts";
|
|
6
7
|
import { validateStandardSchema } from "./standard-schema.ts";
|
|
7
|
-
import type { NormalizedSchemaIssue
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* is bounded at eight levels to keep type checking fast.
|
|
33
|
-
*/
|
|
34
|
-
export type FormPath<Values, Depth extends number = 8> = [Depth] extends [never]
|
|
35
|
-
? never
|
|
36
|
-
: Values extends FormLeaf
|
|
37
|
-
? never
|
|
38
|
-
: Values extends readonly (infer Item)[]
|
|
39
|
-
? `${number}` | `${number}.${FormPath<Item, Decrement[Depth]>}`
|
|
40
|
-
: {
|
|
41
|
-
[Key in keyof Values & string]:
|
|
42
|
-
| Key
|
|
43
|
-
| (FormPath<Values[Key], Decrement[Depth]> extends infer Rest extends string
|
|
44
|
-
? [Rest] extends [never]
|
|
45
|
-
? never
|
|
46
|
-
: `${Key}.${Rest}`
|
|
47
|
-
: never);
|
|
48
|
-
}[keyof Values & string];
|
|
49
|
-
|
|
50
|
-
/** Value type found at `Path` inside `Values`. */
|
|
51
|
-
export type FormPathValue<Values, Path extends string> = Path extends `${infer Head}.${infer Rest}`
|
|
52
|
-
? Values extends readonly (infer Item)[]
|
|
53
|
-
? Head extends `${number}`
|
|
54
|
-
? FormPathValue<Item, Rest>
|
|
55
|
-
: never
|
|
56
|
-
: Head extends keyof Values
|
|
57
|
-
? FormPathValue<Values[Head], Rest>
|
|
58
|
-
: never
|
|
59
|
-
: Values extends readonly (infer Item)[]
|
|
60
|
-
? Path extends `${number}`
|
|
61
|
-
? Item
|
|
62
|
-
: never
|
|
63
|
-
: Path extends keyof Values
|
|
64
|
-
? Values[Path]
|
|
65
|
-
: never;
|
|
66
|
-
|
|
67
|
-
/** Paths whose value is an array (usable with {@link FormControls.fieldArray}). */
|
|
68
|
-
export type FormArrayPath<Values> = {
|
|
69
|
-
[Path in FormPath<Values>]: FormPathValue<Values, Path> extends readonly unknown[] ? Path : never;
|
|
70
|
-
}[FormPath<Values>];
|
|
71
|
-
|
|
72
|
-
/** Item type of the array at `Path`. */
|
|
73
|
-
export type FormArrayItem<Values, Path extends string> =
|
|
74
|
-
FormPathValue<Values, Path> extends readonly (infer Item)[] ? Item : never;
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Error messages keyed by dotted path; `""` holds form-level errors.
|
|
78
|
-
*
|
|
79
|
-
* Known paths are typed for autocompletion; the string index signature
|
|
80
|
-
* stays because schemas and servers may report paths that are not fields.
|
|
81
|
-
*/
|
|
82
|
-
export type FormErrors<Values> = {
|
|
83
|
-
readonly [Path in FormPath<Values> | ""]?: readonly string[];
|
|
84
|
-
} & { readonly [path: string]: readonly string[] | undefined };
|
|
85
|
-
|
|
86
|
-
/** Current errors as recorded: messages keyed by dotted path (`""` = form level). */
|
|
87
|
-
export type FormErrorRecord = Readonly<Record<string, readonly string[]>>;
|
|
88
|
-
|
|
89
|
-
/** Result of a validator: messages, one message, or nothing when valid. */
|
|
90
|
-
export type ValidatorResult = string | readonly string[] | null | undefined | void;
|
|
91
|
-
|
|
92
|
-
/** Context passed to field validators. */
|
|
93
|
-
export interface FieldValidatorContext<Values> {
|
|
94
|
-
/** Current form values (`undefined` for standalone fields). */
|
|
95
|
-
readonly values: Values;
|
|
96
|
-
|
|
97
|
-
/** Dotted path of the validated field. */
|
|
98
|
-
readonly path: string;
|
|
99
|
-
|
|
100
|
-
/** Aborted when a newer validation supersedes this one. */
|
|
101
|
-
readonly signal: AbortSignal;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** Plain validator for one field value. */
|
|
105
|
-
export type FieldValidator<Value, Values = undefined> = (
|
|
106
|
-
value: Value,
|
|
107
|
-
context: FieldValidatorContext<Values>,
|
|
108
|
-
) => ValidatorResult | Promise<ValidatorResult>;
|
|
109
|
-
|
|
110
|
-
/** Plain validator for the whole form, returning errors keyed by path. */
|
|
111
|
-
export type FormValidator<Values> = (
|
|
112
|
-
values: Values,
|
|
113
|
-
context: { readonly signal: AbortSignal },
|
|
114
|
-
) => FormErrors<Values> | undefined | void | Promise<FormErrors<Values> | undefined | void>;
|
|
115
|
-
|
|
116
|
-
/** Per-field validators keyed by path. */
|
|
117
|
-
export type FormFieldValidators<Values> = {
|
|
118
|
-
readonly [Path in FormPath<Values>]?: FieldValidator<FormPathValue<Values, Path>, Values>;
|
|
119
|
-
};
|
|
120
|
-
|
|
121
|
-
/** When validation runs automatically. */
|
|
122
|
-
export type FormValidationTrigger = "change" | "blur" | "submit";
|
|
123
|
-
|
|
124
|
-
/** Discriminated outcome of {@link FormControls.validate} and submission. */
|
|
125
|
-
export type FormResult<Output> =
|
|
126
|
-
| {
|
|
127
|
-
/** Every validator passed. */
|
|
128
|
-
readonly status: "valid";
|
|
129
|
-
/** Schema output, or the values when no schema is configured. */
|
|
130
|
-
readonly value: Output;
|
|
131
|
-
}
|
|
132
|
-
| {
|
|
133
|
-
/** At least one validator failed. */
|
|
134
|
-
readonly status: "invalid";
|
|
135
|
-
/** Errors keyed by path. */
|
|
136
|
-
readonly errors: FormErrorRecord;
|
|
137
|
-
}
|
|
138
|
-
| {
|
|
139
|
-
/** A newer validation started before this one finished. */
|
|
140
|
-
readonly status: "superseded";
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
/** Options for {@link useForm}. */
|
|
144
|
-
export interface UseFormOptions<Values extends object, Output> {
|
|
145
|
-
/** Initial values, or a factory producing fresh initial values. */
|
|
146
|
-
readonly initialValues: Values | (() => Values);
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Standard Schema v1 validator for the whole form. Its output becomes the
|
|
150
|
-
* submitted value.
|
|
151
|
-
*
|
|
152
|
-
* @default undefined
|
|
153
|
-
*/
|
|
154
|
-
readonly schema?: StandardSchemaV1<NoInfer<Values>, Output>;
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Plain whole-form validator.
|
|
158
|
-
*
|
|
159
|
-
* @default undefined
|
|
160
|
-
*/
|
|
161
|
-
readonly validate?: NoInfer<FormValidator<Values>>;
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Plain per-field validators keyed by path.
|
|
165
|
-
*
|
|
166
|
-
* @default {}
|
|
167
|
-
*/
|
|
168
|
-
readonly validators?: NoInfer<FormFieldValidators<Values>>;
|
|
169
|
-
|
|
170
|
-
/**
|
|
171
|
-
* When fields validate before the first submit.
|
|
172
|
-
*
|
|
173
|
-
* @default "submit"
|
|
174
|
-
*/
|
|
175
|
-
readonly validateOn?: FormValidationTrigger;
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* When fields re-validate after the first submit.
|
|
179
|
-
*
|
|
180
|
-
* @default "change"
|
|
181
|
-
*/
|
|
182
|
-
readonly revalidateOn?: FormValidationTrigger;
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* Default submit handler for {@link FormControls.submit}.
|
|
186
|
-
*
|
|
187
|
-
* @default undefined
|
|
188
|
-
*/
|
|
189
|
-
readonly onSubmit?: (value: Output, context: { readonly signal: AbortSignal }) => unknown;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/** Options for {@link FormControls.setValue}. */
|
|
193
|
-
export interface SetFieldValueOptions {
|
|
194
|
-
/**
|
|
195
|
-
* Mark the field touched.
|
|
196
|
-
*
|
|
197
|
-
* @default false
|
|
198
|
-
*/
|
|
199
|
-
readonly touch?: boolean;
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* Validate the field after setting it.
|
|
203
|
-
*
|
|
204
|
-
* @default true while the active trigger is "change"
|
|
205
|
-
*/
|
|
206
|
-
readonly validate?: boolean;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** Reactive controls for one field, returned by {@link FormControls.field}. */
|
|
210
|
-
export interface FormFieldControls<Value, Path extends string = string> {
|
|
211
|
-
/** Dotted path of the field (also a suitable `name` attribute). */
|
|
212
|
-
readonly path: Path;
|
|
213
|
-
|
|
214
|
-
/** Writable value bound to the form state (use with `v-model`). */
|
|
215
|
-
readonly value: WritableComputedRef<Value>;
|
|
216
|
-
|
|
217
|
-
/** Current error messages. */
|
|
218
|
-
readonly errors: ComputedRef<readonly string[]>;
|
|
219
|
-
|
|
220
|
-
/** First error message. */
|
|
221
|
-
readonly error: ComputedRef<string | undefined>;
|
|
222
|
-
|
|
223
|
-
/** Whether the value differs from its initial value. */
|
|
224
|
-
readonly dirty: ComputedRef<boolean>;
|
|
225
|
-
|
|
226
|
-
/** Whether the field was blurred or touched programmatically. */
|
|
227
|
-
readonly touched: ComputedRef<boolean>;
|
|
228
|
-
|
|
229
|
-
/** Whether a validation of this field is pending. */
|
|
230
|
-
readonly validating: ComputedRef<boolean>;
|
|
231
|
-
|
|
232
|
-
/** Mark the field touched (wire to `blur`); validates when configured. */
|
|
233
|
-
readonly onBlur: () => void;
|
|
234
|
-
|
|
235
|
-
/**
|
|
236
|
-
* Validate this field.
|
|
237
|
-
*
|
|
238
|
-
* @returns Whether the field is valid (`false` also when superseded).
|
|
239
|
-
*/
|
|
240
|
-
readonly validate: () => Promise<boolean>;
|
|
241
|
-
|
|
242
|
-
/** Restore the initial value and clear errors and touched state. */
|
|
243
|
-
readonly reset: () => void;
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
/** One entry of a field array, with a stable key for `v-for`. */
|
|
247
|
-
export interface FormArrayEntry<Item, Path extends string = string> {
|
|
248
|
-
/** Stable key that follows the item through moves. */
|
|
249
|
-
readonly key: number;
|
|
250
|
-
|
|
251
|
-
/** Current index. */
|
|
252
|
-
readonly index: number;
|
|
253
|
-
|
|
254
|
-
/** Dotted path of the item, e.g. `items.2`. */
|
|
255
|
-
readonly path: `${Path}.${number}`;
|
|
256
|
-
|
|
257
|
-
/** Current item value. */
|
|
258
|
-
readonly value: Item;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
/** Typed operations on an array field, returned by {@link FormControls.fieldArray}. */
|
|
262
|
-
export interface FormFieldArrayControls<Item, Path extends string = string> {
|
|
263
|
-
/** Entries with stable keys. */
|
|
264
|
-
readonly entries: ComputedRef<readonly FormArrayEntry<Item, Path>[]>;
|
|
265
|
-
|
|
266
|
-
/** Append items. */
|
|
267
|
-
readonly append: (...items: Item[]) => void;
|
|
268
|
-
|
|
269
|
-
/** Prepend items. */
|
|
270
|
-
readonly prepend: (...items: Item[]) => void;
|
|
271
|
-
|
|
272
|
-
/** Insert an item at `index`. */
|
|
273
|
-
readonly insert: (index: number, item: Item) => void;
|
|
274
|
-
|
|
275
|
-
/** Remove the item at `index`, shifting errors and touched state. */
|
|
276
|
-
readonly remove: (index: number) => void;
|
|
277
|
-
|
|
278
|
-
/** Move an item from one index to another, carrying its state along. */
|
|
279
|
-
readonly move: (from: number, to: number) => void;
|
|
280
|
-
|
|
281
|
-
/** Swap two items. */
|
|
282
|
-
readonly swap: (first: number, second: number) => void;
|
|
283
|
-
|
|
284
|
-
/** Replace all items and reset their state. */
|
|
285
|
-
readonly replace: (items: readonly Item[]) => void;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/** Reactive state and actions returned by {@link useForm}. */
|
|
289
|
-
export interface FormControls<Values extends object, Output> {
|
|
290
|
-
/** Current values. Mutations are tracked (dirty state derives from them). */
|
|
291
|
-
readonly values: Ref<Values>;
|
|
292
|
-
|
|
293
|
-
/** Current errors keyed by path; `""` holds form-level errors. */
|
|
294
|
-
readonly errors: Readonly<ShallowRef<FormErrorRecord>>;
|
|
295
|
-
|
|
296
|
-
/** Whether no errors are currently recorded. */
|
|
297
|
-
readonly valid: ComputedRef<boolean>;
|
|
298
|
-
|
|
299
|
-
/** Whether any value differs from its initial value. */
|
|
300
|
-
readonly dirty: ComputedRef<boolean>;
|
|
301
|
-
|
|
302
|
-
/** Whether any validation is pending. */
|
|
303
|
-
readonly validating: ComputedRef<boolean>;
|
|
304
|
-
|
|
305
|
-
/** Whether a submission is in progress. */
|
|
306
|
-
readonly submitting: Readonly<Ref<boolean>>;
|
|
307
|
-
|
|
308
|
-
/** Number of submit attempts. */
|
|
309
|
-
readonly submitCount: Readonly<Ref<number>>;
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Typed controls for one field.
|
|
313
|
-
*
|
|
314
|
-
* @param path Dotted path.
|
|
315
|
-
* @returns Field controls whose value type follows the path.
|
|
316
|
-
*/
|
|
317
|
-
readonly field: <Path extends FormPath<Values>>(
|
|
318
|
-
path: Path,
|
|
319
|
-
) => FormFieldControls<FormPathValue<Values, Path>, Path>;
|
|
320
|
-
|
|
321
|
-
/**
|
|
322
|
-
* Typed operations for an array field.
|
|
323
|
-
*
|
|
324
|
-
* @param path Dotted path of an array.
|
|
325
|
-
* @returns Field array controls.
|
|
326
|
-
*/
|
|
327
|
-
readonly fieldArray: <Path extends FormArrayPath<Values>>(
|
|
328
|
-
path: Path,
|
|
329
|
-
) => FormFieldArrayControls<FormArrayItem<Values, Path>, Path>;
|
|
330
|
-
|
|
331
|
-
/**
|
|
332
|
-
* Read the value at a path.
|
|
333
|
-
*
|
|
334
|
-
* @param path Dotted path.
|
|
335
|
-
* @returns The value.
|
|
336
|
-
*/
|
|
337
|
-
readonly getValue: <Path extends FormPath<Values>>(path: Path) => FormPathValue<Values, Path>;
|
|
338
|
-
|
|
339
|
-
/**
|
|
340
|
-
* Write the value at a path.
|
|
341
|
-
*
|
|
342
|
-
* @param path Dotted path.
|
|
343
|
-
* @param value New value.
|
|
344
|
-
* @param options Touch and validation behavior.
|
|
345
|
-
*/
|
|
346
|
-
readonly setValue: <Path extends FormPath<Values>>(
|
|
347
|
-
path: Path,
|
|
348
|
-
value: FormPathValue<Values, Path>,
|
|
349
|
-
options?: SetFieldValueOptions,
|
|
350
|
-
) => void;
|
|
351
|
-
|
|
352
|
-
/**
|
|
353
|
-
* Replace (or shallowly merge) the values without touching initial values.
|
|
354
|
-
*
|
|
355
|
-
* @param values New values.
|
|
356
|
-
* @param options `merge: true` shallowly merges top-level keys.
|
|
357
|
-
*/
|
|
358
|
-
readonly setValues: (values: Partial<Values>, options?: { readonly merge?: boolean }) => void;
|
|
359
|
-
|
|
360
|
-
/**
|
|
361
|
-
* Whether a field was touched.
|
|
362
|
-
*
|
|
363
|
-
* @param path Dotted path.
|
|
364
|
-
* @returns Touched state.
|
|
365
|
-
*/
|
|
366
|
-
readonly isTouched: (path: FormPath<Values>) => boolean;
|
|
367
|
-
|
|
368
|
-
/**
|
|
369
|
-
* Replace errors (for example with server-side errors).
|
|
370
|
-
*
|
|
371
|
-
* @param errors Errors keyed by path.
|
|
372
|
-
*/
|
|
373
|
-
readonly setErrors: (errors: FormErrors<Values>) => void;
|
|
374
|
-
|
|
375
|
-
/**
|
|
376
|
-
* Clear errors of one path, or all errors.
|
|
377
|
-
*
|
|
378
|
-
* @param path Dotted path; omit to clear everything.
|
|
379
|
-
*/
|
|
380
|
-
readonly clearErrors: (path?: FormPath<Values> | "") => void;
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* Run every validator, aborting any older validation still in flight.
|
|
384
|
-
*
|
|
385
|
-
* @returns The discriminated result; never rejects on validation failure.
|
|
386
|
-
*/
|
|
387
|
-
readonly validate: () => Promise<FormResult<Output>>;
|
|
388
|
-
|
|
389
|
-
/**
|
|
390
|
-
* Validate and, when valid, call `handler` (or the `onSubmit` option).
|
|
391
|
-
* A newer submit aborts an older one's pending validation.
|
|
392
|
-
*
|
|
393
|
-
* @param handler Submit handler overriding `onSubmit`.
|
|
394
|
-
* @returns The validation result.
|
|
395
|
-
*/
|
|
396
|
-
readonly submit: (
|
|
397
|
-
handler?: (value: Output, context: { readonly signal: AbortSignal }) => unknown,
|
|
398
|
-
) => Promise<FormResult<Output>>;
|
|
399
|
-
|
|
400
|
-
/**
|
|
401
|
-
* Create a `submit` event listener that prevents the native submission.
|
|
402
|
-
*
|
|
403
|
-
* @param handler Submit handler overriding `onSubmit`.
|
|
404
|
-
* @returns Event listener for `<form @submit>`.
|
|
405
|
-
*/
|
|
406
|
-
readonly handleSubmit: (
|
|
407
|
-
handler?: (value: Output, context: { readonly signal: AbortSignal }) => unknown,
|
|
408
|
-
) => (event?: Event) => Promise<FormResult<Output>>;
|
|
409
|
-
|
|
410
|
-
/**
|
|
411
|
-
* Restore initial values (or install new ones) and clear all state.
|
|
412
|
-
*
|
|
413
|
-
* @param values New initial values.
|
|
414
|
-
*/
|
|
415
|
-
readonly reset: (values?: Values) => void;
|
|
416
|
-
}
|
|
8
|
+
import type { NormalizedSchemaIssue } from "./standard-schema.ts";
|
|
9
|
+
import type {
|
|
10
|
+
FormControls,
|
|
11
|
+
FormFieldArrayControls,
|
|
12
|
+
FormFieldControls,
|
|
13
|
+
} from "./form-control-types.ts";
|
|
14
|
+
import type {
|
|
15
|
+
FormResetOptions,
|
|
16
|
+
FormResult,
|
|
17
|
+
FormValidationTrigger,
|
|
18
|
+
SetFieldValueOptions,
|
|
19
|
+
UseFormOptions,
|
|
20
|
+
} from "./form-options.ts";
|
|
21
|
+
import type {
|
|
22
|
+
DirtyFields,
|
|
23
|
+
FormArrayItem,
|
|
24
|
+
FormArrayPath,
|
|
25
|
+
FormPath,
|
|
26
|
+
FormPathValue,
|
|
27
|
+
ValidatorResult,
|
|
28
|
+
} from "./form-path-types.ts";
|
|
29
|
+
|
|
30
|
+
export type * from "./form-control-types.ts";
|
|
31
|
+
export type * from "./form-options.ts";
|
|
32
|
+
export type * from "./form-path-types.ts";
|
|
417
33
|
|
|
418
34
|
function cloneValue<Value>(value: Value): Value {
|
|
419
35
|
return structuredClone(toRaw(value));
|
|
420
36
|
}
|
|
421
37
|
|
|
422
|
-
function deepEqual(left: unknown, right: unknown): boolean {
|
|
423
|
-
if (Object.is(left, right)) return true;
|
|
424
|
-
if (left instanceof Date && right instanceof Date) return left.getTime() === right.getTime();
|
|
425
|
-
if (Array.isArray(left) && Array.isArray(right)) {
|
|
426
|
-
return (
|
|
427
|
-
left.length === right.length && left.every((item, index) => deepEqual(item, right[index]))
|
|
428
|
-
);
|
|
429
|
-
}
|
|
430
|
-
if (isContainer(left) && isContainer(right) && !Array.isArray(left) && !Array.isArray(right)) {
|
|
431
|
-
const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
|
|
432
|
-
for (const key of keys) if (!deepEqual(left[key], right[key])) return false;
|
|
433
|
-
return true;
|
|
434
|
-
}
|
|
435
|
-
return false;
|
|
436
|
-
}
|
|
437
|
-
|
|
438
38
|
function toMessages(result: ValidatorResult): readonly string[] {
|
|
439
39
|
if (result === undefined || result === null || result === "") return [];
|
|
440
40
|
return typeof result === "string" ? [result] : result.filter((message) => message !== "");
|
|
@@ -485,7 +85,12 @@ function remapKeys<Entry>(
|
|
|
485
85
|
* … via the `~standard` protocol), a whole-form validator, and per-field
|
|
486
86
|
* validators; all may be asynchronous. A newer validation aborts older ones
|
|
487
87
|
* through their `signal` and their results are discarded, so a slow check
|
|
488
|
-
* can never overwrite fresher errors.
|
|
88
|
+
* can never overwrite fresher errors. `criteriaMode: "first"` keeps one
|
|
89
|
+
* message per path, in source order: schema, form validator, field validator.
|
|
90
|
+
* `dirtyFields` mirrors edited branches, `watch` reads one path, and
|
|
91
|
+
* `setError` updates a single path. `disabled` ignores writes and submission.
|
|
92
|
+
* `reset` can keep dirty values, errors, touched fields, the submit count,
|
|
93
|
+
* or the success flag.
|
|
489
94
|
*
|
|
490
95
|
* This composable owns the *values*. `@vizejs/ui/form` owns accessible
|
|
491
96
|
* error presentation (error summaries, focus management, native constraint
|
|
@@ -528,6 +133,8 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
528
133
|
const pending = ref(new Map<string, number>());
|
|
529
134
|
const submitting = ref(false);
|
|
530
135
|
const submitCount = ref(0);
|
|
136
|
+
const isSubmitSuccessful = ref(false);
|
|
137
|
+
const disabled = computed(() => toValue(options.disabled) === true);
|
|
531
138
|
const arrayKeys = new Map<string, number[]>();
|
|
532
139
|
let nextKey = 0;
|
|
533
140
|
let formController: AbortController | undefined;
|
|
@@ -576,11 +183,18 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
576
183
|
signal: AbortSignal,
|
|
577
184
|
): Promise<{ readonly errors: Record<string, string[]>; readonly output: unknown }> => {
|
|
578
185
|
const snapshot = values.value;
|
|
579
|
-
//
|
|
580
|
-
|
|
581
|
-
const
|
|
186
|
+
// Separate buckets keep message order stable: schema, form, then field.
|
|
187
|
+
// A null prototype keeps paths such as `constructor` as ordinary keys.
|
|
188
|
+
const schemaMessages: Record<string, string[]> = Object.create(null);
|
|
189
|
+
const formMessages: Record<string, string[]> = Object.create(null);
|
|
190
|
+
const fieldMessages: Record<string, string[]> = Object.create(null);
|
|
191
|
+
const add = (
|
|
192
|
+
bucket: Record<string, string[]>,
|
|
193
|
+
path: string,
|
|
194
|
+
messages: readonly string[],
|
|
195
|
+
): void => {
|
|
582
196
|
if (messages.length === 0) return;
|
|
583
|
-
(
|
|
197
|
+
(bucket[path] ??= []).push(...messages);
|
|
584
198
|
};
|
|
585
199
|
let output: unknown = snapshot;
|
|
586
200
|
const tasks: Promise<void>[] = [];
|
|
@@ -589,7 +203,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
589
203
|
tasks.push(
|
|
590
204
|
validateStandardSchema(schema, cloneValue(snapshot)).then((result) => {
|
|
591
205
|
if (result.status === "valid") output = result.value;
|
|
592
|
-
else for (const issue of result.issues) add(issue.path, [issue.message]);
|
|
206
|
+
else for (const issue of result.issues) add(schemaMessages, issue.path, [issue.message]);
|
|
593
207
|
}),
|
|
594
208
|
);
|
|
595
209
|
}
|
|
@@ -599,17 +213,28 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
599
213
|
Promise.resolve(validate(snapshot, { signal })).then((result) => {
|
|
600
214
|
if (!result) return;
|
|
601
215
|
for (const [path, messages] of Object.entries(result)) {
|
|
602
|
-
if (messages !== undefined) add(path, toMessages(messages));
|
|
216
|
+
if (messages !== undefined) add(formMessages, path, toMessages(messages));
|
|
603
217
|
}
|
|
604
218
|
}),
|
|
605
219
|
);
|
|
606
220
|
}
|
|
607
221
|
for (const [path, validator] of validators) {
|
|
608
222
|
tasks.push(
|
|
609
|
-
runValidator(validator, path, snapshot, signal).then((messages) =>
|
|
223
|
+
runValidator(validator, path, snapshot, signal).then((messages) =>
|
|
224
|
+
add(fieldMessages, path, messages),
|
|
225
|
+
),
|
|
610
226
|
);
|
|
611
227
|
}
|
|
612
228
|
await Promise.all(tasks);
|
|
229
|
+
const collected: Record<string, string[]> = Object.create(null);
|
|
230
|
+
const firstOnly = options.criteriaMode === "first";
|
|
231
|
+
for (const bucket of [schemaMessages, formMessages, fieldMessages]) {
|
|
232
|
+
for (const [path, messages] of Object.entries(bucket)) {
|
|
233
|
+
const target = (collected[path] ??= []);
|
|
234
|
+
if (firstOnly && target.length > 0) continue;
|
|
235
|
+
target.push(...(firstOnly ? messages.slice(0, 1) : messages));
|
|
236
|
+
}
|
|
237
|
+
}
|
|
613
238
|
return { errors: { ...collected }, output };
|
|
614
239
|
};
|
|
615
240
|
|
|
@@ -668,7 +293,8 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
668
293
|
: Promise.resolve([]),
|
|
669
294
|
]);
|
|
670
295
|
if (controller.signal.aborted) return false;
|
|
671
|
-
const
|
|
296
|
+
const combined = [...fromSchema, ...fromForm, ...own];
|
|
297
|
+
const messages = options.criteriaMode === "first" ? combined.slice(0, 1) : combined;
|
|
672
298
|
setErrorsFor(path, messages);
|
|
673
299
|
return messages.length === 0;
|
|
674
300
|
} finally {
|
|
@@ -685,6 +311,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
685
311
|
};
|
|
686
312
|
|
|
687
313
|
const setValueAt = (path: string, value: unknown, setOptions: SetFieldValueOptions = {}) => {
|
|
314
|
+
if (disabled.value) return;
|
|
688
315
|
writePath(values.value, path, value);
|
|
689
316
|
if (setOptions.touch) touch(path);
|
|
690
317
|
if (setOptions.validate ?? trigger() === "change") void validateField(path);
|
|
@@ -742,7 +369,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
742
369
|
}),
|
|
743
370
|
errors: computed(() => errors.value[key] ?? []),
|
|
744
371
|
error: computed(() => errors.value[key]?.[0]),
|
|
745
|
-
dirty: computed(() => !
|
|
372
|
+
dirty: computed(() => !valuesEqual(readPath(values.value, key), readPath(initial, key))),
|
|
746
373
|
touched: computed(() => touched.value.has(key)),
|
|
747
374
|
validating: computed(() => pending.value.has(key) || pending.value.has("")),
|
|
748
375
|
onBlur: () => {
|
|
@@ -751,6 +378,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
751
378
|
},
|
|
752
379
|
validate: () => validateField(key),
|
|
753
380
|
reset: () => {
|
|
381
|
+
if (disabled.value) return;
|
|
754
382
|
writePath(values.value, key, cloneValue(readPath(initial, key)));
|
|
755
383
|
setErrorsFor(key, []);
|
|
756
384
|
const next = new Set(touched.value);
|
|
@@ -770,6 +398,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
770
398
|
if (trigger() === "change") void validateField(key);
|
|
771
399
|
};
|
|
772
400
|
const insertAt = (index: number, items: readonly Item[]): void => {
|
|
401
|
+
if (disabled.value) return;
|
|
773
402
|
const array = readArray(key);
|
|
774
403
|
const keys = syncKeys(key, array.length);
|
|
775
404
|
const at = Math.max(0, Math.min(index, array.length));
|
|
@@ -796,6 +425,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
796
425
|
prepend: (...items) => insertAt(0, items),
|
|
797
426
|
insert: (index, item) => insertAt(index, [item]),
|
|
798
427
|
remove: (index) => {
|
|
428
|
+
if (disabled.value) return;
|
|
799
429
|
const array = readArray(key);
|
|
800
430
|
if (index < 0 || index >= array.length) return;
|
|
801
431
|
const keys = syncKeys(key, array.length);
|
|
@@ -805,6 +435,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
805
435
|
afterChange();
|
|
806
436
|
},
|
|
807
437
|
move: (from, to) => {
|
|
438
|
+
if (disabled.value) return;
|
|
808
439
|
const array = readArray(key);
|
|
809
440
|
if (from < 0 || from >= array.length || to < 0 || to >= array.length || from === to) return;
|
|
810
441
|
const keys = syncKeys(key, array.length);
|
|
@@ -821,6 +452,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
821
452
|
afterChange();
|
|
822
453
|
},
|
|
823
454
|
swap: (first, second) => {
|
|
455
|
+
if (disabled.value) return;
|
|
824
456
|
const array = readArray(key);
|
|
825
457
|
if (first < 0 || second < 0 || first >= array.length || second >= array.length) return;
|
|
826
458
|
const keys = syncKeys(key, array.length);
|
|
@@ -834,6 +466,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
834
466
|
afterChange();
|
|
835
467
|
},
|
|
836
468
|
replace: (items) => {
|
|
469
|
+
if (disabled.value) return;
|
|
837
470
|
remapState(key, () => undefined);
|
|
838
471
|
writePath(values.value, key, [...items]);
|
|
839
472
|
arrayKeys.delete(key);
|
|
@@ -850,15 +483,23 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
850
483
|
const submitWith = async (
|
|
851
484
|
handler?: (value: Output, context: { readonly signal: AbortSignal }) => unknown,
|
|
852
485
|
): Promise<FormResult<Output>> => {
|
|
486
|
+
if (disabled.value) return { status: "invalid", errors: {} };
|
|
853
487
|
submitCount.value += 1;
|
|
854
488
|
submitting.value = true;
|
|
855
489
|
try {
|
|
856
490
|
const result = await validate();
|
|
857
491
|
const signal = formController?.signal ?? new AbortController().signal;
|
|
858
492
|
if (result.status === "valid") {
|
|
859
|
-
|
|
860
|
-
|
|
493
|
+
try {
|
|
494
|
+
const onSubmit = handler ?? options.onSubmit;
|
|
495
|
+
if (onSubmit) await onSubmit(result.value, { signal });
|
|
496
|
+
isSubmitSuccessful.value = true;
|
|
497
|
+
} catch (error) {
|
|
498
|
+
isSubmitSuccessful.value = false;
|
|
499
|
+
throw error;
|
|
500
|
+
}
|
|
861
501
|
} else if (result.status === "invalid") {
|
|
502
|
+
isSubmitSuccessful.value = false;
|
|
862
503
|
const next = new Set(touched.value);
|
|
863
504
|
for (const path of Object.keys(result.errors)) if (path !== "") next.add(path);
|
|
864
505
|
touched.value = next;
|
|
@@ -869,17 +510,22 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
869
510
|
}
|
|
870
511
|
};
|
|
871
512
|
|
|
872
|
-
const reset = (next?: Values): void => {
|
|
513
|
+
const reset = (next?: Values, keep: FormResetOptions = {}): void => {
|
|
873
514
|
formController?.abort();
|
|
874
515
|
for (const controller of fieldControllers.values()) controller.abort();
|
|
875
516
|
fieldControllers.clear();
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
517
|
+
const previousInitial = initial;
|
|
518
|
+
const base = next === undefined ? createInitial() : cloneValue(next);
|
|
519
|
+
initial = cloneValue(base);
|
|
520
|
+
values.value = keep.keepDirtyValues
|
|
521
|
+
? cloneValue(valuesKeepingDirty(base, cloneValue(values.value), previousInitial))
|
|
522
|
+
: cloneValue(initial);
|
|
523
|
+
if (!keep.keepErrors) errors.value = {};
|
|
524
|
+
if (!keep.keepTouched) touched.value = new Set();
|
|
880
525
|
pending.value.clear();
|
|
881
|
-
submitCount.value = 0;
|
|
882
|
-
|
|
526
|
+
if (!keep.keepSubmitCount) submitCount.value = 0;
|
|
527
|
+
if (!keep.keepIsSubmitSuccessful) isSubmitSuccessful.value = false;
|
|
528
|
+
if (!keep.keepDirtyValues) arrayKeys.clear();
|
|
883
529
|
bumpKeys();
|
|
884
530
|
};
|
|
885
531
|
|
|
@@ -892,17 +538,23 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
892
538
|
values,
|
|
893
539
|
errors,
|
|
894
540
|
valid: computed(() => Object.keys(errors.value).length === 0),
|
|
895
|
-
dirty: computed(() => !
|
|
541
|
+
dirty: computed(() => !valuesEqual(values.value, initial)),
|
|
542
|
+
dirtyFields: computed(() => dirtyFieldsOf(values.value, initial) as DirtyFields<Values>),
|
|
896
543
|
validating: computed(() => pending.value.size > 0),
|
|
897
544
|
submitting,
|
|
898
545
|
submitCount,
|
|
546
|
+
isSubmitSuccessful,
|
|
547
|
+
disabled,
|
|
899
548
|
field,
|
|
900
549
|
fieldArray,
|
|
901
550
|
getValue: <Path extends FormPath<Values>>(path: Path) =>
|
|
902
551
|
// Same dotted-path walk as `FormPathValue` (see `field`).
|
|
903
552
|
readPath(values.value, path) as FormPathValue<Values, Path>,
|
|
553
|
+
watch: <Path extends FormPath<Values>>(path: Path) =>
|
|
554
|
+
computed(() => readPath(values.value, path) as FormPathValue<Values, Path>),
|
|
904
555
|
setValue: (path, value, setOptions) => setValueAt(path, value, setOptions),
|
|
905
556
|
setValues: (next, setOptions = {}) => {
|
|
557
|
+
if (disabled.value) return;
|
|
906
558
|
if (setOptions.merge) {
|
|
907
559
|
values.value = { ...values.value, ...cloneValue(next) };
|
|
908
560
|
} else {
|
|
@@ -919,6 +571,7 @@ export function useForm<Values extends object, Output = Values>(
|
|
|
919
571
|
}
|
|
920
572
|
errors.value = normalized;
|
|
921
573
|
},
|
|
574
|
+
setError: (path, message) => setErrorsFor(path, toMessages(message)),
|
|
922
575
|
clearErrors,
|
|
923
576
|
validate,
|
|
924
577
|
submit: submitWith,
|