The ecosystem · packages/forms
Forms: the rules written once, checked in the browser and at the endpoint
Write a form's rules once, in Roc, as zod does for TypeScript. The browser checks each field as it is typed; the endpoint runs the same code, reading the post into a typed record or refusing it with the same issues. The rules go past what a type can say: lengths, patterns, email addresses, ranges, choices, days, and checks across fields.
Installing it#
Name the package in your app's header, main.roc. rocx gives the browser's half the same packages, so you name it only here. Forms isn't a plugin, so App.program needs nothing.
app [program] { forms: "../packages/forms/main.roc", pf: platform "…" }Then import forms.Form where you write a schema, and import forms.LiveForm and the field components in a .rocx file.
Try it#
Type in a field, then leave it: a failed check shows its issue under the field until the field passes. Send shows every issue at once, with a summary above the form linking to each field. With none left, the demo shows the record the form reads.
This site is static, so the demo sends nothing: it checks in your browser with the code an endpoint would use. In an app, Send posts the form, and the endpoint has the last word.
One schema#
Build a form with Roc's record builder: each field under the name it is posted as, with its checks in order. The record's type is what the form reads: here age is an I64 and terms a Bool. The two passwords are a small form inside it, so the check comparing them runs whenever both can be read, whatever is wrong elsewhere.
Passwords : { password : Str, confirm : Str }
Account : { name : Str, email : Str, age : I64, passwords : FormsSignup.Passwords, terms : Bool }
## A password, typed twice: a form of its own, so the check across the two runs whenever both
## can be read, whatever the rest of the form says.
passwords : Form(FormsSignup.Passwords)
passwords = ({ password: Form.text("password", [Required, MinLength(8), Secret]), confirm: Form.text("confirm", [Required, Secret]) }.Form).check_at("confirm", |p| p.password == p.confirm, NotSame("password"))
## The sign-up form: each field by the name it is posted as, and its checks, in order.
form : Form(FormsSignup.Account)
form = {
name: Form.text("name", [Trim, Required, MaxLength(80)]),
email: Form.text("email", [Trim, Lowercase, Required, Email]),
age: Form.int("age", [Min(18), Max(130)]),
passwords: FormsSignup.passwords,
terms: Form.checkbox("terms", [Required]),
}.FormIn an app, the schema is a module that page and endpoint both import. Its checks are data, so it also gives each input its attributes and describes the form as JSON Schema. form.json_schema(), as this site is built:
{
"type": "object",
"properties": {
"name": {"type":"string","minLength":1,"maxLength":80},
"email": {"type":"string","minLength":1,"format":"email"},
"age": {"type":"integer","minimum":18,"maximum":130},
"password": {"type":"string","minLength":8,"format":"password"},
"confirm": {"type":"string","minLength":1,"format":"password"},
"terms": {"type":"boolean"}
},
"required": [
"name",
"email",
"age",
"password",
"confirm",
"terms"
]
}At the endpoint#
An endpoint reads its body with the same schema. The page's endpoint is under api/ at its path, and its route file names the form beside the handler, whose body is the form's record (D-093):
import pf.Server
import pf.Endpoint
import ../../../Signup
## What POST /api/signup is sent: an account, read and checked by the form.
post_body = Signup.form
post! : { request : Server.Request, params : {}, context : c, body : Signup.Account } => Try({ welcome : Str }, Endpoint.Refusal)
post! = |{ body, .. }| Ok({ welcome: "Welcome, ${body.name}" })The platform reads the fields (URL-encoded, multipart, or a JSON object) with the form and gives post! the account. What doesn't pass never reaches it: the endpoint answers 422 with the issues as JSON (application/json). An unticked box, which a browser doesn't send at all, is the form's to judge. Generated/Api makes the endpoint so in both copies (Endpoint.checked(Endpoint.remote("POST", "/api/signup"), Signup.form)), so a page's submission is read with the form too, and /openapi.json documents the body with the form's schema. A handler refuses what only it can check (a name already taken) with Issues.refusal. This site's handler:
## POST /signup: given the account, read and checked by `form` (its route file's `post_body =
## Signup.form`), as a form or JSON. What doesn't pass never reaches it: the platform refuses it
## with each field's issues (422, JSON), the same the page shows as it is typed.
post! : { request : Server.Request, params : {}, context : c, body : FormsSignup.Account } => Try({ welcome : Str }, Endpoint.Refusal)
post! = |{ body, .. }| Ok({ welcome: "Welcome, ${body.name}" })Sent the body name=&email=ada%40&age=12&password=short&confirm=shirt, it answers (run as this site is built):
422 application/json
[
{"code":"Required","field":"name","message":"Fill this in"},
{"code":"NotEmail","field":"email","message":"Enter an email address, like name@example.com"},
{"code":{"TooSmall":18.0},"field":"age","message":"Enter 18 or more"},
{"code":{"TooShort":8},"field":"password","message":"Use at least 8 characters"},
{"code":{"NotSame":"password"},"field":"confirm","message":"These don't match"},
{"code":"Unchecked","field":"terms","message":"Tick this box to go on"}
]Read back with Issues.from_problem, as a page reads a refusal, the issues are:
| Field | Code | Message |
|---|---|---|
name | required | Fill this in |
email | not_email | Enter an email address, like name@example.com |
age | too_small | Enter 18 or more |
password | too_short | Use at least 8 characters |
confirm | not_same | These don't match |
terms | unchecked | Tick this box to go on |
A body that passes gets the handler's result: 200 {"welcome":"Welcome, Ada"}. So does the same as JSON: 200 {"welcome":"Welcome, Ada"}. Its body in /openapi.json, the form's schema three ways:
{
"application/json": {
"schema": {"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":80},"email":{"type":"string","minLength":1,"format":"email"},"age":{"type":"integer","minimum":18,"maximum":130},"password":{"type":"string","minLength":8,"format":"password"},"confirm":{"type":"string","minLength":1,"format":"password"},"terms":{"type":"boolean"}},"required":["name","email","age","password","confirm","terms"]}
},
"application/x-www-form-urlencoded": {
"schema": {"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":80},"email":{"type":"string","minLength":1,"format":"email"},"age":{"type":"integer","minimum":18,"maximum":130},"password":{"type":"string","minLength":8,"format":"password"},"confirm":{"type":"string","minLength":1,"format":"password"},"terms":{"type":"boolean"}},"required":["name","email","age","password","confirm","terms"]}
},
"multipart/form-data": {
"schema": {"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":80},"email":{"type":"string","minLength":1,"format":"email"},"age":{"type":"integer","minimum":18,"maximum":130},"password":{"type":"string","minLength":8,"format":"password"},"confirm":{"type":"string","minLength":1,"format":"password"},"terms":{"type":"boolean"}},"required":["name","email","age","password","confirm","terms"]}
}
}In the page#
LiveForm holds a form's state in a component: what each field holds, which fields you have left, and whether the form was sent. Make it once, like a signal. The field components take their attributes from the schema (type="email", required, maxlength, min) and say when they are invalid (aria-invalid, aria-describedby). The demo uses a local form, read only by the browser:
view! : FormsDemo.Props => Html
view! = |{ values }| {
live = LiveForm.local_filled!(FormsSignup.form, values)
<div class="forms-demo">
<IssueSummary live={live} title="Fix these, then send it again" labels={FormsDemo.labels} />
<form on:submit={|| live.show_all!()} novalidate>
<TextField live={live} name="name" label="Name" autocomplete="name" />
<TextField live={live} name="email" label="Email" autocomplete="email" />
<TextField live={live} name="age" label="Age" hint="18 or over." />
<TextField live={live} name="password" label="Password" autocomplete="new-password" />
<TextField live={live} name="confirm" label="Password, again" autocomplete="new-password" />
<CheckboxField live={live} name="terms" label="I accept the terms" />
<div class="actions">
<Button submit primary>Send</Button>
<button type="button" class="again" on:click={|| live.reset!()}>Start again</button>
</div>
</form>
<p class="read" aria-live="polite">{if (live.sent!()) FormsDemo.read(FormsSignup.form.parse(live.fields!())) else ""}</p>
</div>
}
## Each field's label, by its name: the fields' and the summary's.
labels : List((Str, Str))
labels = [("name", "Name"), ("email", "Email"), ("age", "Age"), ("password", "Password"), ("confirm", "Password, again"), ("terms", "The terms")]An app's page posts to its endpoint instead: make the live form with LiveForm.of!(Signup.form, Api.post_api_signup({})) and write <form method="post" action={live.url()} novalidate>, with no on:submit. With the runtime, the form is sent in the background; the page stays and shows the endpoint's issues at their fields. Without it, the browser posts the form, and the page comes back with what was typed (passwords aside) and the issues (a submission read from the flash).
An edit form starts filled in: LiveForm.filled!(TaskForm.editing, save, [("title", task.title), ("notes", task.notes)]). From a handler, live.reset!() puts back what the form started with and forgets every issue, keeping the inputs and focus (Start again, in the demo).
The runtime empties a form whose send succeeded: its inputs go back to what the page wrote in them, and the LiveForm starts afresh with them, so an add form is ready for the next, and accepted!() stays true for a "Saved" to show. An edit form that stays on its page after a save says data-rocx-keep on its <form>, to keep what was saved, in its inputs and in the live form alike. examples/tasks has an add form and an edit form.
Values and their checks#
Each kind of value takes checks, run in order, and reports everything wrong, not just the first. A text check other than Required passes an empty value, as a browser's minlength and pattern do: Value.text([Email]) takes "" or an address.
| Value | Reads | Checks |
|---|---|---|
Value.text(checks) | Str, as typed | Trim, Lowercase, CollapseSpaces (each changes the text for the checks after it); Required; MinLength(n), MaxLength(n) (characters); Matches(pattern) (the whole text); Email (as <input type="email"> checks one); Url (http or https); OneOf(options); Secret (a password, never written back into a page) |
Value.int(checks) | I64: 42, -3, +7 | Min(n), Max(n), Step(n) (counted from the Min, or from 0, as a browser's step is) |
Value.dec(checks) | Dec: 2.5, .5; no exponent | Min(x), Max(x), Step(x) |
Value.checkbox(checks) | Bool: sent or not | [Required]: it must be ticked |
Value.choice(options) | what the option stands for: [("free", Free), ("pro", Pro)] | one of them |
Value.date(checks) | a Date: 2026-11-21 | Min("2026-01-01"), Max(…) |
An empty number, choice or day fails as Required. For anything else, .check(ok, code) adds your own check, and .map and .try_map turn the value into another type (a Username, an Isbn) or an issue.
A bad pattern crashes where the value is made. Roc computes top-level values at compile time, so a typo in a top-level form's pattern stops the build instead of reaching a user.
Putting fields together#
| Function | What it does |
|---|---|
Form.text(name, checks), int, dec, checkbox, choice, date | the field posted as name, read as that kind of value |
Form.field(name, value) | the same, for any Value |
Form.optional(name, value) | Err(Missing) when left empty, otherwise read |
Form.list(name, value, [MinItems(n), MaxItems(n)]) | every value posted as name (boxes that share a name); an item's issues at name[i] |
{ a: …, b: … }.Form | the record builder: every field read, all their issues kept |
.check(ok, code), .check_at(field, ok, code) | a check of your own, its issue at the form's own field, or at another one: a check across fields |
.map(f), .try_map(f), .message(text) | what was read, made into another value; its issues with this message |
.parse(fields), .parse_body(body), .issues(fields) | the record, or every issue: from fields (as Server.form_fields reads them) or from a form's body |
.attributes(name), .json_schema() | the attributes a browser checks a field by; the form as JSON Schema |
.names(), .is_list(name), .secrets() | its fields; whether one takes several values; the Secret ones |
Issues#
An issue is { field : Str, code : Issues.Code, message : Str }: where, what, and the English. A code is a plain tag carrying what its message needs, so a translation can match on it or look it up by its key and params (as intl does). Each code and its English, from the package as this site is built:
| Code | Key and params | English |
|---|---|---|
Required | required | Fill this in |
Unchecked | unchecked | Tick this box to go on |
TooShort(8) | too_short (min: 8) | Use at least 8 characters |
TooLong(80) | too_long (max: 80) | Use 80 characters or fewer |
NoMatch("\\d{5}") | no_match (pattern: \d{5}) | Use the format asked for |
NotEmail | not_email | Enter an email address, like name@example.com |
NotUrl | not_url | Enter a web address, like https://example.com |
NotDate | not_date | Enter a date, like 2026-01-31 |
NotOneOf(["free", "pro"]) | not_one_of (options: free, pro) | Choose one of the options |
NotInteger | not_integer | Enter a whole number |
NotNumber | not_number | Enter a number |
TooSmall(18) | too_small (min: 18) | Enter 18 or more |
TooLarge(130) | too_large (max: 130) | Enter 130 or less |
NotStep(15, 20) | not_step (below: 15, above: 20) | Enter 15 or 20, the nearest allowed |
TooEarly("2026-01-01") | too_early (min: 2026-01-01) | Enter 2026-01-01 or later |
TooLate("2026-12-31") | too_late (max: 2026-12-31) | Enter 2026-12-31 or earlier |
TooFew(1) | too_few (min: 1) | Choose at least 1 |
TooMany(3) | too_many (max: 3) | Choose 3 or fewer |
NotSame("password") | not_same (other: password) | These don't match |
Custom("taken", "That name is taken") | taken | That name is taken |
Issues.at(issues, field) picks out a field's issues, and Issues.under a list's, its items' too. Issues.refusal is an endpoint's 422, and Issues.from_problem reads one back from a submission's error!() or an endpoint's send!.
Patterns#
Roc has no regular expressions, so the package has an engine in plain Roc. A pattern compiles once, to a program; a Pike VM runs it over the text, following every possible match at once, one step per character, so no pattern or text can make it slow. The price: no backreferences, no lookaround. The syntax is JavaScript's, so a pattern means the same in an input's pattern attribute: characters and ., classes ([a-z], [^,], \d \w \s), ^ $ \b, groups, |, and * + ? {m,n}. Matched as this site is built:
| Pattern | Text | matches | find |
|---|---|---|---|
\d{2}-\d{3} | 12-345 | yes | "12-345" at 0 |
\d{2}-\d{3} | 12-3456 | no | "12-345" at 0 |
[a-z]+(-[a-z]+)* | roc-solid | yes | "roc-solid" at 0 |
colou?r | colour | yes | "colour" at 0 |
\bcat\b | a cat sat | no | "cat" at 2 |
\d+ | ab 123 45 | no | "123" at 3 |
(a+)+$ | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa! | no | nowhere |
The last row is the classic trap: a backtracking engine (JavaScript's, say) tries hundreds of millions of ways to split those a's into groups before saying no. Here it is one step per character. Regex.compile says what is wrong with a pattern, and where; Regex.must crashes instead, which in a top-level value stops the build.
The components#
rocx copies the components into your app (Generated/forms/), as it does the charts. import forms.TextField imports the copy.
| Component | Props |
|---|---|
<TextField> | live, name, label; hint, type (when the checks don't give one: tel, search), autocomplete |
<CheckboxField> | live, name, label |
<IssueSummary> | live, title: once the form is sent, its issues, each a link to its field; labels, the fields' labels by name, so a link says which field it is about (Name: Fill this in) |
| LiveForm | What it is |
|---|---|
LiveForm.of!(form, endpoint) | a form that posts to endpoint (through Router.use_submission!): the endpoint's issues show at their fields |
LiveForm.filled!(form, endpoint, values) | the same, starting with values typed in, field by field ([("title", task.title)]; a ticked box is ("done", "on")) |
LiveForm.local!(form), local_filled!(form, values) | a form that posts nowhere, checked as it is typed, for an on:submit handler to read |
live.reset!(), accepted!() | from a handler, start afresh where it is, issues forgotten; whether the endpoint accepted what was last sent (the live form starts afresh as the runtime empties the form then) |
live.value!(name), input!(name, value), leave!(name) | what a field holds; for on:input.value; for on:blur |
live.issues!(name), invalid!(name), all_issues!() | the issues to show now: a field's once it is left, every field's once the form is sent |
live.show_all!(), fields!(), url() | show every issue from now on; what is typed, for form.parse; the form's action |
Colours come from --form-invalid, --form-border, --form-muted and --form-radius; the demo sets them from this site's tokens. The package's README lists every function, and when each issue shows.
Not yet#
Everything above works today; roc test packages/forms/main.roc runs the package's expects. Waiting on proposals in packages/forms/PROPOSALS.md:
- The platform's own refusal with field issues (RFC 9457 problem details). Today it is a
422with the issues' JSON (application/json), whichIssues.from_problemreads back. - Holding back a send in the browser when the form has issues. Today it always reaches the endpoint, which refuses it with the same issues.
And for now: decimals use a .; patterns have no flags or captures; form.parse_body(text) (for a page holding a form's text) reads URL-encoded only (the platform reads an endpoint's body for the form, JSON too). LiveForm shows a 422's issues; another refusal (a 403, a 500) is the submission's error!() to show.
The demo: site/Demos/FormsDemo.rocx
import pf.Html
import forms.LiveForm
import forms.TextField
import forms.CheckboxField
import forms.IssueSummary
import ../Ui/Button
import FormsSignup
## The forms page's demo: `FormsSignup.form`, checked in the browser as it is typed, by the same
## code its endpoint reads it with. The site is static files, with no endpoint to send it to, so it
## is a local form (`LiveForm.local_filled!`): Send shows every issue, or, once there are none, what
## the form reads; Start again goes back to what it started with (`reset!`). An app's page posts
## it instead (`LiveForm.of!(form, endpoint)`). `values` fills it in to start with.
FormsDemo := [].{
Props := { values : List((Str, Str)) ?? [] }
view! : FormsDemo.Props => Html
view! = |{ values }| {
live = LiveForm.local_filled!(FormsSignup.form, values)
<div class="forms-demo">
<IssueSummary live={live} title="Fix these, then send it again" labels={FormsDemo.labels} />
<form on:submit={|| live.show_all!()} novalidate>
<TextField live={live} name="name" label="Name" autocomplete="name" />
<TextField live={live} name="email" label="Email" autocomplete="email" />
<TextField live={live} name="age" label="Age" hint="18 or over." />
<TextField live={live} name="password" label="Password" autocomplete="new-password" />
<TextField live={live} name="confirm" label="Password, again" autocomplete="new-password" />
<CheckboxField live={live} name="terms" label="I accept the terms" />
<div class="actions">
<Button submit primary>Send</Button>
<button type="button" class="again" on:click={|| live.reset!()}>Start again</button>
</div>
</form>
<p class="read" aria-live="polite">{if (live.sent!()) FormsDemo.read(FormsSignup.form.parse(live.fields!())) else ""}</p>
</div>
}
## Each field's label, by its name: the fields' and the summary's.
labels : List((Str, Str))
labels = [("name", "Name"), ("email", "Email"), ("age", "Age"), ("password", "Password"), ("confirm", "Password, again"), ("terms", "The terms")]
## What the form reads, as Roc writes the record (its passwords left out); nothing while it has
## issues, which the fields show.
read : Try(FormsSignup.Account, List(_)) -> Str
read = |parsed|
match parsed {
Ok(account) => "It reads: { name: \"${account.name}\", email: \"${account.email}\", age: ${account.age.to_str()}, terms: Bool.True, passwords: … }"
Err(_) => ""
}
<story name="Empty">
<FormsDemo />
</story>
<story name="Filled in">
<FormsDemo values={[("name", "Ada Lovelace"), ("email", "ada@example.com"), ("age", "36"), ("terms", "on")]} />
</story>
<style>
/* The package's colours, from the site's tokens: its own red is for a light page. */
.forms-demo {
--form-invalid: var(--bad);
--form-border: var(--rule-strong);
--form-muted: var(--text-muted);
--form-radius: var(--radius-sm);
max-width: 30rem;
}
.forms-demo :global(input:not([type="checkbox"])) {
background: var(--fill);
color: var(--text);
}
.actions {
display: flex;
gap: var(--space-2);
}
/* As the site's quiet buttons look (Ui/Button), for one that runs a handler. */
.again {
padding: var(--space-2) var(--space-5);
border: 0;
border-radius: var(--radius);
background: var(--fill);
color: var(--text);
font: inherit;
font-weight: 600;
cursor: pointer;
}
.again:hover {
background: var(--fill-strong);
}
.read {
margin: var(--space-4) 0 0;
color: var(--good);
font-family: var(--mono);
font-size: var(--size-sm);
overflow-wrap: anywhere;
}
.read:empty {
display: none;
}
</style>
}A form's state: packages/forms/components/LiveForm.rocx
import pf.Solid exposing [create_effect!, create_memo!, create_signal!]
import pf.Router exposing [use_submission!]
import pf.Endpoint
import pf.Server
import forms.Form
import forms.Value
import forms.Issues
## A form in a component, checked as it is typed, with the same `Form` its endpoint reads it
## with: what is typed in each field, which fields were left, whether it was sent, and what the
## endpoint refused, and from those, the issues to show at each field.
##
## live = LiveForm.of!(Signup.form, Api.post_api_signup({}))
## <form method="post" action={live.url()} novalidate>
## <TextField live={live} name="email" label="Email" />
## </form>
##
## A field's issues show once it has been left (`leave!`, on blur), and then as it is typed; all of
## them once the form has been sent. The endpoint's issues show at their fields until a field is
## typed in again, the browser's own from then on. The form goes to the endpoint whatever the
## browser thinks of it (the endpoint has the last word, and refuses with the same issues), with
## the runtime as without it (`Router.use_submission!`): after a plain post the endpoint refused,
## what was typed and the endpoint's issues come back with the page.
##
## An edit form starts filled in (`filled!`, with the record's values), and any form can start
## afresh (`reset!`). Once the endpoint has accepted what the runtime sent, the runtime empties the
## form's inputs (D-122), and the live form starts afresh with them (`Submission.emptied!`), so an
## add form is ready for the next; a form that says `data-rocx-keep` (an edit form that stays on
## its page) keeps what was typed, in its inputs and here alike.
LiveForm := {
url : Str,
check : List({ name : Str, value : Str }) -> List(Issues.Issue),
attributes_of : Str -> Value.Attributes,
typed : () => List({ name : Str, value : Str }),
set_typed : List({ name : Str, value : Str }) => {},
left : () => List(Str),
set_left : List(Str) => {},
sent : () => Bool,
set_sent : Bool => {},
edited : () => List(Str),
set_edited : List(Str) => {},
refused : () => List(Issues.Issue),
pending : () => Bool,
accepted : () => Bool,
reset : () => {},
}.{
## The live form for `form`, which posts to `endpoint`, empty. Call it in a component, as a
## signal is made: once.
of! : Form(a), Endpoint(context, arg, result) => LiveForm
of! = |form, endpoint| LiveForm.filled!(form, endpoint, [])
## The live form for `form`, which posts to `endpoint`, starting with `values` typed in, field
## by field: an edit form's record as it is now. A box ticked is `("done", "on")`; leave out one
## that isn't. After a plain post the endpoint refused, what was typed shows instead.
##
## live = LiveForm.filled!(TaskForm.editing, save, [("title", task.title), ("notes", task.notes)])
filled! : Form(a), Endpoint(context, arg, result), List((Str, Str)) => LiveForm
filled! = |form, endpoint, values| {
submission = use_submission!(endpoint)
action = Endpoint.url_of(endpoint)
start = LiveForm.starting(values, Err(NoFlash), action, [])
first = LiveForm.starting(values, Server.flash!({}), action, form.secrets())
(typed!, set_typed!) = create_signal!(first.typed)
(left!, set_left!) = create_signal!([])
(was_sent!, set_sent!) = create_signal!(first.sent)
(edited!, set_edited!) = create_signal!([])
# Whether the runtime has sent it since it was made, or last started afresh.
(sending!, set_sending!) = create_signal!(Bool.False)
refused! = create_memo!(
||
match submission.error!() {
Ok(problem) => Issues.from_problem(problem)
Err(NoError) => []
},
)
waiting! = || submission.pending!()
# Emptied by the runtime once the endpoint accepted it (D-122): afresh, as its inputs are, the
# answer kept (`accepted!`). One that keeps what was typed (`data-rocx-keep`) keeps it here too.
create_effect!(
|| submission.emptied!(),
|emptied|
if emptied {
set_typed!(start.typed)
set_left!([])
set_sent!(Bool.False)
set_edited!([])
} else {
{}
},
)
# Sent with the runtime: every issue shows, and the endpoint's answer is the latest word.
create_effect!(
waiting!,
|pending|
if pending {
set_sent!(Bool.True)
set_edited!([])
set_sending!(Bool.True)
} else {
{}
},
)
{
url: action,
check: |posted| form.issues(posted),
attributes_of: |name| form.attributes(name),
typed: typed!,
set_typed: set_typed!,
left: left!,
set_left: set_left!,
sent: was_sent!,
set_sent: set_sent!,
edited: edited!,
set_edited: set_edited!,
refused: refused!,
pending: waiting!,
accepted: || sending!() and !submission.pending!() and submission.error!().is_err(),
reset: || {
set_typed!(start.typed)
set_left!([])
set_sent!(Bool.False)
set_edited!([])
set_sending!(Bool.False)
# The endpoint's answer, and a plain post's flash, forgotten.
submission.clear!()
},
}
}
## A live form that posts nowhere: checked as it is typed, as `of!`'s is, with no endpoint. For
## a form whose `on:submit` handler shows every issue (`show_all!`) and reads what is typed
## (`form.parse(live.fields!())`): one it sends itself (its endpoint's `send!(arg)`), or one only
## the browser reads. Its `url()` is `""`.
local! : Form(a) => LiveForm
local! = |form| LiveForm.local_filled!(form, [])
## A live form that posts nowhere, starting with `values` typed in, as `filled!`'s does.
local_filled! : Form(a), List((Str, Str)) => LiveForm
local_filled! = |form, values| {
start = LiveForm.starting(values, Err(NoFlash), "", []).typed
(typed!, set_typed!) = create_signal!(start)
(left!, set_left!) = create_signal!([])
(was_sent!, set_sent!) = create_signal!(Bool.False)
(edited!, set_edited!) = create_signal!([])
{
url: "",
check: |posted| form.issues(posted),
attributes_of: |name| form.attributes(name),
typed: typed!,
set_typed: set_typed!,
left: left!,
set_left: set_left!,
sent: was_sent!,
set_sent: set_sent!,
edited: edited!,
set_edited: set_edited!,
refused: || [],
pending: || Bool.False,
accepted: || Bool.False,
reset: || {
set_typed!(start)
set_left!([])
set_sent!(Bool.False)
set_edited!([])
},
}
}
## What a form posting to `action` starts with: what was typed in a plain post the endpoint
## refused (the flash), its secrets left out to be typed again, and sent, so its issues show; or,
## with no such flash (none, another form's, or one the endpoint accepted), `values`, field by
## field, not sent.
starting : List((Str, Str)), Try(Server.Flash, [NoFlash]), Str, List(Str) -> { typed : List({ name : Str, value : Str }), sent : Bool }
starting = |values, flash, action, secrets|
match flash {
Ok(flashed) =>
if flashed.url == action and flashed.status != 200 {
{ typed: flashed.fields.drop_if(|field| secrets.contains(field.name)), sent: Bool.True }
} else {
{ typed: values.map(|(name, value)| { name, value }), sent: Bool.False }
}
Err(NoFlash) => { typed: values.map(|(name, value)| { name, value }), sent: Bool.False }
}
## Starts afresh, from a handler: what it started with typed in again (`filled!`'s values;
## nothing, for `of!`'s), no field left, not sent, and the endpoint's answer forgotten, so no
## issue shows. The inputs stay where they are, focus too.
reset! : LiveForm => {}
reset! = |live| {
reset_it! = live.reset
reset_it!()
}
## Whether the endpoint accepted what the runtime last sent (answered with its result, not a
## refusal), until the form starts afresh with `reset!`: a "Saved" to show. The runtime empties
## the form's inputs then, and the live form starts afresh with them, keeping this (D-122); an
## edit form that stays on its page says `data-rocx-keep`, and keeps what was typed.
##
## <p aria-live="polite">{if (live.accepted!()) "Saved." else ""}</p>
accepted! : LiveForm => Bool
accepted! = |live| {
was_accepted! = live.accepted
was_accepted!()
}
## Every field's issues show from now on, as after a send: from a form's `on:submit` (which
## the runtime doesn't send), before the handler reads it.
show_all! : LiveForm => {}
show_all! = |live| {
set_sent! = live.set_sent
set_sent!(Bool.True)
}
## What is typed, as the form would post it: `form.parse(live.fields!())` reads it in a handler.
fields! : LiveForm => List({ name : Str, value : Str })
fields! = |live| {
typed! = live.typed
typed!()
}
## The URL the form posts to: its `action`.
url : LiveForm -> Str
url = |live| live.url
## What a browser's constraint attributes say of the field `name` (`Value.Attributes`).
attributes : LiveForm, Str -> Value.Attributes
attributes = |live, name| {
of = live.attributes_of
of(name)
}
## What is typed in the field `name`: its value, or `""`.
value! : LiveForm, Str => Str
value! = |live, name| {
typed! = live.typed
match typed!().find_first(|field| field.name == name) {
Ok(found) => found.value
Err(_) => ""
}
}
## Every value of the field `name` (a list's: checkboxes that share a name).
values! : LiveForm, Str => List(Str)
values! = |live, name| {
typed! = live.typed
typed!().keep_if(|field| field.name == name).map(|field| field.value)
}
## Whether the box `name` is ticked: with `value`, for one of several boxes that share a name.
checked! : LiveForm, Str, Str => Bool
checked! = |live, name, value| LiveForm.values!(live, name).contains(value)
## From a field's `on:input.value`: what is typed in it now.
input! : LiveForm, Str, Str => {}
input! = |live, name, value| {
typed! = live.typed
set_typed! = live.set_typed
set_typed!(typed!().drop_if(|field| field.name == name).append({ name, value }))
LiveForm.edit!(live, name)
}
## From a box's `on:change.checked`: ticked with `value` (`"on"` for a lone box) or not.
toggle! : LiveForm, Str, Str, Bool => {}
toggle! = |live, name, value, ticked| {
typed! = live.typed
set_typed! = live.set_typed
others = typed!().drop_if(|field| field.name == name and field.value == value)
set_typed!(if (ticked) others.append({ name, value }) else others)
LiveForm.edit!(live, name)
}
## From a field's `on:blur`: it has been left, so its issues show from now on.
leave! : LiveForm, Str => {}
leave! = |live, name| {
left! = live.left
set_left! = live.set_left
if !left!().contains(name) {
set_left!(left!().append(name))
}
}
## The issues to show at the field `name` now: the endpoint's, until it is typed in again; and
## the browser's, once it has been left or the form sent. Its items' too (`tags[1]`).
issues! : LiveForm, Str => List(Issues.Issue)
issues! = |live, name| {
typed! = live.typed
left! = live.left
was_sent! = live.sent
edited! = live.edited
refused! = live.refused
check = live.check
field = base_name(name)
server = if (edited!().contains(field)) [] else Issues.under(refused!(), name)
shown = was_sent!() or left!().contains(field)
browser = if (shown) Issues.under(check(typed!()), name) else []
server.concat(browser.drop_if(|issue| server.any(|said| said.field == issue.field and said.code == issue.code)))
}
## Whether the field `name` has issues to show: what its `aria-invalid` says.
invalid! : LiveForm, Str => Bool
invalid! = |live, name| !LiveForm.issues!(live, name).is_empty()
## Every issue to show, field by field, and the form's own (at `""`) first: for a summary above
## the form.
all_issues! : LiveForm => List(Issues.Issue)
all_issues! = |live| {
typed! = live.typed
check = live.check
refused! = live.refused
fields = [""].concat(check(typed!()).concat(refused!()).map(|issue| issue.field))
names = fields.fold([], |kept, field| if (kept.contains(field)) kept else kept.append(field))
var $shown = []
for field in names {
$shown = $shown.concat(LiveForm.issues!(live, field).keep_if(|issue| issue.field == field))
}
$shown
}
## Whether the form has been sent (with the runtime, or posted and come back): every issue
## shows from then on.
sent! : LiveForm => Bool
sent! = |live| {
was_sent! = live.sent
was_sent!()
}
## The `id` of the field `name`'s input (`field-email`), which its label and a summary's link
## point at; a list item's is its list's.
field_id : Str -> Str
field_id = |name| "field-${base_name(name)}"
## Whether the form is on its way to the endpoint.
pending! : LiveForm => Bool
pending! = |live| {
waiting! = live.pending
waiting!()
}
## A field typed in: the endpoint's issues there no longer stand.
edit! : LiveForm, Str => {}
edit! = |live, name| {
edited! = live.edited
set_edited! = live.set_edited
if !edited!().contains(name) {
set_edited!(edited!().append(name))
}
}
}
## A list item's field (`tags[1]`) as the list's (`tags`): the name its inputs share.
base_name : Str -> Str
base_name = |field|
match field.split_first("[") {
Ok({ before, .. }) => before
Err(_) => field
}
expect LiveForm.starting([("title", "Buy milk"), ("done", "on")], Err(NoFlash), "/tasks/1", []).typed == [{ name: "title", value: "Buy milk" }, { name: "done", value: "on" }]
expect !LiveForm.starting([("title", "Buy milk")], Err(NoFlash), "/tasks/1", []).sent
expect LiveForm.starting([("title", "Buy milk")], Ok({ url: "/tasks/1", fields: [{ name: "title", value: "" }, { name: "password", value: "hunter2" }], status: 422, body: "[]" }), "/tasks/1", ["password"]) == { typed: [{ name: "title", value: "" }], sent: Bool.True }
expect LiveForm.starting([("title", "Buy milk")], Ok({ url: "/tasks/1", fields: [{ name: "title", value: "Buy bread" }], status: 200, body: "\"1\"" }), "/tasks/1", []) == { typed: [{ name: "title", value: "Buy milk" }], sent: Bool.False }
expect LiveForm.starting([], Ok({ url: "/lists/2", fields: [{ name: "title", value: "Elsewhere" }], status: 422, body: "[]" }), "/tasks/1", []) == { typed: [], sent: Bool.False }A field: packages/forms/components/TextField.rocx
import pf.Html
import LiveForm
## A field of a `LiveForm` to type in: its label, its input, and its issues under it. The input
## has the attributes its value's checks give a browser (`type="email"`, `required`, `minlength`,
## `pattern`, `min`…), so a browser without the runtime checks it the same way, and it says when it
## is invalid (`aria-invalid`) and where why is written (`aria-describedby`), which a screen reader
## reads with it. The form's `novalidate` leaves the saying to these.
##
## <TextField live={live} name="email" label="Email" autocomplete="email" />
##
## `hint` is said under the label (and read with the input); `type` is the input's own, for one its
## checks don't give (`tel`, `search`); `autocomplete`, what a browser may fill it with. A `Secret`
## (a password) is never written back into the page: a refused post's flash leaves it out, and what
## is typed is the input's own already (the package writes its `value` only when the form starts
## afresh).
TextField := [].{
Props := { live : LiveForm, name : Str, label : Str, hint : Str ?? "", type : Str ?? "", autocomplete : Str ?? "" }
view! : TextField.Props => Html
view! = |{ live, name, label, hint, type, autocomplete }| {
id = LiveForm.field_id(name)
said = "${id}-issues"
told = "${id}-hint"
attributes = live.attributes(name)
described! = || Str.join_with([if (hint.is_empty()) "" else told, if (live.invalid!(name)) said else ""].keep_if(|part| !part.is_empty()), " ")
<div class="field" class:invalid={live.invalid!(name)}>
<label for={id}>{label}</label>
<p id={told} class="hint" hidden?={hint.is_empty()}>{hint}</p>
<input
id={id}
name={name}
type={if (type.is_empty()) attributes.type else type}
autocomplete??={autocomplete}
value={live.value!(name)}
required?={attributes.required}
minlength??={attributes.minlength}
maxlength??={attributes.maxlength}
pattern??={attributes.pattern}
min??={attributes.min}
max??={attributes.max}
step??={attributes.step}
aria-invalid={if (live.invalid!(name)) "true" else "false"}
aria-describedby??={described!()}
on:input.value={|typed| live.input!(name, typed)}
on:blur={|| live.leave!(name)}
/>
<ul id={said} class="issues" aria-live="polite">
{...live.issues!(name).map(|issue|
<li key={issue.message}>{issue.message}</li>
)}
</ul>
</div>
}
<style>
.field {
display: grid;
gap: 0.25rem;
margin-block: 0 0.5rem;
}
label {
font-weight: 600;
}
.hint {
margin: 0;
color: var(--form-muted, color-mix(in srgb, currentColor 65%, transparent));
}
input {
font: inherit;
padding: 0.4rem 0.5rem;
border: 1px solid var(--form-border, color-mix(in srgb, currentColor 40%, transparent));
border-radius: var(--form-radius, 4px);
}
.invalid input {
border-color: var(--form-invalid, #b3261e);
}
/* A line kept for an issue: one that shows as the field is left (on a press of Send, say)
moves nothing under it, so the press still lands where it was aimed. */
.issues {
min-height: 1lh;
margin: 0;
padding: 0;
list-style: none;
color: var(--form-invalid, #b3261e);
}
</style>
}