foldkit-form 0.1.2 → 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,24 +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";
5
+ import { mapMessages } from "foldkit/command";
4
6
  import * as FieldValidation from "foldkit/fieldValidation";
5
7
  import { defineMessageUnion } from "foldkit/message";
6
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
+ */
7
19
  const isControlChange = (value) => "change" in value;
8
20
  /** A kind of control. The kinds below are made with it, and so is an application's. */
9
- const kind = (name, spec) => ({
10
- kind: name,
11
- of: (data) => Object.freeze({
21
+ const kind = (name, spec) => {
22
+ return {
12
23
  kind: name,
13
- draft: spec.draft,
14
- shown: spec.shown ?? true,
15
- searches: typeof spec.searches === "function" ? spec.searches(data) : spec.searches ?? false,
16
- data,
17
- parse: spec.parse,
18
- unparsed: spec.unparsed
19
- }),
20
- is: (control) => control.kind === name
21
- });
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
+ };
22
36
  const nothing = Object.freeze({});
23
37
  const Text = kind("Text", { draft: "text" });
24
38
  const Hidden = kind("Hidden", {
@@ -35,7 +49,15 @@ const Number_ = kind("Number", {
35
49
  unparsed: "Enter a number"
36
50
  });
37
51
  const Toggle = kind("Toggle", { draft: "flag" });
38
- 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
+ });
39
61
  const RelationOne = kind("RelationOne", {
40
62
  draft: "text",
41
63
  searches: (data) => data.search
@@ -49,18 +71,17 @@ const key = Metadata.key("foldkit-form/input", {
49
71
  merge: (controls) => controls.slice(-1),
50
72
  summarize: (control) => control.kind
51
73
  });
52
- /** The schema with `null` and `undefined` set aside: optional text is still text. */
53
- const present = (ast) => ast._tag === "Union" ? (ast.types ?? []).filter((member) => member._tag !== "Null" && member._tag !== "Undefined") : [ast];
54
74
  const fromSchema = (schema) => {
55
- const members = present(schema.ast);
75
+ const members = SchemaShape.present(schema.ast);
56
76
  const [only] = members;
57
77
  if (members.length === 1 && only !== void 0) {
58
- if (only._tag === "String") return Text.of(nothing);
59
- if (only._tag === "Number") return Number_.of(nothing);
60
- 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);
61
81
  }
62
- const literals = members.map((member) => member._tag === "Literal" ? member.literal : void 0);
63
- 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;
64
85
  };
65
86
  const Input = {
66
87
  /**
@@ -78,6 +99,29 @@ const Input = {
78
99
  RelationOne,
79
100
  RelationMany,
80
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",
81
125
  text: () => Text.of(nothing),
82
126
  /** Carried and submitted, not shown: the id of the thing being edited. Set it with `fill`. */
83
127
  hidden: () => Hidden.of(nothing),
@@ -86,6 +130,20 @@ const Input = {
86
130
  toggle: () => Toggle.of(nothing),
87
131
  select: (options) => Select.of({ options }),
88
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
+ /**
89
147
  * For a relation key, under `inputs`: its picker, with a search. Too many to
90
148
  * list is the usual case for a relation; the form holds the search text, and
91
149
  * the query that lists the options takes it as input.
@@ -130,17 +188,21 @@ const Input = {
130
188
  * than guessing.
131
189
  */
132
190
  resolve: (member, schema) => {
133
- if (member._tag === "Unmapped") return fromSchema(schema);
134
- if (member._tag === "NestedInput") return void 0;
135
- const owner = member._tag === "Field" ? member : member.relation;
136
- const [explicit] = key.get(owner.metadata);
137
- if (explicit !== void 0) return explicit;
138
- if (member._tag === "Field") return fromSchema(schema);
139
- const data = {
140
- target: member.relation.target(),
141
- search: false
142
- };
143
- 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
+ }
144
206
  }
145
207
  };
146
208
  //#endregion
@@ -168,37 +230,62 @@ const labelKey = Metadata.key("foldkit-form/label", {
168
230
  });
169
231
  /** Assigned once `Form` exists: a form builds the forms of its nested keys with itself. */
170
232
  let makeNested;
171
- /** An edit, however deep: it answers the last submit. An answered check or a blur does not. */
172
- const isEdit = (message) => message._tag === "Nested" ? isEdit(message.message) : [
173
- "Changed",
174
- "RowAdded",
175
- "RowRemoved",
176
- "Reset"
177
- ].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];
178
254
  const kindOf = (draft) => typeof draft === "string" ? "text" : typeof draft === "boolean" ? "flag" : Array.isArray(draft) && draft.every((item) => typeof item === "string") ? "list" : void 0;
179
255
  const sameDraft = (left, right) => Array.isArray(left) && Array.isArray(right) ? left.length === right.length && left.every((item, index) => item === right[index]) : left === right;
180
256
  const isEmpty = (draft) => draft === "" || Array.isArray(draft) && draft.length === 0;
181
257
  /** Text that is read as something else is blank when it is only spaces: `Number(' ')` is 0, which nobody typed. */
182
258
  const isBlank = (control, draft) => isEmpty(draft) || control.parse !== void 0 && typeof draft === "string" && draft.trim() === "";
183
- 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
+ };
184
269
  /** The schema's `title`, else `Form.label` metadata on the member, else the key. */
185
270
  const wordsOf = (key, schema, member) => {
186
271
  const own = member._tag === "Unmapped" ? void 0 : member._tag === "Field" ? member : member.relation;
187
272
  const [labelled] = own === void 0 ? [] : labelKey.get(own.metadata);
188
- const annotated = [schema, ...member._tag === "Field" ? [member.schema] : []].map(annotationsOf);
189
- const title = annotated.map((entry) => entry.title).find((value) => typeof value === "string");
190
- 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));
191
275
  return {
192
- label: title ?? labelled?.label ?? key,
193
- 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)
194
278
  };
195
279
  };
196
280
  const nestedPlanOf = (name, key, schema, member, given, inherited) => {
197
281
  const accepts = Schema.is(Schema.toType(schema));
198
282
  const cardinality = member.relation.cardinality;
199
- 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);
200
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`);
201
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`);
202
289
  return {
203
290
  key,
204
291
  ...wordsOf(key, schema, member),
@@ -212,18 +299,26 @@ const nestedPlanOf = (name, key, schema, member, given, inherited) => {
212
299
  form,
213
300
  cardinality,
214
301
  optional,
215
- nothing: accepts(void 0) ? void 0 : null
302
+ nothing: absent ? void 0 : null
216
303
  };
217
304
  };
218
305
  const planOf = (name, key, schema, member, override, messages) => {
219
- 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);
220
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"`);
221
310
  if (control.draft === "rows") return fail(name, `"${key}" cannot be given a ${control.kind} control; map it with Relation.nested`);
222
311
  const kind = control.draft;
223
- const type = Schema.toType(schema);
312
+ const type = Schema.toType(shape);
224
313
  const decode = Schema.decodeUnknownResult(type);
225
314
  const accepts = Schema.is(type);
226
- 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
+ };
227
322
  const samples = kind === "flag" ? [true, false] : kind === "list" ? [[], ["id"]] : [];
228
323
  if (samples.length > 0 && !samples.some(accepts)) fail(name, `"${key}" is edited as ${control.kind}, but its schema accepts no such value`);
229
324
  const { label, description } = wordsOf(key, schema, member);
@@ -247,18 +342,14 @@ const planOf = (name, key, schema, member, override, messages) => {
247
342
  message
248
343
  }) ?? message
249
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);
250
347
  const check = (draft) => {
251
- if (isBlank(control, draft)) {
252
- for (const nothing of [
253
- void 0,
254
- null,
255
- empty
256
- ]) if (accepts(nothing)) return Result.succeed(nothing);
257
- return Result.fail(say.required);
258
- }
259
- 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;
260
350
  if (value === void 0) return Result.fail(say.unparsed);
261
- 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;
262
353
  };
263
354
  const required = kind !== "flag" && Result.isFailure(check(empty));
264
355
  return {
@@ -271,8 +362,9 @@ const planOf = (name, key, schema, member, override, messages) => {
271
362
  member,
272
363
  label,
273
364
  description,
365
+ bundled,
274
366
  rules: FieldValidation.makeRules({
275
- isEmpty: (draft) => isBlank(control, draft),
367
+ isEmpty: blank,
276
368
  ...required ? { required: say.required } : {},
277
369
  rules: [[(draft) => Result.isSuccess(check(draft)), (draft) => Result.match(check(draft), {
278
370
  onSuccess: () => "",
@@ -294,8 +386,11 @@ const attempt = (name, run) => {
294
386
  return fail(name, error instanceof Error ? error.message : String(error));
295
387
  }
296
388
  };
297
- /** The draft that shows `value`: a number as its text, nothing as the empty draft. */
298
- 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
+ };
299
394
  const Core = {
300
395
  /**
301
396
  * A form for one operation's input. A key mapped with `Relation.nested` holds
@@ -310,6 +405,8 @@ const Core = {
310
405
  const rowsKeys = everyKey.filter((key) => members[key]._tag === "NestedInput");
311
406
  const overrides = options.inputs ?? {};
312
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`);
313
410
  const givenForms = options.nested ?? {};
314
411
  const nestedPlans = Object.fromEntries(rowsKeys.map((key) => [key, nestedPlanOf(name, key, input.schema.fields[key], members[key], givenForms[key], {
315
412
  messages: options.messages,
@@ -320,8 +417,9 @@ const Core = {
320
417
  flag: Schema.Boolean,
321
418
  list: Schema.Array(Schema.String)
322
419
  };
420
+ const schemaOf = (plan) => plan.bundled !== void 0 ? plan.bundled.bundle.Model : draftSchema[plan.kind];
323
421
  const Model = Schema.Struct({
324
- 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]))]))),
325
423
  rows: Schema.Struct(Object.fromEntries(rowsKeys.map((key) => [key, Schema.Array(Schema.Struct({
326
424
  id: Schema.String,
327
425
  model: nestedPlans[key].form.bundle.Model
@@ -339,6 +437,7 @@ const Core = {
339
437
  Schema.Boolean,
340
438
  Schema.Array(Schema.String)
341
439
  ]);
440
+ const ControlKeySchema = controlKeys.length === 0 ? Schema.Never : Schema.Literals(controlKeys);
342
441
  const Message = defineMessageUnion({
343
442
  Changed: {
344
443
  key: KeySchema,
@@ -346,6 +445,12 @@ const Core = {
346
445
  },
347
446
  /** Validates the key as it stands, so a required key left empty says so. */
348
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: {},
349
454
  Submitted: {},
350
455
  Reset: {},
351
456
  /** The answer of a check for the draft it was asked about; one for an older draft is dropped. */
@@ -382,6 +487,15 @@ const Core = {
382
487
  row: Schema.String,
383
488
  message: Schema.Unknown
384
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
+ },
385
499
  /** A new, empty row. A `one` that already has its row takes no other. */
386
500
  RowAdded: { key: Schema.String },
387
501
  /** Removes a row. A `one` that must be there stays. */
@@ -432,37 +546,80 @@ const Core = {
432
546
  const value = Result.getOrUndefined(plans[key].check(drafts(model)[key].value));
433
547
  return value === void 0 ? [] : [[key, value]];
434
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
+ };
435
556
  /** The value of each nested key, or `undefined` while some row has none. */
436
557
  const nestedValues = (model) => {
437
558
  const entries = [];
438
559
  for (const key of rowsKeys) {
439
- const plan = nestedPlans[key];
440
- const values = rowsOf(model)[key].map((row) => plan.form.engine.value(row.model));
441
- if (values.includes(void 0)) return void 0;
442
- 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]);
443
563
  }
444
564
  return Object.fromEntries(entries);
445
565
  };
446
- /** A nested form's Commands as this form's: their Messages arrive wrapped for the row. */
447
- const lift = (key, row, commands) => commands.map((command) => ({
448
- name: command.name,
449
- args: {
450
- ...command.args,
451
- at: key,
452
- row
453
- },
454
- effect: Effect.map(command.effect, (message) => Message.Nested({
566
+ /**
567
+ * A nested form's Commands as this form's: their Messages arrive wrapped for
568
+ * the row. `mapMessages` records the wrap on each Command, so a Story or
569
+ * Scene that resolves the row's check sees the `Nested` Message this update
570
+ * handles, not the inner form's bare answer.
571
+ */
572
+ const lift = (key, row, commands) => mapMessages(commands, (message) => Message.Nested({
573
+ key,
574
+ row,
575
+ message
576
+ }));
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({
455
586
  key,
456
- row,
457
587
  message
458
- }))
459
- }));
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
+ });
460
612
  /**
461
613
  * Validates the draft of one key. A key with a check that passes its schema is
462
614
  * not `Valid` yet: it is `Validating`, with the Command that asks.
463
615
  */
464
616
  const validateKey = (model, key, draft) => {
465
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
+ };
466
623
  const check = checks[key];
467
624
  if (check === void 0 || state._tag !== "Valid") return {
468
625
  model: withField(model, key, state),
@@ -574,16 +731,11 @@ const Core = {
574
731
  });
575
732
  };
576
733
  /**
577
- * A submit: every key not yet validated is, in every row too, so every failure
578
- * shows. With none, the value goes out; with checks still running, the submit
579
- * 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.
580
736
  */
581
- const submit = (model) => {
582
- let next = {
583
- ...model,
584
- errors: [],
585
- submitPending: false
586
- };
737
+ const validateEvery = (model, inRow) => {
738
+ let next = model;
587
739
  const commands = [];
588
740
  for (const key of keys) {
589
741
  const state = drafts(next)[key];
@@ -593,16 +745,34 @@ const Core = {
593
745
  commands.push(...validated.commands);
594
746
  }
595
747
  for (const key of rowsKeys) {
596
- const rows = rowsOf(next)[key].map((row) => {
597
- const submitted = nestedPlans[key].form.engine.submit(row.model);
598
- commands.push(...lift(key, row.id, submitted.commands));
599
- 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 : {
600
753
  id: row.id,
601
- model: submitted.model
754
+ model: answered.model
602
755
  };
603
756
  });
604
- next = withRows(next, key, rows);
757
+ if (rows.some((row, index) => row !== before[index])) next = withRows(next, key, rows);
605
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));
606
776
  if (isValidating(next)) return {
607
777
  model: {
608
778
  ...next,
@@ -654,7 +824,7 @@ const Core = {
654
824
  touched: Object.fromEntries(followers.flatMap((key) => key in given ? isEmpty(draftOf(plans[key], given[key])) ? [] : [[key, true]] : model.touched[key] === true ? [[key, true]] : [])),
655
825
  errors: [],
656
826
  submitPending: false,
657
- 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])
658
828
  };
659
829
  return { model: rowsKeys.reduce((next, key) => {
660
830
  if (!(key in given)) return next;
@@ -664,6 +834,142 @@ const Core = {
664
834
  return numbered(next, key, models.length === 0 && !optional ? [form.initial] : models);
665
835
  }, filled) };
666
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));
845
+ const bundle = Bundle.make(name, {
846
+ Model,
847
+ Message,
848
+ init: () => ({
849
+ model: initial,
850
+ commands: placements.flatMap(({ placed }) => placed.init(initial).commands ?? [])
851
+ }),
852
+ update: (model, message) => {
853
+ switch (message._tag) {
854
+ case "Changed": return kindOf(message.value) !== plans[message.key].kind ? { model } : changed(edited(model), message.key, message.value);
855
+ case "Blurred": {
856
+ const state = drafts(model)[message.key];
857
+ return state._tag === "NotValidated" ? validateKey(model, message.key, state.value) : { model };
858
+ }
859
+ case "ValidatedAll": return validateAll(model);
860
+ case "Refused": {
861
+ const state = drafts(model)[message.key];
862
+ return { model: {
863
+ ...withField(model, message.key, FieldValidation.Invalid({
864
+ value: state.value,
865
+ errors: [message.error]
866
+ })),
867
+ submitPending: false
868
+ } };
869
+ }
870
+ case "About": return { model: {
871
+ ...model,
872
+ subject: message.subject
873
+ } };
874
+ case "Checked": {
875
+ const state = drafts(model)[message.key];
876
+ if (state._tag !== "Validating" || !sameDraft(state.value, message.draft)) return { model };
877
+ return resume(withField(model, message.key, message.error === null ? FieldValidation.Valid({ value: state.value }) : FieldValidation.Invalid({
878
+ value: state.value,
879
+ errors: [message.error]
880
+ })));
881
+ }
882
+ case "Searched": return plans[message.key].control.searches ? { model: {
883
+ ...model,
884
+ searches: {
885
+ ...model.searches,
886
+ [message.key]: message.text
887
+ }
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
+ }
908
+ case "Nested": {
909
+ const plan = nestedPlans[message.key];
910
+ const row = rowsOf(model)[message.key]?.find((held) => held.id === message.row);
911
+ if (plan === void 0 || row === void 0) return { model };
912
+ if (!Schema.is(plan.form.bundle.Message)(message.message)) return { model };
913
+ const inner = message.message;
914
+ if (inner._tag === "Submitted") return submitted(model);
915
+ const answered = plan.form.bundle.update(row.model, inner, void 0);
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 ? {
918
+ id: row.id,
919
+ model: answered.model
920
+ } : held));
921
+ const edit = isEdit(inner) || plan.form.engine.authoredChanged(row.model, answered.model);
922
+ return resume(edit ? edited(next) : next, lifted);
923
+ }
924
+ case "RowAdded": {
925
+ const plan = nestedPlans[message.key];
926
+ const rows = rowsOf(model)[message.key];
927
+ if (plan === void 0 || rows === void 0) return { model };
928
+ if (plan.cardinality === "one" && rows.length > 0) return { model };
929
+ const added = numbered(edited(model), message.key, [plan.form.initial]);
930
+ return { model: withRows(added, message.key, [...rows, ...rowsOf(added)[message.key]]) };
931
+ }
932
+ case "RowRemoved": {
933
+ const plan = nestedPlans[message.key];
934
+ const rows = rowsOf(model)[message.key];
935
+ if (plan === void 0 || rows === void 0) return { model };
936
+ if (plan.cardinality === "one" && !plan.optional) return { model };
937
+ return { model: withRows(edited(model), message.key, rows.filter((held) => held.id !== message.row)) };
938
+ }
939
+ case "Reset": return { model: {
940
+ ...initial,
941
+ subject: model.subject
942
+ } };
943
+ case "Submitted": return submitted(model);
944
+ }
945
+ },
946
+ helpers: { fill },
947
+ ...Object.keys(controlSubscriptions).length === 0 ? {} : { subscriptions: () => controlSubscriptions },
948
+ ...Object.keys(controlResources).length === 0 ? {} : { resources: () => controlResources }
949
+ });
950
+ /**
951
+ * Whether a completed transition changed what the author wrote. Validation
952
+ * state, search text, the edited subject, and row bookkeeping are not
953
+ * authored content, so a blur, a refused edit, or a no-op is not a change.
954
+ * Nested rows recurse through their own forms, and a Bundle-backed control
955
+ * composes because its output is written back before this is asked.
956
+ */
957
+ const authoredChanged = (before, after) => {
958
+ const beforeDrafts = drafts(before);
959
+ const afterDrafts = drafts(after);
960
+ for (const key of keys) if (!sameValue(key, beforeDrafts[key].value, afterDrafts[key].value)) return true;
961
+ for (const key of rowsKeys) {
962
+ const beforeRows = rowsOf(before)[key];
963
+ const afterRows = rowsOf(after)[key];
964
+ if (beforeRows.length !== afterRows.length) return true;
965
+ for (const [index, row] of beforeRows.entries()) {
966
+ const other = afterRows[index];
967
+ if (row.id !== other.id) return true;
968
+ if (nestedPlans[key].form.engine.authoredChanged(row.model, other.model)) return true;
969
+ }
970
+ }
971
+ return false;
972
+ };
667
973
  return {
668
974
  /** The name, input and options the form was made from: what a pipe step makes the next form from. */
669
975
  name,
@@ -673,87 +979,12 @@ const Core = {
673
979
  pipe() {
674
980
  return Pipeable.pipeArguments(this, arguments);
675
981
  },
676
- bundle: Bundle.make(name, {
677
- Model,
678
- Message,
679
- init: () => ({ model: initial }),
680
- update: (model, message) => {
681
- switch (message._tag) {
682
- case "Changed": return kindOf(message.value) !== plans[message.key].kind ? { model } : changed(edited(model), message.key, message.value);
683
- case "Blurred": {
684
- const state = drafts(model)[message.key];
685
- return state._tag === "NotValidated" ? validateKey(model, message.key, state.value) : { model };
686
- }
687
- case "Refused": {
688
- const state = drafts(model)[message.key];
689
- return { model: {
690
- ...withField(model, message.key, FieldValidation.Invalid({
691
- value: state.value,
692
- errors: [message.error]
693
- })),
694
- submitPending: false
695
- } };
696
- }
697
- case "About": return { model: {
698
- ...model,
699
- subject: message.subject
700
- } };
701
- case "Checked": {
702
- const state = drafts(model)[message.key];
703
- if (state._tag !== "Validating" || !sameDraft(state.value, message.draft)) return { model };
704
- return resume(withField(model, message.key, message.error === null ? FieldValidation.Valid({ value: state.value }) : FieldValidation.Invalid({
705
- value: state.value,
706
- errors: [message.error]
707
- })));
708
- }
709
- case "Searched": return plans[message.key].control.searches ? { model: {
710
- ...model,
711
- searches: {
712
- ...model.searches,
713
- [message.key]: message.text
714
- }
715
- } } : { model };
716
- case "Nested": {
717
- const plan = nestedPlans[message.key];
718
- const row = rowsOf(model)[message.key]?.find((held) => held.id === message.row);
719
- if (plan === void 0 || row === void 0) return { model };
720
- if (!Schema.is(plan.form.bundle.Message)(message.message)) return { model };
721
- const inner = message.message;
722
- if (inner._tag === "Submitted") return submitted(model);
723
- const answered = plan.form.bundle.update(row.model, inner, void 0);
724
- const next = withRows(model, message.key, rowsOf(model)[message.key].map((held) => held.id === row.id ? {
725
- id: row.id,
726
- model: answered.model
727
- } : held));
728
- return resume(isEdit(inner) ? edited(next) : next, lift(message.key, row.id, answered.commands ?? []));
729
- }
730
- case "RowAdded": {
731
- const plan = nestedPlans[message.key];
732
- const rows = rowsOf(model)[message.key];
733
- if (plan === void 0 || rows === void 0) return { model };
734
- if (plan.cardinality === "one" && rows.length > 0) return { model };
735
- const added = numbered(edited(model), message.key, [plan.form.initial]);
736
- return { model: withRows(added, message.key, [...rows, ...rowsOf(added)[message.key]]) };
737
- }
738
- case "RowRemoved": {
739
- const plan = nestedPlans[message.key];
740
- const rows = rowsOf(model)[message.key];
741
- if (plan === void 0 || rows === void 0) return { model };
742
- if (plan.cardinality === "one" && !plan.optional) return { model };
743
- return { model: withRows(edited(model), message.key, rows.filter((held) => held.id !== message.row)) };
744
- }
745
- case "Reset": return { model: {
746
- ...initial,
747
- subject: model.subject
748
- } };
749
- case "Submitted": return submitted(model);
750
- }
751
- },
752
- helpers: { fill }
753
- }),
982
+ bundle,
754
983
  Message,
755
984
  /** The reading the form was made from, for `Entity.selectFor` and `Entity.valuesFor`. */
756
985
  input,
986
+ /** Whether a completed transition changed authored content. See the note above. */
987
+ authoredChanged,
757
988
  /** The `fill` helper as a plain function of the form's Model, for a package that wraps the form. */
758
989
  fill,
759
990
  /** The Model the form starts from and resets to: every key empty and not validated. */
@@ -775,7 +1006,25 @@ const Core = {
775
1006
  * `controls`. `model.fields.title` is the same value, typed to that key. A
776
1007
  * nested key has rows and no draft.
777
1008
  */
778
- 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
+ },
779
1028
  /** What was typed to find a choice for a relation key that searches; `''` until something is. */
780
1029
  search: (model, key) => model.searches[key] ?? "",
781
1030
  /** What the form is editing; `{}` while it creates. See `FormModel.subject`. */
@@ -801,6 +1050,7 @@ const Core = {
801
1050
  ...Object.fromEntries([
802
1051
  "Changed",
803
1052
  "Blurred",
1053
+ "ValidatedAll",
804
1054
  "Searched",
805
1055
  "Submitted",
806
1056
  "Reset",
@@ -825,6 +1075,12 @@ const Core = {
825
1075
  return next.value !== void 0 || next.model.submitPending;
826
1076
  },
827
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
+ /**
828
1084
  * The Model with nothing in flight, for one that was stored and is shown
829
1085
  * again: a check that was running when it was stored will never answer, so
830
1086
  * its key is not validated yet, and no submit is waiting. Rows too.
@@ -834,7 +1090,11 @@ const Core = {
834
1090
  submitPending: false,
835
1091
  fields: fieldsFrom((plan) => {
836
1092
  const field = drafts(model)[plan.key];
837
- 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;
838
1098
  }),
839
1099
  rows: Object.fromEntries(rowsKeys.map((key) => [key, rowsOf(model)[key].map((row) => ({
840
1100
  ...row,
@@ -848,12 +1108,10 @@ const Core = {
848
1108
  */
849
1109
  partial: (model) => ({
850
1110
  ...decoded(model),
851
- ...Object.fromEntries(rowsKeys.flatMap((key) => {
852
- const plan = nestedPlans[key];
853
- const values = rowsOf(model)[key].map((row) => plan.form.engine.value(row.model));
854
- if (values.includes(void 0)) return [];
855
- return [[key, plan.cardinality === "many" ? values : values.length === 0 ? plan.nothing : values[0]]];
856
- }))
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
+ })))
857
1115
  }),
858
1116
  /** The form as the form that nests it drives it. */
859
1117
  engine: {
@@ -864,7 +1122,10 @@ const Core = {
864
1122
  commands
865
1123
  };
866
1124
  },
1125
+ validateAll,
867
1126
  isValidating,
1127
+ /** Whether a transition changed authored content, so a nesting form recurses. */
1128
+ authoredChanged,
868
1129
  /** The decoded input when every key and row is valid as it stands; validates nothing. */
869
1130
  value: (model) => finish(model).value
870
1131
  }