A text input with leading and trailing addons inside one border.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
use crate::ui::kbd::Kbd;
pub fn input_group_demo(window: &mut Window, cx: &mut App) -> impl IntoElement {
// Grouped inputs are `.bare()`: the InputGroup draws the border and focus ring.
let search = window.use_keyed_state("search", cx, |_, cx| {
TextInput::new(cx).placeholder("Search...").bare()
});
let website = window.use_keyed_state("website", cx, |_, cx| {
TextInput::new(cx).placeholder("example").bare()
});
let price = window.use_keyed_state("price", cx, |_, cx| {
TextInput::new(cx).placeholder("0.00").bare()
});
div()
.w(px(320.))
.flex()
.flex_col()
.gap_3()
.child(InputGroup::new(search).trailing(Kbd::new("/")))
.child(InputGroup::new(website).leading("https://").trailing(".com"))
.child(InputGroup::new(price).leading("$").trailing("USD"))
}Installation
Copies src/ui/input_group.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/input_group.rs.src/ui/input_group.rs use std::sync::Arc; use gpui::{ div, point, prelude::*, px, AnimationExt, AnyElement, App, BoxShadow, ElementId, Entity, Focusable, MouseButton, SpringAnimation, SpringConfig, Window, }; use crate::theme::ActiveTheme; use crate::ui::input::TextInput; /// shadcn's 150ms `transition-[color,box-shadow]` as a critically damped spring. const FOCUS_SPRING: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); /// A text input with addons (prefix text, a unit, a shortcut hint, a button) inside one border. /// /// Create the input with `.bare()` so the group draws the border and focus ring around /// everything: `InputGroup::new(cx.new(|cx| TextInput::new(cx).bare())).leading("https://")`. #[derive(IntoElement)] pub struct InputGroup { input: Entity<TextInput>, leading: Vec<AnyElement>, trailing: Vec<AnyElement>, block_start: Vec<AnyElement>, block_end: Vec<AnyElement>, } impl InputGroup { pub fn new(input: Entity<TextInput>) -> Self { Self { input, leading: Vec::new(), trailing: Vec::new(), block_start: Vec::new(), block_end: Vec::new(), } } /// Placed before the text, in muted color. pub fn leading(mut self, addon: impl IntoElement) -> Self { self.leading.push(addon.into_any_element()); self } /// Placed after the text, in muted color. pub fn trailing(mut self, addon: impl IntoElement) -> Self { self.trailing.push(addon.into_any_element()); self } /// A full-width row above the input, such as a file name or a label with actions. With a /// block addon the group grows to fit, so it suits a multi-line input like a `Textarea`. pub fn block_start(mut self, addon: impl IntoElement) -> Self { self.block_start.push(addon.into_any_element()); self } /// A full-width row below the input, such as a character count or a submit button. pub fn block_end(mut self, addon: impl IntoElement) -> Self { self.block_end.push(addon.into_any_element()); self } } impl RenderOnce for InputGroup { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let input = self.input.read(cx); let focused = input.is_focused(window); let (invalid, disabled) = (input.is_invalid(), input.is_disabled()); let focus_handle = input.focus_handle(cx); // The group has no id of its own, so its focus spring is keyed by the input it wraps. let spring_id = ElementId::NamedChild( Arc::new(ElementId::View(self.input.entity_id())), "input-group-focus".into(), ); let theme = cx.theme(); let (idle_border, focus_border) = if invalid { (theme.destructive, theme.destructive) } else { (theme.input, theme.ring) }; let ring = if invalid { theme.destructive.opacity(0.2) } else { theme.ring.opacity(0.5) }; let has_leading = !self.leading.is_empty(); let has_trailing = !self.trailing.is_empty(); let addon = || { div() .flex() .flex_none() .items_center() .gap_2() .text_sm() .text_color(theme.muted_foreground) }; let has_block = !self.block_start.is_empty() || !self.block_end.is_empty(); let block = || addon().w_full().px_3().justify_between(); let row = div() .flex() .items_center() .w_full() // 36px with the border; a minimum rather than a fixed height, so a multi-line // input can grow inside a group with block addons. .min_h(px(34.)) .when(has_leading, |this| this.child(addon().pl_3().children(self.leading))) .child( div() .flex_1() .min_w_0() .when(has_block, |this| this.py_2()) .pl(if has_leading { px(8.) } else { px(12.) }) .pr(if has_trailing { px(8.) } else { px(12.) }) .child(self.input), ) .when(has_trailing, |this| this.child(addon().pr_3().children(self.trailing))); div() .flex() .flex_col() .w_full() // Without block addons the group keeps its fixed 36px height, like a plain input. .when(!has_block, |this| this.h(px(36.))) .rounded(theme.radius) .border_1() // GPUI shadows fill the whole shape; the opaque background keeps the ring outside. .bg(theme.background) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) // Clicking an addon focuses the field, as with a `<label>` around an `<input>`. .when(!disabled, |this| { this.cursor_text() .on_mouse_down(MouseButton::Left, move |_, window, cx| { window.focus(&focus_handle, cx); }) }) .when(!self.block_start.is_empty(), |this| { this.child(block().pt_3().children(self.block_start)) }) .child(row) .when(!self.block_end.is_empty(), |this| { this.child(block().pb_3().children(self.block_end)) }) // The border color and focus ring ease in and out, like a lone `TextInput`. .with_spring( spring_id, SpringAnimation::new(FOCUS_SPRING).to(focused && !disabled), move |this, phase| { let amount = phase.interpolate_clamped(0.0, 1.0); let border = phase.interpolate_clamped(idle_border, focus_border); let this = this.border_color(border); if amount <= 0.01 { return this.shadow_xs(); } this.shadow(vec![BoxShadow { color: ring.opacity(amount), offset: point(px(0.), px(0.)), blur_radius: px(0.), spread_radius: px(3.) * amount, inset: false, }]) }, ) } }Register the module
// src/ui/mod.rs pub mod input_group;
Usage
use crate::ui::input_group::*;Examples
Align
leading and trailing place addons at the start and end of the line; block_start and block_end add full-width rows above and below the input.
use gpui::{div, prelude::*, px, App, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
pub fn input_group_align(window: &mut Window, cx: &mut App) -> impl IntoElement {
let start = window.use_keyed_state("input-group-align-start", cx, |_, cx| {
TextInput::new(cx).placeholder("Inline start").bare()
});
let end = window.use_keyed_state("input-group-align-end", cx, |_, cx| {
TextInput::new(cx).placeholder("Inline end").bare()
});
let top = window.use_keyed_state("input-group-align-block-start", cx, |_, cx| {
TextInput::new(cx).placeholder("Jordan Lee").bare()
});
let bottom = window.use_keyed_state("input-group-align-block-end", cx, |_, cx| {
TextInput::new(cx).placeholder("Write a short bio").bare()
});
let bio_length = bottom.read(cx).text().chars().count();
let foreground = cx.theme().foreground;
div()
.w(px(360.))
.flex()
.flex_col()
.gap_4()
.child(InputGroup::new(start).leading("@"))
.child(InputGroup::new(end).trailing("USD"))
.child(
InputGroup::new(top).block_start(
div()
.font_weight(FontWeight::MEDIUM)
.text_color(foreground)
.child("Full Name"),
),
)
.child(InputGroup::new(bottom).block_end(format!("{bio_length}/280 characters")))
}Icon
Any element can be an addon, including icons drawn as paths. Addons use the muted color.
use gpui::{
canvas, div, point, prelude::*, px, rgb, App, Hsla, LineCap, LineJoin, PathBuilder, PathStyle,
StrokeOptions, Window,
};
use crate::theme::ActiveTheme;
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
pub fn input_group_icon(window: &mut Window, cx: &mut App) -> impl IntoElement {
let search = window.use_keyed_state("input-group-icon-search", cx, |_, cx| {
TextInput::new(cx).placeholder("Search...").bare()
});
let card = window.use_keyed_state("input-group-icon-card", cx, |_, cx| {
TextInput::new(cx).placeholder("Card number").bare()
});
let email = window.use_keyed_state("input-group-icon-email", cx, |_, cx| {
TextInput::new(cx).default_value("jordan@example.com").bare()
});
let muted = cx.theme().muted_foreground;
let success: Hsla = rgb(0x16a34a).into();
div()
.w(px(360.))
.flex()
.flex_col()
.gap_4()
.child(InputGroup::new(search).leading(icon(SEARCH, muted)))
.child(InputGroup::new(card).leading(icon(CREDIT_CARD, muted)))
.child(InputGroup::new(email).trailing(icon(CHECK, success)))
}
enum Stroke {
Circle(f32, f32, f32),
Line(&'static [(f32, f32)]),
}
const SEARCH: &[Stroke] = &[
Stroke::Circle(11.0, 11.0, 8.0),
Stroke::Line(&[(21.0, 21.0), (16.65, 16.65)]),
];
const CREDIT_CARD: &[Stroke] = &[
Stroke::Line(&[(2.0, 5.0), (22.0, 5.0), (22.0, 19.0), (2.0, 19.0), (2.0, 5.0)]),
Stroke::Line(&[(2.0, 10.0), (22.0, 10.0)]),
];
const CHECK: &[Stroke] = &[Stroke::Line(&[(20.0, 6.0), (9.0, 17.0), (4.0, 12.0)])];
/// A 16px Lucide icon, drawn from its strokes on the 24x24 grid.
fn icon(strokes: &'static [Stroke], color: Hsla) -> impl IntoElement {
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let unit = bounds.size.width / 24.0;
let at = |x: f32, y: f32| point(bounds.origin.x + unit * x, bounds.origin.y + unit * y);
let mut path = PathBuilder::stroke(unit * 2.0).with_style(PathStyle::Stroke(StrokeOptions {
line_width: (unit * 2.0).as_f32(),
line_cap: LineCap::Round,
line_join: LineJoin::Round,
..Default::default()
}));
for stroke in strokes {
match *stroke {
Stroke::Circle(x, y, r) => {
let radii = point(unit * r, unit * r);
path.move_to(at(x - r, y));
path.arc_to(radii, px(0.0), false, true, at(x + r, y));
path.arc_to(radii, px(0.0), false, true, at(x - r, y));
path.close();
}
Stroke::Line(points) => {
path.move_to(at(points[0].0, points[0].1));
for &(x, y) in &points[1..] {
path.line_to(at(x, y));
}
}
}
}
if let Ok(path) = path.build() {
window.paint_path(path, color);
}
},
)
.size_4()
.flex_none()
}Text
Text addons for currency symbols, units, URL parts and email domains. A block_end row makes room for a live character count.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
use crate::ui::textarea::Textarea;
const MAX_CHARS: usize = 120;
pub fn input_group_text(window: &mut Window, cx: &mut App) -> impl IntoElement {
let price = window.use_keyed_state("input-group-text-price", cx, |_, cx| {
TextInput::new(cx).placeholder("0.00").bare()
});
let url = window.use_keyed_state("input-group-text-url", cx, |_, cx| {
TextInput::new(cx).placeholder("example").bare()
});
let user = window.use_keyed_state("input-group-text-user", cx, |_, cx| {
TextInput::new(cx).placeholder("username").bare()
});
let message = window.use_keyed_state("input-group-text-message", cx, |_, cx| {
Textarea::new(cx).placeholder("Enter your message").bare()
});
let left = MAX_CHARS.saturating_sub(message.read(cx).text().chars().count());
div()
.w(px(360.))
.flex()
.flex_col()
.gap_4()
.child(InputGroup::new(price).leading("$").trailing("USD"))
.child(InputGroup::new(url).leading("https://").trailing(".com"))
.child(InputGroup::new(user).trailing("@company.com"))
.child(InputGroup::new(message).block_end(format!("{left} characters left")))
}Button
A small ghost or secondary Button fits inside the group as an addon, for actions such as copying the value or running a search.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
pub fn input_group_button(window: &mut Window, cx: &mut App) -> impl IntoElement {
let url = window.use_keyed_state("input-group-button-url", cx, |_, cx| {
TextInput::new(cx).default_value("hyuskui.com/docs").bare()
});
let search = window.use_keyed_state("input-group-button-search", cx, |_, cx| {
TextInput::new(cx).placeholder("Type to search...").bare()
});
let copied = window.use_keyed_state("input-group-button-copied", cx, |_, _| false);
let label = if *copied.read(cx) { "Copied" } else { "Copy" };
let value = url.read(cx).text();
div()
.w(px(360.))
.flex()
.flex_col()
.gap_4()
.child(
InputGroup::new(url).leading("https://").trailing(
Button::new("input-group-button-copy", label)
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.on_click(move |_, _, cx| {
cx.write_to_clipboard(gpui::ClipboardItem::new_string(format!(
"https://{value}"
)));
copied.update(cx, |copied, cx| {
*copied = true;
cx.notify();
});
}),
),
)
.child(
InputGroup::new(search).trailing(
Button::new("input-group-button-search-go", "Search")
.variant(ButtonVariant::Secondary)
.size(ButtonSize::Sm),
),
)
}Kbd
Show a keyboard shortcut hint at the end of a search field with Kbd.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
use crate::ui::kbd::Kbd;
pub fn input_group_kbd(window: &mut Window, cx: &mut App) -> impl IntoElement {
let search = window.use_keyed_state("input-group-kbd-search", cx, |_, cx| {
TextInput::new(cx).placeholder("Search...").bare()
});
div()
.w(px(360.))
.child(InputGroup::new(search).trailing(Kbd::new("⌘K")))
}Dropdown
A DropdownMenu with a ghost button trigger works as an addon, here to pick where to search.
use gpui::{div, prelude::*, px, Context, Entity, SharedString, Window};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
use crate::ui::popover::Align;
const SCOPES: [&str; 3] = ["Documentation", "Blog Posts", "Changelog"];
#[derive(Default)]
pub struct InputGroupDropdown {
query: Option<Entity<TextInput>>,
scope: Option<SharedString>,
open: bool,
}
impl Render for InputGroupDropdown {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// The input needs a context to create, so it is made on first render and kept.
let query = self
.query
.get_or_insert_with(|| cx.new(|cx| TextInput::new(cx).placeholder("Enter search query").bare()))
.clone();
let trigger = self.scope.clone().unwrap_or_else(|| "Search In...".into());
let mut menu = DropdownMenu::new("input-group-dropdown-menu", self.open)
.align(Align::End)
.trigger(
Button::new("input-group-dropdown-trigger", trigger)
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}));
for scope in SCOPES {
let view = cx.entity();
menu = menu.item(MenuItem::new(scope).on_select(move |_, _, cx| {
view.update(cx, |this, cx| {
this.scope = Some(scope.into());
cx.notify();
});
}));
}
// Tall enough for the menu to open downward inside the preview.
div()
.w(px(360.))
.h(px(200.))
.child(InputGroup::new(query).trailing(menu))
}
}Spinner
A Spinner addon shows work in progress, such as saving or checking availability.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
use crate::ui::spinner::{Spinner, SpinnerSize};
pub fn input_group_spinner(window: &mut Window, cx: &mut App) -> impl IntoElement {
let search = window.use_keyed_state("input-group-spinner-search", cx, |_, cx| {
TextInput::new(cx).placeholder("Searching...").bare()
});
let saving = window.use_keyed_state("input-group-spinner-saving", cx, |_, cx| {
TextInput::new(cx).default_value("Untitled document").bare()
});
div()
.w(px(360.))
.flex()
.flex_col()
.gap_4()
.child(InputGroup::new(search).trailing(Spinner::new().size(SpinnerSize::Sm)))
.child(
InputGroup::new(saving)
.trailing(Spinner::new().size(SpinnerSize::Sm))
.trailing("Saving..."),
)
}Textarea
A bare Textarea in a group with a header and a footer, like a small code editor. The group grows with the text.
use gpui::{div, prelude::*, px, App, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize};
use crate::ui::input_group::InputGroup;
use crate::ui::textarea::Textarea;
pub fn input_group_textarea(window: &mut Window, cx: &mut App) -> impl IntoElement {
let code = window.use_keyed_state("input-group-textarea-code", cx, |_, cx| {
Textarea::new(cx)
.placeholder("console.log('Hello, world!');")
.bare()
});
let text = code.read(cx).text();
let line = text.lines().count().max(1) + usize::from(text.ends_with('\n'));
let column = text.rsplit('\n').next().map_or(0, |last| last.chars().count()) + 1;
let foreground = cx.theme().foreground;
div().w(px(420.)).child(
InputGroup::new(code)
.block_start(
div()
.font_weight(FontWeight::MEDIUM)
.text_color(foreground)
.child("script.js"),
)
.block_end(format!("Line {line}, Column {column}"))
.block_end(Button::new("input-group-textarea-run", "Run").size(ButtonSize::Sm)),
)
}API Reference
InputGroup
A text input with addons (prefix text, a unit, a shortcut hint, a button) inside one border. Create the input with .bare() so the group draws the border and focus ring around everything: InputGroup::new(cx.new(|cx| TextInput::new(cx).bare())).leading("https://").
InputGroup::new(input: Entity<TextInput>) -> Self.leading(addon: impl IntoElement)Placed before the text, in muted color.
.trailing(addon: impl IntoElement)Placed after the text, in muted color.
.block_start(addon: impl IntoElement)A full-width row above the input, such as a file name or a label with actions. With a block addon the group grows to fit, so it suits a multi-line input like a Textarea.
.block_end(addon: impl IntoElement)A full-width row below the input, such as a character count or a submit button.