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