choose popup: 60% width (60-140), vertically centered, padding, wrapped descriptions, help row inside
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s

This commit is contained in:
hermes committed 2026-10-02 11:24:44 +00:00
1 parent c7341d3085
commit 295b54adb7
1 file changed
+110 -40
+110 -40
View File
@@ -114,7 +114,11 @@ impl Choose {
}
}
/// Centered in the first `bottom` rows (the transcript area).
pub fn draw(&self, f: &mut ratatui::Frame, bottom: u16) {
use ratatui::layout::{Constraint, Layout};
use ratatui::style::Modifier;
use ratatui::widgets::Padding;
let th = theme::t();
let area = f.area();
let (on, off) = if th.sym.bar_full == "#" {
@@ -122,63 +126,81 @@ impl Choose {
} else {
("◉", "○")
};
let w = (area.width * 3 / 5).clamp(60, 140).min(area.width);
let inner = w.saturating_sub(4).max(1) as usize;
let mut lines: Vec<Line> = vec![];
// first line of the selected row, to keep it visible when the list scrolls
let mut sel_line = 0;
for (i, (l, d)) in self.q.options.iter().enumerate() {
let st = if i == self.sel && self.typing.is_none() {
th.sel()
} else {
th.plain()
};
let mark = if self.q.multi {
if self.picked[i] { on } else { off }
} else {
""
};
let mut s = vec![Span::styled(format!(" {} {mark} {l} ", i + 1), st)];
if !d.is_empty() {
s.push(Span::styled(format!(" {d}"), th.dim()));
let on_row = i == self.sel && self.typing.is_none();
if i == self.sel {
sel_line = lines.len();
}
lines.push(Line::from(s));
let st = if on_row { th.sel() } else { th.plain() };
let mark = if !self.q.multi {
""
} else if self.picked[i] {
on
} else {
off
};
lines.push(Line::from(vec![
Span::styled(format!("{} ", i + 1), th.accent()),
Span::styled(format!("{mark} {l} ").replace(" ", " "), st),
]));
for dl in wrap(d, inner.saturating_sub(3)) {
lines.push(Line::styled(format!(" {dl}"), th.dim()));
}
lines.push(Line::raw(""));
}
if self.q.other {
let st = if self.is_other() && self.typing.is_none() {
th.sel()
} else {
th.plain()
};
let n = self.q.options.len();
if self.is_other() {
sel_line = lines.len();
}
lines.push(match &self.typing {
Some(t) => Line::from(vec![
Span::styled(" other: ", th.accent()),
Span::styled(format!("{} ", n + 1), th.accent()),
Span::styled("other: ", th.accent()),
Span::raw(format!("{t}▏")),
]),
None => Line::styled(format!(" {} other…", self.q.options.len() + 1), st),
None => Line::from(vec![
Span::styled(format!("{} ", n + 1), th.accent()),
Span::styled(
"other…",
if self.is_other() {
th.sel()
} else {
th.plain()
},
),
]),
});
}
let w = area.width.min(80).max(20.min(area.width));
let inner = w.saturating_sub(2).max(1) as usize;
let qh = Paragraph::new(self.q.text.as_str())
let q = Paragraph::new(self.q.text.as_str())
.wrap(Wrap { trim: false })
.line_count(inner as u16) as u16;
let h = (qh + lines.len() as u16 + 3).min(bottom);
let r = Rect::new((area.width - w) / 2, bottom.saturating_sub(h), w, h);
.style(th.plain().add_modifier(Modifier::BOLD));
let qh = q.line_count(inner as u16) as u16;
// borders 2 + padding top 1, question, gap, list, help row
let h = (qh + lines.len() as u16 + 5).min(bottom).max(6.min(bottom));
let r = Rect::new((area.width - w) / 2, (bottom - h) / 2, w, h);
f.render_widget(Clear, r);
let block = Block::bordered()
.border_style(th.accent())
.title(Span::styled(format!(" {} ", self.help()), th.dim()));
.padding(Padding::new(1, 1, 1, 0));
let body = block.inner(r);
f.render_widget(block, r);
let [qa, la] = ratatui::layout::Layout::vertical([
ratatui::layout::Constraint::Length(qh.min(body.height)),
ratatui::layout::Constraint::Min(0),
let [qa, _, la, ha] = Layout::vertical([
Constraint::Length(qh.min(body.height.saturating_sub(2))),
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(1),
])
.areas(body);
f.render_widget(
Paragraph::new(self.q.text.as_str()).wrap(Wrap { trim: false }),
qa,
);
// keep the selection visible when the list is taller than the box
let skip = (self.sel as u16).saturating_sub(la.height.saturating_sub(1));
f.render_widget(q, qa);
let skip = (sel_line as u16).saturating_sub(la.height.saturating_sub(2));
f.render_widget(Paragraph::new(lines).scroll((skip, 0)), la);
f.render_widget(Span::styled(self.help(), th.dim()), ha);
}
pub fn summary(&self, answer: &Option<Vec<String>>) -> String {
@@ -189,6 +211,21 @@ impl Choose {
}
}
/// Greedy word wrap to `w` chars (a single longer word is kept whole).
fn wrap(s: &str, w: usize) -> Vec<String> {
let mut out: Vec<String> = vec![];
for word in s.split_whitespace() {
match out.last_mut() {
Some(l) if l.chars().count() + 1 + word.chars().count() <= w => {
l.push(' ');
l.push_str(word);
}
_ => out.push(word.to_string()),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
@@ -259,10 +296,10 @@ mod tests {
assert!(c.typing.is_some());
c.key(k(KeyCode::Esc));
assert!(c.typing.is_none());
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 12)).unwrap();
term.draw(|f| c.draw(f, 11)).unwrap();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 20)).unwrap();
term.draw(|f| c.draw(f, 19)).unwrap();
let b = term.backend().buffer().clone();
let all: String = (0..12)
let all: String = (0..20)
.map(|y| {
(0..60)
.map(|x| b[(x, y)].symbol().to_string())
@@ -275,4 +312,37 @@ mod tests {
"{all}"
);
}
#[test]
fn big_screen_is_wide_centered_and_wraps_descriptions() {
let c = Choose::new(Question {
text: "Which storage backend should the cache use?".into(),
options: vec![
("redis".into(), "word ".repeat(40)),
("none".into(), String::new()),
],
multi: false,
other: true,
});
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 50)).unwrap();
term.draw(|f| c.draw(f, 45)).unwrap();
let b = term.backend().buffer().clone();
let rows: Vec<String> = (0..50)
.map(|y| (0..200).map(|x| b[(x, y)].symbol().to_string()).collect())
.collect();
let top = rows
.iter()
.position(|r| r.contains('┌') || r.contains('╭'))
.unwrap();
let bot = rows
.iter()
.rposition(|r| r.contains('└') || r.contains('╰'))
.unwrap();
assert!(top > 10 && bot < 45, "centered: {top}..{bot}");
let border = &rows[top];
let wd = border.matches('─').count() + 2;
assert_eq!(wd, 120, "{border}");
assert!(rows.iter().filter(|r| r.contains("word word")).count() >= 2);
assert!(rows[bot - 1].contains("enter pick"), "{}", rows[bot - 1]);
}
}