Initial open-source release
This commit is contained in:
57
src/contexts/ThemeContext.tsx
Normal file
57
src/contexts/ThemeContext.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
|
||||
type Theme = "system" | "light" | "dark";
|
||||
|
||||
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>(() => {
|
||||
// Try to get the saved theme from localStorage
|
||||
const savedTheme = localStorage.getItem("theme") as Theme;
|
||||
return savedTheme || "system";
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Save theme preference to localStorage
|
||||
localStorage.setItem("theme", theme);
|
||||
|
||||
// Handle system theme changes
|
||||
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
|
||||
const applyTheme = () => {
|
||||
const root = window.document.documentElement;
|
||||
const isDark =
|
||||
theme === "dark" || (theme === "system" && mediaQuery.matches);
|
||||
|
||||
root.classList.remove("light", "dark");
|
||||
root.classList.add(isDark ? "dark" : "light");
|
||||
};
|
||||
|
||||
applyTheme();
|
||||
|
||||
// Listen for system theme changes
|
||||
const listener = () => applyTheme();
|
||||
mediaQuery.addEventListener("change", listener);
|
||||
|
||||
return () => mediaQuery.removeEventListener("change", listener);
|
||||
}, [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;
|
||||
}
|
||||
Reference in New Issue
Block a user