Skip to main content

parsec_css/values/
color.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! `<color>`, CSS Color Level 4: hex colors, the named and system colors,
5//! `currentcolor`, `transparent`, `rgb()`, `hsl()`, `hwb()`, `lab()`,
6//! `lch()`, `oklab()`, `oklch()` and `color()` in every predefined space,
7//! with `none` and math functions in any component; and from Level 5,
8//! `device-cmyk()` and `light-dark()`.
9//!
10//! Values are kept as written, so a color serializes the way §15 says:
11//! the legacy sRGB forms as `rgb(r, g, b)`, the others in their own
12//! function, with `none` and unresolved math kept.
13
14use std::fmt::{self, Write};
15
16use super::math::{Expect, Leaf, Math};
17use super::units::{Kind, write_number};
18use crate::parser::{ComponentValue, Function};
19use crate::tokenizer::Token;
20
21/// One channel: a number, `none`, or a math function that couldn't be
22/// worked out yet.
23#[derive(Clone, Debug, PartialEq)]
24pub enum Channel {
25    None,
26    Number(f64),
27    Math(Math),
28}
29
30impl Channel {
31    fn number(&self) -> Option<f64> {
32        match self {
33            Channel::Number(v) => Some(*v),
34            _ => None,
35        }
36    }
37}
38
39/// A `color()` space.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum Predefined {
42    Srgb,
43    SrgbLinear,
44    DisplayP3,
45    DisplayP3Linear,
46    A98Rgb,
47    ProphotoRgb,
48    Rec2020,
49    XyzD50,
50    XyzD65,
51}
52
53impl Predefined {
54    const ALL: [(Predefined, &'static str); 9] = [
55        (Predefined::Srgb, "srgb"),
56        (Predefined::SrgbLinear, "srgb-linear"),
57        (Predefined::DisplayP3, "display-p3"),
58        (Predefined::DisplayP3Linear, "display-p3-linear"),
59        (Predefined::A98Rgb, "a98-rgb"),
60        (Predefined::ProphotoRgb, "prophoto-rgb"),
61        (Predefined::Rec2020, "rec2020"),
62        (Predefined::XyzD50, "xyz-d50"),
63        (Predefined::XyzD65, "xyz-d65"),
64    ];
65
66    pub fn name(self) -> &'static str {
67        Predefined::ALL.iter().find(|(p, _)| *p == self).unwrap().1
68    }
69
70    fn parse(name: &str) -> Option<Predefined> {
71        if name.eq_ignore_ascii_case("xyz") {
72            return Some(Predefined::XyzD65);
73        }
74        Predefined::ALL
75            .iter()
76            .find(|(_, n)| n.eq_ignore_ascii_case(name))
77            .map(|(p, _)| *p)
78    }
79}
80
81/// How a color's channels are to be read.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum Model {
84    /// sRGB, 0 to 255: hex, named colors, `rgb()` and `rgba()`.
85    Rgb,
86    /// Hue in degrees, saturation and lightness in percent.
87    Hsl,
88    /// Hue, whiteness and blackness.
89    Hwb,
90    Lab,
91    Lch,
92    Oklab,
93    Oklch,
94    /// `color(space …)`.
95    Color(Predefined),
96    /// `device-cmyk()`, four channels from 0 to 1.
97    DeviceCmyk,
98}
99
100/// A color with channels: everything but the keywords that stand for
101/// one.
102#[derive(Clone, Debug, PartialEq)]
103pub struct Channels {
104    pub model: Model,
105    /// Three, or four for `device-cmyk()`.
106    pub channels: Vec<Channel>,
107    pub alpha: Channel,
108}
109
110/// A `<color>`.
111///
112/// ```
113/// use parsec_css::values::Color;
114///
115/// let v = parsec_css::parse_component_value("hsl(120 30% 50%)").unwrap();
116/// assert_eq!(Color::parse(&v).unwrap().to_string(), "rgb(89, 166, 89)");
117/// let v = parsec_css::parse_component_value("lab(50% 50% -20 / 25%)").unwrap();
118/// assert_eq!(Color::parse(&v).unwrap().to_string(), "lab(50 62.5 -20 / 0.25)");
119/// ```
120#[derive(Clone, Debug, PartialEq)]
121pub enum Color {
122    CurrentColor,
123    /// A named color or `transparent`, in lowercase, which a specified
124    /// value keeps as its name.
125    Named(&'static str),
126    /// A system color, in lowercase: `canvastext`.
127    System(&'static str),
128    Channels(Channels),
129    LightDark(Box<Color>, Box<Color>),
130    /// CSS Color 5's relative color syntax: `rgb(from red r g calc(b / 2))`.
131    Relative(Box<Relative>),
132    /// `contrast-color(<color>)`.
133    Contrast(Box<Color>),
134    /// `color-mix()` or `color-layers()`, as matched by their grammars
135    /// and written out, with what `color-mix()` mixes.
136    Mix(Box<Mix>),
137    /// A colour a computed value has worked out, written out.
138    Text(String),
139}
140
141/// A relative color: an origin color and channels that may name the
142/// origin's, kept as written until there's a value to work them out from.
143#[derive(Clone, Debug, PartialEq)]
144pub struct Relative {
145    /// `rgb`, `hsl`, `hwb`, `lab`, `lch`, `oklab`, `oklch` or `color`.
146    pub function: &'static str,
147    /// For `color()`, its space.
148    pub space: Option<Predefined>,
149    pub origin: Color,
150    pub channels: Vec<RelativeChannel>,
151    pub alpha: Option<RelativeChannel>,
152}
153
154/// A `color-mix()`'s space, hue method, and colours with their
155/// percentages.
156pub type MixParts = (
157    super::convert::Space,
158    &'static str,
159    Vec<(Color, Option<f64>)>,
160);
161
162/// `color-mix()` or `color-layers()`.
163#[derive(Clone, Debug, PartialEq)]
164pub struct Mix {
165    /// The function written out, as a specified value writes it.
166    pub text: String,
167    /// For `color-mix()`: the space, the hue method, and each colour with
168    /// its percentage if it has one.
169    pub parts: Option<MixParts>,
170}
171
172/// One channel of a relative color, as written.
173#[derive(Clone, Debug, PartialEq)]
174pub enum RelativeChannel {
175    Number(f64),
176    Percentage(f64),
177    Angle(f64, super::units::Unit),
178    /// One of the origin's channels: `r`, `h`, `alpha` and so on.
179    Keyword(&'static str),
180    None,
181    Math(Math),
182}
183
184include!("named_colors.rs");
185
186const SYSTEM: &[&str] = &[
187    "accentcolor",
188    "accentcolortext",
189    "activetext",
190    "buttonborder",
191    "buttonface",
192    "buttontext",
193    "canvas",
194    "canvastext",
195    "field",
196    "fieldtext",
197    "graytext",
198    "highlight",
199    "highlighttext",
200    "linktext",
201    "mark",
202    "marktext",
203    "selecteditem",
204    "selecteditemtext",
205    "visitedtext",
206    // Deprecated, still valid.
207    "activeborder",
208    "activecaption",
209    "appworkspace",
210    "background",
211    "buttonhighlight",
212    "buttonshadow",
213    "captiontext",
214    "inactiveborder",
215    "inactivecaption",
216    "inactivecaptiontext",
217    "infobackground",
218    "infotext",
219    "menu",
220    "menutext",
221    "scrollbar",
222    "threeddarkshadow",
223    "threedface",
224    "threedhighlight",
225    "threedlightshadow",
226    "threedshadow",
227    "window",
228    "windowframe",
229    "windowtext",
230];
231
232fn rgb(r: f64, g: f64, b: f64, a: f64) -> Color {
233    Color::Channels(Channels {
234        model: Model::Rgb,
235        channels: vec![Channel::Number(r), Channel::Number(g), Channel::Number(b)],
236        alpha: Channel::Number(a),
237    })
238}
239
240/// What a channel may be, and what 100% of it is.
241#[derive(Clone, Copy)]
242enum Slot {
243    /// A number or a percentage of this.
244    Scaled(f64),
245    Hue,
246}
247
248impl Color {
249    /// The colour's channels in its own space, worked out: relative
250    /// colours and mixes included. `None` for `currentcolor`, a system
251    /// colour, or math that needs an element.
252    pub fn absolute(&self) -> Option<super::convert::Absolute> {
253        super::convert::absolute(self)
254    }
255
256    /// The color with named colors made `rgb()`, as a computed value
257    /// has them; everything else as it is.
258    pub fn computed(&self) -> Color {
259        match self {
260            Color::Named("transparent") => rgb(0.0, 0.0, 0.0, 0.0),
261            Color::Named(name) => {
262                let i = NAMED.binary_search_by(|(n, _)| n.cmp(name)).unwrap();
263                let [r, g, b] = NAMED[i].1.map(f64::from);
264                rgb(r, g, b, 1.0)
265            }
266            Color::LightDark(a, b) => {
267                Color::LightDark(Box::new(a.computed()), Box::new(b.computed()))
268            }
269            c => c.clone(),
270        }
271    }
272
273    /// The color `value` is, or `None` if it isn't one.
274    pub fn parse(value: &ComponentValue<'_>) -> Option<Color> {
275        match value {
276            ComponentValue::Token(Token::Ident(word), _) => Color::keyword(word),
277            ComponentValue::Token(Token::Hash { value, .. }, _) => hex(value),
278            ComponentValue::Function(f)
279                if f.name.eq_ignore_ascii_case("color-mix")
280                    || f.name.eq_ignore_ascii_case("color-layers") =>
281            {
282                guarded(|| {
283                    let mut buf = [0; 32];
284                    let name = super::units::lowercase(&f.name, &mut buf)?;
285                    let c = super::value::match_function(name, std::slice::from_ref(value))?;
286                    let mut text = String::new();
287                    super::value::write_components(&mut text, &c).ok()?;
288                    let parts = super::convert::mix_parts(f);
289                    Some(Color::Mix(Box::new(Mix { text, parts })))
290                })
291            }
292            ComponentValue::Function(f) => function(f),
293            _ => None,
294        }
295    }
296
297    fn keyword(word: &str) -> Option<Color> {
298        let mut buf = [0; 32];
299        let lower = super::units::lowercase(word, &mut buf)?;
300        if lower == "currentcolor" {
301            return Some(Color::CurrentColor);
302        }
303        if lower == "transparent" {
304            return Some(Color::Named("transparent"));
305        }
306        if let Ok(i) = NAMED.binary_search_by(|(n, _)| (*n).cmp(lower)) {
307            return Some(Color::Named(NAMED[i].0));
308        }
309        SYSTEM
310            .iter()
311            .find(|s| **s == lower)
312            .map(|s| Color::System(s))
313    }
314}
315
316fn hex(digits: &str) -> Option<Color> {
317    if !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
318        return None;
319    }
320    let d: Vec<f64> = digits
321        .bytes()
322        .map(|b| f64::from((b as char).to_digit(16).unwrap()))
323        .collect();
324    let (r, g, b, a) = match d.len() {
325        3 => (d[0] * 17.0, d[1] * 17.0, d[2] * 17.0, 255.0),
326        4 => (d[0] * 17.0, d[1] * 17.0, d[2] * 17.0, d[3] * 17.0),
327        6 => (
328            d[0] * 16.0 + d[1],
329            d[2] * 16.0 + d[3],
330            d[4] * 16.0 + d[5],
331            255.0,
332        ),
333        8 => (
334            d[0] * 16.0 + d[1],
335            d[2] * 16.0 + d[3],
336            d[4] * 16.0 + d[5],
337            d[6] * 16.0 + d[7],
338        ),
339        _ => return None,
340    };
341    Some(rgb(r, g, b, a / 255.0))
342}
343
344/// The arguments of a color function: the channels, the alpha after a
345/// `/` or the fourth comma, and whether commas separated them.
346struct Args<'v, 'a> {
347    channels: Vec<&'v ComponentValue<'a>>,
348    alpha: Option<&'v ComponentValue<'a>>,
349    commas: bool,
350}
351
352fn split_args<'v, 'a>(values: &'v [ComponentValue<'a>], count: usize) -> Option<Args<'v, 'a>> {
353    let solid: Vec<&ComponentValue<'_>> = values.iter().filter(|v| !v.is_whitespace()).collect();
354    let is =
355        |v: &ComponentValue<'_>, t: &Token<'_>| matches!(v, ComponentValue::Token(x, _) if x == t);
356    let commas = solid.iter().any(|v| is(v, &Token::Comma));
357    if commas {
358        // a, b, c[, d]: every other value a comma.
359        let mut items = Vec::new();
360        for (i, v) in solid.iter().enumerate() {
361            if i % 2 == 1 {
362                if !is(v, &Token::Comma) {
363                    return None;
364                }
365            } else {
366                items.push(*v);
367            }
368        }
369        if solid.len().is_multiple_of(2) {
370            return None;
371        }
372        let alpha = if items.len() == count + 1 {
373            items.pop()
374        } else {
375            None
376        };
377        return Some(Args {
378            channels: items,
379            alpha,
380            commas,
381        });
382    }
383    let slash = solid.iter().position(|v| is(v, &Token::Delim('/')));
384    let (channels, alpha) = match slash {
385        Some(i) => {
386            if solid.len() != i + 2 {
387                return None;
388            }
389            (solid[..i].to_vec(), Some(solid[i + 1]))
390        }
391        None => (solid, None),
392    };
393    Some(Args {
394        channels,
395        alpha,
396        commas,
397    })
398}
399
400/// A channel's value, read for `slot`: percentages scaled, angles in
401/// degrees, `none` only outside the legacy comma syntax; and how it was
402/// written.
403fn channel(v: &ComponentValue<'_>, slot: Slot, legacy: bool) -> Option<(Channel, Written)> {
404    let scale = match slot {
405        Slot::Scaled(s) => s,
406        Slot::Hue => 1.0,
407    };
408    Some(match v {
409        ComponentValue::Token(Token::Number(n), _) => (Channel::Number(n.value), Written::Number),
410        ComponentValue::Token(Token::Percentage(n), _) if matches!(slot, Slot::Scaled(_)) => {
411            (Channel::Number(n.value / 100.0 * scale), Written::Percent)
412        }
413        ComponentValue::Token(Token::Dimension { number, unit }, _)
414            if matches!(slot, Slot::Hue) =>
415        {
416            let u = super::units::Unit::parse(unit)?;
417            if u.kind() != Kind::Angle {
418                return None;
419            }
420            (
421                Channel::Number(number.value * u.to_canonical()?),
422                Written::Number,
423            )
424        }
425        ComponentValue::Token(Token::Ident(w), _) if !legacy && w.eq_ignore_ascii_case("none") => {
426            (Channel::None, Written::None)
427        }
428        ComponentValue::Function(f) if Math::is_math_function(&f.name) => {
429            let m = Math::parse(f)?;
430            let (ok, unit) = match slot {
431                Slot::Hue => (
432                    m.fits(Expect::Number) || m.fits(Expect::Dimension(Kind::Angle)),
433                    Written::Number,
434                ),
435                Slot::Scaled(_) if m.fits(Expect::Number) => (true, Written::Number),
436                Slot::Scaled(_) => (m.fits(Expect::Percentage), Written::Percent),
437            };
438            if !ok {
439                return None;
440            }
441            (Channel::Math(m), unit)
442        }
443        _ => return None,
444    })
445}
446
447/// What a channel was written as, for the legacy forms' rule that the
448/// three be all numbers or all percentages.
449#[derive(Clone, Copy, PartialEq, Eq)]
450enum Written {
451    Number,
452    Percent,
453    None,
454}
455
456/// Works out a math channel in a legacy form, where it's resolved.
457fn resolve(c: Channel, scale: f64) -> Channel {
458    match c {
459        Channel::Math(m) => match m.leaf() {
460            Some(Leaf::Number(v)) => Channel::Number(nan_zero(v)),
461            Some(Leaf::Percentage(v)) => Channel::Number(nan_zero(v) / 100.0 * scale),
462            Some(Leaf::Dimension(v, _)) => Channel::Number(nan_zero(v)),
463            None => Channel::Math(m),
464        },
465        c => c,
466    }
467}
468
469fn nan_zero(v: f64) -> f64 {
470    if v.is_nan() { 0.0 } else { v }
471}
472
473/// How deep colors may nest inside colors, through `from` and the like.
474const MAX_DEPTH: usize = 16;
475
476fn function(f: &Function<'_>) -> Option<Color> {
477    guarded(|| function_at(f))
478}
479
480/// Colors nest in colors (`light-dark()`, `rgb(from …)`); past a limit a
481/// color is invalid rather than a risk to the stack.
482fn guarded(f: impl FnOnce() -> Option<Color>) -> Option<Color> {
483    let depth = DEPTH.with(|d| d.get());
484    if depth >= MAX_DEPTH {
485        return None;
486    }
487    DEPTH.with(|d| d.set(depth + 1));
488    let result = f();
489    DEPTH.with(|d| d.set(depth));
490    result
491}
492
493fn function_at(f: &Function<'_>) -> Option<Color> {
494    let mut buf = [0; 32];
495    let name = super::units::lowercase(&f.name, &mut buf)?;
496    let first = f.arguments.iter().find(|v| !v.is_whitespace());
497    if matches!(first, Some(ComponentValue::Token(Token::Ident(w), _)) if w.eq_ignore_ascii_case("from"))
498    {
499        return relative(f, name);
500    }
501    if name == "contrast-color" {
502        let solid: Vec<_> = f.arguments.iter().filter(|v| !v.is_whitespace()).collect();
503        return match solid[..] {
504            [v] => Some(Color::Contrast(Box::new(Color::parse(v)?))),
505            _ => None,
506        };
507    }
508    if name == "light-dark" {
509        let parts: Vec<&[ComponentValue<'_>]> = f
510            .arguments
511            .split(|v| matches!(v, ComponentValue::Token(Token::Comma, _)))
512            .collect();
513        let [a, b] = parts[..] else { return None };
514        let one = |vs: &[ComponentValue<'_>]| {
515            let solid: Vec<_> = vs.iter().filter(|v| !v.is_whitespace()).collect();
516            match solid[..] {
517                [v] => Color::parse(v),
518                _ => None,
519            }
520        };
521        return Some(Color::LightDark(Box::new(one(a)?), Box::new(one(b)?)));
522    }
523    let mut values: &[ComponentValue<'_>] = &f.arguments;
524    let model = match name {
525        "rgb" | "rgba" => Model::Rgb,
526        "hsl" | "hsla" => Model::Hsl,
527        "hwb" => Model::Hwb,
528        "lab" => Model::Lab,
529        "lch" => Model::Lch,
530        "oklab" => Model::Oklab,
531        "oklch" => Model::Oklch,
532        "device-cmyk" => Model::DeviceCmyk,
533        "color" => {
534            let start = values.iter().position(|v| !v.is_whitespace())?;
535            let ComponentValue::Token(Token::Ident(space), _) = &values[start] else {
536                return None;
537            };
538            values = &values[start + 1..];
539            Model::Color(Predefined::parse(space)?)
540        }
541        _ => return None,
542    };
543    let count = if model == Model::DeviceCmyk { 4 } else { 3 };
544    let args = split_args(values, count)?;
545    let legacy = args.commas;
546    if legacy && !matches!(model, Model::Rgb | Model::Hsl | Model::DeviceCmyk) {
547        return None;
548    }
549    let slots: &[Slot] = match model {
550        Model::Rgb => &[Slot::Scaled(255.0); 3],
551        Model::Hsl | Model::Hwb => &[Slot::Hue, Slot::Scaled(100.0), Slot::Scaled(100.0)],
552        Model::Lab => &[
553            Slot::Scaled(100.0),
554            Slot::Scaled(125.0),
555            Slot::Scaled(125.0),
556        ],
557        Model::Lch => &[Slot::Scaled(100.0), Slot::Scaled(150.0), Slot::Hue],
558        Model::Oklab => &[Slot::Scaled(1.0), Slot::Scaled(0.4), Slot::Scaled(0.4)],
559        Model::Oklch => &[Slot::Scaled(1.0), Slot::Scaled(0.4), Slot::Hue],
560        Model::Color(_) => &[Slot::Scaled(1.0); 3],
561        Model::DeviceCmyk => &[Slot::Scaled(1.0); 4],
562    };
563    if args.channels.len() != slots.len() {
564        return None;
565    }
566    let mut channels = Vec::with_capacity(slots.len());
567    let mut units = Vec::with_capacity(slots.len());
568    for (v, slot) in args.channels.iter().zip(slots) {
569        let (c, u) = channel(v, *slot, legacy)?;
570        channels.push(c);
571        units.push(u);
572    }
573    if legacy {
574        match model {
575            // All numbers or all percentages.
576            Model::Rgb if units.iter().any(|u| *u != units[0]) => return None,
577            // Saturation and lightness are percentages.
578            Model::Hsl if units[1..].iter().any(|u| *u != Written::Percent) => return None,
579            Model::DeviceCmyk if units.iter().any(|u| *u != Written::Number) => return None,
580            _ => {}
581        }
582    }
583    let mut alpha = match args.alpha {
584        Some(v) => channel(v, Slot::Scaled(1.0), legacy)?.0,
585        None => Channel::Number(1.0),
586    };
587    // Parse-time clamping, of what was written as a number.
588    let clamp = |c: &mut Channel, lo: f64, hi: f64| {
589        if let Channel::Number(v) = c {
590            *v = v.clamp(lo, hi);
591        }
592    };
593    let legacy_model = matches!(model, Model::Rgb | Model::Hsl | Model::Hwb);
594    if legacy_model {
595        for (i, c) in channels.iter_mut().enumerate() {
596            let scale = match slots[i] {
597                Slot::Scaled(s) => s,
598                Slot::Hue => 1.0,
599            };
600            *c = resolve(std::mem::replace(c, Channel::None), scale);
601        }
602        alpha = resolve(alpha, 1.0);
603    }
604    if let Channel::Number(a) = &mut alpha {
605        *a = nan_zero(*a).clamp(0.0, 1.0);
606    }
607    match model {
608        Model::Rgb => channels.iter_mut().for_each(|c| clamp(c, 0.0, 255.0)),
609        Model::DeviceCmyk => channels.iter_mut().for_each(|c| clamp(c, 0.0, 1.0)),
610        Model::Hsl => clamp(&mut channels[1], 0.0, f64::INFINITY),
611        Model::Lab => clamp(&mut channels[0], 0.0, 100.0),
612        Model::Lch => {
613            clamp(&mut channels[0], 0.0, 100.0);
614            clamp(&mut channels[1], 0.0, f64::INFINITY);
615        }
616        Model::Oklab => clamp(&mut channels[0], 0.0, 1.0),
617        Model::Oklch => {
618            clamp(&mut channels[0], 0.0, 1.0);
619            clamp(&mut channels[1], 0.0, f64::INFINITY);
620        }
621        _ => {}
622    }
623    // Hues go round to [0, 360).
624    for (c, slot) in channels.iter_mut().zip(slots) {
625        if let (Slot::Hue, Channel::Number(h)) = (slot, &mut *c) {
626            *h = if h.is_finite() {
627                h.rem_euclid(360.0)
628            } else {
629                0.0
630            };
631        }
632    }
633    Some(Color::Channels(Channels {
634        model,
635        channels,
636        alpha,
637    }))
638}
639
640// ---- conversion and serialization ------------------------------------------
641
642/// sRGB from 0 to 1, from HSL in degrees and percent.
643fn hsl_to_rgb(h: f64, s: f64, l: f64) -> [f64; 3] {
644    let (s, l) = (s / 100.0, l / 100.0);
645    let f = |n: f64| {
646        let k = (n + h / 30.0).rem_euclid(12.0);
647        let a = s * l.min(1.0 - l);
648        l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
649    };
650    [f(0.0), f(8.0), f(4.0)]
651}
652
653fn hwb_to_rgb(h: f64, w: f64, b: f64) -> [f64; 3] {
654    let (w, b) = (w / 100.0, b / 100.0);
655    if w + b >= 1.0 {
656        let gray = w / (w + b);
657        return [gray; 3];
658    }
659    hsl_to_rgb(h, 100.0, 50.0).map(|c| c * (1.0 - w - b) + w)
660}
661
662/// A legacy color's alpha: two decimals if that's still the same in
663/// eight bits, otherwise three.
664fn write_legacy_alpha(out: &mut impl Write, a: f64) -> fmt::Result {
665    let bits = (a * 255.0).round();
666    let two = (a * 100.0).round() / 100.0;
667    let v = if (two * 255.0).round() == bits {
668        two
669    } else {
670        (a * 1000.0).round() / 1000.0
671    };
672    write_number(out, v)
673}
674
675fn write_channel(out: &mut impl Write, c: &Channel, percent: bool) -> fmt::Result {
676    match c {
677        Channel::None => out.write_str("none"),
678        Channel::Number(v) => {
679            write_number(out, *v)?;
680            if percent {
681                out.write_char('%')?;
682            }
683            Ok(())
684        }
685        Channel::Math(m) => write!(out, "{m}"),
686    }
687}
688
689fn write_alpha(out: &mut impl Write, a: &Channel) -> fmt::Result {
690    if *a == Channel::Number(1.0) {
691        return Ok(());
692    }
693    out.write_str(" / ")?;
694    write_channel(out, a, false)
695}
696
697impl Channels {
698    pub(crate) fn model_is_legacy(&self) -> bool {
699        matches!(self.model, Model::Rgb | Model::Hsl | Model::Hwb)
700    }
701
702    pub(crate) fn has_math(&self) -> bool {
703        self.channels
704            .iter()
705            .chain([&self.alpha])
706            .any(|c| matches!(c, Channel::Math(_)))
707    }
708
709    /// Each math channel replaced by what `f` makes of it.
710    pub(crate) fn map_math(&mut self, f: &impl Fn(&Math) -> Math) {
711        for c in self.channels.iter_mut().chain([&mut self.alpha]) {
712            if let Channel::Math(m) = c {
713                *m = f(m);
714            }
715        }
716    }
717
718    /// The color in sRGB, 0 to 1, if it's a legacy one with every channel
719    /// known.
720    fn legacy_srgb(&self) -> Option<[f64; 3]> {
721        let n: Vec<f64> = self
722            .channels
723            .iter()
724            .map(Channel::number)
725            .collect::<Option<_>>()?;
726        self.alpha.number()?;
727        Some(match self.model {
728            Model::Rgb => [n[0] / 255.0, n[1] / 255.0, n[2] / 255.0],
729            Model::Hsl => hsl_to_rgb(n[0], n[1], n[2]),
730            Model::Hwb => hwb_to_rgb(n[0], n[1], n[2]),
731            _ => return None,
732        })
733    }
734
735    fn write(&self, out: &mut impl Write) -> fmt::Result {
736        if let Some(rgb) = self.legacy_srgb() {
737            // Rounded after a millionth's rounding, so 127.4999… from the
738            // arithmetic is the 127.5 it stands for.
739            let [r, g, b] = rgb.map(|c| {
740                ((nan_zero(c) * 255.0 * 1e6).round() / 1e6)
741                    .clamp(0.0, 255.0)
742                    .round()
743            });
744            let a = self.alpha.number().unwrap();
745            if a == 1.0 {
746                return write!(out, "rgb({r}, {g}, {b})");
747            }
748            write!(out, "rgba({r}, {g}, {b}, ")?;
749            write_legacy_alpha(out, a)?;
750            return out.write_char(')');
751        }
752        let (name, percents): (&str, [bool; 3]) = match self.model {
753            Model::Rgb if self.channels.contains(&Channel::None) => {
754                out.write_str("color(srgb")?;
755                for c in &self.channels {
756                    out.write_char(' ')?;
757                    match c {
758                        Channel::Number(v) => write_number(out, v / 255.0)?,
759                        c => write_channel(out, c, false)?,
760                    }
761                }
762                write_alpha(out, &self.alpha)?;
763                return out.write_char(')');
764            }
765            Model::Rgb => ("rgb", [false; 3]),
766            // With `none` the percentages are written; with math, as WPT
767            // has it, they aren't.
768            Model::Hsl | Model::Hwb => {
769                let math = self
770                    .channels
771                    .iter()
772                    .chain([&self.alpha])
773                    .any(|c| matches!(c, Channel::Math(_)));
774                let name = if self.model == Model::Hsl {
775                    "hsl"
776                } else {
777                    "hwb"
778                };
779                (name, [false, !math, !math])
780            }
781            Model::Lab => ("lab", [false; 3]),
782            Model::Lch => ("lch", [false; 3]),
783            Model::Oklab => ("oklab", [false; 3]),
784            Model::Oklch => ("oklch", [false; 3]),
785            Model::Color(space) => {
786                write!(out, "color({}", space.name())?;
787                for c in &self.channels {
788                    out.write_char(' ')?;
789                    write_channel(out, c, false)?;
790                }
791                write_alpha(out, &self.alpha)?;
792                return out.write_char(')');
793            }
794            Model::DeviceCmyk => {
795                out.write_str("color(device-cmyk")?;
796                for c in &self.channels {
797                    out.write_char(' ')?;
798                    write_channel(out, c, false)?;
799                }
800                write_alpha(out, &self.alpha)?;
801                return out.write_char(')');
802            }
803        };
804        write!(out, "{name}(")?;
805        for (i, (c, p)) in self.channels.iter().zip(percents).enumerate() {
806            if i > 0 {
807                out.write_char(' ')?;
808            }
809            write_channel(out, c, p)?;
810        }
811        write_alpha(out, &self.alpha)?;
812        out.write_char(')')
813    }
814}
815
816thread_local! {
817    static DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
818}
819
820/// `rgb(from <color> …)` and the rest, CSS Color 5 §4.
821fn relative(f: &Function<'_>, name: &str) -> Option<Color> {
822    relative_at(f, name)
823}
824
825fn relative_at(f: &Function<'_>, name: &str) -> Option<Color> {
826    let solid: Vec<&ComponentValue<'_>> =
827        f.arguments.iter().filter(|v| !v.is_whitespace()).collect();
828    let origin = Color::parse(solid.get(1)?)?;
829    let mut rest = &solid[2..];
830    let (function, space, keywords, slots): (&'static str, _, &[&'static str], [Slot; 3]) =
831        match name {
832            "rgb" | "rgba" => (
833                "rgb",
834                None,
835                &["r", "g", "b", "alpha"],
836                [Slot::Scaled(1.0); 3],
837            ),
838            "hsl" | "hsla" => (
839                "hsl",
840                None,
841                &["h", "s", "l", "alpha"],
842                [Slot::Hue, Slot::Scaled(1.0), Slot::Scaled(1.0)],
843            ),
844            "hwb" => (
845                "hwb",
846                None,
847                &["h", "w", "b", "alpha"],
848                [Slot::Hue, Slot::Scaled(1.0), Slot::Scaled(1.0)],
849            ),
850            "lab" => (
851                "lab",
852                None,
853                &["l", "a", "b", "alpha"],
854                [Slot::Scaled(1.0); 3],
855            ),
856            "oklab" => (
857                "oklab",
858                None,
859                &["l", "a", "b", "alpha"],
860                [Slot::Scaled(1.0); 3],
861            ),
862            "lch" => (
863                "lch",
864                None,
865                &["l", "c", "h", "alpha"],
866                [Slot::Scaled(1.0), Slot::Scaled(1.0), Slot::Hue],
867            ),
868            "oklch" => (
869                "oklch",
870                None,
871                &["l", "c", "h", "alpha"],
872                [Slot::Scaled(1.0), Slot::Scaled(1.0), Slot::Hue],
873            ),
874            "alpha" => ("alpha", None, &["alpha"], [Slot::Scaled(1.0); 3]),
875            "color" => {
876                let ComponentValue::Token(Token::Ident(s), _) = rest.first()? else {
877                    return None;
878                };
879                let space = Predefined::parse(s)?;
880                rest = &rest[1..];
881                let keywords: &[&'static str] = match space {
882                    Predefined::XyzD50 | Predefined::XyzD65 => &["x", "y", "z", "alpha"],
883                    _ => &["r", "g", "b", "alpha"],
884                };
885                ("color", Some(space), keywords, [Slot::Scaled(1.0); 3])
886            }
887            _ => return None,
888        };
889    let (channels, alpha) = match rest
890        .iter()
891        .position(|v| matches!(v, ComponentValue::Token(Token::Delim('/'), _)))
892    {
893        Some(i) if rest.len() == i + 2 => (&rest[..i], Some(rest[i + 1])),
894        Some(_) => return None,
895        None => (rest, None),
896    };
897    // `alpha(from <color> / …)` has only the alpha.
898    let count = if function == "alpha" { 0 } else { 3 };
899    if channels.len() != count || (count == 0 && alpha.is_none()) {
900        return None;
901    }
902    let read = |v: &ComponentValue<'_>, slot: Slot| -> Option<RelativeChannel> {
903        Some(match v {
904            ComponentValue::Token(Token::Number(n), _) => RelativeChannel::Number(n.value),
905            ComponentValue::Token(Token::Percentage(n), _) if matches!(slot, Slot::Scaled(_)) => {
906                RelativeChannel::Percentage(n.value)
907            }
908            ComponentValue::Token(Token::Dimension { number, unit }, _)
909                if matches!(slot, Slot::Hue) =>
910            {
911                let u = super::units::Unit::parse(unit)?;
912                if u.kind() != Kind::Angle {
913                    return None;
914                }
915                RelativeChannel::Angle(number.value, u)
916            }
917            ComponentValue::Token(Token::Ident(w), _) if w.eq_ignore_ascii_case("none") => {
918                RelativeChannel::None
919            }
920            ComponentValue::Token(Token::Ident(w), _) => {
921                RelativeChannel::Keyword(keywords.iter().find(|k| w.eq_ignore_ascii_case(k))?)
922            }
923            ComponentValue::Function(f) if Math::is_math_function(&f.name) => {
924                let m = Math::parse_with(f, keywords)?;
925                let ok = match slot {
926                    Slot::Hue => m.fits(Expect::Number) || m.fits(Expect::Dimension(Kind::Angle)),
927                    Slot::Scaled(_) => m.fits(Expect::Number) || m.fits(Expect::Percentage),
928                };
929                if !ok {
930                    return None;
931                }
932                RelativeChannel::Math(m)
933            }
934            _ => return None,
935        })
936    };
937    let channels = channels
938        .iter()
939        .zip(slots)
940        .map(|(v, s)| read(v, s))
941        .collect::<Option<Vec<_>>>()?;
942    let alpha = match alpha {
943        Some(v) => Some(read(v, Slot::Scaled(1.0))?),
944        None => None,
945    };
946    Some(Color::Relative(Box::new(Relative {
947        function,
948        space,
949        origin,
950        channels,
951        alpha,
952    })))
953}
954
955impl fmt::Display for RelativeChannel {
956    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957        match self {
958            RelativeChannel::Number(v) => write_number(f, *v),
959            RelativeChannel::Percentage(v) => {
960                write_number(f, *v)?;
961                f.write_char('%')
962            }
963            RelativeChannel::Angle(v, u) => {
964                write_number(f, *v)?;
965                f.write_str(u.as_str())
966            }
967            RelativeChannel::Keyword(k) => f.write_str(k),
968            RelativeChannel::None => f.write_str("none"),
969            RelativeChannel::Math(m) => write!(f, "{m}"),
970        }
971    }
972}
973
974impl fmt::Display for Relative {
975    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976        write!(f, "{}(from ", self.function)?;
977        match &self.origin {
978            // An origin with no alpha, as with no channel, is written in
979            // `color()`, as WPT has it: the legacy form has no `none`.
980            Color::Channels(c) if c.model == Model::Rgb && c.alpha == Channel::None => {
981                f.write_str("color(srgb")?;
982                for ch in &c.channels {
983                    f.write_char(' ')?;
984                    match ch {
985                        Channel::Number(v) => write_number(f, v / 255.0)?,
986                        ch => write_channel(f, ch, false)?,
987                    }
988                }
989                f.write_str(" / none)")?;
990            }
991            origin => write!(f, "{origin}")?,
992        }
993        if let Some(space) = self.space {
994            write!(f, " {}", space.name())?;
995        }
996        for c in &self.channels {
997            write!(f, " {c}")?;
998        }
999        if let Some(a) = &self.alpha {
1000            write!(f, " / {a}")?;
1001        }
1002        f.write_char(')')
1003    }
1004}
1005
1006impl fmt::Display for Color {
1007    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1008        match self {
1009            Color::Relative(r) => write!(f, "{r}"),
1010            Color::Contrast(c) => write!(f, "contrast-color({c})"),
1011            Color::Mix(m) => f.write_str(&m.text),
1012            Color::Text(s) => f.write_str(s),
1013            Color::CurrentColor => f.write_str("currentcolor"),
1014            Color::Named(name) | Color::System(name) => f.write_str(name),
1015            Color::Channels(c) => c.write(f),
1016            Color::LightDark(a, b) => write!(f, "light-dark({a}, {b})"),
1017        }
1018    }
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023    use super::*;
1024
1025    fn color(css: &str) -> Option<String> {
1026        let v = crate::parse_component_value(css).ok()?;
1027        Color::parse(&v).map(|c| c.to_string())
1028    }
1029
1030    #[test]
1031    fn serializes_as_css_color_4_says() {
1032        let cases = [
1033            ("#234", "rgb(34, 51, 68)"),
1034            ("#f6f8", "rgba(255, 102, 255, 0.533)"),
1035            ("transparent", "transparent"),
1036            ("RebeccaPurple", "rebeccapurple"),
1037            ("CanvasText", "canvastext"),
1038            ("currentColor", "currentcolor"),
1039            ("rgb(-2 3 4)", "rgb(0, 3, 4)"),
1040            ("rgba(2, 3, 4, 50%)", "rgba(2, 3, 4, 0.5)"),
1041            ("rgb(128 none none)", "color(srgb 0.501961 none none)"),
1042            ("hsl(120 30% 50%)", "rgb(89, 166, 89)"),
1043            ("hsl(120 30 none / 0.5)", "hsl(120 30% none / 0.5)"),
1044            ("hwb(120 0% 50%)", "rgb(0, 128, 0)"),
1045            ("lab(400 0 10/50%)", "lab(100 0 10 / 0.5)"),
1046            ("lch(0 150 -10)", "lch(0 150 350)"),
1047            ("oklch(1 0.4 700 / 0)", "oklch(1 0.4 340 / 0)"),
1048            ("color(xyz 10% 10% 10%)", "color(xyz-d65 0.1 0.1 0.1)"),
1049            ("rgb(calc(infinity), 0, 0)", "rgb(255, 0, 0)"),
1050            ("lab(calc(50 * 3) 0 0)", "lab(calc(150) 0 0)"),
1051            ("light-dark(black, white)", "light-dark(black, white)"),
1052        ];
1053        for (css, want) in cases {
1054            assert_eq!(color(css).as_deref(), Some(want), "{css}");
1055        }
1056    }
1057
1058    #[test]
1059    fn relative_colors_keep_their_channels() {
1060        let cases = [
1061            (
1062                "rgba(from rgb(20%, 40%, 60%, 80%) r g 25 / 25%)",
1063                "rgb(from rgba(51, 102, 153, 0.8) r g 25 / 25%)",
1064            ),
1065            (
1066                "rgb(from rebeccapurple r calc(g * .5 + g * .5) 10)",
1067                "rgb(from rebeccapurple r calc((0.5 * g) + (0.5 * g)) 10)",
1068            ),
1069            (
1070                "hsl(from red 0deg s l / alpha)",
1071                "hsl(from red 0deg s l / alpha)",
1072            ),
1073            (
1074                "color(from color(srgb 0.7 0.5 0.3) srgb r g b)",
1075                "color(from color(srgb 0.7 0.5 0.3) srgb r g b)",
1076            ),
1077        ];
1078        for (css, want) in cases {
1079            assert_eq!(color(css).as_deref(), Some(want), "{css}");
1080        }
1081        for css in [
1082            "rgb(from red r 10deg 10)",
1083            "rgb(from red l g b)",
1084            "hsl(from red 10% s l)",
1085            "rgb(from red calc(r + 1%) g b)",
1086        ] {
1087            assert_eq!(color(css), None, "{css}");
1088        }
1089    }
1090
1091    #[test]
1092    fn deep_nesting_is_invalid_not_a_crash() {
1093        let css = format!("{}red{}", "light-dark(".repeat(5000), ", red)".repeat(5000));
1094        assert_eq!(color(&css), None);
1095    }
1096
1097    #[test]
1098    fn rejects_what_isnt_a_color() {
1099        for css in [
1100            "#12",
1101            "rgb(1, 2%, 3)",
1102            "hsl(1, 2, 3)",
1103            "rgb(none, 0, 0)",
1104            "lab(1, 2, 3)",
1105            "color(foo 1 2 3)",
1106            "rgb(1 2)",
1107            "blurple",
1108        ] {
1109            assert_eq!(color(css), None, "{css}");
1110        }
1111    }
1112}