crisol-ui-kit 1.8.1

Crisol UI kit: themes, style tokens, icon caches, fonts, localization, base components, and widgets.
Documentation
//! Theme tokens and their application to egui.
//!
//! The canonical palettes, contrast math, and Theme Studio logic live in
//! [`crisol_core::theme`]. This module is the UI adapter: [`Theme`] exposes the same
//! nineteen-year-stable `Color32` fields the workbench has always used, and every
//! conversion is a lossless byte copy (PIX-COL-01, PIX-COL-02).
//!
//! Nine stable theme identifiers cover the GitHub, Dracula, and One Dark Pro families.
//! Every color the shell paints comes from [`Theme`] or from the egui visuals that
//! [`apply_id`] derives from it; components never invent a literal color (the only
//! exceptions are the window close button's red hover and white glyph, as on Windows
//! and GNOME). Contrast is checked in tests against WCAG 2.2 AA.

mod apply;

use egui::{Color32, Stroke};

pub use apply::{
    apply, apply_id, apply_theme, apply_tokens, current, motion_enabled, set_reduced_motion, system_is_dark,
};
#[cfg(feature = "serde")]
pub use crisol_core::theme::ThemeImportError;
pub use crisol_core::theme::{ThemeId, ThemeMode, effective_id};

use crisol_core::color::Rgba;

/// Duration of every hover, tab, and switch animation, in seconds.
pub const ANIMATION_TIME: f32 = crisol_core::theme::ANIMATION_TIME;

/// Convert a core color to an egui color with no rounding.
fn color32(color: Rgba) -> Color32 {
    let [r, g, b, a] = color.to_array();
    Color32::from_rgba_premultiplied(r, g, b, a)
}

/// Convert an egui color to the core representation with no rounding.
fn rgba(color: Color32) -> Rgba {
    Rgba::from_array(color.to_array())
}

/// The color tokens of one theme.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Theme {
    /// Window, editor, and panel background (`visuals.panel_fill`).
    pub background: Color32,
    /// Raised chrome: menus, dialogs, the sidebar, the tab strip (`visuals.window_fill`).
    pub surface: Color32,
    /// A second raised surface for cards.
    pub surface_raised: Color32,
    /// Sunken surfaces: text fields, steppers, segmented controls (`extreme_bg_color`).
    pub sunken: Color32,
    /// Primary text.
    pub text: Color32,
    /// Secondary text: hints, descriptions, inactive tabs.
    pub text_muted: Color32,
    /// Brand accent.
    pub accent: Color32,
    /// Text drawn on the accent.
    pub accent_text: Color32,
    /// Borders and separators.
    pub border: Color32,
    /// Selection background: selected rows, active segments, primary buttons.
    pub selection: Color32,
    /// Hover background for rows and icon buttons.
    pub hover: Color32,
    /// Errors and destructive actions.
    pub danger: Color32,
    /// Warnings and conflict banners.
    pub warning: Color32,
    /// Success messages.
    pub success: Color32,
    /// "Done" purple.
    pub done: Color32,
    /// Hyperlinks.
    pub link: Color32,
    /// Scrollbar handle.
    pub scrollbar: Color32,
    /// Keyboard focus ring, hovered borders, and the active-row marker.
    pub focus: Color32,
}

impl Theme {
    /// GitHub Light.
    pub fn light() -> Self {
        Self::for_id(ThemeId::GithubLight)
    }

    /// GitHub Dark.
    pub fn dark() -> Self {
        Self::for_id(ThemeId::GithubDark)
    }

    /// The tokens for a theme identifier.
    pub fn for_id(id: ThemeId) -> Self {
        Self::from_core(crisol_core::theme::Theme::for_id(id))
    }

    /// The core token set, for persistence and parity checks.
    pub fn to_core(self) -> crisol_core::theme::Theme {
        let mut theme = crisol_core::theme::Theme::default();
        theme.background = rgba(self.background);
        theme.surface = rgba(self.surface);
        theme.surface_raised = rgba(self.surface_raised);
        theme.sunken = rgba(self.sunken);
        theme.text = rgba(self.text);
        theme.text_muted = rgba(self.text_muted);
        theme.accent = rgba(self.accent);
        theme.accent_text = rgba(self.accent_text);
        theme.border = rgba(self.border);
        theme.selection = rgba(self.selection);
        theme.hover = rgba(self.hover);
        theme.danger = rgba(self.danger);
        theme.warning = rgba(self.warning);
        theme.success = rgba(self.success);
        theme.done = rgba(self.done);
        theme.link = rgba(self.link);
        theme.scrollbar = rgba(self.scrollbar);
        theme.focus = rgba(self.focus);
        theme
    }

    /// Build the adapter from core tokens.
    pub fn from_core(theme: crisol_core::theme::Theme) -> Self {
        Self {
            background: color32(theme.background),
            surface: color32(theme.surface),
            surface_raised: color32(theme.surface_raised),
            sunken: color32(theme.sunken),
            text: color32(theme.text),
            text_muted: color32(theme.text_muted),
            accent: color32(theme.accent),
            accent_text: color32(theme.accent_text),
            border: color32(theme.border),
            selection: color32(theme.selection),
            hover: color32(theme.hover),
            danger: color32(theme.danger),
            warning: color32(theme.warning),
            success: color32(theme.success),
            done: color32(theme.done),
            link: color32(theme.link),
            scrollbar: color32(theme.scrollbar),
            focus: color32(theme.focus),
        }
    }

    /// Whether the surface is dark.
    pub fn is_dark(&self) -> bool {
        relative_luminance(self.background) < 0.5
    }

    /// The same tokens with a new brand color, derived exactly as in the core.
    pub fn with_accent(self, accent: Color32) -> Self {
        Self::from_core(self.to_core().with_accent(rgba(accent)))
    }

    /// The pairs that miss WCAG AA, with their ratio.
    pub fn accessibility_issues(&self) -> Vec<(&'static str, f32)> {
        self.to_core().accessibility_issues()
    }

    /// The 1 px border stroke.
    pub fn border_stroke(&self) -> Stroke {
        Stroke::new(1.0, self.border)
    }

    /// The token table, by stable field name.
    pub fn tokens(&self) -> [(&'static str, Color32); 18] {
        [
            ("background", self.background),
            ("surface", self.surface),
            ("surface_raised", self.surface_raised),
            ("sunken", self.sunken),
            ("text", self.text),
            ("text_muted", self.text_muted),
            ("accent", self.accent),
            ("accent_text", self.accent_text),
            ("border", self.border),
            ("selection", self.selection),
            ("hover", self.hover),
            ("danger", self.danger),
            ("warning", self.warning),
            ("success", self.success),
            ("done", self.done),
            ("link", self.link),
            ("scrollbar", self.scrollbar),
            ("focus", self.focus),
        ]
    }

    /// A high-contrast variant, computed by the core.
    pub fn high_contrast(self) -> Self {
        Self::from_core(self.to_core().high_contrast())
    }

    /// Adjust text and accent pairs until they reach WCAG AA.
    pub fn ensure_aa(self) -> Self {
        Self::from_core(self.to_core().ensure_aa())
    }

    /// The theme as `#rrggbb` CSS custom properties.
    pub fn to_css_variables(&self) -> String {
        self.to_core().to_css_variables()
    }

    /// Import a VS Code color theme.
    ///
    /// # Errors
    /// When the JSON is malformed or lacks `editor.background` and `foreground`.
    #[cfg(feature = "serde")]
    pub fn from_vscode_json(text: &str) -> Result<Self, ThemeImportError> {
        crisol_core::theme::Theme::from_vscode_json(text).map(Self::from_core)
    }

    /// The theme as JSON tokens.
    #[cfg(feature = "serde")]
    pub fn to_json(&self) -> serde_json::Value {
        self.to_core().to_json()
    }
}

/// `a` blended towards `b` by `t` (0 = `a`, 1 = `b`), in sRGB.
pub fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
    color32(crisol_core::theme::mix(rgba(a), rgba(b), t))
}

/// Relative luminance of an sRGB color (WCAG 2.2).
pub fn relative_luminance(color: Color32) -> f32 {
    crisol_core::theme::relative_luminance(rgba(color))
}

/// White or `dark`, whichever reads better on `fill` (for text on colored buttons).
pub fn readable_on(fill: Color32, dark: Color32) -> Color32 {
    color32(crisol_core::theme::readable_on(rgba(fill), rgba(dark)))
}

/// Contrast ratio between two opaque colors, from 1.0 to 21.0.
pub fn contrast_ratio(a: Color32, b: Color32) -> f32 {
    crisol_core::theme::contrast_ratio(rgba(a), rgba(b))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_theme_round_trips_through_the_core() {
        for id in ThemeId::ALL {
            let theme = Theme::for_id(id);
            assert_eq!(Theme::from_core(theme.to_core()), theme, "{id:?}");
        }
    }

    #[test]
    fn every_theme_has_consistent_darkness() {
        for id in ThemeId::ALL {
            assert_eq!(Theme::for_id(id).is_dark(), id.mode() == ThemeMode::Dark, "{id:?}");
        }
    }

    #[test]
    fn contrast_meets_aa_for_primary_pairs() {
        for id in ThemeId::ALL {
            let theme = Theme::for_id(id);
            for (foreground, background, label) in [
                (theme.text, theme.background, "text/background"),
                (theme.text, theme.surface, "text/surface"),
                (theme.text_muted, theme.background, "muted/background"),
                (theme.link, theme.background, "link/background"),
                (theme.accent_text, theme.accent, "accent text/accent"),
                (theme.danger, theme.background, "danger/background"),
            ] {
                let ratio = contrast_ratio(foreground, background);
                assert!(ratio >= 4.5, "{id:?} {label}: {ratio:.2}");
            }
            assert!(contrast_ratio(theme.focus, theme.background) >= 3.0, "{id:?} focus");
        }
    }

    #[test]
    fn destructive_text_meets_aa_in_every_theme() {
        for id in ThemeId::ALL {
            let theme = Theme::for_id(id);
            let text = readable_on(theme.danger, theme.background);
            let ratio = contrast_ratio(text, theme.danger);
            assert!(ratio >= 3.0, "{id:?} destructive: {ratio:.2}");
        }
    }

    #[test]
    fn built_in_themes_have_no_accessibility_issues() {
        for id in ThemeId::ALL {
            assert_eq!(Theme::for_id(id).accessibility_issues(), Vec::new(), "{id:?}");
        }
    }

    #[test]
    fn accents_keep_aa_contrast_on_every_base() {
        let accents = [
            Color32::from_rgb(0xff, 0xd7, 0x00),
            Color32::from_rgb(0x00, 0x7a, 0xcc),
            Color32::from_rgb(0xe0, 0x6c, 0x2b),
            Color32::from_rgb(0x8a, 0x2b, 0xe2),
            Color32::from_rgb(0x20, 0xc0, 0x60),
        ];
        for id in ThemeId::ALL {
            for accent in accents {
                let theme = Theme::for_id(id).with_accent(accent);
                assert_eq!(theme.accessibility_issues(), Vec::new(), "{id:?} {accent:?}");
            }
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn vscode_themes_import_and_export() {
        let text = r##"{
            "colors": {
                "editor.background": "#1e1e1e",
                "foreground": "#d4d4d4",
                "focusBorder": "#007acc",
                "list.activeSelectionBackground": "#264f78",
                "descriptionForeground": "#9d9d9d"
            }
        }"##;
        let theme = Theme::from_vscode_json(text).expect("import");
        assert_eq!(theme.background, Color32::from_rgb(0x1e, 0x1e, 0x1e));
        assert_eq!(theme.text, Color32::from_rgb(0xd4, 0xd4, 0xd4));
        assert!(theme.accessibility_issues().is_empty());
        let css = theme.to_css_variables();
        assert!(css.contains("--wb-background: #1e1e1e;"));
        assert_eq!(theme.to_json()["background"], "#1e1e1e");
        assert!(Theme::from_vscode_json("{\"colors\":{}}").is_err());
    }

    #[test]
    fn high_contrast_keeps_aa() {
        for theme in [Theme::dark().high_contrast(), Theme::light().high_contrast()] {
            assert!(theme.accessibility_issues().is_empty());
            assert_eq!(
                theme.background,
                if theme.is_dark() {
                    Color32::BLACK
                } else {
                    Color32::WHITE
                }
            );
        }
    }

    #[test]
    fn black_and_white_are_twenty_one_to_one() {
        assert!((contrast_ratio(Color32::BLACK, Color32::WHITE) - 21.0).abs() < 0.01);
    }

    #[test]
    fn modes_round_trip() {
        for mode in [ThemeMode::Light, ThemeMode::Dark] {
            assert_eq!(ThemeMode::from_setting(mode.as_setting()), mode);
        }
    }
}