-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathuseSafeColorMode.ts
More file actions
44 lines (36 loc) · 1.3 KB
/
useSafeColorMode.ts
File metadata and controls
44 lines (36 loc) · 1.3 KB
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
import { useState, useEffect } from "react";
import ExecutionEnvironment from "@docusaurus/ExecutionEnvironment";
/**
* Safe hook for color mode that handles SSR and avoids ColorModeProvider issues.
* This hook reads the theme directly from the DOM instead of relying on Docusaurus context.
*
* @returns {Object} Object containing colorMode, isDark, and mounted state
*/
export function useSafeColorMode() {
const [mounted, setMounted] = useState(false);
const [colorMode, setColorMode] = useState<"light" | "dark">("light");
const [isDark, setIsDark] = useState(false);
useEffect(() => {
setMounted(true);
if (!ExecutionEnvironment.canUseDOM) return;
const getThemeFromDOM = () =>
(document.documentElement.getAttribute("data-theme") as
| "light"
| "dark") || "light";
const applyTheme = () => {
const mode = getThemeFromDOM();
setColorMode(mode);
setIsDark(mode === "dark");
};
// set immediately on mount
applyTheme();
// watch for changes when navbar toggle is clicked
const observer = new MutationObserver(applyTheme);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme"],
});
return () => observer.disconnect();
}, []);
return { colorMode, isDark, mounted };
}