Skip to main content

rust_css_parser/syntax/color/
hex.rs

1//! Port of `src/syntax/color/hex.ts`.
2
3use crate::syntax::constants::{color_name_to_hex, hex_to_color_name};
4
5/// shortest representation of a hex color or a named color
6pub fn reduce_hex_value(value: &str) -> String {
7    let mut value = value.to_string();
8    if !value.starts_with('#') {
9        if let Some(hex) = color_name_to_hex(&value.to_lowercase()) {
10            value = hex.to_string();
11        }
12    }
13    let named_color = hex_to_color_name(&expand_hex_value(&value));
14    let c: Vec<char> = value.chars().collect();
15    if c.len() == 7 {
16        if c[1] == c[2] && c[3] == c[4] && c[5] == c[6] {
17            value = format!("#{}{}{}", c[1], c[3], c[5]);
18        }
19    } else if c.len() == 9 {
20        if c[1] == c[2] && c[3] == c[4] && c[5] == c[6] && c[7] == c[8] {
21            value = format!("#{}{}{}{}", c[1], c[3], c[5], if c[7] == 'f' { String::new() } else { c[7].to_string() });
22        }
23        if value.ends_with("ff") {
24            value.truncate(value.len() - 2);
25        }
26    }
27    match named_color {
28        Some(n) if n.len() <= value.len() => n.to_string(),
29        _ => value,
30    }
31}
32
33/// `#abc` -> `#aabbcc`, `#abcd` -> `#aabbccdd`
34pub fn expand_hex_value(value: &str) -> String {
35    let c: Vec<char> = value.chars().collect();
36    match c.len() {
37        4 => format!("#{0}{0}{1}{1}{2}{2}", c[1], c[2], c[3]),
38        5 => format!("#{0}{0}{1}{1}{2}{2}{3}{3}", c[1], c[2], c[3], c[4]),
39        _ => value.to_string(),
40    }
41}
42
43use super::color::{color2srgbvalues, get_number};
44use super::rgb::{cmyk2rgbvalues, hsl2rgbvalues, hwb2rgbvalues, srgb2rgb};
45use super::srgb::{lab2srgbvalues, lch2srgbvalues, oklab2srgbvalues, oklch2srgbvalues};
46use super::utils::components::get_color_components;
47use super::utils::values::hex2;
48use crate::ast::arena::AstArena;
49use crate::ast::types::{ColorType, EnumToken};
50use crate::utils::number::js_round;
51
52/// `acc + value.toString(16).padStart(2, "0")`
53fn to_hex_string(values: &[f64], prefix: &str) -> String {
54    values.iter().fold(prefix.to_string(), |acc, &v| acc + &hex2(v))
55}
56
57fn from_string(arena: &AstArena, value: Option<String>) -> Option<u32> {
58    Some(hex_token(arena, &value?))
59}
60
61pub fn rgb2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
62    from_string(arena, rgb2hexvalues(arena, token))
63}
64
65pub fn hsl2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
66    from_string(arena, hsl2hexvalues(arena, token))
67}
68
69pub fn cmyk2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
70    from_string(arena, cmyk2hexvalues(arena, token))
71}
72
73pub fn hwb2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
74    from_string(arena, hwb2hexvalues(arena, token))
75}
76
77pub fn color2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
78    let value = color2srgbvalues(arena, token)?;
79    let rgb: Vec<f64> = value.iter().map(|&curr| srgb2rgb(curr + f64::EPSILON)).collect();
80    Some(hex_token(arena, &to_hex_string(&rgb, "#")))
81}
82
83fn srgb_hex_token(arena: &AstArena, value: Option<Vec<f64>>) -> Option<u32> {
84    let rgb: Vec<f64> = value?.iter().map(|&curr| srgb2rgb(curr)).collect();
85    Some(hex_token(arena, &to_hex_string(&rgb, "#")))
86}
87
88pub fn oklab2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
89    srgb_hex_token(arena, oklab2srgbvalues(arena, token))
90}
91
92pub fn oklch2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
93    srgb_hex_token(arena, oklch2srgbvalues(arena, token))
94}
95
96pub fn lab2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
97    srgb_hex_token(arena, lab2srgbvalues(arena, token))
98}
99
100pub fn lch2hex_token(arena: &AstArena, token: u32) -> Option<u32> {
101    srgb_hex_token(arena, lch2srgbvalues(arena, token))
102}
103
104fn hex_token(arena: &AstArena, value: &str) -> u32 {
105    let value = reduce_hex_value(value);
106    let kin = if value.starts_with('#') { ColorType::HEX } else { ColorType::LIT };
107    arena.create_color(&value, kin, None)
108}
109
110pub fn rgb2hexvalues(arena: &AstArena, token: u32) -> Option<String> {
111    let components = get_color_components(arena, token)?;
112    if components.len() < 3 {
113        return None;
114    }
115    let mut value = String::from("#");
116    for &t in &components[..3] {
117        if arena.data_types.get(t) == EnumToken::Iden && &*arena.resolve_string(arena.string_value.get(t)) == "none" {
118            value.push_str("00");
119        } else {
120            let factor = if arena.data_types.get(t) == EnumToken::PercentageTokenType { 255.0 } else { 1.0 };
121            value.push_str(&hex2(js_round(get_number(arena, t) * factor)));
122        }
123    }
124    if components.len() == 4 {
125        let v = get_number(arena, components[3]);
126        if v < 1.0 {
127            value.push_str(&hex2(js_round(255.0 * v)));
128        }
129    }
130    Some(value)
131}
132
133fn rgb_values_hex(t: Option<Vec<f64>>, prefix: &str) -> Option<String> {
134    let mut t = t?;
135    if t.len() == 4 {
136        t[3] = srgb2rgb(t[3]);
137    }
138    Some(to_hex_string(&t, prefix))
139}
140
141pub fn hsl2hexvalues(arena: &AstArena, token: u32) -> Option<String> {
142    rgb_values_hex(hsl2rgbvalues(arena, token), "#")
143}
144
145pub fn hwb2hexvalues(arena: &AstArena, token: u32) -> Option<String> {
146    rgb_values_hex(hwb2rgbvalues(arena, token), "#")
147}
148
149pub fn cmyk2hexvalues(arena: &AstArena, token: u32) -> Option<String> {
150    rgb_values_hex(cmyk2rgbvalues(arena, token), "#")
151}