# Integrate `Lissajous` from Motion Garden

You are helping me add the **Lissajous** 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:** Lissajous
- **Category:** Backgrounds
- **Summary:** A phosphor oscilloscope tracing Lissajous figures. The beam dwells on one frequency ratio, then retunes to the next by sliding both frequencies continuously, and the chirp while the figure comes apart and re-locks is the same thing you see turning a real scope's timebase knob. Persistence is data, not paint. Instead of the classic translucent-fill fade, which never fully clears and cannot survive a paused repaint, the beam keeps a ring buffer of recent samples and redraws the whole trail from scratch each frame, so the phosphor hold re-grades live when you tune it and a still frame reproduces the exact screen.
- **Reference:** https://motion-garden.netlify.app/components/lissajous
- **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
# Lissajous 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/lissajous/lissajous.tsx`

```tsx
"use client";

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

export interface LissajousProps {
  speed?: number;
  persistence?: number;
  dwell?: number;
  morphSeconds?: number;
  beamWidth?: number;
  glow?: number;
  showGraticule?: boolean;
  phosphorColor?: string;
  backgroundColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const RATIOS: Array<[number, number]> = [
  [3, 2],
  [5, 4],
  [1, 1],
  [3, 4],
  [7, 5],
  [2, 3],
];

const CAPACITY = 2048;
const TAU = Math.PI * 2;

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

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 Lissajous = ({
  speed = 1,
  persistence = 0.6,
  dwell = 4,
  morphSeconds = 1.4,
  beamWidth = 1.6,
  glow = 12,
  showGraticule = true,
  phosphorColor = "#c4b5fd",
  backgroundColor = "#0b0812",
  paused = false,
  reducedMotion = false,
  className = "",
}: LissajousProps) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  const live = useRef({
    speed,
    persistence,
    dwell,
    morphSeconds,
    beamWidth,
    glow,
    showGraticule,
    phosphorColor,
    backgroundColor,
    paused,
    reducedMotion,
  });
  live.current = {
    speed,
    persistence,
    dwell,
    morphSeconds,
    beamWidth,
    glow,
    showGraticule,
    phosphorColor,
    backgroundColor,
    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",
    resizeDebounceMs: 100,
    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;

    let width = 0;
    let height = 0;

    const xs = new Float32Array(CAPACITY);
    const ys = new Float32Array(CAPACITY);
    const ts = new Float32Array(CAPACITY);
    let head = 0;
    let count = 0;

    const tuner = {
      index: 0,
      a: RATIOS[0][0],
      b: RATIOS[0][1],
      px: 0,
      py: 0,
      dwellLeft: 4,
      morphT: -1,
      fromA: RATIOS[0][0],
      fromB: RATIOS[0][1],
      time: 0,
    };

    measureRef.current = ({ width: w, height: h, dpr, bufferWidth, bufferHeight }) => {
      if (w <= 0 || h <= 0) return;
      canvas.width = bufferWidth;
      canvas.height = bufferHeight;
      canvas.style.width = `${w}px`;
      canvas.style.height = `${h}px`;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      width = w;
      height = h;
    };

    const point = (out: { x: number; y: number }, px: number, py: number) => {
      out.x = width / 2 + Math.cos(px) * width * 0.39;
      out.y = height / 2 + Math.sin(py) * height * 0.36;
    };
    const pt = { x: 0, y: 0 };

    const drawGraticule = (r: number, g: number, b: number) => {
      const cols = 10;
      const rows = 8;
      ctx.lineWidth = 1;
      ctx.strokeStyle = `rgba(${r},${g},${b},0.06)`;
      ctx.beginPath();
      for (let i = 1; i < cols; i++) {
        const x = (i / cols) * width;
        ctx.moveTo(x, 0);
        ctx.lineTo(x, height);
      }
      for (let j = 1; j < rows; j++) {
        const y = (j / rows) * height;
        ctx.moveTo(0, y);
        ctx.lineTo(width, y);
      }
      ctx.stroke();
      ctx.strokeStyle = `rgba(${r},${g},${b},0.13)`;
      ctx.beginPath();
      ctx.moveTo(width / 2, 0);
      ctx.lineTo(width / 2, height);
      ctx.moveTo(0, height / 2);
      ctx.lineTo(width, height / 2);
      ctx.stroke();
    };

    const drawStill = () => {
      const cfg = live.current;
      const [r, g, b] = hexToRgb(cfg.phosphorColor);
      ctx.fillStyle = cfg.backgroundColor;
      ctx.fillRect(0, 0, width, height);
      if (cfg.showGraticule) drawGraticule(r, g, b);
      ctx.lineWidth = cfg.beamWidth;
      ctx.strokeStyle = `rgba(${r},${g},${b},0.9)`;
      ctx.shadowColor = `rgba(${r},${g},${b},0.8)`;
      ctx.shadowBlur = cfg.glow * 0.6;
      ctx.beginPath();
      for (let i = 0; i <= 720; i++) {
        const phi = (i / 720) * TAU;
        pt.x = width / 2 + Math.cos(tuner.a * phi) * width * 0.39;
        pt.y = height / 2 + Math.sin(tuner.b * phi) * height * 0.36;
        if (i === 0) ctx.moveTo(pt.x, pt.y);
        else ctx.lineTo(pt.x, pt.y);
      }
      ctx.stroke();
      ctx.shadowBlur = 0;
    };

    const draw = (dt: number): void | false => {
      if (width <= 0 || height <= 0) return;
      const cfg = live.current;

      if (cfg.reducedMotion) {
        drawStill();
        return;
      }

      if (dt > 0) {
        tuner.time += dt;
        if (tuner.morphT < 0) {
          tuner.dwellLeft -= dt;
          if (tuner.dwellLeft <= 0) {
            tuner.fromA = tuner.a;
            tuner.fromB = tuner.b;
            tuner.index = (tuner.index + 1) % RATIOS.length;
            tuner.morphT = 0;
          }
        } else {
          tuner.morphT += dt / Math.max(cfg.morphSeconds, 0.05);
          const e = easeInOut(Math.min(tuner.morphT, 1));
          tuner.a = tuner.fromA + (RATIOS[tuner.index][0] - tuner.fromA) * e;
          tuner.b = tuner.fromB + (RATIOS[tuner.index][1] - tuner.fromB) * e;
          if (tuner.morphT >= 1) {
            tuner.morphT = -1;
            tuner.dwellLeft = cfg.dwell;
          }
        }

        const rate = cfg.speed * 2.2;
        const maxAB = Math.max(tuner.a, tuner.b, 1);
        const total = dt * rate;
        const steps = Math.min(360, Math.max(1, Math.ceil((total * maxAB) / 0.045)));
        const dphi = total / steps;
        for (let s = 0; s < steps; s++) {
          tuner.px = (tuner.px + tuner.a * dphi) % TAU;
          tuner.py = (tuner.py + tuner.b * dphi) % TAU;
          point(pt, tuner.px, tuner.py);
          xs[head] = pt.x;
          ys[head] = pt.y;
          ts[head] = tuner.time;
          head = (head + 1) % CAPACITY;
          if (count < CAPACITY) count++;
        }
      }

      const [r, g, b] = hexToRgb(cfg.phosphorColor);
      ctx.fillStyle = cfg.backgroundColor;
      ctx.fillRect(0, 0, width, height);
      if (cfg.showGraticule) drawGraticule(r, g, b);

      const life = 0.25 + cfg.persistence * 2.75;
      while (count > 0) {
        const tail = (head - count + CAPACITY) % CAPACITY;
        if (tuner.time - ts[tail] <= life) break;
        count--;
      }

      if (count > 1) {
        ctx.lineWidth = cfg.beamWidth;
        ctx.lineJoin = "round";
        ctx.lineCap = "round";
        const BUCKETS = 14;
        let bucket = -1;
        let started = false;
        for (let i = count - 1; i >= 0; i--) {
          const idx = (head - 1 - i + CAPACITY * 2) % CAPACITY;
          const ageFrac = Math.min((tuner.time - ts[idx]) / life, 1);
          const bk = Math.min(BUCKETS - 1, Math.floor(ageFrac * BUCKETS));
          if (bk !== bucket) {
            if (started) ctx.stroke();
            const fade = 1 - (bk + 0.5) / BUCKETS;
            const alpha = fade * fade * 0.9;
            ctx.strokeStyle = `rgba(${r},${g},${b},${alpha.toFixed(3)})`;
            if (bk === 0) {
              ctx.shadowColor = `rgba(${r},${g},${b},0.85)`;
              ctx.shadowBlur = cfg.glow;
            } else {
              ctx.shadowBlur = 0;
            }
            ctx.beginPath();
            ctx.moveTo(xs[idx], ys[idx]);
            bucket = bk;
            started = true;
          } else {
            ctx.lineTo(xs[idx], ys[idx]);
          }
        }
        if (started) ctx.stroke();
        ctx.shadowBlur = 0;

        const headIdx = (head - 1 + CAPACITY) % CAPACITY;
        ctx.fillStyle = `rgba(255,255,255,0.9)`;
        ctx.shadowColor = `rgba(${r},${g},${b},1)`;
        ctx.shadowBlur = cfg.glow * 1.4;
        ctx.beginPath();
        ctx.arc(xs[headIdx], ys[headIdx], Math.max(cfg.beamWidth * 0.9, 1.2), 0, TAU);
        ctx.fill();
        ctx.shadowBlur = 0;
      }
    };
    drawRef.current = draw;

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

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

  useEffect(() => {
    loop.paint();
  }, [
    speed,
    persistence,
    dwell,
    morphSeconds,
    beamWidth,
    glow,
    showGraticule,
    phosphorColor,
    backgroundColor,
    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 Lissajous;
```

### 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 |
| --- | --- | --- | --- |
| `speed` | `number` | `1` | Beam speed along the curve. Range 0.1–3 ×. |
| `persistence` | `number` | `0.6` | Phosphor hold — how long the trail stays lit behind the beam. Range 0.05–0.98. |
| `dwell` | `number` | `4` | Seconds a figure holds before tuning to the next ratio. Range 1–10 s. |
| `morphSeconds` | `number` | `1.4` | Length of the chirp between one ratio and the next. Range 0.3–4 s. |
| `beamWidth` | `number` | `1.6` | Trace stroke width. Range 0.5–4 px. |
| `glow` | `number` | `12` | Bloom on the beam head. Range 0–30 px. |
| `showGraticule` | `boolean` | `true` | Faint scope grid behind the trace. |
| `phosphorColor` | `string (hex)` | `"#c4b5fd"` | The phosphor — amethyst, not heritage green. |
| `backgroundColor` | `string (hex)` | `"#0b0812"` | Dead glass behind the trace. |

## Usage

```tsx
import Lissajous from "@/components/registry/lissajous/lissajous";

<Lissajous
  speed={1}
  persistence={0.6}
  dwell={4}
  morphSeconds={1.4}
  beamWidth={1.6}
  glow={12}
  showGraticule={true}
  phosphorColor="#c4b5fd"
  backgroundColor="#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.
