/
legacy_rgb_and_hsl.rs
89 lines (82 loc) · 3.27 KB
/
legacy_rgb_and_hsl.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std::f64::consts::PI;
use swc_atoms::js_word;
use swc_css_ast::{AbsoluteColorBase, AlphaValue, Angle, ComponentValue, Hue, Number, Percentage};
use crate::compiler::{
utils::{clamp_unit_f32, round_alpha},
Compiler,
};
impl Compiler {
pub(crate) fn process_rgb_and_hsl(&mut self, n: &mut AbsoluteColorBase) {
if let AbsoluteColorBase::Function(function) = n {
let name = function.name.value.to_ascii_lowercase();
let is_rgb = matches!(name, js_word!("rgb") | js_word!("rgba"));
let is_hsl = matches!(name, js_word!("hsl") | js_word!("hsla"));
if is_rgb {
function.value = function
.value
.drain(..)
.into_iter()
.map(|n| match n {
ComponentValue::Percentage(box Percentage {
span,
value: Number { value, .. },
..
}) => ComponentValue::Number(Box::new(Number {
span,
value: clamp_unit_f32(value / 100.0) as f64,
raw: None,
})),
_ => n,
})
.collect();
} else if is_hsl {
function.value = function
.value
.drain(..)
.into_iter()
.map(|n| match n {
ComponentValue::Hue(box Hue::Angle(Angle {
span,
value: Number { value, .. },
unit,
..
})) => {
let value = match unit.value.to_ascii_lowercase() {
js_word!("deg") => value,
js_word!("grad") => value * 180.0 / 200.0,
js_word!("rad") => value * 180.0 / PI,
js_word!("turn") => value * 360.0,
_ => {
unreachable!();
}
};
ComponentValue::Number(Box::new(Number {
span,
value: value.round(),
raw: None,
}))
}
_ => n,
})
.collect();
}
if is_rgb || is_hsl {
if let Some(ComponentValue::AlphaValue(box alpha_value)) = function.value.last_mut()
{
if let AlphaValue::Percentage(Percentage {
span,
value: Number { value: a, .. },
..
}) = alpha_value
{
*alpha_value = AlphaValue::Number(Number {
span: *span,
value: round_alpha(*a / 100.0),
raw: None,
});
}
}
}
}
}
}