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

            
7
use std::cell::Cell;
8

            
9
use tvui::{RowWindow, Viewport};
10

            
11
/// A single entry in a [`SelectWidget`] option list.
12
#[derive(Debug, Clone)]
13
pub struct SelectOption {
14
    pub id: String,
15
    pub label: String,
16
}
17

            
18
/// `options` led by `(none)`, which keeps an unchosen select empty.
19
1058
pub fn with_none(options: Vec<SelectOption>) -> Vec<SelectOption> {
20
1058
    let none = SelectOption {
21
1058
        id: String::new(),
22
1058
        label: "(none)".to_string(),
23
1058
    };
24
1058
    std::iter::once(none).chain(options).collect()
25
1058
}
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)]
33
pub 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

            
48
impl SelectWidget {
49
    #[must_use]
50
3597
    pub fn new() -> Self {
51
3597
        Self {
52
3597
            options: Vec::new(),
53
3597
            focused: 0,
54
3597
            open: false,
55
3597
            query: String::new(),
56
3597
            opened_at: 0,
57
3597
            wanted: None,
58
3597
            window: RowWindow::default(),
59
3597
            scroll: Cell::default(),
60
3597
        }
61
3597
    }
62

            
63
    /// The cell the draw of the field showing this select keeps its scroll in.
64
    #[must_use]
65
1741
    pub fn scroll(&self) -> &Cell<Viewport> {
66
1741
        &self.scroll
67
1741
    }
68

            
69
    /// A select over a choice field's `(id, label)` options, on `default` when given.
70
    #[must_use]
71
357
    pub fn choice(options: &[(&str, &str)], default: Option<&str>) -> Self {
72
357
        let mut select = Self::new();
73
357
        select.set_options(
74
357
            options
75
357
                .iter()
76
                .map(|&(id, label)| SelectOption {
77
1048
                    id: id.to_string(),
78
1048
                    label: label.to_string(),
79
1048
                })
80
                .collect(),
81
        );
82
357
        if let Some(default) = default {
83
261
            select.select_id(default);
84
96
        }
85
357
        select
86
357
    }
87

            
88
    /// Replace the option list, focus the option chosen earlier by id (else
89
    /// the first), and clear any query.
90
4086
    pub fn set_options(&mut self, options: Vec<SelectOption>) {
91
4086
        self.options = options;
92
4086
        self.focused = 0;
93
4086
        self.query.clear();
94
4086
        if let Some(id) = self.wanted.take() {
95
28
            self.select_id(&id);
96
4058
        }
97
4086
    }
98

            
99
    /// Indices into `options` whose label contains `query` case-insensitively.
100
    /// An empty query returns all indices.
101
    #[must_use]
102
11770
    pub fn matches(&self) -> Vec<usize> {
103
11770
        if self.query.is_empty() {
104
11698
            return (0..self.options.len()).collect();
105
72
        }
106
72
        let q = self.query.to_lowercase();
107
72
        self.options
108
72
            .iter()
109
72
            .enumerate()
110
237
            .filter(|(_, o)| o.label.to_lowercase().contains(&q))
111
            .map(|(i, _)| i)
112
            .collect()
113
11770
    }
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
9607
    pub fn value(&self) -> &str {
119
9607
        if let Some(wanted) = self.wanted.as_deref().filter(|_| self.options.is_empty()) {
120
23
            return wanted;
121
9584
        }
122
9584
        let m = self.matches();
123
9584
        m.get(self.focused)
124
8312
            .map(|&idx| self.options[idx].id.as_str())
125
9584
            .unwrap_or("")
126
9607
    }
127

            
128
    /// The display label of the focused filtered option, or `""` when no match.
129
    #[must_use]
130
1810
    pub fn display(&self) -> &str {
131
1810
        let m = self.matches();
132
1810
        m.get(self.focused)
133
1414
            .map(|&idx| self.options[idx].label.as_str())
134
1810
            .unwrap_or("")
135
1810
    }
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
1707
    pub fn select_id(&mut self, id: &str) {
140
2182
        match self.options.iter().position(|o| o.id == id) {
141
            Some(idx) => {
142
1664
                self.query.clear();
143
1664
                self.focused = idx;
144
1664
                self.wanted = None;
145
            }
146
43
            None => self.wanted = Some(id.to_string()),
147
        }
148
1707
    }
149

            
150
    /// Where the open list's window starts, written by the draw.
151
    #[must_use]
152
79
    pub fn window(&self) -> &RowWindow {
153
79
        &self.window
154
79
    }
155

            
156
    /// The raw option list, for rendering.
157
    #[must_use]
158
1728
    pub fn options(&self) -> &[SelectOption] {
159
1728
        &self.options
160
1728
    }
161

            
162
    /// The typed filter while there is one, else the selected label.
163
    #[must_use]
164
1741
    pub fn shown(&self) -> &str {
165
1741
        match self.query() {
166
1725
            "" => self.display(),
167
16
            query => query,
168
        }
169
1741
    }
170

            
171
    /// The active type-ahead query string.
172
    #[must_use]
173
5113
    pub fn query(&self) -> &str {
174
5113
        &self.query
175
5113
    }
176

            
177
    /// Index of the focused entry within the filtered set (i.e. `matches()`).
178
    #[must_use]
179
138
    pub fn focused_in_filtered(&self) -> usize {
180
138
        self.focused
181
138
    }
182

            
183
    /// Advance focus by one step within the filtered set, wrapping around.
184
175
    pub fn next(&mut self) {
185
175
        let n = self.matches().len();
186
175
        if n == 0 {
187
3
            return;
188
172
        }
189
172
        self.wanted = None;
190
172
        self.focused = (self.focused + 1) % n;
191
175
    }
192

            
193
    /// Retreat focus by one step within the filtered set, wrapping around.
194
26
    pub fn prev(&mut self) {
195
26
        let n = self.matches().len();
196
26
        if n == 0 {
197
3
            return;
198
23
        }
199
23
        self.wanted = None;
200
23
        self.focused = (self.focused + n - 1) % n;
201
26
    }
202

            
203
    /// Open the option list, remembering the option to go back to on Esc.
204
602
    pub fn open_list(&mut self) {
205
602
        if !self.open {
206
181
            self.opened_at = self.focused;
207
181
            self.window.reset();
208
181
            self.open = true;
209
421
        }
210
602
    }
211

            
212
    /// Close the list on the option it was opened with, dropping the query.
213
21
    pub fn cancel(&mut self) {
214
21
        self.focused = self.opened_at;
215
21
        self.query.clear();
216
21
        self.open = false;
217
21
    }
218

            
219
    /// Append a character to the type-ahead query and reset focus to 0.
220
452
    pub fn filter_push(&mut self, c: char) {
221
452
        self.open_list();
222
452
        self.query.push(c);
223
452
        self.focused = 0;
224
452
        self.window.reset();
225
452
    }
226

            
227
    /// Remove the last character from the type-ahead query and reset focus to 0.
228
12
    pub fn filter_pop(&mut self) {
229
12
        if self.query.pop().is_none() {
230
6
            return;
231
6
        }
232
6
        self.focused = if self.query.is_empty() {
233
5
            self.opened_at
234
        } else {
235
1
            0
236
        };
237
6
        self.window.reset();
238
12
    }
239

            
240
    /// Close the list on the highlighted option; an unmatched query is dropped first.
241
1
    pub fn close(&mut self) {
242
1
        if self.matches().get(self.focused).is_none() {
243
            self.query.clear();
244
            self.focused = self.opened_at;
245
1
        }
246
1
        self.confirm();
247
1
    }
248

            
249
    /// Closes the list on the filtered option `index`; an index past the options changes nothing.
250
5
    pub fn pick(&mut self, index: usize) {
251
5
        if index < self.matches().len() {
252
4
            self.wanted = None;
253
4
            self.focused = index;
254
4
            self.confirm();
255
1
        }
256
5
    }
257

            
258
    /// Moves the focus a page of the open list down or up, stopping at its ends.
259
28
    pub fn page(&mut self, down: bool) {
260
28
        let last = self.matches().len().saturating_sub(1);
261
28
        let page = self.window.page();
262
28
        self.wanted = None;
263
28
        self.focused = if down {
264
18
            self.focused.saturating_add(page).min(last)
265
        } else {
266
10
            self.focused.saturating_sub(page)
267
        };
268
28
    }
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
58
    pub fn confirm(&mut self) {
274
58
        let m = self.matches();
275
58
        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
1
            return;
279
        };
280
57
        self.focused = raw_idx;
281
57
        self.query.clear();
282
57
        self.open = false;
283
58
    }
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
979
    pub fn set_options_preserving_id(&mut self, options: Vec<SelectOption>) {
288
979
        let current_id = self
289
979
            .wanted
290
979
            .take()
291
976
            .unwrap_or_else(|| self.value().to_string());
292
979
        self.query.clear();
293
979
        self.options = options;
294
979
        self.focused = self
295
979
            .options
296
979
            .iter()
297
2306
            .position(|o| o.id == current_id)
298
979
            .unwrap_or(0);
299
979
    }
300
}
301

            
302
impl Default for SelectWidget {
303
    fn default() -> Self {
304
        Self::new()
305
    }
306
}
307

            
308
#[cfg(test)]
309
#[path = "select_tests.rs"]
310
mod tests;