@vizejs/composable 0.809.0 → 0.811.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.
Files changed (173) hide show
  1. package/dist/abort-signal.mjs +0 -62
  2. package/dist/active-element.mjs +0 -11
  3. package/dist/animate.mjs +0 -19
  4. package/dist/async-resource.mjs +0 -17
  5. package/dist/battery.mjs +0 -13
  6. package/dist/breakpoints.mjs +0 -24
  7. package/dist/capability.mjs +0 -12
  8. package/dist/{catalog-BRX-Wg8B.mjs → catalog-CcpCnLjb.mjs} +0 -14
  9. package/dist/catalog.mjs +1 -1
  10. package/dist/color-mode.mjs +0 -23
  11. package/dist/computed-with-control.mjs +0 -22
  12. package/dist/create-event-hook.mjs +0 -27
  13. package/dist/create-global-state.mjs +0 -23
  14. package/dist/create-shared-composable.mjs +0 -23
  15. package/dist/device-motion.mjs +0 -11
  16. package/dist/device-orientation.mjs +0 -23
  17. package/dist/device-pixel-ratio.mjs +0 -11
  18. package/dist/disposal-scope.mjs +0 -25
  19. package/dist/document-visibility.mjs +0 -14
  20. package/dist/draggable.mjs +0 -14
  21. package/dist/element-bounding.mjs +0 -14
  22. package/dist/element-by-point.mjs +0 -10
  23. package/dist/element-hover.mjs +0 -13
  24. package/dist/element-target.mjs +0 -30
  25. package/dist/focus.mjs +0 -23
  26. package/dist/fps.mjs +0 -12
  27. package/dist/geolocation.mjs +0 -14
  28. package/dist/i18n.mjs +0 -86
  29. package/dist/icu-message.mjs +0 -58
  30. package/dist/idle.mjs +0 -16
  31. package/dist/index.d.mts +2 -2
  32. package/dist/index.mjs +2 -2
  33. package/dist/infinite-scroll.mjs +0 -16
  34. package/dist/intersection-observer.mjs +0 -27
  35. package/dist/locale.mjs +0 -20
  36. package/dist/magic-keys.mjs +0 -35
  37. package/dist/math.mjs +0 -37
  38. package/dist/media-query.mjs +0 -29
  39. package/dist/mouse-in-element.mjs +0 -12
  40. package/dist/mouse.mjs +0 -12
  41. package/dist/mutation-observer.mjs +0 -15
  42. package/dist/network.mjs +0 -24
  43. package/dist/on-click-outside.mjs +0 -16
  44. package/dist/on-key-stroke.mjs +0 -33
  45. package/dist/on-long-press.mjs +0 -14
  46. package/dist/on-start-typing.mjs +0 -23
  47. package/dist/page-leave.mjs +0 -11
  48. package/dist/parent-element.mjs +0 -9
  49. package/dist/pinch.mjs +0 -14
  50. package/dist/pointer-lock.mjs +0 -23
  51. package/dist/pointer.mjs +0 -18
  52. package/dist/preferences.mjs +0 -31
  53. package/dist/preferred-languages.mjs +0 -13
  54. package/dist/ref-auto-reset.mjs +0 -24
  55. package/dist/ref-debounced.mjs +0 -22
  56. package/dist/ref-default.mjs +0 -21
  57. package/dist/resize-observer.mjs +0 -31
  58. package/dist/resolver.mjs +1 -58
  59. package/dist/retry-async.mjs +0 -25
  60. package/dist/retry-delay.mjs +0 -23
  61. package/dist/scope.mjs +0 -14
  62. package/dist/screen-orientation.mjs +0 -15
  63. package/dist/scroll-lock.mjs +0 -14
  64. package/dist/scroll.mjs +0 -27
  65. package/dist/standard-schema.mjs +0 -31
  66. package/dist/swipe.mjs +0 -36
  67. package/dist/temporal.mjs +0 -30
  68. package/dist/text-selection.mjs +0 -15
  69. package/dist/textarea-autosize.mjs +0 -13
  70. package/dist/to-reactive.mjs +0 -20
  71. package/dist/transition.mjs +0 -7
  72. package/dist/until.mjs +0 -25
  73. package/dist/use-array.mjs +0 -52
  74. package/dist/use-barcode-detector.mjs +0 -25
  75. package/dist/use-bluetooth.mjs +0 -27
  76. package/dist/use-broadcast-channel.mjs +0 -30
  77. package/dist/use-builtin-ai.mjs +0 -68
  78. package/dist/use-clipboard.mjs +0 -27
  79. package/dist/use-compression-stream.mjs +0 -78
  80. package/dist/use-contact-picker.mjs +0 -22
  81. package/dist/use-cookie.mjs +0 -63
  82. package/dist/use-countdown.mjs +0 -22
  83. package/dist/use-counter.mjs +0 -29
  84. package/dist/use-css-var.mjs +0 -28
  85. package/dist/use-date-format.mjs +0 -48
  86. package/dist/use-date-time-format.mjs +0 -22
  87. package/dist/use-debounced.mjs +0 -39
  88. package/dist/use-display-media.mjs +0 -22
  89. package/dist/use-display-names.mjs +0 -19
  90. package/dist/use-document-title.mjs +0 -25
  91. package/dist/use-drop-zone.mjs +0 -36
  92. package/dist/use-event-source.mjs +0 -25
  93. package/dist/use-eye-dropper.mjs +0 -19
  94. package/dist/use-favicon.mjs +0 -23
  95. package/dist/use-fetch.mjs +0 -27
  96. package/dist/use-field.mjs +0 -27
  97. package/dist/use-file-dialog.mjs +0 -21
  98. package/dist/{use-form-C2JXZ0i7.mjs → use-form-BZqwMs6k.mjs} +143 -70
  99. package/dist/use-form-field-props.mjs +0 -57
  100. package/dist/use-form.d.mts +123 -18
  101. package/dist/use-form.mjs +1 -1
  102. package/dist/use-fullscreen.mjs +0 -23
  103. package/dist/use-gamepad.mjs +0 -50
  104. package/dist/use-hid.mjs +0 -25
  105. package/dist/use-history.mjs +0 -43
  106. package/dist/use-id-generator.mjs +0 -21
  107. package/dist/use-image.mjs +0 -22
  108. package/dist/use-indexed-db.mjs +0 -39
  109. package/dist/use-interval.mjs +0 -28
  110. package/dist/use-list-format.mjs +0 -18
  111. package/dist/use-machine.mjs +0 -34
  112. package/dist/use-map.mjs +0 -28
  113. package/dist/use-media-controls.mjs +0 -28
  114. package/dist/use-mounted.mjs +0 -18
  115. package/dist/use-navigation-api.mjs +0 -27
  116. package/dist/use-notification.mjs +0 -24
  117. package/dist/use-number-format.mjs +0 -23
  118. package/dist/use-object-url.mjs +0 -22
  119. package/dist/use-offset-pagination.mjs +0 -18
  120. package/dist/use-payment-request.mjs +0 -25
  121. package/dist/use-performance-observer.mjs +0 -27
  122. package/dist/use-permission.mjs +0 -26
  123. package/dist/use-plural-rules.mjs +0 -21
  124. package/dist/use-push-subscription.mjs +0 -28
  125. package/dist/use-queue.mjs +0 -29
  126. package/dist/use-raf-fn.mjs +0 -23
  127. package/dist/use-relative-time-format.mjs +0 -35
  128. package/dist/use-request-idle-callback.mjs +0 -42
  129. package/dist/use-route-query.mjs +0 -17
  130. package/dist/use-scheduler-post-task.mjs +0 -27
  131. package/dist/use-screen-details.mjs +0 -42
  132. package/dist/use-script-tag.mjs +0 -28
  133. package/dist/use-segmenter.mjs +0 -20
  134. package/dist/use-serial.mjs +0 -24
  135. package/dist/use-service-worker.mjs +0 -27
  136. package/dist/use-set.mjs +0 -23
  137. package/dist/use-share.mjs +0 -23
  138. package/dist/use-sorted-locale.mjs +0 -20
  139. package/dist/use-speech-recognition.mjs +0 -24
  140. package/dist/use-speech-synthesis.mjs +0 -26
  141. package/dist/use-stack.mjs +0 -27
  142. package/dist/use-storage-estimate.mjs +0 -41
  143. package/dist/use-storage.mjs +0 -68
  144. package/dist/use-style-tag.mjs +0 -22
  145. package/dist/use-supported.mjs +0 -17
  146. package/dist/use-throttled.mjs +0 -46
  147. package/dist/use-time-ago.mjs +0 -22
  148. package/dist/use-toggle.mjs +0 -19
  149. package/dist/use-url-hash.mjs +0 -28
  150. package/dist/use-url-search-params.mjs +0 -99
  151. package/dist/use-usb.mjs +0 -23
  152. package/dist/use-user-activation.mjs +0 -22
  153. package/dist/use-user-media.mjs +0 -50
  154. package/dist/use-vibrate.mjs +0 -21
  155. package/dist/use-view-transition.mjs +0 -22
  156. package/dist/use-visual-viewport.mjs +0 -25
  157. package/dist/use-wake-lock.mjs +0 -21
  158. package/dist/use-web-authn.mjs +0 -61
  159. package/dist/use-web-locks.mjs +0 -25
  160. package/dist/use-web-midi.mjs +0 -22
  161. package/dist/use-web-vitals.mjs +0 -41
  162. package/dist/use-websocket.mjs +0 -27
  163. package/dist/use-worker-fn.mjs +0 -37
  164. package/dist/virtual-list.mjs +0 -14
  165. package/dist/whenever.mjs +0 -21
  166. package/dist/window-size.mjs +0 -12
  167. package/package.json +2 -2
  168. package/registry/files/form-control-types.ts +260 -0
  169. package/registry/files/form-dirty.ts +131 -0
  170. package/registry/files/form-options.ts +156 -0
  171. package/registry/files/form-path-types.ts +135 -0
  172. package/registry/files/use-form.ts +102 -449
  173. package/registry/registry.json +28 -4
@@ -1,440 +1,40 @@
1
- import { computed, ref, shallowRef, toRaw, triggerRef } from "vue";
2
- import type { ComputedRef, Ref, ShallowRef, WritableComputedRef } from "vue";
1
+ import { computed, ref, shallowRef, toRaw, toValue, triggerRef } from "vue";
2
+ import type { Ref } from "vue";
3
3
 
4
- import { isContainer, readPath, writePath } from "./form-value-paths.ts";
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, StandardSchemaV1 } from "./standard-schema.ts";
8
-
9
- /** Values treated as leaves: paths never descend into them. */
10
- export type FormLeaf =
11
- | string
12
- | number
13
- | bigint
14
- | boolean
15
- | symbol
16
- | null
17
- | undefined
18
- | Date
19
- | RegExp
20
- | Blob
21
- | Map<unknown, unknown>
22
- | Set<unknown>
23
- | ((...arguments_: never[]) => unknown);
24
-
25
- type Decrement = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8];
26
-
27
- /**
28
- * Every dotted path into `Values`, as template-literal keys.
29
- *
30
- * Objects contribute their string keys, arrays and tuples contribute
31
- * `${number}` segments, and {@link FormLeaf} values end a path. Recursion
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
- // No prototype, so a path such as `constructor` is an ordinary key.
580
- const collected: Record<string, string[]> = Object.create(null);
581
- const add = (path: string, messages: readonly string[]): void => {
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
- (collected[path] ??= []).push(...messages);
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) => add(path, 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 messages = [...fromSchema, ...fromForm, ...own];
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(() => !deepEqual(readPath(values.value, key), readPath(initial, key))),
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
- const onSubmit = handler ?? options.onSubmit;
860
- if (onSubmit) await onSubmit(result.value, { signal });
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
- initial = next === undefined ? createInitial() : cloneValue(next);
877
- values.value = cloneValue(initial);
878
- errors.value = {};
879
- touched.value = new Set();
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
- arrayKeys.clear();
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(() => !deepEqual(values.value, initial)),
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,