Spaces:
Paused
Paused
File size: 1,242 Bytes
b7d4394 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import { createContext } from "preact";
import { useContext, useState, useCallback } from "preact/hooks";
import type { ComponentChildren } from "preact";
interface ThemeContextValue {
isDark: boolean;
toggle: () => void;
}
const ThemeContext = createContext<ThemeContextValue>(null!);
function getInitialDark(): boolean {
try {
const saved = localStorage.getItem("codex-proxy-theme");
if (saved === "dark") return true;
if (saved === "light") return false;
} catch {}
return window.matchMedia("(prefers-color-scheme: dark)").matches;
}
export function ThemeProvider({ children }: { children: ComponentChildren }) {
const [isDark, setIsDark] = useState(getInitialDark);
const toggle = useCallback(() => {
setIsDark((prev) => {
const next = !prev;
localStorage.setItem("codex-proxy-theme", next ? "dark" : "light");
if (next) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
return next;
});
}, []);
return (
<ThemeContext.Provider value={{ isDark, toggle }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
return useContext(ThemeContext);
}
|