# Integrate `VoronoiShatter` from Motion Garden

You are helping me add the **VoronoiShatter** 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:** VoronoiShatter
- **Category:** Backgrounds
- **Summary:** Lit cells that fracture apart under the pointer and knit back together behind it. The seam is drawn from the gap between the two nearest seeds rather than the distance to the nearest one, so it holds an even width right through the vertices where three cells meet — and the shatter displaces the space rather than the seeds, so no cell ever swaps neighbours mid-fracture.
- **Reference:** https://motion-garden.netlify.app/components/voronoi-shatter
- **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
bun add ogl
```

## 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/voronoi-shatter/voronoi-shatter.tsx`

```tsx
"use client";

import { memo, useEffect, useRef, useState } from "react";
import { Renderer, Program, Mesh, Triangle } from "ogl";
import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";

interface VoronoiShatterProps {
  density?: number;
  drift?: number;
  seamWidth?: number;
  seamGlow?: number;
  shatter?: number;
  shatterRadius?: number;
  cellContrast?: number;
  seamColor?: string;
  cellColor?: string;
  backgroundColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const PARKED = 4;

const hexToRgb01 = (hex: string): [number, number, number] => {
  const h = hex.replace("#", "");
  const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
  const n = parseInt(full, 16);
  if (Number.isNaN(n) || full.length !== 6) return [1, 1, 1];
  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
};

const supportsWebGL2 = () => {
  try {
    return !!document.createElement("canvas").getContext("webgl2");
  } catch {
    return false;
  }
};

const vertex = `#version 300 es
in vec2 position;
void main() { gl_Position = vec4(position, 0.0, 1.0); }`;

const fragment = `#version 300 es
precision highp float;
out vec4 fragColor;

uniform vec2  uResolution;
uniform float uDpr;
uniform vec2  uPhase;
uniform float uDensity;
uniform float uDrift;
uniform float uSeamWidth;
uniform float uSeamGlow;
uniform float uShatter;
uniform float uShatterRadius;
uniform float uCellContrast;
uniform vec2  uPointer;
uniform vec3  uSeam;
uniform vec3  uCell;
uniform vec3  uBg;

#define TAU 6.28318530718

vec2 hash2(vec2 cell) {
  vec3 p = fract(vec3(cell.xyx) * vec3(0.1031, 0.1030, 0.0973));
  p += dot(p, p.yzx + 33.33);
  return fract((p.xx + p.yz) * p.zy);
}

// (F1, F2, cell id). The id is the seed's own hash, so it survives the seeds
// moving — a cell keeps its brightness for the whole session instead of
// flickering as the ordering of the 3x3 search changes.
vec3 cells(vec2 p) {
  vec2 base = floor(p);
  vec2 local = fract(p);

  float f1 = 8.0;
  float f2 = 8.0;
  float id = 0.0;

  for (int j = -1; j <= 1; j++) {
    for (int i = -1; i <= 1; i++) {
      vec2 offset = vec2(float(i), float(j));
      vec2 rand = hash2(base + offset);
      // Orbit, not translation. Bounded by construction, so the seed can never
      // leave its own cell however high the drift goes.
      vec2 seed = offset + 0.5
        + (rand - 0.5) * 0.7
        + uDrift * vec2(sin(uPhase.x + rand.x * TAU), cos(uPhase.y + rand.y * TAU));

      float d = length(seed - local);
      if (d < f1) {
        f2 = f1;
        f1 = d;
        id = rand.x;
      } else if (d < f2) {
        f2 = d;
      }
    }
  }
  return vec3(f1, f2, id);
}

void main() {
  vec2 res = uResolution / uDpr;
  vec2 uv = (gl_FragCoord.xy / uDpr) / res;
  float aspect = res.x / max(res.y, 1.0);

  vec2 centred = (uv - 0.5) * vec2(aspect, 1.0);
  // gl_FragCoord counts up from the bottom and the pointer is reported from the
  // top, so the y has to be flipped or the fracture appears mirrored about the
  // horizon from wherever the cursor actually is.
  vec2 cursor = vec2(uPointer.x, -uPointer.y) * 0.5 * vec2(aspect, 1.0);

  vec2 away = centred - cursor;
  float reach = max(uShatterRadius, 1e-4);
  // Gaussian rather than a linear falloff: a linear one has a hard outer edge
  // that reads as a circular seam of its own, which is a second shape nobody
  // asked for.
  float force = exp(-dot(away, away) / (reach * reach));
  // Displaced along the raw offset, NOT along its normalised direction. A
  // normalised push has constant magnitude however close to the cursor you get,
  // so every seam in the neighbourhood converges on one point and the fracture
  // collapses into a starburst with a singularity at its centre. Scaling by the
  // raw offset sends the displacement to zero at the cursor, which is what a
  // lens does and what the cells being pushed apart actually looks like.
  centred += away * force * uShatter * 2.0;

  vec3 v = cells(centred * uDensity);
  float border = v.y - v.x;

  // Derivatives outside any branch — fwidth inside divergent control flow is
  // undefined in GLSL ES 3.0, and the 3x3 search above is nothing but branches.
  float w = fwidth(border) + 1e-4;
  float seam = 1.0 - smoothstep(uSeamWidth - w, uSeamWidth + w, border);
  float bloom = exp(-border * 14.0) * uSeamGlow;

  vec3 color = mix(uBg, uCell, v.z * uCellContrast);
  color += uSeam * bloom;
  color = mix(color, uSeam, seam);

  fragColor = vec4(color, 1.0);
}`;

const VoronoiShatter = memo(
  ({
    density = 9,
    drift = 0.28,
    seamWidth = 0.06,
    seamGlow = 0.6,
    shatter = 0.45,
    shatterRadius = 0.35,
    cellContrast = 0.35,
    seamColor = "#e9d5ff",
    cellColor = "#a855f7",
    backgroundColor = "#08050e",
    paused = false,
    reducedMotion = false,
    className,
  }: VoronoiShatterProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const drawRef = useRef<((dt: number) => void | false) | null>(null);
    const measureRef = useRef<((m: Metrics) => void) | null>(null);
    const glRef = useRef<WebGLRenderingContext | WebGL2RenderingContext | null>(null);

    const [fallback, setFallback] = useState(false);

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

    const live = useRef({
      density, drift, seamWidth, seamGlow, shatter,
      shatterRadius, cellContrast, seamColor, cellColor, backgroundColor,
    });
    live.current = {
      density, drift, seamWidth, seamGlow, shatter,
      shatterRadius, cellContrast, seamColor, cellColor, backgroundColor,
    };

    const pointer = useRef({ x: PARKED, y: PARKED, tx: PARKED, ty: PARKED, s: 0, ts: 0 });

    useEffect(() => {
      const container = containerRef.current;
      if (fallback || !container) return;
      if (!supportsWebGL2()) {
        setFallback(true);
        return;
      }

      const renderer = new Renderer({
        webgl: 2,
        alpha: false,
        antialias: false,
        powerPreference: "high-performance",
        dpr: Math.min(window.devicePixelRatio || 1, 2),
      });
      const gl = renderer.gl;
      glRef.current = gl;

      const canvas = gl.canvas as HTMLCanvasElement;
      canvas.style.display = "block";
      canvas.style.position = "absolute";
      canvas.style.top = "0";
      canvas.style.left = "0";
      container.appendChild(canvas);

      const program = new Program(gl, {
        vertex,
        fragment,
        uniforms: {
          uResolution: { value: new Float32Array([1, 1]) },
          uDpr: { value: 1 },
          uPhase: { value: new Float32Array([0, 0]) },
          uDensity: { value: density },
          uDrift: { value: drift },
          uSeamWidth: { value: seamWidth },
          uSeamGlow: { value: seamGlow },
          uShatter: { value: shatter },
          uShatterRadius: { value: shatterRadius },
          uCellContrast: { value: cellContrast },
          uPointer: { value: new Float32Array([PARKED, PARKED]) },
          uSeam: { value: new Float32Array(hexToRgb01(seamColor)) },
          uCell: { value: new Float32Array(hexToRgb01(cellColor)) },
          uBg: { value: new Float32Array(hexToRgb01(backgroundColor)) },
        },
      });
      const mesh = new Mesh(gl, { geometry: new Triangle(gl), program });
      const u = program.uniforms as Record<string, { value: number | Float32Array }>;

      const phase = new Float32Array([0, 0]);
      const RATES = [0.41, 0.27];
      const TAU = Math.PI * 2;

      const sync = () => {
        const l = live.current;
        (u.uPhase.value as Float32Array).set(phase);
        u.uDensity.value = l.density;
        u.uDrift.value = l.drift;
        u.uSeamWidth.value = l.seamWidth;
        u.uSeamGlow.value = l.seamGlow;
        u.uShatter.value = l.shatter * pointer.current.s;
        u.uShatterRadius.value = l.shatterRadius;
        u.uCellContrast.value = l.cellContrast;
        (u.uPointer.value as Float32Array)[0] = pointer.current.x;
        (u.uPointer.value as Float32Array)[1] = pointer.current.y;
        (u.uSeam.value as Float32Array).set(hexToRgb01(l.seamColor));
        (u.uCell.value as Float32Array).set(hexToRgb01(l.cellColor));
        (u.uBg.value as Float32Array).set(hexToRgb01(l.backgroundColor));
      };

      drawRef.current = (dt) => {
        for (let i = 0; i < 2; i++) {
          phase[i] = (phase[i] + dt * RATES[i]) % TAU;
        }
        const p = pointer.current;
        const k = Math.min(1, dt * 6);
        p.x += (p.tx - p.x) * k;
        p.y += (p.ty - p.y) * k;
        const ks = Math.min(1, dt * (p.ts > p.s ? 7 : 2.2));
        p.s += (p.ts - p.s) * ks;
        sync();
        renderer.render({ scene: mesh });
      };

      measureRef.current = ({ width, height, dpr }) => {
        renderer.dpr = dpr;
        renderer.setSize(Math.max(1, Math.floor(width)), Math.max(1, Math.floor(height)));
        const res = u.uResolution.value as Float32Array;
        res[0] = gl.drawingBufferWidth;
        res[1] = gl.drawingBufferHeight;
        u.uDpr.value = dpr;
        sync();
        renderer.render({ scene: mesh });
      };

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

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

    useEffect(() => {
      loop.paint();
    }, [
      density, drift, seamWidth, seamGlow, shatter, shatterRadius,
      cellContrast, seamColor, cellColor, backgroundColor, loop,
    ]);

    const track = (e: React.PointerEvent<HTMLDivElement>) => {
      const r = e.currentTarget.getBoundingClientRect();
      if (r.width === 0 || r.height === 0) return;
      const p = pointer.current;
      p.tx = ((e.clientX - r.left) / r.width) * 2 - 1;
      p.ty = ((e.clientY - r.top) / r.height) * 2 - 1;
      if (p.s < 0.02) {
        p.x = p.tx;
        p.y = p.ty;
      }
      p.ts = 1;
      loop.start();
    };

    const release = () => {
      pointer.current.ts = 0;
      loop.start();
    };

    if (fallback) {
      const cell = 100 / Math.max(3, Math.round(density));
      const line = `${seamColor} 0 1px, transparent 1px ${cell}%`;
      return (
        <div
          className={className ?? "relative h-full w-full overflow-hidden"}
          style={{
            backgroundColor,
            backgroundImage: [
              `repeating-linear-gradient(64deg, ${line})`,
              `repeating-linear-gradient(-38deg, ${line})`,
              `radial-gradient(80% 80% at 50% 50%, ${cellColor} 0%, transparent 70%)`,
            ].join(", "),
            opacity: 0.85,
          }}
        />
      );
    }

    return (
      <div
        ref={containerRef}
        className={className ?? "relative h-full w-full overflow-hidden"}
        onPointerMove={track}
        onPointerLeave={release}
        onPointerCancel={release}
      />
    );
  },
);

VoronoiShatter.displayName = "VoronoiShatter";

export default VoronoiShatter;
```

### 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 |
| --- | --- | --- | --- |
| `density` | `number` | `9` | Cells across the frame. The 3×3 neighbour search runs per pixel regardless, so this changes the look and not the cost — the only knob here that is free. Range 3–30. |
| `drift` | `number` | `0.28` | How far each seed orbits its resting point, in cell widths. An orbit rather than a translation: it is bounded by construction, so the seed can never leave its own cell and the lattice cannot tear however high this goes. Range 0–0.5. |
| `seamWidth` | `number` | `0.06` | Thickness of the lit boundary. Widened by the local derivative before it is thresholded, so a seam running diagonally across a pixel is filtered rather than stepped. Range 0.005–0.25. |
| `seamGlow` | `number` | `0.6` | Bloom carried from the seam out into the cells. This is what makes the cells read as panes with light behind them rather than as flat tiles with a line between them. Range 0–2 ×. |
| `shatter` | `number` | `0.45` | How hard the field is pushed apart under the pointer. At 0 the surface is intact and the component is an ambient cell field; past about 1.2 the near cells stretch far enough to read as smears rather than as panes. Range 0–2. |
| `shatterRadius` | `number` | `0.35` | Reach of the push, as a fraction of frame height. Falls off on a Gaussian — a linear falloff has a hard outer edge that reads as a second circular seam nobody asked for. Range 0.05–1.5. |
| `cellContrast` | `number` | `0.35` | How much cell-to-cell brightness varies. Keyed to the seed's own hash rather than to the search order, so a cell holds its shade for the whole session instead of flickering as the seeds move past each other. Range 0–1. |
| `seamColor` | `string (hex)` | `"#e9d5ff"` | The boundaries, and the bloom they cast into the cells. |
| `cellColor` | `string (hex)` | `"#a855f7"` | What a fully-lit cell grades toward from the background. |
| `backgroundColor` | `string (hex)` | `"#08050e"` | The field behind the cells. Its own material rather than a themed surface, for the same reason every full-bleed background here is. |

## Usage

```tsx
import VoronoiShatter from "@/components/registry/voronoi-shatter/voronoi-shatter";

<VoronoiShatter
  density={9}
  drift={0.28}
  seamWidth={0.06}
  seamGlow={0.6}
  shatter={0.45}
  shatterRadius={0.35}
  cellContrast={0.35}
  seamColor="#e9d5ff"
  cellColor="#a855f7"
  backgroundColor="#08050e"
/>
```

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.
