/Click feedback
Click feedback • React
Theme Switch Trio
Three ways to switch the whole page between light and dark: a diagonal wipe from the corner of the new theme, a circle that grows out of the button, and a stick figure who pops up from the bottom of the screen, throws a lit match at the button and flips the theme where it lands.
Installation
Requires lucide-react for its icons. The shadcn CLI installs it for you; copying the code by hand means installing it yourself.
Terminal
npx shadcn@latest add @microkit/theme-switch-trioCode
1"use client";23import { Flame, Moon, Sun } from "lucide-react";4import { useEffect, useRef, useState, useSyncExternalStore } from "react";5import type { Ref } from "react";6import { createPortal, flushSync } from "react-dom";78type Theme = "light" | "dark";910const listeners = new Set<() => void>();1112function readTheme(): Theme {13const root = document.documentElement;14if (root.dataset.theme === "light" || root.dataset.theme === "dark") return root.dataset.theme;15if (root.classList.contains("dark")) return "dark";16return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";17}1819function subscribe(listener: () => void) {20listeners.add(listener);21// Any other switch on the page can change the theme too, so the root is watched rather than trusted.22const observer = new MutationObserver(listener);23observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "class"] });24const media = window.matchMedia("(prefers-color-scheme: dark)");25media.addEventListener("change", listener);26return () => {27listeners.delete(listener);28observer.disconnect();29media.removeEventListener("change", listener);30};31}3233function applyTheme(theme: Theme) {34const root = document.documentElement;35root.dataset.theme = theme;36root.classList.toggle("dark", theme === "dark");37root.style.colorScheme = theme;38// Notified synchronously, so flushSync paints the new icons into the view transition's new snapshot.39for (const listener of listeners) listener();40}4142const viewTransitionCss = `43:root[data-theme-switch]::view-transition-old(root),44:root[data-theme-switch]::view-transition-new(root) {45animation: none;46mix-blend-mode: normal;47}`;4849const buttonClass =50"inline-flex h-[36px] cursor-pointer items-center gap-[7px] whitespace-nowrap rounded-full border border-[light-dark(#dfe3ea,#2b2f36)] bg-[light-dark(#ffffff,#121418)] py-0 pr-[14px] pl-[11px] [font-family:inherit] text-[13px] font-medium leading-none text-[light-dark(#14181e,#f2f4f6)] [transition:background-color_.2s_ease,transform_.2s_cubic-bezier(.16,1,.3,1)] hover:bg-[light-dark(#f0f2f5,#1b1e23)] active:[transform:scale(.96)] focus-visible:outline-2 focus-visible:outline-offset-[3px] focus-visible:outline-[#f97316] motion-reduce:transition-none";5152const iconClass = "grid size-[16px]";5354const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;5556let switchCount = 0;5758function switchTheme(next: Theme, clipPath: string[], duration: number, easing: string) {59const root = document.documentElement;60if (typeof document.startViewTransition !== "function" || reducedMotion()) {61applyTheme(next);62return;63}6465const id = String(++switchCount);66root.dataset.themeSwitch = id;67const transition = document.startViewTransition(() => flushSync(() => applyTheme(next)));68transition.ready69.then(() => {70root.animate({ clipPath }, { duration, easing, pseudoElement: "::view-transition-new(root)" });71})72.catch(() => {});73transition.finished74.catch(() => {})75.finally(() => {76if (root.dataset.themeSwitch === id) delete root.dataset.themeSwitch;77});78}7980// The light theme sweeps in from the bottom right corner, the dark one from the top left.81const wipes: Record<Theme, string[]> = {82light: ["polygon(171% 50%, 50% 171%, 50% 171%, 171% 50%)", "polygon(171% 50%, 50% 171%, -50% 71%, 50% -71%)"],83dark: ["polygon(50% -71%, -50% 71%, -50% 71%, 50% -71%)", "polygon(50% -71%, -50% 71%, 50% 171%, 171% 50%)"],84};8586function circleFrom(element: HTMLElement) {87const rect = element.getBoundingClientRect();88const x = rect.left + rect.width / 2;89const y = rect.top + rect.height / 2;90const radius = Math.hypot(Math.max(x, window.innerWidth - x), Math.max(y, window.innerHeight - y));91return [`circle(0px at ${x}px ${y}px)`, `circle(${radius}px at ${x}px ${y}px)`];92}9394function nextOf(theme: Theme): Theme {95return theme === "dark" ? "light" : "dark";96}9798function MatchShape({ flameRef, lit }: { flameRef?: Ref<SVGGElement>; lit?: boolean }) {99return (100<>101<rect x="-1.4" y="-24" width="2.8" height="24" rx="1.2" fill="#e8c38f" />102<ellipse cx="0" cy="-26" rx="3" ry="3.8" fill="#b91c1c" />103<g104className="[transform-box:fill-box] [transform-origin:50%_100%] [transform:scale(0)] data-[lit]:[transform:scale(1)]"105data-lit={lit || undefined}106ref={flameRef}107>108<ellipse cx="0" cy="-34" rx="4.5" ry="7.5" fill="#f97316" />109<ellipse cx="0" cy="-32.5" rx="2.3" ry="4.2" fill="#fde047" />110</g>111</>112);113}114115const flicker: Keyframe[] = [116{ transform: "scale(1, 1)" },117{ transform: "scale(.86, 1.12)" },118{ transform: "scale(1.06, .92)" },119{ transform: "scale(1, 1)" },120];121122function MatchScene({ target, onLand }: { target: HTMLElement; onLand: (button: HTMLElement) => void }) {123const figureRef = useRef<HTMLDivElement>(null);124const armRef = useRef<SVGGElement>(null);125const handMatchRef = useRef<SVGGElement>(null);126const handFlameRef = useRef<SVGGElement>(null);127const flyingRef = useRef<HTMLDivElement>(null);128const flyingFlameRef = useRef<SVGGElement>(null);129const onLandRef = useRef(onLand);130131useEffect(() => {132onLandRef.current = onLand;133});134135useEffect(() => {136const figure = figureRef.current;137const arm = armRef.current;138const handMatch = handMatchRef.current;139const handFlame = handFlameRef.current;140const flying = flyingRef.current;141const flyingFlame = flyingFlameRef.current;142if (!figure || !arm || !handMatch || !handFlame || !flying || !flyingFlame) return;143144const running: Animation[] = [];145const play = (element: Element, keyframes: Keyframe[], options: KeyframeAnimationOptions) => {146const animation = element.animate(keyframes, options);147running.push(animation);148return animation.finished;149};150151const run = async () => {152// He pops up from the bottom edge, waist deep, and wobbles to a stop.153await play(154figure,155[156{ transform: "translateY(105%) rotate(0deg)", easing: "cubic-bezier(.3, 0, .2, 1)" },157{ transform: "translateY(-3%) rotate(-5deg)", offset: 0.55, easing: "ease-in-out" },158{ transform: "translateY(1.5%) rotate(3deg)", offset: 0.8, easing: "ease-in-out" },159{ transform: "translateY(0) rotate(0deg)" },160],161{ duration: 620, fill: "forwards" },162);163164// A flick of the wrist strikes the match.165await play(166arm,167[{ transform: "rotate(0deg)" }, { transform: "rotate(18deg)" }, { transform: "rotate(-6deg)" }, { transform: "rotate(0deg)" }],168{ duration: 260, easing: "ease-in-out" },169);170await play(handFlame, [{ transform: "scale(0)" }, { transform: "scale(1.3)", offset: 0.6 }, { transform: "scale(1)" }], {171duration: 240,172easing: "ease-out",173fill: "forwards",174});175play(handFlame, flicker, { duration: 260, iterations: Infinity });176177// Wind up behind his head, then throw overhand.178await play(arm, [{ transform: "rotate(0deg)" }, { transform: "rotate(-70deg)" }], {179duration: 280,180delay: 160,181easing: "cubic-bezier(.4, 0, .2, 1)",182fill: "forwards",183});184play(figure, [{ transform: "rotate(0deg)" }, { transform: "rotate(6deg)" }, { transform: "rotate(0deg)" }], {185duration: 380,186easing: "ease-out",187composite: "add",188});189await play(arm, [{ transform: "rotate(-70deg)" }, { transform: "rotate(55deg)" }], {190duration: 150,191easing: "cubic-bezier(.5, 0, .9, .6)",192fill: "forwards",193});194195// The match leaves the hand and arcs onto the button.196const hand = handMatch.getBoundingClientRect();197const end = target.getBoundingClientRect();198const sx = hand.left + hand.width / 2;199const sy = hand.top + hand.height / 2;200const ex = end.left + end.width / 2;201const ey = end.top + end.height / 2;202const distance = Math.hypot(ex - sx, ey - sy);203// Thrown upward, the arc has to peak above the button so the match comes down onto it.204const arc = Math.max(Math.min(140, Math.max(60, distance * 0.25)), (sy - ey) * 0.4);205const steps = 24;206const path: Keyframe[] = Array.from({ length: steps + 1 }, (_, index) => {207const t = index / steps;208const x = sx + (ex - sx) * t;209const y = sy + (ey - sy) * t - arc * 4 * t * (1 - t);210return { transform: `translate(${x}px, ${y}px) translate(-50%, -50%) rotate(${90 + 720 * t}deg)`, opacity: 1 };211});212213handMatch.style.opacity = "0";214play(flyingFlame, flicker, { duration: 260, iterations: Infinity });215const flight = flying.animate(path, { duration: Math.min(900, Math.max(650, distance * 0.9)), fill: "forwards" });216running.push(flight);217218// He hops and drops back down while the match is still in the air.219play(220figure,221[222{ transform: "translateY(0)", easing: "ease-out" },223{ transform: "translateY(-8px)", offset: 0.3, easing: "cubic-bezier(.5, 0, .75, 0)" },224{ transform: "translateY(105%)" },225],226{ duration: 420, delay: 200, fill: "forwards" },227);228229await flight.finished;230// Taken off the page before the old snapshot is captured, so the match is not frozen into it.231flight.cancel();232onLandRef.current(target);233};234235run().catch(() => {});236return () => {237for (const animation of running) animation.cancel();238};239}, [target]);240241return createPortal(242<>243<div244className="pointer-events-none fixed bottom-0 left-[clamp(16px,6vw,72px)] z-[1000] h-[188px] w-[120px] text-[light-dark(#14181e,#f2f4f6)] [transform:translateY(105%)] [transform-origin:50%_100%]"245ref={figureRef}246aria-hidden="true"247>248<svg249className="block size-full overflow-visible"250viewBox="0 0 96 150"251fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round">252<line x1="48" y1="190" x2="48" y2="98" />253<line x1="48" y1="98" x2="48" y2="87" />254<circle cx="48" cy="74" r="13" />255<circle cx="43" cy="70" r="1.6" fill="currentColor" stroke="none" />256<circle cx="53" cy="70" r="1.6" fill="currentColor" stroke="none" />257<path d="M43.5 79 Q48 82.5 52.5 79" strokeWidth="2.2" />258<polyline points="48,98 30,112 22,134" />259<g className="[transform-box:view-box] [transform-origin:48px_98px]" ref={armRef}>260<polyline points="48,98 66,84 72,60" />261<g transform="translate(72 60) rotate(20)" ref={handMatchRef} stroke="none">262<MatchShape flameRef={handFlameRef} />263</g>264</g>265</svg>266</div>267<div className="pointer-events-none fixed top-0 left-0 z-[1000] h-[48px] w-[16px] opacity-0" ref={flyingRef} aria-hidden="true">268<svg className="block size-full overflow-visible" viewBox="-8 -44 16 48">269<MatchShape flameRef={flyingFlameRef} lit />270</svg>271</div>272</>,273document.body,274);275}276277function ThemeIcon() {278return (279<span className={iconClass}>280<Sun281className="[grid-area:1/1] [transition:opacity_.3s_ease,transform_.45s_cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none group-data-[next=dark]:opacity-0 group-data-[next=dark]:[transform:rotate(-90deg)_scale(.5)]"282size={16}283strokeWidth={2}284aria-hidden="true"285/>286<Moon287className="[grid-area:1/1] [transition:opacity_.3s_ease,transform_.45s_cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none group-data-[next=light]:opacity-0 group-data-[next=light]:[transform:rotate(90deg)_scale(.5)]"288size={16}289strokeWidth={2}290aria-hidden="true"291/>292</span>293);294}295296export function ThemeSwitchTrio() {297const theme = useSyncExternalStore(subscribe, readTheme, () => "dark" as Theme);298const next = nextOf(theme);299const [target, setTarget] = useState<HTMLElement | null>(null);300301const throwMatch = (button: HTMLElement) => {302if (target) return;303if (reducedMotion()) {304applyTheme(next);305return;306}307setTarget(button);308};309310const land = (button: HTMLElement) => {311switchTheme(nextOf(readTheme()), circleFrom(button), 650, "cubic-bezier(.65, 0, .35, 1)");312setTarget(null);313};314315return (316<div className="flex flex-wrap justify-center gap-[8px]">317<style>{viewTransitionCss}</style>318<button319type="button"320className={`group ${buttonClass}`}321data-next={next}322aria-label={`Wipe to ${next} theme`}323onClick={() => switchTheme(next, wipes[next], 700, "cubic-bezier(.4, 0, .2, 1)")}324>325<ThemeIcon />326Wipe327</button>328<button329type="button"330className={`group ${buttonClass}`}331data-next={next}332aria-label={`Circle to ${next} theme`}333onClick={(event) => switchTheme(next, circleFrom(event.currentTarget), 650, "cubic-bezier(.4, 0, .2, 1)")}334>335<ThemeIcon />336Circle337</button>338<button339type="button"340className={`group ${buttonClass}`}341data-next={next}342aria-label={`Creative switch to ${next} theme`}343onClick={(event) => throwMatch(event.currentTarget)}344>345<span className={iconClass}>346<Flame347className="[transition:color_.2s_ease] group-hover:text-[#f97316] motion-reduce:transition-none"348size={16}349strokeWidth={2}350aria-hidden="true"351/>352</span>353Creative354</button>355{target && <MatchScene target={target} onLand={land} />}356</div>357);358}