# Theme Toggle

> A button that switches the page between light and dark, sun to moon. It starts from the system, keeps the visitor's choice, and swaps images that have a night version.

Navigation · theme toggle, dark mode, light mode, dark mode toggle, theme switcher, prefers-color-scheme, data-theme, localStorage, sun moon icon, dark logo · HTML, CSS, vanilla JS · no dependencies · updated 2026-11-05
Demo: https://kodza.dev/components/theme-toggle/
Source on GitHub: https://github.com/kodza-dev/kodza/tree/main/components/theme-toggle

## Files

The code below, served as files: byte for byte what the Kodza site copies (the CSS includes its theme guard).

- [`kodza-theme-toggle.css`](https://kodza.dev/registry/theme-toggle/kodza-theme-toggle.css) · 14.9 KB
- [`kodza-theme-toggle.js`](https://kodza.dev/registry/theme-toggle/kodza-theme-toggle.js) · 10.9 KB
- [`kodza-theme-toggle.html`](https://kodza.dev/registry/theme-toggle/kodza-theme-toggle.html) · 1.8 KB · the markup, to adapt and paste into your page

**Can you run shell commands? Download the CSS and the JS, don't retype them.** Retyping costs thousands of tokens and can drop or change lines of the CSS. Put the files where your stack expects them (Use it says where: change the `-o` paths):

```bash
curl -fsSL --create-dirs -o kodza/kodza-theme-toggle.css https://kodza.dev/registry/theme-toggle/kodza-theme-toggle.css
curl -fsSL --create-dirs -o kodza/kodza-theme-toggle.js https://kodza.dev/registry/theme-toggle/kodza-theme-toggle.js
```

Then load the files from your page as Use it shows, instead of pasting the content. The HTML is the part you adapt (text, links, modifiers): paste it from the Code section. Copy the CSS and the JS from the Code section only if you can't run commands, exactly as they are. (Windows PowerShell: `curl.exe`.)

## API

- Root: `[data-kodza-theme-toggle]`
- Variables (set them on the root element itself: it declares its own defaults):
  - `--kz-theme-toggle-size: 40px`
  - `--kz-theme-toggle-icon: 20px`
  - `--kz-theme-toggle-stroke: 1.75px` — in icon units, 24 across
  - `--kz-theme-toggle-ink: #0a0a0a`
  - `--kz-theme-toggle-surface: rgba(10, 10, 10, 0.06)` — the button at rest
  - `--kz-theme-toggle-hover: rgba(10, 10, 10, 0.11)` — under the pointer
  - `--kz-theme-toggle-duration: 0.5s`
  - `--kz-theme-toggle-ease: cubic-bezier(0.65, 0, 0.35, 1)` — in and out, so the strokes are seen travelling
  - `--kz-theme-toggle-recolor: 0s` — when the ink flips: at once for a page that switches at once, half its
                                    colour transition for one that fades, so it never goes grey on grey
- Modifiers: `.kodza-theme-toggle--label`
- Attributes:
  - `data-attribute`
  - `data-class`
  - `data-dark-src`
  - `data-kodza-theme-toggle`
  - `data-storage`
  - `data-target`
- Events: `kodza:theme-toggle` (bubbling, from the root)
- Lifecycle: `kodza:init` / `kodza:destroy` on `document`, with `{ detail: { root } }` to target a container.

## Keyboard

What each key does, by where the focus is. Keep it working when you adapt the HTML: same elements, same classes.

- On the button (focus in `.kodza-theme-toggle`):
  - `Enter` / `Space`: Switches the page between light and dark

## Dark mode

The values Kodza uses on a dark background (`#0a0a0a`). For a page that follows the system theme, add them after the component's CSS:

```css
@media (prefers-color-scheme: dark) {
  .kodza-theme-toggle {
    --kz-theme-toggle-ink: #f2f2f0;
    --kz-theme-toggle-surface: rgba(255, 255, 255, 0.08);
    --kz-theme-toggle-hover: rgba(255, 255, 255, 0.14);
  }
}
```

A site with its own theme switch puts the same rules under its dark selector instead (`[data-theme="dark"] .kodza-theme-toggle { … }`); a single dark section, under that section's class.

## Use it

### Plain HTML page

- CSS: `kodza/kodza-theme-toggle.css` next to the page (the Files commands as they are), linked in `<head>`: `<link rel="stylesheet" href="kodza/kodza-theme-toggle.css">`. Without a shell, paste it in a `<style>` in `<head>` instead. It only touches `kodza-` classes.
- HTML: where the component goes. Paste it as many times as you need: instances never interfere.
- Where it goes, step by step. (1) In the site's header, at its right end, beside the other buttons; keep one of the two buttons (the icon alone, or the icon with its word). (2) At the top of the <head>, before the stylesheets, put this line in a script tag, so the page never flashes white before the script runs: try{var t=localStorage.getItem('kodza-theme');document.documentElement.setAttribute('data-theme',t==='dark'||t==='light'?t:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(e){} (3) Write the site's dark colours under [data-theme="dark"], and the toggle's Dark mode values there too; if the page fades its colours, set --kz-theme-toggle-recolor to half that time, so the button flips its ink midway. If the theme expects a class instead (dark on <html>, like Tailwind), put data-class="dark" on the button and change the head line to classList.toggle('dark', …); data-attribute names another attribute, data-target another element, data-storage another key (empty: nothing saved). (4) Give every image that has a night version (a logo, a screenshot, a lamp lit) data-dark-src="…" with the night file: it loads on the first switch to dark and lights up over the day one, in the same box. Several toggles on a page stay in step, and the page hears kodza:theme-toggle with the theme in event.detail.
- JS: `kodza/kodza-theme-toggle.js`, loaded with `<script src="kodza/kodza-theme-toggle.js" defer></script>` in `<head>`. Without a shell, paste it in a `<script>` before `</body>` (or in `<head>`: it waits for the page). One copy per page, whatever the number of instances.
- Restyle with the `--kz-…` variables, set on the component's root element itself (the root declares its own defaults, so a value on an ancestor is ignored), and with the modifiers / attributes listed under API.
- Font: it takes the page's own. A site with its own type sets it once for every Kodza component, on `:root`, never by editing the CSS (unset, nothing changes): `--kz-font-label`, the face of the small labels (meta, captions, counters, hints, footer links, button labels); `--kz-font-label-size`, their size, one for all of them (`11px`…); `--kz-font-label-weight`, their weight; `--kz-font-label-tracking`, their letter-spacing; `--kz-font-label-case`, their case (`uppercase`…; code and units keep theirs); `--kz-font-label-leading`, their line-height (`1.45`…; buttons, pills and keys keep their box). The Kodza look is Geist: `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`.
- Corners: a site with its own shapes sets them once for every Kodza component, on `:root`, never by editing the CSS (unset, nothing changes): `--kz-radius-pill` sets the pills (`0` squares them).
- Motion: a site sets its pace once for every Kodza component, on `:root`, never by editing the CSS or the JS: `--kz-motion-scale` multiplies every duration (`0.5` twice as fast, `2` twice as slow, `0` no motion at all, loops stopped, like reduced motion). Unset, nothing changes.
- Content added later (AJAX navigation, a SPA route, a builder preview): start it with `document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: container } }))`; before removing it, the same call with `'kodza:destroy'` stops it and puts the original markup back.

### Claude artifact (claude.ai)

- Paste the CSS in a `<style>` and the JS in a `<script>` at the end, in the artifact itself: it loads stylesheets only from Google Fonts and scripts only from a few CDNs, so no `<link>` or `<script src>` to Kodza.
- Writing the artifact file with a shell? Insert the downloaded files (Files) with a command instead of retyping them: a line `KODZA-CSS` alone inside the `<style>`, `KODZA-JS` inside the `<script>`, then `sed -e '/^KODZA-CSS$/{r kodza/kodza-theme-toggle.css' -e 'd' -e '}' -e '/^KODZA-JS$/{r kodza/kodza-theme-toggle.js' -e 'd' -e '}' page.html > artifact.html`.
- Font: load Geist from Google Fonts (allowed): `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`. A site with its own type sets it once for every Kodza component, on `:root`, never by editing the CSS (unset, nothing changes): `--kz-font-label`, the face of the small labels (meta, captions, counters, hints, footer links, button labels); `--kz-font-label-size`, their size, one for all of them (`11px`…); `--kz-font-label-weight`, their weight; `--kz-font-label-tracking`, their letter-spacing; `--kz-font-label-case`, their case (`uppercase`…; code and units keep theirs); `--kz-font-label-leading`, their line-height (`1.45`…; buttons, pills and keys keep their box).
- Corners: a site with its own shapes sets them once for every Kodza component, on `:root`, never by editing the CSS (unset, nothing changes): `--kz-radius-pill` sets the pills (`0` squares them).
- Motion: a site sets its pace once for every Kodza component, on `:root`, never by editing the CSS or the JS: `--kz-motion-scale` multiplies every duration (`0.5` twice as fast, `2` twice as slow, `0` no motion at all, loops stopped, like reduced motion). Unset, nothing changes.
- Dark mode: the viewer sets `data-theme="dark"` or `"light"` on `<html>`, or nothing when it follows the system. Write the Dark mode rules twice: inside `@media (prefers-color-scheme: dark)` with `:root:not([data-theme="light"])` in front of each selector, and with `:root[data-theme="dark"]` in front of each selector.
- Where it goes, step by step. (1) In the site's header, at its right end, beside the other buttons; keep one of the two buttons (the icon alone, or the icon with its word). (2) At the top of the <head>, before the stylesheets, put this line in a script tag, so the page never flashes white before the script runs: try{var t=localStorage.getItem('kodza-theme');document.documentElement.setAttribute('data-theme',t==='dark'||t==='light'?t:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(e){} (3) Write the site's dark colours under [data-theme="dark"], and the toggle's Dark mode values there too; if the page fades its colours, set --kz-theme-toggle-recolor to half that time, so the button flips its ink midway. If the theme expects a class instead (dark on <html>, like Tailwind), put data-class="dark" on the button and change the head line to classList.toggle('dark', …); data-attribute names another attribute, data-target another element, data-storage another key (empty: nothing saved). (4) Give every image that has a night version (a logo, a screenshot, a lamp lit) data-dark-src="…" with the night file: it loads on the first switch to dark and lights up over the day one, in the same box. Several toggles on a page stay in step, and the page hears kodza:theme-toggle with the theme in event.detail.

### WordPress

- HTML: a **Custom HTML** block (or a pattern / template part). WordPress keeps this markup as it is only for users allowed to post unfiltered HTML (Administrators; Super Admins on multisite): for anyone else it strips tags such as `<svg>`, `<input>` or `<dialog>`, so add it from the theme (a pattern or template part) instead.
- This one is inline (it flows like a word): pasted alone, many themes leave it at the edge of the page (block themes, and classic ones like Twenty Twenty-One or Blocksy), so put the Custom HTML block inside a **Group** block to line it up with the text.
- CSS and JS: the downloaded files go in the theme, under `wp-content/themes/<your-theme>/kodza/` (the child theme if there is one), enqueued from its functions.php (or a code-snippets plugin):
  ```php
  add_action('wp_enqueue_scripts', function () {
    $dir = get_stylesheet_directory() . '/kodza/';
    $uri = get_stylesheet_directory_uri() . '/kodza/';
    wp_enqueue_style('kodza-theme-toggle', $uri . 'kodza-theme-toggle.css', [], filemtime($dir . 'kodza-theme-toggle.css'));
    wp_enqueue_script('kodza-theme-toggle', $uri . 'kodza-theme-toggle.js', [], filemtime($dir . 'kodza-theme-toggle.js'), true);
  });
  ```
  Scoped to `kodza-` classes, the CSS never touches the theme. One copy of the JS, whatever the number of blocks.
- No access to the theme files? The CSS can also go, as it is, in **Appearance → Customize → Additional CSS** (classic theme) or **Styles → Additional CSS** in the Site Editor (block theme).
- Theme with AJAX page transitions: fire `kodza:init` on the new content after each swap (and `kodza:destroy` on the old one).
- Performance plugin (WP Rocket, LiteSpeed Cache, Perfmatters…) with **Delay JavaScript execution** turned on: add `kodza` to the scripts it must not delay. Otherwise the component waits for the visitor's first scroll, tap or mouse move, and that first click can be lost.
- Colours: it takes the colour of the text around it (or keeps its own monochrome): nothing to point at the theme.
- WordPress turns straight quotes and `--` into typographic ones in the text of a Custom HTML block (not inside `<code>` or `<pre>`).

#### With Elementor

- HTML: an **HTML** widget (Elementor shows it to administrators only). It keeps the code exactly as pasted, straight quotes included.
- CSS and JS: as above. Elementor's Site Settings → Theme Style styles every button, field, link and image of the page, components included; the theme guard at the end of the CSS keeps the component's buttons, fields and link colours as they are.
- The Elementor editor redraws each widget after the page has loaded: without the script below, the component stays still in the editor preview (the published page works). Add it once per site, in the footer like the component's script (`kodza/elementor-editor.js`, or a code-snippets plugin):

```js
// Kodza in the Elementor editor: the editor redraws each HTML widget after the page has loaded.
// Start Kodza in what it draws, stop it in what it replaces or removes. Once per site.
window.addEventListener('elementor/frontend/init', () => {
  if (!elementorFrontend.isEditMode()) return;
  class KodzaWidget extends elementorModules.frontend.handlers.Base {
    onInit() {
      super.onInit();
      this.kodza = [...this.$element[0].children];
      document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: this.$element[0] } }));
    }
    onDestroy() {
      super.onDestroy();
      this.kodza.forEach((root) => document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } })));
    }
  }
  elementorFrontend.elementsHandler.attachHandler('html', KodzaWidget);
});
```

- No child theme: everything can go in the HTML widget instead, `<style>` with the CSS, the HTML, then `<script>` with the JS. It works on the page and in the editor without the script above. This one reads the page around it, and a script in the widget runs before the rest of the page exists: put its `<script>` in an HTML widget at the bottom of the page instead.

### Shopify

- Files: `assets/kodza-theme-toggle.css` and `assets/kodza-theme-toggle.js` (the Files commands with `-o assets/…`).
- In the section: `{{ 'kodza-theme-toggle.css' | asset_url | stylesheet_tag }}` and `<script src="{{ 'kodza-theme-toggle.js' | asset_url }}" defer></script>`, then the HTML.
- The theme editor re-renders sections: restart them with
  `document.addEventListener('shopify:section:load', (e) => document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: e.target } })));`
  and the same with `shopify:section:unload` → `kodza:destroy`.
- Where it goes, step by step. (1) In the site's header, at its right end, beside the other buttons; keep one of the two buttons (the icon alone, or the icon with its word). (2) At the top of the <head>, before the stylesheets, put this line in a script tag, so the page never flashes white before the script runs: try{var t=localStorage.getItem('kodza-theme');document.documentElement.setAttribute('data-theme',t==='dark'||t==='light'?t:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(e){} (3) Write the site's dark colours under [data-theme="dark"], and the toggle's Dark mode values there too; if the page fades its colours, set --kz-theme-toggle-recolor to half that time, so the button flips its ink midway. If the theme expects a class instead (dark on <html>, like Tailwind), put data-class="dark" on the button and change the head line to classList.toggle('dark', …); data-attribute names another attribute, data-target another element, data-storage another key (empty: nothing saved). (4) Give every image that has a night version (a logo, a screenshot, a lamp lit) data-dark-src="…" with the night file: it loads on the first switch to dark and lights up over the day one, in the same box. Several toggles on a page stay in step, and the page hears kodza:theme-toggle with the theme in event.detail.

### React / Next.js

- Files, side by side (e.g. in `components/kodza/`): `ThemeToggle.tsx` (below), the CSS block under Code saved as `theme-toggle.css` and the JS block as `theme-toggle.js`, both as they are. The HTML block is already inside the component: skip it.
- Use it: `import { ThemeToggle } from '@/components/kodza/ThemeToggle';` then `<ThemeToggle />`. Props: `variant` ("label", or several in an array), `vars` (the `--kz-…` variables listed under API, e.g. `vars={{ '--kz-theme-toggle-size': … }}`), `onThemeToggle` (the `kodza:theme-toggle` event), `className`, `style` and the other props of its `<button>` (`onClick`, `aria-…`).
- Next.js App Router: it is a Client Component already (`'use client'`). Pages Router: Next.js takes global CSS only in `pages/_app`, so move the `import './theme-toggle.css'` line there.
- Safe under StrictMode, client-side navigation and prop changes: when a prop changes, the `key` gives React a fresh element, `kodza:destroy` stops the script on the old one and `kodza:init` starts it on the new one.
- Built from your data (tabs, rows, options)? Add what the markup is made of to the `key`, as plain values (ids, text, numbers). What the visitor changes (the open tab, the sort, what they type) is the script's: follow it with `onClick` or `onInput` on the root, and change it from your code as a visitor would (click the tab; set the field's value, then dispatch a bubbling `input` event). Fields stay uncontrolled (`defaultValue`, `name`).

```tsx
'use client';
// Kodza — Theme Toggle, for React. From https://kodza.dev/components/theme-toggle/
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Next to this file: theme-toggle.css and theme-toggle.js, the component's CSS and JS from Kodza, as they are.
// Yours to edit: the markup is plain JSX below.
// The script changes this markup once React has rendered it (it adds layers, splits text, moves
// nodes), so React must not patch it afterwards. When a prop changes, the key gives React a fresh
// element: kodza:destroy stops the script on the old one, kodza:init starts it on the new one.
// data-kodza-manual keeps the script from starting it on its own: the effect below does, once
// React has hydrated the markup (on a page that streams in, the script can load first).
// Built from your data (tabs, rows, options)? Put what the markup is made of in the key, as plain
// values (ids, text, numbers): a change starts the script again on fresh markup. What the visitor
// changes (the open tab, the sort, what they type) is the script's: keep it out of the key, follow
// it with onClick or onInput on the root, and change it from your code as a visitor would (click
// the tab; set the field's value, then dispatch a bubbling input event).
import { useRef, useEffect, type ComponentPropsWithoutRef, type ComponentRef, type CSSProperties } from 'react';
import './theme-toggle.css';

type Variant = "label";

export type ThemeToggleProps = Omit<ComponentPropsWithoutRef<'button'>, "children" | "variant" | "vars" | "onThemeToggle"> & {
  /** Modifier class(es): .kodza-theme-toggle--label */
  variant?: Variant | Variant[];
  /** Settings, as CSS variables on the root */
  vars?: {
    /** default: 40px */
    "--kz-theme-toggle-size"?: string | number;
    /** default: 20px */
    "--kz-theme-toggle-icon"?: string | number;
    /** in icon units, 24 across — default: 1.75px */
    "--kz-theme-toggle-stroke"?: string | number;
    /** default: #0a0a0a */
    "--kz-theme-toggle-ink"?: string | number;
    /** the button at rest — default: rgba(10, 10, 10, 0.06) */
    "--kz-theme-toggle-surface"?: string | number;
    /** under the pointer — default: rgba(10, 10, 10, 0.11) */
    "--kz-theme-toggle-hover"?: string | number;
    /** default: 0.5s */
    "--kz-theme-toggle-duration"?: string | number;
    /** in and out, so the strokes are seen travelling — default: cubic-bezier(0.65, 0, 0.35, 1) */
    "--kz-theme-toggle-ease"?: string | number;
    /** when the ink flips: at once for a page that switches at once, half its
                                    colour transition for one that fades, so it never goes grey on grey — default: 0s */
    "--kz-theme-toggle-recolor"?: string | number;
  };
  /** "kodza:theme-toggle", fired by the script (bubbles from the root) */
  onThemeToggle?: (event: CustomEvent) => void;
  className?: string;
};

export function ThemeToggle({ variant, vars, onThemeToggle, className, style, ...rest }: ThemeToggleProps) {
  const ref = useRef<ComponentRef<'button'>>(null);
  const classes = ["kodza-theme-toggle", ...([] as string[]).concat(variant ?? []).map((v) => `kodza-theme-toggle--${v}`), className].filter(Boolean).join(' ');
  // Everything the markup is made of: when it changes, React gets a fresh element (see the top)
  const key = JSON.stringify([classes, vars, style, rest]);

  // Starts the script on this element once React has rendered it, stops it when it goes
  useEffect(() => {
    const root = ref.current;
    let live = true;
    // @ts-ignore: a plain script, no types to find
    import('./theme-toggle.js').then(() => {
      if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
    });
    return () => {
      live = false;
      document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
    };
  }, [key]);

  useEffect(() => {
    const root = ref.current;
    if (!root || !onThemeToggle) return;
    const listener = (event: Event) => onThemeToggle(event as CustomEvent);
    root.addEventListener("kodza:theme-toggle", listener);
    return () => root.removeEventListener("kodza:theme-toggle", listener);
  }, [onThemeToggle, key]);

  return (
    <button type="button" aria-pressed="false" aria-label="Dark mode" data-kodza-theme-toggle="" key={key} {...rest} className={classes} data-kodza-manual style={{ ...vars, ...style } as CSSProperties} ref={ref}>
      <svg className="kodza-theme-toggle__icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
        <g className="kodza-theme-toggle__rays">
          <path className="kodza-theme-toggle__ray" d="M-12 0H12" />
          <path className="kodza-theme-toggle__ray" d="M-12 0H12" />
          <path className="kodza-theme-toggle__ray" d="M-12 0H12" />
          <path className="kodza-theme-toggle__ray" d="M-12 0H12" />
          <path className="kodza-theme-toggle__ray" d="M-12 0H12" />
          <path className="kodza-theme-toggle__ray" d="M-12 0H12" />
          <path className="kodza-theme-toggle__ray" d="M-12 0H12" />
          <path className="kodza-theme-toggle__ray" d="M-12 0H12" />
        </g>
        <circle className="kodza-theme-toggle__disc" cx="12" cy="12" r="4" />
      </svg>
    </button>
  );
}
```

- Where it goes, step by step. (1) In the site's header, at its right end, beside the other buttons; keep one of the two buttons (the icon alone, or the icon with its word). (2) At the top of the <head>, before the stylesheets, put this line in a script tag, so the page never flashes white before the script runs: try{var t=localStorage.getItem('kodza-theme');document.documentElement.setAttribute('data-theme',t==='dark'||t==='light'?t:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(e){} (3) Write the site's dark colours under [data-theme="dark"], and the toggle's Dark mode values there too; if the page fades its colours, set --kz-theme-toggle-recolor to half that time, so the button flips its ink midway. If the theme expects a class instead (dark on <html>, like Tailwind), put data-class="dark" on the button and change the head line to classList.toggle('dark', …); data-attribute names another attribute, data-target another element, data-storage another key (empty: nothing saved). (4) Give every image that has a night version (a logo, a screenshot, a lamp lit) data-dark-src="…" with the night file: it loads on the first switch to dark and lights up over the day one, in the same box. Several toggles on a page stay in step, and the page hears kodza:theme-toggle with the theme in event.detail.

## Code

```html
<button class="kodza-theme-toggle" type="button" aria-pressed="false" aria-label="Dark mode" data-kodza-theme-toggle>
  <svg class="kodza-theme-toggle__icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
    <g class="kodza-theme-toggle__rays">
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
    </g>
    <circle class="kodza-theme-toggle__disc" cx="12" cy="12" r="4"/>
  </svg>
</button>

<button class="kodza-theme-toggle kodza-theme-toggle--label" type="button" aria-pressed="false" aria-label="Dark mode" data-kodza-theme-toggle>
  <svg class="kodza-theme-toggle__icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
    <g class="kodza-theme-toggle__rays">
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
      <path class="kodza-theme-toggle__ray" d="M-12 0H12"/>
    </g>
    <circle class="kodza-theme-toggle__disc" cx="12" cy="12" r="4"/>
  </svg>
  <span class="kodza-theme-toggle__words" aria-hidden="true">
    <span class="kodza-theme-toggle__word">Light</span>
    <span class="kodza-theme-toggle__word">Dark</span>
  </span>
</button>
```

```css
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Theme Toggle
   A real button that switches the page between light and dark. Its sun becomes a moon with the
   strokes of Morph Icons: the rays draw back into the disc, the disc swells, and a shadow slides
   over it from the top right. The page puts its lights out; images that have a night version
   (a logo, a screenshot, a lamp lit) get it laid over the day one, in the same box, so nothing
   moves and the logo never stays dark on a dark page.
   The button shows the theme the page is in: the sun while aria-pressed is false, the moon while it
   is true. The script sets it, and keeps every toggle of the page in step.
   Everything is tuned with the --kz-theme-toggle-* variables. */
.kodza-theme-toggle {
  --kz-theme-toggle-size: 40px;
  --kz-theme-toggle-icon: 20px;
  --kz-theme-toggle-stroke: 1.75px; /* in icon units, 24 across */
  --kz-theme-toggle-ink: #0a0a0a;
  --kz-theme-toggle-surface: rgba(10, 10, 10, 0.06); /* the button at rest */
  --kz-theme-toggle-hover: rgba(10, 10, 10, 0.11); /* under the pointer */
  --kz-theme-toggle-duration: 0.5s;
  --kz-theme-toggle-ease: cubic-bezier(0.65, 0, 0.35, 1); /* in and out, so the strokes are seen travelling */
  --kz-theme-toggle-recolor: 0s; /* when the ink flips: at once for a page that switches at once, half its
                                    colour transition for one that fades, so it never goes grey on grey */

  display: inline-grid;
  grid-auto-flow: column;
  flex: none;
  place-items: center;
  box-sizing: border-box;
  width: var(--kz-theme-toggle-size);
  height: var(--kz-theme-toggle-size);
  margin: 0;
  padding: 0;
  border: 0;
  border-radius: var(--kz-radius-pill, 999px);
  background: var(--kz-theme-toggle-surface);
  color: var(--kz-theme-toggle-ink);
  font: inherit;
  line-height: 1;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  transition:
    background-color calc(0.2s * var(--kz-motion-scale, 1)) ease,
    color 0s linear calc(var(--kz-theme-toggle-recolor) * var(--kz-motion-scale, 1)),
    scale calc(0.15s * var(--kz-motion-scale, 1)) cubic-bezier(0.22, 1, 0.36, 1);
}

.kodza-theme-toggle:focus-visible {
  outline: 2px solid var(--kz-theme-toggle-ink);
  outline-offset: 3px;
}

.kodza-theme-toggle:active {
  scale: 0.94;
}

@media (hover: hover) {
  .kodza-theme-toggle:hover {
    background: var(--kz-theme-toggle-hover);
  }
}

/* With its word: Light or Dark beside the icon, the old word rolls out as the new one comes in */
.kodza-theme-toggle--label {
  gap: 8px;
  width: auto;
  padding: 0 16px 0 12px;
}

.kodza-theme-toggle__words {
  display: grid;
  overflow: hidden;
  font-family: var(--kz-font-label, inherit);
  font-size: var(--kz-font-label-size, 15px);
  font-weight: var(--kz-font-label-weight, 500);
  line-height: var(--kz-font-label-leading, 20px);
  letter-spacing: var(--kz-font-label-tracking, -0.01em);
  text-transform: var(--kz-font-label-case, inherit);
  white-space: nowrap;
}

.kodza-theme-toggle__word {
  grid-area: 1 / 1;
  transition: transform 0s var(--kz-theme-toggle-ease);
}

.kodza-theme-toggle__word + .kodza-theme-toggle__word,
.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__word {
  transform: translateY(105%);
}

.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__word:first-child {
  transform: translateY(-105%);
}

.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__word + .kodza-theme-toggle__word {
  transform: none;
}

/* The icon. The moon's shadow is a hole in a mask that slides over the disc: waiting off the top
   right corner on the sun, over the disc on the moon. No id, no animated d, so Safari plays it */
.kodza-theme-toggle__icon {
  --kz-theme-toggle-hole: calc(var(--kz-theme-toggle-icon) * 0.2708); /* 6.5 icon units */

  display: block;
  width: var(--kz-theme-toggle-icon);
  height: var(--kz-theme-toggle-icon);
  overflow: hidden;
  fill: none;
  stroke: currentColor;
  stroke-width: var(--kz-theme-toggle-stroke);
  stroke-linecap: round;
  pointer-events: none;
  -webkit-mask-image: radial-gradient(circle, transparent calc(var(--kz-theme-toggle-hole) - 0.4px), #000 calc(var(--kz-theme-toggle-hole) + 0.4px));
  mask-image: radial-gradient(circle, transparent calc(var(--kz-theme-toggle-hole) - 0.4px), #000 calc(var(--kz-theme-toggle-hole) + 0.4px));
  -webkit-mask-size: calc(var(--kz-theme-toggle-icon) * 3) calc(var(--kz-theme-toggle-icon) * 3);
  mask-size: calc(var(--kz-theme-toggle-icon) * 3) calc(var(--kz-theme-toggle-icon) * 3);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
  -webkit-mask-position: calc(var(--kz-theme-toggle-icon) * -0.2) calc(var(--kz-theme-toggle-icon) * -1.8);
  mask-position: calc(var(--kz-theme-toggle-icon) * -0.2) calc(var(--kz-theme-toggle-icon) * -1.8);
  transition-property: -webkit-mask-position, mask-position;
  transition-duration: 0s;
  transition-timing-function: var(--kz-theme-toggle-ease);
}

.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__icon {
  -webkit-mask-position: calc(var(--kz-theme-toggle-icon) * -0.8083) calc(var(--kz-theme-toggle-icon) * -1.1917);
  mask-position: calc(var(--kz-theme-toggle-icon) * -0.8083) calc(var(--kz-theme-toggle-icon) * -1.1917);
}

.kodza-theme-toggle__disc {
  fill: currentColor;
  stroke: none;
  transform-box: view-box;
  transform-origin: 12px 12px;
  transition: transform 0s var(--kz-theme-toggle-ease);
}

.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__disc {
  transform: scale(2.125); /* radius 4 to 8.5 */
}

.kodza-theme-toggle__rays {
  transform-box: view-box;
  transform-origin: 12px 12px;
  transition: transform 0s var(--kz-theme-toggle-ease);
}

.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__rays {
  transform: rotate(45deg);
}

/* Every ray is the 24-unit line of Morph Icons, M-12 0H12, turned and pushed out from the middle by
   a transform; the dash shows 2 units of it: dasharray 2 48, offset 2/2 - 12. On the moon it draws
   back towards the disc, shrinks to its middle and thins out with it. The rays go one after the
   other from the top right, where the shadow comes in */
.kodza-theme-toggle__ray {
  --kz-theme-toggle-turn: 0deg;
  --kz-theme-toggle-rank: 1;

  transform: translate(12px, 12px) rotate(var(--kz-theme-toggle-turn)) translateX(8.25px);
  transform-box: view-box;
  transform-origin: 0 0;
  stroke-dasharray: 2px 48px;
  stroke-dashoffset: -11px;
  transition-property: transform, stroke-dasharray, stroke-dashoffset, stroke-width;
  transition-duration: 0s;
  transition-timing-function: var(--kz-theme-toggle-ease);
}

.kodza-theme-toggle__ray:nth-child(2) { --kz-theme-toggle-turn: 45deg; --kz-theme-toggle-rank: 2; }
.kodza-theme-toggle__ray:nth-child(3) { --kz-theme-toggle-turn: 90deg; --kz-theme-toggle-rank: 3; }
.kodza-theme-toggle__ray:nth-child(4) { --kz-theme-toggle-turn: 135deg; --kz-theme-toggle-rank: 4; }
.kodza-theme-toggle__ray:nth-child(5) { --kz-theme-toggle-turn: 180deg; --kz-theme-toggle-rank: 3; }
.kodza-theme-toggle__ray:nth-child(6) { --kz-theme-toggle-turn: 225deg; --kz-theme-toggle-rank: 2; }
.kodza-theme-toggle__ray:nth-child(7) { --kz-theme-toggle-turn: 270deg; --kz-theme-toggle-rank: 1; }
.kodza-theme-toggle__ray:nth-child(8) { --kz-theme-toggle-turn: 315deg; --kz-theme-toggle-rank: 0; }

.kodza-theme-toggle[aria-pressed="true"] .kodza-theme-toggle__ray {
  transform: translate(12px, 12px) rotate(var(--kz-theme-toggle-turn)) translateX(6px);
  stroke-dasharray: 0px 48px;
  stroke-dashoffset: -12px;
  stroke-width: 0;
}

/* Motion starts once the script is ready, so nothing moves on load. To the moon: the rays first,
   then the disc swells and the shadow slides in. Back to the sun: the shadow leaves first, the disc
   shrinks, and the rays come back last, the top right one first */
.kodza-theme-toggle.is-ready :is(.kodza-theme-toggle__icon, .kodza-theme-toggle__disc, .kodza-theme-toggle__rays, .kodza-theme-toggle__ray, .kodza-theme-toggle__word) {
  transition-duration: calc(var(--kz-theme-toggle-duration) * var(--kz-motion-scale, 1));
}

.kodza-theme-toggle.is-ready .kodza-theme-toggle__ray {
  transition-delay: calc(var(--kz-theme-toggle-duration) * (0.3 + 0.05 * var(--kz-theme-toggle-rank)) * var(--kz-motion-scale, 1));
}

.kodza-theme-toggle.is-ready .kodza-theme-toggle__disc {
  transition-delay: calc(var(--kz-theme-toggle-duration) * 0.1 * var(--kz-motion-scale, 1));
}

.kodza-theme-toggle.is-ready[aria-pressed="true"] .kodza-theme-toggle__ray {
  transition-delay: calc(var(--kz-theme-toggle-duration) * 0.05 * var(--kz-theme-toggle-rank) * var(--kz-motion-scale, 1));
}

.kodza-theme-toggle.is-ready[aria-pressed="true"] .kodza-theme-toggle__disc {
  transition-delay: calc(var(--kz-theme-toggle-duration) * 0.08 * var(--kz-motion-scale, 1));
}

.kodza-theme-toggle.is-ready[aria-pressed="true"] .kodza-theme-toggle__icon {
  transition-delay: calc(var(--kz-theme-toggle-duration) * 0.18 * var(--kz-motion-scale, 1));
}

/* Night images, outside the button: the script wraps each img[data-dark-src] of the page in a pair,
   the day image and its night twin in the same grid cell. The night one lights up over the day one,
   which fades out under it, so a logo with a transparent background never shows both */
.kodza-theme-toggle-pair {
  --kz-theme-toggle-fade: 0.6s;
  --kz-theme-toggle-lag: 0.12s; /* the lamp comes on just after the page goes dark (none on the way back) */

  display: inline-grid;
  max-width: 100%;
}

.kodza-theme-toggle-pair--block {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
}

.kodza-theme-toggle-pair > img {
  grid-area: 1 / 1;
}

.kodza-theme-toggle-night {
  opacity: 0;
  pointer-events: none;
}

.kodza-theme-toggle-pair.is-night > img:first-child {
  opacity: 0;
}

.kodza-theme-toggle-pair.is-night > .kodza-theme-toggle-night {
  opacity: 1;
}

/* Back to day, no wait: both images turn with the page, so the night one never lingers on a white page */
.kodza-theme-toggle-pair.is-ready > img {
  transition: opacity calc(var(--kz-theme-toggle-fade) * var(--kz-motion-scale, 1)) cubic-bezier(0.65, 0, 0.35, 1);
}

/* To night, the lamp comes on just after the page has gone dark */
.kodza-theme-toggle-pair.is-ready.is-night > img {
  transition: opacity calc(var(--kz-theme-toggle-fade) * var(--kz-motion-scale, 1)) cubic-bezier(0.55, 0, 1, 0.45) calc(var(--kz-theme-toggle-lag) * var(--kz-motion-scale, 1));
}

.kodza-theme-toggle-pair.is-ready.is-night > .kodza-theme-toggle-night {
  transition-timing-function: cubic-bezier(0.22, 1, 0.36, 1);
}

@media (prefers-reduced-motion: reduce) {
  .kodza-theme-toggle,
  .kodza-theme-toggle *,
  .kodza-theme-toggle-pair > img {
    transition-duration: 0.01ms !important;
    transition-delay: 0s !important;
  }
}

/* kodza-guard 171ad3d0177f — generated by Kodza, do not edit.
   Theme guard: keeps a site's own CSS (WordPress themes, Bootstrap, CSS resets…) off this
   component. :not(#_) is always true and weighs as much as an id, so these lines win over
   theme rules made of classes and tags. Customise the component through its --kz-* variables. */

/* What the browser gives, where the component sets it only in some states: at the lowest weight, so its own rules below put it back */

:where(.kodza-theme-toggle):not(#_) {
  outline: revert;
  outline-offset: revert;
}

:where(.kodza-theme-toggle__icon):not(#_) {
  transition-delay: revert;
}

/* What the browser gives, on everything the component leaves to it */

.kodza-theme-toggle:not(#_) {
  text-decoration: revert;
  list-style: revert;
  position: revert;
  box-shadow: revert;
  appearance: revert;
  max-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
  white-space: revert;
  min-height: revert;
}

.kodza-theme-toggle__icon:not(#_) {
  border: revert;
  margin: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  color: revert;
  font-family: revert;
  font-size: revert;
  font-weight: revert;
  font-style: revert;
  line-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-theme-toggle__rays:not(#_),
.kodza-theme-toggle__ray:not(#_),
.kodza-theme-toggle__disc:not(#_),
.kodza-theme-toggle__words:not(#_),
.kodza-theme-toggle__word:not(#_) {
  box-sizing: revert;
}

/* The component's own rules, one step stronger: real buttons and fields, what it sets on tags themes style (links, lists, headings, images…), and the root width (a theme may narrow it, never widen it) */

.kodza-theme-toggle:not(#_) {
  display: inline-grid;
  grid-auto-flow: column;
  flex: none;
  place-items: center;
  box-sizing: border-box;
  width: var(--kz-theme-toggle-size);
  height: var(--kz-theme-toggle-size);
  margin: 0;
  padding: 0;
  border: 0;
  border-radius: var(--kz-radius-pill, 999px);
  background: var(--kz-theme-toggle-surface);
  color: var(--kz-theme-toggle-ink);
  font: inherit;
  line-height: 1;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  transition: background-color calc(0.2s * var(--kz-motion-scale, 1)) ease,
    color 0s linear calc(var(--kz-theme-toggle-recolor) * var(--kz-motion-scale, 1)),
    scale calc(0.15s * var(--kz-motion-scale, 1)) cubic-bezier(0.22, 1, 0.36, 1);
}

.kodza-theme-toggle:focus-visible:not(#_) {
  outline: 2px solid var(--kz-theme-toggle-ink);
  outline-offset: 3px;
}

.kodza-theme-toggle:active:not(#_) {
  scale: 0.94;
}

@media (hover: hover) {
  .kodza-theme-toggle:hover:not(#_) {
    background: var(--kz-theme-toggle-hover);
  }
}

.kodza-theme-toggle--label:not(#_) {
  gap: 8px;
  width: auto;
  padding: 0 16px 0 12px;
}

.kodza-theme-toggle__icon:not(#_) {
  display: block;
  transition-property: -webkit-mask-position, mask-position;
  transition-duration: 0s;
  transition-timing-function: var(--kz-theme-toggle-ease);
}

.kodza-theme-toggle.is-ready :is(.kodza-theme-toggle__icon, .kodza-theme-toggle__disc, .kodza-theme-toggle__rays, .kodza-theme-toggle__ray, .kodza-theme-toggle__word):where(svg):not(#_) {
  transition-duration: calc(var(--kz-theme-toggle-duration) * var(--kz-motion-scale, 1));
}

.kodza-theme-toggle.is-ready[aria-pressed="true"] .kodza-theme-toggle__icon:not(#_) {
  transition-delay: calc(var(--kz-theme-toggle-duration) * 0.18 * var(--kz-motion-scale, 1));
}

@media (prefers-reduced-motion: reduce) {
  .kodza-theme-toggle:not(#_) {
    transition-duration: 0.01ms !important;
    transition-delay: 0s !important;
  }
}

@media (prefers-reduced-motion: reduce) {
  .kodza-theme-toggle *:where(svg):not(#_) {
    transition-duration: 0.01ms !important;
    transition-delay: 0s !important;
  }
}
```

```js
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Theme Toggle
// Switches the page between light and dark. The theme is written where the site reads it, on <html>
// by default as data-theme="dark" or "light". It starts from the visitor's saved choice, else from
// what the page already says, else from the system setting, which it keeps following until the
// visitor makes a choice. Every toggle on the page stays in step, other tabs too. Images with a night
// version (data-dark-src) get it laid over the day one, loaded the first time the page goes dark.
// Settings, on the button: data-target (the element that carries the theme: by default the nearest
// one around the button that already has the attribute, else <html>), data-attribute (the attribute
// written, "data-theme" by default) or data-class (a class added in the dark, such as "dark",
// instead of the attribute), data-storage (the localStorage key, "kodza-theme" by default; empty,
// nothing is saved). A toggle that themes one part of the page (a section with its own data-theme)
// saves nothing unless data-storage says where, and keeps its theme when the system changes.
//
// Against a white flash on load, put this line in a script tag at the top of <head>, before the
// stylesheets (same key and attribute as the button):
// try{var t=localStorage.getItem('kodza-theme');document.documentElement.setAttribute('data-theme',t==='dark'||t==='light'?t:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(e){}
(() => {
  const SELECTOR = '[data-kodza-theme-toggle]';
  const TARGET = 'html'; // the element that carries the theme, when none around the button has it
  const ATTRIBUTE = 'data-theme'; // written "dark" or "light" on it
  const STORAGE = 'kodza-theme'; // where the visitor's choice is kept
  const NIGHT = 'img[data-dark-src]'; // images that have a night version
  // Shared by every toggle of the page, whichever copy of this script started it
  const PAIRED = Symbol.for('kodza theme-toggle pair'); // on an image already given its night twin
  const CHOSEN = Symbol.for('kodza theme-toggle chosen'); // on a target whose theme the visitor picked
  const system = window.matchMedia('(prefers-color-scheme: dark)');
  const valid = (theme) => (theme === 'dark' || theme === 'light' ? theme : null);

  // One instance, with its own state: two copies on a page never interfere. Everything it
  // starts is tied to `signal` (listeners get { signal }, observers and timers stop on its
  // 'abort' event), so kodza:destroy stops it all.
  function mount(root, signal) {
    const name = root.dataset.class;
    const attribute = root.dataset.attribute || ATTRIBUTE;
    const selector = root.dataset.target || (name ? TARGET : `[${attribute}]`);
    const target = root.closest(selector) || document.querySelector(root.dataset.target || TARGET) || document.documentElement;
    const page = target === document.documentElement;
    const key = root.hasAttribute('data-storage') ? root.dataset.storage : page ? STORAGE : '';
    const pairs = new Set(); // the pairs this toggle made, taken apart on destroy
    let live = false; // after the start, a change of theme is seen happening

    const stored = () => {
      if (!key) return null;
      try { return valid(localStorage.getItem(key)); } catch { return null; }
    };
    const store = (theme) => {
      if (!key) return;
      try { localStorage.setItem(key, theme); } catch { /* private mode: the choice lasts the page */ }
    };
    const given = () => (name ? (target.classList.contains(name) ? 'dark' : null) : valid(target.getAttribute(attribute)));
    const read = () => given() || 'light';
    const preferred = () => (system.matches ? 'dark' : 'light');

    // Each night image goes in a pair with its day one, the night twin a clone that keeps its
    // classes and size, so it lands exactly on top
    const pairUp = () => target.querySelectorAll(NIGHT).forEach((img) => {
      if (img[PAIRED] || img.classList.contains('kodza-theme-toggle-night')) return;
      const pair = document.createElement('span');
      pair.className = 'kodza-theme-toggle-pair';
      if (getComputedStyle(img).display === 'block') pair.classList.add('kodza-theme-toggle-pair--block');
      const night = img.cloneNode(false);
      ['id', 'src', 'srcset', 'sizes', 'loading', 'fetchpriority', 'data-dark-src'].forEach((attr) => night.removeAttribute(attr));
      night.alt = '';
      night.setAttribute('aria-hidden', 'true');
      night.classList.add('kodza-theme-toggle-night');
      img.replaceWith(pair);
      pair.append(img, night);
      img[PAIRED] = pair;
      pairs.add(pair);
    });

    // The night twins light up once their image is decoded, never as an empty box
    const shade = (dark) => target.querySelectorAll('.kodza-theme-toggle-pair').forEach((pair) => {
      const [img, night] = pair.children;
      if (!night) return;
      if (live) pair.classList.add('is-ready');
      if (!dark) return pair.classList.remove('is-night');
      if (!night.getAttribute('src')) night.src = img.dataset.darkSrc;
      night.decode().catch(() => {}).then(() => {
        if (!signal.aborted && read() === 'dark') pair.classList.add('is-night');
      });
    });

    const sync = () => {
      const theme = read();
      root.setAttribute('aria-pressed', String(theme === 'dark'));
      pairUp();
      shade(theme === 'dark');
    };
    const apply = (theme) => {
      if (given() !== theme) {
        if (name) target.classList.toggle(name, theme === 'dark');
        else target.setAttribute(attribute, theme);
      }
      sync();
    };

    // The visitor's choice first, then what the page says (the line in <head> wrote it), then the system
    const follows = page || !given(); // a part of the page with its own theme keeps it
    apply(stored() || given() || preferred());
    live = true;

    // Whoever changes the theme (another toggle, the site's own script), this button follows
    const observer = new MutationObserver(sync);
    observer.observe(target, { attributes: true, attributeFilter: [name ? 'class' : attribute] });

    root.addEventListener('click', () => {
      const theme = read() === 'dark' ? 'light' : 'dark';
      target[CHOSEN] = true;
      store(theme);
      apply(theme);
      root.dispatchEvent(new CustomEvent('kodza:theme-toggle', { bubbles: true, detail: { theme } }));
    }, { signal });

    system.addEventListener('change', () => {
      if (follows && !target[CHOSEN] && !stored()) apply(preferred());
    }, { signal });

    // Chosen in another tab
    window.addEventListener('storage', (event) => {
      if (key && event.key === key) apply(valid(event.newValue) || preferred());
    }, { signal });

    signal.addEventListener('abort', () => {
      observer.disconnect();
      pairs.forEach((pair) => {
        const img = pair.firstElementChild;
        delete img[PAIRED];
        pair.replaceWith(img);
      });
    });
  }

  // Kodza lifecycle, the same in every component: `kodza:init` starts the instances inside
  // event.detail.root (the whole page by default), `kodza:destroy` stops them and puts their
  // markup back. For themes and apps that swap content without a page load. Each running root
  // keeps its markup as written under KODZA, shared by every Kodza script on the page: a Kodza
  // component inside another one is saved as written, not half-started, and stopped with it. Two
  // components on one root (a reveal on a stat card) both start, and stop together.
  const KODZA = Symbol.for('kodza');
  const RUNNING = Symbol.for(`kodza ${SELECTOR}`); // a root this component runs on, for every copy of this script
  const instances = new WeakMap();
  const find = (scope = document) => [scope, ...scope.querySelectorAll(SELECTOR)].filter((el) => el.matches?.(SELECTOR));
  const attrsOf = (el) => [...el.attributes].map((a) => [a.name, a.value]);
  const put = (el, saved) => {
    [...el.attributes].forEach((a) => el.removeAttribute(a.name));
    saved.attrs.forEach(([name, value]) => el.setAttribute(name, value));
    el.innerHTML = saved.html;
  };
  // The markup inside a root as written: Kodza components already running in it give back their own
  const written = (root) => {
    const all = [...root.querySelectorAll('*')];
    if (!all.some((el) => el[KODZA])) return root.innerHTML;
    const copy = root.cloneNode(true);
    const twins = copy.querySelectorAll('*');
    let last = null;
    all.forEach((el, i) => {
      if (!el[KODZA] || last?.contains(el)) return;
      last = el;
      put(twins[i], el[KODZA]);
    });
    return copy.innerHTML;
  };
  const init = (scope) => find(scope).forEach((root) => {
    // Already running, maybe from another copy of this script. Marked is-ready with no Kodza component
    // running on it, a root is a copy of a started one (a cloned slide): it is left as it is
    if (root[RUNNING] || (root.classList.contains('is-ready') && !root[KODZA])) return;
    // Rendered by React (data-kodza-manual): React starts it, with an init aimed at that markup once
    // it has hydrated it. Any earlier start would change markup React has not taken over yet
    const owner = root.closest('[data-kodza-manual]');
    if (owner && !(scope && owner.contains(scope))) return;
    const controller = new AbortController();
    // Another Kodza component already running on this root: its markup as written is kept, and the
    // two stop together
    const before = root[KODZA];
    const saved = { html: before ? before.html : written(root), attrs: before ? before.attrs : attrsOf(root), stop: () => destroy(root) };
    if (before) before.above = saved;
    instances.set(root, { controller, saved, before });
    root[KODZA] = saved;
    root[RUNNING] = true;
    mount(root, controller.signal);
    root.classList.add('is-ready');
  });
  const destroy = (scope) => find(scope).forEach((root) => {
    const instance = instances.get(root);
    if (!instance) return;
    instances.delete(root);
    instance.saved.above?.stop(); // a Kodza component started after it on the same root stops first
    // The Kodza components running inside it stop first: once its markup is put back, their own
    // script could not find them any more
    root.querySelectorAll('*').forEach((el) => el[KODZA]?.stop());
    instance.controller.abort();
    delete root[RUNNING];
    // Started on top of another one: that one stops next, and puts the markup back
    if (instance.before) {
      delete instance.before.above;
      root[KODZA] = instance.before;
      return instance.before.stop();
    }
    delete root[KODZA];
    put(root, instance.saved);
  });
  document.addEventListener('kodza:init', (event) => init(event.detail?.root));
  document.addEventListener('kodza:destroy', (event) => destroy(event.detail?.root));
  init();
  // Loaded in <head>, the script runs before the markup exists: once more when it is parsed
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init(), { once: true });
})();
```

Free to use, from Kodza (https://kodza.dev).
