2022-10-16 15:59:08 +02:00
|
|
|
import type { NextPage } from "next";
|
|
|
|
import { useEffect, useState } from "react";
|
|
|
|
import { useTheme } from "next-themes";
|
2022-10-20 14:58:13 +02:00
|
|
|
import Icon from "@mdi/react";
|
|
|
|
import { mdiWhiteBalanceSunny, mdiWeatherNight, mdiLanguageJavascript } from "@mdi/js";
|
2022-10-16 15:59:08 +02:00
|
|
|
|
|
|
|
import styles from "../../styles/Blog/ThemeSwitch.module.scss";
|
|
|
|
|
|
|
|
interface FadeProperties {
|
|
|
|
sun?: string;
|
|
|
|
moon?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
const ThemeSwitch: NextPage<{ size?: string }> = ({ size }) => {
|
|
|
|
const [mounted, setMounted] = useState(false);
|
|
|
|
const [fadeProps, setFadeProps] = useState<FadeProperties>({});
|
2022-10-29 22:49:21 +02:00
|
|
|
const { resolvedTheme, setTheme } = useTheme();
|
2022-10-16 15:59:08 +02:00
|
|
|
|
|
|
|
// Will be run when the component is rendered.
|
|
|
|
useEffect(() => {
|
|
|
|
setMounted(true);
|
|
|
|
}, []);
|
|
|
|
|
2022-10-18 20:03:49 +02:00
|
|
|
const switchTheme = (theme: string) => {
|
|
|
|
if (theme === "dark") setFadeProps({
|
2022-10-16 15:59:08 +02:00
|
|
|
sun: styles.fadeIn,
|
|
|
|
moon: styles.fadeOut
|
|
|
|
});
|
|
|
|
else setFadeProps({
|
|
|
|
sun: styles.fadeOut,
|
|
|
|
moon: styles.fadeIn
|
|
|
|
});
|
|
|
|
|
2022-10-18 20:03:49 +02:00
|
|
|
setTheme(theme);
|
2022-10-16 15:59:08 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
if (!mounted) {
|
|
|
|
return <div className={styles.switch} title="Theme switching needs JS to be enabled.">
|
2022-10-29 21:13:28 +02:00
|
|
|
<Icon path={mdiLanguageJavascript} size={size || "1.5em"} className={styles.placeHolder} id="mdi_themeswitch_noscript" />
|
2022-10-16 15:59:08 +02:00
|
|
|
</div>;
|
|
|
|
}
|
|
|
|
|
2022-10-29 22:49:21 +02:00
|
|
|
const sunClasses = fadeProps.sun || (resolvedTheme === "dark" ? styles.selected : undefined);
|
|
|
|
const moonClasses = fadeProps.moon || (resolvedTheme === "light" ? styles.selected : undefined);
|
2022-10-16 15:59:08 +02:00
|
|
|
|
|
|
|
return <div className={styles.switch}>
|
2022-10-29 21:13:28 +02:00
|
|
|
<div className={sunClasses} onClick={() => switchTheme("light")}><Icon path={mdiWhiteBalanceSunny} size={size || "1.5em"} title="Light theme" id="mdi_themeswitch_light" /></div>
|
|
|
|
<div className={moonClasses} onClick={() => switchTheme("dark")}><Icon path={mdiWeatherNight} size={size || "1.5em"} title="Dark theme" id="mdi_themeswitch_dark" /></div>
|
2022-10-16 15:59:08 +02:00
|
|
|
</div>;
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
export default ThemeSwitch;
|