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