use forge_core::User; use topcoat::context::Cx; use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; const THEME_COOKIE: &str = "forge_theme"; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Theme { Light, Dark, Auto, } impl Theme { pub fn from_stored(stored: &str) -> Self { match stored { "auto" => Self::Auto, "dark" => Self::Dark, _ => Self::Light, } } pub fn as_str(self) -> &'static str { match self { Self::Light => "light", Self::Dark => "dark", Self::Auto => "auto", } } pub fn next(self) -> Self { match self { Self::Light => Self::Dark, Self::Dark => Self::Auto, Self::Auto => Self::Light, } } } pub fn preference(cx: &Cx, viewer: Option<&User>) -> Theme { let stored = match viewer { Some(user) => user.theme.clone(), None => cookies(cx) .get(THEME_COOKIE) .map(|cookie| cookie.value().to_owned()) .unwrap_or_default(), }; Theme::from_stored(&stored) } pub fn data_theme(cx: &Cx, viewer: Option<&User>) -> Option<&'static str> { match preference(cx, viewer) { Theme::Auto => None, theme => Some(theme.as_str()), } } pub fn set_theme_cookie(cx: &Cx, theme: &str) { cookies(cx).add( Cookie::build((THEME_COOKIE, theme.to_owned())) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Lax) .max_age(time::Duration::days(365)) .build(), ); } #[cfg(test)] mod tests { use super::Theme; #[test] fn the_toggle_cycles_light_dark_auto_light() { assert_eq!(Theme::Light.next(), Theme::Dark); assert_eq!(Theme::Dark.next(), Theme::Auto); assert_eq!(Theme::Auto.next(), Theme::Light); } #[test] fn unknown_or_missing_preferences_fall_back_to_light() { for stored in ["", "neon", "light"] { assert_eq!(Theme::from_stored(stored), Theme::Light, "{stored:?}"); } assert_eq!(Theme::from_stored("dark"), Theme::Dark); assert_eq!(Theme::from_stored("auto"), Theme::Auto); } }