foldkit-form 0.8.0 → 0.9.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,
@@ -446,6 +212,7 @@ const attempt = (name, run) => {
446
212
  const draftOf = (plan, given) => {
447
213
  const value = Option.isOption(given) ? Option.getOrUndefined(given) : given;
448
214
  if (value === null || value === void 0) return plan.empty;
215
+ if (plan.kind === "list" && Array.isArray(value)) return value.map((item) => String(item));
449
216
  if (plan.kind !== "text") return value;
450
217
  const format = plan.control.format;
451
218
  return format === void 0 ? String(value) : format(value, plan.control.data);
@@ -472,11 +239,11 @@ const Core = {
472
239
  const keys = everyKey.filter((key) => members[key]._tag !== "NestedInput");
473
240
  const rowsKeys = everyKey.filter((key) => members[key]._tag === "NestedInput");
474
241
  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 ?? {})]));
242
+ const plans = Object.fromEntries(keys.map((key) => [key, planOf(name, key, input.schema.fields[key], members[key], own(overrides, key), options.messages ?? {})]));
476
243
  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`);
244
+ 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
245
  const givenForms = options.nested ?? {};
479
- const nestedPlans = Object.fromEntries(rowsKeys.map((key) => [key, nestedPlanOf(name, key, input.schema.fields[key], members[key], givenForms[key], {
246
+ const nestedPlans = Object.fromEntries(rowsKeys.map((key) => [key, nestedPlanOf(name, key, input.schema.fields[key], members[key], own(givenForms, key), {
480
247
  messages: options.messages,
481
248
  debounce: options.debounce,
482
249
  operators: options.operators
@@ -496,7 +263,9 @@ const Core = {
496
263
  nextRow: Schema.Number,
497
264
  searches: Schema.Record(Schema.String, Schema.String),
498
265
  touched: Schema.Record(Schema.String, Schema.Boolean),
266
+ attempted: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))),
499
267
  errors: Schema.Array(Schema.String),
268
+ marks: Schema.Record(Schema.String, Schema.Array(Schema.String)).pipe(Schema.withDecodingDefaultKey(Effect.succeed({}))),
500
269
  submitPending: Schema.Boolean,
501
270
  subject: Schema.Record(Schema.String, Schema.String)
502
271
  });
@@ -512,9 +281,18 @@ const Core = {
512
281
  key: KeySchema,
513
282
  value: DraftSchema
514
283
  },
515
- /** Validates the key as it stands, so a required key left empty says so. */
284
+ /**
285
+ * The person left the key. An edit has already validated it, and a key
286
+ * never edited is not judged before a submit, so tabbing through a field
287
+ * says nothing about it: the form changes nothing.
288
+ */
516
289
  Blurred: { key: KeySchema },
517
290
  /**
291
+ * Validates the key as it stands, edited or not: for a program showing a
292
+ * stored value's failure after a `fill`, which validates nothing.
293
+ */
294
+ Validated: { key: KeySchema },
295
+ /**
518
296
  * Validates every key not validated yet, in every row too, as a submit
519
297
  * would, and submits nothing: for a page that submits several forms at once.
520
298
  * A rule spanning keys is said only by a submit.
@@ -522,21 +300,31 @@ const Core = {
522
300
  ValidatedAll: {},
523
301
  Submitted: {},
524
302
  Reset: {},
525
- /** The answer of a check for the draft it was asked about; one for an older draft is dropped. */
303
+ /**
304
+ * The answer of a check for the draft it was asked about; one for an older
305
+ * draft is dropped. `form.Check` also says the `values` and `subject` it
306
+ * read, and an answer about ones the form no longer holds is asked again.
307
+ * One made without them (a test's) answers the form as it is.
308
+ */
526
309
  Checked: {
527
310
  key: KeySchema,
528
311
  draft: DraftSchema,
312
+ values: Schema.optionalKey(Schema.Unknown),
313
+ subject: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
529
314
  error: Schema.NullOr(Schema.String)
530
315
  },
531
316
  /**
532
317
  * 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.
318
+ * server knows. `value` is the key's value in what was refused, as
319
+ * `Submitted` handed it out. While the key still holds it, the key reads
320
+ * invalid with that reason (a mark, see `FormModel.marks`) until the next
321
+ * edit of any key; a key changed since is not what was refused, and the
322
+ * Message is dropped.
536
323
  */
537
324
  Refused: {
538
325
  key: KeySchema,
539
- error: Schema.String
326
+ error: Schema.String,
327
+ value: Schema.Unknown
540
328
  },
541
329
  /**
542
330
  * What the form is editing, for the checks that need to know: a post's own
@@ -618,7 +406,9 @@ const Core = {
618
406
  nextRow: 0,
619
407
  searches: {},
620
408
  touched: {},
409
+ attempted: false,
621
410
  errors: [],
411
+ marks: {},
622
412
  submitPending: false,
623
413
  subject: {}
624
414
  });
@@ -630,6 +420,23 @@ const Core = {
630
420
  [key]: field
631
421
  }
632
422
  });
423
+ const marksOf = (model, key) => Object.hasOwn(model.marks, key) ? model.marks[key] : [];
424
+ const hasMarks = (model) => Object.keys(model.marks).length > 0;
425
+ /** A key's state as a view shows it: its own, made invalid by the marks on it. */
426
+ const shownField = (model, key, field) => {
427
+ const marked = marksOf(model, key);
428
+ if (!Array$1.isReadonlyArrayNonEmpty(marked)) return field;
429
+ const own = FieldValidation.match(field, {
430
+ onNotValidated: () => [],
431
+ onValidating: () => [],
432
+ onValid: () => [],
433
+ onInvalid: ({ errors }) => errors
434
+ });
435
+ return FieldValidation.Invalid({
436
+ value: field.value,
437
+ errors: Array$1.appendAll(own, marked)
438
+ });
439
+ };
633
440
  const checks = options.checks ?? {};
634
441
  const debounce = options.debounce ?? "300 millis";
635
442
  /**
@@ -652,6 +459,8 @@ const Core = {
652
459
  })), Effect.map((error) => Message.Checked({
653
460
  key,
654
461
  draft,
462
+ values,
463
+ subject,
655
464
  error: error ?? null
656
465
  })))
657
466
  });
@@ -723,6 +532,13 @@ const Core = {
723
532
  placed: bundled.bundle.at(link, { args: bundled.args })
724
533
  };
725
534
  });
535
+ /** The Command asking `key`'s check about its draft, with the values and subject the form holds. */
536
+ const ask = (model, key) => Check({
537
+ key,
538
+ draft: drafts(model)[key].value,
539
+ values: decoded(model),
540
+ subject: model.subject
541
+ });
726
542
  /**
727
543
  * Validates the draft of one key. A key with a check that passes its schema is
728
544
  * not `Valid` yet: it is `Validating`, with the Command that asks.
@@ -734,19 +550,14 @@ const Core = {
734
550
  model,
735
551
  commands: []
736
552
  };
737
- if (checks[key] === void 0 || state._tag !== "Valid") return {
553
+ if (own(checks, key) === void 0 || state._tag !== "Valid") return {
738
554
  model: withField(model, key, state),
739
555
  commands: []
740
556
  };
741
557
  const asking = withField(model, key, FieldValidation.Validating({ value: draft }));
742
558
  return {
743
559
  model: asking,
744
- commands: [Check({
745
- key,
746
- draft,
747
- values: decoded(asking),
748
- subject: model.subject
749
- })]
560
+ commands: [ask(asking, key)]
750
561
  };
751
562
  };
752
563
  const followers = keys.filter((key) => plans[key].control.follows !== void 0);
@@ -782,16 +593,23 @@ const Core = {
782
593
  }
783
594
  } : model;
784
595
  const written = validateKey(owned, key, handedBack ? derived(owned, key) : draft);
785
- return followedBy(key).reduce((result, follower) => {
596
+ const result = followedBy(key).reduce((result, follower) => {
786
597
  if (result.model.touched[follower] === true) return result;
787
598
  const next = rewritten(result.model, follower);
788
599
  return {
789
600
  model: next.model,
790
- commands: [...result.commands, ...next.commands]
601
+ asked: [...result.asked, ...next.asked]
791
602
  };
792
- }, written);
603
+ }, {
604
+ model: written.model,
605
+ asked: written.commands.length === 0 ? [] : [key]
606
+ });
607
+ return {
608
+ model: result.model,
609
+ commands: result.asked.map((asked) => ask(result.model, asked))
610
+ };
793
611
  };
794
- /** A follower written from the key it follows, and its own followers after it. */
612
+ /** A follower written from the key it follows, and its own followers after it, with the keys it asks. */
795
613
  const rewritten = (model, follower) => {
796
614
  const draft = derived(model, follower);
797
615
  const written = isEmpty(draft) ? {
@@ -803,9 +621,12 @@ const Core = {
803
621
  const after = rewritten(result.model, next);
804
622
  return {
805
623
  model: after.model,
806
- commands: [...result.commands, ...after.commands]
624
+ asked: [...result.asked, ...after.asked]
807
625
  };
808
- }, written);
626
+ }, {
627
+ model: written.model,
628
+ asked: written.commands.length === 0 ? [] : [follower]
629
+ });
809
630
  };
810
631
  const decodeInput = Schema.decodeUnknownResult(Schema.toType(input.schema));
811
632
  const keyOfField = new Map(keys.flatMap((key) => {
@@ -822,18 +643,20 @@ const Core = {
822
643
  Valid: () => Option.none(),
823
644
  Undecided: () => Option.none(),
824
645
  Invalid: ({ failures }) => {
825
- let next = model;
646
+ const marks = /* @__PURE__ */ new Map();
826
647
  const errors = [];
827
648
  for (const failure of failures) {
828
649
  const shown = failure.path.flatMap((field) => Option.toArray(Option.fromUndefinedOr(keyOfField.get(field))));
829
650
  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
- }));
651
+ for (const key of shown) {
652
+ const held = marks.get(key);
653
+ if (held === void 0) marks.set(key, [failure.message]);
654
+ else held.push(failure.message);
655
+ }
834
656
  }
835
657
  return Option.some({
836
- ...next,
658
+ ...model,
659
+ marks: Object.fromEntries(marks),
837
660
  errors
838
661
  });
839
662
  }
@@ -852,7 +675,7 @@ const Core = {
852
675
  ...model,
853
676
  submitPending: false
854
677
  };
855
- const nested = acceptable(model) ? nestedValues(model) : void 0;
678
+ const nested = acceptable(model) && !hasMarks(model) ? nestedValues(model) : void 0;
856
679
  if (nested === void 0) return { model: settled };
857
680
  return Result.match(decodeInput({
858
681
  ...decoded(model),
@@ -918,8 +741,9 @@ const Core = {
918
741
  const submit = (model) => {
919
742
  const { model: next, commands } = validateEvery({
920
743
  ...model,
921
- errors: [],
922
- submitPending: false
744
+ errors: hasMarks(model) ? model.errors : [],
745
+ submitPending: false,
746
+ attempted: true
923
747
  }, (form, row) => form.engine.submit(row));
924
748
  if (isValidating(next)) return {
925
749
  model: {
@@ -961,6 +785,7 @@ const Core = {
961
785
  const edited = (model) => ({
962
786
  ...model,
963
787
  errors: [],
788
+ marks: {},
964
789
  submitPending: false
965
790
  });
966
791
  /** Shows existing values, as an edit form does; keys not given keep their draft and their rows. */
@@ -976,13 +801,15 @@ const Core = {
976
801
  const filled = {
977
802
  ...model,
978
803
  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]] : [])),
804
+ touched: Object.fromEntries(followers.flatMap((key) => Object.hasOwn(given, key) ? isEmpty(shown(plans[key], given[key])) ? [] : [[key, true]] : model.touched[key] === true ? [[key, true]] : [])),
805
+ attempted: false,
980
806
  errors: [],
807
+ marks: {},
981
808
  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])
809
+ 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
810
  };
984
811
  return { model: rowsKeys.reduce((next, key) => {
985
- if (!(key in given)) return next;
812
+ if (!Object.hasOwn(given, key)) return next;
986
813
  const { form, optional } = nestedPlans[key];
987
814
  const held = given[key];
988
815
  const models = (Array.isArray(held) ? held : held === null || held === void 0 ? [] : [held]).map((value) => form.fill(form.initial, value).model);
@@ -1011,18 +838,24 @@ const Core = {
1011
838
  onNone: () => ({ model }),
1012
839
  onSome: (value) => changed(edited(model), message.key, value)
1013
840
  });
1014
- case "Blurred": {
841
+ case "Validated": {
1015
842
  const state = drafts(model)[message.key];
1016
843
  return state._tag === "NotValidated" ? validateKey(model, message.key, state.value) : { model };
1017
844
  }
1018
845
  case "ValidatedAll": return validateAll(model);
1019
846
  case "Refused": {
1020
- const state = drafts(model)[message.key];
847
+ const holds = Result.match(plans[message.key].check(drafts(model)[message.key].value), {
848
+ onSuccess: (value) => Equal.equals(value, message.value),
849
+ onFailure: () => false
850
+ });
851
+ const marked = marksOf(model, message.key);
852
+ if (!holds || marked.includes(message.error)) return { model };
1021
853
  return { model: {
1022
- ...withField(model, message.key, FieldValidation.Invalid({
1023
- value: state.value,
1024
- errors: [message.error]
1025
- })),
854
+ ...model,
855
+ marks: {
856
+ ...model.marks,
857
+ [message.key]: [...marked, message.error]
858
+ },
1026
859
  submitPending: false
1027
860
  } };
1028
861
  }
@@ -1033,6 +866,10 @@ const Core = {
1033
866
  case "Checked": {
1034
867
  const state = drafts(model)[message.key];
1035
868
  if (state._tag !== "Validating" || !sameDraft(state.value, message.draft)) return { model };
869
+ if (message.values !== void 0 && !Equal.equals(message.values, decoded(model)) || message.subject !== void 0 && !Equal.equals(message.subject, model.subject)) return {
870
+ model,
871
+ commands: [ask(model, message.key)]
872
+ };
1036
873
  return resume(withField(model, message.key, message.error === null ? FieldValidation.Valid({ value: state.value }) : FieldValidation.Invalid({
1037
874
  value: state.value,
1038
875
  errors: [message.error]
@@ -1109,6 +946,7 @@ const Core = {
1109
946
  subject: model.subject
1110
947
  } };
1111
948
  case "Submitted": return submitted(model);
949
+ case "Blurred":
1112
950
  case "FollowedIssue":
1113
951
  case "AskedForMore": return { model };
1114
952
  }
@@ -1140,6 +978,17 @@ const Core = {
1140
978
  }
1141
979
  return false;
1142
980
  };
981
+ const controls = everyKey.map((key) => {
982
+ const { control, label, description, required, member } = plans[key] ?? nestedPlans[key];
983
+ return {
984
+ key,
985
+ control,
986
+ label,
987
+ description,
988
+ required,
989
+ member
990
+ };
991
+ });
1143
992
  return {
1144
993
  /** The name, input and options the form was made from: what a pipe step makes the next form from. */
1145
994
  name,
@@ -1162,25 +1011,21 @@ const Core = {
1162
1011
  /** The Model the form starts from and resets to: every key empty and not validated. */
1163
1012
  initial,
1164
1013
  /** 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
- }),
1014
+ controls,
1015
+ /**
1016
+ * The same controls by key, for a view that places each field itself:
1017
+ * `form.controlsByKey.email.label`.
1018
+ */
1019
+ controlsByKey: Object.fromEntries(controls.map((entry) => [entry.key, entry])),
1176
1020
  /**
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.
1021
+ * One key's state as a view shows it, with its draft as any `Draft`: its
1022
+ * own validation, made `Invalid` by the marks on it (`FormModel.marks`).
1023
+ * `model.fields.title` is the key's own validation alone. A nested key has
1024
+ * rows and no draft.
1180
1025
  */
1181
1026
  field: (model, key) => {
1182
1027
  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`);
1028
+ return shownField(model, key, drafts(model)[key] ?? fail(name, `"${key}" holds rows, not a draft; read it with rows`));
1184
1029
  },
1185
1030
  /**
1186
1031
  * The key edited by a control backed by a Bundle, addressed: `field` is its
@@ -1190,7 +1035,7 @@ const Core = {
1190
1035
  control: (key) => {
1191
1036
  if (plans[key]?.bundled === void 0) fail(name, `"${key}" is not edited by a control backed by a Bundle`);
1192
1037
  return {
1193
- field: (model) => model.fields[key],
1038
+ field: (model) => shownField(model, key, model.fields[key]),
1194
1039
  send: (message) => Message.Control({
1195
1040
  key,
1196
1041
  message
@@ -1247,6 +1092,8 @@ const Core = {
1247
1092
  const next = submit(model);
1248
1093
  return next.value !== void 0 || next.model.submitPending;
1249
1094
  },
1095
+ /** Whether a submit was asked since the form started, was filled or was reset. */
1096
+ attempted: (model) => model.attempted,
1250
1097
  /**
1251
1098
  * Whether the form is valid right now: a submit now would hand over the
1252
1099
  * value at once. Unlike `canSubmit`, a check running, or one a key has not
@@ -1371,4 +1218,4 @@ const Form = {
1371
1218
  makeNested = Core.make;
1372
1219
  export { Form, Input, fillWords };
1373
1220
 
1374
- //# sourceMappingURL=index.mjs.map
1221
+ //# sourceMappingURL=index.js.map