返回 CodeWhale
controller.rs
根目录 / crates / tui / src / tui / settings_picker / controller.rs
1 //! Stable filter/index ownership for transactional settings pickers.
2 //!
3 //! The controller owns the option catalog, search query, tab filter, and the
4 //! mapping from visible row → source index. Callers never re-filter ad hoc
5 //! during render; they read [`SettingsPickerController::visible`] instead.
6
7 use super::option::SettingOption;
8
9 /// Outcome of a navigation or commit attempt.
10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11 pub enum PickerNavResult {
12 /// Selection changed; host should run preview.
13 Preview,
14 /// Enter on an available option; host should commit.
15 Commit,
16 /// Esc / explicit cancel; host should rollback then close.
17 Cancel,
18 /// Secondary action on the focused row.
19 ItemAction,
20 /// No-op (disabled row, empty list, unrecognized key).
21 None,
22 }
23
24 /// Tab + search + selection state with stable filtered indices.
25 #[derive(Debug, Clone)]
26 pub struct SettingsPickerController {
27 options: Vec<SettingOption>,
28 tabs: Vec<String>,
29 active_tab: usize,
30 query: String,
31 /// Indices into `options` that pass the current tab + search filter.
32 filtered: Vec<usize>,
33 /// Index into `filtered` (not into `options`).
34 selected_visible: usize,
35 /// Snapshot of the selection id when the picker opened (for rollback).
36 original_id: String,
37 }
38
39 impl SettingsPickerController {
40 #[must_use]
41 pub fn new(options: Vec<SettingOption>, original_id: impl Into<String>) -> Self {
42 let mut tabs = vec!["all".to_string()];
43 for option in &options {
44 let tab = option.tab.as_ref();
45 if tab != "all" && !tabs.iter().any(|existing| existing == tab) {
46 tabs.push(tab.to_string());
47 }
48 }
49 let mut controller = Self {
50 options,
51 tabs,
52 active_tab: 0,
53 query: String::new(),
54 filtered: Vec::new(),
55 selected_visible: 0,
56 original_id: original_id.into(),
57 };
58 controller.recompute_filter(None);
59 // Prefer landing on the original id when it exists.
60 if !controller.original_id.is_empty() {
61 let original = controller.original_id.clone();
62 controller.recompute_filter(Some(&original));
63 }
64 controller
65 }
66
67 #[must_use]
68 pub fn options(&self) -> &[SettingOption] {
69 &self.options
70 }
71
72 #[must_use]
73 #[cfg(test)]
74 pub fn tabs(&self) -> &[String] {
75 &self.tabs
76 }
77
78 #[must_use]
79 #[cfg(test)]
80 pub fn active_tab(&self) -> usize {
81 self.active_tab
82 }
83
84 #[must_use]
85 pub fn active_tab_name(&self) -> &str {
86 self.tabs
87 .get(self.active_tab)
88 .map(String::as_str)
89 .unwrap_or("all")
90 }
91
92 #[must_use]
93 #[cfg(test)]
94 pub fn query(&self) -> &str {
95 &self.query
96 }
97
98 #[must_use]
99 #[cfg(test)]
100 pub fn original_id(&self) -> &str {
101 &self.original_id
102 }
103
104 /// Visible source indices after tab + search filtering.
105 #[must_use]
106 pub fn visible(&self) -> &[usize] {
107 &self.filtered
108 }
109
110 #[cfg(test)]
111 #[must_use]
112 pub fn tab_match_counts(&self) -> Vec<(String, usize)> {
113 let query = self.query.to_ascii_lowercase();
114 let matches = |option: &SettingOption| {
115 query.is_empty()
116 || option.id.to_ascii_lowercase().contains(&query)
117 || option.label.to_ascii_lowercase().contains(&query)
118 || option.summary.to_ascii_lowercase().contains(&query)
119 || option.detail.to_ascii_lowercase().contains(&query)
120 };
121 self.tabs
122 .iter()
123 .map(|tab| {
124 let count = self
125 .options
126 .iter()
127 .filter(|option| {
128 (tab == "all" || option.tab.as_ref() == tab) && matches(option)
129 })
130 .count();
131 (tab.clone(), count)
132 })
133 .collect()
134 }
135
136 #[must_use]
137 pub fn selected_visible(&self) -> usize {
138 self.selected_visible
139 }
140
141 #[must_use]
142 pub fn selected_source_index(&self) -> Option<usize> {
143 self.filtered.get(self.selected_visible).copied()
144 }
145
146 #[must_use]
147 pub fn selected_option(&self) -> Option<&SettingOption> {
148 self.selected_source_index()
149 .and_then(|idx| self.options.get(idx))
150 }
151
152 #[must_use]
153 pub fn selected_id(&self) -> Option<&str> {
154 self.selected_option().map(|option| option.id.as_ref())
155 }
156
157 /// Recompute the filtered index list, optionally preserving a source id.
158 ///
159 /// A non-empty search query searches across every tab so operators are not
160 /// trapped inside the active tab while typing.
161 pub fn recompute_filter(&mut self, prefer_source_id: Option<&str>) {
162 let tab = self.active_tab_name().to_string();
163 let query = self.query.to_ascii_lowercase();
164 let search_all_tabs = !query.is_empty();
165 self.filtered = self
166 .options
167 .iter()
168 .enumerate()
169 .filter(|(_, option)| {
170 (search_all_tabs || tab == "all" || option.tab.as_ref() == tab)
171 && (query.is_empty()
172 || option.id.to_ascii_lowercase().contains(&query)
173 || option.label.to_ascii_lowercase().contains(&query)
174 || option.summary.to_ascii_lowercase().contains(&query)
175 || option.detail.to_ascii_lowercase().contains(&query))
176 })
177 .map(|(idx, _)| idx)
178 .collect();
179
180 if let Some(id) = prefer_source_id
181 && let Some(visible) = self.filtered.iter().position(|&source| {
182 self.options
183 .get(source)
184 .is_some_and(|o| o.id.as_ref() == id)
185 })
186 {
187 self.selected_visible = visible;
188 return;
189 }
190
191 if self.filtered.is_empty() {
192 self.selected_visible = 0;
193 } else {
194 self.selected_visible = self
195 .selected_visible
196 .min(self.filtered.len().saturating_sub(1));
197 }
198 }
199
200 #[cfg(test)]
201 pub fn set_query(&mut self, query: impl Into<String>) {
202 let keep = self.selected_id().map(str::to_string);
203 self.query = query.into();
204 self.recompute_filter(keep.as_deref());
205 }
206
207 pub fn push_query_char(&mut self, ch: char) {
208 let keep = self.selected_id().map(str::to_string);
209 self.query.push(ch);
210 self.recompute_filter(keep.as_deref());
211 }
212
213 pub fn pop_query_char(&mut self) {
214 let keep = self.selected_id().map(str::to_string);
215 self.query.pop();
216 self.recompute_filter(keep.as_deref());
217 }
218
219 pub fn clear_query(&mut self) {
220 let keep = self.selected_id().map(str::to_string);
221 self.query.clear();
222 self.recompute_filter(keep.as_deref());
223 }
224
225 pub fn set_active_tab(&mut self, tab_idx: usize) {
226 if tab_idx >= self.tabs.len() {
227 return;
228 }
229 let keep = self.selected_id().map(str::to_string);
230 self.active_tab = tab_idx;
231 self.recompute_filter(keep.as_deref());
232 }
233
234 /// Switch to the next tab. Previews the row it lands on only when that
235 /// row is available — a disabled row is shown, never previewed.
236 pub fn next_tab(&mut self) -> PickerNavResult {
237 if self.tabs.is_empty() {
238 return PickerNavResult::None;
239 }
240 let next = (self.active_tab + 1) % self.tabs.len();
241 self.set_active_tab(next);
242 self.preview_if_available()
243 }
244
245 /// Switch to the previous tab; same preview rule as [`Self::next_tab`].
246 pub fn prev_tab(&mut self) -> PickerNavResult {
247 if self.tabs.is_empty() {
248 return PickerNavResult::None;
249 }
250 let prev = (self.active_tab + self.tabs.len() - 1) % self.tabs.len();
251 self.set_active_tab(prev);
252 self.preview_if_available()
253 }
254
255 /// Select by source index when that option is currently visible.
256 pub fn select_source_index(&mut self, source: usize) -> PickerNavResult {
257 let Some(visible) = self.filtered.iter().position(|&idx| idx == source) else {
258 return PickerNavResult::None;
259 };
260 self.selected_visible = visible;
261 if self
262 .selected_option()
263 .is_some_and(|o| o.availability.is_available())
264 {
265 PickerNavResult::Preview
266 } else {
267 PickerNavResult::None
268 }
269 }
270
271 pub fn move_up(&mut self) -> PickerNavResult {
272 if self.filtered.is_empty() {
273 return PickerNavResult::None;
274 }
275 self.selected_visible =
276 (self.selected_visible + self.filtered.len() - 1) % self.filtered.len();
277 self.preview_if_available()
278 }
279
280 pub fn move_down(&mut self) -> PickerNavResult {
281 if self.filtered.is_empty() {
282 return PickerNavResult::None;
283 }
284 self.selected_visible = (self.selected_visible + 1) % self.filtered.len();
285 self.preview_if_available()
286 }
287
288 pub fn jump_home(&mut self) -> PickerNavResult {
289 if self.filtered.is_empty() {
290 return PickerNavResult::None;
291 }
292 self.selected_visible = 0;
293 self.preview_if_available()
294 }
295
296 pub fn jump_end(&mut self) -> PickerNavResult {
297 if self.filtered.is_empty() {
298 return PickerNavResult::None;
299 }
300 self.selected_visible = self.filtered.len().saturating_sub(1);
301 self.preview_if_available()
302 }
303
304 /// 1-indexed digit jump into the *visible* list.
305 pub fn jump_digit(&mut self, digit: u8) -> PickerNavResult {
306 if !(1..=9).contains(&digit) || self.filtered.is_empty() {
307 return PickerNavResult::None;
308 }
309 let idx = usize::from(digit - 1);
310 if idx >= self.filtered.len() {
311 return PickerNavResult::None;
312 }
313 self.selected_visible = idx;
314 self.preview_if_available()
315 }
316
317 pub fn request_commit(&self) -> PickerNavResult {
318 match self.selected_option() {
319 Some(option) if option.availability.is_available() => PickerNavResult::Commit,
320 _ => PickerNavResult::None,
321 }
322 }
323
324 pub fn request_cancel(&self) -> PickerNavResult {
325 PickerNavResult::Cancel
326 }
327
328 pub fn request_item_action(&self) -> PickerNavResult {
329 match self.selected_option() {
330 Some(option) if option.action.is_some() && option.availability.is_available() => {
331 PickerNavResult::ItemAction
332 }
333 _ => PickerNavResult::None,
334 }
335 }
336
337 fn preview_if_available(&self) -> PickerNavResult {
338 match self.selected_option() {
339 Some(option) if option.availability.is_available() => PickerNavResult::Preview,
340 _ => PickerNavResult::None,
341 }
342 }
343 }
344
344 lines RUST