-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThemeSwitch.js
52 lines (45 loc) · 1.24 KB
/
ThemeSwitch.js
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
45
46
47
48
49
50
51
52
import React, { useEffect } from "react";
import { view } from "@risingstack/react-easy-state";
import { LightDarkSwitch } from "./LightDarkSwitch.js";
import { persistentStore } from "./store/persistent-store.js";
const isDarkSchemePreferred = () =>
window.matchMedia("(prefers-color-scheme: dark)").matches;
export const themeStore = persistentStore(
"uiConfig",
{
theme: isDarkSchemePreferred() ? "dark" : "light"
},
{
flipTheme: () =>
(themeStore.theme = themeStore.isDarkTheme() ? "light" : "dark"),
isDarkTheme: () => themeStore.theme === "dark"
}
);
export const ThemeSwitch = view(() => {
const updateTheme = () => {
const classList = document.body.classList;
if (themeStore.isDarkTheme()) {
classList.remove("light");
classList.add("bp3-dark", "dark");
} else {
classList.remove("bp3-dark", "dark");
classList.add("light");
}
};
const flipTheme = () => {
themeStore.flipTheme();
updateTheme();
};
// Set theme on initial render.
useEffect(function () {
updateTheme();
}, []);
const isDarkTheme = themeStore.isDarkTheme();
return (
<LightDarkSwitch
className="ThemeSwitch"
dark={isDarkTheme}
onChange={flipTheme}
/>
);
});