# Integrate `DotField` from Motion Garden

You are helping me add the **DotField** 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:** DotField
- **Category:** Backgrounds
- **Summary:** An interactive dot grid that bulges and glows around the cursor.
- **Reference:** https://motion-garden.netlify.app/components/dot-field
- **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
# DotField needs no npm packages
```

## Files to create

2 files — all of them are required. 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/dot-field/dot-field.tsx`

```tsx
"use client";

import { useEffect, useRef, memo } from 'react'
import { useAnimationLoop, type Metrics } from '@/hooks/use-animation-loop'

const TWO_PI = Math.PI * 2

interface Dot {
  ax: number
  ay: number
  sx: number
  sy: number
  vx: number
  vy: number
  x: number
  y: number
}

interface DotFieldProps {
  dotRadius?: number
  dotSpacing?: number
  cursorRadius?: number
  cursorForce?: number
  bulgeOnly?: boolean
  bulgeStrength?: number
  glowRadius?: number
  sparkle?: boolean
  waveAmplitude?: number
  gradientFrom?: string
  gradientTo?: string
  glowColor?: string
  paused?: boolean
  [key: string]: unknown
}

const DotField = memo(
  ({
    dotRadius = 1.5,
    dotSpacing = 25,
    cursorRadius = 500,
    cursorForce = 0.1,
    bulgeOnly = true,
    bulgeStrength = 67,
    glowRadius = 160,
    sparkle = false,
    waveAmplitude = 0,
    gradientFrom = '#a855f7',
    gradientTo = '#b497cf',
    glowColor = '#a855f7',
    paused = false,
    ...rest
  }: DotFieldProps) => {
    const canvasRef = useRef<HTMLCanvasElement>(null)
    const svgRef = useRef<SVGSVGElement>(null)
    const glowRef = useRef<SVGCircleElement>(null)
    const dotsRef = useRef<Dot[]>([])
    const mouseRef = useRef({
      x: -9999,
      y: -9999,
      prevX: -9999,
      prevY: -9999,
      speed: 0,
    })
    const sizeRef = useRef({ w: 0, h: 0, offsetX: 0, offsetY: 0 })
    const glowOpacity = useRef(0)
    const engagement = useRef(0)
    const isMovingRef = useRef(false)
    const moveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
    const propsRef = useRef<Record<string, unknown>>({})
    propsRef.current = {
      dotRadius,
      dotSpacing,
      cursorRadius,
      cursorForce,
      bulgeOnly,
      bulgeStrength,
      sparkle,
      waveAmplitude,
      gradientFrom,
      gradientTo,
      paused,
    }
    const rebuildRef = useRef<(() => void) | null>(null)
    const containerRef = useRef<HTMLDivElement>(null)
    const drawRef = useRef<(() => void | false) | null>(null)
    const measureRef = useRef<((m: Metrics) => void) | null>(null)

    const loop = useAnimationLoop({
      target: containerRef,
      halted: paused,
      dpr: 2,
      resizeDebounceMs: 100,
      onResize: (metrics) => measureRef.current?.(metrics),
      onFrame: () => (drawRef.current ? drawRef.current() : false),
    })

    const glowIdRef = useRef(
      `dot-field-glow-${Math.random().toString(36).slice(2, 9)}`
    )

    useEffect(() => {
      const canvas = canvasRef.current
      const glowEl = glowRef.current
      if (!canvas) return
      const ctx = canvas.getContext('2d', { alpha: true })
      if (!ctx) return
      measureRef.current = ({ width: w, height: h, dpr, bufferWidth, bufferHeight }) => {
        const rect = canvas!.parentElement!.getBoundingClientRect()

        canvas!.width = bufferWidth
        canvas!.height = bufferHeight
        canvas!.style.width = `${w}px`
        canvas!.style.height = `${h}px`
        ctx!.setTransform(dpr, 0, 0, dpr, 0, 0)

        sizeRef.current = {
          w,
          h,
          offsetX: rect.left + window.scrollX,
          offsetY: rect.top + window.scrollY,
        }

        buildDots(w, h)
      }

      function buildDots(w: number, h: number) {
        const p = propsRef.current
        const step = (p.dotRadius as number) + (p.dotSpacing as number)
        const cols = Math.floor(w / step)
        const rows = Math.floor(h / step)
        const padX = (w % step) / 2
        const padY = (h % step) / 2
        const dots: Dot[] = new Array(rows * cols)
        let idx = 0

        for (let row = 0; row < rows; row++) {
          for (let col = 0; col < cols; col++) {
            const ax = padX + col * step + step / 2
            const ay = padY + row * step + step / 2
            dots[idx++] = { ax, ay, sx: ax, sy: ay, vx: 0, vy: 0, x: ax, y: ay }
          }
        }
        dotsRef.current = dots
      }

      function updatePointer(pageX: number, pageY: number) {
        const s = sizeRef.current
        mouseRef.current.x = pageX - s.offsetX
        mouseRef.current.y = pageY - s.offsetY

        isMovingRef.current = true
        if (moveTimeoutRef.current) clearTimeout(moveTimeoutRef.current)
        moveTimeoutRef.current = setTimeout(() => {
          isMovingRef.current = false
        }, 500)
      }

      function onMouseMove(e: MouseEvent) {
        updatePointer(e.pageX, e.pageY)
      }

      function onTouchMove(e: TouchEvent) {
        const touch = e.touches[0]
        if (touch) updatePointer(touch.pageX, touch.pageY)
      }

      function onTouchEnd() {
        mouseRef.current.x = -9999
        mouseRef.current.y = -9999
      }

      function updateMouseSpeed() {
        if (propsRef.current.paused) return
        const m = mouseRef.current
        const dx = m.prevX - m.x
        const dy = m.prevY - m.y
        const dist = Math.sqrt(dx * dx + dy * dy)
        m.speed += (dist - m.speed) * 0.5
        if (m.speed < 0.001) m.speed = 0
        m.prevX = m.x
        m.prevY = m.y
      }

      const speedInterval = setInterval(updateMouseSpeed, 20)

      let frameCount = 0

      function tick() {
        frameCount++
        const dots = dotsRef.current
        const m = mouseRef.current
        const { w, h } = sizeRef.current
        const p = propsRef.current
        const len = dots.length
        const t = frameCount * 0.02

        const targetEngagement = Math.min(m.speed / 5, 1)
        engagement.current += (targetEngagement - engagement.current) * 0.06
        if (engagement.current < 0.001) engagement.current = 0
        const eng = engagement.current

        glowOpacity.current += (eng - glowOpacity.current) * 0.08

        if (glowEl) {
          glowEl.setAttribute('cx', String(m.x))
          glowEl.setAttribute('cy', String(m.y))
          glowEl.style.opacity = String(glowOpacity.current)
        }

        ctx!.clearRect(0, 0, w, h)

        const grad = ctx!.createLinearGradient(0, 0, w, h)
        grad.addColorStop(0, p.gradientFrom as string)
        grad.addColorStop(1, p.gradientTo as string)
        ctx!.fillStyle = grad

        const cr = p.cursorRadius as number
        const crSq = cr * cr
        const rad = (p.dotRadius as number) / 2
        const isBulge = p.bulgeOnly as boolean

        ctx!.beginPath()

        for (let i = 0; i < len; i++) {
          const d = dots[i]
          const dx = m.x - d.ax
          const dy = m.y - d.ay
          const distSq = dx * dx + dy * dy

          if (distSq < crSq && eng > 0.01) {
            const dist = Math.sqrt(distSq)
            if (isBulge) {
              const t = 1 - dist / cr
              const push = t * t * (p.bulgeStrength as number) * eng
              const angle = Math.atan2(dy, dx)
              d.sx += (d.ax - Math.cos(angle) * push - d.sx) * 0.15
              d.sy += (d.ay - Math.sin(angle) * push - d.sy) * 0.15
            } else {
              const angle = Math.atan2(dy, dx)
              const move = (500 / dist) * (m.speed * (p.cursorForce as number))
              d.vx += Math.cos(angle) * -move
              d.vy += Math.sin(angle) * -move
            }
          } else if (isBulge) {
            d.sx += (d.ax - d.sx) * 0.1
            d.sy += (d.ay - d.sy) * 0.1
          }

          if (!isBulge) {
            d.vx *= 0.9
            d.vy *= 0.9
            d.x = d.ax + d.vx
            d.y = d.ay + d.vy
            d.sx += (d.x - d.sx) * 0.1
            d.sy += (d.y - d.sy) * 0.1
          }

          let drawX = d.sx
          let drawY = d.sy
          if ((p.waveAmplitude as number) > 0) {
            drawY += Math.sin(d.ax * 0.03 + t) * (p.waveAmplitude as number)
            drawX +=
              Math.cos(d.ay * 0.03 + t * 0.7) *
              (p.waveAmplitude as number) *
              0.5
          }

          if (p.sparkle && isMovingRef.current) {
            const hash = ((i * 2654435761) ^ (frameCount >> 3)) >>> 0
            if (hash % 100 < 3) {
              ctx!.moveTo(drawX + rad * 1.8, drawY)
              ctx!.arc(drawX, drawY, rad * 1.8, 0, TWO_PI)
            } else {
              ctx!.moveTo(drawX + rad, drawY)
              ctx!.arc(drawX, drawY, rad, 0, TWO_PI)
            }
          } else {
            ctx!.moveTo(drawX + rad, drawY)
            ctx!.arc(drawX, drawY, rad, 0, TWO_PI)
          }
        }

        ctx!.fill()

        if (propsRef.current.paused) return false
      }
      drawRef.current = tick

      loop.resize()
      loop.start()
      window.addEventListener('mousemove', onMouseMove, { passive: true })
      window.addEventListener('touchstart', onTouchMove, { passive: true })
      window.addEventListener('touchmove', onTouchMove, { passive: true })
      window.addEventListener('touchend', onTouchEnd, { passive: true })
      window.addEventListener('touchcancel', onTouchEnd, { passive: true })

      rebuildRef.current = () => {
        const { w, h } = sizeRef.current
        if (w > 0 && h > 0) buildDots(w, h)
      }

      return () => {
        drawRef.current = null
        measureRef.current = null
        clearInterval(speedInterval)
        if (moveTimeoutRef.current) clearTimeout(moveTimeoutRef.current)
        window.removeEventListener('mousemove', onMouseMove)
        window.removeEventListener('touchstart', onTouchMove)
        window.removeEventListener('touchmove', onTouchMove)
        window.removeEventListener('touchend', onTouchEnd)
        window.removeEventListener('touchcancel', onTouchEnd)
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    useEffect(() => {
      rebuildRef.current?.()
    }, [dotRadius, dotSpacing])

    return (
      <div ref={containerRef} className="relative h-full w-full" {...rest}>
        <canvas
          ref={canvasRef}
          className="touch-none"
          style={{
            position: 'absolute',
            inset: 0,
            width: '100%',
            height: '100%',
          }}
        />
        <svg
          ref={svgRef}
          style={{
            position: 'absolute',
            inset: 0,
            width: '100%',
            height: '100%',
            pointerEvents: 'none',
          }}
        >
          <defs>
            <radialGradient id={glowIdRef.current}>
              <stop offset="0%" stopColor={glowColor} stopOpacity="1" />
              <stop offset="100%" stopColor={glowColor} stopOpacity="0" />
            </radialGradient>
          </defs>
          <circle
            ref={glowRef}
            cx="-9999"
            cy="-9999"
            r={glowRadius}
            fill={`url(#${glowIdRef.current})`}
            style={{ opacity: 0, willChange: 'opacity' }}
          />
        </svg>
      </div>
    )
  }
)

DotField.displayName = 'DotField'

export default DotField
```

### 2. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `dotRadius` | `number` | `1.5` | Radius of each dot. Range 0.5–5 px. |
| `dotSpacing` | `number` | `25` | Spacing between dots. Range 10–50 px. |
| `cursorRadius` | `number` | `500` | Cursor influence radius. Range 100–800 px. |
| `cursorForce` | `number` | `0.1` | Strength of the cursor push. Range 0–1. |
| `bulgeOnly` | `boolean` | `true` | Bulge toward the cursor only (no repel). |
| `bulgeStrength` | `number` | `67` | Bulge displacement strength. Range 0–150. |
| `glowRadius` | `number` | `160` | Radius of the cursor glow. Range 0–400 px. |
| `sparkle` | `boolean` | `false` | Add a sparkle shimmer. |
| `waveAmplitude` | `number` | `0` | Ambient wave motion. Range 0–20. |
| `gradientFrom` | `string (hex)` | `"#a855f7"` | Dot gradient start. |
| `gradientTo` | `string (hex)` | `"#b497cf"` | Dot gradient end. |
| `glowColor` | `string (hex)` | `"#a855f7"` | Cursor glow color. |

## Usage

```tsx
import DotField from "@/components/registry/dot-field/dot-field";

<DotField
  dotRadius={1.5}
  dotSpacing={25}
  cursorRadius={500}
  cursorForce={0.1}
  bulgeOnly={true}
  bulgeStrength={67}
  glowRadius={160}
  sparkle={false}
  waveAmplitude={0}
  gradientFrom="#a855f7"
  gradientTo="#b497cf"
  glowColor="#a855f7"
/>
```

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 runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. 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.
