-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThemeChanger.tsx
91 lines (80 loc) · 2.57 KB
/
ThemeChanger.tsx
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { useAppDispatch, useAppSelector } from "@/hooks/redux";
import { getTheme } from "@/redux/app/appSelector";
import { appActions } from "@/redux/app/appSlice";
import clsx from "clsx";
import { useCallback, useEffect } from "react";
import { Button, Dropdown } from "react-daisyui";
import {
MdOutlineBrightnessAuto,
MdOutlineDarkMode,
MdOutlineLightMode,
} from "react-icons/md";
import { useMedia } from "react-use";
import { themeChange } from "theme-change";
// Set the corresponding daisyUI themes from "tailwind.config.cjs"
const themes = { light: "light", dark: "dark" };
export default function ThemeChanger({
className,
}: {
className?: string;
}): JSX.Element {
const dispatch = useAppDispatch();
const theme = useAppSelector(getTheme);
const deviceThemeDark = useMedia("(prefers-color-scheme: dark)", false);
// Automatically set theme if non is explicitly set
if (!theme) {
const htmlElement = document.querySelector("html")!;
htmlElement.setAttribute(
"data-theme",
deviceThemeDark ? themes.dark : themes.light
);
}
useEffect(() => {
themeChange(false);
}, []);
const themeIcon = useCallback(() => {
switch (theme) {
case themes.light:
return <MdOutlineLightMode className="h-5 w-5" />;
case themes.dark:
return <MdOutlineDarkMode className="h-5 w-5" />;
default:
return <MdOutlineBrightnessAuto className="h-5 w-5" />;
}
}, [theme]);
return (
<Dropdown end className={className}>
<Dropdown.Toggle button={false}>
<Button shape="circle" color="ghost">
{themeIcon()}
</Button>
</Dropdown.Toggle>
<Dropdown.Menu className="mt-3 w-36">
<Dropdown.Item
data-set-theme=""
className={clsx({ active: !theme })}
onClick={() => dispatch(appActions.setTheme(""))}
>
<MdOutlineBrightnessAuto className="h-5 w-5" />
Auto
</Dropdown.Item>
<Dropdown.Item
data-set-theme={themes.dark}
className={clsx({ active: theme === themes.dark })}
onClick={() => dispatch(appActions.setTheme(themes.dark))}
>
<MdOutlineDarkMode className="h-5 w-5" />
Dark
</Dropdown.Item>
<Dropdown.Item
data-set-theme={themes.light}
className={clsx({ active: theme === themes.light })}
onClick={() => dispatch(appActions.setTheme(themes.light))}
>
<MdOutlineLightMode className="h-5 w-5" />
Light
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
);
}