Skip to main content

rspack_lightningcss/values/
color.rs

1//! CSS color values.
2
3#![allow(non_upper_case_globals)]
4
5use super::angle::Angle;
6use super::calc::Calc;
7use super::number::CSSNumber;
8use super::percentage::Percentage;
9use crate::compat::Feature;
10use crate::error::{ParserError, PrinterError};
11use crate::macros::enum_property;
12use crate::properties::PropertyId;
13use crate::rules::supports::SupportsCondition;
14use crate::targets::{should_compile, Browsers, Features, Targets};
15use crate::traits::{FallbackValues, IsCompatible, Parse, ToCss};
16#[cfg(feature = "visitor")]
17use crate::visitor::{Visit, VisitTypes, Visitor};
18use bitflags::bitflags;
19use cssparser::color::{parse_hash_color, parse_named_color};
20use cssparser::*;
21use cssparser_color::{hsl_to_rgb, AngleOrNumber, ColorParser, NumberOrPercentage};
22use std::any::TypeId;
23use std::f32::consts::PI;
24
25/// A CSS [`<color>`](https://www.w3.org/TR/css-color-4/#color-type) value.
26///
27/// CSS supports many different color spaces to represent colors. The most common values
28/// are stored as RGBA using a single byte per component. Less common values are stored
29/// using a `Box` to reduce the amount of memory used per color.
30///
31/// Each color space is represented as a struct that implements the `From` and `Into` traits
32/// for all other color spaces, so it is possible to convert between color spaces easily.
33/// In addition, colors support [interpolation](#method.interpolate) as in the `color-mix()` function.
34#[derive(Debug, Clone, PartialEq)]
35#[cfg_attr(feature = "visitor", derive(Visit))]
36#[cfg_attr(feature = "visitor", visit(visit_color, COLORS))]
37#[cfg_attr(
38  feature = "serde",
39  derive(serde::Serialize, serde::Deserialize),
40  serde(untagged, rename_all = "lowercase")
41)]
42#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
43#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
44pub enum CssColor {
45  /// The [`currentColor`](https://www.w3.org/TR/css-color-4/#currentcolor-color) keyword.
46  #[cfg_attr(feature = "serde", serde(with = "CurrentColor"))]
47  CurrentColor,
48  /// An value in the RGB color space, including values parsed as hex colors, or the `rgb()`, `hsl()`, and `hwb()` functions.
49  #[cfg_attr(
50    feature = "serde",
51    serde(serialize_with = "serialize_rgba", deserialize_with = "deserialize_rgba")
52  )]
53  #[cfg_attr(feature = "jsonschema", schemars(with = "RGBColor"))]
54  RGBA(RGBA),
55  /// A value in a LAB color space, including the `lab()`, `lch()`, `oklab()`, and `oklch()` functions.
56  LAB(Box<LABColor>),
57  /// A value in a predefined color space, e.g. `display-p3`.
58  Predefined(Box<PredefinedColor>),
59  /// A floating point representation of an RGB, HSL, or HWB color when it contains `none` components.
60  Float(Box<FloatColor>),
61  /// The [`light-dark()`](https://drafts.csswg.org/css-color-5/#light-dark) function.
62  #[cfg_attr(feature = "visitor", skip_type)]
63  #[cfg_attr(feature = "serde", serde(with = "LightDark"))]
64  LightDark(Box<CssColor>, Box<CssColor>),
65  /// A [system color](https://drafts.csswg.org/css-color/#css-system-colors) keyword.
66  System(SystemColor),
67}
68
69#[cfg(feature = "serde")]
70#[derive(serde::Serialize, serde::Deserialize)]
71#[serde(tag = "type", rename_all = "lowercase")]
72#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
73enum CurrentColor {
74  CurrentColor,
75}
76
77#[cfg(feature = "serde")]
78impl CurrentColor {
79  fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error>
80  where
81    S: serde::Serializer,
82  {
83    serde::Serialize::serialize(&CurrentColor::CurrentColor, serializer)
84  }
85
86  fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error>
87  where
88    D: serde::Deserializer<'de>,
89  {
90    use serde::Deserialize;
91    let _: CurrentColor = Deserialize::deserialize(deserializer)?;
92    Ok(())
93  }
94}
95
96// Convert RGBA to SRGB to serialize so we get a tagged struct.
97#[cfg(feature = "serde")]
98#[derive(serde::Serialize, serde::Deserialize)]
99#[serde(tag = "type", rename_all = "lowercase")]
100#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
101enum RGBColor {
102  RGB(RGB),
103}
104
105#[cfg(feature = "serde")]
106fn serialize_rgba<S>(rgba: &RGBA, serializer: S) -> Result<S::Ok, S::Error>
107where
108  S: serde::Serializer,
109{
110  use serde::Serialize;
111  RGBColor::RGB(rgba.into()).serialize(serializer)
112}
113
114#[cfg(feature = "serde")]
115fn deserialize_rgba<'de, D>(deserializer: D) -> Result<RGBA, D::Error>
116where
117  D: serde::Deserializer<'de>,
118{
119  use serde::Deserialize;
120  match RGBColor::deserialize(deserializer)? {
121    RGBColor::RGB(srgb) => Ok(srgb.into()),
122  }
123}
124
125// For AST serialization.
126#[cfg(feature = "serde")]
127#[derive(serde::Serialize, serde::Deserialize)]
128#[serde(tag = "type", rename_all = "kebab-case")]
129#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
130enum LightDark {
131  LightDark { light: CssColor, dark: CssColor },
132}
133
134#[cfg(feature = "serde")]
135impl<'de> LightDark {
136  pub fn serialize<S>(light: &Box<CssColor>, dark: &Box<CssColor>, serializer: S) -> Result<S::Ok, S::Error>
137  where
138    S: serde::Serializer,
139  {
140    let wrapper = LightDark::LightDark {
141      light: (**light).clone(),
142      dark: (**dark).clone(),
143    };
144    serde::Serialize::serialize(&wrapper, serializer)
145  }
146
147  pub fn deserialize<D>(deserializer: D) -> Result<(Box<CssColor>, Box<CssColor>), D::Error>
148  where
149    D: serde::Deserializer<'de>,
150  {
151    let v: LightDark = serde::Deserialize::deserialize(deserializer)?;
152    match v {
153      LightDark::LightDark { light, dark } => Ok((Box::new(light), Box::new(dark))),
154    }
155  }
156}
157
158/// A color in a LAB color space, including the `lab()`, `lch()`, `oklab()`, and `oklch()` functions.
159#[derive(Debug, Clone, Copy, PartialEq)]
160#[cfg_attr(feature = "visitor", derive(Visit))]
161#[cfg_attr(
162  feature = "serde",
163  derive(serde::Serialize, serde::Deserialize),
164  serde(tag = "type", rename_all = "lowercase")
165)]
166#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
167pub enum LABColor {
168  /// A `lab()` color.
169  LAB(LAB),
170  /// An `lch()` color.
171  LCH(LCH),
172  /// An `oklab()` color.
173  OKLAB(OKLAB),
174  /// An `oklch()` color.
175  OKLCH(OKLCH),
176}
177
178/// A color in a predefined color space, e.g. `display-p3`.
179#[derive(Debug, Clone, Copy, PartialEq)]
180#[cfg_attr(feature = "visitor", derive(Visit))]
181#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(tag = "type"))]
182#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
183pub enum PredefinedColor {
184  /// A color in the `srgb` color space.
185  #[cfg_attr(feature = "serde", serde(rename = "srgb"))]
186  SRGB(SRGB),
187  /// A color in the `srgb-linear` color space.
188  #[cfg_attr(feature = "serde", serde(rename = "srgb-linear"))]
189  SRGBLinear(SRGBLinear),
190  /// A color in the `display-p3` color space.
191  #[cfg_attr(feature = "serde", serde(rename = "display-p3"))]
192  DisplayP3(P3),
193  /// A color in the `a98-rgb` color space.
194  #[cfg_attr(feature = "serde", serde(rename = "a98-rgb"))]
195  A98(A98),
196  /// A color in the `prophoto-rgb` color space.
197  #[cfg_attr(feature = "serde", serde(rename = "prophoto-rgb"))]
198  ProPhoto(ProPhoto),
199  /// A color in the `rec2020` color space.
200  #[cfg_attr(feature = "serde", serde(rename = "rec2020"))]
201  Rec2020(Rec2020),
202  /// A color in the `xyz-d50` color space.
203  #[cfg_attr(feature = "serde", serde(rename = "xyz-d50"))]
204  XYZd50(XYZd50),
205  /// A color in the `xyz-d65` color space.
206  #[cfg_attr(feature = "serde", serde(rename = "xyz-d65"))]
207  XYZd65(XYZd65),
208}
209
210/// A floating point representation of color types that
211/// are usually stored as RGBA. These are used when there
212/// are any `none` components, which are represented as NaN.
213#[derive(Debug, Clone, Copy, PartialEq)]
214#[cfg_attr(feature = "visitor", derive(Visit))]
215#[cfg_attr(
216  feature = "serde",
217  derive(serde::Serialize, serde::Deserialize),
218  serde(tag = "type", rename_all = "lowercase")
219)]
220#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
221pub enum FloatColor {
222  /// An RGB color.
223  RGB(RGB),
224  /// An HSL color.
225  HSL(HSL),
226  /// An HWB color.
227  HWB(HWB),
228}
229
230bitflags! {
231  /// A color type that is used as a fallback when compiling colors for older browsers.
232  #[derive(PartialEq, Eq, Clone, Copy)]
233  pub struct ColorFallbackKind: u8 {
234    /// An RGB color fallback.
235    const RGB    = 0b01;
236    /// A P3 color fallback.
237    const P3     = 0b10;
238    /// A LAB color fallback.
239    const LAB    = 0b100;
240    /// An OKLAB color fallback.
241    const OKLAB  = 0b1000;
242  }
243}
244
245enum_property! {
246  /// A [color space](https://www.w3.org/TR/css-color-4/#interpolation-space) keyword
247  /// used in interpolation functions such as `color-mix()`.
248  enum ColorSpaceName {
249    "srgb": SRGB,
250    "srgb-linear": SRGBLinear,
251    "lab": LAB,
252    "oklab": OKLAB,
253    "xyz": XYZ,
254    "xyz-d50": XYZd50,
255    "xyz-d65": XYZd65,
256    "hsl": Hsl,
257    "hwb": Hwb,
258    "lch": LCH,
259    "oklch": OKLCH,
260  }
261}
262
263enum_property! {
264  /// A hue [interpolation method](https://www.w3.org/TR/css-color-4/#typedef-hue-interpolation-method)
265  /// used in interpolation functions such as `color-mix()`.
266  pub enum HueInterpolationMethod {
267    /// Angles are adjusted so that θ₂ - θ₁ ∈ [-180, 180].
268    Shorter,
269    /// Angles are adjusted so that θ₂ - θ₁ ∈ {0, [180, 360)}.
270    Longer,
271    /// Angles are adjusted so that θ₂ - θ₁ ∈ [0, 360).
272    Increasing,
273    /// Angles are adjusted so that θ₂ - θ₁ ∈ (-360, 0].
274    Decreasing,
275    /// No fixup is performed. Angles are interpolated in the same way as every other component.
276    Specified,
277  }
278}
279
280impl ColorFallbackKind {
281  pub(crate) fn lowest(&self) -> ColorFallbackKind {
282    // This finds the lowest set bit.
283    *self & ColorFallbackKind::from_bits_truncate(self.bits().wrapping_neg())
284  }
285
286  pub(crate) fn highest(&self) -> ColorFallbackKind {
287    // This finds the highest set bit.
288    if self.is_empty() {
289      return ColorFallbackKind::empty();
290    }
291
292    let zeros = 7 - self.bits().leading_zeros();
293    ColorFallbackKind::from_bits_truncate(1 << zeros)
294  }
295
296  pub(crate) fn and_below(&self) -> ColorFallbackKind {
297    if self.is_empty() {
298      return ColorFallbackKind::empty();
299    }
300
301    *self | ColorFallbackKind::from_bits_truncate(self.bits() - 1)
302  }
303
304  pub(crate) fn supports_condition<'i>(&self) -> SupportsCondition<'i> {
305    let s = match *self {
306      ColorFallbackKind::P3 => "color(display-p3 0 0 0)",
307      ColorFallbackKind::LAB => "lab(0% 0 0)",
308      _ => unreachable!(),
309    };
310
311    SupportsCondition::Declaration {
312      property_id: PropertyId::Color,
313      value: s.into(),
314    }
315  }
316}
317
318impl CssColor {
319  /// Returns the `currentColor` keyword.
320  pub fn current_color() -> CssColor {
321    CssColor::CurrentColor
322  }
323
324  /// Returns the `transparent` keyword.
325  pub fn transparent() -> CssColor {
326    CssColor::RGBA(RGBA::transparent())
327  }
328
329  fn alpha(&self) -> Result<f32, ()> {
330    Ok(match self {
331      CssColor::RGBA(rgba) => rgba.alpha_f32(),
332      CssColor::LAB(lab) => match &**lab {
333        LABColor::LAB(lab) => lab.alpha,
334        LABColor::LCH(lch) => lch.alpha,
335        LABColor::OKLAB(lab) => lab.alpha,
336        LABColor::OKLCH(lch) => lch.alpha,
337      },
338      CssColor::Predefined(predefined) => match &**predefined {
339        PredefinedColor::SRGB(rgb) => rgb.alpha,
340        PredefinedColor::SRGBLinear(rgb) => rgb.alpha,
341        PredefinedColor::DisplayP3(rgb) => rgb.alpha,
342        PredefinedColor::A98(rgb) => rgb.alpha,
343        PredefinedColor::ProPhoto(rgb) => rgb.alpha,
344        PredefinedColor::Rec2020(rgb) => rgb.alpha,
345        PredefinedColor::XYZd50(xyz) => xyz.alpha,
346        PredefinedColor::XYZd65(xyz) => xyz.alpha,
347      },
348      CssColor::Float(float) => match &**float {
349        FloatColor::RGB(rgb) => rgb.alpha,
350        FloatColor::HSL(hsl) => hsl.alpha,
351        FloatColor::HWB(hwb) => hwb.alpha,
352      },
353      CssColor::LightDark(..) | CssColor::CurrentColor | CssColor::System(..) => return Err(()),
354    })
355  }
356
357  fn with_alpha(self, alpha: f32) -> CssColor {
358    match self {
359      CssColor::RGBA(rgba) => {
360        // Store as Float to preserve the exact f32 alpha value through subsequent
361        // relative color computations. Going through u8 here would quantize 0.5 to
362        // 128/255 ≈ 0.50196 and accumulate error in nested alpha()/color-mix() calls.
363        let mut rgb = RGB::from(rgba);
364        rgb.alpha = alpha;
365        CssColor::Float(Box::new(FloatColor::RGB(rgb)))
366      }
367      CssColor::LAB(mut lab) => {
368        match &mut *lab {
369          LABColor::LAB(lab) => lab.alpha = alpha,
370          LABColor::LCH(lch) => lch.alpha = alpha,
371          LABColor::OKLAB(lab) => lab.alpha = alpha,
372          LABColor::OKLCH(lch) => lch.alpha = alpha,
373        }
374        CssColor::LAB(lab)
375      }
376      CssColor::Predefined(mut predefined) => {
377        match &mut *predefined {
378          PredefinedColor::SRGB(rgb) => rgb.alpha = alpha,
379          PredefinedColor::SRGBLinear(rgb) => rgb.alpha = alpha,
380          PredefinedColor::DisplayP3(rgb) => rgb.alpha = alpha,
381          PredefinedColor::A98(rgb) => rgb.alpha = alpha,
382          PredefinedColor::ProPhoto(rgb) => rgb.alpha = alpha,
383          PredefinedColor::Rec2020(rgb) => rgb.alpha = alpha,
384          PredefinedColor::XYZd50(xyz) => xyz.alpha = alpha,
385          PredefinedColor::XYZd65(xyz) => xyz.alpha = alpha,
386        }
387        CssColor::Predefined(predefined)
388      }
389      CssColor::Float(mut float) => {
390        match &mut *float {
391          FloatColor::RGB(rgb) => rgb.alpha = alpha,
392          FloatColor::HSL(hsl) => hsl.alpha = alpha,
393          FloatColor::HWB(hwb) => hwb.alpha = alpha,
394        }
395        CssColor::Float(float)
396      }
397      CssColor::LightDark(light, dark) => CssColor::LightDark(
398        Box::new((*light).with_alpha(alpha)),
399        Box::new((*dark).with_alpha(alpha)),
400      ),
401      color => color,
402    }
403  }
404
405  /// Converts the color to RGBA.
406  pub fn to_rgb(&self) -> Result<CssColor, ()> {
407    match self {
408      CssColor::LightDark(light, dark) => {
409        Ok(CssColor::LightDark(Box::new(light.to_rgb()?), Box::new(dark.to_rgb()?)))
410      }
411      _ => Ok(RGBA::try_from(self)?.into()),
412    }
413  }
414
415  /// Converts the color to the LAB color space.
416  pub fn to_lab(&self) -> Result<CssColor, ()> {
417    match self {
418      CssColor::LightDark(light, dark) => {
419        Ok(CssColor::LightDark(Box::new(light.to_lab()?), Box::new(dark.to_lab()?)))
420      }
421      _ => Ok(LAB::try_from(self)?.into()),
422    }
423  }
424
425  /// Converts the color to the P3 color space.
426  pub fn to_p3(&self) -> Result<CssColor, ()> {
427    match self {
428      CssColor::LightDark(light, dark) => {
429        Ok(CssColor::LightDark(Box::new(light.to_p3()?), Box::new(dark.to_p3()?)))
430      }
431      _ => Ok(P3::try_from(self)?.into()),
432    }
433  }
434
435  pub(crate) fn get_possible_fallbacks(&self, targets: Targets) -> ColorFallbackKind {
436    // Fallbacks occur in levels: Oklab -> Lab -> P3 -> RGB. We start with all levels
437    // below and including the authored color space, and remove the ones that aren't
438    // compatible with our browser targets.
439    let mut fallbacks = match self {
440      CssColor::CurrentColor | CssColor::RGBA(_) | CssColor::Float(..) | CssColor::System(..) => {
441        return ColorFallbackKind::empty()
442      }
443      CssColor::LAB(lab) => match &**lab {
444        LABColor::LAB(..) | LABColor::LCH(..) if should_compile!(targets, LabColors) => {
445          ColorFallbackKind::LAB.and_below()
446        }
447        LABColor::OKLAB(..) | LABColor::OKLCH(..) if should_compile!(targets, OklabColors) => {
448          ColorFallbackKind::OKLAB.and_below()
449        }
450        _ => return ColorFallbackKind::empty(),
451      },
452      CssColor::Predefined(predefined) => match &**predefined {
453        PredefinedColor::DisplayP3(..) if should_compile!(targets, P3Colors) => ColorFallbackKind::P3.and_below(),
454        _ if should_compile!(targets, ColorFunction) => ColorFallbackKind::LAB.and_below(),
455        _ => return ColorFallbackKind::empty(),
456      },
457      CssColor::LightDark(light, dark) => {
458        return light.get_possible_fallbacks(targets) | dark.get_possible_fallbacks(targets);
459      }
460    };
461
462    if fallbacks.contains(ColorFallbackKind::OKLAB) {
463      if !should_compile!(targets, OklabColors) {
464        fallbacks.remove(ColorFallbackKind::LAB.and_below());
465      }
466    }
467
468    if fallbacks.contains(ColorFallbackKind::LAB) {
469      if !should_compile!(targets, LabColors) {
470        fallbacks.remove(ColorFallbackKind::P3.and_below());
471      } else if targets
472        .browsers
473        .map(|targets| Feature::LabColors.is_partially_compatible(targets))
474        .unwrap_or(false)
475      {
476        // We don't need P3 if Lab is supported by some of our targets.
477        // No browser implements Lab but not P3.
478        fallbacks.remove(ColorFallbackKind::P3);
479      }
480    }
481
482    if fallbacks.contains(ColorFallbackKind::P3) {
483      if !should_compile!(targets, P3Colors) {
484        fallbacks.remove(ColorFallbackKind::RGB);
485      } else if fallbacks.highest() != ColorFallbackKind::P3
486        && !targets
487          .browsers
488          .map(|targets| Feature::P3Colors.is_partially_compatible(targets))
489          .unwrap_or(false)
490      {
491        // Remove P3 if it isn't supported by any targets, and wasn't the
492        // original authored color.
493        fallbacks.remove(ColorFallbackKind::P3);
494      }
495    }
496
497    fallbacks
498  }
499
500  /// Returns the color fallback types needed for the given browser targets.
501  pub fn get_necessary_fallbacks(&self, targets: Targets) -> ColorFallbackKind {
502    // Get the full set of possible fallbacks, and remove the highest one, which
503    // will replace the original declaration. The remaining fallbacks need to be added.
504    let fallbacks = self.get_possible_fallbacks(targets);
505    fallbacks - fallbacks.highest()
506  }
507
508  /// Returns a fallback color for the given fallback type.
509  pub fn get_fallback(&self, kind: ColorFallbackKind) -> CssColor {
510    if matches!(self, CssColor::RGBA(_)) {
511      return self.clone();
512    }
513
514    match kind {
515      ColorFallbackKind::RGB => self.to_rgb().unwrap(),
516      ColorFallbackKind::P3 => self.to_p3().unwrap(),
517      ColorFallbackKind::LAB => self.to_lab().unwrap(),
518      _ => unreachable!(),
519    }
520  }
521
522  pub(crate) fn get_features(&self) -> Features {
523    let mut features = Features::empty();
524    match self {
525      CssColor::LAB(labcolor) => match &**labcolor {
526        LABColor::LAB(_) | LABColor::LCH(_) => {
527          features |= Features::LabColors;
528        }
529        LABColor::OKLAB(_) | LABColor::OKLCH(_) => {
530          features |= Features::OklabColors;
531        }
532      },
533      CssColor::Predefined(predefined_color) => {
534        features |= Features::ColorFunction;
535        match &**predefined_color {
536          PredefinedColor::DisplayP3(_) => {
537            features |= Features::P3Colors;
538          }
539          _ => {}
540        }
541      }
542      CssColor::Float(_) => {
543        features |= Features::SpaceSeparatedColorNotation;
544      }
545      CssColor::LightDark(light, dark) => {
546        features |= Features::LightDark;
547        features |= light.get_features();
548        features |= dark.get_features();
549      }
550      _ => {}
551    }
552
553    features
554  }
555}
556
557impl IsCompatible for CssColor {
558  fn is_compatible(&self, browsers: Browsers) -> bool {
559    match self {
560      CssColor::CurrentColor | CssColor::RGBA(_) | CssColor::Float(..) => true,
561      CssColor::LAB(lab) => match &**lab {
562        LABColor::LAB(..) | LABColor::LCH(..) => Feature::LabColors.is_compatible(browsers),
563        LABColor::OKLAB(..) | LABColor::OKLCH(..) => Feature::OklabColors.is_compatible(browsers),
564      },
565      CssColor::Predefined(predefined) => match &**predefined {
566        PredefinedColor::DisplayP3(..) => Feature::P3Colors.is_compatible(browsers),
567        _ => Feature::ColorFunction.is_compatible(browsers),
568      },
569      CssColor::LightDark(light, dark) => {
570        Feature::LightDark.is_compatible(browsers) && light.is_compatible(browsers) && dark.is_compatible(browsers)
571      }
572      CssColor::System(system) => system.is_compatible(browsers),
573    }
574  }
575}
576
577impl FallbackValues for CssColor {
578  fn get_fallbacks(&mut self, targets: Targets) -> Vec<CssColor> {
579    let fallbacks = self.get_necessary_fallbacks(targets);
580
581    let mut res = Vec::new();
582    if fallbacks.contains(ColorFallbackKind::RGB) {
583      res.push(self.to_rgb().unwrap());
584    }
585
586    if fallbacks.contains(ColorFallbackKind::P3) {
587      res.push(self.to_p3().unwrap());
588    }
589
590    if fallbacks.contains(ColorFallbackKind::LAB) {
591      *self = self.to_lab().unwrap();
592    }
593
594    res
595  }
596}
597
598impl Default for CssColor {
599  fn default() -> CssColor {
600    CssColor::transparent()
601  }
602}
603
604impl<'i> Parse<'i> for CssColor {
605  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
606    let location = input.current_source_location();
607    let token = input.next()?;
608    match *token {
609      Token::Hash(ref value) | Token::IDHash(ref value) => parse_hash_color(value.as_bytes())
610        .map(|(r, g, b, a)| CssColor::RGBA(RGBA::new(r, g, b, a)))
611        .map_err(|_| location.new_unexpected_token_error(token.clone())),
612      Token::Ident(ref value) => Ok(match_ignore_ascii_case! { value,
613        "currentcolor" => CssColor::CurrentColor,
614        "transparent" => CssColor::RGBA(RGBA::transparent()),
615        _ => {
616          if let Ok((r, g, b)) = parse_named_color(value) {
617            CssColor::RGBA(RGBA { red: r, green: g, blue: b, alpha: 255 })
618          } else if let Ok(system_color) = SystemColor::parse_string(&value) {
619            CssColor::System(system_color)
620          } else {
621            return Err(location.new_unexpected_token_error(token.clone()))
622          }
623        }
624      }),
625      Token::Function(ref name) => parse_color_function(location, name.clone(), input),
626      _ => Err(location.new_unexpected_token_error(token.clone())),
627    }
628  }
629}
630
631impl ToCss for CssColor {
632  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
633    match self {
634      CssColor::CurrentColor => {
635        dest.write_str("currentColor")?;
636        Ok(())
637      }
638      CssColor::RGBA(color) => {
639        if color.alpha == 255 {
640          let hex: u32 = ((color.red as u32) << 16) | ((color.green as u32) << 8) | (color.blue as u32);
641          if let Some(name) = short_color_name(hex) {
642            dest.write_str(name)?;
643            return Ok(());
644          }
645
646          let compact = compact_hex(hex);
647          if hex == expand_hex(compact) {
648            write!(dest, "#{:03x}", compact)?;
649          } else {
650            write!(dest, "#{:06x}", hex)?;
651          }
652        } else {
653          // If the #rrggbbaa syntax is not supported by the browser targets, output rgba()
654          if should_compile!(dest.targets().current, HexAlphaColors) {
655            // If the browser doesn't support `#rrggbbaa` color syntax, it is converted to `transparent` when compressed(minify = true).
656            // https://www.w3.org/TR/css-color-4/#transparent-black
657            if dest.options().minify && color.red == 0 && color.green == 0 && color.blue == 0 && color.alpha == 0 {
658              dest.write_str("transparent")?;
659              return Ok(());
660            } else {
661              dest.write_str("rgba(")?;
662              write!(dest, "{}", color.red)?;
663              dest.delim(',', false)?;
664              write!(dest, "{}", color.green)?;
665              dest.delim(',', false)?;
666              write!(dest, "{}", color.blue)?;
667              dest.delim(',', false)?;
668
669              // Try first with two decimal places, then with three.
670              let mut rounded_alpha = (color.alpha_f32() * 100.0).round() / 100.0;
671              let clamped = (rounded_alpha * 255.0).round().max(0.).min(255.0) as u8;
672              if clamped != color.alpha {
673                rounded_alpha = (color.alpha_f32() * 1000.).round() / 1000.;
674              }
675
676              rounded_alpha.to_css(dest)?;
677              dest.write_char(')')?;
678              return Ok(());
679            }
680          }
681
682          let hex: u32 = ((color.red as u32) << 24)
683            | ((color.green as u32) << 16)
684            | ((color.blue as u32) << 8)
685            | (color.alpha as u32);
686          let compact = compact_hex(hex);
687          if hex == expand_hex(compact) {
688            write!(dest, "#{:04x}", compact)?;
689          } else {
690            write!(dest, "#{:08x}", hex)?;
691          }
692        }
693        Ok(())
694      }
695      CssColor::LAB(lab) => match &**lab {
696        LABColor::LAB(lab) => write_components("lab", lab.l / 100.0, lab.a, lab.b, lab.alpha, dest),
697        LABColor::LCH(lch) => write_components("lch", lch.l / 100.0, lch.c, lch.h, lch.alpha, dest),
698        LABColor::OKLAB(lab) => write_components("oklab", lab.l, lab.a, lab.b, lab.alpha, dest),
699        LABColor::OKLCH(lch) => write_components("oklch", lch.l, lch.c, lch.h, lch.alpha, dest),
700      },
701      CssColor::Predefined(predefined) => write_predefined(predefined, dest),
702      CssColor::Float(float) => {
703        // Serialize as hex.
704        let rgb = RGB::from(**float);
705        CssColor::from(rgb).to_css(dest)
706      }
707      CssColor::LightDark(light, dark) => {
708        if should_compile!(dest.targets().current, LightDark) {
709          dest.write_str("var(--lightningcss-light")?;
710          dest.delim(',', false)?;
711          light.to_css(dest)?;
712          dest.write_char(')')?;
713          dest.whitespace()?;
714          dest.write_str("var(--lightningcss-dark")?;
715          dest.delim(',', false)?;
716          dark.to_css(dest)?;
717          dest.write_char(')')?;
718          return Ok(());
719        }
720
721        dest.write_str("light-dark(")?;
722        light.to_css(dest)?;
723        dest.delim(',', false)?;
724        dark.to_css(dest)?;
725        dest.write_char(')')?;
726        Ok(())
727      }
728      CssColor::System(system) => system.to_css(dest),
729    }
730  }
731}
732
733// From esbuild: https://github.com/evanw/esbuild/blob/18e13bdfdca5cd3c7a2fae1a8bd739f8f891572c/internal/css_parser/css_decls_color.go#L218
734// 0xAABBCCDD => 0xABCD
735fn compact_hex(v: u32) -> u32 {
736  return ((v & 0x0FF00000) >> 12) | ((v & 0x00000FF0) >> 4);
737}
738
739// 0xABCD => 0xAABBCCDD
740fn expand_hex(v: u32) -> u32 {
741  return ((v & 0xF000) << 16) | ((v & 0xFF00) << 12) | ((v & 0x0FF0) << 8) | ((v & 0x00FF) << 4) | (v & 0x000F);
742}
743
744fn short_color_name(v: u32) -> Option<&'static str> {
745  // These names are shorter than their hex codes
746  let s = match v {
747    0x000080 => "navy",
748    0x008000 => "green",
749    0x008080 => "teal",
750    0x4b0082 => "indigo",
751    0x800000 => "maroon",
752    0x800080 => "purple",
753    0x808000 => "olive",
754    0x808080 => "gray",
755    0xa0522d => "sienna",
756    0xa52a2a => "brown",
757    0xc0c0c0 => "silver",
758    0xcd853f => "peru",
759    0xd2b48c => "tan",
760    0xda70d6 => "orchid",
761    0xdda0dd => "plum",
762    0xee82ee => "violet",
763    0xf0e68c => "khaki",
764    0xf0ffff => "azure",
765    0xf5deb3 => "wheat",
766    0xf5f5dc => "beige",
767    0xfa8072 => "salmon",
768    0xfaf0e6 => "linen",
769    0xff0000 => "red",
770    0xff6347 => "tomato",
771    0xff7f50 => "coral",
772    0xffa500 => "orange",
773    0xffc0cb => "pink",
774    0xffd700 => "gold",
775    0xffe4c4 => "bisque",
776    0xfffafa => "snow",
777    0xfffff0 => "ivory",
778    _ => return None,
779  };
780
781  Some(s)
782}
783
784struct RelativeComponentParser {
785  names: (&'static str, &'static str, &'static str),
786  components: (f32, f32, f32, f32),
787  types: (ChannelType, ChannelType, ChannelType),
788}
789
790impl RelativeComponentParser {
791  fn new<T: ColorSpace>(color: &T) -> Self {
792    Self {
793      names: color.channels(),
794      components: color.components(),
795      types: color.types(),
796    }
797  }
798
799  fn alpha_only(alpha: f32) -> Self {
800    Self {
801      names: ("", "", ""),
802      components: (0.0, 0.0, 0.0, alpha),
803      types: (ChannelType::empty(), ChannelType::empty(), ChannelType::empty()),
804    }
805  }
806
807  fn get_ident(&self, ident: &str, allowed_types: ChannelType) -> Option<(f32, ChannelType)> {
808    if ident.eq_ignore_ascii_case(self.names.0) && allowed_types.intersects(self.types.0) {
809      return Some((self.components.0, self.types.0));
810    }
811
812    if ident.eq_ignore_ascii_case(self.names.1) && allowed_types.intersects(self.types.1) {
813      return Some((self.components.1, self.types.1));
814    }
815
816    if ident.eq_ignore_ascii_case(self.names.2) && allowed_types.intersects(self.types.2) {
817      return Some((self.components.2, self.types.2));
818    }
819
820    if ident.eq_ignore_ascii_case("alpha")
821      && allowed_types.intersects(ChannelType::Number | ChannelType::Percentage)
822    {
823      return Some((self.components.3, ChannelType::Number));
824    }
825
826    None
827  }
828
829  fn parse_ident<'i, 't>(
830    &self,
831    input: &mut Parser<'i, 't>,
832    allowed_types: ChannelType,
833  ) -> Result<(f32, ChannelType), ParseError<'i, ParserError<'i>>> {
834    match self.get_ident(input.expect_ident()?.as_ref(), allowed_types) {
835      Some(v) => Ok(v),
836      None => Err(input.new_error_for_next_token()),
837    }
838  }
839}
840
841impl<'i> ColorParser<'i> for RelativeComponentParser {
842  type Output = cssparser_color::Color;
843  type Error = ParserError<'i>;
844
845  fn parse_angle_or_number<'t>(
846    &self,
847    input: &mut Parser<'i, 't>,
848  ) -> Result<AngleOrNumber, ParseError<'i, Self::Error>> {
849    if let Ok((value, ty)) =
850      input.try_parse(|input| self.parse_ident(input, ChannelType::Angle | ChannelType::Number))
851    {
852      return Ok(match ty {
853        ChannelType::Angle => AngleOrNumber::Angle { degrees: value },
854        ChannelType::Number => AngleOrNumber::Number { value },
855        _ => unreachable!(),
856      });
857    }
858
859    if let Ok(value) = input.try_parse(|input| -> Result<AngleOrNumber, ParseError<'i, ParserError<'i>>> {
860      match Calc::parse_with(input, &|ident| {
861        self
862          .get_ident(ident, ChannelType::Angle | ChannelType::Number)
863          .map(|(value, ty)| match ty {
864            ChannelType::Angle => Calc::Value(Box::new(Angle::Deg(value))),
865            ChannelType::Number => Calc::Number(value),
866            _ => unreachable!(),
867          })
868      }) {
869        Ok(Calc::Value(v)) => Ok(AngleOrNumber::Angle {
870          degrees: v.to_degrees(),
871        }),
872        Ok(Calc::Number(v)) => Ok(AngleOrNumber::Number { value: v }),
873        _ => Err(input.new_custom_error(ParserError::InvalidValue)),
874      }
875    }) {
876      return Ok(value);
877    }
878
879    Err(input.new_error_for_next_token())
880  }
881
882  fn parse_number<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i, Self::Error>> {
883    if let Ok((value, _)) = input.try_parse(|input| self.parse_ident(input, ChannelType::Number)) {
884      return Ok(value);
885    }
886
887    match Calc::parse_with(input, &|ident| {
888      self.get_ident(ident, ChannelType::Number).map(|(v, _)| Calc::Number(v))
889    }) {
890      Ok(Calc::Value(v)) => Ok(*v),
891      Ok(Calc::Number(n)) => Ok(n),
892      _ => Err(input.new_error_for_next_token()),
893    }
894  }
895
896  fn parse_percentage<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i, Self::Error>> {
897    if let Ok((value, _)) = input.try_parse(|input| self.parse_ident(input, ChannelType::Percentage)) {
898      return Ok(value);
899    }
900
901    if let Ok(value) = input.try_parse(|input| -> Result<Percentage, ParseError<'i, ParserError<'i>>> {
902      match Calc::parse_with(input, &|ident| {
903        self
904          .get_ident(ident, ChannelType::Percentage)
905          .map(|(v, _)| Calc::Value(Box::new(Percentage(v))))
906      }) {
907        Ok(Calc::Value(v)) => Ok(*v),
908        _ => Err(input.new_custom_error(ParserError::InvalidValue)),
909      }
910    }) {
911      return Ok(value.0);
912    }
913
914    Err(input.new_error_for_next_token())
915  }
916
917  fn parse_number_or_percentage<'t>(
918    &self,
919    input: &mut Parser<'i, 't>,
920  ) -> Result<NumberOrPercentage, ParseError<'i, Self::Error>> {
921    if let Ok((value, ty)) =
922      input.try_parse(|input| self.parse_ident(input, ChannelType::Percentage | ChannelType::Number))
923    {
924      return Ok(match ty {
925        ChannelType::Percentage => NumberOrPercentage::Percentage { unit_value: value },
926        ChannelType::Number => NumberOrPercentage::Number { value },
927        _ => unreachable!(),
928      });
929    }
930
931    if let Ok(value) = input.try_parse(|input| -> Result<NumberOrPercentage, ParseError<'i, ParserError<'i>>> {
932      match Calc::parse_with(input, &|ident| {
933        self
934          .get_ident(ident, ChannelType::Percentage | ChannelType::Number)
935          .map(|(value, ty)| match ty {
936            ChannelType::Percentage => Calc::Value(Box::new(Percentage(value))),
937            ChannelType::Number => Calc::Number(value),
938            _ => unreachable!(),
939          })
940      }) {
941        Ok(Calc::Value(v)) => Ok(NumberOrPercentage::Percentage { unit_value: v.0 }),
942        Ok(Calc::Number(v)) => Ok(NumberOrPercentage::Number { value: v }),
943        _ => Err(input.new_custom_error(ParserError::InvalidValue)),
944      }
945    }) {
946      return Ok(value);
947    }
948
949    Err(input.new_error_for_next_token())
950  }
951}
952
953pub(crate) trait LightDarkColor {
954  fn light_dark(light: Self, dark: Self) -> Self;
955}
956
957impl LightDarkColor for CssColor {
958  #[inline]
959  fn light_dark(light: Self, dark: Self) -> Self {
960    CssColor::LightDark(Box::new(light), Box::new(dark))
961  }
962}
963
964pub(crate) struct ComponentParser {
965  pub allow_none: bool,
966  from: Option<RelativeComponentParser>,
967}
968
969impl ComponentParser {
970  pub fn new(allow_none: bool) -> Self {
971    Self { allow_none, from: None }
972  }
973
974  pub fn parse_relative<
975    'i,
976    't,
977    T: TryFrom<CssColor> + ColorSpace,
978    C: LightDarkColor,
979    P: Fn(&mut Parser<'i, 't>, &mut Self) -> Result<C, ParseError<'i, ParserError<'i>>>,
980  >(
981    &mut self,
982    input: &mut Parser<'i, 't>,
983    parse: P,
984  ) -> Result<C, ParseError<'i, ParserError<'i>>> {
985    if input.try_parse(|input| input.expect_ident_matching("from")).is_ok() {
986      let from = CssColor::parse(input)?;
987      return self.parse_from::<T, C, P>(from, input, &parse);
988    }
989
990    parse(input, self)
991  }
992
993  fn parse_from<
994    'i,
995    't,
996    T: TryFrom<CssColor> + ColorSpace,
997    C: LightDarkColor,
998    P: Fn(&mut Parser<'i, 't>, &mut Self) -> Result<C, ParseError<'i, ParserError<'i>>>,
999  >(
1000    &mut self,
1001    from: CssColor,
1002    input: &mut Parser<'i, 't>,
1003    parse: &P,
1004  ) -> Result<C, ParseError<'i, ParserError<'i>>> {
1005    if let CssColor::LightDark(light, dark) = from {
1006      let state = input.state();
1007      let light = self.parse_from::<T, C, P>(*light, input, parse)?;
1008      input.reset(&state);
1009      let dark = self.parse_from::<T, C, P>(*dark, input, parse)?;
1010      return Ok(C::light_dark(light, dark));
1011    }
1012
1013    let from = T::try_from(from)
1014      .map_err(|_| input.new_custom_error(ParserError::InvalidValue))?
1015      .resolve();
1016    self.from = Some(RelativeComponentParser::new(&from));
1017
1018    parse(input, self)
1019  }
1020}
1021
1022impl<'i> ColorParser<'i> for ComponentParser {
1023  type Output = cssparser_color::Color;
1024  type Error = ParserError<'i>;
1025
1026  fn parse_angle_or_number<'t>(
1027    &self,
1028    input: &mut Parser<'i, 't>,
1029  ) -> Result<AngleOrNumber, ParseError<'i, Self::Error>> {
1030    if let Some(from) = &self.from {
1031      if let Ok(res) = input.try_parse(|input| from.parse_angle_or_number(input)) {
1032        return Ok(res);
1033      }
1034    }
1035
1036    if let Ok(angle) = input.try_parse(Angle::parse) {
1037      Ok(AngleOrNumber::Angle {
1038        degrees: angle.to_degrees(),
1039      })
1040    } else if let Ok(value) = input.try_parse(CSSNumber::parse) {
1041      Ok(AngleOrNumber::Number { value })
1042    } else if self.allow_none {
1043      input.expect_ident_matching("none")?;
1044      Ok(AngleOrNumber::Number { value: f32::NAN })
1045    } else {
1046      Err(input.new_custom_error(ParserError::InvalidValue))
1047    }
1048  }
1049
1050  fn parse_number<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i, Self::Error>> {
1051    if let Some(from) = &self.from {
1052      if let Ok(res) = input.try_parse(|input| from.parse_number(input)) {
1053        return Ok(res);
1054      }
1055    }
1056
1057    if let Ok(val) = input.try_parse(CSSNumber::parse) {
1058      return Ok(val);
1059    } else if self.allow_none {
1060      input.expect_ident_matching("none")?;
1061      Ok(f32::NAN)
1062    } else {
1063      Err(input.new_custom_error(ParserError::InvalidValue))
1064    }
1065  }
1066
1067  fn parse_percentage<'t>(&self, input: &mut Parser<'i, 't>) -> Result<f32, ParseError<'i, Self::Error>> {
1068    if let Some(from) = &self.from {
1069      if let Ok(res) = input.try_parse(|input| from.parse_percentage(input)) {
1070        return Ok(res);
1071      }
1072    }
1073
1074    if let Ok(val) = input.try_parse(Percentage::parse) {
1075      return Ok(val.0);
1076    } else if self.allow_none {
1077      input.expect_ident_matching("none")?;
1078      Ok(f32::NAN)
1079    } else {
1080      Err(input.new_custom_error(ParserError::InvalidValue))
1081    }
1082  }
1083
1084  fn parse_number_or_percentage<'t>(
1085    &self,
1086    input: &mut Parser<'i, 't>,
1087  ) -> Result<NumberOrPercentage, ParseError<'i, Self::Error>> {
1088    if let Some(from) = &self.from {
1089      if let Ok(res) = input.try_parse(|input| from.parse_number_or_percentage(input)) {
1090        return Ok(res);
1091      }
1092    }
1093
1094    if let Ok(value) = input.try_parse(CSSNumber::parse) {
1095      Ok(NumberOrPercentage::Number { value })
1096    } else if let Ok(value) = input.try_parse(Percentage::parse) {
1097      Ok(NumberOrPercentage::Percentage { unit_value: value.0 })
1098    } else if self.allow_none {
1099      input.expect_ident_matching("none")?;
1100      Ok(NumberOrPercentage::Number { value: f32::NAN })
1101    } else {
1102      Err(input.new_custom_error(ParserError::InvalidValue))
1103    }
1104  }
1105}
1106
1107// https://www.w3.org/TR/css-color-4/#lab-colors
1108fn parse_color_function<'i, 't>(
1109  location: SourceLocation,
1110  function: CowRcStr<'i>,
1111  input: &mut Parser<'i, 't>,
1112) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1113  let mut parser = ComponentParser::new(true);
1114
1115  match_ignore_ascii_case! {&*function,
1116    "lab" => {
1117      parse_lab::<LAB, _>(input, &mut parser, 100.0, 125.0, |l, a, b, alpha| {
1118        LABColor::LAB(LAB { l, a, b, alpha })
1119      })
1120    },
1121    "oklab" => {
1122      parse_lab::<OKLAB, _>(input, &mut parser, 1.0, 0.4, |l, a, b, alpha| {
1123        LABColor::OKLAB(OKLAB { l, a, b, alpha })
1124      })
1125    },
1126    "lch" => {
1127      parse_lch::<LCH, _>(input, &mut parser, 100.0, 150.0, |l, c, h, alpha| {
1128        LABColor::LCH(LCH { l, c, h, alpha })
1129      })
1130    },
1131    "oklch" => {
1132      parse_lch::<OKLCH, _>(input, &mut parser, 1.0, 0.4, |l, c, h, alpha| {
1133        LABColor::OKLCH(OKLCH { l, c, h, alpha })
1134      })
1135    },
1136    "color" => {
1137      let predefined = parse_predefined(input, &mut parser)?;
1138      Ok(predefined)
1139    },
1140    "hsl" | "hsla" => {
1141      parse_hsl_hwb::<HSL, _>(input, &mut parser, true, |h, s, l, a| {
1142        let hsl = HSL { h, s, l, alpha: a };
1143        if !h.is_nan() && !s.is_nan() && !l.is_nan() && !a.is_nan() {
1144          CssColor::RGBA(hsl.into())
1145        } else {
1146          CssColor::Float(Box::new(FloatColor::HSL(hsl)))
1147        }
1148      })
1149    },
1150    "hwb" => {
1151      parse_hsl_hwb::<HWB, _>(input, &mut parser, false, |h, w, b, a| {
1152        let hwb = HWB { h, w, b, alpha: a };
1153        if !h.is_nan() && !w.is_nan() && !b.is_nan() && !a.is_nan() {
1154          CssColor::RGBA(hwb.into())
1155        } else {
1156          CssColor::Float(Box::new(FloatColor::HWB(hwb)))
1157        }
1158      })
1159    },
1160    "rgb" | "rgba" => {
1161       parse_rgb(input, &mut parser)
1162    },
1163    "alpha" => {
1164      parse_relative_alpha(input)
1165    },
1166    "color-mix" => {
1167      input.parse_nested_block(parse_color_mix)
1168    },
1169    "light-dark" => {
1170      input.parse_nested_block(|input| {
1171        let light = match CssColor::parse(input)? {
1172          CssColor::LightDark(light, _) => light,
1173          light => Box::new(light)
1174        };
1175        input.expect_comma()?;
1176        let dark = match CssColor::parse(input)? {
1177          CssColor::LightDark(_, dark) => dark,
1178          dark => Box::new(dark)
1179        };
1180
1181        if light==dark {
1182            return Ok(*light);
1183        }
1184
1185        Ok(CssColor::LightDark(light, dark))
1186      })
1187    },
1188    _ => Err(location.new_unexpected_token_error(
1189      cssparser::Token::Ident(function.clone())
1190    ))
1191  }
1192}
1193
1194/// Parses the lab() and oklab() functions.
1195#[inline]
1196fn parse_lab<'i, 't, T: TryFrom<CssColor> + ColorSpace, F: Fn(f32, f32, f32, f32) -> LABColor>(
1197  input: &mut Parser<'i, 't>,
1198  parser: &mut ComponentParser,
1199  l_basis: f32,
1200  ab_basis: f32,
1201  f: F,
1202) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1203  // https://www.w3.org/TR/css-color-4/#funcdef-lab
1204  input.parse_nested_block(|input| {
1205    parser.parse_relative::<T, _, _>(input, |input, parser| {
1206      // f32::max() does not propagate NaN, so use clamp for now until f32::maximum() is stable.
1207      let l = parse_number_or_percentage(input, parser, l_basis)?.clamp(0.0, f32::MAX);
1208      let a = parse_number_or_percentage(input, parser, ab_basis)?;
1209      let b = parse_number_or_percentage(input, parser, ab_basis)?;
1210      let alpha = parse_alpha(input, parser)?;
1211      let lab = f(l, a, b, alpha);
1212
1213      Ok(CssColor::LAB(Box::new(lab)))
1214    })
1215  })
1216}
1217
1218/// Parses the lch() and oklch() functions.
1219#[inline]
1220fn parse_lch<'i, 't, T: TryFrom<CssColor> + ColorSpace, F: Fn(f32, f32, f32, f32) -> LABColor>(
1221  input: &mut Parser<'i, 't>,
1222  parser: &mut ComponentParser,
1223  l_basis: f32,
1224  c_basis: f32,
1225  f: F,
1226) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1227  // https://www.w3.org/TR/css-color-4/#funcdef-lch
1228  input.parse_nested_block(|input| {
1229    parser.parse_relative::<T, _, _>(input, |input, parser| {
1230      if let Some(from) = &mut parser.from {
1231        // Relative angles should be normalized.
1232        // https://www.w3.org/TR/css-color-5/#relative-LCH
1233        from.components.2 %= 360.0;
1234        if from.components.2 < 0.0 {
1235          from.components.2 += 360.0;
1236        }
1237      }
1238
1239      let l = parse_number_or_percentage(input, parser, l_basis)?.clamp(0.0, f32::MAX);
1240      let c = parse_number_or_percentage(input, parser, c_basis)?.clamp(0.0, f32::MAX);
1241      let h = parse_angle_or_number(input, parser)?;
1242      let alpha = parse_alpha(input, parser)?;
1243      let lab = f(l, c, h, alpha);
1244
1245      Ok(CssColor::LAB(Box::new(lab)))
1246    })
1247  })
1248}
1249
1250/// Parses the alpha() function.
1251/// alpha() = alpha([from <color>] [ / [<alpha-value> | none] ]? )
1252#[inline]
1253fn parse_relative_alpha<'i, 't>(input: &mut Parser<'i, 't>) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1254  // https://drafts.csswg.org/css-color-5/#relative-alpha
1255  input.parse_nested_block(|input| {
1256    input.expect_ident_matching("from")?;
1257    let from = CssColor::parse(input)?;
1258    let res = parse_relative_alpha_from(from, input)?;
1259    input.expect_exhausted()?;
1260    Ok(res)
1261  })
1262}
1263
1264#[inline]
1265fn parse_relative_alpha_from<'i, 't>(
1266  from: CssColor,
1267  input: &mut Parser<'i, 't>,
1268) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1269  if let CssColor::LightDark(light, dark) = from {
1270    let state = input.state();
1271    let light = parse_relative_alpha_from(*light, input)?;
1272    input.reset(&state);
1273    let dark = parse_relative_alpha_from(*dark, input)?;
1274    return Ok(CssColor::LightDark(Box::new(light), Box::new(dark)));
1275  }
1276
1277  let from_alpha = from.alpha().map_err(|_| input.new_custom_error(ParserError::InvalidValue))?;
1278  let alpha = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
1279    let parser = ComponentParser {
1280      allow_none: true,
1281      from: Some(RelativeComponentParser::alpha_only(from_alpha)),
1282    };
1283    parse_number_or_percentage(input, &parser, 1.0)?.clamp(0.0, 1.0)
1284  } else {
1285    from_alpha
1286  };
1287
1288  Ok(from.with_alpha(alpha))
1289}
1290
1291#[inline]
1292fn parse_predefined<'i, 't>(
1293  input: &mut Parser<'i, 't>,
1294  parser: &mut ComponentParser,
1295) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1296  // https://www.w3.org/TR/css-color-4/#color-function
1297  let res = input.parse_nested_block(|input| {
1298    let from = if input.try_parse(|input| input.expect_ident_matching("from")).is_ok() {
1299      Some(CssColor::parse(input)?)
1300    } else {
1301      None
1302    };
1303
1304    let colorspace = input.expect_ident_cloned()?;
1305
1306    if let Some(CssColor::LightDark(light, dark)) = from {
1307      let state = input.state();
1308      let light = parse_predefined_relative(input, parser, &colorspace, Some(&*light))?;
1309      input.reset(&state);
1310      let dark = parse_predefined_relative(input, parser, &colorspace, Some(&*dark))?;
1311      return Ok(CssColor::LightDark(Box::new(light), Box::new(dark)));
1312    }
1313
1314    parse_predefined_relative(input, parser, &colorspace, from.as_ref())
1315  })?;
1316
1317  Ok(res)
1318}
1319
1320#[inline]
1321fn parse_predefined_relative<'i, 't>(
1322  input: &mut Parser<'i, 't>,
1323  parser: &mut ComponentParser,
1324  colorspace: &CowRcStr<'i>,
1325  from: Option<&CssColor>,
1326) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1327  let location = input.current_source_location();
1328  if let Some(from) = from {
1329    let handle_error = |_| input.new_custom_error(ParserError::InvalidValue);
1330    parser.from = Some(match_ignore_ascii_case! { &*&colorspace,
1331      "srgb" => RelativeComponentParser::new(&SRGB::try_from(from).map_err(handle_error)?.resolve_missing()),
1332      "srgb-linear" => RelativeComponentParser::new(&SRGBLinear::try_from(from).map_err(handle_error)?.resolve_missing()),
1333      "display-p3" => RelativeComponentParser::new(&P3::try_from(from).map_err(handle_error)?.resolve_missing()),
1334      "a98-rgb" => RelativeComponentParser::new(&A98::try_from(from).map_err(handle_error)?.resolve_missing()),
1335      "prophoto-rgb" => RelativeComponentParser::new(&ProPhoto::try_from(from).map_err(handle_error)?.resolve_missing()),
1336      "rec2020" => RelativeComponentParser::new(&Rec2020::try_from(from).map_err(handle_error)?.resolve_missing()),
1337      "xyz-d50" => RelativeComponentParser::new(&XYZd50::try_from(from).map_err(handle_error)?.resolve_missing()),
1338      "xyz" | "xyz-d65" => RelativeComponentParser::new(&XYZd65::try_from(from).map_err(handle_error)?.resolve_missing()),
1339      _ => return Err(location.new_unexpected_token_error(
1340        cssparser::Token::Ident(colorspace.clone())
1341      ))
1342    });
1343  }
1344
1345  // Out of gamut values should not be clamped, i.e. values < 0 or > 1 should be preserved.
1346  // The browser will gamut-map the color for the target device that it is rendered on.
1347  let a = input.try_parse(|input| parse_number_or_percentage(input, parser, 1.0))?;
1348  let b = input.try_parse(|input| parse_number_or_percentage(input, parser, 1.0))?;
1349  let c = input.try_parse(|input| parse_number_or_percentage(input, parser, 1.0))?;
1350  let alpha = parse_alpha(input, parser)?;
1351
1352  let res = match_ignore_ascii_case! { &*&colorspace,
1353    "srgb" => PredefinedColor::SRGB(SRGB { r: a, g: b, b: c, alpha }),
1354    "srgb-linear" => PredefinedColor::SRGBLinear(SRGBLinear { r: a, g: b, b: c, alpha }),
1355    "display-p3" => PredefinedColor::DisplayP3(P3 { r: a, g: b, b: c, alpha }),
1356    "a98-rgb" => PredefinedColor::A98(A98 { r: a, g: b, b: c, alpha }),
1357    "prophoto-rgb" => PredefinedColor::ProPhoto(ProPhoto { r: a, g: b, b: c, alpha }),
1358    "rec2020" => PredefinedColor::Rec2020(Rec2020 { r: a, g: b, b: c, alpha }),
1359    "xyz-d50" => PredefinedColor::XYZd50(XYZd50 { x: a, y: b, z: c, alpha}),
1360    "xyz" | "xyz-d65" => PredefinedColor::XYZd65(XYZd65 { x: a, y: b, z: c, alpha }),
1361    _ => return Err(location.new_unexpected_token_error(
1362      cssparser::Token::Ident(colorspace.clone())
1363    ))
1364  };
1365
1366  Ok(CssColor::Predefined(Box::new(res)))
1367}
1368
1369/// Parses the hsl() and hwb() functions.
1370/// The results of this function are stored as floating point if there are any `none` components.
1371#[inline]
1372fn parse_hsl_hwb<'i, 't, T: TryFrom<CssColor> + ColorSpace, F: Fn(f32, f32, f32, f32) -> CssColor>(
1373  input: &mut Parser<'i, 't>,
1374  parser: &mut ComponentParser,
1375  allows_legacy: bool,
1376  f: F,
1377) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1378  // https://drafts.csswg.org/css-color-4/#the-hsl-notation
1379  input.parse_nested_block(|input| {
1380    parser.parse_relative::<T, _, _>(input, |input, parser| {
1381      let (h, a, b, is_legacy) = parse_hsl_hwb_components::<T>(input, parser, allows_legacy)?;
1382      let alpha = if is_legacy {
1383        parse_legacy_alpha(input, parser)?
1384      } else {
1385        parse_alpha(input, parser)?
1386      };
1387
1388      Ok(f(h, a, b, alpha))
1389    })
1390  })
1391}
1392
1393#[inline]
1394pub(crate) fn parse_hsl_hwb_components<'i, 't, T: TryFrom<CssColor> + ColorSpace>(
1395  input: &mut Parser<'i, 't>,
1396  parser: &mut ComponentParser,
1397  allows_legacy: bool,
1398) -> Result<(f32, f32, f32, bool), ParseError<'i, ParserError<'i>>> {
1399  let h = parse_angle_or_number(input, parser)?;
1400  let is_legacy_syntax =
1401    allows_legacy && parser.from.is_none() && !h.is_nan() && input.try_parse(|p| p.expect_comma()).is_ok();
1402  let a = parse_number_or_percentage(input, parser, 100.0)?.clamp(0.0, 100.0);
1403  if is_legacy_syntax {
1404    input.expect_comma()?;
1405  }
1406  let b = parse_number_or_percentage(input, parser, 100.0)?.clamp(0.0, 100.0);
1407  if is_legacy_syntax && (a.is_nan() || b.is_nan()) {
1408    return Err(input.new_custom_error(ParserError::InvalidValue));
1409  }
1410  Ok((h, a, b, is_legacy_syntax))
1411}
1412
1413#[inline]
1414fn parse_rgb<'i, 't>(
1415  input: &mut Parser<'i, 't>,
1416  parser: &mut ComponentParser,
1417) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
1418  // https://drafts.csswg.org/css-color-4/#rgb-functions
1419  input.parse_nested_block(|input| {
1420    parser.parse_relative::<RGB, _, _>(input, |input, parser| {
1421      let (r, g, b, is_legacy) = parse_rgb_components(input, parser)?;
1422      let alpha = if is_legacy {
1423        parse_legacy_alpha(input, parser)?
1424      } else {
1425        parse_alpha(input, parser)?
1426      };
1427
1428      if !r.is_nan() && !g.is_nan() && !b.is_nan() && !alpha.is_nan() {
1429        if is_legacy {
1430          Ok(CssColor::RGBA(RGBA::new(r as u8, g as u8, b as u8, alpha)))
1431        } else {
1432          Ok(CssColor::RGBA(RGBA::from_floats(
1433            r / 255.0,
1434            g / 255.0,
1435            b / 255.0,
1436            alpha,
1437          )))
1438        }
1439      } else {
1440        Ok(CssColor::Float(Box::new(FloatColor::RGB(RGB { r, g, b, alpha }))))
1441      }
1442    })
1443  })
1444}
1445
1446#[inline]
1447pub(crate) fn parse_rgb_components<'i, 't>(
1448  input: &mut Parser<'i, 't>,
1449  parser: &mut ComponentParser,
1450) -> Result<(f32, f32, f32, bool), ParseError<'i, ParserError<'i>>> {
1451  let red = parser.parse_number_or_percentage(input)?;
1452  let is_legacy_syntax =
1453    parser.from.is_none() && !red.unit_value().is_nan() && input.try_parse(|p| p.expect_comma()).is_ok();
1454  let (r, g, b) = if is_legacy_syntax {
1455    match red {
1456      NumberOrPercentage::Number { value } => {
1457        let r = value.round().clamp(0.0, 255.0);
1458        let g = parser.parse_number(input)?.round().clamp(0.0, 255.0);
1459        input.expect_comma()?;
1460        let b = parser.parse_number(input)?.round().clamp(0.0, 255.0);
1461        (r, g, b)
1462      }
1463      NumberOrPercentage::Percentage { unit_value } => {
1464        let r = (unit_value * 255.0).round().clamp(0.0, 255.0);
1465        let g = (parser.parse_percentage(input)? * 255.0).round().clamp(0.0, 255.0);
1466        input.expect_comma()?;
1467        let b = (parser.parse_percentage(input)? * 255.0).round().clamp(0.0, 255.0);
1468        (r, g, b)
1469      }
1470    }
1471  } else {
1472    #[inline]
1473    fn get_component<'i, 't>(value: NumberOrPercentage) -> f32 {
1474      match value {
1475        NumberOrPercentage::Number { value } if value.is_nan() => value,
1476        NumberOrPercentage::Number { value } => value.round().clamp(0.0, 255.0),
1477        NumberOrPercentage::Percentage { unit_value } => (unit_value * 255.0).round().clamp(0.0, 255.0),
1478      }
1479    }
1480
1481    let r = get_component(red);
1482    let g = get_component(parser.parse_number_or_percentage(input)?);
1483    let b = get_component(parser.parse_number_or_percentage(input)?);
1484    (r, g, b)
1485  };
1486
1487  if is_legacy_syntax && (g.is_nan() || b.is_nan()) {
1488    return Err(input.new_custom_error(ParserError::InvalidValue));
1489  }
1490  Ok((r, g, b, is_legacy_syntax))
1491}
1492
1493#[inline]
1494fn parse_angle_or_number<'i, 't>(
1495  input: &mut Parser<'i, 't>,
1496  parser: &ComponentParser,
1497) -> Result<f32, ParseError<'i, ParserError<'i>>> {
1498  Ok(match parser.parse_angle_or_number(input)? {
1499    AngleOrNumber::Number { value } => value,
1500    AngleOrNumber::Angle { degrees } => degrees,
1501  })
1502}
1503
1504#[inline]
1505fn parse_number_or_percentage<'i, 't>(
1506  input: &mut Parser<'i, 't>,
1507  parser: &ComponentParser,
1508  percent_basis: f32,
1509) -> Result<f32, ParseError<'i, ParserError<'i>>> {
1510  Ok(match parser.parse_number_or_percentage(input)? {
1511    NumberOrPercentage::Number { value } => value,
1512    NumberOrPercentage::Percentage { unit_value } => unit_value * percent_basis,
1513  })
1514}
1515
1516#[inline]
1517fn parse_alpha<'i, 't>(
1518  input: &mut Parser<'i, 't>,
1519  parser: &ComponentParser,
1520) -> Result<f32, ParseError<'i, ParserError<'i>>> {
1521  let res = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
1522    parse_number_or_percentage(input, parser, 1.0)?.clamp(0.0, 1.0)
1523  } else if let Some(from) = &parser.from {
1524    from.components.3
1525  } else {
1526    1.0
1527  };
1528  Ok(res)
1529}
1530
1531#[inline]
1532fn parse_legacy_alpha<'i, 't>(
1533  input: &mut Parser<'i, 't>,
1534  parser: &ComponentParser,
1535) -> Result<f32, ParseError<'i, ParserError<'i>>> {
1536  Ok(if !input.is_exhausted() {
1537    input.expect_comma()?;
1538    parse_number_or_percentage(input, parser, 1.0)?.clamp(0.0, 1.0)
1539  } else {
1540    1.0
1541  })
1542}
1543
1544#[inline]
1545fn write_components<PrinterT: crate::printer::PrinterTrait>(
1546  name: &str,
1547  a: f32,
1548  b: f32,
1549  c: f32,
1550  alpha: f32,
1551  dest: &mut PrinterT,
1552) -> Result<(), PrinterError> {
1553  dest.write_str(name)?;
1554  dest.write_char('(')?;
1555  if a.is_nan() {
1556    dest.write_str("none")?;
1557  } else {
1558    Percentage(a).to_css(dest)?;
1559  }
1560  dest.write_char(' ')?;
1561  write_component(b, dest)?;
1562  dest.write_char(' ')?;
1563  write_component(c, dest)?;
1564  if alpha.is_nan() || (alpha - 1.0).abs() > f32::EPSILON {
1565    dest.delim('/', true)?;
1566    write_component(alpha, dest)?;
1567  }
1568
1569  dest.write_char(')')?;
1570
1571  Ok(())
1572}
1573
1574#[inline]
1575fn write_component<PrinterT: crate::printer::PrinterTrait>(
1576  c: f32,
1577  dest: &mut PrinterT,
1578) -> Result<(), PrinterError> {
1579  if c.is_nan() {
1580    dest.write_str("none")?;
1581  } else {
1582    c.to_css(dest)?;
1583  }
1584  Ok(())
1585}
1586
1587#[inline]
1588fn write_predefined<PrinterT: crate::printer::PrinterTrait>(
1589  predefined: &PredefinedColor,
1590  dest: &mut PrinterT,
1591) -> Result<(), PrinterError> {
1592  use PredefinedColor::*;
1593
1594  let (name, a, b, c, alpha) = match predefined {
1595    SRGB(rgb) => ("srgb", rgb.r, rgb.g, rgb.b, rgb.alpha),
1596    SRGBLinear(rgb) => ("srgb-linear", rgb.r, rgb.g, rgb.b, rgb.alpha),
1597    DisplayP3(rgb) => ("display-p3", rgb.r, rgb.g, rgb.b, rgb.alpha),
1598    A98(rgb) => ("a98-rgb", rgb.r, rgb.g, rgb.b, rgb.alpha),
1599    ProPhoto(rgb) => ("prophoto-rgb", rgb.r, rgb.g, rgb.b, rgb.alpha),
1600    Rec2020(rgb) => ("rec2020", rgb.r, rgb.g, rgb.b, rgb.alpha),
1601    XYZd50(xyz) => ("xyz-d50", xyz.x, xyz.y, xyz.z, xyz.alpha),
1602    // "xyz" has better compatibility (Safari 15) than "xyz-d65", and it is shorter.
1603    XYZd65(xyz) => ("xyz", xyz.x, xyz.y, xyz.z, xyz.alpha),
1604  };
1605
1606  dest.write_str("color(")?;
1607  dest.write_str(name)?;
1608  dest.write_char(' ')?;
1609  write_component(a, dest)?;
1610  dest.write_char(' ')?;
1611  write_component(b, dest)?;
1612  dest.write_char(' ')?;
1613  write_component(c, dest)?;
1614
1615  if alpha.is_nan() || (alpha - 1.0).abs() > f32::EPSILON {
1616    dest.delim('/', true)?;
1617    write_component(alpha, dest)?;
1618  }
1619
1620  dest.write_char(')')?;
1621
1622  Ok(())
1623}
1624
1625bitflags! {
1626  /// A channel type for a color space.
1627  #[derive(PartialEq, Eq, Clone, Copy)]
1628  pub struct ChannelType: u8 {
1629    /// Channel represents a percentage.
1630    const Percentage = 0b001;
1631    /// Channel represents an angle.
1632    const Angle = 0b010;
1633    /// Channel represents a number.
1634    const Number = 0b100;
1635  }
1636}
1637
1638/// A trait for color spaces.
1639pub trait ColorSpace {
1640  /// Returns the raw color component values.
1641  fn components(&self) -> (f32, f32, f32, f32);
1642  /// Returns the channel names for this color space.
1643  fn channels(&self) -> (&'static str, &'static str, &'static str);
1644  /// Returns the channel types for this color space.
1645  fn types(&self) -> (ChannelType, ChannelType, ChannelType);
1646  /// Resolves missing color components (e.g. `none` keywords) in the color.
1647  fn resolve_missing(&self) -> Self;
1648  /// Returns a resolved color by replacing missing (i.e. `none`) components with zero,
1649  /// and performing gamut mapping to ensure the color can be represented within the color space.
1650  fn resolve(&self) -> Self;
1651}
1652
1653macro_rules! define_colorspace {
1654  (
1655    $(#[$outer:meta])*
1656    $vis:vis struct $name:ident {
1657      $(#[$a_meta: meta])*
1658      $a: ident: $at: ident,
1659      $(#[$b_meta: meta])*
1660      $b: ident: $bt: ident,
1661      $(#[$c_meta: meta])*
1662      $c: ident: $ct: ident
1663    }
1664  ) => {
1665    $(#[$outer])*
1666    #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "visitor", derive(Visit))]
1667    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1668    #[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1669    pub struct $name {
1670      $(#[$a_meta])*
1671      pub $a: f32,
1672      $(#[$b_meta])*
1673      pub $b: f32,
1674      $(#[$c_meta])*
1675      pub $c: f32,
1676      /// The alpha component.
1677      pub alpha: f32,
1678    }
1679
1680    impl ColorSpace for $name {
1681      fn components(&self) -> (f32, f32, f32, f32) {
1682        (self.$a, self.$b, self.$c, self.alpha)
1683      }
1684
1685      fn channels(&self) -> (&'static str, &'static str, &'static str) {
1686        (stringify!($a), stringify!($b), stringify!($c))
1687      }
1688
1689      fn types(&self) -> (ChannelType, ChannelType, ChannelType) {
1690        (ChannelType::$at, ChannelType::$bt, ChannelType::$ct)
1691      }
1692
1693      #[inline]
1694      fn resolve_missing(&self) -> Self {
1695        Self {
1696          $a: if self.$a.is_nan() { 0.0 } else { self.$a },
1697          $b: if self.$b.is_nan() { 0.0 } else { self.$b },
1698          $c: if self.$c.is_nan() { 0.0 } else { self.$c },
1699          alpha: if self.alpha.is_nan() { 0.0 } else { self.alpha },
1700        }
1701      }
1702
1703      #[inline]
1704      fn resolve(&self) -> Self {
1705        let mut resolved = self.resolve_missing();
1706        if !resolved.in_gamut() {
1707          resolved = map_gamut(resolved);
1708        }
1709        resolved
1710      }
1711    }
1712  };
1713}
1714
1715define_colorspace! {
1716  /// A color in the [`sRGB`](https://www.w3.org/TR/css-color-4/#predefined-sRGB) color space.
1717  pub struct SRGB {
1718    /// The red component.
1719    r: Number,
1720    /// The green component.
1721    g: Number,
1722    /// The blue component.
1723    b: Number
1724  }
1725}
1726
1727// Copied from an older version of cssparser.
1728/// A color with red, green, blue, and alpha components, in a byte each.
1729#[derive(Clone, Copy, PartialEq, Debug)]
1730pub struct RGBA {
1731  /// The red component.
1732  pub red: u8,
1733  /// The green component.
1734  pub green: u8,
1735  /// The blue component.
1736  pub blue: u8,
1737  /// The alpha component.
1738  pub alpha: u8,
1739}
1740
1741impl RGBA {
1742  /// Constructs a new RGBA value from float components. It expects the red,
1743  /// green, blue and alpha channels in that order, and all values will be
1744  /// clamped to the 0.0 ... 1.0 range.
1745  #[inline]
1746  pub fn from_floats(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
1747    Self::new(clamp_unit_f32(red), clamp_unit_f32(green), clamp_unit_f32(blue), alpha)
1748  }
1749
1750  /// Returns a transparent color.
1751  #[inline]
1752  pub fn transparent() -> Self {
1753    Self::new(0, 0, 0, 0.0)
1754  }
1755
1756  /// Same thing, but with `u8` values instead of floats in the 0 to 1 range.
1757  #[inline]
1758  pub fn new(red: u8, green: u8, blue: u8, alpha: f32) -> Self {
1759    RGBA {
1760      red,
1761      green,
1762      blue,
1763      alpha: clamp_unit_f32(alpha),
1764    }
1765  }
1766
1767  /// Returns the red channel in a floating point number form, from 0 to 1.
1768  #[inline]
1769  pub fn red_f32(&self) -> f32 {
1770    self.red as f32 / 255.0
1771  }
1772
1773  /// Returns the green channel in a floating point number form, from 0 to 1.
1774  #[inline]
1775  pub fn green_f32(&self) -> f32 {
1776    self.green as f32 / 255.0
1777  }
1778
1779  /// Returns the blue channel in a floating point number form, from 0 to 1.
1780  #[inline]
1781  pub fn blue_f32(&self) -> f32 {
1782    self.blue as f32 / 255.0
1783  }
1784
1785  /// Returns the alpha channel in a floating point number form, from 0 to 1.
1786  #[inline]
1787  pub fn alpha_f32(&self) -> f32 {
1788    self.alpha as f32 / 255.0
1789  }
1790}
1791
1792fn clamp_unit_f32(val: f32) -> u8 {
1793  // Whilst scaling by 256 and flooring would provide
1794  // an equal distribution of integers to percentage inputs,
1795  // this is not what Gecko does so we instead multiply by 255
1796  // and round (adding 0.5 and flooring is equivalent to rounding)
1797  //
1798  // Chrome does something similar for the alpha value, but not
1799  // the rgb values.
1800  //
1801  // See https://bugzilla.mozilla.org/show_bug.cgi?id=1340484
1802  //
1803  // Clamping to 256 and rounding after would let 1.0 map to 256, and
1804  // `256.0_f32 as u8` is undefined behavior:
1805  //
1806  // https://github.com/rust-lang/rust/issues/10184
1807  clamp_floor_256_f32(val * 255.)
1808}
1809
1810fn clamp_floor_256_f32(val: f32) -> u8 {
1811  val.round().max(0.).min(255.) as u8
1812}
1813
1814define_colorspace! {
1815  /// A color in the [`RGB`](https://w3c.github.io/csswg-drafts/css-color-4/#rgb-functions) color space.
1816  /// Components are in the 0-255 range.
1817  pub struct RGB {
1818    /// The red component.
1819    r: Number,
1820    /// The green component.
1821    g: Number,
1822    /// The blue component.
1823    b: Number
1824  }
1825}
1826
1827define_colorspace! {
1828  /// A color in the [`sRGB-linear`](https://www.w3.org/TR/css-color-4/#predefined-sRGB-linear) color space.
1829  pub struct SRGBLinear {
1830    /// The red component.
1831    r: Number,
1832    /// The green component.
1833    g: Number,
1834    /// The blue component.
1835    b: Number
1836  }
1837}
1838
1839define_colorspace! {
1840  /// A color in the [`display-p3`](https://www.w3.org/TR/css-color-4/#predefined-display-p3) color space.
1841  pub struct P3 {
1842    /// The red component.
1843    r: Number,
1844    /// The green component.
1845    g: Number,
1846    /// The blue component.
1847    b: Number
1848  }
1849}
1850
1851define_colorspace! {
1852  /// A color in the [`a98-rgb`](https://www.w3.org/TR/css-color-4/#predefined-a98-rgb) color space.
1853  pub struct A98 {
1854    /// The red component.
1855    r: Number,
1856    /// The green component.
1857    g: Number,
1858    /// The blue component.
1859    b: Number
1860  }
1861}
1862
1863define_colorspace! {
1864  /// A color in the [`prophoto-rgb`](https://www.w3.org/TR/css-color-4/#predefined-prophoto-rgb) color space.
1865  pub struct ProPhoto {
1866    /// The red component.
1867    r: Number,
1868    /// The green component.
1869    g: Number,
1870    /// The blue component.
1871    b: Number
1872  }
1873}
1874
1875define_colorspace! {
1876  /// A color in the [`rec2020`](https://www.w3.org/TR/css-color-4/#predefined-rec2020) color space.
1877  pub struct Rec2020 {
1878    /// The red component.
1879    r: Number,
1880    /// The green component.
1881    g: Number,
1882    /// The blue component.
1883    b: Number
1884  }
1885}
1886
1887define_colorspace! {
1888  /// A color in the [CIE Lab](https://www.w3.org/TR/css-color-4/#cie-lab) color space.
1889  pub struct LAB {
1890    /// The lightness component.
1891    l: Number,
1892    /// The a component.
1893    a: Number,
1894    /// The b component.
1895    b: Number
1896  }
1897}
1898
1899define_colorspace! {
1900  /// A color in the [CIE LCH](https://www.w3.org/TR/css-color-4/#cie-lab) color space.
1901  pub struct LCH {
1902    /// The lightness component.
1903    l: Number,
1904    /// The chroma component.
1905    c: Number,
1906    /// The hue component.
1907    h: Angle
1908  }
1909}
1910
1911define_colorspace! {
1912  /// A color in the [OKLab](https://www.w3.org/TR/css-color-4/#ok-lab) color space.
1913  pub struct OKLAB {
1914    /// The lightness component.
1915    l: Number,
1916    /// The a component.
1917    a: Number,
1918    /// The b component.
1919    b: Number
1920  }
1921}
1922
1923define_colorspace! {
1924  /// A color in the [OKLCH](https://www.w3.org/TR/css-color-4/#ok-lab) color space.
1925  pub struct OKLCH {
1926    /// The lightness component.
1927    l: Number,
1928    /// The chroma component.
1929    c: Number,
1930    /// The hue component.
1931    h: Angle
1932  }
1933}
1934
1935define_colorspace! {
1936  /// A color in the [`xyz-d50`](https://www.w3.org/TR/css-color-4/#predefined-xyz) color space.
1937  pub struct XYZd50 {
1938    /// The x component.
1939    x: Number,
1940    /// The y component.
1941    y: Number,
1942    /// The z component.
1943    z: Number
1944  }
1945}
1946
1947define_colorspace! {
1948  /// A color in the [`xyz-d65`](https://www.w3.org/TR/css-color-4/#predefined-xyz) color space.
1949  pub struct XYZd65 {
1950    /// The x component.
1951    x: Number,
1952    /// The y component.
1953    y: Number,
1954    /// The z component.
1955    z: Number
1956  }
1957}
1958
1959define_colorspace! {
1960  /// A color in the [`hsl`](https://www.w3.org/TR/css-color-4/#the-hsl-notation) color space.
1961  pub struct HSL {
1962    /// The hue component.
1963    h: Angle,
1964    /// The saturation component.
1965    s: Number,
1966    /// The lightness component.
1967    l: Number
1968  }
1969}
1970
1971define_colorspace! {
1972  /// A color in the [`hwb`](https://www.w3.org/TR/css-color-4/#the-hwb-notation) color space.
1973  pub struct HWB {
1974    /// The hue component.
1975    h: Angle,
1976    /// The whiteness component.
1977    w: Number,
1978    /// The blackness component.
1979    b: Number
1980  }
1981}
1982
1983macro_rules! via {
1984  ($t: ident -> $u: ident -> $v: ident) => {
1985    impl From<$t> for $v {
1986      #[inline]
1987      fn from(t: $t) -> $v {
1988        let xyz: $u = t.into();
1989        xyz.into()
1990      }
1991    }
1992
1993    impl From<$v> for $t {
1994      #[inline]
1995      fn from(t: $v) -> $t {
1996        let xyz: $u = t.into();
1997        xyz.into()
1998      }
1999    }
2000  };
2001}
2002
2003#[inline]
2004fn rectangular_to_polar(l: f32, a: f32, b: f32) -> (f32, f32, f32) {
2005  // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L375
2006  let mut h = b.atan2(a) * 180.0 / PI;
2007  if h < 0.0 {
2008    h += 360.0;
2009  }
2010  let c = (a.powi(2) + b.powi(2)).sqrt();
2011  h = h % 360.0;
2012  (l, c, h)
2013}
2014
2015#[inline]
2016fn polar_to_rectangular(l: f32, c: f32, h: f32) -> (f32, f32, f32) {
2017  // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L385
2018  let a = c * (h * PI / 180.0).cos();
2019  let b = c * (h * PI / 180.0).sin();
2020  (l, a, b)
2021}
2022
2023impl From<LCH> for LAB {
2024  fn from(lch: LCH) -> LAB {
2025    let lch = lch.resolve_missing();
2026    let (l, a, b) = polar_to_rectangular(lch.l, lch.c, lch.h);
2027    LAB {
2028      l,
2029      a,
2030      b,
2031      alpha: lch.alpha,
2032    }
2033  }
2034}
2035
2036impl From<LAB> for LCH {
2037  fn from(lab: LAB) -> LCH {
2038    let lab = lab.resolve_missing();
2039    let (l, c, h) = rectangular_to_polar(lab.l, lab.a, lab.b);
2040    LCH {
2041      l,
2042      c,
2043      h,
2044      alpha: lab.alpha,
2045    }
2046  }
2047}
2048
2049impl From<OKLCH> for OKLAB {
2050  fn from(lch: OKLCH) -> OKLAB {
2051    let lch = lch.resolve_missing();
2052    let (l, a, b) = polar_to_rectangular(lch.l, lch.c, lch.h);
2053    OKLAB {
2054      l,
2055      a,
2056      b,
2057      alpha: lch.alpha,
2058    }
2059  }
2060}
2061
2062impl From<OKLAB> for OKLCH {
2063  fn from(lab: OKLAB) -> OKLCH {
2064    let lab = lab.resolve_missing();
2065    let (l, c, h) = rectangular_to_polar(lab.l, lab.a, lab.b);
2066    OKLCH {
2067      l,
2068      c,
2069      h,
2070      alpha: lab.alpha,
2071    }
2072  }
2073}
2074
2075const D50: &[f32] = &[0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585];
2076
2077impl From<LAB> for XYZd50 {
2078  fn from(lab: LAB) -> XYZd50 {
2079    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L352
2080    const K: f32 = 24389.0 / 27.0; // 29^3/3^3
2081    const E: f32 = 216.0 / 24389.0; // 6^3/29^3
2082
2083    let lab = lab.resolve_missing();
2084    let l = lab.l;
2085    let a = lab.a;
2086    let b = lab.b;
2087
2088    // compute f, starting with the luminance-related term
2089    let f1 = (l + 16.0) / 116.0;
2090    let f0 = a / 500.0 + f1;
2091    let f2 = f1 - b / 200.0;
2092
2093    // compute xyz
2094    let x = if f0.powi(3) > E {
2095      f0.powi(3)
2096    } else {
2097      (116.0 * f0 - 16.0) / K
2098    };
2099
2100    let y = if l > K * E { ((l + 16.0) / 116.0).powi(3) } else { l / K };
2101
2102    let z = if f2.powi(3) > E {
2103      f2.powi(3)
2104    } else {
2105      (116.0 * f2 - 16.0) / K
2106    };
2107
2108    // Compute XYZ by scaling xyz by reference white
2109    XYZd50 {
2110      x: x * D50[0],
2111      y: y * D50[1],
2112      z: z * D50[2],
2113      alpha: lab.alpha,
2114    }
2115  }
2116}
2117
2118impl From<XYZd50> for XYZd65 {
2119  fn from(xyz: XYZd50) -> XYZd65 {
2120    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L319
2121    const MATRIX: &[f32] = &[
2122      0.9554734527042182,
2123      -0.023098536874261423,
2124      0.0632593086610217,
2125      -0.028369706963208136,
2126      1.0099954580058226,
2127      0.021041398966943008,
2128      0.012314001688319899,
2129      -0.020507696433477912,
2130      1.3303659366080753,
2131    ];
2132
2133    let xyz = xyz.resolve_missing();
2134    let (x, y, z) = multiply_matrix(MATRIX, xyz.x, xyz.y, xyz.z);
2135    XYZd65 {
2136      x,
2137      y,
2138      z,
2139      alpha: xyz.alpha,
2140    }
2141  }
2142}
2143
2144impl From<XYZd65> for XYZd50 {
2145  fn from(xyz: XYZd65) -> XYZd50 {
2146    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L319
2147    const MATRIX: &[f32] = &[
2148      1.0479298208405488,
2149      0.022946793341019088,
2150      -0.05019222954313557,
2151      0.029627815688159344,
2152      0.990434484573249,
2153      -0.01707382502938514,
2154      -0.009243058152591178,
2155      0.015055144896577895,
2156      0.7518742899580008,
2157    ];
2158
2159    let xyz = xyz.resolve_missing();
2160    let (x, y, z) = multiply_matrix(MATRIX, xyz.x, xyz.y, xyz.z);
2161    XYZd50 {
2162      x,
2163      y,
2164      z,
2165      alpha: xyz.alpha,
2166    }
2167  }
2168}
2169
2170impl From<XYZd65> for SRGBLinear {
2171  fn from(xyz: XYZd65) -> SRGBLinear {
2172    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L62
2173    const MATRIX: &[f32] = &[
2174      3.2409699419045226,
2175      -1.537383177570094,
2176      -0.4986107602930034,
2177      -0.9692436362808796,
2178      1.8759675015077202,
2179      0.04155505740717559,
2180      0.05563007969699366,
2181      -0.20397695888897652,
2182      1.0569715142428786,
2183    ];
2184
2185    let xyz = xyz.resolve_missing();
2186    let (r, g, b) = multiply_matrix(MATRIX, xyz.x, xyz.y, xyz.z);
2187    SRGBLinear {
2188      r,
2189      g,
2190      b,
2191      alpha: xyz.alpha,
2192    }
2193  }
2194}
2195
2196#[inline]
2197fn multiply_matrix(m: &[f32], x: f32, y: f32, z: f32) -> (f32, f32, f32) {
2198  let a = m[0] * x + m[1] * y + m[2] * z;
2199  let b = m[3] * x + m[4] * y + m[5] * z;
2200  let c = m[6] * x + m[7] * y + m[8] * z;
2201  (a, b, c)
2202}
2203
2204impl From<SRGBLinear> for SRGB {
2205  #[inline]
2206  fn from(rgb: SRGBLinear) -> SRGB {
2207    let rgb = rgb.resolve_missing();
2208    let (r, g, b) = gam_srgb(rgb.r, rgb.g, rgb.b);
2209    SRGB {
2210      r,
2211      g,
2212      b,
2213      alpha: rgb.alpha,
2214    }
2215  }
2216}
2217
2218fn gam_srgb(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
2219  // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L31
2220  // convert an array of linear-light sRGB values in the range 0.0-1.0
2221  // to gamma corrected form
2222  // https://en.wikipedia.org/wiki/SRGB
2223  // Extended transfer function:
2224  // For negative values, linear portion extends on reflection
2225  // of axis, then uses reflected pow below that
2226
2227  #[inline]
2228  fn gam_srgb_component(c: f32) -> f32 {
2229    let abs = c.abs();
2230    if abs > 0.0031308 {
2231      let sign = if c < 0.0 { -1.0 } else { 1.0 };
2232      return sign * (1.055 * abs.powf(1.0 / 2.4) - 0.055);
2233    }
2234
2235    return 12.92 * c;
2236  }
2237
2238  let r = gam_srgb_component(r);
2239  let g = gam_srgb_component(g);
2240  let b = gam_srgb_component(b);
2241  (r, g, b)
2242}
2243
2244impl From<OKLAB> for XYZd65 {
2245  fn from(lab: OKLAB) -> XYZd65 {
2246    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L418
2247    const LMS_TO_XYZ: &[f32] = &[
2248      1.2268798733741557,
2249      -0.5578149965554813,
2250      0.28139105017721583,
2251      -0.04057576262431372,
2252      1.1122868293970594,
2253      -0.07171106666151701,
2254      -0.07637294974672142,
2255      -0.4214933239627914,
2256      1.5869240244272418,
2257    ];
2258
2259    const OKLAB_TO_LMS: &[f32] = &[
2260      0.99999999845051981432,
2261      0.39633779217376785678,
2262      0.21580375806075880339,
2263      1.0000000088817607767,
2264      -0.1055613423236563494,
2265      -0.063854174771705903402,
2266      1.0000000546724109177,
2267      -0.089484182094965759684,
2268      -1.2914855378640917399,
2269    ];
2270
2271    let lab = lab.resolve_missing();
2272    let (a, b, c) = multiply_matrix(OKLAB_TO_LMS, lab.l, lab.a, lab.b);
2273    let (x, y, z) = multiply_matrix(LMS_TO_XYZ, a.powi(3), b.powi(3), c.powi(3));
2274    XYZd65 {
2275      x,
2276      y,
2277      z,
2278      alpha: lab.alpha,
2279    }
2280  }
2281}
2282
2283impl From<XYZd65> for OKLAB {
2284  fn from(xyz: XYZd65) -> OKLAB {
2285    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L400
2286    const XYZ_TO_LMS: &[f32] = &[
2287      0.8190224432164319,
2288      0.3619062562801221,
2289      -0.12887378261216414,
2290      0.0329836671980271,
2291      0.9292868468965546,
2292      0.03614466816999844,
2293      0.048177199566046255,
2294      0.26423952494422764,
2295      0.6335478258136937,
2296    ];
2297
2298    const LMS_TO_OKLAB: &[f32] = &[
2299      0.2104542553,
2300      0.7936177850,
2301      -0.0040720468,
2302      1.9779984951,
2303      -2.4285922050,
2304      0.4505937099,
2305      0.0259040371,
2306      0.7827717662,
2307      -0.8086757660,
2308    ];
2309
2310    let xyz = xyz.resolve_missing();
2311    let (a, b, c) = multiply_matrix(XYZ_TO_LMS, xyz.x, xyz.y, xyz.z);
2312    let (l, a, b) = multiply_matrix(LMS_TO_OKLAB, a.cbrt(), b.cbrt(), c.cbrt());
2313    OKLAB {
2314      l,
2315      a,
2316      b,
2317      alpha: xyz.alpha,
2318    }
2319  }
2320}
2321
2322impl From<XYZd50> for LAB {
2323  fn from(xyz: XYZd50) -> LAB {
2324    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L332
2325    // Assuming XYZ is relative to D50, convert to CIE LAB
2326    // from CIE standard, which now defines these as a rational fraction
2327    const E: f32 = 216.0 / 24389.0; // 6^3/29^3
2328    const K: f32 = 24389.0 / 27.0; // 29^3/3^3
2329
2330    // compute xyz, which is XYZ scaled relative to reference white
2331    let xyz = xyz.resolve_missing();
2332    let x = xyz.x / D50[0];
2333    let y = xyz.y / D50[1];
2334    let z = xyz.z / D50[2];
2335
2336    // now compute f
2337    let f0 = if x > E { x.cbrt() } else { (K * x + 16.0) / 116.0 };
2338
2339    let f1 = if y > E { y.cbrt() } else { (K * y + 16.0) / 116.0 };
2340
2341    let f2 = if z > E { z.cbrt() } else { (K * z + 16.0) / 116.0 };
2342
2343    let l = (116.0 * f1) - 16.0;
2344    let a = 500.0 * (f0 - f1);
2345    let b = 200.0 * (f1 - f2);
2346    LAB {
2347      l,
2348      a,
2349      b,
2350      alpha: xyz.alpha,
2351    }
2352  }
2353}
2354
2355impl From<SRGB> for SRGBLinear {
2356  fn from(rgb: SRGB) -> SRGBLinear {
2357    let rgb = rgb.resolve_missing();
2358    let (r, g, b) = lin_srgb(rgb.r, rgb.g, rgb.b);
2359    SRGBLinear {
2360      r,
2361      g,
2362      b,
2363      alpha: rgb.alpha,
2364    }
2365  }
2366}
2367
2368fn lin_srgb(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
2369  // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L11
2370  // convert sRGB values where in-gamut values are in the range [0 - 1]
2371  // to linear light (un-companded) form.
2372  // https://en.wikipedia.org/wiki/SRGB
2373  // Extended transfer function:
2374  // for negative values, linear portion is extended on reflection of axis,
2375  // then reflected power function is used.
2376
2377  #[inline]
2378  fn lin_srgb_component(c: f32) -> f32 {
2379    let abs = c.abs();
2380    if abs < 0.04045 {
2381      return c / 12.92;
2382    }
2383
2384    let sign = if c < 0.0 { -1.0 } else { 1.0 };
2385    sign * ((abs + 0.055) / 1.055).powf(2.4)
2386  }
2387
2388  let r = lin_srgb_component(r);
2389  let g = lin_srgb_component(g);
2390  let b = lin_srgb_component(b);
2391  (r, g, b)
2392}
2393
2394impl From<SRGBLinear> for XYZd65 {
2395  fn from(rgb: SRGBLinear) -> XYZd65 {
2396    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L50
2397    // convert an array of linear-light sRGB values to CIE XYZ
2398    // using sRGB's own white, D65 (no chromatic adaptation)
2399    const MATRIX: &[f32] = &[
2400      0.41239079926595934,
2401      0.357584339383878,
2402      0.1804807884018343,
2403      0.21263900587151027,
2404      0.715168678767756,
2405      0.07219231536073371,
2406      0.01933081871559182,
2407      0.11919477979462598,
2408      0.9505321522496607,
2409    ];
2410
2411    let rgb = rgb.resolve_missing();
2412    let (x, y, z) = multiply_matrix(MATRIX, rgb.r, rgb.g, rgb.b);
2413    XYZd65 {
2414      x,
2415      y,
2416      z,
2417      alpha: rgb.alpha,
2418    }
2419  }
2420}
2421
2422impl From<XYZd65> for P3 {
2423  fn from(xyz: XYZd65) -> P3 {
2424    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L105
2425    const MATRIX: &[f32] = &[
2426      2.493496911941425,
2427      -0.9313836179191239,
2428      -0.40271078445071684,
2429      -0.8294889695615747,
2430      1.7626640603183463,
2431      0.023624685841943577,
2432      0.03584583024378447,
2433      -0.07617238926804182,
2434      0.9568845240076872,
2435    ];
2436
2437    let xyz = xyz.resolve_missing();
2438    let (r, g, b) = multiply_matrix(MATRIX, xyz.x, xyz.y, xyz.z);
2439    let (r, g, b) = gam_srgb(r, g, b); // same as sRGB
2440    P3 {
2441      r,
2442      g,
2443      b,
2444      alpha: xyz.alpha,
2445    }
2446  }
2447}
2448
2449impl From<P3> for XYZd65 {
2450  fn from(p3: P3) -> XYZd65 {
2451    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L91
2452    // convert linear-light display-p3 values to CIE XYZ
2453    // using D65 (no chromatic adaptation)
2454    // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
2455    const MATRIX: &[f32] = &[
2456      0.4865709486482162,
2457      0.26566769316909306,
2458      0.1982172852343625,
2459      0.2289745640697488,
2460      0.6917385218365064,
2461      0.079286914093745,
2462      0.0000000000000000,
2463      0.04511338185890264,
2464      1.043944368900976,
2465    ];
2466
2467    let p3 = p3.resolve_missing();
2468    let (r, g, b) = lin_srgb(p3.r, p3.g, p3.b);
2469    let (x, y, z) = multiply_matrix(MATRIX, r, g, b);
2470    XYZd65 {
2471      x,
2472      y,
2473      z,
2474      alpha: p3.alpha,
2475    }
2476  }
2477}
2478
2479impl From<A98> for XYZd65 {
2480  fn from(a98: A98) -> XYZd65 {
2481    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L181
2482    #[inline]
2483    fn lin_a98rgb_component(c: f32) -> f32 {
2484      let sign = if c < 0.0 { -1.0 } else { 1.0 };
2485      sign * c.abs().powf(563.0 / 256.0)
2486    }
2487
2488    // convert an array of a98-rgb values in the range 0.0 - 1.0
2489    // to linear light (un-companded) form.
2490    // negative values are also now accepted
2491    let a98 = a98.resolve_missing();
2492    let r = lin_a98rgb_component(a98.r);
2493    let g = lin_a98rgb_component(a98.g);
2494    let b = lin_a98rgb_component(a98.b);
2495
2496    // convert an array of linear-light a98-rgb values to CIE XYZ
2497    // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
2498    // has greater numerical precision than section 4.3.5.3 of
2499    // https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
2500    // but the values below were calculated from first principles
2501    // from the chromaticity coordinates of R G B W
2502    // see matrixmaker.html
2503    const MATRIX: &[f32] = &[
2504      0.5766690429101305,
2505      0.1855582379065463,
2506      0.1882286462349947,
2507      0.29734497525053605,
2508      0.6273635662554661,
2509      0.07529145849399788,
2510      0.02703136138641234,
2511      0.07068885253582723,
2512      0.9913375368376388,
2513    ];
2514
2515    let (x, y, z) = multiply_matrix(MATRIX, r, g, b);
2516    XYZd65 {
2517      x,
2518      y,
2519      z,
2520      alpha: a98.alpha,
2521    }
2522  }
2523}
2524
2525impl From<XYZd65> for A98 {
2526  fn from(xyz: XYZd65) -> A98 {
2527    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L222
2528    // convert XYZ to linear-light a98-rgb
2529    const MATRIX: &[f32] = &[
2530      2.0415879038107465,
2531      -0.5650069742788596,
2532      -0.34473135077832956,
2533      -0.9692436362808795,
2534      1.8759675015077202,
2535      0.04155505740717557,
2536      0.013444280632031142,
2537      -0.11836239223101838,
2538      1.0151749943912054,
2539    ];
2540
2541    #[inline]
2542    fn gam_a98_component(c: f32) -> f32 {
2543      // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L193
2544      // convert linear-light a98-rgb  in the range 0.0-1.0
2545      // to gamma corrected form
2546      // negative values are also now accepted
2547      let sign = if c < 0.0 { -1.0 } else { 1.0 };
2548      sign * c.abs().powf(256.0 / 563.0)
2549    }
2550
2551    let xyz = xyz.resolve_missing();
2552    let (r, g, b) = multiply_matrix(MATRIX, xyz.x, xyz.y, xyz.z);
2553    let r = gam_a98_component(r);
2554    let g = gam_a98_component(g);
2555    let b = gam_a98_component(b);
2556    A98 {
2557      r,
2558      g,
2559      b,
2560      alpha: xyz.alpha,
2561    }
2562  }
2563}
2564
2565impl From<ProPhoto> for XYZd50 {
2566  fn from(prophoto: ProPhoto) -> XYZd50 {
2567    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L118
2568    // convert an array of prophoto-rgb values
2569    // where in-gamut colors are in the range [0.0 - 1.0]
2570    // to linear light (un-companded) form.
2571    // Transfer curve is gamma 1.8 with a small linear portion
2572    // Extended transfer function
2573
2574    #[inline]
2575    fn lin_prophoto_component(c: f32) -> f32 {
2576      const ET2: f32 = 16.0 / 512.0;
2577      let abs = c.abs();
2578      if abs <= ET2 {
2579        return c / 16.0;
2580      }
2581
2582      let sign = if c < 0.0 { -1.0 } else { 1.0 };
2583      sign * c.powf(1.8)
2584    }
2585
2586    let prophoto = prophoto.resolve_missing();
2587    let r = lin_prophoto_component(prophoto.r);
2588    let g = lin_prophoto_component(prophoto.g);
2589    let b = lin_prophoto_component(prophoto.b);
2590
2591    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L155
2592    // convert an array of linear-light prophoto-rgb values to CIE XYZ
2593    // using  D50 (so no chromatic adaptation needed afterwards)
2594    // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
2595    const MATRIX: &[f32] = &[
2596      0.7977604896723027,
2597      0.13518583717574031,
2598      0.0313493495815248,
2599      0.2880711282292934,
2600      0.7118432178101014,
2601      0.00008565396060525902,
2602      0.0,
2603      0.0,
2604      0.8251046025104601,
2605    ];
2606
2607    let (x, y, z) = multiply_matrix(MATRIX, r, g, b);
2608    XYZd50 {
2609      x,
2610      y,
2611      z,
2612      alpha: prophoto.alpha,
2613    }
2614  }
2615}
2616
2617impl From<XYZd50> for ProPhoto {
2618  fn from(xyz: XYZd50) -> ProPhoto {
2619    // convert XYZ to linear-light prophoto-rgb
2620    const MATRIX: &[f32] = &[
2621      1.3457989731028281,
2622      -0.25558010007997534,
2623      -0.05110628506753401,
2624      -0.5446224939028347,
2625      1.5082327413132781,
2626      0.02053603239147973,
2627      0.0,
2628      0.0,
2629      1.2119675456389454,
2630    ];
2631
2632    #[inline]
2633    fn gam_prophoto_component(c: f32) -> f32 {
2634      // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L137
2635      // convert linear-light prophoto-rgb  in the range 0.0-1.0
2636      // to gamma corrected form
2637      // Transfer curve is gamma 1.8 with a small linear portion
2638      // TODO for negative values, extend linear portion on reflection of axis, then add pow below that
2639      const ET: f32 = 1.0 / 512.0;
2640      let abs = c.abs();
2641      if abs >= ET {
2642        let sign = if c < 0.0 { -1.0 } else { 1.0 };
2643        return sign * abs.powf(1.0 / 1.8);
2644      }
2645
2646      16.0 * c
2647    }
2648
2649    let xyz = xyz.resolve_missing();
2650    let (r, g, b) = multiply_matrix(MATRIX, xyz.x, xyz.y, xyz.z);
2651    let r = gam_prophoto_component(r);
2652    let g = gam_prophoto_component(g);
2653    let b = gam_prophoto_component(b);
2654    ProPhoto {
2655      r,
2656      g,
2657      b,
2658      alpha: xyz.alpha,
2659    }
2660  }
2661}
2662
2663impl From<Rec2020> for XYZd65 {
2664  fn from(rec2020: Rec2020) -> XYZd65 {
2665    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L235
2666    // convert an array of rec2020 RGB values in the range 0.0 - 1.0
2667    // to linear light (un-companded) form.
2668    // ITU-R BT.2020-2 p.4
2669
2670    #[inline]
2671    fn lin_rec2020_component(c: f32) -> f32 {
2672      const A: f32 = 1.09929682680944;
2673      const B: f32 = 0.018053968510807;
2674
2675      let abs = c.abs();
2676      if abs < B * 4.5 {
2677        return c / 4.5;
2678      }
2679
2680      let sign = if c < 0.0 { -1.0 } else { 1.0 };
2681      sign * ((abs + A - 1.0) / A).powf(1.0 / 0.45)
2682    }
2683
2684    let rec2020 = rec2020.resolve_missing();
2685    let r = lin_rec2020_component(rec2020.r);
2686    let g = lin_rec2020_component(rec2020.g);
2687    let b = lin_rec2020_component(rec2020.b);
2688
2689    // https://github.com/w3c/csswg-drafts/blob/fba005e2ce9bcac55b49e4aa19b87208b3a0631e/css-color-4/conversions.js#L276
2690    // convert an array of linear-light rec2020 values to CIE XYZ
2691    // using  D65 (no chromatic adaptation)
2692    // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
2693    const MATRIX: &[f32] = &[
2694      0.6369580483012914,
2695      0.14461690358620832,
2696      0.1688809751641721,
2697      0.2627002120112671,
2698      0.6779980715188708,
2699      0.05930171646986196,
2700      0.000000000000000,
2701      0.028072693049087428,
2702      1.060985057710791,
2703    ];
2704
2705    let (x, y, z) = multiply_matrix(MATRIX, r, g, b);
2706    XYZd65 {
2707      x,
2708      y,
2709      z,
2710      alpha: rec2020.alpha,
2711    }
2712  }
2713}
2714
2715impl From<XYZd65> for Rec2020 {
2716  fn from(xyz: XYZd65) -> Rec2020 {
2717    // convert XYZ to linear-light rec2020
2718    const MATRIX: &[f32] = &[
2719      1.7166511879712674,
2720      -0.35567078377639233,
2721      -0.25336628137365974,
2722      -0.6666843518324892,
2723      1.6164812366349395,
2724      0.01576854581391113,
2725      0.017639857445310783,
2726      -0.042770613257808524,
2727      0.9421031212354738,
2728    ];
2729
2730    #[inline]
2731    fn gam_rec2020_component(c: f32) -> f32 {
2732      // convert linear-light rec2020 RGB  in the range 0.0-1.0
2733      // to gamma corrected form
2734      // ITU-R BT.2020-2 p.4
2735
2736      const A: f32 = 1.09929682680944;
2737      const B: f32 = 0.018053968510807;
2738
2739      let abs = c.abs();
2740      if abs > B {
2741        let sign = if c < 0.0 { -1.0 } else { 1.0 };
2742        return sign * (A * abs.powf(0.45) - (A - 1.0));
2743      }
2744
2745      4.5 * c
2746    }
2747
2748    let xyz = xyz.resolve_missing();
2749    let (r, g, b) = multiply_matrix(MATRIX, xyz.x, xyz.y, xyz.z);
2750    let r = gam_rec2020_component(r);
2751    let g = gam_rec2020_component(g);
2752    let b = gam_rec2020_component(b);
2753    Rec2020 {
2754      r,
2755      g,
2756      b,
2757      alpha: xyz.alpha,
2758    }
2759  }
2760}
2761
2762impl From<SRGB> for HSL {
2763  fn from(rgb: SRGB) -> HSL {
2764    // https://drafts.csswg.org/css-color/#rgb-to-hsl
2765    let rgb = rgb.resolve();
2766    let r = rgb.r;
2767    let g = rgb.g;
2768    let b = rgb.b;
2769    let max = r.max(g).max(b);
2770    let min = r.min(g).min(b);
2771    let mut h = f32::NAN;
2772    let mut s: f32 = 0.0;
2773    let l = (min + max) / 2.0;
2774    let d = max - min;
2775
2776    if d != 0.0 {
2777      s = if l == 0.0 || l == 1.0 {
2778        0.0
2779      } else {
2780        (max - l) / l.min(1.0 - l)
2781      };
2782
2783      if max == r {
2784        h = (g - b) / d + (if g < b { 6.0 } else { 0.0 });
2785      } else if max == g {
2786        h = (b - r) / d + 2.0;
2787      } else if max == b {
2788        h = (r - g) / d + 4.0;
2789      }
2790
2791      h = h * 60.0;
2792    }
2793
2794    HSL {
2795      h,
2796      s: s * 100.0,
2797      l: l * 100.0,
2798      alpha: rgb.alpha,
2799    }
2800  }
2801}
2802
2803impl From<HSL> for SRGB {
2804  fn from(hsl: HSL) -> SRGB {
2805    // https://drafts.csswg.org/css-color/#hsl-to-rgb
2806    let hsl = hsl.resolve_missing();
2807    let h = (hsl.h - 360.0 * (hsl.h / 360.0).floor()) / 360.0;
2808    let (r, g, b) = hsl_to_rgb(h, hsl.s / 100.0, hsl.l / 100.0);
2809    SRGB {
2810      r,
2811      g,
2812      b,
2813      alpha: hsl.alpha,
2814    }
2815  }
2816}
2817
2818impl From<SRGB> for HWB {
2819  fn from(rgb: SRGB) -> HWB {
2820    let rgb = rgb.resolve();
2821    let hsl = HSL::from(rgb);
2822    let r = rgb.r;
2823    let g = rgb.g;
2824    let b = rgb.b;
2825    let w = r.min(g).min(b);
2826    let b = 1.0 - r.max(g).max(b);
2827    HWB {
2828      h: hsl.h,
2829      w: w * 100.0,
2830      b: b * 100.0,
2831      alpha: rgb.alpha,
2832    }
2833  }
2834}
2835
2836impl From<HWB> for SRGB {
2837  fn from(hwb: HWB) -> SRGB {
2838    // https://drafts.csswg.org/css-color/#hwb-to-rgb
2839    let hwb = hwb.resolve_missing();
2840    let h = hwb.h;
2841    let w = hwb.w / 100.0;
2842    let b = hwb.b / 100.0;
2843
2844    if w + b >= 1.0 {
2845      let gray = w / (w + b);
2846      return SRGB {
2847        r: gray,
2848        g: gray,
2849        b: gray,
2850        alpha: hwb.alpha,
2851      };
2852    }
2853
2854    let mut rgba = SRGB::from(HSL {
2855      h,
2856      s: 100.0,
2857      l: 50.0,
2858      alpha: hwb.alpha,
2859    });
2860    let x = 1.0 - w - b;
2861    rgba.r = rgba.r * x + w;
2862    rgba.g = rgba.g * x + w;
2863    rgba.b = rgba.b * x + w;
2864    rgba
2865  }
2866}
2867
2868impl From<RGBA> for SRGB {
2869  fn from(rgb: RGBA) -> SRGB {
2870    SRGB {
2871      r: rgb.red_f32(),
2872      g: rgb.green_f32(),
2873      b: rgb.blue_f32(),
2874      alpha: rgb.alpha_f32(),
2875    }
2876  }
2877}
2878
2879impl From<SRGB> for RGBA {
2880  fn from(rgb: SRGB) -> RGBA {
2881    let rgb = rgb.resolve();
2882    RGBA::from_floats(rgb.r, rgb.g, rgb.b, rgb.alpha)
2883  }
2884}
2885
2886impl From<SRGB> for RGB {
2887  fn from(rgb: SRGB) -> Self {
2888    RGB {
2889      r: rgb.r * 255.0,
2890      g: rgb.g * 255.0,
2891      b: rgb.b * 255.0,
2892      alpha: rgb.alpha,
2893    }
2894  }
2895}
2896
2897impl From<RGB> for SRGB {
2898  fn from(rgb: RGB) -> Self {
2899    SRGB {
2900      r: rgb.r / 255.0,
2901      g: rgb.g / 255.0,
2902      b: rgb.b / 255.0,
2903      alpha: rgb.alpha,
2904    }
2905  }
2906}
2907
2908impl From<RGBA> for RGB {
2909  fn from(rgb: RGBA) -> Self {
2910    RGB::from(&rgb)
2911  }
2912}
2913
2914impl From<&RGBA> for RGB {
2915  fn from(rgb: &RGBA) -> Self {
2916    RGB {
2917      r: rgb.red as f32,
2918      g: rgb.green as f32,
2919      b: rgb.blue as f32,
2920      alpha: rgb.alpha_f32(),
2921    }
2922  }
2923}
2924
2925impl From<RGB> for RGBA {
2926  fn from(rgb: RGB) -> Self {
2927    let rgb = rgb.resolve();
2928    RGBA::new(
2929      clamp_floor_256_f32(rgb.r),
2930      clamp_floor_256_f32(rgb.g),
2931      clamp_floor_256_f32(rgb.b),
2932      rgb.alpha,
2933    )
2934  }
2935}
2936
2937// Once Rust specialization is stable, this could be simplified.
2938via!(LAB -> XYZd50 -> XYZd65);
2939via!(ProPhoto -> XYZd50 -> XYZd65);
2940via!(OKLCH -> OKLAB -> XYZd65);
2941
2942via!(LAB -> XYZd65 -> OKLAB);
2943via!(LAB -> XYZd65 -> OKLCH);
2944via!(LAB -> XYZd65 -> SRGB);
2945via!(LAB -> XYZd65 -> SRGBLinear);
2946via!(LAB -> XYZd65 -> P3);
2947via!(LAB -> XYZd65 -> A98);
2948via!(LAB -> XYZd65 -> ProPhoto);
2949via!(LAB -> XYZd65 -> Rec2020);
2950via!(LAB -> XYZd65 -> HSL);
2951via!(LAB -> XYZd65 -> HWB);
2952
2953via!(LCH -> LAB -> XYZd65);
2954via!(LCH -> XYZd65 -> OKLAB);
2955via!(LCH -> XYZd65 -> OKLCH);
2956via!(LCH -> XYZd65 -> SRGB);
2957via!(LCH -> XYZd65 -> SRGBLinear);
2958via!(LCH -> XYZd65 -> P3);
2959via!(LCH -> XYZd65 -> A98);
2960via!(LCH -> XYZd65 -> ProPhoto);
2961via!(LCH -> XYZd65 -> Rec2020);
2962via!(LCH -> XYZd65 -> XYZd50);
2963via!(LCH -> XYZd65 -> HSL);
2964via!(LCH -> XYZd65 -> HWB);
2965
2966via!(SRGB -> SRGBLinear -> XYZd65);
2967via!(SRGB -> XYZd65 -> OKLAB);
2968via!(SRGB -> XYZd65 -> OKLCH);
2969via!(SRGB -> XYZd65 -> P3);
2970via!(SRGB -> XYZd65 -> A98);
2971via!(SRGB -> XYZd65 -> ProPhoto);
2972via!(SRGB -> XYZd65 -> Rec2020);
2973via!(SRGB -> XYZd65 -> XYZd50);
2974
2975via!(P3 -> XYZd65 -> SRGBLinear);
2976via!(P3 -> XYZd65 -> OKLAB);
2977via!(P3 -> XYZd65 -> OKLCH);
2978via!(P3 -> XYZd65 -> A98);
2979via!(P3 -> XYZd65 -> ProPhoto);
2980via!(P3 -> XYZd65 -> Rec2020);
2981via!(P3 -> XYZd65 -> XYZd50);
2982via!(P3 -> XYZd65 -> HSL);
2983via!(P3 -> XYZd65 -> HWB);
2984
2985via!(SRGBLinear -> XYZd65 -> OKLAB);
2986via!(SRGBLinear -> XYZd65 -> OKLCH);
2987via!(SRGBLinear -> XYZd65 -> A98);
2988via!(SRGBLinear -> XYZd65 -> ProPhoto);
2989via!(SRGBLinear -> XYZd65 -> Rec2020);
2990via!(SRGBLinear -> XYZd65 -> XYZd50);
2991via!(SRGBLinear -> XYZd65 -> HSL);
2992via!(SRGBLinear -> XYZd65 -> HWB);
2993
2994via!(A98 -> XYZd65 -> OKLAB);
2995via!(A98 -> XYZd65 -> OKLCH);
2996via!(A98 -> XYZd65 -> ProPhoto);
2997via!(A98 -> XYZd65 -> Rec2020);
2998via!(A98 -> XYZd65 -> XYZd50);
2999via!(A98 -> XYZd65 -> HSL);
3000via!(A98 -> XYZd65 -> HWB);
3001
3002via!(ProPhoto -> XYZd65 -> OKLAB);
3003via!(ProPhoto -> XYZd65 -> OKLCH);
3004via!(ProPhoto -> XYZd65 -> Rec2020);
3005via!(ProPhoto -> XYZd65 -> HSL);
3006via!(ProPhoto -> XYZd65 -> HWB);
3007
3008via!(XYZd50 -> XYZd65 -> OKLAB);
3009via!(XYZd50 -> XYZd65 -> OKLCH);
3010via!(XYZd50 -> XYZd65 -> Rec2020);
3011via!(XYZd50 -> XYZd65 -> HSL);
3012via!(XYZd50 -> XYZd65 -> HWB);
3013
3014via!(Rec2020 -> XYZd65 -> OKLAB);
3015via!(Rec2020 -> XYZd65 -> OKLCH);
3016via!(Rec2020 -> XYZd65 -> HSL);
3017via!(Rec2020 -> XYZd65 -> HWB);
3018
3019via!(HSL -> XYZd65 -> OKLAB);
3020via!(HSL -> XYZd65 -> OKLCH);
3021via!(HSL -> SRGB -> XYZd65);
3022via!(HSL -> SRGB -> HWB);
3023
3024via!(HWB -> SRGB -> XYZd65);
3025via!(HWB -> XYZd65 -> OKLAB);
3026via!(HWB -> XYZd65 -> OKLCH);
3027
3028via!(RGB -> SRGB -> LAB);
3029via!(RGB -> SRGB -> LCH);
3030via!(RGB -> SRGB -> OKLAB);
3031via!(RGB -> SRGB -> OKLCH);
3032via!(RGB -> SRGB -> P3);
3033via!(RGB -> SRGB -> SRGBLinear);
3034via!(RGB -> SRGB -> A98);
3035via!(RGB -> SRGB -> ProPhoto);
3036via!(RGB -> SRGB -> XYZd50);
3037via!(RGB -> SRGB -> XYZd65);
3038via!(RGB -> SRGB -> Rec2020);
3039via!(RGB -> SRGB -> HSL);
3040via!(RGB -> SRGB -> HWB);
3041
3042// RGBA is an 8-bit version. Convert to SRGB, which is a
3043// more accurate floating point representation for all operations.
3044via!(RGBA -> SRGB -> LAB);
3045via!(RGBA -> SRGB -> LCH);
3046via!(RGBA -> SRGB -> OKLAB);
3047via!(RGBA -> SRGB -> OKLCH);
3048via!(RGBA -> SRGB -> P3);
3049via!(RGBA -> SRGB -> SRGBLinear);
3050via!(RGBA -> SRGB -> A98);
3051via!(RGBA -> SRGB -> ProPhoto);
3052via!(RGBA -> SRGB -> XYZd50);
3053via!(RGBA -> SRGB -> XYZd65);
3054via!(RGBA -> SRGB -> Rec2020);
3055via!(RGBA -> SRGB -> HSL);
3056via!(RGBA -> SRGB -> HWB);
3057
3058macro_rules! color_space {
3059  ($space: ty) => {
3060    impl From<LABColor> for $space {
3061      fn from(color: LABColor) -> $space {
3062        use LABColor::*;
3063
3064        match color {
3065          LAB(v) => v.into(),
3066          LCH(v) => v.into(),
3067          OKLAB(v) => v.into(),
3068          OKLCH(v) => v.into(),
3069        }
3070      }
3071    }
3072
3073    impl From<PredefinedColor> for $space {
3074      fn from(color: PredefinedColor) -> $space {
3075        use PredefinedColor::*;
3076
3077        match color {
3078          SRGB(v) => v.into(),
3079          SRGBLinear(v) => v.into(),
3080          DisplayP3(v) => v.into(),
3081          A98(v) => v.into(),
3082          ProPhoto(v) => v.into(),
3083          Rec2020(v) => v.into(),
3084          XYZd50(v) => v.into(),
3085          XYZd65(v) => v.into(),
3086        }
3087      }
3088    }
3089
3090    impl From<FloatColor> for $space {
3091      fn from(color: FloatColor) -> $space {
3092        use FloatColor::*;
3093
3094        match color {
3095          RGB(v) => v.into(),
3096          HSL(v) => v.into(),
3097          HWB(v) => v.into(),
3098        }
3099      }
3100    }
3101
3102    impl TryFrom<&CssColor> for $space {
3103      type Error = ();
3104      fn try_from(color: &CssColor) -> Result<$space, ()> {
3105        Ok(match color {
3106          CssColor::RGBA(rgba) => (*rgba).into(),
3107          CssColor::LAB(lab) => (**lab).into(),
3108          CssColor::Predefined(predefined) => (**predefined).into(),
3109          CssColor::Float(float) => (**float).into(),
3110          CssColor::CurrentColor => return Err(()),
3111          CssColor::LightDark(..) => return Err(()),
3112          CssColor::System(..) => return Err(()),
3113        })
3114      }
3115    }
3116
3117    impl TryFrom<CssColor> for $space {
3118      type Error = ();
3119      fn try_from(color: CssColor) -> Result<$space, ()> {
3120        Ok(match color {
3121          CssColor::RGBA(rgba) => rgba.into(),
3122          CssColor::LAB(lab) => (*lab).into(),
3123          CssColor::Predefined(predefined) => (*predefined).into(),
3124          CssColor::Float(float) => (*float).into(),
3125          CssColor::CurrentColor => return Err(()),
3126          CssColor::LightDark(..) => return Err(()),
3127          CssColor::System(..) => return Err(()),
3128        })
3129      }
3130    }
3131  };
3132}
3133
3134color_space!(LAB);
3135color_space!(LCH);
3136color_space!(OKLAB);
3137color_space!(OKLCH);
3138color_space!(SRGB);
3139color_space!(SRGBLinear);
3140color_space!(XYZd50);
3141color_space!(XYZd65);
3142color_space!(P3);
3143color_space!(A98);
3144color_space!(ProPhoto);
3145color_space!(Rec2020);
3146color_space!(HSL);
3147color_space!(HWB);
3148color_space!(RGB);
3149color_space!(RGBA);
3150
3151macro_rules! predefined {
3152  ($key: ident, $t: ty) => {
3153    impl From<$t> for PredefinedColor {
3154      fn from(color: $t) -> PredefinedColor {
3155        PredefinedColor::$key(color)
3156      }
3157    }
3158
3159    impl From<$t> for CssColor {
3160      fn from(color: $t) -> CssColor {
3161        CssColor::Predefined(Box::new(PredefinedColor::$key(color)))
3162      }
3163    }
3164  };
3165}
3166
3167predefined!(SRGBLinear, SRGBLinear);
3168predefined!(XYZd50, XYZd50);
3169predefined!(XYZd65, XYZd65);
3170predefined!(DisplayP3, P3);
3171predefined!(A98, A98);
3172predefined!(ProPhoto, ProPhoto);
3173predefined!(Rec2020, Rec2020);
3174
3175macro_rules! lab {
3176  ($key: ident, $t: ty) => {
3177    impl From<$t> for LABColor {
3178      fn from(color: $t) -> LABColor {
3179        LABColor::$key(color)
3180      }
3181    }
3182
3183    impl From<$t> for CssColor {
3184      fn from(color: $t) -> CssColor {
3185        CssColor::LAB(Box::new(LABColor::$key(color)))
3186      }
3187    }
3188  };
3189}
3190
3191lab!(LAB, LAB);
3192lab!(LCH, LCH);
3193lab!(OKLAB, OKLAB);
3194lab!(OKLCH, OKLCH);
3195
3196macro_rules! rgb {
3197  ($t: ty) => {
3198    impl From<$t> for CssColor {
3199      fn from(color: $t) -> CssColor {
3200        // TODO: should we serialize as color(srgb, ...)?
3201        // would be more precise than 8-bit color.
3202        CssColor::RGBA(color.into())
3203      }
3204    }
3205  };
3206}
3207
3208rgb!(SRGB);
3209rgb!(HSL);
3210rgb!(HWB);
3211rgb!(RGB);
3212
3213impl From<RGBA> for CssColor {
3214  fn from(color: RGBA) -> CssColor {
3215    CssColor::RGBA(color)
3216  }
3217}
3218
3219/// A trait that colors implement to support [gamut mapping](https://www.w3.org/TR/css-color-4/#gamut-mapping).
3220pub trait ColorGamut {
3221  /// Returns whether the color is within the gamut of the color space.
3222  fn in_gamut(&self) -> bool;
3223  /// Clips the color so that it is within the gamut of the color space.
3224  fn clip(&self) -> Self;
3225}
3226
3227macro_rules! bounded_color_gamut {
3228  ($t: ty, $a: ident, $b: ident, $c: ident) => {
3229    impl ColorGamut for $t {
3230      #[inline]
3231      fn in_gamut(&self) -> bool {
3232        self.$a >= 0.0 && self.$a <= 1.0 && self.$b >= 0.0 && self.$b <= 1.0 && self.$c >= 0.0 && self.$c <= 1.0
3233      }
3234
3235      #[inline]
3236      fn clip(&self) -> Self {
3237        Self {
3238          $a: self.$a.clamp(0.0, 1.0),
3239          $b: self.$b.clamp(0.0, 1.0),
3240          $c: self.$c.clamp(0.0, 1.0),
3241          alpha: self.alpha.clamp(0.0, 1.0),
3242        }
3243      }
3244    }
3245  };
3246}
3247
3248macro_rules! unbounded_color_gamut {
3249  ($t: ty, $a: ident, $b: ident, $c: ident) => {
3250    impl ColorGamut for $t {
3251      #[inline]
3252      fn in_gamut(&self) -> bool {
3253        true
3254      }
3255
3256      #[inline]
3257      fn clip(&self) -> Self {
3258        *self
3259      }
3260    }
3261  };
3262}
3263
3264macro_rules! hsl_hwb_color_gamut {
3265  ($t: ty, $a: ident, $b: ident) => {
3266    impl ColorGamut for $t {
3267      #[inline]
3268      fn in_gamut(&self) -> bool {
3269        self.$a >= 0.0 && self.$a <= 100.0 && self.$b >= 0.0 && self.$b <= 100.0
3270      }
3271
3272      #[inline]
3273      fn clip(&self) -> Self {
3274        Self {
3275          h: self.h % 360.0,
3276          $a: self.$a.clamp(0.0, 100.0),
3277          $b: self.$b.clamp(0.0, 100.0),
3278          alpha: self.alpha.clamp(0.0, 1.0),
3279        }
3280      }
3281    }
3282  };
3283}
3284
3285bounded_color_gamut!(SRGB, r, g, b);
3286bounded_color_gamut!(SRGBLinear, r, g, b);
3287bounded_color_gamut!(P3, r, g, b);
3288bounded_color_gamut!(A98, r, g, b);
3289bounded_color_gamut!(ProPhoto, r, g, b);
3290bounded_color_gamut!(Rec2020, r, g, b);
3291unbounded_color_gamut!(LAB, l, a, b);
3292unbounded_color_gamut!(OKLAB, l, a, b);
3293unbounded_color_gamut!(XYZd50, x, y, z);
3294unbounded_color_gamut!(XYZd65, x, y, z);
3295unbounded_color_gamut!(LCH, l, c, h);
3296unbounded_color_gamut!(OKLCH, l, c, h);
3297hsl_hwb_color_gamut!(HSL, s, l);
3298hsl_hwb_color_gamut!(HWB, w, b);
3299
3300impl ColorGamut for RGB {
3301  #[inline]
3302  fn in_gamut(&self) -> bool {
3303    self.r >= 0.0 && self.r <= 255.0 && self.g >= 0.0 && self.g <= 255.0 && self.b >= 0.0 && self.b <= 255.0
3304  }
3305
3306  #[inline]
3307  fn clip(&self) -> Self {
3308    Self {
3309      r: self.r.clamp(0.0, 255.0),
3310      g: self.g.clamp(0.0, 255.0),
3311      b: self.b.clamp(0.0, 255.0),
3312      alpha: self.alpha.clamp(0.0, 1.0),
3313    }
3314  }
3315}
3316
3317fn delta_eok<T: Into<OKLAB>>(a: T, b: OKLCH) -> f32 {
3318  // https://www.w3.org/TR/css-color-4/#color-difference-OK
3319  let a: OKLAB = a.into();
3320  let b: OKLAB = b.into();
3321  let delta_l = a.l - b.l;
3322  let delta_a = a.a - b.a;
3323  let delta_b = a.b - b.b;
3324
3325  (delta_l.powi(2) + delta_a.powi(2) + delta_b.powi(2)).sqrt()
3326}
3327
3328fn map_gamut<T>(color: T) -> T
3329where
3330  T: Into<OKLCH> + ColorGamut + Into<OKLAB> + From<OKLCH> + Copy,
3331{
3332  const JND: f32 = 0.02;
3333  const EPSILON: f32 = 0.0001;
3334  const LIGHTNESS_EPSILON: f32 = 0.00001;
3335
3336  // https://www.w3.org/TR/css-color-4/#pseudo-binsearch
3337  let mut current: OKLCH = color.into();
3338
3339  // If lightness is >= 100%, return pure white.
3340  if (current.l - 1.0).abs() < LIGHTNESS_EPSILON || current.l > 1.0 {
3341    return OKLCH {
3342      l: 1.0,
3343      c: 0.0,
3344      h: 0.0,
3345      alpha: current.alpha,
3346    }
3347    .into();
3348  }
3349
3350  // If lightness <= 0%, return pure black.
3351  if current.l < LIGHTNESS_EPSILON {
3352    return OKLCH {
3353      l: 0.0,
3354      c: 0.0,
3355      h: 0.0,
3356      alpha: current.alpha,
3357    }
3358    .into();
3359  }
3360
3361  let mut min = 0.0;
3362  let mut max = current.c;
3363  let mut min_in_gamut = true;
3364  let mut clipped = color.clip();
3365  let mut delta_e = delta_eok(clipped, current);
3366  if delta_e < JND {
3367    return clipped;
3368  }
3369
3370  while (max - min) > EPSILON {
3371    let chroma = (min + max) / 2.0;
3372    current.c = chroma;
3373
3374    let converted = T::from(current);
3375    if min_in_gamut && converted.in_gamut() {
3376      min = chroma;
3377      continue;
3378    }
3379
3380    clipped = converted.clip();
3381    delta_e = delta_eok(clipped, current);
3382    if delta_e < JND {
3383      if JND - delta_e < EPSILON {
3384        break;
3385      }
3386      min_in_gamut = false;
3387      min = chroma;
3388    } else {
3389      max = chroma;
3390    }
3391  }
3392
3393  clipped
3394}
3395
3396fn parse_color_mix<'i, 't>(input: &mut Parser<'i, 't>) -> Result<CssColor, ParseError<'i, ParserError<'i>>> {
3397  input.expect_ident_matching("in")?;
3398  let method = ColorSpaceName::parse(input)?;
3399
3400  let hue_method = if matches!(
3401    method,
3402    ColorSpaceName::Hsl | ColorSpaceName::Hwb | ColorSpaceName::LCH | ColorSpaceName::OKLCH
3403  ) {
3404    let hue_method = input.try_parse(HueInterpolationMethod::parse);
3405    if hue_method.is_ok() {
3406      input.expect_ident_matching("hue")?;
3407    }
3408    hue_method
3409  } else {
3410    Ok(HueInterpolationMethod::Shorter)
3411  };
3412
3413  let hue_method = hue_method.unwrap_or(HueInterpolationMethod::Shorter);
3414  input.expect_comma()?;
3415
3416  let first_percent = input.try_parse(|input| input.expect_percentage());
3417  let first_color = CssColor::parse(input)?;
3418  let first_percent = first_percent
3419    .or_else(|_| input.try_parse(|input| input.expect_percentage()))
3420    .ok();
3421  input.expect_comma()?;
3422
3423  let second_percent = input.try_parse(|input| input.expect_percentage());
3424  let second_color = CssColor::parse(input)?;
3425  let second_percent = second_percent
3426    .or_else(|_| input.try_parse(|input| input.expect_percentage()))
3427    .ok();
3428
3429  // https://drafts.csswg.org/css-color-5/#color-mix-percent-norm
3430  let (p1, p2) = if first_percent.is_none() && second_percent.is_none() {
3431    (0.5, 0.5)
3432  } else {
3433    let p2 = second_percent.unwrap_or_else(|| 1.0 - first_percent.unwrap());
3434    let p1 = first_percent.unwrap_or_else(|| 1.0 - second_percent.unwrap());
3435    (p1, p2)
3436  };
3437
3438  if (p1 + p2) == 0.0 {
3439    return Err(input.new_custom_error(ParserError::InvalidValue));
3440  }
3441
3442  match method {
3443    ColorSpaceName::SRGB => first_color.interpolate::<SRGB>(p1, &second_color, p2, hue_method),
3444    ColorSpaceName::SRGBLinear => first_color.interpolate::<SRGBLinear>(p1, &second_color, p2, hue_method),
3445    ColorSpaceName::Hsl => first_color.interpolate::<HSL>(p1, &second_color, p2, hue_method),
3446    ColorSpaceName::Hwb => first_color.interpolate::<HWB>(p1, &second_color, p2, hue_method),
3447    ColorSpaceName::LAB => first_color.interpolate::<LAB>(p1, &second_color, p2, hue_method),
3448    ColorSpaceName::LCH => first_color.interpolate::<LCH>(p1, &second_color, p2, hue_method),
3449    ColorSpaceName::OKLAB => first_color.interpolate::<OKLAB>(p1, &second_color, p2, hue_method),
3450    ColorSpaceName::OKLCH => first_color.interpolate::<OKLCH>(p1, &second_color, p2, hue_method),
3451    ColorSpaceName::XYZ | ColorSpaceName::XYZd65 => {
3452      first_color.interpolate::<XYZd65>(p1, &second_color, p2, hue_method)
3453    }
3454    ColorSpaceName::XYZd50 => first_color.interpolate::<XYZd50>(p1, &second_color, p2, hue_method),
3455  }
3456  .map_err(|_| input.new_custom_error(ParserError::InvalidValue))
3457}
3458
3459impl CssColor {
3460  fn get_type_id(&self) -> TypeId {
3461    match self {
3462      CssColor::RGBA(..) => TypeId::of::<SRGB>(),
3463      CssColor::LAB(lab) => match &**lab {
3464        LABColor::LAB(..) => TypeId::of::<LAB>(),
3465        LABColor::LCH(..) => TypeId::of::<LCH>(),
3466        LABColor::OKLAB(..) => TypeId::of::<OKLAB>(),
3467        LABColor::OKLCH(..) => TypeId::of::<OKLCH>(),
3468      },
3469      CssColor::Predefined(predefined) => match &**predefined {
3470        PredefinedColor::SRGB(..) => TypeId::of::<SRGB>(),
3471        PredefinedColor::SRGBLinear(..) => TypeId::of::<SRGBLinear>(),
3472        PredefinedColor::DisplayP3(..) => TypeId::of::<P3>(),
3473        PredefinedColor::A98(..) => TypeId::of::<A98>(),
3474        PredefinedColor::ProPhoto(..) => TypeId::of::<ProPhoto>(),
3475        PredefinedColor::Rec2020(..) => TypeId::of::<Rec2020>(),
3476        PredefinedColor::XYZd50(..) => TypeId::of::<XYZd50>(),
3477        PredefinedColor::XYZd65(..) => TypeId::of::<XYZd65>(),
3478      },
3479      CssColor::Float(float) => match &**float {
3480        FloatColor::RGB(..) => TypeId::of::<SRGB>(),
3481        FloatColor::HSL(..) => TypeId::of::<HSL>(),
3482        FloatColor::HWB(..) => TypeId::of::<HWB>(),
3483      },
3484      _ => unreachable!(),
3485    }
3486  }
3487
3488  fn to_light_dark(&self) -> CssColor {
3489    match self {
3490      CssColor::LightDark(..) => self.clone(),
3491      _ => CssColor::LightDark(Box::new(self.clone()), Box::new(self.clone())),
3492    }
3493  }
3494
3495  /// Mixes this color with another color, including the specified amount of each.
3496  /// Implemented according to the [`color-mix()`](https://www.w3.org/TR/css-color-5/#color-mix) function.
3497  pub fn interpolate<T>(
3498    &self,
3499    mut p1: f32,
3500    other: &CssColor,
3501    mut p2: f32,
3502    method: HueInterpolationMethod,
3503  ) -> Result<CssColor, ()>
3504  where
3505    for<'a> T: 'static
3506      + TryFrom<&'a CssColor>
3507      + Interpolate
3508      + Into<CssColor>
3509      + Into<OKLCH>
3510      + ColorGamut
3511      + Into<OKLAB>
3512      + From<OKLCH>
3513      + Copy,
3514  {
3515    if matches!(self, CssColor::CurrentColor | CssColor::System(..))
3516      || matches!(other, CssColor::CurrentColor | CssColor::System(..))
3517    {
3518      return Err(());
3519    }
3520
3521    if matches!(self, CssColor::LightDark(..)) || matches!(other, CssColor::LightDark(..)) {
3522      if let (CssColor::LightDark(al, ad), CssColor::LightDark(bl, bd)) =
3523        (self.to_light_dark(), other.to_light_dark())
3524      {
3525        return Ok(CssColor::LightDark(
3526          Box::new(al.interpolate::<T>(p1, &bl, p2, method)?),
3527          Box::new(ad.interpolate::<T>(p1, &bd, p2, method)?),
3528        ));
3529      }
3530    }
3531
3532    let type_id = TypeId::of::<T>();
3533    let converted_first = self.get_type_id() != type_id;
3534    let converted_second = other.get_type_id() != type_id;
3535
3536    // https://drafts.csswg.org/css-color-5/#color-mix-result
3537    let mut first_color = T::try_from(self).map_err(|_| ())?;
3538    let mut second_color = T::try_from(other).map_err(|_| ())?;
3539
3540    if converted_first && !first_color.in_gamut() {
3541      first_color = map_gamut(first_color);
3542    }
3543
3544    if converted_second && !second_color.in_gamut() {
3545      second_color = map_gamut(second_color);
3546    }
3547
3548    // https://www.w3.org/TR/css-color-4/#powerless
3549    if converted_first {
3550      first_color.adjust_powerless_components();
3551    }
3552
3553    if converted_second {
3554      second_color.adjust_powerless_components();
3555    }
3556
3557    // https://drafts.csswg.org/css-color-4/#interpolation-missing
3558    first_color.fill_missing_components(&second_color);
3559    second_color.fill_missing_components(&first_color);
3560
3561    // https://www.w3.org/TR/css-color-4/#hue-interpolation
3562    first_color.adjust_hue(&mut second_color, method);
3563
3564    // https://www.w3.org/TR/css-color-4/#interpolation-alpha
3565    first_color.premultiply();
3566    second_color.premultiply();
3567
3568    // https://drafts.csswg.org/css-color-5/#color-mix-percent-norm
3569    let mut alpha_multiplier = p1 + p2;
3570    if alpha_multiplier != 1.0 {
3571      p1 = p1 / alpha_multiplier;
3572      p2 = p2 / alpha_multiplier;
3573      if alpha_multiplier > 1.0 {
3574        alpha_multiplier = 1.0;
3575      }
3576    }
3577
3578    let mut result_color = first_color.interpolate(p1, &second_color, p2);
3579    result_color.unpremultiply(alpha_multiplier);
3580
3581    Ok(result_color.into())
3582  }
3583}
3584
3585/// A trait that colors implement to support interpolation.
3586pub trait Interpolate {
3587  /// Adjusts components that are powerless to be NaN.
3588  fn adjust_powerless_components(&mut self) {}
3589  /// Fills missing components (represented as NaN) to match the other color to interpolate with.
3590  fn fill_missing_components(&mut self, other: &Self);
3591  /// Adjusts the color hue according to the given hue interpolation method.
3592  fn adjust_hue(&mut self, _: &mut Self, _: HueInterpolationMethod) {}
3593  /// Premultiplies the color by its alpha value.
3594  fn premultiply(&mut self);
3595  /// Un-premultiplies the color by the given alpha multiplier.
3596  fn unpremultiply(&mut self, alpha_multiplier: f32);
3597  /// Interpolates the color with another using the given amounts of each.
3598  fn interpolate(&self, p1: f32, other: &Self, p2: f32) -> Self;
3599}
3600
3601macro_rules! interpolate {
3602  ($a: ident, $b: ident, $c: ident) => {
3603    fn fill_missing_components(&mut self, other: &Self) {
3604      if self.$a.is_nan() {
3605        self.$a = other.$a;
3606      }
3607
3608      if self.$b.is_nan() {
3609        self.$b = other.$b;
3610      }
3611
3612      if self.$c.is_nan() {
3613        self.$c = other.$c;
3614      }
3615
3616      if self.alpha.is_nan() {
3617        self.alpha = other.alpha;
3618      }
3619    }
3620
3621    fn interpolate(&self, p1: f32, other: &Self, p2: f32) -> Self {
3622      Self {
3623        $a: self.$a * p1 + other.$a * p2,
3624        $b: self.$b * p1 + other.$b * p2,
3625        $c: self.$c * p1 + other.$c * p2,
3626        alpha: self.alpha * p1 + other.alpha * p2,
3627      }
3628    }
3629  };
3630}
3631
3632macro_rules! rectangular_premultiply {
3633  ($a: ident, $b: ident, $c: ident) => {
3634    fn premultiply(&mut self) {
3635      if !self.alpha.is_nan() {
3636        self.$a *= self.alpha;
3637        self.$b *= self.alpha;
3638        self.$c *= self.alpha;
3639      }
3640    }
3641
3642    fn unpremultiply(&mut self, alpha_multiplier: f32) {
3643      if !self.alpha.is_nan() && self.alpha != 0.0 {
3644        self.$a /= self.alpha;
3645        self.$b /= self.alpha;
3646        self.$c /= self.alpha;
3647        self.alpha *= alpha_multiplier;
3648      }
3649    }
3650  };
3651}
3652
3653macro_rules! polar_premultiply {
3654  ($a: ident, $b: ident) => {
3655    fn premultiply(&mut self) {
3656      if !self.alpha.is_nan() {
3657        self.$a *= self.alpha;
3658        self.$b *= self.alpha;
3659      }
3660    }
3661
3662    fn unpremultiply(&mut self, alpha_multiplier: f32) {
3663      self.h %= 360.0;
3664      if !self.alpha.is_nan() {
3665        self.$a /= self.alpha;
3666        self.$b /= self.alpha;
3667        self.alpha *= alpha_multiplier;
3668      }
3669    }
3670  };
3671}
3672
3673macro_rules! adjust_powerless_lab {
3674  () => {
3675    fn adjust_powerless_components(&mut self) {
3676      // If the lightness of a LAB color is 0%, both the a and b components are powerless.
3677      if self.l.abs() < f32::EPSILON {
3678        self.a = f32::NAN;
3679        self.b = f32::NAN;
3680      }
3681    }
3682  };
3683}
3684
3685macro_rules! adjust_powerless_lch {
3686  () => {
3687    fn adjust_powerless_components(&mut self) {
3688      // If the chroma of an LCH color is 0%, the hue component is powerless.
3689      // If the lightness of an LCH color is 0%, both the hue and chroma components are powerless.
3690      if self.c.abs() < f32::EPSILON {
3691        self.h = f32::NAN;
3692      }
3693
3694      if self.l.abs() < f32::EPSILON {
3695        self.c = f32::NAN;
3696        self.h = f32::NAN;
3697      }
3698    }
3699
3700    fn adjust_hue(&mut self, other: &mut Self, method: HueInterpolationMethod) {
3701      method.interpolate(&mut self.h, &mut other.h);
3702    }
3703  };
3704}
3705
3706impl Interpolate for SRGB {
3707  rectangular_premultiply!(r, g, b);
3708  interpolate!(r, g, b);
3709}
3710
3711impl Interpolate for SRGBLinear {
3712  rectangular_premultiply!(r, g, b);
3713  interpolate!(r, g, b);
3714}
3715
3716impl Interpolate for XYZd50 {
3717  rectangular_premultiply!(x, y, z);
3718  interpolate!(x, y, z);
3719}
3720
3721impl Interpolate for XYZd65 {
3722  rectangular_premultiply!(x, y, z);
3723  interpolate!(x, y, z);
3724}
3725
3726impl Interpolate for LAB {
3727  adjust_powerless_lab!();
3728  rectangular_premultiply!(l, a, b);
3729  interpolate!(l, a, b);
3730}
3731
3732impl Interpolate for OKLAB {
3733  adjust_powerless_lab!();
3734  rectangular_premultiply!(l, a, b);
3735  interpolate!(l, a, b);
3736}
3737
3738impl Interpolate for LCH {
3739  adjust_powerless_lch!();
3740  polar_premultiply!(l, c);
3741  interpolate!(l, c, h);
3742}
3743
3744impl Interpolate for OKLCH {
3745  adjust_powerless_lch!();
3746  polar_premultiply!(l, c);
3747  interpolate!(l, c, h);
3748}
3749
3750impl Interpolate for HSL {
3751  polar_premultiply!(s, l);
3752
3753  fn adjust_powerless_components(&mut self) {
3754    // If the saturation of an HSL color is 0%, then the hue component is powerless.
3755    // If the lightness of an HSL color is 0% or 100%, both the saturation and hue components are powerless.
3756    if self.s.abs() < f32::EPSILON {
3757      self.h = f32::NAN;
3758    }
3759
3760    if self.l.abs() < f32::EPSILON || (self.l - 100.0).abs() < f32::EPSILON {
3761      self.h = f32::NAN;
3762      self.s = f32::NAN;
3763    }
3764  }
3765
3766  fn adjust_hue(&mut self, other: &mut Self, method: HueInterpolationMethod) {
3767    method.interpolate(&mut self.h, &mut other.h);
3768  }
3769
3770  interpolate!(h, s, l);
3771}
3772
3773impl Interpolate for HWB {
3774  polar_premultiply!(w, b);
3775
3776  fn adjust_powerless_components(&mut self) {
3777    // If white+black is equal to 100% (after normalization), it defines an achromatic color,
3778    // i.e. some shade of gray, without any hint of the chosen hue. In this case, the hue component is powerless.
3779    if (self.w + self.b - 100.0).abs() < f32::EPSILON {
3780      self.h = f32::NAN;
3781    }
3782  }
3783
3784  fn adjust_hue(&mut self, other: &mut Self, method: HueInterpolationMethod) {
3785    method.interpolate(&mut self.h, &mut other.h);
3786  }
3787
3788  interpolate!(h, w, b);
3789}
3790
3791impl HueInterpolationMethod {
3792  fn interpolate(&self, a: &mut f32, b: &mut f32) {
3793    // https://drafts.csswg.org/css-color/#hue-interpolation
3794    if *self != HueInterpolationMethod::Specified {
3795      *a = ((*a % 360.0) + 360.0) % 360.0;
3796      *b = ((*b % 360.0) + 360.0) % 360.0;
3797    }
3798
3799    match self {
3800      HueInterpolationMethod::Shorter => {
3801        // https://www.w3.org/TR/css-color-4/#hue-shorter
3802        let delta = *b - *a;
3803        if delta > 180.0 {
3804          *a += 360.0;
3805        } else if delta < -180.0 {
3806          *b += 360.0;
3807        }
3808      }
3809      HueInterpolationMethod::Longer => {
3810        // https://www.w3.org/TR/css-color-4/#hue-longer
3811        let delta = *b - *a;
3812        if 0.0 < delta && delta < 180.0 {
3813          *a += 360.0;
3814        } else if -180.0 < delta && delta < 0.0 {
3815          *b += 360.0;
3816        }
3817      }
3818      HueInterpolationMethod::Increasing => {
3819        // https://www.w3.org/TR/css-color-4/#hue-increasing
3820        if *b < *a {
3821          *b += 360.0;
3822        }
3823      }
3824      HueInterpolationMethod::Decreasing => {
3825        // https://www.w3.org/TR/css-color-4/#hue-decreasing
3826        if *a < *b {
3827          *a += 360.0;
3828        }
3829      }
3830      HueInterpolationMethod::Specified => {}
3831    }
3832  }
3833}
3834
3835#[cfg(feature = "visitor")]
3836#[cfg_attr(docsrs, doc(cfg(feature = "visitor")))]
3837impl<'i, V: ?Sized + Visitor<'i, T>, T: Visit<'i, T, V>> Visit<'i, T, V> for RGBA {
3838  const CHILD_TYPES: VisitTypes = VisitTypes::empty();
3839  fn visit_children(&mut self, _: &mut V) -> Result<(), V::Error> {
3840    Ok(())
3841  }
3842}
3843
3844#[derive(Debug, Clone, Copy, PartialEq, Parse, ToCss)]
3845#[css(case = lower)]
3846#[cfg_attr(feature = "visitor", derive(Visit))]
3847#[cfg_attr(
3848  feature = "serde",
3849  derive(serde::Serialize, serde::Deserialize),
3850  serde(rename_all = "lowercase")
3851)]
3852#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
3853#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
3854/// A CSS [system color](https://drafts.csswg.org/css-color/#css-system-colors) keyword.
3855pub enum SystemColor {
3856  /// Background of accented user interface controls.
3857  AccentColor,
3858  /// Text of accented user interface controls.
3859  AccentColorText,
3860  /// Text in active links. For light backgrounds, traditionally red.
3861  ActiveText,
3862  /// The base border color for push buttons.
3863  ButtonBorder,
3864  /// The face background color for push buttons.
3865  ButtonFace,
3866  /// Text on push buttons.
3867  ButtonText,
3868  /// Background of application content or documents.
3869  Canvas,
3870  /// Text in application content or documents.
3871  CanvasText,
3872  /// Background of input fields.
3873  Field,
3874  /// Text in input fields.
3875  FieldText,
3876  /// Disabled text. (Often, but not necessarily, gray.)
3877  GrayText,
3878  /// Background of selected text, for example from ::selection.
3879  Highlight,
3880  /// Text of selected text.
3881  HighlightText,
3882  /// Text in non-active, non-visited links. For light backgrounds, traditionally blue.
3883  LinkText,
3884  /// Background of text that has been specially marked (such as by the HTML mark element).
3885  Mark,
3886  /// Text that has been specially marked (such as by the HTML mark element).
3887  MarkText,
3888  /// Background of selected items, for example a selected checkbox.
3889  SelectedItem,
3890  /// Text of selected items.
3891  SelectedItemText,
3892  /// Text in visited links. For light backgrounds, traditionally purple.
3893  VisitedText,
3894
3895  // Deprecated colors: https://drafts.csswg.org/css-color/#deprecated-system-colors
3896  /// Active window border. Same as ButtonBorder.
3897  ActiveBorder,
3898  /// Active window caption. Same as Canvas.
3899  ActiveCaption,
3900  /// Background color of multiple document interface. Same as Canvas.
3901  AppWorkspace,
3902  /// Desktop background. Same as Canvas.
3903  Background,
3904  /// The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border. Same as ButtonFace.
3905  ButtonHighlight,
3906  /// The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border. Same as ButtonFace.
3907  ButtonShadow,
3908  /// Text in caption, size box, and scrollbar arrow box. Same as CanvasText.
3909  CaptionText,
3910  /// Inactive window border. Same as ButtonBorder.
3911  InactiveBorder,
3912  /// Inactive window caption. Same as Canvas.
3913  InactiveCaption,
3914  /// Color of text in an inactive caption. Same as GrayText.
3915  InactiveCaptionText,
3916  /// Background color for tooltip controls. Same as Canvas.
3917  InfoBackground,
3918  /// Text color for tooltip controls. Same as CanvasText.
3919  InfoText,
3920  /// Menu background. Same as Canvas.
3921  Menu,
3922  /// Text in menus. Same as CanvasText.
3923  MenuText,
3924  /// Scroll bar gray area. Same as Canvas.
3925  Scrollbar,
3926  /// The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border. Same as ButtonBorder.
3927  ThreeDDarkShadow,
3928  /// The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border. Same as ButtonFace.
3929  ThreeDFace,
3930  /// The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border. Same as ButtonBorder.
3931  ThreeDHighlight,
3932  /// The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border. Same as ButtonBorder.
3933  ThreeDLightShadow,
3934  /// The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border. Same as ButtonBorder.
3935  ThreeDShadow,
3936  /// Window background. Same as Canvas.
3937  Window,
3938  /// Window frame. Same as ButtonBorder.
3939  WindowFrame,
3940  /// Text in windows. Same as CanvasText.
3941  WindowText,
3942}
3943
3944impl IsCompatible for SystemColor {
3945  fn is_compatible(&self, browsers: Browsers) -> bool {
3946    use SystemColor::*;
3947    match self {
3948      AccentColor | AccentColorText => Feature::AccentSystemColor.is_compatible(browsers),
3949      _ => true,
3950    }
3951  }
3952}