1use crate::config::constants::ui;
2use crate::ui::search::{exact_terms_match, normalize_query};
3use crate::ui::tui::types::{
4 InlineEvent, InlineListItem, InlineListSearchConfig, InlineListSelection, OverlayEvent,
5 OverlayHotkey, OverlayHotkeyAction, OverlayHotkeyKey, OverlaySelectionChange,
6 OverlaySubmission, SecurePromptConfig, WizardModalMode, WizardStep,
7};
8use ratatui::crossterm::event::{KeyCode, KeyEvent};
9use ratatui::widgets::ListState;
10
11#[derive(Clone)]
12pub struct ModalState {
13 pub title: String,
14 pub lines: Vec<String>,
15 pub footer_hint: Option<String>,
16 pub hotkeys: Vec<OverlayHotkey>,
17 pub list: Option<ModalListState>,
18 pub secure_prompt: Option<SecurePromptConfig>,
19 #[allow(dead_code)]
20 pub restore_input: bool,
21 #[allow(dead_code)]
22 pub restore_cursor: bool,
23 pub search: Option<ModalSearchState>,
24}
25
26#[allow(dead_code)]
28#[derive(Clone)]
29pub struct WizardModalState {
30 pub title: String,
31 pub steps: Vec<WizardStepState>,
32 pub current_step: usize,
33 pub search: Option<ModalSearchState>,
34 pub mode: WizardModalMode,
35}
36
37#[allow(dead_code)]
39#[derive(Clone)]
40pub struct WizardStepState {
41 pub title: String,
43 pub question: String,
45 pub list: ModalListState,
47 pub completed: bool,
49 pub answer: Option<InlineListSelection>,
51 pub notes: String,
53 pub notes_active: bool,
55
56 pub allow_freeform: bool,
57 pub freeform_label: Option<String>,
58 pub freeform_placeholder: Option<String>,
59}
60
61#[derive(Debug, Clone, Copy, Default)]
62pub struct ModalKeyModifiers {
63 pub control: bool,
64 pub alt: bool,
65 pub command: bool,
66}
67
68#[derive(Debug, Clone)]
69pub enum ModalListKeyResult {
70 NotHandled,
71 HandledNoRedraw,
72 Redraw,
73 Emit(InlineEvent),
74 Submit(InlineEvent),
75 Cancel(InlineEvent),
76}
77
78#[derive(Clone)]
79pub struct ModalListState {
80 pub items: Vec<ModalListItem>,
81 pub visible_indices: Vec<usize>,
82 pub list_state: ListState,
83 pub total_selectable: usize,
84 pub filter_terms: Vec<String>,
85 pub filter_query: Option<String>,
86 pub viewport_rows: Option<u16>,
87 pub compact_rows: bool,
88 density_behavior: ModalListDensityBehavior,
89}
90
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92enum ModalListDensityBehavior {
93 Adjustable,
94 FixedComfortable,
95}
96
97const CONFIG_LIST_NAVIGATION_HINT: &str =
98 "Navigation: ↑/↓ select • Space/Enter apply • ←/→ change value • Esc close";
99
100#[derive(Clone)]
101pub struct ModalListItem {
102 pub title: String,
103 pub subtitle: Option<String>,
104 pub badge: Option<String>,
105 pub indent: u8,
106 pub selection: Option<InlineListSelection>,
107 pub search_value: Option<String>,
108 pub is_divider: bool,
109}
110
111#[derive(Clone)]
112pub struct ModalSearchState {
113 pub label: String,
114 pub placeholder: Option<String>,
115 pub query: String,
116}
117
118impl From<InlineListSearchConfig> for ModalSearchState {
119 fn from(config: InlineListSearchConfig) -> Self {
120 Self {
121 label: config.label,
122 placeholder: config.placeholder,
123 query: String::new(),
124 }
125 }
126}
127
128impl ModalSearchState {
129 pub fn insert(&mut self, value: &str) {
130 for ch in value.chars() {
131 if matches!(ch, '\n' | '\r') {
132 continue;
133 }
134 self.query.push(ch);
135 }
136 }
137
138 pub fn push_char(&mut self, ch: char) {
139 self.query.push(ch);
140 }
141
142 pub fn backspace(&mut self) -> bool {
143 if self.query.pop().is_some() {
144 return true;
145 }
146 false
147 }
148
149 pub fn clear(&mut self) -> bool {
150 if self.query.is_empty() {
151 return false;
152 }
153 self.query.clear();
154 true
155 }
156}
157
158impl ModalState {
159 pub fn hotkey_action(
160 &self,
161 key: &KeyEvent,
162 modifiers: ModalKeyModifiers,
163 ) -> Option<OverlayHotkeyAction> {
164 self.hotkeys.iter().find_map(|hotkey| match hotkey.key {
165 OverlayHotkeyKey::CtrlChar(ch)
166 if modifiers.control
167 && !modifiers.alt
168 && !modifiers.command
169 && matches!(key.code, KeyCode::Char(key_ch) if key_ch.eq_ignore_ascii_case(&ch))
170 =>
171 {
172 Some(hotkey.action.clone())
173 }
174 _ => None,
175 })
176 }
177
178 pub fn handle_list_key_event(
179 &mut self,
180 key: &KeyEvent,
181 modifiers: ModalKeyModifiers,
182 ) -> ModalListKeyResult {
183 let Some(list) = self.list.as_mut() else {
184 return ModalListKeyResult::NotHandled;
185 };
186
187 if let Some(search) = self.search.as_mut() {
188 match key.code {
189 KeyCode::Char(ch) if !modifiers.control && !modifiers.alt && !modifiers.command => {
190 let previous = list.current_selection();
191 search.push_char(ch);
192 list.apply_search(&search.query);
193 if let Some(event) = selection_change_event(list, previous) {
194 return ModalListKeyResult::Emit(event);
195 }
196 return ModalListKeyResult::Redraw;
197 }
198 KeyCode::Backspace => {
199 if search.backspace() {
200 let previous = list.current_selection();
201 list.apply_search(&search.query);
202 if let Some(event) = selection_change_event(list, previous) {
203 return ModalListKeyResult::Emit(event);
204 }
205 return ModalListKeyResult::Redraw;
206 }
207 return ModalListKeyResult::HandledNoRedraw;
208 }
209 KeyCode::Delete => {
210 if search.clear() {
211 let previous = list.current_selection();
212 list.apply_search(&search.query);
213 if let Some(event) = selection_change_event(list, previous) {
214 return ModalListKeyResult::Emit(event);
215 }
216 return ModalListKeyResult::Redraw;
217 }
218 return ModalListKeyResult::HandledNoRedraw;
219 }
220 KeyCode::Esc => {
221 if search.clear() {
222 let previous = list.current_selection();
223 list.apply_search(&search.query);
224 if let Some(event) = selection_change_event(list, previous) {
225 return ModalListKeyResult::Emit(event);
226 }
227 return ModalListKeyResult::Redraw;
228 }
229 }
230 _ => {}
231 }
232 }
233
234 let previous_selection = list.current_selection();
235 match key.code {
236 KeyCode::Char('d') | KeyCode::Char('D') if modifiers.alt => {
237 if !list.supports_density_toggle() {
238 return ModalListKeyResult::HandledNoRedraw;
239 }
240 list.toggle_row_density();
241 ModalListKeyResult::Redraw
242 }
243 KeyCode::Up => {
244 if modifiers.command {
245 list.select_first();
246 } else {
247 list.select_previous();
248 }
249 if let Some(event) = selection_change_event(list, previous_selection) {
250 ModalListKeyResult::Emit(event)
251 } else {
252 ModalListKeyResult::Redraw
253 }
254 }
255 KeyCode::Down => {
256 if modifiers.command {
257 list.select_last();
258 } else {
259 list.select_next();
260 }
261 if let Some(event) = selection_change_event(list, previous_selection) {
262 ModalListKeyResult::Emit(event)
263 } else {
264 ModalListKeyResult::Redraw
265 }
266 }
267 KeyCode::PageUp => {
268 list.page_up();
269 if let Some(event) = selection_change_event(list, previous_selection) {
270 ModalListKeyResult::Emit(event)
271 } else {
272 ModalListKeyResult::Redraw
273 }
274 }
275 KeyCode::PageDown => {
276 list.page_down();
277 if let Some(event) = selection_change_event(list, previous_selection) {
278 ModalListKeyResult::Emit(event)
279 } else {
280 ModalListKeyResult::Redraw
281 }
282 }
283 KeyCode::Home => {
284 list.select_first();
285 if let Some(event) = selection_change_event(list, previous_selection) {
286 ModalListKeyResult::Emit(event)
287 } else {
288 ModalListKeyResult::Redraw
289 }
290 }
291 KeyCode::End => {
292 list.select_last();
293 if let Some(event) = selection_change_event(list, previous_selection) {
294 ModalListKeyResult::Emit(event)
295 } else {
296 ModalListKeyResult::Redraw
297 }
298 }
299 KeyCode::Tab => {
300 if self.search.is_none() && !list.visible_indices.is_empty() {
303 list.select_first();
304 } else {
305 list.select_next();
306 }
307 if let Some(event) = selection_change_event(list, previous_selection) {
308 ModalListKeyResult::Emit(event)
309 } else {
310 ModalListKeyResult::Redraw
311 }
312 }
313 KeyCode::BackTab => {
314 list.select_previous();
315 if let Some(event) = selection_change_event(list, previous_selection) {
316 ModalListKeyResult::Emit(event)
317 } else {
318 ModalListKeyResult::Redraw
319 }
320 }
321 KeyCode::Left => {
322 if let Some(selection) = list.current_selection()
323 && let Some(adjusted) = map_config_selection_for_arrow(&selection, true)
324 {
325 return ModalListKeyResult::Submit(InlineEvent::Overlay(
326 OverlayEvent::Submitted(OverlaySubmission::Selection(adjusted)),
327 ));
328 }
329 list.select_previous();
330 if let Some(event) = selection_change_event(list, previous_selection) {
331 ModalListKeyResult::Emit(event)
332 } else {
333 ModalListKeyResult::Redraw
334 }
335 }
336 KeyCode::Right => {
337 if let Some(selection) = list.current_selection()
338 && let Some(adjusted) = map_config_selection_for_arrow(&selection, false)
339 {
340 return ModalListKeyResult::Submit(InlineEvent::Overlay(
341 OverlayEvent::Submitted(OverlaySubmission::Selection(adjusted)),
342 ));
343 }
344 list.select_next();
345 if let Some(event) = selection_change_event(list, previous_selection) {
346 ModalListKeyResult::Emit(event)
347 } else {
348 ModalListKeyResult::Redraw
349 }
350 }
351 KeyCode::Enter => {
352 if let Some(selection) = list.current_selection() {
353 ModalListKeyResult::Submit(InlineEvent::Overlay(OverlayEvent::Submitted(
354 OverlaySubmission::Selection(selection),
355 )))
356 } else {
357 ModalListKeyResult::HandledNoRedraw
358 }
359 }
360 KeyCode::Esc => {
361 ModalListKeyResult::Cancel(InlineEvent::Overlay(OverlayEvent::Cancelled))
362 }
363 KeyCode::Char(ch) if modifiers.control || modifiers.alt => match ch {
364 'n' | 'N' | 'j' | 'J' => {
365 list.select_next();
366 if let Some(event) = selection_change_event(list, previous_selection) {
367 ModalListKeyResult::Emit(event)
368 } else {
369 ModalListKeyResult::Redraw
370 }
371 }
372 'p' | 'P' | 'k' | 'K' => {
373 list.select_previous();
374 if let Some(event) = selection_change_event(list, previous_selection) {
375 ModalListKeyResult::Emit(event)
376 } else {
377 ModalListKeyResult::Redraw
378 }
379 }
380 _ => ModalListKeyResult::NotHandled,
381 },
382 _ => ModalListKeyResult::NotHandled,
383 }
384 }
385
386 pub fn handle_list_mouse_click(&mut self, visible_index: usize) -> ModalListKeyResult {
387 let Some(list) = self.list.as_mut() else {
388 return ModalListKeyResult::NotHandled;
389 };
390 let Some(&item_index) = list.visible_indices.get(visible_index) else {
391 return ModalListKeyResult::HandledNoRedraw;
392 };
393 if list
394 .items
395 .get(item_index)
396 .and_then(|item| item.selection.as_ref())
397 .is_none()
398 {
399 return ModalListKeyResult::HandledNoRedraw;
400 }
401
402 let previous_selection = list.current_selection();
403 if list.list_state.selected() == Some(visible_index) {
404 if let Some(selection) = list.current_selection() {
405 return ModalListKeyResult::Submit(InlineEvent::Overlay(OverlayEvent::Submitted(
406 OverlaySubmission::Selection(selection),
407 )));
408 }
409 return ModalListKeyResult::HandledNoRedraw;
410 }
411
412 list.list_state.select(Some(visible_index));
413 if let Some(rows) = list.viewport_rows {
414 list.ensure_visible(rows);
415 }
416 if let Some(event) = selection_change_event(list, previous_selection) {
417 ModalListKeyResult::Emit(event)
418 } else {
419 ModalListKeyResult::Redraw
420 }
421 }
422
423 pub fn handle_list_mouse_scroll(&mut self, down: bool) -> ModalListKeyResult {
424 let Some(list) = self.list.as_mut() else {
425 return ModalListKeyResult::NotHandled;
426 };
427
428 let previous_selection = list.current_selection();
429 if down {
430 list.select_next();
431 } else {
432 list.select_previous();
433 }
434
435 if let Some(event) = selection_change_event(list, previous_selection) {
436 ModalListKeyResult::Emit(event)
437 } else {
438 ModalListKeyResult::Redraw
439 }
440 }
441}
442
443fn selection_change_event(
444 list: &ModalListState,
445 previous: Option<InlineListSelection>,
446) -> Option<InlineEvent> {
447 let current = list.current_selection();
448 if current == previous {
449 return None;
450 }
451 current.map(|selection| {
452 InlineEvent::Overlay(OverlayEvent::SelectionChanged(
453 OverlaySelectionChange::List(selection),
454 ))
455 })
456}
457
458fn is_custom_note_selection(selection: &InlineListSelection) -> bool {
459 matches!(
460 selection,
461 InlineListSelection::RequestUserInputAnswer {
462 selected,
463 other,
464 ..
465 } if selected.is_empty() && other.is_some()
466 )
467}
468
469fn map_config_selection_for_arrow(
470 selection: &InlineListSelection,
471 is_left: bool,
472) -> Option<InlineListSelection> {
473 let InlineListSelection::ConfigAction(action) = selection else {
474 return None;
475 };
476
477 if action.ends_with(":cycle") {
478 if is_left {
479 let key = action.trim_end_matches(":cycle");
480 return Some(InlineListSelection::ConfigAction(format!(
481 "{}:cycle_prev",
482 key
483 )));
484 }
485 return Some(selection.clone());
486 }
487
488 if action.ends_with(":inc") {
489 if is_left {
490 let key = action.trim_end_matches(":inc");
491 return Some(InlineListSelection::ConfigAction(format!("{}:dec", key)));
492 }
493 return Some(selection.clone());
494 }
495
496 if action.ends_with(":dec") {
497 if is_left {
498 return Some(selection.clone());
499 }
500 let key = action.trim_end_matches(":dec");
501 return Some(InlineListSelection::ConfigAction(format!("{}:inc", key)));
502 }
503
504 if action.ends_with(":toggle") {
505 let _ = is_left;
506 return Some(selection.clone());
507 }
508
509 None
510}
511
512impl ModalListItem {
513 pub fn is_header(&self) -> bool {
514 self.selection.is_none() && !self.is_divider
515 }
516
517 fn matches(&self, query: &str) -> bool {
518 if query.is_empty() {
519 return true;
520 }
521 let Some(value) = self.search_value.as_ref() else {
522 return false;
523 };
524 exact_terms_match(query, value)
525 }
526}
527
528#[allow(clippy::const_is_empty)]
529pub fn is_divider_title(item: &InlineListItem) -> bool {
530 if item.selection.is_some() {
531 return false;
532 }
533 if item.indent != 0 {
534 return false;
535 }
536 if item.subtitle.is_some() || item.badge.is_some() {
537 return false;
538 }
539 let symbol = ui::INLINE_USER_MESSAGE_DIVIDER_SYMBOL;
540 if symbol.is_empty() {
541 return false;
542 }
543 item.title
544 .chars()
545 .all(|ch| symbol.chars().any(|needle| needle == ch))
546}
547
548impl ModalListState {
549 pub fn new(items: Vec<InlineListItem>, selected: Option<InlineListSelection>) -> Self {
550 let converted: Vec<ModalListItem> = items
551 .into_iter()
552 .map(|item| {
553 let is_divider = is_divider_title(&item);
554 let search_value = item
555 .search_value
556 .as_ref()
557 .map(|value| value.to_ascii_lowercase());
558 ModalListItem {
559 title: item.title,
560 subtitle: item.subtitle,
561 badge: item.badge,
562 indent: item.indent,
563 selection: item.selection,
564 search_value,
565 is_divider,
566 }
567 })
568 .collect();
569 let total_selectable = converted
570 .iter()
571 .filter(|item| item.selection.is_some())
572 .count();
573 let has_two_line_items = converted.iter().any(|item| {
574 item.subtitle
575 .as_ref()
576 .is_some_and(|subtitle| !subtitle.trim().is_empty())
577 });
578 let density_behavior = Self::density_behavior_for_items(&converted);
579 let is_model_picker_list = Self::is_model_picker_list(&converted);
580 let compact_rows =
581 Self::initial_compact_rows(density_behavior, has_two_line_items, is_model_picker_list);
582 let mut modal_state = Self {
583 visible_indices: (0..converted.len()).collect(),
584 items: converted,
585 list_state: ListState::default(),
586 total_selectable,
587 filter_terms: Vec::new(),
588 filter_query: None,
589 viewport_rows: None,
590 compact_rows,
591 density_behavior,
592 };
593 modal_state.select_initial(selected);
594 modal_state
595 }
596
597 fn density_behavior_for_items(items: &[ModalListItem]) -> ModalListDensityBehavior {
598 if items
599 .iter()
600 .any(|item| matches!(item.selection, Some(InlineListSelection::ConfigAction(_))))
601 {
602 ModalListDensityBehavior::FixedComfortable
603 } else {
604 ModalListDensityBehavior::Adjustable
605 }
606 }
607
608 fn initial_compact_rows(
609 density_behavior: ModalListDensityBehavior,
610 has_two_line_items: bool,
611 is_model_picker_list: bool,
612 ) -> bool {
613 if is_model_picker_list {
614 return false;
615 }
616 match density_behavior {
617 ModalListDensityBehavior::FixedComfortable => false,
618 ModalListDensityBehavior::Adjustable => has_two_line_items,
619 }
620 }
621
622 fn is_model_picker_list(items: &[ModalListItem]) -> bool {
623 let mut has_model_selection = false;
624 for item in items {
625 let Some(selection) = item.selection.as_ref() else {
626 continue;
627 };
628 match selection {
629 InlineListSelection::Model(_)
630 | InlineListSelection::DynamicModel(_)
631 | InlineListSelection::RefreshDynamicModels
632 | InlineListSelection::Reasoning(_)
633 | InlineListSelection::DisableReasoning
634 | InlineListSelection::CustomModel => {
635 has_model_selection = true;
636 }
637 _ => return false,
638 }
639 }
640 has_model_selection
641 }
642
643 pub fn current_selection(&self) -> Option<InlineListSelection> {
644 self.list_state
645 .selected()
646 .and_then(|index| self.visible_indices.get(index))
647 .and_then(|&item_index| self.items.get(item_index))
648 .and_then(|item| item.selection.clone())
649 }
650
651 pub fn get_best_matching_item(&self, query: &str) -> Option<String> {
652 if query.is_empty() {
653 return None;
654 }
655
656 let normalized_query = normalize_query(query);
657 self.visible_indices
658 .iter()
659 .filter_map(|&idx| self.items.get(idx))
660 .filter(|item| item.selection.is_some())
661 .filter_map(|item| item.search_value.as_ref())
662 .find(|search_value| exact_terms_match(&normalized_query, search_value))
663 .cloned()
664 }
665
666 pub fn select_previous(&mut self) {
667 if self.visible_indices.is_empty() {
668 return;
669 }
670 let Some(mut index) = self.list_state.selected() else {
671 if let Some(last) = self.last_selectable_index() {
672 self.list_state.select(Some(last));
673 }
674 return;
675 };
676
677 while index > 0 {
678 index -= 1;
679 let item_index = match self.visible_indices.get(index) {
680 Some(idx) => *idx,
681 None => {
682 tracing::warn!("visible_indices index {index} out of bounds");
683 continue;
684 }
685 };
686 if let Some(item) = self.items.get(item_index)
687 && item.selection.is_some()
688 {
689 self.list_state.select(Some(index));
690 return;
691 }
692 }
693
694 if let Some(first) = self.first_selectable_index() {
695 self.list_state.select(Some(first));
696 } else {
697 self.list_state.select(None);
698 }
699 }
700
701 pub fn select_next(&mut self) {
702 if self.visible_indices.is_empty() {
703 return;
704 }
705 let mut index = self.list_state.selected().unwrap_or(usize::MAX);
706 if index == usize::MAX {
707 if let Some(first) = self.first_selectable_index() {
708 self.list_state.select(Some(first));
709 }
710 return;
711 }
712 while index + 1 < self.visible_indices.len() {
713 index += 1;
714 let item_index = self.visible_indices[index];
715 if self.items[item_index].selection.is_some() {
716 self.list_state.select(Some(index));
717 break;
718 }
719 }
720 }
721
722 pub fn select_first(&mut self) {
723 if let Some(first) = self.first_selectable_index() {
724 self.list_state.select(Some(first));
725 } else {
726 self.list_state.select(None);
727 }
728 if let Some(rows) = self.viewport_rows {
729 self.ensure_visible(rows);
730 }
731 }
732
733 pub fn select_last(&mut self) {
734 if let Some(last) = self.last_selectable_index() {
735 self.list_state.select(Some(last));
736 } else {
737 self.list_state.select(None);
738 }
739 if let Some(rows) = self.viewport_rows {
740 self.ensure_visible(rows);
741 }
742 }
743
744 pub(crate) fn selected_is_last(&self) -> bool {
745 let Some(selected) = self.list_state.selected() else {
746 return false;
747 };
748 self.last_selectable_index()
749 .is_some_and(|last| selected == last)
750 }
751
752 pub fn select_nth_selectable(&mut self, target_index: usize) -> bool {
753 let mut count = 0usize;
754 for (visible_pos, &item_index) in self.visible_indices.iter().enumerate() {
755 if self.items[item_index].selection.is_some() {
756 if count == target_index {
757 self.list_state.select(Some(visible_pos));
758 if let Some(rows) = self.viewport_rows {
759 self.ensure_visible(rows);
760 }
761 return true;
762 }
763 count += 1;
764 }
765 }
766 false
767 }
768
769 pub fn page_up(&mut self) {
770 let step = self.page_step();
771 if step == 0 {
772 self.select_previous();
773 return;
774 }
775 for _ in 0..step {
776 let before = self.list_state.selected();
777 self.select_previous();
778 if self.list_state.selected() == before {
779 break;
780 }
781 }
782 }
783
784 pub fn page_down(&mut self) {
785 let step = self.page_step();
786 if step == 0 {
787 self.select_next();
788 return;
789 }
790 for _ in 0..step {
791 let before = self.list_state.selected();
792 self.select_next();
793 if self.list_state.selected() == before {
794 break;
795 }
796 }
797 }
798
799 pub fn set_viewport_rows(&mut self, rows: u16) {
800 self.viewport_rows = Some(rows);
801 }
802
803 pub(super) fn ensure_visible(&mut self, viewport: u16) {
804 let Some(selected) = self.list_state.selected() else {
805 return;
806 };
807 if viewport == 0 {
808 return;
809 }
810 let visible = viewport as usize;
811 let offset = self.list_state.offset();
812 if selected < offset {
813 *self.list_state.offset_mut() = selected;
814 } else if selected >= offset + visible {
815 *self.list_state.offset_mut() = selected + 1 - visible;
816 }
817 }
818
819 pub fn apply_search(&mut self, query: &str) {
820 let preferred = self.current_selection();
821 self.apply_search_with_preference(query, preferred.clone());
822 }
823
824 pub fn apply_search_with_preference(
825 &mut self,
826 query: &str,
827 preferred: Option<InlineListSelection>,
828 ) {
829 let trimmed = query.trim();
830 if trimmed.is_empty() {
831 if self.filter_query.is_none() {
832 if preferred.is_some() && self.current_selection() != preferred {
833 self.select_initial(preferred);
834 }
835 return;
836 }
837 self.visible_indices = (0..self.items.len()).collect();
838 self.filter_terms.clear();
839 self.filter_query = None;
840 self.select_initial(preferred);
841 return;
842 }
843
844 if self.filter_query.as_deref() == Some(trimmed) {
845 if preferred.is_some() && self.current_selection() != preferred {
846 self.select_initial(preferred);
847 }
848 return;
849 }
850
851 let normalized_query = normalize_query(trimmed);
852 let terms = normalized_query
853 .split_whitespace()
854 .filter(|term| !term.is_empty())
855 .map(|term| term.to_owned())
856 .collect::<Vec<_>>();
857 let mut indices = Vec::new();
858 let mut pending_divider: Option<usize> = None;
859 let mut current_header: Option<usize> = None;
860 let mut header_matches = false;
861 let mut header_included = false;
862
863 for (index, item) in self.items.iter().enumerate() {
864 if item.is_divider {
865 pending_divider = Some(index);
866 current_header = None;
867 header_matches = false;
868 header_included = false;
869 continue;
870 }
871
872 if item.is_header() {
873 current_header = Some(index);
874 header_matches = item.matches(&normalized_query);
875 header_included = false;
876 if header_matches {
877 if let Some(divider_index) = pending_divider.take() {
878 indices.push(divider_index);
879 }
880 indices.push(index);
881 header_included = true;
882 }
883 continue;
884 }
885
886 let item_matches = item.matches(&normalized_query);
887 let include_item = header_matches || item_matches;
888 if include_item {
889 if let Some(divider_index) = pending_divider.take() {
890 indices.push(divider_index);
891 }
892 if let Some(header_index) = current_header
893 && !header_included
894 {
895 indices.push(header_index);
896 header_included = true;
897 }
898 indices.push(index);
899 }
900 }
901 self.visible_indices = indices;
902 self.filter_terms = terms;
903 self.filter_query = Some(trimmed.to_owned());
904 self.select_initial(preferred);
905 }
906
907 fn select_initial(&mut self, preferred: Option<InlineListSelection>) {
908 let mut selection_index = preferred.and_then(|needle| {
909 self.visible_indices
910 .iter()
911 .position(|&idx| self.items[idx].selection.as_ref() == Some(&needle))
912 });
913
914 if selection_index.is_none() {
915 selection_index = self.first_selectable_index();
916 }
917
918 self.list_state.select(selection_index);
919 *self.list_state.offset_mut() = 0;
920 }
921
922 fn first_selectable_index(&self) -> Option<usize> {
923 self.visible_indices
924 .iter()
925 .position(|&idx| self.items[idx].selection.is_some())
926 }
927
928 fn last_selectable_index(&self) -> Option<usize> {
929 self.visible_indices
930 .iter()
931 .rposition(|&idx| self.items[idx].selection.is_some())
932 }
933
934 pub(super) fn filter_active(&self) -> bool {
935 self.filter_query
936 .as_ref()
937 .is_some_and(|value| !value.is_empty())
938 }
939
940 #[cfg(test)]
941 pub(super) fn filter_query(&self) -> Option<&str> {
942 self.filter_query.as_deref()
943 }
944
945 pub(super) fn highlight_terms(&self) -> &[String] {
946 &self.filter_terms
947 }
948
949 pub(super) fn visible_selectable_count(&self) -> usize {
950 self.visible_indices
951 .iter()
952 .filter(|&&idx| self.items[idx].selection.is_some())
953 .count()
954 }
955
956 pub(super) fn total_selectable(&self) -> usize {
957 self.total_selectable
958 }
959
960 pub(super) fn compact_rows(&self) -> bool {
961 self.compact_rows
962 }
963
964 pub(super) fn supports_density_toggle(&self) -> bool {
965 matches!(self.density_behavior, ModalListDensityBehavior::Adjustable)
966 }
967
968 pub(super) fn non_filter_summary_text(&self, footer_hint: Option<&str>) -> Option<String> {
969 if !self.has_non_filter_summary(footer_hint) {
970 return None;
971 }
972 match self.density_behavior {
973 ModalListDensityBehavior::FixedComfortable => {
974 Some(CONFIG_LIST_NAVIGATION_HINT.to_owned())
975 }
976 ModalListDensityBehavior::Adjustable => footer_hint
977 .filter(|hint| !hint.is_empty())
978 .map(ToOwned::to_owned),
979 }
980 }
981
982 pub(crate) fn summary_line_rows(&self, footer_hint: Option<&str>) -> usize {
983 if self.filter_active() || self.has_non_filter_summary(footer_hint) {
984 1
985 } else {
986 0
987 }
988 }
989
990 fn has_non_filter_summary(&self, footer_hint: Option<&str>) -> bool {
991 match self.density_behavior {
992 ModalListDensityBehavior::FixedComfortable => true,
993 ModalListDensityBehavior::Adjustable => {
994 footer_hint.is_some_and(|hint| !hint.is_empty())
995 }
996 }
997 }
998
999 pub fn toggle_row_density(&mut self) {
1000 self.compact_rows = !self.compact_rows;
1001 }
1002
1003 fn page_step(&self) -> usize {
1004 let rows = self.viewport_rows.unwrap_or(0).max(1);
1005 usize::from(rows)
1006 }
1007}
1008
1009#[allow(dead_code)]
1010impl WizardModalState {
1011 pub fn new(
1013 title: String,
1014 steps: Vec<WizardStep>,
1015 current_step: usize,
1016 search: Option<InlineListSearchConfig>,
1017 mode: WizardModalMode,
1018 ) -> Self {
1019 let step_states: Vec<WizardStepState> = steps
1020 .into_iter()
1021 .map(|step| {
1022 let notes_active = step
1023 .items
1024 .first()
1025 .and_then(|item| item.selection.as_ref())
1026 .is_some_and(|selection| match selection {
1027 InlineListSelection::RequestUserInputAnswer {
1028 selected, other, ..
1029 } => selected.is_empty() && other.is_some(),
1030 _ => false,
1031 });
1032 WizardStepState {
1033 title: step.title,
1034 question: step.question,
1035 list: ModalListState::new(step.items, step.answer.clone()),
1036 completed: step.completed,
1037 answer: step.answer,
1038 notes: String::new(),
1039 notes_active,
1040 allow_freeform: step.allow_freeform,
1041 freeform_label: step.freeform_label,
1042 freeform_placeholder: step.freeform_placeholder,
1043 }
1044 })
1045 .collect();
1046
1047 let clamped_step = if step_states.is_empty() {
1048 0
1049 } else {
1050 current_step.min(step_states.len().saturating_sub(1))
1051 };
1052
1053 Self {
1054 title,
1055 steps: step_states,
1056 current_step: clamped_step,
1057 search: search.map(ModalSearchState::from),
1058 mode,
1059 }
1060 }
1061
1062 pub fn handle_key_event(
1064 &mut self,
1065 key: &KeyEvent,
1066 modifiers: ModalKeyModifiers,
1067 ) -> ModalListKeyResult {
1068 if let Some(step) = self.steps.get_mut(self.current_step)
1069 && step.notes_active
1070 {
1071 match key.code {
1072 KeyCode::Char(ch) if !modifiers.control && !modifiers.alt && !modifiers.command => {
1073 step.notes.push(ch);
1074 return ModalListKeyResult::Redraw;
1075 }
1076 KeyCode::Backspace => {
1077 if step.notes.pop().is_some() {
1078 return ModalListKeyResult::Redraw;
1079 }
1080 return ModalListKeyResult::HandledNoRedraw;
1081 }
1082 KeyCode::Tab | KeyCode::Esc => {
1083 if !step.notes.is_empty() {
1084 step.notes.clear();
1085 }
1086 step.notes_active = false;
1087 return ModalListKeyResult::Redraw;
1088 }
1089 _ => {}
1090 }
1091 }
1092
1093 if let Some(step) = self.steps.get_mut(self.current_step)
1094 && !step.notes_active
1095 && Self::step_selected_custom_note_item_index(step).is_some()
1096 {
1097 match key.code {
1098 KeyCode::Char(ch) if !modifiers.control && !modifiers.alt && !modifiers.command => {
1099 step.notes_active = true;
1100 step.notes.push(ch);
1101 return ModalListKeyResult::Redraw;
1102 }
1103 KeyCode::Backspace => {
1104 if step.notes.pop().is_some() {
1105 step.notes_active = true;
1106 return ModalListKeyResult::Redraw;
1107 }
1108 }
1109 _ => {}
1110 }
1111 }
1112
1113 if let Some(search) = self.search.as_mut()
1115 && let Some(step) = self.steps.get_mut(self.current_step)
1116 {
1117 match key.code {
1118 KeyCode::Char(ch) if !modifiers.control && !modifiers.alt && !modifiers.command => {
1119 search.push_char(ch);
1120 step.list.apply_search(&search.query);
1121 return ModalListKeyResult::Redraw;
1122 }
1123 KeyCode::Backspace => {
1124 if search.backspace() {
1125 step.list.apply_search(&search.query);
1126 return ModalListKeyResult::Redraw;
1127 }
1128 return ModalListKeyResult::HandledNoRedraw;
1129 }
1130 KeyCode::Delete => {
1131 if search.clear() {
1132 step.list.apply_search(&search.query);
1133 return ModalListKeyResult::Redraw;
1134 }
1135 return ModalListKeyResult::HandledNoRedraw;
1136 }
1137 KeyCode::Tab => {
1138 if let Some(best_match) = step.list.get_best_matching_item(&search.query) {
1139 search.query = best_match;
1140 step.list.apply_search(&search.query);
1141 return ModalListKeyResult::Redraw;
1142 }
1143 return ModalListKeyResult::HandledNoRedraw;
1144 }
1145 KeyCode::Esc => {
1146 if search.clear() {
1147 step.list.apply_search(&search.query);
1148 return ModalListKeyResult::Redraw;
1149 }
1150 }
1151 _ => {}
1152 }
1153 }
1154
1155 if self.mode == WizardModalMode::MultiStep
1156 && !modifiers.control
1157 && !modifiers.alt
1158 && !modifiers.command
1159 && self.search.is_none()
1160 && let KeyCode::Char(ch) = key.code
1161 && ch.is_ascii_digit()
1162 && ch != '0'
1163 {
1164 let target_index = ch.to_digit(10).unwrap_or(1).saturating_sub(1) as usize;
1165 if let Some(step) = self.steps.get_mut(self.current_step)
1166 && step.list.select_nth_selectable(target_index)
1167 {
1168 return self.submit_current_selection();
1169 }
1170 return ModalListKeyResult::HandledNoRedraw;
1171 }
1172
1173 match key.code {
1174 KeyCode::Char('n') | KeyCode::Char('N')
1175 if modifiers.control && self.mode == WizardModalMode::MultiStep =>
1176 {
1177 if self.current_step < self.steps.len().saturating_sub(1) {
1178 self.current_step += 1;
1179 ModalListKeyResult::Redraw
1180 } else {
1181 ModalListKeyResult::HandledNoRedraw
1182 }
1183 }
1184 KeyCode::Left => {
1186 if self.current_step > 0 {
1187 self.current_step -= 1;
1188 ModalListKeyResult::Redraw
1189 } else {
1190 ModalListKeyResult::HandledNoRedraw
1191 }
1192 }
1193 KeyCode::Right => {
1195 let can_advance = match self.mode {
1196 WizardModalMode::MultiStep => self.current_step_completed(),
1197 WizardModalMode::TabbedList => true,
1198 };
1199
1200 if can_advance && self.current_step < self.steps.len().saturating_sub(1) {
1201 self.current_step += 1;
1202 ModalListKeyResult::Redraw
1203 } else {
1204 ModalListKeyResult::HandledNoRedraw
1205 }
1206 }
1207 KeyCode::Enter => self.submit_current_selection(),
1209 KeyCode::Esc => {
1211 ModalListKeyResult::Cancel(InlineEvent::Overlay(OverlayEvent::Cancelled))
1212 }
1213 KeyCode::Up | KeyCode::Down | KeyCode::Tab | KeyCode::BackTab => {
1215 if let Some(step) = self.steps.get_mut(self.current_step) {
1216 match key.code {
1217 KeyCode::Up => {
1218 if modifiers.command {
1219 step.list.select_first();
1220 } else {
1221 step.list.select_previous();
1222 }
1223 ModalListKeyResult::Redraw
1224 }
1225 KeyCode::Down => {
1226 if modifiers.command {
1227 step.list.select_last();
1228 } else {
1229 step.list.select_next();
1230 }
1231 ModalListKeyResult::Redraw
1232 }
1233 KeyCode::Tab => {
1234 if self.search.is_none()
1235 && (step.allow_freeform
1236 || Self::step_selected_custom_note_item_index(step).is_some())
1237 {
1238 step.notes_active = !step.notes_active;
1239 ModalListKeyResult::Redraw
1240 } else {
1241 step.list.select_next();
1242 ModalListKeyResult::Redraw
1243 }
1244 }
1245 KeyCode::BackTab => {
1246 step.list.select_previous();
1247 ModalListKeyResult::Redraw
1248 }
1249 _ => ModalListKeyResult::NotHandled,
1250 }
1251 } else {
1252 ModalListKeyResult::NotHandled
1253 }
1254 }
1255 _ => ModalListKeyResult::NotHandled,
1256 }
1257 }
1258
1259 pub fn handle_mouse_click(&mut self, visible_index: usize) -> ModalListKeyResult {
1260 let submit_after_click = {
1261 let Some(step) = self.steps.get_mut(self.current_step) else {
1262 return ModalListKeyResult::NotHandled;
1263 };
1264 let Some(&item_index) = step.list.visible_indices.get(visible_index) else {
1265 return ModalListKeyResult::HandledNoRedraw;
1266 };
1267 let Some(item) = step.list.items.get(item_index) else {
1268 return ModalListKeyResult::HandledNoRedraw;
1269 };
1270 let Some(selection) = item.selection.as_ref() else {
1271 return ModalListKeyResult::HandledNoRedraw;
1272 };
1273
1274 let clicked_custom_note = is_custom_note_selection(selection);
1275
1276 if self.mode == WizardModalMode::TabbedList {
1277 step.list.list_state.select(Some(visible_index));
1278 if let Some(rows) = step.list.viewport_rows {
1279 step.list.ensure_visible(rows);
1280 }
1281
1282 if clicked_custom_note && step.notes.trim().is_empty() {
1283 step.notes_active = true;
1284 return ModalListKeyResult::Redraw;
1285 }
1286
1287 true
1288 } else {
1289 if step.list.list_state.selected() == Some(visible_index) {
1290 return ModalListKeyResult::Submit(InlineEvent::Overlay(
1291 OverlayEvent::Submitted(OverlaySubmission::Selection(selection.clone())),
1292 ));
1293 }
1294
1295 step.list.list_state.select(Some(visible_index));
1296 if let Some(rows) = step.list.viewport_rows {
1297 step.list.ensure_visible(rows);
1298 }
1299 return ModalListKeyResult::Redraw;
1300 }
1301 };
1302
1303 if submit_after_click {
1304 return self.submit_current_selection();
1305 }
1306
1307 ModalListKeyResult::Redraw
1308 }
1309
1310 pub fn handle_mouse_scroll(&mut self, down: bool) -> ModalListKeyResult {
1311 let Some(step) = self.steps.get_mut(self.current_step) else {
1312 return ModalListKeyResult::NotHandled;
1313 };
1314
1315 let before = step.list.list_state.selected();
1316 if down {
1317 step.list.select_next();
1318 } else {
1319 step.list.select_previous();
1320 }
1321
1322 if step.list.list_state.selected() == before {
1323 ModalListKeyResult::HandledNoRedraw
1324 } else {
1325 ModalListKeyResult::Redraw
1326 }
1327 }
1328
1329 fn current_selection(&self) -> Option<InlineListSelection> {
1331 self.steps
1332 .get(self.current_step)
1333 .and_then(|step| {
1334 step.list
1335 .current_selection()
1336 .map(|selection| (selection, step))
1337 })
1338 .map(|(selection, step)| match selection {
1339 InlineListSelection::RequestUserInputAnswer {
1340 question_id,
1341 selected,
1342 other,
1343 } => {
1344 let notes = step.notes.trim();
1345 let next_other = if other.is_some() {
1346 Some(notes.to_string())
1347 } else if notes.is_empty() {
1348 None
1349 } else {
1350 Some(notes.to_string())
1351 };
1352 InlineListSelection::RequestUserInputAnswer {
1353 question_id,
1354 selected,
1355 other: next_other,
1356 }
1357 }
1358 InlineListSelection::AskUserChoice {
1359 tab_id, choice_id, ..
1360 } => {
1361 let notes = step.notes.trim();
1362 let text = if notes.is_empty() {
1363 None
1364 } else {
1365 Some(notes.to_string())
1366 };
1367 InlineListSelection::AskUserChoice {
1368 tab_id,
1369 choice_id,
1370 text,
1371 }
1372 }
1373 _ => selection,
1374 })
1375 }
1376
1377 fn current_step_completed(&self) -> bool {
1379 self.steps
1380 .get(self.current_step)
1381 .is_some_and(|step| step.completed)
1382 }
1383
1384 fn step_selected_custom_note_item_index(step: &WizardStepState) -> Option<usize> {
1385 let selected_visible = step.list.list_state.selected()?;
1386 let item_index = *step.list.visible_indices.get(selected_visible)?;
1387 let item = step.list.items.get(item_index)?;
1388 item.selection
1389 .as_ref()
1390 .filter(|selection| is_custom_note_selection(selection))
1391 .map(|_| item_index)
1392 }
1393
1394 fn current_step_selected_custom_note_item_index(&self) -> Option<usize> {
1395 self.steps
1396 .get(self.current_step)
1397 .and_then(Self::step_selected_custom_note_item_index)
1398 }
1399
1400 fn current_step_requires_custom_note_input(&self) -> bool {
1401 self.current_step_selected_custom_note_item_index()
1402 .is_some()
1403 }
1404
1405 fn current_step_supports_notes(&self) -> bool {
1406 self.steps
1407 .get(self.current_step)
1408 .and_then(|step| step.list.current_selection())
1409 .is_some_and(|selection| {
1410 matches!(
1411 selection,
1412 InlineListSelection::RequestUserInputAnswer { .. }
1413 | InlineListSelection::AskUserChoice { .. }
1414 )
1415 })
1416 }
1417
1418 pub fn unanswered_count(&self) -> usize {
1419 self.steps.iter().filter(|step| !step.completed).count()
1420 }
1421
1422 pub fn question_header(&self) -> String {
1423 format!(
1424 "Question {}/{} ({} unanswered)",
1425 self.current_step.saturating_add(1),
1426 self.steps.len(),
1427 self.unanswered_count()
1428 )
1429 }
1430
1431 pub fn notes_line(&self) -> Option<String> {
1432 let step = self.steps.get(self.current_step)?;
1433 if step.notes_active || !step.notes.is_empty() {
1434 let label = step.freeform_label.as_deref().unwrap_or("›");
1435 if step.notes.is_empty()
1436 && let Some(placeholder) = step.freeform_placeholder.as_ref()
1437 {
1438 return Some(format!("{} {}", label, placeholder));
1439 }
1440 Some(format!("{} {}", label, step.notes))
1441 } else {
1442 None
1443 }
1444 }
1445
1446 pub fn notes_active(&self) -> bool {
1447 self.steps
1448 .get(self.current_step)
1449 .is_some_and(|step| step.notes_active)
1450 }
1451
1452 pub fn instruction_lines(&self) -> Vec<String> {
1453 let step = match self.steps.get(self.current_step) {
1454 Some(s) => s,
1455 None => return Vec::new(),
1456 };
1457 let custom_note_selected = self.current_step_requires_custom_note_input();
1458
1459 if self.notes_active() {
1460 if custom_note_selected {
1461 vec!["type custom note | enter to continue | esc to clear".to_string()]
1462 } else {
1463 vec!["tab or esc to clear notes | enter to submit answer".to_string()]
1464 }
1465 } else {
1466 let mut lines = Vec::new();
1467 if custom_note_selected {
1468 lines.push("type custom note | enter to continue".to_string());
1469 } else if step.allow_freeform {
1470 lines.push("tab to add notes | enter to submit answer".to_string());
1471 } else {
1472 lines.push("enter to submit answer".to_string());
1473 }
1474 lines.push("ctrl + n next question | esc to interrupt".to_string());
1475 lines
1476 }
1477 }
1478
1479 fn complete_current_step(&mut self, answer: InlineListSelection) {
1481 if let Some(step) = self.steps.get_mut(self.current_step) {
1482 step.completed = true;
1483 step.answer = Some(answer);
1484 }
1485 }
1486
1487 fn collect_answers(&self) -> Vec<InlineListSelection> {
1489 self.steps
1490 .iter()
1491 .filter_map(|step| step.answer.clone())
1492 .collect()
1493 }
1494
1495 fn submit_current_selection(&mut self) -> ModalListKeyResult {
1496 if self.current_step_requires_custom_note_input()
1497 && let Some(step) = self.steps.get_mut(self.current_step)
1498 && step.notes.trim().is_empty()
1499 {
1500 step.notes_active = true;
1501 return ModalListKeyResult::Redraw;
1502 }
1503
1504 let Some(selection) = self.current_selection() else {
1505 return ModalListKeyResult::HandledNoRedraw;
1506 };
1507
1508 match self.mode {
1509 WizardModalMode::TabbedList => ModalListKeyResult::Submit(InlineEvent::Overlay(
1510 OverlayEvent::Submitted(OverlaySubmission::Wizard(vec![selection])),
1511 )),
1512 WizardModalMode::MultiStep => {
1513 self.complete_current_step(selection.clone());
1514 if self.current_step < self.steps.len().saturating_sub(1) {
1515 self.current_step += 1;
1516 ModalListKeyResult::Redraw
1517 } else {
1518 ModalListKeyResult::Submit(InlineEvent::Overlay(OverlayEvent::Submitted(
1519 OverlaySubmission::Wizard(self.collect_answers()),
1520 )))
1521 }
1522 }
1523 }
1524 }
1525
1526 pub fn all_steps_completed(&self) -> bool {
1528 self.steps.iter().all(|step| step.completed)
1529 }
1530}