{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"text-scramble-reveal","type":"registry:component","title":"Text scramble reveal","description":"Letters scramble near the mouse.","author":"DiMaac (HankTheTank) <https://dimaac.com>","dependencies":["gsap","@gsap/react"],"files":[{"path":"registry/dimaac/text-scramble-reveal/text-scramble-reveal.tsx","type":"registry:component","target":"components/dimaac/text-scramble-reveal.tsx","content":"\"use client\";\n\nimport { Fragment, useRef, type CSSProperties } from \"react\";\nimport { gsap } from \"gsap\";\nimport { useGSAP } from \"@gsap/react\";\n\n// Text that shuffles through other characters and settles into place. It can play once when the\n// text scrolls into view (letters resolve left to right), and it can scramble the letters near\n// the pointer as you move across it.\n//\n// The letters are real spans that React renders and owns. The scramble never edits their text.\n// It sets a data attribute, and a CSS overlay (::after) paints the random glyph on top of the\n// real letter, which is hidden for that moment. So the layout never jumps, React never loses a\n// node it expects, and changing the `text` prop is safe.\n\nexport type TextScrambleRevealProps = {\n  /** The words to show. Plain text. */\n  text: string;\n  /** When it scrambles: \"reveal\" plays once on entering the view, \"hover\" reacts to the pointer, \"both\" does the two. */\n  mode?: \"hover\" | \"reveal\" | \"both\";\n  /** The random characters a letter shuffles through. Every character in the string is one choice. */\n  scrambleChars?: string;\n  /** The colour of the random characters, and of the flash a letter leaves as it settles. Any CSS colour. */\n  scrambleColor?: string;\n  /** How long one letter keeps shuffling, in seconds. Each letter varies a little around it. */\n  scrambleDuration?: number;\n  /** How close the pointer must come to a letter to scramble it, in pixels. */\n  radius?: number;\n  /** In \"reveal\" mode, the gap between one letter starting to settle and the next, in seconds. Long texts are sped up to finish in about two seconds. */\n  stagger?: number;\n  /** Play the reveal only the first time it is seen (true), or every time it scrolls back into view (false). */\n  once?: boolean;\n  /** Text size. A number is pixels, a string is any CSS size such as \"clamp(18px, 4vw, 40px)\". Leave it out to inherit. */\n  fontSize?: number | string;\n  /** Line height, as a multiple of the text size. */\n  lineHeight?: number;\n  /** Extra classes for the paragraph: font, colour, width. The text takes its colour from here. */\n  className?: string;\n};\n\ntype Job = { end: number; swapAt: number };\n\nexport function TextScrambleReveal({\n  text,\n  mode = \"both\",\n  scrambleChars = \".:·+*-\",\n  scrambleColor = \"#00a8e8\",\n  scrambleDuration = 0.45,\n  radius = 80,\n  stagger = 0.01,\n  once = true,\n  fontSize,\n  lineHeight = 1.3,\n  className = \"\",\n}: TextScrambleRevealProps) {\n  const boxRef = useRef<HTMLParagraphElement>(null);\n\n  // Read at the moment they are needed, so changing them never restarts the effect\n  const settings = useRef({ glyphs: [\".\", \":\"], duration: scrambleDuration, radius, color: scrambleColor });\n  const glyphs = Array.from(scrambleChars).filter((c) => c.trim() !== \"\");\n  settings.current = { glyphs: glyphs.length > 0 ? glyphs : [\".\"], duration: scrambleDuration, radius, color: scrambleColor };\n\n  useGSAP(\n    () => {\n      const box = boxRef.current;\n      if (!box) return;\n      const letters = Array.from(box.querySelectorAll<HTMLElement>(\"[data-letter]\"));\n      if (letters.length === 0) return;\n\n      // Reduced motion: no scrambling at all. The text is simply there.\n      const mm = gsap.matchMedia();\n      mm.add(\"(prefers-reduced-motion: no-preference)\", () => {\n        const wantsReveal = mode === \"reveal\" || mode === \"both\";\n        const wantsHover = mode === \"hover\" || mode === \"both\";\n\n        const jobs = new Map<number, Job>(); // letters that are shuffling right now\n        const flashes = new Set<Animation>(); // the colour fade after a letter settles\n        let centres: { x: number; y: number }[] = [];\n        let ticking = false;\n        let ready = !wantsReveal; // hover waits until the reveal has started\n        let last: { x: number; y: number } | null = null;\n\n        const randomGlyph = () => settings.current.glyphs[Math.floor(Math.random() * settings.current.glyphs.length)] ?? \".\";\n        const swapGap = () => 0.04 + Math.random() * 0.03;\n\n        // Settling: show the real letter again and fade it from the scramble colour\n        const settle = (letter: HTMLElement) => {\n          delete letter.dataset.s;\n          const flash = letter.animate([{ color: settings.current.color }], { duration: 650, easing: \"ease-out\" });\n          flashes.add(flash);\n          flash.onfinish = flash.oncancel = () => flashes.delete(flash);\n        };\n\n        const tick = () => {\n          const now = gsap.ticker.time;\n          jobs.forEach((job, index) => {\n            const letter = letters[index]!;\n            if (now >= job.end) {\n              jobs.delete(index);\n              settle(letter);\n            } else if (now >= job.swapAt) {\n              letter.dataset.s = randomGlyph();\n              job.swapAt = now + swapGap();\n            }\n          });\n          if (jobs.size === 0) {\n            gsap.ticker.remove(tick);\n            ticking = false;\n          }\n        };\n\n        // One shared ticker loop for every shuffling letter. It sleeps when nothing is shuffling.\n        const scramble = (index: number, delay = 0) => {\n          const now = gsap.ticker.time;\n          const length = settings.current.duration * (0.75 + Math.random() * 0.5);\n          letters[index]!.dataset.s = randomGlyph();\n          jobs.set(index, { end: now + delay + length, swapAt: now + swapGap() });\n          if (!ticking) {\n            ticking = true;\n            gsap.ticker.add(tick);\n          }\n        };\n\n        // Where each letter is, relative to the paragraph. Measured once, not on every pointer move.\n        const measure = () => {\n          const frame = box.getBoundingClientRect();\n          centres = letters.map((letter) => {\n            const r = letter.getBoundingClientRect();\n            return { x: r.left - frame.left + r.width / 2, y: r.top - frame.top + r.height / 2 };\n          });\n        };\n\n        const resize = new ResizeObserver(measure);\n        resize.observe(box);\n        let fontsDone = false;\n        document.fonts?.ready.then(() => {\n          if (!fontsDone) measure();\n        });\n\n        // The reveal: every letter starts as a random glyph and settles in reading order\n        const hideAll = () => {\n          letters.forEach((letter) => {\n            letter.dataset.s = randomGlyph();\n          });\n        };\n        const playReveal = () => {\n          jobs.forEach((_job, index) => delete letters[index]!.dataset.s);\n          jobs.clear();\n          const step = Math.min(stagger, 2 / letters.length);\n          letters.forEach((_letter, index) => scramble(index, index * step));\n          ready = true;\n        };\n\n        let view: IntersectionObserver | null = null;\n        if (wantsReveal) {\n          hideAll();\n          view = new IntersectionObserver(\n            ([entry]) => {\n              if (!entry) return;\n              if (entry.isIntersecting) {\n                playReveal();\n                if (once) view?.disconnect();\n              } else if (!once) {\n                // Left the screen: get ready to play again\n                jobs.clear();\n                hideAll();\n                ready = false;\n              }\n            },\n            { threshold: 0.35 },\n          );\n          view.observe(box);\n        }\n\n        // Hover: scramble every letter within `radius` of the path the pointer just travelled,\n        // so a fast flick leaves no gaps.\n        const touch = (x: number, y: number) => {\n          const from = last ?? { x, y };\n          const dx = x - from.x;\n          const dy = y - from.y;\n          const lengthSquared = dx * dx + dy * dy;\n          const reach = settings.current.radius;\n          centres.forEach((c, index) => {\n            if (jobs.has(index)) return;\n            const along = lengthSquared === 0 ? 0 : Math.max(0, Math.min(1, ((c.x - from.x) * dx + (c.y - from.y) * dy) / lengthSquared));\n            const ox = c.x - (from.x + dx * along);\n            const oy = c.y - (from.y + dy * along);\n            if (ox * ox + oy * oy < reach * reach) scramble(index);\n          });\n          last = { x, y };\n        };\n\n        const onMove = (event: PointerEvent) => {\n          if (!ready || !event.isPrimary) return;\n          const frame = box.getBoundingClientRect();\n          touch(event.clientX - frame.left, event.clientY - frame.top);\n        };\n        const onLeave = () => {\n          last = null;\n        };\n\n        if (wantsHover) {\n          box.addEventListener(\"pointermove\", onMove);\n          box.addEventListener(\"pointerdown\", onMove);\n          box.addEventListener(\"pointerleave\", onLeave);\n          box.addEventListener(\"pointercancel\", onLeave);\n        }\n\n        return () => {\n          fontsDone = true;\n          gsap.ticker.remove(tick);\n          resize.disconnect();\n          view?.disconnect();\n          box.removeEventListener(\"pointermove\", onMove);\n          box.removeEventListener(\"pointerdown\", onMove);\n          box.removeEventListener(\"pointerleave\", onLeave);\n          box.removeEventListener(\"pointercancel\", onLeave);\n          flashes.forEach((flash) => flash.cancel());\n          flashes.clear();\n          jobs.clear();\n          // Put the real letters back, so a re-run (or a change of props) starts clean\n          letters.forEach((letter) => delete letter.dataset.s);\n        };\n      });\n\n      return () => mm.revert();\n    },\n    { scope: boxRef, dependencies: [text, mode, once, stagger], revertOnUpdate: true },\n  );\n\n  const words = text.trim().split(/\\s+/).filter(Boolean);\n\n  return (\n    <p\n      ref={boxRef}\n      className={`relative ${className}`}\n      style={{ fontSize, lineHeight, touchAction: \"pan-y\", \"--scramble-color\": scrambleColor } as CSSProperties}\n    >\n      {/* Screen readers get the real sentence once. The letters below are only the picture of it. */}\n      <span className=\"sr-only\">{text}</span>\n      <span aria-hidden=\"true\">\n        {words.map((word, w) => (\n          <Fragment key={`${w}-${word}`}>\n            {w > 0 ? \" \" : null}\n            {/* A word never breaks across lines */}\n            <span className=\"whitespace-nowrap\">\n              {Array.from(word).map((letter, i) => (\n                <span\n                  key={i}\n                  data-letter=\"\"\n                  className=\"relative data-[s]:text-transparent after:pointer-events-none after:absolute after:inset-x-0 after:top-0 after:text-center after:content-[attr(data-s)] after:text-[color:var(--scramble-color)]\"\n                >\n                  {letter}\n                </span>\n              ))}\n            </span>\n          </Fragment>\n        ))}\n      </span>\n    </p>\n  );\n}\n"}],"categories":["text","scramble","hover","reveal","gsap"],"docs":"import { TextScrambleReveal } from \"@/components/dimaac/text-scramble-reveal\". Give its parent a size: it fills it. Docs, playground and props: https://ui.dimaac.com/components/text-scramble-reveal","meta":{"tier":"free","preview":"https://ui.dimaac.com/components/text-scramble-reveal","credits":[]}}