{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"signal-field","type":"registry:component","title":"Signal Field","description":"A machined dot grid lit by slow waves of light, with a pointer lens and click ripples.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/signal-field.tsx","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\n/**\n * SignalField — a machined dot grid that light rolls across.\n *\n * Every dot sits on a fixed grid. Three slow interference waves decide how lit\n * each one is, and the brightest take the tint colour. The pointer is a soft\n * lens that lifts and parts the dots under it, and a click or tap sends a ring\n * of light out through the grid.\n *\n * Place it as the FIRST child of the section it sits behind (the section must\n * be position: relative). It listens for the pointer on that section, not on\n * the canvas, so text and buttons layered above it never block the lens.\n *\n * color / tint take any canvas colour (hex, rgb) OR a CSS custom property\n * such as \"var(--accent)\", which is resolved from the page and re-read when\n * the theme class on the html element changes.\n */\nexport function SignalField({\n  spacing = 22,\n  speed = 1,\n  lens = 170,\n  ripples = true,\n  color = \"#e8eaee\",\n  tint = \"#79a4ff\",\n  className = \"\",\n}: {\n  /** Grid pitch in px. */\n  spacing?: number;\n  /** Wave speed multiplier. 0 holds the light still. */\n  speed?: number;\n  /** Pointer lens radius in px. 0 turns the lens off. */\n  lens?: number;\n  /** Click or tap to send a ring of light through the grid. */\n  ripples?: boolean;\n  /** Resting dot colour — hex, rgb, or \"var(--token)\". */\n  color?: string;\n  /** Lit dot colour — hex, rgb, or \"var(--token)\". */\n  tint?: string;\n  className?: string;\n}) {\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n\n  // Props are read by the render loop through a ref, so changing one adjusts\n  // the next frame instead of tearing the loop down. Synced in an effect —\n  // writing a ref during render is a render-phase side effect.\n  const opts = useRef({ spacing, speed, lens, ripples, color, tint });\n  // Set by the loop effect below; re-reads colours and the grid pitch.\n  const refresh = useRef<() => void>(() => {});\n  useEffect(() => {\n    opts.current = { spacing, speed, lens, ripples, color, tint };\n    refresh.current();\n  }, [spacing, speed, lens, ripples, color, tint]);\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    const host = canvas ? canvas.parentElement : null;\n    const ctx = canvas ? canvas.getContext(\"2d\") : null;\n    if (!canvas || !host || !ctx) return;\n\n    const RIPPLE_SPEED = 380;\n    const RIPPLE_LIFE = 1.9;\n    // Brightness above which a dot takes the tint and blooms.\n    const LIT = 0.52;\n    const reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\n    // \"var(--accent)\" → the computed value of --accent on the canvas.\n    // Anything the canvas can't paint falls back rather than silently drawing\n    // in the wrong colour. Bare HSL channels (\"222 47% 11%\", the shadcn token\n    // format) are wrapped in hsl(). The pattern is linear-time on any input.\n    function resolve(value: string, fallback: string): string {\n      const m = /^var\\(\\s*(--[\\w-]+)\\s*(?:,([\\s\\S]*))?\\)$/.exec(value.trim());\n      const raw = m\n        ? getComputedStyle(canvas as HTMLCanvasElement).getPropertyValue(m[1]).trim() || (m[2] || \"\").trim()\n        : value.trim();\n      if (raw && CSS.supports(\"color\", raw)) return raw;\n      if (raw && CSS.supports(\"color\", \"hsl(\" + raw + \")\")) return \"hsl(\" + raw + \")\";\n      return fallback;\n    }\n\n    let ink = \"#e8eaee\";\n    let lit = \"#79a4ff\";\n    function readColors() {\n      ink = resolve(opts.current.color, \"#e8eaee\");\n      lit = resolve(opts.current.tint, \"#79a4ff\");\n    }\n    readColors();\n\n    let width = 0;\n    let height = 0;\n    let cols = 0;\n    let rows = 0;\n    let offsetX = 0;\n    let offsetY = 0;\n    let pitch = opts.current.spacing;\n    // x, y and light for every dot, reused across frames (no per-frame\n    // allocation). Rebuilt only when the grid size changes.\n    let dots = new Float32Array(0);\n\n    const pointer = { x: -9999, y: -9999, tx: -9999, ty: -9999, strength: 0, target: 0 };\n    const rings: { x: number; y: number; born: number }[] = [];\n    let raf = 0;\n    let running = false;\n    let onScreen = true;\n    let last = 0;\n    let clock = 0; // wave time, scaled by speed\n    let real = 0; // wall time, for ripples\n\n    function layout() {\n      // LAYOUT size, not getBoundingClientRect(): the rect includes ancestor\n      // transforms, so inside a scaled card the grid would fill only part of\n      // the box, and a ResizeObserver never re-fires to correct it.\n      width = host!.clientWidth;\n      height = host!.clientHeight;\n      let dpr = Math.min(2, window.devicePixelRatio || 1);\n      // Cap the backing store near 8 megapixels: mounted in a very tall\n      // parent, iOS Safari refuses larger canvases and draws nothing at all.\n      if (width * height * dpr * dpr > 8e6) dpr = Math.max(0.5, Math.sqrt(8e6 / (width * height)));\n      canvas!.width = Math.round(width * dpr);\n      canvas!.height = Math.round(height * dpr);\n      ctx!.setTransform(dpr, 0, 0, dpr, 0, 0);\n      pitch = Math.max(8, opts.current.spacing);\n      cols = Math.ceil(width / pitch) + 1;\n      rows = Math.ceil(height / pitch) + 1;\n      // Centre the grid so both margins match.\n      offsetX = (width - (cols - 1) * pitch) / 2;\n      offsetY = (height - (rows - 1) * pitch) / 2;\n      if (dots.length !== cols * rows * 3) dots = new Float32Array(cols * rows * 3);\n      if (!running) draw();\n    }\n\n    function draw() {\n      ctx!.clearRect(0, 0, width, height);\n      const t = clock;\n      const radius = opts.current.lens;\n      const px = pointer.x;\n      const py = pointer.y;\n      const pull = pointer.strength;\n\n      let n = 0;\n      for (let j = 0; j < rows; j++) {\n        const gy = offsetY + j * pitch;\n        for (let i = 0; i < cols; i++) {\n          const gx = offsetX + i * pitch;\n\n          // Three slow interference waves → roughly 0..1 of \"light\".\n          const w =\n            Math.sin(gx * 0.0105 + t * 0.32) * Math.cos(gy * 0.0145 - t * 0.21) +\n            Math.sin((gx - gy) * 0.0062 + t * 0.17) * 0.8 +\n            Math.cos(Math.hypot(gx - width * 0.62, gy + height * 0.1) * 0.012 - t * 0.42) * 0.6;\n          let light = Math.max(0, (w + 1.1) / 3.5);\n          light = light * light * 1.35;\n\n          let x = gx;\n          let y = gy;\n\n          if (pull > 0.001 && radius > 0) {\n            const dx = gx - px;\n            const dy = gy - py;\n            const d = Math.hypot(dx, dy);\n            if (d < radius) {\n              // Squared falloff: a soft shoulder, no visible circular seam.\n              const k = 1 - d / radius;\n              const f = k * k * pull;\n              light += f * 1.25;\n              const push = (f * 7) / (d + 0.001);\n              x += dx * push;\n              y += dy * push;\n            }\n          }\n\n          for (let r = 0; r < rings.length; r++) {\n            const ring = rings[r];\n            const age = real - ring.born;\n            const d = Math.hypot(gx - ring.x, gy - ring.y);\n            const band = 1 - Math.abs(d - age * RIPPLE_SPEED) / 34;\n            if (band > 0) light += band * band * (1 - age / RIPPLE_LIFE) * 1.3;\n          }\n\n          dots[n++] = x;\n          dots[n++] = y;\n          dots[n++] = light;\n        }\n      }\n\n      // Three passes — resting dots, a faint bloom behind the lit ones, then\n      // the lit dots — so the fill style changes three times per frame\n      // instead of once per dot.\n      for (let pass = 0; pass < 3; pass++) {\n        ctx!.fillStyle = pass === 0 ? ink : lit;\n        for (let k = 0; k < n; k += 3) {\n          const light = dots[k + 2];\n          const isLit = light > LIT;\n          if ((pass > 0) !== isLit) continue;\n          const x = dots[k];\n          const y = dots[k + 1];\n          if (pass === 1) {\n            // Bloom: a wider, very faint square that reads as glow.\n            const glow = 5 + Math.min(4, light * 3);\n            ctx!.globalAlpha = Math.min(0.16, (light - LIT) * 0.22);\n            ctx!.fillRect(x - glow / 2, y - glow / 2, glow, glow);\n            continue;\n          }\n          const size = isLit ? 1.7 + Math.min(1.5, light * 1.1) : 1.3 + light * 1.2;\n          ctx!.globalAlpha = isLit ? Math.min(1, 0.55 + light * 0.45) : 0.18 + light * 0.8;\n          ctx!.fillRect(x - size / 2, y - size / 2, size, size);\n        }\n      }\n      ctx!.globalAlpha = 1;\n    }\n\n    function frame(now: number) {\n      const dt = last ? Math.min(0.05, (now - last) / 1000) : 0;\n      last = now;\n      clock += dt * opts.current.speed;\n      real += dt;\n\n      // Eased toward the target so the lens glides rather than snaps.\n      // Time-based easing, so the lens moves at the same speed on a 60Hz and\n      // a 120Hz display (a fixed per-frame factor runs twice as fast at 120).\n      const follow = 1 - Math.exp(-dt / 0.11);\n      const fade = 1 - Math.exp(-dt / 0.2);\n      pointer.x += (pointer.tx - pointer.x) * follow;\n      pointer.y += (pointer.ty - pointer.y) * follow;\n      pointer.strength += (pointer.target - pointer.strength) * fade;\n\n      for (let r = rings.length - 1; r >= 0; r--) {\n        if (real - rings[r].born > RIPPLE_LIFE) rings.splice(r, 1);\n      }\n\n      draw();\n      raf = requestAnimationFrame(frame);\n    }\n\n    function start() {\n      if (running || reduced || !onScreen || document.hidden) return;\n      running = true;\n      last = 0;\n      raf = requestAnimationFrame(frame);\n    }\n\n    function stop() {\n      running = false;\n      cancelAnimationFrame(raf);\n    }\n\n    // Pointer position in the canvas's own (untransformed) coordinates. The\n    // rect is on screen and may be scaled; width / rect.width undoes that.\n    function toLocal(e: PointerEvent): { x: number; y: number; inside: boolean } {\n      const rect = canvas!.getBoundingClientRect();\n      const sx = rect.width ? width / rect.width : 1;\n      const sy = rect.height ? height / rect.height : 1;\n      const x = (e.clientX - rect.left) * sx;\n      const y = (e.clientY - rect.top) * sy;\n      return { x, y, inside: x >= 0 && y >= 0 && x <= width && y <= height };\n    }\n\n    function onMove(e: PointerEvent) {\n      const { x, y, inside } = toLocal(e);\n      // Jump into place on entry so the lens doesn't sweep in from where the\n      // pointer last left.\n      if (pointer.target === 0 && inside) {\n        pointer.x = x;\n        pointer.y = y;\n      }\n      pointer.tx = x;\n      pointer.ty = y;\n      pointer.target = inside ? 1 : 0;\n    }\n\n    function onLeave() {\n      pointer.target = 0;\n    }\n\n    function onDown(e: PointerEvent) {\n      if (reduced || !opts.current.ripples) return;\n      const { x, y } = toLocal(e);\n      rings.push({ x, y, born: real });\n      if (rings.length > 4) rings.shift();\n    }\n\n    function onVisibility() {\n      if (document.hidden) stop();\n      else start();\n    }\n\n    refresh.current = () => {\n      readColors();\n      layout();\n    };\n\n    layout();\n    const ro = new ResizeObserver(layout);\n    ro.observe(host);\n\n    const io = new IntersectionObserver((entries) => {\n      const entry = entries[entries.length - 1];\n      onScreen = entry ? entry.isIntersecting : true;\n      if (onScreen) start();\n      else stop();\n    });\n    io.observe(host);\n\n    // A theme switch changes the html element's class; re-resolve colours.\n    const mo = new MutationObserver(() => {\n      readColors();\n      if (!running) draw();\n    });\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n\n    host.addEventListener(\"pointermove\", onMove, { passive: true });\n    host.addEventListener(\"pointerleave\", onLeave);\n    host.addEventListener(\"pointerdown\", onDown, { passive: true });\n    document.addEventListener(\"visibilitychange\", onVisibility);\n    start();\n\n    return () => {\n      stop();\n      ro.disconnect();\n      io.disconnect();\n      mo.disconnect();\n      host.removeEventListener(\"pointermove\", onMove);\n      host.removeEventListener(\"pointerleave\", onLeave);\n      host.removeEventListener(\"pointerdown\", onDown);\n      document.removeEventListener(\"visibilitychange\", onVisibility);\n      refresh.current = () => {};\n    };\n  }, []);\n\n  return (\n    <canvas\n      ref={canvasRef}\n      aria-hidden=\"true\"\n      className={\"pointer-events-none absolute inset-0 h-full w-full \" + className}\n    />\n  );\n}\n","type":"registry:component","target":"components/viberdy/signal-field.tsx"}],"meta":{"tier":"free","tags":["background","canvas","cursor","grid","interactive"],"href":"https://viberdy.dev/library/signal-field","aiPrompt":"Create a React + Tailwind component named SignalField: a full-bleed canvas background of small square dots on a fixed grid, lit by slow waves of light, with a pointer lens and click ripples.\n\nLook:\n- Dots sit on a regular grid (`spacing` px, default 22), centred so both margins match.\n- Each dot's brightness comes from three slow, overlapping sine/cosine waves in x, y and a radial term, so soft bands of light roll diagonally across the grid. A full swell should take around 20 seconds; this sits behind headlines and must never pull the eye off them.\n- Dimly lit dots use `color` (default #e8eaee) at low alpha. Dots above a brightness threshold switch to `tint` (default #79a4ff), grow slightly, and get a faint wider square behind them as bloom, so the brightest crests read as accent-coloured light.\n- `color` and `tint` accept any CSS colour OR a custom property like \"var(--accent)\". Resolve the variable with getComputedStyle, wrap bare HSL channels (\"222 47% 11%\") in hsl(), and fall back to the default for anything CSS.supports(\"color\", …) rejects. Re-resolve when the html element's class/style changes (theme switch) using a MutationObserver. Keep the var() pattern linear-time: no nested quantifiers.\n\nInteraction:\n- Pointer lens: within `lens` px of the pointer, dots brighten and are pushed outward with a SQUARED falloff (k = 1 - d / lens; f = k * k), so there is no visible circular seam. Ease the lens position and strength with TIME-based exponential smoothing (factor = 1 - exp(-dt / tau), tau about 0.11 s for position and 0.2 s for strength) so it glides the same on 60 Hz and 120 Hz displays. On first entry, jump the lens to the pointer instead of sweeping in from off-screen.\n- Click or tap (when `ripples` is true): a ring of light expands from the point at about 380 px/s and fades over about 1.9 s. Keep at most four rings.\n- Listen for pointer events on the canvas's PARENT element, not the canvas, so text and buttons layered above the background never block the lens. The canvas itself is pointer-events: none.\n\nImplementation requirements:\n- One <canvas>, absolutely positioned at 100% width and height of its parent. Measure the parent with clientWidth/clientHeight (its LAYOUT size), never getBoundingClientRect: the rect includes ancestor transforms, so inside a scaled card the grid would only fill part of the box. Convert pointer coordinates back the other way (multiply the offset from the rect by width / rect.width). Size the backing store by devicePixelRatio (capped at 2, and lowered so the canvas stays under about 8 megapixels), apply it with ctx.setTransform, and re-layout with a ResizeObserver on the parent.\n- Compute x, y and light for every dot into a reused Float32Array (allocate nothing per frame), then draw in three passes: resting dots, the bloom behind lit dots, then the lit dots. The fill style then changes three times per frame instead of once per dot.\n- Hold props in a ref synced from an effect, so a prop change adjusts the next frame instead of restarting the loop. `spacing`, `color` and `tint` are read at layout time, so that same effect must also re-run the layout and re-resolve the colours, or those props stop working after mount.\n- Pause the requestAnimationFrame loop when the parent scrolls out of view (IntersectionObserver) or the tab is hidden.\n- prefers-reduced-motion: draw a single still frame and disable the lens and ripples.\n- Clean everything up on unmount: cancel the frame and disconnect the observers and listeners.\n\nProps: spacing (number), speed (number, a wave speed multiplier where 0 holds the light still), lens (number, px radius where 0 turns the lens off), ripples (boolean), color (string), tint (string), className (string).\n\nOutput one self-contained \"use client\" component with no dependencies beyond React.","license":"https://viberdy.dev/license"}}