{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"cursor-label-follower","type":"registry:component","title":"Cursor Label Follower","description":"A pill that springs after the pointer and morphs its text, glyph and width per target (View, Drag, Play), with press-to-reveal on touch and focus labels for keyboards.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/cursor-label-follower.tsx","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\nimport type { ReactNode } from \"react\";\n\n/**\n * CursorLabelFollower: a pill that springs after the pointer and names whatever\n * it is over. Any descendant with data-cursor-label=\"View\" sets the text; an\n * optional data-cursor-icon=\"view | drag | play | pause | arrow\" sets the glyph.\n * Text, glyph and width morph between targets. Touch: the label appears on\n * press, lifted above the finger. Keyboard: it appears on focus-visible.\n * The chip is decorative (aria-hidden): repeat the label in the target's name.\n */\n\nconst HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst ICONS = [\"view\", \"drag\", \"play\", \"pause\", \"arrow\"];\nconst TOUCH_LIFT = 54;\nconst TBOX_T = \"width 0.34s cubic-bezier(0.16, 1, 0.3, 1)\";\nconst SLOT_T = \"width 0.3s cubic-bezier(0.16, 1, 0.3, 1)\";\nconst MONO = 'ui-monospace, SFMono-Regular, \"SF Mono\", Menlo, Consolas, monospace';\n\nconst ICON_RULES = ICONS.concat(\"dot\")\n  .map((n) => '.clf-slot[data-icon=\"' + n + '\"] .clf-i[data-i=\"' + n + '\"]')\n  .join(\",\");\n\nconst CSS = [\n  \".clf-hide [data-cursor-label]{cursor:none}\",\n  \".clf-i{position:absolute;left:0;top:0;opacity:0;transform:scale(0.3) rotate(-70deg);filter:blur(2px);transition:opacity .2s ease,transform .42s cubic-bezier(.34,1.56,.64,1),filter .2s ease}\",\n  ICON_RULES + \"{opacity:1;transform:none;filter:none}\",\n  \"@media (prefers-reduced-motion:reduce){.clf-i,.clf-chip,.clf-slot,.clf-tbox{transition-duration:.01ms!important}}\",\n].join(\"\\n\");\n\nfunction inkFor(hex: string): string {\n  let h = hex.slice(1);\n  if (h.length === 3) h = h.split(\"\").map((c) => c + c).join(\"\");\n  const n = parseInt(h, 16);\n  const lum = (0.2126 * ((n >> 16) & 255) + 0.7152 * ((n >> 8) & 255) + 0.0722 * (n & 255)) / 255;\n  return lum > 0.62 ? \"#0a0a0a\" : \"#ffffff\";\n}\n\nfunction Glyphs() {\n  const p = {\n    className: \"clf-i\",\n    viewBox: \"0 0 16 16\",\n    width: 14,\n    height: 14,\n    fill: \"none\",\n    stroke: \"currentColor\",\n    strokeWidth: 1.7,\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\",\n    focusable: \"false\",\n  } as const;\n  return (\n    <>\n      <svg {...p} data-i=\"view\">\n        <path d=\"M1.5 8s2.3-4.5 6.5-4.5S14.5 8 14.5 8s-2.3 4.5-6.5 4.5S1.5 8 1.5 8Z\" />\n        <circle cx=\"8\" cy=\"8\" r=\"2.1\" />\n      </svg>\n      <svg {...p} data-i=\"drag\">\n        <path d=\"M5 4.5 1.8 8 5 11.5M11 4.5 14.2 8 11 11.5M2.5 8h11\" />\n      </svg>\n      <svg {...p} data-i=\"play\">\n        <path d=\"M5.6 3.8v8.4L12.2 8 5.6 3.8Z\" fill=\"currentColor\" strokeWidth=\"1.2\" />\n      </svg>\n      <svg {...p} data-i=\"pause\" strokeWidth={2.3}>\n        <path d=\"M5.3 3.8v8.4M10.7 3.8v8.4\" />\n      </svg>\n      <svg {...p} data-i=\"arrow\">\n        <path d=\"M4.5 11.5 11.5 4.5M5.5 4.5h6v6\" />\n      </svg>\n      <svg {...p} data-i=\"dot\" stroke=\"none\">\n        <circle cx=\"4\" cy=\"8\" r=\"2.4\" fill=\"currentColor\" opacity=\"0.75\" />\n      </svg>\n    </>\n  );\n}\n\nexport function CursorLabelFollower({\n  children,\n  stiffness = 420,\n  showDot = true,\n  color = \"#2563eb\",\n  hideCursor = false,\n  restTarget,\n  className,\n}: {\n  children: ReactNode;\n  /** Spring stiffness of the chip trailing the pointer (damping 30, mass 0.35). */\n  stiffness?: number;\n  /** The small leading dot inside the chip when the target has no icon. */\n  showDot?: boolean;\n  /** Chip colour as #rgb or #rrggbb. Text colour is picked for contrast. */\n  color?: string;\n  /** Hide the native cursor over labelled targets (the chip becomes the cursor). */\n  hideCursor?: boolean;\n  /** Opt-in: park the chip over the first target with this label when the pointer is away (e.g. \"View\"). */\n  restTarget?: string;\n  className?: string;\n}) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const posRef = useRef<HTMLDivElement>(null);\n  const rotRef = useRef<HTMLDivElement>(null);\n  const chipRef = useRef<HTMLDivElement>(null);\n  const slotRef = useRef<HTMLSpanElement>(null);\n  const tboxRef = useRef<HTMLSpanElement>(null);\n  const aRef = useRef<HTMLSpanElement>(null);\n  const bRef = useRef<HTMLSpanElement>(null);\n  const measRef = useRef<HTMLSpanElement>(null);\n  const stiffRef = useRef(stiffness);\n  const dotRef = useRef(showDot);\n  const restRef = useRef(restTarget);\n  const parkRef = useRef<() => void>(() => {});\n\n  useEffect(() => {\n    stiffRef.current = stiffness;\n    dotRef.current = showDot;\n  }, [stiffness, showDot]);\n\n  useEffect(() => {\n    restRef.current = restTarget;\n    parkRef.current();\n  }, [restTarget]);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    const pos = posRef.current;\n    const rot = rotRef.current;\n    const chip = chipRef.current;\n    const slot = slotRef.current;\n    const tbox = tboxRef.current;\n    const la = aRef.current;\n    const lb = bRef.current;\n    const meas = measRef.current;\n    if (!root || !pos || !rot || !chip || !slot || !tbox || !la || !lb || !meas) return;\n    const layers = [la, lb];\n    const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n\n    let active = 0;\n    let shown = \"\";\n    let curIcon = \"\";\n    let slotW = 0;\n    let textW = 0;\n    let visible = false;\n    let pressed = false;\n    let hover = false;\n    let x = 0, y = 0, tx = 0, ty = 0, vx = 0, vy = 0;\n    let raf = 0;\n    let last = 0;\n    let hideT = 0;\n\n    const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));\n    const place = () => {\n      pos.style.transform = \"translate3d(\" + x.toFixed(1) + \"px,\" + y.toFixed(1) + \"px,0)\";\n    };\n    const tilt = (deg: number) => {\n      rot.style.transform = \"translate(-50%,-50%) rotate(\" + deg.toFixed(2) + \"deg)\";\n    };\n    const paintChip = () => {\n      chip.style.opacity = visible ? \"1\" : \"0\";\n      chip.style.transform = visible ? (pressed ? \"scale(0.9)\" : \"scale(1)\") : \"scale(0.6)\";\n    };\n    const setW = (el: HTMLElement, px: number, t: string, instant: boolean) => {\n      if (instant) {\n        el.style.transition = \"none\";\n        el.style.width = px + \"px\";\n        void el.offsetWidth;\n        el.style.transition = t;\n      } else {\n        el.style.width = px + \"px\";\n      }\n    };\n\n    const frame = (t: number) => {\n      const dt = Math.min(0.05, last ? (t - last) / 1000 : 1 / 60);\n      last = t;\n      const k = stiffRef.current;\n      const h = 1 / 240;\n      const n = Math.max(1, Math.round(dt / h));\n      for (let i = 0; i < n; i++) {\n        vx += ((-k * (x - tx) - 30 * vx) / 0.35) * h;\n        vy += ((-k * (y - ty) - 30 * vy) / 0.35) * h;\n        x += vx * h;\n        y += vy * h;\n      }\n      const rest = Math.abs(x - tx) < 0.05 && Math.abs(y - ty) < 0.05 && Math.abs(vx) < 0.5 && Math.abs(vy) < 0.5;\n      if (rest) {\n        x = tx;\n        y = ty;\n        vx = 0;\n        vy = 0;\n      }\n      place();\n      tilt(rest ? 0 : clamp(vx / 260, -6, 6));\n      if (rest) {\n        raf = 0;\n        last = 0;\n        return;\n      }\n      raf = requestAnimationFrame(frame);\n    };\n    const kick = () => {\n      if (mq.matches) {\n        x = tx;\n        y = ty;\n        vx = 0;\n        vy = 0;\n        place();\n        return;\n      }\n      if (!raf) {\n        last = 0;\n        raf = requestAnimationFrame(frame);\n      }\n    };\n\n    const setTarget = (lx: number, ly: number) => {\n      const half = (24 + slotW + textW) / 2 + 2;\n      const w = root.offsetWidth;\n      tx = w > half * 2 ? clamp(lx, half, w - half) : lx;\n      ty = Math.max(16, ly);\n    };\n\n    const applyIcon = (name: string, instant: boolean) => {\n      const nm = ICONS.includes(name) ? name : dotRef.current ? \"dot\" : \"none\";\n      if (nm === curIcon) return;\n      curIcon = nm;\n      slot.dataset.icon = nm;\n      slotW = nm === \"none\" ? 0 : nm === \"dot\" ? 13 : 21;\n      setW(slot, slotW, SLOT_T, instant);\n    };\n\n    const setText = (next: string, instant: boolean) => {\n      if (next === shown) return;\n      const inc = layers[1 - active];\n      const out = layers[active];\n      if (!inc || !out) return;\n      meas.textContent = next;\n      textW = meas.offsetWidth + 1;\n      setW(tbox, textW, TBOX_T, instant);\n      inc.getAnimations().forEach((a) => a.cancel());\n      out.getAnimations().forEach((a) => a.cancel());\n      inc.textContent = next;\n      inc.style.opacity = \"1\";\n      out.style.opacity = \"0\";\n      if (!instant && !mq.matches && inc.animate) {\n        inc.animate(\n          [\n            { opacity: 0, transform: \"translateY(8px)\", filter: \"blur(3px)\" },\n            { opacity: 1, transform: \"translateY(0)\", filter: \"blur(0)\" },\n          ],\n          { duration: 320, easing: \"cubic-bezier(0.16, 1, 0.3, 1)\" },\n        );\n        out.animate(\n          [\n            { opacity: 1, transform: \"translateY(0)\", filter: \"blur(0)\" },\n            { opacity: 0, transform: \"translateY(-8px)\", filter: \"blur(3px)\" },\n          ],\n          { duration: 170, easing: \"ease-out\" },\n        );\n      }\n      active = 1 - active;\n      shown = next;\n    };\n\n    const hide = () => {\n      if (!visible) return;\n      visible = false;\n      pressed = false;\n      paintChip();\n    };\n\n    const read = (el: EventTarget | null) => {\n      const t = el instanceof Element ? el.closest(\"[data-cursor-label]\") : null;\n      if (!t || !root.contains(t)) return null;\n      const label = t.getAttribute(\"data-cursor-label\");\n      if (!label) return null;\n      return { label, icon: t.getAttribute(\"data-cursor-icon\") ?? \"\", el: t };\n    };\n\n    let lastEl: Element | null = null;\n    let lastX = 0;\n    let lastY = 0;\n    let release: () => void = hide;\n    const update = (info: { label: string; icon: string } | null, lx: number, ly: number) => {\n      lastX = lx;\n      lastY = ly;\n      if (!info) {\n        release();\n        return;\n      }\n      const was = visible;\n      applyIcon(info.icon, !was);\n      setText(info.label, !was);\n      setTarget(lx, ly);\n      if (!was) {\n        visible = true;\n        x = tx;\n        y = ty;\n        vx = 0;\n        vy = 0;\n        place();\n        tilt(0);\n      }\n      paintChip();\n      kick();\n    };\n\n    const toLocal = (cx: number, cy: number): [number, number] => {\n      const r = root.getBoundingClientRect();\n      const sx = r.width ? root.offsetWidth / r.width : 1;\n      const sy = r.height ? root.offsetHeight / r.height : 1;\n      return [(cx - r.left) * sx, (cy - r.top) * sy];\n    };\n\n    const onMove = (e: PointerEvent) => {\n      window.clearTimeout(hideT);\n      lastEl = e.target instanceof Element ? e.target : null;\n      const info = read(e.target);\n      hover = !!info;\n      const [lx, ly] = toLocal(e.clientX, e.clientY);\n      update(info, lx, ly - (e.pointerType === \"touch\" ? TOUCH_LIFT : 0));\n    };\n    const onDown = (e: PointerEvent) => {\n      onMove(e);\n      pressed = true;\n      if (visible) paintChip();\n    };\n    const onUp = (e: PointerEvent) => {\n      pressed = false;\n      if (visible) paintChip();\n      if (e.pointerType === \"touch\") {\n        hideT = window.setTimeout(() => {\n          hover = false;\n          release();\n        }, 480);\n      }\n    };\n    const onCancel = () => {\n      pressed = false;\n      hideT = window.setTimeout(() => {\n        hover = false;\n        release();\n      }, 80);\n    };\n    const onLeave = (e: PointerEvent) => {\n      if (e.pointerType === \"touch\") return;\n      hover = false;\n      release();\n    };\n    const onFocusIn = (e: FocusEvent) => {\n      const info = read(e.target);\n      if (!info) return;\n      let fv = true;\n      try {\n        fv = (e.target as Element).matches(\":focus-visible\");\n      } catch {\n        fv = true;\n      }\n      if (!fv) return;\n      lastEl = info.el;\n      const r = info.el.getBoundingClientRect();\n      const [lx, ly] = toLocal(r.left + r.width / 2, r.top + r.height / 2);\n      update(info, lx, ly);\n    };\n    const onFocusOut = () => {\n      if (!hover) release();\n    };\n\n    // Opt-in rest state: park over the first target carrying the restTarget label.\n    release = () => {\n      const want = restRef.current;\n      let el: Element | null = null;\n      if (want) {\n        el = Array.from(root.querySelectorAll(\"[data-cursor-label]\")).find((n) => n.getAttribute(\"data-cursor-label\") === want) ?? null;\n      }\n      const info = el ? read(el) : null;\n      if (!el || !info) {\n        hide();\n        return;\n      }\n      lastEl = el;\n      const r = el.getBoundingClientRect();\n      const [lx, ly] = toLocal(r.left + r.width * 0.5, r.top + r.height * 0.42);\n      update(info, lx, ly);\n    };\n    parkRef.current = () => {\n      if (!hover) release();\n    };\n    parkRef.current();\n    // A target may relabel itself (Drag to Dragging, Play to Pause) without the pointer moving.\n    const mo = new MutationObserver(() => {\n      if (!visible || !lastEl) return;\n      const info = read(lastEl);\n      if (info) update(info, lastX, lastY);\n    });\n    mo.observe(root, { subtree: true, attributes: true, attributeFilter: [\"data-cursor-label\", \"data-cursor-icon\"] });\n    root.addEventListener(\"pointermove\", onMove);\n    root.addEventListener(\"pointerdown\", onDown);\n    root.addEventListener(\"pointerup\", onUp);\n    root.addEventListener(\"pointercancel\", onCancel);\n    root.addEventListener(\"pointerleave\", onLeave);\n    root.addEventListener(\"focusin\", onFocusIn);\n    root.addEventListener(\"focusout\", onFocusOut);\n    return () => {\n      root.removeEventListener(\"pointermove\", onMove);\n      root.removeEventListener(\"pointerdown\", onDown);\n      root.removeEventListener(\"pointerup\", onUp);\n      root.removeEventListener(\"pointercancel\", onCancel);\n      root.removeEventListener(\"pointerleave\", onLeave);\n      root.removeEventListener(\"focusin\", onFocusIn);\n      root.removeEventListener(\"focusout\", onFocusOut);\n      parkRef.current = () => {};\n      mo.disconnect();\n      window.clearTimeout(hideT);\n      if (raf) cancelAnimationFrame(raf);\n    };\n  }, []);\n\n  const bg = HEX.test(color) ? color : \"#2563eb\";\n  const ink = inkFor(bg);\n  const layer = {\n    position: \"absolute\",\n    left: 0,\n    top: 0,\n    opacity: 0,\n    whiteSpace: \"nowrap\",\n  } as const;\n\n  return (\n    <div\n      ref={rootRef}\n      className={\"clf-root relative\" + (hideCursor ? \" clf-hide\" : \"\") + (className ? \" \" + className : \"\")}\n    >\n      {children}\n      <div\n        aria-hidden\n        ref={posRef}\n        className=\"pointer-events-none absolute left-0 top-0 z-50\"\n        style={{ transform: \"translate3d(0,0,0)\", willChange: \"transform\" }}\n      >\n        <style>{CSS}</style>\n        <div ref={rotRef} style={{ transform: \"translate(-50%,-50%)\" }}>\n          <div\n            ref={chipRef}\n            className=\"clf-chip\"\n            style={{\n              display: \"flex\",\n              alignItems: \"center\",\n              height: 30,\n              padding: \"0 11px 0 12px\",\n              borderRadius: 999,\n              background: bg,\n              color: ink,\n              border: \"1px solid \" + (ink === \"#ffffff\" ? \"rgba(255,255,255,0.2)\" : \"rgba(0,0,0,0.14)\"),\n              boxShadow: \"0 10px 24px -8px rgba(0,0,0,0.5), 0 1px 0 rgba(255,255,255,0.22) inset\",\n              overflow: \"hidden\",\n              whiteSpace: \"nowrap\",\n              fontFamily: MONO,\n              fontSize: 11,\n              fontWeight: 500,\n              letterSpacing: \"0.12em\",\n              textTransform: \"uppercase\",\n              lineHeight: \"14px\",\n              opacity: 0,\n              transform: \"scale(0.6)\",\n              transition: \"transform 0.34s cubic-bezier(0.34, 1.45, 0.5, 1), opacity 0.16s ease\",\n            }}\n          >\n            <span\n              ref={slotRef}\n              className=\"clf-slot\"\n              style={{ position: \"relative\", display: \"block\", flex: \"none\", width: 0, height: 14, transition: SLOT_T }}\n            >\n              <Glyphs />\n            </span>\n            <span\n              ref={tboxRef}\n              className=\"clf-tbox\"\n              style={{ position: \"relative\", display: \"block\", flex: \"none\", width: 0, height: 14, transition: TBOX_T }}\n            >\n              <span ref={aRef} style={layer} />\n              <span ref={bRef} style={layer} />\n              <span ref={measRef} style={{ ...layer, visibility: \"hidden\" }} />\n            </span>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n","type":"registry:component","target":"components/viberdy/cursor-label-follower.tsx"}],"meta":{"tier":"free","tags":["cursor","label","spring","affordance","morph","touch"],"href":"https://viberdy.dev/library/cursor-label-follower","aiPrompt":"Create a dependency-free React + Tailwind component named CursorLabelFollower (one \"use client\" file, React 18 and 19 compatible, no animation library).\n\nProps: children (ReactNode), stiffness (number, default 420), showDot (boolean, default true), color (hex #rgb or #rrggbb, default #2563eb, validated with a regex, text colour chosen by luminance: dark ink above 0.62, otherwise white), hideCursor (boolean, default false), className (string).\n\nBehaviour:\n- Root is a div with \"relative\" wrapping children. Inside it, an aria-hidden, pointer-events-none absolute left-0 top-0 z-50 layer holds the chip. Native listeners are attached once in a mount effect: pointermove, pointerdown, pointerup, pointercancel, pointerleave, focusin, focusout.\n- Any descendant with data-cursor-label=\"Text\" names the chip, found by event.target.closest(\"[data-cursor-label]\") (an empty label means no chip). Optional data-cursor-icon: view (eye), drag (left/right chevrons), play, pause, arrow (up-right). With no icon, show a small dot if showDot, otherwise nothing. The label is re-read on every pointermove, so changing the attribute (Drag to Dragging) updates the chip live.\n- Position: a damped spring per axis, k = stiffness, damping 30, mass 0.35, integrated semi-implicitly in 1/240 s steps from requestAnimationFrame (dt capped at 50 ms). Write a single translate3d to the position layer. Stop the loop when |error| < 0.05 px and |velocity| < 0.5; restart on movement. When the chip first appears it snaps to the pointer (no flight). Clamp the target so the chip stays inside the root horizontally. Tilt the chip rotate(clamp(vx / 260, -6, 6) deg) while moving.\n- Chip: 30 px tall pill, padding 0 11px 0 12px, background = color, 1px translucent border, shadow 0 10px 24px -8px rgba(0,0,0,.5) plus a 1px inset top highlight, monospace 11px 500 uppercase, letter-spacing 0.12em, line-height 14px. Hidden: opacity 0, scale 0.6. Visible: opacity 1, scale 1 via transition transform 340ms cubic-bezier(.34,1.45,.5,1), opacity 160ms. Pressed: scale 0.9.\n- Inside the chip: a glyph slot (width 0 / 13 for dot / 21 for an icon, transitioning 300ms cubic-bezier(.16,1,.3,1)) holding all six SVGs stacked; the active one is opacity 1, others opacity 0 scale .3 rotate -70deg blur 2px (opacity .2s, transform 420ms cubic-bezier(.34,1.56,.64,1)). Then a text box whose width is measured from a hidden duplicate span and transitions 340ms cubic-bezier(.16,1,.3,1). Text changes crossfade between two stacked layers with the Web Animations API: incoming translateY(8px) blur(3px) to rest over 320ms cubic-bezier(.16,1,.3,1), outgoing to translateY(-8px) blur(3px) over 170ms. When the chip is hidden, set text and widths without animation.\n- Touch: labels appear on pointerdown/pointermove while the finger is down, positioned 54 px above the touch point; hide 480 ms after pointerup and 80 ms after pointercancel. Mouse/pen: hide on pointerleave and when the pointer is over no labelled element.\n- Keyboard: on focusin of a labelled target matching :focus-visible, show the chip centred on that element; hide on focusout unless the mouse is hovering a labelled target.\n- hideCursor adds a class that sets cursor:none on [data-cursor-label] elements via a small static <style> element rendered beside (never inside) the chip.\n- Coordinates are measured in layout pixels: (client - rect.left) * (offsetWidth / rect.width), so it works inside transform-scaled previews.\n- prefers-reduced-motion (matchMedia, plus a CSS media rule that zeroes transitions): no spring (chip tracks the pointer directly), no tilt, no blur/slide (instant text swap), transitions near-instant.\n- The chip is decorative (aria-hidden); document that the label must also exist in the target's accessible name.\n\nDemo: three media cards (a landscape cover labelled View, a draggable moodboard strip labelled Drag then Dragging with pointer capture, rubber-banding and arrow-key support, a looping reel thumbnail labelled Play then Pause), each built from pure CSS art.","license":"https://viberdy.dev/license"}}