use 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) -> 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 { 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 { 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