Something went wrong. Try again.
A simple TUI Library written in Rust
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431use crate::block::Block;use crate::color::Color;use crate::component::{Component, Update};use crate::input::Key;use crate::style::{Line, Span, Style};
// --- ButtonStyle ---
/// Visual styles for button states.#[derive(Debug, Clone)]pub struct ButtonStyle { pub normal: Style, pub focused: Style, pub pressed: Style,}
impl Default for ButtonStyle { fn default() -> Self { ButtonStyle { normal: Style::new(), focused: Style::new().bold().fg(Color::Cyan), pressed: Style::new().bold().fg(Color::Green), } }}
impl ButtonStyle { pub fn new() -> Self { Self::default() }
pub fn normal(self, style: Style) -> Self { Self { normal: style, ..self } }
pub fn focused(self, style: Style) -> Self { Self { focused: style, ..self } }
pub fn pressed(self, style: Style) -> Self { Self { pressed: style, ..self } }}
// --- Button ---
/// A button with a label and visual style.#[derive(Debug, Clone)]pub struct Button { label: Line, style: ButtonStyle,}
impl Button { pub fn new(label: impl Into<String>) -> Self { Button { label: vec![Span::plain(label.into())], style: ButtonStyle::default(), } }
pub fn label_line(label: Line) -> Self { Button { label, style: ButtonStyle::default(), } }
pub fn style(self, style: ButtonStyle) -> Self { Self { style, ..self } }}
// --- ButtonState ---
/// State of a single button in the component event loop.#[derive(Debug, Clone, PartialEq, Eq)]pub enum ButtonState { Idle, Focused, Pressed,}
// --- Single Button Component ---
/// Create a single-button component./// Enter/Space → Finish(()), Escape/CtrlC → Cancel, other keys → Ignore.pub fn button(btn: Button) -> Component<ButtonState, ()> { let render_btn = btn.clone(); Component::new( ButtonState::Focused, move |state| render_button(&render_btn, state), |_state, key| update_button(key), )}
fn render_button(btn: &Button, state: &ButtonState) -> Block { let style = match state { ButtonState::Idle => &btn.style.normal, ButtonState::Focused => &btn.style.focused, ButtonState::Pressed => &btn.style.pressed, }; let mut line: Line = vec![Span::styled("[ ", style.clone())]; for span in &btn.label { line.push(Span::styled(span.text().to_string(), style.clone())); } line.push(Span::styled(" ]", style.clone())); Block::text(vec![line])}
fn update_button(key: &Key) -> Update<ButtonState, ()> { match key { Key::Enter | Key::Char(' ') => Update::Finish(()), Key::Escape | Key::CtrlC => Update::Cancel, _ => Update::Ignore, }}
// --- ButtonLayout ---
/// Layout direction for a button group.#[derive(Debug, Clone)]pub enum ButtonLayout { Horizontal(usize), Vertical,}
// --- ButtonGroup ---
/// A group of buttons with keyboard navigation.#[derive(Debug, Clone)]pub struct ButtonGroup { buttons: Vec<Button>, layout: ButtonLayout,}
/// Internal state for the button group component.#[derive(Debug, Clone)]pub struct ButtonGroupState { selected: usize, count: usize, buttons: Vec<Button>, layout: ButtonLayout,}
impl ButtonGroup { pub fn new(buttons: Vec<Button>) -> Self { ButtonGroup { buttons, layout: ButtonLayout::Horizontal(2), } }
pub fn layout(self, layout: ButtonLayout) -> Self { Self { layout, ..self } }}
/// Create a button group component./// Left/Up go backward, Right/Down go forward (wrapping)./// Enter/Space → Finish(selected_index), Escape/CtrlC → Cancel.pub fn button_group(bg: ButtonGroup) -> Component<ButtonGroupState, usize> { let count = bg.buttons.len(); let state = ButtonGroupState { selected: 0, count, buttons: bg.buttons, layout: bg.layout, }; Component::new(state, render_button_group, update_button_group)}
fn render_button_group(state: &ButtonGroupState) -> Block { let button_blocks: Vec<Block> = state .buttons .iter() .enumerate() .map(|(i, btn)| { let btn_state = if i == state.selected { ButtonState::Focused } else { ButtonState::Idle }; render_button(btn, &btn_state) }) .collect();
match &state.layout { ButtonLayout::Horizontal(gap) => Block::hstack(button_blocks, *gap), ButtonLayout::Vertical => Block::vstack(button_blocks, 0), }}
fn update_button_group(state: &ButtonGroupState, key: &Key) -> Update<ButtonGroupState, usize> { if state.count == 0 { return match key { Key::Escape | Key::CtrlC => Update::Cancel, _ => Update::Ignore, }; }
match key { Key::Left | Key::Up => { let selected = if state.selected > 0 { state.selected - 1 } else { state.count - 1 }; Update::Continue(ButtonGroupState { selected, ..state.clone() }) } Key::Right | Key::Down => { let selected = if state.selected < state.count - 1 { state.selected + 1 } else { 0 }; Update::Continue(ButtonGroupState { selected, ..state.clone() }) } Key::Enter | Key::Char(' ') => Update::Finish(state.selected), Key::Escape | Key::CtrlC => Update::Cancel, _ => Update::Ignore, }}
#[cfg(test)]mod tests { use super::*;
// --- Single button tests ---
#[test] fn button_enter_finishes() { assert!(matches!(update_button(&Key::Enter), Update::Finish(()))); }
#[test] fn button_space_finishes() { assert!(matches!(update_button(&Key::Char(' ')), Update::Finish(()))); }
#[test] fn button_escape_cancels() { assert!(matches!(update_button(&Key::Escape), Update::Cancel)); }
#[test] fn button_ctrl_c_cancels() { assert!(matches!(update_button(&Key::CtrlC), Update::Cancel)); }
#[test] fn button_tab_ignores() { assert!(matches!(update_button(&Key::Tab), Update::Ignore)); }
#[test] fn button_other_key_ignores() { assert!(matches!(update_button(&Key::Up), Update::Ignore)); }
#[test] fn button_render_height_is_one() { let btn = Button::new("OK"); let block = render_button(&btn, &ButtonState::Focused); assert_eq!(block.height(), 1); }
#[test] fn button_render_contains_label() { let btn = Button::new("Confirm"); let block = render_button(&btn, &ButtonState::Focused); let lines = block.render(30); assert!(lines[0].contains("Confirm")); }
#[test] fn button_render_contains_brackets() { let btn = Button::new("OK"); let block = render_button(&btn, &ButtonState::Idle); let lines = block.render(20); assert!(lines[0].contains("[")); assert!(lines[0].contains("]")); }
// --- Button group tests ---
fn make_group(n: usize) -> ButtonGroupState { let buttons: Vec<Button> = (0..n).map(|i| Button::new(format!("Btn{}", i))).collect(); ButtonGroupState { selected: 0, count: n, buttons, layout: ButtonLayout::Horizontal(2), } }
#[test] fn group_right_moves_forward() { let state = make_group(3); if let Update::Continue(new) = update_button_group(&state, &Key::Right) { assert_eq!(new.selected, 1); } else { panic!("expected Continue"); } }
#[test] fn group_down_moves_forward() { let state = make_group(3); if let Update::Continue(new) = update_button_group(&state, &Key::Down) { assert_eq!(new.selected, 1); } else { panic!("expected Continue"); } }
#[test] fn group_left_wraps_to_end() { let state = make_group(3); // selected=0 if let Update::Continue(new) = update_button_group(&state, &Key::Left) { assert_eq!(new.selected, 2); } else { panic!("expected Continue"); } }
#[test] fn group_right_wraps_to_start() { let mut state = make_group(3); state.selected = 2; if let Update::Continue(new) = update_button_group(&state, &Key::Right) { assert_eq!(new.selected, 0); } else { panic!("expected Continue"); } }
#[test] fn group_enter_returns_index() { let mut state = make_group(3); state.selected = 1; assert!(matches!( update_button_group(&state, &Key::Enter), Update::Finish(1) )); }
#[test] fn group_space_returns_index() { let mut state = make_group(3); state.selected = 2; assert!(matches!( update_button_group(&state, &Key::Char(' ')), Update::Finish(2) )); }
#[test] fn group_escape_cancels() { let state = make_group(3); assert!(matches!( update_button_group(&state, &Key::Escape), Update::Cancel )); }
#[test] fn group_render_horizontal() { let state = make_group(3); let block = render_button_group(&state); // HStack of 3 buttons = 1 row assert_eq!(block.height(), 1); }
#[test] fn group_render_vertical() { let buttons: Vec<Button> = (0..3).map(|i| Button::new(format!("B{}", i))).collect(); let state = ButtonGroupState { selected: 0, count: 3, buttons, layout: ButtonLayout::Vertical, }; let block = render_button_group(&state); assert_eq!(block.height(), 3); }
#[test] fn group_empty_escape_cancels() { let state = ButtonGroupState { selected: 0, count: 0, buttons: vec![], layout: ButtonLayout::Horizontal(2), }; assert!(matches!( update_button_group(&state, &Key::Escape), Update::Cancel )); }
#[test] fn group_empty_other_ignores() { let state = ButtonGroupState { selected: 0, count: 0, buttons: vec![], layout: ButtonLayout::Horizontal(2), }; assert!(matches!( update_button_group(&state, &Key::Enter), Update::Ignore )); }}