# Integrate `PlusGrid` from Motion Garden

You are helping me add the **PlusGrid** 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:** PlusGrid
- **Category:** Backgrounds
- **Summary:** A canvas field of '+' glyphs. Scroll or pointer motion injects a traveling wave that ripples and decays across the grid.
- **Reference:** https://motion-garden.netlify.app/components/plus-grid
- **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
# PlusGrid 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/plus-grid/plus-grid.tsx`

```tsx
"use client";

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

export interface PlusGridConfig {
	gapX: number;
	gapY: number;
	fontSize: number;
	fontWeight: number;
	baseOpacity: number;
	color: string;
	scrollSensitivity: number;
	waveAmplitude: number;
	waveFrequency: number;
	waveSpeed: number;
	waveDecay: number;
	opacityVariance: number;
	ambientAmplitude: number;
	ambientSpeed: number;
	cols?: number;
	rows?: number;
}

export const PLUS_GRID_DEFAULTS: PlusGridConfig = {
	gapX: 42,
	gapY: 38,
	fontSize: 20,
	fontWeight: 400,
	baseOpacity: 0.5,
	color: "#a855f7",
	scrollSensitivity: 0.5,
	waveAmplitude: 12,
	waveFrequency: 0.35,
	waveSpeed: 0.045,
	waveDecay: 0.96,
	opacityVariance: 0.4,
	ambientAmplitude: 1.5,
	ambientSpeed: 0.008,
	cols: undefined,
	rows: undefined,
};

interface Particle {
	x: number;
	y: number;
	col: number;
	row: number;
	opacityMod: number;
}

interface WaveState {
	energy: number;
	direction: number;
	phase: number;
}

export interface PlusGridProps {
	config?: Partial<PlusGridConfig>;
	className?: string;
	scrollContainerRef?: RefObject<HTMLElement | null>;
	pointerEnergy?: boolean;
	autoPulse?: boolean;
	paused?: boolean;
}

export default function PlusGrid({
	config: userConfig,
	className,
	scrollContainerRef,
	pointerEnergy = true,
	autoPulse = true,
	paused = false,
}: PlusGridProps) {
	const containerRef = useRef<HTMLDivElement>(null);
	const canvasRef = useRef<HTMLCanvasElement>(null);
	const merged: PlusGridConfig = { ...PLUS_GRID_DEFAULTS, ...userConfig };
	const cfgRef = useRef<PlusGridConfig>(merged);
	cfgRef.current = merged;
	const flagsRef = useRef({ pointerEnergy, paused });
	flagsRef.current = { pointerEnergy, paused };
	const waveRef = useRef<WaveState>({ energy: 0, direction: 1, phase: 0 });
	const rebuildRef = useRef<(() => void) | null>(null);
	const drawRef = useRef<(() => void | false) | null>(null);
	const measureRef = useRef<((m: Metrics) => void) | null>(null);

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

	useEffect(() => {
		const container = containerRef.current;
		const canvas = canvasRef.current;
		if (!container || !canvas) return;

		const ctx = canvas.getContext("2d");
		if (!ctx) return;

		let particles: Particle[] = [];
		let ambientPhase = 0;
		let fontFamily = "ui-monospace";
		let dpr = 1;

		const wave = waveRef.current;
		const scroller = scrollContainerRef?.current ?? null;
		let lastScrollY = scroller ? scroller.scrollTop : window.scrollY;
		let lastPointerY: number | null = null;

		const buildParticles = (w: number, h: number) => {
			const { gapX, gapY, cols: manualCols, rows: manualRows } = cfgRef.current;
			const cols = manualCols ?? Math.max(1, Math.floor(w / gapX));
			const rows = manualRows ?? Math.max(1, Math.floor(h / gapY));
			const offsetX = (w - (cols - 1) * gapX) / 2;
			const offsetY = (h - (rows - 1) * gapY) / 2;

			particles = [];
			for (let r = 0; r < rows; r++) {
				for (let c = 0; c < cols; c++) {
					particles.push({
						x: offsetX + c * gapX,
						y: offsetY + r * gapY,
						col: c,
						row: r,
						opacityMod:
							Math.random() > 0.45
								? 0.9 + Math.random() * 0.1
								: 0.08 + Math.random() * 0.15,
					});
				}
			}
		};

		measureRef.current = ({ width: w, height: h, dpr: nextDpr, bufferWidth, bufferHeight }) => {
			dpr = nextDpr;
			canvas.width = bufferWidth;
			canvas.height = bufferHeight;
			canvas.style.width = `${w}px`;
			canvas.style.height = `${h}px`;

			ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

			fontFamily =
				getComputedStyle(canvas).getPropertyValue("--font-display").trim() ||
				"ui-monospace";

			buildParticles(w, h);
		};

		const injectEnergy = (delta: number, sensitivity: number) => {
			if (Math.abs(delta) < 0.5) return;
			wave.energy = Math.min(
				1,
				wave.energy + Math.abs(delta) * cfgRef.current.scrollSensitivity * sensitivity,
			);
			wave.direction = delta > 0 ? 1 : -1;
		};

		const onScroll = () => {
			const y = scroller ? scroller.scrollTop : window.scrollY;
			injectEnergy(y - lastScrollY, 0.038);
			lastScrollY = y;
		};

		const onPointerMove = (e: PointerEvent) => {
			if (!flagsRef.current.pointerEnergy || flagsRef.current.paused) return;
			if (lastPointerY !== null) injectEnergy(e.clientY - lastPointerY, 0.02);
			lastPointerY = e.clientY;
		};
		const onPointerLeave = () => {
			lastPointerY = null;
		};

		const scrollTarget: HTMLElement | Window = scroller ?? window;
		scrollTarget.addEventListener("scroll", onScroll, { passive: true });
		container.addEventListener("pointermove", onPointerMove, { passive: true });
		container.addEventListener("pointerleave", onPointerLeave, {
			passive: true,
		});

		const tick = () => {
			const cfg = cfgRef.current;
			const isPaused = flagsRef.current.paused;
			const w = canvas.width / dpr;
			const h = canvas.height / dpr;

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

			if (!isPaused) {
				wave.energy = wave.energy * cfg.waveDecay;
				wave.phase += cfg.waveSpeed;
				ambientPhase += cfg.ambientSpeed;
			}

			ctx.font = `${cfg.fontWeight} ${cfg.fontSize}px ${fontFamily}, ui-monospace, SFMono-Regular, monospace`;
			ctx.textAlign = "center";
			ctx.textBaseline = "middle";
			ctx.fillStyle = cfg.color;

			for (const p of particles) {
				const spatialArg = p.col * cfg.waveFrequency + wave.phase;

				const scrollY =
					Math.sin(spatialArg) *
					cfg.waveAmplitude *
					wave.energy *
					wave.direction;

				const idleY =
					Math.sin(p.col * 0.3 + p.row * 0.4 + ambientPhase) *
					cfg.ambientAmplitude;

				const opacityDelta =
					Math.cos(spatialArg) * cfg.opacityVariance * wave.energy;

				const opacity = Math.max(
					0.04,
					Math.min(0.95, cfg.baseOpacity * p.opacityMod + opacityDelta),
				);

				ctx.globalAlpha = opacity;
				ctx.fillText("+", p.x, p.y + scrollY + idleY);
			}
			ctx.globalAlpha = 1;

			if (isPaused) return false;
		};
		drawRef.current = tick;

		loop.resize();
		loop.start();

		rebuildRef.current = () => {
			const w = container.clientWidth;
			const h = container.clientHeight;
			if (w > 0 && h > 0) buildParticles(w, h);
		};

		return () => {
			drawRef.current = null;
			measureRef.current = null;
			scrollTarget.removeEventListener("scroll", onScroll);
			container.removeEventListener("pointermove", onPointerMove);
			container.removeEventListener("pointerleave", onPointerLeave);
		};
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	useEffect(() => {
		if (!autoPulse || paused) return;
		const id = setInterval(() => {
			const wave = waveRef.current;
			wave.energy = Math.max(wave.energy, 0.7);
			wave.direction *= -1;
		}, 2800);
		return () => clearInterval(id);
	}, [autoPulse, paused]);

	useEffect(() => {
		rebuildRef.current?.();
	}, [merged.gapX, merged.gapY, merged.cols, merged.rows]);

	return (
		<div ref={containerRef} className={className ?? "h-full w-full"}>
			<canvas
				ref={canvasRef}
				className="absolute inset-0 size-full touch-none"
				style={{ display: "block" }}
			/>
		</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 |
| --- | --- | --- | --- |
| `gapX` | `number` | `42` | Horizontal gap between glyphs. Range 24–96 px. |
| `gapY` | `number` | `38` | Vertical gap between glyphs. Range 24–96 px. |
| `fontSize` | `number` | `20` | Glyph size. Range 10–36 px. |
| `baseOpacity` | `number` | `0.5` | Resting opacity of the field. Range 0.05–1. |
| `waveAmplitude` | `number` | `12` | Peak displacement at full wave energy. Range 0–40 px. |
| `waveFrequency` | `number` | `0.35` | Ripple tightness across columns. Range 0.05–1. |
| `waveDecay` | `number` | `0.96` | Energy decay per tick — low snaps back, high lingers. Range 0.9–0.995. |
| `autoPulse` | `boolean` | `true` | Fire a wave pulse every few seconds. |
| `color` | `string (hex)` | `"#a855f7"` | Glyph color. |

## Usage

```tsx
import PlusGrid from "@/components/registry/plus-grid/plus-grid";

<PlusGrid
  gapX={42}
  gapY={38}
  fontSize={20}
  baseOpacity={0.5}
  waveAmplitude={12}
  waveFrequency={0.35}
  waveDecay={0.96}
  autoPulse={true}
  color="#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.
