{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"tooltip-group","type":"registry:component","title":"Tooltip group","description":"One tooltip slides from button to button and reshapes around each label.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/tooltip-group.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from \"react\";\nimport {\n  animate,\n  AnimatePresence,\n  motion,\n  useMotionValue,\n  type Variants,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n/* The teachable part: one shared clock, and one shared bubble, for every\n   tooltip in a group. Scanning a toolbar doesn't swap tooltips; the same\n   bubble slides to the next button and reshapes around its label. */\n\ntype Open = { id: string; instant: boolean } | null;\ntype Shown = { id: string; content: React.ReactNode; dir: number };\ntype Anchor = { el: HTMLElement | null; content: React.ReactNode };\n\ntype Group = {\n  open: Open;\n  anchors: React.RefObject<Map<string, Anchor>>;\n  request: (id: string, immediate: boolean) => void;\n  release: (id: string) => void;\n  dismiss: (id: string) => void;\n};\n\nconst GroupContext = createContext<Group | null>(null);\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// A touch of give on the slide, so the bubble reads as one object being\n// carried over rather than a highlight jumping. Short enough that a fast\n// sweep never leaves it trailing more than a button behind.\nconst GLIDE = { type: \"spring\", visualDuration: 0.22, bounce: 0.12 } as const;\n// The outline itself never overshoots: a pill that briefly outgrows its\n// label looks like a measuring bug.\nconst RESHAPE = { type: \"spring\", visualDuration: 0.22, bounce: 0 } as const;\n// Space between the trigger's top edge and the arrow tip.\nconst OFFSET = 10;\n// Horizontal padding inside the pill, added to the measured label.\nconst PAD_X = 24;\n// A reopen within this window finds the old bubble still fading out, so it\n// slides from there instead of popping in somewhere new.\nconst STILL_VISIBLE = 110;\n\n// The incoming label drifts in from the side the bubble is travelling from,\n// the outgoing one leaves the other way, so the text rides with the motion.\nconst LABEL: Variants = {\n  enter: ({ dir, reduce }: { dir: number; reduce: boolean }) => ({\n    opacity: 0,\n    x: reduce ? 0 : dir * 10,\n    filter: reduce ? \"blur(0px)\" : \"blur(4px)\",\n  }),\n  center: {\n    opacity: 1,\n    x: 0,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.2, ease: EASE_OUT },\n  },\n  // Softer and quicker than the entrance: gone before the new one settles.\n  exit: ({ dir, reduce }: { dir: number; reduce: boolean }) => ({\n    opacity: 0,\n    x: reduce ? 0 : dir * -6,\n    filter: reduce ? \"blur(0px)\" : \"blur(2px)\",\n    transition: { duration: 0.12, ease: EASE_OUT },\n  }),\n};\n\nexport function TooltipGroup({\n  // Long enough that sweeping the cursor across the page never flashes a\n  // tooltip, short enough that a deliberate pause gets one.\n  delay = 500,\n  // How long the group stays warm after the last tooltip closes. Covers the\n  // gap between two buttons with plenty of room to spare.\n  skipDelay = 300,\n  className,\n  children,\n}: {\n  delay?: number;\n  skipDelay?: number;\n  className?: string;\n  children: React.ReactNode;\n}) {\n  const reduceMotion = useReducedMotion() ?? false;\n  const [open, setOpenState] = useState<Open>(null);\n  const [shown, setShown] = useState<Shown | null>(null);\n  // Pointer events can outrun re-renders, so handlers read these refs.\n  const openRef = useRef<Open>(null);\n  const shownId = useRef<string | null>(null);\n  const closedAt = useRef(-Infinity);\n  const warm = useRef(false);\n  const pending = useRef<string | null>(null);\n  const suppressed = useRef<string | null>(null);\n  const delayTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const graceTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const anchors = useRef(new Map<string, Anchor>());\n\n  const root = useRef<HTMLDivElement>(null);\n  const measure = useRef<HTMLSpanElement>(null);\n  // Position of the arrow tip and width of the pill, relative to the group.\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n  const width = useMotionValue(0);\n  const lastOpen = useRef<Open>(null);\n\n  const center = (id: string | null) => {\n    const box = id ? anchors.current.get(id)?.el?.getBoundingClientRect() : null;\n    return box ? box.left + box.width / 2 : null;\n  };\n\n  const setOpen = useCallback((next: Open) => {\n    const previous = openRef.current;\n    openRef.current = next;\n    setOpenState(next);\n    if (!next) {\n      if (previous) closedAt.current = performance.now();\n      return;\n    }\n    const from = center(shownId.current);\n    const to = center(next.id);\n    shownId.current = next.id;\n    setShown({\n      id: next.id,\n      content: anchors.current.get(next.id)?.content,\n      dir: from === null || to === null ? 0 : Math.sign(to - from),\n    });\n  }, []);\n\n  // Measures the new label and moves the bubble before paint, so the first\n  // frame is already heading to the right place.\n  useLayoutEffect(() => {\n    const wasOpen = lastOpen.current !== null;\n    lastOpen.current = open;\n    const el = open ? anchors.current.get(open.id)?.el : null;\n    const box = root.current?.getBoundingClientRect();\n    if (!open || !el || !box || !measure.current) return;\n    const target = el.getBoundingClientRect();\n    const tx = target.left + target.width / 2 - box.left;\n    const ty = target.top - box.top - OFFSET;\n    const tw = measure.current.offsetWidth + PAD_X;\n    const onScreen =\n      wasOpen ||\n      performance.now() - closedAt.current < STILL_VISIBLE;\n    if (!onScreen || reduceMotion) {\n      x.jump(tx);\n      y.jump(ty);\n      width.jump(tw);\n      return;\n    }\n    // Not stopped on cleanup: the next animate() on the same value takes\n    // over mid-flight and keeps its velocity, so a fast sweep bends the\n    // path instead of restarting it.\n    animate(x, tx, GLIDE);\n    animate(y, ty, GLIDE);\n    animate(width, tw, RESHAPE);\n  }, [open, shown, reduceMotion, x, y, width]);\n\n  useEffect(\n    () => () => {\n      x.stop();\n      y.stop();\n      width.stop();\n    },\n    [x, y, width],\n  );\n\n  useEffect(\n    () => () => {\n      clearTimeout(delayTimer.current);\n      clearTimeout(graceTimer.current);\n    },\n    [],\n  );\n\n  const request = useCallback(\n    (id: string, immediate: boolean) => {\n      // Pressed or Escaped: stay quiet until the pointer or focus moves on.\n      if (suppressed.current === id) return;\n      clearTimeout(delayTimer.current);\n      clearTimeout(graceTimer.current);\n      pending.current = null;\n      if (warm.current || openRef.current) {\n        // Scanning the toolbar: no delay and no entrance. The bubble that is\n        // already up slides over instead.\n        setOpen({ id, instant: true });\n        return;\n      }\n      if (immediate) {\n        warm.current = true;\n        setOpen({ id, instant: false });\n        return;\n      }\n      pending.current = id;\n      delayTimer.current = setTimeout(() => {\n        pending.current = null;\n        warm.current = true;\n        setOpen({ id, instant: false });\n      }, delay);\n    },\n    [delay, setOpen],\n  );\n\n  const release = useCallback(\n    (id: string) => {\n      if (suppressed.current === id) suppressed.current = null;\n      if (pending.current === id) {\n        clearTimeout(delayTimer.current);\n        pending.current = null;\n      }\n      // A late leave or blur from a trigger that is no longer showing must\n      // not close or cool down the one that is.\n      if (openRef.current && openRef.current.id !== id) return;\n      if (openRef.current) setOpen(null);\n      if (!warm.current) return;\n      clearTimeout(graceTimer.current);\n      graceTimer.current = setTimeout(() => {\n        warm.current = false;\n      }, skipDelay);\n    },\n    [skipDelay, setOpen],\n  );\n\n  const dismiss = useCallback(\n    (id: string) => {\n      if (pending.current === id) {\n        clearTimeout(delayTimer.current);\n        pending.current = null;\n      }\n      suppressed.current = id;\n      if (openRef.current?.id === id) setOpen(null);\n    },\n    [setOpen],\n  );\n\n  useEffect(() => {\n    if (!open) return;\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") dismiss(open.id);\n    };\n    document.addEventListener(\"keydown\", onKey);\n    return () => document.removeEventListener(\"keydown\", onKey);\n  }, [open, dismiss]);\n\n  const value = useMemo(\n    () => ({ open, anchors, request, release, dismiss }),\n    [open, request, release, dismiss],\n  );\n  const custom = { dir: shown?.dir ?? 0, reduce: reduceMotion };\n\n  return (\n    <GroupContext.Provider value={value}>\n      <div ref={root} className={cn(\"relative w-fit max-w-full\", className)}>\n        {children}\n        {/* Every trigger describes itself with its own hidden text, so this\n            visual copy stays out of the accessibility tree. */}\n        <motion.div\n          aria-hidden\n          style={{ x, y, width }}\n          className={cn(\n            // Anchored by its arrow tip: the CSS translate pulls it up and\n            // left of the point Motion moves, and it grows out of that point.\n            \"pointer-events-none absolute top-0 left-0 z-10 h-7 origin-bottom -translate-x-1/2 -translate-y-full\",\n            \"transition-[opacity,scale] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:scale-100\",\n            // Enters in 150ms and leaves in 100ms: the exit never holds the eye.\n            open ? \"scale-100 opacity-100 duration-150\" : \"scale-[0.97] opacity-0 duration-100\",\n            open?.instant && \"duration-0\",\n          )}\n        >\n          <div className=\"relative size-full overflow-hidden rounded-full bg-foreground text-[13px] font-medium text-background\">\n            <AnimatePresence initial={false} custom={custom}>\n              {shown && (\n                <motion.span\n                  key={shown.id}\n                  custom={custom}\n                  variants={LABEL}\n                  initial=\"enter\"\n                  animate=\"center\"\n                  exit=\"exit\"\n                  className=\"absolute inset-0 flex items-center justify-center gap-2 whitespace-nowrap\"\n                >\n                  {shown.content}\n                </motion.span>\n              )}\n            </AnimatePresence>\n          </div>\n          {/* Part of the same object, so it slides with the pill instead of\n              being redrawn under each trigger. */}\n          <span className=\"absolute top-full left-1/2 -ml-[5px] block border-x-[5px] border-t-[5px] border-x-transparent border-t-foreground\" />\n        </motion.div>\n        {/* Sizes the pill: the same label, laid out but never painted. */}\n        <span\n          ref={measure}\n          aria-hidden\n          className=\"invisible absolute top-0 left-0 flex gap-2 text-[13px] font-medium whitespace-nowrap\"\n        >\n          {shown?.content}\n        </span>\n      </div>\n    </GroupContext.Provider>\n  );\n}\n\nexport function useTooltip(content?: React.ReactNode) {\n  const group = useContext(GroupContext);\n  if (!group) throw new Error(\"useTooltip needs a <TooltipGroup> above it\");\n  const { open, anchors, request, release, dismiss } = group;\n  const id = useId();\n  const isOpen = open?.id === id;\n  const el = useRef<HTMLElement | null>(null);\n\n  // Kept current every render, read only when this tooltip opens.\n  useLayoutEffect(() => {\n    anchors.current.set(id, { el: el.current, content });\n  });\n  useEffect(() => {\n    const map = anchors.current;\n    return () => {\n      map.delete(id);\n    };\n  }, [anchors, id]);\n\n  return {\n    isOpen,\n    // The bubble points at this element.\n    anchorRef: (node: HTMLElement | null) => {\n      el.current = node;\n    },\n    triggerProps: {\n      \"aria-describedby\": id,\n      onPointerEnter: (e: React.PointerEvent) => {\n        // Touch has no hover; a tap would flash the tooltip under the finger.\n        if (e.pointerType !== \"touch\") request(id, false);\n      },\n      onPointerLeave: (e: React.PointerEvent) => {\n        if (e.pointerType !== \"touch\") release(id);\n      },\n      // A press means the user already knows what it does, and the tooltip\n      // would otherwise sit on top of whatever the press changed.\n      onPointerDown: () => dismiss(id),\n      onFocus: (e: React.FocusEvent<HTMLElement>) => {\n        // Keyboard users get it at once: there is no hover to wait out.\n        if (e.currentTarget.matches(\":focus-visible\")) request(id, true);\n      },\n      onBlur: () => release(id),\n    },\n    // Put on a hidden element holding the text, for aria-describedby.\n    tooltipProps: { id, role: \"tooltip\" as const, hidden: true },\n  };\n}\n\n/* A text formatting toolbar built on it. */\n\nexport type FormatItem = {\n  key: string;\n  label: string;\n  // KeyboardEvent.code, so holding Shift never changes which key matches.\n  code: string;\n  shift?: boolean;\n  icon: React.ReactNode;\n};\n\nconst isMac = () => /Mac|iPhone|iPad/.test(navigator.platform);\nconst subscribeNever = () => () => {};\n\nfunction useIsMac() {\n  // The server can't know, so it renders Mac glyphs and the client corrects\n  // them right after hydration.\n  return useSyncExternalStore(subscribeNever, isMac, () => true);\n}\n\nconst keyName = (code: string) => code.replace(/^(Key|Digit)/, \"\");\n\nexport function FormatToolbar({\n  items,\n  pressed,\n  onToggle,\n  label = \"Text formatting\",\n  className,\n}: {\n  items: FormatItem[];\n  pressed: Record<string, boolean>;\n  onToggle: (key: string) => void;\n  label?: string;\n  className?: string;\n}) {\n  const mac = useIsMac();\n  const [active, setActive] = useState(0);\n  const refs = useRef<(HTMLButtonElement | null)[]>([]);\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (mac ? e.metaKey : e.ctrlKey) {\n      const item = items.find(\n        (i) => i.code === e.code && Boolean(i.shift) === e.shiftKey,\n      );\n      if (!item) return;\n      e.preventDefault();\n      onToggle(item.key);\n      return;\n    }\n    // One tab stop for the whole toolbar; arrows move within it.\n    const last = items.length - 1;\n    const moves: Record<string, number> = {\n      ArrowRight: active === last ? 0 : active + 1,\n      ArrowLeft: active === 0 ? last : active - 1,\n      Home: 0,\n      End: last,\n    };\n    const next = moves[e.key];\n    if (next === undefined) return;\n    e.preventDefault();\n    setActive(next);\n    refs.current[next]?.focus();\n  };\n\n  return (\n    <TooltipGroup>\n      {/* 48px pill with 4px padding around 40px buttons keeps the radii\n          concentric: 24 = 20 + 4. */}\n      <div\n        role=\"toolbar\"\n        aria-label={label}\n        onKeyDown={onKeyDown}\n        className={cn(\n          \"flex h-12 items-center gap-1 rounded-full bg-muted p-1 shadow-raised\",\n          className,\n        )}\n      >\n        {items.map((item, i) => (\n          <FormatButton\n            key={item.key}\n            ref={(el) => {\n              refs.current[i] = el;\n            }}\n            item={item}\n            mac={mac}\n            pressed={Boolean(pressed[item.key])}\n            tabIndex={i === active ? 0 : -1}\n            onFocus={() => setActive(i)}\n            onToggle={() => onToggle(item.key)}\n          />\n        ))}\n      </div>\n    </TooltipGroup>\n  );\n}\n\nfunction FormatButton({\n  item,\n  mac,\n  pressed,\n  tabIndex,\n  onFocus,\n  onToggle,\n  ref,\n}: {\n  item: FormatItem;\n  mac: boolean;\n  pressed: boolean;\n  tabIndex: number;\n  onFocus: () => void;\n  onToggle: () => void;\n  ref: (el: HTMLButtonElement | null) => void;\n}) {\n  const key = keyName(item.code);\n  const glyphs = mac\n    ? `⌘${item.shift ? \"⇧\" : \"\"}${key}`\n    : `Ctrl+${item.shift ? \"Shift+\" : \"\"}${key}`;\n  const shortcut = `${mac ? \"Meta\" : \"Control\"}+${item.shift ? \"Shift+\" : \"\"}${key}`;\n  const { anchorRef, triggerProps, tooltipProps } = useTooltip(\n    <>\n      {item.label}\n      <kbd className=\"font-sans text-background/55\">{glyphs}</kbd>\n    </>,\n  );\n\n  return (\n    <>\n      <button\n        ref={(el) => {\n          anchorRef(el);\n          ref(el);\n        }}\n        type=\"button\"\n        aria-label={item.label}\n        aria-pressed={pressed}\n        aria-keyshortcuts={shortcut}\n        tabIndex={tabIndex}\n        onClick={onToggle}\n        {...triggerProps}\n        onFocus={(e) => {\n          onFocus();\n          triggerProps.onFocus(e);\n        }}\n        className={cn(\n          \"flex size-10 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden select-none hover:text-foreground\",\n          \"transition-[scale,color,background-color,box-shadow] duration-150 ease-out motion-reduce:transition-[color,background-color,box-shadow]\",\n          \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96]\",\n          pressed && \"bg-background text-foreground shadow-raised\",\n        )}\n      >\n        <svg\n          viewBox=\"0 0 16 16\"\n          className=\"size-5\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.5}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          aria-hidden\n        >\n          {item.icon}\n        </svg>\n      </button>\n      <span {...tooltipProps}>\n        {item.label}, {glyphs}\n      </span>\n    </>\n  );\n}\n\nconst ITEMS: FormatItem[] = [\n  {\n    key: \"bold\",\n    label: \"Bold\",\n    code: \"KeyB\",\n    icon: (\n      <path d=\"M4.75 3.25h4a2.5 2.5 0 0 1 0 5h-4zM4.75 8.25h4.75a2.25 2.25 0 0 1 0 4.5H4.75z\" />\n    ),\n  },\n  {\n    key: \"italic\",\n    label: \"Italic\",\n    code: \"KeyI\",\n    icon: <path d=\"M6.75 3.25h5M4.25 12.75h5M9.75 3.25l-3.5 9.5\" />,\n  },\n  {\n    key: \"underline\",\n    label: \"Underline\",\n    code: \"KeyU\",\n    icon: <path d=\"M4.5 2.75v4.5a3.5 3.5 0 0 0 7 0v-4.5M3.5 13.25h9\" />,\n  },\n  {\n    key: \"strike\",\n    label: \"Strikethrough\",\n    code: \"KeyX\",\n    shift: true,\n    icon: (\n      <path d=\"M2.75 8h10.5M11 4.5c-.4-1.1-1.5-1.75-3-1.75-1.8 0-3 .9-3 2.25 0 .8.4 1.4 1.2 1.8M5 11.25c.4 1.2 1.6 2 3.1 2 1.9 0 3.15-.95 3.15-2.4 0-.5-.15-.95-.45-1.35\" />\n    ),\n  },\n  {\n    key: \"code\",\n    label: \"Code\",\n    code: \"KeyE\",\n    icon: <path d=\"M5.5 4.5 2 8l3.5 3.5M10.5 4.5 14 8l-3.5 3.5\" />,\n  },\n  {\n    key: \"quote\",\n    label: \"Quote\",\n    code: \"Digit9\",\n    shift: true,\n    icon: <path d=\"M3.25 3.75v8.5M6.5 5.25h6.25M6.5 8h6.25M6.5 10.75h4\" />,\n  },\n];\n\nexport default function TooltipGroupDemo() {\n  const [pressed, setPressed] = useState<Record<string, boolean>>({\n    bold: true,\n  });\n  const toggle = (key: string) =>\n    setPressed((p) => ({ ...p, [key]: !p[key] }));\n\n  // Two separate utilities would both set text-decoration-line and clash.\n  const decoration =\n    [pressed.underline && \"underline\", pressed.strike && \"line-through\"]\n      .filter(Boolean)\n      .join(\" \") || \"none\";\n\n  return (\n    <div className=\"flex flex-col items-center gap-6\">\n      <FormatToolbar items={ITEMS} pressed={pressed} onToggle={toggle} />\n      {/* Fixed height and an always present border, so toggling a style\n          never nudges the toolbar above it. */}\n      <p\n        className={cn(\n          \"h-7 border-l-2 border-transparent pl-3.5 text-[15px]/7 whitespace-nowrap text-foreground transition-[color,border-color] duration-150 ease-out\",\n          pressed.bold && \"font-semibold\",\n          pressed.italic && \"italic\",\n          pressed.code && \"font-mono\",\n          pressed.quote && \"border-foreground/20 text-muted-foreground\",\n        )}\n        style={{ textDecorationLine: decoration }}\n      >\n        Scan the toolbar, not the docs.\n      </p>\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/tooltip-group"}