Tooltip
A tooltip that opens on hover after a short delay and immediately on keyboard focus, closes on blur, pointer down or Escape (without closing a dialog around it), and stays open while the pointer moves onto it. Four sides with an arrow, a skip-delay when moving between triggers, aria-describedby wiring on the trigger, controlled or uncontrolled state, and a TooltipKbd helper for shortcuts.
Source
"use client";
import {
cloneElement, useCallback, useEffect, useId, useRef, useState,
type FocusEvent, type PointerEvent, type ReactElement, type ReactNode,
} from "react";
import { cn } from "@/lib/utils";
export type TooltipSide = "top" | "bottom" | "left" | "right";
// Shared across tooltips: moving from one trigger to the next shows the next one at once.
let lastClosedAt = 0;
const SKIP_DELAY_MS = 300;
export interface TooltipProps {
content: ReactNode;
/** One focusable element, such as a button. It gets aria-describedby pointing at the tooltip. */
children: ReactElement<{ "aria-describedby"?: string }>;
side?: TooltipSide;
/** Milliseconds of hover before showing. Keyboard focus shows it straight away. */
delay?: number;
/** Milliseconds before hiding, so the pointer can cross the gap onto the tooltip. */
closeDelay?: number;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
disabled?: boolean;
className?: string;
wrapperClassName?: string;
}
const placement: Record<TooltipSide, { bubble: string; hidden: string; arrow: string }> = {
top: {
bubble: "bottom-full left-1/2 mb-2 -translate-x-1/2",
hidden: "motion-safe:translate-y-1",
arrow: "left-1/2 top-full -translate-x-1/2 -translate-y-1/2",
},
bottom: {
bubble: "left-1/2 top-full mt-2 -translate-x-1/2",
hidden: "motion-safe:-translate-y-1",
arrow: "bottom-full left-1/2 -translate-x-1/2 translate-y-1/2",
},
left: {
bubble: "right-full top-1/2 mr-2 -translate-y-1/2",
hidden: "motion-safe:translate-x-1",
arrow: "left-full top-1/2 -translate-x-1/2 -translate-y-1/2",
},
right: {
bubble: "left-full top-1/2 ml-2 -translate-y-1/2",
hidden: "motion-safe:-translate-x-1",
arrow: "right-full top-1/2 -translate-y-1/2 translate-x-1/2",
},
};
export function Tooltip({
content, children, side = "top", delay = 500, closeDelay = 120, open: controlled, defaultOpen = false, onOpenChange,
disabled, className, wrapperClassName,
}: TooltipProps) {
const id = useId();
const [uncontrolled, setUncontrolled] = useState(defaultOpen);
const open = (controlled ?? uncontrolled) && !disabled;
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const setOpen = useCallback((next: boolean) => {
if (controlled === undefined) setUncontrolled(next);
onOpenChange?.(next);
if (!next) lastClosedAt = Date.now();
}, [controlled, onOpenChange]);
const schedule = useCallback((next: boolean, ms: number) => {
clearTimeout(timer.current);
if (ms <= 0) setOpen(next);
else timer.current = setTimeout(() => setOpen(next), ms);
}, [setOpen]);
useEffect(() => () => clearTimeout(timer.current), []);
// Escape hides the tooltip first, without also closing a dialog or menu around it.
useEffect(() => {
if (!open) return;
function handleKey(event: KeyboardEvent) {
if (event.key !== "Escape") return;
event.stopPropagation();
schedule(false, 0);
}
document.addEventListener("keydown", handleKey, true);
return () => document.removeEventListener("keydown", handleKey, true);
}, [open, schedule]);
const handlers = {
onPointerEnter(event: PointerEvent<HTMLSpanElement>) {
if (event.pointerType === "touch") return;
schedule(true, Date.now() - lastClosedAt < SKIP_DELAY_MS ? 0 : delay);
},
onPointerLeave(event: PointerEvent<HTMLSpanElement>) {
if (event.pointerType === "touch") return;
schedule(false, closeDelay);
},
onPointerDown() {
schedule(false, 0);
},
onFocus(event: FocusEvent<HTMLSpanElement>) {
// Keyboard focus only: a mouse click that focuses the button should not pop the tooltip.
if ((event.target as HTMLElement).matches?.(":focus-visible")) schedule(true, 0);
},
onBlur() {
schedule(false, 0);
},
};
const describedBy = [children.props["aria-describedby"], id].filter(Boolean).join(" ");
const place = placement[side];
return (
<span className={cn("relative inline-flex", wrapperClassName)} {...handlers}>
{cloneElement(children, { "aria-describedby": describedBy })}
<span
id={id}
role="tooltip"
data-state={open ? "open" : "closed"}
data-side={side}
className={cn(
"absolute z-50 w-max max-w-64 rounded-md bg-foreground px-2.5 py-1.5 text-xs font-medium leading-4 text-background",
"shadow-[0_6px_16px_-6px_rgb(0_0_0/0.35)] transition-[opacity,visibility] duration-150 ease-out",
"motion-safe:transition-[opacity,visibility,translate]",
place.bubble,
open ? "visible opacity-100" : cn("invisible opacity-0", place.hidden),
className,
)}
>
{content}
<span aria-hidden="true" className={cn("absolute -z-10 size-2 rotate-45 rounded-[1px] bg-foreground", place.arrow)} />
</span>
</span>
);
}
/** A small keyboard hint styled for the inverted tooltip surface, such as <TooltipKbd>⌘B</TooltipKbd>. */
export function TooltipKbd({ children }: { children: ReactNode }) {
return (
<kbd className="ml-1.5 inline-flex h-4 items-center rounded-[4px] bg-background/15 px-1 font-sans text-[10px] font-medium text-background/80">
{children}
</kbd>
);
}
