{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"text-scramble","type":"registry:component","title":"Text scramble","description":"Hover a word and a block cursor reads it in, one letter at a time.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":[],"registryDependencies":[],"files":[{"path":"components/text-scramble.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useCallback, useEffect, useRef } from \"react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\n\nconst GLYPHS = \"abcdefghijklmnopqrstuvwxyz0123456789#%&*+=/<>\";\n// Head start before the first character settles, so the noise registers.\nconst LEAD = 180;\n// Each character settles this long after the one before it.\nconst STAGGER = 45;\n// New noise roughly 25 times a second. Changing it every frame reads as\n// flicker rather than decoding.\nconst TICK = 40;\n\n// One character cell wide, cap height on the baseline, so it sits exactly\n// where the letter it covers will land. Letter spacing skips inline blocks,\n// so the margin applies tracking-tight by hand to keep the width exact.\nconst CURSOR =\n  \"inline-block h-[0.72em] w-[1ch] mr-[-0.025em] bg-current align-baseline\";\n// Noise is quieter than the settled text, so the eye reads the decoded part\n// as the word and the rest as signal still coming in.\nconst AHEAD = \"opacity-35\";\n\nfunction noise(original: string) {\n  const glyph = GLYPHS[Math.floor(Math.random() * GLYPHS.length)];\n  return original === original.toUpperCase() ? glyph.toUpperCase() : glyph;\n}\n\n// Writes straight to the node every frame, so decoding never re-renders React.\nexport function useScramble<T extends HTMLElement>(text: string) {\n  const ref = useRef<T>(null);\n  const frame = useRef(0);\n  const reduceMotion = useReducedMotion();\n\n  useEffect(() => () => cancelAnimationFrame(frame.current), []);\n\n  const scramble = useCallback(() => {\n    const node = ref.current;\n    if (!node || reduceMotion) return;\n    cancelAnimationFrame(frame.current);\n\n    const chars = [...text];\n    const current = chars.map(noise);\n    const start = performance.now();\n    let lastTick = start;\n    let lastHead = -1;\n\n    // A block cursor reads the word in: decoded text behind it, a faint\n    // churn of noise ahead. Three nodes built once and rewritten in place,\n    // so a frame is at most two text writes.\n    const done = document.createTextNode(\"\");\n    const cursor = document.createElement(\"span\");\n    cursor.className = CURSOR;\n    const ahead = document.createElement(\"span\");\n    ahead.className = AHEAD;\n    node.replaceChildren(done, cursor, ahead);\n\n    const step = (now: number) => {\n      const elapsed = now - start;\n      const refresh = now - lastTick >= TICK;\n      if (refresh) lastTick = now;\n\n      // Characters settle strictly left to right, so everything before the\n      // first unsettled one is final.\n      let head = chars.length;\n      for (let i = 0; i < chars.length; i++) {\n        if (chars[i] !== \" \" && elapsed < LEAD + i * STAGGER) {\n          head = i;\n          break;\n        }\n      }\n      if (head === chars.length) {\n        node.textContent = text;\n        return;\n      }\n      if (refresh) current.forEach((_, i) => (current[i] = noise(chars[i])));\n      if (refresh || head !== lastHead) {\n        lastHead = head;\n        done.data = chars.slice(0, head).join(\"\");\n        // The cursor covers the character it is decoding, so the word keeps\n        // its exact width the whole way through.\n        ahead.textContent = chars\n          .map((char, i) => (char === \" \" ? \" \" : current[i]))\n          .slice(head + 1)\n          .join(\"\");\n      }\n      frame.current = requestAnimationFrame(step);\n    };\n    // Fill the first frame before hit testing, so the button never shrinks\n    // under a stationary pointer and retriggers pointerenter.\n    step(start);\n  }, [text, reduceMotion]);\n\n  return { ref, scramble };\n}\n\nfunction ScrambleItem({ index, label }: { index: number; label: string }) {\n  const { ref, scramble } = useScramble<HTMLSpanElement>(label);\n\n  return (\n    <li>\n      <button\n        type=\"button\"\n        onPointerEnter={scramble}\n        onFocus={scramble}\n        className=\"group flex items-baseline gap-4 font-mono text-3xl tracking-tight text-muted-foreground uppercase transition-[color] duration-150 ease-out outline-hidden hover:text-foreground focus-visible:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-foreground\"\n      >\n        <span className=\"text-xs tabular-nums\">\n          {String(index + 1).padStart(2, \"0\")}\n        </span>\n        {/* Mono is load-bearing here: every glyph is the same width, so the\n            word doesn't jitter sideways while it decodes. */}\n        <span className=\"sr-only\">{label}</span>\n        {/* Replaced animation nodes must not become pointer event targets. */}\n        <span ref={ref} aria-hidden className=\"pointer-events-none\">\n          {label}\n        </span>\n      </button>\n    </li>\n  );\n}\n\nconst ITEMS = [\"Work\", \"Lab\", \"Writing\", \"Contact\"];\n\nexport default function TextScrambleDemo() {\n  return (\n    <ul className=\"flex flex-col gap-2\">\n      {ITEMS.map((label, i) => (\n        <ScrambleItem key={label} index={i} label={label} />\n      ))}\n    </ul>\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"}],"categories":["text"],"docs":"From ui lab: https://lab.xevrion.dev/lab/text-scramble"}