Something went wrong. Try again.
A simple TUI Library written in Rust
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570use crate::block::Block;use crate::color::Color;use crate::component::{Component, Update};use crate::input::Key;use crate::style::{Span, Style};use crate::widgets::text_input::TextInputStyle;
// --- NumberInput ---
/// Configuration for a numeric input widget.#[derive(Debug, Clone)]pub struct NumberInput { value: f64, min: Option<f64>, max: Option<f64>, step: f64, decimal_places: usize, prompt: String, style: TextInputStyle,}
impl NumberInput { pub fn new(value: f64) -> Self { NumberInput { value, min: None, max: None, step: 1.0, decimal_places: 0, prompt: String::new(), style: TextInputStyle::default(), } }
pub fn min(self, n: f64) -> Self { Self { min: Some(n), ..self } }
pub fn max(self, n: f64) -> Self { Self { max: Some(n), ..self } }
pub fn step(self, s: f64) -> Self { Self { step: s, ..self } }
pub fn decimal_places(self, d: usize) -> Self { Self { decimal_places: d, ..self } }
/// Convenience: integer mode (decimal_places = 0, step = 1). pub fn integer(self) -> Self { Self { decimal_places: 0, step: 1.0, ..self } }
pub fn prompt(self, p: impl Into<String>) -> Self { Self { prompt: p.into(), ..self } }
pub fn style(self, s: TextInputStyle) -> Self { Self { style: s, ..self } }}
// --- NumberInputState ---
#[derive(Clone)]pub struct NumberInputState { /// The text buffer the user is editing. text: String, cursor: usize, error: Option<String>, min: Option<f64>, max: Option<f64>, step: f64, decimal_places: usize, prompt: String, style: TextInputStyle,}
impl std::fmt::Debug for NumberInputState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("NumberInputState") .field("text", &self.text) .field("cursor", &self.cursor) .field("error", &self.error) .finish() }}
impl NumberInputState { /// Parse the current text buffer as f64. Returns None if invalid. pub fn parsed_value(&self) -> Option<f64> { self.text.parse::<f64>().ok() }
fn format_value(v: f64, decimal_places: usize) -> String { if decimal_places == 0 { format!("{}", v as i64) } else { format!("{:.prec$}", v, prec = decimal_places) } }
fn clamp(&self, v: f64) -> f64 { let v = if let Some(min) = self.min { v.max(min) } else { v }; if let Some(max) = self.max { v.min(max) } else { v } }
fn validate_text(&self) -> Result<f64, String> { let v = self .text .parse::<f64>() .map_err(|_| format!("'{}' is not a valid number", self.text))?; if let Some(min) = self.min && v < min { return Err(format!( "minimum is {}", Self::format_value(min, self.decimal_places) )); } if let Some(max) = self.max && v > max { return Err(format!( "maximum is {}", Self::format_value(max, self.decimal_places) )); } Ok(v) }}
// --- Component constructor ---
/// Create a numeric input component.////// - Digit, `-`, `.` chars type into the buffer./// - `Up` increments by `step`; `Down` decrements./// - `Backspace` / `Delete` / `Left` / `Right` / `Home` / `End` edit the buffer./// - `Enter` validates range and finishes with the parsed value./// - `Escape` / `Ctrl+C` → Cancel.pub fn number_input(ni: NumberInput) -> Component<NumberInputState, f64> { let text = NumberInputState::format_value(ni.value, ni.decimal_places); let cursor = text.chars().count(); let state = NumberInputState { text, cursor, error: None, min: ni.min, max: ni.max, step: ni.step, decimal_places: ni.decimal_places, prompt: ni.prompt, style: ni.style, }; Component::new(state, render_number_input, update_number_input)}
// --- Render ---
fn render_number_input(state: &NumberInputState) -> Block { let prompt_part = if state.prompt.is_empty() { String::new() } else { state.prompt.clone() };
let text_chars: Vec<char> = state.text.chars().collect(); let cursor = state.cursor.min(text_chars.len()); let before: String = text_chars[..cursor].iter().collect(); let after: String = text_chars[cursor..].iter().collect();
let active_style = if state.error.is_some() { state.style.error.clone() } else { state.style.focused.clone() };
let mut line = Vec::new(); if !prompt_part.is_empty() { line.push(Span::styled( prompt_part.clone(), state.style.focused.clone(), )); } 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())); }
let mut lines = vec![line]; if let Some(ref err) = state.error { let pad = " ".repeat(prompt_part.chars().count()); lines.push(vec![Span::styled( format!("{}{}", pad, err), Style::new().fg(Color::Red), )]); }
Block::text(lines)}
// --- Update ---
fn update_number_input(state: &NumberInputState, key: &Key) -> Update<NumberInputState, f64> { match key { // Up: increment by step Key::Up => { let current = state.parsed_value().unwrap_or(0.0); let new_val = state.clamp(current + state.step); let new_text = NumberInputState::format_value(new_val, state.decimal_places); let new_cursor = new_text.chars().count(); Update::Continue(NumberInputState { text: new_text, cursor: new_cursor, error: None, ..state.clone() }) }
// Down: decrement by step Key::Down => { let current = state.parsed_value().unwrap_or(0.0); let new_val = state.clamp(current - state.step); let new_text = NumberInputState::format_value(new_val, state.decimal_places); let new_cursor = new_text.chars().count(); Update::Continue(NumberInputState { text: new_text, cursor: new_cursor, error: None, ..state.clone() }) }
// Allow digits, minus sign at start, and decimal point Key::Char(c) => { let is_allowed = c.is_ascii_digit() || (*c == '-' && state.cursor == 0 && !state.text.contains('-')) || (*c == '.' && state.decimal_places > 0 && !state.text.contains('.'));
if !is_allowed { return Update::Ignore; }
let chars: Vec<char> = state.text.chars().collect(); let mut new_chars = chars[..state.cursor].to_vec(); new_chars.push(*c); new_chars.extend_from_slice(&chars[state.cursor..]); let new_text: String = new_chars.into_iter().collect(); Update::Continue(NumberInputState { text: new_text, cursor: state.cursor + 1, error: None, ..state.clone() }) }
Key::Backspace => { if state.cursor == 0 { return Update::Ignore; } let chars: Vec<char> = state.text.chars().collect(); let mut new_chars = chars[..state.cursor - 1].to_vec(); new_chars.extend_from_slice(&chars[state.cursor..]); Update::Continue(NumberInputState { text: new_chars.into_iter().collect(), cursor: state.cursor - 1, error: None, ..state.clone() }) }
Key::Delete => { let char_count = state.text.chars().count(); if state.cursor >= char_count { return Update::Ignore; } let chars: Vec<char> = state.text.chars().collect(); let mut new_chars = chars[..state.cursor].to_vec(); new_chars.extend_from_slice(&chars[state.cursor + 1..]); Update::Continue(NumberInputState { text: new_chars.into_iter().collect(), error: None, ..state.clone() }) }
Key::Left => { if state.cursor == 0 { return Update::Ignore; } Update::Continue(NumberInputState { cursor: state.cursor - 1, ..state.clone() }) }
Key::Right => { if state.cursor >= state.text.chars().count() { return Update::Ignore; } Update::Continue(NumberInputState { cursor: state.cursor + 1, ..state.clone() }) }
Key::Home => Update::Continue(NumberInputState { cursor: 0, ..state.clone() }),
Key::End => { let end = state.text.chars().count(); Update::Continue(NumberInputState { cursor: end, ..state.clone() }) }
Key::Enter => match state.validate_text() { Ok(v) => Update::Finish(v), Err(msg) => Update::Continue(NumberInputState { error: Some(msg), ..state.clone() }), },
Key::Escape | Key::CtrlC => Update::Cancel,
_ => Update::Ignore, }}
#[cfg(test)]mod tests { use super::*;
fn make_state(text: &str) -> NumberInputState { let cursor = text.chars().count(); NumberInputState { text: text.to_string(), cursor, error: None, min: None, max: None, step: 1.0, decimal_places: 0, prompt: String::new(), style: TextInputStyle::default(), } }
fn make_state_at(text: &str, cursor: usize) -> NumberInputState { NumberInputState { cursor, ..make_state(text) } }
// --- Increment / Decrement ---
#[test] fn up_increments_by_step() { let state = make_state("5"); if let Update::Continue(new) = update_number_input(&state, &Key::Up) { assert_eq!(new.text, "6"); } else { panic!("expected Continue"); } }
#[test] fn down_decrements_by_step() { let state = make_state("5"); if let Update::Continue(new) = update_number_input(&state, &Key::Down) { assert_eq!(new.text, "4"); } else { panic!("expected Continue"); } }
#[test] fn up_clamps_to_max() { let mut state = make_state("9"); state.max = Some(10.0); if let Update::Continue(new) = update_number_input(&state, &Key::Up) { assert_eq!(new.text, "10"); } else { panic!("expected Continue"); } // One more up should stay at 10 let state2 = make_state("10"); let mut state2 = state2; state2.max = Some(10.0); if let Update::Continue(new2) = update_number_input(&state2, &Key::Up) { assert_eq!(new2.text, "10"); } else { panic!("expected Continue"); } }
#[test] fn down_clamps_to_min() { let mut state = make_state("1"); state.min = Some(0.0); if let Update::Continue(new) = update_number_input(&state, &Key::Down) { assert_eq!(new.text, "0"); } else { panic!("expected Continue"); } }
// --- Char input ---
#[test] fn digit_inserts() { let state = make_state("12"); if let Update::Continue(new) = update_number_input(&state, &Key::Char('3')) { assert_eq!(new.text, "123"); } else { panic!("expected Continue"); } }
#[test] fn letter_ignored() { let state = make_state("12"); assert!(matches!( update_number_input(&state, &Key::Char('x')), Update::Ignore )); }
#[test] fn minus_allowed_at_start() { let state = make_state_at("5", 0); if let Update::Continue(new) = update_number_input(&state, &Key::Char('-')) { assert_eq!(new.text, "-5"); } else { panic!("expected Continue"); } }
#[test] fn minus_not_allowed_mid_string() { let state = make_state("5"); assert!(matches!( update_number_input(&state, &Key::Char('-')), Update::Ignore )); }
#[test] fn decimal_allowed_when_decimal_places_gt_0() { let mut state = make_state("3"); state.decimal_places = 2; if let Update::Continue(new) = update_number_input(&state, &Key::Char('.')) { assert_eq!(new.text, "3."); } else { panic!("expected Continue"); } }
#[test] fn decimal_blocked_in_integer_mode() { let state = make_state("3"); // decimal_places = 0 assert!(matches!( update_number_input(&state, &Key::Char('.')), Update::Ignore )); }
// --- Enter validation ---
#[test] fn enter_valid_finishes() { let state = make_state("42"); if let Update::Finish(v) = update_number_input(&state, &Key::Enter) { assert!((v - 42.0).abs() < 1e-9); } else { panic!("expected Finish"); } }
#[test] fn enter_invalid_shows_error() { let state = make_state("abc"); if let Update::Continue(new) = update_number_input(&state, &Key::Enter) { assert!(new.error.is_some()); } else { panic!("expected Continue with error"); } }
#[test] fn enter_out_of_range_shows_error() { let mut state = make_state("100"); state.max = Some(50.0); if let Update::Continue(new) = update_number_input(&state, &Key::Enter) { assert!(new.error.is_some()); } else { panic!("expected Continue with error"); } }
// --- Render ---
#[test] fn render_shows_cursor() { let state = make_state("42"); let block = render_number_input(&state); let lines = block.render(20); assert!(lines[0].contains("█")); }
#[test] fn render_error_shows_second_line() { let mut state = make_state("bad"); state.error = Some("not a number".into()); let block = render_number_input(&state); assert_eq!(block.height(), 2); }
// --- Format ---
#[test] fn format_integer() { assert_eq!(NumberInputState::format_value(42.0, 0), "42"); assert_eq!(NumberInputState::format_value(-7.0, 0), "-7"); }
#[test] fn format_decimal() { assert_eq!(NumberInputState::format_value(3.14159, 2), "3.14"); }}