Skip to content
Domphy

Segmented

All-in-one single-select segmented control. Apply segmented({ items }) to a wrapper element — it sets role="radiogroup" on the wrapper and generates role="radio" <button> options from the items array. The container has an inline pill style with a muted background.

PropTypeDefaultDescription
itemsSegmentedItem[][]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>first item's keyInitially selected key. Pass a State to control selection externally.
colorThemeColor"neutral"Background tone of the pill container.
accentColorThemeColor"primary"Color tone for the selected item.
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 { elevation } from "../utils/elevation.js";
import { focusRing } from "../utils/focusRing.js";

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

/**
 * All-in-one single-select segmented control. Generates `<button>` option
 * elements from the `items` array. Apply to any wrapper element.
 *
 * @param props.items - Item definitions `{ label, key? }`.
 * @param props.value - Initially selected key (value or State). Defaults to the first item's key.
 * @param props.color - Theme color for the control background. Defaults to `"neutral"`.
 * @param props.accentColor - Theme color for the selected item. Defaults to `"primary"`.
 * @example
 * { div: null, $: [segmented({ items: [
 *   { label: "Day",   key: "day"   },
 *   { label: "Month", key: "month" },
 *   { label: "Year",  key: "year"  },
 * ] })] }
 */
function segmented(
  props: {
    items: SegmentedItem[];
    value?: ValueOrState<string>;
    color?: ThemeColor;
    accentColor?: ThemeColor;
  } = { items: [] },
): PartialElement {
  const { items = [], color = "neutral", accentColor = "primary" } = props;
  const value = toState(props.value ?? items[0]?.key ?? "");

  return {
    role: "radiogroup",
    // Expose value in context so segmentedItem() escape-hatch still works.
    _context: { segmented: { value } },
    _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: "radio",
          ariaChecked: (l: Listener) => value.get(l) === key,
          onClick: () => value.set(key),
          style: {
            cursor: "pointer",
            fontSize: (l: Listener) => themeSize(l, "inherit"),
            height: themeSpacing(6),
            paddingBlock: themeSpacing(1),
            paddingInline: themeSpacing(3),
            border: "none",
            borderRadius: themeSpacing(10),
            color: (l: Listener) => themeColor(l, "text", color),
            backgroundColor: "transparent",
            transition:
              "background-color 140ms ease, color 140ms ease, box-shadow 140ms ease",
            "&:hover:not([disabled]):not([aria-checked=true])": {
              backgroundColor: (l: Listener) => themeColor(l, "shift-3", color),
            },
            "&:active:not([disabled]):not([aria-checked=true])": {
              backgroundColor: (l: Listener) =>
                themeColor(l, "increase-2", color),
            },
            "&[aria-checked=true]": {
              backgroundColor: (l: Listener) =>
                themeColor(l, "shift-0", accentColor),
              color: (l: Listener) => themeColor(l, "shift-10", accentColor),
              // Selected segment sits slightly above the track.
              boxShadow: elevation("low"),
            },
            "&:focus-visible": {
              boxShadow: (l: Listener) => focusRing(l, accentColor),
            },
            "&[aria-checked=true]:focus-visible": {
              boxShadow: (l: Listener) =>
                `${elevation("low")}, ${focusRing(l, accentColor)}`,
            },
            "&[disabled]": {
              opacity: 0.7,
              cursor: "not-allowed",
            },
          },
        } as DomphyElement<"button">;
      });

      (element as any)[node.tagName] = buttons;
    },
    // Track is a soft surface anchor — shift via dataTone, paint with inherit.
    dataTone: "shift-2",
    style: {
      display: "inline-flex",
      paddingBlock: themeSpacing(1),
      paddingInline: themeSpacing(1),
      gap: themeSpacing(0.5),
      borderRadius: themeSpacing(10),
      backgroundColor: (l: Listener) => themeColor(l, "inherit", color),
      color: (l: Listener) => themeColor(l, "text", color),
    },
  };
}

export { segmented };
export type { SegmentedItem };