Skip to main content

vtcode_tui/core_tui/session/modal/
state.rs

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/// State for a multi-step wizard modal with tabs for navigation
27#[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/// State for a single wizard step
38#[allow(dead_code)]
39#[derive(Clone)]
40pub struct WizardStepState {
41    /// Title displayed in the tab header
42    pub title: String,
43    /// Question or instruction shown above the list
44    pub question: String,
45    /// List state for selectable items
46    pub list: ModalListState,
47    /// Whether this step has been completed
48    pub completed: bool,
49    /// The selected answer for this step
50    pub answer: Option<InlineListSelection>,
51    /// Optional notes for the current step (free text)
52    pub notes: String,
53    /// Whether notes input is active for the current step
54    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                // With no search active, Tab moves to first item for autocomplete behavior
301                // If search is active, we already handled it above
302                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 map_config_selection_for_arrow(
459    selection: &InlineListSelection,
460    is_left: bool,
461) -> Option<InlineListSelection> {
462    let InlineListSelection::ConfigAction(action) = selection else {
463        return None;
464    };
465
466    if action.ends_with(":cycle") {
467        if is_left {
468            let key = action.trim_end_matches(":cycle");
469            return Some(InlineListSelection::ConfigAction(format!(
470                "{}:cycle_prev",
471                key
472            )));
473        }
474        return Some(selection.clone());
475    }
476
477    if action.ends_with(":inc") {
478        if is_left {
479            let key = action.trim_end_matches(":inc");
480            return Some(InlineListSelection::ConfigAction(format!("{}:dec", key)));
481        }
482        return Some(selection.clone());
483    }
484
485    if action.ends_with(":dec") {
486        if is_left {
487            return Some(selection.clone());
488        }
489        let key = action.trim_end_matches(":dec");
490        return Some(InlineListSelection::ConfigAction(format!("{}:inc", key)));
491    }
492
493    if action.ends_with(":toggle") {
494        let _ = is_left;
495        return Some(selection.clone());
496    }
497
498    None
499}
500
501impl ModalListItem {
502    pub fn is_header(&self) -> bool {
503        self.selection.is_none() && !self.is_divider
504    }
505
506    fn matches(&self, query: &str) -> bool {
507        if query.is_empty() {
508            return true;
509        }
510        let Some(value) = self.search_value.as_ref() else {
511            return false;
512        };
513        exact_terms_match(query, value)
514    }
515}
516
517#[allow(clippy::const_is_empty)]
518pub fn is_divider_title(item: &InlineListItem) -> bool {
519    if item.selection.is_some() {
520        return false;
521    }
522    if item.indent != 0 {
523        return false;
524    }
525    if item.subtitle.is_some() || item.badge.is_some() {
526        return false;
527    }
528    let symbol = ui::INLINE_USER_MESSAGE_DIVIDER_SYMBOL;
529    if symbol.is_empty() {
530        return false;
531    }
532    item.title
533        .chars()
534        .all(|ch| symbol.chars().any(|needle| needle == ch))
535}
536
537impl ModalListState {
538    pub fn new(items: Vec<InlineListItem>, selected: Option<InlineListSelection>) -> Self {
539        let converted: Vec<ModalListItem> = items
540            .into_iter()
541            .map(|item| {
542                let is_divider = is_divider_title(&item);
543                let search_value = item
544                    .search_value
545                    .as_ref()
546                    .map(|value| value.to_ascii_lowercase());
547                ModalListItem {
548                    title: item.title,
549                    subtitle: item.subtitle,
550                    badge: item.badge,
551                    indent: item.indent,
552                    selection: item.selection,
553                    search_value,
554                    is_divider,
555                }
556            })
557            .collect();
558        let total_selectable = converted
559            .iter()
560            .filter(|item| item.selection.is_some())
561            .count();
562        let has_two_line_items = converted.iter().any(|item| {
563            item.subtitle
564                .as_ref()
565                .is_some_and(|subtitle| !subtitle.trim().is_empty())
566        });
567        let density_behavior = Self::density_behavior_for_items(&converted);
568        let is_model_picker_list = Self::is_model_picker_list(&converted);
569        let compact_rows =
570            Self::initial_compact_rows(density_behavior, has_two_line_items, is_model_picker_list);
571        let mut modal_state = Self {
572            visible_indices: (0..converted.len()).collect(),
573            items: converted,
574            list_state: ListState::default(),
575            total_selectable,
576            filter_terms: Vec::new(),
577            filter_query: None,
578            viewport_rows: None,
579            compact_rows,
580            density_behavior,
581        };
582        modal_state.select_initial(selected);
583        modal_state
584    }
585
586    fn density_behavior_for_items(items: &[ModalListItem]) -> ModalListDensityBehavior {
587        if items
588            .iter()
589            .any(|item| matches!(item.selection, Some(InlineListSelection::ConfigAction(_))))
590        {
591            ModalListDensityBehavior::FixedComfortable
592        } else {
593            ModalListDensityBehavior::Adjustable
594        }
595    }
596
597    fn initial_compact_rows(
598        density_behavior: ModalListDensityBehavior,
599        has_two_line_items: bool,
600        is_model_picker_list: bool,
601    ) -> bool {
602        if is_model_picker_list {
603            return false;
604        }
605        match density_behavior {
606            ModalListDensityBehavior::FixedComfortable => false,
607            ModalListDensityBehavior::Adjustable => has_two_line_items,
608        }
609    }
610
611    fn is_model_picker_list(items: &[ModalListItem]) -> bool {
612        let mut has_model_selection = false;
613        for item in items {
614            let Some(selection) = item.selection.as_ref() else {
615                continue;
616            };
617            match selection {
618                InlineListSelection::Model(_)
619                | InlineListSelection::DynamicModel(_)
620                | InlineListSelection::RefreshDynamicModels
621                | InlineListSelection::Reasoning(_)
622                | InlineListSelection::DisableReasoning
623                | InlineListSelection::CustomModel => {
624                    has_model_selection = true;
625                }
626                _ => return false,
627            }
628        }
629        has_model_selection
630    }
631
632    pub fn current_selection(&self) -> Option<InlineListSelection> {
633        self.list_state
634            .selected()
635            .and_then(|index| self.visible_indices.get(index))
636            .and_then(|&item_index| self.items.get(item_index))
637            .and_then(|item| item.selection.clone())
638    }
639
640    pub fn get_best_matching_item(&self, query: &str) -> Option<String> {
641        if query.is_empty() {
642            return None;
643        }
644
645        let normalized_query = normalize_query(query);
646        self.visible_indices
647            .iter()
648            .filter_map(|&idx| self.items.get(idx))
649            .filter(|item| item.selection.is_some())
650            .filter_map(|item| item.search_value.as_ref())
651            .find(|search_value| exact_terms_match(&normalized_query, search_value))
652            .cloned()
653    }
654
655    pub fn select_previous(&mut self) {
656        if self.visible_indices.is_empty() {
657            return;
658        }
659        let Some(mut index) = self.list_state.selected() else {
660            if let Some(last) = self.last_selectable_index() {
661                self.list_state.select(Some(last));
662            }
663            return;
664        };
665
666        while index > 0 {
667            index -= 1;
668            let item_index = match self.visible_indices.get(index) {
669                Some(idx) => *idx,
670                None => {
671                    tracing::warn!("visible_indices index {index} out of bounds");
672                    continue;
673                }
674            };
675            if let Some(item) = self.items.get(item_index)
676                && item.selection.is_some()
677            {
678                self.list_state.select(Some(index));
679                return;
680            }
681        }
682
683        if let Some(first) = self.first_selectable_index() {
684            self.list_state.select(Some(first));
685        } else {
686            self.list_state.select(None);
687        }
688    }
689
690    pub fn select_next(&mut self) {
691        if self.visible_indices.is_empty() {
692            return;
693        }
694        let mut index = self.list_state.selected().unwrap_or(usize::MAX);
695        if index == usize::MAX {
696            if let Some(first) = self.first_selectable_index() {
697                self.list_state.select(Some(first));
698            }
699            return;
700        }
701        while index + 1 < self.visible_indices.len() {
702            index += 1;
703            let item_index = self.visible_indices[index];
704            if self.items[item_index].selection.is_some() {
705                self.list_state.select(Some(index));
706                break;
707            }
708        }
709    }
710
711    pub fn select_first(&mut self) {
712        if let Some(first) = self.first_selectable_index() {
713            self.list_state.select(Some(first));
714        } else {
715            self.list_state.select(None);
716        }
717        if let Some(rows) = self.viewport_rows {
718            self.ensure_visible(rows);
719        }
720    }
721
722    pub fn select_last(&mut self) {
723        if let Some(last) = self.last_selectable_index() {
724            self.list_state.select(Some(last));
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_nth_selectable(&mut self, target_index: usize) -> bool {
734        let mut count = 0usize;
735        for (visible_pos, &item_index) in self.visible_indices.iter().enumerate() {
736            if self.items[item_index].selection.is_some() {
737                if count == target_index {
738                    self.list_state.select(Some(visible_pos));
739                    if let Some(rows) = self.viewport_rows {
740                        self.ensure_visible(rows);
741                    }
742                    return true;
743                }
744                count += 1;
745            }
746        }
747        false
748    }
749
750    pub fn page_up(&mut self) {
751        let step = self.page_step();
752        if step == 0 {
753            self.select_previous();
754            return;
755        }
756        for _ in 0..step {
757            let before = self.list_state.selected();
758            self.select_previous();
759            if self.list_state.selected() == before {
760                break;
761            }
762        }
763    }
764
765    pub fn page_down(&mut self) {
766        let step = self.page_step();
767        if step == 0 {
768            self.select_next();
769            return;
770        }
771        for _ in 0..step {
772            let before = self.list_state.selected();
773            self.select_next();
774            if self.list_state.selected() == before {
775                break;
776            }
777        }
778    }
779
780    pub fn set_viewport_rows(&mut self, rows: u16) {
781        self.viewport_rows = Some(rows);
782    }
783
784    pub(super) fn ensure_visible(&mut self, viewport: u16) {
785        let Some(selected) = self.list_state.selected() else {
786            return;
787        };
788        if viewport == 0 {
789            return;
790        }
791        let visible = viewport as usize;
792        let offset = self.list_state.offset();
793        if selected < offset {
794            *self.list_state.offset_mut() = selected;
795        } else if selected >= offset + visible {
796            *self.list_state.offset_mut() = selected + 1 - visible;
797        }
798    }
799
800    pub fn apply_search(&mut self, query: &str) {
801        let preferred = self.current_selection();
802        self.apply_search_with_preference(query, preferred.clone());
803    }
804
805    pub fn apply_search_with_preference(
806        &mut self,
807        query: &str,
808        preferred: Option<InlineListSelection>,
809    ) {
810        let trimmed = query.trim();
811        if trimmed.is_empty() {
812            if self.filter_query.is_none() {
813                if preferred.is_some() && self.current_selection() != preferred {
814                    self.select_initial(preferred);
815                }
816                return;
817            }
818            self.visible_indices = (0..self.items.len()).collect();
819            self.filter_terms.clear();
820            self.filter_query = None;
821            self.select_initial(preferred);
822            return;
823        }
824
825        if self.filter_query.as_deref() == Some(trimmed) {
826            if preferred.is_some() && self.current_selection() != preferred {
827                self.select_initial(preferred);
828            }
829            return;
830        }
831
832        let normalized_query = normalize_query(trimmed);
833        let terms = normalized_query
834            .split_whitespace()
835            .filter(|term| !term.is_empty())
836            .map(|term| term.to_owned())
837            .collect::<Vec<_>>();
838        let mut indices = Vec::new();
839        let mut pending_divider: Option<usize> = None;
840        let mut current_header: Option<usize> = None;
841        let mut header_matches = false;
842        let mut header_included = false;
843
844        for (index, item) in self.items.iter().enumerate() {
845            if item.is_divider {
846                pending_divider = Some(index);
847                current_header = None;
848                header_matches = false;
849                header_included = false;
850                continue;
851            }
852
853            if item.is_header() {
854                current_header = Some(index);
855                header_matches = item.matches(&normalized_query);
856                header_included = false;
857                if header_matches {
858                    if let Some(divider_index) = pending_divider.take() {
859                        indices.push(divider_index);
860                    }
861                    indices.push(index);
862                    header_included = true;
863                }
864                continue;
865            }
866
867            let item_matches = item.matches(&normalized_query);
868            let include_item = header_matches || item_matches;
869            if include_item {
870                if let Some(divider_index) = pending_divider.take() {
871                    indices.push(divider_index);
872                }
873                if let Some(header_index) = current_header
874                    && !header_included
875                {
876                    indices.push(header_index);
877                    header_included = true;
878                }
879                indices.push(index);
880            }
881        }
882        self.visible_indices = indices;
883        self.filter_terms = terms;
884        self.filter_query = Some(trimmed.to_owned());
885        self.select_initial(preferred);
886    }
887
888    fn select_initial(&mut self, preferred: Option<InlineListSelection>) {
889        let mut selection_index = preferred.and_then(|needle| {
890            self.visible_indices
891                .iter()
892                .position(|&idx| self.items[idx].selection.as_ref() == Some(&needle))
893        });
894
895        if selection_index.is_none() {
896            selection_index = self.first_selectable_index();
897        }
898
899        self.list_state.select(selection_index);
900        *self.list_state.offset_mut() = 0;
901    }
902
903    fn first_selectable_index(&self) -> Option<usize> {
904        self.visible_indices
905            .iter()
906            .position(|&idx| self.items[idx].selection.is_some())
907    }
908
909    fn last_selectable_index(&self) -> Option<usize> {
910        self.visible_indices
911            .iter()
912            .rposition(|&idx| self.items[idx].selection.is_some())
913    }
914
915    pub(super) fn filter_active(&self) -> bool {
916        self.filter_query
917            .as_ref()
918            .is_some_and(|value| !value.is_empty())
919    }
920
921    #[cfg(test)]
922    pub(super) fn filter_query(&self) -> Option<&str> {
923        self.filter_query.as_deref()
924    }
925
926    pub(super) fn highlight_terms(&self) -> &[String] {
927        &self.filter_terms
928    }
929
930    pub(super) fn visible_selectable_count(&self) -> usize {
931        self.visible_indices
932            .iter()
933            .filter(|&&idx| self.items[idx].selection.is_some())
934            .count()
935    }
936
937    pub(super) fn total_selectable(&self) -> usize {
938        self.total_selectable
939    }
940
941    pub(super) fn compact_rows(&self) -> bool {
942        self.compact_rows
943    }
944
945    pub(super) fn supports_density_toggle(&self) -> bool {
946        matches!(self.density_behavior, ModalListDensityBehavior::Adjustable)
947    }
948
949    pub(super) fn non_filter_summary_text(&self, footer_hint: Option<&str>) -> Option<String> {
950        match self.density_behavior {
951            ModalListDensityBehavior::FixedComfortable => {
952                Some(CONFIG_LIST_NAVIGATION_HINT.to_owned())
953            }
954            ModalListDensityBehavior::Adjustable => footer_hint
955                .filter(|hint| !hint.is_empty())
956                .map(ToOwned::to_owned),
957        }
958    }
959
960    pub fn toggle_row_density(&mut self) {
961        self.compact_rows = !self.compact_rows;
962    }
963
964    fn page_step(&self) -> usize {
965        let rows = self.viewport_rows.unwrap_or(0).max(1);
966        usize::from(rows)
967    }
968}
969
970#[allow(dead_code)]
971impl WizardModalState {
972    /// Create a new wizard modal state from wizard steps
973    pub fn new(
974        title: String,
975        steps: Vec<WizardStep>,
976        current_step: usize,
977        search: Option<InlineListSearchConfig>,
978        mode: WizardModalMode,
979    ) -> Self {
980        let step_states: Vec<WizardStepState> = steps
981            .into_iter()
982            .map(|step| {
983                let notes_active = step
984                    .items
985                    .first()
986                    .and_then(|item| item.selection.as_ref())
987                    .is_some_and(|selection| match selection {
988                        InlineListSelection::RequestUserInputAnswer {
989                            selected, other, ..
990                        } => selected.is_empty() && other.is_some(),
991                        _ => false,
992                    });
993                WizardStepState {
994                    title: step.title,
995                    question: step.question,
996                    list: ModalListState::new(step.items, step.answer.clone()),
997                    completed: step.completed,
998                    answer: step.answer,
999                    notes: String::new(),
1000                    notes_active,
1001                    allow_freeform: step.allow_freeform,
1002                    freeform_label: step.freeform_label,
1003                    freeform_placeholder: step.freeform_placeholder,
1004                }
1005            })
1006            .collect();
1007
1008        let clamped_step = if step_states.is_empty() {
1009            0
1010        } else {
1011            current_step.min(step_states.len().saturating_sub(1))
1012        };
1013
1014        Self {
1015            title,
1016            steps: step_states,
1017            current_step: clamped_step,
1018            search: search.map(ModalSearchState::from),
1019            mode,
1020        }
1021    }
1022
1023    /// Handle key event for wizard navigation
1024    pub fn handle_key_event(
1025        &mut self,
1026        key: &KeyEvent,
1027        modifiers: ModalKeyModifiers,
1028    ) -> ModalListKeyResult {
1029        if let Some(step) = self.steps.get_mut(self.current_step)
1030            && step.notes_active
1031        {
1032            match key.code {
1033                KeyCode::Char(ch) if !modifiers.control && !modifiers.alt && !modifiers.command => {
1034                    step.notes.push(ch);
1035                    return ModalListKeyResult::Redraw;
1036                }
1037                KeyCode::Backspace => {
1038                    if step.notes.pop().is_some() {
1039                        return ModalListKeyResult::Redraw;
1040                    }
1041                    return ModalListKeyResult::HandledNoRedraw;
1042                }
1043                KeyCode::Tab | KeyCode::Esc => {
1044                    if !step.notes.is_empty() {
1045                        step.notes.clear();
1046                    }
1047                    step.notes_active = false;
1048                    return ModalListKeyResult::Redraw;
1049                }
1050                _ => {}
1051            }
1052        }
1053
1054        if let Some(step) = self.steps.get_mut(self.current_step)
1055            && !step.notes_active
1056            && Self::step_selected_custom_note_item_index(step).is_some()
1057        {
1058            match key.code {
1059                KeyCode::Char(ch) if !modifiers.control && !modifiers.alt && !modifiers.command => {
1060                    step.notes_active = true;
1061                    step.notes.push(ch);
1062                    return ModalListKeyResult::Redraw;
1063                }
1064                KeyCode::Backspace => {
1065                    if step.notes.pop().is_some() {
1066                        step.notes_active = true;
1067                        return ModalListKeyResult::Redraw;
1068                    }
1069                }
1070                _ => {}
1071            }
1072        }
1073
1074        // Search handling (if enabled)
1075        if let Some(search) = self.search.as_mut()
1076            && let Some(step) = self.steps.get_mut(self.current_step)
1077        {
1078            match key.code {
1079                KeyCode::Char(ch) if !modifiers.control && !modifiers.alt && !modifiers.command => {
1080                    search.push_char(ch);
1081                    step.list.apply_search(&search.query);
1082                    return ModalListKeyResult::Redraw;
1083                }
1084                KeyCode::Backspace => {
1085                    if search.backspace() {
1086                        step.list.apply_search(&search.query);
1087                        return ModalListKeyResult::Redraw;
1088                    }
1089                    return ModalListKeyResult::HandledNoRedraw;
1090                }
1091                KeyCode::Delete => {
1092                    if search.clear() {
1093                        step.list.apply_search(&search.query);
1094                        return ModalListKeyResult::Redraw;
1095                    }
1096                    return ModalListKeyResult::HandledNoRedraw;
1097                }
1098                KeyCode::Tab => {
1099                    if let Some(best_match) = step.list.get_best_matching_item(&search.query) {
1100                        search.query = best_match;
1101                        step.list.apply_search(&search.query);
1102                        return ModalListKeyResult::Redraw;
1103                    }
1104                    return ModalListKeyResult::HandledNoRedraw;
1105                }
1106                KeyCode::Esc => {
1107                    if search.clear() {
1108                        step.list.apply_search(&search.query);
1109                        return ModalListKeyResult::Redraw;
1110                    }
1111                }
1112                _ => {}
1113            }
1114        }
1115
1116        if self.mode == WizardModalMode::MultiStep
1117            && !modifiers.control
1118            && !modifiers.alt
1119            && !modifiers.command
1120            && self.search.is_none()
1121            && let KeyCode::Char(ch) = key.code
1122            && ch.is_ascii_digit()
1123            && ch != '0'
1124        {
1125            let target_index = ch.to_digit(10).unwrap_or(1).saturating_sub(1) as usize;
1126            if let Some(step) = self.steps.get_mut(self.current_step)
1127                && step.list.select_nth_selectable(target_index)
1128            {
1129                return self.submit_current_selection();
1130            }
1131            return ModalListKeyResult::HandledNoRedraw;
1132        }
1133
1134        match key.code {
1135            KeyCode::Char('n') | KeyCode::Char('N')
1136                if modifiers.control && self.mode == WizardModalMode::MultiStep =>
1137            {
1138                if self.current_step < self.steps.len().saturating_sub(1) {
1139                    self.current_step += 1;
1140                    ModalListKeyResult::Redraw
1141                } else {
1142                    ModalListKeyResult::HandledNoRedraw
1143                }
1144            }
1145            // Left arrow: go to previous step if available
1146            KeyCode::Left => {
1147                if self.current_step > 0 {
1148                    self.current_step -= 1;
1149                    ModalListKeyResult::Redraw
1150                } else {
1151                    ModalListKeyResult::HandledNoRedraw
1152                }
1153            }
1154            // Right arrow: go to next step if current is completed
1155            KeyCode::Right => {
1156                let can_advance = match self.mode {
1157                    WizardModalMode::MultiStep => self.current_step_completed(),
1158                    WizardModalMode::TabbedList => true,
1159                };
1160
1161                if can_advance && self.current_step < self.steps.len().saturating_sub(1) {
1162                    self.current_step += 1;
1163                    ModalListKeyResult::Redraw
1164                } else {
1165                    ModalListKeyResult::HandledNoRedraw
1166                }
1167            }
1168            // Enter: select current item and mark step complete
1169            KeyCode::Enter => self.submit_current_selection(),
1170            // Escape: cancel wizard
1171            KeyCode::Esc => {
1172                ModalListKeyResult::Cancel(InlineEvent::Overlay(OverlayEvent::Cancelled))
1173            }
1174            // Up/Down/Tab: delegate to current step's list
1175            KeyCode::Up | KeyCode::Down | KeyCode::Tab | KeyCode::BackTab => {
1176                if let Some(step) = self.steps.get_mut(self.current_step) {
1177                    match key.code {
1178                        KeyCode::Up => {
1179                            if modifiers.command {
1180                                step.list.select_first();
1181                            } else {
1182                                step.list.select_previous();
1183                            }
1184                            ModalListKeyResult::Redraw
1185                        }
1186                        KeyCode::Down => {
1187                            if modifiers.command {
1188                                step.list.select_last();
1189                            } else {
1190                                step.list.select_next();
1191                            }
1192                            ModalListKeyResult::Redraw
1193                        }
1194                        KeyCode::Tab => {
1195                            if self.search.is_none()
1196                                && (step.allow_freeform
1197                                    || Self::step_selected_custom_note_item_index(step).is_some())
1198                            {
1199                                step.notes_active = !step.notes_active;
1200                                ModalListKeyResult::Redraw
1201                            } else {
1202                                step.list.select_next();
1203                                ModalListKeyResult::Redraw
1204                            }
1205                        }
1206                        KeyCode::BackTab => {
1207                            step.list.select_previous();
1208                            ModalListKeyResult::Redraw
1209                        }
1210                        _ => ModalListKeyResult::NotHandled,
1211                    }
1212                } else {
1213                    ModalListKeyResult::NotHandled
1214                }
1215            }
1216            _ => ModalListKeyResult::NotHandled,
1217        }
1218    }
1219
1220    pub fn handle_mouse_click(&mut self, visible_index: usize) -> ModalListKeyResult {
1221        let Some(step) = self.steps.get_mut(self.current_step) else {
1222            return ModalListKeyResult::NotHandled;
1223        };
1224        let Some(&item_index) = step.list.visible_indices.get(visible_index) else {
1225            return ModalListKeyResult::HandledNoRedraw;
1226        };
1227        if step
1228            .list
1229            .items
1230            .get(item_index)
1231            .and_then(|item| item.selection.as_ref())
1232            .is_none()
1233        {
1234            return ModalListKeyResult::HandledNoRedraw;
1235        }
1236
1237        if step.list.list_state.selected() == Some(visible_index) {
1238            return self.submit_current_selection();
1239        }
1240
1241        step.list.list_state.select(Some(visible_index));
1242        if let Some(rows) = step.list.viewport_rows {
1243            step.list.ensure_visible(rows);
1244        }
1245        ModalListKeyResult::Redraw
1246    }
1247
1248    pub fn handle_mouse_scroll(&mut self, down: bool) -> ModalListKeyResult {
1249        let Some(step) = self.steps.get_mut(self.current_step) else {
1250            return ModalListKeyResult::NotHandled;
1251        };
1252
1253        let before = step.list.list_state.selected();
1254        if down {
1255            step.list.select_next();
1256        } else {
1257            step.list.select_previous();
1258        }
1259
1260        if step.list.list_state.selected() == before {
1261            ModalListKeyResult::HandledNoRedraw
1262        } else {
1263            ModalListKeyResult::Redraw
1264        }
1265    }
1266
1267    /// Get current selection from the active step
1268    fn current_selection(&self) -> Option<InlineListSelection> {
1269        self.steps
1270            .get(self.current_step)
1271            .and_then(|step| {
1272                step.list
1273                    .current_selection()
1274                    .map(|selection| (selection, step))
1275            })
1276            .map(|(selection, step)| match selection {
1277                InlineListSelection::RequestUserInputAnswer {
1278                    question_id,
1279                    selected,
1280                    other,
1281                } => {
1282                    let notes = step.notes.trim();
1283                    let next_other = if other.is_some() {
1284                        Some(notes.to_string())
1285                    } else if notes.is_empty() {
1286                        None
1287                    } else {
1288                        Some(notes.to_string())
1289                    };
1290                    InlineListSelection::RequestUserInputAnswer {
1291                        question_id,
1292                        selected,
1293                        other: next_other,
1294                    }
1295                }
1296                InlineListSelection::AskUserChoice {
1297                    tab_id, choice_id, ..
1298                } => {
1299                    let notes = step.notes.trim();
1300                    let text = if notes.is_empty() {
1301                        None
1302                    } else {
1303                        Some(notes.to_string())
1304                    };
1305                    InlineListSelection::AskUserChoice {
1306                        tab_id,
1307                        choice_id,
1308                        text,
1309                    }
1310                }
1311                _ => selection,
1312            })
1313    }
1314
1315    /// Check if current step is completed
1316    fn current_step_completed(&self) -> bool {
1317        self.steps
1318            .get(self.current_step)
1319            .is_some_and(|step| step.completed)
1320    }
1321
1322    fn step_selected_custom_note_item_index(step: &WizardStepState) -> Option<usize> {
1323        let selected_visible = step.list.list_state.selected()?;
1324        let item_index = *step.list.visible_indices.get(selected_visible)?;
1325        let item = step.list.items.get(item_index)?;
1326        match item.selection.as_ref() {
1327            Some(InlineListSelection::RequestUserInputAnswer {
1328                selected, other, ..
1329            }) if selected.is_empty() && other.is_some() => Some(item_index),
1330            _ => None,
1331        }
1332    }
1333
1334    fn current_step_selected_custom_note_item_index(&self) -> Option<usize> {
1335        self.steps
1336            .get(self.current_step)
1337            .and_then(Self::step_selected_custom_note_item_index)
1338    }
1339
1340    fn current_step_requires_custom_note_input(&self) -> bool {
1341        self.current_step_selected_custom_note_item_index()
1342            .is_some()
1343    }
1344
1345    fn current_step_supports_notes(&self) -> bool {
1346        self.steps
1347            .get(self.current_step)
1348            .and_then(|step| step.list.current_selection())
1349            .is_some_and(|selection| {
1350                matches!(
1351                    selection,
1352                    InlineListSelection::RequestUserInputAnswer { .. }
1353                        | InlineListSelection::AskUserChoice { .. }
1354                )
1355            })
1356    }
1357
1358    pub fn unanswered_count(&self) -> usize {
1359        self.steps.iter().filter(|step| !step.completed).count()
1360    }
1361
1362    pub fn question_header(&self) -> String {
1363        format!(
1364            "Question {}/{} ({} unanswered)",
1365            self.current_step.saturating_add(1),
1366            self.steps.len(),
1367            self.unanswered_count()
1368        )
1369    }
1370
1371    pub fn notes_line(&self) -> Option<String> {
1372        let step = self.steps.get(self.current_step)?;
1373        if step.notes_active || !step.notes.is_empty() {
1374            let label = step.freeform_label.as_deref().unwrap_or("›");
1375            if step.notes.is_empty()
1376                && let Some(placeholder) = step.freeform_placeholder.as_ref()
1377            {
1378                return Some(format!("{} {}", label, placeholder));
1379            }
1380            Some(format!("{} {}", label, step.notes))
1381        } else {
1382            None
1383        }
1384    }
1385
1386    pub fn notes_active(&self) -> bool {
1387        self.steps
1388            .get(self.current_step)
1389            .is_some_and(|step| step.notes_active)
1390    }
1391
1392    pub fn instruction_lines(&self) -> Vec<String> {
1393        let step = match self.steps.get(self.current_step) {
1394            Some(s) => s,
1395            None => return Vec::new(),
1396        };
1397        let custom_note_selected = self.current_step_requires_custom_note_input();
1398
1399        if self.notes_active() {
1400            if custom_note_selected {
1401                vec!["type custom note | enter to continue | esc to clear".to_string()]
1402            } else {
1403                vec!["tab or esc to clear notes | enter to submit answer".to_string()]
1404            }
1405        } else {
1406            let mut lines = Vec::new();
1407            if custom_note_selected {
1408                lines.push("type custom note | enter to continue".to_string());
1409            } else if step.allow_freeform {
1410                lines.push("tab to add notes | enter to submit answer".to_string());
1411            } else {
1412                lines.push("enter to submit answer".to_string());
1413            }
1414            lines.push("ctrl + n next question | esc to interrupt".to_string());
1415            lines
1416        }
1417    }
1418
1419    /// Mark current step as completed with the given answer
1420    fn complete_current_step(&mut self, answer: InlineListSelection) {
1421        if let Some(step) = self.steps.get_mut(self.current_step) {
1422            step.completed = true;
1423            step.answer = Some(answer);
1424        }
1425    }
1426
1427    /// Collect all answers from completed steps
1428    fn collect_answers(&self) -> Vec<InlineListSelection> {
1429        self.steps
1430            .iter()
1431            .filter_map(|step| step.answer.clone())
1432            .collect()
1433    }
1434
1435    fn submit_current_selection(&mut self) -> ModalListKeyResult {
1436        if self.current_step_requires_custom_note_input()
1437            && let Some(step) = self.steps.get_mut(self.current_step)
1438            && step.notes.trim().is_empty()
1439        {
1440            step.notes_active = true;
1441            return ModalListKeyResult::Redraw;
1442        }
1443
1444        let Some(selection) = self.current_selection() else {
1445            return ModalListKeyResult::HandledNoRedraw;
1446        };
1447
1448        match self.mode {
1449            WizardModalMode::TabbedList => ModalListKeyResult::Submit(InlineEvent::Overlay(
1450                OverlayEvent::Submitted(OverlaySubmission::Wizard(vec![selection])),
1451            )),
1452            WizardModalMode::MultiStep => {
1453                self.complete_current_step(selection.clone());
1454                if self.current_step < self.steps.len().saturating_sub(1) {
1455                    self.current_step += 1;
1456                    ModalListKeyResult::Redraw
1457                } else {
1458                    ModalListKeyResult::Submit(InlineEvent::Overlay(OverlayEvent::Submitted(
1459                        OverlaySubmission::Wizard(self.collect_answers()),
1460                    )))
1461                }
1462            }
1463        }
1464    }
1465
1466    /// Check if all steps are completed
1467    pub fn all_steps_completed(&self) -> bool {
1468        self.steps.iter().all(|step| step.completed)
1469    }
1470}