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 pub(crate) fn model_is_legacy(&self) -> bool {
699 matches!(self.model, Model::Rgb | Model::Hsl | Model::Hwb)
700 }
701
702 pub(crate) fn has_math(&self) -> bool {
703 self.channels
704 .iter()
705 .chain([&self.alpha])
706 .any(|c| matches!(c, Channel::Math(_)))
707 }
708
709 pub(crate) fn map_math(&mut self, f: &impl Fn(&Math) -> Math) {
711 for c in self.channels.iter_mut().chain([&mut self.alpha]) {
712 if let Channel::Math(m) = c {
713 *m = f(m);
714 }
715 }
716 }
717
718 fn legacy_srgb(&self) -> Option<[f64; 3]> {
721 let n: Vec<f64> = self
722 .channels
723 .iter()
724 .map(Channel::number)
725 .collect::<Option<_>>()?;
726 self.alpha.number()?;
727 Some(match self.model {
728 Model::Rgb => [n[0] / 255.0, n[1] / 255.0, n[2] / 255.0],
729 Model::Hsl => hsl_to_rgb(n[0], n[1], n[2]),
730 Model::Hwb => hwb_to_rgb(n[0], n[1], n[2]),
731 _ => return None,
732 })
733 }
734
735 fn write(&self, out: &mut impl Write) -> fmt::Result {
736 if let Some(rgb) = self.legacy_srgb() {
737 let [r, g, b] = rgb.map(|c| {
740 ((nan_zero(c) * 255.0 * 1e6).round() / 1e6)
741 .clamp(0.0, 255.0)
742 .round()
743 });
744 let a = self.alpha.number().unwrap();
745 if a == 1.0 {
746 return write!(out, "rgb({r}, {g}, {b})");
747 }
748 write!(out, "rgba({r}, {g}, {b}, ")?;
749 write_legacy_alpha(out, a)?;
750 return out.write_char(')');
751 }
752 let (name, percents): (&str, [bool; 3]) = match self.model {
753 Model::Rgb if self.channels.contains(&Channel::None) => {
754 out.write_str("color(srgb")?;
755 for c in &self.channels {
756 out.write_char(' ')?;
757 match c {
758 Channel::Number(v) => write_number(out, v / 255.0)?,
759 c => write_channel(out, c, false)?,
760 }
761 }
762 write_alpha(out, &self.alpha)?;
763 return out.write_char(')');
764 }
765 Model::Rgb => ("rgb", [false; 3]),
766 Model::Hsl | Model::Hwb => {
769 let math = self
770 .channels
771 .iter()
772 .chain([&self.alpha])
773 .any(|c| matches!(c, Channel::Math(_)));
774 let name = if self.model == Model::Hsl {
775 "hsl"
776 } else {
777 "hwb"
778 };
779 (name, [false, !math, !math])
780 }
781 Model::Lab => ("lab", [false; 3]),
782 Model::Lch => ("lch", [false; 3]),
783 Model::Oklab => ("oklab", [false; 3]),
784 Model::Oklch => ("oklch", [false; 3]),
785 Model::Color(space) => {
786 write!(out, "color({}", space.name())?;
787 for c in &self.channels {
788 out.write_char(' ')?;
789 write_channel(out, c, false)?;
790 }
791 write_alpha(out, &self.alpha)?;
792 return out.write_char(')');
793 }
794 Model::DeviceCmyk => {
795 out.write_str("color(device-cmyk")?;
796 for c in &self.channels {
797 out.write_char(' ')?;
798 write_channel(out, c, false)?;
799 }
800 write_alpha(out, &self.alpha)?;
801 return out.write_char(')');
802 }
803 };
804 write!(out, "{name}(")?;
805 for (i, (c, p)) in self.channels.iter().zip(percents).enumerate() {
806 if i > 0 {
807 out.write_char(' ')?;
808 }
809 write_channel(out, c, p)?;
810 }
811 write_alpha(out, &self.alpha)?;
812 out.write_char(')')
813 }
814}
815
816thread_local! {
817 static DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
818}
819
820fn relative(f: &Function<'_>, name: &str) -> Option<Color> {
822 relative_at(f, name)
823}
824
825fn relative_at(f: &Function<'_>, name: &str) -> Option<Color> {
826 let solid: Vec<&ComponentValue<'_>> =
827 f.arguments.iter().filter(|v| !v.is_whitespace()).collect();
828 let origin = Color::parse(solid.get(1)?)?;
829 let mut rest = &solid[2..];
830 let (function, space, keywords, slots): (&'static str, _, &[&'static str], [Slot; 3]) =
831 match name {
832 "rgb" | "rgba" => (
833 "rgb",
834 None,
835 &["r", "g", "b", "alpha"],
836 [Slot::Scaled(1.0); 3],
837 ),
838 "hsl" | "hsla" => (
839 "hsl",
840 None,
841 &["h", "s", "l", "alpha"],
842 [Slot::Hue, Slot::Scaled(1.0), Slot::Scaled(1.0)],
843 ),
844 "hwb" => (
845 "hwb",
846 None,
847 &["h", "w", "b", "alpha"],
848 [Slot::Hue, Slot::Scaled(1.0), Slot::Scaled(1.0)],
849 ),
850 "lab" => (
851 "lab",
852 None,
853 &["l", "a", "b", "alpha"],
854 [Slot::Scaled(1.0); 3],
855 ),
856 "oklab" => (
857 "oklab",
858 None,
859 &["l", "a", "b", "alpha"],
860 [Slot::Scaled(1.0); 3],
861 ),
862 "lch" => (
863 "lch",
864 None,
865 &["l", "c", "h", "alpha"],
866 [Slot::Scaled(1.0), Slot::Scaled(1.0), Slot::Hue],
867 ),
868 "oklch" => (
869 "oklch",
870 None,
871 &["l", "c", "h", "alpha"],
872 [Slot::Scaled(1.0), Slot::Scaled(1.0), Slot::Hue],
873 ),
874 "alpha" => ("alpha", None, &["alpha"], [Slot::Scaled(1.0); 3]),
875 "color" => {
876 let ComponentValue::Token(Token::Ident(s), _) = rest.first()? else {
877 return None;
878 };
879 let space = Predefined::parse(s)?;
880 rest = &rest[1..];
881 let keywords: &[&'static str] = match space {
882 Predefined::XyzD50 | Predefined::XyzD65 => &["x", "y", "z", "alpha"],
883 _ => &["r", "g", "b", "alpha"],
884 };
885 ("color", Some(space), keywords, [Slot::Scaled(1.0); 3])
886 }
887 _ => return None,
888 };
889 let (channels, alpha) = match rest
890 .iter()
891 .position(|v| matches!(v, ComponentValue::Token(Token::Delim('/'), _)))
892 {
893 Some(i) if rest.len() == i + 2 => (&rest[..i], Some(rest[i + 1])),
894 Some(_) => return None,
895 None => (rest, None),
896 };
897 let count = if function == "alpha" { 0 } else { 3 };
899 if channels.len() != count || (count == 0 && alpha.is_none()) {
900 return None;
901 }
902 let read = |v: &ComponentValue<'_>, slot: Slot| -> Option<RelativeChannel> {
903 Some(match v {
904 ComponentValue::Token(Token::Number(n), _) => RelativeChannel::Number(n.value),
905 ComponentValue::Token(Token::Percentage(n), _) if matches!(slot, Slot::Scaled(_)) => {
906 RelativeChannel::Percentage(n.value)
907 }
908 ComponentValue::Token(Token::Dimension { number, unit }, _)
909 if matches!(slot, Slot::Hue) =>
910 {
911 let u = super::units::Unit::parse(unit)?;
912 if u.kind() != Kind::Angle {
913 return None;
914 }
915 RelativeChannel::Angle(number.value, u)
916 }
917 ComponentValue::Token(Token::Ident(w), _) if w.eq_ignore_ascii_case("none") => {
918 RelativeChannel::None
919 }
920 ComponentValue::Token(Token::Ident(w), _) => {
921 RelativeChannel::Keyword(keywords.iter().find(|k| w.eq_ignore_ascii_case(k))?)
922 }
923 ComponentValue::Function(f) if Math::is_math_function(&f.name) => {
924 let m = Math::parse_with(f, keywords)?;
925 let ok = match slot {
926 Slot::Hue => m.fits(Expect::Number) || m.fits(Expect::Dimension(Kind::Angle)),
927 Slot::Scaled(_) => m.fits(Expect::Number) || m.fits(Expect::Percentage),
928 };
929 if !ok {
930 return None;
931 }
932 RelativeChannel::Math(m)
933 }
934 _ => return None,
935 })
936 };
937 let channels = channels
938 .iter()
939 .zip(slots)
940 .map(|(v, s)| read(v, s))
941 .collect::<Option<Vec<_>>>()?;
942 let alpha = match alpha {
943 Some(v) => Some(read(v, Slot::Scaled(1.0))?),
944 None => None,
945 };
946 Some(Color::Relative(Box::new(Relative {
947 function,
948 space,
949 origin,
950 channels,
951 alpha,
952 })))
953}
954
955impl fmt::Display for RelativeChannel {
956 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957 match self {
958 RelativeChannel::Number(v) => write_number(f, *v),
959 RelativeChannel::Percentage(v) => {
960 write_number(f, *v)?;
961 f.write_char('%')
962 }
963 RelativeChannel::Angle(v, u) => {
964 write_number(f, *v)?;
965 f.write_str(u.as_str())
966 }
967 RelativeChannel::Keyword(k) => f.write_str(k),
968 RelativeChannel::None => f.write_str("none"),
969 RelativeChannel::Math(m) => write!(f, "{m}"),
970 }
971 }
972}
973
974impl fmt::Display for Relative {
975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976 write!(f, "{}(from ", self.function)?;
977 match &self.origin {
978 Color::Channels(c) if c.model == Model::Rgb && c.alpha == Channel::None => {
981 f.write_str("color(srgb")?;
982 for ch in &c.channels {
983 f.write_char(' ')?;
984 match ch {
985 Channel::Number(v) => write_number(f, v / 255.0)?,
986 ch => write_channel(f, ch, false)?,
987 }
988 }
989 f.write_str(" / none)")?;
990 }
991 origin => write!(f, "{origin}")?,
992 }
993 if let Some(space) = self.space {
994 write!(f, " {}", space.name())?;
995 }
996 for c in &self.channels {
997 write!(f, " {c}")?;
998 }
999 if let Some(a) = &self.alpha {
1000 write!(f, " / {a}")?;
1001 }
1002 f.write_char(')')
1003 }
1004}
1005
1006impl fmt::Display for Color {
1007 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1008 match self {
1009 Color::Relative(r) => write!(f, "{r}"),
1010 Color::Contrast(c) => write!(f, "contrast-color({c})"),
1011 Color::Mix(m) => f.write_str(&m.text),
1012 Color::Text(s) => f.write_str(s),
1013 Color::CurrentColor => f.write_str("currentcolor"),
1014 Color::Named(name) | Color::System(name) => f.write_str(name),
1015 Color::Channels(c) => c.write(f),
1016 Color::LightDark(a, b) => write!(f, "light-dark({a}, {b})"),
1017 }
1018 }
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023 use super::*;
1024
1025 fn color(css: &str) -> Option<String> {
1026 let v = crate::parse_component_value(css).ok()?;
1027 Color::parse(&v).map(|c| c.to_string())
1028 }
1029
1030 #[test]
1031 fn serializes_as_css_color_4_says() {
1032 let cases = [
1033 ("#234", "rgb(34, 51, 68)"),
1034 ("#f6f8", "rgba(255, 102, 255, 0.533)"),
1035 ("transparent", "transparent"),
1036 ("RebeccaPurple", "rebeccapurple"),
1037 ("CanvasText", "canvastext"),
1038 ("currentColor", "currentcolor"),
1039 ("rgb(-2 3 4)", "rgb(0, 3, 4)"),
1040 ("rgba(2, 3, 4, 50%)", "rgba(2, 3, 4, 0.5)"),
1041 ("rgb(128 none none)", "color(srgb 0.501961 none none)"),
1042 ("hsl(120 30% 50%)", "rgb(89, 166, 89)"),
1043 ("hsl(120 30 none / 0.5)", "hsl(120 30% none / 0.5)"),
1044 ("hwb(120 0% 50%)", "rgb(0, 128, 0)"),
1045 ("lab(400 0 10/50%)", "lab(100 0 10 / 0.5)"),
1046 ("lch(0 150 -10)", "lch(0 150 350)"),
1047 ("oklch(1 0.4 700 / 0)", "oklch(1 0.4 340 / 0)"),
1048 ("color(xyz 10% 10% 10%)", "color(xyz-d65 0.1 0.1 0.1)"),
1049 ("rgb(calc(infinity), 0, 0)", "rgb(255, 0, 0)"),
1050 ("lab(calc(50 * 3) 0 0)", "lab(calc(150) 0 0)"),
1051 ("light-dark(black, white)", "light-dark(black, white)"),
1052 ];
1053 for (css, want) in cases {
1054 assert_eq!(color(css).as_deref(), Some(want), "{css}");
1055 }
1056 }
1057
1058 #[test]
1059 fn relative_colors_keep_their_channels() {
1060 let cases = [
1061 (
1062 "rgba(from rgb(20%, 40%, 60%, 80%) r g 25 / 25%)",
1063 "rgb(from rgba(51, 102, 153, 0.8) r g 25 / 25%)",
1064 ),
1065 (
1066 "rgb(from rebeccapurple r calc(g * .5 + g * .5) 10)",
1067 "rgb(from rebeccapurple r calc((0.5 * g) + (0.5 * g)) 10)",
1068 ),
1069 (
1070 "hsl(from red 0deg s l / alpha)",
1071 "hsl(from red 0deg s l / alpha)",
1072 ),
1073 (
1074 "color(from color(srgb 0.7 0.5 0.3) srgb r g b)",
1075 "color(from color(srgb 0.7 0.5 0.3) srgb r g b)",
1076 ),
1077 ];
1078 for (css, want) in cases {
1079 assert_eq!(color(css).as_deref(), Some(want), "{css}");
1080 }
1081 for css in [
1082 "rgb(from red r 10deg 10)",
1083 "rgb(from red l g b)",
1084 "hsl(from red 10% s l)",
1085 "rgb(from red calc(r + 1%) g b)",
1086 ] {
1087 assert_eq!(color(css), None, "{css}");
1088 }
1089 }
1090
1091 #[test]
1092 fn deep_nesting_is_invalid_not_a_crash() {
1093 let css = format!("{}red{}", "light-dark(".repeat(5000), ", red)".repeat(5000));
1094 assert_eq!(color(&css), None);
1095 }
1096
1097 #[test]
1098 fn rejects_what_isnt_a_color() {
1099 for css in [
1100 "#12",
1101 "rgb(1, 2%, 3)",
1102 "hsl(1, 2, 3)",
1103 "rgb(none, 0, 0)",
1104 "lab(1, 2, 3)",
1105 "color(foo 1 2 3)",
1106 "rgb(1 2)",
1107 "blurple",
1108 ] {
1109 assert_eq!(color(css), None, "{css}");
1110 }
1111 }
1112}