Skip to main content

tui/widgets/
select.rs

1//! Dropdown / list select widget.
2//!
3//! Holds an ordered list of options and a focused index. Navigation wraps
4//! around within the type-ahead filtered set. The widget submits the focused
5//! option's `id` (usually a UUID), not its display label.
6
7use std::cell::Cell;
8
9use tvui::{RowWindow, Viewport};
10
11/// A single entry in a [`SelectWidget`] option list.
12#[derive(Debug, Clone)]
13pub struct SelectOption {
14    pub id: String,
15    pub label: String,
16}
17
18/// `options` led by `(none)`, which keeps an unchosen select empty.
19pub fn with_none(options: Vec<SelectOption>) -> Vec<SelectOption> {
20    let none = SelectOption {
21        id: String::new(),
22        label: "(none)".to_string(),
23    };
24    std::iter::once(none).chain(options).collect()
25}
26
27/// A scrollable pick-list widget with type-ahead filtering.
28///
29/// `focused` indexes the **filtered** set returned by [`Self::matches`], not
30/// `options` directly. When the filter matches nothing, `value()`/`display()`
31/// return `""` and `next()`/`prev()` are no-ops.
32#[derive(Debug, Clone)]
33pub struct SelectWidget {
34    options: Vec<SelectOption>,
35    focused: usize,
36    pub open: bool,
37    query: String,
38    /// The option focused when the list opened; Esc and typing back to empty return to it.
39    opened_at: usize,
40    /// An id chosen before its option existed; applied by the next `set_options`.
41    wanted: Option<String>,
42    /// The first option on screen in the open list, kept between frames by the draw.
43    window: RowWindow,
44    /// Where the field showing the filter is scrolled to, kept by the draw.
45    scroll: Cell<Viewport>,
46}
47
48impl SelectWidget {
49    #[must_use]
50    pub fn new() -> Self {
51        Self {
52            options: Vec::new(),
53            focused: 0,
54            open: false,
55            query: String::new(),
56            opened_at: 0,
57            wanted: None,
58            window: RowWindow::default(),
59            scroll: Cell::default(),
60        }
61    }
62
63    /// The cell the draw of the field showing this select keeps its scroll in.
64    #[must_use]
65    pub fn scroll(&self) -> &Cell<Viewport> {
66        &self.scroll
67    }
68
69    /// A select over a choice field's `(id, label)` options, on `default` when given.
70    #[must_use]
71    pub fn choice(options: &[(&str, &str)], default: Option<&str>) -> Self {
72        let mut select = Self::new();
73        select.set_options(
74            options
75                .iter()
76                .map(|&(id, label)| SelectOption {
77                    id: id.to_string(),
78                    label: label.to_string(),
79                })
80                .collect(),
81        );
82        if let Some(default) = default {
83            select.select_id(default);
84        }
85        select
86    }
87
88    /// Replace the option list, focus the option chosen earlier by id (else
89    /// the first), and clear any query.
90    pub fn set_options(&mut self, options: Vec<SelectOption>) {
91        self.options = options;
92        self.focused = 0;
93        self.query.clear();
94        if let Some(id) = self.wanted.take() {
95            self.select_id(&id);
96        }
97    }
98
99    /// Indices into `options` whose label contains `query` case-insensitively.
100    /// An empty query returns all indices.
101    #[must_use]
102    pub fn matches(&self) -> Vec<usize> {
103        if self.query.is_empty() {
104            return (0..self.options.len()).collect();
105        }
106        let q = self.query.to_lowercase();
107        self.options
108            .iter()
109            .enumerate()
110            .filter(|(_, o)| o.label.to_lowercase().contains(&q))
111            .map(|(i, _)| i)
112            .collect()
113    }
114
115    /// The `id` of the focused filtered option, or `""` when no match exists.
116    /// An id chosen before any option was loaded is returned until they arrive.
117    #[must_use]
118    pub fn value(&self) -> &str {
119        if let Some(wanted) = self.wanted.as_deref().filter(|_| self.options.is_empty()) {
120            return wanted;
121        }
122        let m = self.matches();
123        m.get(self.focused)
124            .map(|&idx| self.options[idx].id.as_str())
125            .unwrap_or("")
126    }
127
128    /// The display label of the focused filtered option, or `""` when no match.
129    #[must_use]
130    pub fn display(&self) -> &str {
131        let m = self.matches();
132        m.get(self.focused)
133            .map(|&idx| self.options[idx].label.as_str())
134            .unwrap_or("")
135    }
136
137    /// Focus the option with this `id`, clearing the query; an unknown id
138    /// leaves the selection unchanged and is remembered for the next option list.
139    pub fn select_id(&mut self, id: &str) {
140        match self.options.iter().position(|o| o.id == id) {
141            Some(idx) => {
142                self.query.clear();
143                self.focused = idx;
144                self.wanted = None;
145            }
146            None => self.wanted = Some(id.to_string()),
147        }
148    }
149
150    /// Where the open list's window starts, written by the draw.
151    #[must_use]
152    pub fn window(&self) -> &RowWindow {
153        &self.window
154    }
155
156    /// The raw option list, for rendering.
157    #[must_use]
158    pub fn options(&self) -> &[SelectOption] {
159        &self.options
160    }
161
162    /// The typed filter while there is one, else the selected label.
163    #[must_use]
164    pub fn shown(&self) -> &str {
165        match self.query() {
166            "" => self.display(),
167            query => query,
168        }
169    }
170
171    /// The active type-ahead query string.
172    #[must_use]
173    pub fn query(&self) -> &str {
174        &self.query
175    }
176
177    /// Index of the focused entry within the filtered set (i.e. `matches()`).
178    #[must_use]
179    pub fn focused_in_filtered(&self) -> usize {
180        self.focused
181    }
182
183    /// Advance focus by one step within the filtered set, wrapping around.
184    pub fn next(&mut self) {
185        let n = self.matches().len();
186        if n == 0 {
187            return;
188        }
189        self.wanted = None;
190        self.focused = (self.focused + 1) % n;
191    }
192
193    /// Retreat focus by one step within the filtered set, wrapping around.
194    pub fn prev(&mut self) {
195        let n = self.matches().len();
196        if n == 0 {
197            return;
198        }
199        self.wanted = None;
200        self.focused = (self.focused + n - 1) % n;
201    }
202
203    /// Open the option list, remembering the option to go back to on Esc.
204    pub fn open_list(&mut self) {
205        if !self.open {
206            self.opened_at = self.focused;
207            self.window.reset();
208            self.open = true;
209        }
210    }
211
212    /// Close the list on the option it was opened with, dropping the query.
213    pub fn cancel(&mut self) {
214        self.focused = self.opened_at;
215        self.query.clear();
216        self.open = false;
217    }
218
219    /// Append a character to the type-ahead query and reset focus to 0.
220    pub fn filter_push(&mut self, c: char) {
221        self.open_list();
222        self.query.push(c);
223        self.focused = 0;
224        self.window.reset();
225    }
226
227    /// Remove the last character from the type-ahead query and reset focus to 0.
228    pub fn filter_pop(&mut self) {
229        if self.query.pop().is_none() {
230            return;
231        }
232        self.focused = if self.query.is_empty() {
233            self.opened_at
234        } else {
235            0
236        };
237        self.window.reset();
238    }
239
240    /// Close the list on the highlighted option; an unmatched query is dropped first.
241    pub fn close(&mut self) {
242        if self.matches().get(self.focused).is_none() {
243            self.query.clear();
244            self.focused = self.opened_at;
245        }
246        self.confirm();
247    }
248
249    /// Closes the list on the filtered option `index`; an index past the options changes nothing.
250    pub fn pick(&mut self, index: usize) {
251        if index < self.matches().len() {
252            self.wanted = None;
253            self.focused = index;
254            self.confirm();
255        }
256    }
257
258    /// Moves the focus a page of the open list down or up, stopping at its ends.
259    pub fn page(&mut self, down: bool) {
260        let last = self.matches().len().saturating_sub(1);
261        let page = self.window.page();
262        self.wanted = None;
263        self.focused = if down {
264            self.focused.saturating_add(page).min(last)
265        } else {
266            self.focused.saturating_sub(page)
267        };
268    }
269
270    /// Resolve the current filtered selection to the raw options index, clear
271    /// the query, and close the dropdown. Call this on SelectConfirm so the
272    /// selection survives query removal.
273    pub fn confirm(&mut self) {
274        let m = self.matches();
275        let Some(&raw_idx) = m.get(self.focused) else {
276            // Nothing matches the query — keep the filter open so the user can
277            // correct it rather than silently committing the first option.
278            return;
279        };
280        self.focused = raw_idx;
281        self.query.clear();
282        self.open = false;
283    }
284
285    /// Replace the option list, keeping the previously selected id focused if
286    /// it exists in the new list; falls back to index 0 otherwise. Clears query.
287    pub fn set_options_preserving_id(&mut self, options: Vec<SelectOption>) {
288        let current_id = self
289            .wanted
290            .take()
291            .unwrap_or_else(|| self.value().to_string());
292        self.query.clear();
293        self.options = options;
294        self.focused = self
295            .options
296            .iter()
297            .position(|o| o.id == current_id)
298            .unwrap_or(0);
299    }
300}
301
302impl Default for SelectWidget {
303    fn default() -> Self {
304        Self::new()
305    }
306}
307
308#[cfg(test)]
309#[path = "select_tests.rs"]
310mod tests;