{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"panorama-sphere","type":"registry:ui","title":"Panorama Sphere","description":"Photos tiled across the inside of a sphere that you drag to look around, with inertia and click-to-enlarge.","dependencies":["motion","lucide-react"],"registryDependencies":[],"files":[{"path":"registry/ui/panorama-sphere.tsx","type":"registry:ui","content":"\"use client\";\n/* eslint-disable @next/next/no-img-element */\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { X } from \"lucide-react\";\n\nexport interface PanoramaSphereProps {\n  images: string[];\n  /** Sphere radius in px (also the camera distance). */\n  radius?: number;\n  /** Tiles around the full circle. */\n  columns?: number;\n  /** Rows of tiles, centered on the horizon. */\n  rows?: number;\n  /** Space between tiles as a fraction of their size. */\n  gap?: number;\n  /** Idle rotation in degrees per second. 0 disables. */\n  autoRotate?: number;\n  /** Degrees of rotation per px dragged. */\n  dragSensitivity?: number;\n  /** Max up/down tilt in degrees. */\n  maxPitch?: number;\n  /** Tile corner radius in px. */\n  tileRadius?: number;\n  className?: string;\n}\n\nconst toRad = Math.PI / 180;\n\nexport function PanoramaSphere({\n  images,\n  radius = 560,\n  columns = 22,\n  rows = 5,\n  gap = 0.1,\n  autoRotate = 4,\n  dragSensitivity = 0.18,\n  maxPitch = 22,\n  tileRadius = 14,\n  className,\n}: PanoramaSphereProps) {\n  const root = useRef<HTMLDivElement>(null);\n  const sphere = useRef<HTMLDivElement>(null);\n  const tileEls = useRef<(HTMLDivElement | null)[]>([]);\n  const view = useRef({\n    yaw: 0,\n    pitch: 0,\n    vYaw: 0,\n    vPitch: 0,\n    hover: false,\n    drag: null as null | { x: number; y: number; lx: number; ly: number; moved: boolean; tile: number },\n  });\n  const [open, setOpen] = useState<number | null>(null);\n  const openRef = useRef(open);\n  const closeBtn = useRef<HTMLButtonElement>(null);\n\n  const dLon = 360 / columns;\n  const size = 2 * radius * Math.sin((dLon / 2) * toRad) * (1 - gap);\n  const tiles: { lon: number; lat: number; src: string }[] = [];\n  for (let r = 0; r < rows; r++) {\n    for (let c = 0; c < columns; c++) {\n      // Stagger rows like bricks and spread images so neighbours differ.\n      tiles.push({ lon: (c + (r % 2) * 0.5) * dLon, lat: (r - (rows - 1) / 2) * dLon, src: images[(c * 3 + r * 5) % images.length] ?? \"\" });\n    }\n  }\n\n  useEffect(() => {\n    openRef.current = open;\n    if (open !== null) closeBtn.current?.focus();\n  }, [open]);\n\n  useEffect(() => {\n    const el = root.current!;\n    const v = view.current;\n    const reduce = matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    let raf = 0;\n    let last = performance.now();\n    let visible = true;\n    let stopped = false;\n    const shown: boolean[] = [];\n\n    const frame = (now: number) => {\n      // Observer callbacks can outlive cleanup; never touch the DOM after unmount.\n      const sphereEl = sphere.current;\n      if (stopped || !sphereEl) {\n        raf = 0;\n        return;\n      }\n      const dt = Math.min(0.05, (now - last) / 1000);\n      last = now;\n      if (!v.drag) {\n        v.yaw += v.vYaw;\n        v.pitch += v.vPitch;\n        v.vYaw *= 0.93;\n        v.vPitch *= 0.93;\n        if (!reduce && !v.hover && openRef.current === null && Math.abs(v.vYaw) < 0.05) v.yaw -= autoRotate * dt;\n        // Spring the pitch back inside its limits.\n        const lim = Math.max(-maxPitch, Math.min(maxPitch, v.pitch));\n        v.pitch += (lim - v.pitch) * 0.15;\n      }\n      sphereEl.style.transform = `translateZ(${radius}px) rotateX(${v.pitch}deg) rotateY(${v.yaw}deg)`;\n      const sp = Math.sin(v.pitch * toRad);\n      const cp = Math.cos(v.pitch * toRad);\n      for (let i = 0; i < tiles.length; i++) {\n        const t = tiles[i];\n        const el = tileEls.current[i];\n        if (!el) continue;\n        // How directly the tile faces the camera (1 = dead ahead, <0 = behind).\n        const facing = Math.cos(t.lat * toRad) * Math.cos((t.lon + v.yaw) * toRad) * cp - Math.sin(t.lat * toRad) * sp;\n        const on = facing > 0.2;\n        if (on !== shown[i]) {\n          shown[i] = on;\n          el.style.visibility = on ? \"visible\" : \"hidden\";\n        }\n        if (on) el.style.opacity = String(Math.min(1, (facing - 0.2) * 2.2));\n      }\n      raf = visible ? requestAnimationFrame(frame) : 0;\n    };\n    const start = () => {\n      if (!raf && visible && !stopped) {\n        last = performance.now();\n        raf = requestAnimationFrame(frame);\n      }\n    };\n    const io = new IntersectionObserver(([e]) => {\n      visible = e.isIntersecting;\n      start();\n    });\n    io.observe(el);\n    start();\n    return () => {\n      stopped = true;\n      cancelAnimationFrame(raf);\n      io.disconnect();\n    };\n    // tiles is derived from the props below.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [radius, columns, rows, autoRotate, maxPitch, images]);\n\n  const frontTile = () => {\n    const v = view.current;\n    let best = 0;\n    let bestScore = -Infinity;\n    tiles.forEach((t, i) => {\n      const s = Math.cos((t.lon + v.yaw) * toRad) * Math.cos((t.lat + v.pitch) * toRad);\n      if (s > bestScore) {\n        bestScore = s;\n        best = i;\n      }\n    });\n    return best;\n  };\n\n  const close = () => {\n    setOpen(null);\n    root.current?.focus();\n  };\n\n  return (\n    <div\n      ref={root}\n      role=\"region\"\n      aria-roledescription=\"gallery\"\n      aria-label=\"Dome gallery. Drag or use arrow keys to look around, Enter to enlarge the photo in front.\"\n      tabIndex={0}\n      onKeyDown={(e) => {\n        const v = view.current;\n        if (open !== null) {\n          if (e.key === \"Escape\") close();\n          return;\n        }\n        if (e.key === \"ArrowLeft\") v.vYaw = dLon * 0.07;\n        else if (e.key === \"ArrowRight\") v.vYaw = -dLon * 0.07;\n        else if (e.key === \"ArrowUp\") v.vPitch = -dLon * 0.05;\n        else if (e.key === \"ArrowDown\") v.vPitch = dLon * 0.05;\n        else if (e.key === \"Enter\" || e.key === \" \") setOpen(frontTile());\n        else return;\n        e.preventDefault();\n      }}\n      onPointerEnter={() => (view.current.hover = true)}\n      onPointerLeave={() => (view.current.hover = false)}\n      onPointerDown={(e) => {\n        if (open !== null) return;\n        const tile = (e.target as HTMLElement).closest<HTMLElement>(\"[data-tile]\");\n        e.currentTarget.setPointerCapture(e.pointerId);\n        view.current.drag = { x: e.clientX, y: e.clientY, lx: e.clientX, ly: e.clientY, moved: false, tile: tile ? Number(tile.dataset.tile) : -1 };\n        view.current.vYaw = view.current.vPitch = 0;\n      }}\n      onPointerMove={(e) => {\n        const v = view.current;\n        const d = v.drag;\n        if (!d) return;\n        const dx = e.clientX - d.lx;\n        const dy = e.clientY - d.ly;\n        d.lx = e.clientX;\n        d.ly = e.clientY;\n        if (Math.hypot(e.clientX - d.x, e.clientY - d.y) > 5) d.moved = true;\n        v.yaw -= dx * dragSensitivity;\n        v.pitch = Math.max(-maxPitch - 8, Math.min(maxPitch + 8, v.pitch + dy * dragSensitivity));\n        v.vYaw = -dx * dragSensitivity;\n        v.vPitch = dy * dragSensitivity * 0.5;\n      }}\n      onPointerUp={() => {\n        const d = view.current.drag;\n        view.current.drag = null;\n        if (d && !d.moved && d.tile >= 0) setOpen(d.tile);\n      }}\n      onPointerCancel={() => (view.current.drag = null)}\n      className={`relative size-full cursor-grab touch-none select-none overflow-hidden outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring active:cursor-grabbing ${className ?? \"\"}`}\n    >\n      <div\n        className=\"absolute inset-0\"\n        style={{\n          perspective: radius,\n          maskImage: \"radial-gradient(ellipse at center, #000 40%, transparent 95%)\",\n          WebkitMaskImage: \"radial-gradient(ellipse at center, #000 40%, transparent 95%)\",\n        }}\n      >\n        <div ref={sphere} className=\"absolute left-1/2 top-1/2\" style={{ transformStyle: \"preserve-3d\", transform: `translateZ(${radius}px)` }}>\n          {tiles.map((t, i) => (\n            <div\n              key={i}\n              data-tile={i}\n              ref={(el) => {\n                tileEls.current[i] = el;\n              }}\n              className=\"absolute overflow-hidden bg-muted\"\n              style={{\n                width: size,\n                height: size,\n                left: -size / 2,\n                top: -size / 2,\n                borderRadius: tileRadius,\n                backfaceVisibility: \"hidden\",\n                visibility: \"hidden\",\n                transform: `rotateY(${t.lon}deg) rotateX(${t.lat}deg) translateZ(${-radius}px)`,\n              }}\n            >\n              <img src={t.src} alt=\"\" draggable={false} loading=\"lazy\" className=\"pointer-events-none size-full object-cover\" />\n            </div>\n          ))}\n        </div>\n      </div>\n\n      <AnimatePresence>\n        {open !== null && (\n          <motion.div\n            className=\"absolute inset-0 z-10 grid cursor-zoom-out place-items-center bg-background/60 p-8 backdrop-blur-md\"\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            exit={{ opacity: 0 }}\n            onClick={close}\n            role=\"dialog\"\n            aria-modal=\"true\"\n            aria-label=\"Enlarged photo\"\n          >\n            <motion.img\n              src={tiles[open]?.src}\n              alt=\"\"\n              className=\"max-h-full max-w-full rounded-2xl object-cover shadow-2xl\"\n              style={{ width: Math.min(460, radius), aspectRatio: \"1\" }}\n              initial={{ scale: 0.4, rotateX: 20, opacity: 0 }}\n              animate={{ scale: 1, rotateX: 0, opacity: 1 }}\n              exit={{ scale: 0.6, opacity: 0 }}\n              transition={{ type: \"spring\", stiffness: 260, damping: 24 }}\n            />\n            <button\n              ref={closeBtn}\n              type=\"button\"\n              aria-label=\"Close\"\n              onClick={close}\n              className=\"absolute right-4 top-4 grid size-10 place-items-center rounded-full border border-border bg-card text-foreground outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring\"\n            >\n              <X className=\"size-5\" aria-hidden />\n            </button>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n"}]}