Theme switch
A light, dark and system radio group that applies appearance to a chosen target and optionally remembers it.
pnpm dlx shadcn@latest add @haze/theme-switch---
import { Monitor, Moon, Sun } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Props {
id: string;
name?: string;
label?: string;
value?: "light" | "dark" | "system";
target?: string;
storageKey?: string;
class?: string;
[key: string]: unknown;
}
const { id, name = id, label = "Appearance", value = "dark", target, storageKey, class: className, ...rest } = Astro.props;
const choices = [{ value: "light", label: "Light", icon: Sun }, { value: "dark", label: "Dark", icon: Moon }, { value: "system", label: "System", icon: Monitor }];
---
<fieldset id={id} data-haze-theme-switch data-target={target} data-storage-key={storageKey} class={cn("grid min-w-0 gap-2", className)}>
<legend class="mb-2 text-[0.8125rem]/5 font-medium">{label}</legend>
<div class="inline-flex w-fit max-w-full flex-wrap gap-1 rounded-lg border border-frame bg-muted p-1">
{choices.map(choice => <label class="relative grid cursor-pointer place-items-center">
<input {...rest} type="radio" name={name} value={choice.value} checked={choice.value === value} class="peer sr-only" />
<span class="inline-flex min-h-8 items-center gap-1.5 rounded-sm border border-transparent px-2.5 text-[0.8125rem]/5 text-muted-foreground transition-[background-color,color,border-color] duration-150 ease-snappy hover:text-foreground peer-checked:border-border peer-checked:bg-card peer-checked:text-foreground peer-checked:shadow-key peer-focus-visible:outline-2 peer-focus-visible:outline-offset-1 peer-focus-visible:outline-ring peer-disabled:opacity-50"><choice.icon aria-hidden="true" class="size-3.5 transition-[rotate,scale] duration-200 ease-snappy" /><span>{choice.label}</span></span>
</label>)}
</div>
<span role="status" data-theme-status class="sr-only"></span>
</fieldset>
<script>
function initThemeSwitches() {
document.querySelectorAll<HTMLElement>("[data-haze-theme-switch]").forEach(root => {
if (root.hasAttribute("data-enhanced")) return;
const choices = Array.from(root.querySelectorAll<HTMLInputElement>("input[type=radio]"));
const target = root.dataset.target ? document.getElementById(root.dataset.target) : document.documentElement;
const status = root.querySelector<HTMLElement>("[data-theme-status]");
if (!target || choices.length === 0) return;
const media = matchMedia("(prefers-color-scheme: dark)");
const apply = (announce = false) => {
const value = choices.find(input => input.checked)?.value ?? "dark";
const theme = value === "system" ? media.matches ? "dark" : "light" : value;
target.dataset.theme = theme;
target.classList.toggle("dark", theme === "dark");
target.style.colorScheme = theme;
if (announce && status) status.textContent = `Appearance: ${value}${value === "system" ? ` (${theme})` : ""}.`;
root.dispatchEvent(new CustomEvent("haze:theme-change", { bubbles: true, detail: { value, theme, target } }));
if (announce && root.dataset.storageKey) { try { localStorage.setItem(root.dataset.storageKey, value); } catch { /* Storage may be unavailable. */ } }
};
if (root.dataset.storageKey) {
try { const saved = localStorage.getItem(root.dataset.storageKey); choices.forEach(input => { if (input.value === saved) input.checked = true; }); } catch { /* Use the supplied default. */ }
}
choices.forEach(input => input.addEventListener("change", () => {
const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
const pill = input.nextElementSibling as HTMLElement | null;
if (target === document.documentElement && !reduced && "startViewTransition" in document) {
const r = (pill ?? root).getBoundingClientRect();
const x = Math.round(r.left + r.width / 2);
const y = Math.round(r.top + r.height / 2);
const radius = Math.ceil(Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y)));
document.documentElement.style.setProperty("--theme-origin-x", `${x}px`);
document.documentElement.style.setProperty("--theme-origin-y", `${y}px`);
document.documentElement.style.setProperty("--theme-radius", `${radius}px`);
document.documentElement.dataset.themeMotion = "reveal";
const vt = (document as Document & { startViewTransition: (cb: () => void) => { finished: Promise<void> } }).startViewTransition(() => apply(true));
vt.finished.finally(() => { delete document.documentElement.dataset.themeMotion; });
} else {
apply(true);
}
if (!reduced) pill?.querySelector("svg")?.animate([{ rotate: "-20deg", scale: ".85" }, { rotate: "0deg", scale: "1" }], { duration: 200 });
}));
media.addEventListener("change", () => { if (root.isConnected) apply(); });
root.setAttribute("data-enhanced", "");
apply();
});
}
initThemeSwitches();
if (!document.documentElement.hasAttribute("data-haze-theme-switch-listener")) {
document.documentElement.setAttribute("data-haze-theme-switch-listener", "");
document.addEventListener("astro:page-load", initThemeSwitches);
}
</script>When to use
- People need an explicit light, dark or system appearance preference
- A settings preview should change appearance without affecting the entire document
When not to use
- Use switch for a binary preference unrelated to appearance
- A full light palette must be supplied by the application; this control does not invent theme colors
Installation
Add the Haze registry to components.json once, then install Theme switch with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/theme-switchnpx shadcn@latest add @haze/theme-switchyarn dlx shadcn@latest add @haze/theme-switchbunx --bun shadcn@latest add @haze/theme-switchFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller-supplied prefix for this component and its related elements. |
| name | string | id | Form submission name. |
| label | string | "Appearance" | Legend naming the appearance choices. |
| value | "light" | "dark" | "system" | "dark" | Initial preference before optional stored settings. |
| target | string | – | Element ID to receive data-theme, dark class and color-scheme; defaults to the document root. |
| storageKey | string | – | Optional localStorage key; omitted means no persistence. |
| class | string | – | Additional classes for the component root. |
| ...attributes | native control attributes | – | Other attributes are forwarded to the real form control. |
Keyboard interactions
- Tab, arrow keys, Space
- Reach the radio group, move between appearance choices and select one.
Accessibility
- The three choices are native radios in a named fieldset and submit even without scripts.
- The host supplies its light and dark token rules; haze:theme-change reports the selected preference and resolved theme.
- Initialization and system appearance changes do not animate the control.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Theme switch" with `npx shadcn@latest add @haze/theme-switch`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ThemeSwitch from "@/components/haze/ui/theme-switch.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/theme-switch.md
Customize with real content
Adapt the Haze theme-switch ui for our product. Replace the demo values of these props with our real content: id, name, label, value, target, storageKey, class, ...attributes. Keep the layout, the heading level rules and these accessibility details: The three choices are native radios in a named fieldset and submit even without scripts. The host supplies its light and dark token rules; haze:theme-change reports the selected preference and resolved theme. Initialization and system appearance changes do not animate the control. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using theme-switch, check it fits: use it when people need an explicit light, dark or system appearance preference; a settings preview should change appearance without affecting the entire document. Avoid it when use switch for a binary preference unrelated to appearance; a full light palette must be supplied by the application; this control does not invent theme colors. Alternatives: @haze/switch, @haze/radio-group.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.