{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "recast",
  "type": "registry:ui",
  "title": "Recast",
  "description": "A word that re-forms into a new one: shared letters slide along the baseline to their new home while unique letters iris in and out, then tighten a hair into their final kerning. Real selectable text, announced politely on change; swaps instantly under reduced motion.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/default/text/recast/recast.tsx",
      "type": "registry:ui",
      "target": "components/crucible/recast.tsx",
      "content": "\"use client\";\n\nimport { AnimatePresence, motion, useAnimationControls, type Transition } from \"motion/react\";\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\n\nexport interface RecastProps extends Omit<React.ComponentPropsWithoutRef<\"span\">, \"children\"> {\n  /**\n   * The text to display. Whenever it changes, the word re-forms: shared letters\n   * slide to their new home while unique letters iris in/out.\n   */\n  children?: string;\n  /**\n   * Optional words to auto-cycle through. When provided, the component morphs\n   * between them on a timer (pausing offscreen and on hidden tabs) and\n   * `children` is ignored.\n   */\n  words?: string[];\n  /** Milliseconds each cycled word holds before re-forming into the next. @default 2600 */\n  interval?: number;\n  /** Restart from the first word after the last (cycle mode). @default true */\n  loop?: boolean;\n  /** Freeze cycling on the current word. @default false */\n  paused?: boolean;\n  /** Seconds the position morph / iris takes. @default 0.6 */\n  duration?: number;\n  /** Seconds between each entering/leaving letter's start. @default 0.016 */\n  stagger?: number;\n  /** Fired whenever a new word becomes current (cycle mode). */\n  onIndexChange?: (index: number) => void;\n}\n\n/** Occurrence-indexed keys so shared letters keep a stable identity across a\n *  morph (the second \"n\" in \"Continue\" stays the second \"n\"), which is what\n *  lets motion's layout engine slide them from their old slot to the new one\n *  instead of cross-fading. Letters with no match iris in/out. */\nfunction keyLetters(text: string): { key: string; char: string }[] {\n  const counts = new Map<string, number>();\n  const out: { key: string; char: string }[] = [];\n  for (const char of Array.from(text)) {\n    const n = counts.get(char) ?? 0;\n    counts.set(char, n + 1);\n    out.push({ key: `${char}\u0000${n}`, char });\n  }\n  return out;\n}\n\n/** Split into runs of word (non-space) vs. whitespace so the line only ever\n *  breaks at spaces — each word is its own nowrap group, never split mid-word. */\nfunction tokenize(text: string): { text: string; isSpace: boolean }[] {\n  const chars = Array.from(text);\n  const tokens: { text: string; isSpace: boolean }[] = [];\n  let i = 0;\n  while (i < chars.length) {\n    const isSpace = /\\s/.test(chars[i]!);\n    let j = i;\n    while (j < chars.length && /\\s/.test(chars[j]!) === isSpace) j++;\n    tokens.push({ text: chars.slice(i, j).join(\"\"), isSpace });\n    i = j;\n  }\n  return tokens;\n}\n\n/** One word slot. Owns its own kerning-settle so a phrase's words settle\n *  independently. Letters are keyed by identity; motion's `layout` FLIPs the\n *  survivors along the baseline while `AnimatePresence` iris-transitions the\n *  rest. Shared letters never touch opacity, so they stay fully legible. */\nfunction WordMorph({\n  text,\n  duration,\n  stagger,\n}: {\n  text: string;\n  duration: number;\n  stagger: number;\n}) {\n  const controls = useAnimationControls();\n  const letters = React.useMemo(() => keyLetters(text), [text]);\n  const isFirst = React.useRef(true);\n\n  // Kerning settle: once the letters have slid home, the word tightens by a\n  // hair into its final rest, like type seating in a form. Driven as a\n  // scaleX overshoot on the whole slot — a transform, so it never fights the\n  // letters' layout measurement. Skipped on the initial word.\n  React.useEffect(() => {\n    if (isFirst.current) {\n      isFirst.current = false;\n      return;\n    }\n    void controls.start(\n      { scaleX: [1.03, 1] },\n      { duration: duration * 0.8, delay: duration * 0.45, ease: [0.22, 1, 0.36, 1] }\n    );\n  }, [text, duration, controls]);\n\n  const positionTransition: Transition = { type: \"spring\", duration, bounce: 0.16 };\n\n  return (\n    <motion.span\n      animate={controls}\n      className=\"relative inline-block whitespace-nowrap align-baseline will-change-transform\"\n      style={{ transformOrigin: \"50% 60%\" }}\n    >\n      <AnimatePresence mode=\"popLayout\" initial={false}>\n        {letters.map(({ key, char }, i) => (\n          <motion.span\n            key={key}\n            layout\n            initial={{ opacity: 0, scale: 0.28 }}\n            animate={{ opacity: 1, scale: 1 }}\n            exit={{ opacity: 0, scale: 0.28 }}\n            transition={{\n              layout: positionTransition,\n              opacity: { duration: duration * 0.5, delay: i * stagger, ease: [0.4, 0, 0.2, 1] },\n              scale: { type: \"spring\", duration: duration * 0.7, bounce: 0.32, delay: i * stagger },\n            }}\n            className=\"inline-block whitespace-pre align-baseline will-change-[transform,opacity]\"\n          >\n            {char}\n          </motion.span>\n        ))}\n      </AnimatePresence>\n    </motion.span>\n  );\n}\n\n/**\n * Recast — a word that re-forms into a new one. When the text changes, letters\n * shared with the previous word slide along the baseline to their new home\n * while unique letters iris in and out, so the surviving letters stay legible\n * the whole way through (no blur, no scramble, no flash). The letters tighten a\n * hair into their final kerning once they arrive. Neutral monochrome — it\n * inherits the surrounding text color. The first word server-renders as plain\n * text; reduced motion swaps the text instantly.\n */\nexport function Recast({\n  children = \"\",\n  words,\n  interval = 2600,\n  loop = true,\n  paused = false,\n  duration = 0.6,\n  stagger = 0.016,\n  onIndexChange,\n  className,\n  ...props\n}: RecastProps) {\n  const reducedMotion = useReducedMotion();\n  const cycling = Array.isArray(words) && words.length > 0;\n\n  const [index, setIndex] = React.useState(0);\n  const [mounted, setMounted] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  const [inView, setInView] = React.useState(true);\n  const wrapperRef = React.useRef<HTMLSpanElement>(null);\n\n  const safeIndex = cycling ? Math.max(0, Math.min(index, words!.length - 1)) : 0;\n  const currentText = cycling ? words![safeIndex] ?? \"\" : children;\n\n  React.useEffect(() => {\n    setMounted(true);\n  }, []);\n\n  // Pause cycling on hidden tabs and offscreen — nothing runs at rest.\n  React.useEffect(() => {\n    if (!cycling) return;\n    const onVisibility = () => setHidden(document.hidden);\n    document.addEventListener(\"visibilitychange\", onVisibility);\n    return () => document.removeEventListener(\"visibilitychange\", onVisibility);\n  }, [cycling]);\n\n  React.useEffect(() => {\n    if (!cycling) return;\n    const node = wrapperRef.current;\n    if (!node || typeof IntersectionObserver === \"undefined\") return;\n    const observer = new IntersectionObserver(([entry]) => {\n      setInView(entry?.isIntersecting ?? true);\n    });\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, [cycling]);\n\n  React.useEffect(() => {\n    if (!cycling || paused || hidden || !inView || words!.length < 2) return;\n    if (!loop && safeIndex === words!.length - 1) return;\n    const id = window.setTimeout(() => {\n      setIndex((i) => (i + 1) % words!.length);\n    }, interval);\n    return () => window.clearTimeout(id);\n    // `words.length`, not `words`: an inline array literal is a new identity on\n    // every parent render and would otherwise restart the hold timer each time.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [cycling, safeIndex, paused, hidden, inView, loop, interval, words?.length]);\n\n  const onIndexChangeRef = React.useRef(onIndexChange);\n  React.useEffect(() => {\n    onIndexChangeRef.current = onIndexChange;\n  });\n  const isFirstIndex = React.useRef(true);\n  React.useEffect(() => {\n    if (isFirstIndex.current) {\n      isFirstIndex.current = false;\n      return;\n    }\n    onIndexChangeRef.current?.(safeIndex);\n  }, [safeIndex]);\n\n  // Before mount and under reduced motion: plain, static, selectable text —\n  // matches SSR exactly (no hydration mismatch) and never animates the first word.\n  const showMorph = mounted && !reducedMotion;\n\n  const tokens = React.useMemo(() => (showMorph ? tokenize(currentText) : []), [showMorph, currentText]);\n  let wordSlot = 0;\n\n  return (\n    <span\n      ref={wrapperRef}\n      className={cn(\"inline-block align-baseline\", className)}\n      {...props}\n    >\n      {/* Polite live region announces the current word on every change. */}\n      <span role=\"status\" aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n        {currentText}\n      </span>\n\n      {showMorph ? (\n        <span aria-hidden>\n          {tokens.map((token, i) =>\n            token.isSpace ? (\n              <span key={`s-${i}`} className=\"whitespace-pre\">\n                {token.text}\n              </span>\n            ) : (\n              <WordMorph\n                key={`w-${wordSlot++}`}\n                text={token.text}\n                duration={duration}\n                stagger={stagger}\n              />\n            )\n          )}\n        </span>\n      ) : (\n        <span aria-hidden>{currentText}</span>\n      )}\n    </span>\n  );\n}\n"
    }
  ]
}