crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Theme selection and preferences without a window.
//!
//! [`ThemeState`] is the pure state half: requested and effective theme, follow-system,
//! reduced motion, brand accent, and a custom token set. The UI adapter applies the
//! resulting [`Theme`] to egui and translates `Color32` at the boundary.
//!
//! ```
//! use crisol_core::state::ThemeState;
//! use crisol_core::theme::ThemeId;
//!
//! let mut state = ThemeState::new(ThemeId::GithubDark, false);
//! state.set_requested(ThemeId::Dracula);
//! state.resolve(false);
//! assert_eq!(state.effective(), ThemeId::Dracula);
//! ```

use crate::color::Rgba;
use crate::theme::{Theme, ThemeId, ThemeMode, effective_id};

/// Requested and effective theme, follow-system, and reduced-motion preferences.
///
/// # Example
///
/// ```
/// use crisol_core::state::ThemeState;
/// use crisol_core::theme::ThemeId;
///
/// let state = ThemeState::new(ThemeId::GithubDark, false);
/// assert_eq!(state.effective(), ThemeId::GithubDark);
/// assert!(state.is_dark());
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ThemeState {
    requested: ThemeId,
    follow_system: bool,
    effective: ThemeId,
    reduced_motion: bool,
    accent: Option<Rgba>,
    custom: Option<Theme>,
}

impl ThemeState {
    /// State for `requested`, optionally following the desktop preference.
    pub fn new(requested: ThemeId, follow_system: bool) -> Self {
        Self {
            requested,
            follow_system,
            effective: requested,
            reduced_motion: false,
            accent: None,
            custom: None,
        }
    }

    /// Like [`Self::new`], with reduced motion.
    pub fn with_reduced_motion(requested: ThemeId, follow_system: bool, reduced_motion: bool) -> Self {
        Self {
            reduced_motion,
            ..Self::new(requested, follow_system)
        }
    }

    /// Restore from stored settings; unknown identifiers fall back to GitHub Light.
    pub fn from_settings(requested: &str, follow_system: bool, reduced_motion: bool) -> Self {
        Self::with_reduced_motion(ThemeId::from_setting(requested), follow_system, reduced_motion)
    }

    /// The stored theme preference.
    pub fn requested(&self) -> ThemeId {
        self.requested
    }

    /// The resolved theme.
    pub fn effective(&self) -> ThemeId {
        self.effective
    }

    /// Whether the light/dark base follows the desktop preference.
    pub fn follow_system(&self) -> bool {
        self.follow_system
    }

    /// Whether animations are disabled.
    pub fn reduced_motion(&self) -> bool {
        self.reduced_motion
    }

    /// The brand accent, if one is set.
    pub fn accent(&self) -> Option<Rgba> {
        self.accent
    }

    /// The custom token set, if one replaces the built-ins.
    pub fn custom(&self) -> Option<Theme> {
        self.custom
    }

    /// The tokens for the current state.
    pub fn tokens(&self) -> Theme {
        self.custom.unwrap_or_else(|| {
            let base = Theme::for_id(self.effective);
            self.accent.map_or(base, |accent| base.with_accent(accent))
        })
    }

    /// Whether the effective base is light.
    pub fn is_light(&self) -> bool {
        match self.custom {
            Some(custom) => !custom.is_dark(),
            None => self.effective.mode() == ThemeMode::Light,
        }
    }

    /// Whether the effective base is dark.
    pub fn is_dark(&self) -> bool {
        !self.is_light()
    }

    /// Replace the brand accent.
    pub fn set_accent(&mut self, accent: Option<Rgba>) -> bool {
        if accent == self.accent {
            return false;
        }
        self.accent = accent;
        true
    }

    /// Install or remove a custom token set.
    pub fn set_custom(&mut self, custom: Option<Theme>) -> bool {
        if custom == self.custom {
            return false;
        }
        self.custom = custom;
        true
    }

    /// Change the requested theme.
    pub fn set_requested(&mut self, requested: ThemeId) -> bool {
        if requested == self.requested {
            return false;
        }
        self.requested = requested;
        true
    }

    /// Turn follow-system on or off.
    pub fn set_follow_system(&mut self, follow_system: bool) -> bool {
        if follow_system == self.follow_system {
            return false;
        }
        self.follow_system = follow_system;
        true
    }

    /// Turn reduced motion on or off.
    pub fn set_reduced_motion(&mut self, reduced_motion: bool) -> bool {
        if reduced_motion == self.reduced_motion {
            return false;
        }
        self.reduced_motion = reduced_motion;
        true
    }

    /// Resolve the effective theme for the current desktop preference.
    ///
    /// Returns the effective theme and whether it changed.
    pub fn resolve(&mut self, system_dark: bool) -> (ThemeId, bool) {
        let previous = self.effective;
        if self.custom.is_none() {
            self.effective = effective_id(self.requested, self.follow_system, system_dark);
        }
        (self.effective, self.effective != previous)
    }

    /// Re-resolve after the desktop preference changed.
    ///
    /// Returns `true` when the effective theme changed.
    pub fn sync_system(&mut self, system_dark: bool) -> bool {
        if !self.follow_system || self.custom.is_some() {
            return false;
        }
        let (_, changed) = self.resolve(system_dark);
        changed
    }

    /// The stored theme identifier.
    pub fn theme_setting(&self) -> &'static str {
        self.requested.as_setting()
    }
}

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

    #[test]
    fn defaults_and_settings_round_trip() {
        let state = ThemeState::default();
        assert_eq!(state.requested(), ThemeId::GithubLight);
        assert!(state.is_light());
        let state = ThemeState::from_settings("dracula-soft", false, true);
        assert_eq!(state.requested(), ThemeId::DraculaSoft);
        assert!(state.is_dark());
        assert!(state.reduced_motion());
        assert_eq!(state.theme_setting(), "dracula-soft");
    }

    #[test]
    fn follow_system_resolves_and_only_reports_changes() {
        let mut state = ThemeState::new(ThemeId::GithubDark, true);
        assert!(state.sync_system(false));
        assert_eq!(state.effective(), ThemeId::GithubLight);
        assert!(!state.sync_system(false));
        state.set_custom(Some(Theme::dark()));
        assert!(!state.sync_system(true));
        assert!(state.is_dark());
    }

    #[test]
    fn accent_and_custom_tokens_are_pure() {
        let mut state = ThemeState::new(ThemeId::GithubLight, false);
        assert!(state.set_accent(Some(Rgba::from_rgb(0xe0, 0x6c, 0x2b))));
        assert!(!state.set_accent(Some(Rgba::from_rgb(0xe0, 0x6c, 0x2b))));
        assert!(state.tokens().accessibility_issues().is_empty());
        assert!(state.set_custom(Some(Theme::dark())));
        assert!(state.is_dark());
        assert_eq!(state.custom(), Some(Theme::dark()));
        assert!(state.set_custom(None));
        assert!(!state.set_custom(None));
    }
}