Form / foldkit-form
Controls
A control is pure data: a kind, the draft kept in the Model, and kind
metadata.
| Kind | Draft | Chosen when |
|---|---|---|
Text, Multiline | string | Schema is a string (Multiline when opted in) |
Hidden | string | Opted in for non-visible keys such as id |
Number | string | Schema is a number |
Toggle | boolean | Schema is a boolean |
Select | string | Union of string/number literals; submits the chosen literal |
Choices | string[] | Array of string/number literals; submits chosen literals |
RelationOne | string ("" when empty) | Key is Relation.input of a one relation |
RelationMany | string[] | Key is Relation.input of a many relation |
Control resolution runs from most explicit to least explicit:
inputspassed toForm.make(for this form only).Input.of(control)metadata on the Entity member (everywhere that member is used).- The relation mapped by the key.
- The shape of the key's schema.
Unknown schemas throw with the key name when Form.make runs.
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:
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'draftis'text','flag', or'list'.parseconverts'text'drafts before schema validation (parseListdoes the same for'list'drafts); returningundefinedreportsunparsed. Whitespace-only text counts as empty rather than unparsed.formatturns a stored value back into'text'duringfill(leaving live typing untouched); throwing insideformatfails thefill, naming the key.- Hooks unreachable for the chosen
drafttype fail at compile time. shown: falsehides the control from rendered field lists (likeHidden), and custom kinds render throughfoldkit-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:
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
Controlviacolor.send. Only Messages that changevalue(model)trigger validation, clear submit marks, and flipauthoredChanged; 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, andResetdelegate throughvalue,fill, andsettled. - In-flight control work (
busy): passbusy: model => model.sendingwhen a control runs uploads or lookups. Submitting while busy waits (Validating) untilbusyclears, then validates and submits. Controls withbusyalso requiresettledso restored models settle cleanly. - Empty values and types: returning
undefinedornullfromvaluetriggersRequiredon required keys.model.fields.color.valueis typed as the picker's Model, andcolor.sendaccepts only the picker's Messages. - Constraints: control Bundles omit
OutMessageand command service requirements, validate via schema rather thancheck, 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):
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
fillwith a non-empty value for the dependent key keeps it detached (preserving published slugs). - Cycles and references to non-text keys throw when
Form.makeruns.
A picker that searches
Add Input.search() to hold search text for large relation pickers without
modifying the selected ID or running validation:
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.