Spaces:
Running
Running
| "use client"; | |
| import { createContext, useContext, useEffect, useState } from "react"; | |
| type Theme = "light" | "dark"; | |
| type ThemeContextType = { | |
| theme: Theme; | |
| toggleTheme: () => void; | |
| }; | |
| const ThemeContext = createContext<ThemeContextType | undefined>(undefined); | |
| export function ThemeProvider({ children }: { children: React.ReactNode }) { | |
| const [theme, setTheme] = useState<Theme>("light"); | |
| useEffect(() => { | |
| const savedTheme = localStorage.getItem("theme") as Theme; | |
| if (savedTheme) { | |
| setTheme(savedTheme); | |
| document.documentElement.classList.toggle("dark", savedTheme === "dark"); | |
| } else if (window.matchMedia("(prefers-color-scheme: dark)").matches) { | |
| setTheme("dark"); | |
| document.documentElement.classList.add("dark"); | |
| } | |
| }, []); | |
| const toggleTheme = () => { | |
| const newTheme = theme === "light" ? "dark" : "light"; | |
| setTheme(newTheme); | |
| localStorage.setItem("theme", newTheme); | |
| document.documentElement.classList.toggle("dark", newTheme === "dark"); | |
| }; | |
| return ( | |
| <ThemeContext.Provider value={{ theme, toggleTheme }}> | |
| {children} | |
| </ThemeContext.Provider> | |
| ); | |
| } | |
| export function useTheme() { | |
| const context = useContext(ThemeContext); | |
| if (context === undefined) { | |
| throw new Error("useTheme must be used within a ThemeProvider"); | |
| } | |
| return context; | |
| } |