type Rgb = (u8, u8, u8);
use crate::palette_generated::{
AMBER, AMBER_256, AMBER_DEEP, AMBER_LIGHT, CHARCOAL, CHARCOAL_256, DANGER, DANGER_256, HEADING,
HEADING_256, MUTED, MUTED_256, ON_AMBER, ON_AMBER_256, SUCCESS, SUCCESS_256, WARNING,
WARNING_256,
};
const SPIN_UNICODE: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const SPIN_ASCII: &[&str] = &["-", "\\", "|", "/"];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorTier {
Truecolor,
Ansi256,
Basic,
None,
}
pub struct BoxChars {
pub tl: &'static str,
pub tr: &'static str,
pub bl: &'static str,
pub br: &'static str,
pub h: &'static str,
pub v: &'static str,
}
#[derive(Debug, Clone, Copy)]
pub struct Theme {
pub ascii: bool,
pub tier: ColorTier,
}
impl Theme {
pub fn detect(no_color_flag: bool, ascii_flag: bool) -> Theme {
let no_color = std::env::var_os("NO_COLOR").is_some() || no_color_flag;
Theme {
ascii: ascii_flag || !locale_is_utf8(),
tier: detect_tier(no_color),
}
}
pub fn paints_background(&self) -> bool {
matches!(self.tier, ColorTier::Truecolor | ColorTier::Ansi256)
}
pub fn background_prefix(&self) -> String {
match self.tier {
ColorTier::Truecolor => bg_rgb(CHARCOAL),
ColorTier::Ansi256 => format!("\x1b[48;5;{CHARCOAL_256}m"),
_ => String::new(),
}
}
fn fg(&self, rgb: Rgb, idx: u8, basic: u8, s: &str) -> String {
match self.tier {
ColorTier::Truecolor => format!("\x1b[38;2;{};{};{}m{s}\x1b[39m", rgb.0, rgb.1, rgb.2),
ColorTier::Ansi256 => format!("\x1b[38;5;{idx}m{s}\x1b[39m"),
ColorTier::Basic => format!("\x1b[{basic}m{s}\x1b[39m"),
ColorTier::None => s.to_string(),
}
}
pub fn ok(&self, s: &str) -> String {
self.fg(SUCCESS, SUCCESS_256, 32, s)
}
pub fn fail(&self, s: &str) -> String {
self.fg(DANGER, DANGER_256, 31, s)
}
pub fn accent(&self, s: &str) -> String {
self.fg(AMBER, AMBER_256, 33, s)
}
pub fn warn(&self, s: &str) -> String {
self.fg(WARNING, WARNING_256, 33, s)
}
pub fn dim(&self, s: &str) -> String {
self.fg(MUTED, MUTED_256, 90, s)
}
pub fn heading(&self, s: &str) -> String {
self.bold(&self.fg(HEADING, HEADING_256, 97, s))
}
pub fn bold(&self, s: &str) -> String {
if self.tier == ColorTier::None {
s.to_string()
} else {
format!("\x1b[1m{s}\x1b[22m")
}
}
pub fn amber_gradient(&self, row: usize, s: &str) -> String {
match self.tier {
ColorTier::Truecolor => {
let rgb = match row {
0 => AMBER_LIGHT,
1 => AMBER,
_ => AMBER_DEEP,
};
self.bold(&format!(
"\x1b[38;2;{};{};{}m{s}\x1b[39m",
rgb.0, rgb.1, rgb.2
))
}
_ => self.bold(&self.accent(s)),
}
}
pub fn selection_bar(&self, content: &str, width: usize) -> String {
let body = pad_or_clip(content, width);
match self.tier {
ColorTier::Truecolor => format!(
"{}{}{body}{}",
bg_rgb(AMBER),
fg_rgb(ON_AMBER),
self.restore_base()
),
ColorTier::Ansi256 => format!(
"\x1b[48;5;{AMBER_256}m\x1b[38;5;{ON_AMBER_256}m{body}{}",
self.restore_base()
),
ColorTier::Basic => self.bold(&self.accent(content)),
ColorTier::None => content.to_string(),
}
}
fn restore_base(&self) -> String {
match self.tier {
ColorTier::Truecolor => format!("{}\x1b[39m", bg_rgb(CHARCOAL)),
ColorTier::Ansi256 => format!("\x1b[48;5;{CHARCOAL_256}m\x1b[39m"),
_ => "\x1b[39m".to_string(),
}
}
pub fn spinner(&self, frame: usize) -> &'static str {
if self.ascii {
SPIN_ASCII[frame % SPIN_ASCII.len()]
} else {
SPIN_UNICODE[frame % SPIN_UNICODE.len()]
}
}
pub fn glyph_ok(&self) -> &'static str {
if self.ascii {
"+"
} else {
"✓"
}
}
pub fn glyph_fail(&self) -> &'static str {
if self.ascii {
"x"
} else {
"✗"
}
}
pub fn glyph_pending(&self) -> &'static str {
if self.ascii {
"."
} else {
"•"
}
}
pub fn dot_filled(&self) -> &'static str {
if self.ascii {
"#"
} else {
"●"
}
}
pub fn dot_empty(&self) -> &'static str {
if self.ascii {
"."
} else {
"○"
}
}
pub fn box_checked(&self) -> &'static str {
if self.ascii {
"#"
} else {
"■"
}
}
pub fn box_unchecked(&self) -> &'static str {
if self.ascii {
"."
} else {
"□"
}
}
pub fn box_chars(&self) -> BoxChars {
if self.ascii {
BoxChars {
tl: "+",
tr: "+",
bl: "+",
br: "+",
h: "-",
v: "|",
}
} else {
BoxChars {
tl: "╭",
tr: "╮",
bl: "╰",
br: "╯",
h: "─",
v: "│",
}
}
}
}
fn fg_rgb(rgb: Rgb) -> String {
format!("\x1b[38;2;{};{};{}m", rgb.0, rgb.1, rgb.2)
}
fn bg_rgb(rgb: Rgb) -> String {
format!("\x1b[48;2;{};{};{}m", rgb.0, rgb.1, rgb.2)
}
fn pad_or_clip(content: &str, width: usize) -> String {
let n = content.chars().count();
if n == width {
content.to_string()
} else if n < width {
format!("{content}{}", " ".repeat(width - n))
} else if width == 0 {
String::new()
} else {
let mut out: String = content.chars().take(width.saturating_sub(1)).collect();
out.push('…');
out
}
}
fn detect_tier(no_color: bool) -> ColorTier {
if no_color {
return ColorTier::None;
}
let term = std::env::var("TERM").unwrap_or_default();
if term == "dumb" {
return ColorTier::None;
}
let colorterm = std::env::var("COLORTERM")
.unwrap_or_default()
.to_lowercase();
if colorterm.contains("truecolor") || colorterm.contains("24bit") {
return ColorTier::Truecolor;
}
if term.contains("256color") {
return ColorTier::Ansi256;
}
ColorTier::Basic
}
fn locale_is_utf8() -> bool {
for key in ["LC_ALL", "LC_CTYPE", "LANG"] {
if let Ok(v) = std::env::var(key) {
if v.is_empty() {
continue;
}
let v = v.to_ascii_lowercase();
return v.contains("utf-8") || v.contains("utf8");
}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
fn plain() -> Theme {
Theme {
ascii: false,
tier: ColorTier::None,
}
}
#[test]
fn no_color_tier_emits_plain_text() {
let t = plain();
assert_eq!(t.ok("✓"), "✓");
assert_eq!(t.dim("x"), "x");
assert_eq!(t.accent("a"), "a");
assert_eq!(t.bold("b"), "b");
assert_eq!(t.heading("h"), "h");
assert_eq!(t.selection_bar("row", 3), "row");
}
#[test]
fn truecolor_amber_accent_uses_rgb_sgr() {
let t = Theme {
ascii: false,
tier: ColorTier::Truecolor,
};
let a = t.accent("x");
assert!(
a.contains("\x1b[38;2;235;193;87m"),
"amber rgb missing: {a:?}"
);
assert!(a.ends_with("\x1b[39m"), "fg not reset: {a:?}");
assert!(!a.contains("\x1b[0m"), "must not full-reset: {a:?}");
}
#[test]
fn selection_bar_is_full_width_amber_with_dark_text() {
let t = Theme {
ascii: false,
tier: ColorTier::Truecolor,
};
let bar = t.selection_bar("● Drone", 20);
assert!(
bar.contains("\x1b[48;2;235;193;87m"),
"amber bg missing: {bar:?}"
);
assert!(
bar.contains("\x1b[38;2;26;26;26m"),
"dark fg missing: {bar:?}"
);
assert!(
bar.contains("\x1b[48;2;31;31;31m"),
"charcoal restore missing: {bar:?}"
);
assert_eq!(super::pad_or_clip("● Drone", 20).chars().count(), 20);
}
#[test]
fn background_prefix_only_on_painting_tiers() {
let tc = Theme {
ascii: false,
tier: ColorTier::Truecolor,
};
assert_eq!(tc.background_prefix(), "\x1b[48;2;31;31;31m");
assert!(tc.paints_background());
let basic = Theme {
ascii: false,
tier: ColorTier::Basic,
};
assert!(basic.background_prefix().is_empty());
assert!(!basic.paints_background());
assert!(plain().background_prefix().is_empty());
}
#[test]
fn ascii_tier_uses_ascii_glyphs() {
let t = Theme {
ascii: true,
tier: ColorTier::None,
};
assert_eq!(t.glyph_ok(), "+");
assert_eq!(t.glyph_fail(), "x");
assert_eq!(t.spinner(0), "-");
assert_eq!(t.box_chars().h, "-");
assert_eq!(t.dot_filled(), "#");
assert_eq!(t.box_checked(), "#");
}
#[test]
fn unicode_glyphs_are_single_column() {
let t = plain();
for g in [
t.glyph_ok(),
t.glyph_fail(),
t.glyph_pending(),
t.spinner(2),
t.dot_filled(),
t.dot_empty(),
t.box_checked(),
t.box_unchecked(),
] {
assert_eq!(g.chars().count(), 1, "glyph {g:?} must be one column");
}
}
}