Skip to content
Domphy

Toggle Group

All-in-one toggle group — a single- or multi-select button group. Apply toggleGroup({ items }) to a wrapper element — it sets role="group" on the wrapper and generates <button> toggles with aria-pressed from the items array. In single-select mode, clicking the selected item again deselects it; set multiple: true to allow several items at once.

PropTypeDefaultDescription
itemsToggleItem[][]Item definitions { label, key? }. label is a plain string (auto-wrapped) or any DomphyElement; key defaults to the item's zero-based index as a string.
valueValueOrState<string | string[]>"" (single) or [] (multiple)Selected key(s). Pass a State to control selection externally.
multiplebooleanfalseAllow multiple toggles selected at once.
colorThemeColor"neutral"Background and border tone for the group.
accentColorThemeColor"primary"Color tone for the pressed state.
Customization

Must see the source of patch at the bottom of each patch page to understand the structure then code it still code as html native element.

There are four levels of customization, in increasing order of effort:

  1. Patch props. Each patch exposes a small, stable set of props—typically fewer than five. Lowest friction.
  2. Context attributes. Use dataTone, dataSize, and dataDensity on a container to shift tone, size, or density for an entire subtree without touching individual elements.
  3. Inline override. Native-wins merge strategy: any property set directly on the element overrides the patch value.
  4. Create a variant. Clone a similar patch and edit it. Use this only when you need a reusable custom version.
Formulas

Unit - U = fontSize / 4 - convert final values with themeSpacing(n).

Size - n = intrinsic text lines, w = wrapping level, d = density factor:

height        = (n * 6 + 2 * d * w) * U
paddingBlock  = d * w * U
paddingInline = ceil(3 / w) * d * w * U
radius        = d * w * U

Base density d = 1.5:

Uw=0w=1w=2w=3
height (n = 1)691215
paddingBlock01.534.5
paddingInline34.564.5
radius01.534.5

Tone - K = N / 2 where N is the palette length. For N = 18, K = 9.

RoleShiftn=0
Backgroundparent +/- n0
Textbg + K6
Borderbg + K/23
Hoverbg + 2K/34
Selected / Focusabove +/- K/32-4

State shift range: K/3 <= delta <= 2K/3.

import {
  type DomphyElement,
  type Listener,
  type PartialElement,
  toState,
  type ValueOrState,
} from "@domphy/core";
import {
  type ThemeColor,
  themeColor,
  themeSize,
  themeSpacing,
} from "@domphy/theme";
import { focusRing } from "../utils/focusRing.js";

/** One item inside a toggle group. */
type ToggleItem = {
  /** Button label — plain string (auto-wrapped) or any DomphyElement. */
  label: string | DomphyElement;
  /** Stable key. Defaults to the item's zero-based index as a string. */
  key?: string;
};

/**
 * All-in-one toggle group — single or multi-select button group. Generates
 * `<button>` toggle elements from the `items` array. Apply to any wrapper element.
 *
 * @param props.items - Item definitions `{ label, key? }`.
 * @param props.value - Selected key(s) (value or State). Defaults to `[]` (multiple) or `""` (single).
 * @param props.multiple - Allow multiple items selected at once. Defaults to `false`.
 * @param props.color - Theme color for the group background/border. Defaults to `"neutral"`.
 * @param props.accentColor - Theme color for the pressed state. Defaults to `"primary"`.
 * @example
 * { div: null, $: [toggleGroup({ multiple: true, items: [
 *   { label: "Bold",   key: "bold"   },
 *   { label: "Italic", key: "italic" },
 * ] })] }
 */
function toggleGroup(
  props: {
    items: ToggleItem[];
    value?: ValueOrState<string | string[]>;
    multiple?: boolean;
    color?: ThemeColor;
    accentColor?: ThemeColor;
  } = { items: [] },
): PartialElement {
  const {
    items = [],
    multiple = false,
    color = "neutral",
    accentColor = "primary",
  } = props;
  const value = toState(props.value ?? (multiple ? [] : ""));

  return {
    role: "group",
    // Expose value + multiple in context so toggle() escape-hatch still works.
    _context: { toggleGroup: { value, multiple } },
    _onSchedule: (node, element) => {
      const buttons: DomphyElement<"button">[] = items.map((item, index) => {
        const key = item.key ?? String(index);
        const labelEl: DomphyElement =
          typeof item.label === "string"
            ? ({ span: item.label } as DomphyElement<"span">)
            : item.label;

        return {
          button: [labelEl],
          _key: key,
          type: "button",
          role: "button",
          ariaPressed: (l: Listener) => {
            const val = value.get(l);
            return Array.isArray(val) ? val.includes(key) : val === key;
          },
          onClick: () => {
            const val = value.get();
            if (multiple) {
              const arr = Array.isArray(val) ? [...val] : [];
              value.set(
                arr.includes(key)
                  ? arr.filter((v) => v !== key)
                  : [...arr, key],
              );
            } else {
              value.set(val === key ? "" : key);
            }
          },
          style: {
            cursor: "pointer",
            fontSize: (l: Listener) => themeSize(l, "inherit"),
            height: themeSpacing(6),
            paddingBlock: themeSpacing(1),
            paddingInline: themeSpacing(2),
            border: "none",
            borderRadius: themeSpacing(1.5),
            // Unpressed: shift-13 for readable resting labels (catalog contrast).
            color: (l: Listener) => themeColor(l, "shift-13", color),
            backgroundColor: (l: Listener) => themeColor(l, "inherit", color),
            transition:
              "background-color 140ms ease, color 140ms ease, box-shadow 140ms ease",
            "&:hover:not([disabled]):not([aria-pressed=true])": {
              color: (l: Listener) => themeColor(l, "shift-13", color),
              backgroundColor: (l: Listener) => themeColor(l, "hover", color),
            },
            "&:active:not([disabled])": {
              backgroundColor: (l: Listener) =>
                themeColor(l, "increase-2", color),
            },
            "&[aria-pressed=true]": {
              backgroundColor: (l: Listener) =>
                themeColor(l, "shift-3", accentColor),
              color: (l: Listener) => themeColor(l, "shift-13", accentColor),
            },
            "&:focus-visible": {
              boxShadow: (l: Listener) => focusRing(l, accentColor),
            },
            "&[disabled]": {
              opacity: 0.7,
              cursor: "not-allowed",
            },
          },
        } as DomphyElement<"button">;
      });

      (element as any)[node.tagName] = buttons;
    },
    style: {
      display: "flex",
      paddingBlock: themeSpacing(1),
      paddingInline: themeSpacing(1),
      gap: themeSpacing(1),
      borderRadius: themeSpacing(2),
      fontSize: (l: Listener) => themeSize(l, "inherit"),
      backgroundColor: (l: Listener) => themeColor(l, "inherit", color),
      color: (l: Listener) => themeColor(l, "text", color),
      outline: (l: Listener) => `1px solid ${themeColor(l, "border", color)}`,
      outlineOffset: "-1px",
    },
  };
}

export { toggleGroup };
export type { ToggleItem };