Tooltip
Waits half a second the first time, then every tooltip in the group answers instantly. Flips to whichever side has room.
npx shadcn@latest add https://captain-ui.vercel.app/r/tooltip.jsonRound invoice totals half-even and add a test for the 0.005 case.
"use client";
// Captain UI · Tooltip, MIT. Waits once, then the whole group answers instantly. Flips to the side with room.
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
useCallback,
useContext,
useEffect,
useId,
useRef,
useState,
type ReactElement,
type ReactNode,
type Ref,
} from "react";
import { createPortal } from "react-dom";
import { EASE, clamp, cx, useIsoLayoutEffect } from "@/registry/captain/ui/captain";
type Side = "top" | "bottom" | "left" | "right";
type Group = {
delay: number;
closeDelay: number;
/** After the last tooltip closes, others open instantly for this long. */
skipDelay: number;
lastClose: number;
close: (() => void) | null;
};
const fallback: Group = { delay: 500, closeDelay: 0, skipDelay: 300, lastClose: 0, close: null };
const GroupCtx = createContext<Group>(fallback);
/** Shares one delay across tooltips: after one opens, moving to the next is instant. */
export function TooltipProvider({ delay = 500, closeDelay = 0, skipDelay = 300, children }: { delay?: number; closeDelay?: number; skipDelay?: number; children: ReactNode }) {
const g = useRef<Group>({ delay, closeDelay, skipDelay, lastClose: 0, close: null });
g.current.delay = delay;
g.current.closeDelay = closeDelay;
g.current.skipDelay = skipDelay;
return <GroupCtx.Provider value={g.current}>{children}</GroupCtx.Provider>;
}
type TooltipProps = {
content: ReactNode;
/** Keyboard shortcut shown after the label, e.g. "⌘K". */
shortcut?: string;
side?: Side;
/** Gap between trigger and tooltip. */
offset?: number;
/** Overrides the group delay for this one. */
delay?: number;
/** One focusable element. It receives aria-describedby. */
children: ReactElement;
};
type Pos = { x: number; y: number; side: Side; ox: number; oy: number };
function place(t: DOMRect, w: number, h: number, want: Side, gap: number): Pos {
const vw = window.innerWidth;
const vh = window.innerHeight;
const m = 8;
const room = { top: t.top - gap - m, bottom: vh - t.bottom - gap - m, left: t.left - gap - m, right: vw - t.right - gap - m };
const need = want === "top" || want === "bottom" ? h : w;
const opposite: Record<Side, Side> = { top: "bottom", bottom: "top", left: "right", right: "left" };
const side = room[want] >= need || room[want] >= room[opposite[want]] ? want : opposite[want];
let x: number;
let y: number;
if (side === "top" || side === "bottom") {
x = clamp(t.left + t.width / 2 - w / 2, m, vw - w - m);
y = side === "top" ? t.top - gap - h : t.bottom + gap;
} else {
y = clamp(t.top + t.height / 2 - h / 2, m, vh - h - m);
x = side === "left" ? t.left - gap - w : t.right + gap;
}
// Grow out of the trigger: the origin sits on the edge that faces it.
const ox = side === "left" ? w : side === "right" ? 0 : clamp(t.left + t.width / 2 - x, 0, w);
const oy = side === "top" ? h : side === "bottom" ? 0 : clamp(t.top + t.height / 2 - y, 0, h);
return { x, y, side, ox, oy };
}
function setRef<T>(ref: Ref<T> | undefined, value: T) {
if (typeof ref === "function") ref(value);
else if (ref && typeof ref === "object") (ref as { current: T }).current = value;
}
export function Tooltip({ content, shortcut, side = "top", offset = 6, delay, children }: TooltipProps) {
const group = useContext(GroupCtx);
const [open, setOpen] = useState(false);
const [instant, setInstant] = useState(false);
const [pos, setPos] = useState<Pos | null>(null);
const trigger = useRef<HTMLElement | null>(null);
const tip = useRef<HTMLDivElement | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const reduce = useReducedMotion();
const id = useId();
const clear = () => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
};
const openRef = useRef(false);
openRef.current = open;
const hide = useCallback(() => {
clear();
// Stamp the close now, not in a state updater: the next trigger's pointerenter fires in the same tick.
if (openRef.current) group.lastClose = performance.now();
openRef.current = false;
setOpen(false);
if (group.close === hideRef.current) group.close = null;
}, [group]);
const hideRef = useRef(hide);
hideRef.current = hide;
const show = (now: boolean) => {
clear();
const warm = group.close !== null || performance.now() - group.lastClose < group.skipDelay;
const go = () => {
if (group.close && group.close !== hideRef.current) group.close();
group.close = hideRef.current;
openRef.current = true;
setInstant(warm);
setOpen(true);
};
if (now || warm) go();
else timer.current = setTimeout(go, delay ?? group.delay);
};
const scheduleHide = () => {
clear();
if (group.closeDelay > 0) timer.current = setTimeout(hide, group.closeDelay);
else hide();
};
useEffect(() => () => clear(), []);
useEffect(() => {
if (!open) return;
const key = (e: KeyboardEvent) => e.key === "Escape" && hide();
const away = () => hide();
window.addEventListener("keydown", key);
window.addEventListener("scroll", away, true);
window.addEventListener("resize", away);
return () => {
window.removeEventListener("keydown", key);
window.removeEventListener("scroll", away, true);
window.removeEventListener("resize", away);
};
}, [open, hide]);
useIsoLayoutEffect(() => {
if (!open || !trigger.current || !tip.current) return;
setPos(place(trigger.current.getBoundingClientRect(), tip.current.offsetWidth, tip.current.offsetHeight, side, offset));
}, [open, side, offset, content]);
if (!isValidElement(children)) return children;
const child = children as ReactElement<Record<string, unknown> & { ref?: Ref<HTMLElement> }>;
const cp = child.props;
const call = (name: string, e: unknown) => (cp[name] as ((e: unknown) => void) | undefined)?.(e);
const trig = cloneElement(child, {
ref: (el: HTMLElement | null) => {
trigger.current = el;
setRef(cp.ref, el);
},
"aria-describedby": open ? id : (cp["aria-describedby"] as string | undefined),
onPointerEnter: (e: React.PointerEvent) => {
call("onPointerEnter", e);
if (e.pointerType === "mouse") show(false);
},
onPointerLeave: (e: React.PointerEvent) => {
call("onPointerLeave", e);
scheduleHide();
},
onPointerDown: (e: React.PointerEvent) => {
call("onPointerDown", e);
hide();
},
onFocus: (e: React.FocusEvent<HTMLElement>) => {
call("onFocus", e);
if (e.currentTarget.matches(":focus-visible")) show(true);
},
onBlur: (e: React.FocusEvent) => {
call("onBlur", e);
hide();
},
});
const travel = reduce || instant ? 0 : 1;
const from = pos ? { top: { y: 3 }, bottom: { y: -3 }, left: { x: 3 }, right: { x: -3 } }[pos.side] : {};
return (
<>
{trig}
{typeof document !== "undefined"
? createPortal(
<AnimatePresence>
{open ? (
<motion.div
ref={tip}
id={id}
role="tooltip"
initial={instant ? { opacity: 1, scale: 1, x: 0, y: 0 } : { opacity: 0, scale: reduce ? 1 : 0.96, ...(travel ? from : {}) }}
animate={{ opacity: 1, scale: 1, x: 0, y: 0 }}
exit={{ opacity: 0, transition: { duration: 0.1, ease: EASE } }}
transition={{ duration: 0.14, ease: EASE }}
className={cx(
"pointer-events-none fixed left-0 top-0 z-[100] flex max-w-[260px] items-center gap-2 rounded-[6px] bg-primary px-2 py-[5px] text-[12.5px] font-medium leading-[1.3] text-primary-ink shadow-menu",
)}
style={{
left: pos?.x ?? -9999,
top: pos?.y ?? -9999,
transformOrigin: pos ? `${pos.ox}px ${pos.oy}px` : undefined,
visibility: pos ? "visible" : "hidden",
}}
>
<span>{content}</span>
{shortcut ? <span className="tnum font-normal opacity-65">{shortcut}</span> : null}
</motion.div>
) : null}
</AnimatePresence>,
document.body,
)
: null}
</>
);
}Usage
import { Tooltip, TooltipProvider } from "@/components/ui/tooltip"
<TooltipProvider>
<Tooltip content="Attach a file" shortcut="⌘U">
<button aria-label="Attach a file">…</button>
</Tooltip>
</TooltipProvider>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| content | ReactNode | What the tooltip says. Keep it to one short line. | |
| shortcut | string | A keyboard shortcut set after the label. | |
| side | "top" | "bottom" | "left" | "right" | "top" | Preferred side. Flips when there is no room. |
| offset | number | 6 | Gap to the trigger in px. |
| delay | number | Overrides the group delay for this tooltip. | |
| TooltipProvider delay | number | 500 | First-open delay in ms for the group. |
| TooltipProvider skipDelay | number | 300 | After a tooltip closes, others open instantly for this long. |
Keyboard
- Tab
- Show on keyboard focus
- Esc
- Hide
Accessibility
- role=tooltip, wired to the trigger with aria-describedby while open.
- Opens on keyboard focus (focus-visible only), never on a mouse click.
- Touch never opens it: tooltips hold no information the trigger's label does not.