{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"arrow-callout","type":"registry:component","title":"Arrow callout","description":"A handwritten note whose arrow draws itself to whatever it points at.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/arrow-callout.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState, type ReactNode, type RefObject } from \"react\";\nimport { animate, motion, useMotionValue } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { Caveat } from \"next/font/google\";\nimport { cn } from \"@/lib/utils\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\n\n// A marker hand for the note. Not preloaded: the index bundles every preview,\n// and pages that never draw it shouldn't fetch it.\nconst hand = Caveat({ subsets: [\"latin\"], weight: [\"500\"], preload: false });\n\ntype Pt = { x: number; y: number };\ntype Box = { left: number; top: number; width: number; height: number };\n\nconst round = (n: number) => Math.round(n * 10) / 10;\n// Room between the arrow tip and the target, so it points rather than stabs.\nconst TIP_GAP = 8;\n// Padding around the path's box so round caps and the head never clip.\nconst PAD = 6;\n\n// The curve lives in the note's own coordinates: (0,0) is the note's top left.\nfunction geometry(note: Box, target: Box) {\n  const tc = {\n    x: target.left + target.width / 2 - note.left,\n    y: target.top + target.height / 2 - note.top,\n  };\n  const dx = tc.x - note.width / 2;\n  const dy = tc.y - note.height / 2;\n\n  // Leaves from the side of the note that faces the target, a little below\n  // the middle, the way a note-taker starts an arrow near the last word.\n  let s: Pt;\n  if (Math.abs(dx) > Math.abs(dy)) s = { x: dx < 0 ? -6 : note.width + 6, y: note.height * 0.6 };\n  else s = { x: note.width * 0.35, y: dy < 0 ? -4 : note.height + 4 };\n\n  // Aims at the target's centre and stops where that line meets its edge.\n  const hw = target.width / 2 + TIP_GAP;\n  const hh = target.height / 2 + TIP_GAP;\n  const ax = s.x - tc.x;\n  const ay = s.y - tc.y;\n  const k = Math.min(ax ? hw / Math.abs(ax) : Infinity, ay ? hh / Math.abs(ay) : Infinity);\n  const e = k < 1 ? { x: tc.x + ax * k, y: tc.y + ay * k } : tc;\n\n  // A pen arc: bulges to one side (always upward, like a flick of the\n  // wrist) by about a third of its length, capped so long arrows stay calm.\n  const vx = e.x - s.x;\n  const vy = e.y - s.y;\n  const len = Math.hypot(vx, vy) || 1;\n  let nx = -vy / len;\n  let ny = vx / len;\n  if (ny > 0) {\n    nx = -nx;\n    ny = -ny;\n  }\n  const bulge = Math.min(len * 0.32, 56);\n  // Asymmetric handles: a quick start, a longer approach into the tip.\n  const c1 = { x: s.x + vx * 0.15 + nx * bulge, y: s.y + vy * 0.15 + ny * bulge };\n  const c2 = { x: s.x + vx * 0.7 + nx * bulge * 0.75, y: s.y + vy * 0.7 + ny * bulge * 0.75 };\n\n  // The head follows the curve's last tangent, two unequal barbs like a\n  // quick hand would draw them.\n  const angle = Math.atan2(e.y - c2.y, e.x - c2.x);\n  const barb = (spread: number, length: number) => ({\n    x: e.x - Math.cos(angle + spread) * length,\n    y: e.y - Math.sin(angle + spread) * length,\n  });\n  const b1 = barb(0.5, 9);\n  const b2 = barb(-0.45, 7.5);\n\n  const xs = [s.x, c1.x, c2.x, e.x, b1.x, b2.x];\n  const ys = [s.y, c1.y, c2.y, e.y, b1.y, b2.y];\n  const box = {\n    x: Math.min(...xs) - PAD,\n    y: Math.min(...ys) - PAD,\n    w: Math.max(...xs) - Math.min(...xs) + PAD * 2,\n    h: Math.max(...ys) - Math.min(...ys) + PAD * 2,\n  };\n  const p = (pt: Pt) => `${round(pt.x)} ${round(pt.y)}`;\n  return {\n    box,\n    body: `M${p(s)}C${p(c1)} ${p(c2)} ${p(e)}`,\n    head: `M${p(b1)}L${p(e)}L${p(b2)}`,\n  };\n}\n\nexport function ArrowCallout({\n  target,\n  follow = false,\n  children,\n  className,\n}: {\n  /** The element the arrow points at. It can live anywhere on the page. */\n  target: RefObject<HTMLElement | null>;\n  /** Track the target every frame, for when a script (not a pointer) moves it. */\n  follow?: boolean;\n  children: ReactNode;\n  className?: string;\n}) {\n  const note = useRef<HTMLSpanElement>(null);\n  const svg = useRef<SVGSVGElement>(null);\n  const body = useRef<SVGPathElement>(null);\n  const head = useRef<SVGPathElement>(null);\n\n  useEffect(() => {\n    const el = note.current;\n    const to = target.current;\n    const art = svg.current;\n    if (!el || !to || !art) return;\n\n    // Straight DOM writes: this runs every frame while the target moves, and\n    // a React render per frame would be wasted work.\n    const layout = () => {\n      const n = el.getBoundingClientRect();\n      const t = to.getBoundingClientRect();\n      // Rects are post-transform, but the svg is drawn in the note's own\n      // pixels: inside a scaled container, divide the scale back out.\n      const k = el.offsetWidth ? n.width / el.offsetWidth : 1;\n      const g = geometry(\n        { left: 0, top: 0, width: n.width / k, height: n.height / k },\n        {\n          left: (t.left - n.left) / k,\n          top: (t.top - n.top) / k,\n          width: t.width / k,\n          height: t.height / k,\n        },\n      );\n      art.style.left = `${round(g.box.x)}px`;\n      art.style.top = `${round(g.box.y)}px`;\n      art.setAttribute(\"width\", String(round(g.box.w)));\n      art.setAttribute(\"height\", String(round(g.box.h)));\n      art.setAttribute(\"viewBox\", `${round(g.box.x)} ${round(g.box.y)} ${round(g.box.w)} ${round(g.box.h)}`);\n      body.current?.setAttribute(\"d\", g.body);\n      head.current?.setAttribute(\"d\", g.head);\n    };\n    layout();\n\n    // Any layout change around either end reshapes the arrow.\n    const ro = new ResizeObserver(layout);\n    ro.observe(el);\n    ro.observe(to);\n    ro.observe(document.documentElement);\n\n    // Transforms don't trigger ResizeObserver, so while the target is being\n    // handled (dragged, springing back) follow it frame by frame, and sleep\n    // once it has held still for a few frames.\n    let raf = 0;\n    let still = 0;\n    let last = \"\";\n    let held = follow;\n    const track = () => {\n      const r = to.getBoundingClientRect();\n      const now = `${r.left},${r.top},${r.width},${r.height}`;\n      if (now !== last) {\n        last = now;\n        still = 0;\n        layout();\n      } else still++;\n      if (held || still < 12) raf = requestAnimationFrame(track);\n    };\n    const wake = () => {\n      cancelAnimationFrame(raf);\n      still = 0;\n      raf = requestAnimationFrame(track);\n    };\n    const down = () => {\n      held = true;\n      wake();\n    };\n    const up = () => {\n      held = false;\n    };\n    to.addEventListener(\"pointerdown\", down);\n    window.addEventListener(\"pointerup\", up);\n    window.addEventListener(\"pointercancel\", up);\n    to.addEventListener(\"transitionrun\", wake);\n    if (follow) wake();\n\n    // Draws once, when the note is properly on screen.\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        art.dataset.drawn = \"true\";\n        io.disconnect();\n      },\n      { rootMargin: \"0px 0px -15% 0px\" },\n    );\n    io.observe(el);\n\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n      io.disconnect();\n      to.removeEventListener(\"pointerdown\", down);\n      window.removeEventListener(\"pointerup\", up);\n      window.removeEventListener(\"pointercancel\", up);\n      to.removeEventListener(\"transitionrun\", wake);\n    };\n  }, [target, follow]);\n\n  const ink = {\n    fill: \"none\",\n    stroke: \"currentColor\",\n    strokeWidth: 1.6,\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    pathLength: 1,\n  } as const;\n\n  return (\n    <span ref={note} className={cn(\"relative inline-block text-marker\", className)}>\n      <span className={cn(hand.className, \"inline-block -rotate-3 text-[22px] leading-none whitespace-nowrap\")}>\n        {children}\n      </span>\n      <svg\n        ref={svg}\n        aria-hidden\n        data-drawn=\"false\"\n        className=\"group/arrow pointer-events-none absolute overflow-visible\"\n      >\n        {/* A pen stroke: eases into the line and off it, 650ms because the\n            drawing is the point and it plays once. The head lands after. */}\n        <path\n          ref={body}\n          {...ink}\n          className=\"[stroke-dasharray:1] [stroke-dashoffset:1] transition-[stroke-dashoffset] delay-200 duration-[650ms] ease-[cubic-bezier(0.65,0,0.35,1)] group-data-[drawn=true]/arrow:[stroke-dashoffset:0] motion-reduce:[stroke-dashoffset:0] motion-reduce:transition-none\"\n        />\n        <path\n          ref={head}\n          {...ink}\n          className=\"[stroke-dasharray:1] [stroke-dashoffset:1] transition-[stroke-dashoffset] delay-[830ms] duration-[160ms] ease-out group-data-[drawn=true]/arrow:[stroke-dashoffset:0] motion-reduce:[stroke-dashoffset:0] motion-reduce:transition-none\"\n        />\n      </svg>\n    </span>\n  );\n}\n\n// The same spring the sticker uses to snap home after a real drag.\nconst HOME = { type: \"spring\", stiffness: 400, damping: 30 } as const;\n\nexport default function ArrowCalloutDemo() {\n  const chip = useRef<HTMLButtonElement>(null);\n  const play = usePreviewPlay();\n  const reduceMotion = useReducedMotion();\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n  // True from the first scripted tug until the sticker is home again, so the\n  // arrow tracks it every frame only while it actually moves.\n  const [moving, setMoving] = useState(false);\n  const run = useRef(0);\n\n  // Index preview: someone picks the sticker up, tugs it up and to the\n  // right, lets go, and it springs home with the arrow chasing it.\n  useEffect(() => {\n    if (play !== true || reduceMotion) return;\n    const gen = run;\n    const id = ++gen.current;\n    const live = () => gen.current === id;\n    let timer: ReturnType<typeof setTimeout>;\n    const tug = async () => {\n      setMoving(true);\n      // A hand's drag: quick to start, easing out at the end of the pull.\n      const pull = { duration: 0.55, ease: [0.23, 1, 0.32, 1] } as const;\n      await Promise.all([animate(x, 26, pull), animate(y, -24, pull)]);\n      if (!live()) return;\n      await Promise.all([animate(x, 0, HOME), animate(y, 0, HOME)]);\n      if (live()) timer = setTimeout(tug, 1600);\n    };\n    timer = setTimeout(tug, 200);\n    return () => {\n      clearTimeout(timer);\n      const done = ++gen.current;\n      // Let go mid-tug: it springs home from wherever it is.\n      Promise.all([animate(x, 0, HOME), animate(y, 0, HOME)]).then(() => {\n        if (gen.current === done) setMoving(false);\n      });\n    };\n  }, [play, reduceMotion, x, y]);\n\n  return (\n    <div className=\"relative flex w-[min(360px,100%)] items-center gap-16 py-8 pl-2\">\n      <motion.button\n        ref={chip}\n        type=\"button\"\n        drag\n        // A short leash with rubber past it, so the sticker can't be laid\n        // over its own note and the arrow always has room to point.\n        dragConstraints={{ top: -28, bottom: 28, left: -8, right: 28 }}\n        dragElastic={0.25}\n        // Springs home on release, keeping the throw's velocity; the arrow\n        // follows it the whole way.\n        dragSnapToOrigin\n        dragTransition={{ bounceStiffness: 400, bounceDamping: 30 }}\n        whileTap={{ scale: 0.96 }}\n        style={{ x, y }}\n        className=\"relative z-10 inline-flex h-9 shrink-0 cursor-grab touch-none items-center gap-2 rounded-full bg-muted px-3.5 text-sm font-medium text-foreground shadow-raised outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:cursor-grabbing\"\n      >\n        {/* A six-dot grip, the usual \"this moves\" hint. */}\n        <svg viewBox=\"0 0 8 12\" className=\"size-3 text-muted-foreground\" fill=\"currentColor\" aria-hidden>\n          {[2, 6, 10].map((y) => (\n            <g key={y}>\n              <circle cx=\"2\" cy={y} r=\"1\" />\n              <circle cx=\"6\" cy={y} r=\"1\" />\n            </g>\n          ))}\n        </svg>\n        Sticker\n      </motion.button>\n      <ArrowCallout target={chip} follow={moving} className=\"mt-20\">\n        try dragging this!\n      </ArrowCallout>\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"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"cssVars":{"light":{"marker":"#d93d31","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":{"marker":"#ff6b5f","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":{"color-marker":"var(--marker)","shadow-raised":"var(--shadow-raised)"}},"categories":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/arrow-callout"}