# Theme switch

> A light, dark and system radio group that applies appearance to a chosen target and optionally remembers it.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/theme-switch`
- File: `src/components/haze/ui/theme-switch.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/theme-switch

## Use when
- People need an explicit light, dark or system appearance preference
- A settings preview should change appearance without affecting the entire document

## Avoid 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
- [switch](https://hazeui.com/ui/switch.md)
- [radio-group](https://hazeui.com/ui/radio-group.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller-supplied prefix for this component and its related elements. |
| name | `string` | id | no | Form submission name. |
| label | `string` | "Appearance" | no | Legend naming the appearance choices. |
| value | `"light" \| "dark" \| "system"` | "dark" | no | Initial preference before optional stored settings. |
| target | `string` |  | no | Element ID to receive data-theme, dark class and color-scheme; defaults to the document root. |
| storageKey | `string` |  | no | Optional localStorage key; omitted means no persistence. |
| class | `string` |  | no | Additional classes for the component root. |
| ...attributes | `native control attributes` |  | no | Other attributes are forwarded to the real form control. |

## 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.
- Key Tab, arrow keys, Space: Reach the radio group, move between appearance choices and select one.

## Agent prompts

### 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": "https://hazeui.com/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: https://hazeui.com/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.

## Example requests that should lead here
- Add light, dark and system appearance radios that target a settings preview.

## Source

```astro
---
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>
```
