# Nautilus: Spiral Image Carousel for React

> A carousel laid out as a spiral, like the chambers of a shell: the front card is the current slide, and each card behind it is a little smaller, winding inward to a tiny tail. Every few seconds the trail moves one slot. The front card moves first and the rest follow a beat apart, so the step runs down the trail like a whip; the old front card dives out past the corner and a new one grows out of the tail. Click any card to wind it to the front, or drag sideways to turn the whole spiral by hand.

Spiral Image Carousel for React: slides ride a spiral and each step ripples down the trail. Built with Tailwind CSS; install it with the shadcn CLI. It's a KeyframeUI component: the file lands in your project as source, yours to edit.

- Docs and live preview: https://keyframeui.com/components/nautilus
- Tags: Gallery, Carousel, Motion
- npm dependencies: clsx, tailwind-merge

## Installation

Register the @keyframeui registry in `components.json` once per project:

```json
{
  "registries": {
    "@keyframeui": "https://keyframeui.com/r/{name}.json"
  }
}
```

Then add the component. It lands in `components/ui/nautilus.tsx`, and the CLI also adds `lib/utils.ts` (the `cn` helper) and installs the npm dependencies:

```bash
npx shadcn@latest add @keyframeui/nautilus
```

Or install by URL, without registering the namespace:

```bash
npx shadcn@latest add https://keyframeui.com/r/nautilus.json
```

## Usage

The main demo shows typical usage.

### Selected Work

An architecture studio's selected work, with the project's caption, prev / next and a pause button beside the spiral.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/nautilus-demo
```

```tsx title="components/nautilus-demo.tsx"
"use client";

import * as React from "react";

import { Nautilus } from "@/components/ui/nautilus";

const photo = (id: string) =>
  `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=880&h=1100&q=80`;

const WORK = [
  {
    src: photo("1486718448742-163732cd1544"),
    alt: "Two sweeping terracotta facades of fine horizontal ribs curving apart against a clear blue sky",
    title: "Rib Pavilion",
    place: "Valencia",
    year: "2025",
    note: "Two terracotta walls of fine ribs that curl apart to frame a slice of sky.",
  },
  {
    src: photo("1771520711516-4b677ab05542"),
    alt: "A sculptural armchair made of one looping off-white upholstered tube in a pale room",
    title: "Loop Lounge Chair",
    place: "Milan",
    year: "2024",
    note: "One upholstered tube, bent five times, made for a hotel lobby.",
  },
  {
    src: photo("1758800601480-49aa0f18c1f1"),
    alt: "Curved wood-panelled walls ribboning around a narrow slot of daylight",
    title: "Slot House",
    place: "Kyoto",
    year: "2023",
    note: "Curved oak walls that ribbon around a single slot of daylight.",
  },
  {
    src: photo("1620395458832-6436796c2d4c"),
    alt: "An orange-walled room with a small white round table and red chairs, a turquoise wall at the edge",
    title: "Naranja Café",
    place: "Lisbon",
    year: "2025",
    note: "An orange room for twelve tables, with one turquoise wall to rest the eye.",
  },
  {
    src: photo("1785295061892-44a42aa9ed65"),
    alt: "A white nested archway framing a wide stair, with a white arcade and desert plants under a blue sky",
    title: "Arch Court",
    place: "Marrakech",
    year: "2024",
    note: "Nested white arches that step the stair down into a desert garden.",
  },
  {
    src: photo("1782852884076-d964a06242af"),
    alt: "A red arched panelled door with a fanlight between two gold wall lamps on pale yellow brick",
    title: "Red Door House",
    place: "Porto",
    year: "2023",
    note: "A townhouse entrance rebuilt around its original fanlight.",
  },
  {
    src: photo("1599004831521-f9b1f81f5a84"),
    alt: "A green-framed chair with a light wood back and an orange seat against a teal wall",
    title: "Reading Room Chair",
    place: "Copenhagen",
    year: "2025",
    note: "A steel-framed side chair in ash and orange leather, drawn for a teal reading room.",
  },
  {
    src: photo("1522161135122-3ab7ef2e63b2"),
    alt: "A pink and white tower with blue-glazed windows rising into a cobalt sky",
    title: "Pink Tower",
    place: "Miami",
    year: "2024",
    note: "Twelve floors of pink render and blue glass, stepped back at the top.",
  },
];

const pad = (n: number) => String(n).padStart(2, "0");

export function NautilusDemo() {
  const [index, setIndex] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const captionRef = React.useRef<HTMLDivElement>(null);
  const project = WORK[index];
  const count = WORK.length;

  // The caption rises in with each new front card.
  React.useEffect(() => {
    captionRef.current?.animate(
      [
        { opacity: 0, transform: "translateY(6px)" },
        { opacity: 1, transform: "none" },
      ],
      { duration: 320, easing: "cubic-bezier(0.22, 1, 0.36, 1)" },
    );
  }, [index]);

  return (
    <section className="@container/work w-full overflow-hidden rounded-2xl border border-zinc-200 bg-white text-zinc-950 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50">
      <div className="grid grid-cols-1 @[44rem]/work:grid-cols-[17rem_minmax(0,1fr)]">
        <div className="order-2 flex flex-col justify-between gap-8 border-t border-zinc-200 p-6 @[44rem]/work:order-1 @[44rem]/work:border-t-0 @[44rem]/work:border-r @[44rem]/work:p-8 dark:border-zinc-800">
          <div>
            <p className="text-xs font-medium tracking-[0.14em] text-zinc-500 uppercase dark:text-zinc-400">
              Studio Vell
            </p>
            <h3 className="mt-3 text-[1.75rem] leading-[1.1] font-semibold tracking-[-0.03em] text-balance">
              Rooms, chairs, light.
            </h3>
          </div>

          <div ref={captionRef}>
            <p className="font-mono text-xs text-zinc-500 tabular-nums dark:text-zinc-400">
              <span className="text-[#007f43] dark:text-[#34d399]">{pad(index + 1)}</span> / {pad(count)}
            </p>
            <p className="mt-2 text-lg font-semibold tracking-[-0.02em]">{project.title}</p>
            <p className="text-sm text-zinc-500 dark:text-zinc-400">
              {project.place} · {project.year}
            </p>
            <p className="mt-3 text-sm leading-relaxed text-zinc-600 dark:text-zinc-300">{project.note}</p>
          </div>

          <div className="flex items-center gap-2">
            <button
              type="button"
              aria-label="Previous project"
              onClick={() => setIndex((i) => (i - 1 + count) % count)}
              className="grid size-10 place-items-center rounded-full border border-zinc-200 transition-colors hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:border-zinc-800 dark:hover:bg-zinc-900 dark:focus-visible:outline-white"
            >
              <svg viewBox="0 0 16 16" className="size-4" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden>
                <path d="M10 3.5 5.5 8l4.5 4.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <button
              type="button"
              aria-label="Next project"
              onClick={() => setIndex((i) => (i + 1) % count)}
              className="grid size-10 place-items-center rounded-full border border-zinc-200 transition-colors hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:border-zinc-800 dark:hover:bg-zinc-900 dark:focus-visible:outline-white"
            >
              <svg viewBox="0 0 16 16" className="size-4" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden>
                <path d="M6 3.5 10.5 8 6 12.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <button
              type="button"
              aria-label={paused ? "Play the slideshow" : "Pause the slideshow"}
              aria-pressed={paused}
              onClick={() => setPaused((p) => !p)}
              className="grid size-10 place-items-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:text-zinc-400 dark:hover:bg-zinc-900 dark:hover:text-white dark:focus-visible:outline-white"
            >
              {paused ? (
                <svg viewBox="0 0 16 16" className="size-4" fill="currentColor" aria-hidden>
                  <path d="M5 3.2v9.6a.5.5 0 0 0 .77.42l7.2-4.8a.5.5 0 0 0 0-.84l-7.2-4.8A.5.5 0 0 0 5 3.2Z" />
                </svg>
              ) : (
                <svg viewBox="0 0 16 16" className="size-4" fill="currentColor" aria-hidden>
                  <rect x="4" y="3" width="2.6" height="10" rx="0.8" />
                  <rect x="9.4" y="3" width="2.6" height="10" rx="0.8" />
                </svg>
              )}
            </button>
            <a
              href="https://vell.example/work"
              className="ml-auto text-sm font-medium underline decoration-zinc-300 underline-offset-4 transition-colors hover:decoration-current focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:decoration-zinc-700 dark:focus-visible:outline-white"
            >
              All work
            </a>
          </div>
        </div>

        <Nautilus
          items={WORK}
          index={index}
          onIndexChange={setIndex}
          paused={paused}
          label="Studio Vell selected work"
          className="order-1 h-[22rem] @[44rem]/work:order-2 @[44rem]/work:h-[32rem]"
        />
      </div>
    </section>
  );
}
```

## Examples

Finished sections built with Nautilus. Each one installs whole, with the component included.

### Up Next

A listening queue.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/nautilus-queue-demo
```

```tsx title="components/nautilus-queue-demo.tsx"
"use client";

import * as React from "react";

import { Nautilus } from "@/components/ui/nautilus";

const cover = (id: string) =>
  `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=800&h=800&q=80`;

// Each track plays for a few seconds here; `length` is what the player shows.
const QUEUE = [
  { src: cover("1626875953051-ba3d609252e9"), alt: "Cover of Sunday Blue by Marisol Eke: a sunflower on electric blue", title: "Sunday Blue", artist: "Marisol Eke", length: "3:41" },
  { src: cover("1661432432103-42999ae07367"), alt: "Cover of Backbeat by The Odd Hours: a drummer's silhouette on violet", title: "Backbeat", artist: "The Odd Hours", length: "4:02" },
  { src: cover("1550859492-d5da9d8e45f3"), alt: "Cover of Soft Focus by Toru Vale: a soft blue, orange and pink gradient", title: "Soft Focus", artist: "Toru Vale", length: "2:58" },
  { src: cover("1629276301820-0f3eedc29fd0"), alt: "Cover of Green Room Live by Haddo: a guitarist raised above the crowd in green haze", title: "Green Room Live", artist: "Haddo", length: "5:16" },
  { src: cover("1639835203652-99c8e298d13d"), alt: "Cover of Bloom Cycle by Ines Laraki: magenta flowers on teal", title: "Bloom Cycle", artist: "Ines Laraki", length: "3:27" },
  { src: cover("1545431613-51ec097943c6"), alt: "Cover of Light Leak by Ana Brightwell: a rainbow light leak on black", title: "Light Leak", artist: "Ana Brightwell", length: "4:44" },
  { src: cover("1618005182384-a83a8bd57fbe"), alt: "Cover of Tidal by Kofi Mensa: violet, pink and cyan waves", title: "Tidal", artist: "Kofi Mensa", length: "3:12" },
  { src: cover("1566127385722-1178df27105d"), alt: "Cover of Neon Heart by Lumi Sato: a pink neon heart on a dark wall", title: "Neon Heart", artist: "Lumi Sato", length: "3:55" },
  { src: cover("1602848596718-45693ff58c78"), alt: "Cover of Side B by Marisol Eke: a black record with a blank label", title: "Side B", artist: "Marisol Eke", length: "4:20" },
  { src: cover("1550275994-cdc89cd1948f"), alt: "Cover of Night Drive by The Odd Hours: red and blue light trails on black", title: "Night Drive", artist: "The Odd Hours", length: "3:36" },
];

const PLAY_FOR = 6000; // ms each track plays in the demo

export function NautilusQueueDemo() {
  const [index, setIndex] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);
  const barRef = React.useRef<HTMLDivElement>(null);
  const runRef = React.useRef<Animation | null>(null);
  const track = QUEUE[index];
  const next = QUEUE[(index + 1) % QUEUE.length];

  // The progress bar is the clock: when it fills, the queue moves up one.
  React.useEffect(() => {
    const bar = barRef.current;
    if (!bar) return;
    const run = bar.animate([{ transform: "scaleX(0)" }, { transform: "scaleX(1)" }], {
      duration: PLAY_FOR,
      easing: "linear",
      fill: "forwards",
    });
    run.onfinish = () => setIndex((i) => (i + 1) % QUEUE.length);
    runRef.current = run;
    return () => run.cancel();
  }, [index]);

  React.useEffect(() => {
    const run = runRef.current;
    if (!run) return;
    if (playing) run.play();
    else run.pause();
  }, [playing, index]);

  return (
    <div className="w-full max-w-3xl overflow-hidden rounded-3xl bg-zinc-100 text-zinc-950 ring-1 ring-zinc-950/5 dark:bg-zinc-900 dark:text-white dark:ring-white/10">
      <div className="flex items-center justify-between px-6 pt-5 text-xs">
        <p className="font-semibold tracking-[-0.01em]">Driftwave</p>
        <p className="text-zinc-600 dark:text-zinc-400">Up next · {QUEUE.length} in the queue</p>
      </div>

      <Nautilus
        items={QUEUE}
        index={index}
        onIndexChange={(i) => setIndex(i)}
        autoplay={false}
        aspect={1}
        slots={13}
        growth={1.22}
        label="Listening queue"
        className="h-[20rem] sm:h-[24rem] [--nautilus-radius:0.75rem]"
      />

      <div className="m-2 mt-0 rounded-2xl bg-white p-4 shadow-sm ring-1 ring-zinc-950/5 sm:p-5 dark:bg-zinc-950 dark:ring-white/10">
        <div className="flex items-center gap-4">
          <button
            type="button"
            aria-label={playing ? "Pause" : "Play"}
            onClick={() => setPlaying((p) => !p)}
            className="grid size-11 shrink-0 place-items-center rounded-full bg-zinc-950 text-white transition-transform active:scale-95 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:bg-white dark:text-zinc-950 dark:focus-visible:outline-white"
          >
            {playing ? (
              <svg viewBox="0 0 16 16" className="size-4" fill="currentColor" aria-hidden>
                <rect x="4" y="3" width="2.6" height="10" rx="0.8" />
                <rect x="9.4" y="3" width="2.6" height="10" rx="0.8" />
              </svg>
            ) : (
              <svg viewBox="0 0 16 16" className="size-4 translate-x-px" fill="currentColor" aria-hidden>
                <path d="M5 3.2v9.6a.5.5 0 0 0 .77.42l7.2-4.8a.5.5 0 0 0 0-.84l-7.2-4.8A.5.5 0 0 0 5 3.2Z" />
              </svg>
            )}
          </button>
          <div className="min-w-0 flex-1" aria-live="polite">
            <p className="truncate text-sm font-semibold tracking-[-0.01em]">{track.title}</p>
            <p className="truncate text-sm text-zinc-500 dark:text-zinc-400">{track.artist}</p>
          </div>
          <button
            type="button"
            onClick={() => setIndex((i) => (i + 1) % QUEUE.length)}
            className="hidden min-w-0 items-center gap-2 rounded-full py-1.5 pr-1 pl-3 text-right text-xs text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 sm:flex dark:text-zinc-400 dark:hover:bg-zinc-900 dark:hover:text-white dark:focus-visible:outline-white"
          >
            <span className="truncate">
              Next: <span className="text-zinc-950 dark:text-white">{next.title}</span>
            </span>
            <svg viewBox="0 0 16 16" className="size-4 shrink-0" fill="currentColor" aria-hidden>
              <path d="M3 3.6v8.8a.5.5 0 0 0 .78.42L10 8.6V12a.5.5 0 0 0 .5.5h1a.5.5 0 0 0 .5-.5V4a.5.5 0 0 0-.5-.5h-1A.5.5 0 0 0 10 4v3.4L3.78 3.18A.5.5 0 0 0 3 3.6Z" />
            </svg>
          </button>
        </div>
        <div className="mt-4 flex items-center gap-3 text-[11px] text-zinc-500 tabular-nums dark:text-zinc-400">
          <div className="h-1 flex-1 overflow-hidden rounded-full bg-zinc-200 dark:bg-zinc-800">
            <div ref={barRef} style={{ transform: "scaleX(0)" }} className="h-full origin-left rounded-full bg-[#00a3ff] dark:bg-[#38bdf8]" />
          </div>
          <span>{track.length}</span>
        </div>
      </div>
    </div>
  );
}
```

### New Arrivals

A shop's new arrivals.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/nautilus-shop-demo
```

```tsx title="components/nautilus-shop-demo.tsx"
"use client";

import * as React from "react";

import { Nautilus, type NautilusItem } from "@/components/ui/nautilus";

const shot = (id: string) =>
  `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=800&h=1000&q=80`;

type Piece = NautilusItem & { name: string; price: number; detail: string };

const DROP: Piece[] = [
  { src: shot("1603808033176-9d134e6f2c74"), alt: "A white leather and tan suede low-top sneaker balanced on two pebbles against orange", name: "Pebble Low Sneaker", price: 145, detail: "White leather, tan suede" },
  { src: shot("1599705709640-9f9eb5964485"), alt: "Mirrored aviator sunglasses floating over a white ledge against teal", name: "Mirror Aviators", price: 120, detail: "Steel frame, mirrored lenses" },
  { src: shot("1756474215958-f0c2a31eddc1"), alt: "A yellow mushroom table lamp on a mustard background", name: "Cap Table Lamp", price: 180, detail: "Powder-coated steel, mustard" },
  { src: shot("1681573736425-0caa07d13e09"), alt: "A cobalt glass carafe and upturned cup with two flower stems on pink and magenta", name: "Cobalt Carafe Set", price: 58, detail: "Mouth-blown glass, carafe and cup" },
  { src: shot("1643569556871-91ec60671ed7"), alt: "A ring-shaped sand-colored ceramic vase on beige", name: "Ring Vase", price: 72, detail: "Sand stoneware, 24 cm" },
  { src: shot("1620003039413-b519b3c12e4d"), alt: "A glossy orange shell chair on wooden legs against slate blue", name: "Shell Side Chair", price: 290, detail: "Glossy orange shell, oak legs" },
  { src: shot("1624548140129-74786c5f1279"), alt: "A navy bomber jacket with a cream fleece collar on light grey", name: "Harbour Bomber", price: 210, detail: "Navy nylon, fleece collar" },
  { src: shot("1598532163257-ae3c6b2524b6"), alt: "A brown woven leather tote with a gold chain strap on pale grey", name: "Woven Tote", price: 240, detail: "Tan leather, gold chain strap" },
];

const money = (n: number) => `€${n}`;

export function NautilusShopDemo() {
  const [index, setIndex] = React.useState(0);
  const [bag, setBag] = React.useState<string[]>([]);
  const piece = DROP[index];
  const inBag = bag.includes(piece.name);

  return (
    <div className="@container/drop w-full overflow-hidden rounded-2xl border border-zinc-200 bg-white text-zinc-950 dark:border-zinc-800 dark:bg-zinc-950 dark:text-white">
      <div className="flex items-center justify-between border-b border-zinc-200 px-5 py-3 text-sm dark:border-zinc-800">
        <p className="font-semibold tracking-[-0.02em]">Forma Supply</p>
        <p className="flex items-center gap-2 text-zinc-500 dark:text-zinc-400">
          <svg viewBox="0 0 16 16" className="size-4" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden>
            <path d="M3 5.5h10l-.8 8H3.8L3 5.5Z" strokeLinejoin="round" />
            <path d="M5.8 5.5V4.3a2.2 2.2 0 0 1 4.4 0v1.2" />
          </svg>
          <span className="tabular-nums">{bag.length}</span>
          <span className="sr-only">in your bag</span>
        </p>
      </div>

      <div className="grid grid-cols-1 @[42rem]/drop:grid-cols-[minmax(0,1fr)_16rem]">
        <Nautilus
          items={DROP}
          index={index}
          onIndexChange={(i) => setIndex(i)}
          side="right"
          interval={3.2}
          sweep={280}
          label="New arrivals"
          className="h-[22rem] @[42rem]/drop:h-[30rem] [--nautilus-radius:0.25rem]"
          renderItem={(item) => (
            <div className="relative size-full bg-zinc-100 dark:bg-zinc-800">
              {/* eslint-disable-next-line @next/next/no-img-element -- a remote photo in an installable demo */}
              <img src={item.src} alt="" draggable={false} className="size-full object-cover" />
              <span className="absolute bottom-[4%] left-[5%] rounded-full bg-white/95 px-[0.6em] py-[0.2em] text-[0.8rem] font-medium text-zinc-950 tabular-nums">
                {money(item.price)}
              </span>
            </div>
          )}
        />

        <div className="flex flex-col justify-between gap-6 border-t border-zinc-200 p-5 @[42rem]/drop:border-t-0 @[42rem]/drop:border-l @[42rem]/drop:p-6 dark:border-zinc-800">
          <div>
            <p className="text-xs font-medium tracking-[0.14em] text-[#e0136f] uppercase dark:text-[#ff5ca8]">New this week</p>
            <p className="mt-3 text-xl leading-tight font-semibold tracking-[-0.02em]">{piece.name}</p>
            <p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">{piece.detail}</p>
          </div>
          <div>
            <p className="text-2xl font-semibold tracking-[-0.02em] tabular-nums">{money(piece.price)}</p>
            <button
              type="button"
              aria-pressed={inBag}
              onClick={() => setBag((b) => (inBag ? b.filter((n) => n !== piece.name) : [...b, piece.name]))}
              className="mt-4 flex h-11 w-full items-center justify-center gap-2 rounded-full bg-zinc-950 text-sm font-medium text-white transition-[background-color,transform] active:scale-[0.98] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 aria-pressed:bg-[#e0136f] dark:bg-white dark:text-zinc-950 dark:focus-visible:outline-white dark:aria-pressed:bg-[#ff5ca8]"
            >
              {inBag ? "In your bag" : "Add to bag"}
            </button>
            <p className="mt-3 text-center text-xs text-zinc-500 dark:text-zinc-400">
              {index + 1} of {DROP.length} · drag or click to browse
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `items` (required) | `NautilusItem[]` |  | The slides, front to back: `{ src, alt }`, plus any fields your own `renderItem` reads. Fewer items than `slots` repeat along the trail. Size each image for the front card, about twice its width on screen. |
| `index` | `number` |  | The item at the front. Set it to wind the spiral there (forward when it's already in the trail, otherwise the short way); leave it out and the spiral keeps its own place. |
| `defaultIndex` | `number` | `0` | The item at the front on first render, when `index` isn't set. |
| `onIndexChange` | `(index: number, reason: "auto" \| "user") => void` |  | Called with the new front item's index as soon as a move heads for it, and whether autoplay or a visitor moved it. Use it for a caption next to the spiral. |
| `autoplay` | `boolean` | `true` | Moves the trail one slot every `interval` on its own. It waits while the pointer is over the spiral, while it has focus, during a drag and off screen, and stays off under reduced motion. |
| `paused` | `boolean` | `false` | Holds autoplay, like a pause button. |
| `interval` | `number` | `2.8` | Seconds between steps while it plays on its own. |
| `duration` | `number` | `0.9` | Seconds a one-slot step takes. A longer wind takes a little longer per slot. |
| `ripple` | `number` | `32` | Ms each card waits after the one in front of it, so a step runs down the trail. 0 moves every card as one. |
| `slots` | `number` | `14` | How many cards ride the spiral. |
| `growth` | `number` | `1.2` | How much bigger each card is than the one behind it. Higher makes a bigger front card and a tinier tail. |
| `sweep` | `number` | `300` | Degrees the trail winds from the front card to the tail. |
| `side` | `"left" \| "right"` | `"left"` | Which side the front card sits on. The spiral winds away from it, and the old front card leaves past that side's corner. |
| `aspect` | `number` | `0.8` | Card width over height: 0.8 for portrait prints, 1 for covers, 1.5 for landscape. |
| `align` | `"start" \| "center" \| "end"` | `"center"` | Where the spiral sits when the stage is wider than it needs. Hug the start or end edge to line the trail up with the page's content; set `--nautilus-align` on the stage to change it at a breakpoint (`lg:[--nautilus-align:end]`). |
| `tilt` | `number` | `4` | Degrees the cards lean with the curve. |
| `label` | `string` | `"Gallery"` | Names the carousel for screen readers. |
| `renderItem` | `(item: T, info: { index: number; echo: boolean }) => React.ReactNode` |  | Draws a card's face instead of the plain image, for covers with a title or products with a price. `echo` is true for a repeat of an item already nearer the front. Faces are pictures (the spiral is hidden from screen readers and lists the items' `alt` text instead), so keep links and buttons outside it. |
| `className` | `string` |  | Extra classes for the stage. Set its height here (28rem by default); the spiral fits itself inside. `--nautilus-radius` sets the card corners (0.5rem), and `--nautilus-align` overrides `align`. |

## What to keep

To adapt it, change its props first. When you do edit `components/ui/nautilus.tsx`, keep these, which make it feel and behave right:

- Every card sits on one spiral function of its slot `p` (0 is the front, growing toward the tail), each slot `growth` times smaller than the one in front of it, so after a step the spiral looks exactly as it did before. That is what makes the loop seamless.
- One phase number drives every move (autoplay, clicks, keys, drag). Moves are added on top of each other as segments, so a new one starts from wherever the cards are, and each card reads the phase `ripple` ms later per slot behind the front: that delay is the ripple.
- A card keeps its item for life (it's keyed by its place in the endless sequence), so no image is ever swapped in view: the front card leaves past the corner and a new one grows out of the tail.
- Transform and opacity are written straight to each card in one rAF loop that stops once everything has landed; React only renders when a card enters or leaves the window.
- Reduced motion: no autoplay and no unfurl. A step jumps the cards to their new slots and the stage fades back up; dragging still scrubs.

Its timing (durations, delays, springs and easings) is all in the `TIMING` block at the top of the file; the timing props default to it.

## Source

```tsx title="components/ui/nautilus.tsx"
"use client";

import * as React from "react";

import { cn } from "@/lib/utils";

/**
 * Keep:
 * - Every card sits on one spiral function of its slot `p` (0 is the front, growing toward the
 *   tail), each slot `growth` times smaller than the one in front of it, so after a step the spiral
 *   looks exactly as it did before. That is what makes the loop seamless.
 * - One phase number drives every move (autoplay, clicks, keys, drag). Moves are added on top of
 *   each other as segments, so a new one starts from wherever the cards are, and each card reads the
 *   phase `ripple` ms later per slot behind the front: that delay is the ripple.
 * - A card keeps its item for life (it's keyed by its place in the endless sequence), so no image
 *   is ever swapped in view: the front card leaves past the corner and a new one grows out of the tail.
 * - Transform and opacity are written straight to each card in one rAF loop that stops once
 *   everything has landed; React only renders when a card enters or leaves the window.
 * - Reduced motion: no autoplay and no unfurl. A step jumps the cards to their new slots and the
 *   stage fades back up; dragging still scrubs.
 */
const TIMING = {
  /** Seconds between steps while it plays on its own (the `interval` prop). */
  interval: 2.8,
  /** Seconds a one-slot step takes (the `duration` prop). A longer wind takes a little longer per slot. */
  duration: 0.9,
  /** Ms each card waits after the one in front of it, so a step runs down the trail (the `ripple` prop). */
  ripple: 32,
  /** The step's curve: a soft start and a soft landing, never a snap. */
  ease: [0.65, 0, 0.35, 1],
  /** The first unfurl as the spiral comes into view: seconds of travel, ms between cards, the curve. */
  unfurl: { duration: 1.4, stagger: 42, ease: [0.16, 1, 0.3, 1] },
  /** Reduced motion: the stage fading back up after a jump, in ms. */
  fade: 220,
  /** Seconds of release speed a flick carries into where the drag lands. */
  carry: 0.16,
  /** Ms: the shortest gap between pointer events used to measure a drag's speed, and how long a
   *  drag held still before release counts as stopped (it then carries nothing). */
  flick: { frame: 8, rest: 90 },
  /** A card lifting under the pointer, as Tailwind classes. */
  hover: "duration-200 ease-out",
} as const;

/* ─────────────────────────────────────────────────────────
 * NAUTILUS STORYBOARD
 *
 *  rest      cards lie along one spiral arm like prints on a
 *            table: the front card is the current slide, and
 *            each card behind it is `growth` (1.2×) smaller,
 *            winding `sweep` (300°) inward to a tiny tail.
 *            Cards lean a few degrees with the curve
 *  view      the first time it's on screen the shell unfurls:
 *            every card starts at the tail and rides out to its
 *            slot over 1.4s, front first, 42ms apart, ease-out
 *  step      every `interval` (2.8s) the trail moves one slot
 *            toward the front in `duration` (0.9s), in-out.
 *            The front card moves first and each card behind it
 *            follows `ripple` (32ms) later, so the step runs
 *            down the trail like a whip
 *  leave     the old front card keeps going past the corner,
 *            growing to 1.3× and fading out once it's clear
 *  arrive    a new card grows out of the tail tip, fading up
 *            over its first slot. It brings its own image; no
 *            card ever changes picture in view
 *  wind      click a card in the trail and the spiral winds it
 *            to the front in one move (longer winds take a
 *            little longer per slot), the ripple included
 *  drag      pull sideways and the whole spiral winds with the
 *            pointer, 1:1; let go and it lands on the nearest
 *            card, carrying a flick's speed for 0.16s
 *  hold      autoplay waits while the pointer is over it, while
 *            it has focus, while a drag is on, and off screen
 *  keys      the stage is one tab stop: → / ↓ next, ← / ↑
 *            previous, Home the first item. Each new front is
 *            announced politely when you moved it
 *  touch     a horizontal swipe winds, a vertical one scrolls
 *            the page, a tap winds the tapped card forward
 *  reduced   no autoplay, no unfurl: the spiral sits still.
 *            A step jumps every card to its new slot and the
 *            stage fades up from 40% over 0.22s. Drag scrubs
 * ───────────────────────────────────────────────────────── */

const SPIRAL = {
  front: 130, // degrees: where the front card sits, measured clockwise from 3 o'clock (lower left)
  radius: 1.25, // the front card's distance from the spiral's center, in front-card widths
  radial: 0.66, // how much of `growth` the radius keeps per slot (below 1, the tail spreads out)
  exit: 1.9, // front-card widths the leaving card travels past the corner
  exitDip: 1.1, // how far its path bends down toward the viewer (0 keeps the spiral's own direction)
  exitScale: 0.45, // how much it grows on the way out
  exitTurn: 9, // degrees it turns on the way out
  exitFade: [0.62, 1], // share of the way out over which it fades: solid until it clears the new front
  margin: [0.015, 0.06], // share of the stage kept clear at the sides and at top and bottom (room for the shadow)
  dragSlot: 0.55, // front-card widths of drag per slot
  dragSlop: 6, // px a press travels before it counts as a drag
  flickMax: 3, // the most cards a flick carries past where it was let go
};

export interface NautilusItem {
  /** Image URL. Size it for the front card: about twice its width on screen. */
  src: string;
  /** What the picture shows, for screen readers and the announcement. */
  alt: string;
}

export interface NautilusCardInfo {
  /** The item's index in `items`. */
  index: number;
  /** True for a repeat of an item already shown nearer the front. */
  echo: boolean;
}

export interface NautilusProps<T extends NautilusItem = NautilusItem>
  extends Omit<React.HTMLAttributes<HTMLDivElement>, "children"> {
  /** The slides, front to back. Fewer items than `slots` repeat along the trail. */
  items: T[];
  /** The item at the front. Set it to wind the spiral there; leave it out to let the spiral keep its own place. */
  index?: number;
  /** The item at the front on first render, when `index` isn't set. */
  defaultIndex?: number;
  /** Called with the new front item's index and whether it came from autoplay or a visitor. */
  onIndexChange?: (index: number, reason: "auto" | "user") => void;
  /** Moves the trail one slot every `interval` on its own. Off under reduced motion. */
  autoplay?: boolean;
  /** Holds autoplay, like a pause button. */
  paused?: boolean;
  /** Seconds between steps while it plays on its own. */
  interval?: number;
  /** Seconds a one-slot step takes. */
  duration?: number;
  /** Ms each card waits after the one in front of it, so a step runs down the trail. 0 moves them as one. */
  ripple?: number;
  /** How many cards ride the spiral. */
  slots?: number;
  /** How much bigger each card is than the one behind it. */
  growth?: number;
  /** Degrees the trail winds from the front card to the tail. */
  sweep?: number;
  /** Which side the front card sits on. The spiral winds away from it. */
  side?: "left" | "right";
  /** Card width over height. */
  aspect?: number;
  /** Where the spiral sits when the stage is wider than it needs: hug the start or end edge to line it up with the page's content. `--nautilus-align` on the stage overrides it, per breakpoint. */
  align?: "start" | "center" | "end";
  /** Degrees the cards lean with the curve. */
  tilt?: number;
  /** Names the carousel for screen readers. */
  label?: string;
  /** Draws a card's face instead of the plain image. Faces are pictures: keep links and buttons outside the spiral. */
  renderItem?: (item: T, info: NautilusCardInfo) => React.ReactNode;
}

/* ── Helpers ────────────────────────────────────────────── */

const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);
const mod = (v: number, n: number) => ((v % n) + n) % n;
const smooth = (a: number, b: number, v: number) => {
  const x = clamp((v - a) / (b - a), 0, 1);
  return x * x * (3 - 2 * x);
};
const DEG = Math.PI / 180;

/** A CSS cubic-bezier as a function of progress, so the rAF loop eases exactly like a transition would. */
function bezier([x1, y1, x2, y2]: readonly number[]) {
  const cx = 3 * x1;
  const bx = 3 * (x2 - x1) - cx;
  const ax = 1 - cx - bx;
  const cy = 3 * y1;
  const by = 3 * (y2 - y1) - cy;
  const ay = 1 - cy - by;
  const sx = (t: number) => ((ax * t + bx) * t + cx) * t;
  const sy = (t: number) => ((ay * t + by) * t + cy) * t;
  return (x: number) => {
    if (x <= 0) return 0;
    if (x >= 1) return 1;
    let lo = 0;
    let hi = 1;
    let t = x;
    for (let i = 0; i < 22; i++) {
      if (sx(t) < x) lo = t;
      else hi = t;
      t = (lo + hi) / 2;
    }
    return sy(t);
  };
}

const REDUCED_QUERY = "(prefers-reduced-motion: reduce)";
const subscribeReduced = (onChange: () => void) => {
  const mq = window.matchMedia(REDUCED_QUERY);
  mq.addEventListener("change", onChange);
  return () => mq.removeEventListener("change", onChange);
};
/** Live, and false on the server and in the hydration render, so markup never mismatches. */
function usePrefersReducedMotion() {
  return React.useSyncExternalStore(
    subscribeReduced,
    () => window.matchMedia(REDUCED_QUERY).matches,
    () => false,
  );
}

/* ── Geometry ───────────────────────────────────────────── */

type Shape = { slots: number; growth: number; sweep: number; mirror: number; aspect: number; tilt: number; align: "start" | "center" | "end" };
type Pose = { x: number; y: number; s: number; r: number; o: number };
/** The spiral fitted to the stage: `unit` is the front card's width in px, `ox`/`oy` the center. */
type Fit = Shape & { unit: number; ox: number; oy: number; exitX: number; exitY: number };

/** A slot on the spiral in front-card widths, before fitting. Valid for any p ≥ 0. */
function spiral(sh: Shape, p: number) {
  const step = (sh.sweep * DEG) / Math.max(1, sh.slots - 1);
  const a = SPIRAL.front * DEG - p * step;
  const r = SPIRAL.radius * Math.pow(sh.growth, -p * SPIRAL.radial);
  return {
    x: Math.cos(a) * r * sh.mirror,
    y: Math.sin(a) * r,
    s: Math.pow(sh.growth, -p),
    // Lean with the curve: the front leans back toward the turn, the far side the other way.
    r: -sh.tilt * Math.cos(a - SPIRAL.front * DEG + 0.5) * sh.mirror,
  };
}

function fitSpiral(sh: Shape, w: number, h: number): Fit | null {
  if (w < 8 || h < 8) return null;
  let minX = Infinity;
  let maxX = -Infinity;
  let minY = Infinity;
  let maxY = -Infinity;
  for (let p = 0; p < sh.slots; p++) {
    const c = spiral(sh, p);
    const hw = c.s / 2;
    const hh = c.s / sh.aspect / 2;
    const cos = Math.cos(c.r * DEG);
    const sin = Math.sin(c.r * DEG);
    const ex = Math.abs(hw * cos) + Math.abs(hh * sin);
    const ey = Math.abs(hw * sin) + Math.abs(hh * cos);
    minX = Math.min(minX, c.x - ex);
    maxX = Math.max(maxX, c.x + ex);
    minY = Math.min(minY, c.y - ey);
    maxY = Math.max(maxY, c.y + ey);
  }
  const mx = SPIRAL.margin[0] * Math.min(w, h);
  const my = SPIRAL.margin[1] * Math.min(w, h);
  const unit = Math.min((w - 2 * mx) / (maxX - minX), (h - 2 * my) / (maxY - minY));
  // A stage wider than the spiral needs: sit it at the start, the middle or the end.
  const ox =
    sh.align === "start" ? mx - unit * minX : sh.align === "end" ? w - mx - unit * maxX : w / 2 - (unit * (minX + maxX)) / 2;
  // The leaving card keeps the direction the front card arrived in, bent down toward the viewer.
  const a = spiral(sh, 0);
  const b = spiral(sh, 0.15);
  const along = Math.hypot(a.x - b.x, a.y - b.y) || 1;
  const dx = (a.x - b.x) / along;
  const dy = (a.y - b.y) / along + SPIRAL.exitDip;
  const len = Math.hypot(dx, dy) || 1;
  return {
    ...sh,
    unit,
    ox,
    oy: h / 2 - (unit * (minY + maxY)) / 2,
    exitX: dx / len,
    exitY: dy / len,
  };
}

/** Where a card at slot `p` is drawn, in px of the stage. p < 0 is leaving, p > slots − 1 arriving. */
function pose(f: Fit, p: number): Pose {
  if (p < 0) {
    const q = Math.min(-p, 1.5);
    const c = spiral(f, 0);
    const d = SPIRAL.exit * q;
    return {
      x: f.ox + f.unit * (c.x + f.exitX * d),
      y: f.oy + f.unit * (c.y + f.exitY * d),
      s: 1 + SPIRAL.exitScale * q,
      r: c.r - SPIRAL.exitTurn * q * f.mirror,
      o: 1 - smooth(SPIRAL.exitFade[0], SPIRAL.exitFade[1], q),
    };
  }
  const c = spiral(f, p);
  return {
    x: f.ox + f.unit * c.x,
    y: f.oy + f.unit * c.y,
    s: c.s,
    r: c.r,
    o: clamp(f.slots - p, 0, 1),
  };
}

/* ── Engine ─────────────────────────────────────────────── */

/** One move of the phase, added on top of any still running. `end` is the phase it heads for. */
type Segment = { delta: number; start: number; dur: number; end: number };

const easeStep = bezier(TIMING.ease);
const easeUnfurl = bezier(TIMING.unfurl.ease);

/* ── Nautilus ───────────────────────────────────────────── */

export function Nautilus<T extends NautilusItem = NautilusItem>({
  items,
  index,
  defaultIndex = 0,
  onIndexChange,
  autoplay = true,
  paused = false,
  interval = TIMING.interval,
  duration = TIMING.duration,
  ripple = TIMING.ripple,
  slots: slotsProp = 14,
  growth = 1.2,
  sweep = 300,
  side = "left",
  aspect = 0.8,
  align = "center",
  tilt = 4,
  label = "Gallery",
  renderItem,
  className,
  onKeyDown,
  onPointerDown,
  onPointerEnter,
  onPointerLeave,
  onFocus,
  onBlur,
  ...props
}: NautilusProps<T>) {
  const count = items.length;
  const slots = Math.max(3, Math.round(slotsProp));
  const reduced = usePrefersReducedMotion();
  const rootRef = React.useRef<HTMLDivElement>(null);
  const stageRef = React.useRef<HTMLDivElement>(null);

  const [size, setSize] = React.useState<{ w: number; h: number; align: string } | null>(null);
  const [range, setRange] = React.useState<[number, number]>(() => [(index ?? defaultIndex) - 1, (index ?? defaultIndex) + slots]);
  const [frontSeq, setFrontSeq] = React.useState(index ?? defaultIndex);
  const current = count ? mod(frontSeq, count) : 0;
  const [announce, setAnnounce] = React.useState(false);
  const [hovered, setHovered] = React.useState(false);
  const [focused, setFocused] = React.useState(false);
  const [dragging, setDragging] = React.useState(false);
  const [inView, setInView] = React.useState(false);
  const [pageVisible, setPageVisible] = React.useState(true);
  const [kick, setKick] = React.useState(0);

  // Everything the rAF loop reads lives in one ref, so moves never re-render the cards.
  const engine = React.useRef({
    base: index ?? defaultIndex,
    segs: [] as Segment[],
    fit: null as Fit | null,
    els: new Map<number, HTMLDivElement>(),
    range: [0, 0] as [number, number],
    raf: 0,
    /** The time the last frame was painted at; a card mounted between frames is painted at it too. */
    t: 0,
    unfurlAt: -1,
    ripple,
    reduced,
    front: index ?? defaultIndex,
  });
  const live = React.useRef({ onIndexChange, count, duration, slots });
  React.useEffect(() => {
    live.current = { onIndexChange, count, duration, slots };
    engine.current.ripple = ripple;
    engine.current.reduced = reduced;
  });

  const shape = React.useMemo<Shape>(
    () => ({ slots, growth: Math.max(1.01, growth), sweep, mirror: side === "right" ? -1 : 1, aspect, tilt, align }),
    [slots, growth, sweep, side, aspect, tilt, align],
  );
  const fit = React.useMemo(() => {
    if (!size) return null;
    const css = size.align;
    return fitSpiral(css === "start" || css === "center" || css === "end" ? { ...shape, align: css } : shape, size.w, size.h);
  }, [size, shape]);

  /* The phase every card would read with no ripple, and where all moves end up. */
  const phase = React.useCallback((a: number | null, t: number) => {
    const e = engine.current;
    let v = e.base;
    for (const s of e.segs) {
      const lag = a === null ? 0 : e.ripple * clamp(a - s.end, 0, live.current.slots + 1);
      const u = s.dur <= 0 ? 1 : (t - s.start - lag) / s.dur;
      v += s.delta * easeStep(u);
    }
    return v;
  }, []);
  const target = () => {
    const e = engine.current;
    return e.segs.reduce((v, s) => v + s.delta, e.base);
  };

  const paint = React.useCallback(
    (a: number, el: HTMLDivElement, t: number) => {
      const e = engine.current;
      const f = e.fit;
      if (!f) return;
      let p = a - phase(a, t);
      if (e.unfurlAt >= 0) {
        // Unfurl: every card rides out from just past the tail tip, front first.
        const rank = clamp(Math.round(a - target()), 0, f.slots);
        const u = (t - e.unfurlAt - rank * TIMING.unfurl.stagger) / (TIMING.unfurl.duration * 1000);
        const from = f.slots + 0.5;
        p = from - (from - p) * easeUnfurl(u);
      }
      const q = pose(f, p);
      const w = f.unit / 2;
      const h = f.unit / f.aspect / 2;
      el.style.transform = `translate3d(${(q.x - w).toFixed(2)}px, ${(q.y - h).toFixed(2)}px, 0) rotate(${q.r.toFixed(3)}deg) scale(${q.s.toFixed(5)})`;
      el.style.opacity = q.o.toFixed(3);
      el.style.visibility = q.o < 0.002 ? "hidden" : "";
      el.style.pointerEvents = p < -0.1 || q.o < 0.5 ? "none" : "";
    },
    [phase],
  );

  // The loop reschedules itself through this ref, so it always runs the latest frame.
  const frameRef = React.useRef<(t: number) => void>(() => {});
  const frame = React.useCallback(
    (t: number) => {
      const e = engine.current;
      e.raf = 0;
      e.t = t;
      const f = e.fit;
      if (!f) return;
      const maxLag = e.ripple * (f.slots + 2);
      // Fold finished moves into the base so the list stays short.
      e.segs = e.segs.filter((s) => {
        if (t < s.start + s.dur + maxLag) return true;
        e.base += s.delta;
        return false;
      });
      if (e.unfurlAt >= 0 && t > e.unfurlAt + TIMING.unfurl.duration * 1000 + TIMING.unfurl.stagger * (f.slots + 1)) {
        e.unfurlAt = -1;
      }
      const now = phase(null, t);
      const late = phase(null, t - maxLag);
      const lo = Math.floor(Math.min(now, late)) - 1;
      const hi = Math.ceil(Math.max(now, late)) + f.slots;
      if (lo !== e.range[0] || hi !== e.range[1]) {
        e.range = [lo, hi];
        setRange([lo, hi]);
      }
      for (const [a, el] of e.els) paint(a, el, t);
      if (e.segs.length > 0 || e.unfurlAt >= 0) e.raf = requestAnimationFrame((next) => frameRef.current(next));
    },
    [paint, phase],
  );
  React.useLayoutEffect(() => {
    frameRef.current = frame;
  }, [frame]);

  const wake = React.useCallback(() => {
    const e = engine.current;
    if (!e.raf) e.raf = requestAnimationFrame((t) => frameRef.current(t));
  }, []);

  /** Reports the item now heading for the front, once per change. */
  const settleFront = React.useCallback((reason: "auto" | "user" | "prop") => {
    const e = engine.current;
    const n = live.current.count;
    if (!n) return;
    const front = Math.round(target());
    if (front === e.front) return;
    e.front = front;
    const i = mod(front, n);
    setFrontSeq(front);
    setAnnounce(reason === "user");
    if (reason !== "prop") live.current.onIndexChange?.(i, reason);
  }, []);

  /** Adds a move of `delta` slots. */
  const move = React.useCallback(
    (delta: number, reason: "auto" | "user" | "prop") => {
      if (!delta) return;
      const e = engine.current;
      const t = performance.now();
      const span = Math.abs(delta);
      const dur = e.reduced ? 0 : live.current.duration * 1000 * (1 + 0.45 * Math.log2(span));
      e.segs.push({ delta, start: t, dur, end: target() + delta });
      if (e.reduced && stageRef.current) {
        stageRef.current.animate([{ opacity: 0.4 }, { opacity: 1 }], { duration: TIMING.fade, easing: "ease-out" });
      }
      settleFront(reason);
      // A visitor's move, or the parent's, restarts the wait before the next autoplay step.
      if (reason !== "auto") setKick((k) => k + 1);
      wake();
    },
    [settleFront, wake],
  );

  /** Winds item `i` to the front the short way round. */
  const windTo = React.useCallback(
    (i: number, reason: "user" | "prop") => {
      const n = live.current.count;
      if (!n) return;
      const forward = mod(i - mod(Math.round(target()), n), n);
      // The short way round; a tie goes forward. (A click on a card in the trail always winds forward.)
      const delta = forward <= n - forward ? forward : forward - n;
      move(delta, reason);
    },
    [move],
  );

  // Measure the stage.
  React.useLayoutEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    // `--nautilus-align` on the stage overrides `align`, so it can change at a breakpoint
    // (a breakpoint that changes it also resizes the stage, which re-reads it).
    const measure = () =>
      setSize({ w: root.clientWidth, h: root.clientHeight, align: getComputedStyle(root).getPropertyValue("--nautilus-align").trim() });
    const ro = new ResizeObserver(measure);
    ro.observe(root);
    measure();
    return () => ro.disconnect();
  }, []);

  // Fit the spiral to the stage and repaint.
  React.useLayoutEffect(() => {
    engine.current.fit = fit;
    const t = performance.now();
    for (const [a, el] of engine.current.els) paint(a, el, t);
    wake();
  }, [fit, paint, wake]);

  // Sleep off screen; unfurl the first time it shows.
  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const io = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting), { threshold: 0.15 });
    io.observe(root);
    const onVis = () => setPageVisible(document.visibilityState === "visible");
    document.addEventListener("visibilitychange", onVis);
    return () => {
      io.disconnect();
      document.removeEventListener("visibilitychange", onVis);
    };
  }, []);
  const unfurled = React.useRef(false);
  React.useEffect(() => {
    if (!inView || !size || unfurled.current) return;
    unfurled.current = true;
    if (!reduced) engine.current.unfurlAt = performance.now();
    wake();
  }, [inView, size, reduced, wake]);

  // Autoplay: one step per interval while nothing holds it. A visitor's move restarts the wait.
  const running = autoplay && !paused && !reduced && !hovered && !focused && !dragging && inView && pageVisible && count > 1;
  React.useEffect(() => {
    if (!running) return;
    const id = window.setInterval(() => move(1, "auto"), Math.max(0.3, interval) * 1000);
    return () => window.clearInterval(id);
  }, [running, interval, move, kick]);

  // A controlled `index` winds the spiral to it.
  React.useEffect(() => {
    if (index === undefined || !count) return;
    if (mod(index, count) !== mod(Math.round(target()), count)) windTo(index, "prop");
  }, [index, count, windTo]);

  React.useEffect(() => {
    const e = engine.current;
    return () => {
      if (e.raf) cancelAnimationFrame(e.raf);
      e.raf = 0;
    };
  }, []);

  /* ── Drag, tap and keys ── */

  const drag = React.useRef<{
    id: number;
    x0: number;
    y0: number;
    x: number;
    t: number;
    v: number;
    moved: boolean;
    seq: number | null;
  } | null>(null);

  const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
    onPointerDown?.(event);
    if (event.defaultPrevented || event.button !== 0 || !count) return;
    const card = (event.target as HTMLElement).closest<HTMLElement>("[data-nautilus-seq]");
    drag.current = {
      id: event.pointerId,
      x0: event.clientX,
      y0: event.clientY,
      x: event.clientX,
      t: performance.now(),
      v: 0,
      moved: false,
      seq: card ? Number(card.dataset.nautilusSeq) : null,
    };
  };

  const handlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    const f = engine.current.fit;
    if (!d || d.id !== event.pointerId || !f) return;
    if (!d.moved) {
      const dx = event.clientX - d.x0;
      const dy = event.clientY - d.y0;
      if (Math.abs(dx) < SPIRAL.dragSlop || Math.abs(dx) < Math.abs(dy)) {
        if (Math.abs(dy) > SPIRAL.dragSlop) drag.current = null; // a vertical swipe belongs to the page
        return;
      }
      d.moved = true;
      d.x = event.clientX;
      event.currentTarget.setPointerCapture(event.pointerId);
      setDragging(true);
    }
    const t = performance.now();
    const dx = event.clientX - d.x;
    // Pulling toward the side the front card leaves by winds forward.
    const delta = (-dx * f.mirror) / (f.unit * SPIRAL.dragSlot);
    engine.current.base += delta;
    // Slots per second, smoothed; events closer than a frame apart don't spike it.
    const dt = Math.max(TIMING.flick.frame, t - d.t);
    d.v = d.v * 0.6 + (delta / dt) * 1000 * 0.4;
    d.x = event.clientX;
    d.t = t;
    settleFront("user");
    if (!engine.current.raf) frame(t);
  };

  const handlePointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    if (!d || d.id !== event.pointerId) return;
    drag.current = null;
    if (d.moved) {
      setDragging(false);
      const e = engine.current;
      const at = target();
      // A drag that stopped before letting go carries nothing; a flick carries a few cards at most.
      const v = performance.now() - d.t > TIMING.flick.rest ? 0 : d.v;
      const carry = clamp(v * TIMING.carry, -SPIRAL.flickMax, SPIRAL.flickMax);
      const land = Math.round(at + (e.reduced ? 0 : carry));
      const delta = land - at;
      // Land on the card: a short glide that starts from the drag's own place.
      e.segs.push({ delta, start: performance.now(), dur: e.reduced ? 0 : live.current.duration * 700, end: land });
      settleFront("user");
      setKick((k) => k + 1);
      wake();
      return;
    }
    if (d.seq !== null) {
      const ahead = d.seq - Math.round(target());
      if (ahead > 0) move(ahead, "user");
    }
  };

  const handlePointerCancel = (event: React.PointerEvent<HTMLDivElement>) => {
    if (drag.current?.id !== event.pointerId) return;
    const moved = drag.current.moved;
    drag.current = null;
    if (moved) {
      setDragging(false);
      const at = target();
      engine.current.segs.push({ delta: Math.round(at) - at, start: performance.now(), dur: 300, end: Math.round(at) });
      settleFront("user");
      wake();
    }
  };

  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(event);
    if (event.defaultPrevented || !count) return;
    if (event.key === "ArrowRight" || event.key === "ArrowDown") move(1, "user");
    else if (event.key === "ArrowLeft" || event.key === "ArrowUp") move(-1, "user");
    else if (event.key === "Home") windTo(0, "user");
    else return;
    event.preventDefault();
  };

  /* ── Render ── */

  const cards: React.ReactNode[] = [];
  if (fit && count) {
    // Tail first in the DOM, so every card paints over the ones behind it.
    for (let a = range[1]; a >= range[0]; a--) {
      const i = mod(a, count);
      const echo = a - frontSeq >= count || a < frontSeq;
      cards.push(
        <div
          key={a}
          data-nautilus-seq={a}
          ref={(el) => {
            const els = engine.current.els;
            if (!el) return;
            els.set(a, el);
            // At the frame's own time, so it lines up with the ones the loop just painted.
            paint(a, el, engine.current.t || performance.now());
            return () => {
              if (els.get(a) === el) els.delete(a);
            };
          }}
          className="absolute left-0 top-0 origin-center opacity-0 will-change-transform"
          style={{ width: fit.unit, height: fit.unit / fit.aspect }}
        >
          <div
            className={cn(
              "size-full overflow-hidden rounded-[var(--nautilus-radius,0.5rem)] bg-zinc-200 shadow-[0_18px_40px_-18px_rgb(0_0_0/0.45),0_2px_6px_-2px_rgb(0_0_0/0.18)] ring-1 ring-black/5 transition-transform dark:bg-zinc-800 dark:shadow-[0_18px_40px_-16px_rgb(0_0_0/0.9)] dark:ring-white/10",
              `hover:scale-[1.03] ${TIMING.hover}`,
            )}
          >
            {renderItem ? (
              renderItem(items[i], { index: i, echo })
            ) : (
              // eslint-disable-next-line @next/next/no-img-element -- a remote photo in an installable component
              <img
                src={items[i].src}
                alt=""
                draggable={false}
                decoding="async"
                className="size-full select-none object-cover"
              />
            )}
          </div>
        </div>,
      );
    }
  }

  const item = items[current];

  return (
    <div
      ref={rootRef}
      role="region"
      aria-roledescription="carousel"
      aria-label={label}
      tabIndex={0}
      className={cn(
        "relative h-[28rem] w-full touch-pan-y select-none overflow-hidden outline-offset-[-3px] focus-visible:outline-2 focus-visible:outline-current",
        count > 1 && "cursor-grab active:cursor-grabbing",
        className,
      )}
      onKeyDown={handleKeyDown}
      onPointerDown={handlePointerDown}
      onPointerMove={handlePointerMove}
      onPointerUp={handlePointerUp}
      onPointerCancel={handlePointerCancel}
      onPointerEnter={(event) => {
        onPointerEnter?.(event);
        if (event.pointerType === "mouse") setHovered(true);
      }}
      onPointerLeave={(event) => {
        onPointerLeave?.(event);
        setHovered(false);
      }}
      onFocus={(event) => {
        onFocus?.(event);
        setFocused(true);
      }}
      onBlur={(event) => {
        onBlur?.(event);
        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocused(false);
      }}
      {...props}
    >
      <div ref={stageRef} aria-hidden className="absolute inset-0">
        {cards}
      </div>
      <ul className="sr-only">
        {items.map((it, i) => (
          <li key={i} aria-current={i === current ? "true" : undefined}>
            {it.alt}
          </li>
        ))}
      </ul>
      <p className="sr-only" aria-live={announce ? "polite" : "off"} aria-atomic>
        {item ? `${item.alt}, ${current + 1} of ${count}` : ""}
      </p>
    </div>
  );
}
```
