Build forms in GPUI with typed values, a schema of rules, and the Field component. What React Hook Form and Zod give React.
This page builds a bug report form: a text input and a textarea. On submit the values are validated against a schema and any errors show next to their fields. The form is plain Rust that you copy into your app, so every rule, message and behavior is yours to change.
Demo
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{debug_json, field, string, Form, FormExt, Schema};
use crate::ui::input_group::InputGroup;
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Default, Debug, PartialEq)]
struct BugReport {
title: String,
description: String,
}
fn bug_report_schema() -> Schema<BugReport> {
Schema::<BugReport>::new()
.field(
field!(title),
string()
.min(5, "Bug title must be at least 5 characters.")
.max(32, "Bug title must be at most 32 characters."),
)
.field(
field!(description),
string()
.min(20, "Description must be at least 20 characters.")
.max(100, "Description must be at most 100 characters."),
)
}
pub fn form_demo(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-demo", cx, |_, _| {
Form::new(BugReport::default())
.schema(bug_report_schema())
.on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let title = form.input(field!(title), window, cx, |input| {
input.placeholder("Login button not working on mobile")
});
let description = form.input(field!(description), window, cx, |input| {
input
.multi_line(4)
.bare()
.placeholder("I'm having an issue with the login button on mobile.")
});
let f = form.read(cx);
let count = f.values().description.chars().count();
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Bug Report")
.description("Help us improve by reporting bugs you encounter.")
.child(
div()
.flex()
.flex_col()
.gap_6()
.child(f.field("title").label("Bug Title").child(title))
.child(
f.field("description")
.label("Description")
.description("Include steps to reproduce, expected behavior, and what actually happened.")
.child(InputGroup::new(description).block_end(format!("{count}/100 characters"))),
),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-demo-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-demo-submit", "Submit").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Installation
Copies src/ui/form.rs with the field and input components it binds to. The demos also use card, button and toast; add them the same way.
Approach
Your own struct holds the values. A Schema says what is valid, with each rule carrying its message, like a Zod schema. A Form entity tracks errors, touched fields, the submit count and the pending action, like useForm. The Field component lays out the label, the control, the helper text and the error, and you keep full control of the layout.
Text inputs are owned by the form and bound in one line. Checkboxes, switches, radio groups and selects stay controlled: they read from values() and report back through a handler the form gives you. Each takes a focus handle from the form too, so the form can focus any of them.
Anatomy
let title = form.input(field!(title), window, cx, |input| {
input.placeholder("Login button not working on mobile")
});
let f = form.read(cx);
f.field("title")
.label("Bug Title")
.description("Provide a concise title for your bug report.")
.child(title)Form
Create a schema
Describe the values with a struct, then the rules for each field. field!(title) names a field of the struct; errors are keyed by that name. Write Schema::<BugReport>::new() with the type spelled out: field! reads the field through a closure, and Rust needs to know the struct before it can check that the field exists.
#[derive(Clone, Default, Debug, PartialEq)]
struct BugReport {
title: String,
description: String,
}
fn bug_report_schema() -> Schema<BugReport> {
Schema::<BugReport>::new()
.field(
field!(title),
string()
.min(5, "Bug title must be at least 5 characters.")
.max(32, "Bug title must be at most 32 characters."),
)
.field(
field!(description),
string()
.min(20, "Description must be at least 20 characters.")
.max(100, "Description must be at most 100 characters."),
)
}Set up the form
Create the form once, with its default values and schema, and say what happens after a valid submit. Then create its inputs; the form keeps them in sync with the values.
let form = window.use_keyed_state("form-demo", cx, |_, _| {
Form::new(BugReport::default())
.schema(bug_report_schema())
.on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let title = form.input(field!(title), window, cx, |input| {
input.placeholder("Login button not working on mobile")
});
let description = form.input(field!(description), window, cx, |input| {
input
.multi_line(4)
.bare()
.placeholder("I'm having an issue with the login button on mobile.")
});Build the form
Read the form, and put each control in f.field(name), which shows that field's error and turns its label red. Give the buttons form.handle_submit() and form.handle_reset(). The full source is under the demo above.
let f = form.read(cx);
let count = f.values().description.chars().count();
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Bug Report")
.description("Help us improve by reporting bugs you encounter.")
.child(
div()
.flex()
.flex_col()
.gap_6()
.child(f.field("title").label("Bug Title").child(title))
.child(
f.field("description")
.label("Description")
.description("Include steps to reproduce, expected behavior, and what actually happened.")
.child(InputGroup::new(description).block_end(format!("{count}/100 characters"))),
),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-demo-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-demo-submit", "Submit").on_click(form.handle_submit())),
),
)Done
Submitting runs the schema. If anything fails, the errors appear under their fields and the first invalid field takes focus. If everything passes, on_success receives the values, and an async action runs first if you gave one (see Actions).
Validation
Client-side Validation
Rules start from string(), number(), array(), boolean() or optional(), with helpers such as min, max, email and required. Anything else is a closure: .refine(|name| ..., "message"). Rules across fields, such as matching passwords, go on the schema:
Schema::<SignUp>::new()
.field(field!(password), string().min(8, "Use at least 8 characters."))
.refine("confirm", |values| values.confirm == values.password, "Passwords don't match.")Validation Modes
Form::mode sets when fields validate before the first submit. After a submit, every mode revalidates on change, so errors clear as soon as they are fixed.
| Mode | Description |
|---|---|
| Mode::OnSubmit | Validation triggers on submit (default). |
| Mode::OnBlur | Validation triggers on blur. |
| Mode::OnChange | Validation triggers on every change. |
| Mode::OnTouched | Validation triggers on first blur, then on every change. |
| Mode::All | Validation triggers on blur and change. |
Form::new(Account::default()).schema(account_schema()).mode(Mode::OnTouched)use gpui::{div, prelude::*, px, App, SharedString, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::form::{field, string, Form, FormExt, Mode, Schema};
use crate::ui::select::{Select, SelectOption};
use crate::ui::tabs::Tabs;
#[derive(Clone, Default, Debug, PartialEq)]
struct Account {
email: String,
username: String,
plan: String,
}
const PLANS: [(&str, &str); 3] = [("hobby", "Hobby"), ("pro", "Pro"), ("team", "Team")];
const MODES: [(Mode, &str, &str); 5] = [
(Mode::OnSubmit, "OnSubmit", "Validation triggers on submit (default)."),
(Mode::OnBlur, "OnBlur", "Validation triggers on blur."),
(Mode::OnChange, "OnChange", "Validation triggers on every change."),
(Mode::OnTouched, "OnTouched", "Validation triggers on first blur, then on every change."),
(Mode::All, "All", "Validation triggers on blur and change."),
];
fn account_schema() -> Schema<Account> {
Schema::<Account>::new()
.field(field!(email), string().email("Enter a valid email address."))
.field(
field!(username),
string()
.min(3, "Username must be at least 3 characters.")
.max(10, "Username must be at most 10 characters."),
)
.field(field!(plan), string().min(1, "Pick a plan."))
}
pub fn form_modes(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-modes", cx, |_, _| {
Form::new(Account::default()).schema(account_schema())
});
let email = form.input(field!(email), window, cx, |input| input.placeholder("name@example.com"));
let username = form.input(field!(username), window, cx, |input| input.placeholder("shadcn"));
let plan_focus = form.focus_handle(&field!(plan), window, cx);
let plan_open = window.use_keyed_state("form-modes-plan-open", cx, |_, _| false);
let f = form.read(cx);
let selected = MODES.iter().position(|(mode, _, _)| *mode == f.current_mode()).unwrap_or(0);
let muted = cx.theme().muted_foreground;
let touched = f.touched_fields();
let status = format!(
"Submitted {} times. Touched: {}.",
f.submit_count(),
if touched.is_empty() { "none".to_string() } else { touched.join(", ") }
);
let plan = &f.values().plan;
let plan = PLANS
.iter()
.fold(
Select::new(
"form-modes-plan",
(!plan.is_empty()).then(|| SharedString::from(plan.clone())),
*plan_open.read(cx),
)
.placeholder("Select a plan")
.width(px(448.))
.focus_handle(plan_focus)
.invalid(f.invalid("plan")),
|select, (value, label)| select.option(SelectOption::new(*value, *label)),
)
.on_open_change(move |next, _, cx| {
plan_open.update(cx, |open, cx| {
*open = *next;
cx.notify();
})
})
.on_change(form.on_change_with(field!(plan), |plan: &mut String, value: &SharedString| {
*plan = value.to_string()
}));
let switch_mode = form.downgrade();
div()
.w(px(448.))
.flex()
.flex_col()
.gap_6()
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(
MODES
.iter()
.fold(Tabs::new("form-modes-tabs", selected), |tabs, (_, label, _)| tabs.tab(*label))
.on_select(move |ix, _, cx| {
if let Some((mode, _, _)) = MODES.get(*ix) {
switch_mode.update(cx, |form, cx| form.set_mode(*mode, cx)).ok();
}
}),
)
.child(div().text_sm().text_color(muted).child(MODES[selected].2)),
)
.child(f.field("email").label("Email").child(email))
.child(f.field("username").label("Username").child(username))
.child(f.field("plan").label("Plan").child(plan))
.child(
div()
.flex()
.items_center()
.gap_2()
.child(
Button::new("form-modes-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-modes-submit", "Submit").on_click(form.handle_submit()))
.child(div().ml_2().text_sm().text_color(muted).child(status)),
)
}Revalidation
re_validate_mode sets when fields validate again after a submit, like reValidateMode. delay_error(Duration) holds a new error back until the user stops typing for that long; fixing the field clears its error at once. As in react-hook-form, whose handleSubmit and trigger set errors directly, a submit or trigger shows every error straight away; the delay applies to validation from changes and blurs, before and after a submit.
| ReValidateMode::OnChange | Revalidates on every change after a submit (default). |
| ReValidateMode::OnBlur | Revalidates when a field loses focus after a submit. |
| ReValidateMode::OnSubmit | Waits for the next submit. |
Form::new(Account::default())
.mode(Mode::OnBlur)
.re_validate_mode(ReValidateMode::OnBlur)
.delay_error(Duration::from_millis(500))Async Validation
field_async adds a check that runs off the main flow, such as asking a server whether a username is free. It runs once the field's other rules pass, and a newer run cancels the one before it, so a check that sleeps first also debounces typing. get_field_state(name).is_validating and is_validating() say when one is running, and a submit waits for them before running its action. refine_async checks across fields.
Several async checks on one field run one at a time, in the order you added them, like react-hook-form's validate: { a, b }: the first failure ends the run, or with CriteriaMode::All the rest still run after it and every message is kept. Order matters when a later check is the expensive one. Checks on different fields run at the same time.
async fn username_available(username: String, cx: AsyncApp) -> Result<(), SharedString> {
cx.background_executor().timer(Duration::from_millis(800)).await;
if TAKEN.contains(&username.as_str()) {
Err(format!(""{username}" is already taken.").into())
} else {
Ok(())
}
}
Schema::<SignUp>::new()
.field(field!(username), string().min(3, "Username must be at least 3 characters."))
.field_async(field!(username), username_available)
// Across fields, reported on one path:
.refine_async("email", |values: SignUp, cx| async move { check_invite(values, cx).await })use std::time::Duration;
use gpui::{div, prelude::*, px, AsyncApp, App, SharedString, Window};
use crate::icons::{icon, CIRCLE_CHECK};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{debug_json, field, string, CriteriaMode, Form, FormExt, Mode, Schema};
use crate::ui::spinner::{Spinner, SpinnerSize};
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Default, Debug, PartialEq)]
struct SignUp {
username: String,
password: String,
}
const TAKEN: [&str; 3] = ["admin", "shadcn", "hyuskui"];
/// Stands in for a request to your backend: it answers after 800ms.
async fn username_available(username: String, cx: AsyncApp) -> Result<(), SharedString> {
cx.background_executor().timer(Duration::from_millis(800)).await;
if TAKEN.contains(&username.to_lowercase().as_str()) {
Err(format!("\"{username}\" is already taken.").into())
} else {
Ok(())
}
}
fn sign_up_schema() -> Schema<SignUp> {
Schema::<SignUp>::new()
.field(
field!(username),
string()
.min(3, "Username must be at least 3 characters.")
.refine(
|name| name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
"Use letters, numbers and underscores.",
),
)
.field_async(field!(username), username_available)
.field(
field!(password),
string()
.min(8, "At least 8 characters.")
.refine(|password| password.chars().any(|c| c.is_ascii_digit()), "At least one number.")
.refine(|password| password.chars().any(|c| c.is_ascii_uppercase()), "At least one capital letter."),
)
}
pub fn form_async_validation(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-async-validation", cx, |_, _| {
Form::new(SignUp::default())
.schema(sign_up_schema())
.mode(Mode::OnChange)
.criteria_mode(CriteriaMode::All)
.on_success(|values, _, cx| {
toast(Toast::new("You submitted the following values:").code(debug_json(values)), cx)
})
});
let username = form.input(field!(username), window, cx, |input| input.placeholder("ada_l"));
let password = form.input(field!(password), window, cx, |input| input.password().placeholder("••••••••"));
let theme = cx.theme();
let (muted, foreground) = (theme.muted_foreground, theme.foreground);
let f = form.read(cx);
let state = f.get_field_state("username");
let status = if state.is_validating {
Some(
div()
.flex()
.items_center()
.gap_2()
.text_color(muted)
.child(Spinner::new().size(SpinnerSize::Sm).color(muted))
.child("Checking availability…"),
)
} else if state.is_dirty && !state.invalid {
Some(
div()
.flex()
.items_center()
.gap_2()
.text_color(foreground)
.child(icon(CIRCLE_CHECK).size(px(14.)).text_color(foreground))
.child("Username is available."),
)
} else {
None
};
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Create an account")
.description("Pick a username and a password.")
.child(
div()
.flex()
.flex_col()
.gap_6()
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(f.field("username").label("Username").child(username))
.children(status.map(|status| status.text_sm())),
)
.child(f.field("password").label("Password").child(password)),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-async-validation-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(
Button::new(
"form-async-validation-save",
if f.is_submitting() { "Checking…" } else { "Create account" },
)
.disabled(f.is_submitting())
.on_click(form.handle_submit()),
),
),
)
.child(Toaster::new())
}Criteria Mode
By default a field shows the first rule it fails. With CriteriaMode::All it keeps every failed rule's message, like criteriaMode: "all", and f.field(name) lists them. The password in the demo above uses it.
Form::new(SignUp::default())
.schema(sign_up_schema())
.criteria_mode(CriteriaMode::All)
// f.field(name) lists every message; read them yourself with:
f.error_messages("password") // ["At least 8 characters.", "At least one number."]Validating on demand
trigger validates some fields now, whatever the mode, and shows their errors, like react-hook-form's trigger. It returns a Validation: read now(), or await it when async checks are involved. Use it for a multi-step form's Next button.
let validation = form.update(cx, |form, cx| {
form.trigger("username", cx); // one field
form.trigger(["email", "password"], cx); // several
form.trigger(Names::All, cx) // everything
});
validation.now() // Some(passed), or None while async checks run
// The result is a future, so you can await async checks too:
cx.spawn(async move |_| {
if validation.await {
// all passed
}
})Displaying Errors
f.field(name) shows the field's error under the control and colors the label, like shadcn's data-invalid. A bound text input gets its red border from the form. For other controls, pass f.invalid(name) to their invalid method, the equivalent of aria-invalid.
// A text field: the bound input turns red on its own.
f.field("email").label("Email").child(email)
// Other controls take the invalid state from the form.
Select::new("language", value, open).invalid(f.invalid("language"))
Checkbox::new("terms", f.values().terms).invalid(f.invalid("terms"))
// A message without a label, under a group of controls.
.when_some(f.error("tasks"), |set, error| set.child(Field::new().error(error)))Keyboard and Focus
Every control is a tab stop with a focus ring for keyboard use. Space toggles a checkbox or switch; Enter, Space or the down arrow opens a select, combobox or date picker; the arrow keys move through a radio group and select as they go. A radio group or toggle group is one tab stop, like the platform's own.
Tab order
Tab and Shift-Tab follow the order fields are drawn in. GPUI leaves the Tab key to the app, like a keymap entry, so bind it once at your window's root:
// At your window's root view, once. GPUI leaves Tab to the app.
div()
.track_focus(&self.focus_handle)
.on_key_down(|event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "tab" {
if event.keystroke.modifiers.shift {
window.focus_prev(cx);
} else {
window.focus_next(cx);
}
cx.stop_propagation();
}
})setFocus
set_focus(name) focuses a field's control, like setFocus. Text inputs from form.input are registered already. For other controls, get a handle from form.focus_handle (or focus_handle_at for several controls on one field, like a list of checkboxes) and pass it to the control's .focus_handle(...). On an array row, use item_focus_handle(key, ...) so the handle stays with its row as rows move. A control that owns its handle, such as InputOtp, registers it with register_focus. The form also watches when focus leaves the field, so it counts as touched and validates in Mode::OnBlur. Focus inside a select's, combobox's or date picker's own list is still in the field, so opening one doesn't count; leaving the field does. Without a handle a control keeps its own, so it is still a tab stop.
// Text inputs bound with form.input(...) already have one.
let plan = form.focus_handle(&field!(plan), window, cx);
let addons: Vec<_> = (0..ADDONS.len())
.map(|ix| form.focus_handle_at(&field!(addons), ix, window, cx))
.collect();
let f = form.read(cx);
RadioGroup::new("plan", selected).focus_handle(plan)
Checkbox::new(("addon", ix), checked).focus_handle(addons[ix].clone())
// A control on an array row: keyed by the row, so the handle moves with it.
let role = form.item_focus_handle(key, &field!(members[ix].role), window, cx);
// A control that owns its handle, like InputOtp, registers it.
form.register_focus(&field!(code), otp.focus_handle(cx), window, cx);
// Later, from any handler:
form.set_focus("plan", window, cx);A failed submit focuses the first invalid field in schema order, whatever control it is. Turn that off with should_focus_error(false). In this demo the select comes first in the schema; submit it empty to see focus land there. The buttons focus each field. The field shows its focus ring even though you clicked, as a browser shows :focus-visible when a script moves focus, so the user sees where it went; the next pointer press ends it.
use gpui::{div, prelude::*, px, App, Focusable, SharedString, Subscription, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::checkbox::Checkbox;
use crate::ui::field::Field;
use crate::ui::form::{boolean, debug_json, field, string, Form, FormEvent, FormExt, Schema};
use crate::ui::input_otp::{InputOtp, OtpEvent};
use crate::ui::radio_group::RadioGroup;
use crate::ui::select::{Select, SelectOption};
use crate::ui::switch::Switch;
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Default, Debug, PartialEq)]
struct Invite {
role: String,
contact: String,
name: String,
code: String,
terms: bool,
digest: bool,
}
const ROLES: [(&str, &str); 3] = [("admin", "Admin"), ("editor", "Editor"), ("viewer", "Viewer")];
const CONTACTS: [(&str, &str); 2] = [("email", "Email"), ("phone", "Phone")];
/// The fields `set_focus` can reach, with the button label for each.
const TARGETS: [(&str, &str); 6] = [
("role", "Role"),
("contact", "Contact"),
("name", "Name"),
("code", "Code"),
("terms", "Terms"),
("digest", "Digest"),
];
// The select comes first, so an empty submit focuses it rather than the text input.
fn invite_schema() -> Schema<Invite> {
Schema::<Invite>::new()
.field(field!(role), string().min(1, "Pick a role."))
.field(field!(contact), string().min(1, "Pick how to reach them."))
.field(field!(name), string().min(2, "Enter their name."))
.field(field!(code), string().min(6, "Enter the 6-digit invite code."))
.field(field!(terms), boolean().accepted("They must accept the terms."))
}
pub fn form_set_focus(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-set-focus", cx, |_, _| {
Form::new(Invite::default()).schema(invite_schema()).on_success(|values, _, cx| {
toast(Toast::new("You submitted the following values:").code(debug_json(values)), cx)
})
});
let role_open = window.use_keyed_state("form-set-focus-role-open", cx, |_, _| false);
let name = form.input(field!(name), window, cx, |input| input.placeholder("Ada Lovelace"));
let role_focus = form.focus_handle(&field!(role), window, cx);
let contact_focus = form.focus_handle(&field!(contact), window, cx);
let terms_focus = form.focus_handle(&field!(terms), window, cx);
let digest_focus = form.focus_handle(&field!(digest), window, cx);
// The OTP input owns its focus handle; registering it lets set_focus and a failed submit
// reach it, and its blur mark the field touched.
let code = window.use_keyed_state("form-set-focus-code", cx, |_, cx| InputOtp::new(6, cx).group_size(3));
let code_focus = code.focus_handle(cx);
form.register_focus(&field!(code), code_focus.clone(), window, cx);
sync_code(&form, &code, window, cx);
// Which field has focus, to show next to the buttons.
let focused = [&role_focus, &contact_focus, &code_focus, &terms_focus, &digest_focus]
.into_iter()
.zip(["role", "contact", "code", "terms", "digest"])
.find(|(handle, _)| handle.is_focused(window))
.map(|(_, name)| name)
.or_else(|| name.read(cx).is_focused(window).then_some("name"));
let muted = cx.theme().muted_foreground;
let code_invalid = form.read(cx).invalid("code");
code.update(cx, |code, cx| code.set_invalid(code_invalid, cx));
let f = form.read(cx);
let values = f.values();
let buttons = TARGETS.iter().fold(div().flex().flex_wrap().gap_2(), |row, (target, label)| {
let form = form.clone();
row.child(
Button::new(SharedString::from(format!("form-set-focus-{target}")), *label)
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.on_click(move |_, window, cx| {
form.set_focus(target, window, cx);
}),
)
});
let role = ROLES
.iter()
.fold(
Select::new(
"form-set-focus-role",
(!values.role.is_empty()).then(|| SharedString::from(values.role.clone())),
*role_open.read(cx),
)
.placeholder("Select a role")
.width(px(384.))
.focus_handle(role_focus)
.invalid(f.invalid("role")),
|select, (value, label)| select.option(SelectOption::new(*value, *label)),
)
.on_open_change(move |next, _, cx| {
role_open.update(cx, |open, cx| {
*open = *next;
cx.notify();
})
})
.on_change(form.on_change_with(field!(role), |role: &mut String, value: &SharedString| {
*role = value.to_string()
}));
let contact = CONTACTS
.iter()
.fold(
RadioGroup::new(
"form-set-focus-contact",
CONTACTS.iter().position(|(id, _)| *id == values.contact),
)
.horizontal(true)
.focus_handle(contact_focus)
.invalid(f.invalid("contact")),
|group, (_, label)| group.option(*label),
)
.on_change(form.on_change_with(field!(contact), |contact: &mut String, ix: &usize| {
if let Some((id, _)) = CONTACTS.get(*ix) {
*contact = id.to_string();
}
}));
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Invite a teammate")
.description("Focus any field from code, whatever kind of control it is.")
.child(
div()
.flex()
.flex_col()
.gap_5()
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(buttons)
.child(div().text_xs().text_color(muted).child(match focused {
Some(name) => format!("Focused: {name}"),
None => "Focused: nothing".to_string(),
})),
)
.child(f.field("role").label("Role").child(role))
.child(f.field("contact").label("Contact method").child(contact))
.child(f.field("name").label("Name").child(name))
.child(f.field("code").label("Invite code").child(code))
.child(
Field::new()
.when_some(f.error("terms"), |field, error| field.error(error))
.child(
Checkbox::new("form-set-focus-terms", values.terms)
.label("Accept the terms of service")
.focus_handle(terms_focus)
.invalid(f.invalid("terms"))
.on_toggle(form.on_change(field!(terms))),
),
)
.child(
Switch::new("form-set-focus-digest", values.digest)
.label("Send a weekly digest")
.focus_handle(digest_focus)
.on_toggle(form.on_change(field!(digest))),
),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-set-focus-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-set-focus-save", "Send invite").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}
/// Keeps the OTP input and the `code` field in step: typing sets the field, and a reset clears
/// the digits. The subscriptions live in keyed state, made once.
fn sync_code(form: &gpui::Entity<Form<Invite>>, code: &gpui::Entity<InputOtp>, window: &mut Window, cx: &mut App) {
let (form, code) = (form.clone(), code.clone());
window.use_keyed_state("form-set-focus-code-sync", cx, move |window, cx| {
let typed = {
let form = form.clone();
cx.subscribe_in(&code, window, move |_, _, event: &OtpEvent, window, cx| {
if let OtpEvent::Change(value) = event {
form.update(cx, |form, cx| form.set_value(&field!(code), value.to_string(), window, cx));
}
})
};
let reset = cx.subscribe_in(&form, window, move |_, _, event: &FormEvent, window, cx| {
if *event == FormEvent::Reset {
code.update(cx, |code, cx| code.set_value("", window, cx));
}
});
[typed, reset] as [Subscription; 2]
});
}Working with Different Field Types
Input
form.input(field!(name), window, cx, build) creates the input the first time, binds it, and returns it every render after. Enter submits the form.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{debug_json, field, string, Form, FormExt, Schema};
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Default, Debug, PartialEq)]
struct Profile {
username: String,
}
fn profile_schema() -> Schema<Profile> {
Schema::<Profile>::new().field(
field!(username),
string()
.min(3, "Username must be at least 3 characters.")
.max(10, "Username must be at most 10 characters.")
.refine(
|name| name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
"Username can only contain letters, numbers, and underscores.",
),
)
}
pub fn form_input(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-input", cx, |_, _| {
Form::new(Profile::default()).schema(profile_schema()).on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let username = form.input(field!(username), window, cx, |input| input.placeholder("shadcn"));
let f = form.read(cx);
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Profile Settings")
.description("Update your profile information below.")
.child(
f.field("username")
.label("Username")
.description(
"This is your public display name. Must be between 3 and 10 characters. \
Must only contain letters, numbers, and underscores.",
)
.child(username),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-input-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-input-save", "Save").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Textarea
A multi-line input binds the same way. Enter adds a new line.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{debug_json, field, string, Form, FormExt, Schema};
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Default, Debug, PartialEq)]
struct Personalization {
about: String,
}
fn personalization_schema() -> Schema<Personalization> {
Schema::<Personalization>::new().field(
field!(about),
string()
.min(10, "Please provide at least 10 characters.")
.max(200, "Please keep it under 200 characters."),
)
}
pub fn form_textarea(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-textarea", cx, |_, _| {
Form::new(Personalization::default())
.schema(personalization_schema())
.on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let about = form.input(field!(about), window, cx, |input| {
input.multi_line(5).placeholder("I'm a software engineer...")
});
let f = form.read(cx);
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Personalization")
.description("Customize your experience by telling us more about yourself.")
.child(
f.field("about")
.label("More about you")
.description(
"Tell us more about yourself. This will be used to help us personalize your experience.",
)
.child(about),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-textarea-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-textarea-save", "Save").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Select
Pass the current value from values() and turn the chosen option into the field's value with form.on_change_with.
use gpui::{div, prelude::*, px, App, SharedString, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{debug_json, field, string, Form, FormExt, Schema};
use crate::ui::select::{Select, SelectOption};
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Default, Debug, PartialEq)]
struct LanguagePreferences {
language: String,
}
const SPOKEN_LANGUAGES: [(&str, &str); 7] = [
("en", "English"),
("es", "Spanish"),
("fr", "French"),
("de", "German"),
("it", "Italian"),
("zh", "Chinese"),
("ja", "Japanese"),
];
fn language_schema() -> Schema<LanguagePreferences> {
Schema::<LanguagePreferences>::new().field(
field!(language),
string().min(1, "Please select your spoken language.").refine(
|language| language != "auto",
"Auto-detection is not allowed. Please select a specific language.",
),
)
}
pub fn form_select(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-select", cx, |_, _| {
Form::new(LanguagePreferences::default())
.schema(language_schema())
.on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let open = window.use_keyed_state("form-select-open", cx, |_, _| false);
let focus = form.focus_handle(&field!(language), window, cx);
let f = form.read(cx);
let language = &f.values().language;
let select = Select::new(
"form-select-language",
(!language.is_empty()).then(|| SharedString::from(language.clone())),
*open.read(cx),
)
.placeholder("Select")
.width(px(120.))
.focus_handle(focus)
.invalid(f.invalid("language"))
.option(SelectOption::new("auto", "Auto"))
.separator();
let select = SPOKEN_LANGUAGES
.iter()
.fold(select, |select, (value, label)| select.option(SelectOption::new(*value, *label)))
.on_open_change(move |next, _, cx| {
open.update(cx, |open, cx| {
*open = *next;
cx.notify();
})
})
.on_change(form.on_change_with(field!(language), |language: &mut String, value: &SharedString| {
*language = value.to_string()
}));
div()
.w(px(512.))
.flex()
.flex_col()
.child(
Card::new()
.title("Language Preferences")
.description("Select your preferred spoken language.")
.child(
f.field("language")
.horizontal(true)
.label("Spoken Language")
.description("For best results, select the language you speak.")
.child(select),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-select-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-select-save", "Save").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Checkbox
A group of checkboxes edits one Vec: each box adds or removes its id, and array().min(1, ...) requires one.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::checkbox::Checkbox;
use crate::ui::field::{Field, FieldSet};
use crate::ui::form::{array, debug_json, field, Form, FormExt, Schema};
use crate::ui::separator::Separator;
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Debug, PartialEq)]
struct Notifications {
responses: bool,
tasks: Vec<String>,
}
const TASKS: [(&str, &str); 2] = [("push", "Push notifications"), ("email", "Email notifications")];
fn notifications_schema() -> Schema<Notifications> {
Schema::<Notifications>::new().field(
field!(tasks),
array().min(1, "Please select at least one notification type."),
)
}
pub fn form_checkbox(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-checkbox", cx, |_, _| {
Form::new(Notifications {
responses: true,
tasks: Vec::new(),
})
.schema(notifications_schema())
.on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
// Handles come before `form.read(cx)`, which borrows the form.
let focus: Vec<_> = (0..TASKS.len())
.map(|ix| form.focus_handle_at(&field!(tasks), ix, window, cx))
.collect();
let f = form.read(cx);
let invalid = f.invalid("tasks");
let tasks = TASKS.iter().enumerate().fold(
div().flex().flex_col().gap_3(),
|list, (ix, (id, label))| {
let checked = f.values().tasks.iter().any(|task| task == id);
list.child(
Checkbox::new(("form-checkbox-task", ix), checked)
.label(*label)
.focus_handle(focus[ix].clone())
.invalid(invalid)
.on_toggle(form.on_change_with(field!(tasks), move |tasks: &mut Vec<String>, on: &bool| {
tasks.retain(|task| task != id);
if *on {
tasks.push(id.to_string());
}
})),
)
},
);
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Notifications")
.description("Manage your notification preferences.")
.child(
div()
.flex()
.flex_col()
.gap_6()
.child(
FieldSet::new()
.legend("Responses")
.label_legend(true)
.description(
"Get notified for requests that take time, like research or image generation.",
)
// Always on in this demo, as in shadcn's.
.child(
Checkbox::new("form-checkbox-responses", f.values().responses)
.label("Push notifications")
.disabled(true),
),
)
.child(Separator::horizontal())
.child(
FieldSet::new()
.legend("Tasks")
.label_legend(true)
.description("Get notified when tasks you've created have updates.")
.child(tasks)
.when_some(f.error("tasks"), |set, error| set.child(Field::new().error(error))),
),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-checkbox-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-checkbox-save", "Save").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Radio Group
The radio group reports an index; map it to the value you store.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::field::{Field, FieldSet};
use crate::ui::form::{debug_json, field, string, Form, FormExt, Schema};
use crate::ui::radio_group::RadioGroup;
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Default, Debug, PartialEq)]
struct Subscription {
plan: String,
}
const PLANS: [(&str, &str, &str); 3] = [
("starter", "Starter (100K tokens/month)", "For everyday use with basic features."),
("pro", "Pro (1M tokens/month)", "For advanced AI usage with more features."),
("enterprise", "Enterprise (Unlimited tokens)", "For large teams and heavy usage."),
];
fn subscription_schema() -> Schema<Subscription> {
Schema::<Subscription>::new().field(
field!(plan),
string().min(1, "You must select a subscription plan to continue."),
)
}
pub fn form_radio_group(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-radio-group", cx, |_, _| {
Form::new(Subscription::default())
.schema(subscription_schema())
.on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let focus = form.focus_handle(&field!(plan), window, cx);
let f = form.read(cx);
let selected = PLANS.iter().position(|(id, _, _)| *id == f.values().plan);
let plans = PLANS.iter().fold(
RadioGroup::new("form-radio-group-plan", selected)
.cards(true)
.focus_handle(focus)
.invalid(f.invalid("plan")),
|group, (_, title, description)| group.option_with_description(*title, *description),
);
let plans = plans.on_change(form.on_change_with(field!(plan), |plan: &mut String, ix: &usize| {
if let Some((id, _, _)) = PLANS.get(*ix) {
*plan = id.to_string();
}
}));
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Subscription Plan")
.description("See pricing and features for each plan.")
.child(
FieldSet::new()
.legend("Plan")
.description("You can upgrade or downgrade your plan at any time.")
.child(plans)
.when_some(f.error("plan"), |set, error| set.child(Field::new().error(error))),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-radio-group-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-radio-group-save", "Save").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Switch
form.on_change(field!(two_factor)) hands the switch's new value straight to a bool field.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{boolean, debug_json, field, Form, FormExt, Schema};
use crate::ui::switch::Switch;
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Default, Debug, PartialEq)]
struct Security {
two_factor: bool,
}
fn security_schema() -> Schema<Security> {
Schema::<Security>::new().field(
field!(two_factor),
boolean().accepted("It is highly recommended to enable two-factor authentication."),
)
}
pub fn form_switch(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-switch", cx, |_, _| {
Form::new(Security::default()).schema(security_schema()).on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let focus = form.focus_handle(&field!(two_factor), window, cx);
let f = form.read(cx);
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Security Settings")
.description("Manage your account security preferences.")
.child(
f.field("two_factor")
.horizontal(true)
.label("Multi-factor authentication")
.description("Enable multi-factor authentication to secure your account.")
.child(
Switch::new("form-switch-two-factor", f.values().two_factor)
.focus_handle(focus)
.invalid(f.invalid("two_factor"))
.on_toggle(form.on_change(field!(two_factor))),
),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-switch-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-switch-save", "Save").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Complex Forms
Radio cards, a select, a checkbox list and a switch, all in one schema.
use gpui::{div, prelude::*, px, App, SharedString, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::checkbox::Checkbox;
use crate::ui::field::{Field, FieldSet};
use crate::ui::form::{array, debug_json, field, string, Form, FormExt, Schema};
use crate::ui::radio_group::RadioGroup;
use crate::ui::select::{Select, SelectOption};
use crate::ui::separator::Separator;
use crate::ui::switch::Switch;
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Debug, PartialEq)]
struct Preferences {
plan: String,
billing_period: String,
addons: Vec<String>,
email_notifications: bool,
}
impl Default for Preferences {
fn default() -> Self {
Self {
plan: "basic".into(),
billing_period: String::new(),
addons: Vec::new(),
email_notifications: false,
}
}
}
const PLANS: [(&str, &str, &str); 2] = [
("basic", "Basic", "For individuals and small teams"),
("pro", "Pro", "For businesses with higher demands"),
];
const ADDONS: [(&str, &str, &str); 3] = [
("analytics", "Analytics", "Advanced analytics and reporting"),
("backup", "Backup", "Automated daily backups"),
("support", "Priority Support", "24/7 premium customer support"),
];
fn preferences_schema() -> Schema<Preferences> {
Schema::<Preferences>::new()
.field(
field!(plan),
string().min(1, "Please select a subscription plan.").refine(
|plan| plan == "basic" || plan == "pro",
"Invalid plan selection. Please choose Basic or Pro.",
),
)
.field(field!(billing_period), string().min(1, "Please select a billing period."))
.field(
field!(addons),
array()
.min(1, "Please select at least one add-on")
.max(3, "You can select up to 3 add-ons"),
)
}
pub fn form_complex(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-complex", cx, |_, _| {
Form::new(Preferences::default())
.schema(preferences_schema())
.on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let billing_open = window.use_keyed_state("form-complex-billing-open", cx, |_, _| false);
let plan_focus = form.focus_handle(&field!(plan), window, cx);
let billing_focus = form.focus_handle(&field!(billing_period), window, cx);
let addon_focus: Vec<_> = (0..ADDONS.len())
.map(|ix| form.focus_handle_at(&field!(addons), ix, window, cx))
.collect();
let email_focus = form.focus_handle(&field!(email_notifications), window, cx);
let f = form.read(cx);
let values = f.values();
let plan = PLANS
.iter()
.fold(
RadioGroup::new(
"form-complex-plan",
PLANS.iter().position(|(id, _, _)| *id == values.plan),
)
.cards(true)
.focus_handle(plan_focus)
.invalid(f.invalid("plan")),
|group, (_, title, description)| group.option_with_description(*title, *description),
)
.on_change(form.on_change_with(field!(plan), |plan: &mut String, ix: &usize| {
if let Some((id, _, _)) = PLANS.get(*ix) {
*plan = id.to_string();
}
}));
let billing = Select::new(
"form-complex-billing",
(!values.billing_period.is_empty()).then(|| SharedString::from(values.billing_period.clone())),
*billing_open.read(cx),
)
.placeholder("Select")
.width(px(398.))
.focus_handle(billing_focus)
.invalid(f.invalid("billing_period"))
.option(SelectOption::new("monthly", "Monthly"))
.option(SelectOption::new("yearly", "Yearly"))
.on_open_change(move |next, _, cx| {
billing_open.update(cx, |open, cx| {
*open = *next;
cx.notify();
})
})
.on_change(form.on_change_with(
field!(billing_period),
|period: &mut String, value: &SharedString| *period = value.to_string(),
));
let addons_invalid = f.invalid("addons");
let addons = ADDONS.iter().enumerate().fold(
div().flex().flex_col().gap_4(),
|list, (ix, (id, title, description))| {
let checked = values.addons.iter().any(|addon| addon == id);
list.child(
Checkbox::new(("form-complex-addon", ix), checked)
.label(*title)
.description(*description)
.focus_handle(addon_focus[ix].clone())
.invalid(addons_invalid)
.on_toggle(form.on_change_with(field!(addons), move |addons: &mut Vec<String>, on: &bool| {
addons.retain(|addon| addon != id);
if *on {
addons.push(id.to_string());
}
})),
)
},
);
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("You're almost there!")
.description("Choose your subscription plan and billing period.")
.child(
div()
.flex()
.flex_col()
.gap_6()
.child(
FieldSet::new()
.legend("Subscription Plan")
.description("Choose your subscription plan.")
.child(plan)
.when_some(f.error("plan"), |set, error| set.child(Field::new().error(error))),
)
.child(Separator::horizontal())
.child(
f.field("billing_period")
.label("Billing Period")
.description("Choose how often you want to be billed.")
.child(billing),
)
.child(Separator::horizontal())
.child(
FieldSet::new()
.legend("Add-ons")
.description("Select additional features you'd like to include.")
.child(addons)
.when_some(f.error("addons"), |set, error| set.child(Field::new().error(error))),
)
.child(Separator::horizontal())
.child(
Field::new()
.horizontal(true)
.label("Email Notifications")
.description("Receive email updates about your subscription")
.child(
Switch::new("form-complex-email", values.email_notifications)
.focus_handle(email_focus)
.on_toggle(form.on_change(field!(email_notifications))),
),
),
)
.footer(
div()
.flex()
.gap_2()
.child(Button::new("form-complex-save", "Save Preferences").on_click(form.handle_submit()))
.child(
Button::new("form-complex-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
),
),
)
.child(Toaster::new())
}Watching Values
A view that reads the form re-renders when it changes, so reading a value while rendering is watch(name). To react elsewhere, subscribe: form.watch calls back with one field's new value, form.watch_all with every value and the name that changed. react-hook-form calls back inside setValue; GPUI delivers the call when the form's update returns. That is still before the next frame draws, so whatever the callback changes shows in the same frame, but code later in the same form.update doesn't see it yet.
// While rendering: read the value; the view re-renders when the form changes.
let plan = form.read(cx).get_value(&field!(plan));
// Anywhere else: subscribe. Keep the subscription for as long as you want the calls.
let subscription = form.watch(field!(plan), cx, |plan: &String, cx| {
// Recalculate a price, enable a section...
});
let all = form.watch_all(cx, |values, changed, cx| { /* changed: Option<&SharedString> */ });Form State
The form answers what formState does. get_field_state(name) returns one field's invalid, is_dirty, is_touched, is_validating and error.
| is_dirty() | The values differ from the defaults. |
| dirty_fields() | Names of the fields changed away from their defaults. |
| touched_fields() | Names of the fields that have lost focus. |
| is_valid() | The values pass the schema and every async check that has run. |
| is_validating() | An async check is running. |
| is_submitting() | A submit is waiting for async checks or running its action. |
| is_submitted() | The form was submitted since it was created or reset, valid or not. |
| is_submit_successful() | The last submit passed and its action succeeded. |
| submit_count() | Submits since the form was created or reset. |
| is_loading() | load_values is still waiting for values. |
| default_values() | The values reset returns to. |
use std::time::Duration;
use gpui::{div, prelude::*, px, App, SharedString, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{field, string, Form, FormExt, Mode, ResetOptions, Schema};
use crate::ui::switch::Switch;
#[derive(Clone, Default, Debug, PartialEq)]
struct Account {
email: String,
username: String,
}
const MONO: &str = "Geist Mono";
fn account_schema() -> Schema<Account> {
Schema::<Account>::new()
.field(field!(email), string().email("Enter a valid email address."))
.field(field!(username), string().min(3, "Username must be at least 3 characters."))
}
pub fn form_state(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-state", cx, |_, _| {
Form::new(Account::default()).schema(account_schema()).mode(Mode::OnTouched)
});
// `watch_all` calls back on every change; the subscription lives as long as this state.
let last_change = window.use_keyed_state("form-state-last-change", cx, |_, _| None::<SharedString>);
window.use_keyed_state("form-state-watch", cx, |_, cx| {
let last_change = last_change.clone();
form.watch_all(cx, move |_, name, cx| {
let name = name.cloned().unwrap_or_else(|| "(reset)".into());
last_change.update(cx, |last, cx| {
*last = Some(name);
cx.notify();
})
})
});
let email = form.input(field!(email), window, cx, |input| input.placeholder("m@example.com"));
let username = form.input(field!(username), window, cx, |input| input.placeholder("shadcn"));
let theme = cx.theme();
let (muted, foreground, border) = (theme.muted_foreground, theme.foreground, theme.border);
let f = form.read(cx);
let list = |names: Vec<SharedString>| -> String {
let quoted: Vec<String> = names.iter().map(|name| format!("{name:?}")).collect();
format!("[{}]", quoted.join(", "))
};
let rows: Vec<(&str, String)> = vec![
("isDirty", f.is_dirty().to_string()),
("dirtyFields", list(f.dirty_fields())),
("touchedFields", list(f.touched_fields())),
("isValid", f.is_valid().to_string()),
("isValidating", f.is_validating().to_string()),
("isSubmitted", f.is_submitted().to_string()),
("isSubmitSuccessful", f.is_submit_successful().to_string()),
("submitCount", f.submit_count().to_string()),
("isLoading", f.is_loading().to_string()),
("disabled", f.is_disabled().to_string()),
("watch(email)", format!("{:?}", f.values().email)),
(
"last change",
last_change.read(cx).clone().map_or("none".into(), |name| name.to_string()),
),
];
let inspector = rows.into_iter().fold(
div().flex().flex_col().gap_1().font_family(MONO).text_xs(),
|panel, (name, value)| {
panel.child(
div()
.flex()
.justify_between()
.gap_4()
.child(div().text_color(muted).child(name))
.child(div().text_color(foreground).truncate().child(value)),
)
},
);
let actions = {
let (load, keep_values, keep_errors, disable) =
(form.downgrade(), form.downgrade(), form.downgrade(), form.downgrade());
div()
.flex()
.flex_wrap()
.gap_2()
.child(
Button::new("form-state-load", "Load profile")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.disabled(f.is_loading())
.on_click(move |_, window, cx| {
load.update(cx, |form, cx| {
// Stands in for a request: answers after a second.
form.load_values(
|cx| async move {
cx.background_executor().timer(Duration::from_millis(1000)).await;
Account {
email: "ada@example.com".into(),
username: "ada".into(),
}
},
window,
cx,
)
})
.ok();
}),
)
.child(
Button::new("form-state-reset", "Reset")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.on_click(form.handle_reset()),
)
.child(
Button::new("form-state-keep-values", "Reset, keep values")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.on_click(move |_, window, cx| {
let options = ResetOptions {
keep_values: true,
..ResetOptions::default()
};
keep_values.update(cx, |form, cx| form.reset_with(None, options, window, cx)).ok();
}),
)
.child(
Button::new("form-state-keep-errors", "Reset, keep errors")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.on_click(move |_, window, cx| {
let options = ResetOptions {
keep_errors: true,
..ResetOptions::default()
};
keep_errors.update(cx, |form, cx| form.reset_with(None, options, window, cx)).ok();
}),
)
.child(
Switch::new("form-state-disabled", f.is_disabled())
.label("Disable form")
.size(crate::ui::switch::SwitchSize::Sm)
.on_toggle(move |on, _, cx| {
disable.update(cx, |form, cx| form.set_disabled(*on, cx)).ok();
}),
)
};
div()
.w(px(672.))
.flex()
.gap_4()
.items_start()
.child(
div().w(px(320.)).flex_none().child(
Card::new()
.title("Account")
.description("Edit, blur and submit to watch the state change.")
.child(
div()
.flex()
.flex_col()
.gap_5()
.child(f.field("email").label("Email").disabled(f.is_disabled()).child(email))
.child(f.field("username").label("Username").disabled(f.is_disabled()).child(username)),
)
.footer(
Button::new("form-state-save", "Save")
.disabled(f.is_disabled())
.on_click(form.handle_submit()),
),
),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap_4()
.p_4()
.rounded_lg()
.border_1()
.border_color(border)
.child(div().text_sm().font_weight(gpui::FontWeight::MEDIUM).child("formState"))
.child(inspector)
.child(actions),
)
}Setting Values
Control handlers call set_value, which acts like the user: the field turns dirty and validates as the mode says. From code, set_value_with takes SetValueOptions like setValue's options.
form.update(cx, |form, cx| {
// As if the user picked it: dirty, validated as the mode says.
form.set_value(&field!(plan), "pro".to_string(), window, cx);
// From code, like setValue(name, value, options): only the value changes unless you ask.
form.set_value_with(
&field!(plan),
"pro".to_string(),
SetValueOptions { should_validate: true, should_dirty: true, should_touch: false },
window,
cx,
);
});Values from outside
Like the values prop, set_values takes values loaded elsewhere and makes them the defaults too, so the form isn't dirty. load_values is async defaultValues; the Load profile button above uses it.
// Values from outside the form, such as a query result: replaces values and defaults.
form.set_values(profile, window, cx);
// Async defaults: is_loading() is true until the future resolves.
form.load_values(|cx| async move { fetch_profile(cx).await }, window, cx);Submitting
handle_submit uses the form's on_success and on_invalid. handle_submit_with takes both handlers for one button, like handleSubmit(onValid, onInvalid). Pressing the button with the pointer takes focus off the field being edited, so that field turns touched, as its blur does in a browser; submitting with Enter from a text input leaves it untouched. For server actions, see Actions.
Button::new("save", "Save").on_click(form.handle_submit_with(
|values, window, cx| { /* valid: after any action succeeds */ },
|errors, window, cx| { /* invalid: every error, in field order */ },
))Disabled
A disabled form disables its bound inputs and takes them out of the Tab order, its handlers ignore changes, and submit and reset do nothing. Controls the form doesn't own, and your buttons, show it when you pass f.is_disabled() or f.field_disabled(name) to their disabled. A disabled field isn't validated.
Form::new(values).disabled(true) // the whole form
Form::new(values).disable_field("email") // one field: not validated, changes ignored
form.set_disabled(true, cx);
Button::new("save", "Save").disabled(f.is_disabled()).on_click(form.handle_submit())
Select::new("plan", value, open).disabled(f.field_disabled("plan"))Resetting the Form
reset returns to the default values and clears errors, touched and dirty fields and the submit count. Bound inputs update their text, and a pending submit is abandoned. reset_with takes new values and ResetOptions (keep_errors, keep_dirty, keep_values, keep_defaults, keep_submit_count, keep_touched, keep_dirty_values); reset_field resets one field. keep_dirty_values takes the new values only for fields the user hasn't changed and keeps the rest, with their dirty state, like keepDirtyValues. A changed field on an array row whose rows have since moved keeps its whole array.
form.update(cx, |form, cx| {
form.reset(window, cx);
// New values that also become the defaults, keeping what the options say.
form.reset_with(Some(loaded), ResetOptions { keep_errors: true, ..Default::default() }, window, cx);
// Fresh server values for every field the user hasn't changed, like keepDirtyValues.
form.reset_with(Some(fresh), ResetOptions { keep_dirty_values: true, ..Default::default() }, window, cx);
// One field, optionally with a new default.
form.reset_field(&field!(email), ResetFieldOptions::default(), window, cx);
// Errors only: one field, several, or all.
form.clear_errors_of(["email", "password"], cx);
});Array Fields
A Vec field holds a list of items the user can add to and remove from, like useFieldArray.
use gpui::{div, prelude::*, px, App, Window};
use crate::icons::{icon, ARROW_UP, X};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::field::{Field, FieldSet};
use crate::ui::form::{array, debug_json, field, string, Form, FormExt, Schema};
use crate::ui::input_group::InputGroup;
use crate::ui::toast::{toast, Toast, Toaster};
const MAX_EMAILS: usize = 5;
#[derive(Clone, Default, Debug, PartialEq)]
struct Email {
address: String,
}
#[derive(Clone, Debug, PartialEq)]
struct ContactEmails {
emails: Vec<Email>,
}
fn contact_schema() -> Schema<ContactEmails> {
Schema::<ContactEmails>::new()
.field(
field!(emails),
array()
.min(1, "Add at least one email address.")
.max(MAX_EMAILS, "You can add up to 5 email addresses."),
)
.each(field!(emails), field!(address), string().email("Enter a valid email address."))
}
pub fn form_array(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-array", cx, |_, _| {
Form::new(ContactEmails {
emails: vec![Email::default(), Email::default()],
})
.schema(contact_schema())
.on_success(|values, _, cx| {
toast(
Toast::new("You submitted the following values:").code(debug_json(values)),
cx,
)
})
});
let muted = cx.theme().muted_foreground;
let keys = form.read(cx).keys(&field!(emails));
let count = keys.len();
let rows = keys.into_iter().enumerate().map(|(ix, key)| {
let input = form.item_input(key, field!(emails[ix].address), window, cx, |input| {
input.bare().placeholder("name@example.com")
});
let (remove, raise) = (form.downgrade(), form.downgrade());
let group = InputGroup::new(input).when(count > 1, |group| {
group.trailing(
div()
.flex()
// The first row has nowhere to move up to.
.when(ix > 0, |this| {
this.child(
Button::new(("form-array-up", key), "")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.icon_only()
.leading(icon(ARROW_UP).text_color(muted))
.on_click(move |_, _, cx| {
raise
.update(cx, |form, cx| form.swap(&field!(emails), ix, ix - 1, cx))
.ok();
}),
)
})
.child(
Button::new(("form-array-remove", key), "")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.icon_only()
.leading(icon(X).text_color(muted))
.on_click(move |_, _, cx| {
remove
.update(cx, |form, cx| form.remove(&field!(emails), ix, cx))
.ok();
}),
),
)
});
form.read(cx).field(&format!("emails.{ix}.address")).child(group)
});
let rows: Vec<_> = rows.collect();
let f = form.read(cx);
let (add, insert) = (form.downgrade(), form.downgrade());
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Contact Emails")
.description("Manage your contact email addresses.")
.child(
FieldSet::new()
.legend("Email Addresses")
.description("Add up to 5 email addresses where we can contact you.")
.child(div().flex().flex_col().gap_4().children(rows))
.when_some(f.error("emails"), |set, error| set.child(Field::new().error(error)))
.child(
div()
.flex()
.gap_2()
.child(
Button::new("form-array-add", "Add Email Address")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.disabled(count >= MAX_EMAILS)
.on_click(move |_, _, cx| {
add.update(cx, |form, cx| {
form.append(&field!(emails), Email::default(), cx)
})
.ok();
}),
)
.child(
Button::new("form-array-insert", "Insert at Top")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.disabled(count >= MAX_EMAILS)
.on_click(move |_, _, cx| {
insert
.update(cx, |form, cx| {
form.insert(&field!(emails), 0, Email::default(), cx)
})
.ok();
}),
),
),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-array-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-array-save", "Save").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Stable keys
keys returns one key per item that stays with the item when others are removed or moved. Create each row's input with form.item_input(key, ...) so the row keeps its input and focus.
let keys = form.read(cx).keys(&field!(emails));
let count = keys.len();
let rows = keys.into_iter().enumerate().map(|(ix, key)| {
let input = form.item_input(key, field!(emails[ix].address), window, cx, |input| {
input.bare().placeholder("name@example.com")
});
let (remove, raise) = (form.downgrade(), form.downgrade());
let group = InputGroup::new(input).when(count > 1, |group| {
group.trailing(
div()
.flex()
// The first row has nowhere to move up to.
.when(ix > 0, |this| {
this.child(
Button::new(("form-array-up", key), "")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.icon_only()
.leading(icon(ARROW_UP).text_color(muted))
.on_click(move |_, _, cx| {
raise
.update(cx, |form, cx| form.swap(&field!(emails), ix, ix - 1, cx))
.ok();
}),
)
})
.child(
Button::new(("form-array-remove", key), "")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.icon_only()
.leading(icon(X).text_color(muted))
.on_click(move |_, _, cx| {
remove
.update(cx, |form, cx| form.remove(&field!(emails), ix, cx))
.ok();
}),
),
)
});
form.read(cx).field(&format!("emails.{ix}.address")).child(group)
});Adding, moving and removing items
append, prepend and insert add items; remove drops one with its input and errors; swap and move_item reorder; update replaces one item and replace all of them. Errors, touched and dirty state, inputs and focus stay with their rows, including errors from the server. In the demo, submit with a bad address, then move its row up or insert one above it.
Other controls on rows
A select, checkbox or other control on a row takes its handle from form.item_focus_handle(key, &field!(members[ix].role), ...). The handle stays with the row, so set_focus("members.1.role") and a failed submit reach it wherever the row has moved. Save the demo below to see focus land on the second row's select.
use gpui::{div, prelude::*, px, App, SharedString, Window};
use crate::icons::{icon, X};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{debug_json, field, string, Form, FormExt, Schema};
use crate::ui::select::{Select, SelectOption};
use crate::ui::toast::{toast, Toast, Toaster};
const ROLES: [(&str, &str); 3] = [("admin", "Admin"), ("editor", "Editor"), ("viewer", "Viewer")];
#[derive(Clone, Default, Debug, PartialEq)]
struct Member {
name: String,
role: String,
}
#[derive(Clone, Debug, PartialEq)]
struct Team {
members: Vec<Member>,
}
fn team_schema() -> Schema<Team> {
Schema::<Team>::new()
.each(field!(members), field!(name), string().min(1, "Enter a name."))
.each(field!(members), field!(role), string().min(1, "Pick a role."))
}
pub fn form_array_controls(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-array-controls", cx, |_, _| {
Form::new(Team {
members: vec![
Member { name: "Ada Lovelace".into(), role: "admin".into() },
Member { name: "Grace Hopper".into(), role: String::new() },
],
})
.schema(team_schema())
.on_success(|values, _, cx| {
toast(Toast::new("You submitted the following values:").code(debug_json(values)), cx)
})
});
let muted = cx.theme().muted_foreground;
let keys = form.read(cx).keys(&field!(members));
let count = keys.len();
let rows: Vec<_> = keys
.into_iter()
.enumerate()
.map(|(ix, key)| {
let name = form.item_input(key, field!(members[ix].name), window, cx, |input| input.placeholder("Name"));
// Keyed by the row, so the handle (and the open list) stay with the row as rows move.
let role_focus = form.item_focus_handle(key, &field!(members[ix].role), window, cx);
let open = window.use_keyed_state(("form-array-controls-open", key), cx, |_, _| false);
let f = form.read(cx);
let role = f.get_value(&field!(members[ix].role)).cloned().unwrap_or_default();
let role_path = format!("members.{ix}.role");
let name_path = format!("members.{ix}.name");
let select = ROLES
.iter()
.fold(
Select::new(
("form-array-controls-role", key),
(!role.is_empty()).then(|| SharedString::from(role)),
*open.read(cx),
)
.placeholder("Role")
.width(px(128.))
.focus_handle(role_focus)
.invalid(f.invalid(&role_path)),
|select, (value, label)| select.option(SelectOption::new(*value, *label)),
)
.on_open_change(move |next, _, cx| {
open.update(cx, |open, cx| {
*open = *next;
cx.notify();
})
})
.on_change(form.on_change_with(field!(members[ix].role), |role: &mut String, value: &SharedString| {
*role = value.to_string()
}));
let error = f.error(&name_path).or_else(|| f.error(&role_path));
let remove = form.downgrade();
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.flex()
.items_center()
.gap_2()
.child(div().flex_1().child(name))
.child(select)
.child(
Button::new(("form-array-controls-remove", key), "")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.icon_only()
.disabled(count == 1)
.leading(icon(X).text_color(muted))
.on_click(move |_, _, cx| {
remove.update(cx, |form, cx| form.remove(&field!(members), ix, cx)).ok();
}),
),
)
.when_some(error, |row, error| {
row.child(div().text_sm().text_color(cx.theme().destructive).child(error))
})
})
.collect();
let add = form.downgrade();
div()
.w(px(480.))
.flex()
.flex_col()
.child(
Card::new()
.title("Team")
.description("Everyone on the team needs a role.")
.child(
div()
.flex()
.flex_col()
.gap_4()
.children(rows)
.child(
div().flex().child(
Button::new("form-array-controls-add", "Add Member")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.on_click(move |_, _, cx| {
add.update(cx, |form, cx| form.append(&field!(members), Member::default(), cx))
.ok();
}),
),
),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-array-controls-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(Button::new("form-array-controls-save", "Save").on_click(form.handle_submit())),
),
)
.child(Toaster::new())
}Array Validation
Rules on the array check its length. each checks a field of every item, and its errors land on paths like emails.1.address.
fn contact_schema() -> Schema<ContactEmails> {
Schema::<ContactEmails>::new()
.field(
field!(emails),
array()
.min(1, "Add at least one email address.")
.max(MAX_EMAILS, "You can add up to 5 email addresses."),
)
.each(field!(emails), field!(address), string().email("Enter a valid email address."))
}