{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "magnetic-letters",
  "type": "registry:component",
  "title": "Magnetic Letters",
  "description": "Every letter is pulled toward the cursor by a bouncy spring, tinting and growing as it gets close.",
  "author": "Marcelo Treviño Velázquez <https://furin.dev>",
  "dependencies": [],
  "categories": [
    "Text"
  ],
  "docs": "Installed in components/furin/magnetic-letters/. Docs, live controls and props table: https://furin.dev/components/magnetic-letters/",
  "files": [
    {
      "path": "registry/magnetic-letters/MagneticLetters.tsx",
      "content": "\"use client\";\nimport { useEffect, useRef } from \"react\";\nimport type { CSSProperties, RefObject } from \"react\";\nimport \"./MagneticLetters.css\";\n\nexport interface MagneticLettersProps {\n  /** El texto (acepta saltos de línea). */\n  children?: string;\n  /** Tamaño de la letra, en px. */\n  size?: number;\n  /** Radio de atracción del cursor, en px. */\n  radius?: number;\n  /** Cuánto se acerca cada letra al cursor, en proporción al tamaño (0.1 a 1). */\n  strength?: number;\n  /** Rigidez del resorte: más alto, más nervioso. */\n  stiffness?: number;\n  /** Cuando no hay cursor cerca, un imán invisible pasea por el texto. */\n  idle?: boolean;\n  /** Color del texto. */\n  color?: string;\n  /** Color al que se tiñen las letras atraídas. */\n  accent?: string;\n  /** Clase extra para el contenedor. */\n  className?: string;\n  /** Estilos extra para el contenedor. */\n  style?: CSSProperties;\n}\n\nfunction rgbDe(css: string, def: [number, number, number]): [number, number, number] {\n  try {\n    const c = document.createElement(\"canvas\");\n    c.width = c.height = 1;\n    const x = c.getContext(\"2d\", { willReadFrequently: true })!;\n    x.fillStyle = \"#000\";\n    x.fillStyle = css;\n    x.fillRect(0, 0, 1, 1);\n    const d = x.getImageData(0, 0, 1, 1).data;\n    return [d[0], d[1], d[2]];\n  } catch { return def; }\n}\n\n/** Si el texto no cabe en su contenedor, encoge la letra lo justo (se recalcula al cambiar el tamaño del contenedor). */\nfunction useAjuste(ref: RefObject<HTMLElement | null>, variable: string, dep: unknown) {\n  useEffect(() => {\n    const el = ref.current, padre = el?.parentElement;\n    if (!el || !padre) return;\n    let raf = 0;\n    const ajustar = () => {\n      el.style.setProperty(variable, \"1\");\n      const natural = el.scrollWidth;\n      const libre = padre.clientWidth - 28;\n      el.style.setProperty(variable, (natural > libre && libre > 40 ? Math.max(0.35, libre / natural) : 1).toFixed(3));\n    };\n    const pedir = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(ajustar); };\n    const ro = new ResizeObserver(pedir);\n    ro.observe(padre);\n    document.fonts?.ready.then(pedir);\n    pedir();\n    return () => { cancelAnimationFrame(raf); ro.disconnect(); };\n  }, [dep]);\n}\n\n/** Cada letra es atraída por el cursor con un resorte con rebote, y se tiñe y crece al acercarse. */\nexport function MagneticLetters({\n  children = \"Magnetic\",\n  size = 96,\n  radius = 170,\n  strength = 0.3,\n  stiffness = 210,\n  idle = true,\n  color = \"#E9EBEF\",\n  accent = \"#7CF5C6\",\n  className = \"\",\n  style,\n}: MagneticLettersProps) {\n  const rootRef = useRef<HTMLSpanElement>(null);\n  const texto = String(children ?? \"\");\n  useAjuste(rootRef, \"--furin-ml-fit\", texto + size);\n  const lineas = texto.split(\"\\n\");\n  const cfg = useRef({ size, radius, strength, stiffness, idle, color, accent });\n  cfg.current = { size, radius, strength, stiffness, idle, color, accent };\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const letras = Array.from(root.querySelectorAll<HTMLElement>(\"[data-l]\"));\n    const n = letras.length;\n    const reducido = matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    // Centro de cada letra en reposo, en coordenadas locales del contenedor (sin transformaciones).\n    const cx = new Float32Array(n), cy = new Float32Array(n);\n    const x = new Float32Array(n), y = new Float32Array(n), vx = new Float32Array(n), vy = new Float32Array(n);\n    const esc = new Float32Array(n), rot = new Float32Array(n), vesc = new Float32Array(n), vrot = new Float32Array(n);\n    const mezcla = new Float32Array(n);\n    const ptr = { x: 0, y: 0, activo: false };\n    let visible = true, raf = 0, muerto = false, ultimo = 0, t0 = performance.now();\n    let c0: [number, number, number] = [233, 235, 239], c1: [number, number, number] = [124, 245, 198];\n\n    const medir = () => {\n      for (let i = 0; i < n; i++) {\n        const l = letras[i];\n        cx[i] = l.offsetLeft + l.offsetWidth / 2;\n        cy[i] = l.offsetTop + l.offsetHeight / 2;\n      }\n      c0 = rgbDe(cfg.current.color, c0); c1 = rgbDe(cfg.current.accent, c1);\n    };\n\n    const pintar = () => {\n      for (let i = 0; i < n; i++) {\n        const m = mezcla[i];\n        const l = letras[i];\n        l.style.transform = `translate3d(${x[i].toFixed(2)}px, ${y[i].toFixed(2)}px, 0) rotate(${rot[i].toFixed(2)}deg) scale(${esc[i].toFixed(3)})`;\n        l.style.color = `rgb(${Math.round(c0[0] + (c1[0] - c0[0]) * m)}, ${Math.round(c0[1] + (c1[1] - c0[1]) * m)}, ${Math.round(c0[2] + (c1[2] - c0[2]) * m)})`;\n      }\n    };\n\n    const paso = (now: number) => {\n      raf = 0;\n      if (muerto || !visible) return;\n      const dt = Math.min(0.033, (now - (ultimo || now)) / 1000 || 0.016);\n      ultimo = now;\n      const { size: S, radius: R, strength: F, stiffness: K, idle: ocioso } = cfg.current;\n      const rr = root.getBoundingClientRect();\n      let px = NaN, py = NaN, fantasma = false;\n      if (ptr.activo) { px = ptr.x - rr.left; py = ptr.y - rr.top; }\n      else if (ocioso) {\n        // Un imán invisible que pasea de lado a lado, con un vaivén vertical lento.\n        const t = (now - t0) / 1000;\n        px = rr.width * (0.5 + 0.56 * Math.sin(t * 0.7));\n        py = rr.height * (0.5 + 0.35 * Math.sin(t * 1.13 + 1));\n        fantasma = true;\n      }\n      const C = 2 * Math.sqrt(K) * 0.52; // amortiguamiento: ζ ≈ 0.52, con rebote visible pero sin montarse\n      let mueve = false;\n      const sub = 2, h = dt / sub;\n      for (let i = 0; i < n; i++) {\n        let tx = 0, ty = 0, te = 1, tr = 0, tm = 0;\n        if (px === px) {\n          const dx = px - cx[i], dy = py - cy[i];\n          const d = Math.hypot(dx, dy);\n          if (d < R) {\n            let f = 1 - d / R; f = f * f * (3 - 2 * f);\n            // Atracción máxima a media distancia; justo bajo el cursor la letra casi no se mueve, así no se encimen.\n            const pull = Math.min(d * 0.7, S * F * f * (d / (d + R * 0.28)) * 1.2);\n            // En horizontal la atracción es más suave: las letras se acercan al cursor sin montarse unas sobre otras.\n            tx = (dx / (d || 1)) * pull * 0.3; ty = (dy / (d || 1)) * pull;\n            te = 1 + 0.12 * f; tr = (dx / R) * 9 * f; tm = f;\n          }\n        }\n        for (let s = 0; s < sub; s++) {\n          vx[i] += ((tx - x[i]) * K - vx[i] * C) * h; x[i] += vx[i] * h;\n          vy[i] += ((ty - y[i]) * K - vy[i] * C) * h; y[i] += vy[i] * h;\n          vesc[i] += ((te - esc[i]) * K - vesc[i] * C) * h; esc[i] += vesc[i] * h;\n          vrot[i] += ((tr - rot[i]) * K - vrot[i] * C) * h; rot[i] += vrot[i] * h;\n        }\n        mezcla[i] += (tm - mezcla[i]) * (1 - Math.exp(-dt * 12));\n        if (Math.abs(tx - x[i]) + Math.abs(ty - y[i]) + Math.abs(vx[i]) * 0.05 + Math.abs(vy[i]) * 0.05 + Math.abs(te - esc[i]) * 10 + Math.abs(tm - mezcla[i]) > 0.02) mueve = true;\n      }\n      pintar();\n      if (mueve || fantasma || ptr.activo) raf = requestAnimationFrame(paso);\n      else { ultimo = 0; for (let i = 0; i < n; i++) { x[i] = y[i] = vx[i] = vy[i] = rot[i] = vrot[i] = vesc[i] = 0; esc[i] = 1; mezcla[i] = 0; } pintar(); }\n    };\n    const wake = () => { if (!raf && visible && !muerto && !reducido) { ultimo = 0; raf = requestAnimationFrame(paso); } };\n\n    for (let i = 0; i < n; i++) esc[i] = 1;\n    medir();\n    pintar();\n\n    const onMove = (e: PointerEvent) => {\n      const rr = root.getBoundingClientRect();\n      const m = cfg.current.radius * 1.1;\n      ptr.x = e.clientX; ptr.y = e.clientY;\n      ptr.activo = e.clientX > rr.left - m && e.clientX < rr.right + m && e.clientY > rr.top - m && e.clientY < rr.bottom + m;\n      wake();\n    };\n    const onFuera = () => { ptr.activo = false; wake(); };\n    const onUp = (e: PointerEvent) => { if (e.pointerType !== \"mouse\") onFuera(); };\n    if (!reducido) {\n      window.addEventListener(\"pointermove\", onMove, { passive: true });\n      window.addEventListener(\"pointerdown\", onMove, { passive: true });\n      window.addEventListener(\"pointerup\", onUp, { passive: true });\n      document.documentElement.addEventListener(\"pointerleave\", onFuera);\n    }\n    const ro = new ResizeObserver(() => { medir(); wake(); });\n    ro.observe(root);\n    document.fonts?.ready.then(() => { medir(); wake(); });\n    const io = new IntersectionObserver(([e]) => { visible = e.isIntersecting; if (visible) wake(); }, { rootMargin: \"60px\" });\n    io.observe(root);\n    wake();\n    return () => {\n      muerto = true; cancelAnimationFrame(raf);\n      ro.disconnect(); io.disconnect();\n      window.removeEventListener(\"pointermove\", onMove);\n      window.removeEventListener(\"pointerdown\", onMove);\n      window.removeEventListener(\"pointerup\", onUp);\n      document.documentElement.removeEventListener(\"pointerleave\", onFuera);\n    };\n  }, [texto]);\n\n  const vars = { \"--furin-ml-size\": `${size}px`, \"--furin-ml-color\": color } as CSSProperties;\n  return (\n    <span ref={rootRef} className={`furin-magnetic-letters ${className}`} style={{ ...vars, ...style }}>\n      <span className=\"furin-magnetic-letters__sr\">{texto}</span>\n      <span className=\"furin-magnetic-letters__vis\" aria-hidden=\"true\">\n        {lineas.map((ln, li) => (\n          <span key={li} className=\"furin-magnetic-letters__linea\">\n            {ln.split(\" \").map((palabra, pi, arr) => (\n              <span key={pi} className=\"furin-magnetic-letters__palabra\">\n                {Array.from(palabra).map((ch, ci) => <span key={ci} data-l=\"\" className=\"furin-magnetic-letters__letra\">{ch}</span>)}\n                {pi < arr.length - 1 ? \" \" : null}\n              </span>\n            ))}\n          </span>\n        ))}\n      </span>\n    </span>\n  );\n}\n\nexport default MagneticLetters;\n",
      "type": "registry:component",
      "target": "components/furin/magnetic-letters/MagneticLetters.tsx"
    },
    {
      "path": "registry/magnetic-letters/MagneticLetters.css",
      "content": ".furin-magnetic-letters {\n  position: relative;\n  display: inline-block;\n  max-width: 100%;\n  font-family: \"Geist\", \"Inter\", \"SF Pro Display\", system-ui, -apple-system, \"Helvetica Neue\", Arial, sans-serif;\n  font-size: calc(var(--furin-ml-size) * var(--furin-ml-fit, 1));\n  font-weight: 700;\n  line-height: 1.12;\n  letter-spacing: -0.025em;\n  color: var(--furin-ml-color);\n  text-align: center;\n  -webkit-font-smoothing: antialiased;\n}\n.furin-magnetic-letters__vis { display: block; }\n.furin-magnetic-letters__linea { display: block; }\n.furin-magnetic-letters__palabra { display: inline-block; white-space: nowrap; }\n.furin-magnetic-letters__letra { display: inline-block; will-change: transform; transform-origin: 50% 58%; }\n.furin-magnetic-letters__sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }\n",
      "type": "registry:file",
      "target": "components/furin/magnetic-letters/MagneticLetters.css"
    }
  ]
}
