Menu

Use the menu patch to customize this element.

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.

<div class="blocks">
<div class="block active" data-tab="0">
import {
  merge,
  type PartialElement,
  toState,
  type ValueOrState,
} from "@domphy/core";
import {
  type ThemeColor,
  themeColor,
  themeDensity,
  themeSize,
  themeSpacing,
} from "@domphy/theme";

/**
 * Themed menu container that provides selection context (`activeKey`,
 * `selectable`) to child `menuItem` patches and lays them out vertically.
 * Sets `role="menu"`. Typically applied to a container element such as a
 * `<div>` or `<ul>`.
 *
 * @param props - Optional configuration.
 * @param props.activeKey - Currently selected item key, accepts a value or `State`. Defaults to `null`.
 * @param props.selectable - Whether items track and update the active selection. Defaults to `true`.
 * @param props.color - Background color tone for the menu. Defaults to `"neutral"`.
 * @example { div: "", $: [menu({ activeKey: 0 })] }
 */
function menu(
  props: {
    activeKey?: ValueOrState<number | string>;
    selectable?: boolean;
    color?: ThemeColor;
  } = {},
): PartialElement {
  const { color = "neutral", selectable = true } = props;

  const partial: PartialElement = {
    role: "menu",
    dataTone: "shift-17",
    _onSchedule: (_node, element) => {
      const partial = {
        _context: {
          menu: {
            activeKey: toState(props.activeKey ?? null),
            selectable,
          },
        },
      };
      merge(element, partial);
    },
    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),
    },
  };
  return partial;
}

export { menu };
</div>
<div class="block" data-tab="1">
import type { ElementNode, PartialElement } from "@domphy/core";
import {
  type ThemeColor,
  themeColor,
  themeDensity,
  themeSize,
  themeSpacing,
} from "@domphy/theme";

/**
 * Themed menu entry for use inside a `menu`. Sets `role="menuitem"`, wires
 * click/keyboard selection (Enter/Space activate; Arrow/Home/End move focus),
 * and reflects the active item via `aria-current`. Apply to a `<button>`
 * element placed within a `menu`.
 *
 * @hostTag button
 * @param props - Optional configuration.
 * @param props.accentColor - Accent color tone for the active/focus indicator. Defaults to `"primary"`.
 * @param props.color - Base color tone for the item. Defaults to `"neutral"`.
 * @example { button: "Profile", $: [menuItem()] }
 */
function menuItem(
  props: { accentColor?: ThemeColor; color?: ThemeColor } = {},
): PartialElement {
  const { accentColor = "primary", color = "neutral" } = props;

  const partial: PartialElement = {
    role: "menuitem",
    _onInsert: (node) => {
      if (node.tagName !== "button") {
        console.warn(`"menuItem" patch must use button tag`);
      }

      const context = node.getContext("menu");
      if (!context) {
        console.warn(`"menuItem" patch must be used inside a "menu"`);
        return;
      }
      let children = (node.parent?.children.items ?? []) as ElementNode[];
      children = children.filter(
        (n) =>
          n.type === "ElementNode" && n.attributes.get("role") === "menuitem",
      );
      // Strict key check: an explicit _key of 0 or "" must not fall back to index.
      const key =
        node.key !== null && node.key !== undefined
          ? node.key
          : children.indexOf(node);
      if (context.selectable) {
        node.attributes.set(
          "ariaCurrent",
          (listener) => context.activeKey.get(listener) === key || undefined,
        );
        node.addEvent("click", () => context.activeKey.set(key));
      }
    },
    onKeyDown: (e: KeyboardEvent, node) => {
      const k = (e as KeyboardEvent).key;
      if (k === "Enter" || k === " ") {
        e.preventDefault();
        (node.domElement as HTMLElement)?.click();
        return;
      }
      if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(k)) return;
      e.preventDefault();
      const items = (node.parent?.children.items ?? []).filter(
        (n) =>
          n.type === "ElementNode" &&
          (n as ElementNode).attributes.get("role") === "menuitem",
      ) as ElementNode[];
      const idx = items.indexOf(node);
      let next = idx;
      if (k === "ArrowDown") next = (idx + 1) % items.length;
      else if (k === "ArrowUp") next = (idx - 1 + items.length) % items.length;
      else if (k === "Home") next = 0;
      else if (k === "End") next = items.length - 1;
      (items[next].domElement as HTMLElement)?.focus();
    },
    style: {
      cursor: "pointer",
      display: "flex",
      alignItems: "center",
      gap: (_listener) => themeSpacing(2),
      width: "100%",
      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, "shift-9", color),
      backgroundColor: (listener) => themeColor(listener, "inherit", color),
      "&:hover:not([disabled]):not([aria-current=true])": {
        backgroundColor: (listener) => themeColor(listener, "shift-2", color),
      },
      // Menu uses the current/indicator band instead of the selected fill band.
      "&[aria-current=true]": {
        backgroundColor: (listener) =>
          themeColor(listener, "shift-3", accentColor),
        color: (listener) => themeColor(listener, "shift-10"),
      },
      "&:focus-visible": {
        outline: (listener) =>
          `${themeSpacing(0.5)} solid ${themeColor(listener, "shift-6", accentColor)}`,
        outlineOffset: `-${themeSpacing(0.5)}`,
      },
    },
  };
  return partial;
}

export { menuItem };
</div>
</div>