{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "motion-text-scramble",
  "title": "Text scramble",
  "description": "Text that scrambles into place on mount, when it scrolls into view or on hover of its link.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json"
  ],
  "files": [
    {
      "path": "components/core/text-scramble.tsx",
      "content": "'use client';\nimport { Fragment, useEffect, useEffectEvent, useRef, useState } from 'react';\nimport { motion, MotionProps, useInView } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nimport { motionElementOf } from './motion-elements';\n\nexport type TextScrambleProps = {\n  children: string;\n  duration?: number;\n  speed?: number;\n  characterSet?: string;\n  as?: React.ElementType;\n  className?: string;\n  trigger?: boolean;\n  startOnView?: boolean;\n  replayOnHover?: boolean;\n  delay?: number;\n  stableWidth?: boolean;\n  onScrambleComplete?: () => void;\n} & MotionProps;\n\ntype Cell = {\n  index: number;\n  final: string;\n  shown: string;\n};\n\nconst defaultChars =\n  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\nconst INTERACTIVE_ANCESTOR = [\n  'a[href]',\n  'button',\n  'summary',\n  'label',\n  '[role=\"button\"]',\n  '[role=\"link\"]',\n  '[role=\"tab\"]',\n  '[role=\"menuitem\"]',\n  '[role=\"option\"]',\n].join(', ');\n\nfunction randomCharacterOf(characterSet: string) {\n  const sample = Math.random();\n  const position = sample * characterSet.length;\n  const index = Math.floor(position);\n  return characterSet[index];\n}\n\nfunction scrambledTextOf(text: string, progress: number, characterSet: string) {\n  const settledCount = progress * text.length;\n  let scrambled = '';\n  for (let index = 0; index < text.length; index += 1) {\n    const character = text[index];\n    const isSpace = character === ' ';\n    const isSettled = settledCount > index;\n    if (isSpace) {\n      scrambled += ' ';\n      continue;\n    }\n    if (isSettled) {\n      scrambled += character;\n      continue;\n    }\n    scrambled += randomCharacterOf(characterSet);\n  }\n  return scrambled;\n}\n\nfunction wordsOf(text: string, shown: string) {\n  const words: Cell[][] = [[]];\n  for (let index = 0; index < text.length; index += 1) {\n    const final = text[index];\n    if (final === ' ') {\n      words.push([]);\n      continue;\n    }\n    const lastWordIndex = words.length - 1;\n    const currentWord = words[lastWordIndex];\n    const shownCharacter = shown[index] ?? final;\n    currentWord.push({ index, final, shown: shownCharacter });\n  }\n  return words;\n}\n\nfunction isTouchPointer(event: PointerEvent) {\n  return event.pointerType === 'touch';\n}\n\nfunction isKeyboardFocus(event: FocusEvent) {\n  const target = event.target;\n  if (!(target instanceof Element)) {\n    return false;\n  }\n  return target.matches(':focus-visible');\n}\n\ntype StableLettersProps = {\n  text: string;\n  shown: string;\n};\n\n/** Each character keeps the width of its final letter, so the line never shifts while it scrambles. */\nfunction StableLetters({ text, shown }: StableLettersProps) {\n  const words = wordsOf(text, shown);\n\n  return words.map((word, wordIndex) => (\n    <Fragment key={wordIndex}>\n      {wordIndex > 0 && ' '}\n      <span className='whitespace-nowrap'>\n        {word.map((cell) => (\n          <span key={cell.index} className='inline-grid'>\n            <span className='invisible col-start-1 row-start-1'>\n              {cell.final}\n            </span>\n            <span className='col-start-1 row-start-1 text-center'>\n              {cell.shown}\n            </span>\n          </span>\n        ))}\n      </span>\n    </Fragment>\n  ));\n}\n\ntype ScrambleFaceProps = {\n  text: string;\n  shown: string;\n  stableWidth: boolean;\n};\n\nfunction ScrambleFace({ text, shown, stableWidth }: ScrambleFaceProps) {\n  if (stableWidth) {\n    return <StableLetters text={text} shown={shown} />;\n  }\n  return shown;\n}\n\nexport function TextScramble({\n  children,\n  duration = 0.8,\n  speed = 0.04,\n  characterSet = defaultChars,\n  className,\n  as: Component = 'p',\n  trigger = true,\n  startOnView = false,\n  replayOnHover = false,\n  delay = 0,\n  stableWidth = false,\n  onScrambleComplete,\n  ...props\n}: TextScrambleProps) {\n  const MotionComponent = motionElementOf(Component) as typeof motion.p;\n  const rootRef = useRef<HTMLParagraphElement>(null);\n  const [displayText, setDisplayText] = useState(children);\n  const [settledText, setSettledText] = useState(children);\n  const isAnimatingRef = useRef(false);\n  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);\n  const prefersReducedMotion = usePrefersReducedMotion();\n  const isInView = useInView(rootRef, { once: true });\n  const isWaitingForView = startOnView && !isInView;\n  const shouldStart = trigger && !isWaitingForView;\n\n  const hasNewText = children !== settledText;\n  if (hasNewText) {\n    setSettledText(children);\n    setDisplayText(children);\n  }\n\n  const showFrame = useEffectEvent((progress: number) => {\n    const frame = scrambledTextOf(children, progress, characterSet);\n    setDisplayText(frame);\n  });\n\n  const finish = useEffectEvent(() => {\n    if (intervalRef.current) {\n      clearInterval(intervalRef.current);\n    }\n    intervalRef.current = null;\n    setDisplayText(children);\n    isAnimatingRef.current = false;\n    onScrambleComplete?.();\n  });\n\n  const scramble = useEffectEvent(() => {\n    if (isAnimatingRef.current) return;\n\n    if (prefersReducedMotion) {\n      onScrambleComplete?.();\n      return;\n    }\n\n    isAnimatingRef.current = true;\n\n    const steps = duration / speed;\n    let step = 0;\n\n    const interval = setInterval(() => {\n      const progress = step / steps;\n      showFrame(progress);\n      step++;\n\n      if (step > steps) {\n        finish();\n      }\n    }, speed * 1000);\n\n    intervalRef.current = interval;\n  });\n\n  useEffect(() => {\n    if (!shouldStart) return;\n\n    if (delay <= 0) {\n      scramble();\n      return;\n    }\n\n    const delayMs = delay * 1000;\n    const timer = setTimeout(() => {\n      scramble();\n    }, delayMs);\n    return () => clearTimeout(timer);\n  }, [shouldStart, delay]);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!replayOnHover) {\n      return;\n    }\n    if (!root) {\n      return;\n    }\n    const activator = root.closest<HTMLElement>(INTERACTIVE_ANCESTOR);\n    if (!activator) {\n      return;\n    }\n    const handlePointerEnter = (event: PointerEvent) => {\n      if (isTouchPointer(event)) {\n        return;\n      }\n      scramble();\n    };\n    const handleFocusIn = (event: FocusEvent) => {\n      if (!isKeyboardFocus(event)) {\n        return;\n      }\n      scramble();\n    };\n    activator.addEventListener('pointerenter', handlePointerEnter);\n    activator.addEventListener('focusin', handleFocusIn);\n    return () => {\n      activator.removeEventListener('pointerenter', handlePointerEnter);\n      activator.removeEventListener('focusin', handleFocusIn);\n    };\n  }, [replayOnHover]);\n\n  useEffect(() => {\n    return () => {\n      if (intervalRef.current) {\n        clearInterval(intervalRef.current);\n      }\n    };\n  }, []);\n\n  return (\n    <MotionComponent ref={rootRef} className={className} {...props}>\n      <span className='sr-only'>{children}</span>\n      <span aria-hidden='true'>\n        <ScrambleFace\n          text={children}\n          shown={displayText}\n          stableWidth={stableWidth}\n        />\n      </span>\n    </MotionComponent>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/core/text-scramble.tsx"
    },
    {
      "path": "components/core/motion-elements.ts",
      "content": "import { motion } from 'motion/react';\n\nconst MOTION_ELEMENTS = {\n  a: motion.a,\n  article: motion.article,\n  aside: motion.aside,\n  blockquote: motion.blockquote,\n  button: motion.button,\n  code: motion.code,\n  div: motion.div,\n  em: motion.em,\n  figure: motion.figure,\n  footer: motion.footer,\n  h1: motion.h1,\n  h2: motion.h2,\n  h3: motion.h3,\n  h4: motion.h4,\n  h5: motion.h5,\n  h6: motion.h6,\n  header: motion.header,\n  label: motion.label,\n  li: motion.li,\n  main: motion.main,\n  nav: motion.nav,\n  ol: motion.ol,\n  p: motion.p,\n  pre: motion.pre,\n  section: motion.section,\n  small: motion.small,\n  span: motion.span,\n  strong: motion.strong,\n  ul: motion.ul,\n};\n\ntype MotionElementTag = keyof typeof MOTION_ELEMENTS;\n\nfunction isMotionElementTag(tag: unknown): tag is MotionElementTag {\n  const isString = typeof tag === 'string';\n  return isString && tag in MOTION_ELEMENTS;\n}\n\n/**\n * The motion version of an HTML tag. A lookup such as `motion[tag]` is invisible to the bundler,\n * which drops the tags it never sees and breaks the production build, so every tag is listed here.\n */\nexport function motionElementOf(tag: unknown) {\n  if (isMotionElementTag(tag)) {\n    return MOTION_ELEMENTS[tag];\n  }\n  return MOTION_ELEMENTS.div;\n}\n",
      "type": "registry:component",
      "target": "components/core/motion-elements.ts"
    }
  ],
  "categories": [
    "motion"
  ],
  "type": "registry:component"
}