You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
922 B
37 lines
922 B
import { useEffect, useState } from "react";
|
|
|
|
type Theme = "light" | "dark";
|
|
|
|
export function useTheme() {
|
|
const [theme, setTheme] = useState<Theme>(() => {
|
|
if (typeof window === "undefined") return "light";
|
|
return (
|
|
(document.documentElement.getAttribute("data-theme") as Theme) || "light"
|
|
);
|
|
});
|
|
|
|
useEffect(() => {
|
|
const observer = new MutationObserver((mutations) => {
|
|
for (const mutation of mutations) {
|
|
if (
|
|
mutation.type === "attributes" &&
|
|
mutation.attributeName === "data-theme"
|
|
) {
|
|
const newTheme = document.documentElement.getAttribute(
|
|
"data-theme",
|
|
) as Theme;
|
|
setTheme(newTheme);
|
|
}
|
|
}
|
|
});
|
|
|
|
observer.observe(document.documentElement, {
|
|
attributes: true,
|
|
attributeFilter: ["data-theme"],
|
|
});
|
|
|
|
return () => observer.disconnect();
|
|
}, []);
|
|
|
|
return theme;
|
|
}
|
|
|