animated-theme-toggler.tsx
1"use client"
2
3import { useCallback, useEffect, useRef, useState } from "react"
4import { Moon, Sun } from "lucide-react"
5import { flushSync } from "react-dom"
6
7import { cn } from "@/lib/utils"
8
9interface AnimatedThemeTogglerProps extends React.ComponentPropsWithoutRef<"button"> {
10 duration?: number
11}
12
13export const AnimatedThemeToggler = ({
14 className,
15 duration = 400,
16 ...props
17}: AnimatedThemeTogglerProps) => {
18 const [isDark, setIsDark] = useState(false)
19 const buttonRef = useRef<HTMLButtonElement>(null)
20
21 useEffect(() => {
22 const updateTheme = () => {
23 setIsDark(document.documentElement.classList.contains("dark"))
24 }
25
26 updateTheme()
27
28 const observer = new MutationObserver(updateTheme)
29 observer.observe(document.documentElement, {
30 attributes: true,
31 attributeFilter: ["class"],
32 })
33
34 return () => observer.disconnect()
35 }, [])
36
37 const toggleTheme = useCallback(() => {
38 const button = buttonRef.current
39 if (!button) return
40
41 const { top, left, width, height } = button.getBoundingClientRect()
42 const x = left + width / 2
43 const y = top + height / 2
44 const viewportWidth = window.visualViewport?.width ?? window.innerWidth
45 const viewportHeight = window.visualViewport?.height ?? window.innerHeight
46 const maxRadius = Math.hypot(
47 Math.max(x, viewportWidth - x),
48 Math.max(y, viewportHeight - y)
49 )
50
51 const applyTheme = () => {
52 const newTheme = !isDark
53 setIsDark(newTheme)
54 document.documentElement.classList.toggle("dark")
55 localStorage.setItem("theme", newTheme ? "dark" : "light")
56 }
57
58 if (typeof document.startViewTransition !== "function") {
59 applyTheme()
60 return
61 }
62
63 const transition = document.startViewTransition(() => {
64 flushSync(applyTheme)
65 })
66
67 const ready = transition?.ready
68 if (ready && typeof ready.then === "function") {
69 ready.then(() => {
70 document.documentElement.animate(
71 {
72 clipPath: [
73 `circle(0px at ${x}px ${y}px)`,
74 `circle(${maxRadius}px at ${x}px ${y}px)`,
75 ],
76 },
77 {
78 duration,
79 easing: "ease-in-out",
80 pseudoElement: "::view-transition-new(root)",
81 }
82 )
83 })
84 }
85 }, [isDark, duration])
86
87 return (
88 <button
89 type="button"
90 ref={buttonRef}
91 onClick={toggleTheme}
92 className={cn(className)}
93 {...props}
94 >
95 {isDark ? <Sun /> : <Moon />}
96 <span className="sr-only">Toggle theme</span>
97 </button>
98 )
99}
100