@vizejs/composable 0.804.0 → 0.805.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.
@@ -0,0 +1,498 @@
1
+ import { tryOnScopeDispose } from "./scope.mjs";
2
+ import { validateStandardSchema } from "./standard-schema.mjs";
3
+ import { computed, ref, shallowRef, toRaw, triggerRef } from "vue";
4
+ //#region src/form-value-paths.ts
5
+ /** Whether a value is a plain object or an array that a path may descend into. */
6
+ function isContainer(value) {
7
+ if (Array.isArray(value)) return true;
8
+ if (typeof value !== "object" || value === null) return false;
9
+ const prototype = Object.getPrototypeOf(value);
10
+ return prototype === Object.prototype || prototype === null;
11
+ }
12
+ /** Keys that reach an object's prototype chain instead of its own data. */
13
+ const prototypeKeys = new Set([
14
+ "__proto__",
15
+ "constructor",
16
+ "prototype"
17
+ ]);
18
+ /** Split a dotted path; undefined when a segment names the prototype chain. */
19
+ function splitPath(path) {
20
+ if (path === "") return [];
21
+ const keys = path.split(".");
22
+ return keys.some((key) => prototypeKeys.has(key)) ? void 0 : keys;
23
+ }
24
+ function readChild(container, key) {
25
+ if (Array.isArray(container)) return container[Number(key)];
26
+ const value = container[key];
27
+ return Object.hasOwn(container, key) ? value : void 0;
28
+ }
29
+ function writeChild(container, key, value) {
30
+ if (Array.isArray(container)) container[Number(key)] = value;
31
+ else container[key] = value;
32
+ }
33
+ /** Read a dotted path. */
34
+ function readPath(root, path) {
35
+ const keys = splitPath(path);
36
+ if (keys === void 0) return void 0;
37
+ let current = root;
38
+ for (const key of keys) {
39
+ if (!isContainer(current)) return void 0;
40
+ current = readChild(current, key);
41
+ }
42
+ return current;
43
+ }
44
+ /** Write a dotted path, creating intermediate containers. */
45
+ function writePath(root, path, value) {
46
+ const keys = splitPath(path);
47
+ const last = keys?.at(-1);
48
+ if (keys === void 0 || last === void 0 || !isContainer(root)) return;
49
+ let current = root;
50
+ for (let index = 0; index < keys.length - 1; index += 1) {
51
+ const key = keys[index] ?? "";
52
+ let next = readChild(current, key);
53
+ if (!isContainer(next)) {
54
+ next = /^\d+$/.test(keys[index + 1] ?? "") ? [] : {};
55
+ writeChild(current, key, next);
56
+ }
57
+ if (!isContainer(next)) return;
58
+ current = next;
59
+ }
60
+ writeChild(current, last, value);
61
+ }
62
+ //#endregion
63
+ //#region src/use-form.ts
64
+ function cloneValue(value) {
65
+ return structuredClone(toRaw(value));
66
+ }
67
+ function deepEqual(left, right) {
68
+ if (Object.is(left, right)) return true;
69
+ if (left instanceof Date && right instanceof Date) return left.getTime() === right.getTime();
70
+ if (Array.isArray(left) && Array.isArray(right)) return left.length === right.length && left.every((item, index) => deepEqual(item, right[index]));
71
+ if (isContainer(left) && isContainer(right) && !Array.isArray(left) && !Array.isArray(right)) {
72
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
73
+ for (const key of keys) if (!deepEqual(left[key], right[key])) return false;
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+ function toMessages(result) {
79
+ if (result === void 0 || result === null || result === "") return [];
80
+ return typeof result === "string" ? [result] : result.filter((message) => message !== "");
81
+ }
82
+ function unknownMessages(result) {
83
+ if (typeof result === "string") return result === "" ? [] : [result];
84
+ if (!Array.isArray(result)) return [];
85
+ return result.filter((message) => typeof message === "string" && message !== "");
86
+ }
87
+ /** Rewrite `${arrayPath}.${index}…` keys through an index mapping (undefined drops). */
88
+ function remapKeys(entries, arrayPath, mapIndex) {
89
+ const prefix = `${arrayPath}.`;
90
+ const result = [];
91
+ for (const [key, entry] of entries) {
92
+ if (!key.startsWith(prefix)) {
93
+ result.push([key, entry]);
94
+ continue;
95
+ }
96
+ const rest = key.slice(prefix.length);
97
+ const dot = rest.indexOf(".");
98
+ const indexText = dot === -1 ? rest : rest.slice(0, dot);
99
+ const mapped = /^\d+$/.test(indexText) ? mapIndex(Number(indexText)) : NaN;
100
+ if (mapped === void 0) continue;
101
+ if (Number.isNaN(mapped)) {
102
+ result.push([key, entry]);
103
+ continue;
104
+ }
105
+ result.push([`${prefix}${String(mapped)}${dot === -1 ? "" : rest.slice(dot)}`, entry]);
106
+ }
107
+ return result;
108
+ }
109
+ /**
110
+ * Fully typed form state with validation, field arrays, and submission.
111
+ *
112
+ * The value type is inferred from `initialValues`; every path is a
113
+ * template-literal key, so `field("address.city")` returns controls whose
114
+ * `value` is typed as the city's type and misspelled paths do not compile.
115
+ * Validation combines a Standard Schema v1 validator (Zod, Valibot, ArkType,
116
+ * … via the `~standard` protocol), a whole-form validator, and per-field
117
+ * validators; all may be asynchronous. A newer validation aborts older ones
118
+ * through their `signal` and their results are discarded, so a slow check
119
+ * can never overwrite fresher errors.
120
+ *
121
+ * This composable owns the *values*. `@vizejs/ui/form` owns accessible
122
+ * error presentation (error summaries, focus management, native constraint
123
+ * validation); feed {@link FormControls.errors} into it to render them.
124
+ *
125
+ * Server rendering: pure state, no host access; validation never runs
126
+ * automatically during setup, so server and client render the same markup.
127
+ * Pending validations are aborted when the owning scope stops.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * const form = useForm({
132
+ * initialValues: { name: "", address: { city: "" }, tags: [] as string[] },
133
+ * validators: { name: (name) => (name ? undefined : "Required") },
134
+ * onSubmit: (values) => api.save(values),
135
+ * });
136
+ * const city = form.field("address.city"); // city.value: Ref<string>
137
+ * const tags = form.fieldArray("tags");
138
+ * tags.append("vue");
139
+ * ```
140
+ *
141
+ * @typeParam Values Form values, inferred from `initialValues`.
142
+ * @typeParam Output Submitted value, inferred from `schema` (defaults to `Values`).
143
+ * @param options Initial values, validators, triggers, and submit handler.
144
+ * @returns Form state and actions.
145
+ */
146
+ function useForm(options) {
147
+ const createInitial = () => typeof options.initialValues === "function" ? options.initialValues() : cloneValue(options.initialValues);
148
+ let initial = createInitial();
149
+ const values = ref(cloneValue(initial));
150
+ const errors = shallowRef({});
151
+ const touched = shallowRef(/* @__PURE__ */ new Set());
152
+ const pending = ref(/* @__PURE__ */ new Map());
153
+ const submitting = ref(false);
154
+ const submitCount = ref(0);
155
+ const arrayKeys = /* @__PURE__ */ new Map();
156
+ let nextKey = 0;
157
+ let formController;
158
+ const fieldControllers = /* @__PURE__ */ new Map();
159
+ const validators = Object.entries(options.validators ?? {});
160
+ const runValidator = (validator, path, snapshot, signal) => {
161
+ if (typeof validator !== "function") return Promise.resolve([]);
162
+ const outcome = Reflect.apply(validator, void 0, [readPath(snapshot, path), {
163
+ values: snapshot,
164
+ path,
165
+ signal
166
+ }]);
167
+ return Promise.resolve(outcome).then(unknownMessages);
168
+ };
169
+ const trigger = () => submitCount.value > 0 ? options.revalidateOn ?? "change" : options.validateOn ?? "submit";
170
+ const beginPending = (path) => {
171
+ pending.value.set(path, (pending.value.get(path) ?? 0) + 1);
172
+ };
173
+ const endPending = (path) => {
174
+ const count = (pending.value.get(path) ?? 1) - 1;
175
+ if (count <= 0) pending.value.delete(path);
176
+ else pending.value.set(path, count);
177
+ };
178
+ const setErrorsFor = (path, messages) => {
179
+ const next = { ...errors.value };
180
+ if (messages.length === 0) Reflect.deleteProperty(next, path);
181
+ else next[path] = messages;
182
+ errors.value = next;
183
+ };
184
+ const readFieldValidator = (path) => validators.find(([candidate]) => candidate === path)?.[1];
185
+ /** Collect every error source; resolves to errors keyed by path. */
186
+ const collectErrors = async (signal) => {
187
+ const snapshot = values.value;
188
+ const collected = Object.create(null);
189
+ const add = (path, messages) => {
190
+ if (messages.length === 0) return;
191
+ (collected[path] ??= []).push(...messages);
192
+ };
193
+ let output = snapshot;
194
+ const tasks = [];
195
+ if (options.schema) {
196
+ const schema = options.schema;
197
+ tasks.push(validateStandardSchema(schema, cloneValue(snapshot)).then((result) => {
198
+ if (result.status === "valid") output = result.value;
199
+ else for (const issue of result.issues) add(issue.path, [issue.message]);
200
+ }));
201
+ }
202
+ if (options.validate) {
203
+ const validate = options.validate;
204
+ tasks.push(Promise.resolve(validate(snapshot, { signal })).then((result) => {
205
+ if (!result) return;
206
+ for (const [path, messages] of Object.entries(result)) if (messages !== void 0) add(path, toMessages(messages));
207
+ }));
208
+ }
209
+ for (const [path, validator] of validators) tasks.push(runValidator(validator, path, snapshot, signal).then((messages) => add(path, messages)));
210
+ await Promise.all(tasks);
211
+ return {
212
+ errors: { ...collected },
213
+ output
214
+ };
215
+ };
216
+ const validate = async () => {
217
+ formController?.abort(new DOMException("A newer validation started.", "AbortError"));
218
+ for (const controller of fieldControllers.values()) controller.abort();
219
+ fieldControllers.clear();
220
+ const controller = new AbortController();
221
+ formController = controller;
222
+ beginPending("");
223
+ try {
224
+ const outcome = await collectErrors(controller.signal);
225
+ if (controller.signal.aborted) return { status: "superseded" };
226
+ errors.value = outcome.errors;
227
+ if (Object.keys(outcome.errors).length > 0) return {
228
+ status: "invalid",
229
+ errors: { ...outcome.errors }
230
+ };
231
+ return {
232
+ status: "valid",
233
+ value: outcome.output
234
+ };
235
+ } finally {
236
+ endPending("");
237
+ if (formController === controller) formController = void 0;
238
+ }
239
+ };
240
+ const schemaIssuesFor = async (path) => {
241
+ if (!options.schema) return [];
242
+ const result = await validateStandardSchema(options.schema, cloneValue(values.value));
243
+ if (result.status === "valid") return [];
244
+ return result.issues.filter((issue) => issue.path === path).map((issue) => issue.message);
245
+ };
246
+ const validateField = async (path) => {
247
+ fieldControllers.get(path)?.abort();
248
+ const controller = new AbortController();
249
+ fieldControllers.set(path, controller);
250
+ beginPending(path);
251
+ try {
252
+ const validator = readFieldValidator(path);
253
+ const snapshot = values.value;
254
+ const [own, fromSchema, fromForm] = await Promise.all([
255
+ runValidator(validator, path, snapshot, controller.signal),
256
+ schemaIssuesFor(path),
257
+ options.validate ? Promise.resolve(options.validate(snapshot, { signal: controller.signal })).then((result) => {
258
+ const messages = result ? Reflect.get(result, path) : void 0;
259
+ return Array.isArray(messages) ? messages.filter((message) => typeof message === "string") : [];
260
+ }) : Promise.resolve([])
261
+ ]);
262
+ if (controller.signal.aborted) return false;
263
+ const messages = [
264
+ ...fromSchema,
265
+ ...fromForm,
266
+ ...own
267
+ ];
268
+ setErrorsFor(path, messages);
269
+ return messages.length === 0;
270
+ } finally {
271
+ endPending(path);
272
+ if (fieldControllers.get(path) === controller) fieldControllers.delete(path);
273
+ }
274
+ };
275
+ const touch = (path) => {
276
+ if (touched.value.has(path)) return;
277
+ const next = new Set(touched.value);
278
+ next.add(path);
279
+ touched.value = next;
280
+ };
281
+ const setValueAt = (path, value, setOptions = {}) => {
282
+ writePath(values.value, path, value);
283
+ if (setOptions.touch) touch(path);
284
+ if (setOptions.validate ?? trigger() === "change") validateField(path);
285
+ };
286
+ const syncKeys = (path, length) => {
287
+ let keys = arrayKeys.get(path);
288
+ if (!keys) {
289
+ keys = [];
290
+ arrayKeys.set(path, keys);
291
+ }
292
+ while (keys.length < length) keys.push(nextKey++);
293
+ if (keys.length > length) keys.length = length;
294
+ return keys;
295
+ };
296
+ const readArray = (path) => {
297
+ const current = readPath(values.value, path);
298
+ if (Array.isArray(current)) return current;
299
+ const created = [];
300
+ writePath(values.value, path, created);
301
+ return created;
302
+ };
303
+ const remapState = (path, mapIndex) => {
304
+ errors.value = Object.fromEntries(remapKeys(Object.entries(errors.value), path, mapIndex));
305
+ touched.value = new Set(remapKeys([...touched.value].map((key) => [key, true]), path, mapIndex).map(([key]) => key));
306
+ };
307
+ const keysVersion = shallowRef(0);
308
+ const bumpKeys = () => {
309
+ keysVersion.value += 1;
310
+ triggerRef(keysVersion);
311
+ };
312
+ const field = (path) => {
313
+ const key = path;
314
+ const read = () => readPath(values.value, key);
315
+ return {
316
+ path,
317
+ value: computed({
318
+ get: read,
319
+ set: (next) => setValueAt(key, next)
320
+ }),
321
+ errors: computed(() => errors.value[key] ?? []),
322
+ error: computed(() => errors.value[key]?.[0]),
323
+ dirty: computed(() => !deepEqual(readPath(values.value, key), readPath(initial, key))),
324
+ touched: computed(() => touched.value.has(key)),
325
+ validating: computed(() => pending.value.has(key) || pending.value.has("")),
326
+ onBlur: () => {
327
+ touch(key);
328
+ if (trigger() === "blur") validateField(key);
329
+ },
330
+ validate: () => validateField(key),
331
+ reset: () => {
332
+ writePath(values.value, key, cloneValue(readPath(initial, key)));
333
+ setErrorsFor(key, []);
334
+ const next = new Set(touched.value);
335
+ next.delete(key);
336
+ touched.value = next;
337
+ }
338
+ };
339
+ };
340
+ const fieldArray = (path) => {
341
+ const key = path;
342
+ const afterChange = () => {
343
+ bumpKeys();
344
+ if (trigger() === "change") validateField(key);
345
+ };
346
+ const insertAt = (index, items) => {
347
+ const array = readArray(key);
348
+ const keys = syncKeys(key, array.length);
349
+ const at = Math.max(0, Math.min(index, array.length));
350
+ remapState(key, (old) => old >= at ? old + items.length : old);
351
+ array.splice(at, 0, ...items);
352
+ keys.splice(at, 0, ...items.map(() => nextKey++));
353
+ afterChange();
354
+ };
355
+ return {
356
+ entries: computed(() => {
357
+ keysVersion.value;
358
+ const array = readPath(values.value, key);
359
+ if (!Array.isArray(array)) return [];
360
+ const keys = syncKeys(key, array.length);
361
+ return array.map((value, index) => ({
362
+ key: keys[index] ?? index,
363
+ index,
364
+ path: `${path}.${index}`,
365
+ value
366
+ }));
367
+ }),
368
+ append: (...items) => insertAt(Number.MAX_SAFE_INTEGER, items),
369
+ prepend: (...items) => insertAt(0, items),
370
+ insert: (index, item) => insertAt(index, [item]),
371
+ remove: (index) => {
372
+ const array = readArray(key);
373
+ if (index < 0 || index >= array.length) return;
374
+ const keys = syncKeys(key, array.length);
375
+ remapState(key, (old) => old === index ? void 0 : old > index ? old - 1 : old);
376
+ array.splice(index, 1);
377
+ keys.splice(index, 1);
378
+ afterChange();
379
+ },
380
+ move: (from, to) => {
381
+ const array = readArray(key);
382
+ if (from < 0 || from >= array.length || to < 0 || to >= array.length || from === to) return;
383
+ const keys = syncKeys(key, array.length);
384
+ remapState(key, (old) => {
385
+ if (old === from) return to;
386
+ if (from < to && old > from && old <= to) return old - 1;
387
+ if (from > to && old >= to && old < from) return old + 1;
388
+ return old;
389
+ });
390
+ const [item] = array.splice(from, 1);
391
+ array.splice(to, 0, item);
392
+ const [movedKey] = keys.splice(from, 1);
393
+ keys.splice(to, 0, movedKey ?? nextKey++);
394
+ afterChange();
395
+ },
396
+ swap: (first, second) => {
397
+ const array = readArray(key);
398
+ if (first < 0 || second < 0 || first >= array.length || second >= array.length) return;
399
+ const keys = syncKeys(key, array.length);
400
+ remapState(key, (old) => old === first ? second : old === second ? first : old);
401
+ const firstItem = array[first];
402
+ array[first] = array[second];
403
+ array[second] = firstItem;
404
+ const firstKey = keys[first] ?? nextKey++;
405
+ keys[first] = keys[second] ?? nextKey++;
406
+ keys[second] = firstKey;
407
+ afterChange();
408
+ },
409
+ replace: (items) => {
410
+ remapState(key, () => void 0);
411
+ writePath(values.value, key, [...items]);
412
+ arrayKeys.delete(key);
413
+ afterChange();
414
+ }
415
+ };
416
+ };
417
+ const clearErrors = (path) => {
418
+ if (path === void 0) errors.value = {};
419
+ else setErrorsFor(path, []);
420
+ };
421
+ const submitWith = async (handler) => {
422
+ submitCount.value += 1;
423
+ submitting.value = true;
424
+ try {
425
+ const result = await validate();
426
+ const signal = formController?.signal ?? new AbortController().signal;
427
+ if (result.status === "valid") {
428
+ const onSubmit = handler ?? options.onSubmit;
429
+ if (onSubmit) await onSubmit(result.value, { signal });
430
+ } else if (result.status === "invalid") {
431
+ const next = new Set(touched.value);
432
+ for (const path of Object.keys(result.errors)) if (path !== "") next.add(path);
433
+ touched.value = next;
434
+ }
435
+ return result;
436
+ } finally {
437
+ submitting.value = false;
438
+ }
439
+ };
440
+ const reset = (next) => {
441
+ formController?.abort();
442
+ for (const controller of fieldControllers.values()) controller.abort();
443
+ fieldControllers.clear();
444
+ initial = next === void 0 ? createInitial() : cloneValue(next);
445
+ values.value = cloneValue(initial);
446
+ errors.value = {};
447
+ touched.value = /* @__PURE__ */ new Set();
448
+ pending.value.clear();
449
+ submitCount.value = 0;
450
+ arrayKeys.clear();
451
+ bumpKeys();
452
+ };
453
+ tryOnScopeDispose(() => {
454
+ formController?.abort();
455
+ for (const controller of fieldControllers.values()) controller.abort();
456
+ });
457
+ return {
458
+ values,
459
+ errors,
460
+ valid: computed(() => Object.keys(errors.value).length === 0),
461
+ dirty: computed(() => !deepEqual(values.value, initial)),
462
+ validating: computed(() => pending.value.size > 0),
463
+ submitting,
464
+ submitCount,
465
+ field,
466
+ fieldArray,
467
+ getValue: (path) => readPath(values.value, path),
468
+ setValue: (path, value, setOptions) => setValueAt(path, value, setOptions),
469
+ setValues: (next, setOptions = {}) => {
470
+ if (setOptions.merge) values.value = {
471
+ ...values.value,
472
+ ...cloneValue(next)
473
+ };
474
+ else values.value = {
475
+ ...cloneValue(initial),
476
+ ...cloneValue(next)
477
+ };
478
+ arrayKeys.clear();
479
+ bumpKeys();
480
+ },
481
+ isTouched: (path) => touched.value.has(path),
482
+ setErrors: (next) => {
483
+ const normalized = {};
484
+ for (const [path, messages] of Object.entries(next)) if (messages !== void 0 && messages.length > 0) normalized[path] = messages;
485
+ errors.value = normalized;
486
+ },
487
+ clearErrors,
488
+ validate,
489
+ submit: submitWith,
490
+ handleSubmit: (handler) => (event) => {
491
+ event?.preventDefault();
492
+ return submitWith(handler);
493
+ },
494
+ reset
495
+ };
496
+ }
497
+ //#endregion
498
+ export { useForm as t };