Skip to main content

rust_css_parser/syntax/color/
srgb.rs

1//! Port of `src/syntax/color/srgb.ts` (from <https://www.w3.org/TR/css-color-4/#color-conversion-code>).
2
3use super::color::{color2srgbvalues, get_angle, get_number};
4use super::hex::expand_hex_value;
5use super::hwb::hwbvalues;
6use super::lab::{get_lab_components, lab_to_srgb, lchvalues2labvalues};
7use super::lch::get_lch_components;
8use super::oklab::{get_oklab_components, oklab_to_srgb};
9use super::oklch::get_oklch_components;
10use super::utils::components::get_color_components;
11use super::utils::values::{at, js_sign_or_one, opt};
12use super::xyz::xyz_to_lin_srgb;
13use crate::ast::arena::AstArena;
14use crate::ast::types::{ColorType, EnumToken};
15use crate::syntax::constants::color_name_to_hex;
16use crate::syntax::syntax::parse_color;
17use crate::utils::number::{js_parse_number, to_fixed};
18
19/// srgb values of a color
20pub fn srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
21    let mut token = token;
22    if arena.data_types.get(token) == EnumToken::IdenTokenType {
23        token = parse_color(arena, token);
24    }
25    match arena.color_type.get(token) {
26        ColorType::LIT | ColorType::HEX => Some(hex2srgbvalues(arena, token)),
27        ColorType::RGB => rgb2srgb(arena, token),
28        ColorType::HSL => hsl2srgb(arena, token),
29        ColorType::HWB => hwb2srgbvalues(arena, token),
30        ColorType::LAB => lab2srgbvalues(arena, token),
31        ColorType::LCH => lch2srgbvalues(arena, token),
32        ColorType::OKLAB => oklab2srgbvalues(arena, token),
33        ColorType::OKLCH => oklch2srgbvalues(arena, token),
34        ColorType::COLOR => color2srgbvalues(arena, token),
35        _ => None,
36    }
37}
38
39fn is_none(arena: &AstArena, t: u32) -> bool {
40    arena.data_types.get(t) == EnumToken::IdenTokenType && &*arena.resolve_string(arena.string_value.get(t)) == "none"
41}
42
43pub fn rgb2srgb(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
44    Some(
45        get_color_components(arena, token)?
46            .iter()
47            .enumerate()
48            .map(|(index, &t)| {
49                if index == 3 {
50                    if is_none(arena, t) {
51                        1.0
52                    } else {
53                        get_number(arena, t)
54                    }
55                } else {
56                    (if arena.data_types.get(t) == EnumToken::PercentageTokenType { 255.0 } else { 1.0 }) * get_number(arena, t) / 255.0
57                }
58            })
59            .collect(),
60    )
61}
62
63pub fn rgb2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
64    Some(
65        get_color_components(arena, token)?
66            .iter()
67            .enumerate()
68            .map(|(index, &t)| if index == 3 { get_number(arena, t) } else { get_number(arena, t) / 255.0 })
69            .collect(),
70    )
71}
72
73/// `COLORS_NAMES[name]` of a named color or the value of a hex color, expanded
74pub(super) fn hex_value(arena: &AstArena, token: u32) -> String {
75    let val = arena.resolve_string(arena.string_value.get(token));
76    if arena.color_type.get(token) == ColorType::LIT {
77        // typescript: `undefined` when the name is not a color name
78        expand_hex_value(color_name_to_hex(&val.to_lowercase()).unwrap_or(""))
79    } else {
80        expand_hex_value(&val)
81    }
82}
83
84/// `parseInt(value.slice(i, i + 2), 16)`
85pub(super) fn parse_hex_pair(value: &str, i: usize) -> f64 {
86    let s: String = value.chars().skip(i).take(2).collect();
87    let digits: String = s.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
88    if digits.is_empty() {
89        f64::NAN
90    } else {
91        u32::from_str_radix(&digits, 16).unwrap() as f64
92    }
93}
94
95pub fn hex2srgbvalues(arena: &AstArena, token: u32) -> Vec<f64> {
96    let value = hex_value(arena, token);
97    let len = value.chars().count();
98    let mut rgb = Vec::new();
99    let mut i = 1;
100    while i < len {
101        rgb.push(parse_hex_pair(&value, i) / 255.0);
102        i += 2;
103    }
104    if rgb.len() == 4 {
105        rgb[3] = js_parse_number(&to_fixed(rgb[3], 2));
106    }
107    rgb
108}
109
110/// xyz d65 input
111pub fn xyz2srgb(x: f64, y: f64, z: f64, alpha: Option<f64>) -> Vec<f64> {
112    let values = xyz_to_lin_srgb(x, y, z, None);
113    lsrgb2srgbvalues(at(&values, 0), at(&values, 1), at(&values, 2), alpha)
114}
115
116pub fn hwb2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
117    let Some(v) = hwbvalues(arena, token) else {
118        return Some(Vec::new());
119    };
120    let mut rgb = hwb2srgb(v.h, v.w, v.b, None);
121    if let Some(a) = v.a {
122        if a != 1.0 {
123            rgb.push(a);
124        }
125    }
126    Some(rgb)
127}
128
129/// convert hwb to sRGB
130pub fn hwb2srgb(h: f64, w: f64, b: f64, alpha: Option<f64>) -> Vec<f64> {
131    use crate::utils::number::js_round;
132    let w_norm = w / 100.0;
133    let b_norm = b / 100.0;
134    if w_norm + b_norm >= 1.0 {
135        let gray = w_norm / (w_norm + b_norm);
136        let g = js_round(gray * 10000.0) / 10000.0;
137        return vec![g, g, g];
138    }
139    let h_prime = (h % 360.0) / 60.0;
140    let x = 1.0 - ((h_prime % 2.0) - 1.0).abs();
141    let (r_chroma, g_chroma, b_chroma) = if (0.0..1.0).contains(&h_prime) {
142        (1.0, x, 0.0)
143    } else if (1.0..2.0).contains(&h_prime) {
144        (x, 1.0, 0.0)
145    } else if (2.0..3.0).contains(&h_prime) {
146        (0.0, 1.0, x)
147    } else if (3.0..4.0).contains(&h_prime) {
148        (0.0, x, 1.0)
149    } else if (4.0..5.0).contains(&h_prime) {
150        (x, 0.0, 1.0)
151    } else if (5.0..=6.0).contains(&h_prime) {
152        (1.0, 0.0, x)
153    } else {
154        (0.0, 0.0, 0.0)
155    };
156    let factor = 1.0 - w_norm - b_norm;
157    let mut srgb = vec![r_chroma * factor + w_norm, g_chroma * factor + w_norm, b_chroma * factor + w_norm];
158    if let Some(alpha) = alpha {
159        if alpha != 1.0 {
160            srgb.push(alpha);
161        }
162    }
163    srgb
164}
165
166pub fn hsl2srgb(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
167    let v = hslvalues(arena, token)?;
168    // hue in degrees
169    Some(hslvalues2srgbvalues(v.h, v.s, v.l, v.a))
170}
171
172pub fn cmyk2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
173    let components = get_color_components(arena, token)?;
174    let n = |i: usize| components.get(i).map_or(f64::NAN, |&t| get_number(arena, t));
175    let (c, m, y, k) = (n(0), n(1), n(2), n(3));
176    let mul = 1.0 - k;
177    // `Math.min(1, v)`
178    let min1 = |v: f64| if v.is_nan() { f64::NAN } else { v.min(1.0) };
179    let mut rgb = vec![1.0 - min1(c * mul + k), 1.0 - min1(m * mul + k), 1.0 - min1(y * mul + k)];
180    if components.len() == 5 {
181        rgb.push(get_number(arena, components[4]));
182    }
183    Some(rgb)
184}
185
186pub fn oklab2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
187    let values = get_oklab_components(arena, token).unwrap_or_default();
188    if values.len() < 3 {
189        return None;
190    }
191    let mut rgb = oklab_to_srgb(values[0], values[1], values[2]);
192    if let Some(alpha) = opt(&values, 3) {
193        if alpha != 1.0 {
194            rgb.push(alpha);
195        }
196    }
197    Some(rgb)
198}
199
200pub fn oklch2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
201    let values = get_oklch_components(arena, token).unwrap_or_default();
202    if values.len() < 3 {
203        return None;
204    }
205    let lab = lchvalues2labvalues(values[0], values[1], values[2], None);
206    let mut rgb = oklab_to_srgb(lab[0], lab[1], lab[2]);
207    // `alpha !== 1`: the alpha is always defined (`getOKLCHComponents()`)
208    let alpha = opt(&values, 3);
209    if alpha != Some(1.0) {
210        rgb.push(alpha.unwrap_or(f64::NAN));
211    }
212    Some(rgb)
213}
214
215/// h, s, l, a values of a hsl color
216pub struct HslValues {
217    pub h: f64,
218    pub s: f64,
219    pub l: f64,
220    pub a: Option<f64>,
221}
222
223pub fn hslvalues(arena: &AstArena, token: u32) -> Option<HslValues> {
224    let components = get_color_components(arena, token)?;
225    let n = |i: usize| components.get(i).map_or(f64::NAN, |&t| get_number(arena, t));
226    let typ = |i: usize| components.get(i).map_or(0, |&t| arena.data_types.get(t));
227    let h = components.first().map_or(f64::NAN, |&t| get_angle(arena, t)) * 360.0;
228    let mut s = n(1);
229    let mut l = n(2);
230    if typ(1) == EnumToken::PercentageTokenType {
231        s *= 100.0;
232    }
233    if typ(2) == EnumToken::PercentageTokenType {
234        l *= 100.0;
235    }
236    let a = if components.len() == 4 { Some(n(3)) } else { None };
237    Some(HslValues { h, s, l, a })
238}
239
240pub fn hslvalues2srgbvalues(h: f64, s: f64, l: f64, a: Option<f64>) -> Vec<f64> {
241    let s_norm = s / 100.0;
242    let l_norm = l / 100.0;
243    let chroma = (1.0 - (2.0 * l_norm - 1.0).abs()) * s_norm;
244    let h_prime = h / 60.0;
245    let x = chroma * (1.0 - ((h_prime % 2.0) - 1.0).abs());
246    let (r, g, b) = if (0.0..1.0).contains(&h_prime) {
247        (chroma, x, 0.0)
248    } else if (1.0..2.0).contains(&h_prime) {
249        (x, chroma, 0.0)
250    } else if (2.0..3.0).contains(&h_prime) {
251        (0.0, chroma, x)
252    } else if (3.0..4.0).contains(&h_prime) {
253        (0.0, x, chroma)
254    } else if (4.0..5.0).contains(&h_prime) {
255        (x, 0.0, chroma)
256    } else if (5.0..=6.0).contains(&h_prime) {
257        (chroma, 0.0, x)
258    } else {
259        (0.0, 0.0, 0.0)
260    };
261    let m = l_norm - chroma / 2.0;
262    let mut values = vec![r + m, g + m, b + m];
263    if let Some(a) = a {
264        values.push(a);
265    }
266    // exact float decimals instead of multiplying by 255
267    values
268}
269
270pub fn lab2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
271    let values = get_lab_components(arena, token).unwrap_or_default();
272    if values.len() < 3 {
273        return None;
274    }
275    let mut rgb = lab_to_srgb(values[0], values[1], values[2]);
276    if let Some(alpha) = opt(&values, 3) {
277        if alpha < 1.0 {
278            rgb.push(alpha);
279        }
280    }
281    Some(rgb)
282}
283
284pub fn lch2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
285    let components = get_lch_components(arena, token)?;
286    let values = lchvalues2labvalues(at(&components, 0), at(&components, 1), at(&components, 2), opt(&components, 3));
287    // https://www.w3.org/TR/css-color-4/#lab-to-lch
288    let mut rgb = lab_to_srgb(values[0], values[1], values[2]);
289    let alpha = opt(&values, 3);
290    if alpha != Some(1.0) {
291        rgb.push(alpha.unwrap_or(f64::NAN));
292    }
293    Some(rgb)
294}
295
296/// sRGB -> lRGB
297pub fn srgb2lsrgbvalues(r: f64, g: f64, b: f64, a: Option<f64>) -> Vec<f64> {
298    let mut rgb: Vec<f64> = [r, g, b]
299        .iter()
300        .map(|&val| {
301            let abs = val.abs();
302            if abs <= 0.04045 {
303                return val / 12.92;
304            }
305            js_sign_or_one(val) * ((abs + 0.055) / 1.055).powf(2.4)
306        })
307        .collect();
308    if let Some(a) = a {
309        if a != 1.0 {
310            rgb.push(a);
311        }
312    }
313    rgb
314}
315
316pub fn lsrgb2srgbvalues(r: f64, g: f64, b: f64, alpha: Option<f64>) -> Vec<f64> {
317    let mut rgb: Vec<f64> = [r, g, b]
318        .iter()
319        .map(|&val| {
320            let abs = val.abs();
321            if abs > 0.0031308 {
322                return js_sign_or_one(val) * (1.055 * abs.powf(1.0 / 2.4) - 0.055);
323            }
324            12.92 * val
325        })
326        .collect();
327    if let Some(alpha) = alpha {
328        if alpha != 1.0 {
329            rgb.push(alpha);
330        }
331    }
332    rgb
333}