Skip to content
Domphy

Button

Use the button patch to customize this element. Interactive states: hover (±1), pressed :active (±2), focus-visible ring via the shared focusRing helper, plus [disabled] and [aria-busy].

Props

PropTypeDefaultDescription
colorValueOrState<ThemeColor>"primary"Button color tone.
variant"solid" | "outline" | "ghost""outline"Visual style. "outline" is the tinted-background + outline look and stays the default for backward compatibility. "solid" fills the background with a readable-contrast text color. "ghost" delegates straight to buttonGhost(), so the two stay visually identical.
size"small" | "medium" | "large""medium"Button size preset — scales padding and font size via the density/size tokens.
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, toState, type ValueOrState } from "@domphy/core";
import {
  type ThemeColor,
  themeColor,
  themeDensity,
  themeSize,
  themeSpacing,
} from "@domphy/theme";
import { BUTTON_SIZE_FONT, type ButtonSize } from "../utils/buttonSize.js";
import { focusRing } from "../utils/focusRing.js";
import { buttonGhost } from "./buttonGhost.js";

type ButtonVariant = "solid" | "outline" | "ghost";

const PADDING_STEPS: Record<ButtonSize, { block: number; inline: number }> = {
  small: { block: 0.5, inline: 2 },
  medium: { block: 1, inline: 3 },
  large: { block: 1.5, inline: 4 },
};

/**
 * A themed button control with density-aware padding/radius and hover, pressed
 * (`:active` ±2), focus-visible, `[disabled]`, and `[aria-busy=true]` states.
 * Apply to a `<button>` element.
 *
 * @hostTag button
 * @param props.color - Button color tone. Optional `ValueOrState<ThemeColor>`, default "primary".
 * @param props.variant - Visual style: `"outline"` (tinted background + outline, default,
 *   backward compatible), `"solid"` (filled background, readable contrast text), or `"ghost"`
 *   (no background/border — delegates to `buttonGhost()` so the two stay visually identical).
 * @param props.size - Button size preset. Optional `"small" | "medium" | "large"`, defaults to `"medium"`.
 * @example { button: "Save", $: [button({ color: "primary" })] }
 * @example { button: "Delete", $: [button({ color: "error", variant: "solid" })] }
 */
function button(
  props: {
    color?: ValueOrState<ThemeColor>;
    variant?: ButtonVariant;
    size?: ButtonSize;
  } = {},
): PartialElement {
  const variant = props.variant ?? "outline";
  if (variant === "ghost") {
    return buttonGhost({ color: props.color, size: props.size });
  }

  const color = toState(props.color ?? "primary", "color");
  const isSolid = variant === "solid";
  const padding = PADDING_STEPS[props.size ?? "medium"];
  const fontSize = BUTTON_SIZE_FONT[props.size ?? "medium"];

  return {
    _onInsert: (node) => {
      if (node.tagName !== "button") {
        console.warn(`"button" primitive patch must use button tag`);
      }
    },
    // Solid: deep brand fill (shift-13) + light-end neutral text (shift-0).
    // Mid-ramp shift-8 failed WCAG (~2.2:1 white-on-medium). NOT dataTone-17
    // (that collapsed every color into a near-black pill). Outline text:
    // shift-13 for ≥4.5:1 on light surfaces (shift-9 failed at ~2.57).
    ...(isSolid
      ? {
          _doctorDisable: [
            "low-contrast",
            "color-shift-minimum",
            "tone-background-inherit",
          ] as const,
        }
      : {}),
    style: {
      appearance: "none",
      fontSize: (listener) => themeSize(listener, fontSize),
      // Single-line bounded control: block/radius = 1D, inline = 3D.
      paddingBlock: (listener) =>
        themeSpacing(themeDensity(listener) * padding.block),
      paddingInline: (listener) =>
        themeSpacing(themeDensity(listener) * padding.inline),
      borderRadius: (listener) => themeSpacing(themeDensity(listener) * 1.5),
      width: "fit-content",
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      gap: (listener) => themeSpacing(themeDensity(listener) * 1),
      userSelect: "none",
      cursor: "pointer",
      fontFamily: "inherit",
      lineHeight: "inherit",
      border: "none",
      outlineOffset: "-1px",
      outlineWidth: "1px",
      outline: isSolid
        ? "none"
        : (listener) =>
            `1px solid ${themeColor(listener, "border-strong", color.get(listener))}`,
      color: (listener) =>
        isSolid
          ? themeColor(listener, "shift-0", "neutral")
          : themeColor(listener, "shift-13", color.get(listener)),
      backgroundColor: (listener) =>
        isSolid
          ? themeColor(listener, "shift-13", color.get(listener))
          : themeColor(listener, "inherit", color.get(listener)),
      transition:
        "background-color 140ms ease, color 140ms ease, border-color 140ms ease, box-shadow 140ms ease",
      "&:hover:not([disabled]):not([aria-busy=true])": {
        color: (listener) =>
          isSolid
            ? themeColor(listener, "shift-0", "neutral")
            : themeColor(listener, "shift-14", color.get(listener)),
        backgroundColor: (listener) =>
          isSolid
            ? themeColor(listener, "shift-14", color.get(listener))
            : themeColor(listener, "hover", color.get(listener)),
      },
      // Pressed: solid steps deeper on the brand ramp; outline uses +2 surface.
      "&:active:not([disabled]):not([aria-busy=true])": {
        backgroundColor: (listener) =>
          isSolid
            ? themeColor(listener, "shift-15", color.get(listener))
            : themeColor(listener, "increase-2", color.get(listener)),
      },
      "&:focus-visible": {
        boxShadow: (listener) => focusRing(listener, color.get(listener)),
      },
      "&[disabled]": {
        opacity: 0.7,
        cursor: "not-allowed",
        backgroundColor: (listener) =>
          themeColor(listener, "shift-2", "neutral"),
        outline: (listener) =>
          `1px solid ${themeColor(listener, "border-strong", "neutral")}`,
        color: (listener) => themeColor(listener, "muted", "neutral"),
      },
      "&[aria-busy=true]": {
        opacity: 0.7,
        cursor: "wait",
        pointerEvents: "none",
      },
    },
  };
}

export { button };
export type { ButtonVariant };