Allow paging through long choices in async questions (#62209)

## Why

A choice taller than the TUI's answer area could never be displayed in
full at that terminal size, so users could neither read it to the end
nor submit it.

## What changed

Let `PageUp` and `PageDown` scroll through the wrapped lines of an
oversized choice while keeping it selected. Allow submission once every
line of the choice has been displayed in order and at full width.

## Testing

Add regression coverage for paging without changing the selection,
rejecting submission when repeated page keys skip lines before redraw,
and rejecting choices clipped horizontally.

GitOrigin-RevId: c296323494bd387581c2bb046272a8ccd773ad75
This commit is contained in:
Benjamin Carlsson
2026-11-18 06:50:26 +00:00
committed by copyberry
parent 86d0e458e3
commit ba8ab2d050
10 changed files with 371 additions and 128 deletions
@@ -28,6 +28,9 @@ impl AsyncQuestions {
}
pub(super) fn select_option(&mut self, index: usize) {
if self.selected_option_index() != Some(index) {
self.option_viewport.get_mut().selected = None;
}
self.save_current_draft();
self.state.pending[self.state.current_idx]
.options_state
@@ -83,32 +86,18 @@ impl AsyncQuestions {
)
}
pub(super) fn render_inline_options(&self, area: Rect, buf: &mut ratatui::buffer::Buffer) {
pub(super) fn render_inline_options(
&self,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
lines: &[Vec<HyperlinkLine>],
) {
use ratatui::text::Line;
use ratatui::widgets::Widget;
let input = self.other_input_area(area);
let named_area = Rect::new(area.x, area.y, area.width, input.y.saturating_sub(area.y));
let mut rows = self.option_rows(named_area.width);
rows.pop();
let mut state = ScrollState::default();
while state.scroll_top + 1 < rows.len()
&& measure_rows_height(&rows, &state, rows.len(), named_area.width) > named_area.height
{
state.scroll_top += 1;
}
if measure_rows_height(&rows, &state, rows.len(), named_area.width) <= named_area.height {
self.visible_options
.set((state.scroll_top, rows.len() - state.scroll_top));
}
crate::bottom_pane::request_user_input::render::render_rows_bottom_aligned(
named_area,
buf,
&rows,
&state,
rows.len(),
"",
);
self.render_scrollable_options(named_area, buf, lines);
let margin = Rect::new(
area.x,
input.y,
@@ -197,6 +186,9 @@ impl BottomPaneView for AsyncQuestions {
}
return;
}
if self.page_content(key) {
return;
}
if self.has_options() {
// Default j/k start Other; explicit printable list remaps keep their meaning.
let printable = matches!(key.code, KeyCode::Char(_))
@@ -209,7 +201,7 @@ impl BottomPaneView for AsyncQuestions {
&& (!self.focus_is_notes() || matches!(key.code, KeyCode::Up | KeyCode::Down))
{
let count = self.options_len();
let visible = self.visible_options.get().1.max(1);
let visible = self.option_viewport.borrow().visible.len().max(1);
let mut state = self.state.pending[self.state.current_idx].options_state;
match self.keymap.list.action_for(key) {
Some(ListAction::MoveUp) => state.move_up_wrap(count),
@@ -13,6 +13,7 @@ pub(super) struct LayoutSections {
pub(super) question_area: Rect,
pub(super) question_lines: Vec<HyperlinkLine>,
pub(super) options_area: Rect,
pub(super) option_lines: Vec<Vec<HyperlinkLine>>,
/// Layout already measured the wrapped choices, so the footer can use this flag
/// without parsing and wrapping their Markdown again.
pub(super) show_option_tip: bool,
@@ -24,7 +25,8 @@ pub(super) struct LayoutSections {
impl AsyncQuestions {
pub(super) fn layout_sections(&self, area: Rect) -> LayoutSections {
let has_options = self.has_options();
let full_options_height = self.options_required_height(area.width);
let option_lines = self.option_rows(area.width);
let full_options_height = self.answer_height(area.width, &option_lines);
let mut question_lines = self.wrapped_question_lines(area.width);
let mut footer_pref = self.footer_lines(area.width, /*option_tip*/ None).len() as u16;
if has_options
@@ -112,6 +114,7 @@ impl AsyncQuestions {
question_area,
question_lines,
options_area,
option_lines,
show_option_tip: options_height > 0 && options_height < full_options_height,
notes_area,
footer_lines,
@@ -11,7 +11,7 @@ use crate::bottom_pane::bottom_pane_view::BottomPaneView;
use crate::bottom_pane::chat_composer::ComposerDraft;
use crate::bottom_pane::scroll_state::ScrollState;
use crate::bottom_pane::selection_popup_common::GenericDisplayRow;
use crate::bottom_pane::selection_popup_common::measure_rows_height;
use crate::bottom_pane::selection_popup_common::styled_row_lines;
use crate::key_hint::KeyBindingListExt;
use crate::keymap::KeymapContext;
use crate::keymap::ListAction;
@@ -30,6 +30,7 @@ use unicode_width::UnicodeWidthStr;
mod input;
mod layout;
mod options;
mod render;
mod state;
@@ -69,7 +70,7 @@ pub(crate) struct AsyncQuestions {
pub(crate) has_queued_messages: bool,
pub(crate) delivery_enabled: bool,
pub(crate) submission: Option<QuestionSubmission>,
visible_options: std::cell::Cell<(usize, usize)>,
option_viewport: std::cell::RefCell<options::OptionViewport>,
keymap: RuntimeKeymap,
// Ignore autorepeat from the number key that opened Other.
other_selector: Option<KeyCode>,
@@ -104,7 +105,7 @@ impl AsyncQuestions {
has_queued_messages: false,
delivery_enabled: true,
submission: None,
visible_options: std::cell::Cell::new((0, 0)),
option_viewport: Default::default(),
keymap,
other_selector: None,
composer,
@@ -163,14 +164,14 @@ impl AsyncQuestions {
!self.has_options() || self.other_selected()
}
pub(super) fn option_rows(&self, width: u16) -> Vec<GenericDisplayRow> {
pub(super) fn option_rows(&self, width: u16) -> Vec<Vec<HyperlinkLine>> {
if !self.has_options() {
return Vec::new();
};
}
let other = self.other_label();
self.options()
.iter()
.chain(std::iter::once(&other))
.chain((!self.other_selected()).then_some(&other))
.enumerate()
.map(|(index, label)| {
let prefix = if self.selected_option_index() == Some(index) {
@@ -193,30 +194,32 @@ impl AsyncQuestions {
row.wrapped_name =
prefix_hyperlink_lines(lines, prefix.into(), " ".repeat(indent).into());
}
row
styled_row_lines(
&row,
self.selected_option_index() == Some(index),
/*desc_col*/ 0,
width,
Default::default(),
)
})
.collect()
}
pub(super) fn options_required_height(&self, width: u16) -> u16 {
if !self.has_options() {
return 0;
}
let rows = self.option_rows(width);
if self.other_selected() {
pub(super) fn answer_height(&self, width: u16, lines: &[Vec<HyperlinkLine>]) -> u16 {
let named_height = lines.iter().map(Vec::len).sum::<usize>();
let input_height = if !self.has_options() {
self.composer.inline_input_height(width).clamp(1, 8)
} else if self.other_selected() {
let prefix = self.other_prefix_width(width);
measure_rows_height(
&rows[..rows.len() - 1],
&ScrollState::default(),
rows.len(),
width,
) + self
.composer
self.composer
.inline_input_height(width.saturating_sub(prefix).max(1))
.clamp(1, 8)
} else {
measure_rows_height(&rows, &ScrollState::default(), rows.len(), width)
}
0
};
u16::try_from(named_height)
.unwrap_or(u16::MAX)
.saturating_add(input_height)
}
fn save_current_draft(&mut self) {
@@ -230,6 +233,7 @@ impl AsyncQuestions {
}
fn restore_current_draft(&mut self) {
self.option_viewport.take();
self.sync_composer_placeholder();
let draft = self
.current_answer()
@@ -0,0 +1,153 @@
//! Scroll choices by visual line without changing the answer; only rendered content authorizes it.
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use super::AsyncQuestions;
use crate::terminal_hyperlinks::HyperlinkLine;
use ratatui::widgets::Widget;
#[derive(Default)]
pub(super) struct OptionViewport {
pub(super) area: Rect,
offset: usize,
total: usize,
pub(super) visible: std::ops::Range<usize>,
pub(super) selected: Option<usize>,
selected_start: usize,
seen_end: usize,
selected_height: usize,
horizontally_clipped: Vec<usize>,
}
impl OptionViewport {
pub(super) fn selected_page(&self, down: bool) -> Option<isize> {
let step = usize::from(self.area.height);
if self.selected_height <= step || step == 0 {
return None;
}
if down && self.offset + step < self.selected_start + self.selected_height {
Some(step as isize)
} else if !down && self.offset > self.selected_start {
Some(-(step.min(self.offset - self.selected_start) as isize))
} else {
None
}
}
pub(super) fn scroll(&mut self, delta: isize) {
let page = self.area.height as isize;
let max = self.total.saturating_sub(usize::from(self.area.height));
self.offset = self
.offset
.saturating_add_signed(delta.clamp(-page, page))
.min(max);
}
}
impl AsyncQuestions {
pub(super) fn page_content(&mut self, key: super::KeyEvent) -> bool {
if self.focus_is_notes() {
return false;
}
let down = match self.keymap.list.action_for(key) {
Some(super::ListAction::PageUp) => false,
Some(super::ListAction::PageDown) => true,
_ => return false,
};
// Selection can change between paints; wait for its current measurements.
if self.has_options()
&& self.option_viewport.borrow().selected != self.selected_option_index()
{
return true;
}
let Some(rows) = self.option_viewport.borrow().selected_page(down) else {
return false;
};
self.option_viewport.get_mut().scroll(rows);
true
}
pub(super) fn option_fully_seen(&self, index: usize) -> bool {
let viewport = self.option_viewport.borrow();
(viewport.visible.contains(&index) && !viewport.horizontally_clipped.contains(&index))
|| (viewport.selected == Some(index)
&& (viewport.selected_start..viewport.selected_start + viewport.selected_height)
.contains(&viewport.offset)
&& viewport.selected_height > usize::from(viewport.area.height)
&& viewport.seen_end == viewport.selected_height)
}
pub(super) fn render_scrollable_options(
&self,
area: Rect,
buf: &mut Buffer,
lines: &[Vec<HyperlinkLine>],
) {
let mut viewport = self.option_viewport.borrow_mut();
if area.is_empty() {
*viewport = OptionViewport::default();
return;
}
let selected = self.selected_option_index().unwrap_or(0);
let total = lines.iter().map(Vec::len).sum::<usize>();
let start = lines.iter().take(selected).map(Vec::len).sum::<usize>();
let height = lines.get(selected).map_or(0, Vec::len);
let available = usize::from(area.height);
if viewport.selected != Some(selected) || viewport.area.width != area.width {
viewport.selected = Some(selected);
viewport.seen_end = 0;
let offset = viewport.offset;
if start < offset || height > available {
viewport.offset = start;
} else if start + height > offset + available {
viewport.offset = (start + height).saturating_sub(available);
}
} else if viewport.area.height != area.height && height <= available {
viewport.offset = viewport
.offset
.clamp((start + height).saturating_sub(available), start);
}
viewport.area = area;
viewport.total = total;
viewport.selected_height = height;
viewport.selected_start = start;
let offset = viewport.offset.min(total.saturating_sub(available));
viewport.offset = offset;
let bottom_padding = available.saturating_sub(total);
let mut start = 0;
let mut first_full = None;
let mut full_count = 0;
viewport.horizontally_clipped.clear();
let fits = |line: &HyperlinkLine| line.line.width() <= usize::from(area.width);
for (index, lines) in lines.iter().enumerate() {
let end = start + lines.len();
let visible_start = start.max(offset);
let visible_end = end.min(offset + available);
if visible_start < visible_end {
for line in visible_start..visible_end {
let y = area.y + (bottom_padding + line - offset) as u16;
(&lines[line - start]).render(Rect::new(area.x, y, area.width, 1), buf);
}
if start >= offset && end <= offset + available {
first_full.get_or_insert(index);
full_count += 1;
if !lines.iter().all(fits) {
viewport.horizontally_clipped.push(index);
}
}
if index == selected {
for line in visible_start..visible_end {
let relative = line - start;
if relative == viewport.seen_end && fits(&lines[relative]) {
viewport.seen_end += 1;
}
}
}
}
start = end;
}
let first = first_full.unwrap_or(0);
viewport.visible = first..first + full_count;
}
}
@@ -16,7 +16,6 @@ use crate::terminal_hyperlinks::HyperlinkParagraph;
use super::AsyncQuestions;
use super::TIP_SEPARATOR;
use crate::bottom_pane::request_user_input::render::render_rows_bottom_aligned;
use crate::bottom_pane::request_user_input::render::truncate_line_word_boundary_with_ellipsis;
use crate::keymap::KeymapContext;
@@ -26,26 +25,23 @@ impl Renderable for AsyncQuestions {
}
fn desired_height(&self, width: u16) -> u16 {
let width = menu_surface_inset(Rect::new(/*x*/ 0, /*y*/ 0, width, u16::MAX)).width;
let extra_height = self.options_required_height(width)
+ if !self.has_options() {
self.composer.inline_input_height(width).clamp(1, 8)
} else {
0
}
+ 2
let answer_height = self.answer_height(width, &self.option_rows(width));
let chrome = 2
+ u16::from(!self.has_options() && self.unanswered_count() > 1)
+ self.footer_lines(width, /*option_tip*/ None).len() as u16
+ u16::from(self.unanswered_count() > 1)
+ menu_surface_padding_height();
u16::try_from(self.wrapped_question_lines(width).len() + usize::from(extra_height))
u16::try_from(self.wrapped_question_lines(width).len())
.unwrap_or(u16::MAX)
.saturating_add(answer_height)
.saturating_add(chrome)
}
fn render(&self, area: Rect, buf: &mut Buffer) {
self.visible_options.set((0, 0));
ratatui::widgets::Clear.render(area, buf);
let content_area = render_menu_surface(area, buf);
if content_area.is_empty() {
self.option_viewport.take();
return;
}
let sections = self.layout_sections(content_area);
@@ -57,48 +53,9 @@ impl Renderable for AsyncQuestions {
.render(sections.question_area, buf);
if self.other_selected() {
self.render_inline_options(sections.options_area, buf);
} else if self.has_options() && sections.options_area.height > 0 {
let option_rows = self.option_rows(sections.options_area.width);
let mut options_state = self.state.pending[self.state.current_idx].options_state;
let selected = options_state.selected_idx.unwrap_or(0);
let heights: Vec<_> = option_rows
.iter()
.map(|row| {
super::measure_rows_height(
std::slice::from_ref(row),
&super::ScrollState::default(),
/*max_results*/ 1,
sections.options_area.width,
)
})
.collect();
let available = sections.options_area.height;
if heights.iter().sum::<u16>() <= available {
options_state.scroll_top = 0;
}
let mut first = options_state.scroll_top.min(selected);
while first < selected && heights[first..=selected].iter().sum::<u16>() > available {
first += 1;
}
let mut used = 0;
let visible = heights[first..]
.iter()
.take_while(|&&height| {
used += height;
used <= available
})
.count();
options_state.scroll_top = first;
self.visible_options.set((first, visible));
render_rows_bottom_aligned(
sections.options_area,
buf,
&option_rows,
&options_state,
option_rows.len().max(1),
"No options",
);
self.render_inline_options(sections.options_area, buf, &sections.option_lines);
} else if self.has_options() {
self.render_scrollable_options(sections.options_area, buf, &sections.option_lines);
}
if !self.has_options() {
@@ -8,4 +8,4 @@ expression: "buffer_text(&render_editor(&editor, 50, 8))"
› 2. A suggested answer that is long enough to
wrap across multiple rows
Expand terminal to read the entire option
Scroll to read the entire option
@@ -2,5 +2,5 @@
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
2. pqrstuvw
xyzabcd
› 3. Other
@@ -61,6 +61,9 @@ impl AsyncQuestions {
pub(crate) fn set_expanded(&mut self, expanded: bool) {
self.save_current_draft();
if !expanded {
self.option_viewport.take();
}
self.expanded = expanded && !self.state.pending.is_empty();
if self.expanded {
self.snooze_auto_resolution();
@@ -77,7 +80,6 @@ impl AsyncQuestions {
return false;
};
self.save_current_draft();
self.visible_options.set((0, 0));
self.state.current_idx = next;
self.restore_current_draft();
true
@@ -118,12 +120,11 @@ impl AsyncQuestions {
.and_then(|index| answer.question.options.as_ref()?.get(index))
.map(String::as_str)
.unwrap_or_default();
// Only a fully displayed model-authored option may become user authorization.
let (first, count) = self.visible_options.get();
// Only model-authored content that has been painted may become user authorization.
let index = self.selected_option_index().unwrap_or(0);
if !self.focus_is_notes() && !(first..first + count).contains(&index) {
if !self.focus_is_notes() && !self.option_fully_seen(index) {
self.composer.show_footer_flash(
"Expand terminal to read the entire option".into(),
"Scroll to read the entire option".into(),
Duration::from_secs(5),
);
return;
@@ -182,7 +183,6 @@ impl AsyncQuestions {
0
};
self.expanded &= !self.state.pending.is_empty();
self.visible_options.set((0, 0));
if current_answered {
self.restore_current_draft();
self.composer.reset_vim_mode();
@@ -195,7 +195,6 @@ impl AsyncQuestions {
return;
}
self.composer.flush_pending_input();
self.visible_options.set((0, 0));
self.state.pending.remove(self.state.current_idx);
if self.state.current_idx >= self.state.pending.len() {
self.state.current_idx = 0;
@@ -211,7 +210,6 @@ impl AsyncQuestions {
self.state.current_idx = 0;
self.expanded = false;
self.submission = None;
self.visible_options.set((0, 0));
self.restore_current_draft();
self.composer.reset_vim_mode();
}
@@ -237,7 +235,6 @@ impl AsyncQuestions {
}
pub(crate) fn restore(&mut self, saved: QuestionState) {
self.visible_options.set((0, 0));
let incoming = std::mem::replace(&mut self.state, saved);
let mut answered_ids = incoming.answered_ids;
answered_ids.extend(self.state.answered_ids.iter().cloned());
@@ -277,6 +277,17 @@ fn selected_other_renders_as_a_dim_placeholder() {
assert_eq!(editor.composer.current_text(), "");
}
fn page_to(editor: &mut AsyncQuestions, buffer: &mut Buffer, end: &str) {
for _ in 0..12 {
if buffer_text(buffer).contains(end) {
return;
}
editor.handle_key_event(KeyCode::PageDown.into());
editor.render(buffer.area, buffer);
}
panic!("paging did not reveal {end}");
}
fn buffer_text(buffer: &ratatui::buffer::Buffer) -> String {
(buffer.area.y..buffer.area.bottom())
.map(|y| {
@@ -313,7 +324,7 @@ fn question_choice_remaps_paging_and_inline_feedback() {
assert_eq!(editor.selected_option_index(), Some(1));
let mut buffer = render_editor(&editor, /*width*/ 50, /*height*/ 12);
let area = buffer.area;
let visible = editor.visible_options.get().1;
let visible = editor.option_viewport.borrow().visible.len();
assert_eq!(visible, 2);
editor.handle_key_event(KeyEvent::from(KeyCode::PageDown));
assert_eq!(editor.selected_option_index(), Some(1 + visible));
@@ -371,6 +382,30 @@ fn question_other_remains_visible_at_nine_columns_and_distinguishes_named_other(
insta::assert_snapshot!("question_narrow_other", buffer_text(&buffer));
}
#[test]
fn horizontally_clipped_choice_cannot_be_submitted() {
let mut editor = editor();
editor.state.pending.remove(/*index*/ 0);
editor.state.pending[0].question.options = Some(vec!["界".into(), "x".into()]);
editor.restore_current_draft();
let area = Rect::new(0, 0, 6, 4);
let mut buffer = Buffer::empty(area);
editor.render_scrollable_options(area, &mut buffer, &editor.option_rows(area.width));
editor.go_next_or_submit();
assert!(editor.submission.is_none());
// A numbered shortcut still submits another choice that was fully painted.
editor.handle_key_event(KeyCode::Char('2').into());
assert!(editor.submission.take().is_some());
editor.select_option(/*index*/ 0);
let area = Rect::new(0, 0, 8, 4);
let mut buffer = Buffer::empty(area);
editor.render_scrollable_options(area, &mut buffer, &editor.option_rows(area.width));
editor.go_next_or_submit();
assert!(editor.submission.is_some());
}
#[test]
fn question_options_reserve_wrapped_height_at_the_width_boundary() {
let mut editor = editor();
@@ -382,18 +417,19 @@ fn question_options_reserve_wrapped_height_at_the_width_boundary() {
// The five-column option prefix makes each named choice exactly 21 columns.
assert_eq!(
(
editor.options_required_height(/*width*/ 20),
editor.options_required_height(/*width*/ 21),
editor.answer_height(/*width*/ 20, &editor.option_rows(/*width*/ 20)),
editor.answer_height(/*width*/ 21, &editor.option_rows(/*width*/ 21)),
),
(5, 3)
);
let width = 24;
let buffer = render_editor(&editor, width, editor.desired_height(width));
assert_eq!(editor.visible_options.get(), (0, 3));
assert_eq!(editor.option_viewport.borrow().visible, 0..3);
editor.restore_current_draft();
// Two padding rows and the question leave only one line of the selected two-line option.
let clipped = render_editor(&editor, width, /*height*/ 4);
assert_eq!(editor.visible_options.get(), (0, 0));
assert_eq!(editor.option_viewport.borrow().visible, 0..0);
editor.go_next_or_submit();
assert!(editor.submission.is_none());
insta::assert_snapshot!(
@@ -419,8 +455,8 @@ fn question_other_excludes_clipped_options_at_the_width_boundary() {
/*x*/ 0, /*y*/ 0, /*width*/ 20, /*height*/ 2,
);
let mut buffer = Buffer::empty(area);
editor.render_inline_options(area, &mut buffer);
assert_eq!(editor.visible_options.get(), (0, 0));
editor.render_inline_options(area, &mut buffer, &editor.option_rows(area.width));
assert_eq!(editor.option_viewport.borrow().visible, 0..0);
insta::assert_snapshot!(
"question_other_clipped_width_boundary",
buffer_text(&buffer)
@@ -468,19 +504,22 @@ fn question_wrapped_options_and_other_share_the_text_indent() {
assert_eq!(editor.options().len(), 32);
render_editor(&editor, /*width*/ 50, /*height*/ 10);
let height = editor.desired_height(/*width*/ 50);
assert_eq!(editor.visible_options.get().1, 2);
assert_eq!(editor.option_viewport.borrow().visible.len(), 2);
editor.handle_key_event(KeyEvent::from(KeyCode::End));
assert_eq!(editor.desired_height(/*width*/ 50), height);
assert_eq!(
editor.current_answer().unwrap().options_state,
ScrollState {
selected_idx: Some(editor.options_len() - 1),
scroll_top: editor.options_len() - editor.visible_options.get().1,
scroll_top: editor.options_len() - editor.option_viewport.borrow().visible.len(),
}
);
editor.handle_key_event(KeyEvent::from(KeyCode::Up));
render_editor(&editor, /*width*/ 80, /*height*/ 80);
assert_eq!(editor.visible_options.get(), (0, editor.options_len()));
assert_eq!(
editor.option_viewport.borrow().visible,
0..editor.options_len()
);
editor.state.pending[editor.state.current_idx]
.question
.title = "Long question ".repeat(3 * 65_536);
@@ -616,6 +655,17 @@ fn named_choices_share_selection_while_other_keeps_its_inline_cursor() {
);
}
#[test]
fn resolving_another_question_preserves_the_displayed_choice() {
let mut editor = editor();
editor.navigate(/*forward*/ true);
render_editor(&editor, /*width*/ 40, /*height*/ 12);
let first_id = editor.state.pending[0].question_id.clone();
assert!(!editor.resolve_answers(&[first_id]));
editor.go_next_or_submit();
assert!(editor.submission.is_some());
}
#[test]
fn answered_questions_do_not_reopen_when_history_precedes_local_drafts() {
let mut original = editor();
@@ -656,3 +706,73 @@ fn oversized_question_ids_keep_questions_answerable_without_echoing_the_id() {
};
assert_eq!(reply, "> Question\n\nAnswer");
}
#[test]
fn scrolling_an_oversized_choice_preserves_selection_and_requires_reading_every_line() {
let mut editor = editor();
editor.accept_answer();
editor.state.pending[0].question.options = Some(vec![
"Preceding choice".into(),
format!("Line 1.\n\n{}End of choice.", "More.\n\n".repeat(12)),
"Second choice".into(),
]);
editor.select_option(/*index*/ 1);
let mut buffer = render_editor(&editor, /*width*/ 40, /*height*/ 12);
let area = buffer.area;
// Repeated page keys before painting must not authorize skipped middle lines.
for _ in 0..2 {
editor.handle_key_event(KeyCode::PageDown.into());
}
editor.render(area, &mut buffer);
editor.go_next_or_submit();
assert!(editor.submission.is_none());
for _ in 0..2 {
editor.handle_key_event(KeyCode::PageUp.into());
}
editor.render(area, &mut buffer);
editor.handle_key_event(KeyCode::PageDown.into());
editor.render(area, &mut buffer);
assert!(!buffer_text(&buffer).contains("Line 1."));
page_to(&mut editor, &mut buffer, "End of choice.");
assert_eq!(editor.selected_option_index(), Some(1));
// Returning to the start must not scroll above this choice and revoke submission.
for _ in 0..12 {
if buffer_text(&buffer).contains("Line 1.") {
break;
}
editor.handle_key_event(KeyCode::PageUp.into());
editor.render(area, &mut buffer);
}
assert!(buffer_text(&buffer).contains("Line 1."));
// A taller terminal does not invalidate lines already read at the same width.
render_editor(&editor, /*width*/ 40, /*height*/ 13);
editor.go_next_or_submit();
assert!(editor.submission.take().is_some());
editor.select_option(editor.options().len());
editor.handle_paste("My answer".into());
editor.render(area, &mut buffer);
editor.handle_key_event(KeyCode::PageUp.into());
editor.render(area, &mut buffer);
assert!(buffer_text(&buffer).contains("My answer"));
assert!(editor.cursor_pos(area).is_some());
}
#[test]
fn paging_waits_for_the_current_choice_to_be_rendered() {
let mut editor = editor();
editor.accept_answer();
editor.state.pending[0].question.options = Some(vec![
"First choice".into(),
"Oversized choice.\n\n".repeat(20),
"Third choice".into(),
]);
let mut buffer = render_editor(&editor, /*width*/ 40, /*height*/ 12);
editor.handle_key_event(KeyCode::Down.into());
editor.handle_key_event(KeyCode::PageDown.into());
assert_eq!(editor.selected_option_index(), Some(1));
editor.render(buffer.area, &mut buffer);
editor.handle_key_event(KeyCode::PageDown.into());
assert_eq!(editor.selected_option_index(), Some(1));
}
@@ -447,17 +447,14 @@ fn render_rows_inner(
break;
}
let mut wrapped =
wrap_row_lines(row, desc_col, area.width, column_width.description_layout);
let wrapped = styled_row_lines(
row,
Some(i) == state.selected_idx,
desc_col,
area.width,
column_width.description_layout,
);
clipped |= wrapped.len() > usize::from(area.bottom().saturating_sub(cur_y));
for line in &mut wrapped {
apply_row_state_style(
std::slice::from_mut(&mut line.line),
Some(i) == state.selected_idx && !row.is_disabled,
row.is_disabled,
row.selection_style,
);
}
// Render the wrapped lines.
let mut rendered_item = false;
@@ -491,6 +488,26 @@ fn render_rows_inner(
}
}
/// Wrap one row with the same selection styling used by the shared picker renderer.
pub(crate) fn styled_row_lines(
row: &GenericDisplayRow,
selected: bool,
desc_col: usize,
width: u16,
description_layout: SelectionDescriptionLayout,
) -> Vec<crate::terminal_hyperlinks::HyperlinkLine> {
let mut lines = wrap_row_lines(row, desc_col, width, description_layout);
for line in &mut lines {
apply_row_state_style(
std::slice::from_mut(&mut line.line),
selected && !row.is_disabled,
row.is_disabled,
row.selection_style,
);
}
lines
}
/// Render a list of rows using the provided ScrollState, with shared styling
/// and behavior for selection popups.
/// Description alignment is computed from visible rows only, which allows the