# Tooltip

> A short description shown on hover and keyboard focus, with twelve logical placements, delays shared through Tooltip.Provider, an arrow, pointer following and a collision boundary.

Canonical: https://salmonui.dev/docs/layout/tooltip

`Tooltip` follows the APG Tooltip pattern: it describes its trigger, opens
on pointer hover and on keyboard focus, and closes on Escape, blur and
pointer leave. It lives in `@salmonui/overlays/tooltip` with its own
stylesheet.

```tsx
import { Tooltip } from '@salmonui/overlays/tooltip';
import '@salmonui/overlays/tooltip/styles.css';

<Tooltip content="Save the order">
  <button type="button">Save</button>
</Tooltip>;
```

### Live demo: Tooltip

Live demo: https://salmonui.dev/demos/layout/tooltip

A formatting toolbar whose tooltips share one Tooltip.Provider delay, and a Delete button with a tooltip at the inline end.

`Demo.tsx`:

```tsx
'use client';
import { Button } from '@salmonui/buttons/button';
import { Tooltip } from '@salmonui/overlays/tooltip';

export default function TooltipDemo() {
  return (
    <div>
      <div className="demo-toolbar">
        <Tooltip.Provider delay={300}>
          <Tooltip content="Bold (Ctrl+B)">
            <Button aria-label="Bold" iconOnly variant="outline">
              B
            </Button>
          </Tooltip>
          <Tooltip content="Italic (Ctrl+I)">
            <Button aria-label="Italic" iconOnly variant="outline">
              I
            </Button>
          </Tooltip>
          <Tooltip content="Underline (Ctrl+U)" placement="bottom">
            <Button aria-label="Underline" iconOnly variant="outline">
              U
            </Button>
          </Tooltip>
        </Tooltip.Provider>
        <Tooltip content="Removes the order permanently" placement="end" render={(props) => <Button {...props} tone="danger">Delete</Button>} />
      </div>
    </div>
  );
}
```

## Attaching to the trigger

Salmon UI does not clone children. Two forms attach the tooltip:

- **Children**: the trigger is wrapped in a `<span class="salmon-tooltip-trigger">`
  with `display: contents` (no box, no layout change). Pointer and focus
  events bubble to it; its first element child is the anchor and receives
  `aria-describedby` while the tooltip is open (appended to any value it
  already has).
- **`render`**: `render={(props) => <Button {...props}>Save</Button>}`
  renders the trigger itself with the computed props (event handlers, `ref`,
  `aria-describedby`); no wrapper element.

## Opening and closing

- Pointer hover opens after `delay` (default 600 ms); pointer leave closes
  after `closeDelay` (default 100 ms). Moving the pointer onto the tooltip
  keeps it open, so its text can be read or selected (WCAG 1.4.13).
- Keyboard focus (`:focus-visible`) opens at once; blur closes. A pointer
  press on the trigger closes it.
- Escape closes the tooltip only: a surrounding dialog or popover stays
  open. The Escape listener exists only while a tooltip is open.
- Touch never opens a tooltip: long press is reserved for the
  platform. Put essential information in the label or use a
  [Popover](https://salmonui.dev/docs/layout/popover).
- `disabled` never opens.

`open` / `defaultOpen` / `onOpenChange(open, { reason, source })` control it
(reasons `'hover' | 'focus' | 'blur' | 'leave' | 'escape' | 'press'`,
sources `'pointer' | 'keyboard'`); `onAfterOpen` and `onAfterClose` fire
after the content is shown and removed. With a controlled `open`, the
callback only proposes a change: apply it to open or close, or ignore it to
cancel. To open or close the tooltip from code, set `open`.

## Tooltip.Provider

`Tooltip.Provider` (also `TooltipProvider`) shares `delay` and `closeDelay`
for every tooltip inside it and adds a skip-delay window (`skipDelay`,
default 300 ms): after one tooltip closes, the next opens without waiting,
so moving along a toolbar feels immediate. Only one tooltip of a provider
is open at a time. Timers live in refs, never in React state.

## Placement

`placement` takes twelve logical values, default `'top'`: `top`,
`topStart`, `topEnd`, `bottom`, `bottomStart`, `bottomEnd`, `start`,
`startTop`, `startBottom`, `end`, `endTop`, `endBottom`. `start` / `end`
follow the inherited `dir`. The tooltip flips to the opposite side when it
does not fit and shifts to stay in the viewport, or inside
`collisionBoundary` (default the viewport). Collision handling is automatic
and deterministic, so there is no collision event, and the
position follows scroll and resize, so there is no refresh method.

- `offset`: gap in px (default 6) or `{ mainAxis, crossAxis }`.
- `arrow` (default `true`) points at the anchor's center and stays clamped
  inside the box after a shift, so its position needs no setting.
- `followCursor` positions the tooltip at the
  pointer; pointer moves write a CSS `translate` directly, never React
  state.

The tooltip uses the top layer through `popover="hint"` where supported
(it does not close open popovers), `popover="manual"` otherwise; without
the Popover API it is portaled into `container` (default: the nearest
`ThemeProvider` scope, else `document.body`).

## Content and styling

`content` is any `ReactNode`, rendered only while open. It must not hold
interactive controls; use [Popover](https://salmonui.dev/docs/layout/popover) for those,
including a tooltip that opens on click or stays open. Content that loads
data
can be a component that suspends. HTML strings are not parsed.

- `className` / `style` go on the content element (`.salmon-tooltip`, with
  `data-side` and `data-placement`); `classNames` / `styles` reach the
  `content` and `arrow` parts. Width and height are CSS
  (`styles={{ content: { width: 200 } }}`); the default maximum inline size
  is 280 px.
- `contentProps` (`TooltipContentProps`) adds attributes to the content
  element, `data-*` attributes included; its
  `id` is reserved for `aria-describedby` and its `role` is always
  `tooltip`.
- One fade transition, off under `prefers-reduced-motion`.

## Not included

- One tooltip delegated over many elements by a selector is not
  offered: render one `Tooltip` per trigger. The
  Data Grid keeps its own delegated overflow tooltip.
- There is nothing to persist, and React owns the lifecycle, so
  there are no lifecycle events or destroy method.

### Live demo: Tooltip placement, control and events

Live demo: https://salmonui.dev/demos/layout/tooltip-options

A controlled Tooltip opened from a button with a log of its open change requests, placement, offset and arrow controls, a pointer-following tooltip, a collision boundary, a wide tooltip, a tooltip with extra attributes rendered into a chosen container, and right-to-left.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { Slider } from '@salmonui/inputs/slider';
import { Tooltip, type TooltipPlacement } from '@salmonui/overlays/tooltip';
import { EventLog, useEventLog } from '../../components/demo-kit';

const PLACEMENTS: TooltipPlacement[] = ['top', 'topStart', 'topEnd', 'bottom', 'bottomStart', 'bottomEnd', 'start', 'startTop', 'startBottom', 'end', 'endTop', 'endBottom'];

// Tooltip options: a controlled tooltip opened from a button with a change log
// (a controlled `open` decides every change), the arrow and offset, a pointer-
// following tooltip, a collision boundary, a wide tooltip and right-to-left.
export default function TooltipOptionsDemo() {
  const [open, setOpen] = useState(false);
  const [allowHover, setAllowHover] = useState(true);
  const [placement, setPlacement] = useState<TooltipPlacement>('top');
  const [arrow, setArrow] = useState(true);
  const [offset, setOffset] = useState(6);
  const [rtl, setRtl] = useState(false);
  const [boundary, setBoundary] = useState<HTMLDivElement | null>(null);
  const [portal, setPortal] = useState<HTMLDivElement | null>(null);
  const [log, record] = useEventLog(6);
  return (
    <div dir={rtl ? 'rtl' : 'ltr'}>
      <div className="demo-toolbar">
        <label>
          Placement
          <Select aria-label="Placement" data={PLACEMENTS} value={placement} onValueChange={(value) => value != null && setPlacement(value as TooltipPlacement)} />
        </label>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <label>
            Offset
            <Slider min={0} max={24} value={offset} onValueChange={setOffset} style={{ inlineSize: 160 }} />
          </label>
          <output>{offset} px</output>
        </span>
        <Checkbox checked={arrow} onCheckedChange={(checked) => setArrow(checked)}>
          Arrow
        </Checkbox>
        <Checkbox checked={allowHover} onCheckedChange={(checked) => setAllowHover(checked)}>
          Allow hover and focus to open
        </Checkbox>
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          Right to left
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <Tooltip
          content="Saved 2 minutes ago"
          open={open}
          placement={placement}
          arrow={arrow}
          offset={offset}
          style={{ fontWeight: 600 }}
          onOpenChange={(next, event) => {
            const accepted = !next || allowHover;
            record(`${next ? 'open' : 'close'} requested (${event.reason}, ${event.source})${accepted ? '' : ': ignored'}`);
            if (accepted) setOpen(next);
          }}
          onAfterOpen={() => record('after open')}
          onAfterClose={() => record('after close')}
        >
          <Button variant="outline">Save status</Button>
        </Tooltip>
        <Button variant="ghost" aria-pressed={open} onClick={() => setOpen(!open)}>
          {open ? 'Hide the status tooltip' : 'Show the status tooltip'}
        </Button>
        <Tooltip content="Ships within 2 business days to every EU country; bulky items may take a week longer." styles={{ content: { width: 260 } }} placement="bottom">
          <Button variant="outline">Shipping</Button>
        </Tooltip>
        <Tooltip content="Deletes the draft for every editor" contentProps={{ 'data-variant': 'warning' }} container={portal}>
          <Button variant="outline">Delete draft</Button>
        </Tooltip>
        {/* The Delete draft tooltip is rendered inside this element (`container`), so it inherits its italic text. */}
        <div ref={setPortal} style={{ fontStyle: 'italic' }} />
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
        <Tooltip content="Pointer position" followCursor placement="topStart" delay={0}>
          <div
            tabIndex={0}
            role="group"
            aria-label="Pointer area"
            style={{ inlineSize: 220, blockSize: 96, display: 'grid', placeItems: 'center', border: '1px dashed var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-lg)' }}
          >
            Move the pointer here
          </div>
        </Tooltip>
        <div ref={setBoundary} style={{ inlineSize: 220, blockSize: 96, overflow: 'auto', border: '1px solid var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-lg)', padding: 8 }}>
          <Tooltip content="Kept inside the bordered box" collisionBoundary={boundary} placement="start">
            <Button variant="outline">
              Boundary
            </Button>
          </Tooltip>
        </div>
      </div>
      <EventLog entries={log} label="Tooltip events" />
    </div>
  );
}
```

API reference: [`@salmonui/overlays/tooltip`](https://salmonui.dev/docs/reference/overlays/tooltip).

## Bundle

`@salmonui/overlays/tooltip` is 3.56 KB gzip including the positioning and
top-layer primitives (no dismiss stack or focus scope); its stylesheet is
0.52 KB.
