's'
This commit is contained in:
@@ -21,14 +21,25 @@ type ThemeContextValue = {
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
function getInitialTheme(): Theme {
|
||||
if (typeof window === "undefined") return "light";
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY) as Theme | null;
|
||||
if (stored === "dark" || stored === "light") return stored;
|
||||
if (window.matchMedia("(prefers-color-scheme: dark)").matches) return "dark";
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return "light";
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>("light");
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setThemeState(getInitialTheme());
|
||||
setMounted(true);
|
||||
const hasDark = document.documentElement.classList.contains("dark");
|
||||
setThemeState(hasDark ? "dark" : "light");
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -39,7 +50,11 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
} else {
|
||||
root.classList.remove("dark");
|
||||
}
|
||||
localStorage.setItem(STORAGE_KEY, theme);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, theme);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, [theme, mounted]);
|
||||
|
||||
const setTheme = useCallback((newTheme: Theme) => {
|
||||
|
||||
Reference in New Issue
Block a user