pandora-kit 0.5.5

Interactive TUI toolkit for the Hefesto framework
Documentation
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::{Borders, StatefulWidget},
    Terminal,
};
use hefesto_widgets::{ChoosePopup, ChoosePopupState};

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,

    /// Popup width (0 = auto)
    #[arg(short = 'W', long, default_value = "0")]
    pub width: u16,

    /// Popup height (0 = auto)
    #[arg(short = 'H', long, default_value = "0")]
    pub height: u16,

    /// Max selected items (with --multi)
    #[arg(short = 'M', long)]
    pub max: Option<usize>,

    #[arg(long)]
    pub guide: bool,
}

fn contains(rect: Rect, col: u16, row: u16) -> bool {
    col >= rect.x
        && col < rect.x + rect.width
        && row >= rect.y
        && row < rect.y + rect.height
}

fn is_on_border(popup: Rect, col: u16, row: u16) -> bool {
    if !contains(popup, col, row) {
        return false;
    }
    let inner = Rect {
        x: popup.x + 1,
        y: popup.y + 1,
        width: popup.width.saturating_sub(2),
        height: popup.height.saturating_sub(2),
    };
    !contains(inner, col, row)
}

fn is_drag_area(popup: Rect, col: u16, row: u16) -> bool {
    if !contains(popup, col, row) {
        return false;
    }
    if is_on_border(popup, col, row) {
        return true;
    }
    let header_top = popup.y + 1;
    let header_bottom = header_top + 2;
    row >= header_top && row < header_bottom
}

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_offset: Option<(u16, u16)> = None;
    let mut origin: Option<(u16, 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);
        }
        popup = popup
            .filter_bg_color(style::FILL)
            .filter_borders(Borders::LEFT)
            .filter_border_type(style::FILTER_BORDER);

        let pr = popup.resolve_rect(area);

        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 => 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) => {
                        if is_drag_area(pr, col, row) {
                            let ox = col.saturating_sub(pr.x);
                            let oy = row.saturating_sub(pr.y);
                            drag_offset = Some((ox, oy));
                        } else 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) => {
                        if let Some((dx, dy)) = drag_offset {
                            let max_w = area.width.saturating_sub(pr.width);
                            let max_h = area.height.saturating_sub(pr.height);
                            let nx = (col as i16 - dx as i16).clamp(0, max_w as i16) as u16;
                            let ny = (row as i16 - dy as i16).clamp(0, max_h as i16) as u16;
                            origin = Some((nx, ny));
                        }
                    }
                    MouseEventKind::Up(crossterm::event::MouseButton::Left) => {
                        drag_offset = None;
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    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()),
        ]
    }

    // ── geometry helpers ──

    #[test]
    fn contains_inside() {
        let r = Rect::new(10, 5, 20, 10);
        assert!(contains(r, 15, 8));
    }

    #[test]
    fn contains_outside() {
        let r = Rect::new(10, 5, 20, 10);
        assert!(!contains(r, 5, 8));
        assert!(!contains(r, 35, 8));
    }

    #[test]
    fn contains_excludes_right_and_bottom_edge() {
        let r = Rect::new(10, 5, 20, 10);
        assert!(!contains(r, 30, 8));
        assert!(!contains(r, 15, 15));
    }

    #[test]
    fn is_on_border_top_edge() {
        let r = Rect::new(10, 5, 20, 10);
        assert!(is_on_border(r, 15, 5));
    }

    #[test]
    fn is_on_border_left_edge() {
        let r = Rect::new(10, 5, 20, 10);
        assert!(is_on_border(r, 10, 8));
    }

    #[test]
    fn is_on_border_inside() {
        let r = Rect::new(10, 5, 20, 10);
        assert!(!is_on_border(r, 15, 8));
    }

    #[test]
    fn is_drag_area_in_header() {
        let r = Rect::new(0, 0, 60, 20);
        assert!(is_drag_area(r, 5, 1));
        assert!(is_drag_area(r, 5, 2));
    }

    #[test]
    fn is_drag_area_outside() {
        let r = Rect::new(0, 0, 60, 20);
        assert!(!is_drag_area(r, 100, 5));
    }

    // ── snapshots ──

    #[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);
    }
}