# Integrate `Rotunda` from Motion Garden

You are helping me add the **Rotunda** 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:** Rotunda
- **Category:** Power-User Systems
- **Summary:** Real HTML panels on a drag-spun 3D cylinder. A hand-rolled perspective projection written onto DOM elements rather than a canvas, so the text stays selectable, the links stay clickable, and a screen reader still reads every panel while the ring turns.
- **Reference:** https://motion-garden.netlify.app/components/rotunda
- **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
# Rotunda 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/rotunda/rotunda.tsx`

```tsx
"use client";

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

export interface RotundaProps {
  children?: ReactNode;
  radius?: number;
  perspective?: number;
  autoSpin?: number;
  friction?: number;
  snap?: boolean;
  snapStiffness?: number;
  depthDim?: number;
  depthBlur?: number;
  faceCamera?: boolean;
  dragSensitivity?: number;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const SETTLE_SPEED = 24;

const DRAG_THRESHOLD = 5;

const Rotunda = memo(
  ({
    children,
    radius = 380,
    perspective = 1200,
    autoSpin = 0.06,
    friction = 0.94,
    snap = true,
    snapStiffness = 140,
    depthDim = 0.65,
    depthBlur = 3,
    faceCamera = false,
    dragSensitivity = 0.35,
    paused = false,
    reducedMotion = false,
    className,
  }: RotundaProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const panelsRef = useRef<(HTMLDivElement | null)[]>([]);
    const innersRef = useRef<(HTMLDivElement | null)[]>([]);

    const items = Array.isArray(children) ? children : [children];
    const count = Math.max(items.length, 1);

    const motion = useRef({
      angle: 0,
      velocity: 0,
      pending: false,
      dragging: false,
      moved: false,
      hovering: false,
      pointerId: -1,
      downX: 0,
      grabX: 0,
      grabAngle: 0,
      lastX: 0,
      lastT: 0,
    });

    const live = useRef({
      radius, perspective, autoSpin, friction, snap, snapStiffness,
      depthDim, depthBlur, faceCamera, dragSensitivity, count, reducedMotion,
    });
    live.current = {
      radius, perspective, autoSpin, friction, snap, snapStiffness,
      depthDim, depthBlur, faceCamera, dragSensitivity, count, reducedMotion,
    };

    const apply = useRef<(() => void) | null>(null);

    const loop = useAnimationLoop({
      target: containerRef,
      halted: paused,
      onFrame: ({ dt }) => {
        const l = live.current;
        const m = motion.current;
        const step = 360 / l.count;

        if (!m.dragging) {
          if (!l.reducedMotion && !m.hovering && Math.abs(m.velocity) < SETTLE_SPEED) {
            m.angle += l.autoSpin * 18 * dt;
          }
          const settling = l.snap && Math.abs(m.velocity) < SETTLE_SPEED;
          if (settling) {
            const target = Math.round(m.angle / step) * step;
            const damping = 2 * Math.sqrt(l.snapStiffness);
            const accel =
              -l.snapStiffness * (m.angle - target) - damping * m.velocity;
            m.velocity += accel * dt;
            m.angle += m.velocity * dt;
          } else {
            m.angle += m.velocity * dt;
            m.velocity *= Math.pow(l.friction, dt * 60);
          }
        }

        apply.current?.();
      },
      deps: [],
    });

    useEffect(() => {
      apply.current = () => {
        const l = live.current;
        const m = motion.current;
        const step = 360 / l.count;

        for (let i = 0; i < l.count; i++) {
          const panel = panelsRef.current[i];
          if (!panel) continue;
          const theta = i * step + m.angle;
          const rad = (theta * Math.PI) / 180;
          const front = (Math.cos(rad) + 1) * 0.5;

          panel.style.transform = l.faceCamera
            ? `translate(-50%, -50%) rotateY(${theta}deg) translateZ(${l.radius}px) rotateY(${-theta}deg)`
            : `translate(-50%, -50%) rotateY(${theta}deg) translateZ(${l.radius}px)`;
          panel.style.zIndex = String(Math.round(front * 100));
          panel.style.opacity = String(1 - l.depthDim * (1 - front));
          panel.style.pointerEvents = front > 0.5 ? "auto" : "none";

          const inner = innersRef.current[i];
          if (inner) {
            const blur = l.depthBlur * (1 - front);
            inner.style.filter = blur > 0.05 ? `blur(${blur.toFixed(2)}px)` : "none";
          }
        }
      };
      apply.current();
      loop.paint();
      return () => {
        apply.current = null;
      };
    }, [loop]);

    useEffect(() => {
      apply.current?.();
      loop.paint();
    }, [
      radius, perspective, autoSpin, friction, snap, snapStiffness,
      depthDim, depthBlur, faceCamera, dragSensitivity, count, loop,
    ]);

    const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
      if (e.button !== 0) return;
      const m = motion.current;
      m.pending = true;
      m.dragging = false;
      m.moved = false;
      m.hovering = true;
      m.pointerId = e.pointerId;
      m.downX = e.clientX;
      m.grabX = e.clientX;
      m.grabAngle = m.angle;
      m.lastX = e.clientX;
      m.lastT = e.timeStamp;
      m.velocity = 0;
      window.getSelection()?.removeAllRanges();
      loop.start();
    };

    const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
      const m = motion.current;
      m.hovering = true;
      if (e.pointerId !== m.pointerId) return;

      if (m.pending && !m.dragging) {
        if (Math.abs(e.clientX - m.downX) < DRAG_THRESHOLD) return;
        m.dragging = true;
        m.moved = true;
        m.grabX = e.clientX;
        m.grabAngle = m.angle;
        m.lastX = e.clientX;
        m.lastT = e.timeStamp;
        e.currentTarget.setPointerCapture(e.pointerId);
        containerRef.current?.style.setProperty("user-select", "none");
        window.getSelection()?.removeAllRanges();
      }
      if (!m.dragging) return;

      const l = live.current;
      m.angle = m.grabAngle + (e.clientX - m.grabX) * l.dragSensitivity;

      const dt = (e.timeStamp - m.lastT) / 1000;
      if (dt > 0.001) {
        m.velocity = ((e.clientX - m.lastX) * l.dragSensitivity) / dt;
        m.lastX = e.clientX;
        m.lastT = e.timeStamp;
      }
      loop.start();
    };

    const endDrag = (e: React.PointerEvent<HTMLDivElement>) => {
      const m = motion.current;
      if (m.pointerId !== -1 && e.currentTarget.hasPointerCapture(m.pointerId)) {
        e.currentTarget.releasePointerCapture(m.pointerId);
      }
      m.pending = false;
      m.dragging = false;
      m.pointerId = -1;
      containerRef.current?.style.removeProperty("user-select");
      loop.start();
    };

    const onClickCapture = (e: React.MouseEvent<HTMLDivElement>) => {
      const m = motion.current;
      if (!m.moved) return;
      m.moved = false;
      e.preventDefault();
      e.stopPropagation();
    };

    const onPointerLeave = () => {
      motion.current.hovering = false;
      loop.start();
    };

    const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
      const step = 360 / live.current.count;
      if (e.key === "ArrowRight") {
        motion.current.angle -= step;
      } else if (e.key === "ArrowLeft") {
        motion.current.angle += step;
      } else if (e.key === "Home") {
        motion.current.angle = 0;
      } else {
        return;
      }
      e.preventDefault();
      motion.current.velocity = 0;
      loop.start();
    };

    return (
      <div
        ref={containerRef}
        className={
          className ??
          "relative h-full w-full touch-none overflow-hidden outline-none"
        }
        style={{ perspective: `${perspective}px` }}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={endDrag}
        onPointerCancel={endDrag}
        onPointerLeave={onPointerLeave}
        onClickCapture={onClickCapture}
        onKeyDown={onKeyDown}
        tabIndex={0}
        role="group"
        aria-label="Rotating panel carousel. Use the left and right arrow keys."
      >
        <div
          className="absolute inset-0"
          style={{ transformStyle: "preserve-3d" }}
        >
          {items.map((child, i) => (
            <div
              key={i}
              ref={(el) => {
                panelsRef.current[i] = el;
              }}
              className="absolute top-1/2 left-1/2"
              style={{ transformStyle: "preserve-3d" }}
            >
              <div
                ref={(el) => {
                  innersRef.current[i] = el;
                }}
              >
                {child}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  },
);

Rotunda.displayName = "Rotunda";

export default Rotunda;
```

### 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 |
| --- | --- | --- | --- |
| `radius` | `number` | `380` | Distance from the axis to each panel face. Together with the number of panels this decides whether the ring closes: too small for the count and the faces intersect, which is the one way this arrangement can look broken rather than tight. Range 160–900 px. |
| `perspective` | `number` | `1200` | Depth of the projection, and the control that decides whether this reads as expensive or as a cheap paper fan. Near enough and the front panel distorts violently; far enough and the ring flattens into a row of cards. Range 400–3000 px. |
| `autoSpin` | `number` | `0.06` | Idle rotation while nothing is being dragged. It stops the instant the pointer arrives and does not restart until it leaves, because a carousel that keeps moving under your cursor is a carousel you cannot read. Range 0–1 ×. |
| `friction` | `number` | `0.94` | How much of a fling survives, and the whole feel of the throw. Applied per second rather than per frame, so the same gesture coasts the same distance on a 60Hz and a 120Hz display — the naive per-frame form silently halves the throw on better hardware. Range 0.8–0.995. |
| `snap` | `boolean` | `true` | Settle to the nearest panel once a fling drops below walking pace. Off, the ring stops wherever it stops — honest for a texture, wrong for a menu. |
| `snapStiffness` | `number` | `140` | How hard the ring is pulled to the nearest face. Damping is derived from it at the critical ratio, so raising this arrives faster without ever adding the overshoot that would read as a wobble on a menu. Range 20–400. Ignored while `snap` is `false`. |
| `depthDim` | `number` | `0.65` | How far the back of the ring dims toward the background. Depth cueing sells the illusion harder than the rotation does, because a CSS transform gives you no occlusion to work with. Range 0–1. |
| `depthBlur` | `number` | `3` | Blur on panels past the halfway point. Applied to an inner wrapper rather than the panel itself: a filter on a child of a preserve-3d parent establishes a containing block and flattens the entire ring into a stack. Range 0–10 px. |
| `faceCamera` | `boolean` | `false` | Keep every panel square to the viewer rather than tangent to the ring. This turns the carousel into a card rack, and it is the right choice the moment the panels carry real copy you expect anyone to read off-centre. |
| `dragSensitivity` | `number` | `0.35` | Degrees of rotation per pixel of drag. The honest test is whether the panel under your finger stays under your finger — too low and the ring feels geared down, too high and a small gesture spins it past the panel you were reaching for. Range 0.05–1.5 °/px. |

## Usage

```tsx
import Rotunda from "@/components/registry/rotunda/rotunda";

<Rotunda
  radius={380}
  perspective={1200}
  autoSpin={0.06}
  friction={0.94}
  snap={true}
  snapStiffness={140}
  depthDim={0.65}
  depthBlur={3}
  faceCamera={false}
  dragSensitivity={0.35}
/>
```

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 `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.
- 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.
