{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"magnet-lines","type":"registry:component","title":"Magnet lines","description":"Lines turn toward your cursor like iron filings near a magnet.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":[],"registryDependencies":["utils"],"files":[{"path":"components/magnet-lines.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst COLS = 12;\nconst ROWS = 9;\n// Leaves a clear gap between neighbours even when both point at each other.\nconst LENGTH = 18;\nconst WIDTH = 2;\n// Lines near the pointer grow a little, as if pulled into the field.\nconst GROW = 0.35;\n// Within this distance a line reads as close: brighter and longer.\nconst FIELD = 160;\n// Slightly underdamped (ratio 0.6), so a line swings past and settles\n// instead of snapping straight to its target.\nconst STIFFNESS = 260;\nconst DAMPING_RATIO = 0.6;\n// The distance at which a line has half its full stiffness. Beyond it,\n// lines turn noticeably later, so the pull ripples outward.\nconst HALF_PULL = 90;\n// Even the farthest lines keep this share, so none ever feels stuck.\nconst FAR_STIFFNESS = 0.18;\n// The idle wave: a slow tilt that travels diagonally across the grid.\nconst WAVE_SPEED = 0.7;\nconst WAVE_SWING = 0.45;\n// Soft, so letting go reads as the field relaxing back into the wave.\nconst WAVE_STIFFNESS = 40;\nconst REST = 0.001;\n// A page left open shouldn't animate forever: after this long without\n// pointer activity the wave freezes, and any pointer wakes it again.\nconst IDLE_PAUSE = 10_000;\n\ntype Point = { x: number; y: number };\n\n// Segments have no head, so a line pointing at the cursor or directly away\n// looks the same. Wrapping by half a turn means one never spins 180deg.\nfunction halfTurn(delta: number) {\n  return delta - Math.PI * Math.round(delta / Math.PI);\n}\n\nexport function MagnetLines({ className }: { className?: string }) {\n  const reduce = useReducedMotion() ?? false;\n  const wrapRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n\n  useEffect(() => {\n    const wrap = wrapRef.current;\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!wrap || !canvas || !ctx) return;\n\n    const count = COLS * ROWS;\n    // Flat typed arrays keep the per-frame loop allocation free.\n    const baseX = new Float32Array(count);\n    const baseY = new Float32Array(count);\n    const angle = new Float32Array(count);\n    const spin = new Float32Array(count);\n    // 0 far away, 1 under the pointer; eased so brightness never pops.\n    const near = new Float32Array(count);\n\n    let width = 0;\n    let height = 0;\n    let pointer: Point | null = null;\n    let last: Point | null = null;\n    let frameId = 0;\n    let pending = 0;\n    let then = 0;\n    let inView = true;\n    let visible = true;\n    let activeAt = performance.now();\n    let waveT = performance.now() / 1000;\n    let dim = \"\";\n    let lit = \"\";\n\n    const wave = (i: number, t: number) => {\n      const c = i % COLS;\n      const r = (i / COLS) | 0;\n      return (\n        Math.PI / 4 + WAVE_SWING * Math.sin(t * WAVE_SPEED - c * 0.45 - r * 0.35)\n      );\n    };\n\n    const readColors = () => {\n      // Computed colors resolve light-dark(), which a raw custom property doesn't.\n      dim = getComputedStyle(canvas).color;\n      lit = getComputedStyle(wrap).color;\n    };\n\n    const layout = () => {\n      const dpr = window.devicePixelRatio || 1;\n      width = wrap.clientWidth;\n      height = wrap.clientHeight;\n      canvas.width = Math.round(width * dpr);\n      canvas.height = Math.round(height * dpr);\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      // Each line sits in the middle of an equal cell, so margins match.\n      const cellX = width / COLS;\n      const cellY = height / ROWS;\n      for (let i = 0; i < count; i++) {\n        baseX[i] = (i % COLS) * cellX + cellX / 2;\n        baseY[i] = ((i / COLS) | 0) * cellY + cellY / 2;\n      }\n    };\n\n    const segment = (i: number) => {\n      const half = (LENGTH * (1 + GROW * near[i])) / 2;\n      const dx = Math.cos(angle[i]) * half;\n      const dy = Math.sin(angle[i]) * half;\n      ctx.moveTo(baseX[i] - dx, baseY[i] - dy);\n      ctx.lineTo(baseX[i] + dx, baseY[i] + dy);\n    };\n\n    const draw = () => {\n      ctx.clearRect(0, 0, width, height);\n      ctx.lineWidth = WIDTH;\n      ctx.lineCap = \"round\";\n      // One batched path for the whole field; only the energised lines get\n      // a second, brighter pass on top.\n      ctx.strokeStyle = dim;\n      ctx.beginPath();\n      for (let i = 0; i < count; i++) segment(i);\n      ctx.stroke();\n      ctx.strokeStyle = lit;\n      for (let i = 0; i < count; i++) {\n        if (near[i] < 0.02) continue;\n        ctx.globalAlpha = Math.min(1, near[i]);\n        ctx.beginPath();\n        segment(i);\n        ctx.stroke();\n      }\n      ctx.globalAlpha = 1;\n    };\n\n    const nearness = (i: number, p: Point) => {\n      const d = Math.hypot(baseX[i] - p.x, baseY[i] - p.y);\n      return Math.max(0, 1 - d / FIELD) ** 2;\n    };\n\n    // Reduced motion: every line turns to the pointer in one step, no swing.\n    const orientOnce = (p: Point) => {\n      for (let i = 0; i < count; i++) {\n        angle[i] = Math.atan2(p.y - baseY[i], p.x - baseX[i]);\n        near[i] = nearness(i, p);\n      }\n      draw();\n    };\n\n    const step = (now: number) => {\n      // Clamped so a dropped frame can't kick the springs into orbit.\n      const dt = Math.min((now - then) / 1000, 1 / 30);\n      then = now;\n      // The wave's own clock stops once idle, so its targets hold still, the\n      // springs settle and the loop sleeps. Resuming picks up where it froze.\n      const waving = !pointer && now - activeAt < IDLE_PAUSE;\n      if (waving) waveT += dt;\n      const t = waveT;\n      let moving = waving;\n\n      for (let i = 0; i < count; i++) {\n        let target: number;\n        let k: number;\n        let n = 0;\n        if (pointer) {\n          target = Math.atan2(pointer.y - baseY[i], pointer.x - baseX[i]);\n          const d = Math.hypot(baseX[i] - pointer.x, baseY[i] - pointer.y);\n          k = STIFFNESS * (FAR_STIFFNESS + (1 - FAR_STIFFNESS) / (1 + d / HALF_PULL));\n          n = nearness(i, pointer);\n        } else {\n          target = wave(i, t);\n          k = WAVE_STIFFNESS;\n        }\n        const damping = 2 * DAMPING_RATIO * Math.sqrt(k);\n        const delta = halfTurn(target - angle[i]);\n        spin[i] += (k * delta - damping * spin[i]) * dt;\n        angle[i] += spin[i] * dt;\n        // A plain ease is enough for brightness; it only has to avoid popping.\n        near[i] += (n - near[i]) * Math.min(1, dt * 12);\n\n        if (\n          Math.abs(delta) > REST ||\n          Math.abs(spin[i]) > REST ||\n          Math.abs(n - near[i]) > REST\n        ) {\n          moving = true;\n        }\n      }\n      draw();\n      // With the pointer resting, everything settles and the loop sleeps.\n      // Without one, the idle wave runs for a while, but only on screen.\n      frameId = moving && visible ? requestAnimationFrame(step) : 0;\n    };\n\n    const wake = () => {\n      if (frameId || !visible || reduce) return;\n      then = performance.now();\n      frameId = requestAnimationFrame(step);\n    };\n\n    const aim = (e: PointerEvent) => {\n      activeAt = performance.now();\n      const box = canvas.getBoundingClientRect();\n      const p = { x: e.clientX - box.left, y: e.clientY - box.top };\n      last = p;\n      if (reduce) {\n        // One draw per frame at most; pointermove can fire far faster.\n        if (!pending) {\n          pending = requestAnimationFrame(() => {\n            pending = 0;\n            if (last) orientOnce(last);\n          });\n        }\n        return;\n      }\n      pointer = p;\n      wake();\n    };\n\n    const release = () => {\n      // Reduced motion keeps the last orientation instead of drifting back.\n      if (reduce) return;\n      activeAt = performance.now();\n      pointer = null;\n      wake();\n    };\n\n    const onMove = (e: PointerEvent) => {\n      // A finger only steers while pressed, which onDown captures.\n      if (e.pointerType === \"touch\" && !canvas.hasPointerCapture(e.pointerId)) {\n        return;\n      }\n      aim(e);\n    };\n    const onDown = (e: PointerEvent) => {\n      if (e.pointerType !== \"touch\") return;\n      canvas.setPointerCapture(e.pointerId);\n      aim(e);\n    };\n    const onUp = (e: PointerEvent) => {\n      if (e.pointerType === \"touch\") release();\n    };\n    const onLeave = (e: PointerEvent) => {\n      if (e.pointerType !== \"touch\") release();\n    };\n\n    readColors();\n    layout();\n    if (reduce) waveT = 0;\n    for (let i = 0; i < count; i++) angle[i] = wave(i, waveT);\n    draw();\n    wake();\n\n    const resize = new ResizeObserver(() => {\n      layout();\n      if (reduce && last) orientOnce(last);\n      else draw();\n    });\n    resize.observe(wrap);\n\n    const repaint = () =>\n      requestAnimationFrame(() => {\n        readColors();\n        if (!frameId) draw();\n      });\n    const theme = new MutationObserver(repaint);\n    theme.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"data-theme\"],\n    });\n    const scheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    scheme.addEventListener(\"change\", repaint);\n\n    // Offscreen or in a hidden tab, the loop stops entirely, wave included.\n    // Coming back counts as activity, so the wave plays again for a while.\n    const sync = () => {\n      const was = visible;\n      visible = inView && !document.hidden;\n      if (visible && !was) {\n        activeAt = performance.now();\n        wake();\n      } else if (!visible && frameId) {\n        cancelAnimationFrame(frameId);\n        frameId = 0;\n      }\n    };\n    const seen = new IntersectionObserver(([entry]) => {\n      inView = entry.isIntersecting;\n      sync();\n    });\n    seen.observe(wrap);\n    document.addEventListener(\"visibilitychange\", sync);\n\n    canvas.addEventListener(\"pointermove\", onMove);\n    canvas.addEventListener(\"pointerdown\", onDown);\n    canvas.addEventListener(\"pointerup\", onUp);\n    canvas.addEventListener(\"pointercancel\", onUp);\n    canvas.addEventListener(\"pointerleave\", onLeave);\n\n    return () => {\n      cancelAnimationFrame(frameId);\n      cancelAnimationFrame(pending);\n      resize.disconnect();\n      theme.disconnect();\n      seen.disconnect();\n      document.removeEventListener(\"visibilitychange\", sync);\n      scheme.removeEventListener(\"change\", repaint);\n      canvas.removeEventListener(\"pointermove\", onMove);\n      canvas.removeEventListener(\"pointerdown\", onDown);\n      canvas.removeEventListener(\"pointerup\", onUp);\n      canvas.removeEventListener(\"pointercancel\", onUp);\n      canvas.removeEventListener(\"pointerleave\", onLeave);\n    };\n  }, [reduce]);\n\n  return (\n    <div\n      ref={wrapRef}\n      className={cn(\n        \"relative aspect-[4/3] w-[min(480px,100%)] overflow-hidden rounded-2xl bg-muted text-foreground shadow-raised\",\n        className,\n      )}\n    >\n      {/* touch-none: while a finger is down it steers the field, so the page\n          shouldn't scroll out from under it. */}\n      <canvas\n        ref={canvasRef}\n        aria-hidden\n        className=\"absolute inset-0 size-full touch-none text-muted-foreground\"\n      />\n      <p className=\"sr-only\">\n        A decorative grid of short lines that turn to point at the pointer,\n        like iron filings around a magnet, and drift in a slow wave when left\n        alone.\n      </p>\n    </div>\n  );\n}\n\nexport default function MagnetLinesDemo() {\n  return <MagnetLines />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["playground"],"docs":"From ui lab: https://lab.xevrion.dev/lab/magnet-lines"}