Skip to main content
astrocraft-ui/ components · 101

Toggle

Free · MIT

Headless, accessible, and styled entirely through the attribute surface below — bring your own CSS system, or start from the reference theme.

Install

Without a flag you get no styling at all — plain HTML carrying the attribute surface below. --theme copies the same theme in two dialects;--bridge lumos re-points either one onto Lumos for Astro's tokens (it needs a theme to re-point, and Lumos itself, already in your project).

Unstyled — behavior only, you write the CSS

Install command
npx astrocraft-ui add forms/toggle

Plain-CSS theme — no build step

Install command
npx astrocraft-ui add forms/toggle --theme css

Tailwind theme — needs Tailwind v4

Install command
npx astrocraft-ui add forms/toggle --theme tailwind

Plain-CSS theme, re-pointed onto Lumos tokens

Install command
npx astrocraft-ui add forms/toggle --theme css --bridge lumos

Tailwind theme, re-pointed onto Lumos tokens

Install command
npx astrocraft-ui add forms/toggle --theme tailwind --bridge lumos

Live demo

Toggle & ToggleGroup

State is aria-pressed and nothing else. The group is one tab stop — tab into it, then use the arrow keys.

Attribute surface

With no class-merging machinery, these attributes are the whole extension point. State is a data-attribute or a native attribute; visibility is the hiddenattribute. Generated from source by pnpm slots.

ComponentSlotsVariantsRuntime stateNative state
`Toggle.astro``toggle``data-variant`: `primary` · `secondary` · `outline` · `ghost`
`data-size`: `sm` · `md` · `lg`
—`[aria-pressed]`
`ToggleGroup.astro``toggle-group``data-type`: `single` · `multiple`
`data-orientation`: `horizontal` · `vertical`
——
`ToggleGroupItem.astro``toggle-group-item``data-variant`: `primary` · `secondary` · `outline` · `ghost`
`data-size`: `sm` · `md` · `lg`
—`[aria-pressed]`

Source

What the command copies — 4 files, alias-free so the copy lands standing alone. This is the whole component; there is nothing else.

src/components/ui/forms/toggle/Toggle.astro
---
// src/components/ui/forms/toggle/Toggle.astro — headless primitive (see ../../README.md).
// A two-state button (bold, mute, pin). The script flips `aria-pressed` and that is ALL it does —
// the state lives in the attribute the button already needs for assistive tech, so a theme paints it
// with `[data-slot="toggle"][aria-pressed="true"]` and no class is ever touched (contract rule 4).
// That is the PasswordInput lesson applied: one source of truth, already in the DOM.
//
// Not a checkbox: a toggle button acts immediately, a checkbox is a value you submit with a form.
// If the state is part of the form, use Switch or Checkbox instead.
// Carries Button's `data-variant` / `data-size` surface so one theme rule set styles them together.
import type { HTMLAttributes } from "astro/types";

type Props = HTMLAttributes<"button"> & {
  variant?: "primary" | "secondary" | "outline" | "ghost";
  size?: "sm" | "md" | "lg";
  pressed?: boolean;
};

const {
  variant = "outline",
  size = "md",
  pressed = false,
  class: className,
  ...rest
} = Astro.props;
---

<button
  type="button"
  class={className}
  data-slot="toggle"
  data-variant={variant}
  data-size={size}
  aria-pressed={pressed ? "true" : "false"}
  {...rest}
>
  <slot />
</button>

<script>
  import { onReadyOnce } from "../../_once";

  function wire(button: HTMLElement) {
    button.addEventListener("click", () => {
      button.setAttribute("aria-pressed", String(button.getAttribute("aria-pressed") !== "true"));
    });
  }

  onReadyOnce('[data-slot="toggle"]', wire);
</script>
src/components/ui/forms/toggle/ToggleGroup.astro
---
// src/components/ui/forms/toggle/ToggleGroup.astro — headless primitive (see ../../README.md).
// A row of toggle buttons: `type="single"` is a segmented control (picking one clears the rest),
// `type="multiple"` lets any number be pressed. State is each item's `aria-pressed`; nothing else.
//
// The script adds the two things a plain row of buttons does not have:
//   • roving tabindex — the group is ONE tab stop and the arrow keys move within it, which is what
//     the toolbar pattern asks for. Until it runs every item is individually tabbable, so the group
//     is still fully operable with JavaScript off.
//   • exclusivity in `single` mode, which nothing in HTML provides for buttons.
//
// `aria-pressed` rather than `role="radio"` in single mode, deliberately: these are buttons that act
// on the spot, not a value being chosen for submission. A radio group that submits is RadioGroup.
import type { HTMLAttributes } from "astro/types";

type Props = HTMLAttributes<"div"> & {
  type?: "single" | "multiple";
  orientation?: "horizontal" | "vertical";
};

const { type = "single", orientation = "horizontal", class: className, ...rest } = Astro.props;
---

<div
  class={className}
  role="group"
  data-slot="toggle-group"
  data-type={type}
  data-orientation={orientation}
  {...rest}
>
  <slot />
</div>

<script>
  import { onReadyOnce } from "../../_once";

  function wire(root: HTMLElement) {
    const items = [...root.querySelectorAll<HTMLElement>('[data-slot="toggle-group-item"]')];
    if (items.length === 0) return;
    const single = root.dataset.type !== "multiple";

    const rove = (to: HTMLElement) => {
      for (const item of items) item.tabIndex = item === to ? 0 : -1;
      to.focus();
    };

    // One tab stop into the group: the pressed item if there is one, otherwise the first.
    const entry = items.find((i) => i.getAttribute("aria-pressed") === "true") ?? items[0];
    for (const item of items) item.tabIndex = item === entry ? 0 : -1;

    items.forEach((item, i) => {
      item.addEventListener("click", () => {
        // The tab stop follows the CLICK, and before the early return below. A click focuses the
        // item, and the toolbar pattern is "one tab stop, restored to whatever last had focus" — so
        // without this, clicking the second option left the tab stop on the first: tab away, tab
        // back, and you land on an item that is not the one you chose. Only `rove()` moved it
        // before, and `rove()` only runs on arrow keys, so this was invisible to keyboard testing
        // and to every mouse user who never pressed Tab afterwards.
        for (const other of items) other.tabIndex = other === item ? 0 : -1;

        const pressed = item.getAttribute("aria-pressed") === "true";
        // In single mode the pressed item stays pressed when clicked again — a segmented control
        // always has a selection, and clearing it leaves the control saying nothing.
        if (single && pressed) return;
        item.setAttribute("aria-pressed", String(!pressed));
        if (!single) return;
        for (const other of items) {
          if (other !== item) other.setAttribute("aria-pressed", "false");
        }
      });

      item.addEventListener("keydown", (event) => {
        const moves: Record<string, number | "home" | "end"> = {
          ArrowRight: 1,
          ArrowDown: 1,
          ArrowLeft: -1,
          ArrowUp: -1,
          Home: "home",
          End: "end",
        };
        const move = moves[event.key];
        if (move === undefined) return;
        event.preventDefault();
        const next =
          move === "home"
            ? 0
            : move === "end"
              ? items.length - 1
              : (i + move + items.length) % items.length;
        rove(items[next]);
      });
    });
  }

  onReadyOnce('[data-slot="toggle-group"]', wire);
</script>
src/components/ui/forms/toggle/ToggleGroupItem.astro
---
// src/components/ui/forms/toggle/ToggleGroupItem.astro — ToggleGroup compound part (see ../../README.md).
// One button in the group. `pressed` marks the item that starts selected — in a `single` group set it
// on exactly one, since the group script treats the first pressed item as the group's tab stop.
// No `tabindex` is rendered: until ToggleGroup's script runs every item is tabbable, which is the
// right fallback. Carries Button's `data-variant` / `data-size` surface.
import type { HTMLAttributes } from "astro/types";

type Props = HTMLAttributes<"button"> & {
  variant?: "primary" | "secondary" | "outline" | "ghost";
  size?: "sm" | "md" | "lg";
  pressed?: boolean;
};

const {
  variant = "outline",
  size = "md",
  pressed = false,
  class: className,
  ...rest
} = Astro.props;
---

<button
  type="button"
  class={className}
  data-slot="toggle-group-item"
  data-variant={variant}
  data-size={size}
  aria-pressed={pressed ? "true" : "false"}
  {...rest}
>
  <slot />
</button>
src/components/ui/forms/toggle/index.ts
import Toggle from "./Toggle.astro";
import ToggleGroup from "./ToggleGroup.astro";
import ToggleGroupItem from "./ToggleGroupItem.astro";

export { Toggle, ToggleGroup, ToggleGroupItem };
export default Toggle;

What you get

The component source, copied into your project by npx astrocraft-ui add forms/toggle — no package dependency, no CSS to fight. Whatever the paid blocks compose, this is it.