//! 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(c) => 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 } 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 · 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(); } lines.push(match &self.typing { Some(t) => Line::from(vec![ Span::styled(format!("{} ", n + 1), th.accent()), Span::styled("other: ", th.accent()), Span::raw(format!("{t}▏")), ]), None => Line::from(vec![ Span::styled(format!("{} ", n + 1), th.accent()), Span::styled( "other…", if self.is_other() { th.sel() } else { th.plain() }, ), ]), }); } 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), } } } /// 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, }) } 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 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, }); 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]); } }