{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"rotating-word-swap","type":"registry:component","title":"Rotating Word Swap Headline","description":"A headline whose key word swaps through a list: letters roll up and out with a blur, the next word rolls in letter by letter, the line closes smoothly around each width, and every word gets its own accent. A hairline timer shows the cycle, hover or focus holds it, a tap skips ahead.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/rotating-word-swap.tsx","content":"\"use client\";\n\n/*\n * RotatingWordSwap: a headline whose key word swaps through a list.\n *\n * Every word is its own absolutely positioned layer of per-letter spans. The\n * outgoing word rolls up and out letter by letter with a blur, the incoming\n * word rolls up from below with a longer stagger, and the box around them\n * animates its width between the measured widths of the words, so the text\n * before it glides instead of jumping. Each word has its own accent colour.\n * A hairline under the word shows the timer. The timer itself is a timeout\n * that keeps its remaining time, so hover, focus, off-screen and a hidden tab\n * hold the cycle and release it where it left off.\n * Reduced motion keeps the timing but crossfades the words in place.\n * No dependencies, no stylesheet to import.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from \"react\";\n\nconst DEFAULT_WORDS = [\"fast\", \"clean\", \"vibed\", \"shipped\"];\nconst DEFAULT_COLORS = [\"#ef4444\", \"#d97706\", \"#059669\", \"#3b82f6\"];\nconst SEP = \"\\u0001\";\nconst NBSP = String.fromCharCode(160);\n\nconst CSS = [\n  \".rws-w{position:relative;display:inline-block;vertical-align:baseline;text-align:left;white-space:nowrap;transition:width 640ms cubic-bezier(.22,1,.36,1)}\",\n  \"button.rws-w{appearance:none;background:none;border:0;margin:0;padding:0;font:inherit;letter-spacing:inherit;line-height:inherit;text-transform:inherit;color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent;touch-action:manipulation}\",\n  \"button.rws-w:active{transform:scale(.97);transition:width 640ms cubic-bezier(.22,1,.36,1),transform 120ms ease-out}\",\n  \"button.rws-w:focus-visible{outline:2px solid #3b82f6 !important;outline-offset:6px !important;border-radius:6px}\",\n  \".rws-s{display:inline-block;visibility:hidden}\",\n  \".rws-r .rws-s{width:0;overflow:clip}\",\n  \".rws-m{position:absolute;left:0;top:0;visibility:hidden;pointer-events:none;white-space:nowrap}\",\n  \".rws-l{position:absolute;left:0;top:0;display:inline-block;white-space:nowrap}\",\n  \".rws-c{display:inline-block}\",\n  '.rws-l[data-s=\"in\"] .rws-c{opacity:1;transform:none;filter:blur(0);transition:transform 640ms cubic-bezier(.16,1,.3,1),opacity 360ms ease-out,filter 520ms ease-out;transition-delay:calc(90ms + min(calc(var(--i) * 30ms), 330ms))}',\n  '.rws-l[data-s=\"out\"] .rws-c{opacity:0;transform:translateY(-.62em);filter:blur(8px);transition:transform 420ms cubic-bezier(.6,0,.84,0),opacity 300ms ease-in,filter 360ms ease-in;transition-delay:min(calc(var(--i) * 14ms), 140ms)}',\n  '.rws-l[data-s=\"idle\"]{visibility:hidden}',\n  '.rws-l[data-s=\"idle\"] .rws-c{opacity:0;transform:translateY(.62em);filter:blur(8px);transition:none}',\n  \".rws-b{position:absolute;left:0;right:0;bottom:-.04em;height:max(2px,.04em);border-radius:2px;opacity:.55;transform-origin:left center;transform:scaleX(0);animation:rws-bar linear forwards;pointer-events:none}\",\n  \"@keyframes rws-bar{from{transform:scaleX(0)}to{transform:scaleX(1)}}\",\n  \"@media (prefers-reduced-motion:reduce){.rws-w{transition:none !important}.rws-c{transform:none !important;filter:none !important;transition:opacity 320ms linear !important;transition-delay:0ms !important}.rws-b{opacity:0 !important}}\",\n].join(\"\");\n\nconst grapheme = (s: string): string[] => Array.from(s);\n\nexport function RotatingWordSwap({\n  prefix = \"Make it\",\n  words = DEFAULT_WORDS,\n  interval = 1800,\n  colors = DEFAULT_COLORS,\n  interactive = false,\n  pauseOnHover = true,\n  progress = true,\n  className,\n}: {\n  prefix?: string;\n  words?: string[];\n  interval?: number;\n  /** Accent colour per word (cycled). Pass [\"currentColor\"] to inherit the text colour. */\n  colors?: string[];\n  /** Makes the word a button: Enter, Space or a tap skips ahead, and focusing it holds the cycle. */\n  interactive?: boolean;\n  /** Hold the cycle while the pointer is over the headline. */\n  pauseOnHover?: boolean;\n  /** Show the hairline timer under the word. */\n  progress?: boolean;\n  className?: string;\n}) {\n  const wordsKey = words.join(SEP);\n  const list = useMemo(() => {\n    const l = wordsKey.split(SEP).filter((w) => w.trim());\n    return l.length ? l : DEFAULT_WORDS;\n  }, [wordsKey]);\n  const colorsKey = colors.join(SEP);\n  const palette = useMemo(() => {\n    const c = colorsKey.split(SEP).filter(Boolean);\n    return c.length ? c : DEFAULT_COLORS;\n  }, [colorsKey]);\n  const n = list.length;\n  const dur = Math.max(400, interval);\n\n  const [st, setSt] = useState<{ cur: number; prev: number | null }>({ cur: 0, prev: null });\n  const [widths, setWidths] = useState<number[] | null>(null);\n  const [hover, setHover] = useState(false);\n  const [focus, setFocus] = useState(false);\n  const [away, setAway] = useState(false);\n  const rootRef = useRef<HTMLParagraphElement>(null);\n  const measureRefs = useRef<(HTMLSpanElement | null)[]>([]);\n\n  const idx = st.cur % n;\n  const prevIdx = st.prev === null ? null : st.prev % n;\n\n  const advance = useCallback(() => {\n    setSt((s) => ({ cur: (s.cur + 1) % n, prev: s.cur % n }));\n  }, [n]);\n\n  // Retire the exiting layer once its exit has finished.\n  useEffect(() => {\n    if (st.prev === null) return;\n    const cur = st.cur;\n    const t = window.setTimeout(() => setSt((s) => (s.cur === cur ? { cur: s.cur, prev: null } : s)), 1000);\n    return () => window.clearTimeout(t);\n  }, [st.cur, st.prev]);\n\n  // Measure every word once and whenever fonts or sizes change.\n  useEffect(() => {\n    const els = measureRefs.current.slice(0, n).filter((e): e is HTMLSpanElement => !!e);\n    if (els.length !== n) return;\n    const read = () => {\n      const next = els.map((e) => e.offsetWidth);\n      setWidths((old) => (old && old.length === next.length && old.every((v, i) => v === next[i]) ? old : next));\n    };\n    const ro = new ResizeObserver(read);\n    els.forEach((e) => ro.observe(e));\n    let alive = true;\n    if (document.fonts && document.fonts.ready) void document.fonts.ready.then(() => alive && read());\n    return () => {\n      alive = false;\n      ro.disconnect();\n    };\n  }, [wordsKey, n]);\n\n  // Sleep while off-screen or in a hidden tab.\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    let visible = true;\n    const sync = () => setAway(!visible || document.hidden);\n    const io = new IntersectionObserver((es) => {\n      const e = es[es.length - 1];\n      if (e) visible = e.isIntersecting;\n      sync();\n    });\n    io.observe(root);\n    document.addEventListener(\"visibilitychange\", sync);\n    return () => {\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", sync);\n    };\n  }, []);\n\n  const hold = away || focus || (pauseOnHover && hover);\n  // The clock: a timer that keeps its remaining time across holds. (The hairline is only a picture of it.)\n  const remain = useRef(dur);\n  useEffect(() => {\n    remain.current = dur;\n  }, [st.cur, dur]);\n  useEffect(() => {\n    if (n < 2 || hold) return;\n    const t0 = performance.now();\n    const id = window.setTimeout(advance, remain.current);\n    return () => {\n      window.clearTimeout(id);\n      remain.current = Math.max(0, remain.current - (performance.now() - t0));\n    };\n  }, [st.cur, hold, n, dur, advance]);\n\n  const ready = widths !== null && widths.length === n;\n  const boxStyle: CSSProperties | undefined = ready ? { width: widths[idx] } : undefined;\n  const accent = palette[idx % palette.length] ?? \"currentColor\";\n\n  const inner = (\n    <>\n      <span className=\"rws-s\" aria-hidden=\"true\">\n        {list[0]}\n      </span>\n      {list.map((w, i) => {\n        const state = i === idx ? \"in\" : i === prevIdx ? \"out\" : \"idle\";\n        return (\n          <span key={i} className=\"rws-l\" data-s={state} style={{ color: palette[i % palette.length] }} aria-hidden=\"true\">\n            {grapheme(w).map((ch, j) => (\n              <span key={j} className=\"rws-c\" style={{ \"--i\": j } as CSSProperties}>\n                {ch === \" \" ? NBSP : ch}\n              </span>\n            ))}\n          </span>\n        );\n      })}\n      {list.map((w, i) => (\n        <span\n          key={\"m\" + i}\n          className=\"rws-m\"\n          aria-hidden=\"true\"\n          ref={(el) => {\n            measureRefs.current[i] = el;\n          }}\n        >\n          {w.replace(/ /g, NBSP)}\n        </span>\n      ))}\n      {progress && n > 1 && (\n        <span\n          key={st.cur}\n          className=\"rws-b\"\n          aria-hidden=\"true\"\n          style={{ background: accent, animationDuration: dur + \"ms\", animationPlayState: hold ? \"paused\" : \"running\" }}\n        />\n      )}\n    </>\n  );\n\n  return (\n    <>\n    <style>{CSS}</style>\n    <p\n      ref={rootRef}\n      className={(className ?? \"text-3xl font-black\") + (ready ? \" rws-r\" : \"\")}\n      onPointerEnter={(e) => e.pointerType === \"mouse\" && setHover(true)}\n      onPointerLeave={() => setHover(false)}\n    >\n      <span className=\"sr-only\">{prefix + \" \" + list.join(\", \")}</span>\n      <span aria-hidden=\"true\">{prefix} </span>\n      {interactive ? (\n        <button\n          type=\"button\"\n          className=\"rws-w\"\n          style={boxStyle}\n          aria-label={\"Next word, currently \" + (list[idx] ?? \"\")}\n          onClick={advance}\n          onFocus={() => setFocus(true)}\n          onBlur={() => setFocus(false)}\n        >\n          {inner}\n        </button>\n      ) : (\n        <span className=\"rws-w\" style={boxStyle} onClick={advance}>\n          {inner}\n        </span>\n      )}\n    </p>\n    </>\n  );\n}\n","type":"registry:component","target":"components/viberdy/rotating-word-swap.tsx"}],"meta":{"tier":"free","tags":["text","headline","cycle","swap","per-letter","blur","width-morph","accessible"],"href":"https://viberdy.dev/library/rotating-word-swap","aiPrompt":"Create a React + Tailwind \"rotating word swap\" headline component named RotatingWordSwap. One self-contained \"use client\" file, React only (useState, useEffect, useRef, useMemo, useCallback), no animation library. One static CSS string is rendered in a <style> element placed beside the root <p> (inside a fragment).\n\nProps (all optional): prefix (string, default \"Make it\"); words (string[], default [\"fast\",\"clean\",\"vibed\",\"shipped\"], hoisted to a module constant); interval (ms between swaps, default 1800, clamp min 400); colors (string[], accent per word cycled, default [\"#ef4444\",\"#d97706\",\"#059669\",\"#3b82f6\"]; [\"currentColor\"] inherits); interactive (boolean, default false: when true the word is a <button>); pauseOnHover (default true); progress (default true: hairline timer); className (replaces the default \"text-3xl font-black\" on the root <p>).\n\nStructure: root <p>. Inside: a sr-only span with prefix + \" \" + words joined by \", \" (the only text exposed to assistive tech), an aria-hidden span with the prefix and a trailing space, then the word box (a <button type=\"button\"> when interactive, else a <span>) with class rws-w: relative, inline-block, vertical-align baseline, white-space nowrap, text-align left, button reset (font inherit, no border/background/padding). The button has aria-label \"Next word, currently <word>\". Inside the box: an in-flow invisible sizer span with the first word (gives the baseline and the pre-measurement width; once measured it becomes width 0, overflow clip); one absolutely positioned aria-hidden layer (left 0, top 0, nowrap, colour = palette[i]) per word made of inline-block letter spans (Array.from graphemes, spaces as NBSP) each with a --i index custom property; one hidden absolute measurer span per word; and the hairline.\n\nWidth: measure each measurer's offsetWidth in an effect (ResizeObserver on the measurers plus document.fonts.ready) and store the widths; once measured set the box width to the current word's width with transition width 640ms cubic-bezier(.22,1,.36,1). Before measurement the box is auto width from the sizer.\n\nLayer states by data-s: \"in\" (current), \"out\" (previous, kept for 1000ms then cleared), \"idle\". Letters, in: opacity 1, no transform, blur 0; transition transform 640ms cubic-bezier(.16,1,.3,1), opacity 360ms ease-out, filter 520ms ease-out; delay 90ms + min(i*30ms, 330ms). Out: opacity 0, translateY(-0.62em), blur 8px; transform 420ms cubic-bezier(.6,0,.84,0), opacity 300ms ease-in, filter 360ms ease-in; delay min(i*14ms, 140ms). Idle: layer visibility hidden, letters opacity 0, translateY(0.62em), blur 8px, transition none (so the next \"in\" starts from below).\n\nClock: a timer drives the cycle, not the hairline. One effect keyed on the current index, hold, word count and interval runs setTimeout(advance, remaining); its cleanup clears it and subtracts the elapsed time from a remaining-time ref, which resets to the interval whenever the current word changes, so holds resume where they left off. hold is true while: the pointer (mouse only) is over the root and pauseOnHover; the word button has focus; the root is off-screen (IntersectionObserver); or document.hidden. The hairline is purely visual: absolute, left 0, right 0, bottom -0.04em, height max(2px, 0.04em), background = the current word colour, opacity .55, transform-origin left, animation scaleX(0 to 1) linear forwards for the interval, remounted with key per word index, animation-play-state paused while hold. Click/tap/Enter/Space on the word advances immediately (the current-index change restarts the clock). Button :active scales .97. Focus ring: outline 2px solid #3b82f6 important, offset 6px, radius 6px.\n\nColours: the prefix inherits the text colour; no site tokens; works on light and dark pages.\n\nReduced motion (media query): no width transition; letters have no transform, no blur, no delay, only a 320ms linear opacity crossfade; the hairline is hidden (opacity 0); the timer is unaffected.","license":"https://viberdy.dev/license"}}