use 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, max: Option, 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) -> 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, min: Option, max: Option, 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 { self.text.parse::().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 { let v = self .text .parse::() .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 { 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 = 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 { 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 = 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 = 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 = 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"); } }