# Integrate `FlockField` from Motion Garden

You are helping me add the **FlockField** 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:** FlockField
- **Category:** Backgrounds
- **Summary:** A murmuration of hundreds of boids wheeling as one — separation, alignment, and cohesion resolved every frame through a spatial hash for the crowd, banking toward or scattering from your cursor, smeared into long trails of amethyst and cyan as the flock folds across the dark.
- **Reference:** https://motion-garden.netlify.app/components/flock-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
# FlockField 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/flock-field/flock-field.tsx`

```tsx
"use client";

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

interface FlockFieldProps {
	count?: number;
	speed?: number;
	separation?: number;
	alignment?: number;
	cohesion?: number;
	neighborRadius?: number;
	separationRadius?: number;
	cursorMode?: "attract" | "repel" | "off";
	cursorForce?: number;
	cursorRadius?: number;
	trail?: number;
	color1?: string;
	color2?: string;
	paused?: boolean;
	reducedMotion?: boolean;
	className?: string;
}

interface Boid {
	x: number;
	y: number;
	vx: number;
	vy: number;
	ax: number;
	ay: number;
}

type Rgb = [number, number, number];

const BG: Rgb = [10, 10, 12];
const WARMUP_STEPS = 120;
const MAX_COUNT = 1000;

function hexToRgb(hex: string): Rgb {
	let h = hex.replace("#", "");
	if (h.length === 3)
		h = h
			.split("")
			.map((c) => c + c)
			.join("");
	const n = parseInt(h, 16);
	if (Number.isNaN(n) || h.length !== 6) return [168, 85, 247];
	return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}

export default function FlockField({
	count = 300,
	speed = 2.5,
	separation = 1.2,
	alignment = 1,
	cohesion = 1,
	neighborRadius = 60,
	separationRadius = 24,
	cursorMode = "repel",
	cursorForce = 1.5,
	cursorRadius = 160,
	trail = 0.85,
	color1 = "#a855f7",
	color2 = "#22d3ee",
	paused = false,
	reducedMotion = false,
	className = "",
}: FlockFieldProps) {
	const canvasRef = useRef<HTMLCanvasElement>(null);
	const boidsRef = useRef<Boid[]>([]);
	const mouseRef = useRef({ x: -1e5, y: -1e5 });
	const sizeRef = useRef({ w: 0, h: 0 });
	const containerRef = useRef<HTMLDivElement>(null);
	const drawRef = useRef<(() => void | false) | null>(null);
	const measureRef = useRef<((m: Metrics) => void) | null>(null);

	const live = useRef({
		count,
		speed,
		separation,
		alignment,
		cohesion,
		neighborRadius,
		separationRadius,
		cursorMode,
		cursorForce,
		cursorRadius,
		trail,
		color1,
		color2,
		paused: paused || reducedMotion,
	});
	live.current = {
		count,
		speed,
		separation,
		alignment,
		cohesion,
		neighborRadius,
		separationRadius,
		cursorMode,
		cursorForce,
		cursorRadius,
		trail,
		color1,
		color2,
		paused: paused || reducedMotion,
	};

	const rebuildRef = useRef<(() => void) | null>(null);

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

	useEffect(() => {
		const canvas = canvasRef.current;
		if (!canvas) return;
		const ctx = canvas.getContext("2d", { alpha: false });
		if (!ctx) return;
		const grid = new Map<string, number[]>();

		function initBoids() {
			const { w, h } = sizeRef.current;
			const n = Math.max(1, Math.min(MAX_COUNT, Math.floor(live.current.count)));
			const sp = live.current.speed;
			const boids: Boid[] = new Array(n);
			for (let i = 0; i < n; i++) {
				const ang = Math.random() * Math.PI * 2;
				const v = sp * (0.5 + Math.random() * 0.5);
				boids[i] = {
					x: Math.random() * w,
					y: Math.random() * h,
					vx: Math.cos(ang) * v,
					vy: Math.sin(ang) * v,
					ax: 0,
					ay: 0,
				};
			}
			boidsRef.current = boids;
		}

		function simulate() {
			const { w, h } = sizeRef.current;
			const p = live.current;
			const boids = boidsRef.current;
			const n = boids.length;
			if (n === 0 || w === 0) return;

			const nr = p.neighborRadius;
			const sr = p.separationRadius;
			const cell = Math.max(1, Math.max(nr, sr));
			const nr2 = nr * nr;
			const sr2 = sr * sr;
			const maxSpeed = p.speed;
			const maxForce = maxSpeed * 0.06;
			const minSpeed = maxSpeed * 0.5;

			grid.clear();
			for (let i = 0; i < n; i++) {
				const b = boids[i];
				const key = `${Math.floor(b.x / cell)},${Math.floor(b.y / cell)}`;
				let bucket = grid.get(key);
				if (!bucket) {
					bucket = [];
					grid.set(key, bucket);
				}
				bucket.push(i);
			}

			const m = mouseRef.current;
			const cursorOn = p.cursorMode !== "off" && p.cursorForce > 0 && p.cursorRadius > 0;
			const cr2 = p.cursorRadius * p.cursorRadius;
			const cDir = p.cursorMode === "repel" ? -1 : 1;

			for (let i = 0; i < n; i++) {
				const b = boids[i];
				const cx = Math.floor(b.x / cell);
				const cy = Math.floor(b.y / cell);
				let alignX = 0;
				let alignY = 0;
				let cohX = 0;
				let cohY = 0;
				let sepX = 0;
				let sepY = 0;
				let nCount = 0;
				let sCount = 0;

				for (let gx = cx - 1; gx <= cx + 1; gx++) {
					for (let gy = cy - 1; gy <= cy + 1; gy++) {
						const bucket = grid.get(`${gx},${gy}`);
						if (!bucket) continue;
						for (let k = 0; k < bucket.length; k++) {
							const j = bucket[k];
							if (j === i) continue;
							const o = boids[j];
							const dx = o.x - b.x;
							const dy = o.y - b.y;
							const d2 = dx * dx + dy * dy;
							if (d2 > nr2 || d2 === 0) continue;
							nCount++;
							alignX += o.vx;
							alignY += o.vy;
							cohX += o.x;
							cohY += o.y;
							if (d2 < sr2) {
								sepX += -dx / d2;
								sepY += -dy / d2;
								sCount++;
							}
						}
					}
				}

				let ax = 0;
				let ay = 0;

				if (nCount > 0) {
					let dvx = alignX / nCount;
					let dvy = alignY / nCount;
					let mag = Math.hypot(dvx, dvy);
					if (mag > 0) {
						dvx = (dvx / mag) * maxSpeed;
						dvy = (dvy / mag) * maxSpeed;
						let sx = dvx - b.vx;
						let sy = dvy - b.vy;
						const sm = Math.hypot(sx, sy);
						if (sm > maxForce) {
							sx = (sx / sm) * maxForce;
							sy = (sy / sm) * maxForce;
						}
						ax += sx * p.alignment;
						ay += sy * p.alignment;
					}

					let cxv = cohX / nCount - b.x;
					let cyv = cohY / nCount - b.y;
					mag = Math.hypot(cxv, cyv);
					if (mag > 0) {
						cxv = (cxv / mag) * maxSpeed;
						cyv = (cyv / mag) * maxSpeed;
						let sx = cxv - b.vx;
						let sy = cyv - b.vy;
						const sm = Math.hypot(sx, sy);
						if (sm > maxForce) {
							sx = (sx / sm) * maxForce;
							sy = (sy / sm) * maxForce;
						}
						ax += sx * p.cohesion;
						ay += sy * p.cohesion;
					}
				}

				if (sCount > 0) {
					let mag = Math.hypot(sepX, sepY);
					if (mag > 0) {
						let dvx = (sepX / mag) * maxSpeed;
						let dvy = (sepY / mag) * maxSpeed;
						let sx = dvx - b.vx;
						let sy = dvy - b.vy;
						const sm = Math.hypot(sx, sy);
						if (sm > maxForce) {
							sx = (sx / sm) * maxForce;
							sy = (sy / sm) * maxForce;
						}
						ax += sx * p.separation;
						ay += sy * p.separation;
					}
				}

				if (cursorOn) {
					const dx = m.x - b.x;
					const dy = m.y - b.y;
					const d2 = dx * dx + dy * dy;
					if (d2 < cr2 && d2 > 0) {
						const d = Math.sqrt(d2);
						const falloff = (1 - d / p.cursorRadius) * p.cursorForce;
						const s = falloff * maxForce * 3 * cDir;
						ax += (dx / d) * s;
						ay += (dy / d) * s;
					}
				}

				b.ax = ax;
				b.ay = ay;
			}

			for (let i = 0; i < n; i++) {
				const b = boids[i];
				b.vx += b.ax;
				b.vy += b.ay;
				const sp = Math.hypot(b.vx, b.vy);
				if (sp > maxSpeed) {
					b.vx = (b.vx / sp) * maxSpeed;
					b.vy = (b.vy / sp) * maxSpeed;
				} else if (sp > 0 && sp < minSpeed) {
					b.vx = (b.vx / sp) * minSpeed;
					b.vy = (b.vy / sp) * minSpeed;
				} else if (sp === 0) {
					const a = Math.random() * Math.PI * 2;
					b.vx = Math.cos(a) * minSpeed;
					b.vy = Math.sin(a) * minSpeed;
				}
				b.x += b.vx;
				b.y += b.vy;
				if (b.x < 0) b.x += w;
				else if (b.x >= w) b.x -= w;
				if (b.y < 0) b.y += h;
				else if (b.y >= h) b.y -= h;
			}
		}

		function warmUp() {
			for (let i = 0; i < WARMUP_STEPS; i++) simulate();
		}

		function render(fresh: boolean) {
			const { w, h } = sizeRef.current;
			const p = live.current;
			const boids = boidsRef.current;

			if (p.trail > 0 && !fresh) {
				ctx!.fillStyle = `rgba(${BG[0]},${BG[1]},${BG[2]},${1 - p.trail})`;
			} else {
				ctx!.fillStyle = `rgb(${BG[0]},${BG[1]},${BG[2]})`;
			}
			ctx!.fillRect(0, 0, w, h);

			const [r1, g1, b1] = hexToRgb(p.color1);
			const [r2, g2, b2] = hexToRgb(p.color2);
			const maxSpeed = p.speed;

			for (let i = 0; i < boids.length; i++) {
				const b = boids[i];
				const sp = Math.hypot(b.vx, b.vy);
				const t = maxSpeed > 0 ? Math.min(sp / maxSpeed, 1) : 0;
				const r = Math.round(r1 + (r2 - r1) * t);
				const g = Math.round(g1 + (g2 - g1) * t);
				const bl = Math.round(b1 + (b2 - b1) * t);
				const ang = Math.atan2(b.vy, b.vx);
				const cos = Math.cos(ang);
				const sin = Math.sin(ang);
				const nx = b.x + cos * 5;
				const ny = b.y + sin * 5;
				const lx = b.x + (-cos * 4 - sin * 3);
				const lyv = b.y + (-sin * 4 + cos * 3);
				const rx = b.x + (-cos * 4 + sin * 3);
				const ryv = b.y + (-sin * 4 - cos * 3);
				ctx!.beginPath();
				ctx!.moveTo(nx, ny);
				ctx!.lineTo(lx, lyv);
				ctx!.lineTo(rx, ryv);
				ctx!.closePath();
				ctx!.fillStyle = `rgb(${r},${g},${bl})`;
				ctx!.fill();
			}
		}

		measureRef.current = ({ width, height, dpr, bufferWidth, bufferHeight }) => {
			const w = Math.max(width, 1);
			const h = Math.max(height, 1);
			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 };
			initBoids();
			warmUp();
			render(true);
		};

		drawRef.current = () => {
			if (!live.current.paused) simulate();
			render(false);
			if (live.current.paused) {
				render(true);
				return false;
			}
		};

		rebuildRef.current = () => {
			if (sizeRef.current.w === 0) return;
			initBoids();
			if (!loop.running) {
				warmUp();
				render(true);
			}
		};

		function onPointerMove(e: PointerEvent) {
			const rect = canvas!.getBoundingClientRect();
			mouseRef.current.x = e.clientX - rect.left;
			mouseRef.current.y = e.clientY - rect.top;
		}
		function onPointerGone() {
			mouseRef.current.x = -1e5;
			mouseRef.current.y = -1e5;
		}
		function onPointerUp(e: PointerEvent) {
			if (e.pointerType !== "mouse") onPointerGone();
		}

		window.addEventListener("pointermove", onPointerMove, { passive: true });
		window.addEventListener("pointerup", onPointerUp, { passive: true });
		document.documentElement.addEventListener("pointerleave", onPointerGone);
		loop.resize();
		loop.start();

		return () => {
			drawRef.current = null;
			measureRef.current = null;
			window.removeEventListener("pointermove", onPointerMove);
			window.removeEventListener("pointerup", onPointerUp);
			document.documentElement.removeEventListener("pointerleave", onPointerGone);
			rebuildRef.current = null;
		};
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	useEffect(() => {
		rebuildRef.current?.();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [count]);

	return (
		<div ref={containerRef} className={`relative h-full w-full ${className}`}>
			<canvas
				ref={canvasRef}
				className="cursor-crosshair touch-none"
				style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}
			/>
		</div>
	);
}
```

### 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 |
| --- | --- | --- | --- |
| `count` | `number` | `300` | Number of boids in the flock. Spatial-hash lookup keeps it near-linear. Range 50–1000. |
| `speed` | `number` | `2.5` | Maximum boid speed, px per frame. Range 0.5–6. |
| `separation` | `number` | `1.2` | Weight of steering away from close neighbors. Range 0–3. |
| `alignment` | `number` | `1` | Weight of matching neighbors' heading. Range 0–3. |
| `cohesion` | `number` | `1` | Weight of steering toward the neighbor center of mass. Range 0–3. |
| `neighborRadius` | `number` | `60` | How far a boid sees neighbors; sets the spatial-hash cell size. Range 20–150 px. |
| `separationRadius` | `number` | `24` | Distance under which boids actively push apart. Range 5–60 px. |
| `cursorMode` | `"attract" | "repel" | "off"` | `"repel"` | Whether the cursor draws the flock in, scatters it, or is ignored. |
| `cursorForce` | `number` | `1.5` | Strength of the cursor's pull or push. Range 0–5. Ignored while `cursorMode` is `off`. |
| `cursorRadius` | `number` | `160` | Radius of the cursor's influence. Range 40–400 px. Ignored while `cursorMode` is `off`. |
| `trail` | `number` | `0.85` | Motion-trail persistence — 0 is crisp, high smears long tails. Range 0–0.95. |
| `color1` | `string (hex)` | `"#a855f7"` | Slow-boid color. |
| `color2` | `string (hex)` | `"#22d3ee"` | Fast-boid color — boids grade between the two by speed. |

## Usage

```tsx
import FlockField from "@/components/registry/flock-field/flock-field";

<FlockField
  count={300}
  speed={2.5}
  separation={1.2}
  alignment={1}
  cohesion={1}
  neighborRadius={60}
  separationRadius={24}
  cursorMode="repel"
  cursorForce={1.5}
  cursorRadius={160}
  trail={0.85}
  color1="#a855f7"
  color2="#22d3ee"
/>
```

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`.
- 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.
