use crate::theme::Theme;
use ratatui::{
Frame,
layout::{Constraint, Direction, Layout, Rect},
style::Style,
text::{Line, Span},
widgets::{Block, Clear},
};
const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
pub(crate) fn clear_area(frame: &mut Frame, area: Rect, theme: &Theme) {
frame.render_widget(Clear, area);
frame.render_widget(Block::default().style(Style::default().bg(theme.bg)), area);
}
pub(crate) fn spinner_span(tick: u64, theme: &Theme) -> Span<'static> {
Span::styled(format!(" {} ", spinner_frame(tick)), theme.brand_bold())
}
pub(crate) fn right_pad(mut spans: Vec<Span<'static>>, _width: u16) -> Line<'static> {
spans.push(Span::raw(" ".repeat(120)));
Line::from(spans)
}
pub(crate) fn tilde_path(path: &str) -> String {
match dirs::home_dir() {
Some(home) => {
let home = home.to_string_lossy();
if let Some(rest) = path.strip_prefix(home.as_ref()) {
format!("~{rest}")
} else {
path.to_string()
}
}
None => path.to_string(),
}
}
pub(crate) fn download_percent(downloaded: u64, total: u64) -> f64 {
#[allow(clippy::cast_precision_loss)]
let pct = if total > 0 {
(downloaded as f64 / total as f64 * 100.0).min(100.0)
} else {
0.0
};
pct
}
pub(crate) fn shorten_path(path: &str, max: usize) -> String {
let chars: Vec<char> = path.chars().collect();
if chars.len() <= max {
path.to_string()
} else {
let tail: String = chars[chars.len() - (max - 1)..].iter().collect();
format!("…{tail}")
}
}
pub(crate) fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}
fn spinner_frame(tick: u64) -> &'static str {
#[allow(clippy::cast_possible_truncation)]
let idx = (tick as usize) % SPINNER.len();
SPINNER[idx]
}