Skip to main content

crisol_core/state/
theme_state.rs

1//! Theme selection and preferences without a window.
2//!
3//! [`ThemeState`] is the pure state half: requested and effective theme, follow-system,
4//! reduced motion, brand accent, and a custom token set. The UI adapter applies the
5//! resulting [`Theme`] to egui and translates `Color32` at the boundary.
6//!
7//! ```
8//! use crisol_core::state::ThemeState;
9//! use crisol_core::theme::ThemeId;
10//!
11//! let mut state = ThemeState::new(ThemeId::GithubDark, false);
12//! state.set_requested(ThemeId::Dracula);
13//! state.resolve(false);
14//! assert_eq!(state.effective(), ThemeId::Dracula);
15//! ```
16
17use crate::color::Rgba;
18use crate::theme::{Theme, ThemeId, ThemeMode, effective_id};
19
20/// Requested and effective theme, follow-system, and reduced-motion preferences.
21///
22/// # Example
23///
24/// ```
25/// use crisol_core::state::ThemeState;
26/// use crisol_core::theme::ThemeId;
27///
28/// let state = ThemeState::new(ThemeId::GithubDark, false);
29/// assert_eq!(state.effective(), ThemeId::GithubDark);
30/// assert!(state.is_dark());
31/// ```
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct ThemeState {
36    requested: ThemeId,
37    follow_system: bool,
38    effective: ThemeId,
39    reduced_motion: bool,
40    accent: Option<Rgba>,
41    custom: Option<Theme>,
42}
43
44impl ThemeState {
45    /// State for `requested`, optionally following the desktop preference.
46    pub fn new(requested: ThemeId, follow_system: bool) -> Self {
47        Self {
48            requested,
49            follow_system,
50            effective: requested,
51            reduced_motion: false,
52            accent: None,
53            custom: None,
54        }
55    }
56
57    /// Like [`Self::new`], with reduced motion.
58    pub fn with_reduced_motion(requested: ThemeId, follow_system: bool, reduced_motion: bool) -> Self {
59        Self {
60            reduced_motion,
61            ..Self::new(requested, follow_system)
62        }
63    }
64
65    /// Restore from stored settings; unknown identifiers fall back to GitHub Light.
66    pub fn from_settings(requested: &str, follow_system: bool, reduced_motion: bool) -> Self {
67        Self::with_reduced_motion(ThemeId::from_setting(requested), follow_system, reduced_motion)
68    }
69
70    /// The stored theme preference.
71    pub fn requested(&self) -> ThemeId {
72        self.requested
73    }
74
75    /// The resolved theme.
76    pub fn effective(&self) -> ThemeId {
77        self.effective
78    }
79
80    /// Whether the light/dark base follows the desktop preference.
81    pub fn follow_system(&self) -> bool {
82        self.follow_system
83    }
84
85    /// Whether animations are disabled.
86    pub fn reduced_motion(&self) -> bool {
87        self.reduced_motion
88    }
89
90    /// The brand accent, if one is set.
91    pub fn accent(&self) -> Option<Rgba> {
92        self.accent
93    }
94
95    /// The custom token set, if one replaces the built-ins.
96    pub fn custom(&self) -> Option<Theme> {
97        self.custom
98    }
99
100    /// The tokens for the current state.
101    pub fn tokens(&self) -> Theme {
102        self.custom.unwrap_or_else(|| {
103            let base = Theme::for_id(self.effective);
104            self.accent.map_or(base, |accent| base.with_accent(accent))
105        })
106    }
107
108    /// Whether the effective base is light.
109    pub fn is_light(&self) -> bool {
110        match self.custom {
111            Some(custom) => !custom.is_dark(),
112            None => self.effective.mode() == ThemeMode::Light,
113        }
114    }
115
116    /// Whether the effective base is dark.
117    pub fn is_dark(&self) -> bool {
118        !self.is_light()
119    }
120
121    /// Replace the brand accent.
122    pub fn set_accent(&mut self, accent: Option<Rgba>) -> bool {
123        if accent == self.accent {
124            return false;
125        }
126        self.accent = accent;
127        true
128    }
129
130    /// Install or remove a custom token set.
131    pub fn set_custom(&mut self, custom: Option<Theme>) -> bool {
132        if custom == self.custom {
133            return false;
134        }
135        self.custom = custom;
136        true
137    }
138
139    /// Change the requested theme.
140    pub fn set_requested(&mut self, requested: ThemeId) -> bool {
141        if requested == self.requested {
142            return false;
143        }
144        self.requested = requested;
145        true
146    }
147
148    /// Turn follow-system on or off.
149    pub fn set_follow_system(&mut self, follow_system: bool) -> bool {
150        if follow_system == self.follow_system {
151            return false;
152        }
153        self.follow_system = follow_system;
154        true
155    }
156
157    /// Turn reduced motion on or off.
158    pub fn set_reduced_motion(&mut self, reduced_motion: bool) -> bool {
159        if reduced_motion == self.reduced_motion {
160            return false;
161        }
162        self.reduced_motion = reduced_motion;
163        true
164    }
165
166    /// Resolve the effective theme for the current desktop preference.
167    ///
168    /// Returns the effective theme and whether it changed.
169    pub fn resolve(&mut self, system_dark: bool) -> (ThemeId, bool) {
170        let previous = self.effective;
171        if self.custom.is_none() {
172            self.effective = effective_id(self.requested, self.follow_system, system_dark);
173        }
174        (self.effective, self.effective != previous)
175    }
176
177    /// Re-resolve after the desktop preference changed.
178    ///
179    /// Returns `true` when the effective theme changed.
180    pub fn sync_system(&mut self, system_dark: bool) -> bool {
181        if !self.follow_system || self.custom.is_some() {
182            return false;
183        }
184        let (_, changed) = self.resolve(system_dark);
185        changed
186    }
187
188    /// The stored theme identifier.
189    pub fn theme_setting(&self) -> &'static str {
190        self.requested.as_setting()
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn defaults_and_settings_round_trip() {
200        let state = ThemeState::default();
201        assert_eq!(state.requested(), ThemeId::GithubLight);
202        assert!(state.is_light());
203        let state = ThemeState::from_settings("dracula-soft", false, true);
204        assert_eq!(state.requested(), ThemeId::DraculaSoft);
205        assert!(state.is_dark());
206        assert!(state.reduced_motion());
207        assert_eq!(state.theme_setting(), "dracula-soft");
208    }
209
210    #[test]
211    fn follow_system_resolves_and_only_reports_changes() {
212        let mut state = ThemeState::new(ThemeId::GithubDark, true);
213        assert!(state.sync_system(false));
214        assert_eq!(state.effective(), ThemeId::GithubLight);
215        assert!(!state.sync_system(false));
216        state.set_custom(Some(Theme::dark()));
217        assert!(!state.sync_system(true));
218        assert!(state.is_dark());
219    }
220
221    #[test]
222    fn accent_and_custom_tokens_are_pure() {
223        let mut state = ThemeState::new(ThemeId::GithubLight, false);
224        assert!(state.set_accent(Some(Rgba::from_rgb(0xe0, 0x6c, 0x2b))));
225        assert!(!state.set_accent(Some(Rgba::from_rgb(0xe0, 0x6c, 0x2b))));
226        assert!(state.tokens().accessibility_issues().is_empty());
227        assert!(state.set_custom(Some(Theme::dark())));
228        assert!(state.is_dark());
229        assert_eq!(state.custom(), Some(Theme::dark()));
230        assert!(state.set_custom(None));
231        assert!(!state.set_custom(None));
232    }
233}