| 10 | }); |
| 11 | |
| 12 | export function ThemeProvider({ children }: { children: React.ReactNode }) { |
| 13 | const [theme, setTheme] = useState<Theme>("system"); |
| 14 | |
| 15 | useEffect(() => { |
| 16 | const root = document.documentElement; |
| 17 | root.classList.remove("light", "dark"); |
| 18 | |
| 19 | if (theme === "system") { |
| 20 | const mq = window.matchMedia("(prefers-color-scheme: dark)"); |
| 21 | const apply = () => { |
| 22 | root.classList.remove("light", "dark"); |
| 23 | root.classList.add(mq.matches ? "dark" : "light"); |
| 24 | }; |
| 25 | apply(); |
| 26 | mq.addEventListener("change", apply); |
| 27 | return () => mq.removeEventListener("change", apply); |
| 28 | } |
| 29 | |
| 30 | root.classList.add(theme); |
| 31 | }, [theme]); |
| 32 | |
| 33 | return ( |
| 34 | <ThemeContext.Provider value={{ theme, setTheme }}> |
| 35 | {children} |
| 36 | </ThemeContext.Provider> |
| 37 | ); |
| 38 | } |
| 39 | |
| 40 | export const useTheme = () => useContext(ThemeContext); |