{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "magnetic-field-lines",
  "title": "Magnetic Field Lines",
  "description": "A field of iron filings that line up around a magnet you move: hundreds of short strokes swing round to follow a real dipole field, curving into the classic loops, glowing warm on the north side and cool on the south, and a click flips the poles.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/magnetic-field-lines/magnetic-field-lines.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport interface MagneticFieldLinesProps extends React.ComponentPropsWithoutRef<\"div\"> {\n  /** Distance between filings, in px. */\n  spacing?: number;\n  /** Length of each filing, in px. */\n  length?: number;\n  /** Colours for the north and south sides of the field. */\n  colors?: [string, string];\n  /** Colour of filings far from the magnet. */\n  dim?: string;\n  /** Background behind the filings. */\n  background?: string;\n  /** How far the magnet's pull reaches, as a share of the shorter side. */\n  reach?: number;\n}\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction rgb(hex: string): [number, number, number] {\n  const h = hex.replace(\"#\", \"\");\n  const full = h.length === 3 ? h.split(\"\").map((c) => c + c).join(\"\") : h.slice(0, 6);\n  const n = parseInt(full, 16) || 0;\n  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n}\n\nexport function MagneticFieldLines({ spacing = 22, length = 13, colors = [\"#ff5a5f\", \"#4d8dff\"], dim = \"#3a3d44\", background = \"#0b0c0f\", reach = 0.9, className, style, children, ...props }: MagneticFieldLinesProps) {\n  const reduce = useReducedMotion();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const live = React.useRef({ spacing, length, colors, dim, reach });\n  const kick = React.useRef<() => void>(() => {});\n  React.useEffect(() => {\n    live.current = { spacing, length, colors, dim, reach };\n    kick.current();\n  }, [spacing, length, colors, dim, reach]);\n\n  React.useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!root || !canvas || !ctx) return;\n    // The magnet: position, the direction it points (eases to follow the pointer's motion), and its polarity.\n    const mag = { x: 0, y: 0, tx: 0, ty: 0, a: 0, ta: 0, pol: 1, flip: 1, hover: false };\n    let angles = new Float32Array(0);\n    let w = 0;\n    let h = 0;\n    let raf = 0;\n    let visible = true;\n    let last = 0;\n\n    const resize = () => {\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n      w = root.clientWidth;\n      h = root.clientHeight;\n      canvas.width = Math.round(w * dpr);\n      canvas.height = Math.round(h * dpr);\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      if (!mag.hover) {\n        mag.x = mag.tx = w / 2;\n        mag.y = mag.ty = h / 2;\n      }\n    };\n\n    const draw = (dt: number) => {\n      const L = live.current;\n      // Idle, the magnet sits in the middle and turns slowly; with a pointer, it follows it.\n      if (!mag.hover && !reduce) mag.ta += dt * 0.35;\n      mag.x += (mag.tx - mag.x) * (1 - Math.exp(-dt * 10));\n      mag.y += (mag.ty - mag.y) * (1 - Math.exp(-dt * 10));\n      let da = mag.ta - mag.a;\n      da = Math.atan2(Math.sin(da), Math.cos(da));\n      mag.a += da * (1 - Math.exp(-dt * 5));\n      mag.flip += (mag.pol - mag.flip) * (1 - Math.exp(-dt * 8));\n      const mx = Math.cos(mag.a);\n      const my = Math.sin(mag.a);\n      const scale = Math.min(w, h) * L.reach;\n      const [nr, ng, nb] = rgb(L.colors[0]);\n      const [sr, sg, sb] = rgb(L.colors[1]);\n      const [dr, dg, db] = rgb(L.dim);\n      ctx.clearRect(0, 0, w, h);\n      ctx.lineCap = \"round\";\n      ctx.lineWidth = 1.6;\n      const cols = Math.ceil(w / L.spacing + 1);\n      const rows = Math.ceil(h / L.spacing + 1);\n      // The grid changes with the spacing prop: start the filings fresh when it does.\n      if (angles.length !== cols * rows) angles = new Float32Array(cols * rows).fill(Number.NaN);\n      const ox = (w - (cols - 1) * L.spacing) / 2;\n      const oy = (h - (rows - 1) * L.spacing) / 2;\n      const turn = 1 - Math.exp(-dt * 9);\n      let k = 0;\n      for (let j = 0; j < rows; j++)\n        for (let i = 0; i < cols; i++, k++) {\n          const x = ox + i * L.spacing;\n          const y = oy + j * L.spacing;\n          const rx = (x - mag.x) / scale;\n          const ry = (y - mag.y) / scale;\n          const r2 = rx * rx + ry * ry + 0.0025;\n          const r = Math.sqrt(r2);\n          const ux = rx / r;\n          const uy = ry / r;\n          // Dipole field: B ∝ (3(m·r̂)r̂ − m) / r³, flipped with the polarity.\n          const dot = mx * ux + my * uy;\n          const bx = ((3 * dot * ux - mx) / (r2 * r)) * mag.flip;\n          const by = ((3 * dot * uy - my) / (r2 * r)) * mag.flip;\n          const target = Math.atan2(by, bx);\n          // Filings swing round to the field rather than snapping (they're iron, after all).\n          let a = angles[k];\n          if (Number.isNaN(a) || reduce) a = target;\n          else {\n            let d = target - a;\n            d = Math.atan2(Math.sin(d), Math.cos(d));\n            a += d * turn;\n          }\n          angles[k] = a;\n          const strength = Math.min(1, Math.hypot(bx, by) * 0.045);\n          // North side warm, south side cool, both fading to dim far from the magnet.\n          const side = dot * mag.flip * 0.5 + 0.5;\n          const cr = nr * side + sr * (1 - side);\n          const cg = ng * side + sg * (1 - side);\n          const cb = nb * side + sb * (1 - side);\n          const s = Math.pow(strength, 0.6);\n          ctx.strokeStyle = `rgb(${(dr + (cr - dr) * s) | 0},${(dg + (cg - dg) * s) | 0},${(db + (cb - db) * s) | 0})`;\n          const len = (L.length * (0.55 + 0.45 * s)) / 2;\n          const cx = Math.cos(a) * len;\n          const cy = Math.sin(a) * len;\n          ctx.beginPath();\n          ctx.moveTo(x - cx, y - cy);\n          ctx.lineTo(x + cx, y + cy);\n          ctx.stroke();\n        }\n    };\n\n    const frame = (now: number) => {\n      const dt = Math.min(0.05, last ? (now - last) / 1000 : 1 / 60);\n      last = now;\n      draw(dt);\n      if (visible && !document.hidden && !reduce) raf = requestAnimationFrame(frame);\n      else last = 0;\n    };\n    const start = () => {\n      cancelAnimationFrame(raf);\n      raf = requestAnimationFrame(frame);\n    };\n    kick.current = start;\n\n    const local = (event: PointerEvent) => {\n      const r = root.getBoundingClientRect();\n      const s = r.width / root.offsetWidth || 1;\n      return { x: (event.clientX - r.left) / s, y: (event.clientY - r.top) / s };\n    };\n    const onMove = (event: PointerEvent) => {\n      const p = local(event);\n      const dx = p.x - mag.tx;\n      const dy = p.y - mag.ty;\n      // The magnet turns to point the way it's being moved.\n      if (mag.hover && dx * dx + dy * dy > 4) mag.ta = Math.atan2(dy, dx);\n      mag.tx = p.x;\n      mag.ty = p.y;\n      mag.hover = true;\n      if (reduce) draw(1);\n    };\n    const onLeave = () => {\n      mag.hover = false;\n      mag.tx = w / 2;\n      mag.ty = h / 2;\n    };\n    const onDown = () => {\n      mag.pol *= -1;\n      if (reduce) draw(1);\n    };\n    const ro = new ResizeObserver(() => {\n      resize();\n      draw(1);\n    });\n    ro.observe(root);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      if (visible) start();\n    });\n    io.observe(root);\n    root.addEventListener(\"pointermove\", onMove);\n    root.addEventListener(\"pointerleave\", onLeave);\n    root.addEventListener(\"pointerdown\", onDown);\n    resize();\n    start();\n    return () => {\n      cancelAnimationFrame(raf);\n      kick.current = () => {};\n      ro.disconnect();\n      io.disconnect();\n      root.removeEventListener(\"pointermove\", onMove);\n      root.removeEventListener(\"pointerleave\", onLeave);\n      root.removeEventListener(\"pointerdown\", onDown);\n    };\n  }, [reduce]);\n\n  return (\n    <div ref={rootRef} className={cn(\"relative isolate overflow-hidden\", className)} style={{ background, ...style }} {...props}>\n      <canvas ref={canvasRef} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 -z-10 h-full w-full\" />\n      {children}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}