Skip to content
Domphy

Tooltip

Use the tooltip patch to customize this element.

The tooltip surface uses a low elevation() box-shadow (no outline, kept compact and border-free — the arrow is unbordered too).

Props

PropTypeDefaultDescription
openValueOrState<boolean>falseControlled open state of the tooltip.
placementValueOrState<Placement>"top"Floating placement relative to the trigger element.
contentValueOrState<string>"Tooltip Content"Text content rendered inside the tooltip.
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,
  merge,
  type PartialElement,
  toState,
  type ValueOrState,
} from "@domphy/core";
import type { Placement } from "@domphy/floating";
import {
  themeColor,
  themeDensity,
  themeSize,
  themeSpacing,
} from "@domphy/theme";
import { elevation } from "../utils/elevation.js";
import { createFloating, floatingPanelId } from "../utils/floating.js";
import { popoverArrow } from "./popoverArrow.js";

/**
 * Attaches a floating tooltip to the host element, shown on hover/focus and
 * hidden on leave/blur/Escape. Returns the anchor (trigger) partial; the tooltip
 * surface is positioned via the floating utility and linked with
 * `aria-describedby`. No host tag check; applied to the trigger element.
 *
 * @param props.open - Controlled open state. Optional, accepts a value or state. Defaults to `false`.
 * @param props.placement - Floating placement relative to the trigger. Optional, accepts a value or state (`Placement`). Defaults to `"top"`.
 * @param props.content - Tooltip text content. Optional, accepts a value or state (string only). Defaults to `"Tooltip Content"`.
 * @example { button: "Hover me", $: [tooltip({ content: "Help text" })] }
 */
function tooltip(
  props: {
    open?: ValueOrState<boolean>;
    placement?: ValueOrState<Placement>;
    content?: ValueOrState<string>;
  } = {},
): PartialElement {
  const {
    open = false,
    placement = "top",
    content = "Tooltip Content",
  } = props;

  const placeState = toState(placement);
  const contentState = toState(content);

  // The tooltip id is NOT pre-generated here: a factory-scope id (previously
  // Math.random()-based) churns per generation and mismatches SSR/hydration.
  // Instead the shared floating behavior stamps a deterministic id derived
  // from the anchor's nodeId when the panel mounts (see floating.ts), and the
  // trigger references the same id via _onSchedule below.
  const contentElement: DomphyElement<"span"> = {
    span: (listener) => contentState.get(listener),
  };

  const { show, hide, anchorPartial } = createFloating({
    kind: "tooltip",
    open,
    placement: placeState,
    content: contentElement,
  });

  const tooltipPartial: PartialElement = {
    role: "tooltip",
    dataSize: "decrease-1",
    dataTone: "shift-17",
    style: {
      paddingBlock: (listener) => themeSpacing(themeDensity(listener) * 1),
      paddingInline: (listener) => themeSpacing(themeDensity(listener) * 3),
      borderRadius: (listener) => themeSpacing(themeDensity(listener) * 1.5),
      color: (listener) => themeColor(listener, "text"),
      backgroundColor: (listener) => themeColor(listener),
      fontSize: (listener) => themeSize(listener, "inherit"),
      boxShadow: elevation("low"),
    },
    $: [popoverArrow({ placement: placeState, bordered: false })],
  };
  contentElement.$ ||= [];
  contentElement.$.push(tooltipPartial);

  const triggerPartial: PartialElement = {
    // Declared as a reactive attribute (listener.elementNode is the anchor) so
    // it is present from first render — before the tooltip's first show() —
    // and is re-declared on every patch (patch() strips attributes that are
    // no longer declared, so imperative wiring would not survive re-render).
    ariaDescribedby: (listener) =>
      listener?.elementNode
        ? floatingPanelId("tooltip", listener.elementNode)
        : undefined,
    onMouseEnter: (_e, node) => show(node),
    onMouseLeave: (_e, node) => hide(node),
    onFocus: (_e, node) => show(node),
    onBlur: (_e, node) => hide(node),
    onKeyDown: (e, node) => (e as KeyboardEvent).key === "Escape" && hide(node),
  };

  merge(anchorPartial, triggerPartial);

  return anchorPartial;
}

export { tooltip };