use crate::palette::Palette;
use crate::schema::{ColorScheme, DesignSystem, Theme};
use std::cell::{Cell, RefCell};
thread_local! {
static CURRENT: Cell<Theme> = const { Cell::new(Theme::unified(DesignSystem::Material3)) };
static PENDING: Cell<Option<Theme>> = const { Cell::new(None) };
static OWNED: RefCell<Vec<&'static Palette>> = const { RefCell::new(Vec::new()) };
}
pub fn current_theme() -> Theme {
PENDING
.with(Cell::get)
.unwrap_or_else(|| CURRENT.with(Cell::get))
}
pub fn set_theme(theme: Theme) {
#[cfg(debug_assertions)]
if theme.palette != current_theme().palette {
for line in crate::boundary::palette_report(&theme) {
eprintln!("{line}");
}
}
PENDING.with(|pending| pending.set(Some(theme)));
}
pub fn own_palette(palette: Palette) -> &'static Palette {
OWNED.with_borrow_mut(|owned| {
if let Some(existing) = owned.iter().find(|existing| ***existing == palette) {
return *existing;
}
let home: &'static Palette = Box::leak(Box::new(palette));
owned.push(home);
home
})
}
#[doc(hidden)]
pub fn owned_palette_count() -> usize {
OWNED.with_borrow(Vec::len)
}
pub(crate) fn install(theme: Theme) {
CURRENT.with(|current| current.set(theme));
PENDING.with(|pending| pending.set(None));
}
pub(crate) fn take_pending() -> Option<Theme> {
let theme = PENDING.with(Cell::take)?;
CURRENT.with(|current| current.set(theme));
Some(theme)
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ThemeHandle {
_private: (),
}
impl ThemeHandle {
pub fn get(&self) -> Theme {
current_theme()
}
pub fn set(&self, theme: Theme) {
set_theme(theme);
}
pub fn set_palette(&self, palette: Palette) {
let theme = current_theme().with_palette(own_palette(palette));
set_theme(theme);
}
pub fn clear_palette(&self) {
let mut theme = current_theme();
theme.palette = None;
set_theme(theme);
}
pub fn set_color_scheme(&self, scheme: ColorScheme) {
set_theme(current_theme().with_color_scheme(scheme));
}
}