|
| 1 | +import { |
| 2 | + createContext, |
| 3 | + type ReactNode, |
| 4 | + useCallback, |
| 5 | + useEffect, |
| 6 | + useState, |
| 7 | +} from "react"; |
| 8 | + |
| 9 | +export type Theme = "light" | "dark"; |
| 10 | + |
| 11 | +export interface ThemeContextValue { |
| 12 | + theme: Theme; |
| 13 | + setTheme: (theme: Theme) => void; |
| 14 | + toggleTheme: () => void; |
| 15 | +} |
| 16 | + |
| 17 | +export const ThemeContext = createContext<ThemeContextValue | null>(null); |
| 18 | + |
| 19 | +const STORAGE_KEY = "keywrit-hub-theme"; |
| 20 | + |
| 21 | +function getInitialTheme(): Theme { |
| 22 | + if (typeof window === "undefined") return "light"; |
| 23 | + const stored = localStorage.getItem(STORAGE_KEY); |
| 24 | + if (stored === "light" || stored === "dark") { |
| 25 | + return stored; |
| 26 | + } |
| 27 | + // Auto-detect from system preference on first load |
| 28 | + return window.matchMedia("(prefers-color-scheme: dark)").matches |
| 29 | + ? "dark" |
| 30 | + : "light"; |
| 31 | +} |
| 32 | + |
| 33 | +export function ThemeProvider({ children }: { children: ReactNode }) { |
| 34 | + const [theme, setThemeState] = useState<Theme>(getInitialTheme); |
| 35 | + |
| 36 | + // Apply theme class to document |
| 37 | + useEffect(() => { |
| 38 | + const root = document.documentElement; |
| 39 | + if (theme === "dark") { |
| 40 | + root.classList.add("dark"); |
| 41 | + } else { |
| 42 | + root.classList.remove("dark"); |
| 43 | + } |
| 44 | + }, [theme]); |
| 45 | + |
| 46 | + const setTheme = useCallback((newTheme: Theme) => { |
| 47 | + setThemeState(newTheme); |
| 48 | + localStorage.setItem(STORAGE_KEY, newTheme); |
| 49 | + }, []); |
| 50 | + |
| 51 | + const toggleTheme = useCallback(() => { |
| 52 | + setThemeState((current) => { |
| 53 | + const next = current === "light" ? "dark" : "light"; |
| 54 | + localStorage.setItem(STORAGE_KEY, next); |
| 55 | + return next; |
| 56 | + }); |
| 57 | + }, []); |
| 58 | + |
| 59 | + const value: ThemeContextValue = { |
| 60 | + theme, |
| 61 | + setTheme, |
| 62 | + toggleTheme, |
| 63 | + }; |
| 64 | + |
| 65 | + return ( |
| 66 | + <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider> |
| 67 | + ); |
| 68 | +} |
0 commit comments