Skip to main content

crisol_core/theme/
mod.rs

1//! Theme tokens and palettes.
2//!
3//! Nine stable identifiers cover the GitHub, Dracula, and One Dark Pro families. Every
4//! color the shell paints comes from [`Theme`]; the UI converts the tokens to
5//! `egui::Color32` with a lossless byte conversion. Contrast is checked against WCAG 2.2
6//! AA both here and in the UI's snapshot tests.
7//!
8//! ```
9//! use crisol_core::theme::{Theme, ThemeId, contrast_ratio};
10//!
11//! let theme = Theme::for_id(ThemeId::Dracula);
12//! assert!(theme.is_dark());
13//! assert!(contrast_ratio(theme.text, theme.background) >= 4.5);
14//! ```
15
16mod palette;
17mod studio;
18
19use crate::color::Rgba;
20
21pub use palette::ThemeId;
22#[cfg(feature = "serde")]
23pub use studio::ThemeImportError;
24
25/// Duration of every hover, tab, and switch animation, in seconds.
26/// # Example
27///
28/// ```
29/// use crisol_core::theme::ANIMATION_TIME;
30/// ```
31pub const ANIMATION_TIME: f32 = 0.10;
32
33/// The light or dark base of a theme.
34#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
35#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37#[non_exhaustive]
38/// # Example
39///
40/// ```
41/// use crisol_core::theme::ThemeMode;
42/// ```
43pub enum ThemeMode {
44    /// Light surfaces.
45    #[default]
46    Light,
47    /// Dark surfaces.
48    Dark,
49}
50
51impl ThemeMode {
52    /// Parse a value stored in settings.
53    pub fn from_setting(value: &str) -> Self {
54        if value == "dark" { Self::Dark } else { Self::Light }
55    }
56
57    /// The value stored in settings.
58    pub fn as_setting(self) -> &'static str {
59        match self {
60            Self::Light => "light",
61            Self::Dark => "dark",
62        }
63    }
64}
65
66/// The color tokens of one theme.
67#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69#[non_exhaustive]
70/// # Example
71///
72/// ```
73/// use crisol_core::theme::Theme;
74/// ```
75pub struct Theme {
76    /// Window, editor, and panel background (`visuals.panel_fill`).
77    pub background: Rgba,
78    /// Raised chrome: menus, dialogs, the sidebar, the tab strip (`visuals.window_fill`).
79    pub surface: Rgba,
80    /// A second raised surface for cards.
81    pub surface_raised: Rgba,
82    /// Sunken surfaces: text fields, steppers, segmented controls (`extreme_bg_color`).
83    pub sunken: Rgba,
84    /// Primary text.
85    pub text: Rgba,
86    /// Secondary text: hints, descriptions, inactive tabs.
87    pub text_muted: Rgba,
88    /// Brand accent.
89    pub accent: Rgba,
90    /// Text drawn on the accent.
91    pub accent_text: Rgba,
92    /// Borders and separators.
93    pub border: Rgba,
94    /// Selection background: selected rows, active segments, primary buttons.
95    pub selection: Rgba,
96    /// Hover background for rows and icon buttons.
97    pub hover: Rgba,
98    /// Errors and destructive actions.
99    pub danger: Rgba,
100    /// Warnings and conflict banners.
101    pub warning: Rgba,
102    /// Success messages.
103    pub success: Rgba,
104    /// "Done" purple.
105    pub done: Rgba,
106    /// Hyperlinks.
107    pub link: Rgba,
108    /// Scrollbar handle.
109    pub scrollbar: Rgba,
110    /// Keyboard focus ring, hovered borders, and the active-row marker.
111    pub focus: Rgba,
112}
113
114impl Default for Theme {
115    fn default() -> Self {
116        Self::light()
117    }
118}
119
120impl Theme {
121    /// GitHub Light.
122    pub fn light() -> Self {
123        palette::theme(ThemeId::GithubLight)
124    }
125
126    /// GitHub Dark.
127    pub fn dark() -> Self {
128        palette::theme(ThemeId::GithubDark)
129    }
130
131    /// The tokens for a theme identifier.
132    pub fn for_id(id: ThemeId) -> Self {
133        palette::theme(id)
134    }
135
136    /// Whether the surface is dark.
137    pub fn is_dark(&self) -> bool {
138        relative_luminance(self.background) < 0.5
139    }
140
141    /// The same tokens with a new brand color: `accent`, `focus`, `link`, `selection`,
142    /// and `accent_text` are derived from it so they keep AA contrast on this base.
143    ///
144    /// ```
145    /// use crisol_core::color::Rgba;
146    /// use crisol_core::theme::{Theme, contrast_ratio};
147    ///
148    /// let brand = Theme::dark().with_accent(Rgba::from_rgb(0xe0, 0x6c, 0x2b));
149    /// assert!(contrast_ratio(brand.link, brand.background) >= 4.5);
150    /// assert!(contrast_ratio(brand.accent_text, brand.accent) >= 4.5);
151    /// ```
152    pub fn with_accent(mut self, accent: Rgba) -> Self {
153        let towards = if self.is_dark() { Rgba::WHITE } else { Rgba::BLACK };
154        self.accent = accent;
155        self.focus = until_contrast(accent, self.background, towards, 3.0);
156        self.link = until_contrast(accent, self.background, towards, 4.5);
157        self.selection = mix(self.background, accent, if self.is_dark() { 0.35 } else { 0.28 });
158        // White or black text, whichever reads better on the accent.
159        self.accent_text = if contrast_ratio(Rgba::WHITE, accent) >= contrast_ratio(Rgba::BLACK, accent) {
160            Rgba::WHITE
161        } else {
162            Rgba::BLACK
163        };
164        if contrast_ratio(self.accent_text, self.accent) < 4.5 {
165            // A mid-tone accent: darken (or lighten) it until its text passes.
166            let away = if self.accent_text == Rgba::WHITE {
167                Rgba::BLACK
168            } else {
169                Rgba::WHITE
170            };
171            self.accent = until_contrast(self.accent, self.accent_text, away, 4.5);
172        }
173        self
174    }
175
176    /// The pairs that miss WCAG AA (4.5:1 for text, 3:1 for the focus ring), with their
177    /// ratio. Empty for every built-in theme; check your own themes with it.
178    pub fn accessibility_issues(&self) -> Vec<(&'static str, f32)> {
179        let mut issues = Vec::new();
180        for (label, foreground, background, minimum) in [
181            ("text on background", self.text, self.background, 4.5),
182            ("text on surface", self.text, self.surface, 4.5),
183            ("muted text on background", self.text_muted, self.background, 4.5),
184            ("link on background", self.link, self.background, 4.5),
185            ("accent text on accent", self.accent_text, self.accent, 4.5),
186            ("danger on background", self.danger, self.background, 4.5),
187            ("focus on background", self.focus, self.background, 3.0),
188        ] {
189            let ratio = contrast_ratio(foreground, background);
190            if ratio < minimum {
191                issues.push((label, ratio));
192            }
193        }
194        issues
195    }
196
197    /// Every token, by its stable field name.
198    ///
199    /// This is the table frozen in `tests/fixtures/theme/golden-0.1.3.json`.
200    pub fn tokens(&self) -> [(&'static str, Rgba); 18] {
201        [
202            ("background", self.background),
203            ("surface", self.surface),
204            ("surface_raised", self.surface_raised),
205            ("sunken", self.sunken),
206            ("text", self.text),
207            ("text_muted", self.text_muted),
208            ("accent", self.accent),
209            ("accent_text", self.accent_text),
210            ("border", self.border),
211            ("selection", self.selection),
212            ("hover", self.hover),
213            ("danger", self.danger),
214            ("warning", self.warning),
215            ("success", self.success),
216            ("done", self.done),
217            ("link", self.link),
218            ("scrollbar", self.scrollbar),
219            ("focus", self.focus),
220        ]
221    }
222}
223
224/// Resolve a theme against the system preference, keeping its family.
225/// # Example
226///
227/// ```
228/// use crisol_core::theme::effective_id;
229/// ```
230pub fn effective_id(id: ThemeId, follow_system: bool, system_dark: bool) -> ThemeId {
231    if follow_system {
232        id.follow_system(system_dark)
233    } else {
234        id
235    }
236}
237
238/// `a` blended towards `b` by `t` (0 = `a`, 1 = `b`), in sRGB.
239/// # Example
240///
241/// ```
242/// use crisol_core::theme::mix;
243/// ```
244pub fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
245    a.mix(b, t)
246}
247
248/// `color` moved step by step towards `towards` until it reaches `minimum` contrast
249/// against `background` (or becomes `towards`).
250pub(crate) fn until_contrast(color: Rgba, background: Rgba, towards: Rgba, minimum: f32) -> Rgba {
251    let mut candidate = color;
252    for step in 0..=20 {
253        candidate = mix(color, towards, step as f32 / 20.0);
254        if contrast_ratio(candidate, background) >= minimum {
255            break;
256        }
257    }
258    candidate
259}
260
261/// Relative luminance of an sRGB color (WCAG 2.2).
262/// # Example
263///
264/// ```
265/// use crisol_core::theme::relative_luminance;
266/// ```
267pub fn relative_luminance(color: Rgba) -> f32 {
268    color.relative_luminance()
269}
270
271/// White or `dark`, whichever reads better on `fill` (for text on colored buttons).
272/// # Example
273///
274/// ```
275/// use crisol_core::theme::readable_on;
276/// ```
277pub fn readable_on(fill: Rgba, dark: Rgba) -> Rgba {
278    if contrast_ratio(Rgba::WHITE, fill) >= contrast_ratio(dark, fill) {
279        Rgba::WHITE
280    } else {
281        dark
282    }
283}
284
285/// Contrast ratio between two opaque colors, from 1.0 to 21.0.
286/// # Example
287///
288/// ```
289/// use crisol_core::theme::contrast_ratio;
290/// ```
291pub fn contrast_ratio(a: Rgba, b: Rgba) -> f32 {
292    let (first, second) = (relative_luminance(a), relative_luminance(b));
293    let (light, dark) = if first > second {
294        (first, second)
295    } else {
296        (second, first)
297    };
298    (light + 0.05) / (dark + 0.05)
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn every_theme_has_consistent_darkness() {
307        for id in ThemeId::ALL {
308            assert_eq!(Theme::for_id(id).is_dark(), id.mode() == ThemeMode::Dark, "{id:?}");
309        }
310    }
311
312    #[test]
313    fn contrast_meets_aa_for_primary_pairs() {
314        for id in ThemeId::ALL {
315            let theme = Theme::for_id(id);
316            for (foreground, background, label) in [
317                (theme.text, theme.background, "text/background"),
318                (theme.text, theme.surface, "text/surface"),
319                (theme.text_muted, theme.background, "muted/background"),
320                (theme.link, theme.background, "link/background"),
321                (theme.accent_text, theme.accent, "accent text/accent"),
322                (theme.danger, theme.background, "danger/background"),
323            ] {
324                let ratio = contrast_ratio(foreground, background);
325                assert!(ratio >= 4.5, "{id:?} {label}: {ratio:.2}");
326            }
327            assert!(contrast_ratio(theme.focus, theme.background) >= 3.0, "{id:?} focus");
328        }
329    }
330
331    #[test]
332    fn destructive_text_meets_aa_in_every_theme() {
333        for id in ThemeId::ALL {
334            let theme = Theme::for_id(id);
335            let text = readable_on(theme.danger, theme.background);
336            let ratio = contrast_ratio(text, theme.danger);
337            assert!(ratio >= 3.0, "{id:?} destructive: {ratio:.2}");
338        }
339    }
340
341    #[test]
342    fn the_high_contrast_theme_meets_aaa_text() {
343        let theme = Theme::dark().high_contrast();
344        assert!(contrast_ratio(theme.text, theme.background) >= 7.0);
345        assert!(contrast_ratio(theme.text_muted, theme.background) >= 7.0);
346        assert!(theme.is_dark());
347    }
348
349    #[test]
350    fn built_in_themes_have_no_accessibility_issues() {
351        for id in ThemeId::ALL {
352            assert_eq!(Theme::for_id(id).accessibility_issues(), Vec::new(), "{id:?}");
353        }
354    }
355
356    #[test]
357    fn accents_keep_aa_contrast_on_every_base() {
358        let accents = [
359            Rgba::from_rgb(0xff, 0xd7, 0x00),
360            Rgba::from_rgb(0x00, 0x7a, 0xcc),
361            Rgba::from_rgb(0xe0, 0x6c, 0x2b),
362            Rgba::from_rgb(0x8a, 0x2b, 0xe2),
363            Rgba::from_rgb(0x20, 0xc0, 0x60),
364        ];
365        for id in ThemeId::ALL {
366            for accent in accents {
367                let theme = Theme::for_id(id).with_accent(accent);
368                assert_eq!(theme.accessibility_issues(), Vec::new(), "{id:?} {accent:?}");
369            }
370        }
371    }
372
373    #[cfg(feature = "serde")]
374    #[test]
375    fn vscode_themes_import_and_export() {
376        let text = r##"{
377            "colors": {
378                "editor.background": "#1e1e1e",
379                "foreground": "#d4d4d4",
380                "focusBorder": "#007acc",
381                "list.activeSelectionBackground": "#264f78",
382                "descriptionForeground": "#9d9d9d"
383            }
384        }"##;
385        let theme = Theme::from_vscode_json(text).expect("import");
386        assert_eq!(theme.background, Rgba::from_rgb(0x1e, 0x1e, 0x1e));
387        assert_eq!(theme.text, Rgba::from_rgb(0xd4, 0xd4, 0xd4));
388        assert!(theme.accessibility_issues().is_empty());
389        let css = theme.to_css_variables();
390        assert!(css.contains("--wb-background: #1e1e1e;"));
391        assert_eq!(theme.to_json()["background"], "#1e1e1e");
392        assert!(Theme::from_vscode_json("{\"colors\":{}}").is_err());
393    }
394
395    #[test]
396    fn high_contrast_keeps_aa() {
397        for theme in [Theme::dark().high_contrast(), Theme::light().high_contrast()] {
398            assert!(theme.accessibility_issues().is_empty());
399            assert_eq!(
400                theme.background,
401                if theme.is_dark() { Rgba::BLACK } else { Rgba::WHITE }
402            );
403        }
404    }
405
406    #[test]
407    fn black_and_white_are_twenty_one_to_one() {
408        assert!((contrast_ratio(Rgba::BLACK, Rgba::WHITE) - 21.0).abs() < 0.01);
409    }
410
411    #[test]
412    fn modes_round_trip() {
413        for mode in [ThemeMode::Light, ThemeMode::Dark] {
414            assert_eq!(ThemeMode::from_setting(mode.as_setting()), mode);
415        }
416    }
417
418    #[test]
419    fn tokens_cover_every_field() {
420        let theme = Theme::light();
421        assert_eq!(theme.tokens().len(), 18);
422        assert_eq!(theme.tokens()[0], ("background", theme.background));
423        assert_eq!(theme.tokens()[17], ("focus", theme.focus));
424    }
425}