{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"wave-text","type":"registry:ui","title":"Wave text","description":"Letters ride a springy travelling wave on hover or in view, with wave, bounce, and scatter variants.","categories":["text"],"dependencies":["motion"],"registryDependencies":[],"files":[{"path":"registry/components/wave-text/wave-text.tsx","type":"registry:component","target":"@components/arc/wave-text/wave-text.tsx","content":"\"use client\";\n\nimport { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport type { CSSProperties, PointerEvent as ReactPointerEvent, Ref } from \"react\";\nimport { useReducedMotion } from \"motion/react\";\nimport styles from \"./wave-text.module.css\";\n\nexport type WaveTextVariant = \"wave\" | \"bounce\" | \"scatter\";\n\nexport interface WaveTextHandle {\n  /** Sends a wave through the text, starting at a letter index (0 by default) and travelling outward. */\n  play: (from?: number) => void;\n}\n\n/**\n * Text whose letters ride a travelling wave. Hovering sends a ripple out from the letter under the pointer and a sweep can\n * run when the text scrolls into view. Every letter is its own little spring, so motion overlaps and follows through\n * instead of playing back a keyframe. Screen readers get the plain text once; the animated letters are hidden from them.\n */\nexport interface WaveTextProps {\n  text: string;\n  /** Element to render. Defaults to \"span\". */\n  as?: \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"p\" | \"span\" | \"div\";\n  /** \"wave\" rises and settles, \"bounce\" hops and lands with a squash, \"scatter\" knocks letters loose and pulls them home. */\n  variant?: WaveTextVariant;\n  /** What starts the motion. \"both\" (default) sweeps once in view and ripples on hover. \"manual\" only runs play(). */\n  trigger?: \"hover\" | \"in-view\" | \"both\" | \"manual\";\n  /** Peak lift as a fraction of the font size. Defaults to 0.4. */\n  amplitude?: number;\n  /** Seconds between neighbouring letters. Defaults to 0.032. */\n  stagger?: number;\n  /** Color a letter takes at the top of its travel, fading back as it settles. Defaults to the accent; pass \"currentColor\" to keep one color. */\n  color?: string;\n  ref?: Ref<WaveTextHandle>;\n  className?: string;\n  style?: CSSProperties;\n}\n\ninterface Body { y: number; vy: number; x: number; vx: number; r: number; vr: number; s: number; vs: number; active: boolean }\ninterface Kick { at: number; i: number; strength: number; dir: number }\n\nconst subscribe = () => () => {};\nfunction useReducedFlag() {\n  const hydrated = useSyncExternalStore(subscribe, () => true, () => false);\n  return !!useReducedMotion() && hydrated;\n}\n\nfunction graphemes(text: string) {\n  if (typeof Intl !== \"undefined\" && \"Segmenter\" in Intl) return Array.from(new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).segment(text), part => part.segment);\n  return Array.from(text);\n}\n\n/** Pseudo random but stable per letter, so a scatter is lively without being noisy. */\nconst hash = (n: number) => {\n  const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;\n  return x - Math.floor(x);\n};\n\nexport function WaveText({ text, as: Tag = \"span\", variant = \"wave\", trigger = \"both\", amplitude = .4, stagger = .032, color, ref, className, style }: WaveTextProps) {\n  const reduced = useReducedFlag();\n  const rootRef = useRef<HTMLElement>(null);\n  const letters = useRef<(HTMLSpanElement | null)[]>([]);\n  const bodies = useRef<Body[]>([]);\n  const queue = useRef<Kick[]>([]);\n  const frame = useRef({ raf: 0, last: 0, hovered: -1, kicks: 0 });\n  const loopRef = useRef<FrameRequestCallback>(() => {});\n  const config = useRef({ variant, amplitude, stagger, reduced });\n  useEffect(() => { config.current = { variant, amplitude, stagger, reduced }; }, [variant, amplitude, stagger, reduced]);\n\n  // Words stay together so wrapping happens between words, never inside one.\n  const words = useMemo(() => {\n    let index = 0;\n    return text.split(/(\\s+)/).filter(Boolean).map(part => /^\\s+$/.test(part)\n      ? { space: true as const, text: part }\n      : { space: false as const, chars: graphemes(part).map(char => ({ char, index: index++ })) });\n  }, [text]);\n  const count = words.reduce((sum, word) => sum + (word.space ? 0 : word.chars.length), 0);\n\n  const paint = (i: number, b: Body) => {\n    const el = letters.current[i];\n    if (!el) return;\n    const { variant: v, amplitude: a } = config.current;\n    let sx = 1, sy = 1;\n    if (v === \"bounce\") {\n      // Stretch while flying, squash on landing.\n      const stretch = Math.min(.18, Math.abs(b.vy) * .012);\n      sx = 1 + b.s * .55 - stretch * .5;\n      sy = 1 - b.s + stretch;\n    }\n    el.style.transform = `translate3d(${b.x.toFixed(4)}em, ${b.y.toFixed(4)}em, 0) rotate(${b.r.toFixed(2)}deg) scale(${sx.toFixed(4)}, ${sy.toFixed(4)})`;\n    // The farther a letter travels from home, the more of the lift color it takes.\n    const lift = Math.min(1, Math.hypot(b.x, b.y) / Math.max(.05, a * .7));\n    el.style.setProperty(\"--wave-lift\", lift < .01 ? \"0\" : lift.toFixed(3));\n  };\n\n  const tick = useCallback((now: number) => {\n    const f = frame.current;\n    const dt = Math.min(.032, (now - (f.last || now)) / 1000) || 1 / 60;\n    f.last = now;\n    const { variant: v, amplitude: a } = config.current;\n\n    // Deliver kicks that are due.\n    const due = queue.current.filter(kick => kick.at <= now);\n    if (due.length) queue.current = queue.current.filter(kick => kick.at > now);\n    for (const kick of due) {\n      const b = bodies.current[kick.i];\n      if (!b) continue;\n      const k = kick.strength;\n      b.active = true;\n      if (v === \"wave\") {\n        // Set rather than add, so a pointer lingering on a letter cannot pump it higher and higher.\n        b.vy = Math.min(b.vy, -a * 19 * k);\n        b.vr = Math.abs(b.vr) > Math.abs(kick.dir * 90 * k) ? b.vr : kick.dir * 90 * k;\n      } else if (v === \"bounce\") {\n        if (b.y > -.04 && b.vy > -1) { b.vy = -Math.sqrt(2 * 70 * a * 1.5) * Math.max(.45, k); b.vs -= 4 * k; }\n      } else {\n        const angle = (hash(kick.i + (f.kicks++ % 7) * 13) - .5) * Math.PI * .9 - Math.PI / 2;\n        const force = a * 15 * k;\n        b.vx = Math.cos(angle) * force;\n        b.vy = Math.min(b.vy, Math.sin(angle) * force);\n        b.vr = (hash(kick.i * 3.1 + f.kicks) - .5) * 520 * k;\n      }\n    }\n\n    let busy = queue.current.length > 0;\n    const steps = 3, h = dt / steps;\n    bodies.current.forEach((b, i) => {\n      if (!b.active) return;\n      for (let n = 0; n < steps; n++) {\n        if (v === \"bounce\") {\n          b.vy += 70 * h;\n          b.y += b.vy * h;\n          if (b.y > 0) {\n            const impact = b.vy;\n            b.y = 0;\n            b.vy = impact > 1.4 ? -impact * .34 : 0;\n            b.vs += impact * .55;\n          }\n          b.vs += (-640 * b.s - 20 * b.vs) * h;\n          b.s += b.vs * h;\n          b.x = 0; b.r = 0;\n        } else {\n          const k = v === \"wave\" ? 230 : 150, c = v === \"wave\" ? 13 : 10.5;\n          b.vy += (-k * b.y - c * b.vy) * h; b.y += b.vy * h;\n          b.vx += (-k * b.x - c * b.vx) * h; b.x += b.vx * h;\n          b.vr += (-k * b.r - c * b.vr) * h; b.r += b.vr * h;\n          b.s = 0; b.vs = 0;\n        }\n      }\n      const still = Math.abs(b.y) < .0008 && Math.abs(b.vy) < .01 && Math.abs(b.x) < .0008 && Math.abs(b.vx) < .01 && Math.abs(b.r) < .02 && Math.abs(b.vr) < .5 && Math.abs(b.s) < .0008 && Math.abs(b.vs) < .01;\n      if (still) Object.assign(b, { y: 0, vy: 0, x: 0, vx: 0, r: 0, vr: 0, s: 0, vs: 0, active: false });\n      else busy = true;\n      paint(i, b);\n    });\n\n    if (busy) f.raf = requestAnimationFrame(loopRef.current);\n    else { f.raf = 0; f.last = 0; }\n  }, []);\n  useEffect(() => { loopRef.current = tick; }, [tick]);\n\n  const wake = useCallback(() => {\n    const f = frame.current;\n    if (!f.raf) { f.last = 0; f.raf = requestAnimationFrame(tick); }\n  }, [tick]);\n\n  // Keep one body per letter, and reset transforms when the text or variant changes.\n  useEffect(() => {\n    bodies.current = Array.from({ length: count }, () => ({ y: 0, vy: 0, x: 0, vx: 0, r: 0, vr: 0, s: 0, vs: 0, active: false }));\n    queue.current = [];\n    letters.current.slice(0, count).forEach(el => { if (el) { el.style.transform = \"\"; el.style.removeProperty(\"--wave-lift\"); } });\n  }, [count, text, variant]);\n\n  useEffect(() => () => cancelAnimationFrame(frame.current.raf), []);\n\n  const ripple = useCallback((from: number, reach: number, falloff: number) => {\n    if (config.current.reduced || !bodies.current.length) return;\n    const now = performance.now();\n    const gap = config.current.stagger * 1000;\n    for (let i = 0; i < bodies.current.length; i++) {\n      const distance = Math.abs(i - from);\n      if (distance > reach) continue;\n      queue.current.push({ at: now + distance * gap, i, strength: Math.max(.25, 1 - distance * falloff), dir: i === from ? 0 : Math.sign(i - from) });\n    }\n    wake();\n  }, [wake]);\n\n  const play = useCallback((from = 0) => ripple(Math.max(0, Math.min(count - 1, from)), Infinity, 0), [ripple, count]);\n  useImperativeHandle(ref, () => ({ play }), [play]);\n\n  // Sweep once when the text first scrolls into view.\n  useEffect(() => {\n    if (reduced || (trigger !== \"in-view\" && trigger !== \"both\")) return;\n    const el = rootRef.current;\n    if (!el || typeof IntersectionObserver === \"undefined\") return;\n    const observer = new IntersectionObserver(entries => {\n      if (!entries.some(entry => entry.isIntersecting)) return;\n      observer.disconnect();\n      play(0);\n    }, { threshold: .6 });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [trigger, reduced, play]);\n\n  const hover = trigger === \"hover\" || trigger === \"both\";\n  const onPointerMove = (event: ReactPointerEvent<HTMLElement>) => {\n    const target = (event.target as HTMLElement).closest<HTMLElement>(\"[data-wave-index]\");\n    if (!target) return;\n    const index = Number(target.dataset.waveIndex);\n    const f = frame.current;\n    if (index === f.hovered) return;\n    const entering = f.hovered === -1;\n    f.hovered = index;\n    // Entering sends a ripple through the whole line; moving along it pushes a short swell that follows the pointer.\n    if (entering) ripple(index, Infinity, .06);\n    else ripple(index, 2, .38);\n  };\n  const onPointerLeave = () => { frame.current.hovered = -1; };\n\n  return <Tag\n    ref={rootRef as never}\n    className={[styles.root, className].filter(Boolean).join(\" \")}\n    style={color ? { ...style, \"--wave-text-color\": color } as CSSProperties : style}\n    onPointerMove={hover ? onPointerMove : undefined}\n    onPointerLeave={hover ? onPointerLeave : undefined}\n    data-variant={variant}\n  >\n    <span className={styles.srOnly}>{text}</span>\n    <span className={styles.letters} aria-hidden=\"true\">\n      {words.map((word, w) => word.space\n        ? <span key={w}>{word.text}</span>\n        : <span key={w} className={styles.word}>\n          {word.chars.map(({ char, index }) => <span key={index} ref={el => { letters.current[index] = el; }} className={styles.letter} data-wave-index={index}>{char}</span>)}\n        </span>)}\n    </span>\n  </Tag>;\n}\n"},{"path":"registry/components/wave-text/wave-text.module.css","type":"registry:component","target":"@components/arc/wave-text/wave-text.module.css","content":".root { --wave-text-color: var(--accent); display: inline-block; }\n.letters { display: inline; }\n.word { display: inline-block; white-space: nowrap; }\n/* A letter in flight tints toward the lift color; at rest it is plain text. */\n.letter { display: inline-block; color: color-mix(in oklab, var(--wave-text-color) calc(var(--wave-lift, 0) * 100%), currentColor); transform-origin: 50% 88%; will-change: transform; }\n.srOnly { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }\n"}],"docs":"Docs and live preview: https://uiarc.dev/components/wave-text","meta":{"tier":"free","kind":"component","tags":["text","motion","new"],"docs":"https://uiarc.dev/components/wave-text","markdown":"https://uiarc.dev/components/wave-text/markdown"}}