Skip to content
Domphy

Select Item

Use selectItem on a <div> placed inside a selectList. It reads the select context to set aria-selected and handle click-to-toggle. In single mode the item becomes selected; in multiple mode it toggles its value in the array.

The item is role="option" with tabindex="-1" — the parent selectList owns the tab stop and moves focus between options (see Select List). The selected row uses the same fill/text pairing as button({ variant: "solid" }) (deep brand fill + light-end neutral text) so the chosen option's label clears WCAG AA 4.5.

Props

PropTypeDefaultDescription
valuestring | numbernullThe option value compared against and written to the select state.
colorThemeColor"neutral"Text and resting background tone.
accentColorThemeColor"primary"Selected state and focus tone.
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 { PartialElement } from "@domphy/core";
import {
  type ThemeColor,
  textToneOn,
  themeColor,
  themeDensity,
  themeSize,
  themeSpacing,
} from "@domphy/theme";
import { focusRing } from "../utils/focusRing.js";

/**
 * A single selectable option row (`role="option"`) for use inside a `selectList`. Reads the
 * `select` context to reflect/toggle selection: it sets `aria-selected` from the bound value and
 * toggles the value (single or multiple) on click. Styles hover/selected/focus states.
 *
 * @hostTag div
 * @param props.accentColor - Theme color tone for the selected/focus state. Defaults to `"primary"`.
 * @param props.color - Theme color tone for text/background. Defaults to `"neutral"`.
 * @param props.value - The option value compared against and written to the select state.
 *   Defaults to `null`.
 * @example { div: "Option A", $: [selectItem({ value: "a" })] }
 */
function selectItem(
  props: {
    accentColor?: ThemeColor;
    color?: ThemeColor;
    value?: number | string;
  } = {},
): PartialElement {
  const { accentColor = "primary", color = "neutral", value = null } = props;

  const partial: PartialElement = {
    role: "option",
    // Programmatically focusable (not tabbable): selectBox typeahead and
    // keyboard navigation move focus between options roving-style.
    tabindex: -1,
    // aria-selected and the click toggler must be DECLARED on the partial, not
    // wired imperatively in _onInit: hooks run once per real DOM node, but
    // patch() resets _events and strips undeclared attributes on every
    // ancestor re-render — so imperative wiring was lost on the first reuse
    // while the (once-run) hook never re-installed it. The reactive reader
    // resolves the `select` context lazily through listener.elementNode, so
    // every generation re-binds to whatever context is actually live.
    ariaSelected: (listener) => {
      const select = listener?.elementNode?.getContext("select");
      if (!select) return undefined;
      const val = select.value.get(listener);
      return select.multiple ? val.includes(value) : val === value;
    },
    onClick: (_e, node) => {
      const select = node.getContext("select");
      if (!select) return;
      const state = select.value;
      const val = state.get();
      if (select.multiple) {
        val.includes(value)
          ? state.set(val.filter((v: number | string) => v !== value))
          : state.set(val.concat([value]));
      } else {
        val !== value && state.set(value);
      }
    },
    _onInit: (node) => {
      if (node.tagName !== "div") {
        console.warn(`"selectItem" patch must use div tag`);
      }
    },
    style: {
      cursor: "pointer",
      display: "flex",
      alignItems: "center",
      fontSize: (listener) => themeSize(listener, "inherit"),
      // minHeight, not height: an inherited line-height taller than the row
      // must grow it rather than overflow the content box (see menu.ts).
      minHeight: (listener) => themeSpacing(6 + themeDensity(listener) * 2),
      paddingInline: (listener) => themeSpacing(themeDensity(listener) * 3),
      border: "none",
      outline: "none",
      color: (listener) => themeColor(listener, "text", color),
      backgroundColor: (listener) => themeColor(listener, "inherit", color),
      // Label tracks the hover fill (+2): a fixed "text" label measured
      // 3.58:1 against it (light) / 4.37:1 (dark), below WCAG AA.
      "&:hover:not([disabled]):not([aria-selected=true])": {
        backgroundColor: (listener) => themeColor(listener, "hover", color),
        color: (listener) => themeColor(listener, textToneOn(2), color),
      },
      // Selected row uses the same fill/text pairing as button({variant:"solid"}):
      // deep brand fill + light-end neutral text. The old shift-6 / shift-11
      // pairing measured ~2.6:1 in Chromium (axe `color-contrast`), below the
      // WCAG AA 4.5:1 floor for the label of the CHOSEN option.
      "&[aria-selected=true]": {
        backgroundColor: (listener) =>
          themeColor(listener, "shift-13", accentColor),
        color: (listener) => themeColor(listener, "shift-0", "neutral"),
      },
      transition: "background-color 140ms ease, box-shadow 140ms ease",
      "&:focus-visible": {
        boxShadow: (listener) => focusRing(listener, accentColor),
      },
    },
  };
  return partial;
}

export { selectItem };
import {
  type DomphyElement,
  type ElementNode,
  type PartialElement,
  toState,
  type ValueOrState,
} from "@domphy/core";
import {
  type ThemeColor,
  themeColor,
  themeDensity,
  themeSize,
  themeSpacing,
} from "@domphy/theme";
import { enabledOptionsIn } from "../utils/optionList.js";

// WAI-ARIA APG Listbox keyboard model: Down/Up move to the next/previous
// option, Home/End to the first/last, Enter/Space choose the focused option.
// Focus IS the highlight here (options carry tabindex=-1), matching the
// selectBox typeahead which already moves focus between options.
function onListboxKey(event: Event, node: ElementNode): void {
  const key = (event as KeyboardEvent).key;
  const host = node.domElement as HTMLElement | null;
  if (!host) return;
  const options = enabledOptionsIn(host);
  if (!options.length) return;
  const active = host.ownerDocument.activeElement as HTMLElement | null;
  const current = active ? options.indexOf(active) : -1;

  if (key === "Enter" || key === " ") {
    if (current === -1) return;
    event.preventDefault();
    options[current]!.click();
    return;
  }

  let next: number;
  if (key === "ArrowDown") next = Math.min(options.length - 1, current + 1);
  else if (key === "ArrowUp") next = current <= 0 ? 0 : current - 1;
  else if (key === "Home") next = 0;
  else if (key === "End") next = options.length - 1;
  else return;

  event.preventDefault();
  const target = options[next]!;
  target.focus();
  target.scrollIntoView?.({ block: "nearest" });
}

/**
 * Container for a list of `selectItem`s that owns the selection state. It exposes a `select`
 * context (`{ value, multiple }`) consumed by child items, and injects hidden `<input>`(s)
 * carrying the selected value(s) under `name` for form submission.
 *
 * @hostTag div
 * @param props.multiple - Whether multiple selection is allowed; also sets the default empty
 *   value (`[]` vs `null`). Defaults to `false`.
 * @param props.value - Bound selection value(s). Accepts a value or reactive state of an array of
 *   `number | string | null`, or a single `number | string | null`. Defaults to `[]` when
 *   `multiple`, otherwise `null`.
 * @param props.color - Theme color tone for the background. Defaults to `"neutral"`.
 * @param props.name - Name attribute for the hidden inputs (form field name).
 * @example { div: [{ div: "A", $: [selectItem({ value: "a" })] }], $: [selectList({ name: "pick" })] }
 */
function selectList(
  props: {
    multiple?: boolean;
    value?: ValueOrState<
      Array<number | string | null> | number | string | null
    >;
    color?: ThemeColor;
    name?: string;
  } = {},
): PartialElement {
  const { color = "neutral", multiple = false } = props;
  const state = toState(props.value ?? (multiple ? [] : null));

  // type=hidden form fields (not a visible input) — avoid axe label/listbox noise.
  const inputs: DomphyElement<"div"> = {
    div: (listener) => {
      const val = state.get(listener);
      const vals = Array.isArray(val) ? val : [val];
      return vals.map((v) => ({
        input: null,
        type: "hidden",
        name: props.name,
        // Preserve a legitimate numeric 0 (and other falsy-but-valid values);
        // `v || ""` would drop them.
        value: v == null ? "" : String(v),
      }));
    },
    // Keep out of the a11y tree; listbox children must be options.
    ariaHidden: "true",
    hidden: true,
  };

  const partial: PartialElement = {
    dataTone: "shift-0",
    // selectItem uses role=option; options require a listbox parent (WAI-ARIA).
    role: "listbox",
    ariaLabel: "Options",
    ariaMultiselectable: multiple ? "true" : undefined,
    // Without a tab stop the whole listbox was keyboard-unreachable: its
    // options are tabindex=-1 by design (roving focus), so Tab skipped the
    // entire widget. APG's listbox example puts tabindex=0 on the container.
    tabindex: 0,
    onKeyDown: onListboxKey,
    // Published from _onSchedule (runs once per node), NOT as a declared
    // `_context`: ElementNode.patch re-merges `element._context` on every
    // re-render, and merging a freshly-built State into the live one
    // overwrote its value and its notifier's listeners — an uncontrolled
    // selection silently snapped back to the initial value whenever a
    // reactive ancestor re-rendered. Same fix as segmented/toggleGroup.
    _onSchedule: (node) => {
      node.setContext("select", { value: state, multiple });
    },
    _onInit: (node) => {
      if (node.tagName !== "div") {
        console.warn(`"selectList" patch must use a div tag`);
      }
      node.children.insert(inputs);
    },
    style: {
      display: "flex",
      flexDirection: "column",
      paddingBlock: (listener) => themeSpacing(themeDensity(listener) * 2),
      paddingInline: (listener) => themeSpacing(themeDensity(listener) * 2),
      fontSize: (listener) => themeSize(listener, "inherit"),
      backgroundColor: (listener) => themeColor(listener, "inherit", color),
      color: (listener) => themeColor(listener, "text", color),
    },
  };
  return partial;
}

export { selectList };