# Integrate `MagneticButton` from Motion Garden

You are helping me add the **MagneticButton** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** MagneticButton
- **Category:** Micro-interactions
- **Summary:** A button that leans into your cursor. Caught in a magnetic field it slides toward the pointer while an amethyst aura swells with proximity, then snaps home on a spring and answers every click with a dark ripple bursting outward from the point of contact.
- **Reference:** https://motion-garden.netlify.app/components/magnetic-button
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add motion
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme {
  --font-display: "Space Mono", ui-monospace, "SFMono-Regular", monospace;
}

@theme inline {
  --color-panel: var(--sg-panel);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-panel: #ffffff;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-panel: #101215;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-accent: #a855f7;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

`font-display` expects Space Mono, and this CSS only names it. Load the font (with `next/font/google`, for example) or put my own display face first in the stack; until then it falls back to the system monospace.

## Files to create

One file. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/magnetic-button/magnetic-button.tsx`

```tsx
"use client";

import {
  useEffect,
  useRef,
  useState,
  type PointerEvent as ReactPointerEvent,
  type ReactNode,
} from "react";
import { AnimatePresence, motion, useSpring } from "motion/react";

export interface MagneticButtonProps {
  children?: ReactNode;
  pullStrength?: number;
  radius?: number;
  stiffness?: number;
  damping?: number;
  auraColor?: string;
  auraSize?: number;
  ripple?: boolean;
  rippleColor?: string;
  reducedMotion?: boolean;
  className?: string;
}

interface Ripple {
  id: number;
  x: number;
  y: number;
  size: number;
}

export default function MagneticButton({
  children = "Magnetic",
  pullStrength = 0.4,
  radius = 120,
  stiffness = 260,
  damping = 18,
  auraColor = "#a855f7",
  auraSize = 80,
  ripple = true,
  rippleColor = "#d2abfd",
  reducedMotion = false,
  className,
}: MagneticButtonProps) {
  const buttonRef = useRef<HTMLButtonElement>(null);
  const rippleId = useRef(0);
  const [ripples, setRipples] = useState<Ripple[]>([]);

  const [coarse, setCoarse] = useState(false);
  useEffect(() => {
    const mq = window.matchMedia("(hover: none), (pointer: coarse)");
    const update = () => setCoarse(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);

  const magnetic = !reducedMotion && !coarse;

  const spring = { stiffness, damping } as const;
  const x = useSpring(0, spring);
  const y = useSpring(0, spring);
  const auraOpacity = useSpring(reducedMotion ? 0.35 : 0, spring);

  useEffect(() => {
    auraOpacity.set(reducedMotion ? 0.35 : 0);
    if (reducedMotion) {
      x.set(0);
      y.set(0);
    }
  }, [reducedMotion, auraOpacity, x, y]);

  const handlePointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
    if (!magnetic) return;
    const el = buttonRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const cx = rect.left + rect.width / 2;
    const cy = rect.top + rect.height / 2;
    const dx = e.clientX - cx;
    const dy = e.clientY - cy;
    const dist = Math.hypot(dx, dy);
    if (dist < radius) {
      x.set(dx * pullStrength);
      y.set(dy * pullStrength);
      auraOpacity.set(1 - dist / radius);
    } else {
      x.set(0);
      y.set(0);
      auraOpacity.set(0);
    }
  };

  const handlePointerLeave = () => {
    if (!magnetic) return;
    x.set(0);
    y.set(0);
    auraOpacity.set(0);
  };

  const handleClick = (e: ReactPointerEvent<HTMLButtonElement>) => {
    if (!ripple || reducedMotion) return;
    const el = buttonRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const localX = e.clientX - rect.left;
    const localY = e.clientY - rect.top;
    const size =
      2 *
      Math.max(
        Math.hypot(localX, localY),
        Math.hypot(rect.width - localX, localY),
        Math.hypot(localX, rect.height - localY),
        Math.hypot(rect.width - localX, rect.height - localY),
      );
    const id = rippleId.current++;
    setRipples((prev) => [...prev, { id, x: localX, y: localY, size }]);
  };

  const removeRipple = (id: number) =>
    setRipples((prev) => prev.filter((r) => r.id !== id));

  return (
    <div
      onPointerMove={handlePointerMove}
      onPointerLeave={handlePointerLeave}
      style={{ padding: magnetic ? radius : 0 }}
      className="relative inline-flex max-w-full items-center justify-center"
    >
      <div className="relative inline-flex">
        <motion.span
          aria-hidden
          className="pointer-events-none absolute left-1/2 top-1/2 -z-10 rounded-full"
          style={{
            x,
            y,
            opacity: auraOpacity,
            width: `calc(100% + ${auraSize * 2}px)`,
            height: `calc(100% + ${auraSize * 2}px)`,
            translateX: "-50%",
            translateY: "-50%",
            background: `radial-gradient(circle at center, ${auraColor}, transparent 70%)`,
          }}
        />

        <motion.button
          ref={buttonRef}
          type="button"
          onPointerDown={handleClick}
          style={{ touchAction: "manipulation", ...(magnetic ? { x, y } : {}) }}
          className={
            className ??
            "relative isolate cursor-pointer overflow-hidden rounded-md border border-hairline bg-panel px-6 py-3 font-display text-sm uppercase tracking-widest text-ink transition-colors hover:text-accent"
          }
        >
          <AnimatePresence>
            {ripples.map((r) => (
              <motion.span
                key={r.id}
                aria-hidden
                className="pointer-events-none absolute rounded-full"
                style={{
                  left: r.x,
                  top: r.y,
                  width: r.size,
                  height: r.size,
                  marginLeft: -r.size / 2,
                  marginTop: -r.size / 2,
                  background: rippleColor,
                }}
                initial={{ scale: 0, opacity: 0.5 }}
                animate={{ scale: 1, opacity: 0 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.6, ease: "easeOut" }}
                onAnimationComplete={() => removeRipple(r.id)}
              />
            ))}
          </AnimatePresence>
          <span className="relative z-10">{children}</span>
        </motion.button>
      </div>
    </div>
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `pullStrength` | `number` | `0.4` | Fraction of the cursor offset the button follows. Range 0–1. |
| `radius` | `number` | `120` | Field radius where the magnetic pull begins. Range 40–300 px. |
| `stiffness` | `number` | `260` | Spring stiffness of the pull and return. Range 100–600. |
| `damping` | `number` | `18` | Spring damping — lower overshoots and rings. Range 8–60. |
| `auraColor` | `string (hex)` | `"#a855f7"` | Color of the proximity glow. |
| `auraSize` | `number` | `80` | Spread of the aura at full proximity. Range 0–200 px. |
| `ripple` | `boolean` | `true` | Emit a dark ripple burst on click. |
| `rippleColor` | `string (hex)` | `"#d2abfd"` | Color of the click ripple. Ignored while `ripple` is `false`. |

## Usage

```tsx
import MagneticButton from "@/components/registry/magnetic-button/magnetic-button";

<MagneticButton
  pullStrength={0.4}
  radius={120}
  stiffness={260}
  damping={18}
  auraColor="#a855f7"
  auraSize={80}
  ripple={true}
  rippleColor="#d2abfd"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
