Components / FeedbackStable

Tooltip

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

View as Markdown

Playground

Code

Tooltip.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>
  )
}

Usage

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.

Choose something else when

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

In the Nacre workspace

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 don't

  • DoGive the trigger its own accessible name; the tooltip adds detail.

    Don'tMake the tooltip the only name of an icon button.

  • DoKeep it to one short sentence.

    Don'tPut a link or a button in a tooltip; nobody can reach it.

Anatomy

Hides it from the board. Restore it any time from Settings.
  1. Wrapper. An inline wrapper around the trigger; the bubble is placed against it.
  2. Bubble. Action fill with on-action caption 12/16 text, radius sm, 10 by 6 px padding, shadow 2, at most 256 px wide.

API

contentType ReactNodeDefault -The hint: one short sentence, text only.
childrenType ReactElementDefault -The trigger, a single focusable element that spreads its props (Button does). It gets aria-describedby.
sideType 'top' | 'bottom'Default 'top'Which side of the trigger it opens on, 8 px away.
alignType 'center' | 'start' | 'end'Default 'center'start or end lines it up with that edge of the trigger, for triggers near the edge of the screen.
delayType numberDefault 400Hover delay in ms before it opens. Keyboard focus opens it at once.
openType booleanDefault -Controlled open state. Pair with onOpenChange.
defaultOpenType booleanDefault falseOpen state for the first render when uncontrolled.
onOpenChangeType (open: boolean) => voidDefault -Called when hover, focus, blur or Esc opens or closes it.
classNameType stringDefault -Extra classes for the inline wrapper.

Motion

Open on hoverProperty translate 4 px from the trigger and scale .96 to 1, from the edge facing the triggerDuration base 240Easing springKeyboard Focus opens it at once with no animation.
Fade and focus inProperty opacity, blur 2 px to 0Duration quick 160Easing outKeyboard None.
Next tooltip along a rowProperty none: opens at once while one is open or within 300 ms of one closing (shared warm state)Duration none 0Easing outKeyboard Same.
CloseProperty none (hidden at once)Duration none 0Easing outKeyboard Same: Esc or blur hides it at once.

Accessibility

Keyboard

Tab
Focusing the trigger opens the tooltip at once.
Esc
Closes it without moving focus.

ARIA and semantics

  • 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).

Contrast

Tooltip texton-action on actionLight 17.74:1Dark 17.30:1Needs 4.5:1