Theme transition
Switches light and dark with a rising view transition; reduced motion swaps at once.
Wrap the call that changes the theme: runThemeTransition(() => setTheme("dark")), with setTheme from next-themes or your own function that sets the dark class on <html>. The next appearance rises over the page from the bottom edge, timed by foundation. A second press part-way jumps to the end and starts again. Where the browser has no View Transitions, and for readers who ask for reduced motion, the theme changes at once. The example changes this site's theme and puts your setting back on the second press, or when you leave the page.
Trying the other theme
"use client"
import { useTheme } from "next-themes"
import { useEffect, useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { useHydration } from "@/hooks/use-hydration"
import { runThemeTransition } from "@/lib/theme-transition"
export default function ThemeTransitionTryingTheOtherTheme() {
const { theme, resolvedTheme, setTheme } = useTheme()
const hydrated = useHydration()
// The reader's own setting (system, light or dark) while the other theme is on show.
const [kept, setKept] = useState<string | null>(null)
const restore = useRef<(() => void) | null>(null)
// Leaving the page with the other theme still on puts the setting back.
useEffect(() => {
const back = () => restore.current?.()
window.addEventListener("pagehide", back)
return () => {
window.removeEventListener("pagehide", back)
back()
}
}, [])
function toggle() {
if (kept !== null) {
restore.current = null
runThemeTransition(() => setTheme(kept))
setKept(null)
return
}
const setting = theme ?? "system"
restore.current = () => setTheme(setting)
runThemeTransition(() => setTheme(resolvedTheme === "dark" ? "light" : "dark"))
setKept(setting)
}
return (
<Button variant="outline" disabled={!hydrated} onClick={toggle}>
{kept === null ? "Try the other theme" : "Back to your theme"}
</Button>
)
}
Installation
npx shadcn@latest add @khaeli/theme-transitionbunx --bun shadcn@latest add @khaeli/theme-transitionPair with next-themes: runThemeTransition(() => setTheme(next)). The keyframes live in @khaeli/foundation.
Installs with
- Registry items
Keyboard
EnterSpace- Changes the theme. Focus stays on the button through the transition.
Registry JSON
The item as the shadcn CLI reads it, with every file it ships: https://ui.khaeli.com/r/theme-transition.json