theme.ts

 1export type ThemeMode = "system" | "light" | "dark";
 2
 3const STORAGE_KEY = "shelley-theme";
 4
 5export function getStoredTheme(): ThemeMode {
 6  const stored = localStorage.getItem(STORAGE_KEY);
 7  if (stored === "light" || stored === "dark" || stored === "system") {
 8    return stored;
 9  }
10  return "system";
11}
12
13export function setStoredTheme(theme: ThemeMode): void {
14  localStorage.setItem(STORAGE_KEY, theme);
15}
16
17export function getSystemPrefersDark(): boolean {
18  return window.matchMedia("(prefers-color-scheme: dark)").matches;
19}
20
21export function isDarkModeActive(): boolean {
22  const theme = getStoredTheme();
23  return theme === "dark" || (theme === "system" && getSystemPrefersDark());
24}
25
26export function applyTheme(theme: ThemeMode): void {
27  const isDark = theme === "dark" || (theme === "system" && getSystemPrefersDark());
28  document.documentElement.classList.toggle("dark", isDark);
29}
30
31// Initialize theme on load
32export function initializeTheme(): void {
33  const theme = getStoredTheme();
34  applyTheme(theme);
35
36  // Listen for system preference changes
37  window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
38    const currentTheme = getStoredTheme();
39    if (currentTheme === "system") {
40      applyTheme("system");
41    }
42  });
43}