A text field with IME composition, selection, clipboard and a blinking cursor.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::input::TextInput;
pub fn input_demo(window: &mut Window, cx: &mut App) -> impl IntoElement {
// A TextInput owns its text, selection and focus, so it lives in an Entity. In your own view,
// create it once with `cx.new(|cx| TextInput::new(cx).placeholder("Email"))` and keep the
// handle: read it with `email.read(cx).text()`, or `cx.subscribe(&email, ...)` to get
// `InputEvent::Change` / `InputEvent::Submit`. `use_keyed_state` does the same here.
let email = window.use_keyed_state("email", cx, |_, cx| TextInput::new(cx).placeholder("Email"));
let disabled = window.use_keyed_state("disabled", cx, |_, cx| {
TextInput::new(cx).placeholder("Disabled").disabled(true)
});
div()
.w(px(320.))
.flex()
.flex_col()
.gap_3()
.child(email)
.child(disabled)
}Installation
Copies src/ui/input.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.rs.src/ui/input.rs //! A text field built on GPUI's `EntityInputHandler`, so typing, IME composition (Korean, //! Japanese, Chinese), selection, clipboard and cursor movement go through the platform text //! input path, including GPUI's web IME bridge. //! //! Unlike most hyuskui components this one is stateful: the text, selection and focus live in //! an `Entity<TextInput>` that your view creates once and keeps: //! //! ```ignore //! let email = cx.new(|cx| TextInput::new(cx).placeholder("Email")); //! cx.subscribe(&email, |this, input, event: &InputEvent, cx| { /* ... */ }).detach(); //! let text = email.read(cx).text(); //! ``` use std::{ops::Range, time::Duration}; use gpui::{ div, fill, point, prelude::*, px, relative, size, AnimationExt, App, AvailableSpace, Bounds, BoxShadow, ClipboardItem, ContentMask, Context, CursorStyle, ElementId, ElementInputHandler, Entity, EntityInputHandler, EventEmitter, FocusHandle, Focusable, GlobalElementId, InspectorElementId, KeyDownEvent, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point, SharedString, SpringAnimation, SpringConfig, Style, Task, TextAlign, TextRun, UTF16Selection, UnderlineStyle, Window, WrappedLine, }; use crate::theme::ActiveTheme; const BLINK_INTERVAL: Duration = Duration::from_millis(500); const CURSOR_WIDTH: Pixels = px(1.5); /// What a password shows in place of each character. const MASK: char = '•'; /// shadcn's 150ms `transition-[color,box-shadow]` as a critically damped spring. const FOCUS_SPRING: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); #[derive(Clone, Debug, PartialEq)] pub enum InputEvent { /// The text changed: typing, paste, IME composition or `set_text`. Change(SharedString), /// Enter was pressed in a single-line input. Submit(SharedString), } pub struct TextInput { focus_handle: FocusHandle, content: SharedString, placeholder: SharedString, selected_range: Range<usize>, selection_reversed: bool, marked_range: Option<Range<usize>>, multi_line: bool, rows: usize, disabled: bool, invalid: bool, bare: bool, font_size: Option<Pixels>, password: bool, is_selecting: bool, scroll_x: Pixels, layout: Option<TextLayout>, cursor_visible: bool, blink_task: Option<Task<()>>, } impl TextInput { pub fn new(cx: &mut Context<Self>) -> Self { Self { // A tab stop, so Tab and Shift-Tab move through a form's fields. focus_handle: cx.focus_handle().tab_stop(true), content: SharedString::default(), placeholder: SharedString::default(), selected_range: 0..0, selection_reversed: false, marked_range: None, multi_line: false, rows: 1, disabled: false, invalid: false, bare: false, font_size: None, password: false, is_selecting: false, scroll_x: px(0.), layout: None, cursor_visible: true, blink_task: None, } } pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { self.placeholder = placeholder.into(); self } /// Initial text; the cursor starts at its end. pub fn default_value(mut self, text: impl Into<SharedString>) -> Self { self.content = self.sanitize(&text.into()).into(); self.selected_range = self.content.len()..self.content.len(); self } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self.focus_handle = self.focus_handle.tab_stop(!disabled); self } /// Draws the destructive border, like `aria-invalid` in shadcn/ui. pub fn invalid(mut self, invalid: bool) -> Self { self.invalid = invalid; self } /// Wraps text and accepts Enter as a newline. `rows` sets the minimum height. pub fn multi_line(mut self, rows: usize) -> Self { self.multi_line = true; self.rows = rows.max(1); self } /// Drops the border, padding and focus ring so a wrapper (like `InputGroup`) can draw them. pub fn bare(mut self) -> Self { self.bare = true; self } /// Shows each character as a dot, like `<input type="password">`, and keeps it off the /// clipboard. Single line only. /// Text larger or smaller than the default 14px, such as a big amount field. Pair with /// `bare()`: the framed field keeps its 36px height. pub fn font_size(mut self, size: Pixels) -> Self { self.font_size = Some(size); self } pub fn password(mut self) -> Self { self.password = true; self.multi_line = false; self } pub fn text(&self) -> SharedString { self.content.clone() } pub fn is_disabled(&self) -> bool { self.disabled } pub fn is_invalid(&self) -> bool { self.invalid } pub fn is_focused(&self, window: &Window) -> bool { self.focus_handle.is_focused(window) } pub fn set_text( &mut self, text: impl Into<SharedString>, window: &mut Window, cx: &mut Context<Self>, ) { self.content = self.sanitize(&text.into()).into(); self.selected_range = self.content.len()..self.content.len(); self.selection_reversed = false; self.marked_range = None; window.notify_text_input_changed(&self.focus_handle); cx.emit(InputEvent::Change(self.content.clone())); cx.notify(); } pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) { if self.disabled != disabled { self.disabled = disabled; self.focus_handle = self.focus_handle.clone().tab_stop(!disabled); cx.notify(); } } pub fn set_invalid(&mut self, invalid: bool, cx: &mut Context<Self>) { if self.invalid != invalid { self.invalid = invalid; cx.notify(); } } /// A single-line field has nowhere to show a newline, so pasted or IME-inserted line /// breaks become spaces, as in a browser `<input>`. fn sanitize(&self, text: &str) -> String { if self.multi_line { text.replace("\r\n", "\n") } else { text.replace("\r\n", " ").replace(['\n', '\r'], " ") } } fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) { // Keys pressed mid-composition belong to the IME (a Korean backspace removes a jamo, // not a syllable), so let them reach the platform untouched. if self.disabled || self.marked_range.is_some() { return; } let modifiers = event.keystroke.modifiers; let secondary = modifiers.secondary(cx); let is_mac = cx.platform_info().is_mac(); let by_word = if is_mac { modifiers.alt } else { modifiers.control }; let by_line = is_mac && modifiers.platform; let shift = modifiers.shift; let cursor = self.cursor_offset(); let handled = match event.keystroke.key.as_str() { "left" => { let target = if by_line { self.line_start(cursor) } else if by_word { self.previous_word_start(cursor) } else if !shift && !self.selected_range.is_empty() { self.selected_range.start } else { self.previous_boundary(cursor) }; self.move_or_select(target, shift, window, cx); true } "right" => { let target = if by_line { self.line_end(cursor) } else if by_word { self.next_word_end(cursor) } else if !shift && !self.selected_range.is_empty() { self.selected_range.end } else { self.next_boundary(cursor) }; self.move_or_select(target, shift, window, cx); true } "up" | "down" => { let down = event.keystroke.key == "down"; let target = if by_line { if down { self.content.len() } else { 0 } } else { self.vertical_target(cursor, down) }; self.move_or_select(target, shift, window, cx); true } "home" => { self.move_or_select(self.line_start(cursor), shift, window, cx); true } "end" => { self.move_or_select(self.line_end(cursor), shift, window, cx); true } "backspace" => { if self.selected_range.is_empty() { let target = if by_line { self.line_start(cursor) } else if by_word { self.previous_word_start(cursor) } else { self.previous_boundary(cursor) }; self.select_to(target, window, cx); } self.replace_text_in_range(None, "", window, cx); true } "delete" => { if self.selected_range.is_empty() { let target = if by_word { self.next_word_end(cursor) } else { self.next_boundary(cursor) }; self.select_to(target, window, cx); } self.replace_text_in_range(None, "", window, cx); true } "enter" => { if self.multi_line { self.replace_text_in_range(None, "\n", window, cx); } else { cx.emit(InputEvent::Submit(self.content.clone())); } true } "a" if secondary => { self.selected_range = 0..self.content.len(); self.selection_reversed = false; self.selection_changed(window, cx); true } // A password never reaches the clipboard, as in a browser's password field. "c" | "x" if secondary && self.password => true, "c" | "x" if secondary => { if !self.selected_range.is_empty() { cx.write_to_clipboard(ClipboardItem::new_string( self.content[self.selected_range.clone()].to_string(), )); if event.keystroke.key == "x" { self.replace_text_in_range(None, "", window, cx); } } true } // Native platforms read the clipboard synchronously. The web can't, so there the // key is left alone and the browser's `paste` event reaches `EntityInputHandler::paste`. "v" if secondary => match cx.read_from_clipboard().and_then(|item| item.text()) { Some(text) => { self.replace_text_in_range(None, &text, window, cx); true } None => false, }, _ => false, }; if handled { cx.stop_propagation(); } } fn on_mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) { window.focus(&self.focus_handle, cx); window.request_virtual_keyboard(); let offset = self.index_for_mouse_position(event.position); match event.click_count { 2 => { self.selected_range = self.word_range_at(offset); self.selection_reversed = false; self.selection_changed(window, cx); } count if count >= 3 => { self.selected_range = self.line_start(offset)..self.line_end(offset); self.selection_reversed = false; self.selection_changed(window, cx); } _ => { self.is_selecting = true; self.move_or_select(offset, event.modifiers.shift, window, cx); } } } fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _: &mut Context<Self>) { self.is_selecting = false; } fn on_mouse_move(&mut self, event: &MouseMoveEvent, window: &mut Window, cx: &mut Context<Self>) { if self.is_selecting { self.select_to(self.index_for_mouse_position(event.position), window, cx); } } fn move_or_select(&mut self, offset: usize, select: bool, window: &mut Window, cx: &mut Context<Self>) { if select { self.select_to(offset, window, cx); } else { self.selected_range = offset..offset; self.selection_reversed = false; self.selection_changed(window, cx); } } fn select_to(&mut self, offset: usize, window: &mut Window, cx: &mut Context<Self>) { if self.selection_reversed { self.selected_range.start = offset; } else { self.selected_range.end = offset; } if self.selected_range.end < self.selected_range.start { self.selection_reversed = !self.selection_reversed; self.selected_range = self.selected_range.end..self.selected_range.start; } self.selection_changed(window, cx); } fn selection_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) { window.notify_text_selection_changed(&self.focus_handle); self.restart_blink(cx); cx.notify(); } /// Keeps the cursor solid while the user is acting, then resumes blinking. fn restart_blink(&mut self, cx: &mut Context<Self>) { self.cursor_visible = true; self.blink_task = Some(cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(BLINK_INTERVAL).await; let alive = this.update(cx, |this, cx| { this.cursor_visible = !this.cursor_visible; cx.notify(); }); if alive.is_err() { break; } } })); } fn cursor_offset(&self) -> usize { if self.selection_reversed { self.selected_range.start } else { self.selected_range.end } } fn index_for_mouse_position(&self, position: Point<Pixels>) -> usize { match (&self.layout, self.content.is_empty()) { (Some(layout), false) => self .from_display(layout.index_for_position(position - layout.origin)) .min(self.content.len()), _ => 0, } } fn vertical_target(&self, offset: usize, down: bool) -> usize { let fallback = if down { self.content.len() } else { 0 }; let Some(layout) = self.layout.as_ref().filter(|_| !self.content.is_empty() && !self.password) else { return fallback; }; let position = layout.position_for_index(offset); let y = if down { position.y + layout.line_height * 1.5 } else { position.y - layout.line_height * 0.5 }; if y < px(0.) || y >= layout.height() { return fallback; } layout .index_for_position(point(position.x, y)) .min(self.content.len()) } /// Where `offset` into the content falls in the shaped text, which for a password is one /// dot per character. fn to_display(&self, offset: usize) -> usize { if !self.password { return offset; } self.content[..offset].chars().count() * MASK.len_utf8() } /// The content offset for an offset into the shaped text. fn from_display(&self, offset: usize) -> usize { if !self.password { return offset; } let chars = offset / MASK.len_utf8(); self.content.char_indices().nth(chars).map_or(self.content.len(), |(ix, _)| ix) } fn display_range(&self, range: &Range<usize>) -> Range<usize> { self.to_display(range.start)..self.to_display(range.end) } fn previous_boundary(&self, offset: usize) -> usize { self.content[..offset] .char_indices() .next_back() .map_or(0, |(ix, _)| ix) } fn next_boundary(&self, offset: usize) -> usize { self.content[offset..] .chars() .next() .map_or(self.content.len(), |ch| offset + ch.len_utf8()) } fn previous_word_start(&self, offset: usize) -> usize { self.content[..offset] .trim_end_matches(|ch: char| !ch.is_alphanumeric()) .trim_end_matches(char::is_alphanumeric) .len() } fn next_word_end(&self, offset: usize) -> usize { let rest = self.content[offset..] .trim_start_matches(|ch: char| !ch.is_alphanumeric()) .trim_start_matches(char::is_alphanumeric); self.content.len() - rest.len() } fn word_range_at(&self, offset: usize) -> Range<usize> { let start = self.content[..offset] .trim_end_matches(char::is_alphanumeric) .len(); let end = self.content.len() - self.content[offset..] .trim_start_matches(char::is_alphanumeric) .len(); start..end } fn line_start(&self, offset: usize) -> usize { self.content[..offset].rfind('\n').map_or(0, |ix| ix + 1) } fn line_end(&self, offset: usize) -> usize { self.content[offset..] .find('\n') .map_or(self.content.len(), |ix| offset + ix) } fn offset_from_utf16(&self, offset: usize) -> usize { let mut utf8_offset = 0; let mut utf16_count = 0; for ch in self.content.chars() { if utf16_count >= offset { break; } utf16_count += ch.len_utf16(); utf8_offset += ch.len_utf8(); } utf8_offset } fn offset_to_utf16(&self, offset: usize) -> usize { let mut utf16_offset = 0; let mut utf8_count = 0; for ch in self.content.chars() { if utf8_count >= offset { break; } utf8_count += ch.len_utf8(); utf16_offset += ch.len_utf16(); } utf16_offset } fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> { self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end) } fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> { let start = self.offset_from_utf16(range_utf16.start); start..self.offset_from_utf16(range_utf16.end).max(start) } fn splice(&mut self, range: &Range<usize>, new_text: &str) { self.content = (self.content[..range.start].to_owned() + new_text + &self.content[range.end..]).into(); } } impl EventEmitter<InputEvent> for TextInput {} impl Focusable for TextInput { fn focus_handle(&self, _: &App) -> FocusHandle { self.focus_handle.clone() } } impl EntityInputHandler for TextInput { fn text_for_range( &mut self, range_utf16: Range<usize>, actual_range: &mut Option<Range<usize>>, _window: &mut Window, _cx: &mut Context<Self>, ) -> Option<String> { let range = self.range_from_utf16(&range_utf16); actual_range.replace(self.range_to_utf16(&range)); Some(self.content[range].to_string()) } fn selected_text_range( &mut self, _ignore_disabled_input: bool, _window: &mut Window, _cx: &mut Context<Self>, ) -> Option<UTF16Selection> { Some(UTF16Selection { range: self.range_to_utf16(&self.selected_range), reversed: self.selection_reversed, }) } fn set_selected_text_range( &mut self, range_utf16: Range<usize>, window: &mut Window, cx: &mut Context<Self>, ) { self.selected_range = self.range_from_utf16(&range_utf16); self.selection_reversed = false; self.selection_changed(window, cx); } fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<usize> { Some(self.content.encode_utf16().count()) } fn marked_text_range(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Range<usize>> { self.marked_range.as_ref().map(|range| self.range_to_utf16(range)) } fn unmark_text(&mut self, window: &mut Window, cx: &mut Context<Self>) { self.marked_range = None; window.notify_text_input_changed(&self.focus_handle); cx.notify(); } fn replace_text_in_range( &mut self, range_utf16: Option<Range<usize>>, new_text: &str, window: &mut Window, cx: &mut Context<Self>, ) { if self.disabled { return; } let range = range_utf16 .as_ref() .map(|range_utf16| self.range_from_utf16(range_utf16)) .or(self.marked_range.clone()) .unwrap_or(self.selected_range.clone()); let new_text = self.sanitize(new_text); self.splice(&range, &new_text); let cursor = range.start + new_text.len(); self.selected_range = cursor..cursor; self.selection_reversed = false; self.marked_range = None; window.notify_text_input_changed(&self.focus_handle); self.restart_blink(cx); cx.emit(InputEvent::Change(self.content.clone())); cx.notify(); } fn replace_and_mark_text_in_range( &mut self, range_utf16: Option<Range<usize>>, new_text: &str, new_selected_range_utf16: Option<Range<usize>>, window: &mut Window, cx: &mut Context<Self>, ) { if self.disabled { return; } let range = range_utf16 .as_ref() .map(|range_utf16| self.range_from_utf16(range_utf16)) .or(self.marked_range.clone()) .unwrap_or(self.selected_range.clone()); let new_text = self.sanitize(new_text); self.splice(&range, &new_text); self.marked_range = (!new_text.is_empty()).then(|| range.start..range.start + new_text.len()); let insertion_start_utf16 = self.offset_to_utf16(range.start); let inserted_length_utf16 = new_text.encode_utf16().count(); self.selected_range = new_selected_range_utf16 .map(|selected| { self.range_from_utf16( &(insertion_start_utf16 + selected.start.min(inserted_length_utf16) ..insertion_start_utf16 + selected.end.min(inserted_length_utf16)), ) }) .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len()); self.selection_reversed = false; window.notify_text_input_changed(&self.focus_handle); self.restart_blink(cx); cx.emit(InputEvent::Change(self.content.clone())); cx.notify(); } fn bounds_for_range( &mut self, range_utf16: Range<usize>, _bounds: Bounds<Pixels>, _window: &mut Window, _cx: &mut Context<Self>, ) -> Option<Bounds<Pixels>> { let layout = self.layout.as_ref()?; let range = self.display_range(&self.range_from_utf16(&range_utf16)); let start = layout.position_for_index(range.start); let end = layout.position_for_index(range.end); Some(Bounds::from_corners( layout.origin + start, layout.origin + point(end.x, end.y + layout.line_height), )) } fn selection_bounds_for_range( &mut self, range_utf16: Range<usize>, _bounds: Bounds<Pixels>, _window: &mut Window, _cx: &mut Context<Self>, ) -> Vec<Bounds<Pixels>> { let range = self.display_range(&self.range_from_utf16(&range_utf16)); self.layout .as_ref() .map(|layout| layout.selection_rects(&range)) .unwrap_or_default() } fn character_index_for_point( &mut self, point: Point<Pixels>, _window: &mut Window, _cx: &mut Context<Self>, ) -> Option<usize> { let layout = self.layout.as_ref()?; let offset = self .from_display(layout.index_for_position(point - layout.origin)) .min(self.content.len()); Some(self.offset_to_utf16(offset)) } fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool { !self.disabled } } impl Render for TextInput { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let focused = self.focus_handle.is_focused(window); // The blink timer only runs while focused, so idle inputs never schedule frames. if focused && !self.disabled { if self.blink_task.is_none() { self.restart_blink(cx); } } else { self.blink_task = None; } let theme = cx.theme(); let (idle_border, focus_border) = if self.invalid { (theme.destructive, theme.destructive) } else { (theme.input, theme.ring) }; let ring = if self.invalid { theme.destructive.opacity(0.2) } else { theme.ring.opacity(0.5) }; let (radius, foreground, background) = (theme.radius, theme.foreground, theme.background); let chrome = !self.bare; div() .key_context("TextInput") .track_focus(&self.focus_handle) .w_full() .text_sm() .when_some(self.font_size, |this, size| this.text_size(size)) .text_color(foreground) .when(self.multi_line, |this| { this.when(chrome, |this| this.min_h(px(64.)).py_2()) }) .when(!self.multi_line, |this| { this.flex() .items_center() .when(chrome, |this| this.h(px(36.)).py_1()) }) .when(chrome, |this| { // GPUI shadows fill the element's whole shape, so the field needs an opaque // background for the focus ring to show only around the border. this.px_3().bg(background).rounded(radius).border_1() }) .when(self.disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!self.disabled, |this| { this.cursor(CursorStyle::IBeam) .on_key_down(cx.listener(Self::on_key_down)) .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down)) .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up)) .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up)) .on_mouse_move(cx.listener(Self::on_mouse_move)) }) .child(TextElement { input: cx.entity(), }) // The border color and focus ring ease in and out. .with_spring( "focus-ring", SpringAnimation::new(FOCUS_SPRING).to(focused && !self.disabled), move |this, phase| { if !chrome { return this; } 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, }]) }, ) } } /// The shaped text from the last paint, kept for hit-testing and IME geometry. struct TextLayout { /// One entry per hard line; each may soft-wrap into several rows. lines: Vec<WrappedLine>, line_starts: Vec<usize>, line_height: Pixels, /// Window position of the text's top-left, already shifted by `scroll_x`. origin: Point<Pixels>, scroll_x: Pixels, wrap_width: Option<Pixels>, } impl TextLayout { fn new(lines: Vec<WrappedLine>, line_height: Pixels, wrap_width: Option<Pixels>) -> Self { let mut line_starts = Vec::with_capacity(lines.len()); let mut start = 0; for line in &lines { line_starts.push(start); start += line.len() + 1; } Self { lines, line_starts, line_height, origin: point(px(0.), px(0.)), scroll_x: px(0.), wrap_width, } } fn height(&self) -> Pixels { self.lines .iter() .fold(px(0.), |height, line| height + line.size(self.line_height).height) } fn width(&self) -> Pixels { self.lines .iter() .fold(px(0.), |width, line| width.max(line.width())) } fn line_top(&self, line_ix: usize) -> Pixels { self.lines[..line_ix] .iter() .fold(px(0.), |top, line| top + line.size(self.line_height).height) } /// Relative to the text origin. fn position_for_index(&self, offset: usize) -> Point<Pixels> { let line_ix = self .line_starts .partition_point(|&start| start <= offset) .saturating_sub(1); let Some(line) = self.lines.get(line_ix) else { return point(px(0.), px(0.)); }; let local = (offset - self.line_starts[line_ix]).min(line.len()); let position = line .position_for_index(local, self.line_height) .unwrap_or(point(line.width(), px(0.))); point(position.x, position.y + self.line_top(line_ix)) } /// `position` is relative to the text origin; points past the text clamp to its edges. fn index_for_position(&self, position: Point<Pixels>) -> usize { let mut top = px(0.); for (line_ix, line) in self.lines.iter().enumerate() { let height = line.size(self.line_height).height; if position.y < top + height || line_ix + 1 == self.lines.len() { let local = point( position.x.max(px(0.)), (position.y - top).max(px(0.)).min(height - px(1.)), ); let offset = match line.closest_index_for_position(local, self.line_height) { Ok(offset) | Err(offset) => offset, }; return self.line_starts[line_ix] + offset; } top += height; } 0 } /// Window-space rectangles covering `range`, one per visual row. fn selection_rects(&self, range: &Range<usize>) -> Vec<Bounds<Pixels>> { let start = self.position_for_index(range.start); let end = self.position_for_index(range.end); let line_height = self.line_height; let right = self.wrap_width.unwrap_or_else(|| self.width()); let rect = |left: Pixels, top: Pixels, right: Pixels, bottom: Pixels| { Bounds::from_corners( self.origin + point(left, top), self.origin + point(right, bottom), ) }; if start.y == end.y { return vec![rect(start.x, start.y, end.x, end.y + line_height)]; } let mut rects = vec![rect(start.x, start.y, right, start.y + line_height)]; if end.y > start.y + line_height { rects.push(rect(px(0.), start.y + line_height, right, end.y)); } rects.push(rect(px(0.), end.y, end.x, end.y + line_height)); rects } } /// Paints the text, selection and cursor and registers the input handler with the window. struct TextElement { input: Entity<TextInput>, } struct PrepaintState { layout: Option<TextLayout>, selections: Vec<PaintQuad>, cursor: Option<PaintQuad>, } /// The text to shape (content, or the placeholder when empty) with runs that color the /// selection and underline IME-marked text, the way a native field shows composition. fn display_text_and_runs(input: &TextInput, window: &Window, cx: &App) -> (SharedString, Vec<TextRun>) { let style = window.text_style(); let theme = cx.theme(); let run = |len: usize, color| TextRun { len, font: style.font(), color, background_color: None, underline: None, strikethrough: None, }; if input.content.is_empty() { let placeholder = input.placeholder.clone(); return (placeholder.clone(), vec![run(placeholder.len(), theme.muted_foreground)]); } let text: SharedString = if input.password { MASK.to_string().repeat(input.content.chars().count()).into() } else { input.content.clone() }; let len = text.len(); let selection = if input.focus_handle.is_focused(window) { input.display_range(&input.selected_range) } else { 0..0 }; let marked = input.display_range(&input.marked_range.clone().unwrap_or(0..0)); let mut cuts = vec![0, len, selection.start, selection.end, marked.start, marked.end]; cuts.sort_unstable(); cuts.dedup(); let runs = cuts .windows(2) .map(|pair| { let start = pair[0]; let selected = selection.contains(&start); let mut text_run = run( pair[1] - start, if selected { theme.primary_foreground } else { style.color }, ); if marked.contains(&start) { text_run.underline = Some(UnderlineStyle { color: Some(style.color), thickness: px(1.), wavy: false, }); } text_run }) .collect(); (text, runs) } impl Element for TextElement { type RequestLayoutState = (); type PrepaintState = PrepaintState; fn id(&self) -> Option<ElementId> { None } fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { None } fn request_layout( &mut self, _id: Option<&GlobalElementId>, _inspector_id: Option<&InspectorElementId>, window: &mut Window, cx: &mut App, ) -> (LayoutId, Self::RequestLayoutState) { let input = self.input.read(cx); let line_height = window.line_height(); let mut style = Style::default(); style.size.width = relative(1.).into(); if !input.multi_line { style.size.height = line_height.into(); return (window.request_layout(style, [], cx), ()); } // A textarea grows with its content, so its height depends on how the text wraps at // the width layout gives it. let min_height = line_height * input.rows as f32; let (text, runs) = display_text_and_runs(input, window, cx); let font_size = window.text_style().font_size.to_pixels(window.rem_size()); let layout_id = window.request_measured_layout(style, move |known, available, window, _| { let wrap_width = known.width.or(match available.width { AvailableSpace::Definite(width) => Some(width), _ => None, }); let height = window .text_system() .shape_text(text.clone(), font_size, &runs, wrap_width, None) .map(|lines| { lines .iter() .fold(px(0.), |height, line| height + line.size(line_height).height) }) .unwrap_or(line_height); size(wrap_width.unwrap_or(px(0.)), height.max(min_height)) }); (layout_id, ()) } fn prepaint( &mut self, _id: Option<&GlobalElementId>, _inspector_id: Option<&InspectorElementId>, bounds: Bounds<Pixels>, _request_layout: &mut Self::RequestLayoutState, window: &mut Window, cx: &mut App, ) -> Self::PrepaintState { let input = self.input.read(cx); let (text, runs) = display_text_and_runs(input, window, cx); let font_size = window.text_style().font_size.to_pixels(window.rem_size()); let line_height = window.line_height(); let wrap_width = input.multi_line.then_some(bounds.size.width); let lines = window .text_system() .shape_text(text, font_size, &runs, wrap_width, None) .map(|lines| lines.into_vec()) .unwrap_or_default(); let mut layout = TextLayout::new(lines, line_height, wrap_width); let cursor = if input.content.is_empty() { 0 } else { input.to_display(input.cursor_offset()) }; let cursor_position = layout.position_for_index(cursor); // Single-line text scrolls horizontally just enough to keep the cursor in view. if !input.multi_line { let visible = bounds.size.width - CURSOR_WIDTH; let mut scroll_x = input.scroll_x; if cursor_position.x - scroll_x > visible { scroll_x = cursor_position.x - visible; } if cursor_position.x < scroll_x { scroll_x = cursor_position.x; } layout.scroll_x = scroll_x .min((layout.width() - visible).max(px(0.))) .max(px(0.)); } layout.origin = point(bounds.origin.x - layout.scroll_x, bounds.origin.y); let theme = cx.theme(); let focused = input.focus_handle.is_focused(window); let selections = if focused && !input.selected_range.is_empty() && !input.content.is_empty() { layout .selection_rects(&input.display_range(&input.selected_range)) .into_iter() .map(|rect| fill(rect, theme.primary)) .collect() } else { Vec::new() }; let cursor = (focused && input.cursor_visible && input.selected_range.is_empty()).then(|| { fill( Bounds::new(layout.origin + cursor_position, size(CURSOR_WIDTH, line_height)), theme.foreground, ) }); PrepaintState { layout: Some(layout), selections, cursor, } } fn paint( &mut self, _id: Option<&GlobalElementId>, _inspector_id: Option<&InspectorElementId>, bounds: Bounds<Pixels>, _request_layout: &mut Self::RequestLayoutState, prepaint: &mut Self::PrepaintState, window: &mut Window, cx: &mut App, ) { let focus_handle = self.input.read(cx).focus_handle.clone(); window.handle_input( &focus_handle, ElementInputHandler::new(bounds, self.input.clone()), cx, ); let Some(layout) = prepaint.layout.take() else { return; }; window.with_content_mask(Some(ContentMask { bounds }), |window| { for selection in prepaint.selections.drain(..) { window.paint_quad(selection); } let mut top = layout.origin.y; for line in &layout.lines { line.paint( point(layout.origin.x, top), layout.line_height, TextAlign::Left, None, window, cx, ) .ok(); top += line.size(layout.line_height).height; } if let Some(cursor) = prepaint.cursor.take() { window.paint_quad(cursor); } }); self.input.update(cx, |input, _| { input.scroll_x = layout.scroll_x; input.layout = Some(layout); }); } }Register the module
// src/ui/mod.rs pub mod input;
Usage
use crate::ui::input::*;Examples
Field
Wrap an input in a Field to give it a label and helper text.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn input_field(window: &mut Window, cx: &mut App) -> impl IntoElement {
let username = window.use_keyed_state("input-field-username", cx, |_, cx| {
TextInput::new(cx).placeholder("Enter your username")
});
div().w(px(360.)).child(
Field::new()
.label("Username")
.description("Choose a unique username for your account.")
.child(username),
)
}Field Group
Stack several fields with a shared set of actions. Reset clears every input with set_text.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn input_field_group(window: &mut Window, cx: &mut App) -> impl IntoElement {
let name = window.use_keyed_state("input-field-group-name", cx, |_, cx| {
TextInput::new(cx).placeholder("Jordan Lee")
});
let email = window.use_keyed_state("input-field-group-email", cx, |_, cx| {
TextInput::new(cx).placeholder("name@example.com")
});
let inputs = [name.clone(), email.clone()];
div()
.w(px(360.))
.flex()
.flex_col()
.gap_6()
.child(Field::new().label("Name").child(name))
.child(
Field::new()
.label("Email")
.description("We'll send updates to this address.")
.child(email),
)
.child(
div()
.flex()
.gap_2()
.child(
Button::new("input-field-group-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(move |_, window, cx| {
for input in &inputs {
input.update(cx, |input, cx| input.set_text("", window, cx));
}
}),
)
.child(Button::new("input-field-group-submit", "Submit")),
)
}Disabled
disabled(true) dims the input and ignores focus and typing. Pass the same flag to the Field to dim its label and description.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn input_disabled(window: &mut Window, cx: &mut App) -> impl IntoElement {
let email = window.use_keyed_state("input-disabled-email", cx, |_, cx| {
TextInput::new(cx).placeholder("Email").disabled(true)
});
div().w(px(360.)).child(
Field::new()
.label("Email")
.description("This field is currently disabled.")
.disabled(true)
.child(email),
)
}Invalid
invalid(true) draws the destructive border, like aria-invalid. Give the Field an error so the label and message match.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn input_invalid(window: &mut Window, cx: &mut App) -> impl IntoElement {
let input = window.use_keyed_state("input-invalid", cx, |_, cx| {
TextInput::new(cx).placeholder("Error").invalid(true)
});
div().w(px(360.)).child(
Field::new()
.label("Invalid Input")
.error("This field contains validation errors.")
.child(input),
)
}Inline
Put an input and a button in a row, with the input taking the remaining width.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::Button;
use crate::ui::input::TextInput;
pub fn input_inline(window: &mut Window, cx: &mut App) -> impl IntoElement {
let search = window.use_keyed_state("input-inline-search", cx, |_, cx| {
TextInput::new(cx).placeholder("Search...")
});
div()
.w(px(360.))
.flex()
.items_center()
.gap_2()
.child(div().flex_1().child(search))
.child(Button::new("input-inline-submit", "Search"))
}Grid
Two fields side by side, each growing to half the row.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn input_grid(window: &mut Window, cx: &mut App) -> impl IntoElement {
let first = window.use_keyed_state("input-grid-first", cx, |_, cx| {
TextInput::new(cx).placeholder("Jordan")
});
let last = window.use_keyed_state("input-grid-last", cx, |_, cx| {
TextInput::new(cx).placeholder("Lee")
});
div()
.w(px(420.))
.flex()
.gap_4()
.child(div().flex_1().child(Field::new().label("First Name").child(first)))
.child(div().flex_1().child(Field::new().label("Last Name").child(last)))
}Required
Field::required marks the label with an asterisk. It is display only, so check the value yourself before submitting.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn input_required(window: &mut Window, cx: &mut App) -> impl IntoElement {
let input = window.use_keyed_state("input-required", cx, |_, cx| {
TextInput::new(cx).placeholder("This field is required")
});
div().w(px(360.)).child(
Field::new()
.label("Required Field")
.required(true)
.description("This field must be filled out.")
.child(input),
)
}Badge
Build your own label row to put a Badge beside the label text.
use gpui::{div, prelude::*, px, App, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::badge::{Badge, BadgeVariant};
use crate::ui::input::TextInput;
pub fn input_badge(window: &mut Window, cx: &mut App) -> impl IntoElement {
let webhook = window.use_keyed_state("input-badge-webhook", cx, |_, cx| {
TextInput::new(cx).placeholder("https://api.example.com/webhook")
});
div()
.w(px(360.))
.flex()
.flex_col()
.gap_3()
.child(
div()
.flex()
.items_center()
.gap_2()
.text_sm()
.font_weight(FontWeight::MEDIUM)
.text_color(cx.theme().foreground)
.child("Webhook URL")
.child(Badge::new("Beta").variant(BadgeVariant::Secondary)),
)
.child(webhook)
}Input Group
For text or icons inside the border, use InputGroup with a .bare() input.
use gpui::{
canvas, div, point, prelude::*, px, App, Hsla, LineCap, LineJoin, PathBuilder, PathStyle,
StrokeOptions, Window,
};
use crate::theme::ActiveTheme;
use crate::ui::field::Field;
use crate::ui::input::TextInput;
use crate::ui::input_group::InputGroup;
pub fn input_input_group(window: &mut Window, cx: &mut App) -> impl IntoElement {
let url = window.use_keyed_state("input-input-group-url", cx, |_, cx| {
TextInput::new(cx).placeholder("example.com").bare()
});
let muted = cx.theme().muted_foreground;
div().w(px(360.)).child(
Field::new()
.label("Website URL")
.child(InputGroup::new(url).leading("https://").trailing(info_icon(muted))),
)
}
/// Lucide's `info`, drawn on its 24x24 grid.
fn info_icon(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()
}));
let radii = point(unit * 10.0, unit * 10.0);
path.move_to(at(2.0, 12.0));
path.arc_to(radii, px(0.0), false, true, at(22.0, 12.0));
path.arc_to(radii, px(0.0), false, true, at(2.0, 12.0));
path.close();
path.move_to(at(12.0, 16.0));
path.line_to(at(12.0, 12.0));
path.move_to(at(12.0, 8.0));
path.line_to(at(12.01, 8.0));
if let Ok(path) = path.build() {
window.paint_path(path, color);
}
},
)
.size_4()
.flex_none()
}Form
A complete form: fields in a grid, a multi-line address and actions at the end. Submit is enabled once every required field has a value.
use gpui::{div, prelude::*, px, App, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::field::Field;
use crate::ui::input::TextInput;
pub fn input_form(window: &mut Window, cx: &mut App) -> impl IntoElement {
let name = window.use_keyed_state("input-form-name", cx, |_, cx| {
TextInput::new(cx).placeholder("Jordan Lee")
});
let email = window.use_keyed_state("input-form-email", cx, |_, cx| {
TextInput::new(cx).placeholder("name@example.com")
});
let phone = window.use_keyed_state("input-form-phone", cx, |_, cx| {
TextInput::new(cx).placeholder("+1 (555) 123-4567")
});
let address = window.use_keyed_state("input-form-address", cx, |_, cx| {
TextInput::new(cx).placeholder("123 Main St").multi_line(2)
});
let complete = [&name, &email]
.iter()
.all(|input| !input.read(cx).text().trim().is_empty());
let inputs = [name.clone(), email.clone(), phone.clone(), address.clone()];
div()
.w(px(420.))
.flex()
.flex_col()
.gap_6()
.child(Field::new().label("Name").required(true).child(name))
.child(
div()
.flex()
.gap_4()
.child(div().flex_1().child(Field::new().label("Email").required(true).child(email)))
.child(div().flex_1().child(Field::new().label("Phone").child(phone))),
)
.child(Field::new().label("Address").child(address))
.child(
div()
.flex()
.justify_end()
.gap_2()
.child(
Button::new("input-form-cancel", "Cancel")
.variant(ButtonVariant::Outline)
.on_click(move |_, window, cx| {
for input in &inputs {
input.update(cx, |input, cx| input.set_text("", window, cx));
}
}),
)
.child(Button::new("input-form-submit", "Submit").disabled(!complete)),
)
}API Reference
InputEvent
InputEvent::ChangeThe text changed: typing, paste, IME composition or set_text.
InputEvent::SubmitEnter was pressed in a single-line input.
TextInput
TextInput::new(cx: &mut Context<Self>) -> Self.placeholder(placeholder: impl Into<SharedString>).default_value(text: impl Into<SharedString>)Initial text; the cursor starts at its end.
.disabled(disabled: bool).invalid(invalid: bool)Draws the destructive border, like aria-invalid in shadcn/ui.
.multi_line(rows: usize)Wraps text and accepts Enter as a newline. rows sets the minimum height.
.bare()Drops the border, padding and focus ring so a wrapper (like InputGroup) can draw them.
.font_size(size: Pixels)Shows each character as a dot, like <input type="password">, and keeps it off the clipboard. Single line only. Text larger or smaller than the default 14px, such as a big amount field. Pair with bare(): the framed field keeps its 36px height.
.password().text() -> SharedString.is_disabled() -> bool.is_invalid() -> bool.is_focused(window: &Window) -> bool.set_text(text: impl Into<SharedString>, window: &mut Window, cx: &mut Context<Self>).set_disabled(disabled: bool, cx: &mut Context<Self>).set_invalid(invalid: bool, cx: &mut Context<Self>)