wolf_graph_mermaid/details/
color.rs

1use std::fmt;
2
3#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4pub enum Color {
5    StaticNamed(&'static str),
6    Named(String),
7    Rgb(u8, u8, u8, Option<u8>),
8}
9
10impl Color {
11    pub const fn new(name: &'static str) -> Self {
12        Self::StaticNamed(name)
13    }
14
15    pub fn rgb(r: u8, g: u8, b: u8, a: Option<u8>) -> Self {
16        Self::Rgb(r, g, b, a)
17    }
18
19    pub const RED: Color = Color::new("red");
20    pub const GREEN: Color = Color::new("green");
21    pub const BLUE: Color = Color::new("blue");
22    pub const CYAN: Color = Color::new("cyan");
23    pub const MAGENTA: Color = Color::new("magenta");
24    pub const YELLOW: Color = Color::new("yellow");
25    pub const BLACK: Color = Color::new("black");
26    pub const WHITE: Color = Color::new("white");
27    pub const GRAY: Color = Color::new("gray");
28}
29
30impl fmt::Display for Color {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self {
33            Color::StaticNamed(name) => write!(f, "{}", name),
34            Color::Named(name) => write!(f, "{}", name),
35            Color::Rgb(r, g, b, a) => {
36                let components = [r, g, b]
37                    .into_iter()
38                    .map(|c| format!("{:02x}", c))
39                    .chain(a.map(|a| format!("{:02x}", a)))
40                    .collect::<String>();
41                write!(f, "#{}", components)
42            }
43        }
44    }
45}
46
47impl<T: Into<String>> From<T> for Color {
48    fn from(value: T) -> Self {
49        Color::Named(value.into())
50    }
51}