Skip to content
Domphy

Select List

Use selectList on a div container and selectItem on each child div. The container manages shared selection state via context — selectItem reads it automatically without any prop wiring.

Props

PropTypeDefaultDescription
multiplebooleanfalseAllow multiple selection. When true, value defaults to [] instead of null.
valueValueOrState<Array<number | string | null> | number | string | null>[] / nullBound selection value(s). Defaults to [] when multiple, otherwise null.
colorThemeColor"neutral"Background tone of the list container.
namestringName attribute for the hidden <input>(s) injected for form submission. Required for use inside <form>.
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 PartialElement,
  toState,
  type ValueOrState,
} from "@domphy/core";
import {
  type ThemeColor,
  themeColor,
  themeDensity,
  themeSize,
  themeSpacing,
} from "@domphy/theme";

/**
 * 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,
    _context: {
      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 };
import type { PartialElement } from "@domphy/core";
import {
  type ThemeColor,
  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",
    // 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"),
      height: (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),
      "&:hover:not([disabled]):not([aria-selected=true])": {
        backgroundColor: (listener) => themeColor(listener, "hover", color),
      },
      "&[aria-selected=true]": {
        backgroundColor: (listener) =>
          themeColor(listener, "shift-6", accentColor),
        color: (listener) => themeColor(listener, "shift-11"),
      },
      transition: "background-color 140ms ease, box-shadow 140ms ease",
      "&:focus-visible": {
        boxShadow: (listener) => focusRing(listener, accentColor),
      },
    },
  };
  return partial;
}

export { selectItem };