# Integrate `Mirage` from Motion Garden

You are helping me add the **Mirage** 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:** Mirage
- **Category:** Power-User Systems
- **Summary:** Live, fully interactive HTML seen through moving air. An animated turbulence field displaces the real DOM subtree per pixel, with no snapshot and no canvas replica, so the text stays selectable, the button still takes focus and the link is still a link while the whole panel shimmers.
- **Reference:** https://motion-garden.netlify.app/components/mirage
- **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
# Mirage 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/mirage/mirage.tsx`

```tsx
"use client";

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

export type MirageMode = "haze" | "liquify" | "shatter" | "tear";
export type MirageTrigger = "always" | "hover";

export interface MirageProps {
  children?: ReactNode;
  mode?: MirageMode;
  intensity?: number;
  speed?: number;
  scale?: number;
  chroma?: number;
  trigger?: MirageTrigger;
  edgeHold?: number;
  tintColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const TILE_BASE = 180;
const TILE_MIN = 60;
const TILE_MAX = 720;

const tileFor = (scale: number) =>
  Math.max(
    TILE_MIN,
    Math.min(TILE_MAX, Math.round(TILE_BASE * Math.max(scale, 0.05))),
  );

const CELLS: Record<MirageMode, [number, number]> = {
  haze: [3, 6],
  liquify: [2, 2],
  shatter: [9, 9],
  tear: [1, 11],
};

const OCTAVES: Record<MirageMode, number> = {
  haze: 2,
  liquify: 2,
  shatter: 1,
  tear: 1,
};

const smoothstep = (a: number, b: number, x: number) => {
  const t = Math.min(1, Math.max(0, (x - a) / (b - a || 1e-6)));
  return t * t * (3 - 2 * t);
};

function makeNoise(cellsX: number, cellsY: number, seed: number) {
  const hash = (ix: number, iy: number) => {
    const x = ((ix % cellsX) + cellsX) % cellsX;
    const y = ((iy % cellsY) + cellsY) % cellsY;
    const n = Math.sin(x * 127.1 + y * 311.7 + seed * 74.7) * 43758.5453;
    return n - Math.floor(n);
  };
  return (u: number, v: number) => {
    const fx = u * cellsX;
    const fy = v * cellsY;
    const ix = Math.floor(fx);
    const iy = Math.floor(fy);
    const tx = fx - ix;
    const ty = fy - iy;
    const sx = tx * tx * (3 - 2 * tx);
    const sy = ty * ty * (3 - 2 * ty);
    const a = hash(ix, iy);
    const b = hash(ix + 1, iy);
    const c = hash(ix, iy + 1);
    const d = hash(ix + 1, iy + 1);
    return (a + (b - a) * sx) * (1 - sy) + (c + (d - c) * sx) * sy;
  };
}

function buildNoiseTile(mode: MirageMode, tile: number): HTMLCanvasElement | null {
  const canvas = document.createElement("canvas");
  canvas.width = tile;
  canvas.height = tile;
  const ctx = canvas.getContext("2d");
  if (!ctx) return null;

  const [cx, cy] = CELLS[mode];
  const oct = OCTAVES[mode];
  const n1x = makeNoise(cx, cy, 1);
  const n1y = makeNoise(cx, cy, 2);
  const n2x = makeNoise(cx * 2, cy * 2, 3);
  const n2y = makeNoise(cx * 2, cy * 2, 4);

  const img = ctx.createImageData(tile, tile);
  const data = img.data;
  for (let y = 0; y < tile; y++) {
    const v = y / tile;
    for (let x = 0; x < tile; x++) {
      const u = x / tile;
      let dx = n1x(u, v) - 0.5;
      let dy = n1y(u, v) - 0.5;
      if (oct > 1) {
        dx += (n2x(u, v) - 0.5) * 0.5;
        dy += (n2y(u, v) - 0.5) * 0.5;
      }
      const i = (y * tile + x) * 4;
      data[i] = Math.max(0, Math.min(255, 128 + dx * 220));
      data[i + 1] = Math.max(0, Math.min(255, 128 + dy * 220));
      data[i + 2] = 128;
      data[i + 3] = 255;
    }
  }
  ctx.putImageData(img, 0, 0);
  return canvas;
}

function buildNoiseMap(
  w: number,
  h: number,
  mode: MirageMode,
  tile: number,
): string {
  const src = buildNoiseTile(mode, tile);
  if (!src) return "";
  const canvas = document.createElement("canvas");
  canvas.width = Math.max(1, Math.round(w));
  canvas.height = Math.max(1, Math.round(h));
  const ctx = canvas.getContext("2d");
  if (!ctx) return "";
  const pattern = ctx.createPattern(src, "repeat");
  if (!pattern) return "";
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  return canvas.toDataURL();
}

function buildTaper(w: number, h: number, hold: number): string {
  const canvas = document.createElement("canvas");
  canvas.width = Math.max(1, Math.round(w));
  canvas.height = Math.max(1, Math.round(h));
  const ctx = canvas.getContext("2d");
  if (!ctx) return "";
  const band = Math.max(
    1,
    Math.min(canvas.width, canvas.height) * 0.5 * Math.min(Math.max(hold, 0), 1),
  );
  const img = ctx.createImageData(canvas.width, canvas.height);
  const data = img.data;
  for (let y = 0; y < canvas.height; y++) {
    for (let x = 0; x < canvas.width; x++) {
      const d = Math.min(x, y, canvas.width - 1 - x, canvas.height - 1 - y);
      const t = band <= 1 ? 1 : smoothstep(0, band, d);
      const c = Math.round(t * 255);
      const i = (y * canvas.width + x) * 4;
      data[i] = c;
      data[i + 1] = c;
      data[i + 2] = c;
      data[i + 3] = 255;
    }
  }
  ctx.putImageData(img, 0, 0);
  return canvas.toDataURL();
}

const Mirage = memo(
  ({
    children,
    mode = "haze",
    intensity = 0.4,
    speed = 0.35,
    scale = 2.2,
    chroma = 0.25,
    trigger = "always",
    edgeHold = 0.35,
    tintColor = "#a855f7",
    paused = false,
    reducedMotion = false,
    className,
  }: MirageProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const noiseRef = useRef<SVGFEImageElement>(null);
    const dispRef = useRef<SVGFEDisplacementMapElement>(null);
    const tintRef = useRef<HTMLDivElement>(null);
    const rawId = useId();
    const filterId = `sg-mirage-${rawId.replace(/[^a-zA-Z0-9_-]/g, "")}`;

    const gathered = useRef(0);
    const pointer = useRef({ x: 0.5, y: 0.5, over: false });
    const box = useRef({ w: 0, h: 0 });

    const [maps, setMaps] = useState({
      noise: "",
      taper: "",
      w: 0,
      h: 0,
      tile: tileFor(scale),
    });
    const tileRef = useRef(maps.tile);

    const live = useRef({ mode, intensity, speed, scale, chroma, trigger, edgeHold, reducedMotion });
    live.current = { mode, intensity, speed, scale, chroma, trigger, edgeHold, reducedMotion };

    const rebuild = useRef<(() => void) | null>(null);
    rebuild.current = () => {
      const { w, h } = box.current;
      if (w < 2 || h < 2) return;
      const l = live.current;
      const tile = tileFor(l.scale);
      tileRef.current = tile;
      setMaps({
        noise: buildNoiseMap(w + tile, h + tile, l.mode, tile),
        taper: buildTaper(w, h, l.edgeHold),
        w,
        h,
        tile,
      });
    };

    const loop = useAnimationLoop({
      target: containerRef,
      halted: paused || reducedMotion,
      onResize: (m: Metrics) => {
        const changed =
          Math.abs(m.width - box.current.w) > 1 ||
          Math.abs(m.height - box.current.h) > 1;
        box.current = { w: m.width, h: m.height };
        if (changed) rebuild.current?.();
      },
      onFrame: ({ elapsed }) => {
        const l = live.current;
        const noise = noiseRef.current;
        const disp = dispRef.current;

        const active = l.trigger === "always" ? 1 : pointer.current.over ? 1 : 0;
        gathered.current += (active - gathered.current) * 0.09;

        if (noise) {
          const tile = tileRef.current;
          const t = elapsed * l.speed;
          const ox = -(((t * 26) % tile) + tile) % tile;
          const oy = -(((t * 17) % tile) + tile) % tile;
          noise.setAttribute("x", ox.toFixed(2));
          noise.setAttribute("y", oy.toFixed(2));
        }
        if (disp) {
          disp.setAttribute(
            "scale",
            (l.intensity * 26 * gathered.current).toFixed(2),
          );
        }

        const tint = tintRef.current;
        if (tint) {
          tint.style.opacity = String(
            Math.min(0.45, l.chroma * 0.45 * gathered.current),
          );
          const p = pointer.current;
          tint.style.background = `radial-gradient(circle at ${(p.x * 100).toFixed(1)}% ${(p.y * 100).toFixed(1)}%, currentColor 0%, transparent 62%)`;
        }
      },
      deps: [],
    });

    useEffect(() => {
      rebuild.current?.();
    }, [mode, scale, edgeHold]);

    useEffect(() => {
      loop.paint();
    }, [intensity, speed, chroma, trigger, tintColor, maps, loop]);

    const track = (e: React.PointerEvent<HTMLDivElement>) => {
      const r = e.currentTarget.getBoundingClientRect();
      if (r.width === 0 || r.height === 0) return;
      pointer.current.x = (e.clientX - r.left) / r.width;
      pointer.current.y = (e.clientY - r.top) / r.height;
      pointer.current.over = true;
      loop.start();
    };
    const release = () => {
      pointer.current.over = false;
      loop.start();
    };

    const ready = maps.noise !== "" && maps.taper !== "";

    return (
      <div
        ref={containerRef}
        className={className ?? "relative"}
        onPointerMove={track}
        onPointerLeave={release}
        onPointerCancel={release}
      >
        <svg aria-hidden className="absolute h-0 w-0" focusable="false">
          <defs>
            <filter
              id={filterId}
              colorInterpolationFilters="sRGB"
              x="0"
              y="0"
              width="100%"
              height="100%"
            >
              {ready ? (
                <>
                  <feImage
                    ref={noiseRef}
                    href={maps.noise}
                    x="0"
                    y="0"
                    width={maps.w + maps.tile}
                    height={maps.h + maps.tile}
                    preserveAspectRatio="none"
                    result="noise"
                  />
                  <feImage
                    href={maps.taper}
                    x="0"
                    y="0"
                    width={maps.w}
                    height={maps.h}
                    preserveAspectRatio="none"
                    result="taper"
                  />
                  <feComposite
                    in="noise"
                    in2="taper"
                    operator="arithmetic"
                    k1="1"
                    k2="0"
                    k3="-0.5"
                    k4="0.5"
                    result="map"
                  />
                  <feDisplacementMap
                    ref={dispRef}
                    in="SourceGraphic"
                    in2="map"
                    scale={0}
                    xChannelSelector="R"
                    yChannelSelector="G"
                  />
                </>
              ) : null}
            </filter>
          </defs>
        </svg>

        <div
          style={{
            filter: ready && !reducedMotion ? `url(#${filterId})` : undefined,
          }}
        >
          {children}
        </div>

        <div
          ref={tintRef}
          aria-hidden
          className="pointer-events-none absolute inset-0"
          style={{ color: tintColor, mixBlendMode: "plus-lighter", opacity: 0 }}
        />
      </div>
    );
  },
);

Mirage.displayName = "Mirage";

export default Mirage;
```

### 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 |
| --- | --- | --- | --- |
| `mode` | `"haze" | "liquify" | "shatter" | "tear"` | `"haze"` | How the air moves. The four differ by the anisotropy of the noise rather than by strength: equal frequencies on both axes give soup, and a strongly biased axis is what makes a tear read as a tear instead of as more haze. |
| `intensity` | `number` | `0.4` | How far the content is pushed. This is genuine per-pixel displacement rather than a transform — a transform can only move the whole box, which is why skew-based heat haze never convinces. Past about one the text stops being readable, which is a legitimate look and a terrible default. Range 0–2. |
| `speed` | `number` | `0.35` | Rate the field drifts. The noise is rasterised once as a seamless tile and scrolled, never re-seeded — stepping a turbulence seed swaps in an entirely unrelated field each time, which reads as a component tearing itself apart rather than as air moving. The wrap at one tile is invisible because the tile is seamless. Range 0–2 ×. |
| `scale` | `number` | `2.2` | Size of the turbulence cells, measured against a scrolling tile rather than against the element — so the same setting is the same air whether the panel is a card or a page. This sizes the tile itself, because a tile can hold no feature larger than its own period and the noise lattice only wraps on a whole number of cells; free the cell count instead and the field stops tiling, which shows up as the whole panel jumping to a different distortion once a wrap. Small cells shred the glyphs and large ones move the whole block as a unit; the interesting band is where a cell is roughly the height of a line of text. Range 0.3–4. |
| `chroma` | `number` | `0.25` | Strength of the colour cast the shimmer carries, gathered where the pointer is. Hot air refracts, so a little colour separation is the cue that sells it as air rather than as a wobbling image. Range 0–1. |
| `trigger` | `"always" | "hover"` | `"always"` | What turns the effect on. Whichever you pick it eases rather than switches — a displacement that snaps on reads as the element being swapped out, one that rises reads as air beginning to move. |
| `edgeHold` | `number` | `0.35` | How much of the element's own silhouette is protected. Displacing evenly moves the border too, so a rounded card dissolves into an amoeba and the one edge a reader uses to locate it is the first thing destroyed. This tapers the push toward neutral near the boundary — at zero the outline shreds, and past about half the shimmer is confined to the middle of the panel. Range 0–1. |
| `tintColor` | `string (hex)` | `"#a855f7"` | The colour the shimmer carries. |

## Usage

```tsx
import Mirage from "@/components/registry/mirage/mirage";

<Mirage
  mode="haze"
  intensity={0.4}
  speed={0.35}
  scale={2.2}
  chroma={0.25}
  trigger="always"
  edgeHold={0.35}
  tintColor="#a855f7"
/>
```

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.
