Components56 / 118
Theme Toggle
A dark / light switch in monospaced capitals, split into two equal halves with a moon and a sun. Hover the other half and a pill blooms out of your cursor, a circle that swells to fill the half, while a band of glitch glyphs sweeps across its label and decodes it; leave and it gathers back into your cursor. Click and the selection slides across into it, and the moment it lands every colour flips and the page turns over to the other theme. A proper radio group with arrow keys.
Glitch decodeGlitch decodeCursor bloomCursor bloomTheme flipTheme flipRadio groupRadio groupGSAPGSAPReduced-motion safeReduced-motion safe
Hover the other halfClick to turn the page over
Tweak
LIVELIVELabels
Colours
#0e0c0a
#f8f9ef
60px
Usage
Follows your tweaks.
usage.tsx
import { ThemeToggle } from "@/components/inreact/theme-toggle";
// flips <html data-theme="dark|light"> the moment the selection lands
export function Header() {
return <ThemeToggle applyToDocument />;
}
/* in your CSS:
:root[data-theme="light"] { --bg: #f8f9ef; --fg: #0e0c0a; }
:root[data-theme="dark"] { --bg: #0e0c0a; --fg: #f8f9ef; } */Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/theme-toggle.jsonOr copy the source
Install the dependencies, then save this as components/inreact/theme-toggle.tsx.
terminal
npm install gsapcomponents/inreact/theme-toggle.tsx
"use client";
import { gsap } from "gsap";
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent as RPointerEvent, type ReactNode } from "react";
/**
* Theme Toggle: a dark / light switch that decodes itself and turns the page over.
*
* A slim pill in monospaced capitals, split into two equal halves, a moon and a
* sun. Hover the other half and a pill blooms out of your cursor, a circle that
* swells to fill that half, while a little band of glitch glyphs sweeps across
* its label and decodes it. Leave and it gathers back into your cursor. Click
* and the selection slides across into it; the moment it lands, every colour
* flips and the page turns over to the other theme.
*
* <ThemeToggle defaultValue="dark" applyToDocument />
* // or drive your own theme:
* <ThemeToggle value={theme} onValueChange={setTheme} />
*
* A radio group: arrows and Home/End switch; screen readers read the real
* labels. Reduced motion: no scramble, an instant flip.
*/
export type Theme = "dark" | "light";
export interface ThemeToggleProps {
/** Controlled theme. */
value?: Theme;
/** Initial theme when uncontrolled. */
defaultValue?: Theme;
/** Called with the new theme once the selection has landed. */
onValueChange?: (theme: Theme) => void;
/** Set data-theme and color-scheme on <html> when the theme flips. */
applyToDocument?: boolean;
/** Labels. */
labels?: { dark: string; light: string };
/** The dark colour (page in dark mode, ink in light mode). */
ink?: string;
/** The light colour (page in light mode, ink in dark mode). */
paper?: string;
/** Height in px. */
size?: number;
className?: string;
"aria-label"?: string;
}
const GLYPHS = "!<>-_\\/[]{}=+*^?#;:.@";
const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// a band of glitch glyphs that sweeps across a label from left to right, decoding it as it passes
function sweep(el: HTMLElement, text: string, duration = 0.5, band = 2) {
if (reduced()) {
el.textContent = text;
return null;
}
const st = { p: 0, f: -1 };
return gsap.to(st, {
p: 1,
duration,
ease: "none",
onUpdate() {
const f = Math.floor(st.p * duration * 30); // glyphs change at film rate, not every frame
if (f === st.f) return;
st.f = f;
const head = st.p * (text.length + band);
let out = "";
for (let i = 0; i < text.length; i++) {
const c = text[i];
out += c !== " " && i >= head - band && i < head ? GLYPHS[(Math.random() * GLYPHS.length) | 0] : c;
}
el.textContent = out;
},
onComplete() {
el.textContent = text;
},
});
}
function Moon() {
return (
<svg viewBox="0 0 24 24" width="100%" height="100%" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M19.5 14.6A7.8 7.8 0 0 1 9.4 4.5a7.8 7.8 0 1 0 10.1 10.1Z" />
</svg>
);
}
function Sun() {
return (
<svg viewBox="0 0 24 24" width="100%" height="100%" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" aria-hidden="true">
<circle cx="12" cy="12" r="3.4" />
<path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4" />
</svg>
);
}
export function ThemeToggle({
value,
defaultValue = "dark",
onValueChange,
applyToDocument = false,
labels = { dark: "Dark", light: "Light" },
ink = "#0e0c0a",
paper = "#f8f9ef",
size = 60,
className,
"aria-label": ariaLabel = "Theme",
}: ThemeToggleProps) {
const [inner, setInner] = useState<Theme>(defaultValue);
const theme = value ?? inner;
const rootRef = useRef<HTMLDivElement>(null);
const thumbRef = useRef<HTMLSpanElement>(null);
const bloomRef = useRef<HTMLSpanElement>(null);
const btnRefs = useRef<Record<Theme, HTMLButtonElement | null>>({ dark: null, light: null });
const textRefs = useRef<Record<Theme, HTMLSpanElement | null>>({ dark: null, light: null });
const [lit, setLit] = useState<Theme | null>(null); // the half the bloom sits behind
const busy = useRef(false);
// dark mode: light on dark; light mode: dark on light
const fg = theme === "dark" ? paper : ink;
const bg = theme === "dark" ? ink : paper;
const pad = Math.round(size * 0.09);
const fs = Math.max(9, Math.round(size * 0.185));
// the selection rests under its half
const rest = useCallback(() => {
const t = thumbRef.current, b = btnRefs.current[theme];
if (t && b) gsap.set(t, { x: b.offsetLeft - pad, width: b.offsetWidth });
}, [theme, pad]);
useLayoutEffect(rest, [rest, size, labels.dark, labels.light]);
useEffect(() => {
const ro = new ResizeObserver(() => !busy.current && rest());
if (rootRef.current) ro.observe(rootRef.current);
return () => ro.disconnect();
}, [rest]);
const local = (e: { clientX: number }) => {
const r = rootRef.current!.getBoundingClientRect();
return e.clientX - r.left - pad;
};
// hovering the other half: a circle blooms out of the cursor and swells to fill the half
const bloomIn = (k: Theme, cx?: number) => {
if (k === theme || busy.current) return;
const el = bloomRef.current, b = btnRefs.current[k];
if (!el || !b) return;
setLit(k);
const h = b.offsetHeight;
const x0 = Math.max(b.offsetLeft - pad, Math.min(b.offsetLeft - pad + b.offsetWidth - h, (cx ?? b.offsetLeft - pad + b.offsetWidth / 2) - h / 2));
if (reduced()) gsap.set(el, { x: b.offsetLeft - pad, width: b.offsetWidth, scale: 1, opacity: 1 });
else
gsap
.timeline({ overwrite: true })
.set(el, { x: x0, width: h, scale: 0.35, opacity: 1 })
.to(el, { scale: 1, duration: 0.22, ease: "power3.out" })
.to(el, { x: b.offsetLeft - pad, width: b.offsetWidth, duration: 0.42, ease: "expo.out" }, 0.08);
const t = textRefs.current[k];
if (t) sweep(t, labels[k], 0.5, 2);
};
// leaving: it gathers back into the cursor and is gone
const bloomOut = (cx?: number) => {
const el = bloomRef.current;
if (!el || busy.current) return;
setLit(null);
if (reduced()) return void gsap.set(el, { opacity: 0 });
const h = el.offsetHeight;
const cur = gsap.getProperty(el, "x") as number;
const w = el.offsetWidth;
const x1 = cx !== undefined ? Math.max(cur, Math.min(cur + w - h, cx - h / 2)) : cur + w / 2 - h / 2;
gsap
.timeline({ overwrite: true })
.to(el, { x: x1, width: h, duration: 0.3, ease: "power3.inOut" })
.to(el, { scale: 0.2, opacity: 0, duration: 0.18, ease: "power2.in" }, 0.16);
};
const flip = (k: Theme) => {
if (applyToDocument && typeof document !== "undefined") {
document.documentElement.dataset.theme = k;
document.documentElement.style.colorScheme = k;
}
if (value === undefined) setInner(k);
onValueChange?.(k);
};
// choosing: the selection slides across into the bloom; the moment it lands, everything flips
const choose = (k: Theme) => {
if (k === theme || busy.current) return;
const t = thumbRef.current, b = btnRefs.current[k], el = bloomRef.current;
if (!t || !b || reduced()) return flip(k);
busy.current = true;
if (el && !lit) gsap.set(el, { x: b.offsetLeft - pad, width: b.offsetWidth, scale: 1, opacity: 1 });
gsap.to(t, {
x: b.offsetLeft - pad,
width: b.offsetWidth,
duration: 0.38,
ease: "power3.inOut",
onComplete: () => {
if (el) gsap.set(el, { opacity: 0 });
setLit(null);
busy.current = false;
flip(k);
},
});
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
let k: Theme | null = null;
if (e.key === "ArrowRight" || e.key === "ArrowDown" || e.key === "End") k = "light";
if (e.key === "ArrowLeft" || e.key === "ArrowUp" || e.key === "Home") k = "dark";
if (!k) return;
e.preventDefault();
choose(k);
btnRefs.current[k]?.focus();
};
const half = (k: Theme, icon: ReactNode) => {
const on = theme === k;
const covered = on || lit === k;
return (
<button
key={k}
ref={(el) => {
btnRefs.current[k] = el;
}}
type="button"
role="radio"
aria-checked={on}
aria-label={labels[k]}
tabIndex={on ? 0 : -1}
onPointerEnter={(e: RPointerEvent) => bloomIn(k, local(e))}
onPointerLeave={(e: RPointerEvent) => lit === k && bloomOut(local(e))}
onFocus={() => bloomIn(k)}
onBlur={() => lit === k && bloomOut()}
onClick={() => choose(k)}
className="relative z-10 flex h-full items-center justify-center rounded-full font-mono uppercase outline-none focus-visible:shadow-[inset_0_0_0_1px_currentColor]"
style={{ gap: Math.round(size * 0.22), paddingInline: Math.round(size * 0.36), fontSize: fs, letterSpacing: "0.06em", color: covered ? bg : fg, transition: "color 160ms" }}
>
<span className="grid shrink-0 place-items-center" style={{ width: fs * 1.55, height: fs * 1.55 }}>
{icon}
</span>
{/* sized to the label, so the glitch never moves the layout */}
<span className="relative">
<span aria-hidden="true" className="invisible">
{labels[k]}
</span>
<span
ref={(el) => {
textRefs.current[k] = el;
}}
aria-hidden="true"
className="absolute inset-0 whitespace-nowrap"
>
{labels[k]}
</span>
</span>
</button>
);
};
return (
<div
ref={rootRef}
role="radiogroup"
aria-label={ariaLabel}
onKeyDown={onKeyDown}
className={["relative inline-grid grid-cols-2 select-none rounded-full", className].filter(Boolean).join(" ")}
style={{ height: size, padding: pad, background: bg, boxShadow: `inset 0 0 0 1.5px color-mix(in srgb, ${fg} 17%, ${bg})` }}
>
<span ref={bloomRef} aria-hidden="true" className="pointer-events-none absolute rounded-full opacity-0" style={{ left: pad, top: pad, bottom: pad, background: fg, willChange: "transform, width" }} />
<span ref={thumbRef} aria-hidden="true" className="pointer-events-none absolute rounded-full" style={{ left: pad, top: pad, bottom: pad, background: fg, willChange: "transform, width" }} />
{half("dark", <Moon />)}
{half("light", <Sun />)}
</div>
);
}
export default ThemeToggle;
One prompt, any AI agent
Paste into Claude Code, Codex, Cursor or Windsurf. It carries your tweaks and the full source, so the agent installs it exactly.
Props
10 propsvalue"dark" | "light"Controlled theme.defaultValue"dark" | "light"Initial theme when uncontrolled.default "dark"default "dark"onValueChange(theme) => voidCalled with the new theme once the selection has landed.applyToDocumentbooleanSet data-theme and color-scheme on <html> when it flips.default falsedefault falselabels{ dark: string; light: string }The two labels.default Dark / Lightdefault Dark / LightinkstringThe dark colour.default "#0e0c0a"default "#0e0c0a"paperstringThe light colour.default "#f8f9ef"default "#f8f9ef"sizenumberHeight, px.default 60default 60aria-labelstringAccessible name of the group.default "Theme"default "Theme"classNamestringExtra classes.