返回 CodeWhale
user_input.rs
根目录 / crates / tui / src / tui / user_input.rs
1 //! Modal for request_user_input tool prompts.
2
3 use std::cell::{Cell, RefCell};
4
5 use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
6 use ratatui::layout::{Alignment, Position, Rect};
7 use ratatui::prelude::*;
8 use ratatui::widgets::{Block, Borders, Padding, Paragraph, Widget};
9
10 use crate::tui::pager::PagerRows;
11 use crate::tui::views::{ModalKind, ModalView, ViewAction, ViewEvent, render_modal_surface};
12 use codewhale_engine::tools::user_input::{
13 UserInputAnswer, UserInputAnswerKind, UserInputQuestion, UserInputRequest, UserInputResponse,
14 };
15 use codewhale_localization::{Locale, MessageId, tr};
16 use codewhale_palette as palette;
17 use codewhale_tui_kit::menu_style;
18
19 fn modal_block(title: &str) -> Block<'static> {
20 Block::default()
21 .title(Line::from(vec![Span::styled(
22 title.to_string(),
23 Style::default().fg(palette::WHALE_HUMAN).bold(),
24 )]))
25 .borders(Borders::ALL)
26 .border_style(Style::default().fg(palette::BORDER_COLOR))
27 .style(Style::default().bg(palette::WHALE_BG))
28 .padding(Padding::uniform(1))
29 }
30
31 fn render_modal_chrome(area: Rect, popup_area: Rect, buf: &mut Buffer) {
32 render_modal_surface(area, popup_area, buf);
33 }
34
35 fn hint_label(locale: Locale, id: MessageId) -> Span<'static> {
36 Span::styled(
37 format!(" {}", tr(locale, id)),
38 Style::default().fg(palette::TEXT_MUTED),
39 )
40 }
41
42 fn push_option_lines(
43 lines: &mut Vec<Line<'static>>,
44 selected: bool,
45 number: usize,
46 label: String,
47 description: String,
48 ticked: bool,
49 ) {
50 let row_style = if selected {
51 menu_style::selected_row_style()
52 } else {
53 Style::default().fg(palette::TEXT_PRIMARY)
54 };
55 let detail_style = if selected {
56 row_style
57 } else {
58 Style::default().fg(palette::TEXT_MUTED)
59 };
60 let prefix = codewhale_tui_kit::glyphs::selection_marker(selected);
61 // Multi-select rows get a check-mark gutter when toggled into the pending
62 // set, mirroring the affordance used in other multi-option pickers.
63 let mark = if ticked { "✔ " } else { " " };
64
65 lines.push(Line::from(Span::styled(
66 format!("{prefix}{mark}{number}) {label}"),
67 row_style,
68 )));
69 if !description.is_empty() {
70 lines.push(Line::from(Span::styled(
71 format!(" {description}"),
72 detail_style,
73 )));
74 }
75 }
76
77 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
78 enum InputMode {
79 Selecting,
80 OtherInput,
81 }
82
83 #[derive(Debug, Clone)]
84 pub struct UserInputView {
85 tool_id: String,
86 request: UserInputRequest,
87 locale: Locale,
88 question_index: usize,
89 selected: usize,
90 mode: InputMode,
91 other_input: String,
92 /// Answers committed for previous questions. Going back pops the last
93 /// batch so an accidental Enter is reversible.
94 answered: Vec<Vec<UserInputAnswer>>,
95 /// Indices toggled into the pending multi-select set for the current
96 /// question. Only used when `question.multi_select` is true.
97 multi_pending: Vec<usize>,
98 /// Wheel browsing uses wrapped rows from the last paint. Option navigation
99 /// or typing returns to following focus so the next edit stays visible.
100 manual_scroll: bool,
101 scroll_offset: Cell<usize>,
102 max_scroll: Cell<usize>,
103 option_hitboxes: RefCell<Vec<Rect>>,
104 }
105
106 impl UserInputView {
107 pub fn new(tool_id: impl Into<String>, request: UserInputRequest, locale: Locale) -> Self {
108 let mode = if request
109 .questions
110 .first()
111 .is_some_and(|question| question.options.is_empty())
112 {
113 InputMode::OtherInput
114 } else {
115 InputMode::Selecting
116 };
117 Self {
118 tool_id: tool_id.into(),
119 request,
120 locale,
121 question_index: 0,
122 selected: 0,
123 mode,
124 other_input: String::new(),
125 answered: Vec::new(),
126 multi_pending: Vec::new(),
127 manual_scroll: false,
128 scroll_offset: Cell::new(0),
129 max_scroll: Cell::new(0),
130 option_hitboxes: RefCell::new(Vec::new()),
131 }
132 }
133
134 fn current_question(&self) -> &UserInputQuestion {
135 &self.request.questions[self.question_index]
136 }
137
138 /// Whether the "Other" free-text row is offered for the current question.
139 fn offers_other(&self) -> bool {
140 !self.request.require_typed_answers || self.current_question().allow_free_text
141 }
142
143 fn option_count(&self) -> usize {
144 // Options + conditional "Other" row + conditional "Confirm" row.
145 let mut count = self.current_question().options.len();
146 count += usize::from(self.offers_other());
147 count += usize::from(self.is_multi_select());
148 count
149 }
150
151 fn is_other_selected(&self) -> bool {
152 // "Other" sits immediately before the Confirm row when both exist, and
153 // is last otherwise.
154 let other_last = !self.is_multi_select();
155 if other_last {
156 self.offers_other() && self.selected + 1 == self.option_count()
157 } else {
158 self.offers_other() && self.selected + 2 == self.option_count()
159 }
160 }
161
162 /// True when the multi-select "Confirm selection" row is highlighted.
163 fn is_confirm_selected(&self) -> bool {
164 self.confirm_index() == Some(self.selected)
165 }
166
167 fn confirm_index(&self) -> Option<usize> {
168 self.is_multi_select()
169 .then(|| self.option_count().saturating_sub(1))
170 }
171
172 fn is_multi_select(&self) -> bool {
173 self.current_question().multi_select
174 }
175
176 /// Number of content lines the render path emits for the current state.
177 /// Drives the content-sized popup height so the dialog hugs what it
178 /// shows instead of claiming a fixed share of the screen.
179 fn content_line_count(&self) -> usize {
180 let question = self.current_question();
181 // "Action required" banner, header line, blank, question, blank.
182 let mut count = 5;
183 count += question
184 .detail
185 .as_ref()
186 .map_or(0, |detail| detail.lines().count() + 1);
187 count += question
188 .options
189 .iter()
190 .map(|option| 1 + usize::from(!option.description.is_empty()))
191 .sum::<usize>();
192 if self.offers_other() {
193 count += 2;
194 }
195 if self.is_multi_select() {
196 count += 2;
197 }
198 if self.mode == InputMode::OtherInput {
199 count += 2;
200 }
201 // Trailing blank line + controls hint.
202 count += 2;
203 count
204 }
205
206 fn toggle_pending(&mut self, index: usize) {
207 if let Some(pos) = self.multi_pending.iter().position(|i| *i == index) {
208 self.multi_pending.remove(pos);
209 } else {
210 self.multi_pending.push(index);
211 }
212 }
213
214 /// Build the answer(s) for the current question from a single selected
215 /// option index (single-select and the confirm step of multi-select).
216 fn answers_for_selection(&self, index: usize) -> Vec<UserInputAnswer> {
217 let question = self.current_question();
218 let option = &question.options[index];
219 vec![UserInputAnswer {
220 id: question.id.clone(),
221 label: option.label.clone(),
222 value: option.label.clone(),
223 kind: Some(UserInputAnswerKind::Choice),
224 }]
225 }
226
227 fn committed_answers(&self) -> Vec<UserInputAnswer> {
228 self.answered.iter().flatten().cloned().collect()
229 }
230
231 fn advance_question(&mut self, mut new_answers: Vec<UserInputAnswer>) -> ViewAction {
232 if new_answers.is_empty() {
233 new_answers.push(UserInputAnswer {
234 id: self.current_question().id.clone(),
235 label: String::new(),
236 value: String::new(),
237 kind: Some(UserInputAnswerKind::Skipped),
238 });
239 }
240 self.answered.push(new_answers);
241 if self.question_index + 1 >= self.request.questions.len() {
242 let response = UserInputResponse {
243 answers: self.committed_answers(),
244 };
245 if let Err(error) = self.request.validate_response(&response) {
246 self.answered.pop();
247 return ViewAction::Emit(ViewEvent::StatusToast {
248 level: crate::tui::app::StatusToastLevel::Warning,
249 message: tr(self.locale, MessageId::NotificationInputSubmitFailed)
250 .replace("{error}", &error.to_string()),
251 });
252 }
253 return ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted {
254 tool_id: self.tool_id.clone(),
255 response,
256 });
257 }
258 self.question_index += 1;
259 self.selected = 0;
260 self.mode = if self.current_question().options.is_empty() {
261 InputMode::OtherInput
262 } else {
263 InputMode::Selecting
264 };
265 self.other_input.clear();
266 self.multi_pending.clear();
267 ViewAction::None
268 }
269
270 fn go_back(&mut self) -> ViewAction {
271 if self.answered.is_empty() {
272 return ViewAction::None;
273 }
274 self.answered.pop();
275 self.question_index = self.question_index.saturating_sub(1);
276 self.selected = 0;
277 self.mode = if self.current_question().options.is_empty() {
278 InputMode::OtherInput
279 } else {
280 InputMode::Selecting
281 };
282 self.other_input.clear();
283 self.multi_pending.clear();
284 ViewAction::None
285 }
286
287 /// Content-line range that must stay on screen: the highlighted option,
288 /// or the typed custom-response row while editing it.
289 fn focused_line_range(&self) -> (usize, usize) {
290 if self.mode == InputMode::OtherInput {
291 let start = self.content_line_count().saturating_sub(4);
292 return (start, start.saturating_add(1));
293 }
294 self.option_line_range(self.selected)
295 }
296
297 fn option_line_range(&self, index: usize) -> (usize, usize) {
298 let question = self.current_question();
299 let detail_lines = question
300 .detail
301 .as_ref()
302 .map_or(0, |detail| detail.lines().count() + 1);
303 let option_lines = question
304 .options
305 .iter()
306 .take(index)
307 .map(|option| 1 + usize::from(!option.description.is_empty()))
308 .sum::<usize>();
309 let extra_rows = index.saturating_sub(question.options.len());
310 let start = 5 + detail_lines + option_lines + extra_rows * 2;
311 let height = question
312 .options
313 .get(index)
314 .map_or(2, |option| 1 + usize::from(!option.description.is_empty()));
315 (start, start.saturating_add(height - 1))
316 }
317
318 fn handle_selecting_key(&mut self, key: KeyEvent) -> ViewAction {
319 match key.code {
320 KeyCode::Up | KeyCode::Char('k') => {
321 self.selected = self.selected.saturating_sub(1);
322 ViewAction::None
323 }
324 KeyCode::Down | KeyCode::Char('j') => {
325 self.selected = (self.selected + 1).min(self.option_count().saturating_sub(1));
326 ViewAction::None
327 }
328 KeyCode::Left | KeyCode::Char('h') => self.go_back(),
329 KeyCode::Char(ch) if ch.is_ascii_digit() => {
330 let Some(number) = ch.to_digit(10) else {
331 return ViewAction::None;
332 };
333 if number == 0 {
334 return ViewAction::None;
335 }
336 let index = usize::try_from(number - 1).unwrap_or(usize::MAX);
337 if index >= self.option_count() {
338 return ViewAction::None;
339 }
340 self.selected = index;
341 self.activate_or_confirm_selection()
342 }
343 KeyCode::Char(' ') if self.is_multi_select() => {
344 // Space toggles the highlighted option in the pending set
345 // without leaving the picker (standard multi-select affordance).
346 // The Other row and the Confirm row are not options: toggling
347 // them would corrupt the pending set.
348 let is_confirm = self.confirm_index() == Some(self.selected);
349 if !self.is_other_selected() && !is_confirm {
350 self.toggle_pending(self.selected);
351 }
352 ViewAction::None
353 }
354 KeyCode::Enter => self.activate_or_confirm_selection(),
355 KeyCode::Esc => ViewAction::EmitAndClose(ViewEvent::UserInputCancelled {
356 tool_id: self.tool_id.clone(),
357 }),
358 _ => ViewAction::None,
359 }
360 }
361
362 /// Resolve a digit/Enter activation for the currently highlighted row.
363 ///
364 /// - "Other" row → enter free-text input mode.
365 /// - multi-select option → add to the pending set (never remove — that is
366 /// Space's job) and move focus to the Confirm row, so the single-select
367 /// muscle memory of Enter-then-Enter submits the highlighted option
368 /// instead of toggling it back out and submitting an empty set.
369 /// - multi-select Confirm row → submit the pending set.
370 /// - single-select option → submit immediately (legacy behavior).
371 fn activate_or_confirm_selection(&mut self) -> ViewAction {
372 if self.is_other_selected() {
373 self.mode = InputMode::OtherInput;
374 self.other_input.clear();
375 return ViewAction::None;
376 }
377 if self.is_multi_select() {
378 if self.is_confirm_selected() {
379 // Flush the pending set as this question's answers. An empty
380 // set is allowed (skip-like) — the model is expected to offer a
381 // sensible default, but we don't deadlock.
382 let question = self.current_question();
383 let answers: Vec<UserInputAnswer> = self
384 .multi_pending
385 .iter()
386 .filter_map(|i| question.options.get(*i))
387 .map(|opt| UserInputAnswer {
388 id: question.id.clone(),
389 label: opt.label.clone(),
390 value: opt.label.clone(),
391 kind: Some(UserInputAnswerKind::Choice),
392 })
393 .collect();
394 return self.advance_question(answers);
395 }
396 // Enter on a real option selects it and moves to Confirm. It
397 // never toggles out: double-Enter must submit the highlighted
398 // option, matching single-select on the same view.
399 if !self.multi_pending.contains(&self.selected) {
400 self.multi_pending.push(self.selected);
401 }
402 if let Some(confirm) = self.confirm_index() {
403 self.selected = confirm;
404 }
405 return ViewAction::None;
406 }
407 // Single-select: submit immediately.
408 let answers = self.answers_for_selection(self.selected);
409 self.advance_question(answers)
410 }
411
412 fn handle_other_input_key(&mut self, key: KeyEvent) -> ViewAction {
413 match key.code {
414 KeyCode::Esc => {
415 self.mode = InputMode::Selecting;
416 self.other_input.clear();
417 ViewAction::None
418 }
419 KeyCode::Enter => {
420 let question = self.current_question();
421 let answer = (!self.other_input.trim().is_empty()).then(|| UserInputAnswer {
422 id: question.id.clone(),
423 label: String::new(),
424 value: self.other_input.clone(),
425 kind: Some(UserInputAnswerKind::Custom),
426 });
427 // In multi-select mode a free-text "Other" is still a single
428 // answer appended to whatever options were toggled.
429 let mut answers: Vec<UserInputAnswer> = self
430 .multi_pending
431 .iter()
432 .filter_map(|i| question.options.get(*i))
433 .map(|opt| UserInputAnswer {
434 id: question.id.clone(),
435 label: opt.label.clone(),
436 value: opt.label.clone(),
437 kind: Some(UserInputAnswerKind::Choice),
438 })
439 .collect();
440 answers.extend(answer);
441 self.advance_question(answers)
442 }
443 KeyCode::Backspace => {
444 self.other_input.pop();
445 ViewAction::None
446 }
447 KeyCode::Char('h')
448 if key
449 .modifiers
450 .contains(crossterm::event::KeyModifiers::CONTROL) =>
451 {
452 self.other_input.pop();
453 ViewAction::None
454 }
455 KeyCode::Char(ch) => {
456 if !ch.is_control() {
457 self.other_input.push(ch);
458 }
459 ViewAction::None
460 }
461 _ => ViewAction::None,
462 }
463 }
464 }
465
466 impl ModalView for UserInputView {
467 fn kind(&self) -> ModalKind {
468 ModalKind::UserInput
469 }
470
471 fn input_context_id(&self) -> usize {
472 self.question_index
473 }
474
475 fn user_input_request_id(&self) -> Option<&str> {
476 Some(&self.tool_id)
477 }
478
479 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
480 self
481 }
482
483 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
484 self.manual_scroll = false;
485 match self.mode {
486 InputMode::Selecting => self.handle_selecting_key(key),
487 InputMode::OtherInput => self.handle_other_input_key(key),
488 }
489 }
490
491 /// A pasted custom answer lands in the free-text field (U08-m1); while
492 /// choosing among options the paste is not consumed. Line breaks become
493 /// spaces because Enter submits this single-line answer.
494 fn handle_paste(&mut self, text: &str) -> bool {
495 if self.mode != InputMode::OtherInput {
496 return false;
497 }
498 self.other_input.extend(
499 text.chars()
500 .map(|ch| {
501 if matches!(ch, '\n' | '\r' | '\t') {
502 ' '
503 } else {
504 ch
505 }
506 })
507 .filter(|ch| !ch.is_control()),
508 );
509 true
510 }
511
512 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
513 let scroll = match mouse.kind {
514 MouseEventKind::ScrollUp => self.scroll_offset.get().saturating_sub(3),
515 MouseEventKind::ScrollDown => self.scroll_offset.get().saturating_add(3),
516 MouseEventKind::Down(MouseButton::Left) if self.mode == InputMode::Selecting => {
517 let position = Position::new(mouse.column, mouse.row);
518 let clicked = self
519 .option_hitboxes
520 .borrow()
521 .iter()
522 .position(|rect| rect.contains(position));
523 let Some(index) = clicked else {
524 return ViewAction::None;
525 };
526 self.selected = index;
527 return self.handle_key(KeyEvent::new(KeyCode::Enter, mouse.modifiers));
528 }
529 _ => return ViewAction::None,
530 };
531 self.manual_scroll = true;
532 self.scroll_offset.set(scroll.min(self.max_scroll.get()));
533 ViewAction::None
534 }
535
536 fn render(&self, area: Rect, buf: &mut Buffer) {
537 let question = self.current_question();
538 let locale = self.locale;
539 let total = self.request.questions.len();
540 let header = format!(
541 " {} ",
542 tr(locale, MessageId::UserInputQuestionProgress)
543 .replace("{current}", &(self.question_index + 1).to_string())
544 .replace("{total}", &total.to_string())
545 );
546
547 let mut lines: Vec<Line> = Vec::new();
548 lines.push(Line::from(vec![Span::styled(
549 tr(locale, MessageId::UserInputActionRequired),
550 Style::default().fg(palette::WHALE_ACTION).bold(),
551 )]));
552 lines.push(Line::from(vec![
553 Span::styled(
554 question.header.clone(),
555 Style::default().fg(palette::TEXT_PRIMARY).bold(),
556 ),
557 Span::styled(
558 format!(
559 " {}",
560 tr(locale, MessageId::UserInputQuestionProgress)
561 .replace("{current}", &(self.question_index + 1).to_string())
562 .replace("{total}", &total.to_string())
563 ),
564 Style::default().fg(palette::TEXT_MUTED),
565 ),
566 ]));
567 lines.push(Line::from(""));
568 lines.push(Line::from(vec![Span::styled(
569 question.question.clone(),
570 Style::default().fg(palette::TEXT_PRIMARY).bold(),
571 )]));
572 lines.push(Line::from(""));
573
574 if let Some(detail) = &question.detail {
575 lines.extend(detail.lines().map(|line| {
576 Line::from(Span::styled(
577 line.to_owned(),
578 Style::default().fg(palette::TEXT_PRIMARY),
579 ))
580 }));
581 lines.push(Line::from(""));
582 }
583 for (idx, option) in question.options.iter().enumerate() {
584 let number = idx + 1;
585 let ticked = self.is_multi_select() && self.multi_pending.contains(&idx);
586 push_option_lines(
587 &mut lines,
588 self.selected == idx,
589 number,
590 option.label.clone(),
591 option.description.clone(),
592 ticked,
593 );
594 }
595
596 if self.offers_other() {
597 let other_index = question.options.len();
598 let other_number = other_index + 1;
599 push_option_lines(
600 &mut lines,
601 self.selected == other_index,
602 other_number,
603 tr(locale, MessageId::UserInputOtherLabel).into_owned(),
604 tr(locale, MessageId::UserInputOtherDescription).into_owned(),
605 false,
606 );
607 }
608
609 // Multi-select gets a dedicated "Confirm selection" row after the
610 // options (and after "Other" when present). Selecting and pressing
611 // Enter on it flushes the pending set as the question's answers.
612 if let Some(confirm_index) = self.confirm_index() {
613 let confirm_number = confirm_index + 1;
614 push_option_lines(
615 &mut lines,
616 self.selected == confirm_index,
617 confirm_number,
618 tr(locale, MessageId::UserInputConfirmLabel).into_owned(),
619 tr(locale, MessageId::UserInputConfirmDescription)
620 .replace("{count}", &self.multi_pending.len().to_string()),
621 false,
622 );
623 }
624
625 if self.mode == InputMode::OtherInput {
626 lines.push(Line::from(""));
627 lines.push(Line::from(vec![
628 Span::styled(
629 format!("> {}", tr(locale, MessageId::UserInputCustomPrompt)),
630 Style::default().fg(palette::TEXT_PRIMARY).bold(),
631 ),
632 Span::raw(" "),
633 Span::styled(
634 if self.other_input.is_empty() {
635 tr(locale, MessageId::UserInputCustomPlaceholder).into_owned()
636 } else {
637 self.other_input.clone()
638 },
639 Style::default().fg(palette::WHALE_HUMAN),
640 ),
641 ]));
642 }
643
644 lines.push(Line::from(""));
645 if self.mode == InputMode::OtherInput {
646 lines.push(Line::from(vec![
647 Span::styled("Enter", Style::default().fg(palette::WHALE_ACTION).bold()),
648 hint_label(
649 locale,
650 if self.other_input.trim().is_empty() && self.multi_pending.is_empty() {
651 MessageId::SetupActionSkip
652 } else {
653 MessageId::UserInputHintSubmit
654 },
655 ),
656 Span::raw(" "),
657 Span::styled("Esc", Style::default().fg(palette::WHALE_ACTION).bold()),
658 hint_label(locale, MessageId::UserInputHintBack),
659 ]));
660 } else {
661 let opt_count = self.option_count();
662 let quick_pick_label = if opt_count <= 9 {
663 format!("1-{opt_count}")
664 } else {
665 tr(locale, MessageId::UserInputHintDigit).into_owned()
666 };
667 if self.is_multi_select() {
668 lines.push(Line::from(vec![
669 Span::styled(
670 quick_pick_label,
671 Style::default().fg(palette::WHALE_ACTION).bold(),
672 ),
673 hint_label(locale, MessageId::UserInputHintMove),
674 Span::raw(" "),
675 Span::styled("Space", Style::default().fg(palette::WHALE_ACTION).bold()),
676 hint_label(locale, MessageId::UserInputHintToggle),
677 Span::raw(" "),
678 Span::styled("Enter", Style::default().fg(palette::WHALE_ACTION).bold()),
679 hint_label(locale, MessageId::UserInputHintSelectConfirm),
680 Span::raw(" "),
681 Span::styled("←/h", Style::default().fg(palette::WHALE_ACTION).bold()),
682 hint_label(locale, MessageId::UserInputHintBack),
683 Span::raw(" "),
684 Span::styled("Esc", Style::default().fg(palette::WHALE_ACTION).bold()),
685 hint_label(locale, MessageId::UserInputHintCancel),
686 ]));
687 } else {
688 lines.push(Line::from(vec![
689 Span::styled(
690 quick_pick_label,
691 Style::default().fg(palette::WHALE_ACTION).bold(),
692 ),
693 hint_label(locale, MessageId::UserInputHintQuickPick),
694 Span::raw(" "),
695 Span::styled("↑/↓", Style::default().fg(palette::WHALE_ACTION).bold()),
696 hint_label(locale, MessageId::UserInputHintMove),
697 Span::raw(" "),
698 Span::styled("Enter", Style::default().fg(palette::WHALE_ACTION).bold()),
699 hint_label(locale, MessageId::UserInputHintConfirm),
700 Span::raw(" "),
701 Span::styled("←/h", Style::default().fg(palette::WHALE_ACTION).bold()),
702 hint_label(locale, MessageId::UserInputHintBack),
703 Span::raw(" "),
704 Span::styled("Esc", Style::default().fg(palette::WHALE_ACTION).bold()),
705 hint_label(locale, MessageId::UserInputHintCancel),
706 ]));
707 }
708 }
709
710 let popup_area = sheet_rect(area, self.content_line_count());
711 let inner_h = popup_area.height.saturating_sub(4) as usize;
712 let width = modal_block(&header).inner(popup_area).width.max(1);
713 let (start, end) = self.focused_line_range();
714 let (first, focus_end, total_rows, escaped, continued) =
715 PagerRows::line_range(&lines, usize::from(width), start, end);
716 let inner_h = inner_h.saturating_sub(usize::from(escaped || continued));
717 let focus_start = if self.mode == InputMode::OtherInput {
718 focus_end
719 } else {
720 first
721 };
722 let max_scroll = total_rows.saturating_sub(inner_h);
723 let scroll = if self.manual_scroll {
724 self.scroll_offset.get().min(max_scroll)
725 } else {
726 scroll_to_keep_range_visible((focus_start, focus_end), total_rows, inner_h)
727 };
728 self.scroll_offset.set(scroll);
729 self.max_scroll.set(max_scroll);
730 let inner = modal_block(&header).inner(popup_area);
731 let window = scroll..scroll + inner_h;
732 *self.option_hitboxes.borrow_mut() = (0..self.option_count())
733 .map(|index| {
734 let (start, end) = self.option_line_range(index);
735 let (first, last, ..) =
736 PagerRows::line_range(&lines, usize::from(width), start, end);
737 let top = first.clamp(window.start, window.end);
738 let bottom = (last + 1).clamp(window.start, window.end);
739 Rect {
740 x: inner.x,
741 y: inner.y + u16::try_from(top - scroll).unwrap_or(u16::MAX),
742 width: inner.width,
743 height: u16::try_from(bottom - top).unwrap_or(u16::MAX),
744 }
745 })
746 .collect();
747 let rows = PagerRows::wrap_lines_window(&lines, usize::from(width), scroll);
748 let notice = rows.display_notice(locale, true);
749 let mut visible: Vec<_> = rows.styled.into_iter().take(inner_h).collect();
750 if let Some(notice) = notice {
751 visible.push(Line::from(Span::styled(
752 codewhale_tui_kit::ui_text::truncate_line_to_width(&notice, usize::from(width)),
753 Style::default().fg(palette::TEXT_MUTED),
754 )));
755 }
756 let paragraph = Paragraph::new(visible)
757 .alignment(Alignment::Left)
758 .block(modal_block(&header));
759
760 render_modal_chrome(area, popup_area, buf);
761 paragraph.render(popup_area, buf);
762 }
763
764 fn occupied_region(&self, area: Rect) -> Rect {
765 // Bottom sheet plus the one-cell drop shadow `render_modal_surface`
766 // draws at +1/+1. Transcript above the sheet stays undimmed.
767 let popup = sheet_rect(area, self.content_line_count());
768 Rect {
769 x: popup.x,
770 y: popup.y,
771 width: (popup.width.saturating_add(1)).min(area.right().saturating_sub(popup.x)),
772 height: (popup.height.saturating_add(1)).min(area.bottom().saturating_sub(popup.y)),
773 }
774 }
775 }
776
777 /// Bottom-anchored sheet: grows with content, leaves a transcript strip
778 /// above when the frame is tall enough, and never uses a fixed 22-row cap
779 /// that clips options on every terminal ≥ 37 rows (#6045).
780 fn sheet_rect(r: Rect, content_lines: usize) -> Rect {
781 if r.width == 0 || r.height == 0 {
782 return Rect {
783 x: r.x,
784 y: r.y.saturating_add(r.height),
785 width: 0,
786 height: 0,
787 };
788 }
789 let desired = u16::try_from(content_lines)
790 .unwrap_or(u16::MAX)
791 .saturating_add(4);
792 let transcript_reserve = if r.height >= 16 {
793 4u16.min(r.height.saturating_sub(8))
794 } else {
795 0
796 };
797 let max_height = r
798 .height
799 .saturating_sub(transcript_reserve)
800 .max(6.min(r.height));
801 let height = desired.min(max_height).max(6.min(r.height)).min(r.height);
802 Rect {
803 x: r.x,
804 y: r.y.saturating_add(r.height.saturating_sub(height)),
805 width: r.width,
806 height,
807 }
808 }
809
810 fn scroll_to_keep_range_visible(
811 (focus_start, focus_end): (usize, usize),
812 total_lines: usize,
813 inner_h: usize,
814 ) -> usize {
815 if inner_h == 0 || total_lines <= inner_h {
816 return 0;
817 }
818 let max_scroll = total_lines.saturating_sub(inner_h);
819 let mut scroll = 0usize;
820 if focus_end >= inner_h {
821 scroll = focus_end.saturating_add(1).saturating_sub(inner_h);
822 }
823 if focus_start < scroll {
824 scroll = focus_start;
825 }
826 scroll.min(max_scroll)
827 }
828
829 #[cfg(test)]
830 mod tests {
831 use super::*;
832 use codewhale_engine::tools::user_input::{
833 UserInputOption, UserInputQuestion, UserInputRequest,
834 };
835
836 fn render_view(view: &UserInputView, width: u16, height: u16) -> String {
837 let area = Rect::new(0, 0, width, height);
838 let mut buf = Buffer::empty(area);
839 view.render(area, &mut buf);
840
841 (0..height)
842 .map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect::<String>())
843 .collect::<Vec<_>>()
844 .join("\n")
845 }
846
847 fn sample_view() -> UserInputView {
848 UserInputView::new(
849 "tool-1",
850 UserInputRequest {
851 require_typed_answers: false,
852 questions: vec![UserInputQuestion {
853 detail: None,
854 intent: None,
855 header: "Confirm".to_string(),
856 id: "confirm".to_string(),
857 question: "What should happen next?".to_string(),
858 options: vec![
859 UserInputOption {
860 label: "Ship it".to_string(),
861 description: "Proceed with the current change set".to_string(),
862 },
863 UserInputOption {
864 label: "Revise it".to_string(),
865 description: "Return to editing before continuing".to_string(),
866 },
867 ],
868 allow_free_text: true,
869 multi_select: false,
870 }],
871 },
872 Locale::En,
873 )
874 }
875
876 #[test]
877 fn user_input_modal_calls_out_required_action_and_controls() {
878 let rendered = render_view(&sample_view(), 110, 36);
879
880 assert!(rendered.contains("Action required"));
881 assert!(rendered.contains("Question 1 of 1"));
882 assert!(rendered.contains("quick pick"));
883 // allow_free_text=true surfaces the Other row.
884 assert!(rendered.contains("Other"));
885 }
886
887 #[test]
888 fn clicking_a_painted_option_submits_it() {
889 let mut view = sample_view();
890 let rendered = render_view(&view, 110, 36);
891 let row = rendered
892 .lines()
893 .position(|line| line.contains("2) Revise it"))
894 .expect("option row painted");
895 let action = view.handle_mouse(MouseEvent {
896 kind: MouseEventKind::Down(MouseButton::Left),
897 column: 20,
898 row: u16::try_from(row).unwrap(),
899 modifiers: crossterm::event::KeyModifiers::NONE,
900 });
901 let ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted { response, .. }) = action
902 else {
903 panic!("click must submit the clicked option")
904 };
905 assert_eq!(response.answers[0].label, "Revise it");
906 }
907
908 #[test]
909 fn user_input_modal_renders_custom_response_state() {
910 let mut view = sample_view();
911 view.selected = 2;
912 view.mode = InputMode::OtherInput;
913 view.other_input = "Need one more pass".to_string();
914
915 let rendered = render_view(&view, 110, 36);
916
917 assert!(rendered.contains("Custom response"));
918 assert!(rendered.contains("Need one more pass"));
919 assert!(rendered.contains("Enter"));
920 assert!(rendered.contains("submit"));
921 }
922
923 #[test]
924 fn user_input_modal_keeps_other_row_when_free_text_disabled() {
925 // v0.9.4: a custom free-text response is ALWAYS available alongside
926 // the options, even when the model did not offer it. The wire field
927 // `allow_free_text` stays for backward compatibility but no longer
928 // gates the row (#3102 originally hid it).
929 let mut view = sample_view();
930 view.request.questions[0].allow_free_text = false;
931 view.selected = 0;
932
933 let rendered = render_view(&view, 110, 36);
934 assert!(
935 rendered.contains("Type a custom response"),
936 "Other row must stay reachable even when allow_free_text is false"
937 );
938 assert!(rendered.contains("Other"));
939
940 // Entering the row switches to free-text input mode regardless.
941 view.selected = view.option_count() - 1;
942 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Enter));
943 assert!(matches!(action, ViewAction::None));
944 assert_eq!(view.mode, InputMode::OtherInput);
945
946 for allow_free_text in [false, true] {
947 let mut view = sample_view();
948 view.request.require_typed_answers = true;
949 view.request.questions[0].allow_free_text = allow_free_text;
950 assert_eq!(view.offers_other(), allow_free_text);
951 assert_eq!(view.option_count(), 2 + usize::from(allow_free_text));
952 let rendered = render_view(&view, 110, 36);
953 assert_eq!(rendered.contains("Type a custom response"), allow_free_text);
954 view.selected = view.option_count() - 1;
955 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Enter));
956 let action = if allow_free_text {
957 assert!(matches!(action, ViewAction::None));
958 assert_eq!(view.mode, InputMode::OtherInput);
959 view.other_input = " custom answer ".into();
960 view.handle_other_input_key(KeyEvent::from(KeyCode::Enter))
961 } else {
962 action
963 };
964 let ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted { response, .. }) = action
965 else {
966 panic!("expected valid typed answer")
967 };
968 assert_eq!(
969 response.answers[0].kind,
970 Some(if allow_free_text {
971 UserInputAnswerKind::Custom
972 } else {
973 UserInputAnswerKind::Choice
974 })
975 );
976 view.request.validate_response(&response).unwrap();
977 }
978 let mut view = sample_view();
979 view.request.require_typed_answers = true;
980 view.request.questions[0].allow_free_text = false;
981 view.request.questions[0].multi_select = true;
982 assert_eq!(view.option_count(), 3);
983 view.selected = view.confirm_index().unwrap();
984 assert!(!view.is_other_selected());
985 view.multi_pending = vec![0, 1];
986 let ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted { response, .. }) =
987 view.handle_selecting_key(KeyEvent::from(KeyCode::Enter))
988 else {
989 panic!("expected typed choices")
990 };
991 assert_eq!(response.answers.len(), 2);
992 assert!(
993 response
994 .answers
995 .iter()
996 .all(|answer| answer.kind == Some(UserInputAnswerKind::Choice))
997 );
998 view.request.validate_response(&response).unwrap();
999 }
1000
1001 #[test]
1002 fn user_input_modal_renders_multi_select_ticks_and_confirm() {
1003 // Issue #3102: multi_select=true renders a check-mark gutter on
1004 // toggled options plus a trailing "Confirm selection" row, and the
1005 // controls hint advertises Space/Enter toggle semantics. With the
1006 // v0.9.4 always-available Other row, confirm sits at index 3.
1007 let mut view = sample_view();
1008 view.request.questions[0].multi_select = true;
1009 view.request.questions[0].allow_free_text = false;
1010 // Toggle the first option into the pending set.
1011 view.multi_pending.push(0);
1012 // Highlight the confirm row (last selectable row).
1013 view.selected = view.option_count() - 1;
1014
1015 let rendered = render_view(&view, 120, 40);
1016 assert!(rendered.contains("✔"), "toggled option shows a check mark");
1017 assert!(
1018 rendered.contains("Confirm selection"),
1019 "multi-select renders a confirm row"
1020 );
1021 assert!(rendered.contains("Submit 1 selected"));
1022 assert!(rendered.contains("toggle"));
1023 assert!(
1024 rendered.contains("▸ 4) Confirm selection"),
1025 "confirm row should display selected focus at its real quick-pick index"
1026 );
1027 assert!(
1028 !rendered.contains("5) Confirm selection"),
1029 "confirm row must not advertise an unreachable quick-pick number"
1030 );
1031 }
1032
1033 #[test]
1034 fn user_input_modal_space_toggles_and_enter_confirms_multi_select() {
1035 // Keyboard-first multi-select: Space toggles the highlighted option
1036 // into the pending set without leaving the picker; Enter on the
1037 // confirm row flushes the set.
1038 let mut view = sample_view();
1039 view.request.questions[0].multi_select = true;
1040 view.selected = 0;
1041
1042 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Char(' ')));
1043 assert!(matches!(action, ViewAction::None));
1044 assert_eq!(view.multi_pending, vec![0], "Space toggles option 0 in");
1045
1046 let _action = view.handle_selecting_key(KeyEvent::from(KeyCode::Char(' ')));
1047 assert!(view.multi_pending.is_empty(), "Space toggles option 0 out");
1048
1049 // Space on the confirm row must not toggle it (it is not an option).
1050 view.selected = view.confirm_index().expect("confirm row present");
1051 let before = view.multi_pending.clone();
1052 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Char(' ')));
1053 assert!(matches!(action, ViewAction::None));
1054 assert_eq!(view.multi_pending, before, "Space on confirm is a no-op");
1055
1056 // Enter on the confirm row flushes the pending set as answers.
1057 view.multi_pending.push(0);
1058 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Enter));
1059 assert!(
1060 matches!(action, ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted { tool_id, response })
1061 if tool_id == "tool-1" && response.answers.first().is_some_and(|a| a.value == "Ship it")),
1062 "Enter on confirm submits the toggled options"
1063 );
1064 let mut view = sample_view();
1065 view.request.require_typed_answers = true;
1066 view.request.questions[0].multi_select = true;
1067 view.request.questions[0].options[0].label = "Other".into();
1068 view.request.questions[0].options[1].label = "one, two".into();
1069 view.multi_pending = vec![0, 1];
1070 view.other_input = " custom reply ".into();
1071 let action = view.handle_other_input_key(KeyEvent::from(KeyCode::Enter));
1072 let ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted { response, .. }) = action
1073 else {
1074 panic!("expected typed answer")
1075 };
1076 assert_eq!(response.answers.len(), 3);
1077 assert_eq!(response.answers[0].label, "Other");
1078 assert_eq!(response.answers[1].value, "one, two");
1079 assert_eq!(response.answers[2].kind, Some(UserInputAnswerKind::Custom));
1080 assert_eq!(response.answers[2].label, "");
1081 assert_eq!(response.answers[2].value, " custom reply ");
1082 view.request.validate_response(&response).unwrap();
1083 let mut view = sample_view();
1084 view.request.require_typed_answers = true;
1085 view.other_input.clear();
1086 let action = view.handle_other_input_key(KeyEvent::from(KeyCode::Enter));
1087 let ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted { response, .. }) = action
1088 else {
1089 panic!("expected explicit skip")
1090 };
1091 assert_eq!(response.answers[0].kind, Some(UserInputAnswerKind::Skipped));
1092 view.request.validate_response(&response).unwrap();
1093 }
1094
1095 #[test]
1096 fn user_input_modal_double_enter_never_submits_empty_multi_select() {
1097 // Enter on a multi-select option used to toggle it into the pending
1098 // set, so a second Enter (single-select muscle memory) toggled it
1099 // back out — and Confirm then submitted an empty answer set.
1100 let mut view = sample_view();
1101 view.request.questions[0].multi_select = true;
1102 view.selected = 0;
1103
1104 // First Enter: option 0 joins the pending set, focus moves to Confirm.
1105 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Enter));
1106 assert!(matches!(action, ViewAction::None));
1107 assert_eq!(
1108 view.multi_pending,
1109 vec![0],
1110 "Enter selects the highlighted option"
1111 );
1112 assert!(
1113 view.is_confirm_selected(),
1114 "focus moves to the Confirm row after Enter"
1115 );
1116
1117 // Second Enter submits exactly that option — never an empty set.
1118 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Enter));
1119 assert!(
1120 matches!(action, ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted { tool_id, response })
1121 if tool_id == "tool-1"
1122 && response.answers.len() == 1
1123 && response.answers[0].value == "Ship it"),
1124 "double-Enter must submit the highlighted option, not an empty set"
1125 );
1126 }
1127
1128 #[test]
1129 fn user_input_modal_enter_never_deselects_multi_select_option() {
1130 // Deselecting remains Space's job: Enter on an already-toggled option
1131 // keeps it in the pending set.
1132 let mut view = sample_view();
1133 view.request.questions[0].multi_select = true;
1134 view.selected = 0;
1135
1136 let _ = view.handle_selecting_key(KeyEvent::from(KeyCode::Char(' ')));
1137 assert_eq!(view.multi_pending, vec![0], "Space toggles option 0 in");
1138
1139 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Enter));
1140 assert!(matches!(action, ViewAction::None));
1141 assert_eq!(
1142 view.multi_pending,
1143 vec![0],
1144 "Enter must not toggle the option back out"
1145 );
1146
1147 // Space still toggles both ways.
1148 view.selected = 0;
1149 let _ = view.handle_selecting_key(KeyEvent::from(KeyCode::Char(' ')));
1150 assert!(view.multi_pending.is_empty(), "Space toggles option 0 out");
1151 }
1152
1153 fn many_option_view() -> UserInputView {
1154 UserInputView::new(
1155 "tool-1",
1156 UserInputRequest {
1157 require_typed_answers: false,
1158 questions: vec![
1159 UserInputQuestion {
1160 detail: None,
1161 intent: None,
1162 header: "Choose".to_string(),
1163 id: "q1".to_string(),
1164 question: "Which path?".to_string(),
1165 options: (1..=8)
1166 .map(|n| UserInputOption {
1167 label: format!("Option {n}"),
1168 description: format!(
1169 "A longer description for option {n} that wraps on a narrow terminal"
1170 ),
1171 })
1172 .collect(),
1173 allow_free_text: true,
1174 multi_select: false,
1175 },
1176 UserInputQuestion {
1177 detail: None,
1178 intent: None,
1179 header: "Confirm".to_string(),
1180 id: "q2".to_string(),
1181 question: "Second question after the first.".to_string(),
1182 options: vec![UserInputOption {
1183 label: "Yes".to_string(),
1184 description: "Proceed".to_string(),
1185 }],
1186 allow_free_text: true,
1187 multi_select: false,
1188 },
1189 ],
1190 },
1191 Locale::En,
1192 )
1193 }
1194
1195 #[test]
1196 fn user_input_sheet_is_bottom_anchored_and_not_capped_at_22() {
1197 let area = Rect::new(0, 0, 141, 38);
1198 let view = many_option_view();
1199 let content = view.content_line_count();
1200 let popup = sheet_rect(area, content);
1201
1202 assert_eq!(
1203 popup.bottom(),
1204 area.bottom(),
1205 "sheet must sit on the bottom"
1206 );
1207 assert!(popup.y > 0, "transcript strip remains above the sheet");
1208 assert_eq!(popup.width, area.width);
1209 assert!(
1210 popup.height > 22,
1211 "141×38 must not be stuck at the old 22-row cap, got {}",
1212 popup.height
1213 );
1214
1215 let capped = sheet_rect(area, 100);
1216 assert!(
1217 capped.height > 22,
1218 "long content may grow past 22 rows; got {}",
1219 capped.height
1220 );
1221 assert_eq!(capped.bottom(), area.bottom());
1222 }
1223
1224 fn wheel(view: &mut UserInputView, kind: MouseEventKind) {
1225 assert!(matches!(
1226 view.handle_mouse(MouseEvent {
1227 kind,
1228 column: 1,
1229 row: 1,
1230 modifiers: crossterm::event::KeyModifiers::NONE,
1231 }),
1232 ViewAction::None
1233 ));
1234 }
1235
1236 #[test]
1237 fn user_input_wheel_browses_wrapped_rows_without_changing_answers() {
1238 for (width, height) in [(40, 12), (80, 24), (100, 32), (141, 38)] {
1239 let mut view = many_option_view();
1240 view.request.questions[0].multi_select = true;
1241 view.multi_pending.push(0);
1242 let before = render_view(&view, width, height);
1243 let initial = view.scroll_offset.get();
1244 wheel(&mut view, MouseEventKind::ScrollDown);
1245 let after = render_view(&view, width, height);
1246 assert_eq!(
1247 view.scroll_offset.get(),
1248 (initial + 3).min(view.max_scroll.get())
1249 );
1250 if view.max_scroll.get() == 0 {
1251 assert_eq!(before, after, "fully visible content must stay still");
1252 } else {
1253 assert_ne!(
1254 before, after,
1255 "overflowing question content must scroll at {width}x{height}"
1256 );
1257 }
1258 assert_eq!(view.selected, 0);
1259 assert_eq!(view.multi_pending, [0]);
1260 assert!(view.answered.is_empty());
1261
1262 for _ in 0..100 {
1263 wheel(&mut view, MouseEventKind::ScrollDown);
1264 }
1265 assert_eq!(view.scroll_offset.get(), view.max_scroll.get());
1266 view.handle_key(KeyEvent::from(KeyCode::Down));
1267 let focused = render_view(&view, width, height);
1268 assert!(focused.contains("▸ 2) Option 2"), "{focused}");
1269 assert_eq!(view.multi_pending, [0]);
1270 for _ in 0..100 {
1271 wheel(&mut view, MouseEventKind::ScrollUp);
1272 }
1273 assert_eq!(view.scroll_offset.get(), 0);
1274 }
1275 for count in [0, 1, 100] {
1276 let mut request = sample_view().request;
1277 request.require_typed_answers = true;
1278 request.questions[0].header.clear();
1279 request.questions[0].detail = Some("Supporting detail\nSecond line".into());
1280 request.questions[0].options = (0..count)
1281 .map(|index| UserInputOption {
1282 label: format!("Choice {index}"),
1283 description: String::new(),
1284 })
1285 .collect();
1286 request.validate_transport().unwrap();
1287 let mut view = UserInputView::new("menu", request, Locale::En);
1288 assert_eq!(
1289 view.mode,
1290 if count == 0 {
1291 InputMode::OtherInput
1292 } else {
1293 InputMode::Selecting
1294 }
1295 );
1296 if count > 0 {
1297 view.selected = count - 1;
1298 let rendered = render_view(&view, 80, 24);
1299 assert!(
1300 rendered.contains(&format!("Choice {}", count - 1)),
1301 "{rendered}"
1302 );
1303 let (start, end) = view.focused_line_range();
1304 assert_eq!(start, end);
1305 } else {
1306 let rendered = render_view(&view, 80, 24);
1307 assert!(rendered.contains("Supporting detail"));
1308 assert!(rendered.contains("Custom response"));
1309 assert!(rendered.contains("skip"));
1310 }
1311 }
1312 }
1313
1314 #[test]
1315 fn user_input_wheel_resize_and_typing_restore_custom_answer_visibility() {
1316 let mut view = many_option_view();
1317 view.selected = view.option_count() - 1;
1318 view.handle_key(KeyEvent::from(KeyCode::Enter));
1319 for ch in "retained custom answer".chars() {
1320 view.handle_key(KeyEvent::from(KeyCode::Char(ch)));
1321 }
1322 render_view(&view, 40, 12);
1323 wheel(&mut view, MouseEventKind::ScrollDown);
1324 let narrow_offset = view.scroll_offset.get();
1325 render_view(&view, 141, 38);
1326 assert!(view.max_scroll.get() < narrow_offset);
1327 assert_eq!(view.scroll_offset.get(), view.max_scroll.get());
1328
1329 render_view(&view, 40, 12);
1330 for _ in 0..100 {
1331 wheel(&mut view, MouseEventKind::ScrollUp);
1332 }
1333 let browsing = render_view(&view, 40, 12);
1334 assert!(!browsing.contains("retained custom answer"));
1335 view.handle_key(KeyEvent::from(KeyCode::Char('!')));
1336 let editing = render_view(&view, 40, 12);
1337 assert!(editing.contains("answer!"), "{editing}");
1338 assert_eq!(view.other_input, "retained custom answer!");
1339 view.handle_key(KeyEvent::from(KeyCode::Enter));
1340 assert_eq!(view.answered[0][0].value, "retained custom answer!");
1341 assert_eq!(view.question_index, 1);
1342 view.handle_key(KeyEvent::from(KeyCode::Left));
1343 assert_eq!(view.question_index, 0);
1344 assert!(
1345 view.answered.is_empty(),
1346 "back navigation permits correction"
1347 );
1348 }
1349
1350 #[test]
1351 fn user_input_sheet_fits_80x24_and_keeps_selection_visible() {
1352 let mut view = many_option_view();
1353 view.selected = 7;
1354 let rendered = render_view(&view, 80, 24);
1355 assert!(
1356 rendered.contains("Option 8") || rendered.contains("8) Option"),
1357 "selected last option must be scrolled into view on 80×24:\n{rendered}"
1358 );
1359 let popup = sheet_rect(Rect::new(0, 0, 80, 24), view.content_line_count());
1360 assert_eq!(popup.bottom(), 24);
1361 assert!(popup.height <= 24);
1362 }
1363
1364 #[test]
1365 fn wrapped_questions_keep_choices_and_custom_typing_visible() {
1366 let mut view = sample_view();
1367 let question = &mut view.request.questions[0];
1368 question.question = "Choose a synthetic option to verify the question sheet, its scrolling, and visible selection when both the question and option descriptions wrap across several terminal rows.".into();
1369 question.options = (1..=4)
1370 .map(|n| UserInputOption {
1371 label: format!("Option {n}"),
1372 description: "This synthetic option has a long description that wraps across several rows; choosing it writes no external state and triggers no provider charge.".into(),
1373 })
1374 .collect();
1375 question.multi_select = true;
1376
1377 for (width, height) in [(40, 12), (60, 16), (80, 24), (100, 32), (140, 40)] {
1378 view.mode = InputMode::Selecting;
1379 for selected in 0..view.option_count() {
1380 view.selected = selected;
1381 let label = match selected {
1382 4 => "Other".to_string(),
1383 5 => "Confirm selection".to_string(),
1384 _ => format!("Option {}", selected + 1),
1385 };
1386 let focused = format!(
1387 "{} {}) {label}",
1388 codewhale_tui_kit::glyphs::selection_marker(true),
1389 selected + 1
1390 );
1391 let rendered = render_view(&view, width, height);
1392 assert!(
1393 rendered.contains(&focused),
1394 "highlighted choice must remain visible at {width}x{height}:\n{rendered}"
1395 );
1396 }
1397 view.mode = InputMode::OtherInput;
1398 view.other_input = format!("{}TAIL_SENTINEL", "輸入 text ".repeat(40));
1399 let rendered = render_view(&view, width, height);
1400 assert!(
1401 rendered.contains("TAIL_SENTINEL"),
1402 "custom-response typing end must remain visible at {width}x{height}:\n{rendered}"
1403 );
1404 }
1405
1406 for detail in ["d\n".repeat(70_000), "x".repeat(900_000)] {
1407 let mut view = sample_view();
1408 view.request.questions[0].detail = Some(detail);
1409 view.request.questions[0].options[0].label = "Z".into();
1410 view.request.questions[0].options[0].description.clear();
1411 view.request.validate_transport().unwrap();
1412 let rendered = render_view(&view, 16, 24);
1413 assert!(view.scroll_offset.get() > usize::from(u16::MAX));
1414 assert!(rendered.contains("1) Z"), "{rendered}");
1415 view.handle_key(KeyEvent::from(KeyCode::Enter));
1416 assert_eq!(view.answered[0][0].label, "Z");
1417 }
1418
1419 let mut view = sample_view();
1420 view.mode = InputMode::OtherInput;
1421 view.other_input = format!("{} END", "x".repeat(800_000));
1422 let rendered = render_view(&view, 16, 24);
1423 assert!(view.scroll_offset.get() > usize::from(u16::MAX));
1424 assert!(rendered.contains("END"), "{rendered}");
1425 view.handle_key(KeyEvent::from(KeyCode::Enter));
1426 assert_eq!(view.answered[0][0].value.len(), 800_004);
1427 assert!(view.answered[0][0].value.ends_with(" END"));
1428 }
1429
1430 #[test]
1431 fn user_input_custom_response_stays_visible_while_typing() {
1432 let mut view = many_option_view();
1433 view.selected = view.option_count() - 1;
1434 view.mode = InputMode::OtherInput;
1435 view.other_input = "Need one more pass on the last option".to_string();
1436 for (width, height) in [(141, 38), (80, 24)] {
1437 let rendered = render_view(&view, width, height);
1438 assert!(
1439 rendered.contains("Need one more pass"),
1440 "typed custom response must stay visible at {width}×{height}:\n{rendered}"
1441 );
1442 }
1443 }
1444
1445 #[test]
1446 fn user_input_left_goes_back_to_previous_question() {
1447 let mut view = many_option_view();
1448 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Enter));
1449 assert!(matches!(action, ViewAction::None));
1450 assert_eq!(view.question_index, 1);
1451 assert_eq!(view.answered.len(), 1);
1452
1453 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Left));
1454 assert!(matches!(action, ViewAction::None));
1455 assert_eq!(view.question_index, 0);
1456 assert!(view.answered.is_empty());
1457
1458 let action = view.handle_selecting_key(KeyEvent::from(KeyCode::Char('h')));
1459 assert!(matches!(action, ViewAction::None));
1460 assert_eq!(
1461 view.question_index, 0,
1462 "back on the first question is a no-op"
1463 );
1464
1465 let mut view = many_option_view();
1466 view.request.require_typed_answers = true;
1467 view.request.questions[1].multi_select = true;
1468 assert!(matches!(
1469 view.handle_key(KeyEvent::from(KeyCode::Enter)),
1470 ViewAction::None
1471 ));
1472 let prior = view.answered.clone();
1473 view.mode = InputMode::OtherInput;
1474 view.multi_pending = vec![0];
1475 view.other_input = "🦀".repeat(262_144);
1476 let draft = view.other_input.clone();
1477 let action = view.handle_key(KeyEvent::from(KeyCode::Enter));
1478 assert!(
1479 matches!(action, ViewAction::Emit(ViewEvent::StatusToast { message, level: crate::tui::app::StatusToastLevel::Warning }) if message.contains("transport limits"))
1480 );
1481 assert_eq!(view.answered, prior);
1482 assert_eq!(view.question_index, 1);
1483 assert_eq!(view.mode, InputMode::OtherInput);
1484 assert_eq!(view.multi_pending, vec![0]);
1485 assert_eq!(view.other_input, draft);
1486 view.other_input = " corrected answer ".into();
1487 let ViewAction::EmitAndClose(ViewEvent::UserInputSubmitted { response, .. }) =
1488 view.handle_key(KeyEvent::from(KeyCode::Enter))
1489 else {
1490 panic!("expected corrected response")
1491 };
1492 assert_eq!(response.answers.len(), 3);
1493 assert_eq!(response.answers[0], prior[0][0]);
1494 assert_eq!(response.answers[2].value, " corrected answer ");
1495 view.request.validate_response(&response).unwrap();
1496 }
1497
1498 #[test]
1499 fn user_input_modal_occupied_region_matches_painted_card_plus_shadow() {
1500 let area = Rect::new(0, 0, 120, 40);
1501 let view = sample_view();
1502 let popup = sheet_rect(area, view.content_line_count());
1503 let occupied = view.occupied_region(area);
1504
1505 assert_eq!(occupied.x, popup.x);
1506 assert_eq!(occupied.y, popup.y);
1507 assert_eq!(
1508 occupied.width,
1509 (popup.width.saturating_add(1)).min(area.right().saturating_sub(popup.x))
1510 );
1511 assert_eq!(
1512 occupied.height,
1513 (popup.height.saturating_add(1)).min(area.bottom().saturating_sub(popup.y))
1514 );
1515 assert!(area.right() >= occupied.right());
1516 assert!(area.bottom() >= occupied.bottom());
1517 }
1518
1519 #[test]
1520 fn user_input_modal_leaves_surrounding_frame_visible() {
1521 use crate::tui::views::ViewStack;
1522
1523 let area = Rect::new(0, 0, 120, 40);
1524 let mut buf = Buffer::empty(area);
1525 // Pre-fill the frame as if the live transcript had painted it.
1526 for y in 0..area.height {
1527 for x in 0..area.width {
1528 buf[(x, y)].set_symbol("·");
1529 }
1530 }
1531
1532 let mut stack = ViewStack::default();
1533 stack.push(sample_view());
1534 stack.render(area, &mut buf);
1535
1536 // Transcript above the bottom sheet survives untouched.
1537 assert_eq!(buf[(0, 0)].symbol(), "·");
1538 assert_eq!(buf[(119, 0)].symbol(), "·");
1539 assert_eq!(buf[(60, 0)].symbol(), "·");
1540 assert_eq!(buf[(60, 4)].symbol(), "·");
1541 // The sheet itself is blanked + repainted by the modal surface.
1542 assert_ne!(buf[(60, 39)].symbol(), "·");
1543 assert_ne!(buf[(0, 39)].symbol(), "·");
1544 assert_ne!(buf[(119, 39)].symbol(), "·");
1545 }
1546
1547 #[test]
1548 fn user_input_modal_numbers_confirm_after_other_row() {
1549 let mut view = sample_view();
1550 view.request.questions[0].multi_select = true;
1551 view.request.questions[0].allow_free_text = true;
1552 view.selected = view.option_count() - 1;
1553
1554 let rendered = render_view(&view, 120, 40);
1555 assert!(rendered.contains("3) Other"));
1556 assert!(
1557 rendered.contains("▸ 4) Confirm selection"),
1558 "confirm should follow the optional Other row with selected focus"
1559 );
1560 assert!(!rendered.contains("5) Confirm selection"));
1561 }
1562 }
1563
1563 lines RUST