use clap::Args;
use crossterm::{
event::{
read, DisableMouseCapture, EnableMouseCapture, Event,
KeyModifiers, MouseEventKind,
},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
backend::CrosstermBackend,
layout::Rect,
widgets::StatefulWidget,
Terminal,
};
use hefesto_widgets::{ChoosePopup, ChoosePopupState, PopupSize};
use crate::popup_config::{PopupConfig, PopupConfigurable};
use crate::{keybinds, style};
const SELECT_GUIDE: &str = include_str!("../guides/CHOOSE_GUIDE.md");
#[derive(Args)]
pub struct ChooseArgs {
#[arg(required = true)]
pub items: Vec<String>,
#[arg(short, long, default_value = "Seleccionar")]
pub title: String,
#[arg(short, long)]
pub multi: bool,
#[arg(short = 'W', long, default_value = "0")]
pub width: u16,
#[arg(short = 'H', long, default_value = "0")]
pub height: u16,
#[arg(short = 'M', long)]
pub max: Option<usize>,
#[arg(long)]
pub guide: bool,
}
pub fn run(args: ChooseArgs) {
if args.guide {
println!("{}", SELECT_GUIDE);
return;
}
crate::tty::ensure_terminal_stdin();
let mut tty: Box<dyn std::io::Write> = match std::fs::OpenOptions::new().write(true).open("/dev/tty") {
Ok(f) => Box::new(f),
Err(_) => Box::new(std::io::stdout()),
};
if enable_raw_mode().is_err() || execute!(tty, EnterAlternateScreen, EnableMouseCapture).is_err() {
eprintln!("{} choose: el terminal no es interactivo", crate::BIN_NAME);
std::process::exit(1);
}
let mut terminal = Terminal::new(CrosstermBackend::new(tty)).unwrap();
crate::tty::with_terminal_stdout(|| terminal.clear()).unwrap();
crate::tty::with_terminal_stdout(|| terminal.hide_cursor()).unwrap();
let items: Vec<(String, ratatui::style::Style)> = args.items.iter().map(|s| (s.clone(), ratatui::style::Style::default())).collect();
let mut state = ChoosePopupState::default();
let mut drag = crate::drag::DragState::new();
let mut origin: Option<(u16, u16)> = None;
let mut resize_w: Option<u16> = None;
let mut resize_h: Option<u16> = None;
let mut result: Option<Vec<String>> = None;
let mut pending_g: bool = false;
let mut cfg = PopupConfig::new()
.border_type(style::BORDER)
.header();
if args.width > 0 { cfg = cfg.width(args.width); }
if args.height > 0 { cfg = cfg.height(args.height); }
while result.is_none() {
let size = terminal.size().unwrap();
let area = Rect::new(0, 0, size.width, size.height);
let mut popup = ChoosePopup::new(items.clone())
.title(&args.title)
.with_config(&cfg);
if let Some(max) = args.max {
popup = popup.max_selected(max);
}
if let Some((ox, oy)) = origin {
popup = popup.origin(ox, oy);
}
let h = match cfg.height {
Some(uh) => PopupSize::Fixed(uh),
None => PopupSize::Fixed(crate::popup_rect::choose_default_height(items.len())),
};
popup = popup.height(h);
if let Some(w) = resize_w { popup = popup.width(PopupSize::Fixed(w)); }
if let Some(h) = resize_h { popup = popup.height(PopupSize::Fixed(h)); }
let pr = popup.resolve_rect(area, &state);
if resize_w.is_some() || resize_h.is_some() {
resize_w = Some(pr.width);
resize_h = Some(pr.height);
}
terminal
.draw(|frame| {
StatefulWidget::render(popup.clone(), frame.area(), frame.buffer_mut(), &mut state);
})
.unwrap();
match read().unwrap() {
Event::Key(key) => {
if key.code == keybinds::EMERGENCY && key.modifiers == KeyModifiers::CONTROL {
result = Some(vec![]);
} else {
match key.code {
keybinds::UP | keybinds::UP_ALT | keybinds::BACK_TAB => state.previous(),
keybinds::DOWN | keybinds::DOWN_ALT | keybinds::TAB => state.next(items.len()),
keybinds::TOGGLE_MULTI => {
if args.multi {
state.toggle(state.cursor);
} else if let Some(idx) = state.original_index(&items) {
let selected = vec![args.items[idx].clone()];
result = Some(selected);
}
}
keybinds::CONFIRM => {
if state.chosen_indices.is_empty() {
state.toggle_cursor();
}
let selected: Vec<String> = state
.chosen_indices
.iter()
.map(|&i| args.items[i].clone())
.collect();
result = Some(selected);
}
keybinds::CANCEL | keybinds::CANCEL_ALT => result = Some(vec![]),
keybinds::FIRST => {
if pending_g {
state.first();
pending_g = false;
} else {
pending_g = true;
}
}
keybinds::LAST => state.last(items.len()),
_ => pending_g = false,
}
}
},
Event::Mouse(mouse) => {
let col = mouse.column;
let row = mouse.row;
match mouse.kind {
MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
let zone = crate::drag::default_zone_at(pr, col, row);
drag.begin(pr, col, row, zone);
if !drag.is_dragging() {
if let Some(idx) = popup.item_at(&state, pr, row) {
if args.multi {
state.toggle(idx);
} else {
state.cursor = idx;
}
}
}
}
MouseEventKind::Drag(crossterm::event::MouseButton::Left) => {
match drag.update(area, col, row) {
crate::drag::DragUpdate::Moved { x, y } => origin = Some((x, y)),
crate::drag::DragUpdate::Resized { x, y, w, h } => {
origin = Some((x, y));
resize_w = Some(w);
resize_h = Some(h);
}
crate::drag::DragUpdate::None => {}
}
}
MouseEventKind::Up(crossterm::event::MouseButton::Left) => {
drag.end();
}
_ => {}
}
}
_ => {}
}
}
let selected = result.unwrap();
disable_raw_mode().unwrap();
execute!(terminal.backend_mut(), LeaveAlternateScreen, DisableMouseCapture).unwrap();
terminal.show_cursor().unwrap();
for item in &selected {
println!("{}", item);
}
if selected.is_empty() {
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use super::*;
use insta::assert_snapshot;
use ratatui::{backend::TestBackend, style::Style, Terminal};
use std::collections::HashSet;
fn render_popup(name: &str, popup: ChoosePopup<'_>, state: &mut ChoosePopupState) {
let backend = TestBackend::new(60, 20);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|f| f.render_stateful_widget(popup, f.area(), state))
.unwrap();
insta::with_settings!({
snapshot_path => "choose/snapshots",
prepend_module_to_snapshot => false,
}, {
assert_snapshot!(name, terminal.backend());
});
}
fn items() -> Vec<(String, Style)> {
vec![
("Manzana".to_string(), Style::default()),
("Banana".to_string(), Style::default()),
("Cereza".to_string(), Style::default()),
("Durazno".to_string(), Style::default()),
]
}
#[test]
fn snapshot_default() {
let popup = ChoosePopup::new(items());
let mut state = ChoosePopupState::default();
render_popup("choose_default", popup, &mut state);
}
#[test]
fn snapshot_with_title() {
let popup = ChoosePopup::new(items()).title("Frutas");
let mut state = ChoosePopupState::default();
render_popup("choose_with_title", popup, &mut state);
}
#[test]
fn snapshot_with_selection() {
let popup = ChoosePopup::new(items()).title("Frutas");
let mut state = ChoosePopupState {
chosen_indices: HashSet::from([0, 2]),
..Default::default()
};
render_popup("choose_with_selection", popup, &mut state);
}
}