Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 47 additions & 33 deletions apps/www/registry/magicui/animated-theme-toggler.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client"

import { useCallback, useEffect, useRef, useState } from "react"
import type React from "react"
import { useEffect, useRef, useState } from "react"
import { Moon, Sun } from "lucide-react"
import { flushSync } from "react-dom"

Expand Down Expand Up @@ -34,41 +35,54 @@ export const AnimatedThemeToggler = ({
return () => observer.disconnect()
}, [])

const toggleTheme = useCallback(async () => {
const toggleTheme = () => {
if (!buttonRef.current) return

await document.startViewTransition(() => {
flushSync(() => {
const newTheme = !isDark
setIsDark(newTheme)
document.documentElement.classList.toggle("dark")
localStorage.setItem("theme", newTheme ? "dark" : "light")
const supportsViewTransitions =
typeof document !== "undefined" && "startViewTransition" in document

const newTheme = !isDark
setIsDark(newTheme)
localStorage.setItem("theme", newTheme ? "dark" : "light")


if (supportsViewTransitions) {
const transition = (document as any).startViewTransition(() => {
flushSync(() => {
document.documentElement.classList.toggle("dark")
})
})

transition.ready.then(() => {
if (!buttonRef.current) return

const { top, left, width, height } =
buttonRef.current.getBoundingClientRect()
const x = left + width / 2
const y = top + height / 2
const maxRadius = Math.hypot(
Math.max(left, window.innerWidth - left),
Math.max(top, window.innerHeight - top)
)

document.documentElement.animate(
{
clipPath: [
`circle(0px at ${x}px ${y}px)`,
`circle(${maxRadius}px at ${x}px ${y}px)`,
],
},
{
duration,
easing: "ease-in-out",
pseudoElement: "::view-transition-new(root)",
}
)
})
}).ready

const { top, left, width, height } =
buttonRef.current.getBoundingClientRect()
const x = left + width / 2
const y = top + height / 2
const maxRadius = Math.hypot(
Math.max(left, window.innerWidth - left),
Math.max(top, window.innerHeight - top)
)

document.documentElement.animate(
{
clipPath: [
`circle(0px at ${x}px ${y}px)`,
`circle(${maxRadius}px at ${x}px ${y}px)`,
],
},
{
duration,
easing: "ease-in-out",
pseudoElement: "::view-transition-new(root)",
}
)
}, [isDark, duration])
} else {
document.documentElement.classList.toggle("dark")
}
}

return (
<button
Expand Down