Something went wrong. Try again.
A simple TUI Library written in Rust
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618use 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<T: Clone> { pub label: Line, pub value: T, pub selected: bool, pub enabled: bool,}
impl<T: Clone> MultiSelectorItem<T> { pub fn new(label: impl Into<String>, 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<String>) -> Self { Self { checked_indicator: s.into(), ..self } }
pub fn unchecked_indicator(self, s: impl Into<String>) -> Self { Self { unchecked_indicator: s.into(), ..self } }}
// --- MultiSelector ---
/// Configuration for a multi-select list.#[derive(Debug, Clone)]pub struct MultiSelector<T: Clone> { items: Vec<MultiSelectorItem<T>>, max_height: Option<usize>, min_selections: usize, max_selections: Option<usize>, style: MultiSelectorStyle,}
impl<T: Clone> MultiSelector<T> { pub fn new(items: Vec<MultiSelectorItem<T>>) -> 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<T: Clone> { items: Vec<MultiSelectorItem<T>>, cursor: usize, scroll_offset: usize, max_height: usize, min_selections: usize, max_selections: Option<usize>, style: MultiSelectorStyle,}
impl<T: Clone> MultiSelectorState<T> { pub fn selected_values(&self) -> Vec<T> { 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` — cancelpub fn multi_selector<T: Clone + 'static>( ms: MultiSelector<T>,) -> Component<MultiSelectorState<T>, Vec<T>> { 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<T: Clone>(state: &MultiSelectorState<T>) -> 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<T: Clone>(items: &[MultiSelectorItem<T>], 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<T: Clone>(items: &[MultiSelectorItem<T>], 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<T: Clone>(state: &MultiSelectorState<T>) -> 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<Line> = 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<T: Clone>( state: &MultiSelectorState<T>, key: &Key,) -> Update<MultiSelectorState<T>, Vec<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_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<String> { let items: Vec<MultiSelectorItem<String>> = 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); }}