forked from codechefPesuecc/CodeChef-PESUECC-Chapter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseThemeMode.ts
More file actions
29 lines (25 loc) · 965 Bytes
/
Copy pathuseThemeMode.ts
File metadata and controls
29 lines (25 loc) · 965 Bytes
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
"use client";
import { useEffect, useState } from "react";
/**
* Tracks the active site theme (the `.dark` class the Navbar toggle sets on
* <html>) and updates reactively when it changes. Used to keep the CodeMirror
* editor in sync with light/dark mode. Only ever runs on the client (the editor
* is loaded with `ssr: false`), so the lazy initializer can read the DOM safely.
*/
export function useThemeMode(): "light" | "dark" {
const [mode, setMode] = useState<"light" | "dark">(() =>
typeof document !== "undefined" &&
document.documentElement.classList.contains("dark")
? "dark"
: "light",
);
useEffect(() => {
const root = document.documentElement;
const observer = new MutationObserver(() => {
setMode(root.classList.contains("dark") ? "dark" : "light");
});
observer.observe(root, { attributes: true, attributeFilter: ["class"] });
return () => observer.disconnect();
}, []);
return mode;
}