forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiB0d793e7Tahinli2 hours ago359 commits

theme.rs82 lines, 2.0 KiBHistoryRawDownload
1use forge_core::User;
2use topcoat::context::Cx;
3use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
4
5const THEME_COOKIE: &str = "forge_theme";
6
7#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8pub enum Theme {
9 Light,
10 Dark,
11 Auto,
12}
13
14impl Theme {
15 pub fn from_stored(stored: &str) -> Self {
16 match stored {
17 "auto" => Self::Auto,
18 "dark" => Self::Dark,
19 _ => Self::Light,
20 }
21 }
22
23 pub fn as_str(self) -> &'static str {
24 match self {
25 Self::Light => "light",
26 Self::Dark => "dark",
27 Self::Auto => "auto",
28 }
29 }
30
31 pub fn next(self) -> Self {
32 match self {
33 Self::Light => Self::Dark,
34 Self::Dark => Self::Auto,
35 Self::Auto => Self::Light,
36 }
37 }
38}
39
40pub fn preference(cx: &Cx, viewer: Option<&User>) -> Theme {
41 let stored = match viewer {
42 Some(user) => user.theme.clone(),
43 None => cookies(cx)
44 .get(THEME_COOKIE)
45 .map(|cookie| cookie.value().to_owned())
46 .unwrap_or_default(),
47 };
48 Theme::from_stored(&stored)
49}
50
51pub fn data_theme(cx: &Cx, viewer: Option<&User>) -> Option<&'static str> {
52 match preference(cx, viewer) {
53 Theme::Auto => None,
54 theme => Some(theme.as_str()),
55 }
56}
57
58pub fn set_theme_cookie(cx: &Cx, theme: &str) {
59 cookies(cx).add(
60 Cookie::build((THEME_COOKIE, theme.to_owned()))
61 .path("/")
62 .secure(true)
63 .http_only(true)
64 .same_site(SameSite::Lax)
65 .max_age(time::Duration::days(365))
66 .build(),
67 );
68}
69
70#[cfg(test)]
71mod tests {
72 use super::Theme;
73
74 #[test]
75 fn unknown_or_missing_preferences_fall_back_to_light() {
76 for stored in ["", "neon", "light"] {
77 assert_eq!(Theme::from_stored(stored), Theme::Light, "{stored:?}");
78 }
79 assert_eq!(Theme::from_stored("dark"), Theme::Dark);
80 assert_eq!(Theme::from_stored("auto"), Theme::Auto);
81 }
82}