Skip to main content

crisol_ui_kit/foundation/theme/
apply.rs

1//! Applying theme tokens to an egui context.
2
3use egui::style::{WidgetVisuals, Widgets};
4use egui::{Color32, Stroke};
5
6use super::{ANIMATION_TIME, Theme, ThemeId, ThemeMode, effective_id};
7
8/// Whether the desktop currently prefers a dark theme.
9pub fn system_is_dark(ctx: &egui::Context) -> bool {
10    ctx.input(|input| input.raw.system_theme)
11        .is_some_and(|theme| theme == egui::Theme::Dark)
12}
13
14/// Apply the GitHub light or dark theme.
15pub fn apply(ctx: &egui::Context, mode: ThemeMode) {
16    apply_id(
17        ctx,
18        match mode {
19            ThemeMode::Light => ThemeId::GithubLight,
20            ThemeMode::Dark => ThemeId::GithubDark,
21            _ => ThemeId::GithubLight,
22        },
23    );
24}
25
26/// Apply a theme, following the system light/dark preference when requested.
27pub fn apply_theme(ctx: &egui::Context, id: ThemeId, follow_system: bool) -> ThemeId {
28    let effective = effective_id(id, follow_system, system_is_dark(ctx));
29    apply_id(ctx, effective);
30    effective
31}
32
33/// Apply a theme identifier: visuals, widget states, spacing, scrollbars, and type scale.
34pub fn apply_id(ctx: &egui::Context, id: ThemeId) {
35    apply_tokens(ctx, &Theme::for_id(id));
36}
37
38/// Apply any set of tokens, built-in or your own (see [`Theme::with_accent`] and
39/// [`Theme::accessibility_issues`]). The light or dark egui base follows
40/// [`Theme::is_dark`]; the installed [`crate::style::WorkbenchStyle`] is kept.
41pub fn apply_tokens(ctx: &egui::Context, theme: &Theme) {
42    let theme = *theme;
43    ctx.data_mut(|data| data.insert_temp(current_key(), theme));
44    let mut visuals = if theme.is_dark() {
45        egui::Visuals::dark()
46    } else {
47        egui::Visuals::light()
48    };
49    visuals.panel_fill = theme.background;
50    visuals.window_fill = theme.surface;
51    visuals.faint_bg_color = theme.hover;
52    visuals.extreme_bg_color = theme.sunken;
53    visuals.hyperlink_color = theme.link;
54    visuals.selection.bg_fill = theme.selection;
55    visuals.selection.stroke = Stroke::new(1.0, theme.text);
56    visuals.window_stroke = Stroke::new(1.0, theme.border);
57    // Semantic colors come from the theme, not egui's saturated #FF0000 / #FF6400, so
58    // danger and warning text meets AA on every surface.
59    visuals.error_fg_color = theme.danger;
60    visuals.warn_fg_color = theme.warning;
61
62    paint_widgets(&mut visuals.widgets, &theme);
63    visuals.override_text_color = Some(theme.text);
64
65    ctx.all_styles_mut(|style| {
66        style.visuals = visuals.clone();
67        style.spacing.item_spacing = egui::vec2(8.0, 4.0);
68        style.spacing.button_padding = egui::vec2(8.0, 3.0);
69        style.spacing.interact_size = egui::vec2(26.0, 24.0);
70        style.spacing.menu_margin = egui::Margin::same(4);
71        style.spacing.scroll.bar_width = 6.0;
72        style.spacing.scroll.floating_width = 3.0;
73        style.spacing.scroll.floating_allocated_width = 4.0;
74        style.spacing.scroll.bar_inner_margin = 2.0;
75        style.animation_time = ANIMATION_TIME;
76    });
77    // Radii, border widths, and the type scale come from the installed style.
78    crate::foundation::style::apply_to_egui(ctx, &crate::foundation::style::get(ctx));
79}
80
81/// The five widget states. Fills come from the tokens; every state shares a 1 px
82/// focus-colored foreground stroke before the per-state overrides. Radii and border
83/// widths are set afterwards from the [`crate::style::WorkbenchStyle`].
84fn paint_widgets(widgets: &mut Widgets, theme: &Theme) {
85    let foreground = Stroke::new(1.0, theme.focus);
86    let states: [(&mut WidgetVisuals, Color32); 5] = [
87        (&mut widgets.noninteractive, theme.background),
88        (&mut widgets.inactive, theme.surface),
89        (&mut widgets.hovered, theme.hover),
90        (&mut widgets.active, theme.accent),
91        (&mut widgets.open, theme.surface),
92    ];
93    for (state, fill) in states {
94        state.bg_fill = fill;
95        state.weak_bg_fill = fill;
96        state.fg_stroke = foreground;
97    }
98    widgets.inactive.weak_bg_fill = theme.surface;
99    widgets.inactive.bg_stroke = theme.border_stroke();
100    widgets.hovered.bg_stroke = Stroke::new(1.0, theme.focus);
101    widgets.active.fg_stroke = Stroke::new(1.0, theme.text);
102    widgets.active.bg_stroke = Stroke::new(2.0, theme.focus);
103    widgets.noninteractive.bg_stroke = Stroke::new(1.0, theme.border);
104}
105
106fn current_key() -> egui::Id {
107    egui::Id::unique("crisol::theme::current")
108}
109
110/// The tokens of the theme last applied with [`apply_id`] (or [`apply_theme`]).
111///
112/// Components use it for the roles egui's visuals do not carry, such as
113/// `success`. Falls back to GitHub Light or Dark, following the current visuals,
114/// when no theme was applied.
115pub fn current(ctx: &egui::Context) -> Theme {
116    ctx.data(|data| data.get_temp::<Theme>(current_key()))
117        .unwrap_or_else(|| {
118            if ctx.style_of(ctx.theme()).visuals.dark_mode {
119                Theme::dark()
120            } else {
121                Theme::light()
122            }
123        })
124}
125
126/// Whether animations are on (reduced motion sets the animation time to zero).
127pub fn motion_enabled(ctx: &egui::Context) -> bool {
128    ctx.style_of(ctx.theme()).animation_time > 0.0
129}
130
131/// Turn animations off for reduced-motion preferences, or back on.
132pub fn set_reduced_motion(ctx: &egui::Context, reduced: bool) {
133    ctx.all_styles_mut(|style| {
134        style.animation_time = if reduced { 0.0 } else { ANIMATION_TIME };
135    });
136}