{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"bar-magnet-cursor-that-combs-iron-filings-on-paper-into-field-lines","type":"registry:block","title":"Bar Magnet Cursor That Combs Iron Filings on Paper into Field Lines","description":"Cursor effect with a bar magnet that follows the pointer over iron filings, which turn and chain into field lines. Copy the React code or HTML free.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/bar-magnet-cursor-that-combs-iron-filings-on-paper-into-field-lines.tsx","type":"registry:component","content":"import { useEffect, useRef } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from \"react\";\nimport { useReducedMotion } from \"framer-motion\";\n\n/** One filing for roughly this many square pixels of paper. Lower is denser and slower. */\nconst AREA_PER_FILING = 58;\nconst MAX_FILINGS = 7000;\n/** How many field lines leave the magnet. The filings bunch onto them near the poles. */\nconst LINES = 40;\n/** How far the field combs the filings straight. Raise it and the whole sheet lines up. */\nconst REACH = 240;\nconst INK = [\"#17171b\", \"#3d3d45\"];\nconst PAPER_GRAIN =\n  \"url(\\\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='220' height='220'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 0.35 0 0 0 0 0.32 0 0 0 0 0.28 0 0 0 0.09 0'/%3E%3C/filter%3E%3Crect width='220' height='220' filter='url(%23n)'/%3E%3C/svg%3E\\\")\";\n\nexport default function BarMagnetCursorThatCombsIronFilingsOnPaperIntoFieldLines() {\n  const reduce = useReducedMotion();\n  const sheet = useRef<HTMLButtonElement>(null);\n  const canvas = useRef<HTMLCanvasElement>(null);\n  /** Where the magnet is being led (0 to 1 each way), when a person last led it, and quarter turns still owed. */\n  const aim = useRef({ x: 0.62, y: 0.46, at: -1e6, spin: 0 });\n\n  useEffect(() => {\n    const el = sheet.current;\n    const cv = canvas.current;\n    if (!el || !cv) return;\n    const ctx = cv.getContext(\"2d\");\n    if (!ctx) return;\n\n    let W = 1;\n    let H = 1;\n    let ratio = 1;\n    let n = 0;\n    let hx = new Float32Array(0);\n    let hy = new Float32Array(0);\n    let px = new Float32Array(0);\n    let py = new Float32Array(0);\n    let vx = new Float32Array(0);\n    let vy = new Float32Array(0);\n    let dx = new Float32Array(0);\n    let dy = new Float32Array(0);\n    let ox = new Float32Array(0);\n    let oy = new Float32Array(0);\n    let len = new Float32Array(0);\n    let quick = new Float32Array(0);\n    // The magnet: position, speed, heading and length, in pixels of the sheet.\n    const mag = { x: 0, y: 0, vx: 0, vy: 0, phi: -0.5, len: 96 };\n    let placed = false;\n\n    const scatter = () => {\n      ratio = Math.min(window.devicePixelRatio || 1, 2);\n      W = el.clientWidth;\n      H = el.clientHeight;\n      cv.width = Math.round(W * ratio);\n      cv.height = Math.round(H * ratio);\n      mag.len = Math.max(74, Math.min(128, W * 0.18));\n      n = Math.min(MAX_FILINGS, Math.round((W * H) / AREA_PER_FILING));\n      const cols = Math.ceil(Math.sqrt((n * W) / H));\n      const rows = Math.ceil(n / cols);\n      n = cols * rows;\n      hx = new Float32Array(n);\n      hy = new Float32Array(n);\n      px = new Float32Array(n);\n      py = new Float32Array(n);\n      vx = new Float32Array(n);\n      vy = new Float32Array(n);\n      dx = new Float32Array(n);\n      dy = new Float32Array(n);\n      ox = new Float32Array(n);\n      oy = new Float32Array(n);\n      len = new Float32Array(n);\n      quick = new Float32Array(n);\n      let seed = 11;\n      const rnd = () => {\n        seed = (seed * 1664525 + 1013904223) % 4294967296;\n        return seed / 4294967296;\n      };\n      // Sprinkled evenly but not in a grid: one filing somewhere in each small cell.\n      for (let i = 0; i < n; i++) {\n        hx[i] = (((i % cols) + rnd()) / cols) * W;\n        hy[i] = ((Math.floor(i / cols) + rnd()) / rows) * H;\n        px[i] = hx[i];\n        py[i] = hy[i];\n        const a = rnd() * Math.PI;\n        ox[i] = Math.cos(a);\n        oy[i] = Math.sin(a);\n        dx[i] = ox[i];\n        dy[i] = oy[i];\n        len[i] = rnd() < 0.16 ? 1.2 + rnd() * 1.6 : 3.4 + rnd() * rnd() * 9;\n        quick[i] = 45 + rnd() * 110;\n      }\n      if (!placed) {\n        mag.x = aim.current.x * W;\n        mag.y = aim.current.y * H;\n        placed = true;\n      }\n    };\n\n    const step = (dt: number, settle: boolean) => {\n      const half = mag.len / 2 - 7;\n      const ux = Math.cos(mag.phi);\n      const uy = Math.sin(mag.phi);\n      const nx = mag.x + ux * half;\n      const ny = mag.y + uy * half;\n      const sx = mag.x - ux * half;\n      const sy = mag.y - uy * half;\n      const gap = (Math.PI * 2) / LINES;\n      const keep = mag.len * 0.2;\n      for (let i = 0; i < n; i++) {\n        const ax = hx[i] - nx;\n        const ay = hy[i] - ny;\n        const bx = hx[i] - sx;\n        const by = hy[i] - sy;\n        const r1 = ax * ax + ay * ay + 40;\n        const r2 = bx * bx + by * by + 40;\n        // The field at this filing: out of the north pole, into the south.\n        const fx = ax / r1 - bx / r2;\n        const fy = ay / r1 - by / r2;\n        const f2 = fx * fx + fy * fy + 1e-12;\n        const f = Math.sqrt(f2);\n        // Far from the magnet a filing keeps the angle it fell at. Close in, it turns along the field.\n        const comb = Math.min(1, Math.pow(f * REACH, 0.75));\n        let rx = ox[i];\n        let ry = oy[i];\n        if (rx * fx + ry * fy < 0) {\n          rx = -rx;\n          ry = -ry;\n        }\n        let tx = rx + (fx / f - rx) * comb;\n        let ty = ry + (fy / f - ry) * comb;\n        if (tx * dx[i] + ty * dy[i] < 0) {\n          tx = -tx;\n          ty = -ty;\n        }\n        // Filings chain end to end, so they gather onto separate lines with bare paper between. Slide each one sideways to its nearest line.\n        const psi = Math.atan2(ay, ax) - Math.atan2(by, bx);\n        const off = psi - Math.round(psi / gap) * gap;\n        const apart = gap / f;\n        const hold = Math.max(0, Math.min(1, (30 - apart) / 16));\n        let mx = (off * fy * hold) / f2;\n        let my = (-off * fx * hold) / f2;\n        const far = Math.hypot(mx, my);\n        if (far > 9) {\n          mx *= 9 / far;\n          my *= 9 / far;\n        }\n        // The nearest ones are dragged right up to the poles and bristle there.\n        const d1 = Math.sqrt(r1);\n        const d2 = Math.sqrt(r2);\n        // They stop a little short of the pole itself, so they pile up round the end of the bar and not at one point under it.\n        const p1 = Math.min(30 * Math.exp(-d1 / 44), Math.max(0, d1 - keep));\n        const p2 = Math.min(30 * Math.exp(-d2 / 44), Math.max(0, d2 - keep));\n        const gx = hx[i] + mx - (ax / d1) * p1 - (bx / d2) * p2;\n        const gy = hy[i] + my - (ay / d1) * p1 - (by / d2) * p2;\n        if (settle) {\n          px[i] = gx;\n          py[i] = gy;\n          const m = Math.hypot(tx, ty) || 1;\n          dx[i] = tx / m;\n          dy[i] = ty / m;\n          continue;\n        }\n        const k = quick[i];\n        vx[i] += ((gx - px[i]) * k - vx[i] * 1.5 * Math.sqrt(k)) * dt;\n        vy[i] += ((gy - py[i]) * k - vy[i] * 1.5 * Math.sqrt(k)) * dt;\n        px[i] += vx[i] * dt;\n        py[i] += vy[i] * dt;\n        const turn = Math.min(1, dt * k * 0.1);\n        const qx = dx[i] + (tx - dx[i]) * turn;\n        const qy = dy[i] + (ty - dy[i]) * turn;\n        const m = Math.hypot(qx, qy) || 1;\n        dx[i] = qx / m;\n        dy[i] = qy / m;\n      }\n    };\n\n    const rounded = (x: number, y: number, w: number, h: number, r: number) => {\n      ctx.beginPath();\n      ctx.moveTo(x + r, y);\n      ctx.arcTo(x + w, y, x + w, y + h, r);\n      ctx.arcTo(x + w, y + h, x, y + h, r);\n      ctx.arcTo(x, y + h, x, y, r);\n      ctx.arcTo(x, y, x + w, y, r);\n      ctx.closePath();\n    };\n\n    const paint = () => {\n      const flat = () => ctx.setTransform(ratio, 0, 0, ratio, 0, 0);\n      const turned = () => {\n        flat();\n        ctx.translate(mag.x, mag.y);\n        ctx.rotate(mag.phi);\n      };\n      flat();\n      ctx.clearRect(0, 0, W, H);\n      ctx.lineCap = \"round\";\n      // Each filing lies on the paper, so it has a faint shadow on the side away from the lamp.\n      ctx.beginPath();\n      for (let i = 0; i < n; i++) {\n        const l = len[i] / 2;\n        ctx.moveTo(px[i] - dx[i] * l + 0.9, py[i] - dy[i] * l + 1.3);\n        ctx.lineTo(px[i] + dx[i] * l + 0.9, py[i] + dy[i] * l + 1.3);\n      }\n      ctx.strokeStyle = \"rgba(70,58,40,0.16)\";\n      ctx.lineWidth = 1.6;\n      ctx.stroke();\n      // The filings themselves, in two weights of grey so the sheet does not look printed.\n      for (let tone = 0; tone < 2; tone++) {\n        ctx.beginPath();\n        for (let i = tone; i < n; i += 2) {\n          const l = len[i] / 2;\n          ctx.moveTo(px[i] - dx[i] * l, py[i] - dy[i] * l);\n          ctx.lineTo(px[i] + dx[i] * l, py[i] + dy[i] * l);\n        }\n        ctx.strokeStyle = INK[tone];\n        ctx.lineWidth = tone ? 0.9 : 1.35;\n        ctx.stroke();\n      }\n\n      // The magnet. Its shape turns, but every gradient is laid down in sheet coordinates, so the light stays where the lamp is.\n      const L = mag.len;\n      const T = L * 0.3;\n      const lit = ctx.createLinearGradient(mag.x - L * 0.5, mag.y - L * 0.5, mag.x + L * 0.5, mag.y + L * 0.5);\n      turned();\n      ctx.shadowColor = \"rgba(20,18,14,0.42)\";\n      ctx.shadowBlur = 16 * ratio;\n      ctx.shadowOffsetX = 5 * ratio;\n      ctx.shadowOffsetY = 10 * ratio;\n      rounded(-L / 2, -T / 2, L, T, T * 0.2);\n      flat();\n      lit.addColorStop(0, \"#fbfbfc\");\n      lit.addColorStop(0.45, \"#b6bac2\");\n      lit.addColorStop(1, \"#6f747e\");\n      ctx.fillStyle = lit;\n      ctx.fill();\n      ctx.shadowColor = \"transparent\";\n      // North half in red enamel.\n      turned();\n      ctx.save();\n      rounded(-L / 2, -T / 2, L, T, T * 0.2);\n      ctx.clip();\n      ctx.beginPath();\n      ctx.rect(0, -T / 2, L / 2, T);\n      flat();\n      const red = ctx.createLinearGradient(mag.x - L * 0.5, mag.y - L * 0.5, mag.x + L * 0.5, mag.y + L * 0.5);\n      red.addColorStop(0, \"#ff7a6b\");\n      red.addColorStop(0.45, \"#d8362b\");\n      red.addColorStop(1, \"#8e1711\");\n      ctx.fillStyle = red;\n      ctx.fill();\n      ctx.restore();\n      // A flat top face inside a chamfer: lighter than the body, with a lit and a shaded edge.\n      turned();\n      rounded(-L / 2 + 2.5, -T / 2 + 2.5, L - 5, T - 5, T * 0.14);\n      flat();\n      const face = ctx.createLinearGradient(mag.x - L * 0.5, mag.y - L * 0.5, mag.x + L * 0.5, mag.y + L * 0.5);\n      face.addColorStop(0, \"rgba(255,255,255,0.34)\");\n      face.addColorStop(0.5, \"rgba(255,255,255,0.10)\");\n      face.addColorStop(1, \"rgba(0,0,0,0.10)\");\n      ctx.fillStyle = face;\n      ctx.fill();\n      const edge = ctx.createLinearGradient(mag.x - L * 0.4, mag.y - L * 0.4, mag.x + L * 0.4, mag.y + L * 0.4);\n      edge.addColorStop(0, \"rgba(255,255,255,0.95)\");\n      edge.addColorStop(0.5, \"rgba(255,255,255,0.12)\");\n      edge.addColorStop(1, \"rgba(0,0,0,0.42)\");\n      ctx.strokeStyle = edge;\n      ctx.lineWidth = 1;\n      ctx.stroke();\n      turned();\n      rounded(-L / 2, -T / 2, L, T, T * 0.2);\n      flat();\n      ctx.strokeStyle = \"rgba(30,26,22,0.55)\";\n      ctx.lineWidth = 0.8;\n      ctx.stroke();\n      // The seam between the halves, a long glint on whichever long edge faces the lamp, and the stamped letters.\n      turned();\n      ctx.beginPath();\n      ctx.moveTo(0, -T / 2 + 1);\n      ctx.lineTo(0, T / 2 - 1);\n      ctx.strokeStyle = \"rgba(0,0,0,0.35)\";\n      ctx.lineWidth = 1;\n      ctx.stroke();\n      const side = -Math.sin(mag.phi) * -0.6 + Math.cos(mag.phi) * -0.8 > 0 ? 1 : -1;\n      ctx.beginPath();\n      ctx.moveTo(-L / 2 + T * 0.35, side * T * 0.2);\n      ctx.lineTo(L / 2 - T * 0.35, side * T * 0.2);\n      ctx.strokeStyle = \"rgba(255,255,255,0.5)\";\n      ctx.lineWidth = T * 0.09;\n      ctx.stroke();\n      ctx.font = `700 ${Math.round(T * 0.46)}px ui-sans-serif, system-ui, sans-serif`;\n      ctx.textAlign = \"center\";\n      ctx.textBaseline = \"middle\";\n      for (const [letter, at, ink] of [[\"N\", L * 0.27, \"rgba(70,8,4,0.8)\"], [\"S\", -L * 0.27, \"rgba(40,44,52,0.75)\"]] as const) {\n        ctx.save();\n        ctx.translate(at, 0);\n        ctx.rotate(-mag.phi);\n        ctx.fillStyle = \"rgba(255,255,255,0.5)\";\n        ctx.fillText(letter, 0.6, 1.1);\n        ctx.fillStyle = ink;\n        ctx.fillText(letter, 0, 0.4);\n        ctx.restore();\n      }\n      flat();\n    };\n\n    let visible = true;\n    let raf = 0;\n    let last = 0;\n    const started = performance.now();\n\n    const loop = (stamp: number) => {\n      const t = (stamp - started) / 1000;\n      const dt = Math.min(last ? (stamp - last) / 1000 : 0.016, 0.033);\n      last = stamp;\n      const a = aim.current;\n      let tx = a.x * W;\n      let ty = a.y * H;\n      // Left alone, the magnet is led round the sheet in a slow loop.\n      if (stamp - a.at > 2400) {\n        tx = W * (0.5 + 0.3 * Math.sin(t * 0.52 + 0.9) + 0.04 * Math.sin(t * 1.7));\n        ty = H * (0.5 + 0.24 * Math.sin(t * 0.83 + 2.4));\n      }\n      // It has weight: it lags the pointer, overshoots a touch and trails its long side into the direction of travel.\n      mag.vx += ((tx - mag.x) * 70 - mag.vx * 13) * dt;\n      mag.vy += ((ty - mag.y) * 70 - mag.vy * 13) * dt;\n      mag.x += mag.vx * dt;\n      mag.y += mag.vy * dt;\n      const speed = Math.hypot(mag.vx, mag.vy);\n      if (speed > 8) {\n        let lean = Math.atan2(mag.vy, mag.vx) - mag.phi;\n        lean -= Math.round(lean / Math.PI) * Math.PI;\n        mag.phi += lean * Math.min(1, speed / 500) * Math.min(1, dt * 5);\n      }\n      const owed = a.spin * Math.min(1, dt * 7);\n      mag.phi += owed;\n      a.spin -= owed;\n      step(dt, false);\n      paint();\n      raf = visible && !document.hidden ? requestAnimationFrame(loop) : 0;\n    };\n    const wake = () => {\n      if (reduce) {\n        mag.phi += aim.current.spin;\n        aim.current.spin = 0;\n        mag.x = aim.current.x * W;\n        mag.y = aim.current.y * H;\n        step(0, true);\n        paint();\n        return;\n      }\n      if (!raf && visible && !document.hidden) {\n        last = 0;\n        raf = requestAnimationFrame(loop);\n      }\n    };\n\n    const ro = new ResizeObserver(() => {\n      scatter();\n      step(0, true);\n      paint();\n    });\n    ro.observe(el);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      wake();\n    });\n    io.observe(el);\n    document.addEventListener(\"visibilitychange\", wake);\n    // With motion reduced nothing loops: the sheet redraws once, settled, each time the magnet is moved or turned.\n    el.addEventListener(\"magnet-moved\", wake);\n    scatter();\n    step(0, true);\n    paint();\n    wake();\n\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", wake);\n      el.removeEventListener(\"magnet-moved\", wake);\n    };\n  }, [reduce]);\n\n  const moved = () => sheet.current?.dispatchEvent(new Event(\"magnet-moved\"));\n\n  function lead(e: ReactPointerEvent<HTMLButtonElement>) {\n    const r = e.currentTarget.getBoundingClientRect();\n    aim.current = { ...aim.current, x: (e.clientX - r.left) / r.width, y: (e.clientY - r.top) / r.height, at: performance.now() };\n    moved();\n  }\n  /** Arrow keys slide the magnet. Enter and Space, like a click, give it a quarter turn. */\n  function onKey(e: ReactKeyboardEvent<HTMLButtonElement>) {\n    const by = ({ ArrowLeft: [-0.06, 0], ArrowRight: [0.06, 0], ArrowUp: [0, -0.07], ArrowDown: [0, 0.07] } as Record<string, [number, number]>)[e.key];\n    if (!by) return;\n    e.preventDefault();\n    const a = aim.current;\n    aim.current = { ...a, x: Math.min(0.92, Math.max(0.08, a.x + by[0])), y: Math.min(0.9, Math.max(0.1, a.y + by[1])), at: performance.now() + 6000 };\n    moved();\n  }\n  function quarterTurn() {\n    aim.current = { ...aim.current, spin: aim.current.spin + Math.PI / 2, at: Math.max(aim.current.at, performance.now()) };\n    moved();\n  }\n\n  return (\n    <section className=\"relative isolate flex min-h-[760px] w-full flex-col items-center justify-center overflow-hidden bg-[#dcd9d3] px-4 py-14\">\n      <div aria-hidden=\"true\" className=\"absolute inset-0 -z-10\" style={{ background: \"radial-gradient(70% 60% at 42% 36%, #eeece8 0%, #dcd9d3 60%, #cfcbc4 100%)\" }} />\n      <button\n        ref={sheet}\n        type=\"button\"\n        onClick={quarterTurn}\n        onPointerMove={lead}\n        onPointerDown={lead}\n        onKeyDown={onKey}\n        aria-label=\"A bar magnet on a sheet of paper covered in iron filings. Arrow keys slide the magnet, Enter gives it a quarter turn.\"\n        className=\"relative block aspect-[4/5] w-[min(92vw,720px)] cursor-grab touch-pan-y overflow-hidden rounded-[3px] bg-[#fbfaf6] shadow-[0_1px_0_rgba(255,255,255,0.9)_inset,0_1px_2px_rgba(40,34,24,0.18),0_18px_30px_-12px_rgba(40,34,24,0.28),0_50px_80px_-30px_rgba(40,34,24,0.35)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900 focus-visible:ring-offset-4 focus-visible:ring-offset-[#dcd9d3] active:cursor-grabbing sm:aspect-[3/2]\"\n        style={{ backgroundImage: PAPER_GRAIN }}\n      >\n        <canvas ref={canvas} aria-hidden=\"true\" className=\"absolute inset-0 h-full w-full\" />\n        <span className=\"pointer-events-none absolute bottom-3 left-4 rounded-sm bg-[#fbfaf6]/85 px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-[0.18em] text-neutral-700\">Plate 7 / Field of a bar magnet</span>\n        <span className=\"pointer-events-none absolute bottom-3 right-4 hidden rounded-sm bg-[#fbfaf6]/85 px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-[0.18em] text-neutral-700 sm:block\">Click to turn</span>\n      </button>\n    </section>\n  );\n}\n"}]}
