# Integrate `Moire` from Motion Garden

You are helping me add the **Moire** 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:** Moire
- **Category:** Backgrounds
- **Summary:** Two lattices stacked at a fraction of a degree apart, beating against each other into live interference fringes. Every layer is band-limited in the shader, so what you see is the interference and not the sampling.
- **Reference:** https://motion-garden.netlify.app/components/moire
- **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/moire/moire.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 MoireProps {
  lattice?: "lines" | "grid" | "dots" | "rings";
  pitch?: number;
  angle?: number;
  drift?: number;
  separation?: number;
  thickness?: number;
  contrast?: number;
  pointerInfluence?: number;
  inkColor?: string;
  backgroundColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const LATTICE_ID: Record<string, number> = { lines: 0, grid: 1, dots: 2, rings: 3 };

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 vec3  uPhase;
uniform float uPitch;
uniform float uAngle;
uniform float uDrift;
uniform float uSeparation;
uniform float uThickness;
uniform float uContrast;
uniform vec2  uPointer;
uniform float uPointerInfluence;
uniform float uLattice;
uniform vec3  uInk;
uniform vec3  uBg;

mat2 rot(float a) { float s = sin(a); float c = cos(a); return mat2(c, -s, s, c); }

// Band-limited coverage of one 1D lattice. w is cells per pixel: as it grows the
// smoothstep spans the whole cell and the layer greys out instead of aliasing.
float bandCov(float p, float duty, float w) {
  float d = abs(fract(p) - 0.5);
  float h = 0.5 * duty;
  return 1.0 - smoothstep(h - w, h + w, d);
}

// 1 where the two lattices sit in phase, 0 where they are exactly interleaved.
// This is the beat itself, read off the phase difference rather than inferred
// from the pixels — it varies slowly across the frame, which is why it can carry
// colour without carrying the lattice's own frequency along with it.
float phaseAlign(float d) {
  return 1.0 - 2.0 * abs(fract(d + 0.5) - 0.5);
}

// Derivatives are taken once, before any branch — fwidth inside divergent control
// flow is undefined in GLSL ES 3.0.
float layerCoverage(vec2 p, float duty) {
  vec2 wv = max(fwidth(p), vec2(1e-5));
  if (uLattice < 0.5) {
    return bandCov(p.y, duty, wv.y);
  }
  if (uLattice < 1.5) {
    return max(bandCov(p.x, duty, wv.x), bandCov(p.y, duty, wv.y));
  }
  if (uLattice < 2.5) {
    float d = length(fract(p) - 0.5);
    float w = max(wv.x, wv.y) * 0.75;
    float r = 0.5 * duty;
    return 1.0 - smoothstep(r - w, r + w, d);
  }
  return bandCov(length(p), duty, length(wv) * 0.7);
}

void main() {
  vec2 res = uResolution / uDpr;
  vec2 c = gl_FragCoord.xy / uDpr - res * 0.5;

  // Half the angle onto each layer, so 0° stacks them exactly and the field goes
  // blank — which is the honest reading of "no rotation between the lattices".
  float wobble = sin(uPhase.x) * 0.8 * uDrift;
  float half_ = radians(uAngle + wobble + uPointer.x * 1.2 * uPointerInfluence) * 0.5;

  vec2 slide = vec2(cos(uPhase.y), sin(uPhase.z)) * uDrift * 5.0
             + uPointer * 16.0 * uPointerInfluence;
  vec2 sep = vec2(uSeparation, 0.0) + slide;

  float pitch = max(uPitch, 0.5);
  vec2 pa = (rot(-half_) * c) / pitch;
  vec2 pb = (rot(half_) * (c + sep)) / pitch;

  float a = layerCoverage(pa, uThickness);
  float b = layerCoverage(pb, uThickness);

  // Two ink layers stacked: what stays clear is what neither one covered.
  float ink = 1.0 - (1.0 - a) * (1.0 - b);

  // Expand around the pattern's own mean, not around 0.5 — otherwise raising
  // contrast just floods the frame with ink instead of opening the fringes.
  float pivot = 1.0 - (1.0 - uThickness) * (1.0 - uThickness);
  ink = clamp((ink - pivot) * uContrast + pivot, 0.0, 1.0);

  float align;
  if (uLattice < 0.5)      align = phaseAlign(pa.y - pb.y);
  else if (uLattice < 2.5) align = min(phaseAlign(pa.x - pb.x), phaseAlign(pa.y - pb.y));
  else                     align = phaseAlign(length(pa) - length(pb));

  // Where the lattices agree their ink lands on the same pixels and the band
  // should read as absence, not as more lines. Dimming the ink toward the field
  // in those zones makes the fringe the subject; leave it out and you get an
  // evenly loud grating with a faint beat somewhere inside it.
  vec3 line = mix(uBg, uInk, 0.2 + 0.8 * (1.0 - align));

  fragColor = vec4(mix(uBg, line, ink), 1.0);
}`;

const Moire = memo(
  ({
    lattice = "lines",
    pitch = 9,
    angle = 3.2,
    drift = 0.35,
    separation = 6,
    thickness = 0.16,
    contrast = 1,
    pointerInfluence = 1,
    inkColor = "#a855f7",
    backgroundColor = "#08050e",
    paused = false,
    reducedMotion = false,
    className,
  }: MoireProps) => {
    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({
      lattice, pitch, angle, drift, separation, thickness,
      contrast, pointerInfluence, inkColor, backgroundColor,
    });
    live.current = {
      lattice, pitch, angle, drift, separation, thickness,
      contrast, pointerInfluence, inkColor, backgroundColor,
    };

    const pointer = useRef({ x: 0, y: 0, tx: 0, ty: 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, 0]) },
          uPitch: { value: pitch },
          uAngle: { value: angle },
          uDrift: { value: drift },
          uSeparation: { value: separation },
          uThickness: { value: thickness },
          uContrast: { value: contrast },
          uPointer: { value: new Float32Array([0, 0]) },
          uPointerInfluence: { value: pointerInfluence },
          uLattice: { value: LATTICE_ID[lattice] ?? 0 },
          uInk: { value: new Float32Array(hexToRgb01(inkColor)) },
          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, 0]);
      const RATES = [0.5, 0.23, 0.19];
      const TAU = Math.PI * 2;

      const sync = () => {
        const l = live.current;
        (u.uPhase.value as Float32Array).set(phase);
        u.uPitch.value = l.pitch;
        u.uAngle.value = l.angle;
        u.uDrift.value = l.drift;
        u.uSeparation.value = l.separation;
        u.uThickness.value = l.thickness;
        u.uContrast.value = l.contrast;
        u.uPointerInfluence.value = l.pointerInfluence;
        u.uLattice.value = LATTICE_ID[l.lattice] ?? 0;
        (u.uPointer.value as Float32Array)[0] = pointer.current.x;
        (u.uPointer.value as Float32Array)[1] = pointer.current.y;
        (u.uInk.value as Float32Array).set(hexToRgb01(l.inkColor));
        (u.uBg.value as Float32Array).set(hexToRgb01(l.backgroundColor));
      };

      drawRef.current = (dt) => {
        for (let i = 0; i < 3; 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;
        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();
    }, [
      lattice, pitch, angle, drift, separation, thickness,
      contrast, pointerInfluence, inkColor, backgroundColor, loop,
    ]);

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

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

    if (fallback) {
      const stripe = (deg: number) =>
        `repeating-linear-gradient(${deg}deg, ${inkColor} 0 ${pitch * thickness}px, transparent ${pitch * thickness}px ${pitch}px)`;
      return (
        <div
          className={className ?? "relative h-full w-full overflow-hidden"}
          style={{
            backgroundColor,
            backgroundImage: `${stripe(90 - angle)}, ${stripe(90)}`,
            opacity: 0.9,
          }}
        />
      );
    }

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

Moire.displayName = "Moire";

export default Moire;
```

### 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 |
| --- | --- | --- | --- |
| `lattice` | `"lines" | "grid" | "dots" | "rings"` | `"lines"` | Shape of the two stacked layers. Lines beat into banding, grid into a woven plaid, dots into a rosette, rings into a bullseye that walks as you move. |
| `pitch` | `number` | `9` | Spacing of one lattice cell, in CSS pixels. Widen it and the beat frequency drops — the fringes get broader and travel slower even though nothing else changed. Range 3–40 px. |
| `angle` | `number` | `3.2` | Rotation between the two layers. This is the whole effect: at 0° they stack invisibly, and a tenth of a degree either side sweeps the fringes across the entire field. Range 0–45 °. |
| `drift` | `number` | `0.35` | How far the angle and offset breathe on their own. 0 holds one still interference pattern, which is the honest setting to put behind body copy. Range 0–3 ×. |
| `separation` | `number` | `6` | Offset between the layers — a second beat axis independent of angle, so the fringes shift without rotating. Range 0–40 px. |
| `thickness` | `number` | `0.16` | How much of a lattice cell is ink. Kept low by default so the field stays dark enough to put content on; push it past 0.5 and the two layers cover almost everything, which is a wall rather than a background. Range 0.05–0.95. |
| `contrast` | `number` | `1` | How hard the fringes clip toward light and dark, expanded around the pattern's own mean rather than mid-grey. Above about 1.6 the soft beat becomes hard banding. Range 0.2–2.5 ×. |
| `pointerInfluence` | `number` | `1` | How much the cursor twists and shifts the top lattice. 0 leaves a field that ignores you entirely. Range 0–3 ×. |
| `inkColor` | `string (hex)` | `"#a855f7"` | Amethyst of the lattice lines themselves. |
| `backgroundColor` | `string (hex)` | `"#08050e"` | The dark field the two lattices sit on. |

## Usage

```tsx
import Moire from "@/components/registry/moire/moire";

<Moire
  lattice="lines"
  pitch={9}
  angle={3.2}
  drift={0.35}
  separation={6}
  thickness={0.16}
  contrast={1}
  pointerInfluence={1}
  inkColor="#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.
