el.xwx.moe/components/ToggleDarkMode.tsx

49 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-11-24 06:50:16 -06:00
import useLocalSettingsStore from "@/store/localSettings";
2024-07-27 16:17:38 -05:00
import { useEffect, useState, ChangeEvent } from "react";
2024-06-09 08:27:16 -05:00
import { useTranslation } from "next-i18next";
2023-08-02 12:53:55 -05:00
2023-11-16 02:22:16 -06:00
type Props = {
className?: string;
};
export default function ToggleDarkMode({ className }: Props) {
2024-06-09 08:27:16 -05:00
const { t } = useTranslation();
2023-11-29 14:17:51 -06:00
const { settings, updateSettings } = useLocalSettingsStore();
2023-11-24 06:50:16 -06:00
2024-07-27 17:41:13 -05:00
const [theme, setTheme] = useState<string | null>(
localStorage.getItem("theme")
);
2023-08-02 12:53:55 -05:00
2024-07-27 16:17:38 -05:00
const handleToggle = (e: ChangeEvent<HTMLInputElement>) => {
2023-12-16 08:46:29 -06:00
setTheme(e.target.checked ? "dark" : "light");
2023-08-02 12:53:55 -05:00
};
2023-11-24 02:06:33 -06:00
useEffect(() => {
2024-07-27 16:17:38 -05:00
if (theme) {
updateSettings({ theme });
}
2024-08-18 15:39:43 -05:00
}, [theme]);
2023-11-24 02:06:33 -06:00
2023-08-02 12:53:55 -05:00
return (
2023-11-29 14:17:51 -06:00
<div
className="tooltip tooltip-bottom"
2024-06-09 08:27:16 -05:00
data-tip={t("switch_to", {
theme: settings.theme === "light" ? "Dark" : "Light",
})}
2023-11-27 15:38:38 -06:00
>
2023-11-29 14:17:51 -06:00
<label
className={`swap swap-rotate btn-square text-neutral btn btn-ghost btn-sm ${className}`}
2023-11-24 02:06:33 -06:00
>
2023-11-29 14:17:51 -06:00
<input
type="checkbox"
onChange={handleToggle}
className="theme-controller"
2024-07-27 16:17:38 -05:00
checked={theme === "dark"}
2023-11-29 14:17:51 -06:00
/>
2023-12-17 22:32:33 -06:00
<i className="bi-sun-fill text-xl swap-on"></i>
<i className="bi-moon-fill text-xl swap-off"></i>
2023-11-29 14:17:51 -06:00
</label>
</div>
2023-08-02 12:53:55 -05:00
);
}