# Integrate `WorldMap ASCII` from Motion Garden

You are helping me add the **WorldMap ASCII** 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:** WorldMap ASCII
- **Category:** Backgrounds
- **Summary:** A dot-matrix world map whose particles scatter from the cursor.
- **Reference:** https://motion-garden.netlify.app/components/world-map-ascii
- **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
# WorldMap ASCII 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/world-map-ascii/world-map-ascii.tsx`

```tsx
"use client";

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

interface WorldMapAsciiProps {
	color: string;
	particleSize: number;
	density: number;
	mouseRadius: number;
	drift: number;
	paused?: boolean;
}

interface ParticleData {
	x: number;
	y: number;
	baseX: number;
	baseY: number;
	density: number;
}

function updateParticle(
	p: ParticleData,
	mouseX: number,
	mouseY: number,
	t: number,
	mouseRadius: number,
	drift: number,
) {
	const dx = mouseX - p.x;
	const dy = mouseY - p.y;
	const distSq = dx * dx + dy * dy;
	const maxDistSq = mouseRadius * mouseRadius;

	if (mouseRadius > 0 && distSq < maxDistSq) {
		const distance = Math.sqrt(distSq);
		const force = (mouseRadius - distance) / mouseRadius;
		p.x -= (dx / distance) * force * p.density;
		p.y -= (dy / distance) * force * p.density;
	} else {
		const rx = p.x - p.baseX;
		const ry = p.y - p.baseY;
		if (rx !== 0) p.x -= rx / 15;
		if (ry !== 0) p.y -= ry / 15;
	}

	p.x += Math.sin(t + p.baseY) * drift;
	p.y += Math.cos(t + p.baseX) * drift;
}

export default function WorldMapAscii({
	color,
	particleSize,
	density,
	mouseRadius,
	drift,
	paused = false,
}: WorldMapAsciiProps) {
	const canvasRef = useRef<HTMLCanvasElement>(null);
	const containerRef = useRef<HTMLDivElement>(null);
	const drawRef = useRef<((now: number) => void | false) | null>(null);
	const measureRef = useRef<((m: Metrics) => void) | null>(null);

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

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

		const ctx = canvas.getContext("2d", { alpha: true });
		if (!ctx) return;

		let mouseX = -1000;
		let mouseY = -1000;
		let particles: ParticleData[] = [];

		const mapImage = new Image();

		const initMap = () => {
			if (canvas.width === 0 || canvas.height === 0) return;

			const imgW = mapImage.naturalWidth || mapImage.width;
			const imgH = mapImage.naturalHeight || mapImage.height;
			if (imgW === 0 || imgH === 0) return;

			particles = [];

			const offscreenCanvas = document.createElement("canvas");
			const offscreenCtx = offscreenCanvas.getContext("2d", {
				willReadFrequently: true,
			});
			if (!offscreenCtx) return;

			const imgRatio = imgW / imgH;
			let drawWidth = canvas.width;
			let drawHeight = drawWidth / imgRatio;

			if (drawHeight > canvas.height) {
				drawHeight = canvas.height;
				drawWidth = drawHeight * imgRatio;
			}

			const offsetX = (canvas.width - drawWidth) / 2;
			const offsetY = (canvas.height - drawHeight) / 2;

			offscreenCanvas.width = canvas.width;
			offscreenCanvas.height = canvas.height;
			offscreenCtx.drawImage(mapImage, offsetX, offsetY, drawWidth, drawHeight);

			const imageData = offscreenCtx.getImageData(
				0,
				0,
				canvas.width,
				canvas.height,
			);
			const pixels = imageData.data;

			const res = Math.max(2, Math.round(11 - density));

			for (let y = 0; y < canvas.height; y += res) {
				for (let x = 0; x < canvas.width; x += res) {
					if (pixels[(y * canvas.width + x) * 4 + 3] > 50) {
						particles.push({
							x,
							y,
							baseX: x,
							baseY: y,
							density: Math.random() * 30 + 10,
						});
					}
				}
			}
		};

		const animate = (now: number) => {
			ctx.clearRect(0, 0, canvas.width, canvas.height);

			const t = now * 0.001;
			const len = particles.length;

			ctx.fillStyle = color;
			ctx.beginPath();
			for (let i = 0; i < len; i++) {
				const p = particles[i];
				updateParticle(p, mouseX, mouseY, t, mouseRadius, drift);
				ctx.moveTo(p.x + particleSize, p.y);
				ctx.arc(p.x, p.y, particleSize, 0, Math.PI * 2);
			}
			ctx.fill();

			if (paused) return false;
		};
		drawRef.current = animate;

		measureRef.current = ({ width, height }) => {
			canvas.width = width;
			canvas.height = height;
			initMap();
		};

		mapImage.onload = () => {
			loop.resize();
			loop.start();
		};
		mapImage.src = "/world-map.svg";

		if (mapImage.complete) {
			loop.resize();
			loop.start();
		}

		const handlePointerMove = (e: PointerEvent) => {
			mouseX = e.offsetX;
			mouseY = e.offsetY;
		};

		const handlePointerLeave = () => {
			mouseX = -1000;
			mouseY = -1000;
		};

		canvas.addEventListener("pointermove", handlePointerMove);
		canvas.addEventListener("pointerleave", handlePointerLeave);
		canvas.addEventListener("pointercancel", handlePointerLeave);

		return () => {
			drawRef.current = null;
			measureRef.current = null;
			mapImage.onload = null;
			canvas.removeEventListener("pointermove", handlePointerMove);
			canvas.removeEventListener("pointerleave", handlePointerLeave);
			canvas.removeEventListener("pointercancel", handlePointerLeave);
		};
	}, [color, particleSize, density, mouseRadius, drift, paused, loop]);

	return (
		<div ref={containerRef} className="absolute inset-0 overflow-hidden">
			<canvas ref={canvasRef} className="block h-full w-full touch-none" />
		</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 |
| --- | --- | --- | --- |
| `color` | `string (hex)` | `"#a855f7"` | Particle color. |
| `particleSize` | `number` | `0.7` | Dot radius. Range 0.3–3 px. |
| `density` | `number` | `8` | Particle density — higher packs more particles. Range 1–9. |
| `mouseRadius` | `number` | `80` | Cursor interaction radius; 0 disables the scatter. Range 0–300 px. |
| `drift` | `number` | `0.06` | Idle wobble amplitude. Range 0–0.3. |

## Usage

```tsx
import WorldMapAscii from "@/components/registry/world-map-ascii/world-map-ascii";

<WorldMapAscii
  color="#a855f7"
  particleSize={0.7}
  density={8}
  mouseRadius={80}
  drift={0.06}
/>
```

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.
