use crate::block::Block; use crate::color::Color; use crate::component::{Component, Update}; use crate::input::Key; use crate::style::{Line, Span, Style}; // --- SelectorItem --- /// An item in a selector list. #[derive(Debug, Clone)] pub struct SelectorItem { pub label: Line, pub value: T, pub enabled: bool, } impl SelectorItem { pub fn new(label: impl Into, value: T) -> Self { SelectorItem { label: vec![Span::plain(label.into())], value, enabled: true, } } pub fn label_line(label: Line, value: T) -> Self { SelectorItem { label, value, enabled: true, } } pub fn enabled(self, enabled: bool) -> Self { Self { enabled, ..self } } } // --- ScrollIndicator --- /// How to indicate scrollable content. #[derive(Debug, Clone)] pub enum ScrollIndicator { None, Arrows, } // --- SelectorStyle --- /// Visual styling for the selector. #[derive(Debug, Clone)] pub struct SelectorStyle { pub normal: Style, pub highlighted: Style, pub disabled: Style, pub indicator: String, pub no_indicator: String, pub scroll_indicator: ScrollIndicator, } impl Default for SelectorStyle { fn default() -> Self { SelectorStyle { normal: Style::new(), highlighted: Style::new().bold().fg(Color::Cyan), disabled: Style::new().dim(), indicator: "▶ ".into(), no_indicator: " ".into(), scroll_indicator: ScrollIndicator::Arrows, } } } impl SelectorStyle { pub fn new() -> Self { Self::default() } pub fn normal(self, s: Style) -> Self { Self { normal: s, ..self } } pub fn highlighted(self, s: Style) -> Self { Self { highlighted: s, ..self } } pub fn disabled(self, s: Style) -> Self { Self { disabled: s, ..self } } pub fn indicator(self, ind: impl Into) -> Self { Self { indicator: ind.into(), ..self } } pub fn no_indicator(self, ind: impl Into) -> Self { Self { no_indicator: ind.into(), ..self } } pub fn scroll_indicator(self, si: ScrollIndicator) -> Self { Self { scroll_indicator: si, ..self } } } // --- Selector --- /// Configuration for a single-select list. #[derive(Debug, Clone)] pub struct Selector { items: Vec>, max_height: Option, style: SelectorStyle, } impl Selector { pub fn new(items: Vec>) -> Self { Selector { items, max_height: None, style: SelectorStyle::default(), } } pub fn max_height(self, h: usize) -> Self { Self { max_height: Some(h), ..self } } pub fn style(self, style: SelectorStyle) -> Self { Self { style, ..self } } } // --- SelectorState --- /// Internal state for the selector component. #[derive(Debug, Clone)] pub struct SelectorState { items: Vec>, selected: usize, scroll_offset: usize, max_height: usize, style: SelectorStyle, } // --- Component constructor --- /// Create a selector component. /// Up/Down navigate (skipping disabled, wrapping). Enter → Finish(value). /// Home/End jump. Typing a character does type-ahead search. /// Escape/CtrlC → Cancel. pub fn selector(sel: Selector) -> Component, T> { let count = sel.items.len(); let max_h = sel.max_height.unwrap_or(count); let state = SelectorState { items: sel.items, selected: 0, scroll_offset: 0, max_height: max_h, style: sel.style, }; Component::new(state, render_selector, update_selector) } // --- Scrolling helpers --- fn adjust_scroll(state: &SelectorState) -> usize { let effective_height = effective_item_slots(state); if state.selected < state.scroll_offset { state.selected } else if state.selected >= state.scroll_offset + effective_height { state.selected.saturating_sub(effective_height) + 1 } else { state.scroll_offset } } /// How many item slots are visible (accounting for arrow indicators). fn effective_item_slots(state: &SelectorState) -> usize { let total = state.items.len(); if total <= state.max_height { return total; } match state.style.scroll_indicator { ScrollIndicator::None => state.max_height, ScrollIndicator::Arrows => { let can_up = state.scroll_offset > 0; let can_down = state.scroll_offset + state.max_height < total; let arrows = can_up as usize + can_down as usize; state.max_height.saturating_sub(arrows) } } } // --- Navigation helpers --- fn find_next_enabled(items: &[SelectorItem], from: usize) -> usize { let count = items.len(); for offset in 1..count { let idx = (from + offset) % count; if items[idx].enabled { return idx; } } from } fn find_prev_enabled(items: &[SelectorItem], from: usize) -> usize { let count = items.len(); for offset in 1..count { let idx = (from + count - offset) % count; if items[idx].enabled { return idx; } } from } fn find_first_enabled(items: &[SelectorItem]) -> usize { items.iter().position(|item| item.enabled).unwrap_or(0) } fn find_last_enabled(items: &[SelectorItem]) -> usize { items.iter().rposition(|item| item.enabled).unwrap_or(0) } fn type_ahead_search(state: &SelectorState, c: char) -> Update, T> { let c_lower = c.to_lowercase().next().unwrap_or(c); let count = state.items.len(); for offset in 1..=count { let idx = (state.selected + offset) % count; let item = &state.items[idx]; if item.enabled { let label_text: String = item.label.iter().map(|s| s.text().to_string()).collect(); if let Some(first_char) = label_text.chars().next() && first_char.to_lowercase().next() == Some(c_lower) { let mut new_state = SelectorState { selected: idx, ..state.clone() }; new_state.scroll_offset = adjust_scroll(&new_state); return Update::Continue(new_state); } } } Update::Ignore } // --- Render --- fn render_selector(state: &SelectorState) -> Block { let total = state.items.len(); if total == 0 { return Block::text(vec![vec![Span::plain("(no items)")]]); } let can_scroll_up = state.scroll_offset > 0; let can_scroll_down = state.scroll_offset + state.max_height < total; let show_up_arrow = can_scroll_up && matches!(state.style.scroll_indicator, ScrollIndicator::Arrows); let show_down_arrow = can_scroll_down && matches!(state.style.scroll_indicator, ScrollIndicator::Arrows); let arrow_slots = show_up_arrow as usize + show_down_arrow as usize; let item_slots = state.max_height.saturating_sub(arrow_slots); let vis_start = state.scroll_offset; let vis_end = (vis_start + item_slots).min(total); let mut lines: Vec = Vec::new(); if show_up_arrow { lines.push(vec![Span::styled( format!("{}↑", state.style.no_indicator), Style::new().dim(), )]); } for i in vis_start..vis_end { let item = &state.items[i]; let is_selected = i == state.selected; let prefix = if is_selected { &state.style.indicator } else { &state.style.no_indicator }; let item_style = if !item.enabled { &state.style.disabled } else if is_selected { &state.style.highlighted } else { &state.style.normal }; let mut line: Line = vec![Span::styled(prefix.clone(), item_style.clone())]; for span in &item.label { line.push(Span::styled(span.text().to_string(), item_style.clone())); } lines.push(line); } if show_down_arrow { lines.push(vec![Span::styled( format!("{}↓", state.style.no_indicator), Style::new().dim(), )]); } Block::text(lines) } // --- Update --- fn update_selector(state: &SelectorState, key: &Key) -> Update, T> { let count = state.items.len(); if count == 0 { return match key { Key::Escape | Key::CtrlC => Update::Cancel, _ => Update::Ignore, }; } match key { Key::Up => { let new_selected = find_prev_enabled(&state.items, state.selected); let mut new_state = SelectorState { selected: new_selected, ..state.clone() }; new_state.scroll_offset = adjust_scroll(&new_state); Update::Continue(new_state) } Key::Down => { let new_selected = find_next_enabled(&state.items, state.selected); let mut new_state = SelectorState { selected: new_selected, ..state.clone() }; new_state.scroll_offset = adjust_scroll(&new_state); Update::Continue(new_state) } Key::Home => { let new_selected = find_first_enabled(&state.items); let new_state = SelectorState { selected: new_selected, scroll_offset: 0, ..state.clone() }; Update::Continue(new_state) } Key::End => { let new_selected = find_last_enabled(&state.items); let mut new_state = SelectorState { selected: new_selected, ..state.clone() }; new_state.scroll_offset = adjust_scroll(&new_state); Update::Continue(new_state) } Key::Enter => { if state.items[state.selected].enabled { Update::Finish(state.items[state.selected].value.clone()) } else { Update::Ignore } } Key::Escape | Key::CtrlC => Update::Cancel, Key::Char(c) => type_ahead_search(state, *c), _ => Update::Ignore, } } #[cfg(test)] mod tests { use super::*; fn make_state(labels: &[&str]) -> SelectorState { let items: Vec> = labels .iter() .map(|&l| SelectorItem::new(l, l.to_string())) .collect(); let count = items.len(); SelectorState { items, selected: 0, scroll_offset: 0, max_height: count, style: SelectorStyle::default(), } } fn make_state_with_disabled(labels: &[(&str, bool)]) -> SelectorState { let items: Vec> = labels .iter() .map(|&(l, enabled)| SelectorItem::new(l, l.to_string()).enabled(enabled)) .collect(); let count = items.len(); SelectorState { items, selected: 0, scroll_offset: 0, max_height: count, style: SelectorStyle::default(), } } // --- Navigation --- #[test] fn down_moves_to_next() { let state = make_state(&["A", "B", "C"]); if let Update::Continue(new) = update_selector(&state, &Key::Down) { assert_eq!(new.selected, 1); } else { panic!("expected Continue"); } } #[test] fn up_wraps_to_last() { let state = make_state(&["A", "B", "C"]); if let Update::Continue(new) = update_selector(&state, &Key::Up) { assert_eq!(new.selected, 2); } else { panic!("expected Continue"); } } #[test] fn down_wraps_to_first() { let mut state = make_state(&["A", "B", "C"]); state.selected = 2; if let Update::Continue(new) = update_selector(&state, &Key::Down) { assert_eq!(new.selected, 0); } else { panic!("expected Continue"); } } #[test] fn skip_disabled_down() { let mut state = make_state_with_disabled(&[("A", true), ("B", false), ("C", true)]); state.selected = 0; if let Update::Continue(new) = update_selector(&state, &Key::Down) { assert_eq!(new.selected, 2); } else { panic!("expected Continue"); } } #[test] fn skip_disabled_up() { let mut state = make_state_with_disabled(&[("A", true), ("B", false), ("C", true)]); state.selected = 2; if let Update::Continue(new) = update_selector(&state, &Key::Up) { assert_eq!(new.selected, 0); } else { panic!("expected Continue"); } } #[test] fn enter_finishes_with_value() { let mut state = make_state(&["A", "B", "C"]); state.selected = 1; if let Update::Finish(val) = update_selector(&state, &Key::Enter) { assert_eq!(val, "B"); } else { panic!("expected Finish"); } } #[test] fn enter_disabled_ignores() { let mut state = make_state_with_disabled(&[("A", true), ("B", false), ("C", true)]); state.selected = 1; assert!(matches!( update_selector(&state, &Key::Enter), Update::Ignore )); } #[test] fn escape_cancels() { let state = make_state(&["A", "B"]); assert!(matches!( update_selector(&state, &Key::Escape), Update::Cancel )); } #[test] fn home_jumps_to_first_enabled() { let mut state = make_state_with_disabled(&[("A", false), ("B", true), ("C", true)]); state.selected = 2; if let Update::Continue(new) = update_selector(&state, &Key::Home) { assert_eq!(new.selected, 1); } else { panic!("expected Continue"); } } #[test] fn end_jumps_to_last_enabled() { let state = make_state_with_disabled(&[("A", true), ("B", true), ("C", false)]); if let Update::Continue(new) = update_selector(&state, &Key::End) { assert_eq!(new.selected, 1); } else { panic!("expected Continue"); } } // --- Type-ahead --- #[test] fn type_ahead_finds_match() { let state = make_state(&["Apple", "Banana", "Cherry"]); if let Update::Continue(new) = update_selector(&state, &Key::Char('b')) { assert_eq!(new.selected, 1); } else { panic!("expected Continue"); } } #[test] fn type_ahead_wraps() { let mut state = make_state(&["Apple", "Banana", "Avocado"]); state.selected = 2; // at Avocado if let Update::Continue(new) = update_selector(&state, &Key::Char('a')) { assert_eq!(new.selected, 0); // wraps to Apple } else { panic!("expected Continue"); } } #[test] fn type_ahead_case_insensitive() { let state = make_state(&["apple", "Banana", "Cherry"]); if let Update::Continue(new) = update_selector(&state, &Key::Char('B')) { assert_eq!(new.selected, 1); } else { panic!("expected Continue"); } } #[test] fn type_ahead_no_match_ignores() { let state = make_state(&["Apple", "Banana"]); assert!(matches!( update_selector(&state, &Key::Char('z')), Update::Ignore )); } // --- Scrolling --- #[test] fn scroll_down_adjusts_offset() { let mut state = make_state(&["A", "B", "C", "D", "E"]); state.max_height = 3; state.style.scroll_indicator = ScrollIndicator::None; // Navigate to the bottom state.selected = 2; state.scroll_offset = adjust_scroll(&state); assert_eq!(state.scroll_offset, 0); state.selected = 3; state.scroll_offset = adjust_scroll(&state); assert_eq!(state.scroll_offset, 1); } #[test] fn scroll_up_adjusts_offset() { let mut state = make_state(&["A", "B", "C", "D", "E"]); state.max_height = 3; state.scroll_offset = 2; state.selected = 1; state.style.scroll_indicator = ScrollIndicator::None; state.scroll_offset = adjust_scroll(&state); assert_eq!(state.scroll_offset, 1); } #[test] fn scroll_home_resets() { let mut state = make_state(&["A", "B", "C", "D", "E"]); state.max_height = 3; state.scroll_offset = 2; state.selected = 3; if let Update::Continue(new) = update_selector(&state, &Key::Home) { assert_eq!(new.selected, 0); assert_eq!(new.scroll_offset, 0); } else { panic!("expected Continue"); } } // --- Render --- #[test] fn render_highlights_selected() { let state = make_state(&["A", "B", "C"]); let block = render_selector(&state); let lines = block.render(20); assert_eq!(lines.len(), 3); // First line should contain the indicator assert!(lines[0].contains("▶")); } #[test] fn render_scroll_arrows() { let mut state = make_state(&["A", "B", "C", "D", "E"]); state.max_height = 3; state.scroll_offset = 1; state.selected = 2; let block = render_selector(&state); let lines = block.render(20); // Should have 3 lines: ↑ arrow + 1 item + ↓ arrow assert_eq!(lines.len(), 3); assert!(lines[0].contains("↑")); assert!(lines[2].contains("↓")); } #[test] fn render_no_top_arrow_at_zero() { let mut state = make_state(&["A", "B", "C", "D", "E"]); state.max_height = 3; state.scroll_offset = 0; state.selected = 0; let block = render_selector(&state); let lines = block.render(20); // 2 items + ↓ arrow = 3 lines assert_eq!(lines.len(), 3); assert!(!lines[0].contains("↑")); assert!(lines[2].contains("↓")); } #[test] fn render_no_bottom_arrow_at_end() { let mut state = make_state(&["A", "B", "C", "D", "E"]); state.max_height = 3; state.scroll_offset = 2; state.selected = 4; let block = render_selector(&state); let lines = block.render(20); assert_eq!(lines.len(), 3); assert!(lines[0].contains("↑")); // Last line should NOT be an arrow assert!(!lines[2].contains("↓")); } #[test] fn render_no_scroll_when_fits() { let state = make_state(&["A", "B", "C"]); let block = render_selector(&state); let lines = block.render(20); assert_eq!(lines.len(), 3); assert!(!lines[0].contains("↑")); assert!(!lines[2].contains("↓")); } #[test] fn empty_selector_escape_cancels() { let state: SelectorState = SelectorState { items: vec![], selected: 0, scroll_offset: 0, max_height: 5, style: SelectorStyle::default(), }; assert!(matches!( update_selector(&state, &Key::Escape), Update::Cancel )); } #[test] fn empty_selector_other_ignores() { let state: SelectorState = SelectorState { items: vec![], selected: 0, scroll_offset: 0, max_height: 5, style: SelectorStyle::default(), }; assert!(matches!( update_selector(&state, &Key::Down), Update::Ignore )); } }