|
| 1 | +"use client" |
| 2 | + |
| 3 | +import { Moon, Sun } from "lucide-react" |
| 4 | +import { useTheme } from "next-themes" |
| 5 | +import { useEffect, useState, type ComponentProps } from "react" |
| 6 | + |
| 7 | +import { Button } from "@/components/ui/button" |
| 8 | +import { cn } from "@/lib/utils" |
| 9 | + |
| 10 | +type ThemeToggleProps = { |
| 11 | + className?: string |
| 12 | + size?: ComponentProps<typeof Button>["size"] |
| 13 | + variant?: ComponentProps<typeof Button>["variant"] |
| 14 | +} |
| 15 | + |
| 16 | +export function ThemeToggle({ |
| 17 | + className, |
| 18 | + size = "icon", |
| 19 | + variant = "ghost", |
| 20 | +}: ThemeToggleProps) { |
| 21 | + const { theme, setTheme, resolvedTheme } = useTheme() |
| 22 | + const [mounted, setMounted] = useState(false) |
| 23 | + |
| 24 | + useEffect(() => { |
| 25 | + setMounted(true) |
| 26 | + }, []) |
| 27 | + |
| 28 | + const currentTheme = theme === "system" ? resolvedTheme : theme |
| 29 | + const isDark = currentTheme === "dark" |
| 30 | + |
| 31 | + const handleToggle = () => { |
| 32 | + setTheme(isDark ? "light" : "dark") |
| 33 | + } |
| 34 | + |
| 35 | + return ( |
| 36 | + <Button |
| 37 | + type="button" |
| 38 | + variant={variant} |
| 39 | + size={size} |
| 40 | + onClick={handleToggle} |
| 41 | + aria-label="Toggle theme" |
| 42 | + className={cn("relative", className)} |
| 43 | + > |
| 44 | + <Sun |
| 45 | + className={cn( |
| 46 | + "size-5 transition-all duration-300", |
| 47 | + mounted && isDark ? "rotate-90 scale-0 opacity-0" : "rotate-0 scale-100 opacity-100" |
| 48 | + )} |
| 49 | + aria-hidden="true" |
| 50 | + /> |
| 51 | + <Moon |
| 52 | + className={cn( |
| 53 | + "absolute inset-0 m-auto size-5 transition-all duration-300", |
| 54 | + mounted && isDark ? "rotate-0 scale-100 opacity-100" : "rotate-90 scale-0 opacity-0" |
| 55 | + )} |
| 56 | + aria-hidden="true" |
| 57 | + /> |
| 58 | + <span className="sr-only">Toggle theme</span> |
| 59 | + </Button> |
| 60 | + ) |
| 61 | +} |
0 commit comments