# Integrate `InfiniteCanvas` from Motion Garden

You are helping me add the **InfiniteCanvas** 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:** InfiniteCanvas
- **Category:** Power-User Systems
- **Summary:** A pannable, zoomable infinite board holding real DOM cards. One world element under a single translate-and-scale, so focus survives and nothing ever remounts when the camera moves. Drag the background to pan with inertia. The wheel zooms to the cursor by holding the world point under it fixed, cards drag independently and glide onto the grid on release, and the corner minimap mirrors the extent and jumps the camera where you click. Camera state lives in one ref written by handlers and the loop, and every consumer, from the world transform to the backdrop plane to the minimap, derives from it in a single write pass per frame, so React never renders a camera frame. Arrow keys pan and plus and minus zoom when the board holds focus.
- **Reference:** https://motion-garden.netlify.app/components/infinite-canvas
- **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 clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme inline {
  --color-surface: var(--sg-surface);
  --color-panel: var(--sg-panel);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-surface: #f9f9fb;
  --sg-panel: #ffffff;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-surface: #0a0b0c;
  --sg-panel: #101215;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

## Files to create

3 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/infinite-canvas/infinite-canvas.tsx`

```tsx
"use client";

import { useEffect, useRef, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { useAnimationLoop } from "@/hooks/use-animation-loop";

export type CanvasBackdrop = "dots" | "lines" | "none";

export interface InfiniteCanvasNode {
  id: string;
  x: number;
  y: number;
  width?: number;
  content: ReactNode;
}

export interface InfiniteCanvasProps {
  nodes?: InfiniteCanvasNode[];
  friction?: number;
  zoomSpeed?: number;
  minZoom?: number;
  maxZoom?: number;
  gridSnap?: boolean;
  gridSize?: number;
  minimap?: boolean;
  backdrop?: CanvasBackdrop;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const DEFAULT_NODES: InfiniteCanvasNode[] = [
  { id: "a", x: 40, y: 60, content: "Drag the background to pan." },
  { id: "b", x: 340, y: 140, content: "Wheel zooms to the cursor." },
  { id: "c", x: 120, y: 320, content: "Cards drag independently." },
];

const MINIMAP_W = 128;
const MINIMAP_H = 88;

const InfiniteCanvas = ({
  nodes = DEFAULT_NODES,
  friction = 0.92,
  zoomSpeed = 1,
  minZoom = 0.25,
  maxZoom = 3,
  gridSnap = true,
  gridSize = 24,
  minimap = true,
  backdrop = "dots",
  paused = false,
  reducedMotion = false,
  className,
}: InfiniteCanvasProps) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const worldRef = useRef<HTMLDivElement | null>(null);
  const viewportRectRef = useRef<HTMLDivElement | null>(null);
  const minimapRef = useRef<HTMLDivElement | null>(null);

  const live = useRef({
    friction,
    zoomSpeed,
    minZoom,
    maxZoom,
    gridSnap,
    gridSize,
    backdrop,
    paused,
    reducedMotion,
  });
  live.current = {
    friction,
    zoomSpeed,
    minZoom,
    maxZoom,
    gridSnap,
    gridSize,
    backdrop,
    paused,
    reducedMotion,
  };

  const cam = useRef({
    x: 24,
    y: 24,
    scale: 1,
    vx: 0,
    vy: 0,
    zoomTarget: 1,
    anchorX: 0,
    anchorY: 0,
    glide: null as { x: number; y: number } | null,
    panning: false,
    lastX: 0,
    lastY: 0,
    lastT: 0,
    pointers: new Map<number, { x: number; y: number }>(),
    pinchDist: 0,
  });

  const positions = useRef(new Map<string, { x: number; y: number }>());
  const dragging = useRef<{
    id: string;
    el: HTMLElement;
    startWX: number;
    startWY: number;
    startPX: number;
    startPY: number;
    snapGlide: boolean;
  } | null>(null);

  const applyRef = useRef<(() => void) | null>(null);
  const drawRef = useRef<((dt: number) => void | false) | null>(null);

  const loop = useAnimationLoop({
    target: containerRef,
    halted: false,
    onResize: () => applyRef.current?.(),
    onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
  });

  useEffect(() => {
    const container = containerRef.current;
    const world = worldRef.current;
    if (!container || !world) return;

    const c = cam.current;
    c.zoomTarget = c.scale;

    const nodeEls = () =>
      Array.from(world.querySelectorAll<HTMLElement>("[data-node]"));

    const worldBounds = () => {
      let minX = 0;
      let minY = 0;
      let maxX = 400;
      let maxY = 300;
      for (const el of nodeEls()) {
        const p = positions.current.get(el.dataset.node ?? "");
        if (!p) continue;
        minX = Math.min(minX, p.x);
        minY = Math.min(minY, p.y);
        maxX = Math.max(maxX, p.x + el.offsetWidth);
        maxY = Math.max(maxY, p.y + el.offsetHeight);
      }
      return { minX: minX - 80, minY: minY - 80, maxX: maxX + 80, maxY: maxY + 80 };
    };

    const apply = () => {
      const L = live.current;
      world.style.transform = `translate(${c.x}px, ${c.y}px) scale(${c.scale})`;

      if (L.backdrop !== "none") {
        const cell = L.gridSize * c.scale;
        container.style.backgroundSize =
          L.backdrop === "dots" ? `${cell}px ${cell}px` : `${cell}px ${cell}px`;
        container.style.backgroundPosition = `${c.x}px ${c.y}px`;
      } else {
        container.style.backgroundSize = "";
        container.style.backgroundPosition = "";
      }

      const mini = minimapRef.current;
      const vp = viewportRectRef.current;
      if (mini && vp) {
        const b = worldBounds();
        const bw = Math.max(b.maxX - b.minX, 1);
        const bh = Math.max(b.maxY - b.minY, 1);
        const k = Math.min(MINIMAP_W / bw, MINIMAP_H / bh);
        for (const el of nodeEls()) {
          const id = el.dataset.node ?? "";
          const p = positions.current.get(id);
          const m = mini.querySelector<HTMLElement>(`[data-mini="${id}"]`);
          if (!p || !m) continue;
          m.style.left = `${(p.x - b.minX) * k}px`;
          m.style.top = `${(p.y - b.minY) * k}px`;
          m.style.width = `${Math.max(el.offsetWidth * k, 3)}px`;
          m.style.height = `${Math.max(el.offsetHeight * k, 2)}px`;
        }
        const rect = container.getBoundingClientRect();
        vp.style.left = `${(-c.x / c.scale - b.minX) * k}px`;
        vp.style.top = `${(-c.y / c.scale - b.minY) * k}px`;
        vp.style.width = `${(rect.width / c.scale) * k}px`;
        vp.style.height = `${(rect.height / c.scale) * k}px`;
      }
    };
    applyRef.current = apply;

    for (const el of nodeEls()) {
      const id = el.dataset.node ?? "";
      if (!positions.current.has(id)) {
        positions.current.set(id, {
          x: parseFloat(el.style.left) || 0,
          y: parseFloat(el.style.top) || 0,
        });
      }
    }
    apply();

    const frame = (dt: number) => {
      const L = live.current;
      const still = L.paused || L.reducedMotion;

      if (!c.panning && (Math.abs(c.vx) > 0.01 || Math.abs(c.vy) > 0.01)) {
        c.x += c.vx * dt;
        c.y += c.vy * dt;
        const decay = still ? 0 : Math.exp(Math.log(Math.max(L.friction, 0.01)) * dt * 60);
        c.vx *= decay;
        c.vy *= decay;
        if (Math.abs(c.vx) < 0.5) c.vx = 0;
        if (Math.abs(c.vy) < 0.5) c.vy = 0;
      }

      if (Math.abs(c.zoomTarget - c.scale) > 0.0005) {
        const next = still
          ? c.zoomTarget
          : c.scale + (c.zoomTarget - c.scale) * Math.min(1, dt * 12);
        const ratio = next / c.scale;
        c.x = c.anchorX - (c.anchorX - c.x) * ratio;
        c.y = c.anchorY - (c.anchorY - c.y) * ratio;
        c.scale = next;
      } else {
        c.scale = c.zoomTarget;
      }

      if (c.glide) {
        const k = still ? 1 : Math.min(1, dt * 10);
        c.x += (c.glide.x - c.x) * k;
        c.y += (c.glide.y - c.y) * k;
        if (Math.abs(c.glide.x - c.x) < 0.5 && Math.abs(c.glide.y - c.y) < 0.5) {
          c.x = c.glide.x;
          c.y = c.glide.y;
          c.glide = null;
        }
      }

      const d = dragging.current;
      if (d?.snapGlide) {
        const p = positions.current.get(d.id);
        if (p) {
          const g = Math.max(L.gridSize, 1);
          const tx = Math.round(p.x / g) * g;
          const ty = Math.round(p.y / g) * g;
          const k = still ? 1 : Math.min(1, dt * 14);
          p.x += (tx - p.x) * k;
          p.y += (ty - p.y) * k;
          d.el.style.left = `${p.x}px`;
          d.el.style.top = `${p.y}px`;
          if (Math.abs(tx - p.x) < 0.5 && Math.abs(ty - p.y) < 0.5) {
            p.x = tx;
            p.y = ty;
            d.el.style.left = `${tx}px`;
            d.el.style.top = `${ty}px`;
            dragging.current = null;
          }
        } else {
          dragging.current = null;
        }
      }

      apply();

      const settled =
        !c.panning &&
        c.vx === 0 &&
        c.vy === 0 &&
        Math.abs(c.zoomTarget - c.scale) <= 0.0005 &&
        !c.glide &&
        !(dragging.current && dragging.current.snapGlide);
      if (settled) {
        world.style.willChange = "";
        return false;
      }
      world.style.willChange = "transform";
    };
    drawRef.current = frame;

    const onPointerDown = (e: PointerEvent) => {
      const target = e.target as HTMLElement;
      c.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
      container.setPointerCapture(e.pointerId);

      if (c.pointers.size === 2) {
        const [p1, p2] = Array.from(c.pointers.values());
        c.pinchDist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
        return;
      }

      const card = target.closest<HTMLElement>("[data-node]");
      if (card && world.contains(card)) {
        const p = positions.current.get(card.dataset.node ?? "");
        if (!p) return;
        dragging.current = {
          id: card.dataset.node ?? "",
          el: card,
          startWX: p.x,
          startWY: p.y,
          startPX: e.clientX,
          startPY: e.clientY,
          snapGlide: false,
        };
        card.style.zIndex = "10";
        return;
      }

      c.panning = true;
      c.glide = null;
      c.vx = 0;
      c.vy = 0;
      c.lastX = e.clientX;
      c.lastY = e.clientY;
      c.lastT = performance.now();
      loop.start();
    };

    const onPointerMove = (e: PointerEvent) => {
      if (c.pointers.has(e.pointerId)) {
        c.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
      }

      if (c.pointers.size === 2) {
        const [p1, p2] = Array.from(c.pointers.values());
        const dist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
        if (c.pinchDist > 0) {
          const L = live.current;
          const rect = container.getBoundingClientRect();
          c.anchorX = (p1.x + p2.x) / 2 - rect.left;
          c.anchorY = (p1.y + p2.y) / 2 - rect.top;
          c.zoomTarget = Math.max(
            L.minZoom,
            Math.min(L.maxZoom, c.zoomTarget * (dist / c.pinchDist)),
          );
        }
        c.pinchDist = dist;
        loop.start();
        return;
      }

      const d = dragging.current;
      if (d && !d.snapGlide) {
        const p = positions.current.get(d.id);
        if (!p) return;
        p.x = d.startWX + (e.clientX - d.startPX) / c.scale;
        p.y = d.startWY + (e.clientY - d.startPY) / c.scale;
        d.el.style.left = `${p.x}px`;
        d.el.style.top = `${p.y}px`;
        applyRef.current?.();
        return;
      }

      if (c.panning) {
        const now = performance.now();
        const dx = e.clientX - c.lastX;
        const dy = e.clientY - c.lastY;
        const dtms = Math.max(now - c.lastT, 1);
        c.x += dx;
        c.y += dy;
        c.vx = (dx / dtms) * 1000;
        c.vy = (dy / dtms) * 1000;
        c.lastX = e.clientX;
        c.lastY = e.clientY;
        c.lastT = now;
        applyRef.current?.();
      }
    };

    const onPointerUp = (e: PointerEvent) => {
      c.pointers.delete(e.pointerId);
      try {
        container.releasePointerCapture(e.pointerId);
      } catch {
      }
      if (c.pointers.size < 2) c.pinchDist = 0;

      const d = dragging.current;
      if (d && !d.snapGlide) {
        d.el.style.zIndex = "";
        if (live.current.gridSnap) {
          d.snapGlide = true;
          loop.start();
        } else {
          dragging.current = null;
        }
        return;
      }

      if (c.panning) {
        c.panning = false;
        if (performance.now() - c.lastT > 90) {
          c.vx = 0;
          c.vy = 0;
        }
        loop.start();
      }
    };

    const onWheel = (e: WheelEvent) => {
      e.preventDefault();
      const L = live.current;
      const rect = container.getBoundingClientRect();
      c.anchorX = e.clientX - rect.left;
      c.anchorY = e.clientY - rect.top;
      const factor = Math.exp(-e.deltaY * 0.0012 * L.zoomSpeed);
      c.zoomTarget = Math.max(L.minZoom, Math.min(L.maxZoom, c.zoomTarget * factor));
      loop.start();
    };

    const onKeyDown = (e: KeyboardEvent) => {
      const L = live.current;
      const rect = container.getBoundingClientRect();
      const step = 48;
      let handled = true;
      if (e.key === "ArrowLeft") c.x += step;
      else if (e.key === "ArrowRight") c.x -= step;
      else if (e.key === "ArrowUp") c.y += step;
      else if (e.key === "ArrowDown") c.y -= step;
      else if (e.key === "+" || e.key === "=") {
        c.anchorX = rect.width / 2;
        c.anchorY = rect.height / 2;
        c.zoomTarget = Math.min(L.maxZoom, c.zoomTarget * 1.2);
      } else if (e.key === "-" || e.key === "_") {
        c.anchorX = rect.width / 2;
        c.anchorY = rect.height / 2;
        c.zoomTarget = Math.max(L.minZoom, c.zoomTarget / 1.2);
      } else handled = false;
      if (handled) {
        e.preventDefault();
        loop.start();
      }
    };

    const onMinimapDown = (e: PointerEvent) => {
      const mini = minimapRef.current;
      if (!mini) return;
      e.stopPropagation();
      const rect = container.getBoundingClientRect();
      const mrect = mini.getBoundingClientRect();
      const b = worldBounds();
      const bw = Math.max(b.maxX - b.minX, 1);
      const bh = Math.max(b.maxY - b.minY, 1);
      const k = Math.min(MINIMAP_W / bw, MINIMAP_H / bh);
      const wx = (e.clientX - mrect.left) / k + b.minX;
      const wy = (e.clientY - mrect.top) / k + b.minY;
      cam.current.glide = {
        x: rect.width / 2 - wx * c.scale,
        y: rect.height / 2 - wy * c.scale,
      };
      loop.start();
    };

    container.addEventListener("pointerdown", onPointerDown);
    container.addEventListener("pointermove", onPointerMove);
    container.addEventListener("pointerup", onPointerUp);
    container.addEventListener("pointercancel", onPointerUp);
    container.addEventListener("wheel", onWheel, { passive: false });
    container.addEventListener("keydown", onKeyDown);
    const mini = minimapRef.current;
    mini?.addEventListener("pointerdown", onMinimapDown);

    loop.start();

    return () => {
      drawRef.current = null;
      applyRef.current = null;
      container.removeEventListener("pointerdown", onPointerDown);
      container.removeEventListener("pointermove", onPointerMove);
      container.removeEventListener("pointerup", onPointerUp);
      container.removeEventListener("pointercancel", onPointerUp);
      container.removeEventListener("wheel", onWheel);
      container.removeEventListener("keydown", onKeyDown);
      mini?.removeEventListener("pointerdown", onMinimapDown);
      world.style.willChange = "";
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [nodes]);

  useEffect(() => {
    applyRef.current?.();
  }, [backdrop, gridSize, minimap]);

  const backdropStyle: React.CSSProperties =
    backdrop === "dots"
      ? {
          backgroundImage:
            "radial-gradient(color-mix(in oklab, var(--sg-ink) 18%, transparent) 1px, transparent 1px)",
        }
      : backdrop === "lines"
        ? {
            backgroundImage:
              "linear-gradient(color-mix(in oklab, var(--sg-ink) 9%, transparent) 1px, transparent 1px), linear-gradient(90deg, color-mix(in oklab, var(--sg-ink) 9%, transparent) 1px, transparent 1px)",
          }
        : {};

  return (
    <div
      ref={containerRef}
      role="application"
      aria-label="Pannable canvas. Arrow keys pan, plus and minus zoom."
      tabIndex={0}
      className={cn(
        "relative h-full w-full touch-none select-none overflow-hidden bg-surface",
        "cursor-grab focus-visible:outline-2 focus-visible:outline-accent active:cursor-grabbing",
        className,
      )}
      style={backdropStyle}
    >
      <div ref={worldRef} className="absolute left-0 top-0 origin-top-left">
        {nodes.map((node) => (
          <div
            key={node.id}
            data-node={node.id}
            className="absolute touch-none rounded-lg border border-hairline bg-panel p-3 text-xs leading-relaxed text-ink shadow-lg"
            style={{
              left: node.x,
              top: node.y,
              width: node.width ?? 200,
              cursor: "grab",
            }}
          >
            {node.content}
          </div>
        ))}
      </div>

      {minimap && (
        <div
          ref={minimapRef}
          className="absolute bottom-3 right-3 overflow-hidden rounded-md border border-hairline bg-panel/80 backdrop-blur-sm"
          style={{ width: MINIMAP_W, height: MINIMAP_H }}
        >
          {nodes.map((node) => (
            <div
              key={node.id}
              data-mini={node.id}
              className="absolute rounded-[2px] bg-ink-mute/60"
            />
          ))}
          <div
            ref={viewportRectRef}
            className="absolute rounded-sm border border-accent/80"
          />
        </div>
      )}
    </div>
  );
};

export default InfiniteCanvas;
```

### 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],
  );
}
```

### 3. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `friction` | `number` | `0.92` | Glide decay after a thrown pan — low stops dead, high coasts. Range 0.8–0.99. |
| `zoomSpeed` | `number` | `1` | Wheel-to-zoom gearing. Range 0.2–3 ×. |
| `minZoom` | `number` | `0.25` | How far out the camera may pull. Range 0.05–1 ×. |
| `maxZoom` | `number` | `3` | How far in the camera may push. Range 1–8 ×. |
| `gridSnap` | `boolean` | `true` | Dropped cards glide onto the nearest grid point. |
| `gridSize` | `number` | `24` | World-space grid pitch — the snap target and the backdrop's cell size both. Range 8–64 px. |
| `minimap` | `boolean` | `true` | Corner map of the extent; click it to jump the camera. |
| `backdrop` | `"dots" | "lines" | "none"` | `"dots"` | The plane texture that moves with the camera — it is what makes the pan legible. |

## Usage

```tsx
import InfiniteCanvas from "@/components/registry/infinite-canvas/infinite-canvas";

<InfiniteCanvas
  friction={0.92}
  zoomSpeed={1}
  minZoom={0.25}
  maxZoom={3}
  gridSnap={true}
  gridSize={24}
  minimap={true}
  backdrop="dots"
/>
```

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`.
- The `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- 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.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.
- 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. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. 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.
