1use std::cell::Cell;
8
9use tvui::{RowWindow, Viewport};
10
11#[derive(Debug, Clone)]
13pub struct SelectOption {
14 pub id: String,
15 pub label: String,
16}
17
18pub 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#[derive(Debug, Clone)]
33pub struct SelectWidget {
34 options: Vec<SelectOption>,
35 focused: usize,
36 pub open: bool,
37 query: String,
38 opened_at: usize,
40 wanted: Option<String>,
42 window: RowWindow,
44 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 #[must_use]
65 pub fn scroll(&self) -> &Cell<Viewport> {
66 &self.scroll
67 }
68
69 #[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 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 #[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 #[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 #[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 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 #[must_use]
152 pub fn window(&self) -> &RowWindow {
153 &self.window
154 }
155
156 #[must_use]
158 pub fn options(&self) -> &[SelectOption] {
159 &self.options
160 }
161
162 #[must_use]
164 pub fn shown(&self) -> &str {
165 match self.query() {
166 "" => self.display(),
167 query => query,
168 }
169 }
170
171 #[must_use]
173 pub fn query(&self) -> &str {
174 &self.query
175 }
176
177 #[must_use]
179 pub fn focused_in_filtered(&self) -> usize {
180 self.focused
181 }
182
183 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 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 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 pub fn cancel(&mut self) {
214 self.focused = self.opened_at;
215 self.query.clear();
216 self.open = false;
217 }
218
219 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 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 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 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 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 pub fn confirm(&mut self) {
274 let m = self.matches();
275 let Some(&raw_idx) = m.get(self.focused) else {
276 return;
279 };
280 self.focused = raw_idx;
281 self.query.clear();
282 self.open = false;
283 }
284
285 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;