Lays out a label, a control, helper text and an error message.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn field_demo(window: &mut Window, cx: &mut App) -> impl IntoElement {
let username = window.use_keyed_state("username", cx, |_, cx| {
TextInput::new(cx).placeholder("hyuskui")
});
let email = window.use_keyed_state("email", cx, |_, cx| {
TextInput::new(cx).default_value("hello@").placeholder("you@example.com")
});
let address = email.read(cx).text();
let valid = address.is_empty()
|| address
.split_once('@')
.is_some_and(|(name, domain)| !name.is_empty() && domain.contains('.'));
email.update(cx, |email, cx| email.set_invalid(!valid, cx));
div()
.w(px(360.))
.flex()
.flex_col()
.gap_6()
.child(
Field::new()
.label("Username")
.description("Choose a unique username for your account.")
.child(username),
)
.child(
Field::new()
.label("Email")
.when(!valid, |field| field.error("Enter a valid email address."))
.child(email),
)
}Installation
Copies src/ui/field.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/field.rs.src/ui/field.rs use gpui::{div, prelude::*, px, AnyElement, App, FontWeight, SharedString, Window}; use crate::theme::ActiveTheme; /// Lays out a label, a control, helper text and an error message, like shadcn/ui's Field. /// /// The label is plain text rather than a separate Label component so the file stands alone. /// Setting an error turns the label and message destructive; mark the control itself /// invalid too (for example `TextInput::set_invalid`) so its border matches. #[derive(IntoElement)] pub struct Field { label: Option<SharedString>, description: Option<SharedString>, errors: Vec<SharedString>, disabled: bool, required: bool, horizontal: bool, control: Option<AnyElement>, } impl Field { pub fn new() -> Self { Self { label: None, description: None, errors: Vec::new(), disabled: false, required: false, horizontal: false, control: None, } } pub fn label(mut self, label: impl Into<SharedString>) -> Self { self.label = Some(label.into()); self } pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } /// Shown under the control; pair with `.when(...)` to show it conditionally. pub fn error(mut self, error: impl Into<SharedString>) -> Self { self.errors = vec![error.into()]; self } /// Several errors at once, such as every rule a password fails. More than one shows as a /// bulleted list, like shadcn/ui's FieldError with an `errors` array. pub fn errors(mut self, errors: impl IntoIterator<Item = impl Into<SharedString>>) -> Self { self.errors = errors.into_iter().map(Into::into).collect(); self } /// Dims the label and helper text to match a disabled control. pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// Marks the label with a destructive asterisk. Display only: validate in your view. pub fn required(mut self, required: bool) -> Self { self.required = required; self } /// Puts the label and helper text on the left and the control on the right, like a /// settings row with a `Switch`. pub fn horizontal(mut self, horizontal: bool) -> Self { self.horizontal = horizontal; self } pub fn child(mut self, control: impl IntoElement) -> Self { self.control = Some(control.into_any_element()); self } } impl Default for Field { fn default() -> Self { Self::new() } } impl RenderOnce for Field { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let invalid = !self.errors.is_empty(); let label_color = if invalid { theme.destructive } else { theme.foreground }; let text = |content: SharedString| div().text_sm().line_height(px(20.)).child(content); let label = self.label.map(|label| { div() .flex() .gap_1() .text_sm() .font_weight(FontWeight::MEDIUM) .text_color(label_color) .when(self.disabled, |this| this.opacity(0.5)) .child(label) .when(self.required, |this| { this.child(div().text_color(theme.destructive).child("*")) }) }); let description = self.description.map(|description| { text(description) .text_color(theme.muted_foreground) .when(self.disabled, |this| this.opacity(0.5)) }); let destructive = theme.destructive; let error = match self.errors.len() { 0 => None, 1 => self.errors.into_iter().next().map(|error| text(error).text_color(destructive)), _ => Some(self.errors.into_iter().fold(div().flex().flex_col().gap_1(), |list, error| { list.child( div() .flex() .items_start() .gap_2() .text_color(destructive) // A drawn bullet, centered on the first 20px line. .child(div().mt(px(8.)).ml_1().size(px(4.)).flex_none().rounded_full().bg(destructive)) .child(text(error)), ) })), }; if self.horizontal { return div() .w_full() .flex() .items_center() .justify_between() .gap_4() .child( div() .flex_1() // Lets long helper text wrap instead of pushing the control out. .min_w_0() .flex() .flex_col() .gap_1() .children(label) .children(description) .children(error), ) .children(self.control); } div() .w_full() .flex() .flex_col() .gap_3() .children(label) .children(self.control) .children(description) .children(error) } } /// Groups related fields under a legend and optional description, like a `<fieldset>` /// (shadcn/ui's FieldSet and FieldLegend). Add each field or control with `child`. #[derive(IntoElement)] pub struct FieldSet { legend: Option<SharedString>, description: Option<SharedString>, disabled: bool, label_legend: bool, children: Vec<AnyElement>, } impl FieldSet { /// An empty fieldset; add a legend, a description and children. pub fn new() -> Self { Self { legend: None, description: None, disabled: false, label_legend: false, children: Vec::new(), } } /// The group's heading. pub fn legend(mut self, legend: impl Into<SharedString>) -> Self { self.legend = Some(legend.into()); self } /// Muted text under the legend. pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } /// Dims the legend and description to match disabled controls. pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// Draws the legend at label size, like shadcn/ui's `FieldLegend variant="label"`, for a /// group that sits among other fields rather than heading a section. pub fn label_legend(mut self, label_legend: bool) -> Self { self.label_legend = label_legend; self } /// Appends a field or control; children stack with a gap between them. pub fn child(mut self, child: impl IntoElement) -> Self { self.children.push(child.into_any_element()); self } } impl Default for FieldSet { fn default() -> Self { Self::new() } } impl RenderOnce for FieldSet { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let has_heading = self.legend.is_some() || self.description.is_some(); div() .w_full() .flex() .flex_col() .gap_4() .when(has_heading, |this| { this.child( div() .flex() .flex_col() .gap_1() .when(self.disabled, |this| this.opacity(0.5)) .when_some(self.legend, |this, legend| { this.child( div() .when(self.label_legend, |this| this.text_sm()) .when(!self.label_legend, |this| this.text_base()) .font_weight(FontWeight::MEDIUM) .text_color(theme.foreground) .child(legend), ) }) .when_some(self.description, |this, description| { this.child( div() .text_sm() .line_height(px(20.)) .text_color(theme.muted_foreground) .child(description), ) }), ) }) .children(self.children) } }Register the module
// src/ui/mod.rs pub mod field;
Usage
use crate::ui::field::*;Examples
Input
Text inputs, each in a Field with a label and helper text under the control.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn field_input(window: &mut Window, cx: &mut App) -> impl IntoElement {
let username = window.use_keyed_state("field-input-username", cx, |_, cx| {
TextInput::new(cx).placeholder("Max Leiter")
});
let password = window.use_keyed_state("field-input-password", cx, |_, cx| {
TextInput::new(cx).placeholder("••••••••")
});
div()
.w(px(360.))
.flex()
.flex_col()
.gap_6()
.child(
Field::new()
.label("Username")
.description("Choose a unique username for your account.")
.child(username),
)
.child(
Field::new()
.label("Password")
.description("Must be at least 8 characters long.")
.child(password),
)
}Textarea
A multi-line Textarea in a Field.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::Field;
use crate::ui::textarea::Textarea;
pub fn field_textarea(window: &mut Window, cx: &mut App) -> impl IntoElement {
let feedback = window.use_keyed_state("field-textarea-feedback", cx, |_, cx| {
Textarea::new(cx).placeholder("Your feedback helps us improve...")
});
div().w(px(360.)).child(
Field::new()
.label("Feedback")
.description("Share your thoughts about our service.")
.child(feedback),
)
}Slider
A Slider in a Field, with the description echoing the current value.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::field::Field;
use crate::ui::slider::Slider;
pub struct FieldSlider {
budget: f32,
}
// Starts mid-range, so `Default` is written out instead of derived.
impl Default for FieldSlider {
fn default() -> Self {
Self { budget: 500.0 }
}
}
impl Render for FieldSlider {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(360.)).child(
Field::new()
.label("Price Range")
.description(format!("Set your budget: up to ${}.", self.budget))
.child(
Slider::new("field-slider-budget", self.budget)
.max(1000.0)
.step(10.0)
.on_change(cx.listener(|this, value: &f32, _, cx| {
this.budget = *value;
cx.notify();
})),
),
)
}
}Fieldset
FieldSet groups related fields under a legend and description, like a <fieldset>.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::{Field, FieldSet};
use crate::ui::input::TextInput;
pub fn field_fieldset(window: &mut Window, cx: &mut App) -> impl IntoElement {
let street = window.use_keyed_state("field-fieldset-street", cx, |_, cx| {
TextInput::new(cx).placeholder("123 Main St")
});
let city = window.use_keyed_state("field-fieldset-city", cx, |_, cx| {
TextInput::new(cx).placeholder("New York")
});
let postal = window.use_keyed_state("field-fieldset-postal", cx, |_, cx| {
TextInput::new(cx).placeholder("90502")
});
div().w(px(400.)).child(
FieldSet::new()
.legend("Address Information")
.description("We need your address to deliver your order.")
.child(Field::new().label("Street Address").child(street))
.child(
div()
.flex()
.gap_4()
.child(div().flex_1().child(Field::new().label("City").child(city)))
.child(div().flex_1().child(Field::new().label("Postal Code").child(postal))),
),
)
}Checkbox
A FieldSet of checkboxes, then a single checkbox with a description.
use gpui::{div, prelude::*, px, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::checkbox::Checkbox;
use crate::ui::field::FieldSet;
const ITEMS: [&str; 4] = ["Hard disks", "External disks", "CDs, DVDs, and iPods", "Connected servers"];
pub struct FieldCheckbox {
shown: [bool; 4],
sync: bool,
}
impl Default for FieldCheckbox {
fn default() -> Self {
Self {
shown: [false, true, false, false],
sync: true,
}
}
}
impl Render for FieldCheckbox {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let mut items = FieldSet::new()
.legend("Show these items on the desktop")
.description("Select the items you want to show on the desktop.");
for (ix, label) in ITEMS.into_iter().enumerate() {
items = items.child(
Checkbox::new(("field-checkbox-item", ix), self.shown[ix])
.label(label)
.on_toggle(cx.listener(move |this, checked: &bool, _, cx| {
this.shown[ix] = *checked;
cx.notify();
})),
);
}
div()
.w(px(400.))
.flex()
.flex_col()
.gap_6()
.child(items)
.child(div().h(px(1.)).bg(cx.theme().border))
.child(
Checkbox::new("field-checkbox-sync", self.sync)
.label("Sync Desktop & Documents folders")
.description(
"Your Desktop & Documents folders are being synced with iCloud Drive. \
You can access them from other devices.",
)
.on_toggle(cx.listener(|this, checked: &bool, _, cx| {
this.sync = *checked;
cx.notify();
})),
)
}
}Radio
A RadioGroup under a FieldSet legend.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::field::FieldSet;
use crate::ui::radio_group::RadioGroup;
#[derive(Default)]
pub struct FieldRadio {
plan: Option<usize>,
}
impl Render for FieldRadio {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(360.)).child(
FieldSet::new()
.legend("Subscription Plan")
.description("Yearly and lifetime plans offer significant savings.")
.child(
RadioGroup::new("field-radio-plan", self.plan)
.option("Monthly ($9.99/month)")
.option("Yearly ($99.99/year)")
.option("Lifetime ($299.99)")
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.plan = Some(*ix);
cx.notify();
})),
),
)
}
}Switch
horizontal(true) puts the label and description beside the control, like a settings row.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::field::Field;
use crate::ui::switch::Switch;
#[derive(Default)]
pub struct FieldSwitch {
mfa: bool,
}
impl Render for FieldSwitch {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(400.)).child(
Field::new()
.horizontal(true)
.label("Multi-factor authentication")
.description(
"Enable multi-factor authentication. If you do not have a two-factor \
device, you can use a one-time code sent to your email.",
)
.child(
Switch::new("field-switch-mfa", self.mfa).on_toggle(cx.listener(
|this, on: &bool, _, cx| {
this.mfa = *on;
cx.notify();
},
)),
),
)
}
}Choice Card
RadioGroup::cards turns each option into a selectable card with a title and description.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::field::FieldSet;
use crate::ui::radio_group::RadioGroup;
pub struct FieldChoiceCard {
environment: Option<usize>,
}
// Starts with the first card selected, so `Default` is written out instead of derived.
impl Default for FieldChoiceCard {
fn default() -> Self {
Self { environment: Some(0) }
}
}
impl Render for FieldChoiceCard {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(400.)).child(
FieldSet::new()
.legend("Compute Environment")
.description("Select the compute environment for your cluster.")
.child(
RadioGroup::new("field-choice-card", self.environment)
.cards(true)
.option_with_description(
"Kubernetes",
"Run GPU workloads on a K8s configured cluster.",
)
.option_with_description(
"Virtual Machine",
"Access a VM configured cluster to run GPU workloads.",
)
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.environment = Some(*ix);
cx.notify();
})),
),
)
}
}Field Group
Several FieldSets stacked with a divider, each holding checkboxes with descriptions.
use gpui::{div, prelude::*, px, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::checkbox::Checkbox;
use crate::ui::field::FieldSet;
pub struct FieldFieldGroup {
/// Responses push, Tasks push, Tasks email.
enabled: [bool; 3],
}
impl Default for FieldFieldGroup {
fn default() -> Self {
Self { enabled: [true, false, false] }
}
}
impl FieldFieldGroup {
fn checkbox(&self, ix: usize, label: &'static str, description: &'static str, cx: &mut Context<Self>) -> Checkbox {
Checkbox::new(("field-field-group", ix), self.enabled[ix])
.label(label)
.description(description)
.on_toggle(cx.listener(move |this, checked: &bool, _, cx| {
this.enabled[ix] = *checked;
cx.notify();
}))
}
}
impl Render for FieldFieldGroup {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let divider = cx.theme().border;
div()
.w(px(400.))
.flex()
.flex_col()
.gap_6()
.child(
FieldSet::new()
.legend("Responses")
.description("Get notified when a long-running request finishes.")
.child(self.checkbox(
0,
"Push notifications",
"Receive push notifications on your devices.",
cx,
)),
)
.child(div().h(px(1.)).bg(divider))
.child(
FieldSet::new()
.legend("Tasks")
.description("Get notified when tasks you've created have updates.")
.child(self.checkbox(
1,
"Push notifications",
"Receive push notifications on your devices.",
cx,
))
.child(self.checkbox(
2,
"Email notifications",
"Receive email updates about your tasks.",
cx,
)),
)
}
}API Reference
Field
Lays out a label, a control, helper text and an error message, like shadcn/ui's Field. The label is plain text rather than a separate Label component so the file stands alone. Setting an error turns the label and message destructive; mark the control itself invalid too (for example TextInput::set_invalid) so its border matches.
Field::new() -> Self.label(label: impl Into<SharedString>).description(description: impl Into<SharedString>).error(error: impl Into<SharedString>)Shown under the control; pair with .when(...) to show it conditionally.
.errors(errors: impl IntoIterator<Item = impl Into<SharedString>>)Several errors at once, such as every rule a password fails. More than one shows as a bulleted list, like shadcn/ui's FieldError with an errors array.
.disabled(disabled: bool)Dims the label and helper text to match a disabled control.
.required(required: bool)Marks the label with a destructive asterisk. Display only: validate in your view.
.horizontal(horizontal: bool)Puts the label and helper text on the left and the control on the right, like a settings row with a Switch.
.child(control: impl IntoElement)FieldSet
Groups related fields under a legend and optional description, like a <fieldset> (shadcn/ui's FieldSet and FieldLegend). Add each field or control with child.
FieldSet::new() -> SelfAn empty fieldset; add a legend, a description and children.
.legend(legend: impl Into<SharedString>)The group's heading.
.description(description: impl Into<SharedString>)Muted text under the legend.
.disabled(disabled: bool)Dims the legend and description to match disabled controls.
.label_legend(label_legend: bool)Draws the legend at label size, like shadcn/ui's FieldLegend variant="label", for a group that sits among other fields rather than heading a section.
.child(child: impl IntoElement)Appends a field or control; children stack with a gap between them.