# Tooltip

Explains a control in one short line when someone hovers or focuses it, most often an icon button without a visible label.

Status: Stable. Group: Feedback.

## When to use

- Icon buttons in toolbars and table rows: Archive project, Copy link.
- A keyboard shortcut or a short extra fact next to a labelled control.

## When not to use

- The information is needed to finish the task. Use a hint under the field in Input instead.
- It holds links, buttons or more than one sentence. Use Modal instead.
- People use touch screens to reach it. Use a visible label on the control instead.

## Scenarios

### Board toolbar

The toolbar above the task board has three icon buttons. Each has an aria-label and a Tooltip that repeats the name and adds what happens: Hides it from the board. Restore it any time from Settings.

### Shortcut hint

The New task button shows a Tooltip with the shortcut N after a short hover, so frequent users learn it without reading the docs.

## Do and avoid

- Do: Give the trigger its own accessible name; the tooltip adds detail.
- Avoid: Make the tooltip the only name of an icon button.
- Do: Keep it to one short sentence.
- Avoid: Put a link or a button in a tooltip; nobody can reach it.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `content` | `ReactNode` |  | The hint: one short sentence, text only. |
| `children` | `ReactElement` |  | The trigger, a single focusable element that spreads its props (Button does). It gets aria-describedby. |
| `side` | `'top' \| 'bottom'` | `'top'` | Which side of the trigger it opens on, 8 px away. |
| `align` | `'center' \| 'start' \| 'end'` | `'center'` | start or end lines it up with that edge of the trigger, for triggers near the edge of the screen. |
| `delay` | `number` | `400` | Hover delay in ms before it opens. Keyboard focus opens it at once. |
| `open` | `boolean` |  | Controlled open state. Pair with onOpenChange. |
| `defaultOpen` | `boolean` | `false` | Open state for the first render when uncontrolled. |
| `onOpenChange` | `(open: boolean) => void` |  | Called when hover, focus, blur or Esc opens or closes it. |
| `className` | `string` |  | Extra classes for the inline wrapper. |

## Anatomy

1. Wrapper (`data-part="root"`): An inline wrapper around the trigger; the bubble is placed against it.
2. Bubble (`data-part="content"`): Action fill with on-action caption 12/16 text, radius sm, 10 by 6 px padding, shadow 2, at most 256 px wide.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Open on hover | translate 4 px from the trigger and scale .96 to 1, from the edge facing the trigger | base | spring | Focus opens it at once with no animation. |
| Fade and focus in | opacity, blur 2 px to 0 | quick | out | None. |
| Next tooltip along a row | none: opens at once while one is open or within 300 ms of one closing (shared warm state) | none | out | Same. |
| Close | none (hidden at once) | none | out | Same: Esc or blur hides it at once. |

## Accessibility

| Keys | Action |
| --- | --- |
| Tab | Focusing the trigger opens the tooltip at once. |
| Esc | Closes it without moving focus. |

- The bubble is role tooltip and the trigger points to it with aria-describedby, so it is read as the description.
- Hidden with the hidden attribute while closed; the description is still available to assistive tech.
- Hovering the bubble keeps it open, and Esc closes it from anywhere (WCAG 1.4.13).

## Code

### Tooltip.tsx

```tsx
'use client'
import { cloneElement, useEffect, useId, useRef, useState, type FocusEvent, type PointerEvent, type ReactElement, type ReactNode } from 'react'

// Nacre Tooltip: a short hint for a control, shown on hover after a delay and at once on keyboard focus. React plus
// Tailwind classes only; needs nacre-theme.css. Positioned in flow (no portal, no anchor positioning): an ancestor with
// overflow hidden clips it. Motion: it springs out of its trigger, from the side it opens on: 4 px toward the
// trigger, scale .96 and a 2 px blur to rest, base 240 on the spring curve (opacity and blur quick 160 out), growing
// from the edge that faces the trigger. The first one waits for the delay; while one is open, or for 300 ms after one
// closes, the next opens at once with no animation (one warm state shared by every tooltip on the page), so moving
// along a toolbar feels instant. Keyboard focus opens it at once with no animation; closing is instant. Esc closes it
// from anywhere; touch never opens it. Reduced motion or [data-nacre-motion="off"]: no movement.

export type TooltipSide = 'top' | 'bottom'
export type TooltipAlign = 'center' | 'start' | 'end'

export type TooltipProps = {
  content: ReactNode
  children: ReactElement<{ 'aria-describedby'?: string }>
  side?: TooltipSide
  align?: TooltipAlign
  delay?: number
  open?: boolean
  defaultOpen?: boolean
  onOpenChange?: (open: boolean) => void
  className?: string
}

// Shared warm state: while any tooltip is open, and for this long after one closes, the next opens at once.
const WARM_MS = 300
let warmUntil = 0
let openCount = 0
const warm = () => openCount > 0 || Date.now() < warmUntil

// The before: strip covers the 8 px gap, so moving the pointer onto the bubble keeps it open.
// Each side starts 4 px toward the trigger and grows from the edge that faces it.
const sides: Record<TooltipSide, string> = {
  top: 'bottom-full mb-2 before:top-full starting:translate-y-1',
  bottom: 'top-full mt-2 before:bottom-full starting:-translate-y-1',
}
const aligns: Record<TooltipAlign, string> = {
  center: 'left-1/2 -translate-x-1/2',
  start: 'start-0',
  end: 'end-0',
}
const origins: Record<TooltipSide, Record<TooltipAlign, string>> = {
  top: { center: 'origin-bottom', start: 'origin-bottom-left rtl:origin-bottom-right', end: 'origin-bottom-right rtl:origin-bottom-left' },
  bottom: { center: 'origin-top', start: 'origin-top-left rtl:origin-top-right', end: 'origin-top-right rtl:origin-top-left' },
}

export function Tooltip({ content, children, side = 'top', align = 'center', delay = 400, open: openProp, defaultOpen = false, onOpenChange, className = '' }: TooltipProps) {
  const id = useId()
  const [inner, setInner] = useState(defaultOpen)
  const open = openProp ?? inner
  const [instant, setInstant] = useState(false)
  const timer = useRef<number | undefined>(undefined)
  // Opened by a hover or focus here (not shown open by a prop): only these warm the next tooltip.
  const byUser = useRef(false)
  // Latest open for the delayed timer and the key listener, which would otherwise read the render they were made in.
  const openRef = useRef(open)
  useEffect(() => {
    openRef.current = open
  })

  const setOpen = (next: boolean, now = false) => {
    window.clearTimeout(timer.current)
    if (next === openRef.current) return
    if (openProp === undefined) openRef.current = next
    byUser.current = next
    if (!next) warmUntil = Date.now() + WARM_MS
    setInstant(now)
    if (openProp === undefined) setInner(next)
    onOpenChange?.(next)
  }

  // Esc closes from anywhere while open (WCAG 1.4.13); the ref keeps the listener on the latest props.
  const close = useRef<() => boolean>(() => false)
  useEffect(() => {
    // A controlled tooltip with no onOpenChange cannot close, so it leaves the key alone.
    close.current = () => {
      if (openProp !== undefined && !onOpenChange) return false
      setOpen(false)
      return true
    }
  })
  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return
      // Inside a Modal or Drawer the same Esc must not also cancel the dialog: the tooltip takes this one.
      if (close.current()) e.preventDefault()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [open])
  useEffect(() => () => window.clearTimeout(timer.current), [])
  // Count tooltips a person opened for the shared warm state; one shown open by a prop does not count.
  useEffect(() => {
    if (!open || !byUser.current) return
    openCount++
    return () => {
      openCount--
      warmUntil = Date.now() + WARM_MS
    }
  }, [open])

  const onPointerEnter = (e: PointerEvent) => {
    if (e.pointerType === 'touch') return
    if (openRef.current) return
    if (warm()) return setOpen(true, true)
    window.clearTimeout(timer.current)
    timer.current = window.setTimeout(() => setOpen(true), delay)
  }
  const onFocus = (e: FocusEvent) => {
    if ((e.target as Element).matches(':focus-visible')) setOpen(true, true)
  }

  const describedBy = [children.props['aria-describedby'], id].filter(Boolean).join(' ')
  return (
    <span
      data-part="root"
      className={`relative inline-flex ${className}`}
      onPointerEnter={onPointerEnter}
      onPointerLeave={() => setOpen(false)}
      onFocus={onFocus}
      onBlur={() => setOpen(false)}
    >
      {cloneElement(children, { 'aria-describedby': describedBy })}
      <span
        id={id}
        role="tooltip"
        data-part="content"
        data-side={side}
        data-instant={instant || undefined}
        hidden={!open}
        className={`absolute z-10 w-max max-w-[16rem] rounded-sm bg-action px-2.5 py-1.5 text-caption text-on-action shadow-2 [transition:opacity_var(--nx-dur-quick)_var(--nx-ease-out),filter_var(--nx-dur-quick)_var(--nx-ease-out),scale_var(--nx-dur-base)_var(--nx-ease-spring),translate_var(--nx-dur-base)_var(--nx-ease-spring)] starting:scale-[.96] starting:opacity-0 starting:blur-[2px] data-instant:transition-none before:absolute before:inset-x-0 before:h-2 before:content-[''] ${sides[side]} ${aligns[align]} ${origins[side][align]}`}
      >
        {content}
      </span>
    </span>
  )
}
```

## HTML

The default example as plain HTML, for any stack. Needs nacre-theme.css.

```html
<span data-part="root" class="relative inline-flex ">
  <button type="button" data-part="root" class="group/button relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center rounded-full font-ui font-[600] whitespace-nowrap transition-[color,background-color,border-color,scale] duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus motion-safe:active:not-focus-visible:scale-[.97] disabled:cursor-not-allowed aria-disabled:cursor-progress border border-line bg-secondary text-fg-strong enabled:hover:border-line-strong disabled:border-line-subtle disabled:text-fg-disabled h-10 px-4 text-label w-10 px-0!" aria-label="Archive project" aria-describedby="_R_0_">
    <span data-part="label" class="inline-flex items-center gap-2 transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ">
      <svg aria-hidden="true" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="size-5">
        <path d="M3 5.5h14v2.5H3zM4.5 8v7.5h11V8M8 11h4"></path>
      </svg>
    </span>
  </button>
  <span id="_R_0_" role="tooltip" data-part="content" data-side="top" hidden="" class="absolute z-10 w-max max-w-[16rem] rounded-sm bg-action px-2.5 py-1.5 text-caption text-on-action shadow-2 [transition:opacity_var(--nx-dur-quick)_var(--nx-ease-out),filter_var(--nx-dur-quick)_var(--nx-ease-out),scale_var(--nx-dur-base)_var(--nx-ease-spring),translate_var(--nx-dur-base)_var(--nx-ease-spring)] starting:scale-[.96] starting:opacity-0 starting:blur-[2px] data-instant:transition-none before:absolute before:inset-x-0 before:h-2 before:content-[&#x27;&#x27;] bottom-full mb-2 before:top-full starting:translate-y-1 left-1/2 -translate-x-1/2 origin-bottom">Hides it from the board. Restore it any time from Settings.</span>
</span>
```

## Related

- [Button](https://enxm.me/services/design-systems/nacre/components/button)
- [Badge](https://enxm.me/services/design-systems/nacre/components/badge)
