foldkit-form 0.11.0 → 0.12.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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Arr","defineCommand"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-form` — a form as a Bundle over Foldkit's own field validation.\n *\n * A form is built from an operation's input (`Entity.input`): the struct says\n * what may be submitted, and the Entity says what each key means. The Model\n * holds one `fieldValidation` Field per key, carrying the draft the control\n * edits. `Submitted` leaves as an out Message with the decoded value; what\n * happens to it (a Remote mutation, a Sync operation, a plain `update`) is the\n * parent's.\n */\nimport {\n Array as Arr,\n Duration,\n Effect,\n Equal,\n Match,\n Option,\n Pipeable,\n Result,\n Schema,\n SchemaAST,\n} from 'effect'\nimport { Bundle, Link } from 'foldkit-bundle'\nimport {\n Entity,\n Words,\n type AnyEntity,\n type EntityInput,\n type InputMember,\n type InputMembers,\n type MemoryOperators,\n type NestedInput,\n type SchemaWords,\n} from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport { type Command, define as defineCommand, mapMessages } from 'foldkit/command'\nimport * as FieldValidation from 'foldkit/fieldValidation'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport {\n Input,\n isControlChange,\n type BundleControl,\n type BundleData,\n type Control,\n type ControlChange,\n type Draft,\n type DraftKind,\n type FormRow,\n type NestedForm,\n} from './input.js'\n\nexport {\n Input,\n type BundleControl,\n type BundleControlSpec,\n type BundleData,\n type Control,\n type ControlChange,\n type ControlKind,\n type Draft,\n type DraftKind,\n type Follows,\n type FormRow,\n type NestedData,\n type NestedForm,\n type RelationData,\n} from './input.js'\nimport { own } from './record.js'\n\n/** The draft a key holds, as far as the input's type says: a flag, a list of ids, or text. */\nexport type DraftOf<Value> = [Exclude<Value, null | undefined>] extends [boolean]\n ? boolean\n : [Exclude<Value, null | undefined>] extends [ReadonlyArray<unknown>]\n ? ReadonlyArray<string>\n : string\n\n/** The keys of an input that hold a nested input (`Relation.nested`): rows of a form, not a draft. */\nexport type NestedKey<Members> = {\n [K in keyof Members]: Members[K] extends NestedInput<any, any> ? K : never\n}[keyof Members]\n\n/** The Model of the form a nested key's rows hold. */\nexport type NestedModel<Member> =\n Member extends NestedInput<any, EntityInput<any, infer Fields, infer Members>>\n ? FormModel<Fields, Members>\n : never\n\n/** The controls a form may be given under `inputs`, by key. */\nexport type InputsFor<Fields extends Schema.Struct.Fields, Members> = {\n readonly [K in Exclude<keyof Fields, NestedKey<Members>>]?: Control | ControlChange\n}\n\n/** The keys given a control backed by a Bundle, each with the Bundle's Model: that key's draft. */\nexport type ControlsOf<Inputs> = {\n readonly [\n K in keyof Inputs as Inputs[K] extends BundleControl<any, any, any> ? K : never\n ]: Inputs[K] extends BundleControl<infer Model, any, any> ? Model : never\n}\n\n/**\n * Whether any control backed by a Bundle holds Resources: then the form's\n * Bundle has Resources, and a runtime running it must provide them.\n */\nexport type ControlResourcesOf<Inputs> = true extends {\n readonly [K in keyof Inputs]: Inputs[K] extends BundleControl<any, any, any, infer Resources>\n ? [keyof Resources] extends [never]\n ? false\n : true\n : false\n}[keyof Inputs]\n ? Readonly<Record<string, never>>\n : {}\n\n/** The Message of the Bundle behind a key's control. */\nexport type ControlMessageOf<C> = C extends BundleControl<any, infer Message, any> ? Message : never\n\nexport interface FormModel<Fields extends Schema.Struct.Fields, Members = {}, Controls = {}> {\n /**\n * One `fieldValidation` Field per key that holds a draft. A key given a\n * control backed by a Bundle holds that Bundle's Model as its draft.\n */\n readonly fields: {\n readonly [K in keyof Fields as K extends NestedKey<Members> ? never : K]: FieldValidation.Field<\n K extends keyof Controls ? Controls[K] : DraftOf<Schema.Schema.Type<Fields[K]>>\n >\n }\n /** The rows of each nested key, each a Model of the nested form. */\n readonly rows: {\n readonly [K in keyof Fields as K extends NestedKey<Members> ? K : never]: ReadonlyArray<\n FormRow<NestedModel<Members[K & keyof Members]>>\n >\n }\n /** Counts the rows ever added, so a row's id is never reused. */\n readonly nextRow: number\n /** What was typed to find a choice, by key, for the relation pickers that search. */\n readonly searches: Readonly<Record<string, string>>\n /**\n * The keys that follow another and that the author has written themselves, so\n * they follow no longer. A key that follows nothing is never here.\n */\n readonly touched: Readonly<Record<string, boolean>>\n /**\n * A submit has been asked since the form started, was filled or was reset.\n * A view draws its list of fields to fix only then. `ValidatedAll` is not\n * one: the page that sends it owns the submit.\n */\n readonly attempted: boolean\n /** Failures of the input as a whole, from the last submit: a rule that spans keys. */\n readonly errors: ReadonlyArray<string>\n /**\n * Failures a judgement of the whole put on a key, apart from the key's own\n * schema and check: an Entity invariant's at a submit, or `Message.Refused`.\n * `field` shows them on their key. Any edit clears them, since an edit of\n * one key can mend a rule that names another; until then a submit stops,\n * since the same value would be judged the same.\n */\n readonly marks: Readonly<Record<string, ReadonlyArray<string>>>\n /** A submit is waiting for checks still running; it goes out when the last one passes. */\n readonly submitPending: boolean\n /**\n * What the form is editing, which its values do not say: a post's own row id,\n * so a check that asks whether an address is taken can tell the post's own\n * address from someone else's. Empty until `Message.About` says otherwise,\n * which is what a form that creates something means.\n */\n readonly subject: Readonly<Record<string, string>>\n}\n\n/**\n * A rule only something outside the form can answer: is this slug taken? It is\n * given the decoded value of the key and whatever else in the form currently\n * decodes, and answers with what is wrong, or nothing. It runs after the schema\n * of the key passes, never instead of it.\n */\nexport type FormCheck<A, Values, R = never> = (\n value: A,\n context: {\n readonly values: Values\n /** What the form is editing: `{}` while it creates. See `FormModel.subject`. */\n readonly subject: Readonly<Record<string, string>>\n },\n) => Effect.Effect<string | undefined, never, R>\n\n/** The form's out Message: every key is valid and the input decoded. */\nexport interface Submitted<Value> {\n readonly _tag: 'Submitted'\n readonly value: Value\n}\n\n/** One key of the form, with everything a view needs to draw it except the pixels. */\nexport interface FormControl<Key extends string = string> {\n readonly key: Key\n readonly control: Control\n /** The schema's `title` annotation, else `Form.label` metadata, else the key. */\n readonly label: string\n readonly description: string | undefined\n /** Whether an empty draft fails. */\n readonly required: boolean\n readonly member: InputMember\n}\n\n/** The key a message is about, for wording that names it. */\nexport interface MessageField<Key extends string = string> {\n readonly key: Key\n readonly label: string\n readonly control: Control\n}\n\n/**\n * The form's words. A rule's own wording belongs on the rule\n * (`Schema.isMinLength(3, { message: '…' })`) and arrives here as `message`;\n * these cover what the form says itself, and let an application translate or\n * rewrite what Schema says by default.\n */\nexport interface FormMessages<Key extends string = string> {\n /** An empty draft the schema does not admit. `{label}`, `{key}`. Default `Required`. */\n readonly required?: string | ((field: MessageField<Key>) => string)\n /** Text its control cannot read: a `Number` that is not one. `{label}`, `{key}`. Default: the kind's own words (`Enter a number`). */\n readonly unparsed?: string | ((field: MessageField<Key>) => string)\n /** A draft the key's schema rejects. `{message}` is the check's own, or Schema's; `{label}`, `{key}`. Default: `{message}`. */\n readonly invalid?: string | ((field: MessageField<Key>, message: string) => string)\n /** A failure of the input as a whole: a rule that spans keys. `{message}`. Default: `{message}`. */\n readonly form?: string | ((message: string) => string)\n}\n\n/**\n * Words with their blanks filled: `fillWords('{label} is required', { label: 'Title' })`.\n * A blank with no value is left as it is written. Words as text, not functions,\n * can be kept in one place, translated, and passed anywhere, a view's inputs\n * included, where Foldkit admits no nested function.\n */\nexport const fillWords = (\n template: string,\n values: Readonly<Record<string, string | number>>,\n): string =>\n template.replace(/\\{(\\w+)\\}/g, (blank, name: string) =>\n Object.hasOwn(values, name) ? String(values[name]) : blank,\n )\n\n/**\n * A form made with `Form.make` from the input a key nests. It is an ordinary\n * form: the one that edits an author alone is the one a post's form nests.\n */\nexport interface FormFor<\n Fields extends Schema.Struct.Fields,\n Members,\n R = never,\n Controls = any,\n> extends NestedForm {\n readonly input: EntityInput<any, Fields, Members>\n readonly bundle: {\n readonly Model: Schema.Codec<FormModel<Fields, Members, Controls>, unknown>\n readonly Message: Schema.Codec<any, unknown>\n readonly update: (\n model: any,\n message: any,\n args: void,\n ) => {\n readonly model: any\n readonly commands?: ReadonlyArray<Command<any, never, R>> | undefined\n }\n }\n readonly initial: FormModel<Fields, Members, Controls>\n readonly fill: (model: any, values: any) => { readonly model: any }\n readonly engine: {\n readonly submit: (model: any) => {\n readonly model: any\n readonly commands: ReadonlyArray<Command<any, never, R>>\n }\n readonly validateAll: (model: any) => {\n readonly model: any\n readonly commands: ReadonlyArray<Command<any, never, R>>\n }\n readonly isValidating: (model: any) => boolean\n readonly value: (model: any) => unknown\n /** Whether a transition changed authored content, so a nesting form recurses. */\n readonly authoredChanged: (before: any, after: any) => boolean\n }\n readonly settled: (model: any) => any\n /**\n * The decoded input as `Some` only when every key and row is valid as the\n * form stands; `None` otherwise. All or nothing, unlike `partial`, so a\n * parent submitting several forms reads one complete value per form.\n */\n readonly value: (model: any) => Option.Option<Schema.Struct.Type<Fields>>\n /** Whether a completed transition changed authored content. */\n readonly authoredChanged: (before: any, after: any) => boolean\n}\n\n/** The forms a form may be given for its nested keys: each one made from that key's nested input. */\nexport type NestedForms<Fields extends Schema.Struct.Fields, Members, R> = {\n readonly [K in NestedKey<Members> & keyof Fields]?: Members[K] extends NestedInput<\n any,\n EntityInput<any, infer NestedFields, infer NestedMembers>\n >\n ? NestedFields extends Schema.Struct.Fields\n ? FormFor<NestedFields, NestedMembers, R>\n : never\n : never\n}\n\n/** The constructors of a form's Messages that a row's handle offers, wrapped for the row. */\ntype RowConstructor =\n | 'Changed'\n | 'Blurred'\n | 'ValidatedAll'\n | 'Searched'\n | 'Toggled'\n | 'Submitted'\n | 'Reset'\n | 'RowAdded'\n | 'RowRemoved'\n\n/**\n * One row of a nested key, addressed: the nested form's own Message constructors,\n * each giving the Message of the form the row is in. `send` wraps a Message\n * already made, which is how a row inside a row is reached.\n */\nexport type RowHandle<Child, Message> = {\n readonly [T in RowConstructor]: Child extends {\n readonly Message: { readonly [C in T]: (...args: infer Args) => unknown }\n }\n ? (...args: Args) => Message\n : never\n} & { readonly send: (message: unknown) => Message }\n\n/** What `Form.make` takes beside the input. */\nexport interface FormOptions<\n Fields extends Schema.Struct.Fields,\n Members,\n R,\n Nest extends NestedForms<Fields, Members, R> = {},\n Inputs extends InputsFor<Fields, Members> = InputsFor<Fields, Members>,\n> {\n /**\n * The control for a key the resolver cannot decide, or should not: an unmapped\n * key with an unusual schema, text that wants a multiline control here only,\n * or a control backed by a Bundle (`Input.bundle`).\n */\n readonly inputs?: Inputs\n /** The form's own words, and a rewrite of Schema's: for wording and for translation. */\n readonly messages?: FormMessages<keyof Fields & string>\n /** Rules answered outside the form, by key. The key reads `Validating` while one runs. */\n readonly checks?: {\n readonly [K in Exclude<keyof Fields, NestedKey<Members>>]?: FormCheck<\n Schema.Schema.Type<Fields[K]>,\n Partial<Schema.Struct.Type<Fields>>,\n R\n >\n }\n /** How long a key rests before its check runs, so typing does not ask per keystroke. Default 300ms. */\n readonly debounce?: Duration.Input\n /**\n * The form of a nested key, made with `Form.make` from the input the key nests\n * (`Relation.nested(relation, input)`): the same form that edits the target\n * alone. A nested key given none gets a plain form of its input, with this\n * form's `messages` and `debounce`.\n */\n readonly nested?: Nest\n /**\n * How the Entity's invariants' primitive operators are run while the form\n * judges them (`Operators`): the kernel's when not given. An invariant calling\n * one this table lacks is left to the server, as one over a field the form\n * does not set is. A nested form given none uses this.\n */\n readonly operators?: MemoryOperators | undefined\n}\n\ninterface Label {\n readonly label: string\n readonly description?: string | undefined\n}\n\nconst labelKey = Metadata.key<Label>('foldkit-form/label', {\n merge: labels => labels.slice(-1),\n summarize: label => label.label,\n})\n\ntype Checked = Result.Result<unknown, string>\n\ntype AnyCommand = Command<any, never, any>\n\n/** A form as the form that nests it uses it: untyped, since a nested input is only known at runtime. */\ninterface AnyForm extends NestedForm {\n readonly bundle: {\n readonly Model: Schema.Codec<any, unknown>\n readonly Message: Schema.Codec<any, unknown>\n readonly update: (\n model: any,\n message: any,\n args: void,\n ) => { readonly model: any; readonly commands?: ReadonlyArray<AnyCommand> | undefined }\n }\n readonly initial: unknown\n readonly fill: (model: any, values: any) => { readonly model: any }\n readonly engine: {\n readonly submit: (model: any) => {\n readonly model: any\n readonly commands: ReadonlyArray<AnyCommand>\n }\n readonly validateAll: (model: any) => {\n readonly model: any\n readonly commands: ReadonlyArray<AnyCommand>\n }\n readonly isValidating: (model: any) => boolean\n readonly value: (model: any) => unknown\n readonly authoredChanged: (before: any, after: any) => boolean\n }\n readonly settled: (model: any) => any\n /** Whether a completed transition changed authored content. */\n readonly authoredChanged: (before: any, after: any) => boolean\n}\n\n/**\n * A draft after a press: a flag flipped, or a list with `choice` let go if it is\n * held and added if not. None when the press does not fit the draft's kind.\n */\nconst toggled = (kind: string, draft: Draft, choice: string | undefined): Option.Option<Draft> => {\n if (choice === undefined) return kind === 'flag' ? Option.some(draft !== true) : Option.none()\n if (kind !== 'list' || !Array.isArray(draft)) return Option.none()\n return Option.some(\n draft.includes(choice) ? draft.filter(held => held !== choice) : [...draft, choice],\n )\n}\n\n/** Assigned once `Form` exists: a form builds the forms of its nested keys with itself. */\nlet makeNested: (name: string, input: unknown, options: unknown) => AnyForm\n\ninterface NestedPlan extends FormControl {\n readonly form: AnyForm\n readonly cardinality: 'one' | 'many'\n readonly optional: boolean\n /** What no row submits, for a `one` whose schema admits nothing; `undefined` leaves the key out. */\n readonly nothing: null | undefined\n}\n\n/**\n * The checks a form may be given by key, with what they need left open. Effect's\n * `R` is not an inference site a mapped type can win: asked to infer it, TypeScript\n * answers `never`, and a check that needs anything is refused by the shape meant to\n * accept it. So the shape admits any requirement and `RequirementOf` reads back what\n * was actually passed.\n */\nexport type ChecksFor<F extends Remakeable> = {\n readonly [K in Exclude<keyof F['types']['Fields'], NestedKey<F['types']['Members']>>]?: FormCheck<\n Schema.Schema.Type<F['types']['Fields'][K]>,\n Partial<Schema.Struct.Type<F['types']['Fields']>>,\n any\n >\n}\n\n/** What a set of checks needs between them, read off the functions that were given. */\nexport type RequirementOf<C> = {\n [K in keyof C]: C[K] extends (...args: never) => Effect.Effect<any, any, infer R> ? R : never\n}[keyof C]\n\n/**\n * Which of a form's Messages are edits, which answer the last submit; an answered\n * check or a blur does not. A `Nested` one is an edit when the row's Message is.\n */\nconst edits = {\n Changed: true,\n Blurred: false,\n Validated: false,\n ValidatedAll: false,\n Submitted: false,\n Reset: true,\n Checked: false,\n Refused: false,\n About: false,\n Searched: false,\n Toggled: true,\n Nested: false,\n Control: false,\n RowAdded: true,\n RowRemoved: true,\n FollowedIssue: false,\n AskedForMore: false,\n} as const\n\n/** A form's tags. Every form has these, so a nested form's Message, known only at runtime, is read by them. */\ntype FormTag = keyof typeof edits\n\ninterface AnyFormMessage {\n readonly _tag: FormTag\n readonly message?: unknown\n}\n\n/** An edit, however deep. */\nconst isEdit = (message: AnyFormMessage): boolean =>\n message._tag === 'Nested' ? isEdit(message.message as AnyFormMessage) : edits[message._tag]\n\ninterface Plan extends FormControl {\n readonly kind: HeldDraft\n readonly empty: Draft\n readonly check: (draft: Draft) => Checked\n readonly rules: FieldValidation.Rules<Draft>\n /** For a control backed by a Bundle: the Bundle, and how the key's value lives in its Model. */\n readonly bundled: BundleData | undefined\n}\n\n/** A control's Bundle placed where its key's draft is, as the form drives it. */\ninterface PlacedControl<Model> {\n readonly init: (model: Model) => { readonly commands?: ReadonlyArray<AnyCommand> | undefined }\n readonly update: (\n model: Model,\n message: { readonly _tag: string },\n ) => Option.Option<{\n readonly model: Model\n readonly commands?: ReadonlyArray<AnyCommand> | undefined\n }>\n readonly subscriptions: Readonly<Record<string, never>>\n readonly resources: Readonly<Record<string, never>>\n}\n\n/** The drafts a key holds. `rows` is a nested key's, which holds rows instead. */\ntype HeldDraft = Exclude<DraftKind, 'rows'>\n\nconst kindOf = (draft: unknown): HeldDraft | undefined =>\n typeof draft === 'string'\n ? 'text'\n : typeof draft === 'boolean'\n ? 'flag'\n : Array.isArray(draft) && draft.every(item => typeof item === 'string')\n ? 'list'\n : undefined\n\nconst sameDraft = (left: Draft, right: Draft): boolean =>\n Array.isArray(left) && Array.isArray(right)\n ? left.length === right.length && left.every((item, index) => item === right[index])\n : left === right\n\nconst isEmpty = (draft: Draft): boolean =>\n draft === '' || (Array.isArray(draft) && draft.length === 0)\n\n/** Text that is read as something else is blank when it is only spaces: `Number(' ')` is 0, which nobody typed. */\nconst isBlank = (control: Control, draft: Draft): boolean =>\n isEmpty(draft) ||\n (control.parse !== undefined && typeof draft === 'string' && draft.trim() === '')\n\n/**\n * What an `Option`-typed key holds (`Schema.Option`, `Schema.OptionFromNullOr`),\n * found as Effect's own tools find it: by the declaration's representation id.\n */\nconst optionOf = (schema: Schema.Top): Option.Option<Schema.Top> => {\n const { ast } = schema\n if (!SchemaAST.isDeclaration(ast) || ast.typeParameters.length !== 1) return Option.none()\n const representation: unknown = ast.annotations?.['representation']\n return typeof representation === 'object' &&\n representation !== null &&\n 'id' in representation &&\n representation.id === 'effect/schema/Option'\n ? Option.some(Schema.make(ast.typeParameters[0]!))\n : Option.none()\n}\n\n/** The schema's `title`, else `Form.label` metadata on the member, else the key. */\nconst wordsOf = (\n key: string,\n schema: Schema.Top,\n member: InputMember,\n): { readonly label: string; readonly description: string | undefined } => {\n const own =\n member._tag === 'Unmapped' ? undefined : member._tag === 'Field' ? member : member.relation\n const [labelled] = own === undefined ? [] : labelKey.get(own.metadata)\n const words = [schema, ...(member._tag === 'Field' ? [member.schema as Schema.Top] : [])].map(\n Words.of,\n )\n const first = (pick: (entry: SchemaWords) => Option.Option<string>) =>\n Option.firstSomeOf(words.map(pick))\n return {\n label: Option.getOrElse(\n first(entry => entry.title),\n () => labelled?.label ?? key,\n ),\n description: Option.getOrElse(\n first(entry => entry.description),\n () => labelled?.description,\n ),\n }\n}\n\nconst nestedPlanOf = (\n name: string,\n key: string,\n schema: Schema.Top,\n member: Extract<InputMember, { readonly _tag: 'NestedInput' }>,\n given: AnyForm | undefined,\n inherited: unknown,\n): NestedPlan => {\n const accepts = Schema.is(Schema.toType(schema) as Schema.Codec<unknown>)\n const cardinality = member.relation.cardinality\n const absent = SchemaAST.isOptional(schema.ast) || accepts(undefined)\n const optional = cardinality === 'many' || absent || accepts(null)\n if (given !== undefined && (given as { readonly input?: unknown }).input !== member.input)\n fail(\n name,\n `\"${key}\" is given a form of another input than the one it nests; make it from the input passed to Relation.nested`,\n )\n const form = given ?? makeNested(`${name}.${key}`, member.input, inherited)\n // A row is plain data in this form's Model, so nothing would run a row's own\n // listeners or hold its resources. Say so rather than drop them.\n const lifecycle = form.bundle as {\n readonly subscriptions?: unknown\n readonly resources?: unknown\n }\n if (lifecycle.subscriptions !== undefined || lifecycle.resources !== undefined)\n fail(\n name,\n `\"${key}\" nests a form with a control whose Bundle has Subscriptions or Resources, which rows cannot run yet`,\n )\n return {\n key,\n ...wordsOf(key, schema, member),\n control: Input.Nested.of({ cardinality, optional, form }),\n required: !optional,\n member,\n form,\n cardinality,\n optional,\n nothing: absent ? undefined : null,\n }\n}\n\n/**\n * A form over a variant Entity's input that sets `_tag`: the key that picks\n * the case, and for each key of a field only some cases have, those cases.\n * None for any other form. Such a key must be an optional key of the input, so\n * a row of another case leaves it out.\n */\nconst casesOf = (\n name: string,\n input: EntityInput<AnyEntity, any, any>,\n keys: ReadonlyArray<string>,\n): Option.Option<{\n readonly tagKey: string\n readonly only: ReadonlyMap<string, ReadonlySet<string>>\n}> => {\n const members = input.members as Readonly<Record<string, InputMember>>\n const fields = input.schema.fields as Readonly<Record<string, Schema.Top>>\n const tagKey = keys.find(key => {\n const member = members[key]!\n return member._tag === 'Field' && member.key === '_tag'\n })\n return Option.flatMap(Entity.variantsOf(input.entity), variants => {\n if (tagKey === undefined) return Option.none()\n const only = new Map<string, ReadonlySet<string>>()\n for (const key of keys) {\n const member = members[key]!\n if (member._tag !== 'Field' || member.key === '_tag') continue\n const holders = variants.tags.filter(tag => Object.hasOwn(variants.cases[tag]!, member.key))\n if (holders.length === variants.tags.length) continue\n if (!SchemaAST.isOptional(fields[key]!.ast))\n fail(\n name,\n `\"${key}\" is a field of some cases of ${input.entity.name}; declare it Schema.optionalKey in the input, so a row of another case leaves it out`,\n )\n only.set(key, new Set(holders))\n }\n return Option.some({ tagKey, only })\n })\n}\n\nconst planOf = (\n name: string,\n key: string,\n schema: Schema.Top,\n member: InputMember,\n override: Control | ControlChange | undefined,\n messages: FormMessages,\n): Plan => {\n // A key typed `Option` is edited as what it holds; nothing entered is `Option.none()`.\n const held = optionOf(schema)\n const shape = Option.getOrElse(held, () => schema)\n const resolved = Input.resolve(member, shape)\n const chosen =\n override === undefined\n ? resolved\n : isControlChange(override)\n ? attempt(name, () => override.change(resolved, key))\n : override\n const control = chosen ?? fail(name, `no control for \"${key}\"; name one under \"inputs\"`)\n if (control.draft === 'rows')\n return fail(\n name,\n `\"${key}\" cannot be given a ${control.kind} control; map it with Relation.nested`,\n )\n const kind = control.draft\n const type = Schema.toType(shape) as Schema.Codec<unknown>\n const decode = Schema.decodeUnknownResult(type)\n const accepts = Schema.is(type)\n const bundled = Input.isBundle(control) ? control.data : undefined\n // A control backed by a Bundle holds the Bundle's Model as its draft. Inside\n // the form every draft is carried as a `Draft`; only this plan's own\n // functions read it as the Bundle's Model.\n const empty: Draft =\n bundled !== undefined\n ? (bundled.bundle.init(bundled.args).model as Draft)\n : kind === 'flag'\n ? false\n : kind === 'list'\n ? []\n : ''\n const blank = (draft: Draft): boolean => {\n if (bundled === undefined) return isBlank(control, draft)\n const value = bundled.value(draft)\n return value === undefined || value === null\n }\n\n // A control whose draft can never become the key's value is a wiring mistake.\n // A choice of literals is tried with the first one, two, … of its own options,\n // since an array that must hold some refuses `[]` and an id alike.\n const samples: ReadonlyArray<unknown> =\n kind === 'flag'\n ? [true, false]\n : kind === 'list'\n ? [\n [],\n ['id'],\n ...(Input.Choices.is(control)\n ? control.data.options.map((_, index) => control.data.options.slice(0, index + 1))\n : []),\n ]\n : []\n if (samples.length > 0 && !samples.some(accepts))\n fail(name, `\"${key}\" is edited as ${control.kind}, but its schema accepts no such value`)\n\n const { label, description } = wordsOf(key, schema, member)\n const field: MessageField = { key, label, control }\n const say = {\n required: worded(messages.required, [field], { label, key }) ?? 'Required',\n unparsed: worded(messages.unparsed, [field], { label, key }) ?? control.unparsed ?? 'Not valid',\n invalid: (message: string) =>\n worded(messages.invalid, [field, message], { label, key, message }) ?? message,\n }\n\n // What \"nothing entered\" submits is whatever the input admits for it: leaving\n // an optional key out (`undefined`, which `decoded` omits), `Option.none()`,\n // `null`, or the empty draft itself.\n const [admitted] = (bundled === undefined ? [null, empty] : [null]).filter(value =>\n accepts(value),\n )\n const nothingEntered: Checked =\n SchemaAST.isOptional(schema.ast) || accepts(undefined)\n ? Result.succeed(undefined)\n : Option.isSome(held)\n ? Result.succeed(Option.none())\n : admitted !== undefined\n ? Result.succeed(admitted)\n : Result.fail(say.required)\n\n const check = (draft: Draft): Checked => {\n if (blank(draft)) return nothingEntered\n // A kind may read its text as something else before the schema sees it, and\n // a control backed by a Bundle reads its value from its Model.\n const value =\n bundled !== undefined\n ? bundled.value(draft)\n : control.parse !== undefined && typeof draft === 'string'\n ? control.parse(draft, control.data)\n : control.parseList !== undefined && Array.isArray(draft)\n ? control.parseList(draft, control.data)\n : draft\n if (value === undefined) return Result.fail(say.unparsed)\n const decoded = Result.mapError(decode(value), error => say.invalid(error.message))\n return Option.isSome(held) ? Result.map(decoded, Option.some) : decoded\n }\n\n const required = kind !== 'flag' && Result.isFailure(check(empty))\n return {\n key,\n control,\n kind,\n empty,\n check,\n required,\n member,\n label,\n description,\n bundled,\n rules: FieldValidation.makeRules<Draft>({\n isEmpty: blank,\n ...(required ? { required: say.required } : {}),\n rules: [\n [\n draft => Result.isSuccess(check(draft)),\n draft => Result.match(check(draft), { onSuccess: () => '', onFailure: error => error }),\n ],\n ],\n }),\n }\n}\n\n/** Words given as text have their blanks filled; given as a function, it is asked. */\nconst worded = <Args extends ReadonlyArray<unknown>>(\n words: string | ((...args: Args) => string) | undefined,\n args: Args,\n values: Readonly<Record<string, string | number>>,\n): string | undefined =>\n words === undefined\n ? undefined\n : typeof words === 'string'\n ? fillWords(words, values)\n : words(...args)\n\nconst fail = (name: string, message: string): never => {\n throw new Error(`Form \"${name}\": ${message}`)\n}\n\n/** A failure inside a control change, said as the form's. */\nconst attempt = <A>(name: string, run: () => A): A => {\n try {\n return run()\n } catch (error) {\n return fail(name, error instanceof Error ? error.message : String(error))\n }\n}\n\n/**\n * The draft that shows `value`: the text the control's `format` makes of it, or\n * `String(value)` when it formats nothing; nothing (`Option.none()` too) is the\n * empty draft.\n */\nconst draftOf = (plan: Plan, given: unknown): Draft => {\n const value = Option.isOption(given) ? Option.getOrUndefined(given) : given\n if (value === null || value === undefined) return plan.empty\n // A list draft is text, as an edit sends it: a filled `[1]` reads back as `['1']`.\n if (plan.kind === 'list' && Array.isArray(value)) return value.map(item => String(item))\n if (plan.kind !== 'text') return value as Draft\n const format = plan.control.format\n return format === undefined ? String(value) : format(value, plan.control.data)\n}\n\nconst Core = {\n /**\n * The input of a form that writes no Entity of its own (a sign-up, a search,\n * a login): `Entity.input` over an Entity defined from the same schema, so\n * every key maps itself. `Form.make('Waitlist', Form.input(JoinWaitlist))`.\n */\n input: <Fields extends Schema.Struct.Fields>(\n schema: Schema.Struct<Fields>,\n ): EntityInput<\n Entity<'FormInput', Fields>,\n Fields,\n InputMembers<Entity<'FormInput', Fields>, Fields, {}>\n > => {\n const entity = Entity.define('FormInput', schema)\n // Every key names a field of the Entity, so there is no mapping; the\n // generic `Fields` keeps TypeScript from seeing that the mapping is optional.\n return Entity.input<typeof entity, Fields, {}>(entity, schema, undefined as never)\n },\n\n /**\n * A form for one operation's input. A key mapped with `Relation.nested` holds\n * rows of a form of its own, built here from the nested input; every other key\n * holds a draft. `options` names what the input cannot say: a control, the\n * words, the checks.\n */\n make: <\n const Name extends string,\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n Members extends { readonly [K in keyof Fields]: InputMember },\n R = never,\n const Nest extends NestedForms<Fields, Members, R> = {},\n const Inputs extends InputsFor<Fields, Members> = {},\n >(\n name: Name,\n input: EntityInput<E, Fields, Members>,\n options: FormOptions<Fields, Members, R, Nest, Inputs> = {},\n ) => {\n type AnyKey = keyof Fields & string\n type Key = Exclude<AnyKey, NestedKey<Members>>\n type RowsKey = Extract<AnyKey, NestedKey<Members>>\n type ControlKey = keyof ControlsOf<Inputs> & Key\n type DraftKey = Exclude<Key, ControlKey>\n type Value = Schema.Struct.Type<Fields>\n type Model = FormModel<Fields, Members, ControlsOf<Inputs>>\n\n const members: Readonly<Record<string, InputMember>> = input.members\n const everyKey = Object.keys(input.schema.fields) as ReadonlyArray<AnyKey>\n const keys = everyKey.filter(\n key => members[key]!._tag !== 'NestedInput',\n ) as unknown as ReadonlyArray<Key>\n const rowsKeys = everyKey.filter(\n key => members[key]!._tag === 'NestedInput',\n ) as unknown as ReadonlyArray<RowsKey>\n\n const overrides: Readonly<Record<string, Control | ControlChange | undefined>> =\n options.inputs ?? {}\n const cases = casesOf(name, input, keys)\n const caseOnly = (key: string): ReadonlySet<string> | undefined =>\n Option.match(cases, { onNone: () => undefined, onSome: ({ only }) => only.get(key) })\n const plans = Object.fromEntries(\n keys.map(key => [\n key,\n planOf(\n name,\n key,\n // A key of some cases is asked as the case holds it: required where its schema is.\n (caseOnly(key) === undefined\n ? input.schema.fields[key]\n : (input.schema.fields[key] as unknown as { readonly schema: Schema.Top })\n .schema) as Schema.Top,\n members[key]!,\n own(overrides, key),\n (options.messages ?? {}) as FormMessages,\n ),\n ]),\n ) as Readonly<Record<Key, Plan>>\n\n // The keys whose control is backed by a Bundle: each holds that Bundle's Model.\n const controlKeys = keys.filter(key => plans[key].bundled !== undefined)\n for (const key of controlKeys)\n if (options.checks !== undefined && Object.hasOwn(options.checks, key))\n fail(\n name,\n `\"${key}\" is edited by a control backed by a Bundle, which takes no check; say what is valid in its schema`,\n )\n\n const givenForms: Readonly<Record<string, AnyForm | undefined>> = (options.nested ??\n {}) as never\n const nestedPlans = Object.fromEntries(\n rowsKeys.map(key => [\n key,\n nestedPlanOf(\n name,\n key,\n input.schema.fields[key] as Schema.Top,\n members[key] as Extract<InputMember, { readonly _tag: 'NestedInput' }>,\n own(givenForms, key),\n // A nested form made here takes this form's words and pace.\n { messages: options.messages, debounce: options.debounce, operators: options.operators },\n ),\n ]),\n ) as Readonly<Record<RowsKey, NestedPlan>>\n\n const draftSchema: Record<Exclude<HeldDraft, 'model'>, Schema.Codec<Draft, any>> = {\n text: Schema.String,\n flag: Schema.Boolean,\n list: Schema.Array(Schema.String),\n }\n const schemaOf = (plan: Plan): Schema.Codec<Draft, any> =>\n plan.bundled !== undefined\n ? (plan.bundled.bundle.Model as Schema.Codec<Draft, any>)\n : draftSchema[plan.kind as Exclude<HeldDraft, 'model'>]\n const Model = Schema.Struct({\n fields: Schema.Struct(\n Object.fromEntries(keys.map(key => [key, FieldValidation.Field(schemaOf(plans[key]))])),\n ),\n rows: Schema.Struct(\n Object.fromEntries(\n rowsKeys.map(key => [\n key,\n Schema.Array(\n Schema.Struct({ id: Schema.String, model: nestedPlans[key].form.bundle.Model }),\n ),\n ]),\n ),\n ),\n nextRow: Schema.Number,\n searches: Schema.Record(Schema.String, Schema.String),\n touched: Schema.Record(Schema.String, Schema.Boolean),\n // Defaulted, so a Model stored before it existed still decodes.\n attempted: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))),\n errors: Schema.Array(Schema.String),\n marks: Schema.Record(Schema.String, Schema.Array(Schema.String)).pipe(\n Schema.withDecodingDefaultKey(Effect.succeed({})),\n ),\n submitPending: Schema.Boolean,\n subject: Schema.Record(Schema.String, Schema.String),\n }) as unknown as Schema.Codec<Model, unknown>\n\n // A form of nested keys only has no key to change, and `Literals` needs one.\n const KeySchema = (\n keys.length === 0\n ? Schema.Never\n : Schema.Literals(keys as unknown as readonly [Key, ...Key[]])\n ) as Schema.Literals<readonly [Key, ...Key[]]>\n const DraftSchema = Schema.Union([Schema.String, Schema.Boolean, Schema.Array(Schema.String)])\n const ControlKeySchema = (\n controlKeys.length === 0\n ? Schema.Never\n : Schema.Literals(controlKeys as unknown as readonly [ControlKey, ...ControlKey[]])\n ) as Schema.Literals<readonly [ControlKey, ...ControlKey[]]>\n const Message = defineMessageUnion({\n Changed: { key: KeySchema, value: DraftSchema },\n /**\n * The person left the key. An edit has already validated it, and a key\n * never edited is not judged before a submit, so tabbing through a field\n * says nothing about it: the form changes nothing.\n */\n Blurred: { key: KeySchema },\n /**\n * Validates the key as it stands, edited or not: for a program showing a\n * stored value's failure after a `fill`, which validates nothing.\n */\n Validated: { key: KeySchema },\n /**\n * Validates every key not validated yet, in every row too, as a submit\n * would, and submits nothing: for a page that submits several forms at once.\n * A rule spanning keys is said only by a submit.\n */\n ValidatedAll: {},\n Submitted: {},\n Reset: {},\n /**\n * The answer of a check for the draft it was asked about; one for an older\n * draft is dropped. `form.Check` also says the `values` and `subject` it\n * read, and an answer about ones the form no longer holds is asked again.\n * One made without them (a test's) answers the form as it is.\n */\n Checked: {\n key: KeySchema,\n draft: DraftSchema,\n values: Schema.optionalKey(Schema.Unknown),\n subject: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),\n error: Schema.NullOr(Schema.String),\n },\n /**\n * The outside world refused this key's value: a unique index, a rule only a\n * server knows. `value` is the key's value in what was refused, as\n * `Submitted` handed it out. While the key still holds it, the key reads\n * invalid with that reason (a mark, see `FormModel.marks`) until the next\n * edit of any key; a key changed since is not what was refused, and the\n * Message is dropped.\n */\n Refused: { key: KeySchema, error: Schema.String, value: Schema.Unknown },\n /**\n * What the form is editing, for the checks that need to know: a post's own\n * row id, so \"is this address taken?\" can pass over the post's own address.\n * It changes no draft and validates nothing; a form that creates something\n * never sends it. See `FormModel.subject`.\n */\n About: { subject: Schema.Record(Schema.String, Schema.String) },\n /** What was typed to find a choice for a relation key. It changes no draft and validates nothing. */\n Searched: { key: KeySchema, text: Schema.String },\n /**\n * A press on a flag (no `choice`), or on one choice of a list: the key's\n * draft as it stands now, flipped, or with `choice` let go if held and added\n * if not. A view sends this rather than `Changed`, so two presses before the\n * next draw both land.\n */\n Toggled: { key: KeySchema, choice: Schema.optional(Schema.String) },\n /** A Message of the nested form in one row of a nested key. One that row does not take is dropped. */\n Nested: { key: Schema.String, row: Schema.String, message: Schema.Unknown },\n /**\n * A Message of the control backed by a Bundle that edits `key`. One the\n * Bundle does not take is dropped. It is an edit when it changes the key's\n * value, and is then validated as `Changed` would be.\n */\n Control: { key: ControlKeySchema, message: Schema.Unknown },\n /** A new, empty row. A `one` that already has its row takes no other. */\n RowAdded: { key: Schema.String },\n /** Removes a row. A `one` that must be there stays. */\n RowRemoved: { key: Schema.String, row: Schema.String },\n /**\n * A link to the field drawn with this id was followed, such as one in a\n * view's list of fields to fix. The view moves focus there itself, in the\n * press; the form changes nothing.\n */\n FollowedIssue: { id: Schema.String },\n /**\n * A relation picker's reader asked for more choices than the list shows. The\n * list is the page's, so the page answers (`Crud.screen` does, given\n * `Crud.options`); the form changes nothing.\n */\n AskedForMore: { key: KeySchema },\n } satisfies Record<FormTag, Schema.Struct.Fields>)\n type Message = typeof Message.Type\n type Commands = ReadonlyArray<Command<Message, never, R>>\n\n const fieldsFrom = (draft: (plan: Plan) => FieldValidation.Field<Draft>): Model['fields'] =>\n Object.fromEntries(keys.map(key => [key, draft(plans[key])])) as Model['fields']\n\n type Rows = ReadonlyArray<FormRow<any>>\n const rowsOf = (model: Model): Readonly<Record<string, Rows>> => model.rows as never\n const withRows = (model: Model, key: string, rows: Rows): Model => ({\n ...model,\n rows: { ...model.rows, [key]: rows },\n })\n\n /** Rows numbered from the Model's count, so an id is never reused. */\n const numbered = (model: Model, key: string, models: ReadonlyArray<unknown>): Model => ({\n ...withRows(\n model,\n key,\n models.map((row, index) => ({ id: `r${model.nextRow + index}`, model: row })),\n ),\n nextRow: model.nextRow + models.length,\n })\n\n // A `one` that must be there starts with its row; every other nested key starts with none.\n const initial: Model = rowsKeys.reduce<Model>(\n (model, key) =>\n numbered(model, key, nestedPlans[key].optional ? [] : [nestedPlans[key].form.initial]),\n {\n fields: fieldsFrom(plan => FieldValidation.NotValidated({ value: plan.empty })),\n rows: {} as Model['rows'],\n nextRow: 0,\n searches: {},\n touched: {},\n attempted: false,\n errors: [],\n marks: {},\n submitPending: false,\n subject: {},\n },\n )\n const drafts = (model: Model): Readonly<Record<Key, FieldValidation.Field<Draft>>> =>\n model.fields as never\n const withField = (model: Model, key: Key, field: FieldValidation.Field<Draft>): Model => ({\n ...model,\n fields: { ...model.fields, [key]: field },\n })\n const marksOf = (model: Model, key: string): ReadonlyArray<string> =>\n Object.hasOwn(model.marks, key) ? model.marks[key]! : []\n const hasMarks = (model: Model): boolean => Object.keys(model.marks).length > 0\n /** A key's state as a view shows it: its own, made invalid by the marks on it. */\n const shownField = <F extends FieldValidation.Field<unknown>>(\n model: Model,\n key: string,\n field: F,\n ): F => {\n const marked = marksOf(model, key)\n if (!Arr.isReadonlyArrayNonEmpty(marked)) return field\n const own = FieldValidation.match(field, {\n onNotValidated: (): ReadonlyArray<string> => [],\n onValidating: () => [],\n onValid: () => [],\n onInvalid: ({ errors }) => errors,\n })\n return FieldValidation.Invalid({\n value: field.value,\n errors: Arr.appendAll(own, marked),\n }) as F\n }\n\n const checks: Readonly<Partial<Record<Key, FormCheck<unknown, Partial<Value>, R>>>> =\n (options.checks ?? {}) as never\n const debounce = options.debounce ?? '300 millis'\n\n /**\n * A key's check, after the debounce: a Command definition, so a test matches\n * it as it would any other (`Command.resolve(form.Check, form.Message.Checked(…))`).\n * Its args carry all the check reads, the values and the subject as the key\n * was asked about.\n */\n const Check = defineCommand(`${name}.check`, {\n args: {\n key: KeySchema,\n draft: DraftSchema,\n values: Schema.Unknown,\n subject: Schema.Record(Schema.String, Schema.String),\n },\n messages: [Message.Checked],\n execute: ({ key, draft, values, subject }) =>\n Effect.sleep(debounce).pipe(\n Effect.andThen(\n // Asked only for a key with a check, by `validateKey`.\n checks[key as Key]!(Result.getOrUndefined(plans[key as Key].check(draft)), {\n values: values as Partial<Value>,\n subject,\n }),\n ),\n Effect.map(error =>\n Message.Checked({ key, draft, values, subject, error: error ?? null }),\n ),\n ),\n })\n\n /** The case `_tag`'s draft names, for a form over a variant Entity's input. */\n const chosen = (model: Model): Option.Option<string> =>\n Option.flatMap(cases, ({ tagKey }) =>\n Result.getSuccess(plans[tagKey as Key].check(drafts(model)[tagKey as Key].value)).pipe(\n Option.filter(tag => typeof tag === 'string'),\n ),\n )\n\n /** Whether the form asks `key` now: always, but for a key of cases other than the one chosen. */\n const shows = (model: Model, key: string): boolean => {\n const holders = caseOnly(key)\n return holders === undefined || Option.exists(chosen(model), tag => holders.has(tag))\n }\n\n /** The keys asked now: every key, or, over a variant Entity, those of the case chosen. */\n const asked = (model: Model): ReadonlyArray<Key> =>\n Option.isNone(cases) ? keys : keys.filter(key => shows(model, key))\n\n /** What currently decodes, by key: the context of a check, and the makings of the value. */\n const decoded = (model: Model): Partial<Value> =>\n Object.fromEntries(\n asked(model).flatMap(key => {\n const value = Result.getOrUndefined(plans[key].check(drafts(model)[key].value))\n return value === undefined ? [] : [[key, value] as const]\n }),\n ) as Partial<Value>\n\n /** A nested key's value; none while some row has none. `undefined` is a key left out. */\n const rowsValue = (model: Model, key: RowsKey): Option.Option<unknown> => {\n const plan = nestedPlans[key]\n const values = rowsOf(model)[key]!.map(row => plan.form.engine.value(row.model))\n if (values.includes(undefined)) return Option.none()\n return Option.some(\n plan.cardinality === 'many' ? values : values.length === 0 ? plan.nothing : values[0],\n )\n }\n\n /** The value of each nested key, or `undefined` while some row has none. */\n const nestedValues = (model: Model): Readonly<Record<string, unknown>> | undefined => {\n const entries: Array<readonly [string, unknown]> = []\n for (const key of rowsKeys) {\n const value = rowsValue(model, key)\n if (Option.isNone(value)) return undefined\n if (value.value !== undefined) entries.push([key, value.value])\n }\n return Object.fromEntries(entries)\n }\n\n /**\n * A nested form's Commands as this form's: their Messages arrive wrapped for\n * the row. `mapMessages` records the wrap on each Command, so a Story or\n * Scene that resolves the row's check sees the `Nested` Message this update\n * handles, not the inner form's bare answer.\n */\n const lift = (key: string, row: string, commands: ReadonlyArray<AnyCommand>): Commands =>\n mapMessages(commands, message => Message.Nested({ key, row, message })) as ReadonlyArray<\n Command<Message, never, R>\n >\n\n /**\n * Each control backed by a Bundle, placed where its key's draft is: its\n * Subscriptions and Resources become the form's, keyed by the key, and its\n * Messages travel as `Control`.\n */\n const placements = controlKeys.map(key => {\n const bundled = plans[key].bundled!\n const accepts = Schema.is(bundled.bundle.Message as Schema.Codec<unknown>)\n const toParentMessage = (message: unknown): Message =>\n Message.Control({ key: key as ControlKey, message })\n const fromParentMessage = (message: Message): Option.Option<unknown> =>\n message._tag === 'Control' && message.key === key && accepts(message.message)\n ? Option.some(message.message)\n : Option.none()\n const link = Link.make({\n read: (model: Model) => Option.some(drafts(model)[key].value),\n // The draft changes and its validation state stays: `update` revalidates\n // when the key's value changed.\n write: (model: Model, child: Draft) =>\n withField(model, key, { ...drafts(model)[key], value: child }),\n wrapper: {\n tag: 'Control',\n Schema: Message.Control,\n cases: {},\n make: toParentMessage,\n toParentMessage,\n fromParentMessage,\n } as never,\n path: ['fields', key],\n })\n const placed = bundled.bundle.at(link as never, { args: bundled.args } as never)\n return { key, bundled, placed: placed as unknown as PlacedControl<Model> }\n })\n\n /** The Command asking `key`'s check about its draft, with the values and subject the form holds. */\n const ask = (model: Model, key: Key): Command<Message, never, R> =>\n Check({\n key,\n draft: drafts(model)[key].value,\n values: decoded(model),\n subject: model.subject,\n }) as Command<Message, never, R>\n\n /**\n * Validates the draft of one key. A key with a check that passes its schema is\n * not `Valid` yet: it is `Validating`, with the Command that asks.\n */\n const validateKey = (\n model: Model,\n key: Key,\n draft: Draft,\n ): { readonly model: Model; readonly commands: Commands } => {\n const state = FieldValidation.validate(plans[key].rules)(draft)\n const current = drafts(model)[key]\n // An empty key that may stay empty validates to what it was: the same Model, so nothing redraws.\n if (\n state._tag === 'NotValidated' &&\n current._tag === 'NotValidated' &&\n sameDraft(current.value, draft)\n ) {\n return { model, commands: [] }\n }\n const check = own(checks, key)\n if (check === undefined || state._tag !== 'Valid') {\n return { model: withField(model, key, state), commands: [] }\n }\n const asking = withField(model, key, FieldValidation.Validating({ value: draft }))\n return { model: asking, commands: [ask(asking, key)] }\n }\n\n // The keys that follow another, and for each key, the keys that follow it.\n const followers = keys.filter(key => plans[key].control.follows !== undefined)\n const followedBy = (key: Key): ReadonlyArray<Key> =>\n followers.filter(follower => plans[follower].control.follows!.key === key)\n for (const follower of followers) {\n const source = plans[follower].control.follows!.key as Key\n if (plans[source] === undefined || plans[source].kind !== 'text' || source === follower)\n fail(name, `\"${follower}\" follows \"${source}\", which is not another text key of the form`)\n // A follows B follows A never settles.\n const seen = new Set<string>([follower])\n for (let next: Key | undefined = source; next !== undefined;) {\n if (seen.has(next)) fail(name, `\"${follower}\" follows itself, through \"${next}\"`)\n seen.add(next)\n next = plans[next].control.follows?.key as Key | undefined\n }\n }\n\n /** What a follower's draft is, from the key it follows. */\n const derived = (model: Model, follower: Key): string => {\n const { key, through } = plans[follower].control.follows!\n return through(String(drafts(model)[key as Key].value))\n }\n\n /**\n * An author's edit of one key, and what follows from it. The key becomes theirs,\n * unless they emptied a key that follows another, which hands it back. Every\n * key still following this one is rewritten, and so on down.\n */\n const changed = (\n model: Model,\n key: Key,\n draft: Draft,\n ): { readonly model: Model; readonly commands: Commands } => {\n const follows = plans[key].control.follows !== undefined\n const handedBack = follows && isEmpty(draft)\n const owned: Model = follows\n ? { ...model, touched: { ...model.touched, [key]: !handedBack } }\n : model\n const written = validateKey(owned, key, handedBack ? derived(owned, key) : draft)\n const result = followedBy(key).reduce(\n (result, follower) => {\n if (result.model.touched[follower] === true) return result\n const next = rewritten(result.model, follower)\n return { model: next.model, asked: [...result.asked, ...next.asked] }\n },\n { model: written.model, asked: written.commands.length === 0 ? [] : [key] },\n )\n // Each check is asked once every follower is written, so the values it\n // reads are the ones the form ends with, and its answer is not stale.\n return { model: result.model, commands: result.asked.map(asked => ask(result.model, asked)) }\n }\n\n /** A follower written from the key it follows, and its own followers after it, with the keys it asks. */\n const rewritten = (\n model: Model,\n follower: Key,\n ): { readonly model: Model; readonly asked: ReadonlyArray<Key> } => {\n const draft = derived(model, follower)\n // Nothing to follow yet is nothing entered, not a failure to show.\n const written = isEmpty(draft)\n ? {\n model: withField(model, follower, FieldValidation.NotValidated({ value: draft })),\n commands: [] as Commands,\n }\n : validateKey(model, follower, draft)\n return followedBy(follower).reduce(\n (result, next) => {\n if (result.model.touched[next] === true) return result\n const after = rewritten(result.model, next)\n return { model: after.model, asked: [...result.asked, ...after.asked] }\n },\n { model: written.model, asked: written.commands.length === 0 ? [] : [follower] },\n )\n }\n\n const decodeInput = Schema.decodeUnknownResult(\n Schema.toType(input.schema) as Schema.Codec<Value>,\n )\n\n // The key of this input that sets each field, for showing an invariant beside it.\n const keyOfField = new Map<string, Key>(\n keys.flatMap(key => {\n const member = members[key]!\n if (member._tag !== 'Field') return []\n return [[member.key, key] as const]\n }),\n )\n\n /**\n * The value's row under its Entity's invariants, as the server will judge\n * it: each failure beside the keys its path names that this form sets, or\n * on the whole input when it sets none of them.\n */\n const judged = (model: Model, value: Value): Option.Option<Model> =>\n Match.value(\n Entity.judgeInput(input, value as Readonly<Record<string, unknown>>, options.operators),\n ).pipe(\n Match.tagsExhaustive({\n Valid: () => Option.none(),\n Undecided: () => Option.none(),\n Invalid: ({ failures }) => {\n const marks = new Map<string, Array<string>>()\n const errors: Array<string> = []\n for (const failure of failures) {\n const shown = failure.path.flatMap(field =>\n Option.toArray(Option.fromUndefinedOr(keyOfField.get(field))),\n )\n if (shown.length === 0) errors.push(failure.message)\n for (const key of shown) {\n const held = marks.get(key)\n if (held === undefined) marks.set(key, [failure.message])\n else held.push(failure.message)\n }\n }\n return Option.some({ ...model, marks: Object.fromEntries(marks), errors })\n },\n }),\n )\n\n const acceptable = (model: Model): boolean =>\n asked(model).every(key => {\n const field = drafts(model)[key]\n // Foldkit counts an optional key not checked yet as valid, and `decoded`\n // leaves out a draft that fails: a filled one would vanish from the\n // value. One not checked yet must pass its own check.\n return (\n FieldValidation.isValid(plans[key].rules)(field) &&\n (field._tag !== 'NotValidated' || Result.isSuccess(plans[key].check(field.value)))\n )\n })\n /** A key's Bundle has work in flight its value waits on (`Input.bundle`'s `busy`). */\n const isBusy = (model: Model, key: Key): boolean =>\n plans[key].bundled?.busy(drafts(model)[key].value) === true\n\n /** A check is running, or a Bundle's work, in this form or in a row of it. */\n const isValidating = (model: Model): boolean =>\n keys.some(key => drafts(model)[key]._tag === 'Validating' || isBusy(model, key)) ||\n rowsKeys.some(key =>\n rowsOf(model)[key]!.some(row => nestedPlans[key].form.engine.isValidating(row.model)),\n )\n\n /** The decoded input, once every key and every row is acceptable; else what is wrong with the whole. */\n const finish = (model: Model): { readonly model: Model; readonly value?: Value } => {\n const settled: Model = model.submitPending ? { ...model, submitPending: false } : model\n const nested = acceptable(model) && !hasMarks(model) ? nestedValues(model) : undefined\n if (nested === undefined) return { model: settled }\n return Result.match(decodeInput({ ...decoded(model), ...nested }), {\n onSuccess: value =>\n Option.match(judged(settled, value), {\n onNone: () => ({\n model: settled.errors.length === 0 ? settled : { ...settled, errors: [] },\n value,\n }),\n onSome: refused => ({ model: refused }),\n }),\n onFailure: error => ({\n model: {\n ...settled,\n errors: [\n worded(options.messages?.form, [error.message], { message: error.message }) ??\n error.message,\n ],\n },\n }),\n })\n }\n\n /**\n * Every key not yet validated is, and `inRow` is run on every row, so every\n * failure shows. A key or row this changes nothing in keeps its identity.\n */\n const validateEvery = (\n model: Model,\n inRow: (\n form: AnyForm,\n row: unknown,\n ) => { readonly model: unknown; readonly commands: ReadonlyArray<AnyCommand> },\n ): { readonly model: Model; readonly commands: Commands } => {\n let next = model\n const commands: Array<Command<Message, never, R>> = []\n for (const key of asked(model)) {\n const state = drafts(next)[key]\n // A key whose work is in flight is being found out, as a checked one is:\n // it is validated when the work lands or ends, not called missing now.\n if (isBusy(next, key)) {\n // A key already being found out, or valid, keeps its state and identity.\n if (state._tag === 'NotValidated' || state._tag === 'Invalid')\n next = withField(next, key, FieldValidation.Validating({ value: state.value }))\n continue\n }\n // Any other state already answers for this draft: an edit always revalidates.\n if (state._tag !== 'NotValidated') continue\n const validated = validateKey(next, key, state.value)\n next = validated.model\n commands.push(...validated.commands)\n }\n for (const key of rowsKeys) {\n const before = rowsOf(next)[key]!\n const rows = before.map(row => {\n const answered = inRow(nestedPlans[key].form, row.model)\n commands.push(...lift(key, row.id, answered.commands))\n return answered.model === row.model ? row : { id: row.id, model: answered.model }\n })\n if (rows.some((row, index) => row !== before[index])) next = withRows(next, key, rows)\n }\n return { model: next, commands }\n }\n\n /** Every key and row validated as a submit would, and nothing submitted. */\n const validateAll = (model: Model): { readonly model: Model; readonly commands: Commands } =>\n validateEvery(model, (form, row) => form.engine.validateAll(row))\n\n /**\n * A submit: every key and row is validated. With no failure, the value goes\n * out; with checks still running, the submit waits for them. A submit that\n * changes nothing (a second one of a valid form) keeps the Model it was\n * given, so a parent that refuses the value has nothing to undo.\n */\n const submit = (\n model: Model,\n ): { readonly model: Model; readonly commands: Commands; readonly value?: Value } => {\n // Marks stand until an edit: the same value would be judged the same.\n const cleared = hasMarks(model) || model.errors.length === 0\n const { model: next, commands } = validateEvery(\n cleared && !model.submitPending && model.attempted\n ? model\n : {\n ...model,\n errors: cleared ? model.errors : [],\n submitPending: false,\n attempted: true,\n },\n (form, row) => form.engine.submit(row),\n )\n if (isValidating(next)) return { model: { ...next, submitPending: true }, commands }\n return { ...finish(next), commands }\n }\n\n interface Out {\n readonly model: Model\n readonly commands: Commands\n readonly outMessage?: Submitted<Value>\n }\n const out = (model: Model, commands: Commands, value: Value | undefined): Out =>\n value === undefined\n ? { model, commands }\n : { model, commands, outMessage: { _tag: 'Submitted', value } }\n\n const submitted = (model: Model): Out => {\n const { model: next, commands, value } = submit(model)\n return out(next, commands, value)\n }\n\n /** After an answer: a submit that was waiting goes out once nothing is asked any more. */\n const resume = (model: Model, commands: Commands = []): Out => {\n if (!model.submitPending || isValidating(model)) return { model, commands }\n const { model: next, value } = finish(model)\n return out(next, commands, value)\n }\n\n /** An edit answers the last submit: its failures describe a form that has changed. */\n const edited = (model: Model): Model => ({\n ...model,\n errors: [],\n marks: {},\n submitPending: false,\n })\n\n /** Shows existing values, as an edit form does; keys not given keep their draft and their rows. */\n const fill = (model: Model, values: Partial<Value>): { readonly model: Model } => {\n const given = values as Readonly<Record<string, unknown>>\n // A control that shows a value badly is a wiring mistake, and a fill is\n // where it says so: named by the form and the key it was showing.\n const shown = (plan: Plan, value: unknown): Draft => {\n try {\n return draftOf(plan, value)\n } catch (error) {\n return fail(\n name,\n `\"${plan.key}\" cannot show that value: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n const filled: Model = {\n ...model,\n // Another value to edit is another search.\n searches: {},\n // A key given a value is the author's: a published address does not move\n // because its title did. One given nothing follows again.\n touched: Object.fromEntries(\n followers.flatMap(key =>\n Object.hasOwn(given, key)\n ? isEmpty(shown(plans[key], given[key]))\n ? []\n : [[key, true] as const]\n : model.touched[key] === true\n ? [[key, true] as const]\n : [],\n ),\n ),\n // Another value to edit, with nothing submitted yet.\n attempted: false,\n errors: [],\n marks: {},\n submitPending: false,\n fields: fieldsFrom(plan =>\n Object.hasOwn(given, plan.key)\n ? FieldValidation.NotValidated({\n value:\n plan.bundled !== undefined\n ? (plan.bundled.fill(\n drafts(model)[plan.key as Key].value,\n given[plan.key],\n ) as Draft)\n : shown(plan, given[plan.key]),\n })\n : drafts(model)[plan.key as Key],\n ),\n }\n return {\n model: rowsKeys.reduce<Model>((next, key) => {\n if (!Object.hasOwn(given, key)) return next\n const { form, optional } = nestedPlans[key]\n const held = given[key]\n const shown = Array.isArray(held)\n ? held\n : held === null || held === undefined\n ? []\n : [held]\n const models = shown.map(value => form.fill(form.initial, value).model)\n // A `one` that must be there keeps an empty row when it is given nothing.\n return numbered(next, key, models.length === 0 && !optional ? [form.initial] : models)\n }, filled),\n }\n }\n\n /** Whether a key's draft says the same thing in two Models: a control's by the value it holds. */\n const sameValue = (key: Key, before: Draft, after: Draft): boolean => {\n const bundled = plans[key].bundled\n return bundled === undefined\n ? sameDraft(before, after)\n : Object.is(bundled.value(before), bundled.value(after))\n }\n\n /** The Subscriptions and Resources of the controls backed by a Bundle, which are the form's. */\n const controlSubscriptions = Object.assign(\n {},\n ...placements.map(({ placed }) => placed.subscriptions),\n ) as Readonly<Record<string, never>>\n const controlResources = Object.assign(\n {},\n ...placements.map(({ placed }) => placed.resources),\n ) as ControlResourcesOf<Inputs>\n\n const bundle = Bundle.make(name, {\n Model,\n Message,\n // A control backed by a Bundle starts with its own init Commands.\n init: () => ({\n model: initial,\n // `init` already wraps them as `Control`, through the placement's Link.\n commands: placements.flatMap(\n ({ placed }) => placed.init(initial).commands ?? [],\n ) as Commands,\n }),\n update: (\n model: Model,\n message: Message,\n ): Update.ReturnWithOutMessage<Model, Message, Submitted<Value>, R> => {\n switch (message._tag) {\n case 'Changed':\n // A draft of another kind than the control of the key holds is not an edit.\n return kindOf(message.value) !== plans[message.key].kind\n ? { model }\n : changed(edited(model), message.key, message.value)\n case 'Toggled':\n return Option.match(\n toggled(plans[message.key].kind, drafts(model)[message.key].value, message.choice),\n {\n onNone: () => ({ model }),\n onSome: value => changed(edited(model), message.key, value),\n },\n )\n case 'Validated': {\n const state = drafts(model)[message.key]\n // Only a key not validated yet: any other state already answers for this draft.\n return state._tag === 'NotValidated'\n ? validateKey(model, message.key, state.value)\n : { model }\n }\n case 'ValidatedAll':\n return validateAll(model)\n case 'Refused': {\n const holds = Result.match(plans[message.key].check(drafts(model)[message.key].value), {\n onSuccess: value => Equal.equals(value, message.value),\n onFailure: () => false,\n })\n const marked = marksOf(model, message.key)\n if (!holds || marked.includes(message.error)) return { model }\n return {\n model: {\n ...model,\n marks: { ...model.marks, [message.key]: [...marked, message.error] },\n // A refusal settles a submit that was waiting: it cannot go through.\n submitPending: false,\n },\n }\n }\n case 'About':\n return { model: { ...model, subject: message.subject } }\n case 'Checked': {\n const state = drafts(model)[message.key]\n // An answer for a draft the key no longer holds is dropped.\n if (state._tag !== 'Validating' || !sameDraft(state.value, message.draft)) {\n return { model }\n }\n // Another key or the subject changed while it ran: the answer is about\n // a form that is gone, and a waiting submit must wait for one about this.\n if (\n (message.values !== undefined && !Equal.equals(message.values, decoded(model))) ||\n (message.subject !== undefined && !Equal.equals(message.subject, model.subject))\n ) {\n return {\n model,\n commands: [ask(model, message.key)],\n }\n }\n return resume(\n withField(\n model,\n message.key,\n message.error === null\n ? FieldValidation.Valid({ value: state.value })\n : FieldValidation.Invalid({ value: state.value, errors: [message.error] }),\n ),\n )\n }\n case 'Searched': {\n return plans[message.key].control.searches\n ? {\n model: { ...model, searches: { ...model.searches, [message.key]: message.text } },\n }\n : { model }\n }\n case 'Control': {\n const placement = placements.find(held => held.key === message.key)\n if (placement === undefined) return { model }\n const before = drafts(model)[message.key].value\n const step = placement.placed.update(model, message)\n if (Option.isNone(step)) return { model }\n const { model: moved, commands = [] } = step.value\n const after = drafts(moved)[message.key].value\n // A Message that leaves the key's value as it was, such as a selection, is not an edit.\n const lifted = commands as Commands\n // A submit waiting on this key's work goes once the work lands or ends:\n // work that ended with the value unchanged leaves the key to be validated.\n if (sameValue(message.key, before, after)) {\n const ended =\n isBusy(model, message.key) &&\n !isBusy(moved, message.key) &&\n drafts(moved)[message.key]._tag === 'Validating'\n if (!ended) return resume(moved, lifted)\n const validated = validateKey(moved, message.key, after)\n return resume(validated.model, [...lifted, ...validated.commands])\n }\n const waited = model.submitPending && isBusy(model, message.key)\n const edit = changed(edited(moved), message.key, after)\n return waited\n ? resume({ ...edit.model, submitPending: true }, [...lifted, ...edit.commands])\n : { model: edit.model, commands: [...lifted, ...edit.commands] }\n }\n case 'Nested': {\n const plan: NestedPlan | undefined = nestedPlans[message.key as RowsKey]\n const row = rowsOf(model)[message.key]?.find(held => held.id === message.row)\n if (plan === undefined || row === undefined) return { model }\n if (!Schema.is(plan.form.bundle.Message)(message.message)) return { model }\n // Its Schema took it, so it is a form's Message.\n const inner = message.message as AnyFormMessage\n // Enter in a row submits the form the row is in.\n if (inner._tag === 'Submitted') return submitted(model)\n const answered = plan.form.bundle.update(row.model, inner, undefined)\n const lifted = lift(message.key, row.id, answered.commands ?? [])\n const next =\n answered.model === row.model\n ? model\n : withRows(\n model,\n message.key,\n rowsOf(model)[message.key]!.map(held =>\n held.id === row.id ? { id: row.id, model: answered.model } : held,\n ),\n )\n const edit =\n isEdit(inner) || plan.form.engine.authoredChanged(row.model, answered.model)\n // A row's own work or check that lands is no edit of the person's: a\n // submit waiting on it keeps waiting, and goes once nothing is asked.\n const waited =\n model.submitPending && !isEdit(inner) && plan.form.engine.isValidating(row.model)\n if (waited)\n return resume(\n next === model ? model : { ...edited(next), submitPending: true },\n lifted,\n )\n return resume(edit ? edited(next) : next, lifted)\n }\n case 'RowAdded': {\n const plan: NestedPlan | undefined = nestedPlans[message.key as RowsKey]\n const rows = rowsOf(model)[message.key]\n if (plan === undefined || rows === undefined) return { model }\n if (plan.cardinality === 'one' && rows.length > 0) return { model }\n const added = numbered(edited(model), message.key, [plan.form.initial])\n return {\n model: withRows(added, message.key, [...rows, ...rowsOf(added)[message.key]!]),\n }\n }\n case 'RowRemoved': {\n const plan: NestedPlan | undefined = nestedPlans[message.key as RowsKey]\n const rows = rowsOf(model)[message.key]\n if (plan === undefined || rows === undefined) return { model }\n if (plan.cardinality === 'one' && !plan.optional) return { model }\n return {\n model: withRows(\n edited(model),\n message.key,\n rows.filter(held => held.id !== message.row),\n ),\n }\n }\n case 'Reset':\n // Emptying the form does not change which row it is about.\n return { model: { ...initial, subject: model.subject } }\n case 'Submitted':\n return submitted(model)\n case 'Blurred':\n case 'FollowedIssue':\n case 'AskedForMore':\n return { model }\n }\n },\n helpers: { fill },\n // Only what the controls have: a form with none listens to nothing and holds nothing.\n ...(Object.keys(controlSubscriptions).length === 0\n ? {}\n : { subscriptions: () => controlSubscriptions }),\n ...(Object.keys(controlResources).length === 0 ? {} : { resources: () => controlResources }),\n })\n\n /**\n * Whether a completed transition changed what the author wrote. Validation\n * state, search text, the edited subject, and row bookkeeping are not\n * authored content, so a blur, a refused edit, or a no-op is not a change.\n * Nested rows recurse through their own forms, and a Bundle-backed control\n * composes because its output is written back before this is asked.\n */\n const authoredChanged = (before: Model, after: Model): boolean => {\n const beforeDrafts = drafts(before)\n const afterDrafts = drafts(after)\n for (const key of keys) {\n if (!sameValue(key, beforeDrafts[key].value, afterDrafts[key].value)) return true\n }\n for (const key of rowsKeys) {\n const beforeRows = rowsOf(before)[key]!\n const afterRows = rowsOf(after)[key]!\n if (beforeRows.length !== afterRows.length) return true\n for (const [index, row] of beforeRows.entries()) {\n const other = afterRows[index]!\n if (row.id !== other.id) return true\n if (nestedPlans[key].form.engine.authoredChanged(row.model, other.model)) return true\n }\n }\n return false\n }\n\n const controls = everyKey.map((key): FormControl<AnyKey> => {\n const { control, label, description, required, member } =\n (plans as Readonly<Record<string, FormControl>>)[key] ??\n (nestedPlans as Readonly<Record<string, FormControl>>)[key]!\n return { key, control, label, description, required, member }\n })\n // `Object.fromEntries` forgets the keys, which are exactly the input's.\n const controlsByKey = Object.fromEntries(controls.map(entry => [entry.key, entry])) as {\n readonly [K in AnyKey]: FormControl<K>\n }\n\n return {\n /** The name, input and options the form was made from: what a pipe step makes the next form from. */\n name,\n options,\n /** Type-only: the form's type parameters, for a pipe step to read. Never set. */\n types: undefined as unknown as {\n readonly Name: Name\n readonly E: E\n readonly Fields: Fields\n readonly Members: Members\n readonly R: R\n readonly Nest: Nest\n readonly Inputs: Inputs\n },\n // Typed by `Pipeable`'s overloads, which read `this` at the call.\n ...({\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n } as Pipeable.Pipeable),\n bundle,\n Message,\n /** The Command a key's check runs as, for a test to resolve (`Command.resolve(form.Check, …)`). */\n Check,\n /** The reading the form was made from, for `Entity.selectFor` and `Entity.valuesFor`. */\n input,\n /** Whether a completed transition changed authored content. See the note above. */\n authoredChanged,\n /** The `fill` helper as a plain function of the form's Model, for a package that wraps the form. */\n fill,\n /** The Model the form starts from and resets to: every key empty and not validated. */\n initial,\n /** The keys in the input's order, each with its control, label, and member. */\n controls,\n /**\n * Over a variant Entity's input, the case its `_tag` key names as it\n * stands; none before one is chosen, and for any other form.\n */\n chosen,\n /**\n * Whether a view draws `key` now: a key of a field only some cases have is\n * asked, validated and submitted only once one of those cases is chosen.\n * Every key of any other form.\n */\n shows: (model: Model, key: Key): boolean => shows(model, key),\n /**\n * The same controls by key, for a view that places each field itself:\n * `form.controlsByKey.email.label`.\n */\n controlsByKey,\n /**\n * One key's state as a view shows it, with its draft as any `Draft`: its\n * own validation, made `Invalid` by the marks on it (`FormModel.marks`).\n * `model.fields.title` is the key's own validation alone. A nested key has\n * rows and no draft.\n */\n field: (model: Model, key: DraftKey): FieldValidation.Field<Draft> => {\n if (plans[key as Key]?.bundled !== undefined)\n return fail(name, `\"${key}\" holds a control's Model, not a draft; read it with control`)\n return shownField<FieldValidation.Field<Draft>>(\n model,\n key,\n drafts(model)[key] ?? fail(name, `\"${key}\" holds rows, not a draft; read it with rows`),\n )\n },\n /**\n * The key edited by a control backed by a Bundle, addressed: `field` is its\n * state with the Bundle's Model as its value, and `send` gives the form's\n * Message for one of the Bundle's own.\n */\n control: <K extends ControlKey>(\n key: K,\n ): {\n readonly field: (model: Model) => Model['fields'][K]\n readonly send: (message: ControlMessageOf<Inputs[K]>) => Message\n } => {\n if (plans[key]?.bundled === undefined)\n fail(name, `\"${key}\" is not edited by a control backed by a Bundle`)\n return {\n field: model => shownField(model, key, model.fields[key]),\n send: message => Message.Control({ key, message }),\n }\n },\n /** What was typed to find a choice for a relation key that searches; `''` until something is. */\n search: (model: Model, key: Key): string => model.searches[key] ?? '',\n /** What the form is editing; `{}` while it creates. See `FormModel.subject`. */\n subject: (model: Model): Readonly<Record<string, string>> => model.subject,\n /**\n * The form of each nested key, typed when it was given under `nested`: its\n * `controls`, its `field`, its Messages.\n */\n nested: Object.fromEntries(rowsKeys.map(key => [key, nestedPlans[key].form])) as {\n readonly [K in RowsKey]: K extends keyof Nest ? NonNullable<Nest[K]> : NestedForm\n },\n /**\n * One row of a nested key, addressed: `form.row('author', id).Changed({ key: 'name', value })`\n * is this form's Message for that edit in that row.\n */\n row: <K extends RowsKey>(\n key: K,\n row: string,\n ): RowHandle<K extends keyof Nest ? NonNullable<Nest[K]> : NestedForm, Message> => {\n const make = (nestedPlans[key] ?? fail(name, `\"${key}\" holds a draft, not rows`)).form\n .Message as unknown as Readonly<\n Record<string, (...args: ReadonlyArray<unknown>) => unknown>\n >\n const send = (message: unknown): Message => Message.Nested({ key, row, message })\n return {\n send,\n ...Object.fromEntries(\n (\n [\n 'Changed',\n 'Blurred',\n 'ValidatedAll',\n 'Searched',\n 'Toggled',\n 'Submitted',\n 'Reset',\n 'RowAdded',\n 'RowRemoved',\n ] as const\n ).map(constructor => [\n constructor,\n (...args: ReadonlyArray<unknown>) => send(make[constructor]!(...args)),\n ]),\n ),\n } as never\n },\n /**\n * Whether a key that follows another still does: `false` once the author has\n * written it themselves. A view offers \"regenerate\" by sending the key an empty draft.\n */\n isFollowing: (model: Model, key: Key): boolean =>\n plans[key].control.follows !== undefined && model.touched[key] !== true,\n /** The rows of a nested key, each a Model of `control.form`. */\n rows: (model: Model, key: RowsKey): Model['rows'][RowsKey] =>\n (rowsOf(model)[key] ?? fail(name, `\"${key}\" holds a draft, not rows`)) as never,\n /**\n * Whether a submit now could go through: nothing is invalid. A check still\n * running does not stop it; the submit waits for the answer.\n */\n canSubmit: (model: Model): boolean => {\n const next = submit(model)\n return next.value !== undefined || next.model.submitPending\n },\n /** Whether a submit was asked since the form started, was filled or was reset. */\n attempted: (model: Model): boolean => model.attempted,\n /**\n * Whether the form is valid right now: a submit now would hand over the\n * value at once. Unlike `canSubmit`, a check running, or one a key has not\n * had yet, is not valid until it answers.\n */\n isValid: (model: Model): boolean => submit(model).value !== undefined,\n /**\n * The decoded input as `Some` only when every key and row is valid as the\n * form stands; `None` otherwise. Unlike `partial`, it is all or nothing,\n * so a parent that submits several forms can read one complete value per\n * form. It validates nothing: reveal drafts first (a submit, or\n * `Message.ValidatedAll()`), or read after one did.\n */\n value: (model: Model): Option.Option<Value> => Option.fromUndefinedOr(finish(model).value),\n /**\n * The Model with nothing in flight, for one that was stored and is shown\n * again: a check that was running when it was stored will never answer, so\n * its key is not validated yet, and no submit is waiting. Rows too.\n */\n settled: (model: Model): Model => ({\n ...model,\n submitPending: false,\n fields: fieldsFrom(plan => {\n const field = drafts(model)[plan.key as Key]\n const held: FieldValidation.Field<Draft> =\n plan.bundled === undefined\n ? field\n : ({\n ...field,\n value: plan.bundled.settled(field.value),\n } as FieldValidation.Field<Draft>)\n return held._tag === 'Validating'\n ? FieldValidation.NotValidated({ value: held.value })\n : held\n }),\n rows: Object.fromEntries(\n rowsKeys.map(key => [\n key,\n rowsOf(model)[key]!.map(row => ({\n ...row,\n model: nestedPlans[key].form.settled(row.model),\n })),\n ]),\n ) as unknown as Model['rows'],\n }),\n /**\n * What of the form decodes as it stands, by key: the value, less every key\n * that is not valid yet. For saving unfinished work, which `engine.value`\n * cannot give. A nested key is there once each of its rows has a value.\n */\n partial: (model: Model): Partial<Value> => ({\n ...decoded(model),\n ...Object.fromEntries(\n rowsKeys.flatMap(key =>\n Option.match(\n Option.filter(rowsValue(model, key), held => held !== undefined),\n {\n onNone: () => [],\n onSome: held => [[key, held] as const],\n },\n ),\n ),\n ),\n }),\n /** The form as the form that nests it drives it. */\n engine: {\n submit: (model: Model) => {\n const { model: next, commands } = submit(model)\n return { model: next, commands }\n },\n validateAll,\n isValidating,\n /** Whether a transition changed authored content, so a nesting form recurses. */\n authoredChanged,\n /** The decoded input when every key and row is valid as it stands; validates nothing. */\n value: (model: Model): Value | undefined => finish(model).value,\n },\n }\n },\n\n /**\n * Entity metadata: the label of a member that has no schema to annotate (a\n * relation, a derived member). A field is labelled on its schema, with\n * `Schema.String.annotate({ title })`.\n */\n label: (label: string, description?: string) =>\n labelKey.of(description === undefined ? { label } : { label, description }),\n\n /**\n * What `Form.label` attached to an Entity member, for a package that labels\n * the same member elsewhere, such as a table column.\n */\n labelOf: (member: { readonly metadata: Metadata }): string | undefined =>\n labelKey.get(member.metadata)[0]?.label,\n}\n\n/** The type parameters a form was made with. */\ninterface FormTypes {\n readonly Name: string\n readonly E: AnyEntity\n readonly Fields: Schema.Struct.Fields\n readonly Members: any\n readonly R: unknown\n readonly Nest: any\n readonly Inputs: any\n}\n\n/** A form as a pipe step takes it: what it was made from, and its type parameters. */\ninterface Remakeable<T extends FormTypes = FormTypes> {\n readonly name: string\n readonly input: EntityInput<any, any, any>\n readonly options: object\n readonly types: T\n}\n\n/** The form `Form.make` gives for these type parameters. */\ntype Made<T extends FormTypes> = ReturnType<\n typeof Core.make<T['Name'], T['E'], T['Fields'], T['Members'], T['R'], T['Nest'], T['Inputs']>\n>\n\ntype OptionsOf<T extends FormTypes> = FormOptions<T['Fields'], T['Members'], T['R'], T['Nest']>\n\n/** The form again, with some of its options replaced or added to. */\nconst remake = (form: Remakeable, change: (options: Record<string, any>) => object): never =>\n (Core.make as (name: string, input: unknown, options: object) => unknown)(form.name, form.input, {\n ...form.options,\n ...change(form.options as Record<string, any>),\n }) as never\n\n/**\n * Pipe steps. Each gives a new form, made from the same input with one option\n * added to, so a form can be handed over partly configured and finished where it\n * is used: `AuthorForm.pipe(Form.inputs({ bio: Input.multiline() }), Form.messages(german))`.\n */\nconst steps = {\n /** Controls by key, beside the ones the form already names. */\n inputs:\n <F extends Remakeable, const I extends InputsFor<F['types']['Fields'], F['types']['Members']>>(\n inputs: I,\n ) =>\n (\n form: F,\n ): [keyof ControlsOf<I>] extends [never]\n ? F\n : Made<{\n readonly Name: F['types']['Name']\n readonly E: F['types']['E']\n readonly Fields: F['types']['Fields']\n readonly Members: F['types']['Members']\n readonly R: F['types']['R']\n readonly Nest: F['types']['Nest']\n readonly Inputs: Omit<F['types']['Inputs'], keyof I> & I\n }> =>\n remake(form, options => ({ inputs: { ...options.inputs, ...inputs } })),\n\n /** The form's words, beside the ones it already has. */\n messages:\n <F extends Remakeable>(messages: NonNullable<OptionsOf<F['types']>['messages']>) =>\n (form: F): F =>\n remake(form, options => ({ messages: { ...options.messages, ...messages } })),\n\n /** How long a key rests before its check runs. */\n debounce:\n (debounce: Duration.Input) =>\n <F extends Remakeable>(form: F): F =>\n remake(form, () => ({ debounce })),\n\n /**\n * Checks by key, beside the ones the form already has. What they need (`R`) is\n * added to what the form needs.\n */\n checks:\n <F extends Remakeable, const C extends ChecksFor<F>>(checks: C) =>\n (\n form: F,\n ): Made<{\n readonly Name: F['types']['Name']\n readonly E: F['types']['E']\n readonly Fields: F['types']['Fields']\n readonly Members: F['types']['Members']\n readonly R: F['types']['R'] | RequirementOf<C>\n readonly Nest: F['types']['Nest']\n readonly Inputs: F['types']['Inputs']\n }> =>\n remake(form, options => ({ checks: { ...options.checks, ...checks } })),\n\n /** The forms of nested keys, beside the ones the form was already given. */\n nested:\n <\n F extends Remakeable,\n const N extends NestedForms<F['types']['Fields'], F['types']['Members'], F['types']['R']>,\n >(\n forms: N,\n ) =>\n (\n form: F,\n ): Made<{\n readonly Name: F['types']['Name']\n readonly E: F['types']['E']\n readonly Fields: F['types']['Fields']\n readonly Members: F['types']['Members']\n readonly R: F['types']['R']\n readonly Nest: F['types']['Nest'] & N\n readonly Inputs: F['types']['Inputs']\n }> =>\n remake(form, options => ({ nested: { ...options.nested, ...forms } })),\n}\n\nexport const Form = { ...Core, ...steps }\n\nmakeNested = Core.make as never\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwOA,MAAa,aACX,UACA,WAEA,SAAS,QAAQ,eAAe,OAAO,SACrC,OAAO,OAAO,QAAQ,IAAI,IAAI,OAAO,OAAO,KAAK,IAAI,KACvD;AAwIF,MAAM,WAAW,SAAS,IAAW,sBAAsB;CACzD,QAAO,WAAU,OAAO,MAAM,EAAE;CAChC,YAAW,UAAS,MAAM;AAC5B,CAAC;;;;;AAyCD,MAAM,WAAW,MAAc,OAAc,WAAqD;CAChG,IAAI,WA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,OAA8B;AAC/C,CAAC;;;;;;AAOH,MAAM,QAAQ;;CAEZ,SAEI,YAGA,SAYA,OAAO,OAAM,aAAY,EAAE,QAAQ;EAAE,GAAG,QAAQ;EAAQ,GAAG;CAAO,EAAE,EAAE;;CAG1E,WACyB,cACtB,SACC,OAAO,OAAM,aAAY,EAAE,UAAU;EAAE,GAAG,QAAQ;EAAU,GAAG;CAAS,EAAE,EAAE;;CAGhF,WACG,cACsB,SACrB,OAAO,aAAa,EAAE,SAAS,EAAE;;;;;CAMrC,SACuD,YAEnD,SAUA,OAAO,OAAM,aAAY,EAAE,QAAQ;EAAE,GAAG,QAAQ;EAAQ,GAAG;CAAO,EAAE,EAAE;;CAG1E,SAKI,WAGA,SAUA,OAAO,OAAM,aAAY,EAAE,QAAQ;EAAE,GAAG,QAAQ;EAAQ,GAAG;CAAM,EAAE,EAAE;AAC3E;AAEA,MAAa,OAAO;CAAE,GAAG;CAAM,GAAG;AAAM;AAExC,aAAa,KAAK"}
1
+ {"version":3,"file":"index.js","names":["Arr","defineCommand"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-form` — a form as a Bundle over Foldkit's own field validation.\n *\n * A form is built from an operation's input (`Entity.input`): the struct says\n * what may be submitted, and the Entity says what each key means. The Model\n * holds one `fieldValidation` Field per key, carrying the draft the control\n * edits. `Submitted` leaves as an out Message with the decoded value; what\n * happens to it (a Remote mutation, a Sync operation, a plain `update`) is the\n * parent's.\n */\nimport {\n Array as Arr,\n Duration,\n Effect,\n Equal,\n Match,\n Option,\n Pipeable,\n Result,\n Schema,\n SchemaAST,\n} from 'effect'\nimport { Bundle, Link } from 'foldkit-bundle'\nimport {\n Entity,\n Words,\n type AnyEntity,\n type EntityInput,\n type InputMember,\n type InputMembers,\n type MemoryOperators,\n type NestedInput,\n type RelationInput,\n type SchemaWords,\n} from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport { type Command, define as defineCommand, mapMessages } from 'foldkit/command'\nimport * as FieldValidation from 'foldkit/fieldValidation'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport {\n Input,\n isControlChange,\n type BundleControl,\n type BundleData,\n type Control,\n type ControlChange,\n type Draft,\n type DraftKind,\n type FormRow,\n type NestedForm,\n} from './input.js'\n\nexport {\n Input,\n type BundleControl,\n type BundleControlSpec,\n type BundleData,\n type Control,\n type ControlChange,\n type ControlKind,\n type Draft,\n type DraftKind,\n type Follows,\n type FormRow,\n type NestedData,\n type NestedForm,\n type RelationData,\n} from './input.js'\nimport { own } from './record.js'\n\n/** The draft a key holds, as far as the input's type says: a flag, a list of ids, or text. */\nexport type DraftOf<Value> = [Exclude<Value, null | undefined>] extends [boolean]\n ? boolean\n : [Exclude<Value, null | undefined>] extends [ReadonlyArray<unknown>]\n ? ReadonlyArray<string>\n : string\n\n/** The keys of an input that hold a nested input (`Relation.nested`): rows of a form, not a draft. */\nexport type NestedKey<Members> = {\n [K in keyof Members]: Members[K] extends NestedInput<any, any> ? K : never\n}[keyof Members]\n\n/** The keys of an input that pick a related row (a relation, not nested): its pickers. */\ntype RelationKey<Members> = {\n [K in keyof Members]: Members[K] extends RelationInput<any> ? K : never\n}[keyof Members]\n\n/** The Model of the form a nested key's rows hold. */\nexport type NestedModel<Member> =\n Member extends NestedInput<any, EntityInput<any, infer Fields, infer Members>>\n ? FormModel<Fields, Members>\n : never\n\n/** The controls a form may be given under `inputs`, by key. */\nexport type InputsFor<Fields extends Schema.Struct.Fields, Members> = {\n readonly [K in Exclude<keyof Fields, NestedKey<Members>>]?: Control | ControlChange\n}\n\n/** The keys given a control backed by a Bundle, each with the Bundle's Model: that key's draft. */\nexport type ControlsOf<Inputs> = {\n readonly [\n K in keyof Inputs as Inputs[K] extends BundleControl<any, any, any> ? K : never\n ]: Inputs[K] extends BundleControl<infer Model, any, any> ? Model : never\n}\n\n/**\n * Whether any control backed by a Bundle holds Resources: then the form's\n * Bundle has Resources, and a runtime running it must provide them.\n */\nexport type ControlResourcesOf<Inputs> = true extends {\n readonly [K in keyof Inputs]: Inputs[K] extends BundleControl<any, any, any, infer Resources>\n ? [keyof Resources] extends [never]\n ? false\n : true\n : false\n}[keyof Inputs]\n ? Readonly<Record<string, never>>\n : {}\n\n/** The Message of the Bundle behind a key's control. */\nexport type ControlMessageOf<C> = C extends BundleControl<any, infer Message, any> ? Message : never\n\nexport interface FormModel<Fields extends Schema.Struct.Fields, Members = {}, Controls = {}> {\n /**\n * One `fieldValidation` Field per key that holds a draft. A key given a\n * control backed by a Bundle holds that Bundle's Model as its draft.\n */\n readonly fields: {\n readonly [K in keyof Fields as K extends NestedKey<Members> ? never : K]: FieldValidation.Field<\n K extends keyof Controls ? Controls[K] : DraftOf<Schema.Schema.Type<Fields[K]>>\n >\n }\n /** The rows of each nested key, each a Model of the nested form. */\n readonly rows: {\n readonly [K in keyof Fields as K extends NestedKey<Members> ? K : never]: ReadonlyArray<\n FormRow<NestedModel<Members[K & keyof Members]>>\n >\n }\n /** Counts the rows ever added, so a row's id is never reused. */\n readonly nextRow: number\n /** What was typed to find a choice, by key, for the relation pickers that search. */\n readonly searches: Readonly<Record<string, string>>\n /**\n * The keys that follow another and that the author has written themselves, so\n * they follow no longer. A key that follows nothing is never here.\n */\n readonly touched: Readonly<Record<string, boolean>>\n /**\n * A submit has been asked since the form started, was filled or was reset.\n * A view draws its list of fields to fix only then. `ValidatedAll` is not\n * one: the page that sends it owns the submit.\n */\n readonly attempted: boolean\n /** Failures of the input as a whole, from the last submit: a rule that spans keys. */\n readonly errors: ReadonlyArray<string>\n /**\n * Failures a judgement of the whole put on a key, apart from the key's own\n * schema and check: an Entity invariant's at a submit, or `Message.Refused`.\n * `field` shows them on their key. Any edit clears them, since an edit of\n * one key can mend a rule that names another; until then a submit stops,\n * since the same value would be judged the same.\n */\n readonly marks: Readonly<Record<string, ReadonlyArray<string>>>\n /** A submit is waiting for checks still running; it goes out when the last one passes. */\n readonly submitPending: boolean\n /**\n * What the form is editing, which its values do not say: a post's own row id,\n * so a check that asks whether an address is taken can tell the post's own\n * address from someone else's. Empty until `Message.About` says otherwise,\n * which is what a form that creates something means.\n */\n readonly subject: Readonly<Record<string, string>>\n}\n\n/**\n * A rule only something outside the form can answer: is this slug taken? It is\n * given the decoded value of the key and whatever else in the form currently\n * decodes, and answers with what is wrong, or nothing. It runs after the schema\n * of the key passes, never instead of it.\n */\nexport type FormCheck<A, Values, R = never> = (\n value: A,\n context: {\n readonly values: Values\n /** What the form is editing: `{}` while it creates. See `FormModel.subject`. */\n readonly subject: Readonly<Record<string, string>>\n },\n) => Effect.Effect<string | undefined, never, R>\n\n/** The form's out Message: every key is valid and the input decoded. */\nexport interface Submitted<Value> {\n readonly _tag: 'Submitted'\n readonly value: Value\n}\n\n/** One key of the form, with everything a view needs to draw it except the pixels. */\nexport interface FormControl<Key extends string = string> {\n readonly key: Key\n readonly control: Control\n /** The schema's `title` annotation, else `Form.label` metadata, else the key. */\n readonly label: string\n readonly description: string | undefined\n /** Whether an empty draft fails. */\n readonly required: boolean\n readonly member: InputMember\n}\n\n/** The key a message is about, for wording that names it. */\nexport interface MessageField<Key extends string = string> {\n readonly key: Key\n readonly label: string\n readonly control: Control\n}\n\n/**\n * The form's words. A rule's own wording belongs on the rule\n * (`Schema.isMinLength(3, { message: '…' })`) and arrives here as `message`;\n * these cover what the form says itself, and let an application translate or\n * rewrite what Schema says by default.\n */\nexport interface FormMessages<Key extends string = string> {\n /** An empty draft the schema does not admit. `{label}`, `{key}`. Default `Required`. */\n readonly required?: string | ((field: MessageField<Key>) => string)\n /** Text its control cannot read: a `Number` that is not one. `{label}`, `{key}`. Default: the kind's own words (`Enter a number`). */\n readonly unparsed?: string | ((field: MessageField<Key>) => string)\n /** A draft the key's schema rejects. `{message}` is the check's own, or Schema's; `{label}`, `{key}`. Default: `{message}`. */\n readonly invalid?: string | ((field: MessageField<Key>, message: string) => string)\n /** A failure of the input as a whole: a rule that spans keys. `{message}`. Default: `{message}`. */\n readonly form?: string | ((message: string) => string)\n}\n\n/**\n * Words with their blanks filled: `fillWords('{label} is required', { label: 'Title' })`.\n * A blank with no value is left as it is written. Words as text, not functions,\n * can be kept in one place, translated, and passed anywhere, a view's inputs\n * included, where Foldkit admits no nested function.\n */\nexport const fillWords = (\n template: string,\n values: Readonly<Record<string, string | number>>,\n): string =>\n template.replace(/\\{(\\w+)\\}/g, (blank, name: string) =>\n Object.hasOwn(values, name) ? String(values[name]) : blank,\n )\n\n/**\n * A form made with `Form.make` from the input a key nests. It is an ordinary\n * form: the one that edits an author alone is the one a post's form nests.\n */\nexport interface FormFor<\n Fields extends Schema.Struct.Fields,\n Members,\n R = never,\n Controls = any,\n> extends NestedForm {\n readonly input: EntityInput<any, Fields, Members>\n readonly bundle: {\n readonly Model: Schema.Codec<FormModel<Fields, Members, Controls>, unknown>\n readonly Message: Schema.Codec<any, unknown>\n readonly update: (\n model: any,\n message: any,\n args: void,\n ) => {\n readonly model: any\n readonly commands?: ReadonlyArray<Command<any, never, R>> | undefined\n }\n }\n readonly initial: FormModel<Fields, Members, Controls>\n readonly fill: (model: any, values: any) => { readonly model: any }\n readonly engine: {\n readonly submit: (model: any) => {\n readonly model: any\n readonly commands: ReadonlyArray<Command<any, never, R>>\n }\n readonly validateAll: (model: any) => {\n readonly model: any\n readonly commands: ReadonlyArray<Command<any, never, R>>\n }\n readonly isValidating: (model: any) => boolean\n readonly value: (model: any) => unknown\n /** Whether a transition changed authored content, so a nesting form recurses. */\n readonly authoredChanged: (before: any, after: any) => boolean\n }\n readonly settled: (model: any) => any\n /**\n * The decoded input as `Some` only when every key and row is valid as the\n * form stands; `None` otherwise. All or nothing, unlike `partial`, so a\n * parent submitting several forms reads one complete value per form.\n */\n readonly value: (model: any) => Option.Option<Schema.Struct.Type<Fields>>\n /** Whether a completed transition changed authored content. */\n readonly authoredChanged: (before: any, after: any) => boolean\n}\n\n/** The forms a form may be given for its nested keys: each one made from that key's nested input. */\nexport type NestedForms<Fields extends Schema.Struct.Fields, Members, R> = {\n readonly [K in NestedKey<Members> & keyof Fields]?: Members[K] extends NestedInput<\n any,\n EntityInput<any, infer NestedFields, infer NestedMembers>\n >\n ? NestedFields extends Schema.Struct.Fields\n ? FormFor<NestedFields, NestedMembers, R>\n : never\n : never\n}\n\n/** The constructors of a form's Messages that a row's handle offers, wrapped for the row. */\ntype RowConstructor =\n | 'Changed'\n | 'Blurred'\n | 'ValidatedAll'\n | 'Searched'\n | 'Toggled'\n | 'Submitted'\n | 'Reset'\n | 'RowAdded'\n | 'RowRemoved'\n\n/**\n * One row of a nested key, addressed: the nested form's own Message constructors,\n * each giving the Message of the form the row is in. `send` wraps a Message\n * already made, which is how a row inside a row is reached.\n */\nexport type RowHandle<Child, Message> = {\n readonly [T in RowConstructor]: Child extends {\n readonly Message: { readonly [C in T]: (...args: infer Args) => unknown }\n }\n ? (...args: Args) => Message\n : never\n} & { readonly send: (message: unknown) => Message }\n\n/** What `Form.make` takes beside the input. */\nexport interface FormOptions<\n Fields extends Schema.Struct.Fields,\n Members,\n R,\n Nest extends NestedForms<Fields, Members, R> = {},\n Inputs extends InputsFor<Fields, Members> = InputsFor<Fields, Members>,\n> {\n /**\n * The control for a key the resolver cannot decide, or should not: an unmapped\n * key with an unusual schema, text that wants a multiline control here only,\n * or a control backed by a Bundle (`Input.bundle`).\n */\n readonly inputs?: Inputs\n /** The form's own words, and a rewrite of Schema's: for wording and for translation. */\n readonly messages?: FormMessages<keyof Fields & string>\n /** Rules answered outside the form, by key. The key reads `Validating` while one runs. */\n readonly checks?: {\n readonly [K in Exclude<keyof Fields, NestedKey<Members>>]?: FormCheck<\n Schema.Schema.Type<Fields[K]>,\n Partial<Schema.Struct.Type<Fields>>,\n R\n >\n }\n /** How long a key rests before its check runs, so typing does not ask per keystroke. Default 300ms. */\n readonly debounce?: Duration.Input\n /**\n * Whether a submit made while a check runs waits for its answer (default\n * `true`). `false` refuses it instead: nothing is handed out and nothing\n * waits, the checks go on, and `canSubmit` is `false` until they answer. The\n * refusal is the form's own, decided from the Model, so a submit sent before\n * the frame that drew the button disabled is refused too. A checked key that\n * has never been checked (a form filled from an existing record) therefore\n * cannot submit at rest: the first submit only starts its check and is\n * refused, and the reader submits again after the answer.\n */\n readonly submitWaits?: boolean\n /**\n * The form of a nested key, made with `Form.make` from the input the key nests\n * (`Relation.nested(relation, input)`): the same form that edits the target\n * alone. A nested key given none gets a plain form of its input, with this\n * form's `messages` and `debounce`.\n */\n readonly nested?: Nest\n /**\n * How the Entity's invariants' primitive operators are run while the form\n * judges them (`Operators`): the kernel's when not given. An invariant calling\n * one this table lacks is left to the server, as one over a field the form\n * does not set is. A nested form given none uses this.\n */\n readonly operators?: MemoryOperators | undefined\n}\n\ninterface Label {\n readonly label: string\n readonly description?: string | undefined\n}\n\nconst labelKey = Metadata.key<Label>('foldkit-form/label', {\n merge: labels => labels.slice(-1),\n summarize: label => label.label,\n})\n\ntype Checked = Result.Result<unknown, string>\n\ntype AnyCommand = Command<any, never, any>\n\n/** A form as the form that nests it uses it: untyped, since a nested input is only known at runtime. */\ninterface AnyForm extends NestedForm {\n readonly bundle: {\n readonly Model: Schema.Codec<any, unknown>\n readonly Message: Schema.Codec<any, unknown>\n readonly update: (\n model: any,\n message: any,\n args: void,\n ) => { readonly model: any; readonly commands?: ReadonlyArray<AnyCommand> | undefined }\n }\n readonly initial: unknown\n readonly fill: (model: any, values: any) => { readonly model: any }\n readonly engine: {\n readonly submit: (model: any) => {\n readonly model: any\n readonly commands: ReadonlyArray<AnyCommand>\n }\n readonly validateAll: (model: any) => {\n readonly model: any\n readonly commands: ReadonlyArray<AnyCommand>\n }\n readonly isValidating: (model: any) => boolean\n readonly value: (model: any) => unknown\n readonly authoredChanged: (before: any, after: any) => boolean\n }\n readonly settled: (model: any) => any\n /** Whether a completed transition changed authored content. */\n readonly authoredChanged: (before: any, after: any) => boolean\n}\n\n/**\n * A draft after a press: a flag flipped, or a list with `choice` let go if it is\n * held and added if not. None when the press does not fit the draft's kind.\n */\nconst toggled = (kind: string, draft: Draft, choice: string | undefined): Option.Option<Draft> => {\n if (choice === undefined) return kind === 'flag' ? Option.some(draft !== true) : Option.none()\n if (kind !== 'list' || !Array.isArray(draft)) return Option.none()\n return Option.some(\n draft.includes(choice) ? draft.filter(held => held !== choice) : [...draft, choice],\n )\n}\n\n/** Assigned once `Form` exists: a form builds the forms of its nested keys with itself. */\nlet makeNested: (name: string, input: unknown, options: unknown) => AnyForm\n\ninterface NestedPlan extends FormControl {\n readonly form: AnyForm\n readonly cardinality: 'one' | 'many'\n readonly optional: boolean\n /** What no row submits, for a `one` whose schema admits nothing; `undefined` leaves the key out. */\n readonly nothing: null | undefined\n}\n\n/**\n * The checks a form may be given by key, with what they need left open. Effect's\n * `R` is not an inference site a mapped type can win: asked to infer it, TypeScript\n * answers `never`, and a check that needs anything is refused by the shape meant to\n * accept it. So the shape admits any requirement and `RequirementOf` reads back what\n * was actually passed.\n */\nexport type ChecksFor<F extends Remakeable> = {\n readonly [K in Exclude<keyof F['types']['Fields'], NestedKey<F['types']['Members']>>]?: FormCheck<\n Schema.Schema.Type<F['types']['Fields'][K]>,\n Partial<Schema.Struct.Type<F['types']['Fields']>>,\n any\n >\n}\n\n/** What a set of checks needs between them, read off the functions that were given. */\nexport type RequirementOf<C> = {\n [K in keyof C]: C[K] extends (...args: never) => Effect.Effect<any, any, infer R> ? R : never\n}[keyof C]\n\n/**\n * Which of a form's Messages are edits, which answer the last submit; an answered\n * check or a blur does not. A `Nested` one is an edit when the row's Message is.\n */\nconst edits = {\n Changed: true,\n Blurred: false,\n Validated: false,\n ValidatedAll: false,\n Submitted: false,\n Reset: true,\n Checked: false,\n Refused: false,\n About: false,\n Searched: false,\n Toggled: true,\n Nested: false,\n Control: false,\n RowAdded: true,\n RowRemoved: true,\n FollowedIssue: false,\n AskedForMore: false,\n} as const\n\n/** A form's tags. Every form has these, so a nested form's Message, known only at runtime, is read by them. */\ntype FormTag = keyof typeof edits\n\ninterface AnyFormMessage {\n readonly _tag: FormTag\n readonly message?: unknown\n}\n\n/** An edit, however deep. */\nconst isEdit = (message: AnyFormMessage): boolean =>\n Match.value(message._tag).pipe(\n Match.when('Nested', () => isEdit(message.message as AnyFormMessage)),\n Match.orElse(tag => edits[tag]),\n )\n\ninterface Plan extends FormControl {\n readonly kind: HeldDraft\n readonly empty: Draft\n readonly check: (draft: Draft) => Checked\n readonly rules: FieldValidation.Rules<Draft>\n /** For a control backed by a Bundle: the Bundle, and how the key's value lives in its Model. */\n readonly bundled: BundleData | undefined\n}\n\n/** A control's Bundle placed where its key's draft is, as the form drives it. */\ninterface PlacedControl<Model> {\n readonly init: (model: Model) => { readonly commands?: ReadonlyArray<AnyCommand> | undefined }\n readonly update: (\n model: Model,\n message: { readonly _tag: string },\n ) => Option.Option<{\n readonly model: Model\n readonly commands?: ReadonlyArray<AnyCommand> | undefined\n }>\n readonly subscriptions: Readonly<Record<string, never>>\n readonly resources: Readonly<Record<string, never>>\n}\n\n/** The drafts a key holds. `rows` is a nested key's, which holds rows instead. */\ntype HeldDraft = Exclude<DraftKind, 'rows'>\n\nconst kindOf = (draft: unknown): HeldDraft | undefined =>\n typeof draft === 'string'\n ? 'text'\n : typeof draft === 'boolean'\n ? 'flag'\n : Array.isArray(draft) && draft.every(item => typeof item === 'string')\n ? 'list'\n : undefined\n\nconst sameDraft = (left: Draft, right: Draft): boolean =>\n Array.isArray(left) && Array.isArray(right)\n ? left.length === right.length && left.every((item, index) => item === right[index])\n : left === right\n\nconst isEmpty = (draft: Draft): boolean =>\n draft === '' || (Array.isArray(draft) && draft.length === 0)\n\n/** Text that is read as something else is blank when it is only spaces: `Number(' ')` is 0, which nobody typed. */\nconst isBlank = (control: Control, draft: Draft): boolean =>\n isEmpty(draft) ||\n (control.parse !== undefined && typeof draft === 'string' && draft.trim() === '')\n\n/**\n * What an `Option`-typed key holds (`Schema.Option`, `Schema.OptionFromNullOr`),\n * found as Effect's own tools find it: by the declaration's representation id.\n */\nconst optionOf = (schema: Schema.Top): Option.Option<Schema.Top> => {\n const { ast } = schema\n if (!SchemaAST.isDeclaration(ast) || ast.typeParameters.length !== 1) return Option.none()\n const representation: unknown = ast.annotations?.['representation']\n return typeof representation === 'object' &&\n representation !== null &&\n 'id' in representation &&\n representation.id === 'effect/schema/Option'\n ? Option.some(Schema.make(ast.typeParameters[0]!))\n : Option.none()\n}\n\n/** The schema's `title`, else `Form.label` metadata on the member, else the key. */\nconst wordsOf = (\n key: string,\n schema: Schema.Top,\n member: InputMember,\n): { readonly label: string; readonly description: string | undefined } => {\n const { own, fieldSchemas } = Match.valueTags(member, {\n Unmapped: () => ({ own: undefined, fieldSchemas: [] }),\n Field: field => ({ own: field, fieldSchemas: [field.schema as Schema.Top] }),\n RelationInput: ({ relation }) => ({ own: relation, fieldSchemas: [] }),\n NestedInput: ({ relation }) => ({ own: relation, fieldSchemas: [] }),\n })\n const [labelled] = own === undefined ? [] : labelKey.get(own.metadata)\n const words = [schema, ...fieldSchemas].map(Words.of)\n const first = (pick: (entry: SchemaWords) => Option.Option<string>) =>\n Option.firstSomeOf(words.map(pick))\n return {\n label: Option.getOrElse(\n first(entry => entry.title),\n () => labelled?.label ?? key,\n ),\n description: Option.getOrElse(\n first(entry => entry.description),\n () => labelled?.description,\n ),\n }\n}\n\nconst nestedPlanOf = (\n name: string,\n key: string,\n schema: Schema.Top,\n member: Extract<InputMember, { readonly _tag: 'NestedInput' }>,\n given: AnyForm | undefined,\n inherited: unknown,\n): NestedPlan => {\n const accepts = Schema.is(Schema.toType(schema) as Schema.Codec<unknown>)\n const cardinality = member.relation.cardinality\n const absent = SchemaAST.isOptional(schema.ast) || accepts(undefined)\n const optional = cardinality === 'many' || absent || accepts(null)\n if (given !== undefined && (given as { readonly input?: unknown }).input !== member.input)\n fail(\n name,\n `\"${key}\" is given a form of another input than the one it nests; make it from the input passed to Relation.nested`,\n )\n const form = given ?? makeNested(`${name}.${key}`, member.input, inherited)\n // A row is plain data in this form's Model, so nothing would run a row's own\n // listeners or hold its resources. Say so rather than drop them.\n const lifecycle = form.bundle as {\n readonly subscriptions?: unknown\n readonly resources?: unknown\n }\n if (lifecycle.subscriptions !== undefined || lifecycle.resources !== undefined)\n fail(\n name,\n `\"${key}\" nests a form with a control whose Bundle has Subscriptions or Resources, which rows cannot run yet`,\n )\n return {\n key,\n ...wordsOf(key, schema, member),\n control: Input.Nested.of({ cardinality, optional, form }),\n required: !optional,\n member,\n form,\n cardinality,\n optional,\n nothing: absent ? undefined : null,\n }\n}\n\n/**\n * A form over a variant Entity's input that sets `_tag`: the key that picks\n * the case, and for each key of a field only some cases have, those cases.\n * None for any other form. Such a key must be an optional key of the input, so\n * a row of another case leaves it out.\n */\nconst casesOf = (\n name: string,\n input: EntityInput<AnyEntity, any, any>,\n keys: ReadonlyArray<string>,\n): Option.Option<{\n readonly tagKey: string\n readonly only: ReadonlyMap<string, ReadonlySet<string>>\n}> => {\n const members = input.members as Readonly<Record<string, InputMember>>\n const fields = input.schema.fields as Readonly<Record<string, Schema.Top>>\n const tagKey = keys.find(key => {\n const member = members[key]!\n return member._tag === 'Field' && member.key === '_tag'\n })\n return Option.flatMap(Entity.variantsOf(input.entity), variants => {\n if (tagKey === undefined) return Option.none()\n const only = new Map<string, ReadonlySet<string>>()\n for (const key of keys) {\n const member = members[key]!\n if (member._tag !== 'Field' || member.key === '_tag') continue\n const holders = variants.tags.filter(tag => Object.hasOwn(variants.cases[tag]!, member.key))\n if (holders.length === variants.tags.length) continue\n if (!SchemaAST.isOptional(fields[key]!.ast))\n fail(\n name,\n `\"${key}\" is a field of some cases of ${input.entity.name}; declare it Schema.optionalKey in the input, so a row of another case leaves it out`,\n )\n only.set(key, new Set(holders))\n }\n return Option.some({ tagKey, only })\n })\n}\n\nconst planOf = (\n name: string,\n key: string,\n schema: Schema.Top,\n member: InputMember,\n override: Control | ControlChange | undefined,\n messages: FormMessages,\n): Plan => {\n // A key typed `Option` is edited as what it holds; nothing entered is `Option.none()`.\n const held = optionOf(schema)\n const shape = Option.getOrElse(held, () => schema)\n const resolved = Input.resolve(member, shape)\n const chosen =\n override === undefined\n ? resolved\n : isControlChange(override)\n ? attempt(name, () => override.change(resolved, key))\n : override\n const control = chosen ?? fail(name, `no control for \"${key}\"; name one under \"inputs\"`)\n if (control.draft === 'rows')\n return fail(\n name,\n `\"${key}\" cannot be given a ${control.kind} control; map it with Relation.nested`,\n )\n const kind = control.draft\n const type = Schema.toType(shape) as Schema.Codec<unknown>\n const decode = Schema.decodeUnknownResult(type)\n const accepts = Schema.is(type)\n const bundled = Input.isBundle(control) ? control.data : undefined\n // A control backed by a Bundle holds the Bundle's Model as its draft. Inside\n // the form every draft is carried as a `Draft`; only this plan's own\n // functions read it as the Bundle's Model.\n const empty: Draft =\n bundled !== undefined\n ? (bundled.bundle.init(bundled.args).model as Draft)\n : kind === 'flag'\n ? false\n : kind === 'list'\n ? []\n : ''\n const blank = (draft: Draft): boolean => {\n if (bundled === undefined) return isBlank(control, draft)\n const value = bundled.value(draft)\n return value === undefined || value === null\n }\n\n // A control whose draft can never become the key's value is a wiring mistake.\n // A choice of literals is tried with the first one, two, … of its own options,\n // since an array that must hold some refuses `[]` and an id alike.\n const samples: ReadonlyArray<unknown> =\n kind === 'flag'\n ? [true, false]\n : kind === 'list'\n ? [\n [],\n ['id'],\n ...(Input.Choices.is(control)\n ? control.data.options.map((_, index) => control.data.options.slice(0, index + 1))\n : []),\n ]\n : []\n if (samples.length > 0 && !samples.some(accepts))\n fail(name, `\"${key}\" is edited as ${control.kind}, but its schema accepts no such value`)\n\n const { label, description } = wordsOf(key, schema, member)\n const field: MessageField = { key, label, control }\n const say = {\n required: worded(messages.required, [field], { label, key }) ?? 'Required',\n unparsed: worded(messages.unparsed, [field], { label, key }) ?? control.unparsed ?? 'Not valid',\n invalid: (message: string) =>\n worded(messages.invalid, [field, message], { label, key, message }) ?? message,\n }\n\n // What \"nothing entered\" submits is whatever the input admits for it: leaving\n // an optional key out (`undefined`, which `decoded` omits), `Option.none()`,\n // `null`, or the empty draft itself.\n const [admitted] = (bundled === undefined ? [null, empty] : [null]).filter(value =>\n accepts(value),\n )\n const nothingEntered: Checked =\n SchemaAST.isOptional(schema.ast) || accepts(undefined)\n ? Result.succeed(undefined)\n : Option.isSome(held)\n ? Result.succeed(Option.none())\n : admitted !== undefined\n ? Result.succeed(admitted)\n : Result.fail(say.required)\n\n const check = (draft: Draft): Checked => {\n if (blank(draft)) return nothingEntered\n // A kind may read its text as something else before the schema sees it, and\n // a control backed by a Bundle reads its value from its Model.\n const value =\n bundled !== undefined\n ? bundled.value(draft)\n : control.parse !== undefined && typeof draft === 'string'\n ? control.parse(draft, control.data)\n : control.parseList !== undefined && Array.isArray(draft)\n ? control.parseList(draft, control.data)\n : draft\n if (value === undefined) return Result.fail(say.unparsed)\n const decoded = Result.mapError(decode(value), error => say.invalid(error.message))\n return Option.isSome(held) ? Result.map(decoded, Option.some) : decoded\n }\n\n const required = kind !== 'flag' && Result.isFailure(check(empty))\n return {\n key,\n control,\n kind,\n empty,\n check,\n required,\n member,\n label,\n description,\n bundled,\n rules: FieldValidation.makeRules<Draft>({\n isEmpty: blank,\n ...(required ? { required: say.required } : {}),\n rules: [\n [\n draft => Result.isSuccess(check(draft)),\n draft => Result.match(check(draft), { onSuccess: () => '', onFailure: error => error }),\n ],\n ],\n }),\n }\n}\n\n/** Words given as text have their blanks filled; given as a function, it is asked. */\nconst worded = <Args extends ReadonlyArray<unknown>>(\n words: string | ((...args: Args) => string) | undefined,\n args: Args,\n values: Readonly<Record<string, string | number>>,\n): string | undefined =>\n words === undefined\n ? undefined\n : typeof words === 'string'\n ? fillWords(words, values)\n : words(...args)\n\nconst fail = (name: string, message: string): never => {\n throw new Error(`Form \"${name}\": ${message}`)\n}\n\n/** A failure inside a control change, said as the form's. */\nconst attempt = <A>(name: string, run: () => A): A => {\n try {\n return run()\n } catch (error) {\n return fail(name, error instanceof Error ? error.message : String(error))\n }\n}\n\n/**\n * The draft that shows `value`: the text the control's `format` makes of it, or\n * `String(value)` when it formats nothing; nothing (`Option.none()` too) is the\n * empty draft.\n */\nconst draftOf = (plan: Plan, given: unknown): Draft => {\n const value = Option.isOption(given) ? Option.getOrUndefined(given) : given\n if (value === null || value === undefined) return plan.empty\n // A list draft is text, as an edit sends it: a filled `[1]` reads back as `['1']`.\n if (plan.kind === 'list' && Array.isArray(value)) return value.map(item => String(item))\n if (plan.kind !== 'text') return value as Draft\n const format = plan.control.format\n return format === undefined ? String(value) : format(value, plan.control.data)\n}\n\nconst Core = {\n /**\n * The input of a form that writes no Entity of its own (a sign-up, a search,\n * a login): `Entity.input` over an Entity defined from the same schema, so\n * every key maps itself. `Form.make('Waitlist', Form.input(JoinWaitlist))`.\n */\n input: <Fields extends Schema.Struct.Fields>(\n schema: Schema.Struct<Fields>,\n ): EntityInput<\n Entity<'FormInput', Fields>,\n Fields,\n InputMembers<Entity<'FormInput', Fields>, Fields, {}>\n > => {\n const entity = Entity.define('FormInput', schema)\n // Every key names a field of the Entity, so there is no mapping; the\n // generic `Fields` keeps TypeScript from seeing that the mapping is optional.\n return Entity.input<typeof entity, Fields, {}>(entity, schema, undefined as never)\n },\n\n /**\n * A form for one operation's input. A key mapped with `Relation.nested` holds\n * rows of a form of its own, built here from the nested input; every other key\n * holds a draft. `options` names what the input cannot say: a control, the\n * words, the checks.\n */\n make: <\n const Name extends string,\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n Members extends { readonly [K in keyof Fields]: InputMember },\n R = never,\n const Nest extends NestedForms<Fields, Members, R> = {},\n const Inputs extends InputsFor<Fields, Members> = {},\n >(\n name: Name,\n input: EntityInput<E, Fields, Members>,\n options: FormOptions<Fields, Members, R, Nest, Inputs> = {},\n ) => {\n type AnyKey = keyof Fields & string\n type Key = Exclude<AnyKey, NestedKey<Members>>\n type RowsKey = Extract<AnyKey, NestedKey<Members>>\n type ControlKey = keyof ControlsOf<Inputs> & Key\n type DraftKey = Exclude<Key, ControlKey>\n /** The keys a relation picker edits: what may ask for more choices. */\n type PickerKey = Exclude<Extract<Key, RelationKey<Members>>, ControlKey>\n type Value = Schema.Struct.Type<Fields>\n type Model = FormModel<Fields, Members, ControlsOf<Inputs>>\n\n const members: Readonly<Record<string, InputMember>> = input.members\n const everyKey = Object.keys(input.schema.fields) as ReadonlyArray<AnyKey>\n const keys = everyKey.filter(\n key => members[key]!._tag !== 'NestedInput',\n ) as unknown as ReadonlyArray<Key>\n const rowsKeys = everyKey.filter(\n key => members[key]!._tag === 'NestedInput',\n ) as unknown as ReadonlyArray<RowsKey>\n\n const overrides: Readonly<Record<string, Control | ControlChange | undefined>> =\n options.inputs ?? {}\n const cases = casesOf(name, input, keys)\n const caseOnly = (key: string): ReadonlySet<string> | undefined =>\n Option.match(cases, { onNone: () => undefined, onSome: ({ only }) => only.get(key) })\n const plans = Object.fromEntries(\n keys.map(key => [\n key,\n planOf(\n name,\n key,\n // A key of some cases is asked as the case holds it: required where its schema is.\n (caseOnly(key) === undefined\n ? input.schema.fields[key]\n : (input.schema.fields[key] as unknown as { readonly schema: Schema.Top })\n .schema) as Schema.Top,\n members[key]!,\n own(overrides, key),\n (options.messages ?? {}) as FormMessages,\n ),\n ]),\n ) as Readonly<Record<Key, Plan>>\n\n // The keys whose control is backed by a Bundle: each holds that Bundle's Model.\n const controlKeys = keys.filter(key => plans[key].bundled !== undefined)\n for (const key of controlKeys)\n if (options.checks !== undefined && Object.hasOwn(options.checks, key))\n fail(\n name,\n `\"${key}\" is edited by a control backed by a Bundle, which takes no check; say what is valid in its schema`,\n )\n\n const givenForms: Readonly<Record<string, AnyForm | undefined>> = (options.nested ??\n {}) as never\n const nestedPlans = Object.fromEntries(\n rowsKeys.map(key => [\n key,\n nestedPlanOf(\n name,\n key,\n input.schema.fields[key] as Schema.Top,\n members[key] as Extract<InputMember, { readonly _tag: 'NestedInput' }>,\n own(givenForms, key),\n // A nested form made here takes this form's words and pace.\n { messages: options.messages, debounce: options.debounce, operators: options.operators },\n ),\n ]),\n ) as Readonly<Record<RowsKey, NestedPlan>>\n\n const draftSchema: Record<Exclude<HeldDraft, 'model'>, Schema.Codec<Draft, any>> = {\n text: Schema.String,\n flag: Schema.Boolean,\n list: Schema.Array(Schema.String),\n }\n const schemaOf = (plan: Plan): Schema.Codec<Draft, any> =>\n plan.bundled !== undefined\n ? (plan.bundled.bundle.Model as Schema.Codec<Draft, any>)\n : draftSchema[plan.kind as Exclude<HeldDraft, 'model'>]\n const Model = Schema.Struct({\n fields: Schema.Struct(\n Object.fromEntries(keys.map(key => [key, FieldValidation.Field(schemaOf(plans[key]))])),\n ),\n rows: Schema.Struct(\n Object.fromEntries(\n rowsKeys.map(key => [\n key,\n Schema.Array(\n Schema.Struct({ id: Schema.String, model: nestedPlans[key].form.bundle.Model }),\n ),\n ]),\n ),\n ),\n nextRow: Schema.Number,\n searches: Schema.Record(Schema.String, Schema.String),\n touched: Schema.Record(Schema.String, Schema.Boolean),\n // Defaulted, so a Model stored before it existed still decodes.\n attempted: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))),\n errors: Schema.Array(Schema.String),\n marks: Schema.Record(Schema.String, Schema.Array(Schema.String)).pipe(\n Schema.withDecodingDefaultKey(Effect.succeed({})),\n ),\n submitPending: Schema.Boolean,\n subject: Schema.Record(Schema.String, Schema.String),\n }) as unknown as Schema.Codec<Model, unknown>\n\n // A form of nested keys only has no key to change, and `Literals` needs one.\n const KeySchema = (\n keys.length === 0\n ? Schema.Never\n : Schema.Literals(keys as unknown as readonly [Key, ...Key[]])\n ) as Schema.Literals<readonly [Key, ...Key[]]>\n const DraftSchema = Schema.Union([Schema.String, Schema.Boolean, Schema.Array(Schema.String)])\n const ControlKeySchema = (\n controlKeys.length === 0\n ? Schema.Never\n : Schema.Literals(controlKeys as unknown as readonly [ControlKey, ...ControlKey[]])\n ) as Schema.Literals<readonly [ControlKey, ...ControlKey[]]>\n const pickerKeys = keys.filter(\n key => members[key]!._tag === 'RelationInput' && plans[key].bundled === undefined,\n ) as unknown as ReadonlyArray<PickerKey>\n const PickerKeySchema = (\n pickerKeys.length === 0\n ? Schema.Never\n : Schema.Literals(pickerKeys as unknown as readonly [PickerKey, ...PickerKey[]])\n ) as Schema.Literals<readonly [PickerKey, ...PickerKey[]]>\n const Message = defineMessageUnion({\n Changed: { key: KeySchema, value: DraftSchema },\n /**\n * The person left the key. An edit has already validated it, and a key\n * never edited is not judged before a submit, so tabbing through a field\n * says nothing about it: the form changes nothing.\n */\n Blurred: { key: KeySchema },\n /**\n * Validates the key as it stands, edited or not: for a program showing a\n * stored value's failure after a `fill`, which validates nothing.\n */\n Validated: { key: KeySchema },\n /**\n * Validates every key not validated yet, in every row too, as a submit\n * would, and submits nothing: for a page that submits several forms at once.\n * A rule spanning keys is said only by a submit.\n */\n ValidatedAll: {},\n Submitted: {},\n Reset: {},\n /**\n * The answer of a check for the draft it was asked about; one for an older\n * draft is dropped. `form.Check` also says the `values` and `subject` it\n * read, and an answer about ones the form no longer holds is asked again.\n * One made without them (a test's) answers the form as it is.\n */\n Checked: {\n key: KeySchema,\n draft: DraftSchema,\n values: Schema.optionalKey(Schema.Unknown),\n subject: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),\n error: Schema.NullOr(Schema.String),\n },\n /**\n * The outside world refused this key's value: a unique index, a rule only a\n * server knows. `value` is the key's value in what was refused, as\n * `Submitted` handed it out. While the key still holds it, the key reads\n * invalid with that reason (a mark, see `FormModel.marks`) until the next\n * edit of any key; a key changed since is not what was refused, and the\n * Message is dropped.\n */\n Refused: { key: KeySchema, error: Schema.String, value: Schema.Unknown },\n /**\n * What the form is editing, for the checks that need to know: a post's own\n * row id, so \"is this address taken?\" can pass over the post's own address.\n * It changes no draft and validates nothing; a form that creates something\n * never sends it. See `FormModel.subject`.\n */\n About: { subject: Schema.Record(Schema.String, Schema.String) },\n /** What was typed to find a choice for a relation key. It changes no draft and validates nothing. */\n Searched: { key: KeySchema, text: Schema.String },\n /**\n * A press on a flag (no `choice`), or on one choice of a list: the key's\n * draft as it stands now, flipped, or with `choice` let go if held and added\n * if not. A view sends this rather than `Changed`, so two presses before the\n * next draw both land.\n */\n Toggled: { key: KeySchema, choice: Schema.optional(Schema.String) },\n /** A Message of the nested form in one row of a nested key. One that row does not take is dropped. */\n Nested: { key: Schema.String, row: Schema.String, message: Schema.Unknown },\n /**\n * A Message of the control backed by a Bundle that edits `key`. One the\n * Bundle does not take is dropped. It is an edit when it changes the key's\n * value, and is then validated as `Changed` would be.\n */\n Control: { key: ControlKeySchema, message: Schema.Unknown },\n /** A new, empty row. A `one` that already has its row takes no other. */\n RowAdded: { key: Schema.String },\n /** Removes a row. A `one` that must be there stays. */\n RowRemoved: { key: Schema.String, row: Schema.String },\n /**\n * A link to the field drawn with this id was followed, such as one in a\n * view's list of fields to fix. The view moves focus there itself, in the\n * press; the form changes nothing.\n */\n FollowedIssue: { id: Schema.String },\n /**\n * A relation picker's reader asked for more choices than the list shows. The\n * list is the page's, so the page answers (`Crud.screen` does, given\n * `Crud.options`); the form changes nothing.\n */\n AskedForMore: { key: PickerKeySchema },\n } satisfies Record<FormTag, Schema.Struct.Fields>)\n type Message = typeof Message.Type\n type Commands = ReadonlyArray<Command<Message, never, R>>\n\n const fieldsFrom = (draft: (plan: Plan) => FieldValidation.Field<Draft>): Model['fields'] =>\n Object.fromEntries(keys.map(key => [key, draft(plans[key])])) as Model['fields']\n\n type Rows = ReadonlyArray<FormRow<any>>\n const rowsOf = (model: Model): Readonly<Record<string, Rows>> => model.rows as never\n const withRows = (model: Model, key: string, rows: Rows): Model => ({\n ...model,\n rows: { ...model.rows, [key]: rows },\n })\n\n /** Rows numbered from the Model's count, so an id is never reused. */\n const numbered = (model: Model, key: string, models: ReadonlyArray<unknown>): Model => ({\n ...withRows(\n model,\n key,\n models.map((row, index) => ({ id: `r${model.nextRow + index}`, model: row })),\n ),\n nextRow: model.nextRow + models.length,\n })\n\n // A `one` that must be there starts with its row; every other nested key starts with none.\n const initial: Model = rowsKeys.reduce<Model>(\n (model, key) =>\n numbered(model, key, nestedPlans[key].optional ? [] : [nestedPlans[key].form.initial]),\n {\n fields: fieldsFrom(plan => FieldValidation.NotValidated({ value: plan.empty })),\n rows: {} as Model['rows'],\n nextRow: 0,\n searches: {},\n touched: {},\n attempted: false,\n errors: [],\n marks: {},\n submitPending: false,\n subject: {},\n },\n )\n const drafts = (model: Model): Readonly<Record<Key, FieldValidation.Field<Draft>>> =>\n model.fields as never\n const withField = (model: Model, key: Key, field: FieldValidation.Field<Draft>): Model => ({\n ...model,\n fields: { ...model.fields, [key]: field },\n })\n const marksOf = (model: Model, key: string): ReadonlyArray<string> =>\n Object.hasOwn(model.marks, key) ? model.marks[key]! : []\n const hasMarks = (model: Model): boolean => Object.keys(model.marks).length > 0\n /** A key's state as a view shows it: its own, made invalid by the marks on it. */\n const shownField = <F extends FieldValidation.Field<unknown>>(\n model: Model,\n key: string,\n field: F,\n ): F => {\n const marked = marksOf(model, key)\n if (!Arr.isReadonlyArrayNonEmpty(marked)) return field\n const own = FieldValidation.match(field, {\n onNotValidated: (): ReadonlyArray<string> => [],\n onValidating: () => [],\n onValid: () => [],\n onInvalid: ({ errors }) => errors,\n })\n return FieldValidation.Invalid({\n value: field.value,\n errors: Arr.appendAll(own, marked),\n }) as F\n }\n\n const checks: Readonly<Partial<Record<Key, FormCheck<unknown, Partial<Value>, R>>>> =\n (options.checks ?? {}) as never\n const debounce = options.debounce ?? '300 millis'\n const submitWaits = options.submitWaits ?? true\n\n /**\n * A key's check, after the debounce: a Command definition, so a test matches\n * it as it would any other (`Command.resolve(form.Check, form.Message.Checked(…))`).\n * Its args carry all the check reads, the values and the subject as the key\n * was asked about.\n */\n const Check = defineCommand(`${name}.check`, {\n args: {\n key: KeySchema,\n draft: DraftSchema,\n values: Schema.Unknown,\n subject: Schema.Record(Schema.String, Schema.String),\n },\n messages: [Message.Checked],\n execute: ({ key, draft, values, subject }) =>\n Effect.sleep(debounce).pipe(\n Effect.andThen(\n // Asked only for a key with a check, by `validateKey`.\n checks[key as Key]!(Result.getOrUndefined(plans[key as Key].check(draft)), {\n values: values as Partial<Value>,\n subject,\n }),\n ),\n Effect.map(error =>\n Message.Checked({ key, draft, values, subject, error: error ?? null }),\n ),\n ),\n })\n\n /** The case `_tag`'s draft names, for a form over a variant Entity's input. */\n const chosen = (model: Model): Option.Option<string> =>\n Option.flatMap(cases, ({ tagKey }) =>\n Result.getSuccess(plans[tagKey as Key].check(drafts(model)[tagKey as Key].value)).pipe(\n Option.filter(tag => typeof tag === 'string'),\n ),\n )\n\n /** Whether the form asks `key` now: always, but for a key of cases other than the one chosen. */\n const shows = (model: Model, key: string): boolean => {\n const holders = caseOnly(key)\n return holders === undefined || Option.exists(chosen(model), tag => holders.has(tag))\n }\n\n /** The keys asked now: every key, or, over a variant Entity, those of the case chosen. */\n const asked = (model: Model): ReadonlyArray<Key> =>\n Option.isNone(cases) ? keys : keys.filter(key => shows(model, key))\n\n /** What currently decodes, by key: the context of a check, and the makings of the value. */\n const decoded = (model: Model): Partial<Value> =>\n Object.fromEntries(\n asked(model).flatMap(key => {\n const value = Result.getOrUndefined(plans[key].check(drafts(model)[key].value))\n return value === undefined ? [] : [[key, value] as const]\n }),\n ) as Partial<Value>\n\n /** A nested key's value; none while some row has none. `undefined` is a key left out. */\n const rowsValue = (model: Model, key: RowsKey): Option.Option<unknown> => {\n const plan = nestedPlans[key]\n const values = rowsOf(model)[key]!.map(row => plan.form.engine.value(row.model))\n if (values.includes(undefined)) return Option.none()\n return Option.some(\n plan.cardinality === 'many' ? values : values.length === 0 ? plan.nothing : values[0],\n )\n }\n\n /** The value of each nested key, or `undefined` while some row has none. */\n const nestedValues = (model: Model): Readonly<Record<string, unknown>> | undefined => {\n const entries: Array<readonly [string, unknown]> = []\n for (const key of rowsKeys) {\n const value = rowsValue(model, key)\n if (Option.isNone(value)) return undefined\n if (value.value !== undefined) entries.push([key, value.value])\n }\n return Object.fromEntries(entries)\n }\n\n /**\n * A nested form's Commands as this form's: their Messages arrive wrapped for\n * the row. `mapMessages` records the wrap on each Command, so a Story or\n * Scene that resolves the row's check sees the `Nested` Message this update\n * handles, not the inner form's bare answer.\n */\n const lift = (key: string, row: string, commands: ReadonlyArray<AnyCommand>): Commands =>\n mapMessages(commands, message => Message.Nested({ key, row, message })) as ReadonlyArray<\n Command<Message, never, R>\n >\n\n /**\n * Each control backed by a Bundle, placed where its key's draft is: its\n * Subscriptions and Resources become the form's, keyed by the key, and its\n * Messages travel as `Control`.\n */\n const placements = controlKeys.map(key => {\n const bundled = plans[key].bundled!\n const accepts = Schema.is(bundled.bundle.Message as Schema.Codec<unknown>)\n const toParentMessage = (message: unknown): Message =>\n Message.Control({ key: key as ControlKey, message })\n const fromParentMessage = (message: Message): Option.Option<unknown> => {\n if (message._tag !== 'Control' || message.key !== key || !accepts(message.message))\n return Option.none()\n return Option.some(message.message)\n }\n const link = Link.make({\n read: (model: Model) => Option.some(drafts(model)[key].value),\n // The draft changes and its validation state stays: `update` revalidates\n // when the key's value changed.\n write: (model: Model, child: Draft) =>\n withField(model, key, { ...drafts(model)[key], value: child }),\n wrapper: {\n tag: 'Control',\n Schema: Message.Control,\n cases: {},\n make: toParentMessage,\n toParentMessage,\n fromParentMessage,\n } as never,\n path: ['fields', key],\n })\n const placed = bundled.bundle.at(link as never, { args: bundled.args } as never)\n return { key, bundled, placed: placed as unknown as PlacedControl<Model> }\n })\n\n /** The Command asking `key`'s check about its draft, with the values and subject the form holds. */\n const ask = (model: Model, key: Key): Command<Message, never, R> =>\n Check({\n key,\n draft: drafts(model)[key].value,\n values: decoded(model),\n subject: model.subject,\n }) as Command<Message, never, R>\n\n /**\n * Validates the draft of one key. A key with a check that passes its schema is\n * not `Valid` yet: it is `Validating`, with the Command that asks.\n */\n const validateKey = (\n model: Model,\n key: Key,\n draft: Draft,\n ): { readonly model: Model; readonly commands: Commands } => {\n const state = FieldValidation.validate(plans[key].rules)(draft)\n const current = drafts(model)[key]\n // An empty key that may stay empty validates to what it was: the same Model, so nothing redraws.\n if (\n state._tag === 'NotValidated' &&\n current._tag === 'NotValidated' &&\n sameDraft(current.value, draft)\n ) {\n return { model, commands: [] }\n }\n const check = own(checks, key)\n if (check === undefined || state._tag !== 'Valid') {\n return { model: withField(model, key, state), commands: [] }\n }\n const asking = withField(model, key, FieldValidation.Validating({ value: draft }))\n return { model: asking, commands: [ask(asking, key)] }\n }\n\n // The keys that follow another, and for each key, the keys that follow it.\n const followers = keys.filter(key => plans[key].control.follows !== undefined)\n const followedBy = (key: Key): ReadonlyArray<Key> =>\n followers.filter(follower => plans[follower].control.follows!.key === key)\n for (const follower of followers) {\n const source = plans[follower].control.follows!.key as Key\n if (plans[source] === undefined || plans[source].kind !== 'text' || source === follower)\n fail(name, `\"${follower}\" follows \"${source}\", which is not another text key of the form`)\n // A follows B follows A never settles.\n const seen = new Set<string>([follower])\n for (let next: Key | undefined = source; next !== undefined;) {\n if (seen.has(next)) fail(name, `\"${follower}\" follows itself, through \"${next}\"`)\n seen.add(next)\n next = plans[next].control.follows?.key as Key | undefined\n }\n }\n\n /** What a follower's draft is, from the key it follows. */\n const derived = (model: Model, follower: Key): string => {\n const { key, through } = plans[follower].control.follows!\n return through(String(drafts(model)[key as Key].value))\n }\n\n /**\n * An author's edit of one key, and what follows from it. The key becomes theirs,\n * unless they emptied a key that follows another, which hands it back. Every\n * key still following this one is rewritten, and so on down.\n */\n const changed = (\n model: Model,\n key: Key,\n draft: Draft,\n ): { readonly model: Model; readonly commands: Commands } => {\n const follows = plans[key].control.follows !== undefined\n const handedBack = follows && isEmpty(draft)\n const owned: Model = follows\n ? { ...model, touched: { ...model.touched, [key]: !handedBack } }\n : model\n const written = validateKey(owned, key, handedBack ? derived(owned, key) : draft)\n const result = followedBy(key).reduce(\n (result, follower) => {\n if (result.model.touched[follower] === true) return result\n const next = rewritten(result.model, follower)\n return { model: next.model, asked: [...result.asked, ...next.asked] }\n },\n { model: written.model, asked: written.commands.length === 0 ? [] : [key] },\n )\n // Each check is asked once every follower is written, so the values it\n // reads are the ones the form ends with, and its answer is not stale.\n return { model: result.model, commands: result.asked.map(asked => ask(result.model, asked)) }\n }\n\n /** A follower written from the key it follows, and its own followers after it, with the keys it asks. */\n const rewritten = (\n model: Model,\n follower: Key,\n ): { readonly model: Model; readonly asked: ReadonlyArray<Key> } => {\n const draft = derived(model, follower)\n // Nothing to follow yet is nothing entered, not a failure to show.\n const written = isEmpty(draft)\n ? {\n model: withField(model, follower, FieldValidation.NotValidated({ value: draft })),\n commands: [] as Commands,\n }\n : validateKey(model, follower, draft)\n return followedBy(follower).reduce(\n (result, next) => {\n if (result.model.touched[next] === true) return result\n const after = rewritten(result.model, next)\n return { model: after.model, asked: [...result.asked, ...after.asked] }\n },\n { model: written.model, asked: written.commands.length === 0 ? [] : [follower] },\n )\n }\n\n const decodeInput = Schema.decodeUnknownResult(\n Schema.toType(input.schema) as Schema.Codec<Value>,\n )\n\n // The key of this input that sets each field, for showing an invariant beside it.\n const keyOfField = new Map<string, Key>(\n keys.flatMap(key => {\n const member = members[key]!\n if (member._tag !== 'Field') return []\n const field = member.key\n return [[field, key] as const]\n }),\n )\n\n /**\n * The value's row under its Entity's invariants, as the server will judge\n * it: each failure beside the keys its path names that this form sets, or\n * on the whole input when it sets none of them.\n */\n const judged = (model: Model, value: Value): Option.Option<Model> =>\n Match.value(\n Entity.judgeInput(input, value as Readonly<Record<string, unknown>>, options.operators),\n ).pipe(\n Match.tagsExhaustive({\n Valid: () => Option.none(),\n Undecided: () => Option.none(),\n Invalid: ({ failures }) => {\n const marks = new Map<string, Array<string>>()\n const errors: Array<string> = []\n for (const failure of failures) {\n const shown = failure.path.flatMap(field =>\n Option.toArray(Option.fromUndefinedOr(keyOfField.get(field))),\n )\n if (shown.length === 0) errors.push(failure.message)\n for (const key of shown) {\n const held = marks.get(key)\n if (held === undefined) marks.set(key, [failure.message])\n else held.push(failure.message)\n }\n }\n return Option.some({ ...model, marks: Object.fromEntries(marks), errors })\n },\n }),\n )\n\n const acceptable = (model: Model): boolean =>\n asked(model).every(key => {\n const field = drafts(model)[key]\n // Foldkit counts an optional key not checked yet as valid, and `decoded`\n // leaves out a draft that fails: a filled one would vanish from the\n // value. One not checked yet must pass its own check.\n return (\n FieldValidation.isValid(plans[key].rules)(field) &&\n (field._tag !== 'NotValidated' || Result.isSuccess(plans[key].check(field.value)))\n )\n })\n /** A key's Bundle has work in flight its value waits on (`Input.bundle`'s `busy`). */\n const isBusy = (model: Model, key: Key): boolean =>\n plans[key].bundled?.busy(drafts(model)[key].value) === true\n\n /** A check is running, or a Bundle's work, in this form or in a row of it. */\n const isValidating = (model: Model): boolean =>\n keys.some(key => drafts(model)[key]._tag === 'Validating' || isBusy(model, key)) ||\n rowsKeys.some(key =>\n rowsOf(model)[key]!.some(row => nestedPlans[key].form.engine.isValidating(row.model)),\n )\n\n /** The decoded input, once every key and every row is acceptable; else what is wrong with the whole. */\n const finish = (model: Model): { readonly model: Model; readonly value?: Value } => {\n const settled: Model = model.submitPending ? { ...model, submitPending: false } : model\n const nested = acceptable(model) && !hasMarks(model) ? nestedValues(model) : undefined\n if (nested === undefined) return { model: settled }\n return Result.match(decodeInput({ ...decoded(model), ...nested }), {\n onSuccess: value =>\n Option.match(judged(settled, value), {\n onNone: () => ({\n model: settled.errors.length === 0 ? settled : { ...settled, errors: [] },\n value,\n }),\n onSome: refused => ({ model: refused }),\n }),\n onFailure: error => ({\n model: {\n ...settled,\n errors: [\n worded(options.messages?.form, [error.message], { message: error.message }) ??\n error.message,\n ],\n },\n }),\n })\n }\n\n /**\n * Every key not yet validated is, and `inRow` is run on every row, so every\n * failure shows. A key or row this changes nothing in keeps its identity.\n */\n const validateEvery = (\n model: Model,\n inRow: (\n form: AnyForm,\n row: unknown,\n ) => { readonly model: unknown; readonly commands: ReadonlyArray<AnyCommand> },\n ): { readonly model: Model; readonly commands: Commands } => {\n let next = model\n const commands: Array<Command<Message, never, R>> = []\n for (const key of asked(model)) {\n const state = drafts(next)[key]\n // A key whose work is in flight is being found out, as a checked one is:\n // it is validated when the work lands or ends, not called missing now.\n if (isBusy(next, key)) {\n // A key already being found out, or valid, keeps its state and identity.\n if (state._tag === 'NotValidated' || state._tag === 'Invalid')\n next = withField(next, key, FieldValidation.Validating({ value: state.value }))\n continue\n }\n // Any other state already answers for this draft: an edit always revalidates.\n if (state._tag !== 'NotValidated') continue\n const validated = validateKey(next, key, state.value)\n next = validated.model\n commands.push(...validated.commands)\n }\n for (const key of rowsKeys) {\n const before = rowsOf(next)[key]!\n const rows = before.map(row => {\n const answered = inRow(nestedPlans[key].form, row.model)\n commands.push(...lift(key, row.id, answered.commands))\n return answered.model === row.model ? row : { id: row.id, model: answered.model }\n })\n if (rows.some((row, index) => row !== before[index])) next = withRows(next, key, rows)\n }\n return { model: next, commands }\n }\n\n /** Every key and row validated as a submit would, and nothing submitted. */\n const validateAll = (model: Model): { readonly model: Model; readonly commands: Commands } =>\n validateEvery(model, (form, row) => form.engine.validateAll(row))\n\n /**\n * A submit: every key and row is validated. With no failure, the value goes\n * out; with checks still running, the submit waits for them. A submit that\n * changes nothing (a second one of a valid form) keeps the Model it was\n * given, so a parent that refuses the value has nothing to undo.\n */\n const submit = (\n model: Model,\n ): { readonly model: Model; readonly commands: Commands; readonly value?: Value } => {\n // Marks stand until an edit: the same value would be judged the same.\n const cleared = hasMarks(model) || model.errors.length === 0\n const { model: next, commands } = validateEvery(\n cleared && !model.submitPending && model.attempted\n ? model\n : {\n ...model,\n errors: cleared ? model.errors : [],\n submitPending: false,\n attempted: true,\n },\n (form, row) => form.engine.submit(row),\n )\n if (isValidating(next))\n return { model: submitWaits ? { ...next, submitPending: true } : next, commands }\n return { ...finish(next), commands }\n }\n\n interface Out {\n readonly model: Model\n readonly commands: Commands\n readonly outMessage?: Submitted<Value>\n }\n const out = (model: Model, commands: Commands, value: Value | undefined): Out =>\n value === undefined\n ? { model, commands }\n : { model, commands, outMessage: { _tag: 'Submitted', value } }\n\n const submitted = (model: Model): Out => {\n const { model: next, commands, value } = submit(model)\n return out(next, commands, value)\n }\n\n /** After an answer: a submit that was waiting goes out once nothing is asked any more. */\n const resume = (model: Model, commands: Commands = []): Out => {\n if (!model.submitPending || isValidating(model)) return { model, commands }\n const { model: next, value } = finish(model)\n return out(next, commands, value)\n }\n\n /** An edit answers the last submit: its failures describe a form that has changed. */\n const edited = (model: Model): Model => ({\n ...model,\n errors: [],\n marks: {},\n submitPending: false,\n })\n\n /** Shows existing values, as an edit form does; keys not given keep their draft and their rows. */\n const fill = (model: Model, values: Partial<Value>): { readonly model: Model } => {\n const given = values as Readonly<Record<string, unknown>>\n // A control that shows a value badly is a wiring mistake, and a fill is\n // where it says so: named by the form and the key it was showing.\n const shown = (plan: Plan, value: unknown): Draft => {\n try {\n return draftOf(plan, value)\n } catch (error) {\n return fail(\n name,\n `\"${plan.key}\" cannot show that value: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n const filled: Model = {\n ...model,\n // Another value to edit is another search.\n searches: {},\n // A key given a value is the author's: a published address does not move\n // because its title did. One given nothing follows again.\n touched: Object.fromEntries(\n followers.flatMap(key =>\n Object.hasOwn(given, key)\n ? isEmpty(shown(plans[key], given[key]))\n ? []\n : [[key, true] as const]\n : model.touched[key] === true\n ? [[key, true] as const]\n : [],\n ),\n ),\n // Another value to edit, with nothing submitted yet.\n attempted: false,\n errors: [],\n marks: {},\n submitPending: false,\n fields: fieldsFrom(plan =>\n Object.hasOwn(given, plan.key)\n ? FieldValidation.NotValidated({\n value:\n plan.bundled !== undefined\n ? (plan.bundled.fill(\n drafts(model)[plan.key as Key].value,\n given[plan.key],\n ) as Draft)\n : shown(plan, given[plan.key]),\n })\n : drafts(model)[plan.key as Key],\n ),\n }\n return {\n model: rowsKeys.reduce<Model>((next, key) => {\n if (!Object.hasOwn(given, key)) return next\n const { form, optional } = nestedPlans[key]\n const held = given[key]\n const shown = Array.isArray(held)\n ? held\n : held === null || held === undefined\n ? []\n : [held]\n const models = shown.map(value => form.fill(form.initial, value).model)\n // A `one` that must be there keeps an empty row when it is given nothing.\n return numbered(next, key, models.length === 0 && !optional ? [form.initial] : models)\n }, filled),\n }\n }\n\n /** Whether a key's draft says the same thing in two Models: a control's by the value it holds. */\n const sameValue = (key: Key, before: Draft, after: Draft): boolean => {\n const bundled = plans[key].bundled\n return bundled === undefined\n ? sameDraft(before, after)\n : Object.is(bundled.value(before), bundled.value(after))\n }\n\n /** The Subscriptions and Resources of the controls backed by a Bundle, which are the form's. */\n const controlSubscriptions = Object.assign(\n {},\n ...placements.map(({ placed }) => placed.subscriptions),\n ) as Readonly<Record<string, never>>\n const controlResources = Object.assign(\n {},\n ...placements.map(({ placed }) => placed.resources),\n ) as ControlResourcesOf<Inputs>\n\n const bundle = Bundle.make(name, {\n Model,\n Message,\n // A control backed by a Bundle starts with its own init Commands.\n init: () => ({\n model: initial,\n // `init` already wraps them as `Control`, through the placement's Link.\n commands: placements.flatMap(\n ({ placed }) => placed.init(initial).commands ?? [],\n ) as Commands,\n }),\n update: (\n model: Model,\n message: Message,\n ): Update.ReturnWithOutMessage<Model, Message, Submitted<Value>, R> => {\n switch (message._tag) {\n case 'Changed':\n // A draft of another kind than the control of the key holds is not an edit.\n return kindOf(message.value) !== plans[message.key].kind\n ? { model }\n : changed(edited(model), message.key, message.value)\n case 'Toggled':\n return Option.match(\n toggled(plans[message.key].kind, drafts(model)[message.key].value, message.choice),\n {\n onNone: () => ({ model }),\n onSome: value => changed(edited(model), message.key, value),\n },\n )\n case 'Validated': {\n const state = drafts(model)[message.key]\n // Only a key not validated yet: any other state already answers for this draft.\n return FieldValidation.match(state, {\n onNotValidated: value => validateKey(model, message.key, value),\n onValidating: () => ({ model }),\n onValid: () => ({ model }),\n onInvalid: () => ({ model }),\n })\n }\n case 'ValidatedAll':\n return validateAll(model)\n case 'Refused': {\n const holds = Result.match(plans[message.key].check(drafts(model)[message.key].value), {\n onSuccess: value => Equal.equals(value, message.value),\n onFailure: () => false,\n })\n const marked = marksOf(model, message.key)\n if (!holds || marked.includes(message.error)) return { model }\n return {\n model: {\n ...model,\n marks: { ...model.marks, [message.key]: [...marked, message.error] },\n // A refusal settles a submit that was waiting: it cannot go through.\n submitPending: false,\n },\n }\n }\n case 'About':\n return { model: { ...model, subject: message.subject } }\n case 'Checked': {\n const state = drafts(model)[message.key]\n // An answer for a draft the key no longer holds is dropped.\n if (state._tag !== 'Validating' || !sameDraft(state.value, message.draft)) {\n return { model }\n }\n // Another key or the subject changed while it ran: the answer is about\n // a form that is gone, and a waiting submit must wait for one about this.\n if (\n (message.values !== undefined && !Equal.equals(message.values, decoded(model))) ||\n (message.subject !== undefined && !Equal.equals(message.subject, model.subject))\n ) {\n return {\n model,\n commands: [ask(model, message.key)],\n }\n }\n return resume(\n withField(\n model,\n message.key,\n message.error === null\n ? FieldValidation.Valid({ value: state.value })\n : FieldValidation.Invalid({ value: state.value, errors: [message.error] }),\n ),\n )\n }\n case 'Searched': {\n return plans[message.key].control.searches\n ? {\n model: { ...model, searches: { ...model.searches, [message.key]: message.text } },\n }\n : { model }\n }\n case 'Control': {\n const placement = placements.find(held => held.key === message.key)\n if (placement === undefined) return { model }\n const before = drafts(model)[message.key].value\n const step = placement.placed.update(model, message)\n if (Option.isNone(step)) return { model }\n const { model: moved, commands = [] } = step.value\n const after = drafts(moved)[message.key].value\n // A Message that leaves the key's value as it was, such as a selection, is not an edit.\n const lifted = commands as Commands\n // A submit waiting on this key's work goes once the work lands or ends:\n // work that ended with the value unchanged leaves the key to be validated.\n if (sameValue(message.key, before, after)) {\n const ended =\n isBusy(model, message.key) &&\n !isBusy(moved, message.key) &&\n drafts(moved)[message.key]._tag === 'Validating'\n if (!ended) return resume(moved, lifted)\n const validated = validateKey(moved, message.key, after)\n return resume(validated.model, [...lifted, ...validated.commands])\n }\n const waited = model.submitPending && isBusy(model, message.key)\n const edit = changed(edited(moved), message.key, after)\n return waited\n ? resume({ ...edit.model, submitPending: true }, [...lifted, ...edit.commands])\n : { model: edit.model, commands: [...lifted, ...edit.commands] }\n }\n case 'Nested': {\n const plan: NestedPlan | undefined = nestedPlans[message.key as RowsKey]\n const row = rowsOf(model)[message.key]?.find(held => held.id === message.row)\n if (plan === undefined || row === undefined) return { model }\n if (!Schema.is(plan.form.bundle.Message)(message.message)) return { model }\n // Its Schema took it, so it is a form's Message.\n const inner = message.message as AnyFormMessage\n // Enter in a row submits the form the row is in.\n if (inner._tag === 'Submitted') return submitted(model)\n const answered = plan.form.bundle.update(row.model, inner, undefined)\n const lifted = lift(message.key, row.id, answered.commands ?? [])\n const next =\n answered.model === row.model\n ? model\n : withRows(\n model,\n message.key,\n rowsOf(model)[message.key]!.map(held =>\n held.id === row.id ? { id: row.id, model: answered.model } : held,\n ),\n )\n const edit =\n isEdit(inner) || plan.form.engine.authoredChanged(row.model, answered.model)\n // A row's own work or check that lands is no edit of the person's: a\n // submit waiting on it keeps waiting, and goes once nothing is asked.\n const waited =\n model.submitPending && !isEdit(inner) && plan.form.engine.isValidating(row.model)\n if (waited)\n return resume(\n next === model ? model : { ...edited(next), submitPending: true },\n lifted,\n )\n return resume(edit ? edited(next) : next, lifted)\n }\n case 'RowAdded': {\n const plan: NestedPlan | undefined = nestedPlans[message.key as RowsKey]\n const rows = rowsOf(model)[message.key]\n if (plan === undefined || rows === undefined) return { model }\n if (plan.cardinality === 'one' && rows.length > 0) return { model }\n const added = numbered(edited(model), message.key, [plan.form.initial])\n return {\n model: withRows(added, message.key, [...rows, ...rowsOf(added)[message.key]!]),\n }\n }\n case 'RowRemoved': {\n const plan: NestedPlan | undefined = nestedPlans[message.key as RowsKey]\n const rows = rowsOf(model)[message.key]\n if (plan === undefined || rows === undefined) return { model }\n if (plan.cardinality === 'one' && !plan.optional) return { model }\n return {\n model: withRows(\n edited(model),\n message.key,\n rows.filter(held => held.id !== message.row),\n ),\n }\n }\n case 'Reset':\n // Emptying the form does not change which row it is about.\n return { model: { ...initial, subject: model.subject } }\n case 'Submitted':\n return submitted(model)\n case 'Blurred':\n case 'FollowedIssue':\n case 'AskedForMore':\n return { model }\n }\n },\n helpers: { fill },\n // Only what the controls have: a form with none listens to nothing and holds nothing.\n ...(Object.keys(controlSubscriptions).length === 0\n ? {}\n : { subscriptions: () => controlSubscriptions }),\n ...(Object.keys(controlResources).length === 0 ? {} : { resources: () => controlResources }),\n })\n\n /**\n * Whether a completed transition changed what the author wrote. Validation\n * state, search text, the edited subject, and row bookkeeping are not\n * authored content, so a blur, a refused edit, or a no-op is not a change.\n * Nested rows recurse through their own forms, and a Bundle-backed control\n * composes because its output is written back before this is asked.\n */\n const authoredChanged = (before: Model, after: Model): boolean => {\n const beforeDrafts = drafts(before)\n const afterDrafts = drafts(after)\n for (const key of keys) {\n if (!sameValue(key, beforeDrafts[key].value, afterDrafts[key].value)) return true\n }\n for (const key of rowsKeys) {\n const beforeRows = rowsOf(before)[key]!\n const afterRows = rowsOf(after)[key]!\n if (beforeRows.length !== afterRows.length) return true\n for (const [index, row] of beforeRows.entries()) {\n const other = afterRows[index]!\n if (row.id !== other.id) return true\n if (nestedPlans[key].form.engine.authoredChanged(row.model, other.model)) return true\n }\n }\n return false\n }\n\n const controls = everyKey.map((key): FormControl<AnyKey> => {\n const { control, label, description, required, member } =\n (plans as Readonly<Record<string, FormControl>>)[key] ??\n (nestedPlans as Readonly<Record<string, FormControl>>)[key]!\n return { key, control, label, description, required, member }\n })\n // `Object.fromEntries` forgets the keys, which are exactly the input's.\n const controlsByKey = Object.fromEntries(controls.map(entry => [entry.key, entry])) as {\n readonly [K in AnyKey]: FormControl<K>\n }\n\n return {\n /** The name, input and options the form was made from: what a pipe step makes the next form from. */\n name,\n options,\n /** Type-only: the form's type parameters, for a pipe step to read. Never set. */\n types: undefined as unknown as {\n readonly Name: Name\n readonly E: E\n readonly Fields: Fields\n readonly Members: Members\n readonly R: R\n readonly Nest: Nest\n readonly Inputs: Inputs\n },\n // Typed by `Pipeable`'s overloads, which read `this` at the call.\n ...({\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n } as Pipeable.Pipeable),\n bundle,\n Message,\n /** The Command a key's check runs as, for a test to resolve (`Command.resolve(form.Check, …)`). */\n Check,\n /** The reading the form was made from, for `Entity.selectFor` and `Entity.valuesFor`. */\n input,\n /** Whether a completed transition changed authored content. See the note above. */\n authoredChanged,\n /** The `fill` helper as a plain function of the form's Model, for a package that wraps the form. */\n fill,\n /** The Model the form starts from and resets to: every key empty and not validated. */\n initial,\n /** The keys in the input's order, each with its control, label, and member. */\n controls,\n /**\n * Over a variant Entity's input, the case its `_tag` key names as it\n * stands; none before one is chosen, and for any other form.\n */\n chosen,\n /**\n * Whether a view draws `key` now: a key of a field only some cases have is\n * asked, validated and submitted only once one of those cases is chosen.\n * Every key of any other form.\n */\n shows: (model: Model, key: Key): boolean => shows(model, key),\n /**\n * The same controls by key, for a view that places each field itself:\n * `form.controlsByKey.email.label`.\n */\n controlsByKey,\n /**\n * One key's state as a view shows it, with its draft as any `Draft`: its\n * own validation, made `Invalid` by the marks on it (`FormModel.marks`).\n * `model.fields.title` is the key's own validation alone. A nested key has\n * rows and no draft.\n */\n field: (model: Model, key: DraftKey): FieldValidation.Field<Draft> => {\n if (plans[key as Key]?.bundled !== undefined)\n return fail(name, `\"${key}\" holds a control's Model, not a draft; read it with control`)\n return shownField<FieldValidation.Field<Draft>>(\n model,\n key,\n drafts(model)[key] ?? fail(name, `\"${key}\" holds rows, not a draft; read it with rows`),\n )\n },\n /**\n * The key edited by a control backed by a Bundle, addressed: `field` is its\n * state with the Bundle's Model as its value, and `send` gives the form's\n * Message for one of the Bundle's own.\n */\n control: <K extends ControlKey>(\n key: K,\n ): {\n readonly field: (model: Model) => Model['fields'][K]\n readonly send: (message: ControlMessageOf<Inputs[K]>) => Message\n } => {\n if (plans[key]?.bundled === undefined)\n fail(name, `\"${key}\" is not edited by a control backed by a Bundle`)\n return {\n field: model => shownField(model, key, model.fields[key]),\n send: message => Message.Control({ key, message }),\n }\n },\n /** What was typed to find a choice for a relation key that searches; `''` until something is. */\n search: (model: Model, key: Key): string => model.searches[key] ?? '',\n /** What the form is editing; `{}` while it creates. See `FormModel.subject`. */\n subject: (model: Model): Readonly<Record<string, string>> => model.subject,\n /**\n * The form of each nested key, typed when it was given under `nested`: its\n * `controls`, its `field`, its Messages.\n */\n nested: Object.fromEntries(rowsKeys.map(key => [key, nestedPlans[key].form])) as {\n readonly [K in RowsKey]: K extends keyof Nest ? NonNullable<Nest[K]> : NestedForm\n },\n /**\n * One row of a nested key, addressed: `form.row('author', id).Changed({ key: 'name', value })`\n * is this form's Message for that edit in that row.\n */\n row: <K extends RowsKey>(\n key: K,\n row: string,\n ): RowHandle<K extends keyof Nest ? NonNullable<Nest[K]> : NestedForm, Message> => {\n const make = (nestedPlans[key] ?? fail(name, `\"${key}\" holds a draft, not rows`)).form\n .Message as unknown as Readonly<\n Record<string, (...args: ReadonlyArray<unknown>) => unknown>\n >\n const send = (message: unknown): Message => Message.Nested({ key, row, message })\n return {\n send,\n ...Object.fromEntries(\n (\n [\n 'Changed',\n 'Blurred',\n 'ValidatedAll',\n 'Searched',\n 'Toggled',\n 'Submitted',\n 'Reset',\n 'RowAdded',\n 'RowRemoved',\n ] as const\n ).map(constructor => [\n constructor,\n (...args: ReadonlyArray<unknown>) => send(make[constructor]!(...args)),\n ]),\n ),\n } as never\n },\n /**\n * Whether a key that follows another still does: `false` once the author has\n * written it themselves. A view offers \"regenerate\" by sending the key an empty draft.\n */\n isFollowing: (model: Model, key: Key): boolean =>\n plans[key].control.follows !== undefined && model.touched[key] !== true,\n /** The rows of a nested key, each a Model of `control.form`. */\n rows: (model: Model, key: RowsKey): Model['rows'][RowsKey] =>\n (rowsOf(model)[key] ?? fail(name, `\"${key}\" holds a draft, not rows`)) as never,\n /**\n * Whether a submit now could go through: nothing is invalid. A check still\n * running does not stop it; the submit waits for the answer, unless the\n * form was made with `submitWaits: false`, which refuses it.\n */\n canSubmit: (model: Model): boolean => {\n const next = submit(model)\n return next.value !== undefined || next.model.submitPending\n },\n /** Whether a submit was asked since the form started, was filled or was reset. */\n attempted: (model: Model): boolean => model.attempted,\n /**\n * Whether the form is valid right now: a submit now would hand over the\n * value at once. Unlike `canSubmit`, a check running, or one a key has not\n * had yet, is not valid until it answers.\n */\n isValid: (model: Model): boolean => submit(model).value !== undefined,\n /**\n * The decoded input as `Some` only when every key and row is valid as the\n * form stands; `None` otherwise. Unlike `partial`, it is all or nothing,\n * so a parent that submits several forms can read one complete value per\n * form. It validates nothing: reveal drafts first (a submit, or\n * `Message.ValidatedAll()`), or read after one did.\n */\n value: (model: Model): Option.Option<Value> => Option.fromUndefinedOr(finish(model).value),\n /**\n * The Model with nothing in flight, for one that was stored and is shown\n * again: a check that was running when it was stored will never answer, so\n * its key is not validated yet, and no submit is waiting. Rows too.\n */\n settled: (model: Model): Model => ({\n ...model,\n submitPending: false,\n fields: fieldsFrom(plan => {\n const field = drafts(model)[plan.key as Key]\n const held: FieldValidation.Field<Draft> =\n plan.bundled === undefined\n ? field\n : ({\n ...field,\n value: plan.bundled.settled(field.value),\n } as FieldValidation.Field<Draft>)\n return FieldValidation.match(held, {\n onNotValidated: () => held,\n onValidating: value => FieldValidation.NotValidated({ value }),\n onValid: () => held,\n onInvalid: () => held,\n })\n }),\n rows: Object.fromEntries(\n rowsKeys.map(key => [\n key,\n rowsOf(model)[key]!.map(row => ({\n ...row,\n model: nestedPlans[key].form.settled(row.model),\n })),\n ]),\n ) as unknown as Model['rows'],\n }),\n /**\n * What of the form decodes as it stands, by key: the value, less every key\n * that is not valid yet. For saving unfinished work, which `engine.value`\n * cannot give. A nested key is there once each of its rows has a value.\n */\n partial: (model: Model): Partial<Value> => ({\n ...decoded(model),\n ...Object.fromEntries(\n rowsKeys.flatMap(key =>\n Option.match(\n Option.filter(rowsValue(model, key), held => held !== undefined),\n {\n onNone: () => [],\n onSome: held => [[key, held] as const],\n },\n ),\n ),\n ),\n }),\n /** The form as the form that nests it drives it. */\n engine: {\n submit: (model: Model) => {\n const { model: next, commands } = submit(model)\n return { model: next, commands }\n },\n validateAll,\n isValidating,\n /** Whether a transition changed authored content, so a nesting form recurses. */\n authoredChanged,\n /** The decoded input when every key and row is valid as it stands; validates nothing. */\n value: (model: Model): Value | undefined => finish(model).value,\n },\n }\n },\n\n /**\n * Entity metadata: the label of a member that has no schema to annotate (a\n * relation, a derived member). A field is labelled on its schema, with\n * `Schema.String.annotate({ title })`.\n */\n label: (label: string, description?: string) =>\n labelKey.of(description === undefined ? { label } : { label, description }),\n\n /**\n * What `Form.label` attached to an Entity member, for a package that labels\n * the same member elsewhere, such as a table column.\n */\n labelOf: (member: { readonly metadata: Metadata }): string | undefined =>\n labelKey.get(member.metadata)[0]?.label,\n}\n\n/** The type parameters a form was made with. */\ninterface FormTypes {\n readonly Name: string\n readonly E: AnyEntity\n readonly Fields: Schema.Struct.Fields\n readonly Members: any\n readonly R: unknown\n readonly Nest: any\n readonly Inputs: any\n}\n\n/** A form as a pipe step takes it: what it was made from, and its type parameters. */\ninterface Remakeable<T extends FormTypes = FormTypes> {\n readonly name: string\n readonly input: EntityInput<any, any, any>\n readonly options: object\n readonly types: T\n}\n\n/** The form `Form.make` gives for these type parameters. */\ntype Made<T extends FormTypes> = ReturnType<\n typeof Core.make<T['Name'], T['E'], T['Fields'], T['Members'], T['R'], T['Nest'], T['Inputs']>\n>\n\ntype OptionsOf<T extends FormTypes> = FormOptions<T['Fields'], T['Members'], T['R'], T['Nest']>\n\n/** The form again, with some of its options replaced or added to. */\nconst remake = (form: Remakeable, change: (options: Record<string, any>) => object): never =>\n (Core.make as (name: string, input: unknown, options: object) => unknown)(form.name, form.input, {\n ...form.options,\n ...change(form.options as Record<string, any>),\n }) as never\n\n/**\n * Pipe steps. Each gives a new form, made from the same input with one option\n * added to, so a form can be handed over partly configured and finished where it\n * is used: `AuthorForm.pipe(Form.inputs({ bio: Input.multiline() }), Form.messages(german))`.\n */\nconst steps = {\n /** Controls by key, beside the ones the form already names. */\n inputs:\n <F extends Remakeable, const I extends InputsFor<F['types']['Fields'], F['types']['Members']>>(\n inputs: I,\n ) =>\n (\n form: F,\n ): [keyof ControlsOf<I>] extends [never]\n ? F\n : Made<{\n readonly Name: F['types']['Name']\n readonly E: F['types']['E']\n readonly Fields: F['types']['Fields']\n readonly Members: F['types']['Members']\n readonly R: F['types']['R']\n readonly Nest: F['types']['Nest']\n readonly Inputs: Omit<F['types']['Inputs'], keyof I> & I\n }> =>\n remake(form, options => ({ inputs: { ...options.inputs, ...inputs } })),\n\n /** The form's words, beside the ones it already has. */\n messages:\n <F extends Remakeable>(messages: NonNullable<OptionsOf<F['types']>['messages']>) =>\n (form: F): F =>\n remake(form, options => ({ messages: { ...options.messages, ...messages } })),\n\n /** How long a key rests before its check runs. */\n debounce:\n (debounce: Duration.Input) =>\n <F extends Remakeable>(form: F): F =>\n remake(form, () => ({ debounce })),\n\n /**\n * Checks by key, beside the ones the form already has. What they need (`R`) is\n * added to what the form needs.\n */\n checks:\n <F extends Remakeable, const C extends ChecksFor<F>>(checks: C) =>\n (\n form: F,\n ): Made<{\n readonly Name: F['types']['Name']\n readonly E: F['types']['E']\n readonly Fields: F['types']['Fields']\n readonly Members: F['types']['Members']\n readonly R: F['types']['R'] | RequirementOf<C>\n readonly Nest: F['types']['Nest']\n readonly Inputs: F['types']['Inputs']\n }> =>\n remake(form, options => ({ checks: { ...options.checks, ...checks } })),\n\n /** The forms of nested keys, beside the ones the form was already given. */\n nested:\n <\n F extends Remakeable,\n const N extends NestedForms<F['types']['Fields'], F['types']['Members'], F['types']['R']>,\n >(\n forms: N,\n ) =>\n (\n form: F,\n ): Made<{\n readonly Name: F['types']['Name']\n readonly E: F['types']['E']\n readonly Fields: F['types']['Fields']\n readonly Members: F['types']['Members']\n readonly R: F['types']['R']\n readonly Nest: F['types']['Nest'] & N\n readonly Inputs: F['types']['Inputs']\n }> =>\n remake(form, options => ({ nested: { ...options.nested, ...forms } })),\n}\n\nexport const Form = { ...Core, ...steps }\n\nmakeNested = Core.make as never\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA8OA,MAAa,aACX,UACA,WAEA,SAAS,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