mirror of
https://github.com/WSA-Installer/wsa-website.git
synced 2026-07-29 11:24:39 -07:00
41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
"use client";
|
|
|
|
import { createContext, useContext, useState, useEffect, type ReactNode } from "react";
|
|
|
|
type Theme = "dark" | "light";
|
|
|
|
const ThemeContext = createContext<{ theme: Theme; toggle: () => void }>({
|
|
theme: "dark",
|
|
toggle: () => {},
|
|
});
|
|
|
|
function getInitialTheme(): Theme {
|
|
if (typeof window === "undefined") return "dark";
|
|
const saved = localStorage.getItem("theme") as Theme | null;
|
|
if (saved) return saved;
|
|
return window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
|
|
}
|
|
|
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
|
const [theme, setTheme] = useState<Theme>(getInitialTheme);
|
|
|
|
useEffect(() => {
|
|
document.documentElement.setAttribute("data-theme", theme);
|
|
localStorage.setItem("theme", theme);
|
|
}, [theme]);
|
|
|
|
const toggle = () => {
|
|
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
|
|
};
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, toggle }}>
|
|
{children}
|
|
</ThemeContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useTheme() {
|
|
return useContext(ThemeContext);
|
|
}
|