foldkit-form 0.8.1 → 0.10.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.
@@ -1,247 +1,12 @@
1
- import { Effect, Match, Option, Pipeable, Result, Schema, SchemaAST } from "effect";
1
+ import { Input, isControlChange } from "./input.js";
2
+ import { own } from "./record.js";
3
+ import { Array as Array$1, Effect, Equal, Match, Option, Pipeable, Result, Schema, SchemaAST } from "effect";
2
4
  import { Bundle, Link } from "foldkit-bundle";
3
- import { Entity, SchemaShape, Words } from "foldkit-entity";
5
+ import { Entity, Words } from "foldkit-entity";
4
6
  import { Metadata } from "foldkit-metadata";
5
7
  import { define, mapMessages } from "foldkit/command";
6
8
  import * as FieldValidation from "foldkit/fieldValidation";
7
9
  import { defineMessageUnion } from "foldkit/message";
8
- // src/input.ts
9
- /**
10
- * Controls: what edits one key of a form, described without a renderer.
11
- *
12
- * There is one primitive. A control is a `kind` (a name), the draft the Model
13
- * holds while the user edits, and whatever data its kind needs. `Input.text()`
14
- * and `Input.toggle()` are values of it, made by `Input.kind`, which is what an
15
- * application calls for a date picker or a rich text editor. The kinds here are
16
- * a collection, not a special case. Which DOM, component, or design system
17
- * draws a kind is the application's.
18
- */
19
- const isControlChange = (value) => "change" in value;
20
- /** A kind of control. The kinds below are made with it, and so is an application's. */
21
- const kind = (name, spec) => {
22
- return {
23
- kind: name,
24
- of: (data) => Object.freeze({
25
- kind: name,
26
- draft: spec.draft,
27
- shown: spec.shown ?? true,
28
- searches: typeof spec.searches === "function" ? spec.searches(data) : spec.searches ?? false,
29
- data,
30
- ...spec.draft === "text" ? {
31
- ...spec.parse === void 0 ? {} : { parse: spec.parse },
32
- ...spec.format === void 0 ? {} : { format: spec.format }
33
- } : spec.draft === "list" ? { ...spec.parseList === void 0 ? {} : { parseList: spec.parseList } } : {},
34
- unparsed: spec.unparsed
35
- }),
36
- is: (control) => control.kind === name
37
- };
38
- };
39
- const nothing = Object.freeze({});
40
- const Text = kind("Text", { draft: "text" });
41
- const Hidden = kind("Hidden", {
42
- draft: "text",
43
- shown: false
44
- });
45
- const Multiline = kind("Multiline", { draft: "text" });
46
- const Number_ = kind("Number", {
47
- draft: "text",
48
- parse: (draft) => {
49
- const value = globalThis.Number(draft);
50
- return draft.trim() === "" || !globalThis.Number.isFinite(value) ? void 0 : value;
51
- },
52
- unparsed: "Enter a number"
53
- });
54
- const Toggle = kind("Toggle", { draft: "flag" });
55
- /**
56
- * One of a fixed set, text or numbers. The draft is the option as text, as a
57
- * `<select>` holds it; the value is the option itself, so `3` is stored as `3`.
58
- */
59
- const Select = kind("Select", {
60
- draft: "text",
61
- parse: (draft, data) => data.options.find((option) => String(option) === draft),
62
- unparsed: "Choose one of the options"
63
- });
64
- /**
65
- * One or more of a fixed set, text or numbers. The draft is each chosen option
66
- * as text, as a group of checkboxes holds them; the value is the options
67
- * themselves, so `3` is stored as `3`.
68
- */
69
- const Choices = kind("Choices", {
70
- draft: "list",
71
- parseList: (draft, data) => {
72
- const chosen = draft.map((text) => data.options.find((option) => String(option) === text));
73
- return chosen.some((option) => option === void 0) ? void 0 : chosen;
74
- },
75
- unparsed: "Choose from the options"
76
- });
77
- const RelationOne = kind("RelationOne", {
78
- draft: "text",
79
- searches: (data) => data.search
80
- });
81
- const RelationMany = kind("RelationMany", {
82
- draft: "list",
83
- searches: (data) => data.search
84
- });
85
- const Nested = kind("Nested", { draft: "rows" });
86
- const key = Metadata.key("foldkit-form/input", {
87
- merge: (controls) => controls.slice(-1),
88
- summarize: (control) => control.kind
89
- });
90
- /** The options a schema is a union of, when every member is a string or number literal. */
91
- const optionsOf = (ast) => {
92
- const values = (SchemaAST.isLiteral(ast) ? [ast] : SchemaAST.isUnion(ast) ? ast.types : []).map((member) => SchemaAST.isLiteral(member) ? member.literal : void 0);
93
- const options = values.filter((value) => typeof value === "string" || typeof value === "number");
94
- return options.length > 0 && options.length === values.length ? options : void 0;
95
- };
96
- const fromSchema = (schema) => {
97
- const members = SchemaShape.present(schema.ast);
98
- const [only] = members;
99
- if (members.length === 1 && only !== void 0) {
100
- if (SchemaAST.isString(only)) return Text.of(nothing);
101
- if (SchemaAST.isNumber(only)) return Number_.of(nothing);
102
- if (SchemaAST.isBoolean(only)) return Toggle.of(nothing);
103
- if (SchemaAST.isArrays(only) && only.rest.length === 1) {
104
- const items = optionsOf(only.rest[0]);
105
- if (items !== void 0) return Choices.of({ options: items });
106
- }
107
- }
108
- const literals = members.map((member) => SchemaAST.isLiteral(member) ? member.literal : void 0);
109
- const options = literals.filter((literal) => typeof literal === "string" || typeof literal === "number");
110
- return options.length > 0 && options.length === literals.length ? Select.of({ options }) : void 0;
111
- };
112
- const Input = {
113
- /**
114
- * A kind of control. `Input.kind<{ min: string }>('Date', { draft: 'text' })`
115
- * gives `.of(data)` to make one and `.is(control)` to tell one, exactly as the
116
- * kinds below were made. A view draws it once it is given a renderer for `Date`.
117
- */
118
- kind,
119
- Text,
120
- Hidden,
121
- Multiline,
122
- Number: Number_,
123
- Toggle,
124
- Select,
125
- Choices,
126
- RelationOne,
127
- RelationMany,
128
- Nested,
129
- /**
130
- * A control backed by a Bundle, for a draft that is a Model of its own: a
131
- * color picker with a popover, a page builder, a rich-text editor. The key's
132
- * draft is the Bundle's Model; `value` reads what the key validates and
133
- * submits from it, and `fill` writes a given value into it. The Bundle's
134
- * Messages travel as the form's `Control` Message, and its Commands,
135
- * Subscriptions and Resources become the form's.
136
- */
137
- bundle: (kind, spec) => {
138
- if (spec.busy !== void 0 && spec.settled === void 0) throw new Error(`Input.bundle("${kind}"): give busy a settled too, or a stored form shown again waits for good`);
139
- return Object.freeze({
140
- kind,
141
- draft: "model",
142
- shown: true,
143
- searches: false,
144
- data: Object.freeze({
145
- bundle: spec.bundle,
146
- args: spec.args,
147
- value: spec.value,
148
- fill: spec.fill,
149
- settled: spec.settled ?? ((model) => model),
150
- busy: spec.busy ?? (() => false)
151
- })
152
- });
153
- },
154
- /** Whether a control is backed by a Bundle, whatever its kind is called. */
155
- isBundle: (control) => control.draft === "model",
156
- text: () => Text.of(nothing),
157
- /** Carried and submitted, not shown: the id of the thing being edited. Set it with `fill`. */
158
- hidden: () => Hidden.of(nothing),
159
- multiline: () => Multiline.of(nothing),
160
- number: () => Number_.of(nothing),
161
- toggle: () => Toggle.of(nothing),
162
- select: (options) => Select.of({ options }),
163
- /**
164
- * Any number of a fixed set, text or numbers. A key typed
165
- * `Schema.Array(Schema.Literals([...]))` resolves to one without asking; name
166
- * it here for a set the schema cannot spell.
167
- */
168
- choices: (options) => Choices.of({ options }),
169
- /**
170
- * A picker of one of `target`, for a value that is not a relation of the
171
- * form's Entity: a page Builder's Block prop that holds an id. A relation key
172
- * resolves to its picker without asking.
173
- */
174
- relationOne: (target) => RelationOne.of({
175
- target,
176
- search: false
177
- }),
178
- /** A picker of any number of `target`, as `relationOne` is of one. */
179
- relationMany: (target) => RelationMany.of({
180
- target,
181
- search: false
182
- }),
183
- /**
184
- * For a relation key, under `inputs`: its picker, with a search. Too many to
185
- * list is the usual case for a relation; the form holds the search text, and
186
- * the query that lists the options takes it as input.
187
- */
188
- search: () => ({ change: (resolved, inputKey) => {
189
- if (resolved !== void 0 && RelationOne.is(resolved)) return RelationOne.of({
190
- ...resolved.data,
191
- search: true
192
- });
193
- if (resolved !== void 0 && RelationMany.is(resolved)) return RelationMany.of({
194
- ...resolved.data,
195
- search: true
196
- });
197
- throw new Error(`"${inputKey}" is not a relation, so it has no picker to search`);
198
- } }),
199
- /**
200
- * Under `inputs`: the key's own control, following another key. Until the
201
- * author writes this key, its draft is `through` of that key's text, rewritten
202
- * as that key is edited; once they write it, it is theirs. Emptying it hands
203
- * it back. A form filled with a value for it does not follow: an address that
204
- * is already published must not move because its title did.
205
- */
206
- following: (key, through = (text) => text) => ({ change: (resolved, inputKey) => {
207
- if (resolved === void 0 || resolved.draft !== "text") throw new Error(`"${inputKey}" holds no text, so it cannot follow "${key}"`);
208
- return Object.freeze({
209
- ...resolved,
210
- follows: {
211
- key,
212
- through
213
- }
214
- });
215
- } }),
216
- /**
217
- * Entity metadata: the control a member is edited with wherever it appears,
218
- * e.g. `Entity.annotateMembers({ body: Input.of(Input.multiline()) })`.
219
- */
220
- of: (control) => key.of(control),
221
- /**
222
- * The control for one input key, from the most to the least explicit source:
223
- * the member's `Input.of` metadata, the relation it writes, then the shape of
224
- * its schema. `undefined` when none of them says, which a form reports rather
225
- * than guessing.
226
- */
227
- resolve: (member, schema) => {
228
- switch (member._tag) {
229
- case "Unmapped": return fromSchema(schema);
230
- case "NestedInput": return;
231
- case "Field": return key.get(member.metadata)[0] ?? fromSchema(schema);
232
- case "RelationInput": {
233
- const { relation } = member;
234
- const [explicit] = key.get(relation.metadata);
235
- if (explicit !== void 0) return explicit;
236
- const data = {
237
- target: relation.target(),
238
- search: false
239
- };
240
- return relation.cardinality === "many" ? RelationMany.of(data) : RelationOne.of(data);
241
- }
242
- }
243
- }
244
- };
245
10
  // src/index.ts
246
11
  /**
247
12
  * `foldkit-form` — a form as a Bundle over Foldkit's own field validation.
@@ -282,6 +47,7 @@ let makeNested;
282
47
  const edits = {
283
48
  Changed: true,
284
49
  Blurred: false,
50
+ Validated: false,
285
51
  ValidatedAll: false,
286
52
  Submitted: false,
287
53
  Reset: true,
@@ -350,6 +116,36 @@ const nestedPlanOf = (name, key, schema, member, given, inherited) => {
350
116
  nothing: absent ? void 0 : null
351
117
  };
352
118
  };
119
+ /**
120
+ * A form over a variant Entity's input that sets `_tag`: the key that picks
121
+ * the case, and for each key of a field only some cases have, those cases.
122
+ * None for any other form. Such a key must be an optional key of the input, so
123
+ * a row of another case leaves it out.
124
+ */
125
+ const casesOf = (name, input, keys) => {
126
+ const members = input.members;
127
+ const fields = input.schema.fields;
128
+ const tagKey = keys.find((key) => {
129
+ const member = members[key];
130
+ return member._tag === "Field" && member.key === "_tag";
131
+ });
132
+ return Option.flatMap(Entity.variantsOf(input.entity), (variants) => {
133
+ if (tagKey === void 0) return Option.none();
134
+ const only = /* @__PURE__ */ new Map();
135
+ for (const key of keys) {
136
+ const member = members[key];
137
+ if (member._tag !== "Field" || member.key === "_tag") continue;
138
+ const holders = variants.tags.filter((tag) => Object.hasOwn(variants.cases[tag], member.key));
139
+ if (holders.length === variants.tags.length) continue;
140
+ if (!SchemaAST.isOptional(fields[key].ast)) fail(name, `"${key}" is a field of some cases of ${input.entity.name}; declare it Schema.optionalKey in the input, so a row of another case leaves it out`);
141
+ only.set(key, new Set(holders));
142
+ }
143
+ return Option.some({
144
+ tagKey,
145
+ only
146
+ });
147
+ });
148
+ };
353
149
  const planOf = (name, key, schema, member, override, messages) => {
354
150
  const held = optionOf(schema);
355
151
  const shape = Option.getOrElse(held, () => schema);
@@ -446,6 +242,7 @@ const attempt = (name, run) => {
446
242
  const draftOf = (plan, given) => {
447
243
  const value = Option.isOption(given) ? Option.getOrUndefined(given) : given;
448
244
  if (value === null || value === void 0) return plan.empty;
245
+ if (plan.kind === "list" && Array.isArray(value)) return value.map((item) => String(item));
449
246
  if (plan.kind !== "text") return value;
450
247
  const format = plan.control.format;
451
248
  return format === void 0 ? String(value) : format(value, plan.control.data);
@@ -472,11 +269,16 @@ const Core = {
472
269
  const keys = everyKey.filter((key) => members[key]._tag !== "NestedInput");
473
270
  const rowsKeys = everyKey.filter((key) => members[key]._tag === "NestedInput");
474
271
  const overrides = options.inputs ?? {};
475
- const plans = Object.fromEntries(keys.map((key) => [key, planOf(name, key, input.schema.fields[key], members[key], overrides[key], options.messages ?? {})]));
272
+ const cases = casesOf(name, input, keys);
273
+ const caseOnly = (key) => Option.match(cases, {
274
+ onNone: () => void 0,
275
+ onSome: ({ only }) => only.get(key)
276
+ });
277
+ const plans = Object.fromEntries(keys.map((key) => [key, planOf(name, key, caseOnly(key) === void 0 ? input.schema.fields[key] : input.schema.fields[key].schema, members[key], own(overrides, key), options.messages ?? {})]));
476
278
  const controlKeys = keys.filter((key) => plans[key].bundled !== void 0);
477
- for (const key of controlKeys) if (options.checks !== void 0 && key in options.checks) fail(name, `"${key}" is edited by a control backed by a Bundle, which takes no check; say what is valid in its schema`);
279
+ for (const key of controlKeys) if (options.checks !== void 0 && Object.hasOwn(options.checks, key)) fail(name, `"${key}" is edited by a control backed by a Bundle, which takes no check; say what is valid in its schema`);
478
280
  const givenForms = options.nested ?? {};
479
- const nestedPlans = Object.fromEntries(rowsKeys.map((key) => [key, nestedPlanOf(name, key, input.schema.fields[key], members[key], givenForms[key], {
281
+ const nestedPlans = Object.fromEntries(rowsKeys.map((key) => [key, nestedPlanOf(name, key, input.schema.fields[key], members[key], own(givenForms, key), {
480
282
  messages: options.messages,
481
283
  debounce: options.debounce,
482
284
  operators: options.operators
@@ -496,7 +298,9 @@ const Core = {
496
298
  nextRow: Schema.Number,
497
299
  searches: Schema.Record(Schema.String, Schema.String),
498
300
  touched: Schema.Record(Schema.String, Schema.Boolean),
301
+ attempted: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))),
499
302
  errors: Schema.Array(Schema.String),
303
+ marks: Schema.Record(Schema.String, Schema.Array(Schema.String)).pipe(Schema.withDecodingDefaultKey(Effect.succeed({}))),
500
304
  submitPending: Schema.Boolean,
501
305
  subject: Schema.Record(Schema.String, Schema.String)
502
306
  });
@@ -512,9 +316,18 @@ const Core = {
512
316
  key: KeySchema,
513
317
  value: DraftSchema
514
318
  },
515
- /** Validates the key as it stands, so a required key left empty says so. */
319
+ /**
320
+ * The person left the key. An edit has already validated it, and a key
321
+ * never edited is not judged before a submit, so tabbing through a field
322
+ * says nothing about it: the form changes nothing.
323
+ */
516
324
  Blurred: { key: KeySchema },
517
325
  /**
326
+ * Validates the key as it stands, edited or not: for a program showing a
327
+ * stored value's failure after a `fill`, which validates nothing.
328
+ */
329
+ Validated: { key: KeySchema },
330
+ /**
518
331
  * Validates every key not validated yet, in every row too, as a submit
519
332
  * would, and submits nothing: for a page that submits several forms at once.
520
333
  * A rule spanning keys is said only by a submit.
@@ -522,21 +335,31 @@ const Core = {
522
335
  ValidatedAll: {},
523
336
  Submitted: {},
524
337
  Reset: {},
525
- /** The answer of a check for the draft it was asked about; one for an older draft is dropped. */
338
+ /**
339
+ * The answer of a check for the draft it was asked about; one for an older
340
+ * draft is dropped. `form.Check` also says the `values` and `subject` it
341
+ * read, and an answer about ones the form no longer holds is asked again.
342
+ * One made without them (a test's) answers the form as it is.
343
+ */
526
344
  Checked: {
527
345
  key: KeySchema,
528
346
  draft: DraftSchema,
347
+ values: Schema.optionalKey(Schema.Unknown),
348
+ subject: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
529
349
  error: Schema.NullOr(Schema.String)
530
350
  },
531
351
  /**
532
352
  * The outside world refused this key's value: a unique index, a rule only a
533
- * server knows. The key reads invalid with that reason, keeping what was
534
- * typed, until it is edited again. Unlike `Checked`, it answers no question
535
- * the form asked, so it lands whatever state the key is in.
353
+ * server knows. `value` is the key's value in what was refused, as
354
+ * `Submitted` handed it out. While the key still holds it, the key reads
355
+ * invalid with that reason (a mark, see `FormModel.marks`) until the next
356
+ * edit of any key; a key changed since is not what was refused, and the
357
+ * Message is dropped.
536
358
  */
537
359
  Refused: {
538
360
  key: KeySchema,
539
- error: Schema.String
361
+ error: Schema.String,
362
+ value: Schema.Unknown
540
363
  },
541
364
  /**
542
365
  * What the form is editing, for the checks that need to know: a post's own
@@ -618,7 +441,9 @@ const Core = {
618
441
  nextRow: 0,
619
442
  searches: {},
620
443
  touched: {},
444
+ attempted: false,
621
445
  errors: [],
446
+ marks: {},
622
447
  submitPending: false,
623
448
  subject: {}
624
449
  });
@@ -630,6 +455,23 @@ const Core = {
630
455
  [key]: field
631
456
  }
632
457
  });
458
+ const marksOf = (model, key) => Object.hasOwn(model.marks, key) ? model.marks[key] : [];
459
+ const hasMarks = (model) => Object.keys(model.marks).length > 0;
460
+ /** A key's state as a view shows it: its own, made invalid by the marks on it. */
461
+ const shownField = (model, key, field) => {
462
+ const marked = marksOf(model, key);
463
+ if (!Array$1.isReadonlyArrayNonEmpty(marked)) return field;
464
+ const own = FieldValidation.match(field, {
465
+ onNotValidated: () => [],
466
+ onValidating: () => [],
467
+ onValid: () => [],
468
+ onInvalid: ({ errors }) => errors
469
+ });
470
+ return FieldValidation.Invalid({
471
+ value: field.value,
472
+ errors: Array$1.appendAll(own, marked)
473
+ });
474
+ };
633
475
  const checks = options.checks ?? {};
634
476
  const debounce = options.debounce ?? "300 millis";
635
477
  /**
@@ -652,11 +494,22 @@ const Core = {
652
494
  })), Effect.map((error) => Message.Checked({
653
495
  key,
654
496
  draft,
497
+ values,
498
+ subject,
655
499
  error: error ?? null
656
500
  })))
657
501
  });
502
+ /** The case `_tag`'s draft names, for a form over a variant Entity's input. */
503
+ const chosen = (model) => Option.flatMap(cases, ({ tagKey }) => Result.getSuccess(plans[tagKey].check(drafts(model)[tagKey].value)).pipe(Option.filter((tag) => typeof tag === "string")));
504
+ /** Whether the form asks `key` now: always, but for a key of cases other than the one chosen. */
505
+ const shows = (model, key) => {
506
+ const holders = caseOnly(key);
507
+ return holders === void 0 || Option.exists(chosen(model), (tag) => holders.has(tag));
508
+ };
509
+ /** The keys asked now: every key, or, over a variant Entity, those of the case chosen. */
510
+ const asked = (model) => Option.isNone(cases) ? keys : keys.filter((key) => shows(model, key));
658
511
  /** What currently decodes, by key: the context of a check, and the makings of the value. */
659
- const decoded = (model) => Object.fromEntries(keys.flatMap((key) => {
512
+ const decoded = (model) => Object.fromEntries(asked(model).flatMap((key) => {
660
513
  const value = Result.getOrUndefined(plans[key].check(drafts(model)[key].value));
661
514
  return value === void 0 ? [] : [[key, value]];
662
515
  }));
@@ -723,6 +576,13 @@ const Core = {
723
576
  placed: bundled.bundle.at(link, { args: bundled.args })
724
577
  };
725
578
  });
579
+ /** The Command asking `key`'s check about its draft, with the values and subject the form holds. */
580
+ const ask = (model, key) => Check({
581
+ key,
582
+ draft: drafts(model)[key].value,
583
+ values: decoded(model),
584
+ subject: model.subject
585
+ });
726
586
  /**
727
587
  * Validates the draft of one key. A key with a check that passes its schema is
728
588
  * not `Valid` yet: it is `Validating`, with the Command that asks.
@@ -734,19 +594,14 @@ const Core = {
734
594
  model,
735
595
  commands: []
736
596
  };
737
- if (checks[key] === void 0 || state._tag !== "Valid") return {
597
+ if (own(checks, key) === void 0 || state._tag !== "Valid") return {
738
598
  model: withField(model, key, state),
739
599
  commands: []
740
600
  };
741
601
  const asking = withField(model, key, FieldValidation.Validating({ value: draft }));
742
602
  return {
743
603
  model: asking,
744
- commands: [Check({
745
- key,
746
- draft,
747
- values: decoded(asking),
748
- subject: model.subject
749
- })]
604
+ commands: [ask(asking, key)]
750
605
  };
751
606
  };
752
607
  const followers = keys.filter((key) => plans[key].control.follows !== void 0);
@@ -782,16 +637,23 @@ const Core = {
782
637
  }
783
638
  } : model;
784
639
  const written = validateKey(owned, key, handedBack ? derived(owned, key) : draft);
785
- return followedBy(key).reduce((result, follower) => {
640
+ const result = followedBy(key).reduce((result, follower) => {
786
641
  if (result.model.touched[follower] === true) return result;
787
642
  const next = rewritten(result.model, follower);
788
643
  return {
789
644
  model: next.model,
790
- commands: [...result.commands, ...next.commands]
645
+ asked: [...result.asked, ...next.asked]
791
646
  };
792
- }, written);
647
+ }, {
648
+ model: written.model,
649
+ asked: written.commands.length === 0 ? [] : [key]
650
+ });
651
+ return {
652
+ model: result.model,
653
+ commands: result.asked.map((asked) => ask(result.model, asked))
654
+ };
793
655
  };
794
- /** A follower written from the key it follows, and its own followers after it. */
656
+ /** A follower written from the key it follows, and its own followers after it, with the keys it asks. */
795
657
  const rewritten = (model, follower) => {
796
658
  const draft = derived(model, follower);
797
659
  const written = isEmpty(draft) ? {
@@ -803,9 +665,12 @@ const Core = {
803
665
  const after = rewritten(result.model, next);
804
666
  return {
805
667
  model: after.model,
806
- commands: [...result.commands, ...after.commands]
668
+ asked: [...result.asked, ...after.asked]
807
669
  };
808
- }, written);
670
+ }, {
671
+ model: written.model,
672
+ asked: written.commands.length === 0 ? [] : [follower]
673
+ });
809
674
  };
810
675
  const decodeInput = Schema.decodeUnknownResult(Schema.toType(input.schema));
811
676
  const keyOfField = new Map(keys.flatMap((key) => {
@@ -822,23 +687,25 @@ const Core = {
822
687
  Valid: () => Option.none(),
823
688
  Undecided: () => Option.none(),
824
689
  Invalid: ({ failures }) => {
825
- let next = model;
690
+ const marks = /* @__PURE__ */ new Map();
826
691
  const errors = [];
827
692
  for (const failure of failures) {
828
693
  const shown = failure.path.flatMap((field) => Option.toArray(Option.fromUndefinedOr(keyOfField.get(field))));
829
694
  if (shown.length === 0) errors.push(failure.message);
830
- for (const key of shown) next = withField(next, key, FieldValidation.Invalid({
831
- value: drafts(next)[key].value,
832
- errors: [failure.message]
833
- }));
695
+ for (const key of shown) {
696
+ const held = marks.get(key);
697
+ if (held === void 0) marks.set(key, [failure.message]);
698
+ else held.push(failure.message);
699
+ }
834
700
  }
835
701
  return Option.some({
836
- ...next,
702
+ ...model,
703
+ marks: Object.fromEntries(marks),
837
704
  errors
838
705
  });
839
706
  }
840
707
  }));
841
- const acceptable = (model) => keys.every((key) => {
708
+ const acceptable = (model) => asked(model).every((key) => {
842
709
  const field = drafts(model)[key];
843
710
  return FieldValidation.isValid(plans[key].rules)(field) && (field._tag !== "NotValidated" || Result.isSuccess(plans[key].check(field.value)));
844
711
  });
@@ -848,11 +715,11 @@ const Core = {
848
715
  const isValidating = (model) => keys.some((key) => drafts(model)[key]._tag === "Validating" || isBusy(model, key)) || rowsKeys.some((key) => rowsOf(model)[key].some((row) => nestedPlans[key].form.engine.isValidating(row.model)));
849
716
  /** The decoded input, once every key and every row is acceptable; else what is wrong with the whole. */
850
717
  const finish = (model) => {
851
- const settled = {
718
+ const settled = model.submitPending ? {
852
719
  ...model,
853
720
  submitPending: false
854
- };
855
- const nested = acceptable(model) ? nestedValues(model) : void 0;
721
+ } : model;
722
+ const nested = acceptable(model) && !hasMarks(model) ? nestedValues(model) : void 0;
856
723
  if (nested === void 0) return { model: settled };
857
724
  return Result.match(decodeInput({
858
725
  ...decoded(model),
@@ -860,7 +727,7 @@ const Core = {
860
727
  }), {
861
728
  onSuccess: (value) => Option.match(judged(settled, value), {
862
729
  onNone: () => ({
863
- model: {
730
+ model: settled.errors.length === 0 ? settled : {
864
731
  ...settled,
865
732
  errors: []
866
733
  },
@@ -881,7 +748,7 @@ const Core = {
881
748
  const validateEvery = (model, inRow) => {
882
749
  let next = model;
883
750
  const commands = [];
884
- for (const key of keys) {
751
+ for (const key of asked(model)) {
885
752
  const state = drafts(next)[key];
886
753
  if (isBusy(next, key)) {
887
754
  if (state._tag === "NotValidated" || state._tag === "Invalid") next = withField(next, key, FieldValidation.Validating({ value: state.value }));
@@ -913,13 +780,17 @@ const Core = {
913
780
  const validateAll = (model) => validateEvery(model, (form, row) => form.engine.validateAll(row));
914
781
  /**
915
782
  * A submit: every key and row is validated. With no failure, the value goes
916
- * out; with checks still running, the submit waits for them.
783
+ * out; with checks still running, the submit waits for them. A submit that
784
+ * changes nothing (a second one of a valid form) keeps the Model it was
785
+ * given, so a parent that refuses the value has nothing to undo.
917
786
  */
918
787
  const submit = (model) => {
919
- const { model: next, commands } = validateEvery({
788
+ const cleared = hasMarks(model) || model.errors.length === 0;
789
+ const { model: next, commands } = validateEvery(cleared && !model.submitPending && model.attempted ? model : {
920
790
  ...model,
921
- errors: [],
922
- submitPending: false
791
+ errors: cleared ? model.errors : [],
792
+ submitPending: false,
793
+ attempted: true
923
794
  }, (form, row) => form.engine.submit(row));
924
795
  if (isValidating(next)) return {
925
796
  model: {
@@ -961,6 +832,7 @@ const Core = {
961
832
  const edited = (model) => ({
962
833
  ...model,
963
834
  errors: [],
835
+ marks: {},
964
836
  submitPending: false
965
837
  });
966
838
  /** Shows existing values, as an edit form does; keys not given keep their draft and their rows. */
@@ -976,13 +848,15 @@ const Core = {
976
848
  const filled = {
977
849
  ...model,
978
850
  searches: {},
979
- touched: Object.fromEntries(followers.flatMap((key) => key in given ? isEmpty(shown(plans[key], given[key])) ? [] : [[key, true]] : model.touched[key] === true ? [[key, true]] : [])),
851
+ touched: Object.fromEntries(followers.flatMap((key) => Object.hasOwn(given, key) ? isEmpty(shown(plans[key], given[key])) ? [] : [[key, true]] : model.touched[key] === true ? [[key, true]] : [])),
852
+ attempted: false,
980
853
  errors: [],
854
+ marks: {},
981
855
  submitPending: false,
982
- fields: fieldsFrom((plan) => plan.key in given ? FieldValidation.NotValidated({ value: plan.bundled !== void 0 ? plan.bundled.fill(drafts(model)[plan.key].value, given[plan.key]) : shown(plan, given[plan.key]) }) : drafts(model)[plan.key])
856
+ fields: fieldsFrom((plan) => Object.hasOwn(given, plan.key) ? FieldValidation.NotValidated({ value: plan.bundled !== void 0 ? plan.bundled.fill(drafts(model)[plan.key].value, given[plan.key]) : shown(plan, given[plan.key]) }) : drafts(model)[plan.key])
983
857
  };
984
858
  return { model: rowsKeys.reduce((next, key) => {
985
- if (!(key in given)) return next;
859
+ if (!Object.hasOwn(given, key)) return next;
986
860
  const { form, optional } = nestedPlans[key];
987
861
  const held = given[key];
988
862
  const models = (Array.isArray(held) ? held : held === null || held === void 0 ? [] : [held]).map((value) => form.fill(form.initial, value).model);
@@ -1011,18 +885,24 @@ const Core = {
1011
885
  onNone: () => ({ model }),
1012
886
  onSome: (value) => changed(edited(model), message.key, value)
1013
887
  });
1014
- case "Blurred": {
888
+ case "Validated": {
1015
889
  const state = drafts(model)[message.key];
1016
890
  return state._tag === "NotValidated" ? validateKey(model, message.key, state.value) : { model };
1017
891
  }
1018
892
  case "ValidatedAll": return validateAll(model);
1019
893
  case "Refused": {
1020
- const state = drafts(model)[message.key];
894
+ const holds = Result.match(plans[message.key].check(drafts(model)[message.key].value), {
895
+ onSuccess: (value) => Equal.equals(value, message.value),
896
+ onFailure: () => false
897
+ });
898
+ const marked = marksOf(model, message.key);
899
+ if (!holds || marked.includes(message.error)) return { model };
1021
900
  return { model: {
1022
- ...withField(model, message.key, FieldValidation.Invalid({
1023
- value: state.value,
1024
- errors: [message.error]
1025
- })),
901
+ ...model,
902
+ marks: {
903
+ ...model.marks,
904
+ [message.key]: [...marked, message.error]
905
+ },
1026
906
  submitPending: false
1027
907
  } };
1028
908
  }
@@ -1033,6 +913,10 @@ const Core = {
1033
913
  case "Checked": {
1034
914
  const state = drafts(model)[message.key];
1035
915
  if (state._tag !== "Validating" || !sameDraft(state.value, message.draft)) return { model };
916
+ if (message.values !== void 0 && !Equal.equals(message.values, decoded(model)) || message.subject !== void 0 && !Equal.equals(message.subject, model.subject)) return {
917
+ model,
918
+ commands: [ask(model, message.key)]
919
+ };
1036
920
  return resume(withField(model, message.key, message.error === null ? FieldValidation.Valid({ value: state.value }) : FieldValidation.Invalid({
1037
921
  value: state.value,
1038
922
  errors: [message.error]
@@ -1109,6 +993,7 @@ const Core = {
1109
993
  subject: model.subject
1110
994
  } };
1111
995
  case "Submitted": return submitted(model);
996
+ case "Blurred":
1112
997
  case "FollowedIssue":
1113
998
  case "AskedForMore": return { model };
1114
999
  }
@@ -1140,6 +1025,17 @@ const Core = {
1140
1025
  }
1141
1026
  return false;
1142
1027
  };
1028
+ const controls = everyKey.map((key) => {
1029
+ const { control, label, description, required, member } = plans[key] ?? nestedPlans[key];
1030
+ return {
1031
+ key,
1032
+ control,
1033
+ label,
1034
+ description,
1035
+ required,
1036
+ member
1037
+ };
1038
+ });
1143
1039
  return {
1144
1040
  /** The name, input and options the form was made from: what a pipe step makes the next form from. */
1145
1041
  name,
@@ -1162,25 +1058,32 @@ const Core = {
1162
1058
  /** The Model the form starts from and resets to: every key empty and not validated. */
1163
1059
  initial,
1164
1060
  /** The keys in the input's order, each with its control, label, and member. */
1165
- controls: everyKey.map((key) => {
1166
- const { control, label, description, required, member } = plans[key] ?? nestedPlans[key];
1167
- return {
1168
- key,
1169
- control,
1170
- label,
1171
- description,
1172
- required,
1173
- member
1174
- };
1175
- }),
1061
+ controls,
1062
+ /**
1063
+ * Over a variant Entity's input, the case its `_tag` key names as it
1064
+ * stands; none before one is chosen, and for any other form.
1065
+ */
1066
+ chosen,
1067
+ /**
1068
+ * Whether a view draws `key` now: a key of a field only some cases have is
1069
+ * asked, validated and submitted only once one of those cases is chosen.
1070
+ * Every key of any other form.
1071
+ */
1072
+ shows: (model, key) => shows(model, key),
1073
+ /**
1074
+ * The same controls by key, for a view that places each field itself:
1075
+ * `form.controlsByKey.email.label`.
1076
+ */
1077
+ controlsByKey: Object.fromEntries(controls.map((entry) => [entry.key, entry])),
1176
1078
  /**
1177
- * One key's state with its draft as any `Draft`, for a view that walks
1178
- * `controls`. `model.fields.title` is the same value, typed to that key. A
1179
- * nested key has rows and no draft.
1079
+ * One key's state as a view shows it, with its draft as any `Draft`: its
1080
+ * own validation, made `Invalid` by the marks on it (`FormModel.marks`).
1081
+ * `model.fields.title` is the key's own validation alone. A nested key has
1082
+ * rows and no draft.
1180
1083
  */
1181
1084
  field: (model, key) => {
1182
1085
  if (plans[key]?.bundled !== void 0) return fail(name, `"${key}" holds a control's Model, not a draft; read it with control`);
1183
- return drafts(model)[key] ?? fail(name, `"${key}" holds rows, not a draft; read it with rows`);
1086
+ return shownField(model, key, drafts(model)[key] ?? fail(name, `"${key}" holds rows, not a draft; read it with rows`));
1184
1087
  },
1185
1088
  /**
1186
1089
  * The key edited by a control backed by a Bundle, addressed: `field` is its
@@ -1190,7 +1093,7 @@ const Core = {
1190
1093
  control: (key) => {
1191
1094
  if (plans[key]?.bundled === void 0) fail(name, `"${key}" is not edited by a control backed by a Bundle`);
1192
1095
  return {
1193
- field: (model) => model.fields[key],
1096
+ field: (model) => shownField(model, key, model.fields[key]),
1194
1097
  send: (message) => Message.Control({
1195
1098
  key,
1196
1099
  message
@@ -1247,6 +1150,8 @@ const Core = {
1247
1150
  const next = submit(model);
1248
1151
  return next.value !== void 0 || next.model.submitPending;
1249
1152
  },
1153
+ /** Whether a submit was asked since the form started, was filled or was reset. */
1154
+ attempted: (model) => model.attempted,
1250
1155
  /**
1251
1156
  * Whether the form is valid right now: a submit now would hand over the
1252
1157
  * value at once. Unlike `canSubmit`, a check running, or one a key has not
@@ -1371,4 +1276,4 @@ const Form = {
1371
1276
  makeNested = Core.make;
1372
1277
  export { Form, Input, fillWords };
1373
1278
 
1374
- //# sourceMappingURL=index.mjs.map
1279
+ //# sourceMappingURL=index.js.map