foldkit-form 0.2.0 → 0.3.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.
package/dist/index.mjs CHANGED
@@ -1,25 +1,38 @@
1
- import { Effect, Pipeable, Result, Schema } from "effect";
2
- import { Bundle } from "foldkit-bundle";
1
+ import { Effect, Option, Pipeable, Result, Schema, SchemaAST } from "effect";
2
+ import { Bundle, Link } from "foldkit-bundle";
3
+ import { SchemaShape, Words } from "foldkit-entity";
3
4
  import { Metadata } from "foldkit-metadata";
4
5
  import { mapMessages } from "foldkit/command";
5
6
  import * as FieldValidation from "foldkit/fieldValidation";
6
7
  import { defineMessageUnion } from "foldkit/message";
7
8
  //#region 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
+ */
8
19
  const isControlChange = (value) => "change" in value;
9
20
  /** A kind of control. The kinds below are made with it, and so is an application's. */
10
- const kind = (name, spec) => ({
11
- kind: name,
12
- of: (data) => Object.freeze({
21
+ const kind = (name, spec) => {
22
+ return {
13
23
  kind: name,
14
- draft: spec.draft,
15
- shown: spec.shown ?? true,
16
- searches: typeof spec.searches === "function" ? spec.searches(data) : spec.searches ?? false,
17
- data,
18
- parse: spec.parse,
19
- unparsed: spec.unparsed
20
- }),
21
- is: (control) => control.kind === name
22
- });
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.parse === void 0 ? {} : { parse: spec.parse },
31
+ unparsed: spec.unparsed
32
+ }),
33
+ is: (control) => control.kind === name
34
+ };
35
+ };
23
36
  const nothing = Object.freeze({});
24
37
  const Text = kind("Text", { draft: "text" });
25
38
  const Hidden = kind("Hidden", {
@@ -36,7 +49,15 @@ const Number_ = kind("Number", {
36
49
  unparsed: "Enter a number"
37
50
  });
38
51
  const Toggle = kind("Toggle", { draft: "flag" });
39
- const Select = kind("Select", { draft: "text" });
52
+ /**
53
+ * One of a fixed set, text or numbers. The draft is the option as text, as a
54
+ * `<select>` holds it; the value is the option itself, so `3` is stored as `3`.
55
+ */
56
+ const Select = kind("Select", {
57
+ draft: "text",
58
+ parse: (draft, data) => data.options.find((option) => String(option) === draft),
59
+ unparsed: "Choose one of the options"
60
+ });
40
61
  const RelationOne = kind("RelationOne", {
41
62
  draft: "text",
42
63
  searches: (data) => data.search
@@ -50,18 +71,17 @@ const key = Metadata.key("foldkit-form/input", {
50
71
  merge: (controls) => controls.slice(-1),
51
72
  summarize: (control) => control.kind
52
73
  });
53
- /** The schema with `null` and `undefined` set aside: optional text is still text. */
54
- const present = (ast) => ast._tag === "Union" ? (ast.types ?? []).filter((member) => member._tag !== "Null" && member._tag !== "Undefined") : [ast];
55
74
  const fromSchema = (schema) => {
56
- const members = present(schema.ast);
75
+ const members = SchemaShape.present(schema.ast);
57
76
  const [only] = members;
58
77
  if (members.length === 1 && only !== void 0) {
59
- if (only._tag === "String") return Text.of(nothing);
60
- if (only._tag === "Number") return Number_.of(nothing);
61
- if (only._tag === "Boolean") return Toggle.of(nothing);
78
+ if (SchemaAST.isString(only)) return Text.of(nothing);
79
+ if (SchemaAST.isNumber(only)) return Number_.of(nothing);
80
+ if (SchemaAST.isBoolean(only)) return Toggle.of(nothing);
62
81
  }
63
- const literals = members.map((member) => member._tag === "Literal" ? member.literal : void 0);
64
- return literals.length > 0 && literals.every((literal) => typeof literal === "string") ? Select.of({ options: literals }) : void 0;
82
+ const literals = members.map((member) => SchemaAST.isLiteral(member) ? member.literal : void 0);
83
+ const options = literals.filter((literal) => typeof literal === "string" || typeof literal === "number");
84
+ return options.length > 0 && options.length === literals.length ? Select.of({ options }) : void 0;
65
85
  };
66
86
  const Input = {
67
87
  /**
@@ -79,6 +99,29 @@ const Input = {
79
99
  RelationOne,
80
100
  RelationMany,
81
101
  Nested,
102
+ /**
103
+ * A control backed by a Bundle, for a draft that is a Model of its own: a
104
+ * color picker with a popover, a page builder, a rich-text editor. The key's
105
+ * draft is the Bundle's Model; `value` reads what the key validates and
106
+ * submits from it, and `fill` writes a given value into it. The Bundle's
107
+ * Messages travel as the form's `Control` Message, and its Commands,
108
+ * Subscriptions and Resources become the form's.
109
+ */
110
+ bundle: (kind, spec) => Object.freeze({
111
+ kind,
112
+ draft: "model",
113
+ shown: true,
114
+ searches: false,
115
+ data: Object.freeze({
116
+ bundle: spec.bundle,
117
+ args: spec.args,
118
+ value: spec.value,
119
+ fill: spec.fill,
120
+ settled: spec.settled ?? ((model) => model)
121
+ })
122
+ }),
123
+ /** Whether a control is backed by a Bundle, whatever its kind is called. */
124
+ isBundle: (control) => control.draft === "model",
82
125
  text: () => Text.of(nothing),
83
126
  /** Carried and submitted, not shown: the id of the thing being edited. Set it with `fill`. */
84
127
  hidden: () => Hidden.of(nothing),
@@ -87,6 +130,20 @@ const Input = {
87
130
  toggle: () => Toggle.of(nothing),
88
131
  select: (options) => Select.of({ options }),
89
132
  /**
133
+ * A picker of one of `target`, for a value that is not a relation of the
134
+ * form's Entity: a page Builder's Block prop that holds an id. A relation key
135
+ * resolves to its picker without asking.
136
+ */
137
+ relationOne: (target) => RelationOne.of({
138
+ target,
139
+ search: false
140
+ }),
141
+ /** A picker of any number of `target`, as `relationOne` is of one. */
142
+ relationMany: (target) => RelationMany.of({
143
+ target,
144
+ search: false
145
+ }),
146
+ /**
90
147
  * For a relation key, under `inputs`: its picker, with a search. Too many to
91
148
  * list is the usual case for a relation; the form holds the search text, and
92
149
  * the query that lists the options takes it as input.
@@ -131,17 +188,21 @@ const Input = {
131
188
  * than guessing.
132
189
  */
133
190
  resolve: (member, schema) => {
134
- if (member._tag === "Unmapped") return fromSchema(schema);
135
- if (member._tag === "NestedInput") return void 0;
136
- const owner = member._tag === "Field" ? member : member.relation;
137
- const [explicit] = key.get(owner.metadata);
138
- if (explicit !== void 0) return explicit;
139
- if (member._tag === "Field") return fromSchema(schema);
140
- const data = {
141
- target: member.relation.target(),
142
- search: false
143
- };
144
- return member.relation.cardinality === "many" ? RelationMany.of(data) : RelationOne.of(data);
191
+ switch (member._tag) {
192
+ case "Unmapped": return fromSchema(schema);
193
+ case "NestedInput": return;
194
+ case "Field": return key.get(member.metadata)[0] ?? fromSchema(schema);
195
+ case "RelationInput": {
196
+ const { relation } = member;
197
+ const [explicit] = key.get(relation.metadata);
198
+ if (explicit !== void 0) return explicit;
199
+ const data = {
200
+ target: relation.target(),
201
+ search: false
202
+ };
203
+ return relation.cardinality === "many" ? RelationMany.of(data) : RelationOne.of(data);
204
+ }
205
+ }
145
206
  }
146
207
  };
147
208
  //#endregion
@@ -169,37 +230,62 @@ const labelKey = Metadata.key("foldkit-form/label", {
169
230
  });
170
231
  /** Assigned once `Form` exists: a form builds the forms of its nested keys with itself. */
171
232
  let makeNested;
172
- /** An edit, however deep: it answers the last submit. An answered check or a blur does not. */
173
- const isEdit = (message) => message._tag === "Nested" ? isEdit(message.message) : [
174
- "Changed",
175
- "RowAdded",
176
- "RowRemoved",
177
- "Reset"
178
- ].includes(message._tag);
233
+ /**
234
+ * Which of a form's Messages are edits, which answer the last submit; an answered
235
+ * check or a blur does not. A `Nested` one is an edit when the row's Message is.
236
+ */
237
+ const edits = {
238
+ Changed: true,
239
+ Blurred: false,
240
+ ValidatedAll: false,
241
+ Submitted: false,
242
+ Reset: true,
243
+ Checked: false,
244
+ Refused: false,
245
+ About: false,
246
+ Searched: false,
247
+ Nested: false,
248
+ Control: false,
249
+ RowAdded: true,
250
+ RowRemoved: true
251
+ };
252
+ /** An edit, however deep. */
253
+ const isEdit = (message) => message._tag === "Nested" ? isEdit(message.message) : edits[message._tag];
179
254
  const kindOf = (draft) => typeof draft === "string" ? "text" : typeof draft === "boolean" ? "flag" : Array.isArray(draft) && draft.every((item) => typeof item === "string") ? "list" : void 0;
180
255
  const sameDraft = (left, right) => Array.isArray(left) && Array.isArray(right) ? left.length === right.length && left.every((item, index) => item === right[index]) : left === right;
181
256
  const isEmpty = (draft) => draft === "" || Array.isArray(draft) && draft.length === 0;
182
257
  /** Text that is read as something else is blank when it is only spaces: `Number(' ')` is 0, which nobody typed. */
183
258
  const isBlank = (control, draft) => isEmpty(draft) || control.parse !== void 0 && typeof draft === "string" && draft.trim() === "";
184
- const annotationsOf = (schema) => Schema.resolveAnnotations(schema) ?? {};
259
+ /**
260
+ * What an `Option`-typed key holds (`Schema.Option`, `Schema.OptionFromNullOr`),
261
+ * found as Effect's own tools find it: by the declaration's representation id.
262
+ */
263
+ const optionOf = (schema) => {
264
+ const { ast } = schema;
265
+ if (!SchemaAST.isDeclaration(ast) || ast.typeParameters.length !== 1) return Option.none();
266
+ const representation = ast.annotations?.["representation"];
267
+ return typeof representation === "object" && representation !== null && "id" in representation && representation.id === "effect/schema/Option" ? Option.some(Schema.make(ast.typeParameters[0])) : Option.none();
268
+ };
185
269
  /** The schema's `title`, else `Form.label` metadata on the member, else the key. */
186
270
  const wordsOf = (key, schema, member) => {
187
271
  const own = member._tag === "Unmapped" ? void 0 : member._tag === "Field" ? member : member.relation;
188
272
  const [labelled] = own === void 0 ? [] : labelKey.get(own.metadata);
189
- const annotated = [schema, ...member._tag === "Field" ? [member.schema] : []].map(annotationsOf);
190
- const title = annotated.map((entry) => entry.title).find((value) => typeof value === "string");
191
- const description = annotated.map((entry) => entry.description).find((value) => typeof value === "string");
273
+ const words = [schema, ...member._tag === "Field" ? [member.schema] : []].map(Words.of);
274
+ const first = (pick) => Option.firstSomeOf(words.map(pick));
192
275
  return {
193
- label: title ?? labelled?.label ?? key,
194
- description: description ?? labelled?.description
276
+ label: Option.getOrElse(first((entry) => entry.title), () => labelled?.label ?? key),
277
+ description: Option.getOrElse(first((entry) => entry.description), () => labelled?.description)
195
278
  };
196
279
  };
197
280
  const nestedPlanOf = (name, key, schema, member, given, inherited) => {
198
281
  const accepts = Schema.is(Schema.toType(schema));
199
282
  const cardinality = member.relation.cardinality;
200
- const optional = cardinality === "many" || accepts(void 0) || accepts(null);
283
+ const absent = SchemaAST.isOptional(schema.ast) || accepts(void 0);
284
+ const optional = cardinality === "many" || absent || accepts(null);
201
285
  if (given !== void 0 && given.input !== member.input) fail(name, `"${key}" is given a form of another input than the one it nests; make it from the input passed to Relation.nested`);
202
286
  const form = given ?? makeNested(`${name}.${key}`, member.input, inherited);
287
+ const lifecycle = form.bundle;
288
+ if (lifecycle.subscriptions !== void 0 || lifecycle.resources !== void 0) fail(name, `"${key}" nests a form with a control whose Bundle has Subscriptions or Resources, which rows cannot run yet`);
203
289
  return {
204
290
  key,
205
291
  ...wordsOf(key, schema, member),
@@ -213,18 +299,26 @@ const nestedPlanOf = (name, key, schema, member, given, inherited) => {
213
299
  form,
214
300
  cardinality,
215
301
  optional,
216
- nothing: accepts(void 0) ? void 0 : null
302
+ nothing: absent ? void 0 : null
217
303
  };
218
304
  };
219
305
  const planOf = (name, key, schema, member, override, messages) => {
220
- const resolved = Input.resolve(member, schema);
306
+ const held = optionOf(schema);
307
+ const shape = Option.getOrElse(held, () => schema);
308
+ const resolved = Input.resolve(member, shape);
221
309
  const control = (override === void 0 ? resolved : isControlChange(override) ? attempt(name, () => override.change(resolved, key)) : override) ?? fail(name, `no control for "${key}"; name one under "inputs"`);
222
310
  if (control.draft === "rows") return fail(name, `"${key}" cannot be given a ${control.kind} control; map it with Relation.nested`);
223
311
  const kind = control.draft;
224
- const type = Schema.toType(schema);
312
+ const type = Schema.toType(shape);
225
313
  const decode = Schema.decodeUnknownResult(type);
226
314
  const accepts = Schema.is(type);
227
- const empty = kind === "flag" ? false : kind === "list" ? [] : "";
315
+ const bundled = Input.isBundle(control) ? control.data : void 0;
316
+ const empty = bundled !== void 0 ? bundled.bundle.init(bundled.args).model : kind === "flag" ? false : kind === "list" ? [] : "";
317
+ const blank = (draft) => {
318
+ if (bundled === void 0) return isBlank(control, draft);
319
+ const value = bundled.value(draft);
320
+ return value === void 0 || value === null;
321
+ };
228
322
  const samples = kind === "flag" ? [true, false] : kind === "list" ? [[], ["id"]] : [];
229
323
  if (samples.length > 0 && !samples.some(accepts)) fail(name, `"${key}" is edited as ${control.kind}, but its schema accepts no such value`);
230
324
  const { label, description } = wordsOf(key, schema, member);
@@ -248,18 +342,14 @@ const planOf = (name, key, schema, member, override, messages) => {
248
342
  message
249
343
  }) ?? message
250
344
  };
345
+ const [admitted] = (bundled === void 0 ? [null, empty] : [null]).filter((value) => accepts(value));
346
+ const nothingEntered = SchemaAST.isOptional(schema.ast) || accepts(void 0) ? Result.succeed(void 0) : Option.isSome(held) ? Result.succeed(Option.none()) : admitted !== void 0 ? Result.succeed(admitted) : Result.fail(say.required);
251
347
  const check = (draft) => {
252
- if (isBlank(control, draft)) {
253
- for (const nothing of [
254
- void 0,
255
- null,
256
- empty
257
- ]) if (accepts(nothing)) return Result.succeed(nothing);
258
- return Result.fail(say.required);
259
- }
260
- const value = control.parse !== void 0 && typeof draft === "string" ? control.parse(draft) : draft;
348
+ if (blank(draft)) return nothingEntered;
349
+ const value = bundled !== void 0 ? bundled.value(draft) : control.parse !== void 0 && typeof draft === "string" ? control.parse(draft, control.data) : draft;
261
350
  if (value === void 0) return Result.fail(say.unparsed);
262
- return Result.mapError(decode(value), (error) => say.invalid(error.message));
351
+ const decoded = Result.mapError(decode(value), (error) => say.invalid(error.message));
352
+ return Option.isSome(held) ? Result.map(decoded, Option.some) : decoded;
263
353
  };
264
354
  const required = kind !== "flag" && Result.isFailure(check(empty));
265
355
  return {
@@ -272,8 +362,9 @@ const planOf = (name, key, schema, member, override, messages) => {
272
362
  member,
273
363
  label,
274
364
  description,
365
+ bundled,
275
366
  rules: FieldValidation.makeRules({
276
- isEmpty: (draft) => isBlank(control, draft),
367
+ isEmpty: blank,
277
368
  ...required ? { required: say.required } : {},
278
369
  rules: [[(draft) => Result.isSuccess(check(draft)), (draft) => Result.match(check(draft), {
279
370
  onSuccess: () => "",
@@ -295,8 +386,11 @@ const attempt = (name, run) => {
295
386
  return fail(name, error instanceof Error ? error.message : String(error));
296
387
  }
297
388
  };
298
- /** The draft that shows `value`: a number as its text, nothing as the empty draft. */
299
- const draftOf = (plan, value) => value === null || value === void 0 ? plan.empty : plan.kind === "text" ? String(value) : value;
389
+ /** The draft that shows `value`: a number as its text, nothing (`Option.none()` too) as the empty draft. */
390
+ const draftOf = (plan, given) => {
391
+ const value = Option.isOption(given) ? Option.getOrUndefined(given) : given;
392
+ return value === null || value === void 0 ? plan.empty : plan.kind === "text" ? String(value) : value;
393
+ };
300
394
  const Core = {
301
395
  /**
302
396
  * A form for one operation's input. A key mapped with `Relation.nested` holds
@@ -311,6 +405,8 @@ const Core = {
311
405
  const rowsKeys = everyKey.filter((key) => members[key]._tag === "NestedInput");
312
406
  const overrides = options.inputs ?? {};
313
407
  const plans = Object.fromEntries(keys.map((key) => [key, planOf(name, key, input.schema.fields[key], members[key], overrides[key], options.messages ?? {})]));
408
+ const controlKeys = keys.filter((key) => plans[key].bundled !== void 0);
409
+ 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`);
314
410
  const givenForms = options.nested ?? {};
315
411
  const nestedPlans = Object.fromEntries(rowsKeys.map((key) => [key, nestedPlanOf(name, key, input.schema.fields[key], members[key], givenForms[key], {
316
412
  messages: options.messages,
@@ -321,8 +417,9 @@ const Core = {
321
417
  flag: Schema.Boolean,
322
418
  list: Schema.Array(Schema.String)
323
419
  };
420
+ const schemaOf = (plan) => plan.bundled !== void 0 ? plan.bundled.bundle.Model : draftSchema[plan.kind];
324
421
  const Model = Schema.Struct({
325
- fields: Schema.Struct(Object.fromEntries(keys.map((key) => [key, FieldValidation.Field(draftSchema[plans[key].kind])]))),
422
+ fields: Schema.Struct(Object.fromEntries(keys.map((key) => [key, FieldValidation.Field(schemaOf(plans[key]))]))),
326
423
  rows: Schema.Struct(Object.fromEntries(rowsKeys.map((key) => [key, Schema.Array(Schema.Struct({
327
424
  id: Schema.String,
328
425
  model: nestedPlans[key].form.bundle.Model
@@ -340,6 +437,7 @@ const Core = {
340
437
  Schema.Boolean,
341
438
  Schema.Array(Schema.String)
342
439
  ]);
440
+ const ControlKeySchema = controlKeys.length === 0 ? Schema.Never : Schema.Literals(controlKeys);
343
441
  const Message = defineMessageUnion({
344
442
  Changed: {
345
443
  key: KeySchema,
@@ -347,6 +445,12 @@ const Core = {
347
445
  },
348
446
  /** Validates the key as it stands, so a required key left empty says so. */
349
447
  Blurred: { key: KeySchema },
448
+ /**
449
+ * Validates every key not validated yet, in every row too, as a submit
450
+ * would, and submits nothing: for a page that submits several forms at once.
451
+ * A rule spanning keys is said only by a submit.
452
+ */
453
+ ValidatedAll: {},
350
454
  Submitted: {},
351
455
  Reset: {},
352
456
  /** The answer of a check for the draft it was asked about; one for an older draft is dropped. */
@@ -383,6 +487,15 @@ const Core = {
383
487
  row: Schema.String,
384
488
  message: Schema.Unknown
385
489
  },
490
+ /**
491
+ * A Message of the control backed by a Bundle that edits `key`. One the
492
+ * Bundle does not take is dropped. It is an edit when it changes the key's
493
+ * value, and is then validated as `Changed` would be.
494
+ */
495
+ Control: {
496
+ key: ControlKeySchema,
497
+ message: Schema.Unknown
498
+ },
386
499
  /** A new, empty row. A `one` that already has its row takes no other. */
387
500
  RowAdded: { key: Schema.String },
388
501
  /** Removes a row. A `one` that must be there stays. */
@@ -433,14 +546,20 @@ const Core = {
433
546
  const value = Result.getOrUndefined(plans[key].check(drafts(model)[key].value));
434
547
  return value === void 0 ? [] : [[key, value]];
435
548
  }));
549
+ /** A nested key's value; none while some row has none. `undefined` is a key left out. */
550
+ const rowsValue = (model, key) => {
551
+ const plan = nestedPlans[key];
552
+ const values = rowsOf(model)[key].map((row) => plan.form.engine.value(row.model));
553
+ if (values.includes(void 0)) return Option.none();
554
+ return Option.some(plan.cardinality === "many" ? values : values.length === 0 ? plan.nothing : values[0]);
555
+ };
436
556
  /** The value of each nested key, or `undefined` while some row has none. */
437
557
  const nestedValues = (model) => {
438
558
  const entries = [];
439
559
  for (const key of rowsKeys) {
440
- const plan = nestedPlans[key];
441
- const values = rowsOf(model)[key].map((row) => plan.form.engine.value(row.model));
442
- if (values.includes(void 0)) return void 0;
443
- entries.push([key, plan.cardinality === "many" ? values : values.length === 0 ? plan.nothing : values[0]]);
560
+ const value = rowsValue(model, key);
561
+ if (Option.isNone(value)) return void 0;
562
+ if (value.value !== void 0) entries.push([key, value.value]);
444
563
  }
445
564
  return Object.fromEntries(entries);
446
565
  };
@@ -456,11 +575,51 @@ const Core = {
456
575
  message
457
576
  }));
458
577
  /**
578
+ * Each control backed by a Bundle, placed where its key's draft is: its
579
+ * Subscriptions and Resources become the form's, keyed by the key, and its
580
+ * Messages travel as `Control`.
581
+ */
582
+ const placements = controlKeys.map((key) => {
583
+ const bundled = plans[key].bundled;
584
+ const accepts = Schema.is(bundled.bundle.Message);
585
+ const toParentMessage = (message) => Message.Control({
586
+ key,
587
+ message
588
+ });
589
+ const fromParentMessage = (message) => message._tag === "Control" && message.key === key && accepts(message.message) ? Option.some(message.message) : Option.none();
590
+ const link = Link.make({
591
+ read: (model) => Option.some(drafts(model)[key].value),
592
+ write: (model, child) => withField(model, key, {
593
+ ...drafts(model)[key],
594
+ value: child
595
+ }),
596
+ wrapper: {
597
+ tag: "Control",
598
+ Schema: Message.Control,
599
+ cases: {},
600
+ make: toParentMessage,
601
+ toParentMessage,
602
+ fromParentMessage
603
+ },
604
+ path: ["fields", key]
605
+ });
606
+ return {
607
+ key,
608
+ bundled,
609
+ placed: bundled.bundle.at(link, { args: bundled.args })
610
+ };
611
+ });
612
+ /**
459
613
  * Validates the draft of one key. A key with a check that passes its schema is
460
614
  * not `Valid` yet: it is `Validating`, with the Command that asks.
461
615
  */
462
616
  const validateKey = (model, key, draft) => {
463
617
  const state = FieldValidation.validate(plans[key].rules)(draft);
618
+ const current = drafts(model)[key];
619
+ if (state._tag === "NotValidated" && current._tag === "NotValidated" && sameDraft(current.value, draft)) return {
620
+ model,
621
+ commands: []
622
+ };
464
623
  const check = checks[key];
465
624
  if (check === void 0 || state._tag !== "Valid") return {
466
625
  model: withField(model, key, state),
@@ -572,16 +731,11 @@ const Core = {
572
731
  });
573
732
  };
574
733
  /**
575
- * A submit: every key not yet validated is, in every row too, so every failure
576
- * shows. With none, the value goes out; with checks still running, the submit
577
- * waits for them.
734
+ * Every key not yet validated is, and `inRow` is run on every row, so every
735
+ * failure shows. A key or row this changes nothing in keeps its identity.
578
736
  */
579
- const submit = (model) => {
580
- let next = {
581
- ...model,
582
- errors: [],
583
- submitPending: false
584
- };
737
+ const validateEvery = (model, inRow) => {
738
+ let next = model;
585
739
  const commands = [];
586
740
  for (const key of keys) {
587
741
  const state = drafts(next)[key];
@@ -591,16 +745,34 @@ const Core = {
591
745
  commands.push(...validated.commands);
592
746
  }
593
747
  for (const key of rowsKeys) {
594
- const rows = rowsOf(next)[key].map((row) => {
595
- const submitted = nestedPlans[key].form.engine.submit(row.model);
596
- commands.push(...lift(key, row.id, submitted.commands));
597
- return {
748
+ const before = rowsOf(next)[key];
749
+ const rows = before.map((row) => {
750
+ const answered = inRow(nestedPlans[key].form, row.model);
751
+ commands.push(...lift(key, row.id, answered.commands));
752
+ return answered.model === row.model ? row : {
598
753
  id: row.id,
599
- model: submitted.model
754
+ model: answered.model
600
755
  };
601
756
  });
602
- next = withRows(next, key, rows);
757
+ if (rows.some((row, index) => row !== before[index])) next = withRows(next, key, rows);
603
758
  }
759
+ return {
760
+ model: next,
761
+ commands
762
+ };
763
+ };
764
+ /** Every key and row validated as a submit would, and nothing submitted. */
765
+ const validateAll = (model) => validateEvery(model, (form, row) => form.engine.validateAll(row));
766
+ /**
767
+ * A submit: every key and row is validated. With no failure, the value goes
768
+ * out; with checks still running, the submit waits for them.
769
+ */
770
+ const submit = (model) => {
771
+ const { model: next, commands } = validateEvery({
772
+ ...model,
773
+ errors: [],
774
+ submitPending: false
775
+ }, (form, row) => form.engine.submit(row));
604
776
  if (isValidating(next)) return {
605
777
  model: {
606
778
  ...next,
@@ -652,7 +824,7 @@ const Core = {
652
824
  touched: Object.fromEntries(followers.flatMap((key) => key in given ? isEmpty(draftOf(plans[key], given[key])) ? [] : [[key, true]] : model.touched[key] === true ? [[key, true]] : [])),
653
825
  errors: [],
654
826
  submitPending: false,
655
- fields: fieldsFrom((plan) => plan.key in given ? FieldValidation.NotValidated({ value: draftOf(plan, given[plan.key]) }) : drafts(model)[plan.key])
827
+ 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]) : draftOf(plan, given[plan.key]) }) : drafts(model)[plan.key])
656
828
  };
657
829
  return { model: rowsKeys.reduce((next, key) => {
658
830
  if (!(key in given)) return next;
@@ -662,10 +834,21 @@ const Core = {
662
834
  return numbered(next, key, models.length === 0 && !optional ? [form.initial] : models);
663
835
  }, filled) };
664
836
  };
837
+ /** Whether a key's draft says the same thing in two Models: a control's by the value it holds. */
838
+ const sameValue = (key, before, after) => {
839
+ const bundled = plans[key].bundled;
840
+ return bundled === void 0 ? sameDraft(before, after) : Object.is(bundled.value(before), bundled.value(after));
841
+ };
842
+ /** The Subscriptions and Resources of the controls backed by a Bundle, which are the form's. */
843
+ const controlSubscriptions = Object.assign({}, ...placements.map(({ placed }) => placed.subscriptions));
844
+ const controlResources = Object.assign({}, ...placements.map(({ placed }) => placed.resources));
665
845
  const bundle = Bundle.make(name, {
666
846
  Model,
667
847
  Message,
668
- init: () => ({ model: initial }),
848
+ init: () => ({
849
+ model: initial,
850
+ commands: placements.flatMap(({ placed }) => placed.init(initial).commands ?? [])
851
+ }),
669
852
  update: (model, message) => {
670
853
  switch (message._tag) {
671
854
  case "Changed": return kindOf(message.value) !== plans[message.key].kind ? { model } : changed(edited(model), message.key, message.value);
@@ -673,6 +856,7 @@ const Core = {
673
856
  const state = drafts(model)[message.key];
674
857
  return state._tag === "NotValidated" ? validateKey(model, message.key, state.value) : { model };
675
858
  }
859
+ case "ValidatedAll": return validateAll(model);
676
860
  case "Refused": {
677
861
  const state = drafts(model)[message.key];
678
862
  return { model: {
@@ -702,6 +886,25 @@ const Core = {
702
886
  [message.key]: message.text
703
887
  }
704
888
  } } : { model };
889
+ case "Control": {
890
+ const placement = placements.find((held) => held.key === message.key);
891
+ if (placement === void 0) return { model };
892
+ const before = drafts(model)[message.key].value;
893
+ const step = placement.placed.update(model, message);
894
+ if (Option.isNone(step)) return { model };
895
+ const { model: moved, commands = [] } = step.value;
896
+ const after = drafts(moved)[message.key].value;
897
+ const lifted = commands;
898
+ if (sameValue(message.key, before, after)) return {
899
+ model: moved,
900
+ commands: lifted
901
+ };
902
+ const edit = changed(edited(moved), message.key, after);
903
+ return {
904
+ model: edit.model,
905
+ commands: [...lifted, ...edit.commands]
906
+ };
907
+ }
705
908
  case "Nested": {
706
909
  const plan = nestedPlans[message.key];
707
910
  const row = rowsOf(model)[message.key]?.find((held) => held.id === message.row);
@@ -710,11 +913,13 @@ const Core = {
710
913
  const inner = message.message;
711
914
  if (inner._tag === "Submitted") return submitted(model);
712
915
  const answered = plan.form.bundle.update(row.model, inner, void 0);
713
- const next = withRows(model, message.key, rowsOf(model)[message.key].map((held) => held.id === row.id ? {
916
+ const lifted = lift(message.key, row.id, answered.commands ?? []);
917
+ const next = answered.model === row.model ? model : withRows(model, message.key, rowsOf(model)[message.key].map((held) => held.id === row.id ? {
714
918
  id: row.id,
715
919
  model: answered.model
716
920
  } : held));
717
- return resume(isEdit(inner) ? edited(next) : next, lift(message.key, row.id, answered.commands ?? []));
921
+ const edit = isEdit(inner) || plan.form.engine.authoredChanged(row.model, answered.model);
922
+ return resume(edit ? edited(next) : next, lifted);
718
923
  }
719
924
  case "RowAdded": {
720
925
  const plan = nestedPlans[message.key];
@@ -738,7 +943,9 @@ const Core = {
738
943
  case "Submitted": return submitted(model);
739
944
  }
740
945
  },
741
- helpers: { fill }
946
+ helpers: { fill },
947
+ ...Object.keys(controlSubscriptions).length === 0 ? {} : { subscriptions: () => controlSubscriptions },
948
+ ...Object.keys(controlResources).length === 0 ? {} : { resources: () => controlResources }
742
949
  });
743
950
  /**
744
951
  * Whether a completed transition changed what the author wrote. Validation
@@ -750,7 +957,7 @@ const Core = {
750
957
  const authoredChanged = (before, after) => {
751
958
  const beforeDrafts = drafts(before);
752
959
  const afterDrafts = drafts(after);
753
- for (const key of keys) if (!sameDraft(beforeDrafts[key].value, afterDrafts[key].value)) return true;
960
+ for (const key of keys) if (!sameValue(key, beforeDrafts[key].value, afterDrafts[key].value)) return true;
754
961
  for (const key of rowsKeys) {
755
962
  const beforeRows = rowsOf(before)[key];
756
963
  const afterRows = rowsOf(after)[key];
@@ -799,7 +1006,25 @@ const Core = {
799
1006
  * `controls`. `model.fields.title` is the same value, typed to that key. A
800
1007
  * nested key has rows and no draft.
801
1008
  */
802
- field: (model, key) => drafts(model)[key] ?? fail(name, `"${key}" holds rows, not a draft; read it with rows`),
1009
+ field: (model, key) => {
1010
+ if (plans[key]?.bundled !== void 0) return fail(name, `"${key}" holds a control's Model, not a draft; read it with control`);
1011
+ return drafts(model)[key] ?? fail(name, `"${key}" holds rows, not a draft; read it with rows`);
1012
+ },
1013
+ /**
1014
+ * The key edited by a control backed by a Bundle, addressed: `field` is its
1015
+ * state with the Bundle's Model as its value, and `send` gives the form's
1016
+ * Message for one of the Bundle's own.
1017
+ */
1018
+ control: (key) => {
1019
+ if (plans[key]?.bundled === void 0) fail(name, `"${key}" is not edited by a control backed by a Bundle`);
1020
+ return {
1021
+ field: (model) => model.fields[key],
1022
+ send: (message) => Message.Control({
1023
+ key,
1024
+ message
1025
+ })
1026
+ };
1027
+ },
803
1028
  /** What was typed to find a choice for a relation key that searches; `''` until something is. */
804
1029
  search: (model, key) => model.searches[key] ?? "",
805
1030
  /** What the form is editing; `{}` while it creates. See `FormModel.subject`. */
@@ -825,6 +1050,7 @@ const Core = {
825
1050
  ...Object.fromEntries([
826
1051
  "Changed",
827
1052
  "Blurred",
1053
+ "ValidatedAll",
828
1054
  "Searched",
829
1055
  "Submitted",
830
1056
  "Reset",
@@ -849,6 +1075,12 @@ const Core = {
849
1075
  return next.value !== void 0 || next.model.submitPending;
850
1076
  },
851
1077
  /**
1078
+ * Whether the form is valid right now: a submit now would hand over the
1079
+ * value at once. Unlike `canSubmit`, a check running, or one a key has not
1080
+ * had yet, is not valid until it answers.
1081
+ */
1082
+ isValid: (model) => submit(model).value !== void 0,
1083
+ /**
852
1084
  * The Model with nothing in flight, for one that was stored and is shown
853
1085
  * again: a check that was running when it was stored will never answer, so
854
1086
  * its key is not validated yet, and no submit is waiting. Rows too.
@@ -858,7 +1090,11 @@ const Core = {
858
1090
  submitPending: false,
859
1091
  fields: fieldsFrom((plan) => {
860
1092
  const field = drafts(model)[plan.key];
861
- return field._tag === "Validating" ? FieldValidation.NotValidated({ value: field.value }) : field;
1093
+ const held = plan.bundled === void 0 ? field : {
1094
+ ...field,
1095
+ value: plan.bundled.settled(field.value)
1096
+ };
1097
+ return held._tag === "Validating" ? FieldValidation.NotValidated({ value: held.value }) : held;
862
1098
  }),
863
1099
  rows: Object.fromEntries(rowsKeys.map((key) => [key, rowsOf(model)[key].map((row) => ({
864
1100
  ...row,
@@ -872,12 +1108,10 @@ const Core = {
872
1108
  */
873
1109
  partial: (model) => ({
874
1110
  ...decoded(model),
875
- ...Object.fromEntries(rowsKeys.flatMap((key) => {
876
- const plan = nestedPlans[key];
877
- const values = rowsOf(model)[key].map((row) => plan.form.engine.value(row.model));
878
- if (values.includes(void 0)) return [];
879
- return [[key, plan.cardinality === "many" ? values : values.length === 0 ? plan.nothing : values[0]]];
880
- }))
1111
+ ...Object.fromEntries(rowsKeys.flatMap((key) => Option.match(Option.filter(rowsValue(model, key), (held) => held !== void 0), {
1112
+ onNone: () => [],
1113
+ onSome: (held) => [[key, held]]
1114
+ })))
881
1115
  }),
882
1116
  /** The form as the form that nests it drives it. */
883
1117
  engine: {
@@ -888,6 +1122,7 @@ const Core = {
888
1122
  commands
889
1123
  };
890
1124
  },
1125
+ validateAll,
891
1126
  isValidating,
892
1127
  /** Whether a transition changed authored content, so a nesting form recurses. */
893
1128
  authoredChanged,