# Integrate `Anaglyph` from Motion Garden

You are helping me add the **Anaglyph** 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:** Anaglyph
- **Category:** Text Animations
- **Summary:** Stereoscopic channel-split type. The real headline stays put, selectable, one announcement to a screen reader, while two aria-hidden copies in opposing ink colors slide against each other under the pointer, and the blend mode resolves their overlap back toward white, so the depth lives entirely in the fringes, exactly as it does on a printed anaglyph. The channels chase the cursor through an exponential lerp written straight to transform, and once the pointer goes quiet a slow bounded-phase sway takes the target over so the split keeps breathing on an idle pane.
- **Reference:** https://motion-garden.netlify.app/components/anaglyph
- **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
# Anaglyph 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/anaglyph/anaglyph.tsx`

```tsx
"use client";

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

export type AnaglyphLayers = "two" | "three";
export type AnaglyphBlend = "screen" | "lighten" | "difference";

export interface AnaglyphProps {
  text?: string;
  maxShift?: number;
  response?: number;
  lag?: number;
  sway?: number;
  layers?: AnaglyphLayers;
  blend?: AnaglyphBlend;
  channelA?: string;
  channelB?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const IDLE_AFTER = 1.5;
const TAU = Math.PI * 2;

const Anaglyph = ({
  text = "Anaglyph",
  maxShift = 14,
  response = 1,
  lag = 0.18,
  sway = 0.5,
  layers = "three",
  blend = "screen",
  channelA = "#c4b5fd",
  channelB = "#67e8f9",
  paused = false,
  reducedMotion = false,
  className = "",
}: AnaglyphProps) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const aRef = useRef<HTMLSpanElement | null>(null);
  const bRef = useRef<HTMLSpanElement | null>(null);
  const cRef = useRef<HTMLSpanElement | null>(null);

  const live = useRef({ maxShift, response, lag, sway, paused, reducedMotion });
  live.current = { maxShift, response, lag, sway, paused, reducedMotion };

  const state = useRef({
    tx: 0,
    ty: 0,
    x: 0,
    y: 0,
    time: 0,
    lastInput: -IDLE_AFTER,
    swayPhase: 0,
  });

  const loop = useAnimationLoop({
    target: containerRef,
    halted: paused || reducedMotion,
    onFrame: ({ dt }) => {
      const s = state.current;
      const cfg = live.current;
      const a = aRef.current;
      const b = bRef.current;
      const c = cRef.current;
      if (!a || !b) return;

      if (cfg.reducedMotion) {
        const off = cfg.maxShift * 0.4;
        a.style.transform = `translate3d(${off}px, ${-off * 0.6}px, 0)`;
        b.style.transform = `translate3d(${-off}px, ${off * 0.6}px, 0)`;
        if (c) c.style.transform = `translate3d(${off * 0.3}px, ${off * 0.5}px, 0)`;
        return;
      }

      s.time += dt;

      let tx = s.tx;
      let ty = s.ty;
      if (s.time - s.lastInput > IDLE_AFTER) {
        s.swayPhase = (s.swayPhase + dt * 0.55) % TAU;
        tx = Math.cos(s.swayPhase) * 0.5 * cfg.sway;
        ty = Math.sin(s.swayPhase * 2) * 0.35 * cfg.sway;
      }

      const k = 1 - Math.exp(-dt / Math.max(cfg.lag, 0.01));
      s.x += (tx - s.x) * k;
      s.y += (ty - s.y) * k;

      const ox = s.x * cfg.maxShift;
      const oy = s.y * cfg.maxShift;
      a.style.transform = `translate3d(${ox}px, ${oy}px, 0)`;
      b.style.transform = `translate3d(${-ox}px, ${-oy}px, 0)`;
      if (c) c.style.transform = `translate3d(${-oy * 0.5}px, ${ox * 0.5}px, 0)`;
    },
  });

  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
    const el = containerRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    if (rect.width <= 0 || rect.height <= 0) return;
    const s = state.current;
    const cfg = live.current;
    s.tx = Math.max(-1, Math.min(1, ((e.clientX - rect.left) / rect.width - 0.5) * 2)) * cfg.response;
    s.ty = Math.max(-1, Math.min(1, ((e.clientY - rect.top) / rect.height - 0.5) * 2)) * cfg.response;
    s.lastInput = s.time;
  };

  const onPointerLeave = () => {
    const s = state.current;
    s.tx = 0;
    s.ty = 0;
  };

  useEffect(() => {
    loop.paint();
  }, [maxShift, response, lag, sway, layers, blend, channelA, channelB, loop]);

  const channel = (
    ref: React.RefObject<HTMLSpanElement | null>,
    color: string,
    opacity = 1,
  ) => (
    <span
      ref={ref}
      aria-hidden="true"
      className="pointer-events-none absolute inset-0 will-change-transform"
      style={{ color, opacity, mixBlendMode: blend }}
    >
      {text}
    </span>
  );

  return (
    <div
      ref={containerRef}
      className={`relative inline-block ${className}`.trim()}
      onPointerMove={onPointerMove}
      onPointerLeave={onPointerLeave}
      onPointerCancel={onPointerLeave}
    >
      <span className="relative">{text}</span>
      {channel(aRef, channelA)}
      {channel(bRef, channelB)}
      {layers === "three" && channel(cRef, channelB, 0.45)}
    </div>
  );
};

export default Anaglyph;
```

### 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 |
| --- | --- | --- | --- |
| `maxShift` | `number` | `14` | Peak channel separation at the pane edge. Range 0–40 px. |
| `response` | `number` | `1` | How much pointer travel converts into separation. Range 0.2–3 ×. |
| `lag` | `number` | `0.18` | Chase time constant — the channels arrive after the cursor. Range 0.02–0.6 s. |
| `sway` | `number` | `0.5` | Idle drift amplitude once the pointer has gone quiet. Range 0–1. |
| `layers` | `"two" | "three"` | `"three"` | Two channels split on one axis; three adds a perpendicular half-shift ghost. |
| `blend` | `"screen" | "lighten" | "difference"` | `"screen"` | How the channels composite where they overlap. |
| `channelA` | `string (hex)` | `"#c4b5fd"` | First offset layer. |
| `channelB` | `string (hex)` | `"#67e8f9"` | Opposing offset layer. |

## Usage

```tsx
import Anaglyph from "@/components/registry/anaglyph/anaglyph";

<Anaglyph
  maxShift={14}
  response={1}
  lag={0.18}
  sway={0.5}
  layers="three"
  blend="screen"
  channelA="#c4b5fd"
  channelB="#67e8f9"
/>
```

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.
