fernctl/domain/tokens/
color.rs

1//! # Type-Safe Color Tokens
2//!
3//! This module provides color tokens with semantic roles encoded in the type
4//! system. The compiler ensures colors are used appropriately — you cannot
5//! accidentally use a text color as a background.
6//!
7//! ## Design Rationale
8//!
9//! In a traditional design system, colors are just values:
10//!
11//! ```rust,ignore
12//! let surface = "#313244";
13//! let text = "#cdd6f4";
14//!
15//! // Oops! Using text color as background — compiles but looks wrong
16//! button.background = text;
17//! ```
18//!
19//! With type-safe colors, the compiler catches this mistake:
20//!
21//! ```rust,ignore
22//! let surface: ColorToken<Surface> = ColorToken::from_hex("#313244")?;
23//! let text: ColorToken<Foreground> = ColorToken::from_hex("#cdd6f4")?;
24//!
25//! // This function only accepts background colors
26//! fn set_background(color: impl BackgroundRole) { /* ... */ }
27//!
28//! set_background(surface);  // ✓ Compiles — Surface is a BackgroundRole
29//! set_background(text);     // ✗ Error! — Foreground is not a BackgroundRole
30//! ```
31//!
32//! ## Color Roles
33//!
34//! Colors are categorized by their semantic role:
35//!
36//! | Role | Trait | Example Uses |
37//! |------|-------|--------------|
38//! | Background | [`BackgroundRole`] | Panel backgrounds, button fills |
39//! | Foreground | [`ForegroundRole`] | Text, icons |
40//! | Accent | [`AccentRole`] | Focus rings, highlights |
41//! | Status | [`StatusRole`] | Error, warning, success |
42//!
43//! ## Creating Colors
44//!
45//! ```rust
46//! use fernctl::domain::tokens::color::*;
47//!
48//! // From hex string
49//! let color = ColorToken::<Surface>::from_hex("#313244").unwrap();
50//!
51//! // From RGB values
52//! let color = ColorToken::<Surface>::from_rgb(0x31, 0x32, 0x44);
53//!
54//! // With alpha
55//! let color = ColorToken::<Surface>::from_rgba(0x31, 0x32, 0x44, 0x80);
56//! ```
57//!
58//! ## Zero-Cost Abstraction
59//!
60//! The type parameter uses [`PhantomData`] and adds no runtime overhead.
61//! A `ColorToken<Surface>` has the exact same memory layout as four `u8`s.
62
63use crate::error::ConfigError;
64use serde::{Deserialize, Serialize};
65use std::fmt;
66use std::marker::PhantomData;
67
68// ============================================================================
69// Sealed Trait Pattern
70// ============================================================================
71
72/// Private module to seal the role traits.
73///
74/// This prevents external crates from implementing role traits, ensuring
75/// the type system guarantees remain sound.
76mod private {
77    /// Sealed trait that cannot be implemented outside this crate.
78    pub trait Sealed {}
79}
80
81// ============================================================================
82// Role Marker Traits
83// ============================================================================
84
85/// Marker trait for all color roles.
86///
87/// This is the base trait that all specific role traits extend. It is sealed,
88/// meaning only types defined in this crate can implement it.
89///
90/// # Implementors
91///
92/// - [`Background`], [`Surface`], [`SurfaceHover`] — Background roles
93/// - [`Foreground`], [`ForegroundDim`] — Foreground (text) roles
94/// - [`Accent`] — Accent color role
95/// - [`Error`], [`Warning`], [`Success`], [`Info`] — Status roles
96pub trait ColorRole: private::Sealed + fmt::Debug + Clone + Copy + 'static {
97    /// Returns the name of this role for debugging and serialization.
98    fn role_name() -> &'static str;
99}
100
101/// Marker trait for colors that can be used as backgrounds.
102///
103/// Background colors are used for:
104/// - Panel and window backgrounds
105/// - Button fills
106/// - Card surfaces
107/// - Input field backgrounds
108///
109/// # Implementors
110///
111/// - [`Background`] — Primary background color
112/// - [`Surface`] — Elevated surface color
113/// - [`SurfaceHover`] — Hover state for surfaces
114pub trait BackgroundRole: ColorRole {}
115
116/// Marker trait for colors that can be used as foreground (text/icons).
117///
118/// Foreground colors are used for:
119/// - Body text
120/// - Icons
121/// - Labels
122/// - Any content that appears on top of a background
123///
124/// # Implementors
125///
126/// - [`Foreground`] — Primary text color
127/// - [`ForegroundDim`] — Secondary/muted text color
128pub trait ForegroundRole: ColorRole {}
129
130/// Marker trait for accent colors.
131///
132/// Accent colors are used for:
133/// - Focus indicators
134/// - Active states
135/// - Links
136/// - Highlighted elements
137///
138/// # Implementors
139///
140/// - [`Accent`] — The primary accent color
141pub trait AccentRole: ColorRole {}
142
143/// Marker trait for status indication colors.
144///
145/// Status colors communicate state to the user:
146/// - Errors and failures
147/// - Warnings and cautions
148/// - Success and confirmations
149/// - Informational messages
150///
151/// # Implementors
152///
153/// - [`Error`] — Error/failure states
154/// - [`Warning`] — Warning/caution states
155/// - [`Success`] — Success/confirmation states
156/// - [`Info`] — Informational states
157pub trait StatusRole: ColorRole {}
158
159// ============================================================================
160// Role Marker Types
161// ============================================================================
162
163/// Primary background color role.
164///
165/// Used for the main background of panels, windows, and the shell itself.
166/// This is typically the darkest color in dark themes or lightest in light themes.
167///
168/// # Example
169///
170/// ```rust
171/// use fernctl::domain::tokens::color::*;
172///
173/// let bg: ColorToken<Background> = ColorToken::from_hex("#1e1e2e").unwrap();
174/// ```
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
176pub struct Background;
177
178impl private::Sealed for Background {}
179impl ColorRole for Background {
180    fn role_name() -> &'static str {
181        "background"
182    }
183}
184impl BackgroundRole for Background {}
185
186/// Elevated surface color role.
187///
188/// Used for elements that appear elevated above the background, such as:
189/// - Cards
190/// - Modals
191/// - Dropdown menus
192/// - Tooltips
193///
194/// # Example
195///
196/// ```rust
197/// use fernctl::domain::tokens::color::*;
198///
199/// let surface: ColorToken<Surface> = ColorToken::from_hex("#313244").unwrap();
200/// ```
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
202pub struct Surface;
203
204impl private::Sealed for Surface {}
205impl ColorRole for Surface {
206    fn role_name() -> &'static str {
207        "surface"
208    }
209}
210impl BackgroundRole for Surface {}
211
212/// Hover state for surfaces.
213///
214/// Used when the user hovers over interactive surface elements.
215/// Should be visually distinct from [`Surface`] but not jarring.
216///
217/// # Example
218///
219/// ```rust
220/// use fernctl::domain::tokens::color::*;
221///
222/// let hover: ColorToken<SurfaceHover> = ColorToken::from_hex("#45475a").unwrap();
223/// ```
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
225pub struct SurfaceHover;
226
227impl private::Sealed for SurfaceHover {}
228impl ColorRole for SurfaceHover {
229    fn role_name() -> &'static str {
230        "surface_hover"
231    }
232}
233impl BackgroundRole for SurfaceHover {}
234
235/// Primary foreground (text) color role.
236///
237/// Used for primary text content and icons. Should have sufficient contrast
238/// against background colors for readability.
239///
240/// # Example
241///
242/// ```rust
243/// use fernctl::domain::tokens::color::*;
244///
245/// let text: ColorToken<Foreground> = ColorToken::from_hex("#cdd6f4").unwrap();
246/// ```
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
248pub struct Foreground;
249
250impl private::Sealed for Foreground {}
251impl ColorRole for Foreground {
252    fn role_name() -> &'static str {
253        "foreground"
254    }
255}
256impl ForegroundRole for Foreground {}
257
258/// Dimmed/secondary foreground color role.
259///
260/// Used for secondary text, placeholders, and less important content.
261/// Should be readable but visually subordinate to primary foreground.
262///
263/// # Example
264///
265/// ```rust
266/// use fernctl::domain::tokens::color::*;
267///
268/// let dim: ColorToken<ForegroundDim> = ColorToken::from_hex("#a6adc8").unwrap();
269/// ```
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
271pub struct ForegroundDim;
272
273impl private::Sealed for ForegroundDim {}
274impl ColorRole for ForegroundDim {
275    fn role_name() -> &'static str {
276        "foreground_dim"
277    }
278}
279impl ForegroundRole for ForegroundDim {}
280
281/// Accent color role.
282///
283/// Used for focus indicators, active states, links, and branded elements.
284/// This is typically the most vibrant color in the palette.
285///
286/// # Example
287///
288/// ```rust
289/// use fernctl::domain::tokens::color::*;
290///
291/// let accent: ColorToken<Accent> = ColorToken::from_hex("#89b4fa").unwrap();
292/// ```
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
294pub struct Accent;
295
296impl private::Sealed for Accent {}
297impl ColorRole for Accent {
298    fn role_name() -> &'static str {
299        "accent"
300    }
301}
302impl AccentRole for Accent {}
303
304/// Error status color role.
305///
306/// Used to indicate errors, failures, and destructive actions.
307///
308/// # Example
309///
310/// ```rust
311/// use fernctl::domain::tokens::color::*;
312///
313/// let error: ColorToken<Error> = ColorToken::from_hex("#f38ba8").unwrap();
314/// ```
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
316pub struct Error;
317
318impl private::Sealed for Error {}
319impl ColorRole for Error {
320    fn role_name() -> &'static str {
321        "error"
322    }
323}
324impl StatusRole for Error {}
325
326/// Warning status color role.
327///
328/// Used to indicate warnings, cautions, and potentially dangerous actions.
329///
330/// # Example
331///
332/// ```rust
333/// use fernctl::domain::tokens::color::*;
334///
335/// let warning: ColorToken<Warning> = ColorToken::from_hex("#f9e2af").unwrap();
336/// ```
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
338pub struct Warning;
339
340impl private::Sealed for Warning {}
341impl ColorRole for Warning {
342    fn role_name() -> &'static str {
343        "warning"
344    }
345}
346impl StatusRole for Warning {}
347
348/// Success status color role.
349///
350/// Used to indicate success, completion, and positive actions.
351///
352/// # Example
353///
354/// ```rust
355/// use fernctl::domain::tokens::color::*;
356///
357/// let success: ColorToken<Success> = ColorToken::from_hex("#a6e3a1").unwrap();
358/// ```
359#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
360pub struct Success;
361
362impl private::Sealed for Success {}
363impl ColorRole for Success {
364    fn role_name() -> &'static str {
365        "success"
366    }
367}
368impl StatusRole for Success {}
369
370/// Info status color role.
371///
372/// Used for informational messages and neutral highlights.
373///
374/// # Example
375///
376/// ```rust
377/// use fernctl::domain::tokens::color::*;
378///
379/// let info: ColorToken<Info> = ColorToken::from_hex("#89dceb").unwrap();
380/// ```
381#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
382pub struct Info;
383
384impl private::Sealed for Info {}
385impl ColorRole for Info {
386    fn role_name() -> &'static str {
387        "info"
388    }
389}
390impl StatusRole for Info {}
391
392// ============================================================================
393// ColorToken Implementation
394// ============================================================================
395
396/// A color token with its semantic role encoded in the type.
397///
398/// `ColorToken<Role>` represents an RGBA color value along with its semantic
399/// meaning in the design system. The role is tracked at compile time via the
400/// type parameter, enabling the compiler to prevent misuse.
401///
402/// # Type Parameter
403///
404/// The `Role` parameter must implement [`ColorRole`] and determines how the
405/// color can be used:
406///
407/// - `ColorToken<Surface>` — Can be used where [`BackgroundRole`] is expected
408/// - `ColorToken<Foreground>` — Can be used where [`ForegroundRole`] is expected
409///
410/// # Memory Layout
411///
412/// Despite the type parameter, `ColorToken` has the same size as four bytes:
413///
414/// ```rust
415/// use fernctl::domain::tokens::color::*;
416/// use std::mem::size_of;
417///
418/// assert_eq!(size_of::<ColorToken<Surface>>(), 4);
419/// ```
420///
421/// This is because `PhantomData<Role>` is a zero-sized type.
422///
423/// # Creating Colors
424///
425/// ```rust
426/// use fernctl::domain::tokens::color::*;
427///
428/// // From hex string (most common)
429/// let color = ColorToken::<Surface>::from_hex("#313244").unwrap();
430///
431/// // From RGB values
432/// let color = ColorToken::<Surface>::from_rgb(0x31, 0x32, 0x44);
433///
434/// // From RGBA values
435/// let color = ColorToken::<Surface>::from_rgba(0x31, 0x32, 0x44, 0xFF);
436/// ```
437///
438/// # Converting to Output Formats
439///
440/// ```rust
441/// use fernctl::domain::tokens::color::*;
442///
443/// let color = ColorToken::<Surface>::from_hex("#313244").unwrap();
444///
445/// assert_eq!(color.to_hex(), "#313244");
446/// assert_eq!(color.to_rgb_tuple(), (0x31, 0x32, 0x44));
447/// assert_eq!(color.to_css_rgb(), "rgb(49, 50, 68)");
448/// ```
449#[derive(Clone, Copy, PartialEq, Eq, Hash)]
450pub struct ColorToken<Role: ColorRole> {
451    /// Red component (0-255).
452    r: u8,
453    /// Green component (0-255).
454    g: u8,
455    /// Blue component (0-255).
456    b: u8,
457    /// Alpha component (0-255, where 255 is fully opaque).
458    a: u8,
459    /// Marker for the color's semantic role.
460    _role: PhantomData<Role>,
461}
462
463impl<Role: ColorRole> ColorToken<Role> {
464    /// Creates a new color token from RGB values (fully opaque).
465    ///
466    /// # Arguments
467    ///
468    /// * `r` — Red component (0-255)
469    /// * `g` — Green component (0-255)
470    /// * `b` — Blue component (0-255)
471    ///
472    /// # Example
473    ///
474    /// ```rust
475    /// use fernctl::domain::tokens::color::*;
476    ///
477    /// let color = ColorToken::<Surface>::from_rgb(0x31, 0x32, 0x44);
478    /// assert_eq!(color.alpha(), 255);
479    /// ```
480    #[must_use]
481    pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
482        Self {
483            r,
484            g,
485            b,
486            a: 255,
487            _role: PhantomData,
488        }
489    }
490
491    /// Creates a new color token from RGBA values.
492    ///
493    /// # Arguments
494    ///
495    /// * `r` — Red component (0-255)
496    /// * `g` — Green component (0-255)
497    /// * `b` — Blue component (0-255)
498    /// * `a` — Alpha component (0-255, where 255 is fully opaque)
499    ///
500    /// # Example
501    ///
502    /// ```rust
503    /// use fernctl::domain::tokens::color::*;
504    ///
505    /// let color = ColorToken::<Surface>::from_rgba(0x31, 0x32, 0x44, 0x80);
506    /// assert_eq!(color.alpha(), 0x80);
507    /// ```
508    #[must_use]
509    pub const fn from_rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
510        Self {
511            r,
512            g,
513            b,
514            a,
515            _role: PhantomData,
516        }
517    }
518
519    /// Creates a color token from a hex string.
520    ///
521    /// Supports the following formats:
522    /// - `#RGB` — 3-digit shorthand (expands to 6-digit)
523    /// - `#RRGGBB` — 6-digit hex (opaque)
524    /// - `#RRGGBBAA` — 8-digit hex with alpha
525    ///
526    /// The `#` prefix is required.
527    ///
528    /// # Errors
529    ///
530    /// Returns [`ConfigError::InvalidColor`] if:
531    /// - The string doesn't start with `#`
532    /// - The length is not 4, 7, or 9 characters
533    /// - Any character is not a valid hex digit
534    ///
535    /// # Example
536    ///
537    /// ```rust
538    /// use fernctl::domain::tokens::color::*;
539    ///
540    /// // 6-digit hex
541    /// let color = ColorToken::<Surface>::from_hex("#313244").unwrap();
542    ///
543    /// // 3-digit shorthand
544    /// let white = ColorToken::<Foreground>::from_hex("#fff").unwrap();
545    ///
546    /// // 8-digit with alpha
547    /// let transparent = ColorToken::<Surface>::from_hex("#31324480").unwrap();
548    ///
549    /// // Invalid
550    /// assert!(ColorToken::<Surface>::from_hex("313244").is_err());  // Missing #
551    /// assert!(ColorToken::<Surface>::from_hex("#gg0000").is_err()); // Invalid hex
552    /// ```
553    pub fn from_hex(hex: &str) -> Result<Self, ConfigError> {
554        parse_hex_color(hex).ok_or_else(|| ConfigError::InvalidColor {
555            value: hex.to_string(),
556            span: None,
557            source_code: None,
558        })
559    }
560
561    /// Returns the red component (0-255).
562    #[must_use]
563    pub const fn red(&self) -> u8 {
564        self.r
565    }
566
567    /// Returns the green component (0-255).
568    #[must_use]
569    pub const fn green(&self) -> u8 {
570        self.g
571    }
572
573    /// Returns the blue component (0-255).
574    #[must_use]
575    pub const fn blue(&self) -> u8 {
576        self.b
577    }
578
579    /// Returns the alpha component (0-255, where 255 is fully opaque).
580    #[must_use]
581    pub const fn alpha(&self) -> u8 {
582        self.a
583    }
584
585    /// Returns `true` if the color is fully opaque (alpha = 255).
586    #[must_use]
587    pub const fn is_opaque(&self) -> bool {
588        self.a == 255
589    }
590
591    /// Returns the color as an RGB tuple.
592    ///
593    /// # Example
594    ///
595    /// ```rust
596    /// use fernctl::domain::tokens::color::*;
597    ///
598    /// let color = ColorToken::<Surface>::from_hex("#313244").unwrap();
599    /// assert_eq!(color.to_rgb_tuple(), (0x31, 0x32, 0x44));
600    /// ```
601    #[must_use]
602    pub const fn to_rgb_tuple(&self) -> (u8, u8, u8) {
603        (self.r, self.g, self.b)
604    }
605
606    /// Returns the color as an RGBA tuple.
607    ///
608    /// # Example
609    ///
610    /// ```rust
611    /// use fernctl::domain::tokens::color::*;
612    ///
613    /// let color = ColorToken::<Surface>::from_rgba(0x31, 0x32, 0x44, 0x80);
614    /// assert_eq!(color.to_rgba_tuple(), (0x31, 0x32, 0x44, 0x80));
615    /// ```
616    #[must_use]
617    pub const fn to_rgba_tuple(&self) -> (u8, u8, u8, u8) {
618        (self.r, self.g, self.b, self.a)
619    }
620
621    /// Returns the color as a hex string.
622    ///
623    /// Returns 6-digit format for opaque colors, 8-digit for transparent.
624    ///
625    /// # Example
626    ///
627    /// ```rust
628    /// use fernctl::domain::tokens::color::*;
629    ///
630    /// let opaque = ColorToken::<Surface>::from_hex("#313244").unwrap();
631    /// assert_eq!(opaque.to_hex(), "#313244");
632    ///
633    /// let transparent = ColorToken::<Surface>::from_rgba(0x31, 0x32, 0x44, 0x80);
634    /// assert_eq!(transparent.to_hex(), "#31324480");
635    /// ```
636    #[must_use]
637    pub fn to_hex(&self) -> String {
638        if self.is_opaque() {
639            format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
640        } else {
641            format!("#{:02x}{:02x}{:02x}{:02x}", self.r, self.g, self.b, self.a)
642        }
643    }
644
645    /// Returns the color as a CSS `rgb()` or `rgba()` function.
646    ///
647    /// # Example
648    ///
649    /// ```rust
650    /// use fernctl::domain::tokens::color::*;
651    ///
652    /// let opaque = ColorToken::<Surface>::from_rgb(49, 50, 68);
653    /// assert_eq!(opaque.to_css_rgb(), "rgb(49, 50, 68)");
654    ///
655    /// let transparent = ColorToken::<Surface>::from_rgba(49, 50, 68, 128);
656    /// assert_eq!(transparent.to_css_rgb(), "rgba(49, 50, 68, 0.50)");
657    /// ```
658    #[must_use]
659    pub fn to_css_rgb(&self) -> String {
660        if self.is_opaque() {
661            format!("rgb({}, {}, {})", self.r, self.g, self.b)
662        } else {
663            let alpha = f32::from(self.a) / 255.0;
664            format!("rgba({}, {}, {}, {:.2})", self.r, self.g, self.b, alpha)
665        }
666    }
667
668    /// Returns the semantic role name of this color.
669    ///
670    /// # Example
671    ///
672    /// ```rust
673    /// use fernctl::domain::tokens::color::*;
674    ///
675    /// let color = ColorToken::<Surface>::from_rgb(0, 0, 0);
676    /// assert_eq!(color.role_name(), "surface");
677    /// ```
678    #[must_use]
679    pub fn role_name(&self) -> &'static str {
680        Role::role_name()
681    }
682
683    /// Creates a new color with a different alpha value.
684    ///
685    /// # Example
686    ///
687    /// ```rust
688    /// use fernctl::domain::tokens::color::*;
689    ///
690    /// let opaque = ColorToken::<Surface>::from_hex("#313244").unwrap();
691    /// let transparent = opaque.with_alpha(128);
692    /// assert_eq!(transparent.alpha(), 128);
693    /// ```
694    #[must_use]
695    pub const fn with_alpha(&self, alpha: u8) -> Self {
696        Self {
697            r: self.r,
698            g: self.g,
699            b: self.b,
700            a: alpha,
701            _role: PhantomData,
702        }
703    }
704}
705
706impl<Role: ColorRole> fmt::Debug for ColorToken<Role> {
707    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
708        f.debug_struct("ColorToken")
709            .field("role", &Role::role_name())
710            .field("hex", &self.to_hex())
711            .finish()
712    }
713}
714
715impl<Role: ColorRole> fmt::Display for ColorToken<Role> {
716    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
717        write!(f, "{}", self.to_hex())
718    }
719}
720
721impl<Role: ColorRole> Default for ColorToken<Role> {
722    /// Returns a default color (black, fully opaque).
723    fn default() -> Self {
724        Self::from_rgb(0, 0, 0)
725    }
726}
727
728// Serialization: Colors serialize to hex strings
729impl<Role: ColorRole> Serialize for ColorToken<Role> {
730    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
731    where
732        S: serde::Serializer,
733    {
734        self.to_hex().serialize(serializer)
735    }
736}
737
738impl<'de, Role: ColorRole> Deserialize<'de> for ColorToken<Role> {
739    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
740    where
741        D: serde::Deserializer<'de>,
742    {
743        let hex = String::deserialize(deserializer)?;
744        Self::from_hex(&hex).map_err(serde::de::Error::custom)
745    }
746}
747
748// ============================================================================
749// Helper Functions
750// ============================================================================
751
752/// Parses a hex color string into RGBA components.
753///
754/// Supports `#RGB`, `#RRGGBB`, and `#RRGGBBAA` formats.
755fn parse_hex_color<Role: ColorRole>(hex: &str) -> Option<ColorToken<Role>> {
756    let hex = hex.strip_prefix('#')?;
757
758    match hex.len() {
759        // #RGB shorthand
760        3 => {
761            let r = parse_hex_digit(hex.as_bytes().first()?)?;
762            let g = parse_hex_digit(hex.as_bytes().get(1)?)?;
763            let b = parse_hex_digit(hex.as_bytes().get(2)?)?;
764            // Expand: F -> FF
765            Some(ColorToken::from_rgb(r | (r << 4), g | (g << 4), b | (b << 4)))
766        }
767        // #RRGGBB
768        6 => {
769            let r = parse_hex_byte(&hex[0..2])?;
770            let g = parse_hex_byte(&hex[2..4])?;
771            let b = parse_hex_byte(&hex[4..6])?;
772            Some(ColorToken::from_rgb(r, g, b))
773        }
774        // #RRGGBBAA
775        8 => {
776            let r = parse_hex_byte(&hex[0..2])?;
777            let g = parse_hex_byte(&hex[2..4])?;
778            let b = parse_hex_byte(&hex[4..6])?;
779            let a = parse_hex_byte(&hex[6..8])?;
780            Some(ColorToken::from_rgba(r, g, b, a))
781        }
782        _ => None,
783    }
784}
785
786/// Parses a single hex digit.
787fn parse_hex_digit(byte: &u8) -> Option<u8> {
788    match byte {
789        b'0'..=b'9' => Some(byte - b'0'),
790        b'a'..=b'f' => Some(byte - b'a' + 10),
791        b'A'..=b'F' => Some(byte - b'A' + 10),
792        _ => None,
793    }
794}
795
796/// Parses a two-character hex byte.
797fn parse_hex_byte(s: &str) -> Option<u8> {
798    u8::from_str_radix(s, 16).ok()
799}
800
801// ============================================================================
802// Tests
803// ============================================================================
804
805#[cfg(test)]
806mod tests {
807    use super::*;
808
809    #[test]
810    fn color_token_size() {
811        assert_eq!(std::mem::size_of::<ColorToken<Surface>>(), 4);
812    }
813
814    #[test]
815    fn from_rgb() {
816        let color = ColorToken::<Surface>::from_rgb(0x31, 0x32, 0x44);
817        assert_eq!(color.red(), 0x31);
818        assert_eq!(color.green(), 0x32);
819        assert_eq!(color.blue(), 0x44);
820        assert_eq!(color.alpha(), 255);
821        assert!(color.is_opaque());
822    }
823
824    #[test]
825    fn from_rgba() {
826        let color = ColorToken::<Surface>::from_rgba(0x31, 0x32, 0x44, 0x80);
827        assert_eq!(color.alpha(), 0x80);
828        assert!(!color.is_opaque());
829    }
830
831    #[test]
832    fn from_hex_6_digit() {
833        let color = ColorToken::<Surface>::from_hex("#313244").unwrap();
834        assert_eq!(color.red(), 0x31);
835        assert_eq!(color.green(), 0x32);
836        assert_eq!(color.blue(), 0x44);
837    }
838
839    #[test]
840    fn from_hex_3_digit() {
841        let color = ColorToken::<Foreground>::from_hex("#fff").unwrap();
842        assert_eq!(color.red(), 255);
843        assert_eq!(color.green(), 255);
844        assert_eq!(color.blue(), 255);
845    }
846
847    #[test]
848    fn from_hex_8_digit() {
849        let color = ColorToken::<Surface>::from_hex("#31324480").unwrap();
850        assert_eq!(color.alpha(), 0x80);
851    }
852
853    #[test]
854    fn from_hex_invalid() {
855        assert!(ColorToken::<Surface>::from_hex("313244").is_err()); // Missing #
856        assert!(ColorToken::<Surface>::from_hex("#gg0000").is_err()); // Invalid hex
857        assert!(ColorToken::<Surface>::from_hex("#12345").is_err()); // Wrong length
858    }
859
860    #[test]
861    fn to_hex_roundtrip() {
862        let original = "#89b4fa";
863        let color = ColorToken::<Accent>::from_hex(original).unwrap();
864        assert_eq!(color.to_hex(), original);
865    }
866
867    #[test]
868    fn serialization_roundtrip() {
869        let color = ColorToken::<Surface>::from_hex("#313244").unwrap();
870        let json = serde_json::to_string(&color).unwrap();
871        assert_eq!(json, "\"#313244\"");
872
873        let restored: ColorToken<Surface> = serde_json::from_str(&json).unwrap();
874        assert_eq!(color, restored);
875    }
876
877    #[test]
878    fn role_name() {
879        let surface = ColorToken::<Surface>::from_rgb(0, 0, 0);
880        assert_eq!(surface.role_name(), "surface");
881
882        let foreground = ColorToken::<Foreground>::from_rgb(0, 0, 0);
883        assert_eq!(foreground.role_name(), "foreground");
884    }
885}