日本語

Fields bound to a form

Each form field has a variant that binds it to a field of a Form, shows the form's message for that field, and marks the field touched when the visitor leaves it.

Result

signup.rs
use hypersig::html::{Role, div, p};
use hypersig::style::Style;
use hypersig::style::pattern::{hstack, stack};
use hypersig::style::value::rem;
use hypersig::{Form, Page, Rules, Sig, Signals, Validate};
use hypersig_ui::{
    Autocomplete, ButtonSize, ButtonVariant, InputKind, TextField, button, checkbox_in_form,
    select_field_in_form, submit_button, token,
};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Default)]
pub(super) enum Plan {
    #[default]
    Unset,
    Free,
    Pro,
}

#[derive(Signals, Serialize, Deserialize, Clone, Default)]
pub(super) struct Signup {
    email: String,
    password: String,
    confirm: String,
    plan: Plan,
    terms: bool,
}

impl Validate for Signup {
    fn rules<S>(form: Sig<S, Self>, rules: &mut Rules<S, Self>) {
        let email = form.at(Signup::email());
        let password = form.at(Signup::password());
        rules
            .check(
                Signup::email(),
                email.contains("@"),
                "Enter an email address.",
            )
            .check(
                Signup::password(),
                password.char_count().ge(8),
                "Use 8 or more characters.",
            )
            .check(
                Signup::confirm(),
                form.at(Signup::confirm()).equals(password),
                "The passwords differ.",
            )
            .check(
                Signup::plan(),
                !form.at(Signup::plan()).equals(&Plan::Unset),
                "Choose a plan.",
            )
            .check(
                Signup::terms(),
                form.at(Signup::terms()),
                "Accept the terms to continue.",
            );
    }
}

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Join {
    signup: Form<Signup>,
    joined: bool,
}

pub(super) fn page() -> Page<Join> {
    let signup = Join::signup();
    let joined = Join::joined();
    let initial = Join {
        signup: Form::new(Signup::default()),
        joined: false,
    };
    Page::new(
        "Sign up",
        initial,
    )
    .child(
        signup
            // The site has no server, so a valid submit sets a signal where
            // an application would call an action.
            .form(joined.set(true).then(signup.reset()))
            .css(stack(rem(1.25)).max_width(rem(24)))
            .child(
                TextField::in_form(
                    "Email",
                    signup,
                    Signup::email(),
                )
                .kind(InputKind::Email)
                .autocomplete(Autocomplete::Email),
            )
            .child(
                TextField::in_form(
                    "Password",
                    signup,
                    Signup::password(),
                )
                .kind(InputKind::Password)
                .autocomplete(Autocomplete::NewPassword),
            )
            .child(
                TextField::in_form(
                    "Confirm password",
                    signup,
                    Signup::confirm(),
                )
                .kind(InputKind::Password)
                .autocomplete(Autocomplete::NewPassword),
            )
            .child(select_field_in_form(
                "Plan",
                signup,
                Signup::plan(),
                [
                    (
                        Plan::Unset,
                        "Choose…",
                    ),
                    (Plan::Free, "Free"),
                    (Plan::Pro, "Pro"),
                ],
            ))
            .child(checkbox_in_form(
                "I accept the terms",
                signup,
                Signup::terms(),
            ))
            .child(
                div()
                    .css(hstack(rem(0.75)))
                    .child(
                        submit_button(ButtonVariant::Default, ButtonSize::Default).text("Create account"),
                    )
                    .child(
                        button(ButtonVariant::Outline, ButtonSize::Default)
                            .show(signup.is_dirty())
                            .on_click(signup.reset())
                            .text("Clear"),
                    ),
            )
            .child(
                p().role(Role::Status)
                    .css(Style::new().color(token::muted_foreground().var()))
                    .show(joined.and(!signup.is_dirty()))
                    .text("Every rule passed."),
            ),
    )
}

Accessibility

Each variant is the control of its own page with the form's message for the field added under it. The message sits in an aria-live="polite" region, the control points at it with aria-describedby, and aria-invalid is true while it is not empty, so a screen reader reads the message after the control's name and says the value is invalid. The message waits until the visitor leaves the control, so it does not interrupt their typing. The keys are those of each control's page.

The variants

Each takes the form's signal, a Sig<S, Form<T>>, and the field of T, a Sig<T, U>, in place of the plain signal:

VariantField typeThe control
TextField::in_formStringText field
NumberField::in_formi32 or f64Number field
DateField::in_formCalendarDate or Option<CalendarDate>Date field
checkbox_in_formboolCheckbox
switch_in_formboolSwitch
radio_group_in_formany Serialize + PartialEqRadio group
select_field_in_formany Serialize + PartialEqSelect
impl<S> TextField<S> {
    pub fn in_form<T: Validate>(label: impl Into<String>, form: Sig<S, Form<T>>, field: Sig<T, String>) -> Self
}
impl<S, T: Numeric> NumberField<S, T> {
    pub fn in_form<V: Validate>(label: impl Into<String>, form: Sig<S, Form<V>>, field: Sig<V, T>) -> Self
}
impl<S, T: Dated> DateField<S, T> {
    pub fn in_form<V: Validate>(label: impl Into<String>, form: Sig<S, Form<V>>, field: Sig<V, T>) -> Self
}

pub fn checkbox_in_form<S, T: Validate>(text: impl Into<String>, form: Sig<S, Form<T>>, field: Sig<T, bool>) -> El<S>
pub fn switch_in_form<S, T: Validate>(text: impl Into<String>, form: Sig<S, Form<T>>, field: Sig<T, bool>) -> El<S>
pub fn radio_group_in_form<S, T: Validate, U: Serialize + PartialEq, L: Into<String>>(
    title: impl Into<String>, form: Sig<S, Form<T>>, field: Sig<T, U>, options: impl IntoIterator<Item = (U, L)>,
) -> El<S>
pub fn select_field_in_form<S, T: Validate, U: Serialize + PartialEq, L: Into<String>>(
    title: impl Into<String>, form: Sig<S, Form<T>>, field: Sig<T, U>, options: impl IntoIterator<Item = (U, L)>,
) -> El<S>

Each one binds the control to form.field(field), shows form.error(field) under it, and runs form.touch(field) when the visitor leaves it. form.error shows the first failing rule's message once the field is touched, and submitting the form touches every field with a rule, which is why the message waits. Where no rule fails, a message the server sent with Sig::reject shows until the next submit. The three in_form constructors return the builder, so kind, min, description, and the other methods still apply.

A form is sent by a submit_button inside it, which writes type="submit", as Button shows. Any other button in the form is type="button" and does not send it.

What they render

TextField::in_form("Email", Join::signup(), Signup::email()) renders as follows before the field is touched, without the ids from the signal's path and the class:

<div>
  <label for="…">Email</label>
  <input id="…" type="text" aria-describedby="…" aria-invalid="false" value="">
  <p id="…" aria-live="polite"></p>
</div>

ARIA allows aria-invalid on a radio group but not on a plain group, so radio_group_in_form gives the <fieldset> role="radiogroup", names it by its legend through aria-labelledby, puts aria-describedby and aria-invalid on it, and the message inside it. The field is marked touched when focus leaves the group, not while the arrow keys move between its radios:

<fieldset role="radiogroup" aria-describedby="…" aria-labelledby="…" aria-invalid="false">
  <legend id="…">Plan</legend>
  <label>…Hobby</label>
  <label>…Pro</label>
  <p id="…" aria-live="polite"></p>
</fieldset>

A field of another form

The field's first type parameter is the form's value type T, so a field of another struct fails to compile with E0308, even where the two structs have a field of the same name:

use hypersig::{Form, Rules, Sig, Signals, Validate};
use hypersig_ui::TextField;
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize, Clone)]
struct Signup {
    email: String,
}

impl Validate for Signup {
    fn rules<S>(_form: Sig<S, Self>, _rules: &mut Rules<S, Self>) {}
}

#[derive(Signals, Serialize, Deserialize, Clone)]
struct Profile {
    email: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Join {
    signup: Form<Signup>,
}

// A field of `Profile`, which the form on this page does not hold.
let email = TextField::in_form("Email", Join::signup(), Profile::email());

The form's value type has to implement Validate, and the field's type has to match the control: a bool field in TextField::in_form fails with E0308, and a String field in NumberField::in_form with E0277, as on the control's own page.

What the types leave unchecked

  • A field that no rule of Validate::rules checks never has a message, and its control is never invalid.
  • The <form> from Sig::form has novalidate, so the browser does not check required, min_length, min, max, or type="email" before the submit. They still set the on-screen keyboard and what a screen reader announces; write each check as a rule too.
  • The rules run in the browser, so the server checks the value it receives again, as Validating a form shows.
  • Two controls bound to one field of one form get the same ids, and the second one's message points at the first.

Example: a sign-up form

Every variant on one form, sent to an action by its submit button:

use hypersig::{Action, CalendarDate, Form, Page, Rules, Sig, Signals, Validate};
use hypersig_ui::{
    ButtonSize, ButtonVariant, DateField, InputKind, NumberField, TextField, checkbox_in_form,
    radio_group_in_form, select_field_in_form, submit_button, switch_in_form,
};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Default)]
enum Plan {
    #[default]
    Unset,
    Hobby,
    Pro,
}

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Default)]
enum Region {
    #[default]
    Tokyo,
    Frankfurt,
}

#[derive(Signals, Serialize, Deserialize, Clone, Default)]
struct Signup {
    email: String,
    seats: i32,
    start: Option<CalendarDate>,
    plan: Plan,
    region: Region,
    newsletter: bool,
    terms: bool,
}

impl Validate for Signup {
    fn rules<S>(form: Sig<S, Self>, rules: &mut Rules<S, Self>) {
        let email = form.at(Signup::email());
        rules.check(Signup::email(), email.contains("@"), "Enter an email address.");
        rules.check(Signup::seats(), form.at(Signup::seats()).ge(1), "Add at least one seat.");
        let chosen = !form.at(Signup::plan()).equals(&Plan::Unset);
        rules.check(Signup::plan(), chosen, "Choose a plan.");
        rules.check(Signup::terms(), form.at(Signup::terms()), "Accept the terms.");
    }
}

#[derive(Signals, Serialize, Deserialize)]
struct Join {
    signup: Form<Signup>,
}

hypersig::routes! {
    fn pages(Router<()>);
    action JOIN: Action<Join, Signup> = post "/join" => join;
}

let signup = Join::signup();
let page = Page::new("Join", Join { signup: Form::new(Signup::default()) }).child(
    signup
        .form(JOIN.call_with(signup.value()))
        .child(TextField::in_form("Email", signup, Signup::email()).kind(InputKind::Email))
        .child(NumberField::in_form("Seats", signup, Signup::seats()).min(1))
        .child(DateField::in_form("Start", signup, Signup::start()))
        .child(radio_group_in_form(
            "Plan",
            signup,
            Signup::plan(),
            [(Plan::Hobby, "Hobby"), (Plan::Pro, "Pro")],
        ))
        .child(select_field_in_form(
            "Region",
            signup,
            Signup::region(),
            [(Region::Tokyo, "Tokyo"), (Region::Frankfurt, "Frankfurt")],
        ))
        .child(switch_in_form("Newsletter", signup, Signup::newsletter()))
        .child(checkbox_in_form("I accept the terms", signup, Signup::terms()))
        .child(submit_button(ButtonVariant::Default, ButtonSize::Default).text("Join")),
);

Next

Forms covers Form<T>, form.field, and form.touch, and Validating a form writes the rules and checks the value again on the server.