Installation
Add the component
npx shadcn@latest add https://prequeluianimate.terravidhal.me/r/theme-toggler.jsonFirst component? Set up your project first
Frameworks
The live preview is React. Each tab below is the file that ships for that framework, with the same durations, springs and reduced-motion rule.
"use client";
import * as React from "react";
import { flushSync } from "react-dom";
import { useReduceMotion, useTempo } from "../motion";
import { useMounted } from "./shared";
export type ThemeSelection = "light" | "dark" | "system";
export type ResolvedTheme = "light" | "dark";
export type ThemeWipeDirection = "btt" | "ttb" | "ltr" | "rtl";
type ViewTransitionLike = {
ready: Promise<void>;
finished: Promise<void>;
};
type DocumentWithTransitions = Document & {
startViewTransition?: (
arg:
| (() => void)
| { update: () => void; types?: string[] },
) => ViewTransitionLike;
};
function systemResolved(): ResolvedTheme {
if (typeof window === "undefined") return "light";
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
function clipKeyframes(direction: ThemeWipeDirection): [string, string] {
switch (direction) {
case "rtl":
return ["inset(0 0 0 100%)", "inset(0 0 0 0)"];
case "ttb":
return ["inset(0 0 100% 0)", "inset(0 0 0 0)"];
case "btt":
return ["inset(100% 0 0 0)", "inset(0 0 0 0)"];
case "ltr":
default:
return ["inset(0 100% 0 0)", "inset(0 0 0 0)"];
}
}
const WIPE_DURATION = 700;
const WIPE_EASING = "ease-in-out";
const WIPE_TYPE = "prequel-theme-wipe";
const WIPE_STYLE =
"::view-transition-old(root), ::view-transition-new(root){animation:none;mix-blend-mode:normal;}" +
`:root:active-view-transition-type(${WIPE_TYPE}) body, :root:active-view-transition-type(${WIPE_TYPE}) body *{view-transition-name:none !important;}`;
function startWipe(update: () => void): ViewTransitionLike | null {
const documentWithTransitions = document as DocumentWithTransitions;
if (!documentWithTransitions.startViewTransition) return null;
try {
return documentWithTransitions.startViewTransition({
update,
types: [WIPE_TYPE],
});
} catch {
return documentWithTransitions.startViewTransition(update);
}
}
export type ThemeTogglerRenderState = {
resolved: ResolvedTheme;
effective: ThemeSelection;
toggleTheme: (theme: ThemeSelection) => void;
};
export type ThemeTogglerProps = {
theme: ThemeSelection;
resolvedTheme: ResolvedTheme;
setTheme: (theme: ThemeSelection) => void;
direction?: ThemeWipeDirection;
onImmediateChange?: (theme: ThemeSelection) => void;
children?:
| React.ReactNode
| ((state: ThemeTogglerRenderState) => React.ReactNode);
};
type Preview = { effective: ThemeSelection; resolved: ResolvedTheme } | null;
const PLACEHOLDER = {
effective: "system" as ThemeSelection,
resolved: "light" as ResolvedTheme,
};
export function ThemeToggler({
theme,
resolvedTheme,
setTheme,
direction = "ltr",
onImmediateChange,
children,
}: ThemeTogglerProps) {
const mounted = useMounted();
const reduce = useReduceMotion();
const tempo = useTempo();
const wipeDuration = WIPE_DURATION * tempo;
const [preview, setPreview] = React.useState<Preview>(null);
const [current, setCurrent] = React.useState<{
effective: ThemeSelection;
resolved: ResolvedTheme;
}>({ effective: theme, resolved: resolvedTheme });
React.useEffect(() => {
setCurrent({ effective: theme, resolved: resolvedTheme });
}, [theme, resolvedTheme]);
React.useEffect(() => {
if (
preview &&
theme === preview.effective &&
resolvedTheme === preview.resolved
) {
setPreview(null);
}
}, [preview, resolvedTheme, theme]);
const [fromClip, toClip] = clipKeyframes(direction);
const toggleTheme = React.useCallback(
(next: ThemeSelection) => {
const resolved = next === "system" ? systemResolved() : next;
setCurrent({ effective: next, resolved });
onImmediateChange?.(next);
if (next === "system" && resolved === resolvedTheme) {
setTheme(next);
return;
}
if (reduce) {
flushSync(() => setPreview({ effective: next, resolved }));
setTheme(next);
return;
}
const transition = startWipe(() => {
flushSync(() => {
setPreview({ effective: next, resolved });
document.documentElement.classList.toggle("dark", resolved === "dark");
});
});
if (!transition) {
setPreview({ effective: next, resolved });
setTheme(next);
return;
}
void transition.ready.then(() => {
document.documentElement
.animate(
{ clipPath: [fromClip, toClip] },
{
duration: wipeDuration,
easing: WIPE_EASING,
pseudoElement: "::view-transition-new(root)",
},
)
.finished.finally(() => setTheme(next));
});
},
[
fromClip,
onImmediateChange,
reduce,
resolvedTheme,
setTheme,
toClip,
wipeDuration,
],
);
const state = mounted ? current : PLACEHOLDER;
return (
<>
<span data-slot="theme-toggler" style={{ display: "contents" }}>
{typeof children === "function"
? children({
effective: state.effective,
resolved: state.resolved,
toggleTheme,
})
: children}
</span>
<style>{WIPE_STYLE}</style>
</>
);
}Install
npx shadcn@latest add https://prequeluianimate.terravidhal.me/r/theme-toggler.jsonDependencies
motion lucide-reactThe registry keeps the component source, its motion tokens and the reduced-motion branch together, so the install never pulls a different animation from the preview.
Usage
Import the component and compose it exactly like the primitive it wraps. Motion is enabled by default; the tempo prop scales every duration and softens every spring.
import { ThemeToggler } from "@/components/prequelui/effects/theme-toggler";
import { useTheme } from "@/components/site/theme-provider";
export default function Demo() {
const { theme, resolvedTheme, setTheme } = useTheme();
return (
<ThemeToggler theme={theme} resolvedTheme={resolvedTheme} setTheme={setTheme}>
{({ resolved, toggleTheme }) => (
<button onClick={() => toggleTheme(resolved === "dark" ? "light" : "dark")}>
Toggle theme
</button>
)}
</ThemeToggler>
);
}import { ThemeToggler } from "@/components/prequelui/theme-toggler";
export function Variant() {
return (
<ThemeToggler tempo={1.2}>
…
</ThemeToggler>
);
}Animation
The theme change is performed inside a View Transition, and the new snapshot is revealed by a clip-path wipe. The button, the preview and the theme provider all read the same resolved value, so no element flashes the wrong colour.
- Wipe: 700 ms ease-in-out, scaled by the motion tempo.
- Four directions: left-to-right, right-to-left, top-to-bottom and bottom-to-top.
- The old and new roots never crossfade; the new one is clipped over the old one.
- Without View Transitions or with reduced motion, the theme changes instantly.
API Reference
Each part accepts the usual HTML props in addition to the motion props below. No accessibility prop is hidden behind the animation layer.
ThemeToggler
| Prop | Type | Default |
|---|---|---|
| theme | "light" | "dark" | "system" | — |
| resolvedTheme | "light" | "dark" | — |
| setTheme | (theme) => void | — |
| direction | "ltr" | "rtl" | "ttb" | "btt" | "ltr" |
| onImmediateChange | (theme) => void | — |
| children | ReactNode | (state) => ReactNode | — |