{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"word-rotator","type":"registry:component","title":"Word rotator","description":"Keeps the letters two words share and glides them into place as the rest trade out.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":[],"registryDependencies":["utils"],"files":[{"path":"components/word-rotator.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\n\ntype Letter = { id: number; ch: string };\ntype Exiting = Letter & { left: number };\n\nconst EASE_OUT = \"cubic-bezier(0.23, 1, 0.32, 1)\";\nconst EASE_IN_OUT = \"cubic-bezier(0.77, 0, 0.175, 1)\";\n// Shared letters can travel most of a word across, so they get longer than a\n// typical UI tween; any shorter and the glide reads as a jump.\nconst GLIDE_MS = 440;\nconst ENTER_MS = 320;\n// Leaving letters are gone before the glide lands, so the eye follows the\n// letters that stay rather than the ones that go.\nconst EXIT_MS = 200;\nconst STAGGER_MS = 28;\n\n// Longest common subsequence, so the most letters possible survive the swap\n// while keeping their order (\"fast\" to \"honest\" keeps both s and t).\nfunction matchLetters(prev: string[], next: string[]) {\n  const dp = Array.from({ length: prev.length + 1 }, () =>\n    new Array<number>(next.length + 1).fill(0),\n  );\n  for (let i = prev.length - 1; i >= 0; i--)\n    for (let j = next.length - 1; j >= 0; j--)\n      dp[i][j] =\n        prev[i] === next[j]\n          ? dp[i + 1][j + 1] + 1\n          : Math.max(dp[i + 1][j], dp[i][j + 1]);\n  // next index -> prev index\n  const pairs = new Map<number, number>();\n  let i = 0;\n  let j = 0;\n  while (i < prev.length && j < next.length) {\n    if (prev[i] === next[j]) {\n      pairs.set(j, i);\n      i++;\n      j++;\n    } else if (dp[i + 1][j] >= dp[i][j + 1]) i++;\n    else j++;\n  }\n  return pairs;\n}\n\nexport function WordRotator({\n  words,\n  // Long enough to read the whole sentence once per word.\n  interval = 2600,\n  paused: pausedProp = false,\n  className,\n}: {\n  words: string[];\n  interval?: number;\n  /** Stops rotating and settles back on the first word. */\n  paused?: boolean;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const nextId = useRef(words[0].length);\n\n  const [index, setIndex] = useState(0);\n  const [letters, setLetters] = useState<Letter[]>(() =>\n    [...words[0]].map((ch, id) => ({ id, ch })),\n  );\n  const [exiting, setExiting] = useState<Exiting[]>([]);\n\n  const box = useRef<HTMLSpanElement>(null);\n  const nodes = useRef(new Map<number, HTMLSpanElement>());\n  // Where things were on screen just before a swap, read back after it.\n  const before = useRef<{\n    lefts: Map<number, number>;\n    width: number;\n    entering: Set<number>;\n  } | null>(null);\n  const paused = useRef(false);\n  const exitTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  useEffect(() => {\n    const swapTo = (nextIndex: number) => {\n      if (!box.current) return;\n      const from = box.current.getBoundingClientRect();\n      // Rects are post-transform; a scaled ancestor (a zoomed preview) would\n      // otherwise have every offset below applied twice.\n      const s = from.width / box.current.offsetWidth || 1;\n      const lefts = new Map<number, number>();\n      for (const l of letters) {\n        const el = nodes.current.get(l.id);\n        // Visual position, mid-animation included, so a swap that lands\n        // during a glide continues from where the letter really is.\n        if (el)\n          lefts.set(l.id, (el.getBoundingClientRect().left - from.left) / s);\n      }\n\n      const nextChars = [...words[nextIndex]];\n      // Reduced motion is a plain crossfade: nothing travels.\n      const pairs = reduceMotion\n        ? new Map<number, number>()\n        : matchLetters(\n            letters.map((l) => l.ch),\n            nextChars,\n          );\n      const kept = new Set(pairs.values());\n      const entering = new Set<number>();\n      const nextLetters = nextChars.map((ch, j) => {\n        const p = pairs.get(j);\n        if (p !== undefined) return letters[p];\n        const l = { id: nextId.current++, ch };\n        entering.add(l.id);\n        return l;\n      });\n\n      before.current = { lefts, width: from.width / s, entering };\n      setExiting(\n        letters\n          .filter((_, i) => !kept.has(i))\n          .map((l) => ({ ...l, left: lefts.get(l.id) ?? 0 })),\n      );\n      setLetters(nextLetters);\n      setIndex(nextIndex);\n      clearTimeout(exitTimer.current);\n      exitTimer.current = setTimeout(() => setExiting([]), EXIT_MS + 40);\n    };\n\n    if (pausedProp) {\n      // One last swap home after a short beat, then nothing runs.\n      if (index === 0) return;\n      const home = setTimeout(() => swapTo(0), 250);\n      return () => clearTimeout(home);\n    }\n    const tick = setInterval(() => {\n      if (paused.current || document.hidden) return;\n      swapTo((index + 1) % words.length);\n    }, interval);\n    return () => clearInterval(tick);\n  }, [index, letters, words, interval, reduceMotion, pausedProp]);\n\n  useEffect(() => () => clearTimeout(exitTimer.current), []);\n\n  useLayoutEffect(() => {\n    const prev = before.current;\n    const el = box.current;\n    if (!prev || !el) return;\n    before.current = null;\n\n    // Settle everything first so the measurements below are the final\n    // layout, then animate from the old picture to it.\n    el.getAnimations().forEach((a) => a.cancel());\n    for (const l of letters)\n      nodes.current\n        .get(l.id)\n        ?.getAnimations()\n        .forEach((a) => a.cancel());\n    const to = el.getBoundingClientRect();\n    const s = to.width / el.offsetWidth || 1;\n    const toWidth = to.width / s;\n    const nows = new Map<number, number>();\n    for (const l of letters) {\n      const node = nodes.current.get(l.id);\n      if (node)\n        nows.set(l.id, (node.getBoundingClientRect().left - to.left) / s);\n    }\n\n    // Width, not scale: the sentence needs real layout space so the words\n    // around it slide instead of snapping. It is one inline box, so the\n    // reflow per frame is tiny.\n    if (!reduceMotion && Math.abs(toWidth - prev.width) > 0.5) {\n      el.animate([{ width: `${prev.width}px` }, { width: `${toWidth}px` }], {\n        duration: GLIDE_MS,\n        easing: EASE_IN_OUT,\n      });\n    }\n\n    let order = 0;\n    for (const l of letters) {\n      const node = nodes.current.get(l.id);\n      if (!node) continue;\n      if (prev.entering.has(l.id)) {\n        node.animate(\n          reduceMotion\n            ? [{ opacity: 0 }, { opacity: 1 }]\n            : [\n                {\n                  opacity: 0,\n                  transform: \"translateY(0.4em)\",\n                  filter: \"blur(4px)\",\n                },\n                { opacity: 1, transform: \"translateY(0)\", filter: \"blur(0px)\" },\n              ],\n          {\n            duration: ENTER_MS,\n            // A beat for the leaving letters to clear the space, then a\n            // small left-to-right cascade.\n            delay: reduceMotion ? 0 : 90 + order++ * STAGGER_MS,\n            easing: EASE_OUT,\n            fill: \"backwards\",\n          },\n        );\n      } else {\n        const was = prev.lefts.get(l.id);\n        const now = nows.get(l.id);\n        if (was === undefined || now === undefined) continue;\n        if (Math.abs(was - now) < 0.5) continue;\n        node.animate(\n          [\n            { transform: `translateX(${was - now}px)` },\n            { transform: \"translateX(0)\" },\n          ],\n          { duration: GLIDE_MS, easing: EASE_IN_OUT },\n        );\n      }\n    }\n  }, [letters, reduceMotion]);\n\n  // Leaving letters stay where they stood, then float up and out.\n  const exitRef = (node: HTMLSpanElement | null) => {\n    if (!node || node.dataset.leaving) return;\n    node.dataset.leaving = \"1\";\n    node.animate(\n      reduceMotion\n        ? [{ opacity: 1 }, { opacity: 0 }]\n        : [\n            { opacity: 1, transform: \"translateY(0)\", filter: \"blur(0px)\" },\n            {\n              opacity: 0,\n              transform: \"translateY(-0.35em)\",\n              filter: \"blur(4px)\",\n            },\n          ],\n      { duration: EXIT_MS, easing: EASE_OUT, fill: \"forwards\" },\n    );\n  };\n\n  return (\n    <span\n      className={cn(\"relative inline-block\", className)}\n      onPointerEnter={(e) => {\n        if (e.pointerType !== \"touch\") paused.current = true;\n      }}\n      onPointerLeave={() => {\n        paused.current = false;\n      }}\n    >\n      {/* Read once as a list of every word instead of announcing each swap. */}\n      <span className=\"sr-only\">{words.join(\", \")}</span>\n      <span\n        ref={box}\n        aria-hidden\n        className=\"relative inline-block text-left whitespace-pre\"\n      >\n        {letters.map((l) => (\n          <span\n            key={l.id}\n            ref={(n) => {\n              if (n) nodes.current.set(l.id, n);\n              else nodes.current.delete(l.id);\n            }}\n            className=\"inline-block\"\n          >\n            {l.ch}\n          </span>\n        ))}\n        {exiting.map((l) => (\n          <span\n            key={l.id}\n            ref={exitRef}\n            className=\"pointer-events-none absolute top-0 inline-block\"\n            style={{ left: l.left }}\n          >\n            {l.ch}\n          </span>\n        ))}\n      </span>\n    </span>\n  );\n}\n\n// In an index card the rotator waits at rest and plays quicker on hover.\nconst PREVIEW_INTERVAL = 1400;\n\nexport default function WordRotatorDemo() {\n  const play = usePreviewPlay();\n  return (\n    <h2 className=\"relative text-center text-2xl font-semibold tracking-tight text-muted-foreground sm:text-4xl\">\n      Design that feels{\" \"}\n      <WordRotator\n        words={[\"calm\", \"fast\", \"honest\", \"alive\"]}\n        paused={play === false}\n        interval={play ? PREVIEW_INTERVAL : undefined}\n        className=\"text-foreground\"\n      />\n    </h2>\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"}],"categories":["text"],"docs":"From ui lab: https://lab.xevrion.dev/lab/word-rotator"}