Files
hx/crates/hx-tui/src/choose.rs
T
johannesandClaude Haiku 4.5 ec1c4fb41a
build / version (push) Successful in 16s
build / build (aarch64-apple-darwin) (push) Successful in 4m9s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m8s
build / release (push) Successful in 26s
feat: cursor movement in ask_user free-form input
- Replace bare string with Editor in choose.rs typing input
- Support ←/→ (left/right arrow keys) for cursor movement
- Add Home/End, ctrl-a/ctrl-e, Delete, Up/Down between lines
- Keep ctrl-w (kill word), add ctrl-u (kill line)
- Render cursor marker ▏ at actual position in multi-line answers
- Update help text to mention cursor movement
- Add test: type, move cursor, insert character mid-text

Also: delete 4 comment lines from scripts/lint-comments.sh (tautology).

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-11-21 13:45:53 +01:00

474 lines
16 KiB
Rust

use crate::editor::Editor;
use crate::theme;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use hx_core::Question;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
pub enum Act {
None,
Done(Option<Vec<String>>),
}
pub struct Choose {
q: Question,
sel: usize,
picked: Vec<bool>,
typing: Option<Editor>,
direct: bool,
}
impl Choose {
pub fn new(q: Question) -> Self {
Self {
picked: vec![false; q.options.len()],
q,
sel: 0,
typing: None,
direct: false,
}
}
pub fn input(q: Question) -> Self {
let mut c = Self::new(q);
c.typing = Some(Editor::default());
c.direct = true;
c
}
fn rows(&self) -> usize {
self.q.options.len() + usize::from(self.q.other)
}
fn is_other(&self) -> bool {
self.q.other && self.sel == self.q.options.len()
}
fn labels(&self) -> Vec<String> {
let mut v: Vec<String> = (0..self.picked.len())
.filter(|&i| self.picked[i])
.map(|i| self.q.options[i].0.clone())
.collect();
if v.is_empty() && !self.is_other() && self.sel < self.q.options.len() {
v.push(self.q.options[self.sel].0.clone());
}
v
}
pub fn key(&mut self, k: KeyEvent) -> Act {
if k.modifiers.contains(KeyModifiers::CONTROL) && k.code == KeyCode::Char('c') {
return Act::Done(None);
}
let picked = if self.q.multi { self.labels() } else { vec![] };
if let Some(ed) = &mut self.typing {
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
match k.code {
KeyCode::Esc if self.direct => return Act::Done(None),
KeyCode::Esc => self.typing = None,
KeyCode::Backspace => ed.backspace(),
KeyCode::Delete => ed.delete(),
KeyCode::Left => ed.left(),
KeyCode::Right => ed.right(),
KeyCode::Up => ed.up(),
KeyCode::Down => ed.down(),
KeyCode::Home => ed.home(),
KeyCode::End => ed.end(),
KeyCode::Char('a') if ctrl => ed.home(),
KeyCode::Char('e') if ctrl => ed.end(),
KeyCode::Char('u') if ctrl => ed.kill_line(),
KeyCode::Char('w') if ctrl => ed.kill_word(),
KeyCode::Char('j') if ctrl => ed.insert("\n"),
KeyCode::Enter
if k.modifiers
.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT) =>
{
ed.insert("\n")
}
KeyCode::Char(c) if !ctrl => ed.insert(c.encode_utf8(&mut [0; 4])),
KeyCode::Enter if !ed.buf.trim().is_empty() => {
let mut v = picked;
v.push(ed.buf.trim().to_string());
return Act::Done(Some(v));
}
_ => {}
}
return Act::None;
}
let n = self.rows();
match k.code {
KeyCode::Esc => return Act::Done(None),
KeyCode::Up | KeyCode::Char('k') => self.sel = (self.sel + n.max(1) - 1) % n.max(1),
KeyCode::Down | KeyCode::Char('j') => self.sel = (self.sel + 1) % n.max(1),
KeyCode::Char(' ') if self.q.multi && !self.is_other() => {
self.picked[self.sel] = !self.picked[self.sel];
}
KeyCode::Char(c @ '1'..='9') => {
let i = c as usize - '1' as usize;
if i < n {
self.sel = i;
if self.q.multi && !self.is_other() {
self.picked[i] = !self.picked[i];
} else {
return self.enter();
}
}
}
KeyCode::Enter => return self.enter(),
_ => {}
}
Act::None
}
pub fn paste(&mut self, s: &str) {
if let Some(ed) = &mut self.typing {
ed.insert(s);
}
}
fn enter(&mut self) -> Act {
if self.is_other() || self.rows() == 0 {
self.typing = Some(Editor::default());
return Act::None;
}
Act::Done(Some(self.labels()))
}
pub fn help(&self) -> &'static str {
if self.typing.is_some() {
"enter send · ←→ move · shift/alt-enter newline · ctrl-w word · esc back"
} else if self.q.multi {
"↑↓ move · space toggle · enter confirm · esc skip"
} else {
"↑↓ move · 1-9 · enter pick · esc skip"
}
}
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 == "#" {
("[x]", "[ ]")
} 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![];
let mut sel_line = 0;
for (i, (l, d)) in self.q.options.iter().enumerate() {
let on_row = i == self.sel && self.typing.is_none();
if i == self.sel {
sel_line = lines.len();
}
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 n = self.q.options.len();
if self.is_other() {
sel_line = lines.len();
}
if let Some(ed) = &self.typing {
let pre = format!("{} other: ", n + 1);
let (a, b) = ed.buf.split_at(ed.cur);
let rows = hard_wrap(&format!("{pre}{a}▏{b}"), inner);
let before = hard_wrap(&format!("{pre}{a}▏"), inner).len();
sel_line = lines.len() + before - 1;
for (i, r) in rows.into_iter().enumerate() {
if i == 0 {
let k = pre.len().min(r.len());
lines.push(Line::from(vec![
Span::styled(r[..k].to_string(), th.accent()),
Span::raw(r[k..].to_string()),
]));
} else {
lines.push(Line::raw(r));
}
}
} else {
let st = if self.is_other() {
th.sel()
} else {
th.plain()
};
lines.push(Line::from(vec![
Span::styled(format!("{} ", n + 1), th.accent()),
Span::styled("other…", st),
]));
}
}
let q = Paragraph::new(self.q.text.as_str())
.wrap(Wrap { trim: false })
.style(th.plain().add_modifier(Modifier::BOLD));
let qh = q.line_count(inner as u16) as u16;
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())
.padding(Padding::new(1, 1, 1, 0));
let body = block.inner(r);
f.render_widget(block, r);
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(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 {
match answer {
Some(v) => format!("? {} → {}", self.q.text, v.join(", ")),
None => format!("? {} → (skipped)", self.q.text),
}
}
}
fn hard_wrap(s: &str, w: usize) -> Vec<String> {
let w = w.max(1);
let mut out = vec![];
for para in s.split('\n') {
let mut cur: Vec<char> = vec![];
for c in para.chars() {
if cur.len() >= w {
let at = cur.iter().rposition(|&x| x == ' ').map_or(w, |i| i + 1);
out.push(cur.drain(..at).collect());
}
cur.push(c);
}
out.push(cur.into_iter().collect());
}
out
}
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::*;
fn q(multi: bool) -> Choose {
Choose::new(Question {
text: "which db?".into(),
options: vec![
("pg".into(), "postgres".into()),
("lite".into(), String::new()),
],
multi,
other: true,
plan: None,
})
}
fn k(c: KeyCode) -> KeyEvent {
KeyEvent::new(c, KeyModifiers::NONE)
}
fn done(a: Act) -> Option<Vec<String>> {
match a {
Act::Done(v) => v,
Act::None => panic!("not done"),
}
}
#[test]
fn single_pick_by_enter_number_esc() {
let mut c = q(false);
c.key(k(KeyCode::Down));
assert_eq!(done(c.key(k(KeyCode::Enter))), Some(vec!["lite".into()]));
assert_eq!(
done(q(false).key(k(KeyCode::Char('1')))),
Some(vec!["pg".into()])
);
assert_eq!(done(q(false).key(k(KeyCode::Esc))), None);
let mut c = q(false);
c.key(k(KeyCode::Up));
assert!(c.is_other());
}
#[test]
fn input_starts_typing_and_esc_dismisses() {
let q = || Question {
text: "why?".into(),
options: vec![],
multi: false,
other: true,
plan: None,
};
let mut c = Choose::input(q());
c.key(k(KeyCode::Char('h')));
c.key(k(KeyCode::Char('i')));
assert!(matches!(c.key(k(KeyCode::Enter)), Act::Done(Some(v)) if v == ["hi"]));
let mut c = Choose::input(q());
assert!(matches!(c.key(k(KeyCode::Esc)), Act::Done(None)));
}
#[test]
fn arrows_move_the_cursor() {
let mut c = Choose::input(Question {
text: "why?".into(),
options: vec![],
multi: false,
other: true,
plan: None,
});
for ch in "abc".chars() {
c.key(k(KeyCode::Char(ch)));
}
c.key(k(KeyCode::Left));
c.key(k(KeyCode::Left));
c.key(k(KeyCode::Char('X')));
assert_eq!(done(c.key(k(KeyCode::Enter))), Some(vec!["aXbc".into()]));
}
#[test]
fn multi_toggle_and_other_text() {
let mut c = q(true);
c.key(k(KeyCode::Char(' ')));
c.key(k(KeyCode::Char('2')));
assert_eq!(
done(c.key(k(KeyCode::Enter))),
Some(vec!["pg".into(), "lite".into()])
);
let mut c = q(true);
c.key(k(KeyCode::Char('1')));
c.key(k(KeyCode::Char('3')));
assert!(matches!(c.key(k(KeyCode::Enter)), Act::None));
for ch in "duck".chars() {
c.key(k(KeyCode::Char(ch)));
}
assert_eq!(
done(c.key(k(KeyCode::Enter))),
Some(vec!["pg".into(), "duck".into()])
);
}
#[test]
fn long_answer_wraps_and_stays_visible() {
let mut c = q(false);
c.key(k(KeyCode::Char('3')));
for ch in "word ".repeat(30).chars().chain("END".chars()) {
c.key(k(KeyCode::Char(ch)));
}
c.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT));
c.paste("pasted\r\nmore");
c.key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL));
assert!(
c.typing
.as_ref()
.unwrap()
.buf
.ends_with("pasted\nmore".trim_end_matches("more"))
);
for ch in "tail".chars() {
c.key(k(KeyCode::Char(ch)));
}
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24)).unwrap();
term.draw(|f| c.draw(f, 23)).unwrap();
let b = term.backend().buffer().clone();
let all: String = (0..24)
.map(|y| {
(0..80)
.map(|x| b[(x, y)].symbol().to_string())
.collect::<String>()
+ "\n"
})
.collect();
assert!(all.contains("END") && all.contains("tail▏"), "{all}");
assert_eq!(hard_wrap("aaaa bbbb cccc", 9), ["aaaa ", "bbbb cccc"]);
assert_eq!(hard_wrap("abcdefgh", 3), ["abc", "def", "gh"]);
}
#[test]
fn typing_esc_goes_back_and_renders() {
let mut c = q(false);
c.key(k(KeyCode::Char('3')));
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, 20)).unwrap();
term.draw(|f| c.draw(f, 19)).unwrap();
let b = term.backend().buffer().clone();
let all: String = (0..20)
.map(|y| {
(0..60)
.map(|x| b[(x, y)].symbol().to_string())
.collect::<String>()
+ "\n"
})
.collect();
assert!(
all.contains("which db?") && all.contains("postgres") && all.contains("other…"),
"{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,
plan: None,
});
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]);
}
}