use crate::block::Block; use crate::color::Color; use crate::component::{Component, Update}; use crate::input::Key; use crate::style::{Line, Span, Style}; // --- MultiSelectorItem --- /// An item in a multi-select list. #[derive(Debug, Clone)] pub struct MultiSelectorItem { pub label: Line, pub value: T, pub selected: bool, pub enabled: bool, } impl MultiSelectorItem { pub fn new(label: impl Into, value: T) -> Self { MultiSelectorItem { label: vec![Span::plain(label.into())], value, selected: false, enabled: true, } } pub fn label_line(label: Line, value: T) -> Self { MultiSelectorItem { label, value, selected: false, enabled: true, } } pub fn selected(self, s: bool) -> Self { Self { selected: s, ..self } } pub fn enabled(self, e: bool) -> Self { Self { enabled: e, ..self } } } // --- MultiSelectorStyle --- #[derive(Debug, Clone)] pub struct MultiSelectorStyle { pub normal: Style, pub highlighted: Style, pub disabled: Style, pub checked_indicator: String, pub unchecked_indicator: String, pub no_indicator: String, pub show_count: bool, } impl Default for MultiSelectorStyle { fn default() -> Self { MultiSelectorStyle { normal: Style::new(), highlighted: Style::new().bold().fg(Color::Cyan), disabled: Style::new().dim(), checked_indicator: "◉ ".into(), unchecked_indicator: "○ ".into(), no_indicator: " ".into(), show_count: false, } } } impl MultiSelectorStyle { pub fn new() -> Self { Self::default() } pub fn show_count(self, show: bool) -> Self { Self { show_count: show, ..self } } pub fn checked_indicator(self, s: impl Into) -> Self { Self { checked_indicator: s.into(), ..self } } pub fn unchecked_indicator(self, s: impl Into) -> Self { Self { unchecked_indicator: s.into(), ..self } } } // --- MultiSelector --- /// Configuration for a multi-select list. #[derive(Debug, Clone)] pub struct MultiSelector { items: Vec>, max_height: Option, min_selections: usize, max_selections: Option, style: MultiSelectorStyle, } impl MultiSelector { pub fn new(items: Vec>) -> Self { MultiSelector { items, max_height: None, min_selections: 0, max_selections: None, style: MultiSelectorStyle::default(), } } pub fn max_height(self, h: usize) -> Self { Self { max_height: Some(h), ..self } } pub fn min_selections(self, n: usize) -> Self { Self { min_selections: n, ..self } } pub fn max_selections(self, n: usize) -> Self { Self { max_selections: Some(n), ..self } } pub fn style(self, style: MultiSelectorStyle) -> Self { Self { style, ..self } } } // --- MultiSelectorState --- #[derive(Debug, Clone)] pub struct MultiSelectorState { items: Vec>, cursor: usize, scroll_offset: usize, max_height: usize, min_selections: usize, max_selections: Option, style: MultiSelectorStyle, } impl MultiSelectorState { pub fn selected_values(&self) -> Vec { self.items .iter() .filter(|item| item.selected) .map(|item| item.value.clone()) .collect() } pub fn selection_count(&self) -> usize { self.items.iter().filter(|i| i.selected).count() } fn can_submit(&self) -> bool { self.selection_count() >= self.min_selections } fn can_select_more(&self) -> bool { match self.max_selections { None => true, Some(max) => self.selection_count() < max, } } } // --- Component constructor --- /// Create a multi-selector component. /// /// - `Up` / `Down` — move cursor (wraps, skips disabled) /// - `Space` — toggle item selection /// - `Enter` — submit if `min_selections` met, otherwise ignore /// - `Ctrl+A` — select all enabled /// - `Ctrl+D` — deselect all /// - `Escape` / `Ctrl+C` — cancel pub fn multi_selector( ms: MultiSelector, ) -> Component, Vec> { let count = ms.items.len(); let max_h = ms.max_height.unwrap_or(count.max(1)); let state = MultiSelectorState { items: ms.items, cursor: 0, scroll_offset: 0, max_height: max_h, min_selections: ms.min_selections, max_selections: ms.max_selections, style: ms.style, }; Component::new(state, render_multi, update_multi) } // --- Scroll helpers --- fn adjust_scroll(state: &MultiSelectorState) -> usize { let h = state.max_height; if state.cursor < state.scroll_offset { state.cursor } else if state.cursor >= state.scroll_offset + h { state.cursor.saturating_sub(h) + 1 } else { state.scroll_offset } } fn find_next_enabled(items: &[MultiSelectorItem], 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: &[MultiSelectorItem], 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 } // --- Render --- fn render_multi(state: &MultiSelectorState) -> Block { let total = state.items.len(); if total == 0 { return Block::text(vec![vec![Span::plain("(no items)")]]); } let vis_start = state.scroll_offset; let vis_end = (vis_start + state.max_height).min(total); let mut lines: Vec = Vec::new(); for i in vis_start..vis_end { let item = &state.items[i]; let is_cursor = i == state.cursor; let item_style = if !item.enabled { &state.style.disabled } else if is_cursor { &state.style.highlighted } else { &state.style.normal }; let indicator = if item.selected { &state.style.checked_indicator } else { &state.style.unchecked_indicator }; let mut line: Line = vec![Span::styled(indicator.clone(), item_style.clone())]; for span in &item.label { line.push(Span::styled(span.text().to_string(), item_style.clone())); } lines.push(line); } if state.style.show_count { let n = state.selection_count(); lines.push(vec![Span::styled( format!(" {} selected", n), Style::new().dim(), )]); } Block::text(lines) } // --- Update --- fn update_multi( state: &MultiSelectorState, key: &Key, ) -> Update, Vec> { 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_cursor = find_prev_enabled(&state.items, state.cursor); let mut new_state = MultiSelectorState { cursor: new_cursor, ..state.clone() }; new_state.scroll_offset = adjust_scroll(&new_state); Update::Continue(new_state) } Key::Down => { let new_cursor = find_next_enabled(&state.items, state.cursor); let mut new_state = MultiSelectorState { cursor: new_cursor, ..state.clone() }; new_state.scroll_offset = adjust_scroll(&new_state); Update::Continue(new_state) } Key::Char(' ') => { let item = &state.items[state.cursor]; if !item.enabled { return Update::Ignore; } // Toggle: if currently selected, deselect. If not, check max. if item.selected || state.can_select_more() { let mut new_items = state.items.clone(); new_items[state.cursor].selected = !new_items[state.cursor].selected; Update::Continue(MultiSelectorState { items: new_items, ..state.clone() }) } else { Update::Ignore } } Key::Enter => { if state.can_submit() { Update::Finish(state.selected_values()) } else { Update::Ignore } } // Ctrl+A — select all enabled Key::Ctrl('a') => { let can_select_all = state .max_selections .map(|max| { let enabled_count = state.items.iter().filter(|i| i.enabled).count(); enabled_count <= max }) .unwrap_or(true); if can_select_all { let mut new_items = state.items.clone(); for item in &mut new_items { if item.enabled { item.selected = true; } } Update::Continue(MultiSelectorState { items: new_items, ..state.clone() }) } else { Update::Ignore } } // Ctrl+D — deselect all Key::Ctrl('d') => { let mut new_items = state.items.clone(); for item in &mut new_items { item.selected = false; } Update::Continue(MultiSelectorState { items: new_items, ..state.clone() }) } Key::Escape | Key::CtrlC => Update::Cancel, _ => Update::Ignore, } } #[cfg(test)] mod tests { use super::*; fn make_state(labels: &[&str]) -> MultiSelectorState { let items: Vec> = labels .iter() .map(|&l| MultiSelectorItem::new(l, l.to_string())) .collect(); let count = items.len(); MultiSelectorState { items, cursor: 0, scroll_offset: 0, max_height: count.max(1), min_selections: 0, max_selections: None, style: MultiSelectorStyle::default(), } } // --- Navigation --- #[test] fn down_moves_cursor() { let state = make_state(&["A", "B", "C"]); if let Update::Continue(new) = update_multi(&state, &Key::Down) { assert_eq!(new.cursor, 1); } else { panic!("expected Continue"); } } #[test] fn down_wraps() { let mut state = make_state(&["A", "B", "C"]); state.cursor = 2; if let Update::Continue(new) = update_multi(&state, &Key::Down) { assert_eq!(new.cursor, 0); } else { panic!("expected Continue"); } } #[test] fn up_wraps_to_last() { let state = make_state(&["A", "B", "C"]); if let Update::Continue(new) = update_multi(&state, &Key::Up) { assert_eq!(new.cursor, 2); } else { panic!("expected Continue"); } } // --- Toggle --- #[test] fn space_selects_item() { let state = make_state(&["A", "B"]); if let Update::Continue(new) = update_multi(&state, &Key::Char(' ')) { assert!(new.items[0].selected); } else { panic!("expected Continue"); } } #[test] fn space_deselects_item() { let mut state = make_state(&["A", "B"]); state.items[0].selected = true; if let Update::Continue(new) = update_multi(&state, &Key::Char(' ')) { assert!(!new.items[0].selected); } else { panic!("expected Continue"); } } #[test] fn space_on_disabled_ignores() { let mut state = make_state(&["A", "B"]); state.items[0].enabled = false; assert!(matches!( update_multi(&state, &Key::Char(' ')), Update::Ignore )); } // --- Submit --- #[test] fn enter_submits_selected() { let mut state = make_state(&["A", "B", "C"]); state.items[0].selected = true; state.items[2].selected = true; if let Update::Finish(vals) = update_multi(&state, &Key::Enter) { assert_eq!(vals, vec!["A".to_string(), "C".to_string()]); } else { panic!("expected Finish"); } } #[test] fn enter_below_min_ignores() { let mut state = make_state(&["A", "B"]); state.min_selections = 2; assert!(matches!(update_multi(&state, &Key::Enter), Update::Ignore)); } // --- Ctrl+A / Ctrl+D --- #[test] fn ctrl_a_selects_all() { let state = make_state(&["A", "B", "C"]); if let Update::Continue(new) = update_multi(&state, &Key::Ctrl('a')) { assert!(new.items.iter().all(|i| i.selected)); } else { panic!("expected Continue"); } } #[test] fn ctrl_d_deselects_all() { let mut state = make_state(&["A", "B"]); state.items[0].selected = true; state.items[1].selected = true; if let Update::Continue(new) = update_multi(&state, &Key::Ctrl('d')) { assert!(new.items.iter().all(|i| !i.selected)); } else { panic!("expected Continue"); } } // --- Max selections --- #[test] fn max_selections_blocks_over_limit() { let mut state = make_state(&["A", "B", "C"]); state.max_selections = Some(1); state.items[0].selected = true; state.cursor = 1; // Trying to select B when A is already selected and max=1 → Ignore assert!(matches!( update_multi(&state, &Key::Char(' ')), Update::Ignore )); } #[test] fn max_selections_allows_deselect() { let mut state = make_state(&["A", "B"]); state.max_selections = Some(1); state.items[0].selected = true; // Deselecting A should work if let Update::Continue(new) = update_multi(&state, &Key::Char(' ')) { assert!(!new.items[0].selected); } else { panic!("expected Continue"); } } // --- Cancel --- #[test] fn escape_cancels() { let state = make_state(&["A"]); assert!(matches!(update_multi(&state, &Key::Escape), Update::Cancel)); } // --- Render --- #[test] fn render_shows_indicators() { let mut state = make_state(&["A", "B"]); state.items[0].selected = true; let block = render_multi(&state); let lines = block.render(20); assert_eq!(lines.len(), 2); assert!(lines[0].contains("◉")); // selected assert!(lines[1].contains("○")); // not selected } #[test] fn render_count_line() { let mut state = make_state(&["A", "B"]); state.style.show_count = true; state.items[0].selected = true; let block = render_multi(&state); let lines = block.render(20); // 2 items + count line = 3 assert_eq!(lines.len(), 3); assert!(lines[2].contains("1 selected")); } #[test] fn render_scrolls() { let mut state = make_state(&["A", "B", "C", "D", "E"]); state.max_height = 3; state.scroll_offset = 1; let block = render_multi(&state); let lines = block.render(20); assert_eq!(lines.len(), 3); // Should show B, C, D assert!(lines[0].contains("B")); assert!(lines[2].contains("D")); } #[test] fn selection_count() { let mut state = make_state(&["A", "B", "C"]); state.items[0].selected = true; state.items[2].selected = true; assert_eq!(state.selection_count(), 2); } }