formo-react 0.0.0-stage → 0.2.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 (87) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -2
  3. package/dist/components/FormoBlueprint.d.ts +5 -0
  4. package/dist/components/FormoBlueprint.js +30 -0
  5. package/dist/components/FormoButton.d.ts +6 -0
  6. package/dist/components/FormoButton.js +23 -0
  7. package/dist/components/FormoCheckbox.d.ts +7 -0
  8. package/dist/components/FormoCheckbox.js +10 -0
  9. package/dist/components/FormoChecklist.d.ts +5 -0
  10. package/dist/components/FormoChecklist.js +15 -0
  11. package/dist/components/FormoChoices.d.ts +8 -0
  12. package/dist/components/FormoChoices.js +33 -0
  13. package/dist/components/FormoContext.d.ts +27 -0
  14. package/dist/components/FormoContext.js +69 -0
  15. package/dist/components/FormoErrors.d.ts +5 -0
  16. package/dist/components/FormoErrors.js +14 -0
  17. package/dist/components/FormoField.d.ts +17 -0
  18. package/dist/components/FormoField.js +148 -0
  19. package/dist/components/FormoForm.d.ts +15 -0
  20. package/dist/components/FormoForm.js +76 -0
  21. package/dist/components/FormoGroup.d.ts +5 -0
  22. package/dist/components/FormoGroup.js +15 -0
  23. package/dist/components/FormoHelp.d.ts +6 -0
  24. package/dist/components/FormoHelp.js +9 -0
  25. package/dist/components/FormoInput.d.ts +6 -0
  26. package/dist/components/FormoInput.js +24 -0
  27. package/dist/components/FormoLabel.d.ts +6 -0
  28. package/dist/components/FormoLabel.js +9 -0
  29. package/dist/components/FormoProvider.d.ts +11 -0
  30. package/dist/components/FormoProvider.js +13 -0
  31. package/dist/components/FormoRest.d.ts +6 -0
  32. package/dist/components/FormoRest.js +23 -0
  33. package/dist/components/FormoSelect.d.ts +6 -0
  34. package/dist/components/FormoSelect.js +36 -0
  35. package/dist/components/FormoUneditable.d.ts +6 -0
  36. package/dist/components/FormoUneditable.js +12 -0
  37. package/dist/core/builder.d.ts +42 -0
  38. package/dist/core/builder.js +166 -0
  39. package/dist/core/controls.d.ts +27 -0
  40. package/dist/core/controls.js +24 -0
  41. package/dist/core/fields.d.ts +63 -0
  42. package/dist/core/fields.js +177 -0
  43. package/dist/core/messages.d.ts +35 -0
  44. package/dist/core/messages.js +69 -0
  45. package/dist/core/normalize.d.ts +35 -0
  46. package/dist/core/normalize.js +234 -0
  47. package/dist/core/options.d.ts +44 -0
  48. package/dist/core/options.js +146 -0
  49. package/dist/core/rules.d.ts +41 -0
  50. package/dist/core/rules.js +230 -0
  51. package/dist/core/store.d.ts +155 -0
  52. package/dist/core/store.js +830 -0
  53. package/dist/core/theme.d.ts +20 -0
  54. package/dist/core/theme.js +21 -0
  55. package/dist/core/tree.d.ts +74 -0
  56. package/dist/core/tree.js +119 -0
  57. package/dist/core/utils.d.ts +35 -0
  58. package/dist/core/utils.js +206 -0
  59. package/dist/hooks/subscriptions.d.ts +38 -0
  60. package/dist/hooks/subscriptions.js +65 -0
  61. package/dist/hooks/useFormo.d.ts +18 -0
  62. package/dist/hooks/useFormo.js +25 -0
  63. package/dist/index.d.ts +28 -0
  64. package/dist/index.js +27 -0
  65. package/dist/schema/form.d.ts +92 -0
  66. package/dist/schema/form.js +304 -0
  67. package/dist/schema/index.d.ts +22 -0
  68. package/dist/schema/index.js +21 -0
  69. package/dist/schema/ir.d.ts +189 -0
  70. package/dist/schema/ir.js +130 -0
  71. package/dist/schema/json-schema.d.ts +25 -0
  72. package/dist/schema/json-schema.js +351 -0
  73. package/dist/schema/laravel.d.ts +57 -0
  74. package/dist/schema/laravel.js +555 -0
  75. package/dist/schema/openapi.d.ts +24 -0
  76. package/dist/schema/openapi.js +67 -0
  77. package/dist/schema/policy.d.ts +60 -0
  78. package/dist/schema/policy.js +315 -0
  79. package/dist/schema/spec.d.ts +75 -0
  80. package/dist/schema/spec.js +1 -0
  81. package/dist/schema/values.d.ts +35 -0
  82. package/dist/schema/values.js +151 -0
  83. package/dist/schema/zod.d.ts +79 -0
  84. package/dist/schema/zod.js +236 -0
  85. package/dist/types.d.ts +400 -0
  86. package/dist/types.js +1 -0
  87. package/package.json +70 -4
@@ -0,0 +1,830 @@
1
+ import { fitValues, isEditable, labelResolver, submittableValues, validateGroups, validateLeaves, } from './fields';
2
+ import { uiStrings } from './messages';
3
+ import { buildInitialValues, normalize, rowDefaults } from './normalize';
4
+ import { settleValue } from './options';
5
+ import { evaluateChecklist, parseRules } from './rules';
6
+ import { buildTree, flattenErrors, flattenTree, leavesOf, rowIndexIn, shiftRowPaths, toFormPath, valuePathOf, } from './tree';
7
+ import { ancestorPaths, deepClone, deepEqual, deepMerge, getPath, humanize, interpolate, sameLeafValue, setIn, } from './utils';
8
+ const EMPTY = Object.freeze([]);
9
+ /** Equal item by item (`sameLeafValue`: arrays of scalars compare by content) */
10
+ function sameDeps(a, b) {
11
+ return a.length === b.length && a.every((v, i) => sameLeafValue(v, b[i]));
12
+ }
13
+ function sameChecklist(a, b) {
14
+ return (!!a &&
15
+ a.length === b.length &&
16
+ a.every((item, i) => item.rule === b[i].rule && item.label === b[i].label && item.passed === b[i].passed && item.message === b[i].message));
17
+ }
18
+ /** Checklists that read other fields (`@refs`, function rules, schemas): re-evaluated on any change */
19
+ function readsOtherFields(node) {
20
+ return parseRules(node.rules).some((rule) => !!rule.fn || rule.params.some((p) => typeof p === 'string' && p.startsWith('@')));
21
+ }
22
+ export class FormoStore {
23
+ definition;
24
+ options;
25
+ root;
26
+ config = {};
27
+ baseline;
28
+ controller;
29
+ /* ---- State ------------------------------------------------------------- */
30
+ values;
31
+ errors = {};
32
+ allErrors = {};
33
+ touched = {};
34
+ checklists = {};
35
+ submitting = false;
36
+ outcome = null;
37
+ dirtyPaths = new Set();
38
+ structureDirty = false;
39
+ stateCache = null;
40
+ /* ---- Structure (rebuilt only when rows are added / removed, or on load / reset) */
41
+ tree = [];
42
+ items = new Map();
43
+ leaves = [];
44
+ /** Container path (`''`, a group's path, a row's path) → its items */
45
+ children = new Map();
46
+ /** Fields whose state depends on every value (`editable` functions) */
47
+ valueDependents = [];
48
+ /**
49
+ * `namespaces: false` groups: their value is the object their fields live in
50
+ * (not at their own path) — value path → the groups showing it
51
+ */
52
+ valueWatchers = new Map();
53
+ checklistPaths = new Set();
54
+ globalChecklists = new Set();
55
+ labelFor = (p) => p;
56
+ /* ---- Row keys ---------------------------------------------------------- */
57
+ rowKeys = new Map();
58
+ nextKey = 0;
59
+ /* ---- Subscriptions & caches ------------------------------------------- */
60
+ listeners = new Map();
61
+ allListeners = new Set();
62
+ pendingNotify = false;
63
+ handles = new Map();
64
+ snapshots = new Map();
65
+ fieldsCache = new Map();
66
+ rowsCache = new Map();
67
+ rowCache = new Map();
68
+ checklistRuns = new Map();
69
+ submitLock = null;
70
+ configKey;
71
+ initialValues;
72
+ /** The definition's content (a builder's `toSchema()`), to tell a new object from a new definition */
73
+ schema;
74
+ constructor(definition, options = {}) {
75
+ this.definition = definition;
76
+ this.options = options;
77
+ this.configKey = JSON.stringify(options.config ?? {});
78
+ this.initialValues = options.initialValues;
79
+ this.schema = schemaOf(definition);
80
+ this.root = normalize(definition);
81
+ this.config = { ...options.config };
82
+ this.baseline = this.computeBaseline();
83
+ this.values = deepClone(this.baseline);
84
+ this.rebuild();
85
+ this.recomputeDirty();
86
+ this.controller = createController(this);
87
+ this.runChecklists(this.checklistPaths);
88
+ }
89
+ /* ======================================================================== */
90
+ /* Subscriptions */
91
+ /* ======================================================================== */
92
+ /** Listen to one path: its value, error, touched state, checklist — and what's below it structurally */
93
+ subscribe = (path, listener) => {
94
+ let set = this.listeners.get(path);
95
+ if (!set)
96
+ this.listeners.set(path, (set = new Set()));
97
+ set.add(listener);
98
+ return () => {
99
+ set.delete(listener);
100
+ if (!set.size)
101
+ this.listeners.delete(path);
102
+ };
103
+ };
104
+ /** Listen to every change (form-wide selectors: `useFormoState`) */
105
+ subscribeAll = (listener) => {
106
+ this.allListeners.add(listener);
107
+ return () => this.allListeners.delete(listener);
108
+ };
109
+ /** A summary when printed / serialized (the store references the whole form) */
110
+ toJSON() {
111
+ return this.getState();
112
+ }
113
+ /** Everything that changes, as one immutable object (a new one after each change) */
114
+ getState = () => {
115
+ if (!this.stateCache) {
116
+ this.stateCache = {
117
+ values: this.values,
118
+ errors: this.errors,
119
+ allErrors: this.allErrors,
120
+ touched: this.touched,
121
+ checklists: this.checklists,
122
+ dirty: this.dirtyPaths.size > 0 || this.structureDirty,
123
+ submitting: this.submitting,
124
+ outcome: this.outcome,
125
+ };
126
+ }
127
+ return this.stateCache;
128
+ };
129
+ notify(paths) {
130
+ this.stateCache = null;
131
+ const fns = new Set();
132
+ for (const path of paths)
133
+ this.listeners.get(path)?.forEach((fn) => fns.add(fn));
134
+ this.allListeners.forEach((fn) => fns.add(fn));
135
+ fns.forEach((fn) => fn());
136
+ }
137
+ notifyEverything() {
138
+ this.notify(this.listeners.keys());
139
+ }
140
+ /**
141
+ * A value changed at `path`: the field, the groups above it, `namespaces: false`
142
+ * groups whose values object contains it, fields depending on every value
143
+ */
144
+ notifyValue(path) {
145
+ const above = [path, ...ancestorPaths(path)];
146
+ const watchers = this.valueWatchers.size ? above.flatMap((p) => this.valueWatchers.get(p) ?? []) : [];
147
+ this.notify([...above, ...watchers, ...this.valueDependents]);
148
+ }
149
+ /* ======================================================================== */
150
+ /* Sync with the React side */
151
+ /* ======================================================================== */
152
+ /**
153
+ * Called while rendering `useFormo`: take a new definition, `config` or
154
+ * `initialValues` into account without notifying (React forbids updates
155
+ * during render) — `flush()` does it after commit. Returns whether anything changed.
156
+ */
157
+ sync(definition, options) {
158
+ this.options = options;
159
+ const configKey = JSON.stringify(options.config ?? {});
160
+ if (definition !== this.definition && configKey === this.configKey) {
161
+ // A new object (an inline definition, a builder made while rendering): rebuild only if its content changed
162
+ const schema = schemaOf(definition);
163
+ if (deepEqual(schema, this.schema))
164
+ this.definition = definition;
165
+ else
166
+ this.schema = schema;
167
+ }
168
+ if (definition !== this.definition || configKey !== this.configKey) {
169
+ this.definition = definition;
170
+ this.schema = schemaOf(definition);
171
+ this.configKey = configKey;
172
+ this.config = { ...options.config };
173
+ this.root = normalize(definition);
174
+ this.initialValues = options.initialValues;
175
+ this.baseline = this.computeBaseline();
176
+ // Keep what the user typed; new fields get their defaults
177
+ this.values = fitValues(this.root, deepMerge(buildInitialValues(this.root, this.config), deepClone(this.values)), this.config);
178
+ this.rebuild();
179
+ this.recomputeDirty();
180
+ this.runChecklists(this.checklistPaths);
181
+ this.pendingNotify = true;
182
+ }
183
+ else if (options.initialValues !== this.initialValues) {
184
+ const changed = !deepEqual(options.initialValues, this.initialValues);
185
+ this.initialValues = options.initialValues;
186
+ if (changed) {
187
+ this.baseline = this.computeBaseline();
188
+ this.recomputeDirty();
189
+ this.pendingNotify = true;
190
+ }
191
+ }
192
+ return this.pendingNotify;
193
+ }
194
+ /** Notify what `sync()` changed (after commit) */
195
+ flush() {
196
+ if (!this.pendingNotify)
197
+ return;
198
+ this.pendingNotify = false;
199
+ this.notifyEverything();
200
+ }
201
+ /* ======================================================================== */
202
+ /* Structure */
203
+ /* ======================================================================== */
204
+ computeBaseline() {
205
+ const initial = buildInitialValues(this.root, this.config);
206
+ return fitValues(this.root, deepMerge(initial, deepClone(this.initialValues ?? {})), this.config);
207
+ }
208
+ /** Rebuild the tree for the current values (after a structural change) */
209
+ rebuild() {
210
+ this.tree = buildTree(this.root, this.values, this.config);
211
+ const all = flattenTree(this.tree);
212
+ this.items = new Map(all.map((item) => [item.path, item]));
213
+ this.leaves = leavesOf(this.tree);
214
+ this.children = new Map([['', this.tree]]);
215
+ for (const item of all) {
216
+ if (item.kind === 'group')
217
+ this.children.set(item.path, item.children);
218
+ if (item.kind === 'blueprint') {
219
+ for (const row of item.rows)
220
+ this.children.set(row.path, row.children);
221
+ this.keysOf(item.path, item.rows.length);
222
+ }
223
+ }
224
+ this.valueDependents = this.leaves.filter((l) => typeof l.node.editable === 'function').map((l) => l.path);
225
+ this.valueWatchers = new Map();
226
+ for (const item of all) {
227
+ if (item.kind !== 'group' || item.childPrefix === item.path)
228
+ continue;
229
+ this.valueWatchers.set(item.childPrefix, [...(this.valueWatchers.get(item.childPrefix) ?? []), item.path]);
230
+ }
231
+ this.checklistPaths = new Set(this.leaves.filter((l) => l.errorDisplay === 'checklist').map((l) => l.path));
232
+ this.globalChecklists = new Set(this.leaves.filter((l) => this.checklistPaths.has(l.path) && readsOtherFields(l.node)).map((l) => l.path));
233
+ this.labelFor = labelResolver(this.leaves);
234
+ // Checklists of fields that are gone
235
+ const stale = Object.keys(this.checklists).filter((p) => !this.checklistPaths.has(p));
236
+ if (stale.length) {
237
+ const next = { ...this.checklists };
238
+ for (const p of stale)
239
+ delete next[p];
240
+ this.checklists = next;
241
+ }
242
+ this.pruneMissingRows(all.filter((i) => i.kind === 'blueprint'));
243
+ }
244
+ /**
245
+ * Rows that are gone (fewer rows after `load()`, `val()`, `reset()`) take their
246
+ * errors and touched state with them — a row added later at that index starts clean
247
+ */
248
+ pruneMissingRows(blueprints) {
249
+ if (!blueprints.length)
250
+ return;
251
+ const gone = (path) => blueprints.some((bp) => {
252
+ const row = rowIndexIn(path, bp.path);
253
+ return row !== undefined && row >= bp.rows.length;
254
+ });
255
+ const prune = (record) => {
256
+ const keys = Object.keys(record).filter(gone);
257
+ if (!keys.length)
258
+ return record;
259
+ const next = { ...record };
260
+ for (const key of keys)
261
+ delete next[key];
262
+ return next;
263
+ };
264
+ this.errors = prune(this.errors);
265
+ this.allErrors = prune(this.allErrors);
266
+ this.touched = prune(this.touched);
267
+ this.checklists = prune(this.checklists);
268
+ }
269
+ recomputeDirty() {
270
+ this.dirtyPaths = new Set(this.leaves.filter((l) => !deepEqual(getPath(this.values, l.path), getPath(this.baseline, l.path))).map((l) => l.path));
271
+ this.structureDirty = [...this.items.values()].some((item) => {
272
+ if (item.kind !== 'blueprint')
273
+ return false;
274
+ const base = getPath(this.baseline, item.path);
275
+ return !Array.isArray(base) || base.length !== item.rows.length;
276
+ });
277
+ }
278
+ /** Replace every value (structural changes, load, reset): rebuild, notify everyone */
279
+ replaceValues(values) {
280
+ this.values = values;
281
+ this.rebuild();
282
+ this.recomputeDirty();
283
+ this.notifyEverything();
284
+ this.runChecklists(this.checklistPaths);
285
+ }
286
+ /** Keys of a blueprint's rows: the ones we have (rows changed from outside keep theirs), new rows get new ones */
287
+ keysOf(path, length) {
288
+ let keys = this.rowKeys.get(path) ?? [];
289
+ if (keys.length === length)
290
+ return keys;
291
+ if (keys.length > length)
292
+ keys = keys.slice(0, length);
293
+ while (keys.length < length)
294
+ keys = [...keys, this.nextKey++];
295
+ this.rowKeys.set(path, keys);
296
+ return keys;
297
+ }
298
+ /* ======================================================================== */
299
+ /* Values */
300
+ /* ======================================================================== */
301
+ getValue(path) {
302
+ return path === '' ? this.values : getPath(this.values, path);
303
+ }
304
+ /**
305
+ * Set a value. A field's value is written in place of the old one (only the
306
+ * objects along its path are copied) and notifies that field, the groups above
307
+ * it, and fields depending on every value. Anything else (a group, a blueprint's
308
+ * rows) is a structural change.
309
+ */
310
+ setValue(path, value) {
311
+ const item = this.items.get(path);
312
+ if (item?.kind === 'field') {
313
+ const next = item.node.driver === 'select' ? settleValue(item.node, value) : value;
314
+ if (Object.is(getPath(this.values, path), next))
315
+ return;
316
+ this.values = setIn(this.values, path, next);
317
+ if (deepEqual(next, getPath(this.baseline, path)))
318
+ this.dirtyPaths.delete(path);
319
+ else
320
+ this.dirtyPaths.add(path);
321
+ this.notifyValue(path);
322
+ this.runChecklistsAfter(path);
323
+ return;
324
+ }
325
+ const written = path === '' ? value : setIn(this.values, path, value);
326
+ this.replaceValues(fitValues(this.root, deepClone(written), this.config));
327
+ }
328
+ load(next) {
329
+ this.replaceValues(fitValues(this.root, deepMerge(deepClone(this.values), deepClone(next)), this.config));
330
+ }
331
+ reset(next) {
332
+ this.errors = {};
333
+ this.allErrors = {};
334
+ this.touched = {};
335
+ // Like formo-vue: the given values over the initial ones (a partial reset keeps the other fields' initial values)
336
+ this.replaceValues(next ? fitValues(this.root, deepMerge(deepClone(this.baseline), deepClone(next)), this.config) : deepClone(this.baseline));
337
+ }
338
+ touch(path) {
339
+ if (this.touched[path])
340
+ return;
341
+ this.touched = { ...this.touched, [path]: true };
342
+ this.notify([path]);
343
+ }
344
+ /* ======================================================================== */
345
+ /* Blueprint rows */
346
+ /* ======================================================================== */
347
+ addRow(path, rowValues = {}) {
348
+ const item = this.items.get(path);
349
+ if (item?.kind !== 'blueprint')
350
+ return;
351
+ if (item.node.max !== undefined && item.rows.length >= item.node.max)
352
+ return;
353
+ const rows = getPath(this.values, path);
354
+ const row = deepMerge(rowDefaults(item.node, item.config), deepClone(rowValues));
355
+ const written = setIn(this.values, path, [...(Array.isArray(rows) ? rows : []), row]);
356
+ this.replaceValues(fitValues(this.root, deepClone(written), this.config));
357
+ }
358
+ removeRow(path, index) {
359
+ const item = this.items.get(path);
360
+ if (item?.kind !== 'blueprint')
361
+ return;
362
+ const length = item.rows.length;
363
+ if (index < 0 || index >= length || length <= (item.node.min ?? 0))
364
+ return;
365
+ // The rows after it move up: so do their keys, errors, touched state, checklists — and the keys of blueprints inside them
366
+ const keys = [...this.keysOf(path, length)];
367
+ keys.splice(index, 1);
368
+ this.rowKeys = new Map(Object.entries(shiftRowPaths(Object.fromEntries(this.rowKeys), path, index)));
369
+ this.rowKeys.set(path, keys);
370
+ this.errors = shiftRowPaths(this.errors, path, index);
371
+ this.allErrors = shiftRowPaths(this.allErrors, path, index);
372
+ this.touched = shiftRowPaths(this.touched, path, index);
373
+ this.checklists = shiftRowPaths(this.checklists, path, index);
374
+ const rows = getPath(this.values, path);
375
+ const written = setIn(this.values, path, Array.isArray(rows) ? rows.filter((_, i) => i !== index) : []);
376
+ this.replaceValues(fitValues(this.root, deepClone(written), this.config));
377
+ }
378
+ /* ======================================================================== */
379
+ /* Errors, validation, checklists */
380
+ /* ======================================================================== */
381
+ /** Replace the errors, notifying only the paths whose errors changed (unchanged lists keep their identity) */
382
+ setErrorState(errors, allErrors) {
383
+ const changed = new Set();
384
+ const nextAll = {};
385
+ for (const [path, list] of Object.entries(allErrors)) {
386
+ const prev = this.allErrors[path];
387
+ nextAll[path] = prev && sameLeafValue(prev, list) ? prev : list;
388
+ if (nextAll[path] !== prev)
389
+ changed.add(path);
390
+ }
391
+ for (const path of Object.keys(this.allErrors))
392
+ if (!(path in allErrors))
393
+ changed.add(path);
394
+ for (const path of new Set([...Object.keys(errors), ...Object.keys(this.errors)])) {
395
+ if (errors[path] !== this.errors[path])
396
+ changed.add(path);
397
+ }
398
+ this.errors = errors;
399
+ this.allErrors = nextAll;
400
+ this.notify(changed);
401
+ }
402
+ setErrors(input) {
403
+ const all = flattenErrors(input, (p) => this.items.has(p));
404
+ const flat = {};
405
+ for (const [path, list] of Object.entries(all))
406
+ flat[path] = list[0];
407
+ this.setErrorState(flat, all);
408
+ }
409
+ /** Validate fields, then group rules; store and return the errors */
410
+ async runValidation() {
411
+ const values = this.values;
412
+ const result = await validateLeaves(this.leaves, values);
413
+ await validateGroups(this.tree, values, result.errors, result.allErrors);
414
+ this.setErrorState(result.errors, result.allErrors);
415
+ return result.errors;
416
+ }
417
+ async validate() {
418
+ return Object.keys(await this.runValidation()).length === 0;
419
+ }
420
+ /** After a field changed: its own checklist, and checklists reading other fields */
421
+ runChecklistsAfter(path) {
422
+ if (!this.checklistPaths.size)
423
+ return;
424
+ const targets = new Set(this.globalChecklists);
425
+ if (this.checklistPaths.has(path))
426
+ targets.add(path);
427
+ if (targets.size)
428
+ this.runChecklists(targets);
429
+ }
430
+ /** Evaluate checklists (async); a result only lands if it's the latest for its path and differs */
431
+ runChecklists(paths) {
432
+ for (const path of paths) {
433
+ const leaf = this.items.get(path);
434
+ if (leaf?.kind !== 'field')
435
+ continue;
436
+ const run = (this.checklistRuns.get(path) ?? 0) + 1;
437
+ this.checklistRuns.set(path, run);
438
+ const values = this.values;
439
+ const parentValues = leaf.parentPath ? (getPath(values, leaf.parentPath) ?? {}) : values;
440
+ void evaluateChecklist(leaf.node, getPath(values, path), values, path, { parentValues, labelFor: this.labelFor }).then((items) => {
441
+ if (this.checklistRuns.get(path) !== run || sameChecklist(this.checklists[path], items))
442
+ return;
443
+ this.checklists = { ...this.checklists, [path]: items };
444
+ this.notify([path]);
445
+ });
446
+ }
447
+ }
448
+ /* ======================================================================== */
449
+ /* Submit */
450
+ /* ======================================================================== */
451
+ setStatus(submitting, outcome) {
452
+ this.submitting = submitting;
453
+ if (outcome)
454
+ this.outcome = outcome;
455
+ this.notify([]);
456
+ }
457
+ submit(handler) {
458
+ if (this.submitLock)
459
+ return this.submitLock;
460
+ const options = this.options;
461
+ const run = (async () => {
462
+ this.setStatus(true);
463
+ const settle = (outcome, ok) => {
464
+ this.setStatus(this.submitting, outcome);
465
+ return ok;
466
+ };
467
+ try {
468
+ const errors = await this.runValidation();
469
+ if (Object.keys(errors).length) {
470
+ const inv = { result: 'invalid', errors };
471
+ settle(inv, false);
472
+ options.onInvalid?.(errors, inv);
473
+ options.onSettled?.(inv);
474
+ return false;
475
+ }
476
+ const fn = handler ?? options.onSubmit;
477
+ const data = fn ? await fn(submittableValues(this.tree, this.values)) : undefined;
478
+ if (data === false) {
479
+ const rej = { result: 'rejected', reason: 'handler' };
480
+ settle(rej, false);
481
+ options.onRejected?.(rej);
482
+ options.onSettled?.(rej);
483
+ return false;
484
+ }
485
+ const ok = { result: 'success', data };
486
+ settle(ok, true);
487
+ options.onSuccess?.(data, ok);
488
+ options.onSettled?.(ok);
489
+ return true;
490
+ }
491
+ catch (err) {
492
+ const rej = { result: 'rejected', reason: 'error', error: err };
493
+ settle(rej, false);
494
+ options.onRejected?.(rej);
495
+ options.onSettled?.(rej);
496
+ return false;
497
+ }
498
+ finally {
499
+ this.submitLock = null;
500
+ this.setStatus(false);
501
+ }
502
+ })();
503
+ this.submitLock = run;
504
+ return run;
505
+ }
506
+ /* ======================================================================== */
507
+ /* Handles */
508
+ /* ======================================================================== */
509
+ /** The live handle of a path — one object per path; its getters read the current state */
510
+ handleAt(path) {
511
+ let handle = this.handles.get(path);
512
+ if (!handle) {
513
+ handle = createLiveHandle(this, path);
514
+ this.handles.set(path, handle);
515
+ }
516
+ return handle;
517
+ }
518
+ /** By path (as written, or a server's `phones.0.number`), else by alias — the shallowest match */
519
+ field(pathOrAlias) {
520
+ if (this.items.has(pathOrAlias))
521
+ return this.handleAt(pathOrAlias);
522
+ const formPath = toFormPath(pathOrAlias, (p) => this.items.has(p));
523
+ if (this.items.has(formPath))
524
+ return this.handleAt(formPath);
525
+ let best;
526
+ for (const item of this.items.values()) {
527
+ if (String(item.node.alias) === pathOrAlias && (!best || item.depth < best.depth))
528
+ best = item;
529
+ }
530
+ return best ? this.handleAt(best.path) : undefined;
531
+ }
532
+ /** The handles of a container (`''`, a group, a row), by alias — the same object while they're the same */
533
+ fieldsOf(containerPath) {
534
+ const items = this.children.get(containerPath) ?? EMPTY;
535
+ const handles = items.map((item) => this.handleAt(item.path));
536
+ const cached = this.fieldsCache.get(containerPath);
537
+ if (cached && cached.handles.length === handles.length && cached.handles.every((h, i) => h === handles[i]))
538
+ return cached.obj;
539
+ const obj = {};
540
+ items.forEach((item, i) => (obj[String(item.node.alias)] = handles[i]));
541
+ this.fieldsCache.set(containerPath, { handles, obj });
542
+ return obj;
543
+ }
544
+ /** A blueprint's rows — the same array while nothing about them changed */
545
+ rowsOf(path) {
546
+ const item = this.items.get(path);
547
+ if (item?.kind !== 'blueprint')
548
+ return EMPTY;
549
+ const keys = this.keysOf(path, item.rows.length);
550
+ const canRemove = item.rows.length > (item.node.min ?? 0);
551
+ const rows = item.rows.map((row) => {
552
+ const key = keys[row.index];
553
+ const label = rowLabel(item, row.index);
554
+ const fields = this.fieldsOf(row.path);
555
+ const cacheKey = `${path}#${key}`;
556
+ const cached = this.rowCache.get(cacheKey);
557
+ if (cached && cached.index === row.index && cached.path === row.path && cached.label === label && cached.canRemove === canRemove && cached.fields === fields) {
558
+ return cached;
559
+ }
560
+ const handle = {
561
+ key,
562
+ index: row.index,
563
+ path: row.path,
564
+ label,
565
+ fields,
566
+ canRemove,
567
+ remove: () => this.removeRow(path, row.index),
568
+ };
569
+ withToJSON(handle, () => ({ key, index: row.index, path: row.path, label }));
570
+ this.rowCache.set(cacheKey, handle);
571
+ return handle;
572
+ });
573
+ const cached = this.rowsCache.get(path);
574
+ if (cached && sameLeafValue(cached, rows))
575
+ return cached;
576
+ this.rowsCache.set(path, rows);
577
+ return rows;
578
+ }
579
+ /** What a handle shows right now, as a plain object — the same object until something in it changes */
580
+ snapshot(path, withValue = true) {
581
+ const key = `${withValue ? 'v' : 's'}|${path}`;
582
+ const cached = this.snapshots.get(key);
583
+ const item = this.items.get(path);
584
+ // A path that's gone (its row was removed): keep what was last shown until it unmounts
585
+ if (!item)
586
+ return cached?.obj ?? this.handleAt(path);
587
+ const { node } = item;
588
+ const value = withValue ? this.valueOf(item) : undefined;
589
+ const editable = item.kind === 'field' ? isEditable(item, this.values) : true;
590
+ const fields = item.kind === 'group' ? this.fieldsOf(path) : undefined;
591
+ const rows = item.kind === 'blueprint' ? this.rowsOf(path) : undefined;
592
+ const canAdd = item.kind === 'blueprint' ? node.max === undefined || item.rows.length < node.max : undefined;
593
+ const canRemove = item.kind === 'blueprint' ? item.rows.length > (node.min ?? 0) : undefined;
594
+ const deps = [
595
+ node,
596
+ item.kind,
597
+ value,
598
+ this.errors[path],
599
+ this.allErrors[path],
600
+ this.touched[path],
601
+ editable,
602
+ this.checklists[path],
603
+ item.kind === 'field' ? item.errorDisplay : undefined,
604
+ fields,
605
+ rows,
606
+ canAdd,
607
+ canRemove,
608
+ ];
609
+ if (cached && sameDeps(cached.deps, deps))
610
+ return cached.obj;
611
+ const live = this.handleAt(path);
612
+ const error = this.errors[path];
613
+ const obj = {
614
+ kind: item.kind,
615
+ path,
616
+ alias: node.alias,
617
+ node,
618
+ form: this.controller,
619
+ value: withValue ? value : live.value,
620
+ error,
621
+ errors: this.allErrors[path] ?? (error ? [error] : EMPTY),
622
+ invalid: Boolean(error),
623
+ touched: Boolean(this.touched[path]),
624
+ required: node.required,
625
+ editable,
626
+ disabled: node.disabled,
627
+ errorDisplay: item.kind === 'field' ? item.errorDisplay : 'first',
628
+ checklist: this.checklists[path] ?? EMPTY,
629
+ options: node.options,
630
+ setValue: live.setValue,
631
+ setBlur: live.setBlur,
632
+ };
633
+ if (fields)
634
+ obj.fields = fields;
635
+ if (rows) {
636
+ obj.rows = rows;
637
+ obj.add = live.add;
638
+ obj.remove = live.remove;
639
+ obj.canAdd = canAdd;
640
+ obj.canRemove = canRemove;
641
+ }
642
+ withToJSON(obj, () => handleJSON(obj));
643
+ this.snapshots.set(key, { deps, obj });
644
+ return obj;
645
+ }
646
+ /** A field's value; a subform's values object; a blueprint's rows */
647
+ valueOf(item) {
648
+ if (item.kind === 'field')
649
+ return getPath(this.values, item.path);
650
+ const valuePath = valuePathOf(item);
651
+ return valuePath === '' ? this.values : getPath(this.values, valuePath);
652
+ }
653
+ }
654
+ /**
655
+ * Handles reach the whole form through their getters (`form`, `fields`, `rows`…):
656
+ * printing or `JSON.stringify`-ing one would walk — or loop through — all of it.
657
+ * Their `toJSON` is a compact summary instead (non-enumerable: spreading and
658
+ * destructuring are unaffected).
659
+ */
660
+ function handleJSON(h) {
661
+ return {
662
+ kind: h.kind,
663
+ path: h.path,
664
+ value: h.value,
665
+ error: h.error,
666
+ touched: h.touched,
667
+ editable: h.editable,
668
+ ...(h.fields ? { fields: Object.keys(h.fields) } : {}),
669
+ ...(h.rows ? { rows: h.rows.map((r) => r.path) } : {}),
670
+ };
671
+ }
672
+ function withToJSON(obj, toJSON) {
673
+ Object.defineProperty(obj, 'toJSON', { value: toJSON, enumerable: false });
674
+ return obj;
675
+ }
676
+ /** A definition's content: a builder's schema, or the definition object itself */
677
+ function schemaOf(definition) {
678
+ return typeof definition.toSchema === 'function' ? definition.toSchema() : definition;
679
+ }
680
+ /** A blueprint row's heading: `rowLabel` (`:index` from 1, `:label`), default ":label #:index" */
681
+ function rowLabel(item, index) {
682
+ const label = item.node.label || humanize(item.node.alias);
683
+ return interpolate(item.node.rowLabel ?? uiStrings.rowLabel, { label, index: index + 1 });
684
+ }
685
+ /** A live handle: stable identity, every getter reads the store's current state (formo-vue's handles) */
686
+ function createLiveHandle(store, path) {
687
+ let lastNode;
688
+ let lastKind = 'field';
689
+ const item = () => {
690
+ const found = store.items.get(path);
691
+ if (found) {
692
+ lastNode = found.node;
693
+ lastKind = found.kind;
694
+ }
695
+ return found;
696
+ };
697
+ const node = () => item()?.node ?? lastNode;
698
+ const kind = () => item()?.kind ?? lastKind;
699
+ const setValue = (value) => {
700
+ const it = item();
701
+ store.setValue(it && it.kind === 'group' ? valuePathOf(it) : path, value);
702
+ };
703
+ const setBlur = () => store.touch(path);
704
+ const add = (values) => store.addRow(path, values);
705
+ const remove = (index) => store.removeRow(path, index);
706
+ const handle = {
707
+ get kind() {
708
+ return kind();
709
+ },
710
+ path,
711
+ get alias() {
712
+ return node()?.alias ?? path;
713
+ },
714
+ get node() {
715
+ return node();
716
+ },
717
+ get form() {
718
+ return store.controller;
719
+ },
720
+ get value() {
721
+ const it = item();
722
+ return it ? store.valueOf(it) : getPath(store.values, path);
723
+ },
724
+ get error() {
725
+ return store.errors[path];
726
+ },
727
+ get errors() {
728
+ return store.allErrors[path] ?? (store.errors[path] ? [store.errors[path]] : EMPTY);
729
+ },
730
+ get invalid() {
731
+ return Boolean(store.errors[path]);
732
+ },
733
+ get touched() {
734
+ return Boolean(store.touched[path]);
735
+ },
736
+ get required() {
737
+ return node()?.required ?? false;
738
+ },
739
+ get editable() {
740
+ const it = item();
741
+ return it?.kind === 'field' ? isEditable(it, store.values) : true;
742
+ },
743
+ get disabled() {
744
+ return node()?.disabled ?? false;
745
+ },
746
+ get errorDisplay() {
747
+ const it = item();
748
+ return it?.kind === 'field' ? it.errorDisplay : 'first';
749
+ },
750
+ get checklist() {
751
+ return store.checklists[path] ?? EMPTY;
752
+ },
753
+ get options() {
754
+ return node()?.options ?? EMPTY;
755
+ },
756
+ setValue,
757
+ setBlur,
758
+ get fields() {
759
+ return kind() === 'group' ? store.fieldsOf(path) : undefined;
760
+ },
761
+ get rows() {
762
+ return kind() === 'blueprint' ? store.rowsOf(path) : undefined;
763
+ },
764
+ get add() {
765
+ return kind() === 'blueprint' ? add : undefined;
766
+ },
767
+ get remove() {
768
+ return kind() === 'blueprint' ? remove : undefined;
769
+ },
770
+ get canAdd() {
771
+ const it = item();
772
+ return it?.kind === 'blueprint' ? it.node.max === undefined || it.rows.length < it.node.max : undefined;
773
+ },
774
+ get canRemove() {
775
+ const it = item();
776
+ return it?.kind === 'blueprint' ? it.rows.length > (it.node.min ?? 0) : undefined;
777
+ },
778
+ };
779
+ return withToJSON(handle, () => handleJSON(handle));
780
+ }
781
+ /** The controller `useFormo` returns: stable, its getters read the current state (not reactive — see `useFormoState`) */
782
+ function createController(store) {
783
+ function val(path, ...rest) {
784
+ if (rest.length === 0)
785
+ return store.getValue(path);
786
+ store.setValue(path, rest[0]);
787
+ return rest[0];
788
+ }
789
+ const controller = {
790
+ store,
791
+ get root() {
792
+ return store.root;
793
+ },
794
+ get values() {
795
+ return store.values;
796
+ },
797
+ get errors() {
798
+ return store.errors;
799
+ },
800
+ get allErrors() {
801
+ return store.allErrors;
802
+ },
803
+ get touched() {
804
+ return store.touched;
805
+ },
806
+ get dirty() {
807
+ return store.getState().dirty;
808
+ },
809
+ get submitting() {
810
+ return store.submitting;
811
+ },
812
+ get outcome() {
813
+ return store.outcome;
814
+ },
815
+ get fields() {
816
+ return store.fieldsOf('');
817
+ },
818
+ field: (pathOrAlias) => store.field(pathOrAlias),
819
+ val,
820
+ load: (values) => store.load(values),
821
+ reset: (values) => store.reset(values),
822
+ setErrors: (errors) => store.setErrors(errors),
823
+ validate: () => store.validate(),
824
+ submit: (handler) => store.submit(handler),
825
+ };
826
+ return withToJSON(controller, () => {
827
+ const { values, errors, dirty, submitting, outcome } = store.getState();
828
+ return { values, errors, dirty, submitting, outcome };
829
+ });
830
+ }