//! Editable text input widget. //! //! [`TextInput`] owns the edited text and caret, exposing granular editing and navigation //! operations plus a [`TextInput::input`] helper that maps a [`Key`](rustik_tui_core::Key) to the //! matching operation. [`TextField`] renders that state into an area, scrolling to keep the caret //! visible and recording the caret's screen position so the caller can place the terminal cursor. //! //! Columns are measured in characters, so caret placement assumes single-width glyphs; wide //! characters shift the rendered caret by one cell each. use rustik_tui_core as tui_core; use tui_core::{Buffer, Constraint, Key, Point, Rect, RenderResult, Size, StatefulWidget, Style}; /// Editable text buffer with a caret and viewport offsets. #[derive(Clone, Debug)] pub struct TextInput { /// Edited text, with `\n` separating logical lines. value: String, /// Caret position as a byte offset into [`TextInput::value`]. cursor: usize, /// First visible logical line, maintained while rendering. scroll: usize, /// First visible column, maintained while rendering. hscroll: usize, /// Caret screen position recorded by the last render. caret: Point, } impl Default for TextInput { fn default() -> Self { Self { value: String::new(), cursor: 0, scroll: 0, hscroll: 0, caret: Point::new(0, 0), } } } impl TextInput { /// Creates an empty input with the caret at the start. pub fn new() -> Self { Self::default() } /// Creates an input initialized with `value`. pub fn with_value(value: String) -> Self { let cursor = value.len(); Self { value, cursor, scroll: 0, hscroll: 0, caret: Point::new(0, 0), } } /// Returns the edited text. pub fn value(&self) -> &str { &self.value } /// Returns whether the input has no non-whitespace content. pub fn is_empty(&self) -> bool { self.value.trim().is_empty() } /// Returns the caret screen position recorded by the last render. pub fn caret(&self) -> Point { self.caret } /// Applies the edit or navigation bound to `key`. /// /// Returns whether the buffer or caret changed. `Enter`, `Tab`, and other /// keys are left to the caller so it can decide submit, focus, and newline /// semantics for its own mode. pub fn input(&mut self, key: Key) -> bool { match key { Key::Char(ch) => self.insert(ch), Key::Backspace => self.backspace(), Key::Delete => self.delete(), Key::Left => self.move_left(), Key::Right => self.move_right(), Key::Up => self.move_up(), Key::Down => self.move_down(), Key::Home => self.move_home(), Key::End => self.move_end(), _ => false, } } /// Inserts `ch` at the caret. /// /// The caret is stored as a byte offset, so movement after insertion uses /// the UTF-8 width of the inserted character. pub fn insert(&mut self, ch: char) -> bool { self.value.insert(self.cursor, ch); self.cursor += ch.len_utf8(); true } /// Inserts a line break at the caret. pub fn newline(&mut self) -> bool { self.insert('\n') } /// Deletes the character before the caret. pub fn backspace(&mut self) -> bool { let Some(ch) = self.value[..self.cursor].chars().next_back() else { return false; }; let start = self.cursor - ch.len_utf8(); self.value.remove(start); self.cursor = start; true } /// Deletes the character at the caret. pub fn delete(&mut self) -> bool { if self.cursor >= self.value.len() { return false; } self.value.remove(self.cursor); true } /// Moves the caret one character left. pub fn move_left(&mut self) -> bool { let Some(ch) = self.value[..self.cursor].chars().next_back() else { return false; }; self.cursor -= ch.len_utf8(); true } /// Moves the caret one character right. pub fn move_right(&mut self) -> bool { let Some(ch) = self.value[self.cursor..].chars().next() else { return false; }; self.cursor += ch.len_utf8(); true } /// Moves the caret to the start of the current line. pub fn move_home(&mut self) -> bool { let start = self.value[..self.cursor].rfind('\n').map_or(0, |i| i + 1); if start == self.cursor { return false; } self.cursor = start; true } /// Moves the caret to the end of the current line. pub fn move_end(&mut self) -> bool { let end = self.value[self.cursor..] .find('\n') .map_or(self.value.len(), |i| self.cursor + i); if end == self.cursor { return false; } self.cursor = end; true } /// Moves the caret up one line, keeping the column where possible. /// /// Columns are counted in `char`s and then translated back to a byte offset /// on the target line. Moving to a shorter line clamps at that line's end. pub fn move_up(&mut self) -> bool { let (row, col) = self.row_col(); if row == 0 { return false; } self.cursor = self.offset_at(row - 1, col); true } /// Moves the caret down one line, keeping the column where possible. /// /// Columns are counted in `char`s and then translated back to a byte offset /// on the target line. Moving to a shorter line clamps at that line's end. pub fn move_down(&mut self) -> bool { let (row, col) = self.row_col(); if row + 1 >= self.lines().count() { return false; } self.cursor = self.offset_at(row + 1, col); true } /// Returns the logical lines split on `\n`. fn lines(&self) -> impl Iterator { self.value.split('\n') } /// Returns the byte range of each logical line, excluding separators. fn line_ranges(&self) -> Vec<(usize, usize)> { let mut ranges = Vec::new(); let mut start = 0; for (i, byte) in self.value.bytes().enumerate() { if byte == b'\n' { ranges.push((start, i)); start = i + 1; } } ranges.push((start, self.value.len())); ranges } /// Returns the caret's `(row, column)` in characters. fn row_col(&self) -> (usize, usize) { let before = &self.value[..self.cursor]; let row = before.matches('\n').count(); let col = before .rsplit('\n') .next() .map_or(0, |line| line.chars().count()); (row, col) } /// Returns the byte offset of `column` on `row`, clamped to the line end. /// /// `column` is a character column, not a byte index. This keeps the stored /// cursor on a UTF-8 boundary even when the edited text contains non-ASCII /// characters. fn offset_at(&self, row: usize, column: usize) -> usize { let ranges = self.line_ranges(); let Some(&(start, end)) = ranges.get(row) else { return self.value.len(); }; let line = &self.value[start..end]; let offset = line .char_indices() .nth(column) .map_or(end - start, |(i, _)| i); start + offset } } /// Renders a [`TextInput`] into an area with a visible caret. #[derive(Clone, Debug)] pub struct TextField { /// Style applied to the edited text. style: Style, /// Placeholder shown when the input is empty. placeholder: Option, /// Style applied to the placeholder text. placeholder_style: Style, } impl TextField { /// Creates a text field with default styling and no placeholder. pub fn new() -> Self { Self { style: Style::default(), placeholder: None, placeholder_style: Style::default().dim(), } } /// Sets the text style. pub fn style(mut self, style: Style) -> Self { self.style = style; self } /// Sets the placeholder shown while the input is empty. pub fn placeholder(mut self, placeholder: impl Into) -> Self { self.placeholder = Some(placeholder.into()); self } /// Sets the placeholder style. pub fn placeholder_style(mut self, style: Style) -> Self { self.placeholder_style = style; self } } impl Default for TextField { fn default() -> Self { Self::new() } } impl StatefulWidget for TextField { type State = TextInput; fn size(&self, parent: Constraint) -> Size { parent.bounded_size() } fn render_with_state( &mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State, ) -> RenderResult { if area.is_empty() { return RenderResult::default(); } if state.value.is_empty() { if let Some(placeholder) = &self.placeholder { let text: String = placeholder.chars().take(area.cols).collect(); buf.set_str(area.x, area.y, &text, self.placeholder_style); } state.scroll = 0; state.hscroll = 0; state.caret = Point::new(area.x, area.y); return RenderResult { cursor: Some(state.caret()), }; } let (row, col) = state.row_col(); if row < state.scroll { state.scroll = row; } else if row >= state.scroll + area.rows { state.scroll = row + 1 - area.rows; } if col < state.hscroll { state.hscroll = col; } else if col >= state.hscroll + area.cols { state.hscroll = col + 1 - area.cols; } let ranges = state.line_ranges(); for screen_row in 0..area.rows { let Some(&(start, end)) = ranges.get(state.scroll + screen_row) else { break; }; // Horizontal scrolling is also character-based to match caret // movement. Wide glyphs are documented as an approximation. let text: String = state.value[start..end] .chars() .skip(state.hscroll) .take(area.cols) .collect(); buf.set_str(area.x, area.y + screen_row, &text, self.style); } state.caret = Point::new( area.x + col.saturating_sub(state.hscroll), area.y + row.saturating_sub(state.scroll), ); RenderResult { cursor: Some(state.caret()), } } } #[cfg(test)] mod tests { use super::*; use tui_core::Buffer; #[test] fn typing_and_backspace_track_the_caret() { let mut input = TextInput::new(); for ch in "abc".chars() { input.insert(ch); } assert_eq!(input.value(), "abc"); assert!(input.backspace()); assert_eq!(input.value(), "ab"); assert!(input.move_left()); assert!(input.insert('X')); assert_eq!(input.value(), "aXb"); } #[test] fn vertical_navigation_keeps_column() { let mut input = TextInput::new(); for ch in "ab\ncd\nefgh".chars() { input.input(Key::Char(ch)); } input.move_home(); for _ in 0..2 { input.move_right(); } // Caret is at column 2 on the last line; move up twice to the first. assert!(input.move_up()); assert!(input.move_up()); assert_eq!(input.row_col(), (0, 2)); } #[test] fn move_up_clamps_to_shorter_line() { let mut input = TextInput::new(); for ch in "ab\nlonger".chars() { input.insert(ch); } input.move_end(); assert!(input.move_up()); assert_eq!(input.row_col(), (0, 2)); } #[test] fn render_places_caret_and_scrolls_to_keep_it_visible() { let mut field = TextField::new(); let mut input = TextInput::new(); for ch in "one\ntwo\nthree".chars() { input.insert(ch); } let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 2)); field.render_with_state(buffer.area(), &mut buffer, &mut input); // The caret is on the third line; a two-row area scrolls to show it. assert_eq!(buffer.lines(), vec!["two ", "three "]); assert_eq!(input.caret(), Point::new(5, 1)); } #[test] fn with_value_places_caret_after_initial_text() { let mut input = TextInput::with_value("abc".to_owned()); let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 1)); TextField::new().render_with_state(buffer.area(), &mut buffer, &mut input); assert_eq!(input.value(), "abc"); assert_eq!(input.caret(), Point::new(3, 0)); } #[test] fn empty_input_renders_placeholder() { let mut field = TextField::new().placeholder("type here"); let mut input = TextInput::new(); let mut buffer = Buffer::empty(Rect::new(0, 0, 9, 1)); field.render_with_state(buffer.area(), &mut buffer, &mut input); assert_eq!(buffer.lines(), vec!["type here"]); } }