Typed form state with a zod-like schema, validation modes, field bindings and async submit actions.
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 into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/form.rs.src/ui/form.rs //! Forms for GPUI: typed values, a schema of rules, validation timing, field bindings and //! async submit actions. What react-hook-form, zod and `useActionState` give a React app. //! //! Your own struct holds the values; a `Schema` says what is valid; a `Form` entity tracks //! errors, touched and dirty fields, focus, submits and the pending action: //! //! ```ignore //! #[derive(Clone, Default, Debug, PartialEq)] //! struct Profile { username: String } //! //! // `Schema::<Profile>` names the values type up front: `field!` needs it to read the field. //! let form = cx.new(|_| { //! Form::new(Profile::default()) //! .schema(Schema::<Profile>::new().field(field!(username), string().min(3, "Too short."))) //! .on_success(|values, _, cx| toast(Toast::new("Saved").description(debug_json(values)), cx)) //! }); //! let username = form.input(field!(username), window, cx, |input| input.placeholder("shadcn")); //! form.read(cx).field("username").label("Username").child(username) //! ``` use std::{ cell::RefCell, collections::{HashMap, HashSet}, fmt::{Debug, Write as _}, future::Future, pin::Pin, rc::Rc, task::{Context as TaskContext, Poll, Waker}, time::Duration, }; use gpui::{ prelude::*, App, AsyncApp, ClickEvent, Context, Entity, EventEmitter, FocusHandle, Focusable, SharedString, Subscription, Task, Window, }; use crate::theme::focus_visibly; use crate::ui::field::Field; use crate::ui::input::{InputEvent, TextInput}; type Getter<T, V> = Rc<dyn Fn(&T) -> Option<&V>>; type GetterMut<T, V> = Rc<dyn Fn(&mut T) -> Option<&mut V>>; type ActionFuture = Pin<Box<dyn Future<Output = Result<(), ServerErrors>>>>; type Action<T> = Rc<dyn Fn(T, AsyncApp) -> ActionFuture>; type SuccessHandler<T> = Rc<dyn Fn(&T, &mut Window, &mut App)>; type InvalidHandler = Rc<dyn Fn(&[Issue], &mut Window, &mut App)>; type CheckFuture = Pin<Box<dyn Future<Output = Result<(), SharedString>>>>; type AsyncCheck<T> = Rc<dyn Fn(&T, AsyncApp) -> CheckFuture>; type LoadFuture<T> = Pin<Box<dyn Future<Output = T>>>; /// Swaps one field's value between two `T`s, so `keep_dirty_values` can carry a dirty value /// into new values without `V: Clone`. type Swap<T> = Rc<dyn Fn(&mut T, &mut T)>; // Pinning the closures' signatures here is what lets them borrow from their argument. fn getter<T, V>(get: impl Fn(&T) -> Option<&V> + 'static) -> Getter<T, V> { Rc::new(get) } fn getter_mut<T, V>(get: impl Fn(&mut T) -> Option<&mut V> + 'static) -> GetterMut<T, V> { Rc::new(get) } /// Names a field of `T` holding a `V`, like `"title"` or `"emails.2.address"`. Build one with /// the [`field!`] macro rather than by hand. pub struct FieldPath<T, V> { name: SharedString, get: Getter<T, V>, get_mut: GetterMut<T, V>, } impl<T, V> Clone for FieldPath<T, V> { fn clone(&self) -> Self { Self { name: self.name.clone(), get: self.get.clone(), get_mut: self.get_mut.clone(), } } } impl<T: 'static, V: 'static> FieldPath<T, V> { /// A path from its name and accessors; `field!(title)` writes this for you. The accessors /// are plain `fn`s so the macro's closures learn `T` from where the path is used. pub fn new( name: impl Into<SharedString>, get: fn(&T) -> Option<&V>, get_mut: fn(&mut T) -> Option<&mut V>, ) -> Self { Self { name: name.into(), get: getter(get), get_mut: getter_mut(get_mut), } } /// The dotted name errors are keyed by, such as `emails.2.address`. pub fn name(&self) -> &SharedString { &self.name } /// The value, or `None` when the path points past the end of an array. pub fn get<'a>(&self, values: &'a T) -> Option<&'a V> { (self.get)(values) } pub fn get_mut<'a>(&self, values: &'a mut T) -> Option<&'a mut V> { (self.get_mut)(values) } /// `outer.then(inner)` as a function, for the `field!` macro. pub fn join<W: 'static>(outer: Self, inner: FieldPath<V, W>) -> FieldPath<T, W> { outer.then(inner) } /// Continues into a field of the value, such as an array item's `address`. pub fn then<W: 'static>(&self, next: FieldPath<V, W>) -> FieldPath<T, W> { let (get, next_get) = (self.get.clone(), next.get.clone()); let (get_mut, next_get_mut) = (self.get_mut.clone(), next.get_mut.clone()); FieldPath { name: format!("{}.{}", self.name, next.name).into(), get: getter(move |values: &T| get(values).and_then(|value| next_get(value))), get_mut: getter_mut(move |values: &mut T| { get_mut(values).and_then(|value| next_get_mut(value)) }), } } } impl<T: 'static, E: 'static> FieldPath<T, Vec<E>> { /// `array.at(index)` as a function, for the `field!` macro. pub fn index(array: Self, index: usize) -> FieldPath<T, E> { array.at(index) } /// The item at `index` of an array field. pub fn at(&self, index: usize) -> FieldPath<T, E> { let (get, get_mut) = (self.get.clone(), self.get_mut.clone()); FieldPath { name: format!("{}.{index}", self.name).into(), get: getter(move |values: &T| get(values).and_then(|items| items.get(index))), get_mut: getter_mut(move |values: &mut T| { get_mut(values).and_then(|items| items.get_mut(index)) }), } } } /// A [`FieldPath`] to a field of your values struct: `field!(title)`, `field!(address.city)`, /// or `field!(emails[ix].address)` into an array item. macro_rules! field { // Associated-function calls rather than `.at()` / `.then()`, so the value type flows in // from where the path is used and the closures below can name its fields. ($head:ident [$ix:expr] . $($rest:tt)+) => { $crate::ui::form::FieldPath::join( $crate::ui::form::FieldPath::index($crate::ui::form::field!($head), $ix), $crate::ui::form::field!($($rest)+), ) }; ($head:ident [$ix:expr]) => { $crate::ui::form::FieldPath::index($crate::ui::form::field!($head), $ix) }; ($head:ident . $($rest:tt)+) => { $crate::ui::form::FieldPath::join($crate::ui::form::field!($head), $crate::ui::form::field!($($rest)+)) }; ($head:ident) => { $crate::ui::form::FieldPath::new( stringify!($head), |values| Some(&values.$head), |values| Some(&mut values.$head), ) }; } pub(crate) use field; /// How many failed rules a field reports, like react-hook-form's `criteriaMode`. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum CriteriaMode { /// The first failed rule's message. #[default] FirstError, /// Every failed rule's message, read back with [`Form::error_messages`]. All, } /// The rules for one value, each with the message shown when it fails. Start from /// [`string`], [`number`], [`array`], [`boolean`] or [`optional`]; add your own with `refine`. pub struct Check<V> { tests: Vec<(Box<dyn Fn(&V) -> bool>, SharedString)>, } impl<V: 'static> Check<V> { /// A check with no rules. pub fn new() -> Self { Self { tests: Vec::new() } } /// Passes when `test` returns true, like zod's `.refine`. pub fn refine(mut self, test: impl Fn(&V) -> bool + 'static, message: impl Into<SharedString>) -> Self { self.tests.push((Box::new(test), message.into())); self } /// The messages of the rules that fail: the first one, or all of them. fn failures(&self, value: &V, criteria: CriteriaMode) -> Vec<SharedString> { let failed = self.tests.iter().filter(|(test, _)| !test(value)).map(|(_, message)| message.clone()); match criteria { CriteriaMode::FirstError => failed.take(1).collect(), CriteriaMode::All => failed.collect(), } } } impl<V: 'static> Default for Check<V> { fn default() -> Self { Self::new() } } /// Rules for a `String`. pub fn string() -> Check<String> { Check::new() } impl Check<String> { /// At least `len` characters (not bytes, so "한글" is two). pub fn min(self, len: usize, message: impl Into<SharedString>) -> Self { self.refine(move |value| value.chars().count() >= len, message) } /// At most `len` characters. pub fn max(self, len: usize, message: impl Into<SharedString>) -> Self { self.refine(move |value| value.chars().count() <= len, message) } /// Not empty once surrounding whitespace is trimmed. pub fn required(self, message: impl Into<SharedString>) -> Self { self.refine(|value| !value.trim().is_empty(), message) } /// Shaped like an email address: one `@`, a dotted domain, no spaces. pub fn email(self, message: impl Into<SharedString>) -> Self { self.refine(|value| is_email(value), message) } } fn is_email(value: &str) -> bool { let Some((local, domain)) = value.split_once('@') else { return false; }; !local.is_empty() && !value.chars().any(char::is_whitespace) && !domain.contains('@') && domain.split('.').count() >= 2 && domain.split('.').all(|part| !part.is_empty()) } /// Number types `number()` accepts. pub trait Number: PartialOrd + Copy + 'static {} impl Number for i32 {} impl Number for i64 {} impl Number for u32 {} impl Number for u64 {} impl Number for usize {} impl Number for f32 {} impl Number for f64 {} /// Rules for a number. pub fn number<N: Number>() -> Check<N> { Check::new() } impl<N: Number> Check<N> { /// At least `min`, inclusive. pub fn min(self, min: N, message: impl Into<SharedString>) -> Self { self.refine(move |value| *value >= min, message) } /// At most `max`, inclusive. pub fn max(self, max: N, message: impl Into<SharedString>) -> Self { self.refine(move |value| *value <= max, message) } } /// Rules for a `Vec`, such as how many items it may hold. Check each item with /// [`Schema::each`]. pub fn array<E: 'static>() -> Check<Vec<E>> { Check::new() } impl<E: 'static> Check<Vec<E>> { /// At least `len` items. pub fn min(self, len: usize, message: impl Into<SharedString>) -> Self { self.refine(move |items| items.len() >= len, message) } /// At most `len` items. pub fn max(self, len: usize, message: impl Into<SharedString>) -> Self { self.refine(move |items| items.len() <= len, message) } } /// Rules for a `bool`, such as a switch that must be on. pub fn boolean() -> Check<bool> { Check::new() } impl Check<bool> { /// Passes only when the value is `true`. pub fn accepted(self, message: impl Into<SharedString>) -> Self { self.refine(|value| *value, message) } } /// Rules for an `Option`, such as a select with nothing chosen yet. pub fn optional<V: 'static>() -> Check<Option<V>> { Check::new() } impl<V: 'static> Check<Option<V>> { /// Passes once a value is set. pub fn required(self, message: impl Into<SharedString>) -> Self { self.refine(|value| value.is_some(), message) } } /// A validation failure: which field, and what to tell the user. #[derive(Clone, Debug, PartialEq)] pub struct Issue { pub path: SharedString, pub message: SharedString, } type Rule<T> = Box<dyn Fn(&T, CriteriaMode, &mut Vec<Issue>)>; struct AsyncRule<T> { path: SharedString, check: AsyncCheck<T>, } /// What makes a `T` valid, like a zod object schema. Rules run in the order you add them, /// which is also the order "focus the first invalid field" follows. pub struct Schema<T> { rules: Vec<Rule<T>>, /// The field each rule reports on, in rule order, so errors can be sorted the same way. paths: Vec<SharedString>, async_rules: Vec<AsyncRule<T>>, } impl<T: 'static> Schema<T> { /// A schema that accepts everything. pub fn new() -> Self { Self { rules: Vec::new(), paths: Vec::new(), async_rules: Vec::new(), } } /// Checks one field. pub fn field<V: 'static>(mut self, path: FieldPath<T, V>, check: Check<V>) -> Self { self.paths.push(path.name().clone()); self.rules.push(Box::new(move |values, criteria, issues| { let Some(value) = path.get(values) else { return; }; for message in check.failures(value, criteria) { issues.push(Issue { path: path.name().clone(), message, }); } })); self } /// Checks a field of every array item; errors land on `emails.2.address`-style paths. pub fn each<E: 'static, V: 'static>( mut self, array: FieldPath<T, Vec<E>>, item: FieldPath<E, V>, check: Check<V>, ) -> Self { self.paths.push(array.name().clone()); self.rules.push(Box::new(move |values, criteria, issues| { let Some(items) = array.get(values) else { return; }; for (ix, entry) in items.iter().enumerate() { let Some(value) = item.get(entry) else { continue; }; for message in check.failures(value, criteria) { issues.push(Issue { path: format!("{}.{ix}.{}", array.name(), item.name()).into(), message, }); } } })); self } /// A rule across fields, such as "passwords match", reported on `path`. pub fn refine( mut self, path: impl Into<SharedString>, test: impl Fn(&T) -> bool + 'static, message: impl Into<SharedString>, ) -> Self { let (path, message) = (path.into(), message.into()); self.paths.push(path.clone()); self.rules.push(Box::new(move |values, _, issues| { if !test(values) { issues.push(Issue { path: path.clone(), message: message.clone(), }); } })); self } /// An async check of one field, such as "is this username free?" against a server. It /// runs only once the field's other rules pass, and its newer runs cancel older ones. /// Return `Err(message)` to fail. pub fn field_async<V: Clone + 'static, F>( mut self, path: FieldPath<T, V>, check: impl Fn(V, AsyncApp) -> F + 'static, ) -> Self where F: Future<Output = Result<(), SharedString>> + 'static, { let name = path.name().clone(); let check: AsyncCheck<T> = Rc::new(move |values, cx| match path.get(values) { Some(value) => Box::pin(check(value.clone(), cx)), None => Box::pin(async { Ok(()) }), }); self.async_rules.push(AsyncRule { path: name, check }); self } /// An async rule across fields, like zod's async `refine`, reported on `path`. pub fn refine_async<F>(mut self, path: impl Into<SharedString>, check: impl Fn(T, AsyncApp) -> F + 'static) -> Self where T: Clone, F: Future<Output = Result<(), SharedString>> + 'static, { let check: AsyncCheck<T> = Rc::new(move |values: &T, cx| Box::pin(check(values.clone(), cx))); self.async_rules.push(AsyncRule { path: path.into(), check, }); self } /// Every failure, at most one per field, in rule order. pub fn validate(&self, values: &T) -> Vec<Issue> { self.validate_with(values, CriteriaMode::FirstError) } /// Every failure in rule order: one per field, or with `CriteriaMode::All` every failed /// rule of every field. pub fn validate_with(&self, values: &T, criteria: CriteriaMode) -> Vec<Issue> { let mut issues = Vec::new(); for rule in &self.rules { rule(values, criteria, &mut issues); } if criteria == CriteriaMode::FirstError { let mut seen = HashSet::new(); issues.retain(|issue| seen.insert(issue.path.clone())); } issues } /// Where errors on `path` sort: the first rule that reports on it or a field containing /// it. Errors nothing reports on (from the server, say) go last. fn order(&self, path: &str) -> usize { self.paths .iter() .position(|rule| is_within(path, rule)) .unwrap_or(usize::MAX) } } impl<T: 'static> Default for Schema<T> { fn default() -> Self { Self::new() } } /// What a submit action reports back: errors for fields and/or one for the whole form. #[derive(Clone, Debug, Default, PartialEq)] pub struct ServerErrors { fields: Vec<Issue>, form: Option<SharedString>, } impl ServerErrors { pub fn new() -> Self { Self::default() } /// An error shown on one field, like "That name is taken." pub fn field(mut self, path: impl Into<SharedString>, message: impl Into<SharedString>) -> Self { self.fields.push(Issue { path: path.into(), message: message.into(), }); self } /// An error about the submission as a whole, read back with [`Form::form_error`]. pub fn form(mut self, message: impl Into<SharedString>) -> Self { self.form = Some(message.into()); self } } /// When fields validate before the first submit, like react-hook-form's `mode`. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum Mode { /// Only on submit. #[default] OnSubmit, /// When a field loses focus. OnBlur, /// On every change. OnChange, /// On a field's first blur, then on every change. OnTouched, /// On blur and on change. All, } /// When fields validate again after a submit, like react-hook-form's `reValidateMode`. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum ReValidateMode { /// On every change, so errors clear as the user fixes them. #[default] OnChange, /// When a field loses focus. OnBlur, /// Only on the next submit. OnSubmit, } /// Where the last submit got to. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum SubmitState { /// Not submitted since the form was created or reset. #[default] Idle, /// Async checks or the action are running. Pending, /// Valid, and the action (if any) succeeded. Succeeded, /// Invalid, or the action returned errors. Failed, } /// What a form tells its subscribers; see [`FormExt::watch`]. #[derive(Clone, Debug, PartialEq)] pub enum FormEvent { /// The value at this path, or something inside it, changed. Change(SharedString), /// The form was reset, or given new values from outside. Reset, } /// One field's state, like react-hook-form's `getFieldState`. #[derive(Clone, Debug, Default, PartialEq)] pub struct FieldState { pub invalid: bool, pub is_dirty: bool, pub is_touched: bool, pub is_validating: bool, pub error: Option<SharedString>, } /// Options for [`Form::set_value_with`], like react-hook-form's `setValue` options. All off by /// default: the value changes and nothing else does. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct SetValueOptions { /// Validate the field now. pub should_validate: bool, /// Update the field's dirty state. pub should_dirty: bool, /// Mark the field touched. pub should_touch: bool, } /// What [`Form::reset_with`] keeps instead of resetting, like react-hook-form's `reset` /// options. All off by default: a full reset. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct ResetOptions { pub keep_errors: bool, pub keep_dirty: bool, /// Keep the current values; new values passed to `reset_with` only become the defaults. pub keep_values: bool, /// Keep the defaults; new values passed to `reset_with` only become the values. pub keep_defaults: bool, /// Keep the submit count and submit state. pub keep_submit_count: bool, pub keep_touched: bool, /// Keep the values of dirty fields (and their dirty state); the other fields take the new /// values. Like `keepDirtyValues`, for refreshing a form from the server while the user edits. pub keep_dirty_values: bool, } /// What [`Form::reset_field`] keeps, like react-hook-form's `resetField` options. #[derive(Clone, Debug, PartialEq)] pub struct ResetFieldOptions<V> { pub keep_error: bool, pub keep_dirty: bool, pub keep_touched: bool, /// A new default for the field, which it is also reset to. pub default_value: Option<V>, } impl<V> Default for ResetFieldOptions<V> { fn default() -> Self { Self { keep_error: false, keep_dirty: false, keep_touched: false, default_value: None, } } } /// Which fields an operation covers: `"email"`, `["email", "password"]` or `Names::All`. #[derive(Clone, Debug, PartialEq)] pub enum Names { All, Some(Vec<SharedString>), } impl Names { /// Whether `path` is one of the names or inside one. pub fn covers(&self, path: &str) -> bool { match self { Names::All => true, Names::Some(names) => names.iter().any(|name| is_within(path, name)), } } } impl From<&str> for Names { fn from(name: &str) -> Self { Names::Some(vec![SharedString::from(name.to_string())]) } } impl From<String> for Names { fn from(name: String) -> Self { Names::Some(vec![name.into()]) } } impl From<SharedString> for Names { fn from(name: SharedString) -> Self { Names::Some(vec![name]) } } impl From<&SharedString> for Names { fn from(name: &SharedString) -> Self { Names::Some(vec![name.clone()]) } } impl<const N: usize> From<[&str; N]> for Names { fn from(names: [&str; N]) -> Self { Names::Some(names.iter().map(|name| SharedString::from(name.to_string())).collect()) } } impl From<Vec<SharedString>> for Names { fn from(names: Vec<SharedString>) -> Self { Names::Some(names) } } /// The result of [`Form::trigger`]: whether the fields passed, once their async checks /// finish. Await it (from `cx.spawn`), or read `now()` when no check is async. pub struct Validation(Rc<RefCell<Outcome>>); #[derive(Default)] struct Outcome { passed: Option<bool>, waker: Option<Waker>, } impl Validation { fn pending() -> Self { Self(Rc::default()) } /// The result, or `None` while async checks are still running. pub fn now(&self) -> Option<bool> { self.0.borrow().passed } } impl Future for Validation { type Output = bool; fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<bool> { let mut outcome = self.0.borrow_mut(); match outcome.passed { Some(passed) => Poll::Ready(passed), None => { outcome.waker = Some(cx.waker().clone()); Poll::Pending } } } } #[derive(Clone, Copy, Debug, PartialEq)] enum Source { Schema, Async, /// From `set_error` or an action. Stays until its own field changes; schema errors also /// clear once another field's change fixes them, like a "passwords match" rule. Manual, } #[derive(Clone)] struct Error { path: SharedString, /// The first is shown; `CriteriaMode::All` keeps the rest. messages: Vec<SharedString>, source: Source, } impl Error { fn issue(&self) -> Issue { Issue { path: self.path.clone(), message: self.messages.first().cloned().unwrap_or_default(), } } } /// What one submit calls when it ends: the form's own handlers, or a button's from /// `handle_submit_with`. struct Handlers<T> { on_success: Option<SuccessHandler<T>>, on_invalid: Option<InvalidHandler>, } /// A text input the form owns and keeps in sync with one field. struct Binding<T> { key: SharedString, /// The field's name now. After an array operation it can be ahead of `path`, which is /// refreshed when the row next renders. name: SharedString, path: FieldPath<T, String>, /// The row moved and `path` still points at its old index, so its text mustn't be synced. stale: bool, input: Entity<TextInput>, _subscriptions: [Subscription; 3], } /// Another control's focus handle, registered by [`FormExt::focus_handle`]. struct FocusBinding { key: SharedString, name: SharedString, handle: FocusHandle, _subscriptions: [Subscription; 2], } /// Marks the binding keys of inputs inside array items. const ITEM_KEY_PREFIX: &str = "#"; /// Item keys start here so they never collide with the `0..len` keys of an untouched array. const FIRST_ITEM_KEY: u64 = 1 << 32; /// A form over your values type `T`: its values and defaults, the schema, errors, touched /// and dirty fields, focus handles, submit count and the pending action. Create it once with /// `cx.new` (or `window.use_keyed_state`) and render from `form.read(cx)`. pub struct Form<T> { values: T, defaults: T, schema: Schema<T>, mode: Mode, re_validate_mode: ReValidateMode, criteria_mode: CriteriaMode, delay_error: Option<Duration>, should_focus_error: bool, errors: Vec<Error>, /// Errors waiting out `delay_error` before they show, each with its timer. delayed: HashMap<SharedString, Task<()>>, form_error: Option<SharedString>, touched: HashSet<SharedString>, dirty: HashSet<SharedString>, disabled: bool, disabled_fields: HashSet<SharedString>, submit_count: usize, state: SubmitState, bindings: Vec<Binding<T>>, focus: Vec<FocusBinding>, /// The binding key of the field that has focus, as of the last frame. focused: Option<SharedString>, /// How to carry each dirty field's value into new values, for `keep_dirty_values`. swaps: HashMap<SharedString, Swap<T>>, item_keys: HashMap<SharedString, Vec<u64>>, next_item_key: u64, /// Running async checks by field, with the run number that tells a stale result apart. validating: HashMap<SharedString, (u64, Task<()>)>, runs: u64, waiters: Vec<(Names, Rc<RefCell<Outcome>>)>, loading: Option<Task<()>>, action: Option<Action<T>>, on_success: Option<SuccessHandler<T>>, on_invalid: Option<InvalidHandler>, /// Dropping the task cancels the submit, which is how reset abandons one. task: Option<Task<()>>, } impl<T: 'static> EventEmitter<FormEvent> for Form<T> {} impl<T: Clone + PartialEq + 'static> Form<T> { /// A form starting at `defaults`, which `reset` returns to. pub fn new(defaults: T) -> Self { Self { values: defaults.clone(), defaults, schema: Schema::new(), mode: Mode::default(), re_validate_mode: ReValidateMode::default(), criteria_mode: CriteriaMode::default(), delay_error: None, should_focus_error: true, errors: Vec::new(), delayed: HashMap::new(), form_error: None, touched: HashSet::new(), dirty: HashSet::new(), disabled: false, disabled_fields: HashSet::new(), submit_count: 0, state: SubmitState::Idle, bindings: Vec::new(), focus: Vec::new(), focused: None, swaps: HashMap::new(), item_keys: HashMap::new(), next_item_key: FIRST_ITEM_KEY, validating: HashMap::new(), runs: 0, waiters: Vec::new(), loading: None, action: None, on_success: None, on_invalid: None, task: None, } } pub fn schema(mut self, schema: Schema<T>) -> Self { self.schema = schema; self } /// When fields validate before the first submit. See [`Mode`]. pub fn mode(mut self, mode: Mode) -> Self { self.mode = mode; self } /// When fields validate again after a submit. See [`ReValidateMode`]. pub fn re_validate_mode(mut self, mode: ReValidateMode) -> Self { self.re_validate_mode = mode; self } /// Whether a field keeps every failed rule's message. See [`CriteriaMode`]. pub fn criteria_mode(mut self, criteria: CriteriaMode) -> Self { self.criteria_mode = criteria; self } /// Waits this long after a change before showing a new error, and starts over on every /// change, so errors don't flash while the user types. Fixing the field clears its error /// at once, and a submit shows every error straight away. pub fn delay_error(mut self, delay: Duration) -> Self { self.delay_error = Some(delay); self } /// Whether a failed submit focuses the first invalid field (on by default). pub fn should_focus_error(mut self, focus: bool) -> Self { self.should_focus_error = focus; self } /// Disables every field: bound inputs turn disabled and leave the Tab order, the handlers /// from [`FormExt`] ignore changes, and submit and reset do nothing. Pass /// [`Form::is_disabled`] to other controls' and buttons' `.disabled(...)`. pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// Disables one field, like `register(name, { disabled: true })`: it isn't validated and /// its controls ignore changes. pub fn disable_field(mut self, name: impl Into<SharedString>) -> Self { self.disabled_fields.insert(name.into()); self } /// An async action that receives the valid values, like a server action. While it runs /// the form is pending and further submits are ignored; return `ServerErrors` to show /// errors on fields or on the form. pub fn action<F>( mut self, action: impl Fn(T, AsyncApp) -> F + 'static, ) -> Self where F: Future<Output = Result<(), ServerErrors>> + 'static, { self.action = Some(Rc::new(move |values, cx| Box::pin(action(values, cx)))); self } /// Runs after a valid submit, once the action (if any) has succeeded. pub fn on_success(mut self, handler: impl Fn(&T, &mut Window, &mut App) + 'static) -> Self { self.on_success = Some(Rc::new(handler)); self } /// Runs after a submit fails validation, with every error in field order: react-hook-form's /// `handleSubmit(onValid, onInvalid)`. pub fn on_invalid(mut self, handler: impl Fn(&[Issue], &mut Window, &mut App) + 'static) -> Self { self.on_invalid = Some(Rc::new(handler)); self } pub fn values(&self) -> &T { &self.values } /// The values, like `getValues()`. The same as [`Form::values`]. pub fn get_values(&self) -> &T { &self.values } /// One field's value, like `getValues(name)` or reading `watch(name)` while rendering. pub fn get_value<'a, V: 'static>(&'a self, path: &FieldPath<T, V>) -> Option<&'a V> { path.get(&self.values) } pub fn defaults(&self) -> &T { &self.defaults } /// The values `reset` returns to, like `formState.defaultValues`. pub fn default_values(&self) -> &T { &self.defaults } /// The error shown on a field, such as `"title"` or `"emails.2.address"`. pub fn error(&self, name: &str) -> Option<SharedString> { self.shown(name).and_then(|error| error.messages.first().cloned()) } /// Every failed rule's message for a field with `CriteriaMode::All`; just the shown one /// otherwise. Like react-hook-form's `errors[name].types`. pub fn error_messages(&self, name: &str) -> Vec<SharedString> { self.shown(name).map(|error| error.messages.clone()).unwrap_or_default() } fn shown(&self, name: &str) -> Option<&Error> { if self.delayed.contains_key(name) { return None; } self.errors.iter().find(|error| error.path.as_ref() == name) } /// Whether a field has an error; pass it to a control's `.invalid(...)`. pub fn invalid(&self, name: &str) -> bool { self.error(name).is_some() } /// Every shown error, in schema order. pub fn errors(&self) -> impl Iterator<Item = Issue> + '_ { self.errors .iter() .filter(|error| !self.delayed.contains_key(&error.path)) .map(Error::issue) } /// A `Field` for `name` that shows its error (every failed rule with /// `CriteriaMode::All`) and turns its label destructive. pub fn field(&self, name: &str) -> Field { Field::new().errors(self.error_messages(name)) } /// The error an action reported for the whole form. pub fn form_error(&self) -> Option<SharedString> { self.form_error.clone() } pub fn current_mode(&self) -> Mode { self.mode } pub fn state(&self) -> SubmitState { self.state } /// Whether a submit is running its async checks or action; disable the submit button /// and show a spinner. pub fn is_pending(&self) -> bool { self.state == SubmitState::Pending } /// The same as [`Form::is_pending`], by react-hook-form's name. pub fn is_submitting(&self) -> bool { self.is_pending() } /// Whether the form has been submitted since it was created or reset, valid or not. pub fn is_submitted(&self) -> bool { self.submit_count > 0 } /// Whether the last submit passed validation and its action succeeded. pub fn is_submit_successful(&self) -> bool { self.state == SubmitState::Succeeded } pub fn submit_count(&self) -> usize { self.submit_count } /// Whether the values pass the schema and every async check that has run, shown or not. pub fn is_valid(&self) -> bool { self.validating.is_empty() && !self.errors.iter().any(|error| error.source != Source::Schema) && self .schema .validate(&self.values) .iter() .all(|issue| self.field_disabled(&issue.path)) } /// Whether any async check is running. pub fn is_validating(&self) -> bool { !self.validating.is_empty() } /// Whether `load_values` is still waiting for values, like `formState.isLoading`. pub fn is_loading(&self) -> bool { self.loading.is_some() } /// Whether the values differ from the defaults. pub fn is_dirty(&self) -> bool { self.values != self.defaults } /// Whether one field differs from its default. pub fn dirty<V: PartialEq + 'static>(&self, path: &FieldPath<T, V>) -> bool { path.get(&self.values) != path.get(&self.defaults) } /// Fields the user changed away from their defaults, sorted, like `formState.dirtyFields`. pub fn dirty_fields(&self) -> Vec<SharedString> { sorted(&self.dirty) } /// Whether a field has lost focus since the form was created or reset. pub fn touched(&self, name: &str) -> bool { self.touched.contains(name) } /// Fields that have lost focus, sorted, like `formState.touchedFields`. pub fn touched_fields(&self) -> Vec<SharedString> { sorted(&self.touched) } /// Whether the whole form is disabled. pub fn is_disabled(&self) -> bool { self.disabled } /// Whether a field is disabled, on its own or with the whole form. pub fn field_disabled(&self, name: &str) -> bool { self.disabled || self.disabled_fields.iter().any(|field| is_within(name, field)) } /// One field's state, like react-hook-form's `getFieldState(name)`. pub fn get_field_state(&self, name: &str) -> FieldState { let error = self.error(name); FieldState { invalid: error.is_some(), is_dirty: self.dirty.iter().any(|dirty| is_within(dirty, name)), is_touched: self.touched.contains(name), is_validating: self.validating.keys().any(|path| is_within(path, name)), error, } } /// Stable keys for an array field's items, one per item, in order. Key each row's element /// ids and inputs by these so a row keeps its state when another is removed or moved. pub fn keys<E: 'static>(&self, path: &FieldPath<T, Vec<E>>) -> Vec<u64> { let len = path.get(&self.values).map_or(0, Vec::len); match self.item_keys.get(path.name()) { Some(keys) if keys.len() == len => keys.clone(), _ => (0..len as u64).collect(), } } /// Changes when fields validate, clearing errors and submit state. pub fn set_mode(&mut self, mode: Mode, cx: &mut Context<Self>) { self.mode = mode; self.errors.clear(); self.delayed.clear(); self.touched.clear(); self.submit_count = 0; self.state = SubmitState::Idle; self.sync_invalid(cx); cx.notify(); } /// Disables or enables the whole form. See [`Form::disabled`]. pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) { self.disabled = disabled; self.sync_disabled(cx); cx.notify(); } /// Disables or enables one field. See [`Form::disable_field`]. pub fn set_field_disabled(&mut self, name: impl Into<SharedString>, disabled: bool, cx: &mut Context<Self>) { let name = name.into(); if disabled { self.errors.retain(|error| !is_within(&error.path, &name)); self.disabled_fields.insert(name); } else { self.disabled_fields.remove(&name); } self.sync_disabled(cx); self.sync_invalid(cx); cx.notify(); } /// Sets a field as the user would: bound inputs update, the field turns dirty, and it /// validates as the mode says. Controls' change handlers call this. pub fn set_value<V: PartialEq + 'static>( &mut self, path: &FieldPath<T, V>, value: V, window: &mut Window, cx: &mut Context<Self>, ) { let Some(slot) = path.get_mut(&mut self.values) else { return; }; if *slot == value { return; } *slot = value; self.mark_dirty(path); self.sync_inputs(window, cx); self.changed(path.name().clone(), cx); } /// Sets a field from code, like react-hook-form's `setValue(name, value, options)`: by /// default nothing but the value changes; the options validate, dirty or touch it too. pub fn set_value_with<V: PartialEq + 'static>( &mut self, path: &FieldPath<T, V>, value: V, options: SetValueOptions, window: &mut Window, cx: &mut Context<Self>, ) { let Some(slot) = path.get_mut(&mut self.values) else { return; }; *slot = value; let name = path.name().clone(); if options.should_dirty { self.mark_dirty(path); } if options.should_touch { self.touched.insert(name.clone()); } self.sync_inputs(window, cx); if options.should_validate { self.validate_names(&Names::from(&name), false, cx); } self.sync_invalid(cx); cx.emit(FormEvent::Change(name)); cx.notify(); } /// Edits a field in place, for values like a list of checked ids. pub fn update_value<V: Clone + PartialEq + 'static>( &mut self, path: &FieldPath<T, V>, update: impl FnOnce(&mut V), window: &mut Window, cx: &mut Context<Self>, ) { let Some(mut value) = path.get(&self.values).cloned() else { return; }; update(&mut value); self.set_value(path, value, window, cx); } /// Shows an error on a field until that field changes, like react-hook-form's `setError`. pub fn set_error(&mut self, name: impl Into<SharedString>, message: impl Into<SharedString>, cx: &mut Context<Self>) { let path = name.into(); self.errors.retain(|error| error.path != path); self.delayed.remove(&path); self.errors.push(Error { path, messages: vec![message.into()], source: Source::Manual, }); self.sort_errors(); self.sync_invalid(cx); cx.notify(); } /// Clears every field error and the form error. pub fn clear_errors(&mut self, cx: &mut Context<Self>) { self.errors.clear(); self.delayed.clear(); self.form_error = None; self.sync_invalid(cx); cx.notify(); } /// Clears the errors of some fields (and the fields inside them), like /// `clearErrors(name)` or `clearErrors([a, b])`. pub fn clear_errors_of(&mut self, names: impl Into<Names>, cx: &mut Context<Self>) { let names = names.into(); self.errors.retain(|error| !names.covers(&error.path)); self.delayed.retain(|path, _| !names.covers(path)); if names == Names::All { self.form_error = None; } self.sync_invalid(cx); cx.notify(); } /// Validates some fields now, whatever the mode, like react-hook-form's `trigger`: one /// name, several, or `Names::All`. Errors show at once. The result says whether they all /// passed, once any async checks finish. pub fn trigger(&mut self, names: impl Into<Names>, cx: &mut Context<Self>) -> Validation { let names = names.into(); self.validate_names(&names, true, cx); self.sync_invalid(cx); cx.notify(); self.wait_for(names) } /// Moves focus to a field's control, like react-hook-form's `setFocus`. Works for any /// control bound with [`FormExt::input`] or given a handle from [`FormExt::focus_handle`]. /// Returns whether the field had one. The control shows its focus ring even after a click, /// as a browser does for focus a script moves after keyboard use, so the user sees where /// focus went. pub fn set_focus(&self, name: &str, window: &mut Window, cx: &mut App) -> bool { match self.focus_handle_for(name, cx) { Some(handle) => { focus_visibly(&handle, window, cx); true } None => false, } } /// The handle `set_focus` would focus for `name`. fn focus_handle_for(&self, name: &str, cx: &App) -> Option<FocusHandle> { let input = self .bindings .iter() .find(|binding| binding.name.as_ref() == name) .map(|binding| binding.input.focus_handle(cx)); input.or_else(|| { self.focus .iter() .find(|binding| binding.name.as_ref() == name) .map(|binding| binding.handle.clone()) }) } /// Validates everything, waiting for async checks; if it all passes, runs the action and /// then `on_success`. If not, runs `on_invalid` and focuses the first invalid field. pub fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) { let handlers = Handlers { on_success: self.on_success.clone(), on_invalid: self.on_invalid.clone(), }; self.submit_with(handlers, window, cx); } /// `submit` with handlers for this submit only, for `handle_submit_with`. fn submit_with(&mut self, handlers: Handlers<T>, window: &mut Window, cx: &mut Context<Self>) { // A second click while the action runs would send it twice. if self.is_pending() || self.disabled { return; } self.submit_count += 1; self.form_error = None; self.validate_names(&Names::All, true, cx); self.sync_invalid(cx); cx.notify(); let validation = self.wait_for(Names::All); if let Some(passed) = validation.now() { self.validated(passed, handlers, window, cx); return; } self.state = SubmitState::Pending; self.task = Some(cx.spawn_in(window, async move |this, cx| { let passed = validation.await; this.update_in(cx, |form, window, cx| { form.task = None; form.validated(passed, handlers, window, cx) }) .ok(); })); } fn validated(&mut self, passed: bool, handlers: Handlers<T>, window: &mut Window, cx: &mut Context<Self>) { if !passed { self.state = SubmitState::Failed; self.invalid_submit(&handlers, window, cx); cx.notify(); return; } let values = self.values.clone(); let Some(action) = self.action.clone() else { self.state = SubmitState::Succeeded; cx.notify(); if let Some(on_success) = handlers.on_success { on_success(&values, window, cx); } return; }; self.state = SubmitState::Pending; cx.notify(); let pending = action(values.clone(), cx.to_async()); self.task = Some(cx.spawn_in(window, async move |this, cx| { let result = pending.await; this.update_in(cx, |form, window, cx| form.finish(&values, result, &handlers, window, cx)) .ok(); })); } fn invalid_submit(&mut self, handlers: &Handlers<T>, window: &mut Window, cx: &mut Context<Self>) { if self.should_focus_error { self.focus_first_error(window, cx); } if let Some(on_invalid) = handlers.on_invalid.clone() { let issues: Vec<Issue> = self.errors().collect(); on_invalid(&issues, window, cx); } } fn finish( &mut self, values: &T, result: Result<(), ServerErrors>, handlers: &Handlers<T>, window: &mut Window, cx: &mut Context<Self>, ) { self.task = None; match result { Ok(()) => { self.state = SubmitState::Succeeded; if let Some(on_success) = handlers.on_success.clone() { on_success(values, window, cx); } } Err(server) => { self.state = SubmitState::Failed; self.form_error = server.form; for issue in server.fields { self.errors.retain(|error| error.path != issue.path); self.errors.push(Error { path: issue.path, messages: vec![issue.message], source: Source::Manual, }); } self.sort_errors(); self.sync_invalid(cx); if self.should_focus_error { self.focus_first_error(window, cx); } } } cx.notify(); } /// Back to the defaults, with errors, touched and dirty fields and the submit count /// cleared. A pending submit is abandoned. pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) { self.reset_with(None, ResetOptions::default(), window, cx); } /// Resets to new values, which also become the defaults, keeping whatever `options` say: /// react-hook-form's `reset(values, options)`. `None` resets to the current defaults. pub fn reset_with(&mut self, values: Option<T>, options: ResetOptions, window: &mut Window, cx: &mut Context<Self>) { self.task = None; let next = match values { Some(values) => { if !options.keep_defaults { self.defaults = values.clone(); } values } None => self.defaults.clone(), }; // Arrays carried over whole keep their row keys, inputs and focus handles. let mut kept_arrays = HashSet::new(); if !options.keep_values { let mut next = next; if options.keep_dirty_values { let kept = self.keep_dirty_into(&mut next); self.dirty.retain(|name| kept.iter().any(|path| is_within(name, path))); kept_arrays = self.item_keys.keys().filter(|array| kept.contains(*array)).cloned().collect(); } self.values = next; } if !options.keep_errors { self.errors.clear(); self.delayed.clear(); self.form_error = None; } if !options.keep_dirty && !options.keep_dirty_values { self.dirty.clear(); } if !options.keep_touched { self.touched.clear(); } if !options.keep_submit_count { self.submit_count = 0; self.state = SubmitState::Idle; } else if self.state == SubmitState::Pending { self.state = SubmitState::Idle; } self.validating.clear(); self.settle_waiters(); if !options.keep_values { self.item_keys.retain(|array, _| kept_arrays.contains(array)); // Array rows go back to the new values' keys, so their inputs are made afresh. let in_kept = |name: &SharedString| kept_arrays.iter().any(|array| is_within(name, array)); self.bindings .retain(|binding| !binding.key.starts_with(ITEM_KEY_PREFIX) || in_kept(&binding.name)); self.focus .retain(|binding| !binding.key.starts_with(ITEM_KEY_PREFIX) || in_kept(&binding.name)); } self.sync_inputs(window, cx); self.sync_invalid(cx); cx.emit(FormEvent::Reset); cx.notify(); } /// Values from outside the form, like react-hook-form's `values` prop: they replace the /// values and the defaults, so the form isn't dirty afterwards. Call it whenever the /// source changes, such as when a query returns. pub fn set_values(&mut self, values: T, window: &mut Window, cx: &mut Context<Self>) { self.reset_with(Some(values), ResetOptions::default(), window, cx); } /// Moves each dirty field's current value into `next`, for `keep_dirty_values`, and returns /// the paths it moved. A row field whose row has moved since it changed goes with its whole /// array, the nearest path that still knows how. fn keep_dirty_into(&mut self, next: &mut T) -> Vec<SharedString> { let mut names: Vec<SharedString> = self .dirty .iter() .filter_map(|name| { let mut path = name.as_ref(); loop { if self.swaps.contains_key(path) { return Some(SharedString::from(path.to_string())); } path = &path[..path.rfind('.')?]; } }) .collect(); names.sort(); names.dedup(); // A path inside another that moves goes with it. let outer: Vec<SharedString> = names .iter() .filter(|name| !names.iter().any(|other| other != *name && is_within(name, other))) .cloned() .collect(); for name in &outer { if let Some(swap) = self.swaps.get(name) { swap(next, &mut self.values); } } outer } /// Loads the defaults asynchronously, like an async `defaultValues`: `is_loading` is true /// until the future resolves, then the form resets to what it returned. pub fn load_values<F>(&mut self, load: impl FnOnce(AsyncApp) -> F, window: &mut Window, cx: &mut Context<Self>) where F: Future<Output = T> + 'static, { let pending: LoadFuture<T> = Box::pin(load(cx.to_async())); self.loading = Some(cx.spawn_in(window, async move |this, cx| { let values = pending.await; this.update_in(cx, |form, window, cx| { form.loading = None; form.set_values(values, window, cx); }) .ok(); })); cx.notify(); } /// Resets one field to its default (or a new one), like `resetField(name, options)`. pub fn reset_field<V: Clone + PartialEq + 'static>( &mut self, path: &FieldPath<T, V>, options: ResetFieldOptions<V>, window: &mut Window, cx: &mut Context<Self>, ) { if let Some(default) = options.default_value { if let Some(slot) = path.get_mut(&mut self.defaults) { *slot = default; } } let Some(default) = path.get(&self.defaults).cloned() else { return; }; if let Some(slot) = path.get_mut(&mut self.values) { *slot = default; } let name = path.name().clone(); if !options.keep_error { self.errors.retain(|error| !is_within(&error.path, &name)); self.delayed.retain(|path, _| !is_within(path, &name)); self.validating.retain(|path, _| !is_within(path, &name)); } if !options.keep_dirty { self.dirty.retain(|path| !is_within(path, &name)); } if !options.keep_touched { self.touched.retain(|path| !is_within(path, &name)); } self.sync_inputs(window, cx); self.sync_invalid(cx); self.settle_waiters(); cx.emit(FormEvent::Change(name)); cx.notify(); } /// Adds an item to the end of an array field, like `useFieldArray`'s `append`. pub fn append<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, item: E, cx: &mut Context<Self>) { let len = path.get(&self.values).map_or(0, Vec::len); self.insert(path, len, item, cx); } /// Adds an item to the start of an array field. pub fn prepend<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, item: E, cx: &mut Context<Self>) { self.insert(path, 0, item, cx); } /// Adds an item at `index` (clamped to the end) of an array field; the rows from there /// move down with their inputs and errors. pub fn insert<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, index: usize, item: E, cx: &mut Context<Self>) { let old = self.keys(path); let Some(items) = path.get_mut(&mut self.values) else { return; }; let index = index.min(items.len()); items.insert(index, item); let mut keys = old.clone(); keys.insert(index, self.fresh_key()); self.rows_moved(path, old, keys, cx); } /// Removes the item at `index` of an array field, with its input and errors. pub fn remove<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, index: usize, cx: &mut Context<Self>) { let old = self.keys(path); let Some(items) = path.get_mut(&mut self.values) else { return; }; if index >= items.len() { return; } items.remove(index); let mut keys = old.clone(); keys.remove(index); self.rows_moved(path, old, keys, cx); } /// Swaps two items of an array field; inputs and errors go with their rows. pub fn swap<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, a: usize, b: usize, cx: &mut Context<Self>) { let old = self.keys(path); let Some(items) = path.get_mut(&mut self.values) else { return; }; if a >= items.len() || b >= items.len() || a == b { return; } items.swap(a, b); let mut keys = old.clone(); keys.swap(a, b); self.rows_moved(path, old, keys, cx); } /// Moves the item at `from` to `to` in an array field. pub fn move_item<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, from: usize, to: usize, cx: &mut Context<Self>) { let old = self.keys(path); let Some(items) = path.get_mut(&mut self.values) else { return; }; if from >= items.len() || to >= items.len() || from == to { return; } let item = items.remove(from); items.insert(to, item); let mut keys = old.clone(); let key = keys.remove(from); keys.insert(to, key); self.rows_moved(path, old, keys, cx); } /// Replaces the item at `index`. The row keeps its key, so its inputs stay mounted and /// show the new values; its old errors go. pub fn update<E: PartialEq + 'static>( &mut self, path: &FieldPath<T, Vec<E>>, index: usize, item: E, window: &mut Window, cx: &mut Context<Self>, ) { let Some(slot) = path.get_mut(&mut self.values).and_then(|items| items.get_mut(index)) else { return; }; *slot = item; let row: SharedString = format!("{}.{index}", path.name()).into(); self.errors.retain(|error| !is_within(&error.path, &row)); self.delayed.retain(|path, _| !is_within(path, &row)); self.mark_dirty(path); self.sync_inputs(window, cx); // Other rows' server errors still apply. self.validate_change(path.name().clone(), cx); } /// Replaces every item of an array field; each row gets a fresh key. pub fn replace<E: PartialEq + 'static>( &mut self, path: &FieldPath<T, Vec<E>>, items: Vec<E>, window: &mut Window, cx: &mut Context<Self>, ) { let old = self.keys(path); let Some(slot) = path.get_mut(&mut self.values) else { return; }; let len = items.len(); *slot = items; let keys = (0..len).map(|_| self.fresh_key()).collect(); self.rows_moved(path, old, keys, cx); self.sync_inputs(window, cx); } fn fresh_key(&mut self) -> u64 { let key = self.next_item_key; self.next_item_key += 1; key } /// After an array operation: rows went from `old` keys to `new` keys. Errors, touched and /// dirty state, inputs and focus handles follow their rows to their new indices; those of /// rows that are gone go too. fn rows_moved<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, old: Vec<u64>, new: Vec<u64>, cx: &mut Context<Self>) { let array = path.name().clone(); let moved = |index: usize| old.get(index).and_then(|key| new.iter().position(|k| k == key)); let remap = |name: &SharedString| remap_row(name, &array, moved); self.errors.retain_mut(|error| match remap(&error.path) { Some(Some(path)) => { error.path = path.into(); true } Some(None) => false, None => true, }); self.delayed = std::mem::take(&mut self.delayed) .into_iter() .filter_map(|(path, task)| match remap(&path) { Some(Some(path)) => Some((path.into(), task)), Some(None) => None, None => Some((path, task)), }) .collect(); for set in [&mut self.touched, &mut self.dirty] { *set = std::mem::take(set) .into_iter() .filter_map(|path| match remap(&path) { Some(Some(path)) => Some(path.into()), Some(None) => None, None => Some(path), }) .collect(); } // An async check's result is keyed by the row's old path; drop it rather than land on // another row. self.validating.retain(|path, _| remap(path).is_none()); self.bindings.retain_mut(|binding| match remap(&binding.name) { Some(Some(path)) => { binding.stale |= path != binding.name.as_ref(); binding.name = path.into(); true } Some(None) => false, None => true, }); self.focus.retain_mut(|binding| match remap(&binding.name) { Some(Some(path)) => { binding.name = path.into(); true } Some(None) => false, None => true, }); // Row swaps point at old indices; a dirty row moves with its array's swap instead. self.swaps.retain(|name, _| remap(name).is_none()); self.item_keys.insert(array.clone(), new); self.mark_dirty(path); self.settle_waiters(); // A server error on the array itself (say, "too many") is about the old length; those // on rows moved with their rows and still apply. self.errors.retain(|error| !(error.source == Source::Manual && error.path == array)); // Inputs stay with their rows by key, so their text needs no syncing; each picks up its // new index when it next renders. self.validate_change(array, cx); } /// Binds a text input to a `String` field: typing sets the value, `set_value` and `reset` /// set the text, an error marks it invalid, blur counts as touched and Enter submits. /// Binding the same input again just updates its path, so it is safe to call every render. pub fn bind_input( &mut self, key: impl Into<SharedString>, path: FieldPath<T, String>, input: Entity<TextInput>, window: &mut Window, cx: &mut Context<Self>, ) { let key = key.into(); if let Some(binding) = self.bindings.iter_mut().find(|binding| binding.key == key) { if binding.stale || binding.path.name() != path.name() { binding.name = path.name().clone(); binding.path = path; binding.stale = false; self.sync_invalid(cx); self.sync_disabled(cx); } return; } let (change_key, blur_key, focus_key) = (key.clone(), key.clone(), key.clone()); let handle = input.focus_handle(cx); let subscriptions = [ cx.subscribe_in(&input, window, move |form, _, event: &InputEvent, window, cx| match event { InputEvent::Change(text) => form.input_changed(&change_key, text, cx), InputEvent::Submit(_) => form.submit(window, cx), }), cx.on_blur(&handle, window, move |form, _, cx| form.blurred(&blur_key, cx)), cx.on_focus_in(&handle, window, move |form, _, _| form.focused = Some(focus_key.clone())), ]; self.bindings.push(Binding { key, name: path.name().clone(), path, stale: false, input, _subscriptions: subscriptions, }); self.sync_inputs(window, cx); self.sync_invalid(cx); self.sync_disabled(cx); } /// Registers another control's focus handle for `name`, so `set_focus` and "focus the /// first error" reach it and its blur counts as touched. Called by /// [`FormExt::focus_handle`]; safe to call every render. pub fn bind_focus( &mut self, key: impl Into<SharedString>, name: impl Into<SharedString>, window: &mut Window, cx: &mut Context<Self>, ) -> FocusHandle { self.bind_focus_handle(key, name, None, window, cx) } /// Like [`Form::bind_focus`] with a handle the control owns, such as an `InputOtp`'s. /// `None` makes one. Called by [`FormExt::register_focus`]; safe to call every render. pub fn bind_focus_handle( &mut self, key: impl Into<SharedString>, name: impl Into<SharedString>, handle: Option<FocusHandle>, window: &mut Window, cx: &mut Context<Self>, ) -> FocusHandle { let (key, name) = (key.into(), name.into()); let disabled = self.field_disabled(&name); if let Some(binding) = self.focus.iter_mut().find(|binding| binding.key == key) { if handle.as_ref().is_none_or(|handle| *handle == binding.handle) { binding.name = name; return binding.handle.clone().tab_stop(!disabled); } // The control was made again with a new handle. self.focus.retain(|binding| binding.key != key); } let handle = handle.unwrap_or_else(|| cx.focus_handle()).tab_stop(!disabled); let (blur_key, focus_key) = (key.clone(), key.clone()); // Focus out rather than blur: a select, combobox or date picker tracks this handle around // its popup, so moving into its own list isn't leaving the field. let subscriptions = [ cx.on_focus_out(&handle, window, move |form, _, _, cx| form.blurred(&blur_key, cx)), cx.on_focus_in(&handle, window, move |form, _, _| form.focused = Some(focus_key.clone())), ]; self.focus.push(FocusBinding { key, name, handle: handle.clone(), _subscriptions: subscriptions, }); handle } fn input_changed(&mut self, key: &SharedString, text: &SharedString, cx: &mut Context<Self>) { let Some(binding) = self.binding(key) else { return; }; if binding.stale || self.field_disabled(&binding.name) { return; } let path = binding.path.clone(); let Some(slot) = path.get_mut(&mut self.values) else { return; }; // `set_text` from a reset echoes back here with the value already in place. if slot.as_str() == text.as_ref() { return; } *slot = text.to_string(); self.mark_dirty(&path); self.changed(path.name().clone(), cx); } fn blurred(&mut self, key: &SharedString, cx: &mut Context<Self>) { if self.focused.as_ref() == Some(key) { self.focused = None; } let name = self .binding(key) .map(|binding| binding.name.clone()) .or_else(|| self.focus.iter().find(|binding| &binding.key == key).map(|binding| binding.name.clone())); let Some(name) = name else { return; }; self.touched.insert(name.clone()); let validate = if self.submit_count > 0 { self.re_validate_mode == ReValidateMode::OnBlur } else { matches!(self.mode, Mode::OnBlur | Mode::OnTouched | Mode::All) }; if validate { self.validate_names(&Names::from(&name), false, cx); self.sync_invalid(cx); } cx.notify(); } /// A pointer press on a submit button takes focus off the field being edited, so in a /// browser that field blurs and turns touched before the submit runs. Here a failed submit /// puts focus straight back on the first invalid field within the same frame, and GPUI, /// which compares focus between frames, never reports the blur; so count it here. fn pointer_submit(&mut self, cx: &mut Context<Self>) { if self.disabled || self.is_pending() { return; } if let Some(key) = self.focused.clone() { self.blurred(&key, cx); } } fn binding(&self, key: &SharedString) -> Option<&Binding<T>> { self.bindings.iter().find(|binding| &binding.key == key) } fn mark_dirty<V: PartialEq + 'static>(&mut self, path: &FieldPath<T, V>) { if !self.swaps.contains_key(path.name()) { let swap_path = path.clone(); let swap: Swap<T> = Rc::new(move |a: &mut T, b: &mut T| { if let (Some(a), Some(b)) = (swap_path.get_mut(a), swap_path.get_mut(b)) { std::mem::swap(a, b); } }); self.swaps.insert(path.name().clone(), swap); } if path.get(&self.values) != path.get(&self.defaults) { self.dirty.insert(path.name().clone()); } else { self.dirty.remove(path.name()); } } fn changed(&mut self, name: SharedString, cx: &mut Context<Self>) { // An error the server put on this field is about the old value. self.errors .retain(|error| !(error.source == Source::Manual && is_within(&error.path, &name))); self.validate_change(name, cx); } /// Validates after a change as the mode says, and tells subscribers. fn validate_change(&mut self, name: SharedString, cx: &mut Context<Self>) { let validate = if self.submit_count > 0 { self.re_validate_mode == ReValidateMode::OnChange } else { matches!(self.mode, Mode::OnChange | Mode::All) || (self.mode == Mode::OnTouched && self.touched.contains(&name)) }; if validate { self.validate_names(&Names::from(&name), false, cx); } self.sync_invalid(cx); cx.emit(FormEvent::Change(name)); cx.notify(); } /// Runs the whole schema, like zod's resolver, but only shows new errors for `names` (and /// the fields under them), so untouched fields stay quiet. Errors elsewhere that are now /// fixed still clear. Starts the async checks of the named fields that pass the rest. /// `explicit` (a submit or `trigger`) also clears `set_error` and server errors on the /// names and shows errors without `delay_error`; a change keeps them, since `changed` /// already dropped the ones on the field that changed. fn validate_names(&mut self, names: &Names, explicit: bool, cx: &mut Context<Self>) { let issues: Vec<Issue> = self .schema .validate_with(&self.values, self.criteria_mode) .into_iter() .filter(|issue| !self.field_disabled(&issue.path)) .collect(); let before: HashSet<SharedString> = self.errors.iter().map(|error| error.path.clone()).collect(); self.errors.retain(|error| { if names.covers(&error.path) { return error.source == Source::Manual && !explicit; } error.source != Source::Schema || issues.iter().any(|issue| issue.path == error.path) }); for issue in issues.iter().filter(|issue| names.covers(&issue.path)) { match self.errors.iter_mut().find(|error| error.path == issue.path) { Some(error) if error.source == Source::Schema => error.messages.push(issue.message.clone()), // A server error on the field says more than the schema; it shows until the // field changes. Some(_) => {} None => self.errors.push(Error { path: issue.path.clone(), messages: vec![issue.message.clone()], source: Source::Schema, }), } } let paths: Vec<SharedString> = self .schema .async_rules .iter() .map(|rule| rule.path.clone()) .filter(|path| names.covers(path) && !self.field_disabled(path)) .collect(); for path in dedup(paths) { if self.errors.iter().any(|error| error.path == path) { // The field's own rules already fail; there's nothing to ask the server. self.validating.remove(&path); } else { self.run_async(path, cx); } } self.sort_errors(); self.delay_new_errors(&before, explicit, cx); self.settle_waiters(); } fn run_async(&mut self, path: SharedString, cx: &mut Context<Self>) { let checks: Vec<CheckFuture> = self .schema .async_rules .iter() .filter(|rule| rule.path == path) .map(|rule| (rule.check)(&self.values, cx.to_async())) .collect(); self.runs += 1; let run = self.runs; let criteria = self.criteria_mode; let task_path = path.clone(); let task = cx.spawn(async move |this, cx| { let mut messages = Vec::new(); for check in checks { if let Err(message) = check.await { messages.push(message); if criteria == CriteriaMode::FirstError { break; } } } this.update(cx, |form, cx| form.finish_async(task_path, run, messages, cx)).ok(); }); // Replacing the old run drops its task, which cancels it. self.validating.insert(path, (run, task)); } fn finish_async(&mut self, path: SharedString, run: u64, messages: Vec<SharedString>, cx: &mut Context<Self>) { if self.validating.get(&path).map(|(current, _)| *current) != Some(run) { return; } self.validating.remove(&path); let before: HashSet<SharedString> = self.errors.iter().map(|error| error.path.clone()).collect(); self.errors.retain(|error| !(error.source == Source::Async && error.path == path)); let fails_already = self.errors.iter().any(|error| error.path == path); if !messages.is_empty() && !fails_already { self.errors.push(Error { path, messages, source: Source::Async, }); self.sort_errors(); } self.delay_new_errors(&before, self.is_pending(), cx); self.settle_waiters(); self.sync_invalid(cx); cx.notify(); } /// With `delay_error`, hides errors that weren't showing before and shows them once the /// delay passes with no further change. fn delay_new_errors(&mut self, before: &HashSet<SharedString>, submitting: bool, cx: &mut Context<Self>) { let current: HashSet<SharedString> = self.errors.iter().map(|error| error.path.clone()).collect(); self.delayed.retain(|path, _| current.contains(path)); let Some(delay) = self.delay_error.filter(|_| !submitting) else { self.delayed.clear(); return; }; for path in current { if before.contains(&path) && !self.delayed.contains_key(&path) { continue; } let shown = path.clone(); let timer = cx.spawn(async move |this, cx| { cx.background_executor().timer(delay).await; this.update(cx, |form, cx| { form.delayed.remove(&shown); form.sync_invalid(cx); cx.notify(); }) .ok(); }); // A newer change restarts the wait. self.delayed.insert(path, timer); } } fn wait_for(&mut self, names: Names) -> Validation { let validation = Validation::pending(); self.waiters.push((names, validation.0.clone())); self.settle_waiters(); validation } /// Answers every `trigger` and submit whose fields have no async check left running. fn settle_waiters(&mut self) { let waiters = std::mem::take(&mut self.waiters); for (names, outcome) in waiters { if self.validating.keys().any(|path| names.covers(path)) { self.waiters.push((names, outcome)); continue; } let passed = !self.errors.iter().any(|error| names.covers(&error.path)); let mut outcome = outcome.borrow_mut(); outcome.passed = Some(passed); if let Some(waker) = outcome.waker.take() { waker.wake(); } } } fn sort_errors(&mut self) { let schema = &self.schema; self.errors.sort_by_key(|error| schema.order(&error.path)); } fn focus_first_error(&self, window: &mut Window, cx: &mut App) { let handle = self.errors.iter().find_map(|error| self.focus_handle_for(&error.path, cx)); if let Some(handle) = handle { focus_visibly(&handle, window, cx); } } fn sync_inputs(&self, window: &mut Window, cx: &mut App) { for binding in self.bindings.iter().filter(|binding| !binding.stale) { let Some(value) = binding.path.get(&self.values) else { continue; }; if binding.input.read(cx).text().as_ref() != value.as_str() { let value = value.clone(); binding.input.update(cx, |input, cx| input.set_text(value, window, cx)); } } } fn sync_invalid(&self, cx: &mut App) { for binding in &self.bindings { let invalid = self.invalid(&binding.name); binding.input.update(cx, |input, cx| input.set_invalid(invalid, cx)); } } fn sync_disabled(&self, cx: &mut App) { for binding in &self.bindings { let disabled = self.field_disabled(&binding.name); binding.input.update(cx, |input, cx| input.set_disabled(disabled, cx)); } for binding in &self.focus { let _ = binding.handle.clone().tab_stop(!self.field_disabled(&binding.name)); } } } fn sorted(set: &HashSet<SharedString>) -> Vec<SharedString> { let mut names: Vec<SharedString> = set.iter().cloned().collect(); names.sort(); names } fn dedup(paths: Vec<SharedString>) -> Vec<SharedString> { let mut seen = HashSet::new(); paths.into_iter().filter(|path| seen.insert(path.clone())).collect() } /// `path` is `name` itself or a field inside it: `emails.2.address` is within `emails`. fn is_within(path: &str, name: &str) -> bool { let name = name.trim_end_matches('.'); path == name || path.strip_prefix(name).is_some_and(|rest| rest.starts_with('.')) } /// Where a path inside an array row goes when rows move: `None` if it isn't in a row of /// `array`, `Some(None)` if its row is gone, or its new path. `moved` maps old row indices to /// new ones. fn remap_row(path: &str, array: &str, moved: impl Fn(usize) -> Option<usize>) -> Option<Option<String>> { let rest = path.strip_prefix(array)?.strip_prefix('.')?; let (index, tail) = match rest.split_once('.') { Some((index, tail)) => (index, Some(tail)), None => (rest, None), }; let index: usize = index.parse().ok()?; Some(moved(index).map(|to| match tail { Some(tail) => format!("{array}.{to}.{tail}"), None => format!("{array}.{to}"), })) } /// One-line wiring for controls, called on the form entity from a render function. Create /// inputs and focus handles before `form.read(cx)`, which borrows the form. pub trait FormExt<T> { /// A text input bound to `path`, created by `build` the first time and owned by the form. fn input( &self, path: FieldPath<T, String>, window: &mut Window, cx: &mut App, build: impl FnOnce(TextInput) -> TextInput, ) -> Entity<TextInput>; /// Like `input`, for a field inside an array item: keyed by the item's stable key from /// [`Form::keys`] so the row keeps its input when others are removed. fn item_input( &self, item_key: u64, path: FieldPath<T, String>, window: &mut Window, cx: &mut App, build: impl FnOnce(TextInput) -> TextInput, ) -> Entity<TextInput>; /// A focus handle for any other control bound to `path`: pass it to the control's /// `.focus_handle(...)`. The form keeps it, so `set_focus(name)` and "focus the first /// error" reach the control, and its blur marks the field touched (and validates in /// `Mode::OnBlur`). It leaves the Tab order while the field is disabled. fn focus_handle<V: 'static>(&self, path: &FieldPath<T, V>, window: &mut Window, cx: &mut App) -> FocusHandle; /// Like `focus_handle`, for the `index`-th of several controls bound to one field, such /// as a list of checkboxes editing one `Vec`. `set_focus` goes to the first. fn focus_handle_at<V: 'static>(&self, path: &FieldPath<T, V>, index: usize, window: &mut Window, cx: &mut App) -> FocusHandle; /// Like `focus_handle`, for a control inside an array item, such as a select on each row: /// keyed by the item's stable key from [`Form::keys`], so the handle stays with its row /// when rows are inserted, swapped or removed, and `set_focus("rows.2.role")` finds it. fn item_focus_handle<V: 'static>(&self, item_key: u64, path: &FieldPath<T, V>, window: &mut Window, cx: &mut App) -> FocusHandle; /// Registers the focus handle of a control that owns one, such as an `InputOtp`, so /// `set_focus` and "focus the first error" reach it and its blur counts as touched. Safe to /// call every render. fn register_focus<V: 'static>(&self, path: &FieldPath<T, V>, handle: FocusHandle, window: &mut Window, cx: &mut App); /// A handler that sets `path` to the control's new value: a checkbox's or switch's /// `on_toggle`, a select's `on_change` for a `SharedString` field. fn on_change<V: Clone + PartialEq + 'static>( &self, path: FieldPath<T, V>, ) -> impl Fn(&V, &mut Window, &mut App) + 'static; /// A handler that edits `path` from what the control reports, such as a radio index /// mapped to a plan id, or adding a checked id to a list. fn on_change_with<V: Clone + PartialEq + 'static, A: 'static>( &self, path: FieldPath<T, V>, update: impl Fn(&mut V, &A) + 'static, ) -> impl Fn(&A, &mut Window, &mut App) + 'static; /// A submit button's `on_click`. fn handle_submit(&self) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static; /// A submit button's `on_click` with its own handlers, like react-hook-form's /// `handleSubmit(onValid, onInvalid)`: `on_valid` gets the values after any action /// succeeds, `on_invalid` the errors in field order. fn handle_submit_with( &self, on_valid: impl Fn(&T, &mut Window, &mut App) + 'static, on_invalid: impl Fn(&[Issue], &mut Window, &mut App) + 'static, ) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static; /// A reset button's `on_click`. fn handle_reset(&self) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static; /// [`Form::set_focus`] on the entity, for use outside `form.update`. fn set_focus(&self, name: &str, window: &mut Window, cx: &mut App) -> bool; /// Calls `callback` with a field's new value whenever it (or a field inside it) changes or /// the form resets, like `watch(name, callback)`. Keep the subscription alive as long as /// you want the calls. Where react-hook-form calls back inside `setValue`, GPUI delivers /// the call when the form's update returns: still before the next frame draws, so what the /// callback changes shows in the same frame, but code later in that same update doesn't /// see it yet. fn watch<V: Clone + 'static>( &self, path: FieldPath<T, V>, cx: &mut App, callback: impl Fn(&V, &mut App) + 'static, ) -> Subscription; /// Calls `callback` with every value and the changed field's name (`None` for a reset) /// on any change, like `watch(callback)`. fn watch_all(&self, cx: &mut App, callback: impl Fn(&T, Option<&SharedString>, &mut App) + 'static) -> Subscription; } impl<T: Clone + PartialEq + 'static> FormExt<T> for Entity<Form<T>> { fn input( &self, path: FieldPath<T, String>, window: &mut Window, cx: &mut App, build: impl FnOnce(TextInput) -> TextInput, ) -> Entity<TextInput> { let key = path.name().clone(); bound_input(self, key, path, window, cx, build) } fn item_input( &self, item_key: u64, path: FieldPath<T, String>, window: &mut Window, cx: &mut App, build: impl FnOnce(TextInput) -> TextInput, ) -> Entity<TextInput> { let key = row_binding_key(item_key, path.name()); bound_input(self, key, path, window, cx, build) } fn focus_handle<V: 'static>(&self, path: &FieldPath<T, V>, window: &mut Window, cx: &mut App) -> FocusHandle { let name = path.name().clone(); self.update(cx, |form, cx| form.bind_focus(name.clone(), name, window, cx)) } fn focus_handle_at<V: 'static>(&self, path: &FieldPath<T, V>, index: usize, window: &mut Window, cx: &mut App) -> FocusHandle { let name = path.name().clone(); // The first keeps the plain name so a later `focus_handle` call finds the same one. let key: SharedString = if index == 0 { name.clone() } else { format!("{name}@{index}").into() }; self.update(cx, |form, cx| form.bind_focus(key, name, window, cx)) } fn item_focus_handle<V: 'static>(&self, item_key: u64, path: &FieldPath<T, V>, window: &mut Window, cx: &mut App) -> FocusHandle { let name = path.name().clone(); let key = row_binding_key(item_key, &name); self.update(cx, |form, cx| form.bind_focus(key, name, window, cx)) } fn register_focus<V: 'static>(&self, path: &FieldPath<T, V>, handle: FocusHandle, window: &mut Window, cx: &mut App) { let name = path.name().clone(); self.update(cx, |form, cx| form.bind_focus_handle(name.clone(), name, Some(handle), window, cx)); } fn on_change<V: Clone + PartialEq + 'static>( &self, path: FieldPath<T, V>, ) -> impl Fn(&V, &mut Window, &mut App) + 'static { self.on_change_with(path, |value: &mut V, new: &V| *value = new.clone()) } fn on_change_with<V: Clone + PartialEq + 'static, A: 'static>( &self, path: FieldPath<T, V>, update: impl Fn(&mut V, &A) + 'static, ) -> impl Fn(&A, &mut Window, &mut App) + 'static { let form = self.downgrade(); move |event, window, cx| { form.update(cx, |form, cx| { if !form.field_disabled(path.name()) { form.update_value(&path, |value| update(value, event), window, cx) } }) .ok(); } } fn handle_submit(&self) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static { let form = self.downgrade(); move |event, window, cx| { form.update(cx, |form, cx| { if !event.is_keyboard() { form.pointer_submit(cx); } form.submit(window, cx) }) .ok(); } } fn handle_submit_with( &self, on_valid: impl Fn(&T, &mut Window, &mut App) + 'static, on_invalid: impl Fn(&[Issue], &mut Window, &mut App) + 'static, ) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static { let form = self.downgrade(); let (on_valid, on_invalid): (SuccessHandler<T>, InvalidHandler) = (Rc::new(on_valid), Rc::new(on_invalid)); move |event, window, cx| { let handlers = Handlers { on_success: Some(on_valid.clone()), on_invalid: Some(on_invalid.clone()), }; form.update(cx, |form, cx| { if !event.is_keyboard() { form.pointer_submit(cx); } form.submit_with(handlers, window, cx) }) .ok(); } } fn handle_reset(&self) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static { let form = self.downgrade(); move |_, window, cx| { form.update(cx, |form, cx| { if !form.is_disabled() { form.reset(window, cx) } }) .ok(); } } fn set_focus(&self, name: &str, window: &mut Window, cx: &mut App) -> bool { let handle = self.read(cx).focus_handle_for(name, cx); match handle { Some(handle) => { focus_visibly(&handle, window, cx); true } None => false, } } fn watch<V: Clone + 'static>( &self, path: FieldPath<T, V>, cx: &mut App, callback: impl Fn(&V, &mut App) + 'static, ) -> Subscription { cx.subscribe(self, move |form, event: &FormEvent, cx| { let changed = match event { FormEvent::Change(name) => is_within(name, path.name()) || is_within(path.name(), name), FormEvent::Reset => true, }; if !changed { return; } let value = path.get(form.read(cx).values()).cloned(); if let Some(value) = value { callback(&value, cx); } }) } fn watch_all(&self, cx: &mut App, callback: impl Fn(&T, Option<&SharedString>, &mut App) + 'static) -> Subscription { cx.subscribe(self, move |form, event: &FormEvent, cx| { let values = form.read(cx).values().clone(); let name = match event { FormEvent::Change(name) => Some(name), FormEvent::Reset => None, }; callback(&values, name, cx); }) } } /// The binding key of a control in an array row: the row's stable key plus the field's path /// inside the row, neither of which shifts with the row's index. fn row_binding_key(item_key: u64, name: &str) -> SharedString { let segments: Vec<&str> = name.split('.').collect(); let inside = segments .iter() .rposition(|segment| segment.parse::<usize>().is_ok()) .map_or(&segments[..], |index| &segments[index + 1..]); format!("{ITEM_KEY_PREFIX}{item_key}.{}", inside.join(".")).into() } fn bound_input<T: Clone + PartialEq + 'static>( form: &Entity<Form<T>>, key: SharedString, path: FieldPath<T, String>, window: &mut Window, cx: &mut App, build: impl FnOnce(TextInput) -> TextInput, ) -> Entity<TextInput> { if let Some(binding) = form.read(cx).binding(&key) { let (input, stale) = (binding.input.clone(), binding.stale || binding.path.name() != path.name()); if stale { form.update(cx, |form, cx| form.bind_input(key, path, input.clone(), window, cx)); } return input; } let text = path.get(form.read(cx).values()).cloned().unwrap_or_default(); let input = cx.new(|cx| build(TextInput::new(cx)).default_value(text)); form.update(cx, |form, cx| form.bind_input(key, path, input.clone(), window, cx)); input } /// Your values as JSON-like text for a toast or a debug panel: `Debug` output with field /// names quoted, `Some(x)` as `x`, `None` as `null` and unit enum variants as strings. Not a /// JSON serializer: it reads `{:?}`, so it needs no serde. pub fn debug_json(value: &impl Debug) -> String { let text = format!("{value:?}"); let mut parser = DebugParser { text: &text, pos: 0 }; match parser.value() { Some(json) if parser.at_end() => { let mut out = String::new(); json.write(&mut out, 0); out } _ => format!("{value:#?}"), } } enum Json { Raw(String), Text(String), List(Vec<Json>), Object(Vec<(String, Json)>), } impl Json { fn write(&self, out: &mut String, depth: usize) { let pad = " ".repeat(depth + 1); let close = " ".repeat(depth); match self { Json::Raw(raw) => out.push_str(raw), Json::Text(text) => { let _ = write!(out, "{text:?}"); } Json::List(items) if items.is_empty() => out.push_str("[]"), Json::List(items) => { out.push_str("[\n"); for (ix, item) in items.iter().enumerate() { out.push_str(&pad); item.write(out, depth + 1); out.push_str(if ix + 1 < items.len() { ",\n" } else { "\n" }); } out.push_str(&close); out.push(']'); } Json::Object(fields) if fields.is_empty() => out.push_str("{}"), Json::Object(fields) => { out.push_str("{\n"); for (ix, (name, value)) in fields.iter().enumerate() { let _ = write!(out, "{pad}{name:?}: "); value.write(out, depth + 1); out.push_str(if ix + 1 < fields.len() { ",\n" } else { "\n" }); } out.push_str(&close); out.push('}'); } } } } /// Reads the compact `{:?}` grammar: strings, chars, numbers, `Name { field: v }`, /// `Name(v, ..)`, `[..]`, `{k: v}` maps, `(..)` tuples and bare identifiers. struct DebugParser<'a> { text: &'a str, pos: usize, } impl DebugParser<'_> { fn rest(&self) -> &str { &self.text[self.pos..] } fn at_end(&mut self) -> bool { self.skip_space(); self.pos == self.text.len() } fn skip_space(&mut self) { let trimmed = self.rest().trim_start(); self.pos = self.text.len() - trimmed.len(); } fn eat(&mut self, token: char) -> bool { self.skip_space(); if self.rest().starts_with(token) { self.pos += token.len_utf8(); true } else { false } } fn value(&mut self) -> Option<Json> { self.skip_space(); let first = self.rest().chars().next()?; match first { '"' => self.quoted('"').map(Json::Text), '\'' => self.quoted('\'').map(Json::Text), '[' => { self.pos += 1; self.list(']').map(Json::List) } '(' => { self.pos += 1; self.list(')').map(Json::List) } '{' => { self.pos += 1; self.map() } '-' | '0'..='9' => { let len = self .rest() .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+' | '_'))) .unwrap_or(self.rest().len()); let number = self.rest()[..len].to_string(); self.pos += len; Some(Json::Raw(number)) } _ => self.named(), } } fn quoted(&mut self, quote: char) -> Option<String> { let mut chars = self.rest().char_indices().skip(1); let mut out = String::new(); while let Some((ix, c)) = chars.next() { match c { '\\' => { let (_, escaped) = chars.next()?; out.push(match escaped { 'n' => '\n', 't' => '\t', 'r' => '\r', '0' => '\0', other => other, }); } c if c == quote => { self.pos += ix + c.len_utf8(); return Some(out); } c => out.push(c), } } None } fn ident(&mut self) -> Option<String> { self.skip_space(); let len = self .rest() .find(|c: char| !(c.is_alphanumeric() || c == '_')) .unwrap_or(self.rest().len()); if len == 0 { return None; } let ident = self.rest()[..len].to_string(); self.pos += len; Some(ident) } fn named(&mut self) -> Option<Json> { let name = self.ident()?; if self.eat('{') { return self.map(); } if self.eat('(') { let mut items = self.list(')')?; return Some(if items.len() == 1 { items.remove(0) } else { Json::List(items) }); } Some(match name.as_str() { "None" => Json::Raw("null".into()), "true" | "false" | "NaN" | "inf" => Json::Raw(name), _ => Json::Text(name), }) } fn list(&mut self, close: char) -> Option<Vec<Json>> { let mut items = Vec::new(); loop { if self.eat(close) { return Some(items); } items.push(self.value()?); if !self.eat(',') { return self.eat(close).then_some(items); } } } /// The inside of `{ .. }`: struct fields (`name: v`) or map entries (`"k": v`). fn map(&mut self) -> Option<Json> { let mut fields = Vec::new(); loop { if self.eat('}') { return Some(Json::Object(fields)); } // `..` closes a struct with skipped fields. if self.rest().trim_start().starts_with("..") { self.skip_space(); self.pos += 2; continue; } let key = match self.value()? { Json::Text(key) | Json::Raw(key) => key, _ => return None, }; if !self.eat(':') { return None; } fields.push((key, self.value()?)); if !self.eat(',') { return self.eat('}').then(|| Json::Object(fields)); } } } }Register the module
// src/ui/mod.rs pub mod form;
Usage
use crate::ui::form::*;Examples
Input
Bind a TextInput to a String field with form.input(...). The form owns the input, keeps its text in sync on reset, and marks it invalid when the field has an error.
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 TextInput binds the same way; Enter adds a newline instead of submitting.
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
Controls that don't hold text read their value from values() and report changes through form.on_change_with(...). Pass f.invalid(...) to show the error state, and a handle from form.focus_handle(...) so the form can focus the trigger.
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 field: on_change_with adds or removes the box's id, and array().min(...) requires at least one. Each box gets a focus handle from focus_handle_at, so an empty submit focuses the first 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 field stores the plan id; on_change_with maps the picked option's index to it. The group's focus handle comes from the form, so an empty submit focuses it.
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(...) hands a switch's or checkbox's new value straight to a bool field; boolean().accepted(...) requires it on.
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 in one form, validated by one schema. Every control has a focus handle from the form, so Tab walks them in order and an empty submit focuses the first invalid one, whatever kind of control it is.
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())
}Array Fields
append, insert, swap and remove edit a Vec field. keys gives each row a stable key, so a row keeps its input (and focus) when others move. each validates every item; errors land on paths like emails.1.address and move with their rows.
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())
}Actions
An async action runs after validation passes, like a server action. While it runs the form is pending: the button shows a spinner and further submits are ignored. It can return errors for a field or for the whole form. Try the name acme, or the EU West region.
use std::time::Duration;
use gpui::{div, prelude::*, px, App, SharedString, Window};
use crate::theme::ActiveTheme;
use crate::ui::alert::{Alert, AlertIcon, AlertVariant};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{field, string, Form, FormExt, Schema, ServerErrors};
use crate::ui::select::{Select, SelectOption};
use crate::ui::spinner::Spinner;
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Debug, PartialEq)]
struct NewProject {
name: String,
region: String,
}
const REGIONS: [(&str, &str); 3] = [
("us-east", "US East (Virginia)"),
("eu-west", "EU West (Ireland)"),
("ap-northeast", "Asia Pacific (Seoul)"),
];
fn project_schema() -> Schema<NewProject> {
Schema::<NewProject>::new().field(
field!(name),
string()
.min(2, "Project name must be at least 2 characters.")
.max(24, "Project name must be at most 24 characters.")
.refine(
|name| name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
"Use lowercase letters, numbers and dashes.",
),
)
}
/// Stands in for a request to your backend: it answers after a second and a half.
async fn create_project(project: NewProject, cx: gpui::AsyncApp) -> Result<(), ServerErrors> {
cx.background_executor().timer(Duration::from_millis(1500)).await;
if project.name == "acme" {
return Err(ServerErrors::new().field("name", "That name is taken."));
}
if project.region == "eu-west" {
return Err(ServerErrors::new().form("EU West is at capacity right now. Pick another region."));
}
Ok(())
}
pub fn form_actions(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-actions", cx, |_, _| {
Form::new(NewProject {
name: String::new(),
region: "us-east".into(),
})
.schema(project_schema())
.action(create_project)
.on_success(|project, _, cx| {
toast(
Toast::new("Project created").description(format!("{} is live in {}.", project.name, project.region)),
cx,
)
})
});
let region_open = window.use_keyed_state("form-actions-region-open", cx, |_, _| false);
let name = form.input(field!(name), window, cx, |input| input.placeholder("acme-web"));
let f = form.read(cx);
let pending = f.is_pending();
let spinner_color = cx.theme().primary_foreground;
let region = REGIONS
.iter()
.fold(
Select::new(
"form-actions-region",
Some(SharedString::from(f.values().region.clone())),
*region_open.read(cx),
)
.width(px(398.)),
|select, (value, label)| select.option(SelectOption::new(*value, *label)),
)
.on_open_change(move |next, _, cx| {
region_open.update(cx, |open, cx| {
*open = *next;
cx.notify();
})
})
.on_change(form.on_change_with(field!(region), |region: &mut String, value: &SharedString| {
*region = value.to_string()
}));
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Create project")
.description("Deploy your new project in one click.")
.child(
div()
.flex()
.flex_col()
.gap_6()
.when_some(f.form_error(), |this, error| {
this.child(
Alert::new("Couldn't create the project")
.description(error)
.variant(AlertVariant::Destructive)
.icon(AlertIcon::CircleAlert),
)
})
.child(
f.field("name")
.label("Name")
.description("Lowercase letters, numbers and dashes.")
.child(name),
)
.child(f.field("region").label("Region").child(region)),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-actions-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(
Button::new("form-actions-submit", if pending { "Creating" } else { "Create project" })
.disabled(pending)
.when(pending, |button| button.leading(Spinner::new().color(spinner_color)))
.on_click(form.handle_submit()),
),
),
)
.child(Toaster::new())
}Validation Modes
Pick a mode, then type in a field and tab away to see when its error appears. Opening the plan's list doesn't count as leaving it; leaving the field does. After the first submit every mode revalidates on change.
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)),
)
}Set Focus
set_focus(name) moves focus to any bound control: a text input, a select, radio group, checkbox or switch given a handle from form.focus_handle(...), or an OTP input whose own handle is registered with form.register_focus(...). The control shows its focus ring even when a click moved focus there. A failed submit focuses the first invalid field in schema order, here the select.
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]
});
}Async Validation
field_async checks a username with a (simulated) server once its other rules pass; each keystroke cancels the check before it. get_field_state shows it running. The password uses CriteriaMode::All, so every rule it fails is listed. Try admin, shadcn or hyuskui.
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())
}Form State
Everything react-hook-form's formState holds, live: dirty and touched fields, validity, submit state. watch_all reports each change as it happens, load_values fills the form from a (simulated) request, and the reset buttons show reset_with's keep-options.
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),
)
}Array Row Controls
A select on every row of an array field. item_focus_handle keys each row's handle by the row's stable key, so it moves with the row, and a failed submit can focus the select of the row that needs a role.
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())
}API Reference
FieldPath
Names a field of T holding a V, like "title" or "emails.2.address". Build one with the [field!] macro rather than by hand.
FieldPath::new(name: impl Into<SharedString>, get: fn(&T) -> Option<&V>, get_mut: fn(&mut T) -> Option<&mut V>) -> SelfA path from its name and accessors; field!(title) writes this for you. The accessors are plain fns so the macro's closures learn T from where the path is used.
.name() -> &SharedStringThe dotted name errors are keyed by, such as emails.2.address.
FieldPath::get<'a>(&self, values: &'a T) -> Option<&'a V>The value, or None when the path points past the end of an array.
FieldPath::get_mut<'a>(&self, values: &'a mut T) -> Option<&'a mut V>FieldPath::join<W: 'static>(outer: Self, inner: FieldPath<V, W>) -> FieldPath<T, W>outer.then(inner) as a function, for the field! macro.
FieldPath::then<W: 'static>(&self, next: FieldPath<V, W>) -> FieldPath<T, W>Continues into a field of the value, such as an array item's address.
CriteriaMode
How many failed rules a field reports, like react-hook-form's criteriaMode.
CriteriaMode::FirstErrorThe first failed rule's message.
CriteriaMode::AllEvery failed rule's message, read back with [Form::error_messages].
Check
The rules for one value, each with the message shown when it fails. Start from [string], [number], [array], [boolean] or [optional]; add your own with refine.
Check::new() -> SelfA check with no rules.
.refine(test: impl Fn(&V) -> bool + 'static, message: impl Into<SharedString>)Passes when test returns true, like zod's .refine.
Check::min(self, len: usize, message: impl Into<SharedString>) -> SelfAt least len characters (not bytes, so "한글" is two).
Check::max(self, len: usize, message: impl Into<SharedString>) -> SelfAt most len characters.
Check::required(self, message: impl Into<SharedString>) -> SelfNot empty once surrounding whitespace is trimmed.
Check::email(self, message: impl Into<SharedString>) -> SelfShaped like an email address: one @, a dotted domain, no spaces.
Check::min(self, min: N, message: impl Into<SharedString>) -> SelfAt least min, inclusive.
Check::max(self, max: N, message: impl Into<SharedString>) -> SelfAt most max, inclusive.
Check::accepted(self, message: impl Into<SharedString>) -> SelfPasses only when the value is true.
Schema
What makes a T valid, like a zod object schema. Rules run in the order you add them, which is also the order "focus the first invalid field" follows.
Schema::new() -> SelfA schema that accepts everything.
Schema::field<V: 'static>(mut self, path: FieldPath<T, V>, check: Check<V>) -> SelfChecks one field.
Schema::each<E: 'static, V: 'static>(mut self, array: FieldPath<T, Vec<E>>, item: FieldPath<E, V>, check: Check<V>) -> SelfChecks a field of every array item; errors land on emails.2.address-style paths.
.refine(path: impl Into<SharedString>, test: impl Fn(&T) -> bool + 'static, message: impl Into<SharedString>)A rule across fields, such as "passwords match", reported on path.
Schema::field_async<V: Clone + 'static, F>(mut self, path: FieldPath<T, V>, check: impl Fn(V, AsyncApp) -> F + 'static) -> SelfAn async check of one field, such as "is this username free?" against a server. It runs only once the field's other rules pass, and its newer runs cancel older ones. Return Err(message) to fail.
Schema::refine_async<F>(mut self, path: impl Into<SharedString>, check: impl Fn(T, AsyncApp) -> F + 'static) -> SelfAn async rule across fields, like zod's async refine, reported on path.
.validate(values: &T) -> Vec<Issue>Every failure, at most one per field, in rule order.
.validate_with(values: &T, criteria: CriteriaMode) -> Vec<Issue>Every failure in rule order: one per field, or with CriteriaMode::All every failed rule of every field.
ServerErrors
What a submit action reports back: errors for fields and/or one for the whole form.
ServerErrors::new() -> Self.field(path: impl Into<SharedString>, message: impl Into<SharedString>)An error shown on one field, like "That name is taken."
.form(message: impl Into<SharedString>)An error about the submission as a whole, read back with [Form::form_error].
Mode
When fields validate before the first submit, like react-hook-form's mode.
Mode::OnSubmitOnly on submit.
Mode::OnBlurWhen a field loses focus.
Mode::OnChangeOn every change.
Mode::OnTouchedOn a field's first blur, then on every change.
Mode::AllOn blur and on change.
ReValidateMode
When fields validate again after a submit, like react-hook-form's reValidateMode.
ReValidateMode::OnChangeOn every change, so errors clear as the user fixes them.
ReValidateMode::OnBlurWhen a field loses focus.
ReValidateMode::OnSubmitOnly on the next submit.
SubmitState
Where the last submit got to.
SubmitState::IdleNot submitted since the form was created or reset.
SubmitState::PendingAsync checks or the action are running.
SubmitState::SucceededValid, and the action (if any) succeeded.
SubmitState::FailedInvalid, or the action returned errors.
FormEvent
What a form tells its subscribers; see [FormExt::watch].
FormEvent::ChangeThe value at this path, or something inside it, changed.
FormEvent::ResetThe form was reset, or given new values from outside.
Names
Which fields an operation covers: "email", ["email", "password"] or Names::All.
Names::AllNames::SomeValidation
The result of [Form::trigger]: whether the fields passed, once their async checks finish. Await it (from cx.spawn), or read now() when no check is async.
.now() -> Option<bool>The result, or None while async checks are still running.
Form
A form over your values type T: its values and defaults, the schema, errors, touched and dirty fields, focus handles, submit count and the pending action. Create it once with cx.new (or window.use_keyed_state) and render from form.read(cx).
Form::new(defaults: T) -> SelfA form starting at defaults, which reset returns to.
.schema(schema: Schema<T>).mode(mode: Mode)When fields validate before the first submit. See [Mode].
.re_validate_mode(mode: ReValidateMode)When fields validate again after a submit. See [ReValidateMode].
.criteria_mode(criteria: CriteriaMode)Whether a field keeps every failed rule's message. See [CriteriaMode].
.delay_error(delay: Duration)Waits this long after a change before showing a new error, and starts over on every change, so errors don't flash while the user types. Fixing the field clears its error at once, and a submit shows every error straight away.
.should_focus_error(focus: bool)Whether a failed submit focuses the first invalid field (on by default).
.disabled(disabled: bool)Disables every field: bound inputs turn disabled and leave the Tab order, the handlers from [FormExt] ignore changes, and submit and reset do nothing. Pass [Form::is_disabled] to other controls' and buttons' .disabled(...).
.disable_field(name: impl Into<SharedString>)Disables one field, like register(name, { disabled: true }): it isn't validated and its controls ignore changes.
Form::action<F>(mut self, action: impl Fn(T, AsyncApp) -> F + 'static) -> SelfAn async action that receives the valid values, like a server action. While it runs the form is pending and further submits are ignored; return ServerErrors to show errors on fields or on the form.
.on_success(handler: impl Fn(&T, &mut Window, &mut App) + 'static)Runs after a valid submit, once the action (if any) has succeeded.
.on_invalid(handler: impl Fn(&[Issue], &mut Window, &mut App) + 'static)Runs after a submit fails validation, with every error in field order: react-hook-form's handleSubmit(onValid, onInvalid).
.values() -> &T.get_values() -> &TThe values, like getValues(). The same as [Form::values].
Form::get_value<'a, V: 'static>(&'a self, path: &FieldPath<T, V>) -> Option<&'a V>One field's value, like getValues(name) or reading watch(name) while rendering.
.defaults() -> &T.default_values() -> &TThe values reset returns to, like formState.defaultValues.
.error(name: &str) -> Option<SharedString>The error shown on a field, such as "title" or "emails.2.address".
.error_messages(name: &str) -> Vec<SharedString>Every failed rule's message for a field with CriteriaMode::All; just the shown one otherwise. Like react-hook-form's errors[name].types.
.invalid(name: &str) -> boolWhether a field has an error; pass it to a control's .invalid(...).
.errors() -> impl Iterator<Item = Issue> + '_Every shown error, in schema order.
.field(name: &str) -> FieldA Field for name that shows its error (every failed rule with CriteriaMode::All) and turns its label destructive.
.form_error() -> Option<SharedString>The error an action reported for the whole form.
.current_mode() -> Mode.state() -> SubmitState.is_pending() -> boolWhether a submit is running its async checks or action; disable the submit button and show a spinner.
.is_submitting() -> boolThe same as [Form::is_pending], by react-hook-form's name.
.is_submitted() -> boolWhether the form has been submitted since it was created or reset, valid or not.
.is_submit_successful() -> boolWhether the last submit passed validation and its action succeeded.
.submit_count() -> usize.is_valid() -> boolWhether the values pass the schema and every async check that has run, shown or not.
.is_validating() -> boolWhether any async check is running.
.is_loading() -> boolWhether load_values is still waiting for values, like formState.isLoading.
.is_dirty() -> boolWhether the values differ from the defaults.
Form::dirty<V: PartialEq + 'static>(&self, path: &FieldPath<T, V>) -> boolWhether one field differs from its default.
.dirty_fields() -> Vec<SharedString>Fields the user changed away from their defaults, sorted, like formState.dirtyFields.
.touched(name: &str) -> boolWhether a field has lost focus since the form was created or reset.
.touched_fields() -> Vec<SharedString>Fields that have lost focus, sorted, like formState.touchedFields.
.is_disabled() -> boolWhether the whole form is disabled.
.field_disabled(name: &str) -> boolWhether a field is disabled, on its own or with the whole form.
.get_field_state(name: &str) -> FieldStateOne field's state, like react-hook-form's getFieldState(name).
Form::keys<E: 'static>(&self, path: &FieldPath<T, Vec<E>>) -> Vec<u64>Stable keys for an array field's items, one per item, in order. Key each row's element ids and inputs by these so a row keeps its state when another is removed or moved.
.set_mode(mode: Mode, cx: &mut Context<Self>)Changes when fields validate, clearing errors and submit state.
.set_disabled(disabled: bool, cx: &mut Context<Self>)Disables or enables the whole form. See [Form::disabled].
.set_field_disabled(name: impl Into<SharedString>, disabled: bool, cx: &mut Context<Self>)Disables or enables one field. See [Form::disable_field].
Form::set_value<V: PartialEq + 'static>(&mut self, path: &FieldPath<T, V>, value: V, window: &mut Window, cx: &mut Context<Self>)Sets a field as the user would: bound inputs update, the field turns dirty, and it validates as the mode says. Controls' change handlers call this.
Form::set_value_with<V: PartialEq + 'static>(&mut self, path: &FieldPath<T, V>, value: V, options: SetValueOptions, window: &mut Window, cx: &mut Context<Self>)Sets a field from code, like react-hook-form's setValue(name, value, options): by default nothing but the value changes; the options validate, dirty or touch it too.
Form::update_value<V: Clone + PartialEq + 'static>(&mut self, path: &FieldPath<T, V>, update: impl FnOnce(&mut V), window: &mut Window, cx: &mut Context<Self>)Edits a field in place, for values like a list of checked ids.
.set_error(name: impl Into<SharedString>, message: impl Into<SharedString>, cx: &mut Context<Self>)Shows an error on a field until that field changes, like react-hook-form's setError.
.clear_errors(cx: &mut Context<Self>)Clears every field error and the form error.
.clear_errors_of(names: impl Into<Names>, cx: &mut Context<Self>)Clears the errors of some fields (and the fields inside them), like clearErrors(name) or clearErrors([a, b]).
.trigger(names: impl Into<Names>, cx: &mut Context<Self>) -> ValidationValidates some fields now, whatever the mode, like react-hook-form's trigger: one name, several, or Names::All. Errors show at once. The result says whether they all passed, once any async checks finish.
.set_focus(name: &str, window: &mut Window, cx: &mut App) -> boolMoves focus to a field's control, like react-hook-form's setFocus. Works for any control bound with [FormExt::input] or given a handle from [FormExt::focus_handle]. Returns whether the field had one. The control shows its focus ring even after a click, as a browser does for focus a script moves after keyboard use, so the user sees where focus went.
.submit(window: &mut Window, cx: &mut Context<Self>)Validates everything, waiting for async checks; if it all passes, runs the action and then on_success. If not, runs on_invalid and focuses the first invalid field.
.reset(window: &mut Window, cx: &mut Context<Self>)Back to the defaults, with errors, touched and dirty fields and the submit count cleared. A pending submit is abandoned.
.reset_with(values: Option<T>, options: ResetOptions, window: &mut Window, cx: &mut Context<Self>)Resets to new values, which also become the defaults, keeping whatever options say: react-hook-form's reset(values, options). None resets to the current defaults.
.set_values(values: T, window: &mut Window, cx: &mut Context<Self>)Values from outside the form, like react-hook-form's values prop: they replace the values and the defaults, so the form isn't dirty afterwards. Call it whenever the source changes, such as when a query returns.
Form::load_values<F>(&mut self, load: impl FnOnce(AsyncApp) -> F, window: &mut Window, cx: &mut Context<Self>)Loads the defaults asynchronously, like an async defaultValues: is_loading is true until the future resolves, then the form resets to what it returned.
Form::reset_field<V: Clone + PartialEq + 'static>(&mut self, path: &FieldPath<T, V>, options: ResetFieldOptions<V>, window: &mut Window, cx: &mut Context<Self>)Resets one field to its default (or a new one), like resetField(name, options).
Form::append<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, item: E, cx: &mut Context<Self>)Adds an item to the end of an array field, like useFieldArray's append.
Form::prepend<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, item: E, cx: &mut Context<Self>)Adds an item to the start of an array field.
Form::insert<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, index: usize, item: E, cx: &mut Context<Self>)Adds an item at index (clamped to the end) of an array field; the rows from there move down with their inputs and errors.
Form::remove<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, index: usize, cx: &mut Context<Self>)Removes the item at index of an array field, with its input and errors.
Form::swap<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, a: usize, b: usize, cx: &mut Context<Self>)Swaps two items of an array field; inputs and errors go with their rows.
Form::move_item<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, from: usize, to: usize, cx: &mut Context<Self>)Moves the item at from to to in an array field.
Form::update<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, index: usize, item: E, window: &mut Window, cx: &mut Context<Self>)Replaces the item at index. The row keeps its key, so its inputs stay mounted and show the new values; its old errors go.
Form::replace<E: PartialEq + 'static>(&mut self, path: &FieldPath<T, Vec<E>>, items: Vec<E>, window: &mut Window, cx: &mut Context<Self>)Replaces every item of an array field; each row gets a fresh key.
.bind_input(key: impl Into<SharedString>, path: FieldPath<T, String>, input: Entity<TextInput>, window: &mut Window, cx: &mut Context<Self>)Binds a text input to a String field: typing sets the value, set_value and reset set the text, an error marks it invalid, blur counts as touched and Enter submits. Binding the same input again just updates its path, so it is safe to call every render.
.bind_focus(key: impl Into<SharedString>, name: impl Into<SharedString>, window: &mut Window, cx: &mut Context<Self>) -> FocusHandleRegisters another control's focus handle for name, so set_focus and "focus the first error" reach it and its blur counts as touched. Called by [FormExt::focus_handle]; safe to call every render.
.bind_focus_handle(key: impl Into<SharedString>, name: impl Into<SharedString>, handle: Option<FocusHandle>, window: &mut Window, cx: &mut Context<Self>) -> FocusHandleLike [Form::bind_focus] with a handle the control owns, such as an InputOtp's. None makes one. Called by [FormExt::register_focus]; safe to call every render.