//! Popup for the `ask_user` tool: pick one or several options, or type an own answer. 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, /// Close and answer: chosen labels / typed text, None = dismissed. Done(Option>), } pub struct Choose { q: Question, sel: usize, picked: Vec, /// Some while typing an own answer typing: Option, } impl Choose { pub fn new(q: Question) -> Self { Self { picked: vec![false; q.options.len()], q, sel: 0, typing: None, } } 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 { let mut v: Vec = (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(t) = &mut self.typing { match k.code { KeyCode::Esc => self.typing = None, KeyCode::Backspace => { t.pop(); } KeyCode::Char('w') if k.modifiers.contains(KeyModifiers::CONTROL) => { let n = t .trim_end() .trim_end_matches(|c: char| !c.is_whitespace()) .len(); t.truncate(n); } KeyCode::Char('j') if k.modifiers.contains(KeyModifiers::CONTROL) => t.push('\n'), KeyCode::Enter if k.modifiers .intersects(KeyModifiers::SHIFT | KeyModifiers::ALT) => { t.push('\n') } KeyCode::Char(c) if !k.modifiers.contains(KeyModifiers::CONTROL) => t.push(c), KeyCode::Enter if !t.trim().is_empty() => { let mut v = picked; v.push(t.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 } /// Bracketed paste: append to the own answer while typing. pub fn paste(&mut self, s: &str) { if let Some(t) = &mut self.typing { t.push_str(&s.replace("\r\n", "\n").replace('\r', "\n")); } } fn enter(&mut self) -> Act { if self.is_other() || self.rows() == 0 { self.typing = Some(String::new()); return Act::None; } Act::Done(Some(self.labels())) } pub fn help(&self) -> &'static str { if self.typing.is_some() { "enter send · 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" } } /// 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 == "#" { ("[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 = 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 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(t) = &self.typing { let pre = format!("{} other: ", n + 1); let rows = hard_wrap(&format!("{pre}{t}▏"), inner); sel_line = lines.len() + rows.len() - 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; // 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()) .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>) -> String { match answer { Some(v) => format!("? {} → {}", self.q.text, v.join(", ")), None => format!("? {} → (skipped)", self.q.text), } } } /// Wrap to `w` chars keeping all spaces/newlines; break at last space, else hard. fn hard_wrap(s: &str, w: usize) -> Vec { let w = w.max(1); let mut out = vec![]; for para in s.split('\n') { let mut cur: Vec = 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 } /// Greedy word wrap to `w` chars (a single longer word is kept whole). fn wrap(s: &str, w: usize) -> Vec { let mut out: Vec = 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> { 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); // wraps up from the top onto "other" let mut c = q(false); c.key(k(KeyCode::Up)); assert!(c.is_other()); } #[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)); // empty text: stays 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_deref() .unwrap() .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::() + "\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::() + "\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 = (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]); } }