Form / foldkit-form

Controls

A control is pure data: a kind, the draft kept in the Model, and kind metadata.

KindDraftChosen when
Text, MultilinestringSchema is a string (Multiline when opted in)
HiddenstringOpted in for non-visible keys such as id
NumberstringSchema is a number
TogglebooleanSchema is a boolean
SelectstringUnion of string/number literals; submits the chosen literal
Choicesstring[]Array of string/number literals; submits chosen literals
RelationOnestring ("" when empty)Key is Relation.input of a one relation
RelationManystring[]Key is Relation.input of a many relation

Control resolution runs from most explicit to least explicit:

  1. inputs passed to Form.make (for this form only).
  2. Input.of(control) metadata on the Entity member (everywhere that member is used).
  3. The relation mapped by the key.
  4. The shape of the key's schema.

Unknown schemas throw with the key name when Form.make runs.

ts
import { Form, Input } from 'foldkit-form'

const Cms = Post.pipe(Entity.annotateMembers({ title: Input.of(Input.multiline()) }))

Form.make('Rename', Entity.input(Cms, RenameInput), { inputs: { id: Input.text() } })

Keys holding an ID without an Entity relation can request a picker via Input.relationOne(Author) or Input.relationMany(Tag). Unbounded literal arrays like Schema.Array(Schema.Number) take options via Input.choices([1, 2]). Select and Choices store drafts as strings and reject collisions where two values format identically (such as '1' and 1).

Your own kind of control

Custom kinds such as prices or date pickers are built with Input.kind:

ts
const Cents = Input.kind<{ readonly currency: string }>('Cents', {
  draft: 'text', // what the Model holds while it is edited
  // The value the schema is given, when that is not the text itself.
  parse: draft => (/^\d+(\.\d{1,2})?$/.test(draft) ? Math.round(Number(draft) * 100) : undefined),
  // The text a value is shown as when the form is filled with it, the inverse
  // of `parse`. Without it, a filled value shows as `String(value)`.
  format: (value, data) => (Number(value) / 100).toFixed(2),
  unparsed: 'Enter an amount',
})

const Price = Form.make('Price', input, { inputs: { cents: Cents.of({ currency: 'USD' }) } })

const { control } = Price.controlsByKey.cents
Cents.is(control) && control.data.currency // 'USD'
  • draft is 'text', 'flag', or 'list'.
  • parse converts 'text' drafts before schema validation (parseList does the same for 'list' drafts); returning undefined reports unparsed. Whitespace-only text counts as empty rather than unparsed.
  • format turns a stored value back into 'text' during fill (leaving live typing untouched); throwing inside format fails the fill, naming the key.
  • Hooks unreachable for the chosen draft type fail at compile time.
  • shown: false hides the control from rendered field lists (like Hidden), and custom kinds render through foldkit-mixins-form.

A control with a Model of its own

Rich controls — a color picker with an open popover, a page builder with selection and undo, or a rich-text editor — wrap an ordinary Bundle with Input.bundle:

ts
const ColorInput = Input.bundle('ColorPicker', {
  bundle: ColorPicker, // Model { open, hex, recent }, its own Messages, a Command, a Subscription
  value: model => model.hex, // what the key validates and submits
  fill: (model, hex) => ({ ...model, hex }), // a value the form was given, written into the Model
  settled: model => ({ ...model, open: false }), // a stored form shown again: nothing in flight
})

const PostForm = Form.make('PostForm', input, { inputs: { color: ColorInput } })
const color = PostForm.control('color')

color.field(PostForm.initial) // { _tag, value: { open, hex, recent } }: validation state, the Model as value
color.send(ColorMessage.Opened()) // the form's Message carrying one of the picker's own
  • Messaging and edits: control Messages travel through Control via color.send. Only Messages that change value(model) trigger validation, clear submit marks, and flip authoredChanged; UI-only changes such as opening a popover keep validation and dirty state clean.
  • Effects and lifecycle: Commands, Subscriptions, and Managed Resources lift into the parent form keyed by the control (ColorPicker@fields.color/…). fill, partial, settled, submit, and Reset delegate through value, fill, and settled.
  • In-flight control work (busy): pass busy: model => model.sending when a control runs uploads or lookups. Submitting while busy waits (Validating) until busy clears, then validates and submits. Controls with busy also require settled so restored models settle cleanly.
  • Empty values and types: returning undefined or null from value triggers Required on required keys. model.fields.color.value is typed as the picker's Model, and color.send accepts only the picker's Messages.
  • Constraints: control Bundles omit OutMessage and command service requirements, validate via schema rather than check, and omit Subscriptions and Resources inside nested row forms.

A key that follows another

Use Input.following when one field derives from another until edited manually (such as a URL slug following a title):

ts
const SlugForm = Form.make('SlugForm', input, {
  inputs: { slug: Input.following('title', slugify) },
})

SlugForm.isFollowing(SlugForm.initial, 'slug') // false once the author has written it
SlugForm.partial(SlugForm.initial) // what decodes as it stands, by key: for saving unfinished work
SlugForm.settled(SlugForm.initial) // a stored Model, shown again with no check or submit in flight
SlugForm.Message.Refused({ key: 'slug', error: 'That address is taken', value: 'hello' }) // a server's word on the value sent
  • Until the user edits the dependent key, edits to the source key rewrite and validate it automatically (suppressing premature errors while empty until submit).
  • Editing the dependent key detaches it; clearing it back to empty resumes following.
  • Calling fill with a non-empty value for the dependent key keeps it detached (preserving published slugs).
  • Cycles and references to non-text keys throw when Form.make runs.

A picker that searches

Add Input.search() to hold search text for large relation pickers without modifying the selected ID or running validation:

ts
const EditPost = Form.make('EditPost', input, { inputs: { authorId: Input.search() } })

const searched = EditPost.Message.Searched({ key: 'authorId', text: 'ad' })
const { model } = EditPost.bundle.update(EditPost.initial, searched, undefined)
EditPost.search(model, 'authorId') // 'ad'

Your application feeds Form.search(model, key) into the query listing picker choices. fill and Reset clear the search text. Applying Input.search() to a non-relation key throws.

Labels

Labels and descriptions come from Effect Schema's annotate({ title, description }) (checking the input key's schema first, then the Entity field's) or Form.label('Author', 'Who wrote it') on relations, falling back to the key name.