You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.8 KiB
67 lines
1.8 KiB
import type React from "react";
|
|
import { createContext, useContext, useEffect, useState } from "react";
|
|
|
|
type Theme = "light" | "dark" | "system";
|
|
|
|
interface ThemeContextType {
|
|
theme: Theme;
|
|
setTheme: (theme: Theme) => void;
|
|
}
|
|
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
|
|
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
|
const [theme, setTheme] = useState<Theme>(() => {
|
|
if (typeof window !== "undefined") {
|
|
const savedTheme = localStorage.getItem("theme") as Theme;
|
|
return savedTheme || "system";
|
|
}
|
|
return "system";
|
|
});
|
|
|
|
useEffect(() => {
|
|
const root = window.document.documentElement;
|
|
root.classList.remove("light", "dark");
|
|
|
|
if (theme === "system") {
|
|
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
|
|
.matches
|
|
? "dark"
|
|
: "light";
|
|
root.classList.add(systemTheme);
|
|
} else {
|
|
root.classList.add(theme);
|
|
}
|
|
|
|
localStorage.setItem("theme", theme);
|
|
}, [theme]);
|
|
|
|
useEffect(() => {
|
|
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
|
|
|
const handleChange = () => {
|
|
if (theme === "system") {
|
|
const root = window.document.documentElement;
|
|
root.classList.remove("light", "dark");
|
|
root.classList.add(mediaQuery.matches ? "dark" : "light");
|
|
}
|
|
};
|
|
|
|
mediaQuery.addEventListener("change", handleChange);
|
|
return () => mediaQuery.removeEventListener("change", handleChange);
|
|
}, [theme]);
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, setTheme }}>
|
|
{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;
|
|
}
|
|
|