Something went wrong. Try again.
A simple TUI Library written in Rust
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915use crate::block::Block;use crate::color::Color;use crate::component::{Component, Update};use crate::input::Key;use crate::style::{Line, Span, Style};
// --- InputMask ---
/// How the input value is displayed.#[derive(Clone)]pub enum InputMask { Plain, Password, Custom(fn(&str) -> String),}
impl std::fmt::Debug for InputMask { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { InputMask::Plain => write!(f, "Plain"), InputMask::Password => write!(f, "Password"), InputMask::Custom(_) => write!(f, "Custom(...)"), } }}
// --- TextInputStyle ---
/// Visual styling for the text input.#[derive(Debug, Clone)]pub struct TextInputStyle { pub normal: Style, pub focused: Style, pub error: Style, pub placeholder_style: Style, pub cursor_char: String,}
impl Default for TextInputStyle { fn default() -> Self { TextInputStyle { normal: Style::new(), focused: Style::new(), error: Style::new().fg(Color::Red), placeholder_style: Style::new().dim(), cursor_char: "█".into(), } }}
impl TextInputStyle { pub fn new() -> Self { Self::default() }
pub fn normal(self, s: Style) -> Self { Self { normal: s, ..self } }
pub fn focused(self, s: Style) -> Self { Self { focused: s, ..self } }
pub fn error(self, s: Style) -> Self { Self { error: s, ..self } }
pub fn placeholder_style(self, s: Style) -> Self { Self { placeholder_style: s, ..self } }
pub fn cursor_char(self, c: impl Into<String>) -> Self { Self { cursor_char: c.into(), ..self } }}
// --- TextInput ---
/// Configuration for a single-line text input.#[derive(Debug, Clone)]pub struct TextInput { initial_value: String, placeholder: String, mask: InputMask, max_length: Option<usize>, validator: Option<fn(&str) -> Result<(), String>>, style: TextInputStyle, prompt: String, display_width: usize,}
impl Default for TextInput { fn default() -> Self { Self::new() }}
impl TextInput { pub fn new() -> Self { TextInput { initial_value: String::new(), placeholder: String::new(), mask: InputMask::Plain, max_length: None, validator: None, style: TextInputStyle::default(), prompt: String::new(), display_width: 40, } }
pub fn value(self, v: impl Into<String>) -> Self { Self { initial_value: v.into(), ..self } }
pub fn placeholder(self, p: impl Into<String>) -> Self { Self { placeholder: p.into(), ..self } }
pub fn mask(self, m: InputMask) -> Self { Self { mask: m, ..self } }
pub fn max_length(self, n: usize) -> Self { Self { max_length: Some(n), ..self } }
pub fn validator(self, v: fn(&str) -> Result<(), String>) -> Self { Self { validator: Some(v), ..self } }
pub fn style(self, s: TextInputStyle) -> Self { Self { style: s, ..self } }
pub fn prompt(self, p: impl Into<String>) -> Self { Self { prompt: p.into(), ..self } }
pub fn display_width(self, w: usize) -> Self { Self { display_width: w, ..self } }}
// --- TextInputState ---
/// Internal state for the text input component.#[derive(Clone)]pub struct TextInputState { value: String, cursor: usize, scroll_offset: usize, error: Option<String>, placeholder: String, mask: InputMask, max_length: Option<usize>, validator: Option<fn(&str) -> Result<(), String>>, style: TextInputStyle, prompt: String, display_width: usize,}
impl std::fmt::Debug for TextInputState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TextInputState") .field("value", &self.value) .field("cursor", &self.cursor) .field("scroll_offset", &self.scroll_offset) .field("error", &self.error) .finish() }}
impl TextInputState { /// Get the current value. pub fn value(&self) -> &str { &self.value }
/// Get the current cursor position (character index). pub fn cursor(&self) -> usize { self.cursor }
/// Get the current validation error, if any. pub fn error(&self) -> Option<&str> { self.error.as_deref() }}
// --- Component constructor ---
/// Create a text input component./// Char inserts, Backspace/Delete remove, Left/Right/Home/End navigate,/// Ctrl+U clears, Ctrl+W deletes word. Enter validates and finishes./// Escape/CtrlC → Cancel.pub fn text_input(ti: TextInput) -> Component<TextInputState, String> { let initial_cursor = ti.initial_value.chars().count(); let state = TextInputState { value: ti.initial_value, cursor: initial_cursor, scroll_offset: 0, error: None, placeholder: ti.placeholder, mask: ti.mask, max_length: ti.max_length, validator: ti.validator, style: ti.style, prompt: ti.prompt, display_width: ti.display_width, }; Component::new(state, render_text_input, update_text_input)}
// --- String helpers ---
fn insert_char_at(s: &str, char_idx: usize, c: char) -> String { let mut chars: Vec<char> = s.chars().collect(); chars.insert(char_idx, c); chars.into_iter().collect()}
fn remove_char_at(s: &str, char_idx: usize) -> String { let mut chars: Vec<char> = s.chars().collect(); if char_idx < chars.len() { chars.remove(char_idx); } chars.into_iter().collect()}
fn delete_word_backward(s: &str, cursor: usize) -> (String, usize) { let chars: Vec<char> = s.chars().collect(); if cursor == 0 { return (s.to_string(), 0); } let mut pos = cursor; // Skip trailing whitespace while pos > 0 && chars[pos - 1].is_whitespace() { pos -= 1; } // Delete until whitespace or start while pos > 0 && !chars[pos - 1].is_whitespace() { pos -= 1; } let new_chars: String = chars[..pos].iter().chain(chars[cursor..].iter()).collect(); (new_chars, pos)}
fn apply_mask(value: &str, mask: &InputMask) -> String { match mask { InputMask::Plain => value.to_string(), InputMask::Password => "•".repeat(value.chars().count()), InputMask::Custom(f) => f(value), }}
fn adjust_text_scroll(state: &mut TextInputState) { let visible_width = state.display_width; if state.cursor < state.scroll_offset { state.scroll_offset = state.cursor; } if state.cursor >= state.scroll_offset + visible_width { state.scroll_offset = state.cursor - visible_width + 1; }}
// --- Render ---
fn render_text_input(state: &TextInputState) -> Block { let display_width = state.display_width;
let prompt_spans: Vec<Span> = if state.prompt.is_empty() { vec![] } else { vec![Span::styled( state.prompt.clone(), state.style.focused.clone(), )] };
let display_value = apply_mask(&state.value, &state.mask); let char_count = display_value.chars().count();
let input_line: Line = if char_count == 0 && !state.placeholder.is_empty() { let mut line = prompt_spans; line.push(Span::styled( state.style.cursor_char.clone(), state.style.focused.clone(), )); let placeholder_text: String = state .placeholder .chars() .take(display_width.saturating_sub(1)) .collect(); line.push(Span::styled( placeholder_text, state.style.placeholder_style.clone(), )); line } else { let visible_chars: Vec<char> = display_value.chars().skip(state.scroll_offset).collect(); let cursor_in_view = state.cursor.saturating_sub(state.scroll_offset);
let before: String = visible_chars[..cursor_in_view.min(visible_chars.len())] .iter() .collect(); let after: String = visible_chars[cursor_in_view.min(visible_chars.len())..] .iter() .take(display_width.saturating_sub(cursor_in_view)) .collect();
let active_style = if state.error.is_some() { &state.style.error } else { &state.style.focused };
let mut line = prompt_spans; if !before.is_empty() { line.push(Span::styled(before, active_style.clone())); } line.push(Span::styled( state.style.cursor_char.clone(), active_style.clone(), )); if !after.is_empty() { line.push(Span::styled(after, active_style.clone())); } line };
let mut lines = vec![input_line];
if let Some(ref err_msg) = state.error { let padding = " ".repeat(state.prompt.chars().count()); lines.push(vec![Span::styled( format!("{}{}", padding, err_msg), state.style.error.clone(), )]); }
Block::text(lines)}
// --- Update ---
fn update_text_input(state: &TextInputState, key: &Key) -> Update<TextInputState, String> { match key { Key::Char(c) => { if let Some(max) = state.max_length && state.value.chars().count() >= max { return Update::Ignore; } let new_value = insert_char_at(&state.value, state.cursor, *c); let new_cursor = state.cursor + 1; let mut new_state = TextInputState { value: new_value, cursor: new_cursor, error: None, ..state.clone() }; adjust_text_scroll(&mut new_state); Update::Continue(new_state) }
Key::Backspace => { if state.cursor == 0 { return Update::Ignore; } let new_value = remove_char_at(&state.value, state.cursor - 1); let mut new_state = TextInputState { value: new_value, cursor: state.cursor - 1, error: None, ..state.clone() }; adjust_text_scroll(&mut new_state); Update::Continue(new_state) }
Key::Delete => { let char_count = state.value.chars().count(); if state.cursor >= char_count { return Update::Ignore; } let new_value = remove_char_at(&state.value, state.cursor); Update::Continue(TextInputState { value: new_value, error: None, ..state.clone() }) }
Key::Left => { if state.cursor == 0 { return Update::Ignore; } let mut new_state = TextInputState { cursor: state.cursor - 1, ..state.clone() }; adjust_text_scroll(&mut new_state); Update::Continue(new_state) }
Key::Right => { let char_count = state.value.chars().count(); if state.cursor >= char_count { return Update::Ignore; } let mut new_state = TextInputState { cursor: state.cursor + 1, ..state.clone() }; adjust_text_scroll(&mut new_state); Update::Continue(new_state) }
Key::Home => Update::Continue(TextInputState { cursor: 0, scroll_offset: 0, ..state.clone() }),
Key::End => { let char_count = state.value.chars().count(); let mut new_state = TextInputState { cursor: char_count, ..state.clone() }; adjust_text_scroll(&mut new_state); Update::Continue(new_state) }
// Ctrl+U: clear line Key::Ctrl('u') => Update::Continue(TextInputState { value: String::new(), cursor: 0, scroll_offset: 0, error: None, ..state.clone() }),
// Ctrl+W: delete word backward Key::Ctrl('w') => { let (new_value, new_cursor) = delete_word_backward(&state.value, state.cursor); let mut new_state = TextInputState { value: new_value, cursor: new_cursor, error: None, ..state.clone() }; adjust_text_scroll(&mut new_state); Update::Continue(new_state) }
Key::Enter => { if let Some(validator) = &state.validator { match validator(&state.value) { Ok(()) => Update::Finish(state.value.clone()), Err(msg) => Update::Continue(TextInputState { error: Some(msg), ..state.clone() }), } } else { Update::Finish(state.value.clone()) } }
Key::Escape | Key::CtrlC => Update::Cancel, _ => Update::Ignore, }}
#[cfg(test)]mod tests { use super::*;
fn make_state(value: &str) -> TextInputState { let cursor = value.chars().count(); TextInputState { value: value.to_string(), cursor, scroll_offset: 0, error: None, placeholder: String::new(), mask: InputMask::Plain, max_length: None, validator: None, style: TextInputStyle::default(), prompt: String::new(), display_width: 40, } }
fn make_state_at(value: &str, cursor: usize) -> TextInputState { TextInputState { cursor, ..make_state(value) } }
// --- Char insertion ---
#[test] fn insert_char_at_end() { let state = make_state(""); if let Update::Continue(new) = update_text_input(&state, &Key::Char('a')) { assert_eq!(new.value, "a"); assert_eq!(new.cursor, 1); } else { panic!("expected Continue"); } }
#[test] fn insert_char_at_middle() { let state = make_state_at("ac", 1); if let Update::Continue(new) = update_text_input(&state, &Key::Char('b')) { assert_eq!(new.value, "abc"); assert_eq!(new.cursor, 2); } else { panic!("expected Continue"); } }
#[test] fn insert_respects_max_length() { let mut state = make_state("abc"); state.max_length = Some(3); assert!(matches!( update_text_input(&state, &Key::Char('d')), Update::Ignore )); }
#[test] fn insert_clears_error() { let mut state = make_state(""); state.error = Some("bad".into()); if let Update::Continue(new) = update_text_input(&state, &Key::Char('x')) { assert!(new.error.is_none()); } else { panic!("expected Continue"); } }
// --- Deletion ---
#[test] fn backspace_removes_before_cursor() { let state = make_state("abc"); if let Update::Continue(new) = update_text_input(&state, &Key::Backspace) { assert_eq!(new.value, "ab"); assert_eq!(new.cursor, 2); } else { panic!("expected Continue"); } }
#[test] fn backspace_at_start_ignores() { let state = make_state_at("abc", 0); assert!(matches!( update_text_input(&state, &Key::Backspace), Update::Ignore )); }
#[test] fn delete_removes_after_cursor() { let state = make_state_at("abc", 1); if let Update::Continue(new) = update_text_input(&state, &Key::Delete) { assert_eq!(new.value, "ac"); assert_eq!(new.cursor, 1); } else { panic!("expected Continue"); } }
#[test] fn delete_at_end_ignores() { let state = make_state("abc"); // cursor=3 assert!(matches!( update_text_input(&state, &Key::Delete), Update::Ignore )); }
// --- Cursor movement ---
#[test] fn left_moves_cursor() { let state = make_state_at("abc", 2); if let Update::Continue(new) = update_text_input(&state, &Key::Left) { assert_eq!(new.cursor, 1); } else { panic!("expected Continue"); } }
#[test] fn left_at_start_ignores() { let state = make_state_at("abc", 0); assert!(matches!( update_text_input(&state, &Key::Left), Update::Ignore )); }
#[test] fn right_moves_cursor() { let state = make_state_at("abc", 1); if let Update::Continue(new) = update_text_input(&state, &Key::Right) { assert_eq!(new.cursor, 2); } else { panic!("expected Continue"); } }
#[test] fn right_at_end_ignores() { let state = make_state("abc"); // cursor=3 assert!(matches!( update_text_input(&state, &Key::Right), Update::Ignore )); }
#[test] fn home_moves_to_start() { let state = make_state("abc"); // cursor=3 if let Update::Continue(new) = update_text_input(&state, &Key::Home) { assert_eq!(new.cursor, 0); assert_eq!(new.scroll_offset, 0); } else { panic!("expected Continue"); } }
#[test] fn end_moves_to_end() { let state = make_state_at("abc", 0); if let Update::Continue(new) = update_text_input(&state, &Key::End) { assert_eq!(new.cursor, 3); } else { panic!("expected Continue"); } }
// --- Editing shortcuts ---
#[test] fn ctrl_u_clears_line() { let state = make_state("hello world"); if let Update::Continue(new) = update_text_input(&state, &Key::Ctrl('u')) { assert_eq!(new.value, ""); assert_eq!(new.cursor, 0); } else { panic!("expected Continue"); } }
#[test] fn ctrl_w_deletes_word() { let state = make_state("hello world"); if let Update::Continue(new) = update_text_input(&state, &Key::Ctrl('w')) { assert_eq!(new.value, "hello "); assert_eq!(new.cursor, 6); } else { panic!("expected Continue"); } }
#[test] fn ctrl_w_skips_trailing_spaces() { let state = make_state("hello "); if let Update::Continue(new) = update_text_input(&state, &Key::Ctrl('w')) { assert_eq!(new.value, ""); assert_eq!(new.cursor, 0); } else { panic!("expected Continue"); } }
#[test] fn ctrl_w_at_start_does_nothing() { let state = make_state_at("hello", 0); if let Update::Continue(new) = update_text_input(&state, &Key::Ctrl('w')) { assert_eq!(new.value, "hello"); assert_eq!(new.cursor, 0); } else { panic!("expected Continue"); } }
// --- Enter + validation ---
#[test] fn enter_no_validator_finishes() { let state = make_state("test"); if let Update::Finish(val) = update_text_input(&state, &Key::Enter) { assert_eq!(val, "test"); } else { panic!("expected Finish"); } }
fn accept_all(_: &str) -> Result<(), String> { Ok(()) }
fn reject_empty(s: &str) -> Result<(), String> { if s.is_empty() { Err("cannot be empty".into()) } else { Ok(()) } }
#[test] fn enter_valid_finishes() { let mut state = make_state("hello"); state.validator = Some(accept_all); if let Update::Finish(val) = update_text_input(&state, &Key::Enter) { assert_eq!(val, "hello"); } else { panic!("expected Finish"); } }
#[test] fn enter_invalid_shows_error() { let mut state = make_state(""); state.validator = Some(reject_empty); if let Update::Continue(new) = update_text_input(&state, &Key::Enter) { assert_eq!(new.error, Some("cannot be empty".into())); } else { panic!("expected Continue"); } }
// --- Escape ---
#[test] fn escape_cancels() { let state = make_state("test"); assert!(matches!( update_text_input(&state, &Key::Escape), Update::Cancel )); }
#[test] fn ctrl_c_cancels() { let state = make_state("test"); assert!(matches!( update_text_input(&state, &Key::CtrlC), Update::Cancel )); }
// --- Mask ---
#[test] fn password_mask() { assert_eq!(apply_mask("secret", &InputMask::Password), "••••••"); }
#[test] fn plain_mask() { assert_eq!(apply_mask("hello", &InputMask::Plain), "hello"); }
#[test] fn custom_mask() { fn stars(s: &str) -> String { "*".repeat(s.len()) } assert_eq!(apply_mask("abc", &InputMask::Custom(stars)), "***"); }
// --- Scroll ---
#[test] fn scroll_right_on_overflow() { let mut state = make_state(""); state.display_width = 5; // Type 6 characters for c in "abcdef".chars() { if let Update::Continue(new) = update_text_input(&state, &Key::Char(c)) { state = new; } } assert_eq!(state.value, "abcdef"); assert_eq!(state.cursor, 6); assert!(state.scroll_offset > 0); }
#[test] fn scroll_resets_on_home() { let mut state = make_state("abcdefghij"); state.display_width = 5; state.scroll_offset = 5; if let Update::Continue(new) = update_text_input(&state, &Key::Home) { assert_eq!(new.scroll_offset, 0); assert_eq!(new.cursor, 0); } else { panic!("expected Continue"); } }
// --- Render ---
#[test] fn render_with_placeholder() { let mut state = make_state(""); state.placeholder = "Enter name...".into(); let block = render_text_input(&state); let lines = block.render(50); assert_eq!(lines.len(), 1); assert!(lines[0].contains("Enter name...")); }
#[test] fn render_cursor_visible() { let state = make_state_at("abc", 1); let block = render_text_input(&state); let lines = block.render(50); assert!(lines[0].contains("█")); }
#[test] fn render_error_shows_second_line() { let mut state = make_state("bad"); state.error = Some("invalid input".into()); let block = render_text_input(&state); assert_eq!(block.height(), 2); let lines = block.render(50); assert!(lines[1].contains("invalid input")); }
#[test] fn render_no_error_single_line() { let state = make_state("good"); let block = render_text_input(&state); assert_eq!(block.height(), 1); }
#[test] fn render_with_prompt() { let mut state = make_state("value"); state.prompt = "Name: ".into(); let block = render_text_input(&state); let lines = block.render(50); assert!(lines[0].contains("Name: ")); }
// --- String helper unit tests ---
#[test] fn test_insert_char_at() { assert_eq!(insert_char_at("ac", 1, 'b'), "abc"); assert_eq!(insert_char_at("", 0, 'a'), "a"); assert_eq!(insert_char_at("ab", 2, 'c'), "abc"); }
#[test] fn test_remove_char_at() { assert_eq!(remove_char_at("abc", 1), "ac"); assert_eq!(remove_char_at("abc", 0), "bc"); assert_eq!(remove_char_at("abc", 2), "ab"); }
#[test] fn test_delete_word_backward() { assert_eq!( delete_word_backward("hello world", 11), ("hello ".to_string(), 6) ); assert_eq!(delete_word_backward("hello ", 8), ("".to_string(), 0)); assert_eq!(delete_word_backward("hello", 0), ("hello".to_string(), 0)); assert_eq!( delete_word_backward("one two three", 7), ("one three".to_string(), 4) ); }}