35 lines
1.1 KiB
TypeScript
35 lines
1.1 KiB
TypeScript
const applyThemeToDocument = (isDark: boolean) => {
|
|
if (typeof document === "undefined") {
|
|
return;
|
|
}
|
|
const theme = isDark ? "dark" : "light";
|
|
const root = document.documentElement;
|
|
const body = document.body;
|
|
|
|
root.classList.toggle("dark", isDark);
|
|
root.setAttribute("data-theme", theme);
|
|
|
|
if (body) {
|
|
body.classList.toggle("dark", isDark);
|
|
body.setAttribute("data-theme", theme);
|
|
body.style.colorScheme = isDark ? "dark" : "light";
|
|
}
|
|
};
|
|
|
|
export const initSystemThemeWatcher = () => {
|
|
if (typeof window === "undefined" || typeof window.matchMedia === "undefined") {
|
|
return;
|
|
}
|
|
|
|
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
|
const applyMatch = (matches: boolean) => applyThemeToDocument(matches);
|
|
const handleChange = (event: MediaQueryListEvent) => applyMatch(event.matches);
|
|
|
|
applyMatch(mediaQuery.matches);
|
|
if (typeof mediaQuery.addEventListener === "function") {
|
|
mediaQuery.addEventListener("change", handleChange);
|
|
} else if (typeof mediaQuery.addListener === "function") {
|
|
mediaQuery.addListener(handleChange);
|
|
}
|
|
};
|