Theme Toggle
Switch between light and dark: a one-click toggle with page transitions, or a picker that can follow the system.
Picker
Light, dark, or follow the operating system. A three-way choice for settings menus, remembered between visits.
Appearance
Installation
$npx shadcn@latest add @stillui/theme-pickerOr copy the source into your project. It needs the shadcn color tokens and the cn helper.
components/theme-picker.tsx
"use client";
// stillui.dev/components/theme-toggle#picker
import { motion, useReducedMotion } from "motion/react";
import { useEffect, useId, useRef, useSyncExternalStore, type KeyboardEvent } from "react";
import { cn } from "@/lib/utils";
const GLIDE = { type: "spring", stiffness: 420, damping: 40, mass: 0.8 } as const;
const CHANGE = "still-theme-change";
type Choice = "light" | "dark" | "system";
const choices: { value: Choice; label: string; d: string }[] = [
{ value: "light", label: "Light", d: "M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM8 1.5v1.25M8 13.25v1.25M1.5 8h1.25M13.25 8h1.25M3.4 3.4l.9.9M11.7 11.7l.9.9M3.4 12.6l.9-.9M11.7 4.3l.9-.9" },
{ value: "dark", label: "Dark", d: "M13.5 9.5A5.5 5.5 0 0 1 6.5 2.5a5.5 5.5 0 1 0 7 7z" },
{ value: "system", label: "System", d: "M2.5 3.5h11v7h-11zM6 13.5h4M8 10.5v3" },
];
// "system" is stored as no value, so a pre-paint script can fall back to the OS setting.
function read(): Choice {
try {
const saved = localStorage.getItem("theme");
return saved === "light" || saved === "dark" ? saved : "system";
} catch {
return "system";
}
}
// Re-reads when this picker saves, another tab saves, or any other toggle flips the dark class.
function subscribe(onChange: () => void) {
const observer = new MutationObserver(onChange);
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
window.addEventListener(CHANGE, onChange);
window.addEventListener("storage", onChange);
return () => {
observer.disconnect();
window.removeEventListener(CHANGE, onChange);
window.removeEventListener("storage", onChange);
};
}
function systemDark() {
return matchMedia("(prefers-color-scheme: dark)").matches;
}
function save(choice: Choice) {
try {
if (choice === "system") localStorage.removeItem("theme");
else localStorage.setItem("theme", choice);
} catch {}
document.documentElement.classList.toggle("dark", choice === "dark" || (choice === "system" && systemDark()));
window.dispatchEvent(new Event(CHANGE));
}
/** Light, dark, or follow the operating system. The choice is remembered. */
export function ThemePicker({ className }: { className?: string }) {
const reduce = useReducedMotion();
const layoutId = useId();
const choice = useSyncExternalStore(subscribe, read, () => "system" as Choice);
const refs = useRef<(HTMLButtonElement | null)[]>([]);
// While following the system, react when the OS switches (e.g. at sunset).
useEffect(() => {
if (choice !== "system") return;
const query = matchMedia("(prefers-color-scheme: dark)");
const sync = () => document.documentElement.classList.toggle("dark", query.matches);
query.addEventListener("change", sync);
return () => query.removeEventListener("change", sync);
}, [choice]);
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
if (!step) return;
event.preventDefault();
const index = choices.findIndex((c) => c.value === choice);
const next = (index + step + choices.length) % choices.length;
save(choices[next].value);
refs.current[next]?.focus();
};
return (
<div role="radiogroup" aria-label="Theme" onKeyDown={onKeyDown} className={cn("inline-flex items-center rounded-full bg-muted p-1", className)}>
{choices.map((c, i) => {
const selected = c.value === choice;
return (
<button
key={c.value}
ref={(el) => {
refs.current[i] = el;
}}
type="button"
role="radio"
aria-checked={selected}
aria-label={c.label}
title={c.label}
tabIndex={selected ? 0 : -1}
onClick={() => save(c.value)}
className={cn(
"relative grid size-8 place-items-center rounded-full transition-[color,background-color,box-shadow,scale] active:scale-[0.92] duration-150",
selected ? "text-foreground" : "text-muted-foreground hover:text-foreground",
)}
>
{selected ? (
<motion.span
layoutId={layoutId}
aria-hidden
className="absolute inset-0 rounded-full bg-card shadow-raised"
transition={reduce ? { duration: 0 } : GLIDE}
/>
) : null}
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="relative size-4" aria-hidden>
<path d={c.d} />
</svg>
</button>
);
})}
</div>
);
}States
- Light / Dark
- Sets the theme and saves it under “theme” in localStorage.
- System
- Removes the saved value and follows the OS, including when it changes at sunset.
- Switching
- A raised pill glides to the chosen icon.
- In sync
- Every picker and toggle on the page updates together, and other tabs follow too.
- Keyboard
- A radio group: one tab stop, arrow keys to choose. Each icon has a name.
- Reduced motion
- The pill jumps instead of gliding.
Notes
Pair it with a pre-paint script that reads localStorage “theme” and falls back to prefers-color-scheme, so pages never flash.