T06g forms structure: form with Cmd-Enter submit, sections, fields, labels, errors, field arrays, inline forms, dirty indicator

This commit is contained in:
ZacharyZhang-NY committed 2026-09-25 10:46:27 -04:00
1 parent 0ca1ff65c7
commit 05ff67ad9f
13 files changed
+850 -78

No files matched your search

+4 -2
View File
@@ -18,11 +18,13 @@ static URL: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^https?://[^\s/?#]+\.[^\s/?#]+\S*$").expect("url pattern compiles")
});
pub(crate) fn is_email(text: &str) -> bool {
/// Whether `text` reads as one email address.
pub fn is_email(text: &str) -> bool {
EMAIL.is_match(text)
}
pub(crate) fn is_url(text: &str) -> bool {
/// Whether `text` reads as a web link.
pub fn is_url(text: &str) -> bool {
URL.is_match(text)
}
+6 -2
View File
@@ -33,6 +33,7 @@ mod select;
mod signature;
mod slider;
mod stepper;
mod structure;
mod switch;
mod tags;
#[cfg(all(test, feature = "test-support"))]
@@ -45,7 +46,7 @@ pub use card::{CheckboxCard, RadioCard};
pub use cascade::{Cascade, Cascader};
pub use catalogs::FontPicker;
pub use check::{CheckState, Checkbox, CheckboxGroup};
pub use checked::{EmailInput, UrlInput};
pub use checked::{EmailInput, UrlInput, is_email, is_url};
pub use chips::ChoiceChips;
pub use code::{CodeInput, JsonInput, code_highlights, json_highlights};
pub use color::{ColorPalette, ColorPicker, ColorSwatch, EyeDropper, GradientEditor, GradientStop};
@@ -69,7 +70,7 @@ pub use mention::{MentionInput, mention_highlights};
pub use multi::MultiSelect;
pub use number::{NumberInput, ScrubInput};
pub use options::Choice;
pub use pairs::{KeyValueInput, ListInput};
pub use pairs::{FieldArray, KeyValueInput, ListInput};
pub use path::PathInput;
pub use pattern::{RegexInput, regex_highlights};
pub use pin::PinInput;
@@ -80,6 +81,9 @@ pub use select::Select;
pub use signature::{SignaturePad, Stroke};
pub use slider::{RangeSlider, Slider};
pub use stepper::Stepper;
pub use structure::{
DirtyIndicator, Form, FormError, FormField, FormLabel, FormSection, InlineForm,
};
pub use switch::Switch;
pub use tags::TagInput;
pub(crate) use text::bind_keys;
+122 -59
View File
@@ -1,11 +1,11 @@
use std::rc::Rc;
use gpui::{
App, Context, ElementId, Entity, IntoElement, ParentElement, RenderOnce, SharedString, Styled,
Subscription, Window, div, prelude::*,
AnyElement, App, Context, ElementId, Entity, IntoElement, ParentElement, RenderOnce,
SharedString, Styled, Subscription, Window, div, prelude::*,
};
use super::{Input, InputEvent, TextInput};
use super::{Input, InputEvent, TextInput, options::Run};
use crate::{
buttons::{Button, ButtonVariant, IconButton},
primitives::IconName,
@@ -85,68 +85,131 @@ fn rows_state(
})
}
fn render_rows(
id: &ElementId,
state: Entity<Rows>,
add: &'static str,
cx: &App,
) -> impl IntoElement + use<> {
let rows = state.read(cx).rows.len();
let lines = (0..rows).map(|ix| {
let fields: Vec<Entity<TextInput>> = state.read(cx).rows[ix]
.iter()
.map(|(field, _)| field.clone())
.collect();
let remove = state.clone();
type OnRemove = Rc<dyn Fn(usize, &mut Window, &mut App)>;
/// Rows the owner builds, each with a remove button, and a button that adds one.
#[derive(IntoElement)]
pub struct FieldArray {
id: ElementId,
rows: Vec<AnyElement>,
add_label: SharedString,
on_add: Option<Run>,
on_remove: Option<OnRemove>,
}
impl FieldArray {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
rows: Vec::new(),
add_label: SharedString::from("Add"),
on_add: None,
on_remove: None,
}
}
pub fn row(mut self, row: impl IntoElement) -> Self {
self.rows.push(row.into_any_element());
self
}
pub fn add_label(mut self, text: impl Into<SharedString>) -> Self {
self.add_label = text.into();
self
}
pub fn on_add(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_add = Some(Rc::new(handler));
self
}
/// Runs with the index of the row to remove.
pub fn on_remove(mut self, handler: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
self.on_remove = Some(Rc::new(handler));
self
}
}
impl RenderOnce for FieldArray {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
let lines = self.rows.into_iter().enumerate().map(|(ix, row)| {
let (id, remove) = (id.clone(), self.on_remove.clone());
div()
.flex()
.items_center()
.gap_2()
.child(div().flex_1().min_w_0().child(row))
.child(
IconButton::new(("remove-row", ix), IconName::Minus)
.size(ControlSize::Sm)
.tooltip("Remove")
.on_click(move |_, window, cx| {
log::info!("field array {id:?}: removed row {ix}");
if let Some(remove) = &remove {
remove(ix, window, cx);
}
}),
)
});
let add = self.on_add;
div()
.id(self.id)
.flex()
.items_center()
.flex_col()
.gap_2()
.children(fields.iter().map(|field| {
div()
.flex_1()
.child(Input::new(field).size(ControlSize::Sm))
}))
.w_full()
.children(lines)
.child(
IconButton::new(("remove-row", ix), IconName::Minus)
.size(ControlSize::Sm)
.tooltip("Remove")
.on_click(move |_, window, cx| {
log::info!("rows: removed {ix}");
remove.update(cx, |rows, cx| {
rows.rows.remove(ix);
rows.report(window, cx);
cx.notify();
})
}),
div().flex().child(
Button::new(("add-row", 0usize), self.add_label)
.size(ControlSize::Sm)
.variant(ButtonVariant::Ghost)
.icon(IconName::Plus)
.on_click(move |_, window, cx| {
log::info!("field array {id:?}: added a row");
if let Some(add) = &add {
add(window, cx);
}
}),
),
)
});
let grow = state.clone();
div()
.id(id.clone())
.flex()
.flex_col()
.gap_2()
.w_full()
.children(lines)
.child(
div().child(
Button::new(("add-row", 0usize), add)
.size(ControlSize::Sm)
.variant(ButtonVariant::Ghost)
.icon(IconName::Plus)
.on_click(move |_, window, cx| {
log::info!("rows: added one");
grow.update(cx, |rows, cx| {
rows.push(&[], window, cx);
let last = rows.rows.last().expect("just pushed");
window.focus(&last[0].0.read(cx).focus().clone());
rows.report(window, cx);
cx.notify();
})
}),
),
}
}
fn render_rows(id: &ElementId, state: Entity<Rows>, add: &'static str, cx: &App) -> FieldArray {
let (grow, remove) = (state.clone(), state.clone());
let array = FieldArray::new(id.clone())
.add_label(add)
.on_add(move |window, cx| {
grow.update(cx, |rows, cx| {
rows.push(&[], window, cx);
let last = rows.rows.last().expect("just pushed");
window.focus(&last[0].0.read(cx).focus().clone());
rows.report(window, cx);
cx.notify();
})
})
.on_remove(move |ix, window, cx| {
remove.update(cx, |rows, cx| {
rows.rows.remove(ix);
rows.report(window, cx);
cx.notify();
})
});
state.read(cx).rows.iter().fold(array, |array, row| {
array.row(
div()
.flex()
.items_center()
.gap_2()
.children(row.iter().map(|(field, _)| {
div()
.flex_1()
.child(Input::new(field).size(ControlSize::Sm))
})),
)
})
}
/// Rows of key and value fields; add and remove rows.
+368
View File
@@ -0,0 +1,368 @@
use std::rc::Rc;
use gpui::{
Animation, AnimationExt, AnyElement, App, ElementId, InteractiveElement, IntoElement,
ParentElement, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, div,
prelude::*,
};
use smallvec::SmallVec;
use super::{options::Run, text::Submit};
use crate::{
motion,
primitives::{Icon, IconName, Tooltip},
theme::{ActiveTheme, IconSize, TextSize},
typography::{Caption, Heading, Label},
};
/// Sections stacked with room between them. Cmd-Enter in any field submits the form.
#[derive(IntoElement)]
pub struct Form {
id: ElementId,
children: SmallVec<[AnyElement; 4]>,
on_submit: Option<Run>,
}
impl Form {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
children: SmallVec::new(),
on_submit: None,
}
}
pub fn on_submit(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_submit = Some(Rc::new(handler));
self
}
}
impl ParentElement for Form {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for Form {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
div()
.id(self.id)
.flex()
.flex_col()
.gap_8()
.w_full()
.when_some(self.on_submit, |form, submit| {
form.capture_action(move |_: &Submit, window, cx| {
cx.stop_propagation();
log::info!("form {id:?}: submitted");
submit(window, cx);
})
})
.children(self.children)
}
}
/// A titled group of fields, with a line of context under the title.
#[derive(IntoElement)]
pub struct FormSection {
title: SharedString,
description: Option<SharedString>,
children: SmallVec<[AnyElement; 4]>,
}
impl FormSection {
pub fn new(title: impl Into<SharedString>) -> Self {
Self {
title: title.into(),
description: None,
children: SmallVec::new(),
}
}
pub fn description(mut self, text: impl Into<SharedString>) -> Self {
self.description = Some(text.into());
self
}
}
impl ParentElement for FormSection {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for FormSection {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap_4()
.w_full()
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(Heading::h4(self.title))
.children(self.description.map(Caption::new)),
)
.children(self.children)
}
}
/// A field's name, with a required mark and a help tip when asked.
#[derive(IntoElement)]
pub struct FormLabel {
id: ElementId,
text: SharedString,
required: bool,
help: Option<SharedString>,
}
impl FormLabel {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
required: false,
help: None,
}
}
pub fn required(mut self) -> Self {
self.required = true;
self
}
/// A tip behind a help mark beside the name.
pub fn help(mut self, text: impl Into<SharedString>) -> Self {
self.help = Some(text.into());
self
}
}
impl RenderOnce for FormLabel {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let colors = &cx.theme().colors;
div()
.flex()
.items_center()
.gap_1()
.child(Label::new(self.text))
.when(self.required, |label| {
label.child(div().text_color(colors.danger).child("*"))
})
.when_some(self.help, |label, help| {
label.child(
div()
.id((self.id, "help"))
.child(
Icon::new(IconName::CircleHelp)
.size(IconSize::Xs)
.color(colors.fg_subtle),
)
.tooltip(Tooltip::text(help)),
)
})
}
}
/// Why a field failed, in the danger color. Each new message eases in.
#[derive(IntoElement)]
pub struct FormError {
id: ElementId,
text: SharedString,
}
impl FormError {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
}
}
}
impl RenderOnce for FormError {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let danger = theme.colors.danger;
div()
.flex()
.items_center()
.gap_1()
.text_size(theme.text_size(TextSize::Sm))
.text_color(danger)
.child(
Icon::new(IconName::CircleAlert)
.size(IconSize::Xs)
.color(danger),
)
.child(self.text.clone())
.with_animation(
ElementId::from((self.id, self.text)),
Animation::new(motion::duration(motion::FAST, cx))
.with_easing(motion::ease_out_cubic),
|error, t| error.opacity(t).mt(motion::NUDGE * (t - 1.0)),
)
}
}
/// A labeled control, with a description beneath, or the error once it fails.
#[derive(IntoElement)]
pub struct FormField {
id: ElementId,
label: FormLabel,
description: Option<SharedString>,
error: Option<SharedString>,
children: SmallVec<[AnyElement; 2]>,
}
impl FormField {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
let id = id.into();
Self {
label: FormLabel::new((id.clone(), "label"), label),
id,
description: None,
error: None,
children: SmallVec::new(),
}
}
pub fn required(mut self) -> Self {
self.label = self.label.required();
self
}
pub fn help(mut self, text: impl Into<SharedString>) -> Self {
self.label = self.label.help(text);
self
}
pub fn description(mut self, text: impl Into<SharedString>) -> Self {
self.description = Some(text.into());
self
}
/// Shown in place of the description.
pub fn error(mut self, text: impl Into<SharedString>) -> Self {
self.error = Some(text.into());
self
}
}
impl ParentElement for FormField {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for FormField {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let note = match (self.error, self.description) {
(Some(error), _) => Some(FormError::new((self.id, "error"), error).into_any_element()),
(None, Some(description)) => Some(Caption::new(description).into_any_element()),
(None, None) => None,
};
div()
.flex()
.flex_col()
.gap_1p5()
.w_full()
.child(self.label)
.children(self.children)
.children(note)
}
}
/// Fields and actions in one row, their bottoms aligned; the row wraps when narrow.
#[derive(IntoElement)]
pub struct InlineForm {
children: SmallVec<[AnyElement; 4]>,
}
impl InlineForm {
pub fn new() -> Self {
Self {
children: SmallVec::new(),
}
}
}
impl Default for InlineForm {
fn default() -> Self {
Self::new()
}
}
impl ParentElement for InlineForm {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for InlineForm {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div()
.flex()
.flex_wrap()
.items_end()
.gap_3()
.w_full()
.children(self.children)
}
}
/// A dot and a word while there are unsaved changes; nothing once saved.
#[derive(IntoElement)]
pub struct DirtyIndicator {
id: ElementId,
dirty: bool,
label: SharedString,
}
impl DirtyIndicator {
pub fn new(id: impl Into<ElementId>, dirty: bool) -> Self {
Self {
id: id.into(),
dirty,
label: SharedString::from("Unsaved changes"),
}
}
pub fn label(mut self, text: impl Into<SharedString>) -> Self {
self.label = text.into();
self
}
}
impl RenderOnce for DirtyIndicator {
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let shown = self.dirty.then(|| {
div()
.flex()
.items_center()
.gap_1p5()
.text_size(theme.text_size(TextSize::Sm))
.text_color(theme.colors.fg_muted)
.child(
div()
.size(theme.status_dot())
.rounded_full()
.bg(theme.colors.warning),
)
.child(self.label)
.with_animation(
self.id,
Animation::new(motion::duration(motion::BASE, cx))
.with_easing(motion::ease_out_cubic),
|shown, t| shown.opacity(t),
)
});
div().children(shown)
}
}
+1
View File
@@ -2,6 +2,7 @@ mod choices;
mod colors;
mod dates;
mod other;
mod structure;
use gpui::{
AppContext as _, Context, Entity, EntityInputHandler, IntoElement, KeyUpEvent, Keystroke,
+113
View File
@@ -0,0 +1,113 @@
use gpui::{
AppContext as _, Context, Entity, IntoElement, KeyUpEvent, Keystroke, ParentElement, Render,
TestAppContext, VisualTestContext, Window, div,
};
use super::setup;
use crate::forms::{FieldArray, Form, FormField, Input, InputEvent, TextInput};
struct Signup {
name: Entity<TextInput>,
sent: usize,
field_submits: usize,
}
impl Render for Signup {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let view = cx.entity();
Form::new("signup")
.on_submit(move |_, cx| {
view.update(cx, |view, cx| {
view.sent += 1;
cx.notify();
})
})
.child(
FormField::new("signup-name", "Name")
.required()
.child(Input::new(&self.name)),
)
}
}
#[gpui::test]
fn cmd_enter_in_a_field_submits_the_form_once(cx: &mut TestAppContext) {
setup(cx);
let (view, cx) = cx.add_window_view(|window, cx| {
let name = cx.new(|cx| TextInput::new(window, cx));
cx.subscribe(&name, |view: &mut Signup, _, event, _| {
if *event == InputEvent::Submit {
view.field_submits += 1;
}
})
.detach();
Signup {
name,
sent: 0,
field_submits: 0,
}
});
cx.update(|window, _| window.focus_next());
cx.simulate_input("Ada");
cx.simulate_keystrokes("cmd-enter");
let counts = view.read_with(cx, |view, _| (view.sent, view.field_submits));
assert_eq!(counts, (1, 0));
}
struct Rows {
rows: Vec<&'static str>,
}
impl Render for Rows {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (grow, shrink) = (cx.entity(), cx.entity());
self.rows.iter().fold(
FieldArray::new("rows")
.on_add(move |_, cx| {
grow.update(cx, |view, cx| {
view.rows.push("new");
cx.notify();
})
})
.on_remove(move |ix, _, cx| {
shrink.update(cx, |view, cx| {
view.rows.remove(ix);
cx.notify();
})
}),
|array, row| array.row(div().child(*row)),
)
}
}
fn press(key: &str, cx: &mut VisualTestContext) {
cx.simulate_keystrokes(key);
cx.simulate_event(KeyUpEvent {
keystroke: Keystroke::parse(key).unwrap(),
});
}
#[gpui::test]
fn field_array_buttons_remove_their_own_row_and_add_one(cx: &mut TestAppContext) {
setup(cx);
let (view, cx) = cx.add_window_view(|_, _| Rows {
rows: vec!["a", "b", "c"],
});
cx.update(|window, _| {
window.focus_next();
window.focus_next();
});
press("space", cx);
assert_eq!(view.read_with(cx, |view, _| view.rows.clone()), ["a", "c"]);
cx.update(|window, _| {
window.blur();
for _ in 0..3 {
window.focus_next();
}
});
press("space", cx);
assert_eq!(
view.read_with(cx, |view, _| view.rows.clone()),
["a", "c", "new"]
);
}
+1 -1
View File
@@ -10,7 +10,7 @@ use gpui::{
Subscription, Task, Window, WrappedLine,
};
pub(crate) use actions::{Backspace, Down, Enter, Up, bind_keys};
pub(crate) use actions::{Backspace, Down, Enter, Submit, Up, bind_keys};
use edit::{History, Snapshot};
use crate::theme::ActiveTheme;