Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,199 @@
//! Question prompt rows — the options and the typed answer, measured and laid out into lines.
use super::state::QuestionPromptState;
use super::{CUSTOM_PLACEHOLDER, MAX_DESCRIPTION_ROWS, MIN_DESCRIPTION_WIDTH, RECOMMENDED_BADGE};
use crate::widgets::truncate_end as truncate;
use ratatui::text::{Line, Span};
/// One selectable row laid out into terminal lines, so a click region can span its real height.
pub(super) struct LaidOutRow {
pub(super) lines: Vec<Line<'static>>,
}
/// What every row is measured against.
#[derive(Clone, Copy)]
struct RowGeometry {
indent: usize,
text_width: usize,
show_rationale: bool,
custom_rows: usize,
}
/// One row's lines of spans: an option's label with its badge and rationale, or the typed answer.
fn row_content(
state: &QuestionPromptState,
theme: &crate::theme::styles::ThemeStyles,
i: usize,
geometry: &RowGeometry,
) -> Vec<Vec<Span<'static>>> {
let RowGeometry { indent, text_width, show_rationale, custom_rows } = *geometry;
let selected = i == state.selected();
let cursor_style = theme.accent_on(selected);
let label_style = theme.label_on(selected);
let mut spans = vec![Span::styled(crate::glyphs::Mark::Cursor.gutter(selected), cursor_style)];
if state.multi {
let box_glyph = if state.is_checked(i) {
format!("[{}] ", crate::glyphs::Mark::Yes)
} else {
"[ ] ".to_string()
};
spans.push(Span::styled(box_glyph, cursor_style));
}
let mut content: Vec<Vec<Span<'static>>> = Vec::new();
match state.options.get(i) {
Some(option) => {
// The label outranks the badge: on a narrow panel the cursor already opens on
// the recommendation, so a clipped label buys nothing.
let label = format!("{}. {}", i + 1, option.label);
let room = text_width.saturating_sub(indent);
let badged =
option.recommended && room >= label.chars().count() + RECOMMENDED_BADGE.len();
let label_width = if badged { room - RECOMMENDED_BADGE.len() } else { room };
spans.push(Span::styled(truncate(&label, label_width), label_style));
if badged {
spans.push(Span::styled(RECOMMENDED_BADGE, theme.success));
}
content.push(spans);
if show_rationale {
let rationale = option.description.as_deref().unwrap_or_default();
for line in wrapped_rows(rationale, room, MAX_DESCRIPTION_ROWS) {
content
.push(vec![Span::raw(" ".repeat(indent)), Span::styled(line, theme.muted)]);
}
}
}
// The typed answer, always last and numbered like the rest. It wraps rather than
// truncating: an answer cut off at the right edge is one the reader cannot check
// before sending it.
None => {
let body = if state.editing() {
format!("{}▏", state.custom())
} else if state.custom().is_empty() {
CUSTOM_PLACEHOLDER.to_string()
} else {
state.custom().to_string()
};
let number = format!("{}. ", i + 1);
// The text column, wherever a longer number puts it
let text_at = indent + number.chars().count().saturating_sub(3);
let room = text_width.saturating_sub(text_at);
let (mut wrapped, scrolled) = custom_view(&body, room, custom_rows, state.editing());
// An answer of nothing but spaces still owns a row: it is the one the cursor
// can land on, and the click regions are laid out over the rows there are.
if wrapped.is_empty() {
wrapped.push(String::new());
}
for (index, row) in wrapped.into_iter().enumerate() {
let mut line = if index == 0 {
let mut first = std::mem::take(&mut spans);
first.push(Span::styled(number.clone(), label_style));
first
} else {
vec![Span::raw(" ".repeat(text_at))]
};
// Said in the row's first cell, so the text column holds still while the
// window scrolls
if scrolled {
let lead = if index == 0 { "…" } else { " " };
line.push(Span::styled(lead, cursor_style));
}
line.push(Span::styled(row, label_style));
content.push(line);
}
}
}
content
}
/// Lay out the options and the free-text row.
///
/// `with_descriptions` keeps each option's rationale, and `custom_rows` is what the typed answer
/// may spend before its window starts scrolling — the two knobs [`super::plan`] turns down to fit.
pub(super) fn lay_out_rows(
state: &QuestionPromptState,
theme: &crate::theme::styles::ThemeStyles,
inner_width: usize,
with_descriptions: bool,
custom_rows: usize,
) -> Vec<LaidOutRow> {
// `❯ `, the optional checkbox, and `1. ` — what a rationale has to clear to line up under
// its label.
let indent = 2 + if state.multi { 4 } else { 0 } + 3;
// Whether a rationale is worth setting at all: what is left of the panel after the slab's
// frame and the label's own indent has to be wide enough to read. A narrower panel shows the
// labels alone rather than a column of two-word fragments.
let roomy = inner_width.saturating_sub(crate::widgets::SELECTION_FRAME + indent)
>= MIN_DESCRIPTION_WIDTH;
let show_rationale = with_descriptions && roomy;
let custom_rows = custom_rows.min(MAX_DESCRIPTION_ROWS + 1);
// What a row's text may occupy: the panel, less the slab's two cap cells.
let text_width = inner_width.saturating_sub(crate::widgets::SELECTION_FRAME);
let geometry = RowGeometry { indent, text_width, show_rationale, custom_rows };
let rows: Vec<(bool, Vec<Vec<Span<'static>>>)> = (0..state.row_count())
.map(|i| (i == state.selected(), row_content(state, theme, i, &geometry)))
.collect();
debug_assert!(
rows.iter().all(|(_, lines)| lines.len() <= MAX_DESCRIPTION_ROWS + 1),
"a row is taller than the rationale budget"
);
rows.into_iter()
// One slab for the whole option, not one per line: the label and the rationale under it are
// a single choice.
.map(|(selected, content)| LaidOutRow {
lines: crate::widgets::selection_block(content, inner_width, selected, theme),
})
.collect()
}
/// Word-wrap `text` to `width` columns.
fn wrap_rows(text: &str, width: usize) -> Vec<String> {
let text = text.trim();
if text.is_empty() || width == 0 {
return Vec::new();
}
let line = Line::from(Span::raw(text.to_string()));
crate::widgets::wrap_line(&line, width)
.into_iter()
.map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect())
.collect()
}
/// Word-wrap `text` to `width` columns, clipped to `max_rows` with an ellipsis on the last row.
pub(super) fn wrapped_rows(text: &str, width: usize, max_rows: usize) -> Vec<String> {
if max_rows == 0 {
return Vec::new();
}
let mut rows = wrap_rows(text, width);
if rows.len() > max_rows {
rows.truncate(max_rows);
if let Some(last) = rows.last_mut() {
*last = truncate(&format!("{last}…"), width);
}
}
rows
}
/// The rows of a typed answer that fit, and whether any were left above them.
///
/// While the row is being edited the caret is what has to stay on screen, so the window follows
/// the tail of the answer; at rest it reads from the top like any other text, with the usual
/// clipped-tail mark.
fn custom_view(text: &str, width: usize, max_rows: usize, editing: bool) -> (Vec<String>, bool) {
if !editing {
return (wrapped_rows(text, width, max_rows), false);
}
if max_rows == 0 {
return (Vec::new(), false);
}
let rows = wrap_rows(text, width);
if rows.len() <= max_rows {
return (rows, false);
}
// a cell short, for the mark that says there is more above
let mut rows = wrap_rows(text, width.saturating_sub(1));
(rows.split_off(rows.len() - max_rows), true)
}

View File

@@ -0,0 +1,264 @@
//! Question prompt state — which row the cursor is on, what is checked, and what a key does.
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use luxe_core::question::{default_selection, QuestionOption, QuestionRequestId};
/// State for an in-flight question modal (one at a time — tools dispatch sequentially).
#[derive(Clone, Debug)]
pub struct QuestionPromptState {
/// Correlates the answer with the awaiting engine turn.
pub id: QuestionRequestId,
/// The question text.
pub prompt: String,
/// Selectable options, each with its optional rationale.
pub options: Vec<QuestionOption>,
/// Whether multiple options may be selected.
pub multi: bool,
/// Cursor row: `0..options.len()` selects an option; `options.len()` is the free-text row.
selected: usize,
/// Per-option checkbox state (multi-select only).
checked: Vec<bool>,
/// The user's free-text answer.
custom: String,
/// Whether the free-text row is being edited (keystrokes append to `custom`).
editing: bool,
/// Whether the typed answer is checked (multi-select): typing checks it, Space toggles it.
custom_checked: bool,
}
/// Outcome of a keypress on the question modal.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum QuestionPromptOutcome {
/// Answer the question with these values (option labels and/or the free text) and close it.
Answer(Vec<String>),
/// Dismiss the question without answering.
Cancel,
/// Key consumed; the modal stays open.
Consumed,
}
impl QuestionPromptState {
pub fn new(
id: QuestionRequestId,
prompt: String,
options: Vec<QuestionOption>,
multi: bool,
) -> Self {
let checked = vec![false; options.len()];
let selected = default_selection(&options);
Self {
id,
prompt,
options,
multi,
selected,
checked,
custom: String::new(),
editing: false,
custom_checked: false,
}
}
/// Index of the free-text ("type your own") row.
pub(super) fn custom_row(&self) -> usize {
self.options.len()
}
/// Total selectable rows (options + the free-text row).
pub(super) fn row_count(&self) -> usize {
self.options.len() + 1
}
/// Highlighted row index (for rendering / clicks).
pub fn selected(&self) -> usize {
self.selected
}
/// Whether row `i` is checked (multi-select), the typed answer included.
pub fn is_checked(&self, i: usize) -> bool {
if i == self.custom_row() {
return self.custom_checked && !self.custom.trim().is_empty();
}
self.checked.get(i).copied().unwrap_or(false)
}
/// The current free-text entry.
pub fn custom(&self) -> &str {
&self.custom
}
/// Whether the free-text row is in edit mode.
pub fn editing(&self) -> bool {
self.editing
}
/// Take pasted text into the free-text row, jumping to it the way typing does.
pub fn paste(&mut self, text: &str) {
let text = crate::editor::single_line_paste(text);
if text.is_empty() {
return;
}
self.start_typing();
self.custom.push_str(&text);
}
/// Move the cursor to `index` (a hover or a click), clamped to range.
///
/// Landing on the row already selected keeps an answer being typed open: the pointer resting
/// on it is not a reason to drop the caret.
pub fn select(&mut self, index: usize) {
let index = index.min(self.row_count().saturating_sub(1));
if index != self.selected {
self.editing = false;
}
self.selected = index;
}
/// Put the cursor in the typed answer and pick it, as typing anywhere does.
fn start_typing(&mut self) {
self.selected = self.custom_row();
self.editing = true;
self.custom_checked = true;
}
fn move_up(&mut self) {
let n = self.row_count();
self.selected = if self.selected == 0 { n - 1 } else { self.selected - 1 };
}
pub(super) fn move_down(&mut self) {
self.selected = (self.selected + 1) % self.row_count();
}
/// Collects the final answer: every checked row (multi), or the one chosen (single), where
/// `None` is the typed answer.
///
/// A single answer is one answer. Text left in the typed row while picking another option used
/// to ride along with it, which made a choice and an abandoned draft one reply.
fn collect(&self, option: Option<usize>) -> Vec<String> {
let custom = self.custom.trim();
if !self.multi {
return match option {
Some(i) => vec![self.options[i].label.clone()],
None if custom.is_empty() => Vec::new(),
None => vec![custom.to_string()],
};
}
let mut answers: Vec<String> = (0..self.options.len())
.filter(|i| self.checked[*i])
.map(|i| self.options[i].label.clone())
.collect();
if self.is_checked(self.custom_row()) {
answers.push(custom.to_string());
}
answers
}
/// Route a keypress. Everything not understood is swallowed (the modal is modal), so stray
/// keystrokes never leak into the composer while an answer is pending.
pub fn on_key(&mut self, key: &KeyEvent) -> QuestionPromptOutcome {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
if self.editing {
return self.on_key_editing(key, ctrl);
}
match key.code {
KeyCode::Esc => QuestionPromptOutcome::Cancel,
KeyCode::Char('c') if ctrl => QuestionPromptOutcome::Cancel,
KeyCode::Up => {
self.move_up();
QuestionPromptOutcome::Consumed
}
KeyCode::Down | KeyCode::Tab => {
self.move_down();
QuestionPromptOutcome::Consumed
}
// Digit shortcut: pick / toggle the nth option, the typed answer's number included.
KeyCode::Char(c @ '1'..='9') => {
let i = (c as usize) - ('1' as usize);
if i == self.custom_row() {
self.start_typing();
QuestionPromptOutcome::Consumed
} else if i < self.options.len() {
if self.multi {
self.checked[i] = !self.checked[i];
self.selected = i;
QuestionPromptOutcome::Consumed
} else {
QuestionPromptOutcome::Answer(self.collect(Some(i)))
}
} else {
QuestionPromptOutcome::Consumed
}
}
KeyCode::Char(' ') => {
if self.selected == self.custom_row() {
if self.multi && self.is_checked(self.selected) {
self.custom_checked = false;
} else {
self.start_typing();
}
} else if self.multi {
self.checked[self.selected] = !self.checked[self.selected];
}
QuestionPromptOutcome::Consumed
}
KeyCode::Enter => {
if self.multi {
QuestionPromptOutcome::Answer(self.collect(None))
} else if self.selected == self.custom_row() {
if self.custom.trim().is_empty() {
self.editing = true;
QuestionPromptOutcome::Consumed
} else {
QuestionPromptOutcome::Answer(self.collect(None))
}
} else {
QuestionPromptOutcome::Answer(self.collect(Some(self.selected)))
}
}
// Start typing anywhere jumps into the free-text row.
KeyCode::Char(c) if !ctrl => {
self.start_typing();
self.custom.push(c);
QuestionPromptOutcome::Consumed
}
_ => QuestionPromptOutcome::Consumed,
}
}
fn on_key_editing(&mut self, key: &KeyEvent, ctrl: bool) -> QuestionPromptOutcome {
match key.code {
KeyCode::Esc => {
// Leave edit mode but keep the modal open (Esc again cancels it).
self.editing = false;
QuestionPromptOutcome::Consumed
}
KeyCode::Char('c') if ctrl => {
self.custom.clear();
QuestionPromptOutcome::Consumed
}
KeyCode::Backspace => {
self.custom.pop();
QuestionPromptOutcome::Consumed
}
KeyCode::Enter => {
if self.multi {
// Commit the text and submit everything checked plus the free text.
self.editing = false;
QuestionPromptOutcome::Answer(self.collect(None))
} else if self.custom.trim().is_empty() {
self.editing = false;
QuestionPromptOutcome::Consumed
} else {
QuestionPromptOutcome::Answer(self.collect(None))
}
}
KeyCode::Char(c) if !ctrl => {
self.custom.push(c);
self.custom_checked = true;
QuestionPromptOutcome::Consumed
}
_ => QuestionPromptOutcome::Consumed,
}
}
}

View File

@@ -0,0 +1,545 @@
use super::*;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use luxe_core::question::{QuestionOption, QuestionRequestId};
fn state(multi: bool) -> QuestionPromptState {
QuestionPromptState::new(
QuestionRequestId::new(),
"Pick a stack".into(),
vec!["Rust".into(), "Go".into()],
multi,
)
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn theme() -> crate::theme::styles::ThemeStyles {
let registry = luxe_core::theme::ThemeRegistry::new();
let resolved = registry.resolve("dark").expect("dark theme resolves");
crate::theme::styles::ThemeStyles::from_resolved(&resolved, "dark")
}
/// A flattened buffer cut back into its rows.
fn grid(text: &str, width: u16) -> Vec<String> {
text.chars()
.collect::<Vec<_>>()
.chunks(usize::from(width))
.map(|row| row.iter().collect())
.collect()
}
/// Render into a fixed grid and return both the flattened text and the click regions.
fn render(
state: &QuestionPromptState,
width: u16,
height: u16,
) -> (String, Vec<(ratatui::layout::Rect, crate::mouse::MouseTarget)>) {
use ratatui::{backend::TestBackend, layout::Rect, Terminal};
let theme = theme();
let hit = std::cell::RefCell::new(crate::mouse::HitRegions::default());
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test terminal");
terminal
.draw(|frame| {
render_question_prompt(
frame,
Rect::new(0, 0, width, height),
height,
state,
&theme,
&hit,
)
})
.expect("render question prompt");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
let regions = hit.borrow().clicks().map(|(rect, target)| (rect, target.clone())).collect();
(text, regions)
}
/// The typed answer is an option like the others: numbered after them, with a checkbox of its
/// own in multi-select, and its number picks it.
#[test]
fn the_typed_answer_is_numbered_and_checked_like_an_option() {
let (text, _) = render(&state(false), 50, 20);
assert!(text.contains("3. Type your own answer"), "{text}");
let mut s = state(true);
let (text, _) = render(&s, 50, 20);
assert!(text.contains("[ ] 3. Type your own answer"), "{text}");
// its number starts the typing, and typing checks it
s.on_key(&key(KeyCode::Char('3')));
assert!(s.editing() && s.selected() == s.custom_row());
assert!(!s.is_checked(s.custom_row()), "nothing typed, nothing to send");
for c in "Zig".chars() {
s.on_key(&key(KeyCode::Char(c)));
}
assert!(s.is_checked(s.custom_row()));
let (text, _) = render(&s, 50, 20);
assert!(text.contains(&format!("[{}] 3. Zig", crate::glyphs::Mark::Yes)), "{text}");
assert_eq!(s.on_key(&key(KeyCode::Enter)), QuestionPromptOutcome::Answer(vec!["Zig".into()]));
}
/// Typing from any row picks the typed answer, so Enter sends it; Space unchecks it again
/// without throwing the text away.
#[test]
fn typing_picks_the_typed_answer_and_space_can_unpick_it() {
let mut s = state(true);
s.on_key(&key(KeyCode::Char(' '))); // check Rust
for c in "Zig".chars() {
s.on_key(&key(KeyCode::Char(c)));
}
s.on_key(&key(KeyCode::Esc)); // done typing
assert!(s.is_checked(s.custom_row()));
s.on_key(&key(KeyCode::Char(' ')));
assert!(!s.is_checked(s.custom_row()) && s.custom() == "Zig", "unchecked, still there");
assert_eq!(s.on_key(&key(KeyCode::Enter)), QuestionPromptOutcome::Answer(vec!["Rust".into()]));
}
/// One answer to a single-select question: a draft left in the typed row does not ride along
/// with an option picked after it.
#[test]
fn a_single_answer_leaves_an_abandoned_draft_behind() {
let mut s = state(false);
s.on_key(&key(KeyCode::Char('x')));
s.on_key(&key(KeyCode::Esc));
s.select(0);
assert_eq!(s.on_key(&key(KeyCode::Enter)), QuestionPromptOutcome::Answer(vec!["Rust".into()]));
}
/// The pointer resting on the row being typed into keeps the caret; moving to another row
/// puts it away.
#[test]
fn hovering_the_row_being_typed_keeps_it_open() {
let mut s = state(false);
s.on_key(&key(KeyCode::Char('x')));
s.select(s.custom_row());
assert!(s.editing());
s.select(0);
assert!(!s.editing());
}
#[test]
fn single_select_enter_answers_the_cursor_option() {
let mut s = state(false);
assert_eq!(s.on_key(&key(KeyCode::Enter)), QuestionPromptOutcome::Answer(vec!["Rust".into()]));
s.move_down();
assert_eq!(s.on_key(&key(KeyCode::Enter)), QuestionPromptOutcome::Answer(vec!["Go".into()]));
}
#[test]
fn digit_shortcut_answers_single_select_directly() {
let mut s = state(false);
assert_eq!(
s.on_key(&key(KeyCode::Char('2'))),
QuestionPromptOutcome::Answer(vec!["Go".into()])
);
}
#[test]
fn multi_select_toggles_and_submits_checked_options() {
let mut s = state(true);
assert_eq!(s.on_key(&key(KeyCode::Char(' '))), QuestionPromptOutcome::Consumed); // check Rust
s.move_down();
assert_eq!(s.on_key(&key(KeyCode::Char(' '))), QuestionPromptOutcome::Consumed); // check Go
assert!(s.is_checked(0) && s.is_checked(1));
assert_eq!(
s.on_key(&key(KeyCode::Enter)),
QuestionPromptOutcome::Answer(vec!["Rust".into(), "Go".into()])
);
}
#[test]
fn typing_jumps_to_free_text_and_enter_submits_it() {
let mut s = state(false);
assert_eq!(s.on_key(&key(KeyCode::Char('x'))), QuestionPromptOutcome::Consumed);
assert!(s.editing());
assert_eq!(s.custom(), "x");
for c in "yz".chars() {
s.on_key(&key(KeyCode::Char(c)));
}
assert_eq!(s.on_key(&key(KeyCode::Enter)), QuestionPromptOutcome::Answer(vec!["xyz".into()]));
}
/// Pasting is typing: an answer copied from somewhere else lands in the free-text row rather
/// than in the composer behind the modal.
#[test]
fn a_paste_lands_in_the_free_text_row() {
let mut s = state(false);
s.paste("copied answer\n");
assert!(s.editing());
assert_eq!(s.custom(), "copied answer");
assert_eq!(s.selected(), s.custom_row(), "and the cursor followed it there");
s.paste(" ");
assert_eq!(s.custom(), "copied answer", "a paste of nothing types nothing");
assert_eq!(
s.on_key(&key(KeyCode::Enter)),
QuestionPromptOutcome::Answer(vec!["copied answer".into()])
);
}
#[test]
fn free_text_combines_with_checked_options_in_multi() {
let mut s = state(true);
s.on_key(&key(KeyCode::Char(' '))); // check Rust
s.select(s.custom_row());
s.on_key(&key(KeyCode::Char(' '))); // enter edit on free-text row
assert!(s.editing());
for c in "Zig".chars() {
s.on_key(&key(KeyCode::Char(c)));
}
assert_eq!(
s.on_key(&key(KeyCode::Enter)),
QuestionPromptOutcome::Answer(vec!["Rust".into(), "Zig".into()])
);
}
#[test]
fn esc_cancels_when_not_editing_and_exits_edit_first() {
let mut s = state(false);
s.on_key(&key(KeyCode::Char('a'))); // start editing
assert!(s.editing());
assert_eq!(s.on_key(&key(KeyCode::Esc)), QuestionPromptOutcome::Consumed); // exit edit
assert!(!s.editing());
assert_eq!(s.on_key(&key(KeyCode::Esc)), QuestionPromptOutcome::Cancel);
// now cancel
}
#[test]
fn render_shows_title_prompt_options_and_free_text_row() {
let (text, _) = render(&state(true), 60, 14);
assert!(text.contains("Question"), "title present");
assert!(text.contains("Pick a stack"), "prompt present");
assert!(text.contains("1. Rust"), "first option present");
assert!(text.contains("[ ]"), "multi checkbox present");
assert!(text.contains("Type your own answer"), "free-text row present");
assert!(text.contains('❯'), "selection cursor present");
assert!(text.contains('╭'), "rounded panel border present");
}
fn advised() -> QuestionPromptState {
QuestionPromptState::new(
QuestionRequestId::new(),
"Which runtime?".into(),
vec![
QuestionOption::new("async-std").with_description("smaller, fewer users"),
QuestionOption::new("tokio")
.with_description("already a dependency here")
.recommended(),
],
false,
)
}
#[test]
fn the_cursor_opens_on_the_recommended_option() {
let mut s = advised();
assert_eq!(s.selected(), 1, "the recommendation, not the first row");
// So Enter answers with it, without the user weighing every row first.
assert_eq!(s.on_key(&key(KeyCode::Enter)), QuestionPromptOutcome::Answer(vec!["tokio".into()]));
}
#[test]
fn render_shows_the_rationale_and_the_recommended_badge() {
let (text, _) = render(&advised(), 60, 20);
assert!(text.contains("1. async-std"), "labels stay numbered");
assert!(text.contains("smaller, fewer users"), "rationale rendered");
assert!(text.contains("already a dependency here"));
assert!(text.contains("recommended"), "the recommendation is badged, not implied");
}
#[test]
fn click_regions_cover_the_rows_a_wrapped_rationale_actually_occupies() {
let long = "a".repeat(30) + " " + &"b".repeat(30);
let s = QuestionPromptState::new(
QuestionRequestId::new(),
"Pick".into(),
vec![QuestionOption::new("first").with_description(&long), QuestionOption::new("second")],
false,
);
let (_, regions) = render(&s, 40, 20);
let rows: Vec<_> = regions
.iter()
.filter_map(|(rect, target)| match target {
crate::mouse::MouseTarget::QuestionRow(i) => Some((*i, *rect)),
_ => None,
})
.collect();
assert_eq!(rows.len(), 3, "two options plus the free-text row");
assert!(rows[0].1.height > 1, "the wrapped rationale is part of its own row");
// Regions stack without overlapping, so a click never lands on two rows.
for pair in rows.windows(2) {
assert_eq!(pair[0].1.bottom(), pair[1].1.y, "rows are contiguous: {rows:?}");
}
}
#[test]
fn a_short_panel_drops_rationale_instead_of_clipping_the_options() {
let s = advised();
let (tall, _) = render(&s, 60, 20);
assert!(tall.contains("already a dependency here"));
// Ten rows fits the chrome, prompt, and three option/free-text rows — nothing more. Nine
// used to, by clipping the keys off the bottom.
let (short, regions) = render(&s, 60, 10);
assert!(!short.contains("already a dependency"), "rationale dropped: {short}");
assert!(short.contains("1. async-std") && short.contains("2. tokio"), "options survive");
assert!(short.contains("Type your own answer"), "free text survives");
assert_eq!(
regions
.iter()
.filter(|(_, target)| matches!(target, crate::mouse::MouseTarget::QuestionRow(_)))
.count(),
3
);
}
#[test]
fn a_long_question_wraps_instead_of_being_cut_off() {
let s = QuestionPromptState::new(
QuestionRequestId::new(),
"Should the migration run before or after the index is rebuilt on the replica?".into(),
vec!["before".into(), "after".into()],
false,
);
let (text, _) = render(&s, 44, 20);
assert!(text.contains("Should the migration run"));
assert!(text.contains("replica?"), "the tail of the question survives: {text}");
}
#[test]
fn a_narrow_panel_drops_rationale_rather_than_shredding_it() {
let (wide, _) = render(&advised(), 60, 20);
assert!(wide.contains("already a dependency here"));
// Under ~24 columns of rationale width the wrap turns into fragments; labels alone win.
// Four of those columns are the slab's frame — a cap and the pad inside it at each end —
// which every row spends whether or not it is the chosen one, and that is what keeps the
// label column from shifting sideways as the cursor moves.
let (narrow, _) = render(&advised(), 26, 20);
assert!(!narrow.contains("already"), "rationale dropped: {narrow}");
assert!(narrow.contains("1. async-std"), "full labels survive: {narrow}");
assert!(narrow.contains("2. tokio"), "including the recommended one: {narrow}");
assert!(!narrow.contains("recommended"), "the badge yields to the label, not vice versa");
}
/// The label column sits at the same cell on every row, chosen or not. A list that shifts
/// sideways under the cursor is the thing the slab's always-spent frame cells exist to prevent.
#[test]
fn the_option_column_does_not_move_under_the_cursor() {
const WIDTH: u16 = 60;
let mut state = advised();
// The buffer is a flat run of cells, so the column is the offset within its own row.
let column_of = |state: &QuestionPromptState| {
let (text, _) = render(state, WIDTH, 20);
let cells: Vec<char> = text.chars().collect();
let label: Vec<char> = "1. async-std".chars().collect();
let at = cells.windows(label.len()).position(|window| window == label.as_slice())?;
Some(at % usize::from(WIDTH))
};
// `advised()` opens on the recommended option, so option 1 starts unselected.
let unselected = column_of(&state).expect("the first option renders");
state.select(0);
let selected = column_of(&state).expect("and still does when chosen");
assert_eq!(unselected, selected, "the label must not move as the cursor lands on it");
}
#[test]
fn a_short_panel_spends_its_last_rows_on_the_options_not_the_question() {
let s = QuestionPromptState::new(
QuestionRequestId::new(),
"Should the migration run before or after the replica index is rebuilt?".into(),
vec!["before".into(), "after".into()],
false,
);
// Wide enough to wrap the question over three rows, too short to afford them.
let (text, _) = render(&s, 44, 11);
assert!(text.contains("1. before") && text.contains("2. after"), "options: {text}");
assert!(text.contains("Type your own answer"), "free text survives");
assert!(text.contains("esc cancel"), "the way out survives");
}
/// A footer too wide for the panel drops whole keys and keeps the way out, rather than cutting
/// the last one to `Es…`.
#[test]
fn a_narrow_footer_drops_keys_not_letters() {
let s = QuestionPromptState::new(
QuestionRequestId::new(),
"Which?".into(),
vec!["a".into(), "b".into()],
true,
);
let (text, _) = render(&s, 52, 14);
assert!(text.contains("esc cancel"), "the way out survives: {text}");
assert!(!text.contains('…'), "no key is cut short: {text}");
}
#[test]
fn wrapped_rows_clips_with_an_ellipsis_and_skips_empty_text() {
assert!(wrapped_rows(" ", 20, 2).is_empty());
assert!(wrapped_rows("text", 0, 2).is_empty());
let rows = wrapped_rows(&"word ".repeat(20), 10, 2);
assert_eq!(rows.len(), 2);
assert!(rows[1].ends_with('…'), "clipped tail is marked: {rows:?}");
assert!(rows.iter().all(|row| row.chars().count() <= 10));
// Text that exactly fills its rows was not clipped, so it is not marked as though it was.
assert_eq!(wrapped_rows("aaaa bbbb", 4, 2), vec!["aaaa", "bbbb"]);
}
/// Typing an answer the row cannot hold wraps it. Truncating instead capped how much of their
/// own answer a reader could ever see, which is most of what makes a free-text row usable.
#[test]
fn a_typed_answer_wraps_instead_of_being_cut_off() {
let mut s = state(false);
let answer = "keep the runtime minimal and pull in only what the first milestone needs";
for c in answer.chars() {
s.on_key(&key(KeyCode::Char(c)));
}
let (text, regions) = render(&s, 50, 24);
assert!(text.contains("keep the runtime minimal"), "the head is on screen");
assert!(text.contains("first milestone needs"), "and so is the tail: {text}");
assert!(!text.contains('…'), "nothing was clipped: {text}");
// The number and the cursor belong to the row, not to each of its lines: both sit on the
// first, and the wrap below them runs under the text rather than under the chrome.
let rows = grid(&text, 50);
let numbered = rows.iter().position(|row| row.contains("3. keep")).expect("numbered");
assert!(rows[numbered].contains('❯'), "the cursor sits on the row's first line");
assert_eq!(rows.iter().filter(|row| row.contains('❯')).count(), 1, "and only there");
let column = |row: &str, text: &str| row.find(text).map(|at| row[..at].chars().count());
assert_eq!(
column(&rows[numbered + 1], "only"),
column(&rows[numbered], "keep"),
"the wrap runs under the text: {rows:#?}"
);
// The row a click has to reach is as tall as the answer made it.
let custom = regions
.iter()
.find(|(_, target)| matches!(target, crate::mouse::MouseTarget::QuestionRow(i) if *i == 2))
.expect("the free-text row publishes a click region");
assert!(custom.0.height > 1, "the wrapped answer is part of its own row: {custom:?}");
}
/// Past the rows it is allowed, the window follows the caret — what you are typing now is
/// what you need to see — and says the answer carries on above it.
#[test]
fn a_long_answer_follows_the_caret_and_marks_what_is_above_it() {
let mut s = state(false);
for c in "alpha ".repeat(40).chars() {
s.on_key(&key(KeyCode::Char(c)));
}
for c in "omega".chars() {
s.on_key(&key(KeyCode::Char(c)));
}
let (typing, _) = render(&s, 50, 30);
assert!(typing.contains("omega▏"), "the caret stays on screen: {typing}");
assert!(typing.contains('…'), "and the row says there is more above it");
// At rest it reads from the top instead, with the clipped tail marked as usual.
s.on_key(&key(KeyCode::Esc));
assert!(!s.editing());
let (resting, _) = render(&s, 50, 30);
assert!(!resting.contains("omega"), "the tail is folded away: {resting}");
assert!(resting.contains('…'));
}
/// The answer grows the panel upward; it must not push the options sideways as it goes. The
/// cut is measured from the width, not from the tallest row, for exactly this reason.
#[test]
fn a_growing_answer_leaves_the_option_column_where_it_was() {
const WIDTH: u16 = 60;
let column_of = |state: &QuestionPromptState, label: &str| {
let (text, _) = render(state, WIDTH, 30);
let cells: Vec<char> = text.chars().collect();
let label: Vec<char> = label.chars().collect();
let at = cells.windows(label.len()).position(|window| window == label.as_slice())?;
Some(at % usize::from(WIDTH))
};
for (mut s, label) in [(state(false), "1. Rust"), (advised(), "1. async-std")] {
let before = column_of(&s, label).expect("the first option renders");
for c in "a".repeat(400).chars() {
s.on_key(&key(KeyCode::Char(c)));
}
assert_eq!(column_of(&s, label), Some(before), "{label} moved as the answer grew");
}
}
/// The answer grows to its budget and not a line more, at every width.
///
/// A narrow panel used to get a single row: the slab's two caps were halves of one diagonal, so
/// a row could be no taller than the cut had cells to lean through, and a width that reserved
/// none capped the answer at one line. Square caps have no such ceiling, so the only thing
/// deciding how tall the answer gets is how much answer there is.
#[test]
fn the_answer_takes_its_whole_budget_and_not_a_line_more() {
let theme = theme();
for (width, expected) in [
(26u16, MAX_CUSTOM_ROWS),
(44, MAX_CUSTOM_ROWS),
(60, MAX_CUSTOM_ROWS),
(100, MAX_CUSTOM_ROWS),
] {
let mut s = advised();
for c in "a longer answer than one row can hold ".repeat(6).chars() {
s.on_key(&key(KeyCode::Char(c)));
}
let rows = lay_out_rows(&s, &theme, inner_width(width), true, MAX_CUSTOM_ROWS);
let tallest = rows.iter().map(|row| row.lines.len()).max().unwrap_or(0);
assert_eq!(tallest, expected, "{width}: the answer got {tallest} lines");
// And the shape still fits: nothing spills past the panel's inner width.
for row in &rows {
for line in &row.lines {
let cells: usize = line
.spans
.iter()
.map(|span| unicode_width::UnicodeWidthStr::width(span.content.as_ref()))
.sum();
assert!(cells <= inner_width(width), "{width}: a line of {cells} cells");
}
}
}
}
/// A panel with no room left shrinks the answer's window rather than clipping itself — and
/// shrinks it no further than it has to, because every row it gives up is answer nobody can
/// read. The caret and the way out are what a clipped panel loses first.
#[test]
fn a_short_panel_shrinks_the_answer_before_it_clips_itself() {
let mut s = advised();
for c in "a longer answer than one row can hold ".repeat(3).chars() {
s.on_key(&key(KeyCode::Char(c)));
}
let (text, _) = render(&s, 60, 12);
assert!(text.contains('▏'), "the caret is on screen: {text}");
assert!(text.contains("esc cancel"), "and so is the way out: {text}");
assert!(text.contains("1. async-std") && text.contains("2. tokio"), "options: {text}");
assert_eq!(height(&s, &theme(), 60, 12), 12, "it spends every row it was given");
}
/// What the panel measures is what it draws, or the transcript stands down from the wrong
/// number of rows and the modal covers the output it is asking about.
#[test]
fn the_measured_height_is_the_height_it_draws() {
let theme = theme();
let mut s = state(false);
for width in [40u16, 60, 100] {
for available in [9u16, 16, 40] {
let measured = height(&s, &theme, width, available);
let (text, _) = render(&s, width, available);
let drawn = grid(&text, width)
.iter()
.filter(|row| row.chars().any(|cell| !cell.is_whitespace()))
.count();
assert_eq!(usize::from(measured), drawn, "{width}x{available}");
}
// And still does once the answer has grown the panel.
for c in "a longer answer than the row can hold on its own ".repeat(4).chars() {
s.on_key(&key(KeyCode::Char(c)));
}
}
assert_eq!(height(&s, &theme, 0, 20), 0, "no width, no panel");
}