Teseria
All elements

Tooltip

A dark pill that pops out of a blur from the side of whatever you are over. It waits once, then hops instantly between neighbours.

Code

1. Install

Terminal
npm i framer-motion lucide-react

2. Files

Tooltip.tsx219 lines
"use client";
// Tooltip: a dark pill that pops out of a blur from the side of whatever you are over. It waits once, then hops instantly between
// neighbours. `Tooltip` is a ready-made row (icon buttons plus an info note); `Tip` and `InfoTip` wrap anything you have.
import { cloneElement, useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties, type ReactElement, type ReactNode, type RefObject } from "react";
import { AnimatePresence, MotionConfig, motion } from "framer-motion";
import { Bookmark, Info, Share2, Trash2 } from "lucide-react";

export type TooltipSide = "top" | "bottom" | "left" | "right";

export type TooltipItem = {
  /** Accessible name of the button, and the default tooltip text. */
  label: string;
  /** Icon inside the round button, about 16px. */
  icon: ReactNode;
  /** Tooltip text if different from `label`. */
  tip?: ReactNode;
  /** Keyboard shortcut shown inside the tooltip. */
  kbd?: string;
  /** Which side the tooltip opens on. */
  side?: TooltipSide;
};

export type TooltipProps = {
  /** The icon buttons, each with its own tooltip. */
  items?: TooltipItem[];
  /** Text before the info icon under the buttons. Pass "" to hide the note. */
  note?: string;
  /** What the info icon explains. */
  noteTip?: ReactNode;
  /** Milliseconds before the first tooltip shows. */
  delay?: number;
  /** Called with the item when one of the buttons is pressed. */
  onSelect?: (item: TooltipItem) => void;
  /** Shows the first tooltip from the start. */
  defaultOpen?: boolean;
  className?: string;
  style?: CSSProperties;
};

export const DEFAULT_ITEMS: TooltipItem[] = [
  { label: "Bookmark", icon: <Bookmark style={{ translate: "0 1px" }} />, kbd: "B" },
  { label: "Share", icon: <Share2 style={{ translate: "-1px" }} /> },
  { label: "Delete", icon: <Trash2 /> },
];

const SPRING = { type: "spring", stiffness: 500, damping: 26, mass: 0.7 } as const;
const OPPOSITE: Record<TooltipSide, TooltipSide> = { top: "bottom", bottom: "top", left: "right", right: "left" };
// slide-in offset (px) and growth corner per side
const ENTER: Record<TooltipSide, { x: number; y: number; origin: string }> = {
  top: { x: 0, y: 6, origin: "50% 100%" },
  bottom: { x: 0, y: -6, origin: "50% 0%" },
  left: { x: 6, y: 0, origin: "100% 50%" },
  right: { x: -6, y: 0, origin: "0% 50%" },
};
const VIEWPORT_MARGIN = 8;
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));

/** Spot beside the anchor on `side` (flipped when out of room), kept inside the viewport. */
function place(anchor: DOMRect, width: number, height: number, side: TooltipSide, gap: number) {
  const middleX = anchor.left + anchor.width / 2 - width / 2;
  const middleY = anchor.top + anchor.height / 2 - height / 2;
  const spot = (s: TooltipSide) => {
    if (s === "top") return { x: middleX, y: anchor.top - gap - height, room: anchor.top - gap - height - VIEWPORT_MARGIN };
    if (s === "bottom") return { x: middleX, y: anchor.bottom + gap, room: innerHeight - VIEWPORT_MARGIN - (anchor.bottom + gap + height) };
    if (s === "left") return { x: anchor.left - gap - width, y: middleY, room: anchor.left - gap - width - VIEWPORT_MARGIN };
    return { x: anchor.right + gap, y: middleY, room: innerWidth - VIEWPORT_MARGIN - (anchor.right + gap + width) };
  };
  const chosen = spot(side).room < 0 && spot(OPPOSITE[side]).room >= 0 ? OPPOSITE[side] : side;
  const { x, y } = spot(chosen);
  return { x: clamp(x, VIEWPORT_MARGIN, innerWidth - width - VIEWPORT_MARGIN), y: clamp(y, VIEWPORT_MARGIN, innerHeight - height - VIEWPORT_MARGIN), side: chosen };
}

/** The floating pill, in the top layer (popover="manual"); a resting pill stays in the page. */
function Box({ anchor, rest, side, id, children }: { anchor: RefObject<HTMLElement | null>; rest: boolean; side: TooltipSide; id: string; children: ReactNode }) {
  const el = useRef<HTMLDivElement>(null);
  const inline = useRef(rest).current;
  const [pos, setPos] = useState<{ x: number; y: number; side: TooltipSide } | null>(null);
  useLayoutEffect(() => {
    if (!inline) el.current?.showPopover?.(); // top layer where supported, otherwise it stays a fixed element
    const update = () => {
      const f = el.current;
      const a = anchor.current?.getBoundingClientRect();
      const o = inline && f?.offsetParent?.getBoundingClientRect();
      if (a && f) setPos(place(o ? new DOMRect(a.x - o.x, a.y - o.y, a.width, a.height) : a, f.offsetWidth, f.offsetHeight, side, 7));
    };
    update();
    window.addEventListener("scroll", update, true);
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", update, true);
      window.removeEventListener("resize", update);
    };
  }, [anchor, side]);
  const s = pos?.side ?? side;
  return (
    <motion.div
      ref={el}
      role="tooltip"
      id={id}
      popover={inline ? undefined : "manual"}
      className="ttip-pop"
      style={{ position: inline ? "absolute" : "fixed", left: pos?.x ?? 0, top: pos?.y ?? 0, zIndex: 50, visibility: pos ? "visible" : "hidden", transformOrigin: ENTER[s].origin }}
      initial={{ opacity: 0, scale: 0.9, filter: "blur(6px)", x: ENTER[s].x, y: ENTER[s].y }}
      animate={{ opacity: 1, scale: 1, filter: "blur(0px)", x: 0, y: 0, transitionEnd: { filter: "none" } }}
      exit={{ opacity: 0, scale: 0.94, filter: "blur(5px)", x: ENTER[s].x, y: ENTER[s].y, transition: { duration: 0.14, ease: [0.4, 0, 1, 1] } }}
      transition={{ ...SPRING, opacity: { duration: 0.16 }, filter: { duration: 0.2 } }}
    >
      {children}
    </motion.div>
  );
}

let warmUntil = 0; // another tooltip closed recently, so the next one opens instantly
let shut: ((open: boolean) => void) | undefined; // one at a time

export type TipProps = {
  /** What the tooltip says. */
  content: ReactNode;
  /** Which side it opens on (flips if there is no room). */
  side?: TooltipSide;
  /** Milliseconds before it shows; skipped when another tooltip was just open. */
  delay?: number;
  /** Keyboard shortcut shown in a small key cap. */
  kbd?: string;
  /** Shows from the start. */
  defaultOpen?: boolean;
  /** The element to describe (one focusable element). */
  children: ReactElement<{ "aria-describedby"?: string }>;
  className?: string;
};

/** Wraps one element; the tooltip opens on hover or focus and closes on leave, press or Escape. */
export function Tip({ content, side = "top", delay = 320, kbd, defaultOpen = false, children, className }: TipProps) {
  const id = useId();
  const [open, setOpen] = useState(defaultOpen);
  const rest = useRef(defaultOpen);
  const anchor = useRef<HTMLSpanElement>(null);
  const t = useRef(0);
  const show = () => {
    rest.current = false;
    window.clearTimeout(t.current);
    const wait = performance.now() < warmUntil ? 0 : delay;
    t.current = window.setTimeout(() => setOpen(true), wait);
  };
  const hide = () => {
    window.clearTimeout(t.current);
    if (open) warmUntil = performance.now() + 400;
    setOpen(false);
  };
  useEffect(() => () => window.clearTimeout(t.current), []);
  useEffect(() => {
    if (!open) return;
    if (shut !== setOpen) shut?.(false);
    shut = setOpen;
    const k = (e: KeyboardEvent) => e.key === "Escape" && !rest.current && hide();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, [open]);

  return (
    <>
      <span ref={anchor} className={className ? `ttip-anchor ${className}` : "ttip-anchor"} onPointerEnter={(e) => e.pointerType === "mouse" && show()} onPointerLeave={hide} onPointerDown={hide} onFocus={show} onBlur={hide}>
        {cloneElement(children, { "aria-describedby": open ? id : undefined })}
      </span>
      <MotionConfig reducedMotion="user">
        <AnimatePresence>
          {open && (
            <Box key="f" anchor={anchor} rest={rest.current} side={side} id={id}>
              <span className="ttip-text">{content}</span>
              {kbd && <kbd className="ttip-kbd">{kbd}</kbd>}
            </Box>
          )}
        </AnimatePresence>
      </MotionConfig>
    </>
  );
}

export type InfoTipProps = {
  /** What the tooltip says. */
  content: ReactNode;
  /** Which side it opens on. */
  side?: TooltipSide;
  /** Accessible name of the (i) button. */
  label?: string;
  className?: string;
};

/** A small (i) that explains itself on hover or focus. */
export function InfoTip({ content, side = "top", label = "More info", className }: InfoTipProps) {
  return (
    <Tip content={content} side={side} className={className}>
      <button type="button" className="ttip-info" aria-label={label}>
        <Info size={14} strokeWidth={2} aria-hidden />
      </button>
    </Tip>
  );
}

export function Tooltip({ items = DEFAULT_ITEMS, note = "Net revenue", noteTip = "After fees and refunds.", delay, onSelect, defaultOpen, className, style }: TooltipProps) {
  return (
    <div className={className ? `ttip-root ${className}` : "ttip-root"} style={style}>
      <div className="ttip-row">
        {items.map((it, i) => (
          <Tip key={it.label} content={it.tip ?? it.label} side={it.side} kbd={it.kbd} delay={delay} defaultOpen={defaultOpen && !i}>
            <button type="button" className="ttip-btn" aria-label={it.label} onClick={() => onSelect?.(it)}>
              <span className="ttip-ico">{it.icon}</span>
            </button>
          </Tip>
        ))}
      </div>
      {note !== "" && (
        <div className="ttip-note">
          {note} <InfoTip content={noteTip} side="right" />
        </div>
      )}
    </div>
  );
}
Tooltip.css102 lines
/* Tooltip. Prefix ttip-. The tip can live in the top layer, so it carries its own basics. */
.ttip-root, .ttip-root *, .ttip-pop, .ttip-pop *, .ttip-anchor, .ttip-anchor * { box-sizing: border-box; }
.ttip-root, .ttip-pop { font-family: var(--ts-font, system-ui, sans-serif); }
:where(.ttip-root) button { font: inherit; color: inherit; background: none; border: 0; padding: 0; margin: 0; cursor: pointer; }
:where(.ttip-root) :focus-visible { outline: 2px solid var(--ts-focus); outline-offset: 2px; }

.ttip-root {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 40px;
  color: var(--ts-fg);
}
.ttip-row,
.ttip-note {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 4px;
  font-size: 14px;
}
.ttip-btn {
  background: var(--ts-raised);
  width: 40px;
  height: 40px;
  border-radius: 999px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: var(--ts-edge);
  user-select: none;
  -webkit-tap-highlight-color: transparent;
  transition: scale 0.22s cubic-bezier(.22, 1, .36, 1), background 0.16s cubic-bezier(.22, 1, .36, 1);
}
.ttip-btn:hover {
  background: rgba(var(--ts-fg-rgb), 0.05);
}
.ttip-btn:active {
  scale: 0.96;
}
.ttip-btn:focus-visible {
  outline: 0;
  box-shadow: 0 0 0 2px var(--ts-page), 0 0 0 4px var(--ts-accent);
}
.ttip-ico {
  display: inline-flex;
}
.ttip-ico svg {
  width: 18px;
  height: 18px;
}
.ttip-anchor {
  display: inline-flex;
}
.ttip-pop {
  inset: auto;
  margin: 0;
  border: 0;
  overflow: visible;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  height: 30px;
  padding: 0 10px;
  border-radius: 999px;
  background: var(--ts-fg);
  color: var(--ts-fg-inverse);
  font-size: 12px;
  font-weight: 500;
  letter-spacing: -0.01em;
  white-space: nowrap;
  pointer-events: none;
}
.ttip-kbd {
  font: inherit;
  font-size: 11px;
  padding: 1px 5px;
  border-radius: 5px;
  background: color-mix(in srgb, var(--ts-fg-inverse) 16%, transparent);
  color: inherit;
}
.ttip-info {
  padding: 0;
  border: 0;
  background: transparent;
  width: 22px;
  height: 22px;
  border-radius: 999px;
  color: color-mix(in srgb, var(--ts-fg) 48%, var(--ts-raised));
  display: grid;
  place-items: center;
  cursor: help;
  transition: color 0.16s cubic-bezier(.22, 1, .36, 1), background 0.16s cubic-bezier(.22, 1, .36, 1), scale 0.22s cubic-bezier(.22, 1, .36, 1);
}
.ttip-info:hover {
  color: var(--ts-fg);
  background: rgba(var(--ts-fg-rgb), 0.07);
}
.ttip-info:active {
  scale: 0.92;
}
tokens.cssshared · add once
/*
 * Teseria tokens — the only colours, fonts and corner radii a block reads.
 *
 * Every name sits under --ts- so it never collides with your app's own variables. Include this file once, or point
 * the names at your theme (e.g. --ts-accent: var(--brand)). Light by default; dark follows [data-theme="dark"] on
 * any ancestor, or the OS setting unless [data-theme="light"] is set.
 *
 *   Surfaces   page → raised (cards, popovers) · sunken (wells, tracks) · tint-1..3 (neutral fills, light to deep)
 *   Text       fg → secondary → tertiary → muted → faint · fg-inverse sits on an fg-coloured fill
 *   Lines      border · edge (the box-shadow a filled surface uses instead of an outline: soft in light, nothing in
 *              dark; composes with other shadows)
 *   Signals    accent · focus · success · warning · danger
 *   Corners    controls are always pills · r-panel (dialogs, sheets, cards) · r-pop (menus, popovers, toasts) · r-inner
 *              (thumbnails, inner cards); a row inside a panel uses the panel radius minus the panel padding
 */
:root {
  --ts-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
  --ts-r-panel: 24px;
  --ts-r-pop: 18px;
  --ts-r-inner: 12px;

  --ts-page: #ffffff;
  --ts-raised: #ffffff;
  --ts-sunken: #f3f2f0;
  --ts-tint-1: #f5f4f2;
  --ts-tint-2: #ecebe8;
  --ts-tint-3: #e3e1dd;

  --ts-fg: #161514;
  --ts-fg-rgb: 22, 21, 20;
  --ts-fg-secondary: #3a3836;
  --ts-fg-tertiary: #585552;
  --ts-fg-muted: #6d6a66;
  --ts-fg-faint: #89857f;
  --ts-fg-inverse: #ffffff;

  --ts-border: rgba(22, 21, 20, 0.1);
  --ts-edge: 0 0 0 1px rgba(22, 21, 20, 0.07), 0 1px 2px rgba(22, 21, 20, 0.05);

  --ts-accent: #3446eb;
  --ts-focus: #3446eb;
  --ts-success: #13804a;
  --ts-warning: #a9650b;
  --ts-danger: #df474e;
}

:root[data-theme="dark"] {
  --ts-page: #0b0a09;
  --ts-raised: #24221f;
  --ts-sunken: #0d0c0b;
  --ts-tint-1: #131211;
  --ts-tint-2: #1b1a18;
  --ts-tint-3: #2b2926;

  --ts-fg: #f6f5f3;
  --ts-fg-rgb: 246, 245, 243;
  --ts-fg-secondary: #bab8b4;
  --ts-fg-tertiary: #9e9b97;
  --ts-fg-muted: #8e8b86;
  --ts-fg-faint: #72706c;
  --ts-fg-inverse: #0b0a09;

  --ts-border: rgba(246, 245, 243, 0.1);
  --ts-edge: 0 0 #0000;

  --ts-accent: #3446eb;
  --ts-focus: #7f8cff;
  --ts-success: #3ccf80;
  --ts-warning: #efa130;
  --ts-danger: #df474e;
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --ts-page: #0b0a09;
    --ts-raised: #24221f;
    --ts-sunken: #0d0c0b;
    --ts-tint-1: #131211;
    --ts-tint-2: #1b1a18;
    --ts-tint-3: #2b2926;

    --ts-fg: #f6f5f3;
    --ts-fg-rgb: 246, 245, 243;
    --ts-fg-secondary: #bab8b4;
    --ts-fg-tertiary: #9e9b97;
    --ts-fg-muted: #8e8b86;
    --ts-fg-faint: #72706c;
    --ts-fg-inverse: #0b0a09;

    --ts-border: rgba(246, 245, 243, 0.1);
    --ts-edge: 0 0 #0000;

    --ts-accent: #3446eb;
    --ts-focus: #7f8cff;
    --ts-success: #3ccf80;
    --ts-warning: #efa130;
    --ts-danger: #df474e;
  }
}

3. Usage

Demo.tsx
import { Tooltip } from "./Tooltip";
import "./Tooltip.css";

export default function Demo() {
  return <Tooltip />;
}