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    // the components cannot be computed: var(), ...
118    let v = hwbvalues(arena, token)?;
119    let mut rgb = hwb2srgb(v.h, v.w, v.b, None);
120    if let Some(a) = v.a {
121        if a != 1.0 {
122            rgb.push(a);
123        }
124    }
125    Some(rgb)
126}
127
128/// convert hwb to sRGB
129pub fn hwb2srgb(h: f64, w: f64, b: f64, alpha: Option<f64>) -> Vec<f64> {
130    use crate::utils::number::js_round;
131    let w_norm = w / 100.0;
132    let b_norm = b / 100.0;
133    if w_norm + b_norm >= 1.0 {
134        let gray = w_norm / (w_norm + b_norm);
135        let g = js_round(gray * 10000.0) / 10000.0;
136        return vec![g, g, g];
137    }
138    let h_prime = (h % 360.0) / 60.0;
139    let x = 1.0 - ((h_prime % 2.0) - 1.0).abs();
140    let (r_chroma, g_chroma, b_chroma) = if (0.0..1.0).contains(&h_prime) {
141        (1.0, x, 0.0)
142    } else if (1.0..2.0).contains(&h_prime) {
143        (x, 1.0, 0.0)
144    } else if (2.0..3.0).contains(&h_prime) {
145        (0.0, 1.0, x)
146    } else if (3.0..4.0).contains(&h_prime) {
147        (0.0, x, 1.0)
148    } else if (4.0..5.0).contains(&h_prime) {
149        (x, 0.0, 1.0)
150    } else if (5.0..=6.0).contains(&h_prime) {
151        (1.0, 0.0, x)
152    } else {
153        (0.0, 0.0, 0.0)
154    };
155    let factor = 1.0 - w_norm - b_norm;
156    let mut srgb = vec![r_chroma * factor + w_norm, g_chroma * factor + w_norm, b_chroma * factor + w_norm];
157    if let Some(alpha) = alpha {
158        if alpha != 1.0 {
159            srgb.push(alpha);
160        }
161    }
162    srgb
163}
164
165pub fn hsl2srgb(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
166    let v = hslvalues(arena, token)?;
167    // hue in degrees
168    Some(hslvalues2srgbvalues(v.h, v.s, v.l, v.a))
169}
170
171pub fn cmyk2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
172    let components = get_color_components(arena, token)?;
173    let n = |i: usize| components.get(i).map_or(f64::NAN, |&t| get_number(arena, t));
174    let (c, m, y, k) = (n(0), n(1), n(2), n(3));
175    let mul = 1.0 - k;
176    // `Math.min(1, v)`
177    let min1 = |v: f64| if v.is_nan() { f64::NAN } else { v.min(1.0) };
178    let mut rgb = vec![1.0 - min1(c * mul + k), 1.0 - min1(m * mul + k), 1.0 - min1(y * mul + k)];
179    if components.len() == 5 {
180        rgb.push(get_number(arena, components[4]));
181    }
182    Some(rgb)
183}
184
185pub fn oklab2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
186    let values = get_oklab_components(arena, token).unwrap_or_default();
187    if values.len() < 3 {
188        return None;
189    }
190    let mut rgb = oklab_to_srgb(values[0], values[1], values[2]);
191    if let Some(alpha) = opt(&values, 3) {
192        if alpha != 1.0 {
193            rgb.push(alpha);
194        }
195    }
196    Some(rgb)
197}
198
199pub fn oklch2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
200    let values = get_oklch_components(arena, token).unwrap_or_default();
201    if values.len() < 3 {
202        return None;
203    }
204    let lab = lchvalues2labvalues(values[0], values[1], values[2], None);
205    let mut rgb = oklab_to_srgb(lab[0], lab[1], lab[2]);
206    // `alpha !== 1`: the alpha is always defined (`getOKLCHComponents()`)
207    let alpha = opt(&values, 3);
208    if alpha != Some(1.0) {
209        rgb.push(alpha.unwrap_or(f64::NAN));
210    }
211    Some(rgb)
212}
213
214/// h, s, l, a values of a hsl color
215pub struct HslValues {
216    pub h: f64,
217    pub s: f64,
218    pub l: f64,
219    pub a: Option<f64>,
220}
221
222pub fn hslvalues(arena: &AstArena, token: u32) -> Option<HslValues> {
223    let components = get_color_components(arena, token)?;
224    let n = |i: usize| components.get(i).map_or(f64::NAN, |&t| get_number(arena, t));
225    let typ = |i: usize| components.get(i).map_or(0, |&t| arena.data_types.get(t));
226    let h = components.first().map_or(f64::NAN, |&t| get_angle(arena, t)) * 360.0;
227    let mut s = n(1);
228    let mut l = n(2);
229    if typ(1) == EnumToken::PercentageTokenType {
230        s *= 100.0;
231    }
232    if typ(2) == EnumToken::PercentageTokenType {
233        l *= 100.0;
234    }
235    let a = if components.len() == 4 { Some(n(3)) } else { None };
236    Some(HslValues { h, s, l, a })
237}
238
239pub fn hslvalues2srgbvalues(h: f64, s: f64, l: f64, a: Option<f64>) -> Vec<f64> {
240    let s_norm = s / 100.0;
241    let l_norm = l / 100.0;
242    let chroma = (1.0 - (2.0 * l_norm - 1.0).abs()) * s_norm;
243    let h_prime = h / 60.0;
244    let x = chroma * (1.0 - ((h_prime % 2.0) - 1.0).abs());
245    let (r, g, b) = if (0.0..1.0).contains(&h_prime) {
246        (chroma, x, 0.0)
247    } else if (1.0..2.0).contains(&h_prime) {
248        (x, chroma, 0.0)
249    } else if (2.0..3.0).contains(&h_prime) {
250        (0.0, chroma, x)
251    } else if (3.0..4.0).contains(&h_prime) {
252        (0.0, x, chroma)
253    } else if (4.0..5.0).contains(&h_prime) {
254        (x, 0.0, chroma)
255    } else if (5.0..=6.0).contains(&h_prime) {
256        (chroma, 0.0, x)
257    } else {
258        (0.0, 0.0, 0.0)
259    };
260    let m = l_norm - chroma / 2.0;
261    let mut values = vec![r + m, g + m, b + m];
262    if let Some(a) = a {
263        values.push(a);
264    }
265    // exact float decimals instead of multiplying by 255
266    values
267}
268
269pub fn lab2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
270    let values = get_lab_components(arena, token).unwrap_or_default();
271    if values.len() < 3 {
272        return None;
273    }
274    let mut rgb = lab_to_srgb(values[0], values[1], values[2]);
275    if let Some(alpha) = opt(&values, 3) {
276        if alpha < 1.0 {
277            rgb.push(alpha);
278        }
279    }
280    Some(rgb)
281}
282
283pub fn lch2srgbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
284    let components = get_lch_components(arena, token)?;
285    let values = lchvalues2labvalues(at(&components, 0), at(&components, 1), at(&components, 2), opt(&components, 3));
286    // https://www.w3.org/TR/css-color-4/#lab-to-lch
287    let mut rgb = lab_to_srgb(values[0], values[1], values[2]);
288    let alpha = opt(&values, 3);
289    if alpha != Some(1.0) {
290        rgb.push(alpha.unwrap_or(f64::NAN));
291    }
292    Some(rgb)
293}
294
295/// sRGB -> lRGB
296pub fn srgb2lsrgbvalues(r: f64, g: f64, b: f64, a: Option<f64>) -> Vec<f64> {
297    let mut rgb: Vec<f64> = [r, g, b]
298        .iter()
299        .map(|&val| {
300            let abs = val.abs();
301            if abs <= 0.04045 {
302                return val / 12.92;
303            }
304            js_sign_or_one(val) * ((abs + 0.055) / 1.055).powf(2.4)
305        })
306        .collect();
307    if let Some(a) = a {
308        if a != 1.0 {
309            rgb.push(a);
310        }
311    }
312    rgb
313}
314
315pub fn lsrgb2srgbvalues(r: f64, g: f64, b: f64, alpha: Option<f64>) -> Vec<f64> {
316    let mut rgb: Vec<f64> = [r, g, b]
317        .iter()
318        .map(|&val| {
319            let abs = val.abs();
320            if abs > 0.0031308 {
321                return js_sign_or_one(val) * (1.055 * abs.powf(1.0 / 2.4) - 0.055);
322            }
323            12.92 * val
324        })
325        .collect();
326    if let Some(alpha) = alpha {
327        if alpha != 1.0 {
328            rgb.push(alpha);
329        }
330    }
331    rgb
332}