crisol-core 1.0.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Theme tokens and palettes.
//!
//! Nine stable identifiers cover the GitHub, Dracula, and One Dark Pro families. Every
//! color the shell paints comes from [`Theme`]; the UI converts the tokens to
//! `egui::Color32` with a lossless byte conversion. Contrast is checked against WCAG 2.2
//! AA both here and in the UI's snapshot tests.
//!
//! ```
//! use crisol_core::theme::{Theme, ThemeId, contrast_ratio};
//!
//! let theme = Theme::for_id(ThemeId::Dracula);
//! assert!(theme.is_dark());
//! assert!(contrast_ratio(theme.text, theme.background) >= 4.5);
//! ```

mod palette;
mod studio;

use crate::color::Rgba;

pub use palette::ThemeId;
#[cfg(feature = "serde")]
pub use studio::ThemeImportError;

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

/// The light or dark base of a theme.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::theme::ThemeMode;
/// ```
pub enum ThemeMode {
    /// Light surfaces.
    #[default]
    Light,
    /// Dark surfaces.
    Dark,
}

impl ThemeMode {
    /// Parse a value stored in settings.
    pub fn from_setting(value: &str) -> Self {
        if value == "dark" { Self::Dark } else { Self::Light }
    }

    /// The value stored in settings.
    pub fn as_setting(self) -> &'static str {
        match self {
            Self::Light => "light",
            Self::Dark => "dark",
        }
    }
}

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

impl Default for Theme {
    fn default() -> Self {
        Self::light()
    }
}

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

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

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

    /// 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: `accent`, `focus`, `link`, `selection`,
    /// and `accent_text` are derived from it so they keep AA contrast on this base.
    ///
    /// ```
    /// use crisol_core::color::Rgba;
    /// use crisol_core::theme::{Theme, contrast_ratio};
    ///
    /// let brand = Theme::dark().with_accent(Rgba::from_rgb(0xe0, 0x6c, 0x2b));
    /// assert!(contrast_ratio(brand.link, brand.background) >= 4.5);
    /// assert!(contrast_ratio(brand.accent_text, brand.accent) >= 4.5);
    /// ```
    pub fn with_accent(mut self, accent: Rgba) -> Self {
        let towards = if self.is_dark() { Rgba::WHITE } else { Rgba::BLACK };
        self.accent = accent;
        self.focus = until_contrast(accent, self.background, towards, 3.0);
        self.link = until_contrast(accent, self.background, towards, 4.5);
        self.selection = mix(self.background, accent, if self.is_dark() { 0.35 } else { 0.28 });
        // White or black text, whichever reads better on the accent.
        self.accent_text = if contrast_ratio(Rgba::WHITE, accent) >= contrast_ratio(Rgba::BLACK, accent) {
            Rgba::WHITE
        } else {
            Rgba::BLACK
        };
        if contrast_ratio(self.accent_text, self.accent) < 4.5 {
            // A mid-tone accent: darken (or lighten) it until its text passes.
            let away = if self.accent_text == Rgba::WHITE {
                Rgba::BLACK
            } else {
                Rgba::WHITE
            };
            self.accent = until_contrast(self.accent, self.accent_text, away, 4.5);
        }
        self
    }

    /// The pairs that miss WCAG AA (4.5:1 for text, 3:1 for the focus ring), with their
    /// ratio. Empty for every built-in theme; check your own themes with it.
    pub fn accessibility_issues(&self) -> Vec<(&'static str, f32)> {
        let mut issues = Vec::new();
        for (label, foreground, background, minimum) in [
            ("text on background", self.text, self.background, 4.5),
            ("text on surface", self.text, self.surface, 4.5),
            ("muted text on background", self.text_muted, self.background, 4.5),
            ("link on background", self.link, self.background, 4.5),
            ("accent text on accent", self.accent_text, self.accent, 4.5),
            ("danger on background", self.danger, self.background, 4.5),
            ("focus on background", self.focus, self.background, 3.0),
        ] {
            let ratio = contrast_ratio(foreground, background);
            if ratio < minimum {
                issues.push((label, ratio));
            }
        }
        issues
    }

    /// Every token, by its stable field name.
    ///
    /// This is the table frozen in `tests/fixtures/theme/golden-0.1.3.json`.
    pub fn tokens(&self) -> [(&'static str, Rgba); 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),
        ]
    }
}

/// Resolve a theme against the system preference, keeping its family.
/// # Example
///
/// ```
/// use crisol_core::theme::effective_id;
/// ```
pub fn effective_id(id: ThemeId, follow_system: bool, system_dark: bool) -> ThemeId {
    if follow_system {
        id.follow_system(system_dark)
    } else {
        id
    }
}

/// `a` blended towards `b` by `t` (0 = `a`, 1 = `b`), in sRGB.
/// # Example
///
/// ```
/// use crisol_core::theme::mix;
/// ```
pub fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
    a.mix(b, t)
}

/// `color` moved step by step towards `towards` until it reaches `minimum` contrast
/// against `background` (or becomes `towards`).
pub(crate) fn until_contrast(color: Rgba, background: Rgba, towards: Rgba, minimum: f32) -> Rgba {
    let mut candidate = color;
    for step in 0..=20 {
        candidate = mix(color, towards, step as f32 / 20.0);
        if contrast_ratio(candidate, background) >= minimum {
            break;
        }
    }
    candidate
}

/// Relative luminance of an sRGB color (WCAG 2.2).
/// # Example
///
/// ```
/// use crisol_core::theme::relative_luminance;
/// ```
pub fn relative_luminance(color: Rgba) -> f32 {
    color.relative_luminance()
}

/// White or `dark`, whichever reads better on `fill` (for text on colored buttons).
/// # Example
///
/// ```
/// use crisol_core::theme::readable_on;
/// ```
pub fn readable_on(fill: Rgba, dark: Rgba) -> Rgba {
    if contrast_ratio(Rgba::WHITE, fill) >= contrast_ratio(dark, fill) {
        Rgba::WHITE
    } else {
        dark
    }
}

/// Contrast ratio between two opaque colors, from 1.0 to 21.0.
/// # Example
///
/// ```
/// use crisol_core::theme::contrast_ratio;
/// ```
pub fn contrast_ratio(a: Rgba, b: Rgba) -> f32 {
    let (first, second) = (relative_luminance(a), relative_luminance(b));
    let (light, dark) = if first > second {
        (first, second)
    } else {
        (second, first)
    };
    (light + 0.05) / (dark + 0.05)
}

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

    #[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 = [
            Rgba::from_rgb(0xff, 0xd7, 0x00),
            Rgba::from_rgb(0x00, 0x7a, 0xcc),
            Rgba::from_rgb(0xe0, 0x6c, 0x2b),
            Rgba::from_rgb(0x8a, 0x2b, 0xe2),
            Rgba::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, Rgba::from_rgb(0x1e, 0x1e, 0x1e));
        assert_eq!(theme.text, Rgba::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() { Rgba::BLACK } else { Rgba::WHITE }
            );
        }
    }

    #[test]
    fn black_and_white_are_twenty_one_to_one() {
        assert!((contrast_ratio(Rgba::BLACK, Rgba::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);
        }
    }

    #[test]
    fn tokens_cover_every_field() {
        let theme = Theme::light();
        assert_eq!(theme.tokens().len(), 18);
        assert_eq!(theme.tokens()[0], ("background", theme.background));
        assert_eq!(theme.tokens()[17], ("focus", theme.focus));
    }
}