diff --git a/src/lib/theme.ts b/src/lib/theme.ts index dfddbd9..d0723a9 100644 --- a/src/lib/theme.ts +++ b/src/lib/theme.ts @@ -1,13 +1,18 @@ export type Theme = "light" | "dark" | "system"; const STORAGE_KEY = "nowhatever-theme"; +const VALID_THEMES: Theme[] = ["light", "dark", "system"]; export function getStoredTheme(): Theme { if (typeof window === "undefined") return "system"; - return (localStorage.getItem(STORAGE_KEY) as Theme) || "system"; + const stored = localStorage.getItem(STORAGE_KEY); + return stored && VALID_THEMES.includes(stored as Theme) + ? (stored as Theme) + : "system"; } export function setStoredTheme(theme: Theme): void { + if (typeof window === "undefined") return; localStorage.setItem(STORAGE_KEY, theme); applyTheme(theme); } @@ -21,11 +26,13 @@ function resolveTheme(theme: Theme): "light" | "dark" { } export function applyTheme(theme: Theme): void { + if (typeof window === "undefined") return; const resolved = resolveTheme(theme); document.documentElement.setAttribute("data-theme", resolved); } export function initTheme(): void { + if (typeof window === "undefined") return; const theme = getStoredTheme(); applyTheme(theme);