Skip to main content

waxterm/widgets/
select_list.rs

1use std::fmt::Display;
2
3use ratatui::layout::Rect;
4use ratatui::style::{Color, Modifier, Style};
5use ratatui::text::{Line, Span};
6use ratatui::widgets::Paragraph;
7use ratatui::Frame;
8
9use crate::input::KeyPress;
10
11use super::WidgetResult;
12
13/// Single-selection list widget (arrow keys + Enter).
14pub struct SelectList<T> {
15    label: String,
16    items: Vec<T>,
17    selected: usize,
18}
19
20impl<T: Display + Clone> SelectList<T> {
21    pub fn new(label: impl Into<String>, items: Vec<T>) -> Self {
22        Self {
23            label: label.into(),
24            items,
25            selected: 0,
26        }
27    }
28
29    /// Index of the currently highlighted item.
30    pub fn selected_index(&self) -> usize {
31        self.selected
32    }
33
34    /// Reference to the currently highlighted item, if any.
35    pub fn selected_item(&self) -> Option<&T> {
36        self.items.get(self.selected)
37    }
38
39    /// Builder: set the initial selection index.
40    pub fn with_selected(mut self, idx: usize) -> Self {
41        if idx < self.items.len() {
42            self.selected = idx;
43        }
44        self
45    }
46
47    /// Read-only reference to items.
48    pub fn items(&self) -> &[T] {
49        &self.items
50    }
51
52    /// Mutable reference to items, for updating status in place.
53    pub fn items_mut(&mut self) -> &mut Vec<T> {
54        &mut self.items
55    }
56
57    /// Set the selected index (clamped to bounds).
58    pub fn set_selected(&mut self, idx: usize) {
59        if idx < self.items.len() {
60            self.selected = idx;
61        }
62    }
63
64    /// Clamp the selected index to be within bounds after items are removed.
65    pub fn clamp_selected(&mut self) {
66        if !self.items.is_empty() {
67            self.selected = self.selected.min(self.items.len() - 1);
68        }
69    }
70
71    pub fn handle_key(&mut self, key: &KeyPress) -> WidgetResult<T> {
72        match key {
73            KeyPress::ArrowUp => {
74                if self.selected > 0 {
75                    self.selected -= 1;
76                }
77                WidgetResult::Pending
78            }
79            KeyPress::ArrowDown => {
80                if self.selected + 1 < self.items.len() {
81                    self.selected += 1;
82                }
83                WidgetResult::Pending
84            }
85            KeyPress::Enter => {
86                if let Some(item) = self.items.get(self.selected) {
87                    WidgetResult::Confirmed(item.clone())
88                } else {
89                    WidgetResult::Pending
90                }
91            }
92            KeyPress::Escape => WidgetResult::Cancelled,
93            _ => WidgetResult::Pending,
94        }
95    }
96
97    /// Render the list. Uses up to `items.len() + 1` rows (label + items).
98    pub fn render(&self, frame: &mut Frame, area: Rect) {
99        let mut lines = Vec::with_capacity(self.items.len() + 1);
100
101        lines.push(Line::from(Span::styled(
102            &self.label,
103            Style::default().fg(Color::Cyan),
104        )));
105
106        for (i, item) in self.items.iter().enumerate() {
107            let marker = if i == self.selected { "> " } else { "  " };
108            let style = if i == self.selected {
109                Style::default()
110                    .fg(Color::Yellow)
111                    .add_modifier(Modifier::BOLD)
112            } else {
113                Style::default()
114            };
115            lines.push(Line::from(Span::styled(format!("{marker}{item}"), style)));
116        }
117
118        let paragraph = Paragraph::new(lines);
119        frame.render_widget(paragraph, area);
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn test_navigate_and_select() {
129        let mut list = SelectList::new("Pick:", vec!["a", "b", "c"]);
130        assert_eq!(list.selected_index(), 0);
131        list.handle_key(&KeyPress::ArrowDown);
132        assert_eq!(list.selected_index(), 1);
133        list.handle_key(&KeyPress::ArrowDown);
134        assert_eq!(list.selected_index(), 2);
135        // Can't go past end
136        list.handle_key(&KeyPress::ArrowDown);
137        assert_eq!(list.selected_index(), 2);
138        assert_eq!(
139            list.handle_key(&KeyPress::Enter),
140            WidgetResult::Confirmed("c")
141        );
142    }
143
144    #[test]
145    fn test_arrow_up_clamps() {
146        let mut list = SelectList::new("Pick:", vec!["a", "b"]);
147        list.handle_key(&KeyPress::ArrowUp);
148        assert_eq!(list.selected_index(), 0);
149    }
150
151    #[test]
152    fn test_escape() {
153        let mut list = SelectList::new("Pick:", vec!["a"]);
154        assert_eq!(
155            list.handle_key(&KeyPress::Escape),
156            WidgetResult::<&str>::Cancelled
157        );
158    }
159
160    #[test]
161    fn test_set_selected() {
162        let mut list = SelectList::new("Pick:", vec!["a", "b", "c"]);
163        list.set_selected(2);
164        assert_eq!(list.selected_index(), 2);
165        // Beyond bounds — should be ignored.
166        list.set_selected(99);
167        assert_eq!(list.selected_index(), 2);
168        // Set back to 0.
169        list.set_selected(0);
170        assert_eq!(list.selected_index(), 0);
171    }
172}