Skip to main content

rust_css_parser/syntax/color/
hwb.rs

1//! Port of `src/syntax/color/hwb.ts`.
2
3use super::color::{color2srgbvalues, get_angle, get_number};
4use super::srgb::{cmyk2srgbvalues, hslvalues, lab2srgbvalues, lch2srgbvalues, oklab2srgbvalues, oklch2srgbvalues};
5use super::tokens::{number, percentage, slash};
6use super::utils::components::get_color_components;
7use super::utils::values::{at, js_max, js_min, opt};
8use crate::ast::arena::AstArena;
9use crate::ast::types::{ColorType, EnumToken};
10
11macro_rules! to_token {
12    ($name:ident, $values:ident) => {
13        pub fn $name(arena: &AstArena, token: u32) -> Option<u32> {
14            let values = $values(arena, token)?;
15            Some(hwb_token(arena, &values))
16        }
17    };
18}
19
20to_token!(rgb2hwb_token, rgb2hwbvalues);
21to_token!(hsl2hwb_token, hsl2hwbvalues);
22to_token!(cmyk2hwb_token, cmyk2hwbvalues);
23to_token!(oklab2hwb_token, oklab2hwbvalues);
24to_token!(oklch2hwb_token, oklch2hwbvalues);
25to_token!(lab2hwb_token, lab2hwbvalues);
26to_token!(lch2hwb_token, lch2hwbvalues);
27to_token!(color2hwb_token, color2hwbvalues);
28
29pub fn hwb_token(arena: &AstArena, values: &[f64]) -> u32 {
30    let mut chi = vec![number(arena, at(values, 0)), percentage(arena, at(values, 1)), percentage(arena, at(values, 2))];
31    if values.len() == 4 {
32        chi.push(slash(arena));
33        chi.push(percentage(arena, values[3] * 100.0));
34    }
35    arena.create_color("hwb", ColorType::HWB, Some(&chi))
36}
37
38fn to_hwb(values: &[f64]) -> Vec<f64> {
39    srgb2hwb(at(values, 0), at(values, 1), at(values, 2), opt(values, 3))
40}
41
42/// `None` when the components cannot be computed: `var()`, ...
43pub fn rgb2hwbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
44    let values: Vec<f64> = get_color_components(arena, token)?
45        .iter()
46        .enumerate()
47        .map(|(index, &t)| {
48            if index == 3 {
49                get_number(arena, t)
50            } else {
51                // the components are from 0 to 255: 100% is 255
52                (if arena.data_types.get(t) == EnumToken::PercentageTokenType { 255.0 } else { 1.0 }) * get_number(arena, t)
53                    / 255.0
54            }
55        })
56        .collect();
57    Some(to_hwb(&values))
58}
59
60pub fn cmyk2hwbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
61    Some(to_hwb(&cmyk2srgbvalues(arena, token)?))
62}
63
64pub fn hsl2hwbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
65    let v = hslvalues(arena, token)?;
66    Some(hslvalues2hwbvalues(v.h, v.s, v.l, v.a))
67}
68
69pub fn lab2hwbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
70    Some(to_hwb(&lab2srgbvalues(arena, token)?))
71}
72
73pub fn lch2hwbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
74    Some(to_hwb(&lch2srgbvalues(arena, token)?))
75}
76
77pub fn oklab2hwbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
78    Some(to_hwb(&oklab2srgbvalues(arena, token)?))
79}
80
81pub fn oklch2hwbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
82    Some(to_hwb(&oklch2srgbvalues(arena, token)?))
83}
84
85pub fn color2hwbvalues(arena: &AstArena, token: u32) -> Option<Vec<f64>> {
86    Some(to_hwb(&color2srgbvalues(arena, token)?))
87}
88
89/// h, w, b, a values of a hwb color
90pub struct HwbValues {
91    pub h: f64,
92    pub w: f64,
93    pub b: f64,
94    pub a: Option<f64>,
95}
96
97pub fn hwbvalues(arena: &AstArena, token: u32) -> Option<HwbValues> {
98    let components = get_color_components(arena, token)?;
99    let n = |i: usize| components.get(i).map_or(f64::NAN, |&t| get_number(arena, t));
100    let h = components.first().map_or(f64::NAN, |&t| get_angle(arena, t)) * 360.0;
101    let w = n(1) * 100.0;
102    let b = n(2) * 100.0;
103    let a = if components.len() == 4 { Some(n(3)) } else { None };
104    Some(HwbValues { h, w, b, a })
105}
106
107/// `Math.min(1, Math.max(0, v))`
108fn clamp01(v: f64) -> f64 {
109    js_min(&[1.0, js_max(&[0.0, v])])
110}
111
112pub fn srgb2hwb(r: f64, g: f64, b: f64, a: Option<f64>) -> Vec<f64> {
113    let r_clamp = clamp01(r);
114    let g_clamp = clamp01(g);
115    let b_clamp = clamp01(b);
116    let c_max = js_max(&[r_clamp, g_clamp, b_clamp]);
117    let c_min = js_min(&[r_clamp, g_clamp, b_clamp]);
118    let delta = c_max - c_min;
119    let w = c_min;
120    let bl = 1.0 - c_max;
121    let mut h = 0.0;
122    if delta != 0.0 {
123        if c_max == r_clamp {
124            h = 60.0 * (((g_clamp - b_clamp) / delta) % 6.0);
125        } else if c_max == g_clamp {
126            h = 60.0 * ((b_clamp - r_clamp) / delta + 2.0);
127        } else if c_max == b_clamp {
128            h = 60.0 * ((r_clamp - g_clamp) / delta + 4.0);
129        }
130        if h < 0.0 {
131            h += 360.0;
132        }
133    }
134    let mut result = vec![h, w * 100.0, bl * 100.0];
135    if let Some(a) = a {
136        result.push(a);
137    }
138    result
139}
140
141pub fn hslvalues2hwbvalues(h: f64, s: f64, l: f64, a: Option<f64>) -> Vec<f64> {
142    let s_norm = s / 100.0;
143    let l_norm = l / 100.0;
144    let hue = ((h % 360.0) + 360.0) % 360.0;
145    let v = l_norm + s_norm * js_min(&[l_norm, 1.0 - l_norm]);
146    let chroma = 2.0 * (v - l_norm);
147    let w = v - chroma;
148    let b = 1.0 - v;
149    let mut hwb = vec![hue, w * 100.0, b * 100.0];
150    if let Some(a) = a.filter(|&a| a != 1.0) {
151        hwb.push(a);
152    }
153    hwb
154}