{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"text-morph","type":"registry:component","title":"Text Morph","description":"Text that morphs between strings: shared letters glide into place while new ones spring up one by one and old ones drop away. For button states.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","motion","tailwind-merge"],"registryDependencies":[],"docs":"Text Morph: usage, props and types at https://beui.dev/micro-interactions/text-morph.md","files":[{"path":"components/motion/text-morph.tsx","type":"registry:component","target":"@components/motion/text-morph.tsx","content":"\"use client\";\n// beui.dev/micro-interactions/text-morph\n\nimport { AnimatePresence, animate, motion, useReducedMotion } from \"motion/react\";\nimport { useLayoutEffect, useRef, useState } from \"react\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface TextMorphProps {\n  /** The text to show. Changing it morphs from the previous string. */\n  children: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\ntype Glyph = { id: number; char: string };\n\ntype Morph = {\n  text: string;\n  glyphs: Glyph[];\n  nextId: number;\n  /** For each new glyph, the kept neighbour it travels in with. */\n  enterAnchor: Map<number, number>;\n  /** For each leaving glyph, the kept neighbour it rides out with. */\n  leaveAnchor: Map<number, number>;\n  /** Arrival order of new glyphs, left to right. */\n  enterOrder: Map<number, number>;\n  /** Departure order of leaving glyphs, last letter first. */\n  leaveOrder: Map<number, number>;\n};\n\n// Letters arrive one at a time and spring up into place. This spring is a\n// little looser than SPRING_SWAP on purpose: a small settle on each letter is\n// what makes the sequence read as letters landing rather than a fade.\nconst SPRING_LETTER = { type: \"spring\", stiffness: 520, damping: 22, mass: 0.6 } as const;\nconst STAGGER_IN = 0.035;\n// Leaving letters go faster than new ones arrive, so the exit never holds up the entry.\nconst STAGGER_OUT = 0.02;\nconst RISE = 8;\nconst FADE_IN = { duration: 0.16, ease: EASE_OUT } as const;\nconst FADE_OUT = { duration: 0.12, ease: EASE_OUT } as const;\n\n/** Index pairs (old, new) of the longest common subsequence of two lists. */\nfunction lcsPairs(a: string[], b: string[]): [number, number][] {\n  const cols = b.length + 1;\n  const table = new Uint16Array((a.length + 1) * cols);\n  for (let i = a.length - 1; i >= 0; i--) {\n    for (let j = b.length - 1; j >= 0; j--) {\n      table[i * cols + j] =\n        a[i] === b[j]\n          ? table[(i + 1) * cols + j + 1] + 1\n          : Math.max(table[(i + 1) * cols + j], table[i * cols + j + 1]);\n    }\n  }\n  const pairs: [number, number][] = [];\n  let i = 0;\n  let j = 0;\n  while (i < a.length && j < b.length) {\n    if (a[i] === b[j]) {\n      pairs.push([i, j]);\n      i++;\n      j++;\n    } else if (table[(i + 1) * cols + j] >= table[i * cols + j + 1]) i++;\n    else j++;\n  }\n  return pairs;\n}\n\n/** The nearest id in `ids` that is kept, searching one way first and then the other. */\nfunction nearestKept(index: number, ids: number[], kept: Set<number>, forwardFirst: boolean) {\n  const scan = (step: number) => {\n    for (let k = index + step; k >= 0 && k < ids.length; k += step) {\n      if (kept.has(ids[k])) return ids[k];\n    }\n    return undefined;\n  };\n  return forwardFirst ? (scan(1) ?? scan(-1)) : (scan(-1) ?? scan(1));\n}\n\nfunction firstMorph(text: string): Morph {\n  const glyphs = Array.from(text, (char, id) => ({ id, char }));\n  return {\n    text,\n    glyphs,\n    nextId: glyphs.length,\n    enterAnchor: new Map(),\n    leaveAnchor: new Map(),\n    enterOrder: new Map(),\n    leaveOrder: new Map(),\n  };\n}\n\n/**\n * Pairs the old glyphs with the new string by their longest common\n * subsequence: paired glyphs keep their id (and their element), the rest\n * leave or arrive, each tied to the nearest glyph that stays.\n */\nfunction nextMorph(previous: Morph, text: string): Morph {\n  const chars = Array.from(text);\n  const pairs = lcsPairs(\n    previous.glyphs.map((glyph) => glyph.char),\n    chars,\n  );\n  const reuse = new Map(pairs.map(([o, n]) => [n, previous.glyphs[o].id]));\n  let nextId = previous.nextId;\n  const glyphs = chars.map((char, index) => ({ id: reuse.get(index) ?? nextId++, char }));\n\n  const kept = new Set(reuse.values());\n  const oldIds = previous.glyphs.map((glyph) => glyph.id);\n  const newIds = glyphs.map((glyph) => glyph.id);\n  const leaveAnchor = new Map<number, number>();\n  oldIds.forEach((id, index) => {\n    if (kept.has(id)) return;\n    const anchor = nearestKept(index, oldIds, kept, true);\n    if (anchor !== undefined) leaveAnchor.set(id, anchor);\n  });\n  const enterAnchor = new Map<number, number>();\n  newIds.forEach((id, index) => {\n    if (kept.has(id)) return;\n    const anchor = nearestKept(index, newIds, kept, false);\n    if (anchor !== undefined) enterAnchor.set(id, anchor);\n  });\n  const enterOrder = new Map(newIds.filter((id) => !kept.has(id)).map((id, order) => [id, order]));\n  const leaveOrder = new Map(\n    oldIds\n      .filter((id) => !kept.has(id))\n      .reverse()\n      .map((id, order) => [id, order]),\n  );\n  return { text, glyphs, nextId, enterAnchor, leaveAnchor, enterOrder, leaveOrder };\n}\n\n/** The x a glyph is drawn at right now, mid-slide included. */\nfunction drawnX(el: HTMLElement) {\n  const transform = getComputedStyle(el).transform;\n  return transform && transform !== \"none\" ? new DOMMatrixReadOnly(transform).m41 : 0;\n}\n\n/**\n * Morphs one string into another. Letters the two strings share (paired by\n * their longest common subsequence) glide on a spring from where they are\n * drawn to their new place. Letters that leave ride along with their nearest\n * neighbour that stays while they shrink and fade; new letters grow in from\n * where theirs came from; the box springs to the new width. A change mid-morph\n * retargets every spring from where it is.\n */\nexport function TextMorph({ children: text, className }: TextMorphProps) {\n  const reduce = Boolean(useReducedMotion());\n  const [morph, setMorph] = useState(() => firstMorph(text));\n  // Derive the next morph during render, so the new glyphs and their ids\n  // land in the same commit as the text.\n  let current = morph;\n  if (morph.text !== text) {\n    current = nextMorph(morph, text);\n    setMorph(current);\n  }\n\n  const rootRef = useRef<HTMLSpanElement>(null);\n  const nodes = useRef(new Map<number, HTMLSpanElement>());\n  // Each glyph's layout x inside the root from the last commit, transforms excluded.\n  const layout = useRef(new Map<number, number>());\n  const [width, setWidth] = useState<number>();\n\n  useLayoutEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const origin = root.getBoundingClientRect().left;\n    const next = new Map<number, number>();\n    for (const glyph of current.glyphs) {\n      const el = nodes.current.get(glyph.id);\n      if (el) next.set(glyph.id, el.getBoundingClientRect().left - origin - drawnX(el));\n    }\n    const before = layout.current;\n    layout.current = next;\n    setWidth(root.offsetWidth);\n    if (reduce || before.size === 0) return;\n\n    const travel = (id: number) => {\n      const from = before.get(id);\n      const to = next.get(id);\n      return from === undefined || to === undefined ? 0 : to - from;\n    };\n\n    for (const glyph of current.glyphs) {\n      const el = nodes.current.get(glyph.id);\n      if (!el) continue;\n      if (before.has(glyph.id)) {\n        // Kept: jump back to where it is drawn, then spring to the new place.\n        const from = drawnX(el) - travel(glyph.id);\n        if (Math.abs(from) > 0.5) animate(el, { x: [from, 0] }, SPRING_LAYOUT);\n      } else {\n        // New: start where its anchor came from and travel in with it.\n        const anchor = current.enterAnchor.get(glyph.id);\n        const from = anchor === undefined ? 0 : -travel(anchor);\n        if (Math.abs(from) > 0.5) animate(el, { x: [from, 0] }, SPRING_LAYOUT);\n      }\n    }\n    // Leaving: popLayout has pinned them where they were; ride the anchor out.\n    for (const [id, anchor] of current.leaveAnchor) {\n      const el = nodes.current.get(id);\n      const shift = travel(anchor);\n      if (el && Math.abs(shift) > 0.5) animate(el, { x: drawnX(el) + shift }, SPRING_LAYOUT);\n    }\n  }, [current, reduce]);\n\n  return (\n    <motion.span\n      initial={false}\n      animate={width === undefined ? undefined : { width }}\n      transition={reduce ? { duration: 0 } : SPRING_SWAP}\n      className={cn(\"inline-block whitespace-pre\", className)}\n    >\n      <span className=\"sr-only\">{text}</span>\n      <span ref={rootRef} aria-hidden=\"true\" className=\"relative inline-flex whitespace-pre\">\n        {/* `custom` hands the latest morph to leaving letters too, so each\n            one knows its place in the departure order. */}\n        <AnimatePresence initial={false} mode=\"popLayout\" custom={current}>\n          {current.glyphs.map((glyph) => (\n            <motion.span\n              key={glyph.id}\n              ref={(node: HTMLSpanElement | null) => {\n                if (node) nodes.current.set(glyph.id, node);\n                else nodes.current.delete(glyph.id);\n              }}\n              className=\"inline-block\"\n              custom={current}\n              variants={{\n                // Each new letter springs up from just below, on its own beat.\n                enter: { opacity: 0, y: reduce ? 0 : RISE },\n                shown: (morph: Morph) => {\n                  const delay = reduce ? 0 : (morph.enterOrder.get(glyph.id) ?? 0) * STAGGER_IN;\n                  return {\n                    opacity: 1,\n                    y: 0,\n                    transition: { y: { ...SPRING_LETTER, delay }, opacity: { ...FADE_IN, delay } },\n                  };\n                },\n                // Leaving letters drop back down the way new ones rise, last letter first.\n                gone: (morph: Morph) => {\n                  const delay = reduce ? 0 : (morph.leaveOrder.get(glyph.id) ?? 0) * STAGGER_OUT;\n                  return {\n                    opacity: 0,\n                    y: reduce ? 0 : RISE,\n                    transition: { y: { ...SPRING_LETTER, delay }, opacity: { ...FADE_OUT, delay } },\n                  };\n                },\n              }}\n              initial=\"enter\"\n              animate=\"shown\"\n              exit=\"gone\"\n            >\n              {glyph.char}\n            </motion.span>\n          ))}\n        </AnimatePresence>\n      </span>\n    </motion.span>\n  );\n}\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps — label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances — modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides — pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) — critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"}]}