{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"marquee","type":"registry:component","title":"Marquee","description":"Drifts endlessly past a reading lens, and brakes gently when you hover.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":[],"registryDependencies":["utils"],"files":[{"path":"components/marquee.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useSyncExternalStore } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nconst REDUCE = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduce = (onChange: () => void) => {\n  const query = window.matchMedia(REDUCE);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\n\n// The markup differs with reduced motion (one copy or two, dimmed or not),\n// so hydration renders the server's answer first and switches right after,\n// instead of mismatching.\nfunction useReducedMotion() {\n  return useSyncExternalStore(\n    subscribeReduce,\n    () => window.matchMedia(REDUCE).matches,\n    () => false,\n  );\n}\n\n// Braking is a response to the pointer, so it stays inside the 300ms budget.\nconst STOP_MS = 300;\n// Picking back up is ambient, not a response, so it eases in a little slower\n// and never feels like the row lurches away from the cursor.\nconst RESUME_MS = 450;\n\nexport function Marquee({\n  items,\n  // px per second, so a longer list scrolls at the same pace, not faster.\n  speed = 40,\n  direction = \"left\",\n  label,\n  // Dims the row except for a reading window in the middle.\n  lens = true,\n  className,\n}: {\n  items: string[];\n  speed?: number;\n  direction?: \"left\" | \"right\";\n  label?: string;\n  lens?: boolean;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const trackRef = useRef<HTMLDivElement>(null);\n  const lensRef = useRef<HTMLDivElement>(null);\n  const groupRef = useRef<HTMLUListElement>(null);\n  const anims = useRef<Animation[]>([]);\n  const raf = useRef(0);\n  // A still row has nothing crossing the window, and hand-scrolling it\n  // would slide the base copy out from under the lit one.\n  const showLens = lens && !reduceMotion;\n\n  useEffect(() => {\n    const track = trackRef.current;\n    const group = groupRef.current;\n    if (!track || !group || reduceMotion) return;\n\n    // Constant motion is the one place linear is right: any easing would make\n    // the loop visibly surge and settle at the seam. WAAPI keyframes run on\n    // the compositor like CSS ones, with no JS per frame, but also expose\n    // playbackRate for the hover brake.\n    const run = (el: HTMLElement) =>\n      el.animate(\n        [{ transform: \"translateX(0)\" }, { transform: \"translateX(-50%)\" }],\n        {\n          duration: (group.offsetWidth / speed) * 1000,\n          iterations: Infinity,\n          easing: \"linear\",\n          direction: direction === \"right\" ? \"reverse\" : \"normal\",\n        },\n      );\n    // The lit copy runs its own animation, created in the same frame so the\n    // two start together; every later change is applied to both.\n    const all = [track, lensRef.current]\n      .filter((el): el is HTMLDivElement => el !== null)\n      .map(run);\n    anims.current = all;\n\n    // Width changes (fonts loading, resizes) retime the loop, keeping the\n    // current progress so the row never jumps.\n    const ro = new ResizeObserver(() => {\n      const next = (group.offsetWidth / speed) * 1000;\n      const [a] = all;\n      const prev = Number(a.effect?.getTiming().duration) || next;\n      if (Math.abs(next - prev) < 1) return;\n      const at = (((Number(a.currentTime) || 0) % prev) / prev) * next;\n      for (const b of all) {\n        b.effect?.updateTiming({ duration: next });\n        b.currentTime = at;\n      }\n    });\n    ro.observe(group);\n\n    return () => {\n      cancelAnimationFrame(raf.current);\n      ro.disconnect();\n      all.forEach((a) => a.cancel());\n      anims.current = [];\n    };\n  }, [reduceMotion, speed, direction, showLens]);\n\n  // animation-play-state can only snap and playbackRate can't be\n  // transitioned, so ease the rate by hand. Starting from the current rate\n  // means re-entering mid-resume brakes smoothly from wherever it got to.\n  const rampTo = (target: number) => {\n    const all = anims.current;\n    const a = all[0];\n    if (!a) return;\n    cancelAnimationFrame(raf.current);\n    if (target > 0 && a.playState === \"paused\") all.forEach((b) => b.play());\n    const from = a.playbackRate;\n    // A partial ramp takes a proportional share of the time.\n    const ms = (target === 0 ? STOP_MS : RESUME_MS) * Math.abs(target - from);\n    const start = performance.now();\n    const tick = (now: number) => {\n      const t = ms > 0 ? Math.min(1, (now - start) / ms) : 1;\n      // Braking bites hard then coasts (ease-out cubic); resuming builds up\n      // gently (ease-in-out quad) so the speed change reads as momentum.\n      const e =\n        target === 0\n          ? 1 - (1 - t) ** 3\n          : t < 0.5\n            ? 2 * t * t\n            : 1 - (-2 * t + 2) ** 2 / 2;\n      for (const b of all) b.playbackRate = from + (target - from) * e;\n      if (t < 1) raf.current = requestAnimationFrame(tick);\n      // Fully stopped: pause so the compositor stops ticking an idle loop.\n      // Both pause on the same frame, so the copies stay locked together.\n      else if (target === 0) all.forEach((b) => b.pause());\n    };\n    raf.current = requestAnimationFrame(tick);\n  };\n\n  const group = (hidden: boolean) => (\n    <ul\n      ref={hidden ? undefined : groupRef}\n      // list-style: none drops list semantics in Safari; this restores them.\n      role={hidden ? undefined : \"list\"}\n      aria-hidden={hidden || undefined}\n      aria-label={hidden ? undefined : label}\n      // The trailing separator lives inside each copy, so the seam spacing\n      // matches every other gap and -50% lands exactly on the next copy.\n      className=\"flex shrink-0 items-center\"\n    >\n      {items.map((item) => (\n        <li key={item} className=\"flex items-center whitespace-nowrap\">\n          {item}\n          {/* Sized in em so the dot and gap scale with whatever text size\n              the row is given. */}\n          <span\n            aria-hidden\n            className=\"mx-[0.85em] size-[0.28em] shrink-0 rounded-full bg-current opacity-30\"\n          />\n        </li>\n      ))}\n    </ul>\n  );\n\n  return (\n    <div\n      onPointerEnter={(e) => {\n        if (e.pointerType !== \"touch\") rampTo(0);\n      }}\n      onPointerLeave={(e) => {\n        if (e.pointerType !== \"touch\") rampTo(1);\n      }}\n      className={cn(\n        \"relative overflow-hidden py-2 select-none\",\n        // Fades 12% of each edge so items drift in and out instead of being\n        // cut by a hard wall.\n        \"[mask-image:linear-gradient(to_right,transparent,black_12%,black_88%,transparent)]\",\n        // Standing still, clipped items would be unreachable, so the row\n        // scrolls by hand instead.\n        reduceMotion &&\n          \"overflow-x-auto [scrollbar-width:none] select-auto [&::-webkit-scrollbar]:hidden\",\n        className,\n      )}\n    >\n      <div\n        ref={trackRef}\n        className={cn(\n          \"flex w-max\",\n          // Outside the lens the row sits back, so the lit copy is the\n          // only thing at full strength.\n          showLens && \"opacity-40\",\n        )}\n      >\n        {group(false)}\n        {!reduceMotion && group(true)}\n      </div>\n      {showLens && (\n        // A second copy of the row at full strength, revealed only through a\n        // soft window in the middle: words brighten as they cross it, and\n        // braking on hover leaves one sitting in the lens, read.\n        <div\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0 py-2 [mask-image:linear-gradient(to_right,transparent_28%,black_40%,black_60%,transparent_72%)]\"\n        >\n          <div ref={lensRef} className=\"flex w-max\">\n            {group(true)}\n            {group(true)}\n          </div>\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport default function MarqueeDemo() {\n  return (\n    <div className=\"flex w-[520px] max-w-full flex-col gap-2 font-medium\">\n      <Marquee\n        label=\"Topics\"\n        className=\"text-lg text-foreground\"\n        items={[\n          \"Motion\",\n          \"Springs\",\n          \"Easing\",\n          \"Layout\",\n          \"Gestures\",\n          \"Tokens\",\n          \"Focus\",\n          \"Blur\",\n        ]}\n      />\n      {/* Slower, quieter and moving the other way, so it reads as a layer\n          further back rather than a second copy. */}\n      <Marquee\n        label=\"Techniques\"\n        direction=\"right\"\n        speed={24}\n        // One lens per stack: the back row stays evenly quiet.\n        lens={false}\n        className=\"text-[15px] text-muted-foreground\"\n        items={[\n          \"Stagger\",\n          \"Clip path\",\n          \"Velocity\",\n          \"Origin\",\n          \"Presence\",\n          \"Drag\",\n          \"Shadows\",\n          \"Radius\",\n        ]}\n      />\n    </div>\n  );\n}\n"}],"categories":["text"],"docs":"From ui lab: https://lab.xevrion.dev/lab/marquee"}