37 lines
1.3 KiB
TypeScript
37 lines
1.3 KiB
TypeScript
|
|
import { Moon, Sun } from "lucide-react";
|
||
|
|
import { Button } from "@/components/ui/button";
|
||
|
|
import { useEffect, useState } from "react";
|
||
|
|
|
||
|
|
export function ThemeToggle() {
|
||
|
|
const [theme, setTheme] = useState<"light" | "dark">("light");
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const savedTheme = localStorage.getItem("theme") as "light" | "dark" | null;
|
||
|
|
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||
|
|
const initialTheme = savedTheme || (prefersDark ? "dark" : "light");
|
||
|
|
|
||
|
|
setTheme(initialTheme);
|
||
|
|
document.documentElement.classList.toggle("dark", initialTheme === "dark");
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
const toggleTheme = () => {
|
||
|
|
const newTheme = theme === "light" ? "dark" : "light";
|
||
|
|
setTheme(newTheme);
|
||
|
|
localStorage.setItem("theme", newTheme);
|
||
|
|
document.documentElement.classList.toggle("dark", newTheme === "dark");
|
||
|
|
};
|
||
|
|
|
||
|
|
return (
|
||
|
|
<Button
|
||
|
|
variant="ghost"
|
||
|
|
size="icon"
|
||
|
|
onClick={toggleTheme}
|
||
|
|
className="relative rounded-full cursor-pointer hover:bg-gray-100 dark:hover:bg-cyan-900/30 transition-colors"
|
||
|
|
aria-label="Toggle theme"
|
||
|
|
>
|
||
|
|
<Sun className={`h-5 w-5 transition-all absolute ${theme === "light" ? "rotate-0 scale-100" : "rotate-90 scale-0"}`} />
|
||
|
|
<Moon className={`h-5 w-5 transition-all absolute ${theme === "dark" ? "rotate-0 scale-100" : "rotate-90 scale-0"}`} />
|
||
|
|
</Button>
|
||
|
|
);
|
||
|
|
}
|