Skip to main content

eternal_styler/
values.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Value types shared between specified and computed styles.
6
7use std::sync::Arc;
8
9/// A colour as gamma-encoded sRGB with straight (not premultiplied) alpha,
10/// each component in `0.0..=1.0`.
11///
12/// Every colour syntax the parser accepts ends up here, so a renderer only
13/// ever deals with one representation.
14#[derive(Clone, Copy, Debug, PartialEq, Default)]
15pub struct Color {
16    pub r: f32,
17    pub g: f32,
18    pub b: f32,
19    pub a: f32,
20}
21
22impl Color {
23    pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0);
24    pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0);
25    pub const TRANSPARENT: Color = Color::rgba(0.0, 0.0, 0.0, 0.0);
26
27    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
28        Self { r, g, b, a }
29    }
30
31    pub const fn rgb(r: f32, g: f32, b: f32) -> Self {
32        Self::rgba(r, g, b, 1.0)
33    }
34
35    /// From 8-bit components, the way hex colours are written.
36    pub fn from_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
37        Self::rgba(
38            f32::from(r) / 255.0,
39            f32::from(g) / 255.0,
40            f32::from(b) / 255.0,
41            f32::from(a) / 255.0,
42        )
43    }
44
45    /// From a packed `0xRRGGBBAA` value.
46    pub fn from_packed_rgba(rgba: u32) -> Self {
47        Self::from_rgba8(
48            (rgba >> 24) as u8,
49            (rgba >> 16) as u8,
50            (rgba >> 8) as u8,
51            rgba as u8,
52        )
53    }
54
55    /// The components as bytes, `[r, g, b, a]`, rounded to nearest.
56    pub fn to_rgba8(self) -> [u8; 4] {
57        let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8;
58        [byte(self.r), byte(self.g), byte(self.b), byte(self.a)]
59    }
60
61    pub fn with_alpha(self, a: f32) -> Self {
62        Self { a, ..self }
63    }
64
65    /// From linear-light sRGB components, as `color(srgb-linear ...)` gives.
66    pub fn from_linear_srgb(r: f32, g: f32, b: f32, a: f32) -> Self {
67        Self::rgba(gamma_encode(r), gamma_encode(g), gamma_encode(b), a).clamped()
68    }
69
70    /// From HSL. Hue in degrees; saturation and lightness in `0.0..=1.0`.
71    pub fn from_hsl(hue: f32, saturation: f32, lightness: f32, a: f32) -> Self {
72        let (r, g, b) = cssparser_color::hsl_to_rgb(
73            normalize_hue(hue) / 360.0,
74            saturation.clamp(0.0, 1.0),
75            lightness.clamp(0.0, 1.0),
76        );
77        Self::rgba(r, g, b, a)
78    }
79
80    /// From HWB. Hue in degrees; whiteness and blackness in `0.0..=1.0`.
81    pub fn from_hwb(hue: f32, whiteness: f32, blackness: f32, a: f32) -> Self {
82        let (r, g, b) = cssparser_color::hwb_to_rgb(
83            normalize_hue(hue) / 360.0,
84            whiteness.clamp(0.0, 1.0),
85            blackness.clamp(0.0, 1.0),
86        );
87        Self::rgba(r, g, b, a)
88    }
89
90    /// From Oklab, with lightness in `0.0..=1.0`. Colours outside the sRGB
91    /// gamut are clipped component-wise.
92    pub fn from_oklab(lightness: f32, a: f32, b: f32, alpha: f32) -> Self {
93        let l_ = lightness + 0.396_337_78 * a + 0.215_803_76 * b;
94        let m_ = lightness - 0.105_561_346 * a - 0.063_854_17 * b;
95        let s_ = lightness - 0.089_484_18 * a - 1.291_485_5 * b;
96        let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
97        Self::from_linear_srgb(
98            4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
99            -1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s,
100            -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
101            alpha,
102        )
103    }
104
105    /// From Oklch, with lightness in `0.0..=1.0` and hue in degrees.
106    pub fn from_oklch(lightness: f32, chroma: f32, hue: f32, alpha: f32) -> Self {
107        let (a, b) = polar_to_rect(chroma, hue);
108        Self::from_oklab(lightness, a, b, alpha)
109    }
110
111    /// From CIELAB (D50), with lightness in `0.0..=100.0`. Colours outside
112    /// the sRGB gamut are clipped component-wise.
113    pub fn from_lab(lightness: f32, a: f32, b: f32, alpha: f32) -> Self {
114        // Lab to XYZ, relative to the D50 white point.
115        const EPSILON: f32 = 216.0 / 24389.0;
116        const KAPPA: f32 = 24389.0 / 27.0;
117        const WHITE: [f32; 3] = [0.964_22, 1.0, 0.825_21];
118        let fy = (lightness + 16.0) / 116.0;
119        let fx = a / 500.0 + fy;
120        let fz = fy - b / 200.0;
121        let inverse = |f: f32| {
122            let cubed = f * f * f;
123            if cubed > EPSILON {
124                cubed
125            } else {
126                (116.0 * f - 16.0) / KAPPA
127            }
128        };
129        let x = inverse(fx) * WHITE[0];
130        let y = if lightness > KAPPA * EPSILON {
131            fy * fy * fy
132        } else {
133            lightness / KAPPA
134        } * WHITE[1];
135        let z = inverse(fz) * WHITE[2];
136
137        // Bradford chromatic adaptation from D50 to D65.
138        let x65 = 0.955_473_4 * x - 0.023_098_538 * y + 0.063_259_31 * z;
139        let y65 = -0.028_369_706 * x + 1.009_995_5 * y + 0.021_041_399 * z;
140        let z65 = 0.012_314_002 * x - 0.020_507_697 * y + 1.330_365_9 * z;
141
142        Self::from_xyz_d65(x65, y65, z65, alpha)
143    }
144
145    /// From CIELCH (D50), with lightness in `0.0..=100.0` and hue in degrees.
146    pub fn from_lch(lightness: f32, chroma: f32, hue: f32, alpha: f32) -> Self {
147        let (a, b) = polar_to_rect(chroma, hue);
148        Self::from_lab(lightness, a, b, alpha)
149    }
150
151    /// From linear Display P3 components, as `color(display-p3 ...)` gives.
152    /// Colours outside the sRGB gamut are clipped component-wise.
153    pub fn from_display_p3(r: f32, g: f32, b: f32, alpha: f32) -> Self {
154        let (r, g, b) = (gamma_decode(r), gamma_decode(g), gamma_decode(b));
155        let x = 0.486_570_95 * r + 0.265_667_7 * g + 0.198_217_29 * b;
156        let y = 0.228_974_57 * r + 0.691_738_55 * g + 0.079_286_91 * b;
157        let z = 0.045_113_38 * g + 1.043_944_4 * b;
158        Self::from_xyz_d65(x, y, z, alpha)
159    }
160
161    fn from_xyz_d65(x: f32, y: f32, z: f32, alpha: f32) -> Self {
162        Self::from_linear_srgb(
163            3.240_97 * x - 1.537_383_2 * y - 0.498_610_76 * z,
164            -0.969_243_65 * x + 1.875_967_5 * y + 0.041_555_06 * z,
165            0.055_630_08 * x - 0.203_976_96 * y + 1.056_971_5 * z,
166            alpha,
167        )
168    }
169
170    fn clamped(self) -> Self {
171        Self::rgba(
172            self.r.clamp(0.0, 1.0),
173            self.g.clamp(0.0, 1.0),
174            self.b.clamp(0.0, 1.0),
175            self.a.clamp(0.0, 1.0),
176        )
177    }
178}
179
180fn gamma_encode(linear: f32) -> f32 {
181    if linear <= 0.003_130_8 {
182        12.92 * linear
183    } else {
184        1.055 * linear.powf(1.0 / 2.4) - 0.055
185    }
186}
187
188fn gamma_decode(encoded: f32) -> f32 {
189    if encoded <= 0.040_45 {
190        encoded / 12.92
191    } else {
192        ((encoded + 0.055) / 1.055).powf(2.4)
193    }
194}
195
196fn normalize_hue(hue: f32) -> f32 {
197    hue - 360.0 * (hue / 360.0).floor()
198}
199
200fn polar_to_rect(chroma: f32, hue_degrees: f32) -> (f32, f32) {
201    let radians = hue_degrees.to_radians();
202    (chroma * radians.cos(), chroma * radians.sin())
203}
204
205/// How a border is drawn.
206#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
207pub enum BorderStyle {
208    /// No border. The computed border width is zero.
209    #[default]
210    None,
211    /// Like `None` for drawing and layout, kept distinct because CSS does.
212    Hidden,
213    Solid,
214    Dashed,
215    Dotted,
216    Double,
217}
218
219impl BorderStyle {
220    /// Whether the border takes up space and is drawn.
221    pub fn is_visible(self) -> bool {
222        !matches!(self, Self::None | Self::Hidden)
223    }
224}
225
226#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
227pub enum FontStyle {
228    #[default]
229    Normal,
230    Italic,
231    Oblique,
232}
233
234#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
235pub enum TextAlign {
236    /// The start of the line in the writing direction.
237    #[default]
238    Start,
239    End,
240    Left,
241    Right,
242    Center,
243    Justify,
244}
245
246/// A font weight from 1 to 1000, where 400 is normal and 700 is bold.
247#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
248pub struct FontWeight(f32);
249
250impl FontWeight {
251    pub const NORMAL: FontWeight = FontWeight(400.0);
252    pub const BOLD: FontWeight = FontWeight(700.0);
253
254    /// Clamped to `1.0..=1000.0`.
255    pub fn new(weight: f32) -> Self {
256        Self(weight.clamp(1.0, 1000.0))
257    }
258
259    pub fn value(self) -> f32 {
260        self.0
261    }
262
263    /// `bolder` relative to this weight, per the CSS Fonts table.
264    pub fn bolder(self) -> Self {
265        Self(if self.0 < 350.0 {
266            400.0
267        } else if self.0 < 550.0 {
268            700.0
269        } else if self.0 < 900.0 {
270            900.0
271        } else {
272            self.0
273        })
274    }
275
276    /// `lighter` relative to this weight, per the CSS Fonts table.
277    pub fn lighter(self) -> Self {
278        Self(if self.0 < 100.0 {
279            self.0
280        } else if self.0 < 550.0 {
281            100.0
282        } else if self.0 < 750.0 {
283            400.0
284        } else {
285            700.0
286        })
287    }
288}
289
290impl Default for FontWeight {
291    fn default() -> Self {
292        Self::NORMAL
293    }
294}
295
296/// A prioritised list of font family names.
297///
298/// Generic families (`sans-serif`, `serif`, `monospace`, `system-ui`, ...)
299/// are passed through as plain lower-case names; it is up to the toolkit to
300/// map them to real fonts.
301#[derive(Clone, Debug, PartialEq, Eq, Hash)]
302pub struct FontFamily(Arc<[String]>);
303
304impl FontFamily {
305    pub fn new<I, S>(names: I) -> Self
306    where
307        I: IntoIterator<Item = S>,
308        S: Into<String>,
309    {
310        Self(names.into_iter().map(Into::into).collect())
311    }
312
313    /// The names in order of preference.
314    pub fn names(&self) -> &[String] {
315        &self.0
316    }
317}
318
319impl Default for FontFamily {
320    fn default() -> Self {
321        Self::new(["sans-serif"])
322    }
323}
324
325/// One value per side of a box, in the CSS order.
326#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
327pub struct Sides<T> {
328    pub top: T,
329    pub right: T,
330    pub bottom: T,
331    pub left: T,
332}
333
334impl<T> Sides<T> {
335    pub const fn new(top: T, right: T, bottom: T, left: T) -> Self {
336        Self {
337            top,
338            right,
339            bottom,
340            left,
341        }
342    }
343
344    pub fn all(value: T) -> Self
345    where
346        T: Clone,
347    {
348        Self::new(value.clone(), value.clone(), value.clone(), value)
349    }
350}
351
352/// One value per corner of a box, in the CSS order.
353#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
354pub struct Corners<T> {
355    pub top_left: T,
356    pub top_right: T,
357    pub bottom_right: T,
358    pub bottom_left: T,
359}
360
361impl<T> Corners<T> {
362    pub const fn new(top_left: T, top_right: T, bottom_right: T, bottom_left: T) -> Self {
363        Self {
364            top_left,
365            top_right,
366            bottom_right,
367            bottom_left,
368        }
369    }
370
371    pub fn all(value: T) -> Self
372    where
373        T: Clone,
374    {
375        Self::new(value.clone(), value.clone(), value.clone(), value)
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    fn close(color: Color, expected: [u8; 4]) {
384        let got = color.to_rgba8();
385        for (g, e) in got.iter().zip(expected) {
386            assert!(
387                (i16::from(*g) - i16::from(e)).abs() <= 1,
388                "{got:?} vs {expected:?}"
389            );
390        }
391    }
392
393    #[test]
394    fn packed_and_bytes_round_trip() {
395        let color = Color::from_packed_rgba(0x1a2b3c80);
396        assert_eq!(color.to_rgba8(), [0x1a, 0x2b, 0x3c, 0x80]);
397    }
398
399    #[test]
400    fn hsl_and_hwb() {
401        close(Color::from_hsl(120.0, 1.0, 0.5, 1.0), [0, 255, 0, 255]);
402        close(Color::from_hsl(-240.0, 1.0, 0.5, 1.0), [0, 255, 0, 255]);
403        close(Color::from_hwb(0.0, 0.0, 0.0, 1.0), [255, 0, 0, 255]);
404        close(Color::from_hwb(0.0, 0.5, 0.5, 1.0), [128, 128, 128, 255]);
405    }
406
407    #[test]
408    fn oklab_and_oklch() {
409        close(Color::from_oklab(1.0, 0.0, 0.0, 1.0), [255, 255, 255, 255]);
410        close(Color::from_oklab(0.0, 0.0, 0.0, 1.0), [0, 0, 0, 255]);
411        close(
412            Color::from_oklab(0.627_955, 0.224_863, 0.125_846, 1.0),
413            [255, 0, 0, 255],
414        );
415        close(
416            Color::from_oklch(0.627_955, 0.257_683, 29.233_9, 1.0),
417            [255, 0, 0, 255],
418        );
419    }
420
421    #[test]
422    fn lab_and_lch() {
423        close(Color::from_lab(100.0, 0.0, 0.0, 1.0), [255, 255, 255, 255]);
424        close(Color::from_lab(0.0, 0.0, 0.0, 1.0), [0, 0, 0, 255]);
425        close(Color::from_lab(50.0, 0.0, 0.0, 1.0), [119, 119, 119, 255]);
426        close(Color::from_lab(54.29, 80.80, 69.89, 1.0), [255, 0, 0, 255]);
427        close(Color::from_lch(54.29, 106.84, 40.86, 1.0), [255, 0, 0, 255]);
428    }
429
430    #[test]
431    fn display_p3_and_linear() {
432        close(
433            Color::from_display_p3(1.0, 1.0, 1.0, 1.0),
434            [255, 255, 255, 255],
435        );
436        close(Color::from_display_p3(0.0, 0.0, 0.0, 1.0), [0, 0, 0, 255]);
437        close(
438            Color::from_linear_srgb(0.0, 0.214_04, 1.0, 0.5),
439            [0, 128, 255, 128],
440        );
441    }
442
443    #[test]
444    fn font_weight_relative_keywords() {
445        assert_eq!(FontWeight::NORMAL.bolder(), FontWeight::BOLD);
446        assert_eq!(FontWeight::BOLD.bolder(), FontWeight::new(900.0));
447        assert_eq!(FontWeight::new(900.0).bolder(), FontWeight::new(900.0));
448        assert_eq!(FontWeight::BOLD.lighter(), FontWeight::NORMAL);
449        assert_eq!(FontWeight::NORMAL.lighter(), FontWeight::new(100.0));
450        assert_eq!(FontWeight::new(50.0).lighter(), FontWeight::new(50.0));
451    }
452}