use ratatui::layout::Rect;
pub fn truncate(s: &str, max: usize) -> String {
if s.chars().count() > max {
s.chars().take(max.saturating_sub(1)).collect::<String>() + "…"
} else {
s.to_string()
}
}
pub fn fmt_ms(ms: u32) -> String {
let s = ms / 1000;
format!("{}:{:02}", s / 60, s % 60)
}
pub fn vol_u16(pct: u8) -> u16 {
(pct as u32 * 65535 / 100) as u16
}
pub fn center_v(area: Rect, height: u16) -> Rect {
let y = area.y + area.height.saturating_sub(height) / 2;
Rect {
x: area.x,
y,
width: area.width,
height: height.min(area.height),
}
}
pub fn uri_to_url(uri: &str) -> String {
let mut p = uri.split(':');
p.next();
let kind = p.next().unwrap_or("");
let id = p.next().unwrap_or("");
format!("https://open.spotify.com/{kind}/{id}")
}
pub fn track_id_from_uri(uri: &str) -> Option<String> {
let mut parts = uri.split(':');
match (parts.next(), parts.next(), parts.next()) {
(Some("spotify"), Some("track"), Some(id)) => Some(id.to_string()),
_ => None,
}
}
pub fn urlencode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}