{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ascii-text",
  "type": "registry:component",
  "title": "ASCII Text",
  "description": "Text drawn with ASCII characters. A lens around the cursor magnifies, rotates and scrambles them.",
  "author": "Marcelo Treviño Velázquez <https://furin.dev>",
  "dependencies": [],
  "categories": [
    "Text"
  ],
  "docs": "Installed in components/furin/ascii-text/. Docs, live controls and props table: https://furin.dev/components/ascii-text/",
  "files": [
    {
      "path": "registry/ascii-text/AsciiText.tsx",
      "content": "\"use client\";\nimport { useEffect, useRef } from \"react\";\nimport type { CSSProperties } from \"react\";\nimport \"./AsciiText.css\";\n\nexport interface AsciiTextProps {\n  /** El texto que se dibuja con caracteres (acepta saltos de línea). */\n  children?: string;\n  /** Tamaño máximo de la letra del texto, en px (se reduce solo si no cabe). */\n  size?: number;\n  /** Tamaño de cada carácter ASCII, en px: más chico, más detalle. */\n  cell?: number;\n  /** Alto del lienzo, en px. */\n  height?: number;\n  /** Radio de la lente del cursor, en px. */\n  radius?: number;\n  /** Caracteres de menor a mayor densidad. */\n  charset?: string;\n  /** Cuando no hay cursor, una lente pasea sola por el texto. */\n  idle?: boolean;\n  /** Color de los caracteres. */\n  color?: string;\n  /** Color de los caracteres dentro de la lente. */\n  accent?: string;\n  /** Clase extra para el contenedor. */\n  className?: string;\n  /** Estilos extra para el contenedor. */\n  style?: CSSProperties;\n}\n\nconst MONO = `\"JetBrains Mono\", ui-monospace, \"SF Mono\", Menlo, Consolas, monospace`;\nconst SANS = `\"Geist\", \"Inter\", \"SF Pro Display\", system-ui, -apple-system, \"Helvetica Neue\", Arial, sans-serif`;\nconst S = 3; // submuestras por celda en cada eje\n\nconst hash = (a: number, b: number, c: number) => {\n  let h = (a * 374761393 + b * 668265263 + c * 2147483647) | 0;\n  h = Math.imul(h ^ (h >>> 13), 1274126177);\n  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;\n};\nconst suave = (t: number) => t * t * (3 - 2 * t);\n\n/** El texto se dibuja con caracteres ASCII en un lienzo; una lente alrededor del cursor los reacomoda y los revuelve. */\nexport function AsciiText({\n  children = \"ASCII\",\n  size = 190,\n  cell = 8,\n  height = 260,\n  radius = 104,\n  charset = \" .:-=+*#%@\",\n  idle = true,\n  color = \"#E9EBEF\",\n  accent = \"#7CF5C6\",\n  className = \"\",\n  style,\n}: AsciiTextProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const texto = String(children ?? \"\");\n  const cfg = useRef({ size, cell, radius, charset, idle, color, accent });\n  cfg.current = { size, cell, radius, charset, idle, color, accent };\n  const vivo = useRef<{ build: () => void } | null>(null);\n\n  useEffect(() => {\n    const root = rootRef.current, canvas = canvasRef.current;\n    if (!root || !canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n    const reducido = matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    let W = 0, H = 0, dpr = 1, cols = 0, rows = 0, cw = 6, ch = 10, ox = 0, oy = 0, LW = 0, LH = 0;\n    let lum = new Float32Array(0);\n    let listo = false, visible = true, raf = 0, muerto = false, ultimo = 0, pintado = 0;\n    const t0 = performance.now();\n    const L = { x: 0, y: 0, act: 0, ptrActivo: false, px: 0, py: 0 };\n\n    const fuente = (px: number, peso = 800) => `${peso} ${px}px ${SANS}`;\n\n    // Dibuja el texto en un lienzo pequeño, con una resolución de S×S por celda ASCII.\n    const construir = () => {\n      if (muerto) return;\n      W = root.clientWidth; H = root.clientHeight;\n      if (!W || !H) return;\n      dpr = Math.min(window.devicePixelRatio || 1, 2);\n      canvas.width = Math.round(W * dpr); canvas.height = Math.round(H * dpr);\n      const c = cfg.current;\n      ctx.setTransform(1, 0, 0, 1, 0, 0);\n      ctx.font = `500 ${c.cell}px ${MONO}`;\n      cw = ctx.measureText(\"0\").width || c.cell * 0.6;\n      ch = Math.round(c.cell * 1.18);\n      cols = Math.max(4, Math.floor(W / cw)); rows = Math.max(3, Math.floor(H / ch));\n      ox = (W - cols * cw) / 2; oy = (H - rows * ch) / 2;\n      LW = cols * S; LH = rows * S;\n      const off = document.createElement(\"canvas\");\n      off.width = LW; off.height = LH;\n      const o = off.getContext(\"2d\", { willReadFrequently: true })!;\n      o.setTransform(S / cw, 0, 0, S / ch, 0, 0);\n      const lineas = texto.split(\"\\n\");\n      const gw = cols * cw, gh = rows * ch;\n      let fs = c.size;\n      o.font = fuente(fs);\n      const ancho = Math.max(...lineas.map((l) => o.measureText(l).width), 1);\n      fs = Math.min(fs, (fs * gw * 0.9) / ancho, (gh * 0.82) / (lineas.length * 0.98));\n      o.font = fuente(fs);\n      o.fillStyle = \"#fff\";\n      o.textAlign = \"center\";\n      o.textBaseline = \"alphabetic\";\n      const lh = fs * 0.98;\n      const m0 = o.measureText(lineas[0]), mN = o.measureText(lineas[lineas.length - 1]);\n      const top = -m0.actualBoundingBoxAscent, bot = (lineas.length - 1) * lh + mN.actualBoundingBoxDescent;\n      const mid = (top + bot) / 2;\n      lineas.forEach((ln, i) => o.fillText(ln, gw / 2, gh / 2 + i * lh - mid));\n      const img = o.getImageData(0, 0, LW, LH).data;\n      lum = new Float32Array(LW * LH);\n      for (let i = 0; i < lum.length; i++) lum[i] = img[i * 4 + 3] / 255;\n      listo = true;\n      L.x = gw * 0.5; L.y = gh * 0.5;\n      pintar(performance.now(), true);\n      wake();\n    };\n\n    // Luminosidad de la imagen en el punto (u, v), en unidades de celda (interpolación bilineal).\n    const muestra = (u: number, v: number) => {\n      const x = u * S - 0.5, y = v * S - 0.5;\n      const x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0;\n      const g = (a: number, b: number) => (a < 0 || b < 0 || a >= LW || b >= LH ? 0 : lum[b * LW + a]);\n      return (g(x0, y0) * (1 - fx) + g(x0 + 1, y0) * fx) * (1 - fy) + (g(x0, y0 + 1) * (1 - fx) + g(x0 + 1, y0 + 1) * fx) * fy;\n    };\n\n    const pintar = (now: number, estatico = false) => {\n      if (!listo) return;\n      const c = cfg.current;\n      const ramp = c.charset.length > 1 ? c.charset : \" .:-=+*#%@\";\n      const nR = ramp.length;\n      const t = estatico || reducido ? 0 : (now - t0) / 1000;\n      const tq = Math.floor(t * 22); // los caracteres revueltos cambian ~22 veces por segundo\n      const gw = cols * cw;\n      const R = c.radius;\n      // Cubetas por (nivel de opacidad, color): una sola asignación de estilo por cubeta.\n      const NIV = 5;\n      const cub: number[][] = Array.from({ length: NIV * 2 }, () => []);\n      const chars: string[] = [];\n      for (let j = 0; j < rows; j++) {\n        const y = j * ch + ch / 2;\n        for (let i = 0; i < cols; i++) {\n          const x = i * cw + cw / 2;\n          let u = i + 0.5, v = j + 0.5, f = 0;\n          if (L.act > 0.002) {\n            const dx = x - L.x, dy = y - L.y;\n            const d2 = dx * dx + dy * dy;\n            if (d2 < R * R) {\n              f = suave(1 - Math.sqrt(d2) / R) * L.act;\n              // La lente acerca y gira un poco el texto que tiene debajo.\n              const th = f * 0.75, cs = Math.cos(th), sn = Math.sin(th), k = 1 - 0.55 * f;\n              u = (L.x + (dx * cs - dy * sn) * k) / cw;\n              v = (L.y + (dx * sn + dy * cs) * k) / ch;\n            }\n          }\n          let val = muestra(u, v);\n          const ruido = 0.5 * (Math.sin(i * 0.31 + t * 1.1 + j * 0.17) + Math.sin(j * 0.41 - t * 0.8 + i * 0.09));\n          let idx = 0, nivel = 0;\n          if (val > 0.04) {\n            val = Math.min(1, val * (0.8 + 0.2 * ruido + 0.2));\n            idx = Math.min(nR - 1, Math.max(1, Math.round(Math.pow(val, 0.9) * (nR - 1))));\n            nivel = Math.min(NIV - 1, Math.floor(0.25 * NIV + val * (NIV * 0.75)));\n          } else {\n            // Un campo muy tenue de puntos alrededor, que se enciende cerca del cursor.\n            const h = hash(i, j, Math.floor(t * 1.4));\n            if (h > 0.022 + f * 0.1) continue;\n            idx = 1; nivel = f > 0.1 ? 1 : 0;\n          }\n          if (f > 0.12 && hash(i, j, tq) < f * 1.05) {\n            // Dentro de la lente, algunos caracteres se reacomodan al azar antes de asentarse.\n            idx = 1 + Math.floor(hash(j, i, tq + 7) * (nR - 1));\n          }\n          const col = f > 0.3 ? 1 : 0;\n          cub[nivel * 2 + col].push(chars.length, x, y);\n          chars.push(ramp[idx]);\n        }\n      }\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      ctx.clearRect(0, 0, W, H);\n      ctx.font = `500 ${c.cell}px ${MONO}`;\n      ctx.textAlign = \"center\";\n      ctx.textBaseline = \"middle\";\n      for (let b = 0; b < cub.length; b++) {\n        const arr = cub[b];\n        if (!arr.length) continue;\n        const nivel = b >> 1;\n        ctx.globalAlpha = 0.16 + (0.84 * (nivel + 1)) / NIV;\n        ctx.fillStyle = b & 1 ? c.accent : c.color;\n        for (let k = 0; k < arr.length; k += 3) ctx.fillText(chars[arr[k]], ox + arr[k + 1], oy + arr[k + 2]);\n      }\n      ctx.globalAlpha = 1;\n      void gw;\n    };\n\n    const paso = (now: number) => {\n      raf = 0;\n      if (muerto || !visible || !listo) return;\n      const dt = Math.min(0.05, (now - (ultimo || now)) / 1000 || 0.016);\n      ultimo = now;\n      const c = cfg.current;\n      const gw = cols * cw, gh = rows * ch;\n      let objX = L.x, objY = L.y, objAct = 0;\n      if (L.ptrActivo) { objX = L.px - ox; objY = L.py - oy; objAct = 1; }\n      else if (c.idle) {\n        const t = (now - t0) / 1000;\n        objX = gw * (0.5 + 0.4 * Math.sin(t * 0.55)); objY = gh * (0.5 + 0.24 * Math.sin(t * 0.93 + 1));\n        objAct = 1;\n      }\n      const k = 1 - Math.exp(-dt * 14);\n      L.x += (objX - L.x) * k; L.y += (objY - L.y) * k;\n      L.act += (objAct - L.act) * (1 - Math.exp(-dt * 7));\n      const vivoAhora = L.act > 0.01;\n      // Con la lente apagada solo respira (≈15 cuadros por segundo); con lente, a velocidad completa.\n      if (!vivoAhora && now - pintado < 66) { raf = requestAnimationFrame(paso); return; }\n      pintado = now;\n      pintar(now);\n      if (!reducido) raf = requestAnimationFrame(paso);\n    };\n    const wake = () => { if (!raf && visible && listo && !muerto && !reducido) { ultimo = 0; raf = requestAnimationFrame(paso); } };\n\n    const onMove = (e: PointerEvent) => {\n      const r = canvas.getBoundingClientRect();\n      const m = cfg.current.radius * 0.6;\n      L.px = e.clientX - r.left; L.py = e.clientY - r.top;\n      L.ptrActivo = e.clientX > r.left - m && e.clientX < r.right + m && e.clientY > r.top - m && e.clientY < r.bottom + m;\n      wake();\n    };\n    const onFuera = () => { L.ptrActivo = 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 io = new IntersectionObserver(([e]) => { visible = e.isIntersecting; if (visible) wake(); }, { rootMargin: \"80px\" });\n    io.observe(root);\n    let pend = 0;\n    const pedir = () => { cancelAnimationFrame(pend); pend = requestAnimationFrame(construir); };\n    const ro = new ResizeObserver(pedir);\n    ro.observe(root);\n    vivo.current = { build: pedir };\n    // Pinta ya con lo que haya y reconstruye cuando la fuente de verdad esté lista.\n    Promise.all([document.fonts?.load(fuente(100)), document.fonts?.load(`500 12px ${MONO}`)]).catch(() => {}).then(() => { pedir(); });\n    pedir();\n    return () => {\n      muerto = true; vivo.current = null;\n      cancelAnimationFrame(raf); cancelAnimationFrame(pend);\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  useEffect(() => { vivo.current?.build(); }, [size, cell, height, charset, color]);\n\n  return (\n    <div ref={rootRef} className={`furin-ascii-text ${className}`} style={{ height, ...style }} role=\"img\" aria-label={texto.replace(/\\n/g, \" \")}>\n      <canvas ref={canvasRef} className=\"furin-ascii-text__lienzo\" aria-hidden=\"true\" />\n      <span className=\"furin-ascii-text__sr\">{texto}</span>\n    </div>\n  );\n}\n\nexport default AsciiText;\n",
      "type": "registry:component",
      "target": "components/furin/ascii-text/AsciiText.tsx"
    },
    {
      "path": "registry/ascii-text/AsciiText.css",
      "content": ".furin-ascii-text {\n  position: relative;\n  display: block;\n  width: min(100%, 520px);\n  user-select: none;\n}\n.furin-ascii-text__lienzo { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }\n.furin-ascii-text__sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }\n",
      "type": "registry:file",
      "target": "components/furin/ascii-text/AsciiText.css"
    }
  ]
}
