|
| 1 | +import React, {createContext, useContext, useEffect, useState} from "react"; |
| 2 | + |
| 3 | +type Theme = "corporate" | "business" |
| 4 | + |
| 5 | +interface ThemeContextType { |
| 6 | + theme: Theme; |
| 7 | + switchTheme: () => void; |
| 8 | +} |
| 9 | + |
| 10 | +const ThemeContext = createContext<ThemeContextType | undefined>(undefined); |
| 11 | + |
| 12 | +export const ThemeProvider = ({children}: { children: React.ReactNode }) => { |
| 13 | + const getPreferredTheme = (): Theme => { |
| 14 | + const stored = localStorage.getItem("theme") as Theme | null; |
| 15 | + if (stored) return stored; |
| 16 | + |
| 17 | + if (window.matchMedia("(prefers-color-scheme: dark)").matches) { |
| 18 | + return "business"; |
| 19 | + } |
| 20 | + |
| 21 | + return "corporate"; |
| 22 | + }; |
| 23 | + |
| 24 | + const [theme, setTheme] = useState<Theme>(getPreferredTheme); |
| 25 | + |
| 26 | + useEffect(() => { |
| 27 | + document.documentElement.setAttribute("data-theme", theme); |
| 28 | + localStorage.setItem("theme", theme); |
| 29 | + }, [theme]); |
| 30 | + |
| 31 | + useEffect(() => { |
| 32 | + const media = window.matchMedia("(prefers-color-scheme: dark)"); |
| 33 | + const handler = (e: MediaQueryListEvent) => { |
| 34 | + if (!localStorage.getItem("theme")) { |
| 35 | + setTheme(e.matches ? "business" : "corporate"); |
| 36 | + } |
| 37 | + }; |
| 38 | + media.addEventListener("change", handler); |
| 39 | + return () => media.removeEventListener("change", handler); |
| 40 | + }, []); |
| 41 | + |
| 42 | + const switchTheme = () => { |
| 43 | + setTheme(currentTheme => { |
| 44 | + switch (currentTheme) { |
| 45 | + case "corporate": |
| 46 | + return "business" |
| 47 | + case "business": |
| 48 | + return "corporate" |
| 49 | + } |
| 50 | + }) |
| 51 | + } |
| 52 | + |
| 53 | + return ( |
| 54 | + <ThemeContext.Provider value={{theme, switchTheme}}> |
| 55 | + {children} |
| 56 | + </ThemeContext.Provider> |
| 57 | + ); |
| 58 | +}; |
| 59 | + |
| 60 | +export const useTheme = () => { |
| 61 | + const ctx = useContext(ThemeContext); |
| 62 | + if (!ctx) throw new Error("useTheme must be used within ThemeProvider"); |
| 63 | + return ctx; |
| 64 | +}; |
0 commit comments