BillTracker/client/contexts/ThemeContext.tsx

111 lines
3.5 KiB
TypeScript
Raw Normal View History

import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
2026-05-03 19:51:57 -05:00
/**
* Themes: 'light' | 'dark' | 'system'
2026-05-03 19:51:57 -05:00
* Persisted to localStorage under key 'bt-theme'.
*
* 'system' follows the device's `prefers-color-scheme` and updates live when the
* OS flips. `resolvedTheme` is always the concrete 'light' | 'dark' actually
* applied consume it for anything that needs a real value (e.g. Sonner).
*
2026-05-03 19:51:57 -05:00
* Class mapping on document.documentElement:
* light (no classes) dark 'dark'
2026-05-03 19:51:57 -05:00
*/
type Theme = 'light' | 'dark' | 'system';
type ResolvedTheme = 'light' | 'dark';
2026-05-03 19:51:57 -05:00
const STORAGE_KEY = 'bt-theme';
const VALID_THEMES: Theme[] = ['light', 'dark', 'system'];
const DEFAULT_THEME: Theme = 'dark';
2026-05-03 19:51:57 -05:00
// Keep in sync with the inline pre-bundle script in index.html.
const THEME_COLORS: Record<ResolvedTheme, string> = { light: '#ffffff', dark: '#18181b' };
function systemPrefersDark(): boolean {
return typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches;
}
function resolveTheme(theme: Theme): ResolvedTheme {
if (theme === 'system') return systemPrefersDark() ? 'dark' : 'light';
return theme;
}
function applyTheme(theme: Theme): ResolvedTheme {
const resolved = resolveTheme(theme);
2026-05-03 19:51:57 -05:00
const root = document.documentElement;
root.classList.toggle('dark', resolved === 'dark');
const meta = document.querySelector('meta[name="theme-color"]');
if (meta) meta.setAttribute('content', THEME_COLORS[resolved]);
return resolved;
2026-05-03 19:51:57 -05:00
}
function loadStoredTheme(): Theme {
2026-05-03 19:51:57 -05:00
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === 'dark-purple') return 'dark';
if (stored && (VALID_THEMES as string[]).includes(stored)) return stored as Theme;
2026-05-03 19:51:57 -05:00
} catch {
// localStorage unavailable
}
return DEFAULT_THEME;
}
interface ThemeContextValue {
theme: Theme;
resolvedTheme: ResolvedTheme;
setTheme: (theme: string) => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
2026-05-03 19:51:57 -05:00
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(() => {
2026-05-03 19:51:57 -05:00
const stored = loadStoredTheme();
// Apply immediately (before first paint) to avoid flash.
2026-05-03 19:51:57 -05:00
applyTheme(stored);
return stored;
});
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>(() => resolveTheme(loadStoredTheme()));
2026-05-03 19:51:57 -05:00
const setTheme = (newTheme: string) => {
if (!(VALID_THEMES as string[]).includes(newTheme)) return;
const next = newTheme as Theme;
setResolvedTheme(applyTheme(next));
setThemeState(next);
2026-05-03 19:51:57 -05:00
try {
localStorage.setItem(STORAGE_KEY, next);
2026-05-03 19:51:57 -05:00
} catch {
// localStorage unavailable
}
};
// Keep DOM in sync if theme state ever changes externally.
useEffect(() => {
setResolvedTheme(applyTheme(theme));
}, [theme]);
// While on 'system', re-apply live when the OS light/dark preference flips.
2026-05-03 19:51:57 -05:00
useEffect(() => {
if (theme !== 'system' || typeof window === 'undefined' || !window.matchMedia) return;
const mq = window.matchMedia('(prefers-color-scheme: dark)');
const onChange = () => setResolvedTheme(applyTheme('system'));
mq.addEventListener('change', onChange);
return () => mq.removeEventListener('change', onChange);
2026-05-03 19:51:57 -05:00
}, [theme]);
return (
<ThemeContext.Provider value={{ theme, resolvedTheme, setTheme }}>
2026-05-03 19:51:57 -05:00
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return ctx;
}