haj 0.3.5

the beautiful, cross-distro package manager and tui.
use crossterm::style::Stylize;
use std::io::{IsTerminal, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::task::AbortHandle;

const SHARK_FRAMES: &[&str] = &[
    "[><((*>   ]",
    "[ ><((*>  ]",
    "[  ><((*> ]",
    "[   ><((*>]",
    "[  <*))>< ]",
    "[ <*))><  ]",
    "[<*))><   ]",
];

// Keep exact frame display width (11 columns) + 2-column spacing/margin.
const FRAME_WIDTH: usize = 11;

struct RenderState {
    message: String,
    active: bool,
    cleared: bool,
}

pub struct ProgressBar {
    state: Arc<Mutex<RenderState>>,
    stop: Arc<AtomicBool>,
    abort: Mutex<Option<AbortHandle>>,
    is_tty: bool,
}

fn normalize_spinner_msg(raw: &str) -> String {
    let flat = raw.replace(['\r', '\n'], " ");
    let trimmed = flat.trim();
    for prefix in [":: ", "\x1b[34m::\x1b[39m ", "\x1b[38;5;12m::\x1b[39m "] {
        if let Some(rest) = trimmed.strip_prefix(prefix) {
            return rest.trim_start().to_string();
        }
    }
    trimmed.to_string()
}

fn clamp_ansi_visible(text: &str, max_cols: usize) -> String {
    if max_cols == 0 {
        return String::new();
    }
    let mut out = String::with_capacity(text.len());
    let mut visible = 0usize;
    let mut has_ansi = false;
    let mut chars = text.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\x1b' {
            has_ansi = true;
            out.push(c);
            if chars.peek() == Some(&'[') {
                for seq in chars.by_ref() {
                    out.push(seq);
                    if seq.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
            continue;
        }
        if c.is_control() {
            continue;
        }
        if visible >= max_cols {
            break;
        }
        out.push(c);
        visible += 1;
    }

    if has_ansi {
        out.push_str("\x1b[0m");
    }
    out
}

fn format_spinner_line(frame: &str, message: &str, term_cols: usize) -> String {
    let max_msg_cols = term_cols.saturating_sub(FRAME_WIDTH + 2).max(16);
    let clean = normalize_spinner_msg(message);
    let clamped = clamp_ansi_visible(&clean, max_msg_cols);
    format!("{} {clamped}", frame.cyan())
}

impl ProgressBar {
    pub fn new_spinner() -> Self {
        let is_tty = std::io::stdout().is_terminal();
        ProgressBar {
            state: Arc::new(Mutex::new(RenderState {
                message: String::new(),
                active: is_tty,
                cleared: !is_tty,
            })),
            stop: Arc::new(AtomicBool::new(false)),
            abort: Mutex::new(None),
            is_tty,
        }
    }

    pub fn enable_steady_tick(&mut self, duration: Duration) {
        if !self.is_tty {
            return;
        }
        let state = Arc::clone(&self.state);
        let stop = Arc::clone(&self.stop);
        let period = if duration.is_zero() {
            Duration::from_millis(100)
        } else {
            duration
        };

        // Hide cursor during active spin to prevent cursor jitter inside frames.
        print!("\x1b[?25l");
        let _ = std::io::stdout().flush();

        let join = tokio::spawn(async move {
            let mut i = 0usize;
            loop {
                if stop.load(Ordering::Acquire) {
                    break;
                }
                {
                    let guard = state
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    if !guard.active || stop.load(Ordering::Acquire) {
                        break;
                    }
                    let cols = crossterm::terminal::size()
                        .map(|(w, _)| w as usize)
                        .unwrap_or(80);
                    let line = format_spinner_line(SHARK_FRAMES[i], &guard.message, cols);
                    print!("\r\x1b[2K{line}");
                    let _ = std::io::stdout().flush();
                }
                i = (i + 1) % SHARK_FRAMES.len();
                tokio::time::sleep(period).await;
            }
        });

        *self
            .abort
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(join.abort_handle());
    }

    pub fn set_message(&self, message: String) {
        let mut guard = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.message = message;
    }

    pub fn finish_and_clear(&self) {
        self.stop.store(true, Ordering::Release);
        if let Some(handle) = self
            .abort
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
        {
            handle.abort();
        }
        let mut guard = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.active = false;
        if self.is_tty && !guard.cleared {
            guard.cleared = true;
            print!("\r\x1b[2K\x1b[?25h");
            let _ = std::io::stdout().flush();
        }
    }
}

impl Drop for ProgressBar {
    fn drop(&mut self) {
        self.finish_and_clear();
    }
}

pub fn spinner(message: &str) -> ProgressBar {
    let mut pb = ProgressBar::new_spinner();
    pb.set_message(message.to_string());
    pb.enable_steady_tick(Duration::from_millis(100));
    pb
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_shark_frames_uniform_ascii_width() {
        for frame in SHARK_FRAMES {
            assert!(frame.is_ascii(), "frame must be pure ASCII: {frame:?}");
            assert_eq!(frame.len(), FRAME_WIDTH);
        }
    }

    #[test]
    fn test_normalize_and_clamp_prevents_wrapping() {
        assert_eq!(
            normalize_spinner_msg(":: packaging\nbinary..."),
            "packaging binary..."
        );
        assert_eq!(clamp_ansi_visible("hello\nworld", 5), "hello");

        let colored = format!("compiling {}...", "ripgrep".bold());
        let clamped = clamp_ansi_visible(&colored, 12);
        assert!(clamped.ends_with("\x1b[0m"));
    }
}