Field unstable
Groups a form control, or a group of them, with its label, description and error message, and reports whether the control is invalid, touched or focused on each of them. The label names the control, and the control points at the description and the error, without the consumer writing an id.
Field is a headless component: it keeps whether its control has focus
and whether it was ever left, and generates the ids.
Anatomy
| Part | Element |
|---|---|
root |
any element, usually a <div> |
label |
<label> |
control |
<input>, <textarea>, <select> or <button> |
legend |
any element, the group's visible name |
group |
any element, around the group's controls |
focusWithin |
any element, around a control and its popup |
member |
<input>, <textarea>, <select> or <button> |
description |
any element, usually a <p> |
error |
any element, usually a <div> |
Each part takes the consumer's builder and returns it, so the consumer
goes on chaining and adds children with .children(...):
field.root(h.div).children(field.label(h.label).children("Name"), field.control(h.input)).
No part adds markup.
control's result is still a builder, so it is another kit call's
element, and both share one element:
Input(h, { element: field.control(h.input), props }) for a text input,
checkbox.root(field.control(h.button)) for a checkbox and
parts.root(field.control(h.button)) for a switch.
A field takes one of three shapes:
- one
controland alabel - a
groupofmembers and alegend, for a control made of several focusable elements, such as a range slider's thumbs, or for a set of controls, such as checkboxes. For a range slider, draw the slider's root withslider.root(field.group(h.div))and each thumb's input withfield.member(h.input) - a
focusWithinwrapper with amembertrigger, for a single control whose focus moves into a popup, such as a select or a combobox. Wrap the trigger and the popup's positioner infield.focusWithin(h.div)(or combine it with the root,field.root(field.focusWithin(h.div))) and draw the trigger withfield.member
error returns undefined unless the field is invalid and enabled, so
write field.error(h.div)?.children(message). The message is the consumer's:
validate in update, pass the outcome as invalid and the text as the
error's children. The error has role="alert" for live-region updates.
Submitting again with unchanged text and focus creates no new alert.
Chain .attr("role", undefined) after the part to remove the alert role.
Data attributes
On every part, each present with an empty value or absent:
data-disableddata-invalid/data-valid, neither whileinvalidis left outdata-touched: the control, the group or thefocusWithinwrapper has lost focus at least oncedata-focused: the control, or an element inside the group or thefocusWithinwrapper, has focusdata-dirtydata-filled
Keyboard
Field adds no key handler. The control keeps its own keyboard.
Usage
A view that renders more than one field gives each a key. A component
drawn inside a field's view, such as a checkbox, is that field's
child, so it needs no key of its own.
The control can't tell whether a description was drawn, so say so with
the described prop. description fails the render without it.
With it, draw the description, or the control points at an id nothing
has. The same goes for the error: while the field is invalid and
enabled the control points at the error's id, so draw error in every
field that can be invalid.
A disabled field disables its control, which then submits nothing. A
control's own parts don't hear of it: pass disabled: field.disabled to a
checkbox whose indicator shows data-disabled.
A field inside a Fieldset is disabled while the fieldset is, with
nothing passed to it, and field.disabled says so. Use a Fieldset for
several fields under one legend, each with its own label and error. One
value with one error is a single field with a group, and
field.group(h.fieldset) draws that group as a native fieldset.
In a group, the legend names the group and each member keeps its own
name, from a wrapping <label> or an aria-label. Draw the legend, or
the group points at an id nothing has. The description and the error
are read on each member, where focus lands.
A field drawn with focusWithin draws neither field.label nor
field.legend: the control's own label part names it, and focusWithin
and field.member write no id and no aria-labelledby. Drawing
field.label would point for at an id nothing has.
In a group or focusWithin, focus moving inside neither touches the
field nor drops its focus. Focus leaving the window counts as leaving it,
as it counts as leaving a single control. An element between group or
focusWithin and a focusable descendant that handles focusin or
focusout itself hides them from the field, because only the innermost
handler gets a bubbling event.
touched and focused are the field's own. Give the field another
key to start over, such as after the form is reset.
With Validation
When a form validates with Validation from effect/ui, spread
fieldValidationProps into props to map a Validation.Field to
invalid and filled:
Field(h, { props: { ...fieldValidationProps(state), disabled }, view }).
The mode given to Validation.make decides when a field shows its
error. For const Signup = Validation.make(fields, { mode: "onBlur" }),
send a message from the control's blur handler and call
Signup.blur(state, name) in update. That touched state is separate
from data-touched, which ignores a blur caused by disabling the control.
Example A labelled, described name field
import { UiSchema } from "effect/ui"import { Html, HtmlServer } from "effect/ui/html"import { Field, Input } from "effect/ui/kit"import { Effect, Schema } from "effect"
const ProfileMessage = UiSchema.TaggedEnum({ UpdatedName: { value: Schema.String } })
const Profile = Html.component({ name: "Profile", model: Schema.Struct({ name: Schema.String }), message: ProfileMessage}).make({ init: () => ({ name: "" }), update: { UpdatedName: ($, { value }) => $.evolve({ name: value }) }, view: (h, model) => Field(h, { props: { invalid: model.name === "", filled: model.name !== "", described: true }, view: (field) => field.root(h.div.class("field")).children( field.label(h.label).children("Name"), Input(h, { element: field.control(h.input), props: { value: model.name }, onUpdate: ({ value }) => ProfileMessage.UpdatedName({ value }) }).attr("name", "name"), field.description(h.p).children("Visible on your profile"), field.error(h.div)?.children("Enter your name") ) })})
// The label points at the input, which is marked invalid.const { html } = await Effect.runPromise(HtmlServer.renderToHtml(Profile, {}))if (!/<label [^>]*for="([^"]+)"[^>]*>Name<\/label><input [^>]*id="\1"[^>]* aria-invalid="true"/.test(html)) { throw new Error("the label doesn't point at an invalid input")}Components
A headless field. Call it with the consumer's h, the props, and a
view closure that draws the root with field.root(h.div) and, inside it,
the label, the control, and the description and error when it has them.
Details
The parts also return disabled, invalid, valid, touched,
dirty, filled and focused as booleans, for markup that depends on
them.
The field's own attributes win over the ones the consumer set on the builder before the part, including the ones a state leaves absent:
- every part: the data attributes
label:for, the control's idcontrol:idandaria-invalidmember:aria-invalidlegendanddescription:iderror:idandrole="alert"
A part writes them when it is applied, so an attribute the consumer
chains after it is the consumer's to answer for. Leave the control's
id to the field: the label points at it.
control and member add the ids of the description and the shown
error to the element's aria-describedby, next to the consumer's own,
set before the part or after it. group adds the legend's id to
aria-labelledby the same way.
group sets role="group" when the element is built, unless it is a
<fieldset> or has a role of its own by then, such as one chained
after the part or another kit call's. aria-invalid isn't allowed on a
group, so it goes on the members only.
A disabled field writes disabled and data-disabled on the control,
and on each member, when the element is built, so they win over what
the consumer chains and over another kit call on the same element. It
also leaves out the hidden input a checkbox or a switch drawn on the
control keeps its form value in, so a disabled field submits nothing.
An enabled field does none of it, so the control keeps its own.
control handles focus and blur on a layer of its own, so the
consumer's handlers for them, and another kit call's, still run.
focusWithin and group do the same with focusin and focusout, and
member handles no focus event. A disabled field shows no focus, and
isn't touched until it is enabled and left. A field disabled while its
control has focus drops the focus, and shows it again only when the
control is focused again. A control that loses focus because something
disabled it, such as a <fieldset disabled> the field doesn't read,
doesn't touch the field either.
The field reads the nearest Fieldset above it, if there is one, and is
disabled while that fieldset or its own disabled prop says so.
History restore saves touched and not focused, so after Back, forward
or a reload the field shows as touched and unfocused.
Signature
declare const Field: Headless<{ readonly described?: boolean; readonly dirty?: boolean; readonly disabled?: boolean; readonly filled?: boolean; readonly id?: string; readonly invalid?: boolean;}, never, { control: Part<"input" | "button" | "select" | "textarea", [], never>; description: Part<string, [], never>; dirty: boolean; disabled: boolean; error: <B extends PartTarget<string>>(element: B) => ReturnType<B["attr"]> | undefined; filled: boolean; focused: boolean; focusWithin: Part<string, [], never>; group: Part<string, [], never>; invalid: boolean; label: Part<"label", [], never>; legend: Part<string, [], never>; member: Part<"input" | "button" | "select" | "textarea", [], never>; root: Part<string, [], never>; touched: boolean; valid: boolean;}, never, never, never, never, never, never, { readonly focused: boolean; readonly touched: boolean;}, { readonly _tag: "FocusedControl";} | { readonly _tag: "BlurredControl"; readonly disabled: boolean;} | { readonly _tag: "ChangedFieldset"; readonly disabled: boolean;}, QueryEntries<{}, {}>>Helpers
fieldValidationProps
unstableMaps a Validation.Field from effect/ui to Field's invalid and
filled props.
Details
invalid:trueforInvalid,falseforValid, andundefinedforNotValidatedandValidating, so a field that hasn't shown yet or is waiting on a check shows neitherdata-invalidnordata-valid.filled:trueunless the field isempty.
Signature
declare function fieldValidationProps(field: Field<unknown>): { readonly filled: boolean; readonly invalid: boolean | undefined;}Example
import { Validation } from "effect/ui"import { fieldValidationProps } from "effect/ui/kit"
const Login = Validation.make({ email: { required: "Email is required", rules: [Validation.Rule.email()] }})
let state = Login.init({ email: "" })let props = fieldValidationProps(Login.validate(state).fields.email)if (props.invalid !== undefined || props.filled) throw new Error("a field not validated yet has a verdict")
state = Login.submit(state)props = fieldValidationProps(Login.validate(state).fields.email)if (props.invalid !== true || props.filled) throw new Error("the empty field isn't invalid after submit")
state = Login.change(state, "email", "ada@example.com")props = fieldValidationProps(Login.validate(state).fields.email)if (props.invalid !== false || !props.filled) throw new Error("the filled field isn't valid")Models
The props of a Field.
Signature
type FieldProps = typeof FieldProps.TypeSchemas
FieldProps
unstableProps for the state a field reports on its parts.
Details
id: the control'sidand the label'sfor; generated if omitted. If another component writes the control's ID, pass the sameidto both.disabled: disables the control with the nativedisabledattribute, setsdata-disabledon every part and hides the error. Left out, the control keeps its owndisabled. A disabledFieldsetaround the field does the same, whatever this prop says.invalid:truemarks the field invalid, withdata-invalidon every part and, while the field is enabled,aria-invalidon the control and the error shown.falsemarks it valid, withdata-valid. Left out, the field is neither, as before it was validated.described: the field draws adescription, so the control points at it witharia-describedby.dirty: setsdata-dirty. The consumer knows the value the field started with, so it says whether the value differs.filled: setsdata-filled. The consumer holds the value, so it says whether there is one.
Signature
declare const FieldProps: Struct<{ readonly described: optional<Boolean>; readonly dirty: optional<Boolean>; readonly disabled: optional<Boolean>; readonly filled: optional<Boolean>; readonly id: optional<String>; readonly invalid: optional<Boolean>;}>