Skip to main content

azul_css/props/basic/
color.rs

1//! CSS color types and parser.
2//!
3//! Core types: [`ColorU`] (u8 RGBA), [`ColorF`] (f32 RGBA), [`ColorOrSystem`]
4//! (concrete color or runtime system-theme reference). The parser supports hex,
5//! `rgb()`/`rgba()`, `hsl()`/`hsla()`, CSS named colors, and `system:*` syntax.
6
7use alloc::string::{String, ToString};
8use core::fmt;
9use crate::corety::AzString;
10use crate::props::basic::error::{ParseFloatError, ParseIntError};
11
12use crate::{
13    impl_option,
14    props::basic::{
15        direction::{
16            parse_direction, CssDirectionParseError, CssDirectionParseErrorOwned, Direction,
17        },
18        length::{PercentageParseError, PercentageValue},
19    },
20};
21
22/// Round-saturating `f32` → `u8` for colour channels. Rust's `as u8` already
23/// saturates a float (NaN→0, negatives→0, >255→255, otherwise truncates toward
24/// zero), so this is behaviour-preserving; it just names the intent and isolates
25/// the one unavoidable float→int cast (there is no infallible `f32`→`u8` in std).
26#[inline]
27#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
28const fn channel_to_u8(v: f32) -> u8 {
29    v as u8
30}
31
32/// u8-based color, range 0 to 255 (similar to webrenders `ColorU`)
33#[derive(Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq, Hash)]
34#[repr(C)]
35pub struct ColorU {
36    pub r: u8,
37    pub g: u8,
38    pub b: u8,
39    pub a: u8,
40}
41
42impl_option!(
43    ColorU,
44    OptionColorU,
45    [Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq, Hash]
46);
47
48impl Default for ColorU {
49    fn default() -> Self {
50        Self::BLACK
51    }
52}
53
54impl fmt::Display for ColorU {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        write!(
57            f,
58            "rgba({}, {}, {}, {})",
59            self.r,
60            self.g,
61            self.b,
62            f32::from(self.a) / 255.0
63        )
64    }
65}
66
67// Colour math keeps explicit `a*b + c` rather than `mul_add`: the latter is a
68// software `fmaf` (slower) without target `+fma` and changes results bit-for-bit.
69#[allow(clippy::suboptimal_flops)]
70impl ColorU {
71    pub const ALPHA_TRANSPARENT: u8 = 0;
72    pub const ALPHA_OPAQUE: u8 = 255;
73    pub const RED: Self = Self {
74        r: 255,
75        g: 0,
76        b: 0,
77        a: Self::ALPHA_OPAQUE,
78    };
79    pub const GREEN: Self = Self {
80        r: 0,
81        g: 255,
82        b: 0,
83        a: Self::ALPHA_OPAQUE,
84    };
85    pub const BLUE: Self = Self {
86        r: 0,
87        g: 0,
88        b: 255,
89        a: Self::ALPHA_OPAQUE,
90    };
91    pub const WHITE: Self = Self {
92        r: 255,
93        g: 255,
94        b: 255,
95        a: Self::ALPHA_OPAQUE,
96    };
97    pub const BLACK: Self = Self {
98        r: 0,
99        g: 0,
100        b: 0,
101        a: Self::ALPHA_OPAQUE,
102    };
103    pub const TRANSPARENT: Self = Self {
104        r: 0,
105        g: 0,
106        b: 0,
107        a: Self::ALPHA_TRANSPARENT,
108    };
109
110    // Additional common colors
111    pub const YELLOW: Self = Self { r: 255, g: 255, b: 0, a: Self::ALPHA_OPAQUE };
112    pub const CYAN: Self = Self { r: 0, g: 255, b: 255, a: Self::ALPHA_OPAQUE };
113    pub const MAGENTA: Self = Self { r: 255, g: 0, b: 255, a: Self::ALPHA_OPAQUE };
114    pub const ORANGE: Self = Self { r: 255, g: 165, b: 0, a: Self::ALPHA_OPAQUE };
115    pub const PINK: Self = Self { r: 255, g: 192, b: 203, a: Self::ALPHA_OPAQUE };
116    pub const PURPLE: Self = Self { r: 128, g: 0, b: 128, a: Self::ALPHA_OPAQUE };
117    pub const BROWN: Self = Self { r: 139, g: 69, b: 19, a: Self::ALPHA_OPAQUE };
118    pub const GRAY: Self = Self { r: 128, g: 128, b: 128, a: Self::ALPHA_OPAQUE };
119    pub const LIGHT_GRAY: Self = Self { r: 211, g: 211, b: 211, a: Self::ALPHA_OPAQUE };
120    pub const DARK_GRAY: Self = Self { r: 64, g: 64, b: 64, a: Self::ALPHA_OPAQUE };
121    pub const NAVY: Self = Self { r: 0, g: 0, b: 128, a: Self::ALPHA_OPAQUE };
122    pub const TEAL: Self = Self { r: 0, g: 128, b: 128, a: Self::ALPHA_OPAQUE };
123    pub const OLIVE: Self = Self { r: 128, g: 128, b: 0, a: Self::ALPHA_OPAQUE };
124    pub const MAROON: Self = Self { r: 128, g: 0, b: 0, a: Self::ALPHA_OPAQUE };
125    pub const LIME: Self = Self { r: 0, g: 255, b: 0, a: Self::ALPHA_OPAQUE };
126    pub const AQUA: Self = Self { r: 0, g: 255, b: 255, a: Self::ALPHA_OPAQUE };
127    pub const SILVER: Self = Self { r: 192, g: 192, b: 192, a: Self::ALPHA_OPAQUE };
128    pub const FUCHSIA: Self = Self { r: 255, g: 0, b: 255, a: Self::ALPHA_OPAQUE };
129    pub const INDIGO: Self = Self { r: 75, g: 0, b: 130, a: Self::ALPHA_OPAQUE };
130    pub const GOLD: Self = Self { r: 255, g: 215, b: 0, a: Self::ALPHA_OPAQUE };
131    pub const CORAL: Self = Self { r: 255, g: 127, b: 80, a: Self::ALPHA_OPAQUE };
132    pub const SALMON: Self = Self { r: 250, g: 128, b: 114, a: Self::ALPHA_OPAQUE };
133    pub const TURQUOISE: Self = Self { r: 64, g: 224, b: 208, a: Self::ALPHA_OPAQUE };
134    pub const VIOLET: Self = Self { r: 238, g: 130, b: 238, a: Self::ALPHA_OPAQUE };
135    pub const CRIMSON: Self = Self { r: 220, g: 20, b: 60, a: Self::ALPHA_OPAQUE };
136    pub const CHOCOLATE: Self = Self { r: 210, g: 105, b: 30, a: Self::ALPHA_OPAQUE };
137    pub const SKY_BLUE: Self = Self { r: 135, g: 206, b: 235, a: Self::ALPHA_OPAQUE };
138    pub const FOREST_GREEN: Self = Self { r: 34, g: 139, b: 34, a: Self::ALPHA_OPAQUE };
139    pub const SEA_GREEN: Self = Self { r: 46, g: 139, b: 87, a: Self::ALPHA_OPAQUE };
140    pub const SLATE_GRAY: Self = Self { r: 112, g: 128, b: 144, a: Self::ALPHA_OPAQUE };
141    pub const MIDNIGHT_BLUE: Self = Self { r: 25, g: 25, b: 112, a: Self::ALPHA_OPAQUE };
142    pub const DARK_RED: Self = Self { r: 139, g: 0, b: 0, a: Self::ALPHA_OPAQUE };
143    pub const DARK_GREEN: Self = Self { r: 0, g: 100, b: 0, a: Self::ALPHA_OPAQUE };
144    pub const DARK_BLUE: Self = Self { r: 0, g: 0, b: 139, a: Self::ALPHA_OPAQUE };
145    pub const LIGHT_BLUE: Self = Self { r: 173, g: 216, b: 230, a: Self::ALPHA_OPAQUE };
146    pub const LIGHT_GREEN: Self = Self { r: 144, g: 238, b: 144, a: Self::ALPHA_OPAQUE };
147    pub const LIGHT_YELLOW: Self = Self { r: 255, g: 255, b: 224, a: Self::ALPHA_OPAQUE };
148    pub const LIGHT_PINK: Self = Self { r: 255, g: 182, b: 193, a: Self::ALPHA_OPAQUE };
149
150    // Constructor functions for C API (become AzColorU_red(), AzColorU_cyan(), etc.)
151    #[must_use] pub const fn red() -> Self { Self::RED }
152    #[must_use] pub const fn green() -> Self { Self::GREEN }
153    #[must_use] pub const fn blue() -> Self { Self::BLUE }
154    #[must_use] pub const fn white() -> Self { Self::WHITE }
155    #[must_use] pub const fn black() -> Self { Self::BLACK }
156    #[must_use] pub const fn transparent() -> Self { Self::TRANSPARENT }
157    #[must_use] pub const fn yellow() -> Self { Self::YELLOW }
158    #[must_use] pub const fn cyan() -> Self { Self::CYAN }
159    #[must_use] pub const fn magenta() -> Self { Self::MAGENTA }
160    #[must_use] pub const fn orange() -> Self { Self::ORANGE }
161    #[must_use] pub const fn pink() -> Self { Self::PINK }
162    #[must_use] pub const fn purple() -> Self { Self::PURPLE }
163    #[must_use] pub const fn brown() -> Self { Self::BROWN }
164    #[must_use] pub const fn gray() -> Self { Self::GRAY }
165    #[must_use] pub const fn light_gray() -> Self { Self::LIGHT_GRAY }
166    #[must_use] pub const fn dark_gray() -> Self { Self::DARK_GRAY }
167    #[must_use] pub const fn navy() -> Self { Self::NAVY }
168    #[must_use] pub const fn teal() -> Self { Self::TEAL }
169    #[must_use] pub const fn olive() -> Self { Self::OLIVE }
170    #[must_use] pub const fn maroon() -> Self { Self::MAROON }
171    #[must_use] pub const fn lime() -> Self { Self::LIME }
172    #[must_use] pub const fn aqua() -> Self { Self::AQUA }
173    #[must_use] pub const fn silver() -> Self { Self::SILVER }
174    #[must_use] pub const fn fuchsia() -> Self { Self::FUCHSIA }
175    #[must_use] pub const fn indigo() -> Self { Self::INDIGO }
176    #[must_use] pub const fn gold() -> Self { Self::GOLD }
177    #[must_use] pub const fn coral() -> Self { Self::CORAL }
178    #[must_use] pub const fn salmon() -> Self { Self::SALMON }
179    #[must_use] pub const fn turquoise() -> Self { Self::TURQUOISE }
180    #[must_use] pub const fn violet() -> Self { Self::VIOLET }
181    #[must_use] pub const fn crimson() -> Self { Self::CRIMSON }
182    #[must_use] pub const fn chocolate() -> Self { Self::CHOCOLATE }
183    #[must_use] pub const fn sky_blue() -> Self { Self::SKY_BLUE }
184    #[must_use] pub const fn forest_green() -> Self { Self::FOREST_GREEN }
185    #[must_use] pub const fn sea_green() -> Self { Self::SEA_GREEN }
186    #[must_use] pub const fn slate_gray() -> Self { Self::SLATE_GRAY }
187    #[must_use] pub const fn midnight_blue() -> Self { Self::MIDNIGHT_BLUE }
188    #[must_use] pub const fn dark_red() -> Self { Self::DARK_RED }
189    #[must_use] pub const fn dark_green() -> Self { Self::DARK_GREEN }
190    #[must_use] pub const fn dark_blue() -> Self { Self::DARK_BLUE }
191    #[must_use] pub const fn light_blue() -> Self { Self::LIGHT_BLUE }
192    #[must_use] pub const fn light_green() -> Self { Self::LIGHT_GREEN }
193    #[must_use] pub const fn light_yellow() -> Self { Self::LIGHT_YELLOW }
194    #[must_use] pub const fn light_pink() -> Self { Self::LIGHT_PINK }
195
196    /// Creates a new color with RGBA values.
197    #[must_use] pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
198        Self { r, g, b, a }
199    }
200    /// Creates a new color with RGB values (alpha = 255).
201    #[must_use] pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
202        Self { r, g, b, a: 255 }
203    }
204    /// Alias for `rgba` - kept for internal compatibility, not exposed in FFI.
205    #[inline]
206    #[must_use] pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
207        Self::rgba(r, g, b, a)
208    }
209    /// Alias for `rgb` - kept for internal compatibility, not exposed in FFI.
210    #[inline]
211    #[must_use] pub const fn new_rgb(r: u8, g: u8, b: u8) -> Self {
212        Self::rgb(r, g, b)
213    }
214
215    /// Linearly interpolate all four RGBA channels between `self` and `other`.
216    /// `t = 0.0` returns `self`, `t = 1.0` returns `other`.
217    #[must_use] pub fn interpolate(&self, other: &Self, t: f32) -> Self {
218        Self {
219            r: channel_to_u8(libm::roundf(f32::from(self.r) + (f32::from(other.r) - f32::from(self.r)) * t)),
220            g: channel_to_u8(libm::roundf(f32::from(self.g) + (f32::from(other.g) - f32::from(self.g)) * t)),
221            b: channel_to_u8(libm::roundf(f32::from(self.b) + (f32::from(other.b) - f32::from(self.b)) * t)),
222            a: channel_to_u8(libm::roundf(f32::from(self.a) + (f32::from(other.a) - f32::from(self.a)) * t)),
223        }
224    }
225    
226    /// Lighten a color by a percentage (0.0 to 1.0).
227    /// Returns a new color blended towards white, preserving the original alpha.
228    #[must_use] pub fn lighten(&self, amount: f32) -> Self {
229        let mut c = self.interpolate(&Self::WHITE, amount.clamp(0.0, 1.0));
230        c.a = self.a;
231        c
232    }
233
234    /// Darken a color by a percentage (0.0 to 1.0).
235    /// Returns a new color blended towards black, preserving the original alpha.
236    #[must_use] pub fn darken(&self, amount: f32) -> Self {
237        let mut c = self.interpolate(&Self::BLACK, amount.clamp(0.0, 1.0));
238        c.a = self.a;
239        c
240    }
241    
242    /// Mix two colors together with a given ratio (0.0 = self, 1.0 = other).
243    #[must_use] pub fn mix(&self, other: &Self, ratio: f32) -> Self {
244        self.interpolate(other, ratio.clamp(0.0, 1.0))
245    }
246    
247    /// Create a hover variant (slightly lighter for dark colors, darker for light colors).
248    /// This is useful for button hover states.
249    #[must_use] pub fn hover_variant(&self) -> Self {
250        let luminance = self.relative_luminance();
251        if luminance > 0.5 {
252            self.darken(0.08)
253        } else {
254            self.lighten(0.12)
255        }
256    }
257
258    /// Create an active/pressed variant (darker than hover).
259    /// This is useful for button active states.
260    #[must_use] pub fn active_variant(&self) -> Self {
261        let luminance = self.relative_luminance();
262        if luminance > 0.5 {
263            self.darken(0.15)
264        } else {
265            self.lighten(0.05)
266        }
267    }
268    
269    /// Calculate approximate luminance (0.0 = black, 1.0 = white).
270    ///
271    /// **Note:** This applies BT.709 coefficients directly to gamma-encoded sRGB
272    /// values without linearizing first, so it is only an approximation.
273    /// For accurate results (e.g. WCAG contrast checks), use [`relative_luminance()`].
274    #[must_use] pub fn luminance(&self) -> f32 {
275        let r = f32::from(self.r) / 255.0;
276        let g = f32::from(self.g) / 255.0;
277        let b = f32::from(self.b) / 255.0;
278        0.2126 * r + 0.7152 * g + 0.0722 * b
279    }
280
281    /// Returns white or black text color for best contrast on this background.
282    #[must_use] pub fn contrast_text(&self) -> Self {
283        self.best_contrast_text()
284    }
285    
286    // ============================================================
287    // WCAG Accessibility and Contrast Helpers
288    // Based on W3C WCAG 2.1 guidelines and Chromium research
289    // ============================================================
290    
291    /// Converts a single sRGB channel to linear RGB.
292    /// Used for accurate luminance and contrast calculations.
293    fn srgb_to_linear(c: f32) -> f32 {
294        if c <= 0.03928 {
295            c / 12.92
296        } else {
297            libm::powf((c + 0.055) / 1.055, 2.4)
298        }
299    }
300    
301    /// Calculate relative luminance per WCAG 2.1 specification.
302    /// Returns a value between 0.0 (darkest) and 1.0 (lightest).
303    /// Uses the sRGB to linear conversion for accurate results.
304    #[must_use] pub fn relative_luminance(&self) -> f32 {
305        let r = Self::srgb_to_linear(f32::from(self.r) / 255.0);
306        let g = Self::srgb_to_linear(f32::from(self.g) / 255.0);
307        let b = Self::srgb_to_linear(f32::from(self.b) / 255.0);
308        0.2126 * r + 0.7152 * g + 0.0722 * b
309    }
310    
311    /// Calculate the contrast ratio between this color and another.
312    /// Returns a value between 1.0 (no contrast) and 21.0 (max contrast).
313    /// 
314    /// WCAG 2.1 requirements:
315    /// - AA normal text: >= 4.5:1
316    /// - AA large text: >= 3.0:1
317    /// - AAA normal text: >= 7.0:1
318    /// - AAA large text: >= 4.5:1
319    #[must_use] pub fn contrast_ratio(&self, other: &Self) -> f32 {
320        let l1 = self.relative_luminance();
321        let l2 = other.relative_luminance();
322        let lighter = if l1 > l2 { l1 } else { l2 };
323        let darker = if l1 > l2 { l2 } else { l1 };
324        (lighter + 0.05) / (darker + 0.05)
325    }
326    
327    /// Check if the contrast ratio meets WCAG AA requirements for normal text (>= 4.5:1).
328    #[must_use] pub fn meets_wcag_aa(&self, other: &Self) -> bool {
329        self.contrast_ratio(other) >= 4.5
330    }
331    
332    /// Check if the contrast ratio meets WCAG AA requirements for large text (>= 3.0:1).
333    /// Large text is defined as 18pt+ or 14pt+ bold.
334    #[must_use] pub fn meets_wcag_aa_large(&self, other: &Self) -> bool {
335        self.contrast_ratio(other) >= 3.0
336    }
337    
338    /// Check if the contrast ratio meets WCAG AAA requirements for normal text (>= 7.0:1).
339    #[must_use] pub fn meets_wcag_aaa(&self, other: &Self) -> bool {
340        self.contrast_ratio(other) >= 7.0
341    }
342    
343    /// Check if the contrast ratio meets WCAG AAA requirements for large text (>= 4.5:1).
344    #[must_use] pub fn meets_wcag_aaa_large(&self, other: &Self) -> bool {
345        self.contrast_ratio(other) >= 4.5
346    }
347    
348    /// Returns true if this color is considered "light" (relative luminance > 0.5).
349    /// Useful for determining if dark or light text should be used.
350    #[must_use] pub fn is_light(&self) -> bool {
351        self.relative_luminance() > 0.5
352    }
353
354    /// Returns true if this color is considered "dark" (relative luminance <= 0.5).
355    #[must_use] pub fn is_dark(&self) -> bool {
356        self.relative_luminance() <= 0.5
357    }
358    
359    /// Suggest the best text color (black or white) for this background,
360    /// ensuring WCAG AA compliance for normal text.
361    /// 
362    /// If neither black nor white meets AA requirements (unlikely), 
363    /// returns the one with higher contrast.
364    #[must_use] pub fn best_contrast_text(&self) -> Self {
365        let white_contrast = self.contrast_ratio(&Self::WHITE);
366        let black_contrast = self.contrast_ratio(&Self::BLACK);
367        
368        if white_contrast >= black_contrast {
369            Self::WHITE
370        } else {
371            Self::BLACK
372        }
373    }
374    
375    /// Adjust the color to ensure it meets the minimum contrast ratio against a background.
376    /// Lightens or darkens the color as needed.
377    /// 
378    /// Returns the original color if it already meets the requirement,
379    /// otherwise returns an adjusted color that meets the minimum contrast.
380    #[must_use] pub fn ensure_contrast(&self, background: &Self, min_ratio: f32) -> Self {
381        let current_ratio = self.contrast_ratio(background);
382        if current_ratio >= min_ratio {
383            return *self;
384        }
385        
386        // Determine if we should lighten or darken
387        let bg_luminance = background.relative_luminance();
388        let should_lighten = bg_luminance < 0.5;
389        
390        // Binary search for the right amount
391        let mut low = 0.0f32;
392        let mut high = 1.0f32;
393        let mut result = *self;
394        
395        for _ in 0..16 {
396            let mid = f32::midpoint(low, high);
397            let candidate = if should_lighten {
398                self.lighten(mid)
399            } else {
400                self.darken(mid)
401            };
402            
403            if candidate.contrast_ratio(background) >= min_ratio {
404                result = candidate;
405                high = mid;
406            } else {
407                low = mid;
408            }
409        }
410        
411        result
412    }
413    
414    /// Calculate the APCA (Accessible Perceptual Contrast Algorithm) contrast.
415    /// This is a newer algorithm that may replace WCAG contrast in future standards.
416    /// Returns a value between -108 (white on black) and 106 (black on white).
417    ///
418    /// **Note:** This is an approximation — it reuses the WCAG piecewise sRGB
419    /// linearization and BT.709 luminance coefficients rather than the APCA-specific
420    /// TRC exponents and coefficients from the full 0.0.98G specification.
421    ///
422    /// The sign indicates polarity (negative = light text on dark bg).
423    /// For most purposes, use the absolute value.
424    #[must_use] pub fn apca_contrast(&self, background: &Self) -> f32 {
425        // APCA 0.0.98G constants
426        const NORMBLKTXT: f32 = 0.56;
427        const NORMWHT: f32 = 0.57;
428        const REVTXT: f32 = 0.62;
429        const REVWHT: f32 = 0.65;
430        const BLKTHRS: f32 = 0.022;
431        const SCALEBLKT: f32 = 1.414;
432        const SCALEWHT: f32 = 1.14;
433
434        // Convert to Y (luminance) using sRGB TRC
435        let text_y = self.relative_luminance();
436        let bg_y = background.relative_luminance();
437        
438        // Soft clamp
439        let text_y = if text_y < 0.0 { 0.0 } else { text_y };
440        let bg_y = if bg_y < 0.0 { 0.0 } else { bg_y };
441        
442        
443        // Clamp black levels
444        let txt_clamp = if text_y < BLKTHRS { 
445            text_y + libm::powf(BLKTHRS - text_y, SCALEBLKT)
446        } else { 
447            text_y 
448        };
449        let bg_clamp = if bg_y < BLKTHRS { 
450            bg_y + libm::powf(BLKTHRS - bg_y, SCALEBLKT)
451        } else { 
452            bg_y 
453        };
454        
455        // Calculate contrast
456        if bg_clamp > txt_clamp {
457            // Dark text on light bg
458            let s = (libm::powf(bg_clamp, NORMWHT) - libm::powf(txt_clamp, NORMBLKTXT)) * SCALEWHT;
459            if s < 0.1 { 0.0 } else { s * 100.0 }
460        } else {
461            // Light text on dark bg
462            let s = (libm::powf(bg_clamp, REVWHT) - libm::powf(txt_clamp, REVTXT)) * SCALEWHT;
463            if s > -0.1 { 0.0 } else { s * 100.0 }
464        }
465    }
466    
467    /// Check if the APCA contrast meets the recommended minimum for body text (|Lc| >= 60).
468    #[must_use] pub fn meets_apca_body(&self, background: &Self) -> bool {
469        libm::fabsf(self.apca_contrast(background)) >= 60.0
470    }
471    
472    /// Check if the APCA contrast meets the minimum for large text (|Lc| >= 45).
473    #[must_use] pub fn meets_apca_large(&self, background: &Self) -> bool {
474        libm::fabsf(self.apca_contrast(background)) >= 45.0
475    }
476    
477    /// Set the alpha channel while keeping RGB values.
478    #[must_use] pub const fn with_alpha(&self, a: u8) -> Self {
479        Self { r: self.r, g: self.g, b: self.b, a }
480    }
481    
482    /// Set the alpha as a float (0.0 to 1.0).
483    #[must_use] pub fn with_alpha_f32(&self, a: f32) -> Self {
484        self.with_alpha(channel_to_u8(a.clamp(0.0, 1.0) * 255.0))
485    }
486    
487    /// Invert the color (keeping alpha).
488    #[must_use] pub const fn invert(&self) -> Self {
489        Self {
490            r: 255 - self.r,
491            g: 255 - self.g,
492            b: 255 - self.b,
493            a: self.a,
494        }
495    }
496    
497    /// Convert to grayscale using luminance weights.
498    #[must_use] pub fn to_grayscale(&self) -> Self {
499        let gray = channel_to_u8(0.299 * f32::from(self.r) + 0.587 * f32::from(self.g) + 0.114 * f32::from(self.b));
500        Self { r: gray, g: gray, b: gray, a: self.a }
501    }
502
503    /// Returns `true` if the alpha channel is not fully opaque (i.e. `a != 255`).
504    #[must_use] pub const fn has_alpha(&self) -> bool {
505        self.a != Self::ALPHA_OPAQUE
506    }
507
508    /// Format the color as an 8-digit lowercase hex string (e.g. `#ff0000ff`).
509    #[must_use] pub fn to_hash(&self) -> String {
510        format!("#{:02x}{:02x}{:02x}{:02x}", self.r, self.g, self.b, self.a)
511    }
512
513    // ============================================================
514    // Elementary OS color palette (with shade parameter 100-900)
515    // ============================================================
516
517    /// Strawberry color palette (shade: 100, 300, 500, 700, 900)
518    #[must_use] pub const fn strawberry(shade: usize) -> Self {
519        match shade {
520            0..=200 => Self::rgb(0xff, 0x8c, 0x82),   // 100: #ff8c82
521            201..=400 => Self::rgb(0xed, 0x53, 0x53), // 300: #ed5353
522            401..=600 => Self::rgb(0xc6, 0x26, 0x2e), // 500: #c6262e
523            601..=800 => Self::rgb(0xa1, 0x07, 0x05), // 700: #a10705
524            _ => Self::rgb(0x7a, 0x00, 0x00),         // 900: #7a0000
525        }
526    }
527
528    /// Orange color palette (shade: 100, 300, 500, 700, 900)
529    #[must_use] pub const fn palette_orange(shade: usize) -> Self {
530        match shade {
531            0..=200 => Self::rgb(0xff, 0xc2, 0x7d),   // 100: #ffc27d
532            201..=400 => Self::rgb(0xff, 0xa1, 0x54), // 300: #ffa154
533            401..=600 => Self::rgb(0xf3, 0x73, 0x29), // 500: #f37329
534            601..=800 => Self::rgb(0xcc, 0x3b, 0x02), // 700: #cc3b02
535            _ => Self::rgb(0xa6, 0x21, 0x00),         // 900: #a62100
536        }
537    }
538
539    /// Banana color palette (shade: 100, 300, 500, 700, 900)
540    #[must_use] pub const fn banana(shade: usize) -> Self {
541        match shade {
542            0..=200 => Self::rgb(0xff, 0xf3, 0x94),   // 100: #fff394
543            201..=400 => Self::rgb(0xff, 0xe1, 0x6b), // 300: #ffe16b
544            401..=600 => Self::rgb(0xf9, 0xc4, 0x40), // 500: #f9c440
545            601..=800 => Self::rgb(0xd4, 0x8e, 0x15), // 700: #d48e15
546            _ => Self::rgb(0xad, 0x5f, 0x00),         // 900: #ad5f00
547        }
548    }
549
550    /// Lime color palette (shade: 100, 300, 500, 700, 900)
551    #[must_use] pub const fn palette_lime(shade: usize) -> Self {
552        match shade {
553            0..=200 => Self::rgb(0xd1, 0xff, 0x82),   // 100: #d1ff82
554            201..=400 => Self::rgb(0x9b, 0xdb, 0x4d), // 300: #9bdb4d
555            401..=600 => Self::rgb(0x68, 0xb7, 0x23), // 500: #68b723
556            601..=800 => Self::rgb(0x3a, 0x91, 0x04), // 700: #3a9104
557            _ => Self::rgb(0x20, 0x6b, 0x00),         // 900: #206b00
558        }
559    }
560
561    /// Mint color palette (shade: 100, 300, 500, 700, 900)
562    #[must_use] pub const fn mint(shade: usize) -> Self {
563        match shade {
564            0..=200 => Self::rgb(0x89, 0xff, 0xdd),   // 100: #89ffdd
565            201..=400 => Self::rgb(0x43, 0xd6, 0xb5), // 300: #43d6b5
566            401..=600 => Self::rgb(0x28, 0xbc, 0xa3), // 500: #28bca3
567            601..=800 => Self::rgb(0x0e, 0x9a, 0x83), // 700: #0e9a83
568            _ => Self::rgb(0x00, 0x73, 0x67),         // 900: #007367
569        }
570    }
571
572    /// Blueberry color palette (shade: 100, 300, 500, 700, 900)
573    #[must_use] pub const fn blueberry(shade: usize) -> Self {
574        match shade {
575            0..=200 => Self::rgb(0x8c, 0xd5, 0xff),   // 100: #8cd5ff
576            201..=400 => Self::rgb(0x64, 0xba, 0xff), // 300: #64baff
577            401..=600 => Self::rgb(0x36, 0x89, 0xe6), // 500: #3689e6
578            601..=800 => Self::rgb(0x0d, 0x52, 0xbf), // 700: #0d52bf
579            _ => Self::rgb(0x00, 0x2e, 0x99),         // 900: #002e99
580        }
581    }
582
583    /// Grape color palette (shade: 100, 300, 500, 700, 900)
584    #[must_use] pub const fn grape(shade: usize) -> Self {
585        match shade {
586            0..=200 => Self::rgb(0xe4, 0xc6, 0xfa),   // 100: #e4c6fa
587            201..=400 => Self::rgb(0xcd, 0x9e, 0xf7), // 300: #cd9ef7
588            401..=600 => Self::rgb(0xa5, 0x6d, 0xe2), // 500: #a56de2
589            601..=800 => Self::rgb(0x72, 0x39, 0xb3), // 700: #7239b3
590            _ => Self::rgb(0x45, 0x29, 0x81),         // 900: #452981
591        }
592    }
593
594    /// Bubblegum color palette (shade: 100, 300, 500, 700, 900)
595    #[must_use] pub const fn bubblegum(shade: usize) -> Self {
596        match shade {
597            0..=200 => Self::rgb(0xfe, 0x9a, 0xb8),   // 100: #fe9ab8
598            201..=400 => Self::rgb(0xf4, 0x67, 0x9d), // 300: #f4679d
599            401..=600 => Self::rgb(0xde, 0x3e, 0x80), // 500: #de3e80
600            601..=800 => Self::rgb(0xbc, 0x24, 0x5d), // 700: #bc245d
601            _ => Self::rgb(0x91, 0x0e, 0x38),         // 900: #910e38
602        }
603    }
604
605    /// Cocoa color palette (shade: 100, 300, 500, 700, 900)
606    #[must_use] pub const fn cocoa(shade: usize) -> Self {
607        match shade {
608            0..=200 => Self::rgb(0xa3, 0x90, 0x7c),   // 100: #a3907c
609            201..=400 => Self::rgb(0x8a, 0x71, 0x5e), // 300: #8a715e
610            401..=600 => Self::rgb(0x71, 0x53, 0x44), // 500: #715344
611            601..=800 => Self::rgb(0x57, 0x39, 0x2d), // 700: #57392d
612            _ => Self::rgb(0x3d, 0x21, 0x1b),         // 900: #3d211b
613        }
614    }
615
616    /// Silver color palette (shade: 100, 300, 500, 700, 900)
617    #[must_use] pub const fn palette_silver(shade: usize) -> Self {
618        match shade {
619            0..=200 => Self::rgb(0xfa, 0xfa, 0xfa),   // 100: #fafafa
620            201..=400 => Self::rgb(0xd4, 0xd4, 0xd4), // 300: #d4d4d4
621            401..=600 => Self::rgb(0xab, 0xac, 0xae), // 500: #abacae
622            601..=800 => Self::rgb(0x7e, 0x80, 0x87), // 700: #7e8087
623            _ => Self::rgb(0x55, 0x57, 0x61),         // 900: #555761
624        }
625    }
626
627    /// Slate color palette (shade: 100, 300, 500, 700, 900)
628    #[must_use] pub const fn slate(shade: usize) -> Self {
629        match shade {
630            0..=200 => Self::rgb(0x95, 0xa3, 0xab),   // 100: #95a3ab
631            201..=400 => Self::rgb(0x66, 0x78, 0x85), // 300: #667885
632            401..=600 => Self::rgb(0x48, 0x5a, 0x6c), // 500: #485a6c
633            601..=800 => Self::rgb(0x27, 0x34, 0x45), // 700: #273445
634            _ => Self::rgb(0x0e, 0x14, 0x1f),         // 900: #0e141f
635        }
636    }
637
638    /// Dark color palette (shade: 100, 300, 500, 700, 900)
639    #[must_use] pub const fn dark(shade: usize) -> Self {
640        match shade {
641            0..=200 => Self::rgb(0x66, 0x66, 0x66),   // 100: #666
642            201..=400 => Self::rgb(0x4d, 0x4d, 0x4d), // 300: #4d4d4d
643            401..=600 => Self::rgb(0x33, 0x33, 0x33), // 500: #333
644            601..=800 => Self::rgb(0x1a, 0x1a, 0x1a), // 700: #1a1a1a
645            _ => Self::rgb(0x00, 0x00, 0x00),         // 900: #000
646        }
647    }
648
649    // ============================================================
650    // Apple System Colors (light and dark variants)
651    // ============================================================
652
653    /// Apple Red (light mode)
654    #[must_use] pub const fn apple_red() -> Self { Self::rgb(255, 59, 48) }
655    /// Apple Red (dark mode)
656    #[must_use] pub const fn apple_red_dark() -> Self { Self::rgb(255, 69, 58) }
657    /// Apple Orange (light mode)
658    #[must_use] pub const fn apple_orange() -> Self { Self::rgb(255, 149, 0) }
659    /// Apple Orange (dark mode)
660    #[must_use] pub const fn apple_orange_dark() -> Self { Self::rgb(255, 159, 10) }
661    /// Apple Yellow (light mode)
662    #[must_use] pub const fn apple_yellow() -> Self { Self::rgb(255, 204, 0) }
663    /// Apple Yellow (dark mode)
664    #[must_use] pub const fn apple_yellow_dark() -> Self { Self::rgb(255, 214, 10) }
665    /// Apple Green (light mode)
666    #[must_use] pub const fn apple_green() -> Self { Self::rgb(40, 205, 65) }
667    /// Apple Green (dark mode)
668    #[must_use] pub const fn apple_green_dark() -> Self { Self::rgb(40, 215, 75) }
669    /// Apple Mint (light mode)
670    #[must_use] pub const fn apple_mint() -> Self { Self::rgb(0, 199, 190) }
671    /// Apple Mint (dark mode)
672    #[must_use] pub const fn apple_mint_dark() -> Self { Self::rgb(102, 212, 207) }
673    /// Apple Teal (light mode)
674    #[must_use] pub const fn apple_teal() -> Self { Self::rgb(89, 173, 196) }
675    /// Apple Teal (dark mode)
676    #[must_use] pub const fn apple_teal_dark() -> Self { Self::rgb(106, 196, 220) }
677    /// Apple Cyan (light mode)
678    #[must_use] pub const fn apple_cyan() -> Self { Self::rgb(85, 190, 240) }
679    /// Apple Cyan (dark mode)
680    #[must_use] pub const fn apple_cyan_dark() -> Self { Self::rgb(90, 200, 245) }
681    /// Apple Blue (light mode)
682    #[must_use] pub const fn apple_blue() -> Self { Self::rgb(0, 122, 255) }
683    /// Apple Blue (dark mode)
684    #[must_use] pub const fn apple_blue_dark() -> Self { Self::rgb(10, 132, 255) }
685    /// Apple Indigo (light mode)
686    #[must_use] pub const fn apple_indigo() -> Self { Self::rgb(88, 86, 214) }
687    /// Apple Indigo (dark mode)
688    #[must_use] pub const fn apple_indigo_dark() -> Self { Self::rgb(94, 92, 230) }
689    /// Apple Purple (light mode)
690    #[must_use] pub const fn apple_purple() -> Self { Self::rgb(175, 82, 222) }
691    /// Apple Purple (dark mode)
692    #[must_use] pub const fn apple_purple_dark() -> Self { Self::rgb(191, 90, 242) }
693    /// Apple Pink (light mode)
694    #[must_use] pub const fn apple_pink() -> Self { Self::rgb(255, 45, 85) }
695    /// Apple Pink (dark mode)
696    #[must_use] pub const fn apple_pink_dark() -> Self { Self::rgb(255, 55, 95) }
697    /// Apple Brown (light mode)
698    #[must_use] pub const fn apple_brown() -> Self { Self::rgb(162, 132, 94) }
699    /// Apple Brown (dark mode)
700    #[must_use] pub const fn apple_brown_dark() -> Self { Self::rgb(172, 142, 104) }
701    /// Apple Gray (light mode)
702    #[must_use] pub const fn apple_gray() -> Self { Self::rgb(142, 142, 147) }
703    /// Apple Gray (dark mode)
704    #[must_use] pub const fn apple_gray_dark() -> Self { Self::rgb(152, 152, 157) }
705
706    // ============================================================
707    // Bootstrap-style semantic button colors
708    // These provide consistent button styling across platforms
709    // ============================================================
710
711    /// Primary button color (blue) - used for main actions
712    #[must_use] pub const fn bootstrap_primary() -> Self { Self::rgb(13, 110, 253) }
713    #[must_use] pub const fn bootstrap_primary_hover() -> Self { Self::rgb(11, 94, 215) }
714    #[must_use] pub const fn bootstrap_primary_active() -> Self { Self::rgb(10, 88, 202) }
715    
716    /// Secondary button color (gray) - used for secondary actions
717    #[must_use] pub const fn bootstrap_secondary() -> Self { Self::rgb(108, 117, 125) }
718    #[must_use] pub const fn bootstrap_secondary_hover() -> Self { Self::rgb(92, 99, 106) }
719    #[must_use] pub const fn bootstrap_secondary_active() -> Self { Self::rgb(86, 94, 100) }
720    
721    /// Success button color (green) - used for confirmations
722    #[must_use] pub const fn bootstrap_success() -> Self { Self::rgb(25, 135, 84) }
723    #[must_use] pub const fn bootstrap_success_hover() -> Self { Self::rgb(21, 115, 71) }
724    #[must_use] pub const fn bootstrap_success_active() -> Self { Self::rgb(20, 108, 67) }
725    
726    /// Danger button color (red) - used for destructive actions
727    #[must_use] pub const fn bootstrap_danger() -> Self { Self::rgb(220, 53, 69) }
728    #[must_use] pub const fn bootstrap_danger_hover() -> Self { Self::rgb(187, 45, 59) }
729    #[must_use] pub const fn bootstrap_danger_active() -> Self { Self::rgb(176, 42, 55) }
730    
731    /// Warning button color (yellow) - used for warnings, uses BLACK text
732    #[must_use] pub const fn bootstrap_warning() -> Self { Self::rgb(255, 193, 7) }
733    #[must_use] pub const fn bootstrap_warning_hover() -> Self { Self::rgb(255, 202, 44) }
734    #[must_use] pub const fn bootstrap_warning_active() -> Self { Self::rgb(255, 205, 57) }
735    
736    /// Info button color (teal/cyan) - used for informational actions
737    #[must_use] pub const fn bootstrap_info() -> Self { Self::rgb(13, 202, 240) }
738    #[must_use] pub const fn bootstrap_info_hover() -> Self { Self::rgb(49, 210, 242) }
739    #[must_use] pub const fn bootstrap_info_active() -> Self { Self::rgb(61, 213, 243) }
740    
741    /// Light button color - used for light-themed buttons
742    #[must_use] pub const fn bootstrap_light() -> Self { Self::rgb(248, 249, 250) }
743    #[must_use] pub const fn bootstrap_light_hover() -> Self { Self::rgb(233, 236, 239) }
744    #[must_use] pub const fn bootstrap_light_active() -> Self { Self::rgb(218, 222, 226) }
745    
746    /// Dark button color - used for dark-themed buttons
747    #[must_use] pub const fn bootstrap_dark() -> Self { Self::rgb(33, 37, 41) }
748    #[must_use] pub const fn bootstrap_dark_hover() -> Self { Self::rgb(66, 70, 73) }
749    #[must_use] pub const fn bootstrap_dark_active() -> Self { Self::rgb(78, 81, 84) }
750    
751    /// Link button text color
752    #[must_use] pub const fn bootstrap_link() -> Self { Self::rgb(13, 110, 253) }
753    #[must_use] pub const fn bootstrap_link_hover() -> Self { Self::rgb(10, 88, 202) }
754}
755
756/// f32-based color, range 0.0 to 1.0 (similar to webrenders `ColorF`)
757#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
758pub struct ColorF {
759    pub r: f32,
760    pub g: f32,
761    pub b: f32,
762    pub a: f32,
763}
764
765impl Default for ColorF {
766    fn default() -> Self {
767        Self::BLACK
768    }
769}
770
771impl fmt::Display for ColorF {
772    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
773        write!(
774            f,
775            "rgba({}, {}, {}, {})",
776            self.r * 255.0,
777            self.g * 255.0,
778            self.b * 255.0,
779            self.a
780        )
781    }
782}
783
784impl ColorF {
785    pub const ALPHA_TRANSPARENT: f32 = 0.0;
786    pub const ALPHA_OPAQUE: f32 = 1.0;
787    pub const WHITE: Self = Self {
788        r: 1.0,
789        g: 1.0,
790        b: 1.0,
791        a: Self::ALPHA_OPAQUE,
792    };
793    pub const BLACK: Self = Self {
794        r: 0.0,
795        g: 0.0,
796        b: 0.0,
797        a: Self::ALPHA_OPAQUE,
798    };
799    pub const TRANSPARENT: Self = Self {
800        r: 0.0,
801        g: 0.0,
802        b: 0.0,
803        a: Self::ALPHA_TRANSPARENT,
804    };
805}
806
807impl From<ColorU> for ColorF {
808    fn from(input: ColorU) -> Self {
809        Self {
810            r: f32::from(input.r) / 255.0,
811            g: f32::from(input.g) / 255.0,
812            b: f32::from(input.b) / 255.0,
813            a: f32::from(input.a) / 255.0,
814        }
815    }
816}
817
818impl From<ColorF> for ColorU {
819    fn from(input: ColorF) -> Self {
820        Self {
821            r: channel_to_u8(input.r.min(1.0) * 255.0),
822            g: channel_to_u8(input.g.min(1.0) * 255.0),
823            b: channel_to_u8(input.b.min(1.0) * 255.0),
824            a: channel_to_u8(input.a.min(1.0) * 255.0),
825        }
826    }
827}
828
829/// A color reference that can be either a concrete color or a system color.
830/// System colors are lazily evaluated at runtime based on the user's system theme.
831/// 
832/// CSS syntax: `system:accent`, `system:text`, `system:background`, etc.
833#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
834#[repr(C, u8)]
835pub enum ColorOrSystem {
836    /// A concrete RGBA color value.
837    Color(ColorU),
838    /// A reference to a system color, resolved at runtime.
839    System(SystemColorRef),
840}
841
842impl Default for ColorOrSystem {
843    fn default() -> Self {
844        Self::Color(ColorU::BLACK)
845    }
846}
847
848impl From<ColorU> for ColorOrSystem {
849    fn from(color: ColorU) -> Self {
850        Self::Color(color)
851    }
852}
853
854impl ColorOrSystem {
855    /// Create a new `ColorOrSystem` from a concrete color.
856    #[must_use] pub const fn color(c: ColorU) -> Self {
857        Self::Color(c)
858    }
859    
860    /// Create a new `ColorOrSystem` from a system color reference.
861    #[must_use] pub const fn system(s: SystemColorRef) -> Self {
862        Self::System(s)
863    }
864    
865    /// Resolve the color against a `SystemColors` struct.
866    /// Returns the system color if available, or falls back to the provided default.
867    #[must_use] pub fn resolve(&self, system_colors: &crate::system::SystemColors, fallback: ColorU) -> ColorU {
868        match self {
869            Self::Color(c) => *c,
870            Self::System(ref_type) => ref_type.resolve(system_colors, fallback),
871        }
872    }
873    
874    /// Returns the concrete color if available, or a default fallback for system colors.
875    /// Use this when `SystemColors` is not available (e.g., during rendering setup).
876    #[must_use] pub const fn to_color_u_with_fallback(&self, fallback: ColorU) -> ColorU {
877        match self {
878            Self::Color(c) => *c,
879            Self::System(_) => fallback,
880        }
881    }
882    
883    /// Returns the concrete color if available, or a gray fallback for system colors.
884    #[must_use] pub const fn to_color_u_default(&self) -> ColorU {
885        self.to_color_u_with_fallback(ColorU { r: 128, g: 128, b: 128, a: 255 })
886    }
887}
888
889/// Reference to a specific system color.
890/// These are resolved at runtime based on the user's system preferences.
891#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
892#[repr(C)]
893pub enum SystemColorRef {
894    /// System text color (e.g., black on light theme, white on dark)
895    Text,
896    /// System background color
897    Background,
898    /// System accent color (user-selected highlight color)
899    Accent,
900    /// Text color when on accent background
901    AccentText,
902    /// Button face background color
903    ButtonFace,
904    /// Button text color
905    ButtonText,
906    /// Window/panel background color
907    WindowBackground,
908    /// Selection/highlight background color
909    SelectionBackground,
910    /// Text color when selected
911    SelectionText,
912}
913
914impl SystemColorRef {
915    /// Resolve this system color reference against actual system colors.
916    #[must_use] pub fn resolve(&self, colors: &crate::system::SystemColors, fallback: ColorU) -> ColorU {
917        match self {
918            Self::Text => colors.text.as_option().copied().unwrap_or(fallback),
919            Self::Background => colors.background.as_option().copied().unwrap_or(fallback),
920            Self::Accent => colors.accent.as_option().copied().unwrap_or(fallback),
921            Self::AccentText => colors.accent_text.as_option().copied().unwrap_or(fallback),
922            Self::ButtonFace => colors.button_face.as_option().copied().unwrap_or(fallback),
923            Self::ButtonText => colors.button_text.as_option().copied().unwrap_or(fallback),
924            Self::WindowBackground => colors.window_background.as_option().copied().unwrap_or(fallback),
925            Self::SelectionBackground => colors.selection_background.as_option().copied().unwrap_or(fallback),
926            Self::SelectionText => colors.selection_text.as_option().copied().unwrap_or(fallback),
927        }
928    }
929    
930    /// Get the CSS syntax for this system color reference.
931    #[must_use] pub const fn as_css_str(&self) -> &'static str {
932        match self {
933            Self::Text => "system:text",
934            Self::Background => "system:background",
935            Self::Accent => "system:accent",
936            Self::AccentText => "system:accent-text",
937            Self::ButtonFace => "system:button-face",
938            Self::ButtonText => "system:button-text",
939            Self::WindowBackground => "system:window-background",
940            Self::SelectionBackground => "system:selection-background",
941            Self::SelectionText => "system:selection-text",
942        }
943    }
944}
945
946// --- PARSER ---
947
948#[derive(Debug, Copy, Clone, PartialEq, Eq)]
949#[repr(C)]
950pub enum CssColorComponent {
951    Red,
952    Green,
953    Blue,
954    Hue,
955    Saturation,
956    Lightness,
957    Alpha,
958}
959
960#[derive(Clone, PartialEq)]
961pub enum CssColorParseError<'a> {
962    InvalidColor(&'a str),
963    InvalidFunctionName(&'a str),
964    InvalidColorComponent(u8),
965    IntValueParseErr(ParseIntError),
966    FloatValueParseErr(ParseFloatError),
967    FloatValueOutOfRange(f32),
968    MissingColorComponent(CssColorComponent),
969    ExtraArguments(&'a str),
970    UnclosedColor(&'a str),
971    EmptyInput,
972    DirectionParseError(CssDirectionParseError<'a>),
973    UnsupportedDirection(&'a str),
974    InvalidPercentage(PercentageParseError),
975}
976
977impl_debug_as_display!(CssColorParseError<'a>);
978impl_display! {CssColorParseError<'a>, {
979    InvalidColor(i) => format!("Invalid CSS color: \"{}\"", i),
980    InvalidFunctionName(i) => format!("Invalid function name, expected one of: \"rgb\", \"rgba\", \"hsl\", \"hsla\" got: \"{}\"", i),
981    InvalidColorComponent(i) => format!("Invalid color component when parsing CSS color: \"{}\"", i),
982    IntValueParseErr(e) => format!("CSS color component: Value not in range between 00 - FF: \"{}\"", e),
983    FloatValueParseErr(e) => format!("CSS color component: Value cannot be parsed as floating point number: \"{}\"", e),
984    FloatValueOutOfRange(v) => format!("CSS color component: Value not in range between 0.0 - 1.0: \"{}\"", v),
985    MissingColorComponent(c) => format!("CSS color is missing {:?} component", c),
986    ExtraArguments(a) => format!("Extra argument to CSS color: \"{}\"", a),
987    EmptyInput => format!("Empty color string."),
988    UnclosedColor(i) => format!("Unclosed color: \"{}\"", i),
989    DirectionParseError(e) => format!("Could not parse direction argument for CSS color: \"{}\"", e),
990    UnsupportedDirection(d) => format!("Unsupported direction type for CSS color: \"{}\"", d),
991    InvalidPercentage(p) => format!("Invalid percentage when parsing CSS color: \"{}\"", p),
992}}
993
994impl From<ParseIntError> for CssColorParseError<'_> {
995    fn from(e: ParseIntError) -> Self {
996        CssColorParseError::IntValueParseErr(e)
997    }
998}
999impl From<ParseFloatError> for CssColorParseError<'_> {
1000    fn from(e: ParseFloatError) -> Self {
1001        CssColorParseError::FloatValueParseErr(e)
1002    }
1003}
1004impl From<core::num::ParseIntError> for CssColorParseError<'_> {
1005    fn from(e: core::num::ParseIntError) -> Self {
1006        CssColorParseError::IntValueParseErr(ParseIntError::from(e))
1007    }
1008}
1009impl From<core::num::ParseFloatError> for CssColorParseError<'_> {
1010    fn from(e: core::num::ParseFloatError) -> Self {
1011        CssColorParseError::FloatValueParseErr(ParseFloatError::from(e))
1012    }
1013}
1014impl_from!(
1015    CssDirectionParseError<'a>,
1016    CssColorParseError::DirectionParseError
1017);
1018
1019#[derive(Debug, Clone, PartialEq)]
1020#[repr(C, u8)]
1021pub enum CssColorParseErrorOwned {
1022    InvalidColor(AzString),
1023    InvalidFunctionName(AzString),
1024    InvalidColorComponent(u8),
1025    IntValueParseErr(ParseIntError),
1026    FloatValueParseErr(ParseFloatError),
1027    FloatValueOutOfRange(f32),
1028    MissingColorComponent(CssColorComponent),
1029    ExtraArguments(AzString),
1030    UnclosedColor(AzString),
1031    EmptyInput,
1032    DirectionParseError(CssDirectionParseErrorOwned),
1033    UnsupportedDirection(AzString),
1034    InvalidPercentage(PercentageParseError),
1035}
1036
1037impl CssColorParseError<'_> {
1038    #[must_use] pub fn to_contained(&self) -> CssColorParseErrorOwned {
1039        match self {
1040            CssColorParseError::InvalidColor(s) => {
1041                CssColorParseErrorOwned::InvalidColor((*s).to_string().into())
1042            }
1043            CssColorParseError::InvalidFunctionName(s) => {
1044                CssColorParseErrorOwned::InvalidFunctionName((*s).to_string().into())
1045            }
1046            CssColorParseError::InvalidColorComponent(n) => {
1047                CssColorParseErrorOwned::InvalidColorComponent(*n)
1048            }
1049            CssColorParseError::IntValueParseErr(e) => {
1050                CssColorParseErrorOwned::IntValueParseErr(*e)
1051            }
1052            CssColorParseError::FloatValueParseErr(e) => {
1053                CssColorParseErrorOwned::FloatValueParseErr(*e)
1054            }
1055            CssColorParseError::FloatValueOutOfRange(n) => {
1056                CssColorParseErrorOwned::FloatValueOutOfRange(*n)
1057            }
1058            CssColorParseError::MissingColorComponent(c) => {
1059                CssColorParseErrorOwned::MissingColorComponent(*c)
1060            }
1061            CssColorParseError::ExtraArguments(s) => {
1062                CssColorParseErrorOwned::ExtraArguments((*s).to_string().into())
1063            }
1064            CssColorParseError::UnclosedColor(s) => {
1065                CssColorParseErrorOwned::UnclosedColor((*s).to_string().into())
1066            }
1067            CssColorParseError::EmptyInput => CssColorParseErrorOwned::EmptyInput,
1068            CssColorParseError::DirectionParseError(e) => {
1069                CssColorParseErrorOwned::DirectionParseError(e.to_contained())
1070            }
1071            CssColorParseError::UnsupportedDirection(s) => {
1072                CssColorParseErrorOwned::UnsupportedDirection((*s).to_string().into())
1073            }
1074            CssColorParseError::InvalidPercentage(e) => {
1075                CssColorParseErrorOwned::InvalidPercentage(e.clone())
1076            }
1077        }
1078    }
1079}
1080
1081impl CssColorParseErrorOwned {
1082    #[must_use] pub fn to_shared(&self) -> CssColorParseError<'_> {
1083        match self {
1084            Self::InvalidColor(s) => CssColorParseError::InvalidColor(s),
1085            Self::InvalidFunctionName(s) => {
1086                CssColorParseError::InvalidFunctionName(s)
1087            }
1088            Self::InvalidColorComponent(n) => {
1089                CssColorParseError::InvalidColorComponent(*n)
1090            }
1091            Self::IntValueParseErr(e) => {
1092                CssColorParseError::IntValueParseErr(*e)
1093            }
1094            Self::FloatValueParseErr(e) => {
1095                CssColorParseError::FloatValueParseErr(*e)
1096            }
1097            Self::FloatValueOutOfRange(n) => {
1098                CssColorParseError::FloatValueOutOfRange(*n)
1099            }
1100            Self::MissingColorComponent(c) => {
1101                CssColorParseError::MissingColorComponent(*c)
1102            }
1103            Self::ExtraArguments(s) => CssColorParseError::ExtraArguments(s),
1104            Self::UnclosedColor(s) => CssColorParseError::UnclosedColor(s),
1105            Self::EmptyInput => CssColorParseError::EmptyInput,
1106            Self::DirectionParseError(e) => {
1107                CssColorParseError::DirectionParseError(e.to_shared())
1108            }
1109            Self::UnsupportedDirection(s) => {
1110                CssColorParseError::UnsupportedDirection(s)
1111            }
1112            Self::InvalidPercentage(e) => {
1113                CssColorParseError::InvalidPercentage(e.clone())
1114            }
1115        }
1116    }
1117}
1118
1119#[cfg(feature = "parser")]
1120/// # Errors
1121///
1122/// Returns an error if `input` is not a valid CSS `css-color` value.
1123pub fn parse_css_color(input: &str) -> Result<ColorU, CssColorParseError<'_>> {
1124    use crate::props::basic::parse::{parse_parentheses, ParenthesisParseError};
1125
1126    let input = input.trim();
1127    if let Some(rest) = input.strip_prefix('#') {
1128        return parse_color_no_hash(rest);
1129    }
1130
1131    match parse_parentheses(input, &["rgba", "rgb", "hsla", "hsl"]) {
1132        Ok((stopword, inner_value)) => match stopword {
1133            "rgba" => parse_color_rgb(inner_value, true),
1134            "rgb" => parse_color_rgb(inner_value, false),
1135            "hsla" => parse_color_hsl(inner_value, true),
1136            "hsl" => parse_color_hsl(inner_value, false),
1137            _ => unreachable!(),
1138        },
1139        Err(e) => match e {
1140            ParenthesisParseError::UnclosedBraces | ParenthesisParseError::NoClosingBraceFound => {
1141                Err(CssColorParseError::UnclosedColor(input))
1142            }
1143            ParenthesisParseError::EmptyInput => Err(CssColorParseError::EmptyInput),
1144            ParenthesisParseError::StopWordNotFound(stopword) => {
1145                Err(CssColorParseError::InvalidFunctionName(stopword))
1146            }
1147            ParenthesisParseError::NoOpeningBraceFound => parse_color_builtin(input),
1148        },
1149    }
1150}
1151
1152/// Parse a color that can be either a concrete color or a system color reference.
1153/// 
1154/// Supports all standard CSS color formats plus:
1155/// - `system:accent` - System accent/highlight color
1156/// - `system:text` - System text color
1157/// - `system:background` - System background color
1158/// - `system:selection-background` - Selection/highlight background
1159/// - `system:selection-text` - Text color when selected
1160/// - `system:button-face` - Button background color
1161/// - `system:button-text` - Button text color
1162/// - `system:window-background` - Window background color
1163/// - `system:accent-text` - Text color on accent background
1164#[cfg(feature = "parser")]
1165/// # Errors
1166///
1167/// Returns an error if `input` is not a valid CSS `color-or-system` value.
1168pub fn parse_color_or_system(input: &str) -> Result<ColorOrSystem, CssColorParseError<'_>> {
1169    let input = input.trim();
1170    
1171    // Check for system color syntax: "system:name"
1172    if let Some(system_name) = input.strip_prefix("system:") {
1173        let system_ref = match system_name.trim() {
1174            "text" => SystemColorRef::Text,
1175            "background" => SystemColorRef::Background,
1176            "accent" => SystemColorRef::Accent,
1177            "accent-text" => SystemColorRef::AccentText,
1178            "button-face" => SystemColorRef::ButtonFace,
1179            "button-text" => SystemColorRef::ButtonText,
1180            "window-background" => SystemColorRef::WindowBackground,
1181            "selection-background" => SystemColorRef::SelectionBackground,
1182            "selection-text" => SystemColorRef::SelectionText,
1183            _ => return Err(CssColorParseError::InvalidColor(input)),
1184        };
1185        return Ok(ColorOrSystem::System(system_ref));
1186    }
1187    
1188    // Otherwise parse as regular color
1189    parse_css_color(input).map(ColorOrSystem::Color)
1190}
1191
1192#[cfg(feature = "parser")]
1193fn parse_color_no_hash(input: &str) -> Result<ColorU, CssColorParseError<'_>> {
1194    #[inline]
1195    const fn from_hex<'a>(c: u8) -> Result<u8, CssColorParseError<'a>> {
1196        match c {
1197            b'0'..=b'9' => Ok(c - b'0'),
1198            b'a'..=b'f' => Ok(c - b'a' + 10),
1199            b'A'..=b'F' => Ok(c - b'A' + 10),
1200            _ => Err(CssColorParseError::InvalidColorComponent(c)),
1201        }
1202    }
1203
1204    match input.len() {
1205        3 => {
1206            let mut bytes = input.bytes();
1207            let r = bytes.next().unwrap();
1208            let g = bytes.next().unwrap();
1209            let b = bytes.next().unwrap();
1210            Ok(ColorU::new_rgb(
1211                from_hex(r)? * 17,
1212                from_hex(g)? * 17,
1213                from_hex(b)? * 17,
1214            ))
1215        }
1216        4 => {
1217            let mut bytes = input.bytes();
1218            let r = bytes.next().unwrap();
1219            let g = bytes.next().unwrap();
1220            let b = bytes.next().unwrap();
1221            let a = bytes.next().unwrap();
1222            Ok(ColorU::new(
1223                from_hex(r)? * 17,
1224                from_hex(g)? * 17,
1225                from_hex(b)? * 17,
1226                from_hex(a)? * 17,
1227            ))
1228        }
1229        6 => {
1230            let val = u32::from_str_radix(input, 16)?;
1231            Ok(ColorU::new_rgb(
1232                ((val >> 16) & 0xFF) as u8,
1233                ((val >> 8) & 0xFF) as u8,
1234                (val & 0xFF) as u8,
1235            ))
1236        }
1237        8 => {
1238            let val = u32::from_str_radix(input, 16)?;
1239            Ok(ColorU::new(
1240                ((val >> 24) & 0xFF) as u8,
1241                ((val >> 16) & 0xFF) as u8,
1242                ((val >> 8) & 0xFF) as u8,
1243                (val & 0xFF) as u8,
1244            ))
1245        }
1246        _ => Err(CssColorParseError::InvalidColor(input)),
1247    }
1248}
1249
1250#[cfg(feature = "parser")]
1251fn parse_color_rgb(
1252    input: &str,
1253    parse_alpha: bool,
1254) -> Result<ColorU, CssColorParseError<'_>> {
1255    let mut components = input.split(',').map(str::trim);
1256    let rgb_color = parse_color_rgb_components(&mut components)?;
1257    let a = if parse_alpha {
1258        parse_alpha_component(&mut components)?
1259    } else {
1260        255
1261    };
1262    if let Some(arg) = components.next() {
1263        return Err(CssColorParseError::ExtraArguments(arg));
1264    }
1265    Ok(ColorU { a, ..rgb_color })
1266}
1267
1268#[cfg(feature = "parser")]
1269fn parse_color_rgb_components<'a>(
1270    components: &mut dyn Iterator<Item = &'a str>,
1271) -> Result<ColorU, CssColorParseError<'a>> {
1272    #[inline]
1273    fn component_from_str<'a>(
1274        components: &mut dyn Iterator<Item = &'a str>,
1275        which: CssColorComponent,
1276    ) -> Result<u8, CssColorParseError<'a>> {
1277        let c = components
1278            .next()
1279            .ok_or(CssColorParseError::MissingColorComponent(which))?;
1280        if c.is_empty() {
1281            return Err(CssColorParseError::MissingColorComponent(which));
1282        }
1283        Ok(c.parse::<u8>()?)
1284    }
1285    Ok(ColorU {
1286        r: component_from_str(components, CssColorComponent::Red)?,
1287        g: component_from_str(components, CssColorComponent::Green)?,
1288        b: component_from_str(components, CssColorComponent::Blue)?,
1289        a: 255,
1290    })
1291}
1292
1293#[cfg(feature = "parser")]
1294fn parse_color_hsl(
1295    input: &str,
1296    parse_alpha: bool,
1297) -> Result<ColorU, CssColorParseError<'_>> {
1298    let mut components = input.split(',').map(str::trim);
1299    let rgb_color = parse_color_hsl_components(&mut components)?;
1300    let a = if parse_alpha {
1301        parse_alpha_component(&mut components)?
1302    } else {
1303        255
1304    };
1305    if let Some(arg) = components.next() {
1306        return Err(CssColorParseError::ExtraArguments(arg));
1307    }
1308    Ok(ColorU { a, ..rgb_color })
1309}
1310
1311#[cfg(feature = "parser")]
1312#[allow(clippy::many_single_char_names)] // domain-standard h/s/l/r/g/b colour component names
1313fn parse_color_hsl_components<'a>(
1314    components: &mut dyn Iterator<Item = &'a str>,
1315) -> Result<ColorU, CssColorParseError<'a>> {
1316    #[inline]
1317    fn angle_from_str<'a>(
1318        components: &mut dyn Iterator<Item = &'a str>,
1319        which: CssColorComponent,
1320    ) -> Result<f32, CssColorParseError<'a>> {
1321        let c = components
1322            .next()
1323            .ok_or(CssColorParseError::MissingColorComponent(which))?;
1324        if c.is_empty() {
1325            return Err(CssColorParseError::MissingColorComponent(which));
1326        }
1327        let dir = parse_direction(c)?;
1328        match dir {
1329            Direction::Angle(deg) => Ok(deg.to_degrees()),
1330            Direction::FromTo(_) => Err(CssColorParseError::UnsupportedDirection(c)),
1331        }
1332    }
1333
1334    #[inline]
1335    fn percent_from_str<'a>(
1336        components: &mut dyn Iterator<Item = &'a str>,
1337        which: CssColorComponent,
1338    ) -> Result<f32, CssColorParseError<'a>> {
1339        use crate::props::basic::parse_percentage_value;
1340
1341        let c = components
1342            .next()
1343            .ok_or(CssColorParseError::MissingColorComponent(which))?;
1344        if c.is_empty() {
1345            return Err(CssColorParseError::MissingColorComponent(which));
1346        }
1347
1348        // Modern CSS allows both percentage and unitless values for HSL
1349        Ok(parse_percentage_value(c)
1350            .map_err(CssColorParseError::InvalidPercentage)?
1351            .normalized()
1352            * 100.0)
1353    }
1354
1355    #[inline]
1356    #[allow(clippy::suboptimal_flops)] // explicit FP; mul_add slower without +fma
1357    #[allow(clippy::many_single_char_names)] // domain-standard colour/coordinate component names
1358    fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (u8, u8, u8) {
1359        let s = s / 100.0;
1360        let l = l / 100.0;
1361        let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
1362        let h_prime = h / 60.0;
1363        let x = c * (1.0 - ((h_prime % 2.0) - 1.0).abs());
1364        let (r1, g1, b1) = if (0.0..1.0).contains(&h_prime) {
1365            (c, x, 0.0)
1366        } else if (1.0..2.0).contains(&h_prime) {
1367            (x, c, 0.0)
1368        } else if (2.0..3.0).contains(&h_prime) {
1369            (0.0, c, x)
1370        } else if (3.0..4.0).contains(&h_prime) {
1371            (0.0, x, c)
1372        } else if (4.0..5.0).contains(&h_prime) {
1373            (x, 0.0, c)
1374        } else {
1375            (c, 0.0, x)
1376        };
1377        let m = l - c / 2.0;
1378        (
1379            channel_to_u8((r1 + m) * 255.0),
1380            channel_to_u8((g1 + m) * 255.0),
1381            channel_to_u8((b1 + m) * 255.0),
1382        )
1383    }
1384
1385    let (h, s, l) = (
1386        angle_from_str(components, CssColorComponent::Hue)?,
1387        percent_from_str(components, CssColorComponent::Saturation)?,
1388        percent_from_str(components, CssColorComponent::Lightness)?,
1389    );
1390
1391    let (r, g, b) = hsl_to_rgb(h, s, l);
1392    Ok(ColorU { r, g, b, a: 255 })
1393}
1394
1395#[cfg(feature = "parser")]
1396fn parse_alpha_component<'a>(
1397    components: &mut dyn Iterator<Item = &'a str>,
1398) -> Result<u8, CssColorParseError<'a>> {
1399    let a_str = components
1400        .next()
1401        .ok_or(CssColorParseError::MissingColorComponent(
1402            CssColorComponent::Alpha,
1403        ))?;
1404    if a_str.is_empty() {
1405        return Err(CssColorParseError::MissingColorComponent(
1406            CssColorComponent::Alpha,
1407        ));
1408    }
1409    let a = a_str.parse::<f32>()?;
1410    if !(0.0..=1.0).contains(&a) {
1411        return Err(CssColorParseError::FloatValueOutOfRange(a));
1412    }
1413    Ok(channel_to_u8((a * 255.0).round()))
1414}
1415
1416#[cfg(feature = "parser")]
1417#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose CSS parser/formatter/dispatch table (one branch per property/variant)
1418fn parse_color_builtin(input: &str) -> Result<ColorU, CssColorParseError<'_>> {
1419    let (r, g, b, a) = match input.to_lowercase().as_str() {
1420        "aliceblue" => (240, 248, 255, 255),
1421        "antiquewhite" => (250, 235, 215, 255),
1422        "aqua" | "cyan" => (0, 255, 255, 255),
1423        "aquamarine" => (127, 255, 212, 255),
1424        "azure" => (240, 255, 255, 255),
1425        "beige" => (245, 245, 220, 255),
1426        "bisque" => (255, 228, 196, 255),
1427        "black" => (0, 0, 0, 255),
1428        "blanchedalmond" => (255, 235, 205, 255),
1429        "blue" => (0, 0, 255, 255),
1430        "blueviolet" => (138, 43, 226, 255),
1431        "brown" => (165, 42, 42, 255),
1432        "burlywood" => (222, 184, 135, 255),
1433        "cadetblue" => (95, 158, 160, 255),
1434        "chartreuse" => (127, 255, 0, 255),
1435        "chocolate" => (210, 105, 30, 255),
1436        "coral" => (255, 127, 80, 255),
1437        "cornflowerblue" => (100, 149, 237, 255),
1438        "cornsilk" => (255, 248, 220, 255),
1439        "crimson" => (220, 20, 60, 255),
1440        "darkblue" => (0, 0, 139, 255),
1441        "darkcyan" => (0, 139, 139, 255),
1442        "darkgoldenrod" => (184, 134, 11, 255),
1443        "darkgray" | "darkgrey" => (169, 169, 169, 255),
1444        "darkgreen" => (0, 100, 0, 255),
1445        "darkkhaki" => (189, 183, 107, 255),
1446        "darkmagenta" => (139, 0, 139, 255),
1447        "darkolivegreen" => (85, 107, 47, 255),
1448        "darkorange" => (255, 140, 0, 255),
1449        "darkorchid" => (153, 50, 204, 255),
1450        "darkred" => (139, 0, 0, 255),
1451        "darksalmon" => (233, 150, 122, 255),
1452        "darkseagreen" => (143, 188, 143, 255),
1453        "darkslateblue" => (72, 61, 139, 255),
1454        "darkslategray" | "darkslategrey" => (47, 79, 79, 255),
1455        "darkturquoise" => (0, 206, 209, 255),
1456        "darkviolet" => (148, 0, 211, 255),
1457        "deeppink" => (255, 20, 147, 255),
1458        "deepskyblue" => (0, 191, 255, 255),
1459        "dimgray" | "dimgrey" => (105, 105, 105, 255),
1460        "dodgerblue" => (30, 144, 255, 255),
1461        "firebrick" => (178, 34, 34, 255),
1462        "floralwhite" => (255, 250, 240, 255),
1463        "forestgreen" => (34, 139, 34, 255),
1464        "fuchsia" | "magenta" => (255, 0, 255, 255),
1465        "gainsboro" => (220, 220, 220, 255),
1466        "ghostwhite" => (248, 248, 255, 255),
1467        "gold" => (255, 215, 0, 255),
1468        "goldenrod" => (218, 165, 32, 255),
1469        "gray" | "grey" => (128, 128, 128, 255),
1470        "green" => (0, 128, 0, 255),
1471        "greenyellow" => (173, 255, 47, 255),
1472        "honeydew" => (240, 255, 240, 255),
1473        "hotpink" => (255, 105, 180, 255),
1474        "indianred" => (205, 92, 92, 255),
1475        "indigo" => (75, 0, 130, 255),
1476        "ivory" => (255, 255, 240, 255),
1477        "khaki" => (240, 230, 140, 255),
1478        "lavender" => (230, 230, 250, 255),
1479        "lavenderblush" => (255, 240, 245, 255),
1480        "lawngreen" => (124, 252, 0, 255),
1481        "lemonchiffon" => (255, 250, 205, 255),
1482        "lightblue" => (173, 216, 230, 255),
1483        "lightcoral" => (240, 128, 128, 255),
1484        "lightcyan" => (224, 255, 255, 255),
1485        "lightgoldenrodyellow" => (250, 250, 210, 255),
1486        "lightgray" | "lightgrey" => (211, 211, 211, 255),
1487        "lightgreen" => (144, 238, 144, 255),
1488        "lightpink" => (255, 182, 193, 255),
1489        "lightsalmon" => (255, 160, 122, 255),
1490        "lightseagreen" => (32, 178, 170, 255),
1491        "lightskyblue" => (135, 206, 250, 255),
1492        "lightslategray" | "lightslategrey" => (119, 136, 153, 255),
1493        "lightsteelblue" => (176, 196, 222, 255),
1494        "lightyellow" => (255, 255, 224, 255),
1495        "lime" => (0, 255, 0, 255),
1496        "limegreen" => (50, 205, 50, 255),
1497        "linen" => (250, 240, 230, 255),
1498        "maroon" => (128, 0, 0, 255),
1499        "mediumaquamarine" => (102, 205, 170, 255),
1500        "mediumblue" => (0, 0, 205, 255),
1501        "mediumorchid" => (186, 85, 211, 255),
1502        "mediumpurple" => (147, 112, 219, 255),
1503        "mediumseagreen" => (60, 179, 113, 255),
1504        "mediumslateblue" => (123, 104, 238, 255),
1505        "mediumspringgreen" => (0, 250, 154, 255),
1506        "mediumturquoise" => (72, 209, 204, 255),
1507        "mediumvioletred" => (199, 21, 133, 255),
1508        "midnightblue" => (25, 25, 112, 255),
1509        "mintcream" => (245, 255, 250, 255),
1510        "mistyrose" => (255, 228, 225, 255),
1511        "moccasin" => (255, 228, 181, 255),
1512        "navajowhite" => (255, 222, 173, 255),
1513        "navy" => (0, 0, 128, 255),
1514        "oldlace" => (253, 245, 230, 255),
1515        "olive" => (128, 128, 0, 255),
1516        "olivedrab" => (107, 142, 35, 255),
1517        "orange" => (255, 165, 0, 255),
1518        "orangered" => (255, 69, 0, 255),
1519        "orchid" => (218, 112, 214, 255),
1520        "palegoldenrod" => (238, 232, 170, 255),
1521        "palegreen" => (152, 251, 152, 255),
1522        "paleturquoise" => (175, 238, 238, 255),
1523        "palevioletred" => (219, 112, 147, 255),
1524        "papayawhip" => (255, 239, 213, 255),
1525        "peachpuff" => (255, 218, 185, 255),
1526        "peru" => (205, 133, 63, 255),
1527        "pink" => (255, 192, 203, 255),
1528        "plum" => (221, 160, 221, 255),
1529        "powderblue" => (176, 224, 230, 255),
1530        "purple" => (128, 0, 128, 255),
1531        "rebeccapurple" => (102, 51, 153, 255),
1532        "red" => (255, 0, 0, 255),
1533        "rosybrown" => (188, 143, 143, 255),
1534        "royalblue" => (65, 105, 225, 255),
1535        "saddlebrown" => (139, 69, 19, 255),
1536        "salmon" => (250, 128, 114, 255),
1537        "sandybrown" => (244, 164, 96, 255),
1538        "seagreen" => (46, 139, 87, 255),
1539        "seashell" => (255, 245, 238, 255),
1540        "sienna" => (160, 82, 45, 255),
1541        "silver" => (192, 192, 192, 255),
1542        "skyblue" => (135, 206, 235, 255),
1543        "slateblue" => (106, 90, 205, 255),
1544        "slategray" | "slategrey" => (112, 128, 144, 255),
1545        "snow" => (255, 250, 250, 255),
1546        "springgreen" => (0, 255, 127, 255),
1547        "steelblue" => (70, 130, 180, 255),
1548        "tan" => (210, 180, 140, 255),
1549        "teal" => (0, 128, 128, 255),
1550        "thistle" => (216, 191, 216, 255),
1551        "tomato" => (255, 99, 71, 255),
1552        "transparent" => (0, 0, 0, 0),
1553        "turquoise" => (64, 224, 208, 255),
1554        "violet" => (238, 130, 238, 255),
1555        "wheat" => (245, 222, 179, 255),
1556        "white" => (255, 255, 255, 255),
1557        "whitesmoke" => (245, 245, 245, 255),
1558        "yellow" => (255, 255, 0, 255),
1559        "yellowgreen" => (154, 205, 50, 255),
1560        _ => return Err(CssColorParseError::InvalidColor(input)),
1561    };
1562    Ok(ColorU { r, g, b, a })
1563}
1564
1565#[cfg(all(test, feature = "parser"))]
1566mod tests {
1567    use super::*;
1568
1569    #[test]
1570    fn test_parse_color_keywords() {
1571        assert_eq!(parse_css_color("red").unwrap(), ColorU::RED);
1572        assert_eq!(parse_css_color("blue").unwrap(), ColorU::BLUE);
1573        assert_eq!(parse_css_color("transparent").unwrap(), ColorU::TRANSPARENT);
1574        assert_eq!(
1575            parse_css_color("rebeccapurple").unwrap(),
1576            ColorU::new_rgb(102, 51, 153)
1577        );
1578    }
1579
1580    #[test]
1581    fn test_parse_color_hex() {
1582        // 3-digit
1583        assert_eq!(parse_css_color("#f00").unwrap(), ColorU::RED);
1584        // 4-digit
1585        assert_eq!(
1586            parse_css_color("#f008").unwrap(),
1587            ColorU::new(255, 0, 0, 136)
1588        );
1589        // 6-digit
1590        assert_eq!(parse_css_color("#00ff00").unwrap(), ColorU::GREEN);
1591        // 8-digit
1592        assert_eq!(
1593            parse_css_color("#0000ff80").unwrap(),
1594            ColorU::new(0, 0, 255, 128)
1595        );
1596        // Uppercase
1597        assert_eq!(
1598            parse_css_color("#FFC0CB").unwrap(),
1599            ColorU::new_rgb(255, 192, 203)
1600        ); // Pink
1601    }
1602
1603    #[test]
1604    fn test_parse_color_rgb() {
1605        assert_eq!(parse_css_color("rgb(255, 0, 0)").unwrap(), ColorU::RED);
1606        assert_eq!(
1607            parse_css_color("rgba(0, 255, 0, 0.5)").unwrap(),
1608            ColorU::new(0, 255, 0, 128)
1609        );
1610        assert_eq!(
1611            parse_css_color("rgba(10, 20, 30, 1)").unwrap(),
1612            ColorU::new_rgb(10, 20, 30)
1613        );
1614        assert_eq!(parse_css_color("rgb( 0 , 0 , 0 )").unwrap(), ColorU::BLACK);
1615    }
1616
1617    #[test]
1618    fn test_parse_color_hsl() {
1619        assert_eq!(parse_css_color("hsl(0, 100%, 50%)").unwrap(), ColorU::RED);
1620        assert_eq!(
1621            parse_css_color("hsl(120, 100%, 50%)").unwrap(),
1622            ColorU::GREEN
1623        );
1624        assert_eq!(
1625            parse_css_color("hsla(240, 100%, 50%, 0.5)").unwrap(),
1626            ColorU::new(0, 0, 255, 128)
1627        );
1628        assert_eq!(parse_css_color("hsl(0, 0%, 0%)").unwrap(), ColorU::BLACK);
1629    }
1630
1631    #[test]
1632    fn test_parse_color_errors() {
1633        assert!(parse_css_color("redd").is_err());
1634        assert!(parse_css_color("#12345").is_err()); // Invalid length
1635        assert!(parse_css_color("#ggg").is_err()); // Invalid hex digit
1636        assert!(parse_css_color("rgb(255, 0)").is_err()); // Missing component
1637        assert!(parse_css_color("rgba(255, 0, 0, 2)").is_err()); // Alpha out of range
1638        assert!(parse_css_color("rgb(256, 0, 0)").is_err()); // Value out of range
1639                                                             // Modern CSS allows both hsl(0, 100%, 50%) and hsl(0 100 50)
1640        assert!(parse_css_color("hsl(0, 100, 50%)").is_ok()); // Valid in modern CSS
1641        assert!(parse_css_color("rgb(255 0 0)").is_err()); // Missing commas (this implementation
1642                                                           // requires commas)
1643    }
1644
1645    #[test]
1646    fn test_parse_system_colors() {
1647        // Test parsing system color syntax
1648        assert_eq!(
1649            parse_color_or_system("system:accent").unwrap(),
1650            ColorOrSystem::System(SystemColorRef::Accent)
1651        );
1652        assert_eq!(
1653            parse_color_or_system("system:text").unwrap(),
1654            ColorOrSystem::System(SystemColorRef::Text)
1655        );
1656        assert_eq!(
1657            parse_color_or_system("system:background").unwrap(),
1658            ColorOrSystem::System(SystemColorRef::Background)
1659        );
1660        assert_eq!(
1661            parse_color_or_system("system:selection-background").unwrap(),
1662            ColorOrSystem::System(SystemColorRef::SelectionBackground)
1663        );
1664        assert_eq!(
1665            parse_color_or_system("system:selection-text").unwrap(),
1666            ColorOrSystem::System(SystemColorRef::SelectionText)
1667        );
1668        assert_eq!(
1669            parse_color_or_system("system:accent-text").unwrap(),
1670            ColorOrSystem::System(SystemColorRef::AccentText)
1671        );
1672        assert_eq!(
1673            parse_color_or_system("system:button-face").unwrap(),
1674            ColorOrSystem::System(SystemColorRef::ButtonFace)
1675        );
1676        assert_eq!(
1677            parse_color_or_system("system:button-text").unwrap(),
1678            ColorOrSystem::System(SystemColorRef::ButtonText)
1679        );
1680        assert_eq!(
1681            parse_color_or_system("system:window-background").unwrap(),
1682            ColorOrSystem::System(SystemColorRef::WindowBackground)
1683        );
1684        
1685        // Invalid system color should error
1686        assert!(parse_color_or_system("system:invalid").is_err());
1687        
1688        // Regular colors should still work
1689        assert_eq!(
1690            parse_color_or_system("red").unwrap(),
1691            ColorOrSystem::Color(ColorU::RED)
1692        );
1693        assert_eq!(
1694            parse_color_or_system("#ff0000").unwrap(),
1695            ColorOrSystem::Color(ColorU::RED)
1696        );
1697    }
1698
1699    #[test]
1700    fn test_system_color_resolution() {
1701        use crate::system::SystemColors;
1702        
1703        let system_colors = SystemColors {
1704            text: OptionColorU::Some(ColorU::BLACK),
1705            secondary_text: OptionColorU::None,
1706            tertiary_text: OptionColorU::None,
1707            background: OptionColorU::Some(ColorU::WHITE),
1708            accent: OptionColorU::Some(ColorU::new_rgb(0, 122, 255)), // macOS blue
1709            accent_text: OptionColorU::Some(ColorU::WHITE),
1710            button_face: OptionColorU::Some(ColorU::new_rgb(240, 240, 240)),
1711            button_text: OptionColorU::Some(ColorU::BLACK),
1712            disabled_text: OptionColorU::None,
1713            window_background: OptionColorU::Some(ColorU::WHITE),
1714            under_page_background: OptionColorU::None,
1715            selection_background: OptionColorU::Some(ColorU::new_rgb(0, 120, 215)),
1716            selection_text: OptionColorU::Some(ColorU::WHITE),
1717            selection_background_inactive: OptionColorU::None,
1718            selection_text_inactive: OptionColorU::None,
1719            link: OptionColorU::None,
1720            separator: OptionColorU::None,
1721            grid: OptionColorU::None,
1722            find_highlight: OptionColorU::None,
1723            sidebar_background: OptionColorU::None,
1724            sidebar_selection: OptionColorU::None,
1725        };
1726        
1727        // Test resolution of system colors
1728        let accent_ref = ColorOrSystem::System(SystemColorRef::Accent);
1729        let resolved = accent_ref.resolve(&system_colors, ColorU::GRAY);
1730        assert_eq!(resolved, ColorU::new_rgb(0, 122, 255));
1731        
1732        // Test resolution with fallback when color is not set
1733        let empty_colors = SystemColors::default();
1734        let resolved_fallback = accent_ref.resolve(&empty_colors, ColorU::GRAY);
1735        assert_eq!(resolved_fallback, ColorU::GRAY);
1736        
1737        // Test that concrete colors just return themselves
1738        let concrete = ColorOrSystem::Color(ColorU::RED);
1739        let resolved_concrete = concrete.resolve(&system_colors, ColorU::GRAY);
1740        assert_eq!(resolved_concrete, ColorU::RED);
1741    }
1742
1743    #[test]
1744    fn test_system_color_css_str() {
1745        assert_eq!(SystemColorRef::Accent.as_css_str(), "system:accent");
1746        assert_eq!(SystemColorRef::Text.as_css_str(), "system:text");
1747        assert_eq!(SystemColorRef::Background.as_css_str(), "system:background");
1748        assert_eq!(SystemColorRef::SelectionBackground.as_css_str(), "system:selection-background");
1749    }
1750}