# Integrate `Contour` from Motion Garden

You are helping me add the **Contour** 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:** Contour
- **Category:** Backgrounds
- **Summary:** A topographic map of terrain that will not hold still. The lines are not drawn, they are found. A height field is sampled onto a grid every frame and marching squares walks it once per altitude, emitting segments wherever the land crosses that height. Nothing here knows what a ridge is. Ridges are where the crossings bunch up. The pointer raises a hill the contours have to route around, and because the interval is fixed rather than the line count, that extra altitude produces extra rings instead of restretching the ones already on screen.
- **Reference:** https://motion-garden.netlify.app/components/contour
- **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
# Contour 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/contour/contour.tsx`

```tsx
"use client";

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

interface ContourProps {
  levels?: number;
  cellSize?: number;
  speed?: number;
  warp?: number;
  cursorRadius?: number;
  cursorStrength?: number;
  indexEvery?: number;
  lineWidth?: number;
  lineColor?: string;
  indexColor?: string;
  background?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const NOISE_SCALE = 0.0034;

const DRIFT = 0.055;

const MAX_CELLS = 200;

const PERM = (() => {
  const base = new Uint8Array(256);
  for (let i = 0; i < 256; i++) base[i] = i;
  let s = 1337 >>> 0;
  const rnd = () => {
    s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
    return s / 4294967296;
  };
  for (let i = 255; i > 0; i--) {
    const j = Math.floor(rnd() * (i + 1));
    const t = base[i];
    base[i] = base[j];
    base[j] = t;
  }
  const p = new Uint8Array(512);
  for (let i = 0; i < 512; i++) p[i] = base[i & 255];
  return p;
})();

const latticeValue = (xi: number, yi: number) =>
  PERM[(PERM[xi & 255] + (yi & 255)) & 511] / 255;

const fade = (t: number) => t * t * (3 - 2 * t);

function valueNoise(x: number, y: number): number {
  const xi = Math.floor(x);
  const yi = Math.floor(y);
  const u = fade(x - xi);
  const v = fade(y - yi);
  const a = latticeValue(xi, yi);
  const b = latticeValue(xi + 1, yi);
  const c = latticeValue(xi, yi + 1);
  const d = latticeValue(xi + 1, yi + 1);
  const top = a + (b - a) * u;
  const bottom = c + (d - c) * u;
  return top + (bottom - top) * v;
}

function fbm(x: number, y: number): number {
  return (
    (valueNoise(x, y) * 0.5 +
      valueNoise(x * 2, y * 2) * 0.25 +
      valueNoise(x * 4, y * 4) * 0.125) /
    0.875
  );
}

const Contour = memo(
  ({
    levels = 22,
    cellSize = 14,
    speed = 0.6,
    warp = 0.35,
    cursorRadius = 180,
    cursorStrength = 0.55,
    indexEvery = 5,
    lineWidth = 1,
    lineColor = "#5b5772",
    indexColor = "#a855f7",
    background = "#0d0d12",
    paused = false,
    reducedMotion = false,
    className,
  }: ContourProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const drawRef = useRef<((dt: number) => void | false) | null>(null);
    const measureRef = useRef<((m: Metrics) => void) | null>(null);
    const pointer = useRef({ x: 0, y: 0, inside: false });

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

    const live = useRef({
      levels, cellSize, speed, warp, cursorRadius, cursorStrength,
      indexEvery, lineWidth, lineColor, indexColor, background, reducedMotion,
    });
    live.current = {
      levels, cellSize, speed, warp, cursorRadius, cursorStrength,
      indexEvery, lineWidth, lineColor, indexColor, background, reducedMotion,
    };

    const state = useRef({
      ctx: null as CanvasRenderingContext2D | null,
      field: new Float32Array(0),
      gw: 0,
      gh: 0,
      cs: 0,
      w: 0,
      h: 0,
      ox: 0,
      oy: 0,
      px: 0,
      py: 0,
      influence: 0,
      elapsed: 0,
    });

    measureRef.current = ({ width, height, dpr, bufferWidth, bufferHeight }) => {
      const canvas = canvasRef.current;
      if (!canvas || width < 1 || height < 1) return;
      const s = state.current;
      if (!s.ctx) s.ctx = canvas.getContext("2d", { alpha: false });
      canvas.width = bufferWidth;
      canvas.height = bufferHeight;
      canvas.style.width = `${width}px`;
      canvas.style.height = `${height}px`;
      s.ctx?.setTransform(dpr, 0, 0, dpr, 0, 0);

      const cs = Math.max(
        live.current.cellSize,
        width / MAX_CELLS,
        height / MAX_CELLS,
      );
      const gw = Math.max(2, Math.ceil(width / cs));
      const gh = Math.max(2, Math.ceil(height / cs));
      s.cs = cs;
      s.gw = gw;
      s.gh = gh;
      s.w = width;
      s.h = height;
      const need = (gw + 1) * (gh + 1);
      if (s.field.length !== need) s.field = new Float32Array(need);
      if (!pointer.current.inside) {
        s.px = width / 2;
        s.py = height / 2;
      }
    };

    drawRef.current = (dt) => {
      const s = state.current;
      const l = live.current;
      const ctx = s.ctx;
      if (!ctx || s.gw < 2) return;

      s.elapsed = (s.elapsed + dt) % 3600;

      s.ox = (s.ox + dt * l.speed * DRIFT) % 256;
      s.oy = (s.oy + dt * l.speed * DRIFT * 0.62) % 256;

      const ease = (rate: number) => 1 - Math.exp(-dt * rate);
      s.px += (pointer.current.x - s.px) * ease(9);
      s.py += (pointer.current.y - s.py) * ease(9);
      const want = pointer.current.inside && !l.reducedMotion ? 1 : 0;
      s.influence += (want - s.influence) * ease(4);

      const { gw, gh, cs, field } = s;
      const bump = l.cursorStrength * s.influence;
      const sigma = Math.max(8, l.cursorRadius * 0.5);
      const inv2s2 = 1 / (2 * sigma * sigma);
      const warpAmt = l.warp * 1.6;

      let min = Infinity;
      let max = -Infinity;

      for (let j = 0; j <= gh; j++) {
        const py = j * cs;
        const ny = py * NOISE_SCALE + s.oy;
        const rowBase = j * (gw + 1);
        for (let i = 0; i <= gw; i++) {
          const px = i * cs;
          const nx = px * NOISE_SCALE + s.ox;

          let sx = nx;
          let sy = ny;
          if (warpAmt > 0) {
            sx += (valueNoise(nx * 1.7 + 11.3, ny * 1.7) - 0.5) * warpAmt;
            sy += (valueNoise(nx * 1.7, ny * 1.7 + 5.7) - 0.5) * warpAmt;
          }

          let v = fbm(sx, sy);

          if (bump !== 0) {
            const dx = px - s.px;
            const dy = py - s.py;
            v += bump * Math.exp(-(dx * dx + dy * dy) * inv2s2);
          }

          field[rowBase + i] = v;
          if (v < min) min = v;
          if (v > max) max = v;
        }
      }

      ctx.fillStyle = l.background;
      ctx.fillRect(0, 0, s.w, s.h);

      const interval = 1 / Math.max(1, l.levels);
      const first = Math.ceil(min / interval);
      const last = Math.floor(max / interval);
      const every = Math.max(2, Math.round(l.indexEvery));

      const regular = new Path2D();
      const indexed = new Path2D();

      for (let k = first; k <= last; k++) {
        const iso = k * interval;
        const path = Math.abs(k) % every === 0 ? indexed : regular;

        for (let j = 0; j < gh; j++) {
          const top = j * (gw + 1);
          const bot = top + gw + 1;
          const y0 = j * cs;
          const y1 = y0 + cs;

          for (let i = 0; i < gw; i++) {
            const a = field[top + i];
            const b = field[top + i + 1];
            const c = field[bot + i + 1];
            const d = field[bot + i];

            let code = 0;
            if (a >= iso) code |= 1;
            if (b >= iso) code |= 2;
            if (c >= iso) code |= 4;
            if (d >= iso) code |= 8;
            if (code === 0 || code === 15) continue;

            const x0 = i * cs;
            const x1 = x0 + cs;

            const tx = x0 + (cs * (iso - a)) / (b - a);
            const rx = y0 + (cs * (iso - b)) / (c - b);
            const bx = x0 + (cs * (iso - d)) / (c - d);
            const lx = y0 + (cs * (iso - a)) / (d - a);

            const seg = (ax: number, ay: number, bx2: number, by: number) => {
              path.moveTo(ax, ay);
              path.lineTo(bx2, by);
            };

            switch (code) {
              case 1:
              case 14:
                seg(x0, lx, tx, y0);
                break;
              case 2:
              case 13:
                seg(tx, y0, x1, rx);
                break;
              case 3:
              case 12:
                seg(x0, lx, x1, rx);
                break;
              case 4:
              case 11:
                seg(x1, rx, bx, y1);
                break;
              case 6:
              case 9:
                seg(tx, y0, bx, y1);
                break;
              case 7:
              case 8:
                seg(x0, lx, bx, y1);
                break;
              case 5: {
                if ((a + b + c + d) * 0.25 >= iso) {
                  seg(x0, lx, bx, y1);
                  seg(tx, y0, x1, rx);
                } else {
                  seg(x0, lx, tx, y0);
                  seg(x1, rx, bx, y1);
                }
                break;
              }
              case 10: {
                if ((a + b + c + d) * 0.25 >= iso) {
                  seg(x0, lx, tx, y0);
                  seg(x1, rx, bx, y1);
                } else {
                  seg(x0, lx, bx, y1);
                  seg(tx, y0, x1, rx);
                }
                break;
              }
            }
          }
        }
      }

      ctx.lineCap = "round";
      ctx.lineJoin = "round";
      ctx.globalAlpha = 0.42;
      ctx.strokeStyle = l.lineColor;
      ctx.lineWidth = l.lineWidth;
      ctx.stroke(regular);
      ctx.globalAlpha = 0.92;
      ctx.strokeStyle = l.indexColor;
      ctx.lineWidth = l.lineWidth * 1.5;
      ctx.stroke(indexed);
      ctx.globalAlpha = 1;
    };

    const track = (e: React.PointerEvent<HTMLDivElement>) => {
      const rect = e.currentTarget.getBoundingClientRect();
      pointer.current.x = e.clientX - rect.left;
      pointer.current.y = e.clientY - rect.top;
      pointer.current.inside = true;
    };

    const leave = () => {
      pointer.current.inside = false;
    };

    return (
      <div
        ref={containerRef}
        className={`relative h-full w-full ${className ?? ""}`}
        onPointerMove={track}
        onPointerLeave={leave}
        onPointerCancel={leave}
      >
        <canvas
          ref={canvasRef}
          className="absolute inset-0 block h-full w-full"
        />
      </div>
    );
  },
);

Contour.displayName = "Contour";

export default Contour;
```

### 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 |
| --- | --- | --- | --- |
| `levels` | `number` | `22` | Contours per unit of altitude — the map's contour interval, inverted into the number a reader actually wants. This is a density rather than a count: how many lines land on screen is whatever that interval yields across the range the terrain currently occupies, so raising a peak under the cursor adds rings instead of crowding the ones already drawn. Range 6–48. |
| `cellSize` | `number` | `14` | Spacing of the height samples, and therefore the resolution of the whole map. Contours can only turn at a cell boundary, so a coarse grid gives visibly faceted rings while a fine one costs another full field sweep every frame. Below about 10px on a wide canvas a cost cap takes over and the cell grows back on its own. Range 6–28 px. |
| `speed` | `number` | `0.6` | How fast the land drifts beneath the frame. It is scrolled, never regenerated — the same hills pass through and leave, which is why a feature holds its shape long enough to be recognised on the way out. Range 0–3. |
| `warp` | `number` | `0.35` | Domain warp: the sample coordinates are displaced by the field itself before it is read. At zero the map is concentric ovals and reads as a lava lamp. Raising it folds the contours into ridges, valleys and saddles, which is the point at which it starts to look surveyed rather than generated. Range 0–1. |
| `cursorRadius` | `number` | `180` | Width of the landform the pointer raises, as the sigma of a Gaussian. Small and sharp reads as a volcanic plug with rings stacked tight around it; wide and low reads as a swell the contours merely lean around. Range 40–400 px. |
| `cursorStrength` | `number` | `0.55` | Height of that landform, in the same units as the terrain. Negative digs a depression instead and the map reads as a crater rather than a hill. Zero takes the pointer off the map entirely. Range -1–1. |
| `indexEvery` | `number` | `5` | Every Nth contour is an index contour, drawn brighter and heavier the way a real map weights its counted lines. The emphasis is keyed to absolute altitude rather than to draw order, so a given ring keeps its weight as the land moves under it instead of the highlight crawling through the set. Range 2–10. |
| `lineWidth` | `number` | `1` | Weight of an ordinary contour. Index contours are always drawn at one and a half times this, so the hierarchy survives at any setting. Range 0.5–3 px. |
| `lineColor` | `string (hex)` | `"#5b5772"` | The ordinary contours. Deliberately close to the paper — they are the texture, not the subject. |
| `indexColor` | `string (hex)` | `"#a855f7"` | The index contours, and the only real light on the map. |
| `background` | `string (hex)` | `"#0d0d12"` | The paper. |

## Usage

```tsx
import Contour from "@/components/registry/contour/contour";

<Contour
  levels={22}
  cellSize={14}
  speed={0.6}
  warp={0.35}
  cursorRadius={180}
  cursorStrength={0.55}
  indexEvery={5}
  lineWidth={1}
  lineColor="#5b5772"
  indexColor="#a855f7"
  background="#0d0d12"
/>
```

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