# Theme Toggle

Light and dark theme switch with six distinct icon animations: rotate, morph, flip, slide, eclipse, and spring.

- Category: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/theme-toggle.json
- CLI: `npx markasui@latest add theme-toggle`

## When to use

A light and dark switch in a site header, settings page, or app shell that uses the dark class from markas.css.

- Use one storageKey for the whole site so every toggle and the head script agree
- Set the dark class in a small head script before paint to avoid a flash of the wrong theme
- Pick one animation per site and keep it the same in every toggle

## Code

### Blade

Save at `resources/views/components/markas/theme-toggle.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'animation' => 'rotate',
    'variant' => 'ghost',
    'size' => 'md',
    'theme' => null,
    'storageKey' => 'markas-theme',
    'showText' => false,
    'lightLabel' => 'Switch to light theme',
    'darkLabel' => 'Switch to dark theme',
])

@php
    $base = 'group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50';
    $variants = [
        'ghost' => 'text-ink hover:bg-subtle',
        'outline' => 'border border-line bg-surface text-ink hover:bg-subtle',
        'solid' => 'bg-primary text-on-primary hover:bg-primary-strong',
    ];
    // Per size: icon-only button, button with text, icon.
    $sizes = [
        'sm' => ['size-8 rounded-md', 'h-8 rounded-md px-3 text-sm', 'size-4'],
        'md' => ['size-10 rounded-lg', 'h-10 rounded-lg px-4 text-sm', 'size-5'],
        'lg' => ['size-12 rounded-lg', 'h-12 rounded-lg px-6 text-base', 'size-6'],
    ];
    // Parts scale and rotate around the icon center.
    $icon = '**:origin-[12px_12px]';
    // Moon and stars start hidden (the light look); the keyframes show them.
    $hidden = 'opacity-0';
    $moonPath = 'M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z';
    $starPaths = ['M18 2v4m-2-2h4', 'M21.5 9h0', 'M14.5 1.5h0'];
    $srOnly = 'sr-only';
    // Keyframes from light to dark (reverse for dark to light), the same as React and Vue:
    // "selector inside the button|property:value,value;property:...|stagger ms".
    $moves = [
        'rotate' => [
            'g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0',
            'g>path|scale:1,1.6,1.6,0',
            'svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1',
        ],
        'morph' => [
            'g>circle|scale:1,1.6',
            'mask>circle|translate:24px -12px,15.5px -3.5px',
            'g>path|scale:1,0;opacity:1,0|50',
        ],
        'flip' => [
            'svg|transform:perspective(60px) rotateY(0),perspective(60px) rotateY(90deg),perspective(60px) rotateY(-90deg),perspective(60px) rotateY(0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1',
            'g|opacity:1,1,0,0;offset:0,.5,.5,1',
            'svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1',
        ],
        'slide' => [
            'g|translate:0,0 24px',
            'svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1',
        ],
        'eclipse' => [
            'mask>circle|translate:-6px 0,13.5px -1.5px',
            'g>path|scale:1,1.7,.75;opacity:1,.3,.4',
        ],
        'spring' => [
            'svg|scale:1,.6,1.15,.95,1',
            'g|opacity:1,1,0,0',
            'svg>:nth-child(3)|opacity:0,0,1,1',
            'svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120',
        ],
    ];

    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-theme-toggle|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $maskId = 'mask'.hash('xxh32', $idKey.$idIndex);
@endphp

{{-- Same logic as React and Vue: saved choice, then the page dark class, then the system setting. --}}
<button
    x-data="{
        state: null,
        requested: null,
        key: @js($storageKey),
        moves: @js($moves[$animation]),
        page: () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light'),
        setDark: (theme) => document.documentElement.classList.toggle('dark', theme === 'dark'),
        {{-- mode 0 jumps to the look, 1 animates the switch, 2 plays there and back (demo). --}}
        play(toDark, mode) {
            const still = mode === 0 || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
            for (const move of this.moves) {
                const [selector, frames, stagger = 0] = move.split('|');
                const keyframes = Object.fromEntries(frames.split(';').map((frame) => {
                    const [property, values] = frame.split(':');
                    return [property, values.split(',')];
                }));
                this.$root.querySelectorAll(selector).forEach((part, i) => part.animate(keyframes, {
                    duration: still ? 0 : +stagger ? 325 : 650,
                    delay: still ? 0 : i * +stagger,
                    fill: 'both',
                    iterations: mode === 2 ? 2 : 1,
                    direction: ['reverse', 'normal', 'alternate-reverse', 'alternate'][+toDark + (mode === 2 ? 2 : 0)],
                }));
            }
        },
        show(theme) {
            if (theme === this.state) return;
            this.state = theme;
            this.play(theme === 'dark', theme === this.requested ? 1 : 0);
            this.requested = null;
        },
        init() {
            let saved = null;
            try {
                saved = localStorage.getItem(this.key);
            } catch {}
            const target = @js($theme) ?? (saved === 'light' || saved === 'dark' ? saved : this.page() === 'dark' || window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
            if (target !== this.page()) this.setDark(target);
            this.show(this.page());
            this.observer = new MutationObserver(() => this.show(this.page()));
            this.observer.observe(document.documentElement, { attributeFilter: ['class'] });
        },
        destroy() {
            this.observer?.disconnect();
        },
        toggle() {
            const theme = this.page() === 'dark' ? 'light' : 'dark';
            this.requested = theme;
            this.setDark(theme);
            try {
                localStorage.setItem(this.key, theme);
            } catch {}
            document.dispatchEvent(new CustomEvent('markas-theme-change', { detail: theme }));
        },
    }"
    x-on:click="toggle()"
    x-on:markas-theme-demo.document="play(page() !== 'dark', 2)"
    x-bind:data-state="state"
    {{ $attributes->merge(['type' => 'button'])->class([$base, $variants[$variant], $sizes[$size][$showText ? 1 : 0]]) }}
>
    {{-- The icon parts are animated from JavaScript, so Livewire skips them when it re-renders. --}}
    <svg class="{{ $sizes[$size][2] }} {{ $icon }}" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" wire:ignore>
        <mask id="{{ $maskId }}">
            <rect width="24" height="24" fill="white" />
            <circle cy="12" r="5" fill="black" />
        </mask>
        <g>
            <circle cx="12" cy="12" r="4.5" stroke="none" mask="url(#{{ $maskId }})" />
            @for ($ray = 0; $ray < 8; $ray++)
                <path style="rotate: {{ $ray * 45 }}deg" d="M12 2v2" />
            @endfor
        </g>
        <path class="{{ $hidden }}" d="{{ $moonPath }}" />
        @foreach ($starPaths as $starPath)
            <path class="{{ $hidden }}" d="{{ $starPath }}" />
        @endforeach
    </svg>
    <span class="{{ $showText ? '' : $srOnly }}" x-text="state === 'dark' ? @js($lightLabel) : @js($darkLabel)">{{ $darkLabel }}</span>
</button>
```

```blade
<x-markas.theme-toggle />

<x-markas.theme-toggle animation="eclipse" variant="outline" size="sm" />

<x-markas.theme-toggle :show-text="true" dark-label="Dark mode" light-label="Light mode" animation="flip" />
```

### React

Save at `src/components/markas/ThemeToggle.tsx`. No extra dependencies.

```tsx
"use client";

import {
  useEffect,
  useId,
  useRef,
  useSyncExternalStore,
  type ComponentProps,
  type MouseEvent,
} from "react";

const base =
  "group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
const variants = {
  ghost: "text-ink hover:bg-subtle",
  outline: "border border-line bg-surface text-ink hover:bg-subtle",
  solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
  sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
  md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
  lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const rays = [0, 45, 90, 135, 180, 225, 270, 315];
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";

/**
 * Keyframes from light to dark; dark to light plays them in reverse. Every part that
 * differs between the themes is animated, and the last frame stays (fill both).
 * Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
 */
const turn = "perspective(60px) rotateY(";
const moves = {
  rotate: [
    "g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
    "g>path|scale:1,1.6,1.6,0",
    "svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
  ],
  morph: [
    "g>circle|scale:1,1.6",
    "mask>circle|translate:24px -12px,15.5px -3.5px",
    "g>path|scale:1,0;opacity:1,0|50",
  ],
  flip: [
    `svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
    "g|opacity:1,1,0,0;offset:0,.5,.5,1",
    "svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
  ],
  slide: [
    "g|translate:0,0 24px",
    "svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
  ],
  eclipse: [
    "mask>circle|translate:-6px 0,13.5px -1.5px",
    "g>path|scale:1,1.7,.75;opacity:1,.3,.4",
  ],
  spring: [
    "svg|scale:1,.6,1.15,.95,1",
    "g|opacity:1,1,0,0",
    "svg>:nth-child(3)|opacity:0,0,1,1",
    "svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
  ],
};
const DURATION = 650;
/** Indexed by toDark + 2 for a demo, which plays there and back. */
const directions = [
  "reverse",
  "normal",
  "alternate-reverse",
  "alternate",
] as const;
const SET = 0;
const SWITCH = 1;
const DEMO = 2;

type Theme = "light" | "dark";
type Animation = keyof typeof moves;

const html = () => document.documentElement;
const pageTheme = (): Theme =>
  html().classList.contains("dark") ? "dark" : "light";
const subscribe = (onChange: () => void) => {
  const observer = new MutationObserver(onChange);
  observer.observe(html(), { attributeFilter: ["class"] });
  return () => observer.disconnect();
};
const setDark = (theme: Theme) =>
  html().classList.toggle("dark", theme === "dark");

/** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
function play(
  button: HTMLElement,
  animation: Animation,
  toDark: boolean,
  mode: number,
) {
  const still =
    mode === SET ||
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  for (const move of moves[animation]) {
    const [selector = "", frames = "", stagger = 0] = move.split("|");
    const keyframes = Object.fromEntries(
      frames.split(";").map((frame) => {
        const [property, values = ""] = frame.split(":");
        return [property, values.split(",")];
      }),
    ) as Parameters<HTMLElement["animate"]>[0];
    button.querySelectorAll(selector).forEach((part, i) =>
      part.animate(keyframes, {
        duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
        delay: still ? 0 : i * +stagger,
        fill: "both",
        iterations: mode === DEMO ? 2 : 1,
        direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
      }),
    );
  }
}

/** Saved choice first, then a dark class the page already set, then the system setting. */
function readTheme(storageKey: string): Theme {
  let saved: string | null = null;
  try {
    saved = localStorage.getItem(storageKey);
  } catch {
    // Storage blocked: fall back to the page and the system setting.
  }
  if (saved === "light" || saved === "dark") return saved;
  return pageTheme() === "dark" ||
    window.matchMedia?.("(prefers-color-scheme: dark)").matches
    ? "dark"
    : "light";
}

export type ThemeToggleProps = Omit<ComponentProps<"button">, "children"> & {
  animation?: Animation;
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  /** Controlled theme. Leave empty to read localStorage and the system setting. */
  theme?: Theme;
  storageKey?: string;
  /** Show the label as visible text next to the icon. */
  showText?: boolean;
  lightLabel?: string;
  darkLabel?: string;
  onThemeChange?: (theme: Theme) => void;
};

export function ThemeToggle({
  animation = "rotate",
  variant = "ghost",
  size = "md",
  theme,
  storageKey = "markas-theme",
  showText = false,
  lightLabel = "Switch to light theme",
  darkLabel = "Switch to dark theme",
  onThemeChange,
  className,
  onClick,
  ...props
}: ThemeToggleProps) {
  const maskId = `mask${useId()}`;
  const button = useRef<HTMLButtonElement>(null);
  /** The theme a click asked for: reaching it animates, any other change jumps. */
  const requested = useRef<Theme>(undefined);
  // Follow the html class, so every toggle on the page and outside changes stay in sync.
  const state = useSyncExternalStore(subscribe, pageTheme, () => undefined);

  // Mount and controlled changes: put the page on the wanted theme. The parent saves a controlled theme.
  useEffect(() => {
    const target = theme ?? readTheme(storageKey);
    if (target !== pageTheme()) setDark(target);
    // Only a new controlled theme should run this again.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [theme]);

  // Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere.
  useEffect(() => {
    if (!state || !button.current) return;
    const mode = state === requested.current ? SWITCH : SET;
    requested.current = undefined;
    play(button.current, animation, state === "dark", mode);
  }, [state, animation]);

  // "Play all" demos: document.dispatchEvent(new Event("markas-theme-demo")).
  useEffect(() => {
    const demo = () =>
      button.current &&
      play(button.current, animation, pageTheme() !== "dark", DEMO);
    document.addEventListener("markas-theme-demo", demo);
    return () => document.removeEventListener("markas-theme-demo", demo);
  }, [animation]);

  const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented) return;
    const next = pageTheme() === "dark" ? "light" : "dark";
    requested.current = next;
    if (theme === undefined) {
      setDark(next);
      try {
        localStorage.setItem(storageKey, next);
      } catch {
        // Storage blocked: the theme still applies until the page closes.
      }
      document.dispatchEvent(
        new CustomEvent("markas-theme-change", { detail: next }),
      );
    }
    onThemeChange?.(next);
  };

  return (
    <button
      ref={button}
      type="button"
      data-state={state}
      onClick={handleClick}
      className={`${base} ${variants[variant]} ${sizes[size][+showText]} ${className ?? ""}`}
      {...props}
    >
      <svg
        className={`${sizes[size][2]} ${icon}`}
        viewBox="0 0 24 24"
        fill="currentColor"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        aria-hidden="true"
      >
        <mask id={maskId}>
          <rect width="24" height="24" fill="white" />
          <circle cy="12" r="5" fill="black" />
        </mask>
        <g>
          <circle
            cx="12"
            cy="12"
            r="4.5"
            stroke="none"
            mask={`url(#${maskId})`}
          />
          {rays.map((deg) => (
            <path key={deg} style={{ rotate: `${deg}deg` }} d="M12 2v2" />
          ))}
        </g>
        <path className={hidden} d={moonPath} />
        {starPaths.map((d) => (
          <path key={d} className={hidden} d={d} />
        ))}
      </svg>
      <span className={showText ? undefined : srOnly}>
        {state === "dark" ? lightLabel : darkLabel}
      </span>
    </button>
  );
}
```

```tsx
import { ThemeToggle } from "@/components/markas/ThemeToggle";

<ThemeToggle />
<ThemeToggle animation="eclipse" variant="outline" size="sm" />
<ThemeToggle showText darkLabel="Dark mode" lightLabel="Light mode" animation="flip" onThemeChange={(theme) => console.log(theme)} />
```

### Vue

Save at `src/components/markas/ThemeToggle.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import {
  onBeforeUnmount,
  onMounted,
  ref,
  useId,
  useTemplateRef,
  watch,
  watchEffect,
} from "vue";

const variants = {
  ghost: "text-ink hover:bg-subtle",
  outline: "border border-line bg-surface text-ink hover:bg-subtle",
  solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
  sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
  md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
  lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";

/**
 * Keyframes from light to dark; dark to light plays them in reverse. Every part that
 * differs between the themes is animated, and the last frame stays (fill both).
 * Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
 */
const turn = "perspective(60px) rotateY(";
const moves = {
  rotate: [
    "g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
    "g>path|scale:1,1.6,1.6,0",
    "svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
  ],
  morph: [
    "g>circle|scale:1,1.6",
    "mask>circle|translate:24px -12px,15.5px -3.5px",
    "g>path|scale:1,0;opacity:1,0|50",
  ],
  flip: [
    `svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
    "g|opacity:1,1,0,0;offset:0,.5,.5,1",
    "svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
  ],
  slide: [
    "g|translate:0,0 24px",
    "svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
  ],
  eclipse: [
    "mask>circle|translate:-6px 0,13.5px -1.5px",
    "g>path|scale:1,1.7,.75;opacity:1,.3,.4",
  ],
  spring: [
    "svg|scale:1,.6,1.15,.95,1",
    "g|opacity:1,1,0,0",
    "svg>:nth-child(3)|opacity:0,0,1,1",
    "svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
  ],
};
const DURATION = 650;
/** Indexed by toDark + 2 for a demo, which plays there and back. */
const directions = [
  "reverse",
  "normal",
  "alternate-reverse",
  "alternate",
] as const;
const SET = 0;
const SWITCH = 1;
const DEMO = 2;

type Theme = "light" | "dark";

const props = withDefaults(
  defineProps<{
    animation?: keyof typeof moves;
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** Controlled theme. Leave empty to read localStorage and the system setting. */
    theme?: Theme;
    storageKey?: string;
    /** Show the label as visible text next to the icon. */
    showText?: boolean;
    lightLabel?: string;
    darkLabel?: string;
  }>(),
  {
    animation: "rotate",
    variant: "ghost",
    size: "md",
    theme: undefined,
    storageKey: "markas-theme",
    showText: false,
    lightLabel: "Switch to light theme",
    darkLabel: "Switch to dark theme",
  },
);
const emit = defineEmits<{ change: [theme: Theme] }>();

const base =
  "group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";

const maskId = `mask${useId()}`;
const buttonRef = useTemplateRef<HTMLButtonElement>("buttonRef");
const state = ref<Theme>();
/** The theme a click asked for: reaching it animates, any other change jumps. */
let requested: Theme | undefined;
let observer: MutationObserver | undefined;

const html = () => document.documentElement;
const pageTheme = (): Theme =>
  html().classList.contains("dark") ? "dark" : "light";
const setDark = (theme: Theme) =>
  html().classList.toggle("dark", theme === "dark");

/** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
function play(
  button: HTMLElement,
  animation: keyof typeof moves,
  toDark: boolean,
  mode: number,
) {
  const still =
    mode === SET ||
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  for (const move of moves[animation]) {
    const [selector = "", frames = "", stagger = 0] = move.split("|");
    const keyframes = Object.fromEntries(
      frames.split(";").map((frame) => {
        const [property, values = ""] = frame.split(":");
        return [property, values.split(",")];
      }),
    ) as Parameters<HTMLElement["animate"]>[0];
    button.querySelectorAll(selector).forEach((part, i) =>
      part.animate(keyframes, {
        duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
        delay: still ? 0 : i * +stagger,
        fill: "both",
        iterations: mode === DEMO ? 2 : 1,
        direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
      }),
    );
  }
}

// "Play all" demos: document.dispatchEvent(new Event("markas-theme-demo")).
const demo = () =>
  buttonRef.value &&
  play(buttonRef.value, props.animation, pageTheme() !== "dark", DEMO);

onMounted(() => {
  // Now and on controlled changes: put the page on the wanted theme. The parent saves a controlled theme.
  // Saved choice first, then a dark class the page already set, then the system setting.
  watchEffect(() => {
    let saved: string | null = null;
    try {
      saved = localStorage.getItem(props.storageKey);
    } catch {
      // Storage blocked: fall back to the page and the system setting.
    }
    const target: Theme =
      props.theme ??
      (saved === "light" || saved === "dark"
        ? saved
        : pageTheme() === "dark" ||
            window.matchMedia?.("(prefers-color-scheme: dark)").matches
          ? "dark"
          : "light");
    if (target !== pageTheme()) setDark(target);
    state.value = pageTheme();
  });
  // Follow the html class, so every toggle on the page and outside changes stay in sync.
  observer = new MutationObserver(() => (state.value = pageTheme()));
  observer.observe(html(), { attributeFilter: ["class"] });
  document.addEventListener("markas-theme-demo", demo);
});
onBeforeUnmount(() => {
  observer?.disconnect();
  document.removeEventListener("markas-theme-demo", demo);
});

// Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere.
watch(state, (theme) => {
  if (!theme || !buttonRef.value) return;
  const mode = theme === requested ? SWITCH : SET;
  requested = undefined;
  play(buttonRef.value, props.animation, theme === "dark", mode);
});

function toggle() {
  const next = pageTheme() === "dark" ? "light" : "dark";
  requested = next;
  if (props.theme === undefined) {
    setDark(next);
    try {
      localStorage.setItem(props.storageKey, next);
    } catch {
      // Storage blocked: the theme still applies until the page closes.
    }
    document.dispatchEvent(
      new CustomEvent("markas-theme-change", { detail: next }),
    );
  }
  emit("change", next);
}
</script>

<template>
  <button
    ref="buttonRef"
    type="button"
    :data-state="state"
    :class="[base, variants[props.variant], sizes[props.size][+props.showText]]"
    @click="toggle"
  >
    <svg
      :class="[sizes[props.size][2], icon]"
      viewBox="0 0 24 24"
      fill="currentColor"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      aria-hidden="true"
    >
      <mask :id="maskId">
        <rect width="24" height="24" fill="white" />
        <circle cy="12" r="5" fill="black" />
      </mask>
      <g>
        <circle
          cx="12"
          cy="12"
          r="4.5"
          stroke="none"
          :mask="`url(#${maskId})`"
        />
        <path
          v-for="ray in 8"
          :key="ray"
          :style="{ rotate: `${ray * 45}deg` }"
          d="M12 2v2"
        />
      </g>
      <path :class="hidden" :d="moonPath" />
      <path v-for="d in starPaths" :key="d" :class="hidden" :d="d" />
    </svg>
    <span :class="props.showText ? undefined : srOnly">{{
      state === "dark" ? props.lightLabel : props.darkLabel
    }}</span>
  </button>
</template>
```

```vue
<script setup lang="ts">
import ThemeToggle from "@/components/markas/ThemeToggle.vue";
</script>

<template>
  <ThemeToggle />
  <ThemeToggle animation="eclipse" variant="outline" size="sm" />
  <ThemeToggle
    show-text
    dark-label="Dark mode"
    light-label="Light mode"
    animation="flip"
    @change="(theme) => console.log(theme)"
  />
</template>
```

### Svelte

Save at `src/lib/components/markas/ThemeToggle.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import type { HTMLButtonAttributes } from "svelte/elements";

  const base =
    "group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
  const variants = {
    ghost: "text-ink hover:bg-subtle",
    outline: "border border-line bg-surface text-ink hover:bg-subtle",
    solid: "bg-primary text-on-primary hover:bg-primary-strong",
  };
  /** Per size: icon-only button, button with text, icon. */
  const sizes = {
    sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
    md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
    lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
  };
  /** Parts scale and rotate around the icon center. */
  const icon = "**:origin-[12px_12px]";
  /** Moon and stars start hidden (the light look); the keyframes show them. */
  const hidden = "opacity-0";
  const rays = [0, 45, 90, 135, 180, 225, 270, 315];
  const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
  const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
  const srOnly = "sr-only";

  /**
   * Keyframes from light to dark; dark to light plays them in reverse. Every part that
   * differs between the themes is animated, and the last frame stays (fill both).
   * Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
   */
  const turn = "perspective(60px) rotateY(";
  const moves = {
    rotate: [
      "g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
      "g>path|scale:1,1.6,1.6,0",
      "svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
    ],
    morph: [
      "g>circle|scale:1,1.6",
      "mask>circle|translate:24px -12px,15.5px -3.5px",
      "g>path|scale:1,0;opacity:1,0|50",
    ],
    flip: [
      `svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
      "g|opacity:1,1,0,0;offset:0,.5,.5,1",
      "svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
    ],
    slide: [
      "g|translate:0,0 24px",
      "svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
    ],
    eclipse: [
      "mask>circle|translate:-6px 0,13.5px -1.5px",
      "g>path|scale:1,1.7,.75;opacity:1,.3,.4",
    ],
    spring: [
      "svg|scale:1,.6,1.15,.95,1",
      "g|opacity:1,1,0,0",
      "svg>:nth-child(3)|opacity:0,0,1,1",
      "svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
    ],
  };
  const DURATION = 650;
  /** Indexed by toDark + 2 for a demo, which plays there and back. */
  const directions = [
    "reverse",
    "normal",
    "alternate-reverse",
    "alternate",
  ] as const;
  const SET = 0;
  const SWITCH = 1;
  const DEMO = 2;

  type Theme = "light" | "dark";
  type Animation = keyof typeof moves;

  const html = () => document.documentElement;
  const pageTheme = (): Theme =>
    html().classList.contains("dark") ? "dark" : "light";
  const setDark = (theme: Theme) =>
    html().classList.toggle("dark", theme === "dark");

  /** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
  function play(
    button: HTMLElement,
    animation: Animation,
    toDark: boolean,
    mode: number,
  ) {
    const still =
      mode === SET ||
      window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
    for (const move of moves[animation]) {
      const [selector = "", frames = "", stagger = 0] = move.split("|");
      const keyframes = Object.fromEntries(
        frames.split(";").map((frame) => {
          const [property, values = ""] = frame.split(":");
          return [property, values.split(",")];
        }),
      ) as Parameters<HTMLElement["animate"]>[0];
      button.querySelectorAll(selector).forEach((part, i) =>
        part.animate(keyframes, {
          duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
          delay: still ? 0 : i * +stagger,
          fill: "both",
          iterations: mode === DEMO ? 2 : 1,
          direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
        }),
      );
    }
  }

  /** Saved choice first, then a dark class the page already set, then the system setting. */
  function readTheme(storageKey: string): Theme {
    let saved: string | null = null;
    try {
      saved = localStorage.getItem(storageKey);
    } catch {
      // Storage blocked: fall back to the page and the system setting.
    }
    if (saved === "light" || saved === "dark") return saved;
    return pageTheme() === "dark" ||
      window.matchMedia?.("(prefers-color-scheme: dark)").matches
      ? "dark"
      : "light";
  }

  type Props = Omit<HTMLButtonAttributes, "children"> & {
    animation?: Animation;
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** Controlled theme. Leave empty to read localStorage and the system setting. */
    theme?: Theme;
    storageKey?: string;
    /** Show the label as visible text next to the icon. */
    showText?: boolean;
    lightLabel?: string;
    darkLabel?: string;
    onThemeChange?: (theme: Theme) => void;
  };

  let {
    animation = "rotate",
    variant = "ghost",
    size = "md",
    theme,
    storageKey = "markas-theme",
    showText = false,
    lightLabel = "Switch to light theme",
    darkLabel = "Switch to dark theme",
    onThemeChange,
    class: className,
    onclick,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const maskId = `mask${generatedId}`;
  let button = $state<HTMLButtonElement>();
  let current = $state<Theme>();
  /** The theme a click asked for: reaching it animates, any other change jumps. */
  let requested: Theme | undefined;

  // Follow the html class, so every toggle on the page and outside changes stay in sync.
  $effect(() => {
    current = pageTheme();
    const observer = new MutationObserver(() => (current = pageTheme()));
    observer.observe(html(), { attributeFilter: ["class"] });
    return () => observer.disconnect();
  });

  // Mount and controlled changes: put the page on the wanted theme. The parent saves a controlled theme.
  $effect(() => {
    const target = theme ?? readTheme(storageKey);
    if (target !== pageTheme()) setDark(target);
  });

  // Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere.
  $effect(() => {
    const shown = current;
    const name = animation;
    if (!shown || !button) return;
    const mode = shown === requested ? SWITCH : SET;
    requested = undefined;
    play(button, name, shown === "dark", mode);
  });

  // "Play all" demos: document.dispatchEvent(new Event("markas-theme-demo")).
  $effect(() => {
    const name = animation;
    const demo = () =>
      button && play(button, name, pageTheme() !== "dark", DEMO);
    document.addEventListener("markas-theme-demo", demo);
    return () => document.removeEventListener("markas-theme-demo", demo);
  });

  function handleClick(
    event: MouseEvent & { currentTarget: EventTarget & HTMLButtonElement },
  ) {
    onclick?.(event);
    if (event.defaultPrevented) return;
    const next = pageTheme() === "dark" ? "light" : "dark";
    requested = next;
    if (theme === undefined) {
      setDark(next);
      try {
        localStorage.setItem(storageKey, next);
      } catch {
        // Storage blocked: the theme still applies until the page closes.
      }
      document.dispatchEvent(
        new CustomEvent("markas-theme-change", { detail: next }),
      );
    }
    onThemeChange?.(next);
  }
</script>

<button
  bind:this={button}
  type="button"
  data-state={current}
  onclick={handleClick}
  class={[base, variants[variant], sizes[size][+showText], className]}
  {...rest}
>
  <svg
    class={[sizes[size][2], icon]}
    viewBox="0 0 24 24"
    fill="currentColor"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    aria-hidden="true"
  >
    <mask id={maskId}>
      <rect width="24" height="24" fill="white" />
      <circle cy="12" r="5" fill="black" />
    </mask>
    <g>
      <circle cx="12" cy="12" r="4.5" stroke="none" mask={`url(#${maskId})`} />
      {#each rays as deg (deg)}
        <path style:rotate={`${deg}deg`} d="M12 2v2" />
      {/each}
    </g>
    <path class={hidden} d={moonPath} />
    {#each starPaths as d (d)}
      <path class={hidden} {d} />
    {/each}
  </svg>
  <span class={showText ? undefined : srOnly}
    >{current === "dark" ? lightLabel : darkLabel}</span
  >
</button>
```

```svelte
<script lang="ts">
  import ThemeToggle from "$lib/components/markas/ThemeToggle.svelte";
</script>

<ThemeToggle animation="morph" variant="outline" />
```

### Astro

Save at `src/components/markas/ThemeToggle.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const base =
  "group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
const variants = {
  ghost: "text-ink hover:bg-subtle",
  outline: "border border-line bg-surface text-ink hover:bg-subtle",
  solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
  sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
  md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
  lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const rays = [0, 45, 90, 135, 180, 225, 270, 315];
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";

type Props = Omit<HTMLAttributes<"button">, "children"> & {
  animation?: "rotate" | "morph" | "flip" | "slide" | "eclipse" | "spring";
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  /** Theme to apply on load. Leave empty to read localStorage and the system setting. */
  theme?: "light" | "dark";
  storageKey?: string;
  /** Show the label as visible text next to the icon. */
  showText?: boolean;
  lightLabel?: string;
  darkLabel?: string;
};

const {
  animation = "rotate",
  variant = "ghost",
  size = "md",
  theme,
  storageKey = "markas-theme",
  showText = false,
  lightLabel = "Switch to light theme",
  darkLabel = "Switch to dark theme",
  class: className,
  ...rest
} = Astro.props;
const maskId = `mask-markas-theme-toggle-${crypto.randomUUID().slice(0, 8)}`;
---

<markas-theme-toggle
  class="contents"
  data-animation={animation}
  data-theme={theme}
  data-storage-key={storageKey}
  data-light-label={lightLabel}
  data-dark-label={darkLabel}
>
  <button
    type="button"
    class:list={[base, variants[variant], sizes[size][+showText], className]}
    {...rest}
  >
    <svg
      class:list={[sizes[size][2], icon]}
      viewBox="0 0 24 24"
      fill="currentColor"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      aria-hidden="true"
    >
      <mask id={maskId}>
        <rect width="24" height="24" fill="white"></rect>
        <circle cy="12" r="5" fill="black"></circle>
      </mask>
      <g>
        <circle cx="12" cy="12" r="4.5" stroke="none" mask={`url(#${maskId})`}></circle>
        {rays.map((deg) => <path style={`rotate: ${deg}deg`} d="M12 2v2"></path>)}
      </g>
      <path class={hidden} d={moonPath}></path>
      {starPaths.map((d) => <path class={hidden} d={d}></path>)}
    </svg>
    <span class={showText ? undefined : srOnly}>{darkLabel}</span>
  </button>
</markas-theme-toggle>

<script>
  /**
   * Keyframes from light to dark; dark to light plays them in reverse. Every part that
   * differs between the themes is animated, and the last frame stays (fill both).
   * Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
   */
  const turn = "perspective(60px) rotateY(";
  const moves = {
    rotate: [
      "g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
      "g>path|scale:1,1.6,1.6,0",
      "svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
    ],
    morph: [
      "g>circle|scale:1,1.6",
      "mask>circle|translate:24px -12px,15.5px -3.5px",
      "g>path|scale:1,0;opacity:1,0|50",
    ],
    flip: [
      `svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
      "g|opacity:1,1,0,0;offset:0,.5,.5,1",
      "svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
    ],
    slide: [
      "g|translate:0,0 24px",
      "svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
    ],
    eclipse: [
      "mask>circle|translate:-6px 0,13.5px -1.5px",
      "g>path|scale:1,1.7,.75;opacity:1,.3,.4",
    ],
    spring: [
      "svg|scale:1,.6,1.15,.95,1",
      "g|opacity:1,1,0,0",
      "svg>:nth-child(3)|opacity:0,0,1,1",
      "svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
    ],
  };
  const DURATION = 650;
  /** Indexed by toDark + 2 for a demo, which plays there and back. */
  const directions = [
    "reverse",
    "normal",
    "alternate-reverse",
    "alternate",
  ] as const;
  const SET = 0;
  const SWITCH = 1;
  const DEMO = 2;

  type Theme = "light" | "dark";
  type Animation = keyof typeof moves;

  const html = () => document.documentElement;
  const pageTheme = (): Theme =>
    html().classList.contains("dark") ? "dark" : "light";
  const setDark = (theme: Theme) =>
    html().classList.toggle("dark", theme === "dark");

  /** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
  function play(
    button: HTMLElement,
    animation: Animation,
    toDark: boolean,
    mode: number,
  ) {
    const still =
      mode === SET ||
      window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
    for (const move of moves[animation]) {
      const [selector = "", frames = "", stagger = 0] = move.split("|");
      const keyframes = Object.fromEntries(
        frames.split(";").map((frame) => {
          const [property, values = ""] = frame.split(":");
          return [property, values.split(",")];
        }),
      ) as Parameters<HTMLElement["animate"]>[0];
      button.querySelectorAll(selector).forEach((part, i) =>
        part.animate(keyframes, {
          duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
          delay: still ? 0 : i * +stagger,
          fill: "both",
          iterations: mode === DEMO ? 2 : 1,
          direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
        }),
      );
    }
  }

  /** Saved choice first, then a dark class the page already set, then the system setting. */
  function readTheme(storageKey: string): Theme {
    let saved: string | null = null;
    try {
      saved = localStorage.getItem(storageKey);
    } catch {
      // Storage blocked: fall back to the page and the system setting.
    }
    if (saved === "light" || saved === "dark") return saved;
    return pageTheme() === "dark" ||
      window.matchMedia?.("(prefers-color-scheme: dark)").matches
      ? "dark"
      : "light";
  }


  /**
   * Per instance: saved choice first, then the page dark class, then the system setting. Each
   * toggle follows the html class, so every toggle on the page stays in sync, and a click
   * animates the switch it asked for.
   */
  class ThemeToggle extends HTMLElement {
    #requested: Theme | undefined;
    #shown: Theme | undefined;
    #stop = () => {};

    get #button() {
      return this.querySelector("button");
    }

    get #animation() {
      return (this.dataset.animation ?? "rotate") as Animation;
    }

    connectedCallback() {
      const button = this.#button;
      if (!button) return;
      const forced = this.dataset.theme;
      const target =
        forced === "light" || forced === "dark"
          ? forced
          : readTheme(this.dataset.storageKey ?? "markas-theme");
      if (target !== pageTheme()) setDark(target);
      this.#show();
      const observer = new MutationObserver(() => this.#show());
      observer.observe(html(), { attributeFilter: ["class"] });
      const click = (event: MouseEvent) => this.#toggle(event);
      const demo = () =>
        play(button, this.#animation, pageTheme() !== "dark", DEMO);
      button.addEventListener("click", click);
      document.addEventListener("markas-theme-demo", demo);
      this.#stop = () => {
        observer.disconnect();
        button.removeEventListener("click", click);
        document.removeEventListener("markas-theme-demo", demo);
      };
    }

    disconnectedCallback() {
      this.#stop();
    }

    /** Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere. */
    #show() {
      const button = this.#button;
      const theme = pageTheme();
      if (!button || theme === this.#shown) return;
      this.#shown = theme;
      button.dataset.state = theme;
      const label = button.querySelector("span");
      if (label)
        label.textContent =
          (theme === "dark"
            ? this.dataset.lightLabel
            : this.dataset.darkLabel) ?? "";
      const mode = theme === this.#requested ? SWITCH : SET;
      this.#requested = undefined;
      play(button, this.#animation, theme === "dark", mode);
    }

    #toggle(event: MouseEvent) {
      if (event.defaultPrevented) return;
      const next = pageTheme() === "dark" ? "light" : "dark";
      this.#requested = next;
      setDark(next);
      try {
        localStorage.setItem(this.dataset.storageKey ?? "markas-theme", next);
      } catch {
        // Storage blocked: the theme still applies until the page closes.
      }
      document.dispatchEvent(
        new CustomEvent("markas-theme-change", { detail: next }),
      );
    }
  }

  if (!customElements.get("markas-theme-toggle"))
    customElements.define("markas-theme-toggle", ThemeToggle);
</script>
```

```astro
---
import ThemeToggle from "@/components/markas/ThemeToggle.astro";
---

<ThemeToggle animation="morph" variant="outline" />
```

A small bundled script runs each toggle through the `markas-theme-toggle` element.

### Angular

Save at `src/app/markas/theme-toggle.component.ts`. No extra dependencies.

```ts
import {
  afterRenderEffect,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  DestroyRef,
  ElementRef,
  inject,
  input,
  output,
  signal,
} from "@angular/core";

const base =
  "group inline-flex shrink-0 items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50";
const variants = {
  ghost: "text-ink hover:bg-subtle",
  outline: "border border-line bg-surface text-ink hover:bg-subtle",
  solid: "bg-primary text-on-primary hover:bg-primary-strong",
};
/** Per size: icon-only button, button with text, icon. */
const sizes = {
  sm: ["size-8 rounded-md", "h-8 rounded-md px-3 text-sm", "size-4"],
  md: ["size-10 rounded-lg", "h-10 rounded-lg px-4 text-sm", "size-5"],
  lg: ["size-12 rounded-lg", "h-12 rounded-lg px-6 text-base", "size-6"],
};
/** Parts scale and rotate around the icon center. */
const icon = "**:origin-[12px_12px]";
/** Moon and stars start hidden (the light look); the keyframes show them. */
const hidden = "opacity-0";
const rays = [0, 45, 90, 135, 180, 225, 270, 315];
const moonPath = "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z";
const starPaths = ["M18 2v4m-2-2h4", "M21.5 9h0", "M14.5 1.5h0"];
const srOnly = "sr-only";

/**
 * Keyframes from light to dark; dark to light plays them in reverse. Every part that
 * differs between the themes is animated, and the last frame stays (fill both).
 * Each entry: "selector inside the button|property:value,value;property:...|stagger ms".
 */
const turn = "perspective(60px) rotateY(";
const moves = {
  rotate: [
    "g|rotate:0deg,1turn;scale:1,1.15,0;opacity:1,1,0",
    "g>path|scale:1,1.6,1.6,0",
    "svg>:nth-child(3)|rotate:-1turn,-1turn,0deg;scale:0,0,1;opacity:0,0,1",
  ],
  morph: [
    "g>circle|scale:1,1.6",
    "mask>circle|translate:24px -12px,15.5px -3.5px",
    "g>path|scale:1,0;opacity:1,0|50",
  ],
  flip: [
    `svg|transform:${turn}0),${turn}90deg),${turn}-90deg),${turn}0);translate:0,0 -6px,0 -6px,0;offset:0,.5,.5,1`,
    "g|opacity:1,1,0,0;offset:0,.5,.5,1",
    "svg>:nth-child(3)|opacity:0,0,1,1;offset:0,.5,.5,1",
  ],
  slide: [
    "g|translate:0,0 24px",
    "svg>:nth-child(3)|translate:0 -24px,0 -24px,0,0 4px,0;opacity:1,1",
  ],
  eclipse: [
    "mask>circle|translate:-6px 0,13.5px -1.5px",
    "g>path|scale:1,1.7,.75;opacity:1,.3,.4",
  ],
  spring: [
    "svg|scale:1,.6,1.15,.95,1",
    "g|opacity:1,1,0,0",
    "svg>:nth-child(3)|opacity:0,0,1,1",
    "svg>path~path|scale:0,1.5,.7,1;opacity:0,1,.3,1|120",
  ],
};
const DURATION = 650;
/** Indexed by toDark + 2 for a demo, which plays there and back. */
const directions = [
  "reverse",
  "normal",
  "alternate-reverse",
  "alternate",
] as const;
const SET = 0;
const SWITCH = 1;
const DEMO = 2;

type Theme = "light" | "dark";
type Animation = keyof typeof moves;

const html = () => document.documentElement;
const pageTheme = (): Theme =>
  html().classList.contains("dark") ? "dark" : "light";
const setDark = (theme: Theme) =>
  html().classList.toggle("dark", theme === "dark");

/** SET jumps to the theme's look, SWITCH animates to it, DEMO plays there and back. */
function play(
  button: HTMLElement,
  animation: Animation,
  toDark: boolean,
  mode: number,
) {
  const still =
    mode === SET ||
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  for (const move of moves[animation]) {
    const [selector = "", frames = "", stagger = 0] = move.split("|");
    const keyframes = Object.fromEntries(
      frames.split(";").map((frame) => {
        const [property, values = ""] = frame.split(":");
        return [property, values.split(",")];
      }),
    ) as Parameters<HTMLElement["animate"]>[0];
    button.querySelectorAll(selector).forEach((part, i) =>
      part.animate(keyframes, {
        duration: still ? 0 : +stagger ? DURATION / 2 : DURATION,
        delay: still ? 0 : i * +stagger,
        fill: "both",
        iterations: mode === DEMO ? 2 : 1,
        direction: directions[+toDark + (mode === DEMO ? 2 : 0)],
      }),
    );
  }
}

/** Saved choice first, then a dark class the page already set, then the system setting. */
function readTheme(storageKey: string): Theme {
  let saved: string | null = null;
  try {
    saved = localStorage.getItem(storageKey);
  } catch {
    // Storage blocked: fall back to the page and the system setting.
  }
  if (saved === "light" || saved === "dark") return saved;
  return pageTheme() === "dark" ||
    window.matchMedia?.("(prefers-color-scheme: dark)").matches
    ? "dark"
    : "light";
}

export type ThemeToggleAnimation = Animation;
export type ThemeToggleVariant = keyof typeof variants;
export type ThemeToggleSize = keyof typeof sizes;

let nextId = 0;

/**
 * Attribute selector on the native button: disabled, aria-*, and the user's class stay on the
 * button itself. Follows the html dark class, so every toggle on the page stays in sync.
 */
@Component({
  selector: "button[markas-theme-toggle]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    "[attr.type]": "type()",
    "[attr.data-state]": "current()",
    "[class]": "classes()",
    "(click)": "toggle($event)",
  },
  template: `
    <svg
      [class]="iconClasses()"
      viewBox="0 0 24 24"
      fill="currentColor"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      aria-hidden="true"
    >
      <mask [id]="maskId">
        <rect width="24" height="24" fill="white" />
        <circle cy="12" r="5" fill="black" />
      </mask>
      <g>
        <circle
          cx="12"
          cy="12"
          r="4.5"
          stroke="none"
          [attr.mask]="'url(#' + maskId + ')'"
        />
        @for (deg of rays; track deg) {
          <path [style.rotate]="deg + 'deg'" d="M12 2v2" />
        }
      </g>
      <path [class]="hidden" [attr.d]="moonPath" />
      @for (d of starPaths; track d) {
        <path [class]="hidden" [attr.d]="d" />
      }
    </svg>
    <span [class]="showText() ? '' : srOnly">{{
      current() === "dark" ? lightLabel() : darkLabel()
    }}</span>
  `,
})
export class ThemeToggle {
  readonly animation = input<ThemeToggleAnimation>("rotate");
  readonly variant = input<ThemeToggleVariant>("ghost");
  readonly size = input<ThemeToggleSize>("md");
  /** Controlled theme. Leave empty to read localStorage and the system setting. */
  readonly theme = input<Theme>();
  readonly storageKey = input("markas-theme");
  /** Show the label as visible text next to the icon. */
  readonly showText = input(false, { transform: booleanAttribute });
  readonly lightLabel = input("Switch to light theme");
  readonly darkLabel = input("Switch to dark theme");
  readonly type = input<"button" | "submit" | "reset">("button");
  /** Emits the theme a click asked for. */
  readonly themeChange = output<Theme>();

  protected readonly rays = rays;
  protected readonly hidden = hidden;
  protected readonly moonPath = moonPath;
  protected readonly starPaths = starPaths;
  protected readonly srOnly = srOnly;
  protected readonly maskId = `mask-markas-theme-toggle-${nextId++}`;
  protected readonly current = signal<Theme | undefined>(undefined);
  protected readonly classes = computed(
    () =>
      `${base} ${variants[this.variant()]} ${sizes[this.size()][+this.showText()]}`,
  );
  protected readonly iconClasses = computed(
    () => `${sizes[this.size()][2]} ${icon}`,
  );
  private readonly button = inject<ElementRef<HTMLButtonElement>>(ElementRef);
  /** The theme a click asked for: reaching it animates, any other change jumps. */
  private requested: Theme | undefined;

  constructor() {
    const destroyRef = inject(DestroyRef);
    // Follow the html class, so every toggle on the page and outside changes stay in sync.
    afterRenderEffect(() => {
      // Mount and controlled changes: put the page on the wanted theme. The parent saves a controlled theme.
      const target = this.theme() ?? readTheme(this.storageKey());
      if (target !== pageTheme()) setDark(target);
      this.current.set(pageTheme());
    });
    if (typeof MutationObserver === "function") {
      const observer = new MutationObserver(() =>
        this.current.set(pageTheme()),
      );
      observer.observe(html(), { attributeFilter: ["class"] });
      destroyRef.onDestroy(() => observer.disconnect());
    }
    // Show the theme on the icon: animated after a click, a jump on load or a change made elsewhere.
    afterRenderEffect(() => {
      const shown = this.current();
      const name = this.animation();
      if (!shown) return;
      const mode = shown === this.requested ? SWITCH : SET;
      this.requested = undefined;
      play(this.button.nativeElement, name, shown === "dark", mode);
    });
    // "Play all" demos: document.dispatchEvent(new Event("markas-theme-demo")).
    const demo = () =>
      play(
        this.button.nativeElement,
        this.animation(),
        pageTheme() !== "dark",
        DEMO,
      );
    document.addEventListener("markas-theme-demo", demo);
    destroyRef.onDestroy(() =>
      document.removeEventListener("markas-theme-demo", demo),
    );
  }

  protected toggle(event: MouseEvent) {
    if (event.defaultPrevented) return;
    const next = pageTheme() === "dark" ? "light" : "dark";
    this.requested = next;
    if (this.theme() === undefined) {
      setDark(next);
      try {
        localStorage.setItem(this.storageKey(), next);
      } catch {
        // Storage blocked: the theme still applies until the page closes.
      }
      document.dispatchEvent(
        new CustomEvent("markas-theme-change", { detail: next }),
      );
    }
    this.themeChange.emit(next);
  }
}
```

```ts
import { Component } from "@angular/core";
import { ThemeToggle } from "./markas/theme-toggle.component";

@Component({
  selector: "app-header",
  imports: [ThemeToggle],
  template: `
    <button markas-theme-toggle animation="morph" variant="outline"></button>
  `,
})
export class Header {}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `animation` | `'rotate' \| 'morph' \| 'flip' \| 'slide' \| 'eclipse' \| 'spring'` | rotate | Icon animation, played on click with the Web Animations API (transform and opacity only, 650ms). |
| `variant` | `'ghost' \| 'outline' \| 'solid'` | ghost | Visual style. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Size 32, 40, or 48px, the same heights as Button. |
| `theme` | `'light' \| 'dark'` | - | Controlled theme in React and Vue: the parent saves it and handles clicks. Blade applies it once on load. |
| `storageKey` | `string` | markas-theme | localStorage key that keeps the choice. |
| `showText` | `boolean` | false | Shows the label as visible text next to the icon. Pair it with short labels such as Dark mode. |
| `lightLabel` | `string` | Switch to light theme | Name while the dark theme is on. Visible text with showText. |
| `darkLabel` | `string` | Switch to dark theme | Name while the light theme is on. Visible text with showText. |
| `onThemeChange` | `(theme: 'light' \| 'dark') => void` | - | React callback after a click. Vue emits change. Every version also dispatches markas-theme-change on document. |
| `themeChange` | `output<"light" \| "dark">` | - | Angular only. Emits the theme a click asked for. Svelte uses onThemeChange. |

## Accessibility

- A native button element, so Enter and Space work and focus shows a 2px primary outline.
- The name says the action, Switch to dark theme or Switch to light theme, and follows the button data-state.
- The icon is aria-hidden, so screen readers only hear the label.
- With prefers-reduced-motion the icon swaps at once, without animation.

## Notes

- The toggle adds or removes the `dark` class on `<html>`, saves the choice in localStorage (`storageKey`), and dispatches `markas-theme-change` on `document` with the theme as `detail`.
- On load it reads the saved choice, then a `dark` class the page already set, then `prefers-color-scheme`. Add this to `<head>` so the page never flashes the wrong theme:

```html
<script>
  try {
    const saved = localStorage.getItem("markas-theme");
    document.documentElement.classList.toggle(
      "dark",
      saved
        ? saved === "dark"
        : matchMedia("(prefers-color-scheme: dark)").matches,
    );
  } catch {}
</script>
```

- Animations: `rotate`, `morph`, `flip`, `slide`, `eclipse`, `spring`. Each click plays keyframes with the Web Animations API (transform and opacity only). Users with reduced motion get an instant swap.
- `document.dispatchEvent(new Event("markas-theme-demo"))` plays every toggle there and back without changing the theme, handy for a "Play all" button.
- The button keeps its own `data-state` (light or dark) and follows the `dark` class on `<html>`, so several toggles, or a theme set elsewhere, stay in sync.
