{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "magnet-letters",
  "title": "Magnet Letters",
  "description": "A wrong word is repelled by magnet and the right word drops in: 'Launch videos, in code.'.",
  "dependencies": ["remotion", "@remotion/google-fonts"],
  "files": [
    {
      "path": "registry/remocn/magnet-letters/index.tsx",
      "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Figtree\";\nimport { useLayoutEffect, useRef, useState } from \"react\";\nimport {\n  AbsoluteFill,\n  continueRender,\n  delayRender,\n  Easing,\n  interpolate,\n  useCurrentFrame,\n  useVideoConfig,\n} from \"remotion\";\n\nconst face = loadFont(\"normal\", { weights: [\"400\"], subsets: [\"latin\"] });\n\nexport interface MagnetLettersProps {\n  /** Text before the word that gets swapped. Keep the trailing space. */\n  before?: string;\n  /** The right word. It drops in once the wrong one is repelled. */\n  word?: string;\n  /** Text after the swapped word. */\n  after?: string;\n  /** The wrong word the magnet pulls into line first, then repels. */\n  wrongWord?: string;\n  /** Magnet body, landing ticks and the right word. */\n  accent?: string;\n  theme?: \"dark\" | \"light\";\n  speed?: number;\n}\n\nconst THEMES = {\n  light: {\n    bg: \"#FAFAF9\",\n    fg: \"#0E0E0D\",\n    tipA: \"#C9C9C4\",\n    tipB: \"#8F8F8A\",\n  },\n  dark: {\n    bg: \"#0A0A0A\",\n    fg: \"#F2F2F0\",\n    tipA: \"#DCDCD8\",\n    tipB: \"#8A8A86\",\n  },\n} as const;\n\nconst EASE_OUT = Easing.bezier(0.22, 1, 0.36, 1);\nconst EASE_IN_OUT = Easing.bezier(0.65, 0, 0.35, 1);\nconst EASE_SWEEP = Easing.bezier(0.45, 0, 0.4, 1);\nconst EASE_PULL = Easing.bezier(0.55, 0, 0.9, 0.5);\nconst EASE_EXIT = Easing.bezier(0.55, 0, 0.8, 0.4);\nconst clamp = { extrapolateLeft: \"clamp\", extrapolateRight: \"clamp\" } as const;\n\n// Beats, in frames at 30fps (before `speed`).\nconst IN = 0;\nconst MAG_IN = 10;\nconst SWEEP = 32;\nconst SWEEP_END = 90;\nconst RETURN = 98;\nconst RETURN_END = 118;\nconst FLIP = 120;\nconst FLIP_LEN = 9;\nconst REPEL = 128;\nconst REPEL_LEN = 24;\nconst REFLOW = 136;\nconst REFLOW_LEN = 20;\nconst FLIP_BACK = 142;\nconst DROP = 152;\nconst DROP_STAGGER = 4;\nconst FALL = 11;\nconst EXIT = 190;\nconst EXIT_LEN = 26;\n\n/** Frames a letter takes from rest to the baseline once the magnet reaches it. */\nconst SNAP = 8;\nconst LINE_HEIGHT = 1.2;\n\ninterface Row {\n  xs: number[];\n  ws: number[];\n  w: number;\n}\n\ninterface Layout {\n  a: Row;\n  b: Row;\n  baseline: number;\n  rowH: number;\n}\n\ntype Kind = \"pre\" | \"wrong\" | \"right\" | \"post\";\n\ninterface Item {\n  ch: string;\n  kind: Kind;\n  /** Index in the wrong row, or -1. */\n  ia: number;\n  /** Index in the right row, or -1. */\n  ib: number;\n  /** Index inside its own word, for staggers. */\n  k: number;\n  n: number;\n}\n\n/** Deterministic 0..1 noise. */\nfunction hash(n: number) {\n  const s = Math.sin(n * 127.1 + 311.7) * 43758.5453;\n  return s - Math.floor(s);\n}\n\nfunction sameLayout(a: Layout | null, b: Layout) {\n  return (\n    a !== null &&\n    a.a.xs.join() === b.a.xs.join() &&\n    a.b.xs.join() === b.b.xs.join() &&\n    a.baseline === b.baseline\n  );\n}\n\n/** Flat horseshoe magnet, poles up, centred on x = 0, top of the poles at y = 0. */\nfunction Magnet({\n  size,\n  body,\n  tipA,\n  tipB,\n}: {\n  size: number;\n  body: string;\n  tipA: string;\n  tipB: string;\n}) {\n  const T = 0.2 * size;\n  const r = 0.22 * size;\n  const tip = 0.15 * size;\n  const arm = 0.2 * size;\n  const w = 2 * r + T;\n  const h = tip + arm + r + T / 2;\n  return (\n    <svg\n      viewBox={`${-w / 2} 0 ${w} ${h}`}\n      width={w}\n      height={h}\n      style={{ display: \"block\", overflow: \"visible\" }}\n      aria-hidden\n    >\n      <path\n        d={`M ${-r} ${tip - 0.5} L ${-r} ${tip + arm} A ${r} ${r} 0 0 0 ${r} ${tip + arm} L ${r} ${tip - 0.5}`}\n        fill=\"none\"\n        stroke={body}\n        strokeWidth={T}\n      />\n      <rect x={-r - T / 2} y={0} width={T} height={tip} fill={tipA} />\n      <rect x={r - T / 2} y={0} width={T} height={tip} fill={tipB} />\n    </svg>\n  );\n}\n\nexport function MagnetLetters({\n  before = \"Launch \",\n  word = \"videos\",\n  after = \", in code.\",\n  wrongWord = \"slides\",\n  accent = \"#3B5BFD\",\n  theme = \"dark\",\n  speed = 1,\n}: MagnetLettersProps) {\n  const frame = useCurrentFrame() * speed;\n  const { width, height } = useVideoConfig();\n  const t = THEMES[theme];\n\n  const em = Math.round(width * 0.07);\n  const textStyle = {\n    fontFamily: face.fontFamily,\n    fontSize: em,\n    fontWeight: 400,\n    letterSpacing: \"-0.03em\",\n    lineHeight: LINE_HEIGHT,\n    whiteSpace: \"pre\",\n  } as const;\n\n  const pre = Array.from(before);\n  const wrong = Array.from(wrongWord);\n  const right = Array.from(word);\n  const post = Array.from(after);\n  const rowA = [...pre, ...wrong, ...post];\n  const rowB = [...pre, ...right, ...post];\n\n  const aRef = useRef<HTMLDivElement>(null);\n  const bRef = useRef<HTMLDivElement>(null);\n  const baseRef = useRef<HTMLSpanElement>(null);\n  const [layout, setLayout] = useState<Layout | null>(null);\n  const [handle] = useState(() => delayRender(\"magnet-letters: measuring\"));\n  const released = useRef(false);\n\n  // biome-ignore lint/correctness/useExhaustiveDependencies: re-measure when the copy or size changes\n  useLayoutEffect(() => {\n    let live = true;\n    face\n      .waitUntilDone()\n      .catch(() => undefined)\n      .then(() => document.fonts.ready)\n      .then(() => {\n        if (!live) return;\n        const a = aRef.current;\n        const b = bRef.current;\n        const base = baseRef.current;\n        if (a && b && base) {\n          const read = (row: HTMLDivElement): Row => {\n            const r = row.getBoundingClientRect();\n            const scale = r.width / row.offsetWidth || 1;\n            const spans = Array.from(row.querySelectorAll(\"[data-l]\"));\n            return {\n              xs: spans.map(\n                (el) => (el.getBoundingClientRect().left - r.left) / scale,\n              ),\n              ws: spans.map((el) => el.getBoundingClientRect().width / scale),\n              w: row.offsetWidth,\n            };\n          };\n          const next: Layout = {\n            a: read(a),\n            b: read(b),\n            baseline: base.offsetTop,\n            rowH: a.offsetHeight,\n          };\n          setLayout((prev) => (sameLayout(prev, next) ? prev : next));\n        }\n        if (!released.current) {\n          released.current = true;\n          continueRender(handle);\n        }\n      });\n    return () => {\n      live = false;\n    };\n  }, [before, word, after, wrongWord, em, handle]);\n\n  const L = layout;\n  const wA = L?.a.w ?? 0;\n  const wB = L?.b.w ?? 0;\n  const leftA = width / 2 - wA / 2;\n  const leftB = width / 2 - wB / 2;\n  const baseY = height / 2 + em * 0.2;\n  const rowTop = baseY - (L?.baseline ?? em);\n\n  const ax = (i: number) => leftA + (L?.a.xs[i] ?? 0);\n  const bx = (i: number) => leftB + (L?.b.xs[i] ?? 0);\n  const acx = (i: number) => ax(i) + (L?.a.ws[i] ?? 0) / 2;\n  const bcx = (i: number) => bx(i) + (L?.b.ws[i] ?? 0) / 2;\n\n  const items: Item[] = [];\n  const push = (ch: string, kind: Kind, ia: number, ib: number, k: number) =>\n    items.push({ ch, kind, ia, ib, k, n: items.length });\n  pre.forEach((ch, i) => {\n    push(ch, \"pre\", i, i, i);\n  });\n  wrong.forEach((ch, i) => {\n    push(ch, \"wrong\", pre.length + i, -1, i);\n  });\n  right.forEach((ch, i) => {\n    push(ch, \"right\", -1, pre.length + i, i);\n  });\n  post.forEach((ch, i) => {\n    push(\n      ch,\n      \"post\",\n      pre.length + wrong.length + i,\n      pre.length + right.length + i,\n      i,\n    );\n  });\n\n  const wrongCentre =\n    wrong.length > 0\n      ? (ax(pre.length) +\n          ax(pre.length + wrong.length - 1) +\n          (L?.a.ws[pre.length + wrong.length - 1] ?? 0)) /\n        2\n      : leftA + wA / 2;\n  const rightCentre =\n    right.length > 0\n      ? (bx(pre.length) +\n          bx(pre.length + right.length - 1) +\n          (L?.b.ws[pre.length + right.length - 1] ?? 0)) /\n        2\n      : leftB + wB / 2;\n\n  // The magnet: glides in, sweeps the line, returns to the wrong word,\n  // follows the reflow to the right word's slot, then glides off.\n  const startX = leftA - em * 0.45;\n  const endX = leftA + wA + em * 0.35;\n  const magnetX = (f: number) => {\n    if (f < SWEEP)\n      return interpolate(f, [MAG_IN, SWEEP], [-em, startX], {\n        ...clamp,\n        easing: EASE_OUT,\n      });\n    if (f < RETURN)\n      return interpolate(f, [SWEEP, SWEEP_END], [startX, endX], {\n        ...clamp,\n        easing: EASE_SWEEP,\n      });\n    if (f < REFLOW)\n      return interpolate(f, [RETURN, RETURN_END], [endX, wrongCentre], {\n        ...clamp,\n        easing: EASE_IN_OUT,\n      });\n    if (f < EXIT)\n      return interpolate(\n        f,\n        [REFLOW, REFLOW + REFLOW_LEN],\n        [wrongCentre, rightCentre],\n        { ...clamp, easing: EASE_IN_OUT },\n      );\n    return interpolate(f, [EXIT, EXIT + EXIT_LEN], [rightCentre, width + em], {\n      ...clamp,\n      easing: EASE_EXIT,\n    });\n  };\n  // A letter lands a couple of frames after the magnet passes under it.\n  const landAt = (cx: number) => {\n    for (let f = SWEEP; f <= SWEEP_END; f++) if (magnetX(f) >= cx) return f + 2;\n    return SWEEP_END + 2;\n  };\n\n  const flipA = interpolate(frame, [FLIP, FLIP + FLIP_LEN], [0, 1], {\n    ...clamp,\n    easing: EASE_IN_OUT,\n  });\n  const flipB = interpolate(frame, [FLIP_BACK, FLIP_BACK + FLIP_LEN], [0, 1], {\n    ...clamp,\n    easing: EASE_IN_OUT,\n  });\n  const magnetScaleX = Math.cos(Math.PI * (flipA + flipB));\n  const reflow = interpolate(frame, [REFLOW, REFLOW + REFLOW_LEN], [0, 1], {\n    ...clamp,\n    easing: EASE_IN_OUT,\n  });\n\n  const bump = (land: number) => {\n    const d = frame - land;\n    if (d < 0 || d > 7) return 0;\n    return Math.sin((Math.PI * d) / 7) * (1 - d / 9);\n  };\n\n  const ticks: { x: number; land: number; key: string }[] = [];\n\n  const glyphs = items.map((it) => {\n    if (it.ch === \" \") return null;\n    const seed = it.n + 1;\n    const wGlyph =\n      it.kind === \"right\" ? (L?.b.ws[it.ib] ?? 0) : (L?.a.ws[it.ia] ?? 0);\n    let x = 0;\n    let y = 0;\n    let rot = 0;\n    let sx = 1;\n    let sy = 1;\n    let opacity = 1;\n    let blur = 0;\n\n    if (it.kind === \"right\") {\n      const start = DROP + it.k * DROP_STAGGER;\n      const land = start + FALL;\n      const p = interpolate(frame, [start, land], [0, 1], clamp);\n      x = bx(it.ib);\n      y = -em * 1.7 * (1 - p * p);\n      rot = (hash(seed * 4.3) - 0.5) * 18 * (1 - p);\n      opacity = interpolate(p, [0, 0.45], [0, 1], clamp);\n      blur = (1 - opacity) * 6;\n      const b = bump(land);\n      sx = 1 + 0.03 * b;\n      sy = 1 - 0.06 * b;\n      ticks.push({ x: bcx(it.ib), land, key: `r${it.n}` });\n    } else {\n      const land = landAt(acx(it.ia));\n      const home =\n        it.kind === \"wrong\"\n          ? ax(it.ia)\n          : interpolate(reflow, [0, 1], [ax(it.ia), bx(it.ib)]);\n      // Scattered on three loose tiers so neighbours never sit on top of each other.\n      const dx = (hash(seed * 3.1) - 0.5) * 0.35 * em;\n      const dy = -(0.35 + (it.n % 3) * 0.62 + hash(seed * 7.7) * 0.3) * em;\n      const r0 = (hash(seed * 5.3) - 0.5) * 40;\n      const lean = interpolate(frame, [land - SNAP - 10, land - SNAP], [0, 1], {\n        ...clamp,\n        easing: EASE_IN_OUT,\n      });\n      const q = interpolate(frame, [land - SNAP, land], [0, 1], {\n        ...clamp,\n        easing: EASE_PULL,\n      });\n      const fadeIn = interpolate(\n        frame,\n        [IN + hash(seed * 9.1) * 14, IN + hash(seed * 9.1) * 14 + 16],\n        [0, 1],\n        { ...clamp, easing: EASE_OUT },\n      );\n      x = home + (dx - dx * 0.1 * lean) * (1 - q);\n      y = (dy + em * 0.08 * lean + em * 0.2 * (1 - fadeIn)) * (1 - q);\n      rot = r0 * (1 - 0.18 * lean) * (1 - q);\n      opacity = fadeIn;\n      blur = (1 - fadeIn) * 8;\n      const b = bump(land);\n      sx = 1 + 0.03 * b;\n      sy = 1 - 0.06 * b;\n      ticks.push({ x: acx(it.ia), land, key: `a${it.n}` });\n\n      if (it.kind === \"wrong\") {\n        // Repelled: the word lifts off the line as a unit, then the letters\n        // fan out upwards from the magnet and dissolve.\n        const n = wrong.length;\n        const side = n > 1 ? it.k / (n - 1) - 0.5 : 0;\n        const delay = Math.abs(side) * 4;\n        const rp = interpolate(\n          frame,\n          [REPEL + delay, REPEL + delay + REPEL_LEN],\n          [0, 1],\n          clamp,\n        );\n        const e = EASE_OUT(rp);\n        x += side * em * 1.1 * e;\n        y +=\n          -em * 0.06 * flipA -\n          em * (1.6 + hash(seed * 2.9) * 0.6 - Math.abs(side) * 0.6) * e;\n        rot += side * (30 + hash(seed * 6.1) * 20) * e;\n        opacity *= 1 - interpolate(rp, [0.25, 0.85], [0, 1], clamp);\n        blur += interpolate(rp, [0.2, 0.85], [0, 10], clamp);\n      }\n    }\n\n    return (\n      <span\n        key={it.n}\n        style={{\n          ...textStyle,\n          position: \"absolute\",\n          left: x,\n          top: rowTop,\n          color: it.kind === \"right\" ? accent : t.fg,\n          opacity,\n          filter: blur > 0.05 ? `blur(${blur}px)` : undefined,\n          transformOrigin: `${wGlyph / 2}px ${L?.baseline ?? em}px`,\n          transform: `translateY(${y}px) rotate(${rot}deg) scale(${sx}, ${sy})`,\n        }}\n      >\n        {it.ch}\n      </span>\n    );\n  });\n\n  const hair = Math.max(1.5, width / 640);\n  const mx = magnetX(frame);\n\n  return (\n    <AbsoluteFill style={{ background: t.bg, overflow: \"hidden\" }}>\n      {/* measuring rows: never shown */}\n      <div style={{ position: \"absolute\", visibility: \"hidden\", top: 0 }}>\n        <div ref={aRef} style={{ ...textStyle, display: \"inline-block\" }}>\n          {rowA.map((ch, i) => (\n            <span key={i} data-l=\"\">\n              {ch}\n            </span>\n          ))}\n          <span\n            ref={baseRef}\n            style={{ display: \"inline-block\", width: 0, height: 0 }}\n          />\n        </div>\n        <br />\n        <div ref={bRef} style={{ ...textStyle, display: \"inline-block\" }}>\n          {rowB.map((ch, i) => (\n            <span key={i} data-l=\"\">\n              {ch}\n            </span>\n          ))}\n        </div>\n      </div>\n\n      <div style={{ position: \"absolute\", inset: 0, opacity: L ? 1 : 0 }}>\n        {ticks.map((tk) => {\n          const d = frame - tk.land;\n          if (d < 0 || d > 24) return null;\n          const grow = interpolate(d, [0, 3], [0, 1], {\n            ...clamp,\n            easing: EASE_OUT,\n          });\n          const fade = interpolate(d, [6, 24], [1, 0], clamp);\n          return (\n            <div\n              key={tk.key}\n              style={{\n                position: \"absolute\",\n                left: tk.x - hair / 2,\n                top: baseY + em * 0.1,\n                width: hair,\n                height: em * 0.13 * grow,\n                background: accent,\n                opacity: fade,\n              }}\n            />\n          );\n        })}\n\n        {glyphs}\n\n        <div\n          style={{\n            position: \"absolute\",\n            left: mx,\n            top: baseY + em * 0.36,\n            transform: `translateX(-50%) scaleX(${magnetScaleX})`,\n          }}\n        >\n          <Magnet size={em} body={accent} tipA={t.tipA} tipB={t.tipB} />\n        </div>\n      </div>\n    </AbsoluteFill>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/remocn/magnet-letters.tsx"
    }
  ],
  "type": "registry:component"
}
