# Integrate `Stipple` from Motion Garden

You are helping me add the **Stipple** 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:** Stipple
- **Category:** Backgrounds
- **Summary:** A flowing luminance field crushed to ink and paper by error diffusion. Each cell's quantization error is pushed onto its unvisited neighbours in a serpentine scan, so mid-tones resolve into the organic scattered grain of a stippled engraving instead of a fixed lattice. Atkinson forwards only three-quarters of the error, which is why the classic-Mac look keeps its blown highlights. Floyd–Steinberg and Sierra spread all of it for a smoother ramp. The field is diffused on the CPU into an ImageData at one cell per CSS pixel-group, then scaled up with smoothing off, so the grid survives retina intact.
- **Reference:** https://motion-garden.netlify.app/components/stipple
- **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
# Stipple 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/stipple/stipple.tsx`

```tsx
"use client";

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

export type StippleAlgorithm = "atkinson" | "floyd-steinberg" | "sierra";

export interface StippleProps {
  algorithm?: StippleAlgorithm;
  pixelSize?: number;
  fieldScale?: number;
  speed?: number;
  contrast?: number;
  serpentine?: boolean;
  ink?: string;
  paper?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const hexToRgb = (hex: string): [number, number, number] => {
  const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  if (!m) return [255, 255, 255];
  return [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)];
};

const hash2 = (x: number, y: number): number => {
  let h = (Math.imul(x | 0, 374761393) + Math.imul(y | 0, 668265263)) | 0;
  h = Math.imul(h ^ (h >>> 13), 1274126177);
  h ^= h >>> 16;
  return (h >>> 0) / 4294967296;
};

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

const vnoise = (x: number, y: number): number => {
  const xi = Math.floor(x);
  const yi = Math.floor(y);
  const xf = x - xi;
  const yf = y - yi;
  const u = smooth(xf);
  const v = smooth(yf);
  const a = hash2(xi, yi);
  const b = hash2(xi + 1, yi);
  const c = hash2(xi, yi + 1);
  const d = hash2(xi + 1, yi + 1);
  return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
};

const MAX_CELLS = 180_000;

const Stipple = ({
  algorithm = "atkinson",
  pixelSize = 4,
  fieldScale = 2,
  speed = 0.25,
  contrast = 1.1,
  serpentine = true,
  ink = "#c4b5fd",
  paper = "#0b0812",
  paused = false,
  reducedMotion = false,
  className = "",
}: StippleProps) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  const live = useRef({
    algorithm,
    pixelSize,
    fieldScale,
    speed,
    contrast,
    serpentine,
    ink,
    paper,
    paused,
    reducedMotion,
  });
  live.current = {
    algorithm,
    pixelSize,
    fieldScale,
    speed,
    contrast,
    serpentine,
    ink,
    paper,
    paused,
    reducedMotion,
  };

  const drawRef = useRef<((dt: number) => void | false) | null>(null);
  const measureRef = useRef<((m: Metrics) => void) | null>(null);

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

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const cellCanvas = document.createElement("canvas");
    const cellCtx = cellCanvas.getContext("2d");
    if (!cellCtx) return;

    let cols = 0;
    let rows = 0;
    let field = new Float32Array(0);
    let image: ImageData | null = null;
    let simTime = 0;

    const rebuild = (width: number, height: number) => {
      const cfg = live.current;
      let cell = Math.max(2, cfg.pixelSize);
      const rawCells = Math.ceil(width / cell) * Math.ceil(height / cell);
      if (rawCells > MAX_CELLS) {
        cell = Math.ceil(Math.sqrt((width * height) / MAX_CELLS));
      }
      cols = Math.max(1, Math.ceil(width / cell));
      rows = Math.max(1, Math.ceil(height / cell));
      if (field.length < cols * rows) field = new Float32Array(cols * rows);
      cellCanvas.width = cols;
      cellCanvas.height = rows;
      image = cellCtx.createImageData(cols, rows);
    };

    measureRef.current = ({ width, height, bufferWidth, bufferHeight }) => {
      if (width <= 0 || height <= 0) return;
      canvas.width = bufferWidth;
      canvas.height = bufferHeight;
      canvas.style.width = `${width}px`;
      canvas.style.height = `${height}px`;
      rebuild(width, height);
      draw(0);
    };

    const draw = (dt: number): void | false => {
      if (!image || cols === 0) return;
      const cfg = live.current;
      simTime += dt * cfg.speed;

      const s = cfg.fieldScale * 0.05;
      const t1 = simTime * 0.6;
      const t2 = simTime * 0.37;
      let i = 0;
      for (let r = 0; r < rows; r++) {
        const ry1 = r * s + t2;
        const ry2 = r * s * 2.3 - t1 * 0.5;
        for (let c = 0; c < cols; c++) {
          const n =
            vnoise(c * s + t1, ry1) * 0.68 +
            vnoise(c * s * 2.3 + 7.31 - t2, ry2) * 0.32;
          field[i++] = (n - 0.5) * cfg.contrast + 0.5;
        }
      }

      const algo = cfg.algorithm;
      const serp = cfg.serpentine;
      for (let r = 0; r < rows; r++) {
        const reverse = serp && (r & 1) === 1;
        const step = reverse ? -1 : 1;
        const start = reverse ? cols - 1 : 0;
        const end = reverse ? -1 : cols;
        for (let c = start; c !== end; c += step) {
          const idx = r * cols + c;
          const oldV = field[idx];
          const newV = oldV >= 0.5 ? 1 : 0;
          field[idx] = newV;
          const err = oldV - newV;
          if (err === 0) continue;

          const cf = c + step;
          const cb = c - step;
          const below = idx + cols;
          const hasBelow = r + 1 < rows;

          if (algo === "floyd-steinberg") {
            const e16 = err / 16;
            if (cf >= 0 && cf < cols) field[idx + step] += e16 * 7;
            if (hasBelow) {
              if (cb >= 0 && cb < cols) field[below - step] += e16 * 3;
              field[below] += e16 * 5;
              if (cf >= 0 && cf < cols) field[below + step] += e16 * 1;
            }
          } else if (algo === "atkinson") {
            const e8 = err / 8;
            const cf2 = c + step * 2;
            if (cf >= 0 && cf < cols) field[idx + step] += e8;
            if (cf2 >= 0 && cf2 < cols) field[idx + step * 2] += e8;
            if (hasBelow) {
              if (cb >= 0 && cb < cols) field[below - step] += e8;
              field[below] += e8;
              if (cf >= 0 && cf < cols) field[below + step] += e8;
              if (r + 2 < rows) field[below + cols] += e8;
            }
          } else {
            const e32 = err / 32;
            const cf2 = c + step * 2;
            const cb2 = c - step * 2;
            if (cf >= 0 && cf < cols) field[idx + step] += e32 * 5;
            if (cf2 >= 0 && cf2 < cols) field[idx + step * 2] += e32 * 3;
            if (hasBelow) {
              if (cb2 >= 0 && cb2 < cols) field[below - step * 2] += e32 * 2;
              if (cb >= 0 && cb < cols) field[below - step] += e32 * 4;
              field[below] += e32 * 5;
              if (cf >= 0 && cf < cols) field[below + step] += e32 * 4;
              if (cf2 >= 0 && cf2 < cols) field[below + step * 2] += e32 * 2;
              if (r + 2 < rows) {
                const below2 = below + cols;
                if (cb >= 0 && cb < cols) field[below2 - step] += e32 * 2;
                field[below2] += e32 * 3;
                if (cf >= 0 && cf < cols) field[below2 + step] += e32 * 2;
              }
            }
          }
        }
      }

      const [ir, ig, ib] = hexToRgb(cfg.ink);
      const [pr, pg, pb] = hexToRgb(cfg.paper);
      const data = image.data;
      const total = cols * rows;
      for (let k = 0, p = 0; k < total; k++, p += 4) {
        const on = field[k] >= 0.5;
        data[p] = on ? ir : pr;
        data[p + 1] = on ? ig : pg;
        data[p + 2] = on ? ib : pb;
        data[p + 3] = 255;
      }
      cellCtx.putImageData(image, 0, 0);

      ctx.imageSmoothingEnabled = false;
      ctx.drawImage(cellCanvas, 0, 0, cols, rows, 0, 0, canvas.width, canvas.height);
    };
    drawRef.current = draw;

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

    return () => {
      drawRef.current = null;
      measureRef.current = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    loop.resize();
  }, [pixelSize, loop]);

  useEffect(() => {
    loop.paint();
  }, [algorithm, fieldScale, speed, contrast, serpentine, ink, paper, loop]);

  return (
    <div
      ref={containerRef}
      className={`relative h-full w-full overflow-hidden ${className}`.trim()}
    >
      <canvas
        ref={canvasRef}
        className="absolute inset-0 block size-full"
      />
    </div>
  );
};

export default Stipple;
```

### 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 |
| --- | --- | --- | --- |
| `algorithm` | `"atkinson" | "floyd-steinberg" | "sierra"` | `"atkinson"` | Error-diffusion kernel. Atkinson drops a quarter of the error for punchy highlights; Floyd–Steinberg is the textbook 4-tap spread; Sierra pushes across three rows for the smoothest grain. |
| `pixelSize` | `number` | `4` | CSS pixels per dither cell. The grid is measured in CSS pixels so a retina screen doesn't silently halve the cells. Range 2–12 px. |
| `fieldScale` | `number` | `2` | Spatial scale of the underlying luminance field. Range 0.5–6. |
| `speed` | `number` | `0.25` | Flow speed of the field. Zero freezes the pattern without blanking it. Range 0–2 ×. |
| `contrast` | `number` | `1.1` | Contrast curve applied around mid-grey before quantization — low values are all grain, high values are all shape. Range 0.2–3. |
| `serpentine` | `boolean` | `true` | Alternate the scan direction per row. One-way scans drag directional worm artifacts across flat regions; the boustrophedon hides them. |
| `ink` | `string (hex)` | `"#c4b5fd"` | The quantized on tone. |
| `paper` | `string (hex)` | `"#0b0812"` | The quantized off tone. |

## Usage

```tsx
import Stipple from "@/components/registry/stipple/stipple";

<Stipple
  algorithm="atkinson"
  pixelSize={4}
  fieldScale={2}
  speed={0.25}
  contrast={1.1}
  serpentine={true}
  ink="#c4b5fd"
  paper="#0b0812"
/>
```

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.
