{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "spiral-gallery",
  "title": "Spiral Gallery",
  "description": "Photo cards wound around an endless 3D helix that turns and climbs with the wheel, a drag or the arrow keys, with the far strand glowing faintly through, a big index and caption, and line indicators to jump anywhere.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/spiral-gallery/spiral-gallery.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport interface SpiralPhoto {\n  src: string;\n  alt?: string;\n  title?: string;\n  caption?: string;\n}\n\nexport type SpiralGalleryTheme = \"dark\" | \"light\";\n\nexport interface SpiralGalleryProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  photos?: SpiralPhoto[];\n  theme?: SpiralGalleryTheme;\n  height?: number;\n  /** Card size in px on wide screens; everything scales down on narrow ones. */\n  cardWidth?: number;\n  cardHeight?: number;\n  /** Distance of the cards from the spiral's axis. */\n  radius?: number;\n  /** Turn between neighbouring cards, in degrees. */\n  angleStep?: number;\n  /** Climb between neighbouring cards, in px. */\n  rise?: number;\n  /** 0–1, how quickly the spiral catches up. */\n  smoothing?: number;\n  wheelSensitivity?: number;\n  /** Seconds between automatic steps; 0 turns it off. */\n  autoPlay?: number;\n  borderRadius?: number;\n  showLines?: boolean;\n  showCaption?: boolean;\n  enableLightbox?: boolean;\n}\n\nconst PALETTES = {\n  dark: {\n    background: \"#080808\",\n    text: \"rgba(255,255,255,0.92)\",\n    muted: \"rgba(255,255,255,0.42)\",\n    lineColor: \"rgba(255,255,255,0.25)\",\n    activeLineColor: \"#FFFFFF\",\n    tile: \"#141414\",\n    cardShadow: \"0 18px 40px rgba(0,0,0,0.5)\",\n    lightboxBackground: \"rgba(8,8,8,0.95)\",\n    controlColor: \"rgba(255,255,255,0.8)\",\n    emptyText: \"rgba(255,255,255,0.4)\",\n    emptyBorder: \"1.5px dashed rgba(255,255,255,0.15)\",\n  },\n  light: {\n    background: \"#F5F5F3\",\n    text: \"rgba(0,0,0,0.88)\",\n    muted: \"rgba(0,0,0,0.42)\",\n    lineColor: \"rgba(0,0,0,0.2)\",\n    activeLineColor: \"#000000\",\n    tile: \"#E6E6E3\",\n    cardShadow: \"0 18px 40px rgba(0,0,0,0.14)\",\n    lightboxBackground: \"rgba(255,255,255,0.96)\",\n    controlColor: \"rgba(0,0,0,0.75)\",\n    emptyText: \"rgba(0,0,0,0.4)\",\n    emptyBorder: \"1.5px dashed rgba(0,0,0,0.15)\",\n  },\n} as const;\n\nconst DEFAULT_PHOTOS: SpiralPhoto[] = [\n  { src: \"/demo/41.webp\", title: \"Mei Arai\", caption: \"Ceramicist · Kyoto\" },\n  { src: \"/demo/1.webp\", title: \"Living room\", caption: \"Lisbon, first light\" },\n  { src: \"/demo/42.webp\", title: \"Kenji Ito\", caption: \"Architect · Osaka\" },\n  { src: \"/demo/3.webp\", title: \"Curtain study\", caption: \"Late spring\" },\n  { src: \"/demo/43.webp\", title: \"Rafael Duarte\", caption: \"Sculptor · Porto\" },\n  { src: \"/demo/4.webp\", title: \"Kitchen\", caption: \"Sunday, 9 a.m.\" },\n  { src: \"/demo/44.webp\", title: \"Sofia Marin\", caption: \"Editor · Madrid\" },\n  { src: \"/demo/6.webp\", title: \"Stair hall\", caption: \"North light\" },\n  { src: \"/demo/45.webp\", title: \"Amara Okafor\", caption: \"Musician · Lagos\" },\n  { src: \"/demo/8.webp\", title: \"Bath\", caption: \"Limewash and stone\" },\n  { src: \"/demo/46.webp\", title: \"Nia Bello\", caption: \"Painter · Accra\" },\n  { src: \"/demo/9.webp\", title: \"Kitchen at dusk\", caption: \"Oak and steel\" },\n  { src: \"/demo/55.webp\", title: \"Elin Berg\", caption: \"Writer · Oslo\" },\n  { src: \"/demo/10.webp\", title: \"Tea room\", caption: \"October\" },\n];\n\nconst DEG = Math.PI / 180;\nconst clamp = (v: number, min: number, max: number) => Math.min(Math.max(v, min), max);\n\n/** Signed distance from the current position to card i, wrapped so the spiral never ends. */\nfunction wrapped(i: number, p: number, n: number) {\n  let k = (((i - p) % n) + n) % n;\n  if (k > n / 2) k -= n;\n  return k;\n}\n\nfunction cardState(k: number, angleStep: number, rise: number, radius: number) {\n  const angle = k * angleStep;\n  const facing = Math.cos(angle * DEG);\n  const fade = clamp(1 - (Math.abs(k) - 4.6) / 1.8, 0, 1);\n  // Front cards bright, the far strand faint through the gap, the ends fading out vertically.\n  const light = facing > 0 ? 0.32 + 0.68 * Math.pow(facing, 4) : 0.14 + 0.14 * (1 + facing);\n  return {\n    // Fixed precision so the server and browser print the same string.\n    transform: `translateY(${(-k * rise).toFixed(2)}px) rotateY(${angle.toFixed(3)}deg) translateZ(${radius.toFixed(2)}px)`,\n    opacity: Number((light * fade).toFixed(3)),\n    zIndex: Math.round(1000 + facing * 500),\n    back: facing < 0,\n  };\n}\n\nexport function SpiralGallery({\n  photos = DEFAULT_PHOTOS,\n  theme = \"dark\",\n  height = 620,\n  cardWidth = 168,\n  cardHeight = 222,\n  radius = 290,\n  angleStep = 36,\n  rise = 30,\n  smoothing = 0.085,\n  wheelSensitivity = 1,\n  autoPlay = 0,\n  borderRadius = 3,\n  showLines = true,\n  showCaption = true,\n  enableLightbox = true,\n  className,\n  ...props\n}: SpiralGalleryProps) {\n  const palette = PALETTES[theme];\n  const n = photos.length;\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const stageRef = React.useRef<HTMLDivElement>(null);\n  const cardRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n\n  const [scale, setScale] = React.useState(1);\n  const [active, setActive] = React.useState(0);\n  const pos = React.useRef({ p: 0, target: 0 });\n  const drag = React.useRef({ active: false, moved: false, x: 0, y: 0, start: 0, card: null as number | null });\n  const snapTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n  const wakeRef = React.useRef<() => void>(() => {});\n  const lastInput = React.useRef(0);\n\n  const s = scale;\n  const geo = { w: cardWidth * s, h: cardHeight * s, r: radius * s, rise: rise * s };\n  const optsRef = React.useRef({ n, angleStep, geo, smoothing, wheelSensitivity });\n  React.useEffect(() => {\n    optsRef.current = { n, angleStep, geo, smoothing, wheelSensitivity };\n    wakeRef.current();\n  });\n\n  const [lightbox, setLightbox] = React.useState<number | null>(null);\n  const dialogRef = React.useRef<HTMLDivElement>(null);\n  const closeButtonRef = React.useRef<HTMLButtonElement>(null);\n  const lastFocusedRef = React.useRef<HTMLElement | null>(null);\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const update = () => setScale(clamp(el.clientWidth / 760, 0.6, 1));\n    update();\n    const observer = new ResizeObserver(update);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  React.useEffect(() => {\n    let raf: number | null = null;\n    let inView = true;\n    const paint = () => {\n      const { n, angleStep, geo } = optsRef.current;\n      const { p } = pos.current;\n      cardRefs.current.forEach((el, i) => {\n        if (!el) return;\n        const st = cardState(wrapped(i, p, n), angleStep, geo.rise, geo.r);\n        el.style.transform = st.transform;\n        el.style.opacity = String(st.opacity);\n        el.style.zIndex = String(st.zIndex);\n        el.style.visibility = st.opacity < 0.01 ? \"hidden\" : \"visible\";\n        // Cards on the far strand show their back: flip the photo so it doesn't read mirrored.\n        const img = el.querySelector(\"img\");\n        if (img) img.style.transform = st.back ? \"scaleX(-1)\" : \"\";\n      });\n    };\n    const tick = () => {\n      const { smoothing, n } = optsRef.current;\n      const v = pos.current;\n      v.p += (v.target - v.p) * (drag.current.active ? 0.3 : smoothing);\n      const settled = Math.abs(v.target - v.p) < 0.0005 && !drag.current.active;\n      if (settled) v.p = v.target;\n      paint();\n      const nearest = ((Math.round(v.p) % n) + n) % n;\n      setActive((cur) => (cur === nearest ? cur : nearest));\n      raf = inView && !settled ? requestAnimationFrame(tick) : null;\n    };\n    wakeRef.current = () => {\n      if (raf === null && inView) raf = requestAnimationFrame(tick);\n    };\n    paint();\n    const observer = new IntersectionObserver(([entry]) => {\n      inView = entry.isIntersecting;\n      if (inView) wakeRef.current();\n    });\n    if (rootRef.current) observer.observe(rootRef.current);\n    return () => {\n      if (raf) cancelAnimationFrame(raf);\n      observer.disconnect();\n    };\n  }, []);\n\n  /** Move to the nearest copy of card i (the spiral wraps, so go the short way round). */\n  const goTo = React.useCallback((i: number) => {\n    const { n } = optsRef.current;\n    const v = pos.current;\n    v.target = Math.round(v.target) + wrapped(i, Math.round(v.target), n);\n    lastInput.current = performance.now();\n    wakeRef.current();\n  }, []);\n\n  const step = React.useCallback((dir: number) => {\n    const v = pos.current;\n    v.target = Math.round(v.target) + dir;\n    lastInput.current = performance.now();\n    wakeRef.current();\n  }, []);\n\n  // Wheel and drag move the spiral freely; it settles on the nearest card when input stops.\n  React.useEffect(() => {\n    const el = stageRef.current;\n    if (!el) return;\n    const snapSoon = () => {\n      if (snapTimer.current) clearTimeout(snapTimer.current);\n      snapTimer.current = setTimeout(() => {\n        pos.current.target = Math.round(pos.current.target);\n        wakeRef.current();\n      }, 140);\n    };\n    const onWheel = (e: WheelEvent) => {\n      const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;\n      // wheelSensitivity={0} hands the wheel back to the page.\n      if (!delta || !optsRef.current.wheelSensitivity) return;\n      e.preventDefault();\n      pos.current.target += (delta / 120) * 0.5 * optsRef.current.wheelSensitivity;\n      lastInput.current = performance.now();\n      wakeRef.current();\n      snapSoon();\n    };\n    const onDown = (e: PointerEvent) => {\n      if (e.button !== 0) return;\n      const cardEl = (e.target as HTMLElement).closest<HTMLElement>(\"[data-card]\");\n      drag.current = { active: true, moved: false, x: e.clientX, y: e.clientY, start: pos.current.target, card: cardEl ? Number(cardEl.dataset.card) : null };\n      el.setPointerCapture(e.pointerId);\n    };\n    const onMove = (e: PointerEvent) => {\n      const d = drag.current;\n      if (!d.active) return;\n      const dx = e.clientX - d.x;\n      const dy = e.clientY - d.y;\n      if (!d.moved && Math.hypot(dx, dy) < 6) return;\n      if (!d.moved) {\n        d.moved = true;\n        el.style.cursor = \"grabbing\";\n      }\n      // Pull up (or left) to climb the spiral; whichever axis moved more wins.\n      const along = Math.abs(dy) > Math.abs(dx) ? -dy : -dx;\n      pos.current.target = d.start + along / (optsRef.current.geo.rise * 2.2);\n      lastInput.current = performance.now();\n      wakeRef.current();\n    };\n    const onUp = () => {\n      const d = drag.current;\n      if (!d.active) return;\n      d.active = false;\n      el.style.cursor = \"\";\n      if (d.moved) {\n        pos.current.target = Math.round(pos.current.target);\n        wakeRef.current();\n        return;\n      }\n      if (d.card === null) return;\n      const k = wrapped(d.card, pos.current.p, optsRef.current.n);\n      if (Math.abs(k) < 0.5 && enableLightbox) setLightbox(d.card);\n      else goTo(d.card);\n    };\n    el.addEventListener(\"wheel\", onWheel, { passive: false });\n    el.addEventListener(\"pointerdown\", onDown);\n    el.addEventListener(\"pointermove\", onMove);\n    el.addEventListener(\"pointerup\", onUp);\n    el.addEventListener(\"pointercancel\", onUp);\n    return () => {\n      el.removeEventListener(\"wheel\", onWheel);\n      el.removeEventListener(\"pointerdown\", onDown);\n      el.removeEventListener(\"pointermove\", onMove);\n      el.removeEventListener(\"pointerup\", onUp);\n      el.removeEventListener(\"pointercancel\", onUp);\n      if (snapTimer.current) clearTimeout(snapTimer.current);\n    };\n  }, [enableLightbox, goTo]);\n\n  // Optional slow auto-advance, paused for a while after any input and while the lightbox is open.\n  React.useEffect(() => {\n    if (!autoPlay || lightbox !== null) return;\n    const id = setInterval(() => {\n      if (drag.current.active || performance.now() - lastInput.current < autoPlay * 1000 * 1.5) return;\n      pos.current.target = Math.round(pos.current.target) + 1;\n      wakeRef.current();\n    }, autoPlay * 1000);\n    return () => clearInterval(id);\n  }, [autoPlay, lightbox]);\n\n  React.useEffect(() => {\n    if (lightbox === null) {\n      lastFocusedRef.current?.focus();\n      lastFocusedRef.current = null;\n      return;\n    }\n    lastFocusedRef.current = document.activeElement as HTMLElement | null;\n    closeButtonRef.current?.focus();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [lightbox !== null]);\n\n  React.useEffect(() => {\n    if (lightbox === null) return;\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") setLightbox(null);\n      else if (e.key === \"ArrowRight\") setLightbox((i) => (i === null ? null : (i + 1) % n));\n      else if (e.key === \"ArrowLeft\") setLightbox((i) => (i === null ? null : (i - 1 + n) % n));\n      else if (e.key === \"Tab\") {\n        const focusables = Array.from(dialogRef.current?.querySelectorAll<HTMLElement>(\"button\") ?? []);\n        if (focusables.length === 0) return;\n        const first = focusables[0];\n        const last = focusables[focusables.length - 1];\n        if (e.shiftKey && document.activeElement === first) {\n          e.preventDefault();\n          last.focus();\n        } else if (!e.shiftKey && document.activeElement === last) {\n          e.preventDefault();\n          first.focus();\n        }\n      }\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [lightbox, n]);\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (lightbox !== null) return;\n    if (e.key === \"ArrowUp\" || e.key === \"ArrowRight\") step(1);\n    else if (e.key === \"ArrowDown\" || e.key === \"ArrowLeft\") step(-1);\n    else if ((e.key === \"Enter\" || e.key === \" \") && enableLightbox) setLightbox(active);\n    else return;\n    e.preventDefault();\n  };\n\n  if (n === 0) {\n    return (\n      <div className={cn(\"flex h-full w-full items-center justify-center rounded-xl\", className)} style={{ minHeight: 300, background: palette.background, border: palette.emptyBorder }} {...props}>\n        <span className=\"text-center text-sm leading-[1.6]\" style={{ color: palette.emptyText }}>\n          Add photos\n        </span>\n      </div>\n    );\n  }\n\n  const current = photos[active];\n  const lines = Array.from({ length: n }, (_, i) => i);\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\"relative w-full overflow-hidden outline-none select-none\", className)}\n      style={{ height, background: palette.background }}\n      tabIndex={0}\n      role=\"region\"\n      aria-roledescription=\"spiral gallery\"\n      aria-label=\"Spiral gallery. Scroll, drag or use the arrow keys to move through the photos.\"\n      onKeyDown={onKeyDown}\n      {...props}\n    >\n      <div ref={stageRef} className=\"absolute inset-0 cursor-grab touch-none\" style={{ perspective: `${Math.round(1400 * s)}px`, perspectiveOrigin: \"50% 50%\" }}>\n        {photos.map((photo, i) => {\n          const st = cardState(wrapped(i, 0, n), angleStep, geo.rise, geo.r);\n          return (\n            <div\n              key={i}\n              ref={(el) => {\n                cardRefs.current[i] = el;\n              }}\n              data-card={i}\n              className=\"absolute top-1/2 left-1/2\"\n              style={{\n                width: geo.w,\n                height: geo.h,\n                marginLeft: -geo.w / 2,\n                marginTop: -geo.h / 2,\n                transform: st.transform,\n                opacity: st.opacity,\n                zIndex: st.zIndex,\n                visibility: st.opacity < 0.01 ? \"hidden\" : \"visible\",\n                cursor: \"pointer\",\n              }}\n            >\n              {/* Clip on an inner box: WebKit drops perspective from a 3D-transformed element that clips itself. */}\n              <div className=\"h-full w-full overflow-hidden\" style={{ borderRadius, background: palette.tile, boxShadow: palette.cardShadow }}>\n                <img src={photo.src} alt={photo.alt || photo.title || \"\"} draggable={false} className=\"pointer-events-none block h-full w-full object-cover\" style={{ transform: st.back ? \"scaleX(-1)\" : undefined }} />\n              </div>\n            </div>\n          );\n        })}\n      </div>\n\n      {showCaption && (\n        <div className=\"pointer-events-none absolute bottom-6 left-5 z-[3000] sm:bottom-9 sm:left-9\" aria-live=\"polite\">\n          <div className=\"flex items-baseline gap-2 tabular-nums\">\n            <span className=\"text-[34px] leading-none font-light sm:text-[44px]\" style={{ color: palette.text }}>\n              {String(active + 1).padStart(2, \"0\")}\n            </span>\n            <span className=\"text-[11px] tracking-[0.16em]\" style={{ color: palette.muted }}>\n              / {String(n).padStart(2, \"0\")}\n            </span>\n          </div>\n          {current.title && (\n            <div key={active} className=\"mt-3 animate-[spiral-in_0.5s_cubic-bezier(0.22,1,0.36,1)]\">\n              <div className=\"text-[14px]\" style={{ color: palette.text }}>\n                {current.title}\n              </div>\n              {current.caption && (\n                <div className=\"mt-1 text-[10px] tracking-[0.2em] uppercase\" style={{ color: palette.muted }}>\n                  {current.caption}\n                </div>\n              )}\n            </div>\n          )}\n        </div>\n      )}\n\n      {showLines && (\n        <div className=\"absolute top-1/2 right-4 z-[3000] flex -translate-y-1/2 flex-col items-end gap-[5px] sm:right-8\">\n          {lines.map((i) => {\n            const isActive = i === active;\n            return (\n              <button\n                key={i}\n                type=\"button\"\n                onClick={() => goTo(i)}\n                aria-label={`Go to ${photos[i].title ?? `photo ${i + 1}`}`}\n                aria-current={isActive ? \"true\" : undefined}\n                className=\"flex h-[5px] cursor-pointer items-center justify-end border-0 bg-transparent p-0\"\n              >\n                <span className=\"block transition-[width,background] duration-[250ms] ease-[ease]\" style={{ height: 1, width: isActive ? 22 : 12, background: isActive ? palette.activeLineColor : palette.lineColor }} />\n              </button>\n            );\n          })}\n        </div>\n      )}\n\n      <style>{`@keyframes spiral-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }`}</style>\n\n      {enableLightbox &&\n        lightbox !== null &&\n        createPortal(\n          <div ref={dialogRef} onClick={() => setLightbox(null)} role=\"dialog\" aria-modal=\"true\" aria-label=\"Photo preview\" className=\"fixed inset-0 z-[999999] flex flex-col items-center justify-center\" style={{ background: palette.lightboxBackground }}>\n            <button\n              ref={closeButtonRef}\n              onClick={(e) => {\n                e.stopPropagation();\n                setLightbox(null);\n              }}\n              aria-label=\"Close\"\n              className=\"absolute top-6 right-8 h-10 w-10 cursor-pointer border-0 bg-transparent text-[28px] leading-none\"\n              style={{ color: palette.controlColor }}\n            >\n              ×\n            </button>\n            {n > 1 && (\n              <>\n                <button\n                  onClick={(e) => {\n                    e.stopPropagation();\n                    setLightbox((lightbox - 1 + n) % n);\n                  }}\n                  aria-label=\"Previous\"\n                  className=\"absolute top-1/2 left-6 h-11 w-11 -translate-y-1/2 cursor-pointer border-0 bg-transparent text-[32px]\"\n                  style={{ color: palette.controlColor }}\n                >\n                  ‹\n                </button>\n                <button\n                  onClick={(e) => {\n                    e.stopPropagation();\n                    setLightbox((lightbox + 1) % n);\n                  }}\n                  aria-label=\"Next\"\n                  className=\"absolute top-1/2 right-6 h-11 w-11 -translate-y-1/2 cursor-pointer border-0 bg-transparent text-[32px]\"\n                  style={{ color: palette.controlColor }}\n                >\n                  ›\n                </button>\n              </>\n            )}\n            <img\n              src={photos[lightbox].src}\n              alt={photos[lightbox].alt || photos[lightbox].title || \"\"}\n              onClick={(e) => e.stopPropagation()}\n              className=\"max-w-[82%] object-contain\"\n              style={{ maxHeight: \"78%\", borderRadius: 4, boxShadow: \"0 20px 60px rgba(0,0,0,0.6)\" }}\n              draggable={false}\n            />\n            <div className=\"mt-5 flex items-baseline gap-3 text-[13px]\" style={{ color: palette.controlColor }} onClick={(e) => e.stopPropagation()}>\n              {photos[lightbox].title && <span>{photos[lightbox].title}</span>}\n              <span className=\"text-[11px] tracking-[0.16em] uppercase tabular-nums opacity-60\">\n                {String(lightbox + 1).padStart(2, \"0\")} / {String(n).padStart(2, \"0\")}\n              </span>\n            </div>\n          </div>,\n          document.body,\n        )}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}