Components · Overlay
note:Copy source: not an npm package.
Tooltip
A small hint for icon-only controls: opens on hover and keyboard focus, dismisses with Escape, stays hoverable and supports a shortcut hint.
- hover
- focus
- WCAG 1.4.13
- Dependencies
- None beyond React
- Source
- src/components/collection/tooltip/tooltip.tsx
Preview & code
Hover, or Tab to a button: the hint appears and Escape dismisses it. Each button still has its own accessible name; the tooltip only adds a description.
"use client";/** * Tooltip — a short, non-essential hint for an icon-only control. * * Motion (after the transitions.dev tooltip open/close recipe): * - Opens on pointer hover after `openDelay` (300ms), and immediately on * keyboard focus: opacity 0 → 1, translateY(4px → 0), scale(0.98 → 1), 150ms ease-out. * - Moving to a neighbouring trigger within 400ms opens it at once, and the * bubble travels from the previous position (160ms) instead of popping. * - Closes with a quick 100ms opacity fade. The bubble sits inside the * trigger's hover area, so the pointer can still move onto it (WCAG 1.4.13). * - Placement: shifts sideways to stay 8px inside the viewport, and flips to * the other side when there's no room. Reduced motion: no animation. * - Escape dismisses it without moving focus or the pointer. * - Touch: never opens on tap. Use `forceOpen` for transient feedback such as * "Copied", which is shown on every input type. * - Linked with aria-describedby, so screen readers announce it as a * description even while it is visually hidden. * * The trigger must be a single focusable element that accepts * aria-describedby (a button or link) and keeps its own accessible name. * Never put essential information only in a tooltip. No collision detection: * choose `side` and `align` and keep content short. * * Styling uses Tailwind utilities backed by CSS variables (--text, --surface). * The optional entry animation expects a `tooltip-in` keyframe (fade + 2px rise). * * Source: Sayed Risat's portfolio component collection. Copy freely. */import { cloneElement, isValidElement, useEffect, useId, useLayoutEffect, useRef, useState, type FocusEvent, type PointerEvent, type ReactElement, type ReactNode,} from "react";export type TooltipProps = { content: ReactNode; children: ReactElement<{ "aria-describedby"?: string }>; side?: "top" | "bottom"; /** Horizontal alignment to the trigger. Use "end" near the right edge of the screen. */ align?: "center" | "start" | "end"; /** Optional keyboard shortcut, rendered as a <kbd> after the content. */ shortcut?: string; /** Hover delay before opening, in ms. Keyboard focus opens immediately. */ openDelay?: number; /** Delay before closing after the pointer leaves, in ms. Instant by default. */ closeDelay?: number; /** Show the tooltip regardless of hover or focus (e.g. "Copied" feedback). Escape still hides it. */ forceOpen?: boolean; /** Start open (for static previews). Hover, focus and Escape take over afterwards. */ defaultOpen?: boolean; className?: string;};/** Shared across every tooltip on the page: the neighbour grace period. */const GRACE_MS = 400;const EXIT_MS = 100;const EDGE = 8;const group = { openCount: 0, lastClosedAt: -Infinity, /** Where the last bubble was, so a neighbour can travel from there. */ lastRect: null as { cx: number; top: number } | null,};function isWarm(): boolean { return group.openCount > 0 || performance.now() - group.lastClosedAt < GRACE_MS;}const alignClass = { center: "left-1/2 -translate-x-1/2", start: "left-0", end: "right-0",} as const;export function Tooltip({ content, children, side = "top", align = "center", shortcut, openDelay = 300, closeDelay = 0, forceOpen = false, defaultOpen = false, className,}: TooltipProps) { const id = useId(); const [hoverOpen, setHoverOpen] = useState(defaultOpen); const [dismissed, setDismissed] = useState(false); const [lastForceOpen, setLastForceOpen] = useState(forceOpen); const timer = useRef<number | undefined>(undefined); // Only tooltips opened by hover or focus join the grace-period group, so a // `defaultOpen` preview never makes the rest of the page open instantly. const interactive = useRef(false); const bubble = useRef<HTMLSpanElement>(null); const [closing, setClosing] = useState(false); const closeTimer = useRef<number | undefined>(undefined); const openRef = useRef(false); // A new forced state (e.g. a fresh "Copied") is visible again after an earlier Escape. if (forceOpen !== lastForceOpen) { setLastForceOpen(forceOpen); if (forceOpen) setDismissed(false); } const open = (hoverOpen || forceOpen) && !dismissed; useLayoutEffect(() => { openRef.current = open; }); // Track this tooltip in the shared group so neighbours can open instantly. useEffect(() => { if (!open || !interactive.current) return; group.openCount += 1; return () => { group.openCount -= 1; group.lastClosedAt = performance.now(); }; }, [open]); useEffect( () => () => { window.clearTimeout(timer.current); window.clearTimeout(closeTimer.current); }, [], ); // Before paint: keep the bubble inside the viewport, then choose the entrance // (travel from a neighbour's bubble, or rise in). useLayoutEffect(() => { const el = bubble.current; if (!open || !el) return; Object.assign(el.style, { marginLeft: "", top: "", bottom: "", marginTop: "", marginBottom: "" }); let rect = el.getBoundingClientRect(); const vw = document.documentElement.clientWidth; const shift = rect.left < EDGE ? EDGE - rect.left : rect.right > vw - EDGE ? vw - EDGE - rect.right : 0; if (shift) el.style.marginLeft = `${Math.round(shift)}px`; const flip = side === "top" ? rect.top < EDGE : rect.bottom > window.innerHeight - EDGE; if (flip) { Object.assign( el.style, side === "top" ? { top: "100%", bottom: "auto", marginTop: "0.375rem", marginBottom: "0" } : { bottom: "100%", top: "auto", marginBottom: "0.375rem", marginTop: "0" }, ); } el.style.setProperty("--tooltip-dy", (side === "top") !== flip ? "4px" : "-4px"); rect = el.getBoundingClientRect(); const last = group.lastRect; const travel = interactive.current && last && performance.now() - group.lastClosedAt < GRACE_MS && Math.abs(last.top - rect.top) < 4; el.dataset.motion = travel ? "travel" : "in"; el.style.setProperty("--tooltip-from-x", travel ? `${Math.round(last.cx - (rect.left + rect.width / 2))}px` : "0px"); }, [open, side]); /** Close with a short fade (skipped under reduced motion). */ function hide() { if (openRef.current && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) { setClosing(true); window.clearTimeout(closeTimer.current); closeTimer.current = window.setTimeout(() => setClosing(false), EXIT_MS); } setHoverOpen(false); } useEffect(() => { if (!open) return; const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape") return; window.clearTimeout(timer.current); hide(); setDismissed(true); }; document.addEventListener("keydown", onKeyDown); return () => document.removeEventListener("keydown", onKeyDown); }, [open]); function remember() { const el = bubble.current; if (!el || el.dataset.state !== "open") return; const rect = el.getBoundingClientRect(); group.lastRect = { cx: rect.left + rect.width / 2, top: rect.top }; // Stamp the close now: a neighbour's layout effect runs before this tooltip's effect cleanup. group.lastClosedAt = performance.now(); } function schedule(next: boolean, delay: number) { window.clearTimeout(timer.current); if (!next) remember(); interactive.current = true; if (next) { setDismissed(false); window.clearTimeout(closeTimer.current); setClosing(false); } const apply = () => (next ? setHoverOpen(true) : hide()); if (delay <= 0) apply(); else timer.current = window.setTimeout(apply, delay); } const trigger = isValidElement(children) ? cloneElement(children, { "aria-describedby": [children.props["aria-describedby"], id].filter(Boolean).join(" "), }) : children; return ( <span className={["relative inline-flex", className].filter(Boolean).join(" ")} onPointerEnter={(event: PointerEvent) => { if (event.pointerType === "touch") return; schedule(true, isWarm() ? 0 : openDelay); }} onPointerLeave={(event: PointerEvent) => { if (event.pointerType === "touch") return; schedule(false, closeDelay); }} onFocus={(event: FocusEvent<HTMLElement>) => { if (event.target.matches(":focus-visible")) schedule(true, 0); }} onBlur={() => schedule(false, 0)} > {trigger} <span ref={bubble} role="tooltip" id={id} data-state={open ? "open" : closing ? "closing" : "closed"} data-side={side} className={[ "absolute z-50 w-max max-w-[min(16rem,80vw)] rounded-[var(--rad-sm,6px)] px-2 py-1", "bg-[var(--text,#1b2428)] text-[0.78125rem] leading-snug font-medium text-[var(--surface,#f8f9f7)] shadow-md", side === "top" ? "origin-bottom" : "origin-top", alignClass[align], // An invisible bridge across the gap keeps the tooltip hoverable. "before:absolute before:inset-x-0 before:h-2 before:content-['']", side === "top" ? "bottom-full mb-1.5 before:top-full" : "top-full mt-1.5 before:bottom-full", // Closed tooltips leave layout entirely (no overflow at screen edges); // aria-describedby still resolves hidden content for screen readers. open ? "flex items-center gap-2 motion-safe:data-[motion=in]:animate-[tooltip-in_150ms_ease-out] motion-safe:data-[motion=travel]:animate-[tooltip-travel_160ms_cubic-bezier(0.22,1,0.36,1)]" : closing ? "pointer-events-none flex items-center gap-2 motion-safe:animate-[tooltip-out_100ms_ease-out_forwards]" : "hidden", ].join(" ")} > <span>{content}</span> {shortcut && ( <kbd className="rounded-[4px] border border-[color-mix(in_srgb,var(--surface,#f8f9f7)_35%,transparent)] px-1 font-mono text-[0.6875rem] leading-4 font-medium"> {shortcut} </kbd> )} </span> </span> );}When to use it
Icon-only buttons and dense toolbars benefit from a short hint, but a tooltip must work for keyboard and screen-reader users too, must be dismissible without moving away, and must not get in the way of touch.
Usage
- Copy
src/components/collection/tooltip/tooltip.tsxinto your project (from the Code tab above). - Import it from where you placed it. In this repo that’s
@/components/collection/tooltip/tooltip.
import { Tooltip } from "@/components/collection/tooltip/tooltip";export function ThemeButton({ onToggle }: { onToggle: () => void }) { return ( <Tooltip content="Toggle theme" shortcut="D" side="bottom"> <button type="button" aria-label="Toggle theme" onClick={onToggle}>◐</button> </Tooltip> );}API
| Prop | Type | Default | Description |
|---|---|---|---|
| content* (required) | ReactNode | — | Short, non-essential hint text. |
| children* (required) | ReactElement | — | One focusable trigger (button or link) that accepts aria-describedby and has its own accessible name. |
| side | "top" | "bottom" | "top" | Preferred side. It flips to the other side when there isn't room in the viewport. |
| align | "center" | "start" | "end" | "center" | Horizontal alignment to the trigger. The bubble also shifts sideways to stay inside the viewport. |
| shortcut | string | — | A keyboard shortcut rendered as a kbd after the content, e.g. "D". |
| openDelay | number | 300 | Hover delay in ms. Within 400ms of another tooltip closing it opens instantly and travels from the previous position; keyboard focus always opens immediately. |
| closeDelay | number | 0 | Delay in ms before closing after the pointer leaves. Closing then takes a 100ms fade; the bubble stays hoverable because it sits inside the trigger's hover area. |
| forceOpen | boolean | false | Show it regardless of hover or focus, on every input type, e.g. for "Copied" feedback. Escape still hides it. |
| defaultOpen | boolean | false | Start open, for static previews. Hover, focus and Escape take over afterwards. |
| className | string | — | Classes on the wrapper span. |
* required
Accessibility
- Tab
- Focusing the trigger shows the tooltip; moving focus away hides it.
- Escape
- Dismisses the tooltip without moving focus.
- The tooltip has role="tooltip" and is linked with aria-describedby, so it's announced as a description of the trigger.
- It opens on keyboard focus (focus-visible), not only on hover.
- Dismissible (Escape), hoverable (pointer can move onto it) and persistent while hovered or focused, per WCAG 1.4.13.
- Triggers keep their own accessible name; the tooltip never replaces a label.
- It never opens on touch, where hover doesn't exist; transient feedback uses forceOpen instead.
Limits & tests
Limitations
- Collision handling covers the viewport only (sideways shift and flip), not scrolling containers; keep content short.
- Not for interactive content: use a popover or disclosure instead.
- The neighbour grace period is shared through module state, so it spans every Tooltip on the page.
Tests
tests/e2e/components.spec.ts
- Opens on keyboard focus and is linked via aria-describedby
- Escape dismisses it while focus stays on the trigger
- Opens on hover after the delay, and instantly on a neighbour within the grace period
- Never opens on touch