{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "live-grid",
  "type": "registry:component",
  "title": "Live Grid",
  "description": "A grid of dots that part and light up around the cursor, on a spring.",
  "author": "Marcelo Treviño Velázquez <https://furin.dev>",
  "dependencies": [],
  "categories": [
    "Backgrounds"
  ],
  "docs": "Installed in components/furin/live-grid/. Docs, live controls and props table: https://furin.dev/components/live-grid/",
  "files": [
    {
      "path": "registry/live-grid/LiveGrid.tsx",
      "content": "\"use client\";\nimport { useEffect, useRef } from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport \"./LiveGrid.css\";\n\nexport interface LiveGridProps {\n  /** Distancia entre un punto y el siguiente, en px. */\n  spacing?: number;\n  /** Diámetro de cada punto en reposo, en px. */\n  dotSize?: number;\n  /** Radio de influencia del cursor (o del dedo), en px. */\n  radius?: number;\n  /** Cuánto se apartan los puntos del cursor: 1 es casi un espacio entero. */\n  strength?: number;\n  /** Color de los puntos en reposo (cualquier color CSS, sin variables). */\n  baseColor?: string;\n  /** Color de los puntos que el cursor ilumina. */\n  activeColor?: string;\n  /** Si no hay cursor, lanza de vez en cuando una onda suave para que la rejilla no se vea muerta. */\n  ambientWave?: boolean;\n  /**\n   * Dónde escucha el cursor: en su contenedor (\"parent\") o en toda la ventana (\"window\"). Usa \"window\" cuando la\n   * rejilla es el fondo de una sección con contenido encima, para que reaccione aunque el cursor pase sobre ese contenido.\n   */\n  listenTo?: \"parent\" | \"window\";\n  /** Clase extra para el contenedor. */\n  className?: string;\n  /** Estilos extra para el contenedor. */\n  style?: CSSProperties;\n  /** Contenido que se dibuja encima de la rejilla, centrado. */\n  children?: ReactNode;\n}\n\ntype Rgba = [number, number, number, number];\n\n/** Valores que el bucle de dibujo lee en cada cuadro (así cambiar una prop no reconstruye la rejilla). */\ninterface LiveValues {\n  dotSize: number;\n  radius: number;\n  strength: number;\n  base: Rgba;\n  active: Rgba;\n  ambientWave: boolean;\n  /** Mancha de luz suave ya pintada, que se dibuja detrás de los puntos encendidos. */\n  halo: HTMLCanvasElement | null;\n}\n\n/** Rigidez y amortiguación del resorte: algo subamortiguado, así los puntos \"rebotan\" un poco al volver. */\nconst SPRING = 190;\nconst DAMPING = 15;\n/** Cuánto crece un punto con la luz al máximo (1.6 = 2.6 veces su tamaño). */\nconst GROW = 1.6;\n/** La onda ambiental: velocidad y grosor del anillo, en px. */\nconst WAVE_SPEED = 420;\nconst WAVE_WIDTH = 90;\nconst MAX_DPR = 2;\nconst TAU = Math.PI * 2;\n\nlet colorContext: CanvasRenderingContext2D | null = null;\n\n/** Convierte cualquier color CSS a [r, g, b, a] (r, g y b de 0 a 255, a de 0 a 1). */\nfunction toRgba(color: string): Rgba {\n  colorContext ??= document.createElement(\"canvas\").getContext(\"2d\");\n  if (!colorContext) return [0, 0, 0, 1];\n  colorContext.fillStyle = \"#000000\";\n  colorContext.fillStyle = color; // si el color no es válido se queda en negro\n  const normalized = colorContext.fillStyle; // \"#rrggbb\" o \"rgba(r, g, b, a)\"\n  if (normalized.startsWith(\"#\")) {\n    const n = parseInt(normalized.slice(1), 16);\n    return [n >> 16, (n >> 8) & 255, n & 255, 1];\n  }\n  const [r, g, b, a = 1] = normalized.match(/[\\d.]+/g)!.map(Number);\n  return [r, g, b, a];\n}\n\n/** Pinta una vez la mancha de luz del color activo: dibujar una imagen es más barato que un degradado por punto. */\nfunction paintHalo(color: Rgba): HTMLCanvasElement {\n  const size = 64;\n  const halo = document.createElement(\"canvas\");\n  halo.width = halo.height = size;\n  const g = halo.getContext(\"2d\")!;\n  const gradient = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);\n  const [r, green, b] = color.map(Math.round);\n  gradient.addColorStop(0, `rgba(${r}, ${green}, ${b}, 0.85)`);\n  gradient.addColorStop(0.35, `rgba(${r}, ${green}, ${b}, 0.3)`);\n  gradient.addColorStop(1, `rgba(${r}, ${green}, ${b}, 0)`);\n  g.fillStyle = gradient;\n  g.fillRect(0, 0, size, size);\n  return halo;\n}\n\nconst css = ([r, g, b, a]: Rgba) => `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${a.toFixed(3)})`;\n\n/** Mezcla dos colores: amount 0 da `from`, 1 da `to`. */\nconst mix = (from: Rgba, to: Rgba, amount: number): Rgba => [\n  from[0] + (to[0] - from[0]) * amount,\n  from[1] + (to[1] - from[1]) * amount,\n  from[2] + (to[2] - from[2]) * amount,\n  from[3] + (to[3] - from[3]) * amount,\n];\n\n/** Rejilla de puntos que se aparta y se ilumina alrededor del cursor. Llena a su padre, que debe tener position: relative. */\nexport function LiveGrid({\n  spacing = 28,\n  dotSize = 3,\n  radius = 170,\n  strength = 1,\n  baseColor = \"#4A4A62\",\n  activeColor = \"#8C9BFF\",\n  ambientWave = true,\n  listenTo = \"parent\",\n  className = \"\",\n  style,\n  children,\n}: LiveGridProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const live = useRef<LiveValues>({ dotSize, radius, strength, base: [0, 0, 0, 1], active: [0, 0, 0, 1], ambientWave, halo: null });\n  const refresh = useRef<() => void>(() => {});\n\n  // Pasa las props actuales al bucle de dibujo y lo despierta si estaba dormido.\n  useEffect(() => {\n    const active = toRgba(activeColor);\n    live.current = { dotSize, radius, strength, base: toRgba(baseColor), active, ambientWave, halo: paintHalo(active) };\n    refresh.current();\n  }, [dotSize, radius, strength, baseColor, activeColor, ambientWave]);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!root || !canvas || !ctx) return;\n\n    // Los eventos se escuchan en el padre: así reacciona aunque haya contenido encima de la rejilla.\n    const host = root.parentElement ?? root;\n    const reducedMotion = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    const gap = Math.max(8, spacing);\n\n    let width = 0;\n    let height = 0;\n    let count = 0;\n    // Un arreglo por dato (en vez de un objeto por punto) para no generar basura en cada cuadro.\n    let homeX = new Float32Array(0); // posición de reposo\n    let homeY = new Float32Array(0);\n    let offX = new Float32Array(0); // desplazamiento actual respecto al reposo\n    let offY = new Float32Array(0);\n    let velX = new Float32Array(0); // velocidad del resorte\n    let velY = new Float32Array(0);\n    let glow = new Float32Array(0); // 0 = apagado, 1 = encendido al máximo\n\n    const pointer = { x: 0, y: 0, active: false };\n    const wave = { active: false, x: 0, y: 0, r: 0, maxR: 0 };\n    let nextWaveAt = performance.now() + 900;\n    let visible = true;\n    let frameId = 0;\n    let timerId = 0;\n    let lastNow = 0;\n\n    /** Coloca los puntos en una rejilla centrada que respeta un margen de medio espacio. */\n    const layout = () => {\n      const dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR);\n      width = root.clientWidth;\n      height = root.clientHeight;\n      canvas.width = Math.max(1, Math.round(width * dpr));\n      canvas.height = Math.max(1, Math.round(height * dpr));\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n\n      const cols = Math.max(1, Math.floor(width / gap));\n      const rows = Math.max(1, Math.floor(height / gap));\n      count = cols * rows;\n      homeX = new Float32Array(count);\n      homeY = new Float32Array(count);\n      offX = new Float32Array(count);\n      offY = new Float32Array(count);\n      velX = new Float32Array(count);\n      velY = new Float32Array(count);\n      glow = new Float32Array(count);\n      const startX = (width - (cols - 1) * gap) / 2;\n      const startY = (height - (rows - 1) * gap) / 2;\n      for (let i = 0; i < count; i++) {\n        homeX[i] = startX + (i % cols) * gap;\n        homeY[i] = startY + Math.floor(i / cols) * gap;\n      }\n    };\n\n    /** Avanza la física. Devuelve true mientras algo siga moviéndose. */\n    const step = (dt: number): boolean => {\n      const { radius, strength } = live.current;\n      const radiusSq = radius * radius;\n      const maxPush = gap * 0.95 * strength;\n      const glowUp = 1 - Math.exp(-dt * 16); // se enciende rápido…\n      const glowDown = 1 - Math.exp(-dt * 4.5); // …y se apaga despacio\n      let moving = false;\n\n      if (wave.active) {\n        wave.r += WAVE_SPEED * dt;\n        if (wave.r > wave.maxR) {\n          wave.active = false;\n          nextWaveAt = performance.now() + 4000 + Math.random() * 3000;\n        }\n      }\n\n      for (let i = 0; i < count; i++) {\n        let targetX = 0;\n        let targetY = 0;\n        let targetGlow = 0;\n\n        if (pointer.active) {\n          const dx = homeX[i] - pointer.x;\n          const dy = homeY[i] - pointer.y;\n          const distSq = dx * dx + dy * dy;\n          if (distSq < radiusSq) {\n            const dist = Math.sqrt(distSq);\n            const near = 1 - dist / radius; // 1 junto al cursor, 0 en el borde del radio\n            const push = near * near * maxPush;\n            const inv = dist > 0.001 ? 1 / dist : 0;\n            targetX = dx * inv * push;\n            targetY = dy * inv * push;\n            targetGlow = near * near * (3 - 2 * near);\n          }\n        }\n\n        if (wave.active) {\n          const dx = homeX[i] - wave.x;\n          const dy = homeY[i] - wave.y;\n          const dist = Math.sqrt(dx * dx + dy * dy);\n          const band = (dist - wave.r) / WAVE_WIDTH;\n          const lift = Math.exp(-band * band);\n          if (lift > 0.01) {\n            const inv = dist > 0.001 ? 1 / dist : 0;\n            targetX += dx * inv * lift * maxPush * 0.3;\n            targetY += dy * inv * lift * maxPush * 0.3;\n            targetGlow = Math.max(targetGlow, lift * 0.85);\n          }\n        }\n\n        // Punto en reposo y sin nada que lo mueva: no hay que calcular nada.\n        if (targetGlow === 0 && glow[i] === 0 && offX[i] === 0 && offY[i] === 0) continue;\n\n        // Resorte hacia el desplazamiento objetivo.\n        velX[i] += ((targetX - offX[i]) * SPRING - velX[i] * DAMPING) * dt;\n        velY[i] += ((targetY - offY[i]) * SPRING - velY[i] * DAMPING) * dt;\n        offX[i] += velX[i] * dt;\n        offY[i] += velY[i] * dt;\n        glow[i] += (targetGlow - glow[i]) * (targetGlow > glow[i] ? glowUp : glowDown);\n\n        const error = Math.abs(targetX - offX[i]) + Math.abs(targetY - offY[i]) + Math.abs(velX[i]) + Math.abs(velY[i]);\n        const glowError = Math.abs(targetGlow - glow[i]);\n        if (error > 0.04 || glowError > 0.004) {\n          moving = true;\n        } else if (targetGlow === 0 && targetX === 0 && targetY === 0) {\n          // Ya volvió: se deja exactamente en reposo.\n          offX[i] = offY[i] = velX[i] = velY[i] = glow[i] = 0;\n        }\n      }\n      return moving || wave.active;\n    };\n\n    const draw = () => {\n      ctx.clearRect(0, 0, width, height);\n      const { dotSize, base, active, halo } = live.current;\n      const baseRadius = dotSize / 2;\n\n      // Los puntos en reposo son la gran mayoría: se dibujan todos juntos en un solo trazo.\n      ctx.fillStyle = css(base);\n      ctx.beginPath();\n      for (let i = 0; i < count; i++) {\n        if (glow[i] !== 0 || offX[i] !== 0 || offY[i] !== 0) continue;\n        ctx.moveTo(homeX[i] + baseRadius, homeY[i]);\n        ctx.arc(homeX[i], homeY[i], baseRadius, 0, TAU);\n      }\n      ctx.fill();\n\n      // Los puntos tocados por la luz, uno por uno, con su color y tamaño propios.\n      for (let i = 0; i < count; i++) {\n        const light = glow[i];\n        if (light === 0 && offX[i] === 0 && offY[i] === 0) continue;\n        const x = homeX[i] + offX[i];\n        const y = homeY[i] + offY[i];\n        const dotRadius = baseRadius * (1 + light * GROW);\n        if (halo && light > 0.05) {\n          // Mancha de luz suave detrás del punto.\n          const haloRadius = dotRadius * 4.2;\n          ctx.globalAlpha = light * 0.55;\n          ctx.drawImage(halo, x - haloRadius, y - haloRadius, haloRadius * 2, haloRadius * 2);\n          ctx.globalAlpha = 1;\n        }\n        ctx.fillStyle = css(mix(base, active, light));\n        ctx.beginPath();\n        ctx.arc(x, y, dotRadius, 0, TAU);\n        ctx.fill();\n      }\n    };\n\n    /** Con movimiento reducido: una mancha de luz fija en la rejilla, sin animación. */\n    const drawStill = () => {\n      const lightRadius = Math.max(live.current.radius * 1.6, Math.min(width, height) * 0.4);\n      for (let i = 0; i < count; i++) {\n        const near = Math.max(0, 1 - Math.hypot(homeX[i] - width * 0.5, homeY[i] - height * 0.45) / lightRadius);\n        glow[i] = near * near * (3 - 2 * near);\n      }\n      draw();\n    };\n\n    const frame = (now: number) => {\n      frameId = 0;\n      const dt = Math.min((now - lastNow) / 1000, 1 / 30);\n      lastNow = now;\n      const busy = step(dt);\n      draw();\n      if (busy) frameId = requestAnimationFrame(frame);\n      else scheduleWave();\n    };\n\n    /** Despierta el bucle. Cuando todo está quieto el bucle se duerme y no gasta nada. */\n    const wake = () => {\n      if (frameId || !visible || reducedMotion.matches) return;\n      window.clearTimeout(timerId);\n      timerId = 0;\n      lastNow = performance.now();\n      frameId = requestAnimationFrame(frame);\n    };\n\n    /** Con todo en reposo, programa la próxima onda ambiental. */\n    const scheduleWave = () => {\n      if (timerId || !live.current.ambientWave || pointer.active) return;\n      timerId = window.setTimeout(() => {\n        timerId = 0;\n        if (pointer.active || !live.current.ambientWave) return;\n        wave.x = width * (0.25 + Math.random() * 0.5);\n        wave.y = height * (0.25 + Math.random() * 0.5);\n        wave.r = 0;\n        wave.maxR = Math.hypot(width, height) + WAVE_WIDTH * 2;\n        wave.active = true;\n        wake();\n      }, Math.max(0, nextWaveAt - performance.now()));\n    };\n\n    const sleep = () => {\n      cancelAnimationFrame(frameId);\n      window.clearTimeout(timerId);\n      frameId = 0;\n      timerId = 0;\n    };\n\n    const onPointerMove = (event: PointerEvent) => {\n      const rect = canvas.getBoundingClientRect();\n      const x = event.clientX - rect.left;\n      const y = event.clientY - rect.top;\n      // Escuchando la ventana, el cursor fuera de la rejilla cuenta como \"irse\".\n      if (listenTo === \"window\" && (x < 0 || y < 0 || x > rect.width || y > rect.height)) {\n        if (pointer.active) onPointerLeave();\n        return;\n      }\n      pointer.x = x;\n      pointer.y = y;\n      pointer.active = true;\n      wake();\n    };\n    const onPointerLeave = () => {\n      pointer.active = false;\n      nextWaveAt = performance.now() + 2500;\n      wake();\n    };\n    // Con el dedo, soltar es \"irse\"; con el mouse solo cuenta salir del padre.\n    const onPointerUp = (event: PointerEvent) => {\n      if (event.pointerType !== \"mouse\") onPointerLeave();\n    };\n\n    const resizeObserver = new ResizeObserver(() => {\n      layout();\n      if (reducedMotion.matches) drawStill();\n      else {\n        draw();\n        wake();\n      }\n    });\n    resizeObserver.observe(root);\n\n    const visibilityObserver = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      if (visible) wake();\n      else sleep();\n    });\n    visibilityObserver.observe(root);\n\n    const applyMotionPreference = () => {\n      if (reducedMotion.matches) {\n        sleep();\n        pointer.active = false;\n        wave.active = false;\n        drawStill();\n      } else {\n        glow.fill(0);\n        draw();\n        wake();\n      }\n    };\n    reducedMotion.addEventListener(\"change\", applyMotionPreference);\n\n    // \"window\": el cursor se sigue en toda la página; salir del documento cuenta como \"irse\".\n    const target: HTMLElement | Window = listenTo === \"window\" ? window : host;\n    const leaveTarget: HTMLElement = listenTo === \"window\" ? document.documentElement : host;\n    target.addEventListener(\"pointermove\", onPointerMove as EventListener, { passive: true });\n    target.addEventListener(\"pointerdown\", onPointerMove as EventListener, { passive: true });\n    target.addEventListener(\"pointerup\", onPointerUp as EventListener);\n    target.addEventListener(\"pointercancel\", onPointerLeave);\n    leaveTarget.addEventListener(\"pointerleave\", onPointerLeave);\n\n    refresh.current = () => (reducedMotion.matches ? drawStill() : wake());\n    layout();\n    if (reducedMotion.matches) drawStill();\n    else {\n      draw();\n      wake();\n    }\n\n    return () => {\n      sleep();\n      resizeObserver.disconnect();\n      visibilityObserver.disconnect();\n      reducedMotion.removeEventListener(\"change\", applyMotionPreference);\n      target.removeEventListener(\"pointermove\", onPointerMove as EventListener);\n      target.removeEventListener(\"pointerdown\", onPointerMove as EventListener);\n      target.removeEventListener(\"pointerup\", onPointerUp as EventListener);\n      target.removeEventListener(\"pointercancel\", onPointerLeave);\n      leaveTarget.removeEventListener(\"pointerleave\", onPointerLeave);\n      refresh.current = () => {};\n    };\n  }, [spacing, listenTo]);\n\n  return (\n    <div ref={rootRef} className={`furin-live-grid ${className}`.trim()} style={style}>\n      <canvas ref={canvasRef} className=\"furin-live-grid__canvas\" aria-hidden=\"true\" />\n      {children !== undefined && <div className=\"furin-live-grid__content\">{children}</div>}\n    </div>\n  );\n}\n\nexport default LiveGrid;\n",
      "type": "registry:component",
      "target": "components/furin/live-grid/LiveGrid.tsx"
    },
    {
      "path": "registry/live-grid/LiveGrid.css",
      "content": ".furin-live-grid {\n  position: absolute;\n  inset: 0;\n  overflow: hidden;\n  color: #fff;\n  /* Es un fondo: no estorba al resto de la página. Los eventos se escuchan en el padre. */\n  pointer-events: none;\n}\n\n.furin-live-grid__canvas {\n  position: absolute;\n  inset: 0;\n  width: 100%;\n  height: 100%;\n  display: block;\n}\n\n/* El contenido va encima, centrado. */\n.furin-live-grid__content {\n  position: relative;\n  z-index: 1;\n  width: 100%;\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  text-align: center;\n}\n\n/* Lo que pongas encima sí recibe clics y toques. */\n.furin-live-grid__content > * {\n  pointer-events: auto;\n}\n",
      "type": "registry:file",
      "target": "components/furin/live-grid/LiveGrid.css"
    }
  ]
}
