# Segmented Control

> Two to five exclusive choices on real radio buttons. An ink pill slides to the one you pick, stretching on the way, and the labels turn white exactly at its edges.

Forms · segmented control, toggle, radio, pricing toggle, form · HTML, CSS, vanilla JS · no dependencies · updated 2026-11-03
Demo: https://kodza.dev/components/segmented-control/
Source on GitHub: https://github.com/kodza-dev/kodza/tree/main/components/segmented-control

## Files

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

- [`kodza-segmented-control.css`](https://kodza.dev/registry/segmented-control/kodza-segmented-control.css) · 14.0 KB
- [`kodza-segmented-control.js`](https://kodza.dev/registry/segmented-control/kodza-segmented-control.js) · 11.2 KB
- [`kodza-segmented-control.html`](https://kodza.dev/registry/segmented-control/kodza-segmented-control.html) · 3.6 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-segmented-control.css https://kodza.dev/registry/segmented-control/kodza-segmented-control.css
curl -fsSL --create-dirs -o kodza/kodza-segmented-control.js https://kodza.dev/registry/segmented-control/kodza-segmented-control.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: `.kodza-segmented`
- Variables (set them on the root element itself: it declares its own defaults):
  - `--kz-segmented-bg: #ffffff`
  - `--kz-segmented-fg: #0a0a0a`
  - `--kz-segmented-muted: rgba(10, 10, 10, 0.58)`
  - `--kz-segmented-border: rgba(10, 10, 10, 0.1)`
  - `--kz-segmented-ink: #0a0a0a`
  - `--kz-segmented-on-ink: #ffffff`
  - `--kz-segmented-badge: rgba(10, 10, 10, 0.07)` — the badge on the track
  - `--kz-segmented-badge-on-ink: rgba(255, 255, 255, 0.2)` — the badge under the pill
  - `--kz-segmented-height: 44px` — the whole pill; the options are 2 × --kz-segmented-pad shorter
  - `--kz-segmented-pad: 4px` — the room around the ink pill
  - `--kz-segmented-width: var(--kz-field-width, 360px)` — --block: the width it fills, at most
  - `--kz-segmented-duration: 0.55s` — the slide of the pill. 0s = no motion
- Modifiers: `.kodza-segmented--block`, `.kodza-segmented--icons`
- 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 an option (focus in `.kodza-segmented__input`):
  - `ArrowRight` / `ArrowDown`: Picks the next option, round and round
  - `ArrowLeft` / `ArrowUp`: Picks the previous option, round and round

## 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-segmented {
    --kz-segmented-bg: #161616;
    --kz-segmented-fg: #f2f2f0;
    --kz-segmented-muted: rgba(242, 242, 240, 0.62);
    --kz-segmented-border: rgba(255, 255, 255, 0.12);
    --kz-segmented-ink: #f2f2f0;
    --kz-segmented-on-ink: #0a0a0a;
    --kz-segmented-badge: rgba(255, 255, 255, 0.1);
    --kz-segmented-badge-on-ink: rgba(10, 10, 10, 0.12);
  }
}
```

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

## Use it

### Plain HTML page

- CSS: `kodza/kodza-segmented-control.css` next to the page (the Files commands as they are), linked in `<head>`: `<link rel="stylesheet" href="kodza/kodza-segmented-control.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.
- JS: `kodza/kodza-segmented-control.js`, loaded with `<script src="kodza/kodza-segmented-control.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); `--kz-font-mono`, the monospace face (code, labels, counters). 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).
- Width: a form sets it once for every Kodza field, on the form or on `:root` (`--kz-field-width: 100%` fills the column). Unset, nothing changes.
- 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-segmented-control.css' -e 'd' -e '}' -e '/^KODZA-JS$/{r kodza/kodza-segmented-control.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); `--kz-font-mono`, the monospace face (code, labels, counters).
- 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).
- Width: a form sets it once for every Kodza field, on the form or on `:root` (`--kz-field-width: 100%` fills the column). Unset, nothing changes.
- 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.
- Forms: there is nowhere to send them. Handle `submit` in your script with `event.preventDefault()` and show the result in the page.

### 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-segmented-control', $uri . 'kodza-segmented-control.css', [], filemtime($dir . 'kodza-segmented-control.css'));
    wp_enqueue_script('kodza-segmented-control', $uri . 'kodza-segmented-control.js', [], filemtime($dir . 'kodza-segmented-control.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: by default, match the theme's palette. After the component's CSS, point these variables at the theme's colours, on the component root, Kodza's value as the fallback:
  `.kodza-segmented { --kz-segmented-fg: var(TEXT, #0a0a0a); --kz-segmented-bg: var(BACKGROUND, #ffffff); --kz-segmented-ink: var(ACCENT, #0a0a0a); --kz-segmented-on-ink: var(BACKGROUND, #ffffff); }`
  TEXT, BACKGROUND and ACCENT (the colour the theme fills its own buttons with) are the theme's own colour variables — block themes (theme.json, like Twenty Twenty-Five): `--wp--preset--color--contrast`, `--wp--preset--color--base`, `--wp--preset--color--contrast` (they fill their buttons with it; their accent-1… colours are decorative); Astra: `--ast-global-color-2`, `--ast-global-color-4`, `--ast-global-color-0`; Kadence: `--global-palette3`, `--global-palette9`, `--global-palette1`; GeneratePress: `--contrast`, `--base-3`, `--accent`; Blocksy: `--theme-palette-color-4`, `--theme-palette-color-8`, `--theme-palette-color-1`. Use only these names, and only if the site really has them (the theme's CSS, or Styles → Colors): the `--wp--preset--color--black`, `--white`, `--vivid-…` that WordPress adds everywhere are not the theme's palette. Another theme, or one without these variables (Hello Elementor, OceanWP): leave the variables alone, it keeps Kodza's monochrome; same when the developer asks for monochrome or the Kodza look. Leave the translucent greys (`rgba(10, 10, 10, …)`) as they are: they suit any light background. On a dark palette, set the other variables from Dark mode too.
- 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.

### Shopify

- Files: `assets/kodza-segmented-control.css` and `assets/kodza-segmented-control.js` (the Files commands with `-o assets/…`).
- In the section: `{{ 'kodza-segmented-control.css' | asset_url | stylesheet_tag }}` and `<script src="{{ 'kodza-segmented-control.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`.

### React / Next.js

- Files, side by side (e.g. in `components/kodza/`): `SegmentedControl.tsx` (below), the CSS block under Code saved as `segmented-control.css` and the JS block as `segmented-control.js`, both as they are. The HTML block is already inside the component: skip it.
- Use it: `import { SegmentedControl } from '@/components/kodza/SegmentedControl';` then `<SegmentedControl />`. Props: `variant` ("block", "icons", or several in an array), `vars` (the `--kz-…` variables listed under API, e.g. `vars={{ '--kz-segmented-bg': … }}`), `className`, `style` and the other props of its `<fieldset>` (`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 './segmented-control.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 — Segmented Control, for React. From https://kodza.dev/components/segmented-control/
// 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: segmented-control.css and segmented-control.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 './segmented-control.css';

type Variant = "block" | "icons";

export type SegmentedControlProps = Omit<ComponentPropsWithoutRef<'fieldset'>, "children" | "variant" | "vars"> & {
  /** Modifier class(es): .kodza-segmented--block, .kodza-segmented--icons */
  variant?: Variant | Variant[];
  /** Settings, as CSS variables on the root */
  vars?: {
    /** default: #ffffff */
    "--kz-segmented-bg"?: string | number;
    /** default: #0a0a0a */
    "--kz-segmented-fg"?: string | number;
    /** default: rgba(10, 10, 10, 0.58) */
    "--kz-segmented-muted"?: string | number;
    /** default: rgba(10, 10, 10, 0.1) */
    "--kz-segmented-border"?: string | number;
    /** default: #0a0a0a */
    "--kz-segmented-ink"?: string | number;
    /** default: #ffffff */
    "--kz-segmented-on-ink"?: string | number;
    /** the badge on the track — default: rgba(10, 10, 10, 0.07) */
    "--kz-segmented-badge"?: string | number;
    /** the badge under the pill — default: rgba(255, 255, 255, 0.2) */
    "--kz-segmented-badge-on-ink"?: string | number;
    /** the whole pill; the options are 2 × --kz-segmented-pad shorter — default: 44px */
    "--kz-segmented-height"?: string | number;
    /** the room around the ink pill — default: 4px */
    "--kz-segmented-pad"?: string | number;
    /** --block: the width it fills, at most — default: var(--kz-field-width, 360px) */
    "--kz-segmented-width"?: string | number;
    /** the slide of the pill. 0s = no motion — default: 0.55s */
    "--kz-segmented-duration"?: string | number;
  };
  className?: string;
};

export function SegmentedControl({ variant, vars, className, style, ...rest }: SegmentedControlProps) {
  const ref = useRef<ComponentRef<'fieldset'>>(null);
  const classes = ["kodza-segmented", ...([] as string[]).concat(variant ?? []).map((v) => `kodza-segmented--${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('./segmented-control.js').then(() => {
      if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
    });
    return () => {
      live = false;
      document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
    };
  }, [key]);

  return (
    <fieldset key={key} {...rest} className={classes} data-kodza-manual style={{ ...vars, ...style } as CSSProperties} ref={ref}>
      <legend className="kodza-segmented__legend kodza-segmented__legend--hidden">Billing</legend>
      <div className="kodza-segmented__track">
        <label className="kodza-segmented__option">
          <input className="kodza-segmented__input" type="radio" name="billing" defaultValue="monthly" defaultChecked />
          {' '}
          <span className="kodza-segmented__label">Monthly</span>
        </label>
        {' '}
        <label className="kodza-segmented__option">
          <input className="kodza-segmented__input" type="radio" name="billing" defaultValue="annual" />
          {' '}
          <span className="kodza-segmented__label">Annual <span className="kodza-segmented__badge">−20%</span></span>
        </label>
      </div>
    </fieldset>
  );
}
```

## Code

```html
<fieldset class="kodza-segmented">
  <legend class="kodza-segmented__legend kodza-segmented__legend--hidden">Billing</legend>
  <div class="kodza-segmented__track">
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="billing" value="monthly" checked>
      <span class="kodza-segmented__label">Monthly</span>
    </label>
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="billing" value="annual">
      <span class="kodza-segmented__label">Annual <span class="kodza-segmented__badge">−20%</span></span>
    </label>
  </div>
</fieldset>

<fieldset class="kodza-segmented kodza-segmented--icons">
  <legend class="kodza-segmented__legend kodza-segmented__legend--hidden">View</legend>
  <div class="kodza-segmented__track">
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="view" value="list" checked>
      <span class="kodza-segmented__label">
        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" aria-hidden="true"><path d="M4 6.5h16M4 12h16M4 17.5h16"/></svg>
        <span class="kodza-segmented__name">List</span>
      </span>
    </label>
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="view" value="grid">
      <span class="kodza-segmented__label">
        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="4" y="13.5" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="13.5" width="6.5" height="6.5" rx="1.5"/></svg>
        <span class="kodza-segmented__name">Grid</span>
      </span>
    </label>
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="view" value="board">
      <span class="kodza-segmented__label">
        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="4" width="4.5" height="16" rx="1.5"/><rect x="9.75" y="4" width="4.5" height="11" rx="1.5"/><rect x="15.5" y="4" width="4.5" height="7" rx="1.5"/></svg>
        <span class="kodza-segmented__name">Board</span>
      </span>
    </label>
  </div>
</fieldset>

<fieldset class="kodza-segmented kodza-segmented--block">
  <legend class="kodza-segmented__legend">Size</legend>
  <div class="kodza-segmented__track">
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="size" value="xs">
      <span class="kodza-segmented__label">XS</span>
    </label>
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="size" value="s">
      <span class="kodza-segmented__label">S</span>
    </label>
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="size" value="m" checked>
      <span class="kodza-segmented__label">M</span>
    </label>
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="size" value="l">
      <span class="kodza-segmented__label">L</span>
    </label>
    <label class="kodza-segmented__option">
      <input class="kodza-segmented__input" type="radio" name="size" value="xl" disabled>
      <span class="kodza-segmented__label">XL</span>
    </label>
  </div>
</fieldset>
```

```css
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Segmented Control
   Two to five exclusive choices on real radio buttons, in one pill. An ink pill slides to the
   option you pick, its front edge first and its back edge catching up, like a drop of ink, and
   the labels turn white exactly at its edges. Arrow keys move the choice, like any radio group,
   and the form gets the value as usual. Without the script, the chosen option simply fills
   with ink.
   --block fills the width with equal segments (sizes, a form), --icons shows icons only (the
   names stay for screen readers), and a badge (−20%) can ride in a label.
   Everything is tuned with the --kz-segmented-* variables; the stretch of the pill, with the
   constants at the top of the script. */
.kodza-segmented {
  --kz-segmented-bg: #ffffff;
  --kz-segmented-fg: #0a0a0a;
  --kz-segmented-muted: rgba(10, 10, 10, 0.58);
  --kz-segmented-border: rgba(10, 10, 10, 0.1);
  --kz-segmented-ink: #0a0a0a;
  --kz-segmented-on-ink: #ffffff;
  --kz-segmented-badge: rgba(10, 10, 10, 0.07); /* the badge on the track */
  --kz-segmented-badge-on-ink: rgba(255, 255, 255, 0.2); /* the badge under the pill */
  --kz-segmented-height: 44px; /* the whole pill; the options are 2 × --kz-segmented-pad shorter */
  --kz-segmented-pad: 4px; /* the room around the ink pill */
  --kz-segmented-width: var(--kz-field-width, 360px); /* --block: the width it fills, at most */
  --kz-segmented-duration: 0.55s; /* the slide of the pill. 0s = no motion */

  display: inline-block;
  min-width: 0;
  max-width: 100%;
  margin: 0;
  padding: 0;
  border: 0;
  color: var(--kz-segmented-fg);
}

.kodza-segmented__legend {
  margin-bottom: 10px;
  padding: 0;
  font-family: var(--kz-font-label, var(--kz-font-mono, ui-monospace, "SF Mono", Menlo, monospace));
  font-size: var(--kz-font-label-size, 12px);
  font-weight: var(--kz-font-label-weight, inherit);
  line-height: var(--kz-font-label-leading, inherit);
  letter-spacing: var(--kz-font-label-tracking, inherit);
  text-transform: var(--kz-font-label-case, inherit);
  color: var(--kz-segmented-muted);
}

/* A name for screen readers only (a pricing toggle needs no visible title) */
.kodza-segmented__legend--hidden,
.kodza-segmented--icons .kodza-segmented__name {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.kodza-segmented__track {
  position: relative;
  display: flex;
  box-sizing: border-box;
  max-width: 100%;
  height: var(--kz-segmented-height);
  padding: var(--kz-segmented-pad);
  border-radius: var(--kz-radius-pill, 999px);
  background: var(--kz-segmented-bg);
  box-shadow: inset 0 0 0 1px var(--kz-segmented-border);
}

.kodza-segmented__option {
  position: relative;
  flex: 0 1 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  min-width: 0;
  height: 100%;
  margin: 0;
  padding: 0 16px;
  border-radius: var(--kz-radius-pill, 999px);
  cursor: pointer;
  user-select: none;
  -webkit-tap-highlight-color: transparent;
}

/* The state colours the text, not the option (the white copies hold their own) */
.kodza-segmented__option > .kodza-segmented__label {
  color: var(--kz-segmented-muted);
  transition: color calc(0.25s * var(--kz-motion-scale, 1)) ease;
}

/* The real radio covers its option: a click anywhere picks it */
.kodza-segmented__input {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  opacity: 0;
  cursor: inherit;
}

.kodza-segmented__label {
  display: flex;
  align-items: center;
  gap: 7px;
  min-width: 0;
  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: 1;
  letter-spacing: var(--kz-font-label-tracking, inherit);
  text-transform: var(--kz-font-label-case, inherit);
  white-space: nowrap;
}

.kodza-segmented__label svg {
  display: block;
  flex: none;
}

.kodza-segmented__badge {
  display: inline-flex;
  align-items: center;
  height: 20px;
  padding: 0 7px;
  border-radius: var(--kz-radius-pill, 999px);
  background: var(--kz-segmented-badge);
  color: var(--kz-segmented-fg);
  font-size: var(--kz-font-label-size, 12px);
  font-variant-numeric: tabular-nums;
  letter-spacing: 0;
  text-transform: none;
}

@media (hover: hover) {
  .kodza-segmented__option:hover > .kodza-segmented__label {
    color: var(--kz-segmented-fg);
  }
}

.kodza-segmented__option:has(.kodza-segmented__input:checked) > .kodza-segmented__label {
  color: var(--kz-segmented-fg);
}

.kodza-segmented__option:has(.kodza-segmented__input:focus-visible) {
  outline: 2px solid var(--kz-segmented-fg);
  outline-offset: 2px;
}

.kodza-segmented__option:has(.kodza-segmented__input:disabled) {
  cursor: not-allowed;
  opacity: 0.4;
}

/* Without the script: the chosen option fills with ink */
.kodza-segmented:not(.is-ready) .kodza-segmented__option:has(.kodza-segmented__input:checked) {
  background: var(--kz-segmented-ink);
}

.kodza-segmented:not(.is-ready) .kodza-segmented__option:has(.kodza-segmented__input:checked) > .kodza-segmented__label {
  color: var(--kz-segmented-on-ink);
}

/* The ink pill (added by the script): two windows slide in the lane, one cut at the pill's left
   edge, one at its right edge, while the ink inside them holds still. Only transforms move, so
   the slide stays smooth on a busy page, and the corners stay round */
.kodza-segmented__lane {
  position: absolute;
  inset: var(--kz-segmented-pad);
  overflow: hidden;
  pointer-events: none;
}

.kodza-segmented__pill,
.kodza-segmented__edge,
.kodza-segmented__mirror {
  position: absolute;
  inset: 0;
}

.kodza-segmented__pill {
  overflow: hidden;
  border-radius: var(--kz-radius-pill, 999px) 0 0 var(--kz-radius-pill, 999px);
  transform: translateX(var(--kz-seg-l, 0px));
}

.kodza-segmented__edge {
  overflow: hidden;
  border-radius: 0 var(--kz-radius-pill, 999px) var(--kz-radius-pill, 999px) 0;
  transform: translateX(calc(-1 * var(--kz-seg-l, 0px) - var(--kz-seg-r, 100%)));
}

/* The ink, with a white copy of the labels: the text turns white exactly at the edges of the
   pill, never all at once */
.kodza-segmented__mirror {
  background: var(--kz-segmented-ink);
  color: var(--kz-segmented-on-ink);
  transform: translateX(var(--kz-seg-r, 100%));
}

.kodza-segmented__ghost {
  position: absolute;
  top: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  padding: 0 16px;
}

.kodza-segmented__mirror .kodza-segmented__badge {
  background: var(--kz-segmented-badge-on-ink);
  color: var(--kz-segmented-on-ink);
}

/* --icons: round options around one icon */
.kodza-segmented--icons .kodza-segmented__option,
.kodza-segmented--icons .kodza-segmented__ghost {
  padding: 0 9px;
}

/* --block: the width of a form field, in equal segments */
.kodza-segmented--block {
  display: block;
  width: 100%;
  max-width: var(--kz-segmented-width);
}

.kodza-segmented--block .kodza-segmented__option {
  flex: 1 1 0;
  padding: 0 8px;
}

.kodza-segmented--block .kodza-segmented__ghost {
  padding: 0 8px;
}

@media (prefers-reduced-motion: reduce) {
  .kodza-segmented__option > .kodza-segmented__label {
    transition-duration: 0.01ms !important;
  }
}

/* Theming example — on a dark background:
.dark-section .kodza-segmented {
  --kz-segmented-bg: #161616;
  --kz-segmented-fg: #f2f2f0;
  --kz-segmented-muted: rgba(242, 242, 240, 0.62);
  --kz-segmented-border: rgba(255, 255, 255, 0.12);
  --kz-segmented-ink: #f2f2f0;
  --kz-segmented-on-ink: #0a0a0a;
  --kz-segmented-badge: rgba(255, 255, 255, 0.1);
  --kz-segmented-badge-on-ink: rgba(10, 10, 10, 0.12);
}
*/

/* kodza-guard b5ecb7ec5cd0 — 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-segmented__legend):not(#_) {
  position: revert;
  margin-top: revert;
  margin-right: revert;
  margin-left: revert;
  white-space: revert;
}

:where(.kodza-segmented__option):not(#_) {
  outline: revert;
  background-color: revert;
  background-image: revert;
  outline-offset: revert;
}

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

.kodza-segmented:not(#_) {
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-height: 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-segmented__legend:not(#_) {
  border: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  font-style: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-segmented__option:not(#_) {
  border: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  float: revert;
  box-shadow: 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-segmented__input:not(#_) {
  border: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: 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;
  white-space: revert;
  min-height: revert;
}

.kodza-segmented__label:not(#_),
.kodza-segmented__badge:not(#_),
.kodza-segmented__lane:not(#_),
.kodza-segmented__pill:not(#_),
.kodza-segmented__edge:not(#_),
.kodza-segmented__mirror:not(#_),
.kodza-segmented__name:not(#_) {
  box-sizing: revert;
}

.kodza-segmented__label svg:where(:not([class*="kodza-"])):not(#_) {
  border: revert;
  margin: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: 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-segmented__legend:not(#_):where(:not([hidden])),
.kodza-segmented__input:not(#_):where(:not([hidden])) {
  display: revert;
}

.kodza-segmented__legend:not(#_):where([hidden]),
.kodza-segmented__input:not(#_):where([hidden]) {
  display: none;
}

/* 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-segmented:not(#_) {
  display: inline-block;
  padding: 0;
  border: 0;
  color: var(--kz-segmented-fg);
}

.kodza-segmented__legend:not(#_) {
  margin-bottom: 10px;
  padding: 0;
  font-family: var(--kz-font-label, var(--kz-font-mono, ui-monospace, "SF Mono", Menlo, monospace));
  font-size: var(--kz-font-label-size, 12px);
  font-weight: var(--kz-font-label-weight, inherit);
  line-height: var(--kz-font-label-leading, inherit);
  letter-spacing: var(--kz-font-label-tracking, inherit);
  text-transform: var(--kz-font-label-case, inherit);
  color: var(--kz-segmented-muted);
}

.kodza-segmented__legend--hidden:not(#_) {
  position: absolute;
  margin: 0;
  white-space: nowrap;
}

.kodza-segmented__option:not(#_) {
  position: relative;
  display: flex;
  box-sizing: border-box;
  margin: 0;
  padding: 0 16px;
  border-radius: var(--kz-radius-pill, 999px);
}

.kodza-segmented__input:not(#_) {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  opacity: 0;
  cursor: inherit;
}

.kodza-segmented__label svg:not(#_) {
  display: block;
}

.kodza-segmented__option:has(.kodza-segmented__input:focus-visible):not(#_) {
  outline: 2px solid var(--kz-segmented-fg);
  outline-offset: 2px;
}

.kodza-segmented:not(.is-ready) .kodza-segmented__option:has(.kodza-segmented__input:checked):not(#_) {
  background: var(--kz-segmented-ink);
}

.kodza-segmented--icons .kodza-segmented__option:not(#_) {
  padding: 0 9px;
}

.kodza-segmented--block:not(#_) {
  display: block;
}

.kodza-segmented--block:not(#_) {
  width: min(100%, var(--kz-segmented-width));
}

.kodza-segmented--block .kodza-segmented__option:not(#_) {
  padding: 0 8px;
}
```

```js
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Segmented Control
// Adds the ink pill: it slides to the option you pick, its front edge first and its back edge
// catching up, with a white copy of the labels cut to the same shape. The radios stay native:
// arrow keys, the form value and the change event are the browser's. The stretch is tuned with
// the constants below (LEAD 1 and LAG 0: a plain slide).
(() => {
  const SELECTOR = '.kodza-segmented';
  const LEAD = 0.7; // the front edge arrives in this share of the slide
  const LAG = 0.14; // the back edge waits this share of the slide before it follows
  const SAMPLES = 30; // keyframes per slide: each edge follows its own curve
  const ease = (t) => 1 - (1 - t) ** 4; // close to cubic-bezier(0.22, 1, 0.36, 1)

  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  // The site's pace, --kz-motion-scale (set on :root, read on the instance): every duration of the
  // script times it, and 0 moves nothing, like reduced motion
  const paceOf = (el) => {
    const pace = parseFloat(getComputedStyle(el).getPropertyValue('--kz-motion-scale'));
    return pace >= 0 ? pace : 1;
  };
  const seconds = (value) => {
    const n = parseFloat(value);
    if (!(n >= 0)) return 0.55;
    return /ms\s*$/.test(value) ? n / 1000 : n;
  };

  // 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 pace = paceOf(root);
    const still = reduceMotion || !pace; // the still path: no motion asked, by the visitor or the site
    const track = root.querySelector('.kodza-segmented__track');
    const options = track ? [...track.querySelectorAll('.kodza-segmented__option')] : [];
    const inputs = options.map((option) => option.querySelector('.kodza-segmented__input'));
    if (!options.length || inputs.some((input) => !input)) return;
    const duration = seconds(getComputedStyle(root).getPropertyValue('--kz-segmented-duration')) * pace * 1000;

    // The pill over the labels: the lane, the window cut at its left edge (pill), the window cut
    // at its right edge (edge), and the ink with the white copy of the labels (mirror)
    const layer = (name) => {
      const el = document.createElement('span');
      el.className = `kodza-segmented__${name}`;
      return el;
    };
    const lane = layer('lane');
    lane.setAttribute('aria-hidden', 'true');
    const pill = layer('pill');
    const edge = layer('edge');
    const mirror = layer('mirror');
    const ghosts = options.map((option) => {
      const ghost = layer('ghost');
      const label = option.querySelector('.kodza-segmented__label');
      if (label) ghost.append(label.cloneNode(true));
      return ghost;
    });
    mirror.append(...ghosts);
    edge.append(mirror);
    pill.append(edge);
    lane.append(pill);
    track.append(lane);

    // Each option's place in the lane, in its own pixels (a parent scaled by a transform, like
    // a thumbnail, changes nothing)
    let boxes = [];
    const measure = () => {
      const box = lane.getBoundingClientRect();
      const scale = box.width / lane.offsetWidth || 1;
      const full = lane.offsetWidth;
      boxes = options.map((option) => {
        const rect = option.getBoundingClientRect();
        const left = (rect.left - box.left) / scale;
        const width = rect.width / scale;
        return { left, width, right: full - left - width };
      });
      ghosts.forEach((ghost, i) => {
        ghost.style.left = `${boxes[i].left}px`;
        ghost.style.width = `${boxes[i].width}px`;
      });
    };

    // The three moving layers for given edges: the windows put their cuts there, the ink cancels
    // their shift and stays put
    const shifts = ({ left, right }) => [left, -left - right, right];
    const rest = (edges) => {
      track.style.setProperty('--kz-seg-l', `${edges.left}px`);
      track.style.setProperty('--kz-seg-r', `${edges.right}px`);
    };

    // The edges at a point of a slide: the front edge (the side it goes to) leads, the back
    // edge follows, so the pill stretches on the way and shrinks back as it lands
    let move = null;
    const edgesAt = ({ from, to, forward, grow }, t) => {
      const front = ease(grow ? t : Math.min(1, t / LEAD));
      const back = grow ? front : ease(Math.max(0, (t - LAG) / (1 - LAG)));
      return {
        left: from.left + (to.left - from.left) * (forward ? back : front),
        right: from.right + (to.right - from.right) * (forward ? front : back),
      };
    };
    const now = () => {
      const t = move?.animations[0].currentTime;
      return move && t != null && move.animations[0].playState === 'running' ? edgesAt(move, Math.min(1, t / duration)) : null;
    };
    const stop = () => {
      move?.animations.forEach((animation) => animation.cancel());
      move = null;
    };
    // From nothing chosen, the pill opens from the middle of the option
    const slide = (from, to) => {
      stop();
      rest(to);
      if (still) return;
      const grow = !from;
      if (grow) from = { left: to.left + to.width / 2, right: to.right + to.width / 2 };
      const plan = { from, to, grow, forward: to.left > from.left };
      const frames = [[], [], []];
      for (let i = 0; i <= SAMPLES; i += 1) {
        shifts(edgesAt(plan, i / SAMPLES)).forEach((x, n) => frames[n].push({ transform: `translateX(${x}px)` }));
      }
      const timing = { duration, easing: 'linear' };
      move = { ...plan, animations: [pill, edge, mirror].map((el, n) => el.animate(frames[n], timing)) };
      move.animations[0].onfinish = () => { move = null; };
    };

    // Nothing chosen: the pill is cut down to nothing
    const clear = () => {
      stop();
      track.style.removeProperty('--kz-seg-l');
      track.style.removeProperty('--kz-seg-r');
    };

    let current = inputs.findIndex((input) => input.checked);
    const update = () => {
      const next = inputs.findIndex((input) => input.checked);
      if (next === current) return;
      const from = now() || boxes[current] || null;
      current = next;
      if (next < 0) return clear();
      slide(from, boxes[next]);
    };
    // A resize that leaves the options where they are (the page around it) lets a slide run on
    const place = () => {
      const before = boxes;
      measure();
      const same = move && boxes.every((box, i) => Math.abs(box.left - before[i].left) < 0.5 && Math.abs(box.width - before[i].width) < 0.5);
      if (same) return;
      stop();
      if (current >= 0) rest(boxes[current]);
      else clear();
    };

    root.addEventListener('change', update, { signal });
    // A form reset puts the radios back without a change event
    root.closest('form')?.addEventListener('reset', () => requestAnimationFrame(update), { signal });

    place();
    const observer = new ResizeObserver(place);
    observer.observe(track);
    signal.addEventListener('abort', () => {
      observer.disconnect();
      stop();
    });
    document.fonts?.ready.then(() => !signal.aborted && place());
  }

  // 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).
