use http::header::COOKIE;
use topcoat::context::{Cx, try_request_context};
use super::current;
const THEME_COOKIE: &str = "tablo_theme";
const SCHEME_COOKIE: &str = "tablo_scheme";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Theme {
Light,
Dark,
System,
}
impl Theme {
fn stored(cx: &Cx) -> Option<Self> {
match request_cookie(cx, THEME_COOKIE).as_deref() {
Some("light") => Some(Self::Light),
Some("dark") => Some(Self::Dark),
Some("system") => Some(Self::System),
_ => None,
}
}
pub(super) fn current(cx: &Cx) -> Self {
Self::stored(cx).unwrap_or(if Self::panel_default_dark(cx) {
Self::Dark
} else {
Self::Light
})
}
fn panel_default_dark(cx: &Cx) -> bool {
current(cx).is_some_and(|panel| panel.dark_mode)
}
pub(super) fn renders_dark(cx: &Cx, default_dark: bool) -> bool {
match Self::stored(cx) {
Some(Self::Dark) => true,
Some(Self::Light) => false,
Some(Self::System) => match request_cookie(cx, SCHEME_COOKIE).as_deref() {
Some("dark") => true,
Some("light") => false,
_ => default_dark,
},
None => default_dark,
}
}
pub(super) fn name(self) -> &'static str {
match self {
Self::Light => "light",
Self::Dark => "dark",
Self::System => "system",
}
}
}
pub(super) const SIDEBAR_COOKIE: &str = "tablo_sidebar";
pub(super) fn request_cookie(cx: &Cx, name: &str) -> Option<String> {
let header = try_request_context::<http::request::Parts>(cx)?
.headers
.get(COOKIE)?
.to_str()
.ok()?;
header.split(';').find_map(|part| {
let (key, value) = part.trim().split_once('=')?;
(key == name).then(|| value.to_string())
})
}