{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"carousel","type":"registry:ui","title":"Carousel","description":"A swipeable carousel with momentum snapping, a focused center slide and screen reader announcements.","dependencies":["motion"],"registryDependencies":["https://ui.mekaigames.com/r/theme.json"],"files":[{"path":"components/ui/carousel.tsx","type":"registry:ui","content":"\"use client\";\n\nimport {\n  animate,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n  type MotionValue,\n  type PanInfo,\n} from \"motion/react\";\nimport { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from \"react\";\n\nexport type CarouselItem = {\n  id?: string;\n  /** Image URL, shown as a cover. */\n  src?: string;\n  alt?: string;\n  /** Any slide content. Takes priority over src. */\n  content?: ReactNode;\n  /** Short name used in the slide's accessible label and announcements. */\n  label?: string;\n};\n\ntype CarouselProps = {\n  items: CarouselItem[];\n  index?: number;\n  defaultIndex?: number;\n  onIndexChange?: (index: number) => void;\n  /** Slide width as a fraction of the viewport, 0.4 to 1. Neighbors peek in the rest. */\n  slideWidth?: number;\n  gap?: number;\n  aspectRatio?: string;\n  /** Wraps from the last slide back to the first, and the other way round. */\n  loop?: boolean;\n  /** Milliseconds per slide. Pauses on hover, focus and drag. */\n  autoplay?: number | false;\n  showArrows?: boolean;\n  showDots?: boolean;\n  /** Scales the active slide up and fades its neighbors. */\n  focusEffect?: boolean;\n  /** Accessible name of the carousel. */\n  label?: string;\n  /** Color of the active dot. */\n  color?: string;\n  className?: string;\n};\n\nconst SPRING = { type: \"spring\" as const, stiffness: 300, damping: 34, mass: 0.9 };\n\nfunction Media({ item }: { item: CarouselItem }) {\n  if (item.content !== undefined) return <>{item.content}</>;\n  if (item.src) {\n    return (\n      <span\n        role=\"img\"\n        aria-label={item.alt ?? \"\"}\n        className=\"block size-full bg-cover bg-center\"\n        style={{ backgroundImage: `url(\"${item.src}\")` }}\n      />\n    );\n  }\n  return null;\n}\n\nfunction Slide({\n  item,\n  i,\n  count,\n  x,\n  step,\n  active,\n  aspectRatio,\n  focusEffect,\n  reduce,\n  onPick,\n}: {\n  item: CarouselItem;\n  i: number;\n  count: number;\n  x: MotionValue<number>;\n  step: number;\n  active: number;\n  aspectRatio: string;\n  focusEffect: boolean;\n  reduce: boolean;\n  onPick: (i: number) => void;\n}) {\n  // 0 when this slide sits in the center, 1 once it is a full slide away.\n  const distance = useTransform(x, (v) => (step > 0 ? Math.min(1, Math.abs(-v / step - i)) : i === active ? 0 : 1));\n  const scale = useTransform(distance, [0, 1], [1, focusEffect && !reduce ? 0.86 : 1]);\n  const opacity = useTransform(distance, [0, 1], [1, focusEffect ? 0.42 : 1]);\n  const isActive = i === active;\n\n  return (\n    <motion.div\n      role=\"group\"\n      aria-roledescription=\"slide\"\n      aria-label={`${i + 1} of ${count}${item.label ? `: ${item.label}` : \"\"}`}\n      onClick={() => onPick(i)}\n      className={`relative shrink-0 overflow-hidden rounded-3xl bg-ink-800 ring-1 ring-inset ring-white/5 ${isActive ? \"\" : \"cursor-pointer\"}`}\n      // The track is padded to the slide width, so 100% of its content box is exactly one slide.\n      style={{ flexBasis: \"100%\", aspectRatio, scale, opacity }}\n    >\n      <div className=\"size-full\" inert={!isActive}>\n        <Media item={item} />\n      </div>\n    </motion.div>\n  );\n}\n\nexport function Carousel({\n  items,\n  index,\n  defaultIndex = 0,\n  onIndexChange,\n  slideWidth = 0.78,\n  gap = 16,\n  aspectRatio = \"16 / 10\",\n  loop = false,\n  autoplay = false,\n  showArrows = true,\n  showDots = true,\n  focusEffect = true,\n  label = \"Gallery\",\n  color = \"#ff784f\",\n  className = \"\",\n}: CarouselProps) {\n  const autoId = useId();\n  const reduce = Boolean(useReducedMotion());\n  const count = items.length;\n  const ratio = Math.max(0.4, Math.min(1, slideWidth));\n  const [inner, setInner] = useState(defaultIndex);\n  const active = Math.max(0, Math.min(count - 1, index ?? inner));\n\n  const viewport = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(0);\n  const step = width > 0 ? width * ratio + gap : 0;\n  const x = useMotionValue(0);\n  const fling = useRef(0);\n  const lastStep = useRef(0);\n  const dragged = useRef(false);\n\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [dragging, setDragging] = useState(false);\n  const [paused, setPaused] = useState(false);\n  const playing = Boolean(autoplay) && !paused && !hovered && !focused && !dragging && count > 1;\n\n  useEffect(() => {\n    const el = viewport.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  // Glide to the active slide. A resize jumps there instead of animating.\n  useEffect(() => {\n    const target = -active * step;\n    if (step !== lastStep.current || reduce) {\n      lastStep.current = step;\n      x.jump(target);\n      return;\n    }\n    const controls = animate(x, target, { ...SPRING, velocity: fling.current });\n    fling.current = 0;\n    return () => controls.stop();\n  }, [active, step, reduce, x]);\n\n  function go(i: number) {\n    const next = loop ? (i + count) % count : Math.max(0, Math.min(count - 1, i));\n    if (next === active) return;\n    if (index === undefined) setInner(next);\n    onIndexChange?.(next);\n  }\n\n  useEffect(() => {\n    if (!playing || !autoplay) return;\n    const timer = window.setTimeout(() => {\n      const next = active + 1 >= count ? 0 : active + 1;\n      if (index === undefined) setInner(next);\n      onIndexChange?.(next);\n    }, autoplay);\n    return () => window.clearTimeout(timer);\n  }, [playing, autoplay, active, count, index, onIndexChange]);\n\n  function onDragEnd(_: unknown, info: PanInfo) {\n    setDragging(false);\n    if (step <= 0) return;\n    const projected = x.get() + info.velocity.x * 0.22;\n    let target = Math.round(-projected / step);\n    // A short, deliberate swipe still moves one slide.\n    if (target === active && Math.abs(info.offset.x) > step * 0.12) target = active + (info.offset.x < 0 ? 1 : -1);\n    const wrapped = loop && (target > count - 1 || target < 0) ? (target < 0 ? count - 1 : 0) : Math.max(0, Math.min(count - 1, target));\n    if (wrapped === active) {\n      animate(x, -active * step, reduce ? { duration: 0 } : { ...SPRING, velocity: info.velocity.x });\n      return;\n    }\n    fling.current = wrapped === target ? info.velocity.x : 0;\n    go(wrapped);\n  }\n\n  function onKeyDown(e: KeyboardEvent<HTMLElement>) {\n    const tag = (e.target as HTMLElement).tagName;\n    if (tag === \"INPUT\" || tag === \"TEXTAREA\" || tag === \"SELECT\") return;\n    if (e.key === \"ArrowRight\") {\n      e.preventDefault();\n      go(active + 1);\n    } else if (e.key === \"ArrowLeft\") {\n      e.preventDefault();\n      go(active - 1);\n    }\n  }\n\n  const canPrev = loop || active > 0;\n  const canNext = loop || active < count - 1;\n  const current = items[active];\n  const arrow =\n    \"grid size-10 place-items-center rounded-full border border-ink-600 bg-ink-900/80 text-bone backdrop-blur transition-colors hover:border-ember/60 disabled:pointer-events-none disabled:opacity-30\";\n\n  return (\n    <section\n      aria-roledescription=\"carousel\"\n      aria-label={label}\n      onKeyDown={onKeyDown}\n      onPointerEnter={(e) => {\n        if (e.pointerType === \"mouse\") setHovered(true);\n      }}\n      onPointerLeave={() => setHovered(false)}\n      onFocus={() => setFocused(true)}\n      onBlur={(e) => {\n        if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(false);\n      }}\n      className={`relative w-full ${className}`}\n    >\n      <div ref={viewport} className=\"overflow-hidden\">\n        <motion.div\n          id={`${autoId}-track`}\n          className=\"flex cursor-grab touch-pan-y select-none active:cursor-grabbing\"\n          style={{ x, gap, paddingInline: `${((1 - ratio) / 2) * 100}%` }}\n          drag={count > 1 ? \"x\" : false}\n          dragConstraints={{ left: -(count - 1) * step, right: 0 }}\n          dragElastic={0.14}\n          dragMomentum={false}\n          onPointerDownCapture={() => {\n            dragged.current = false;\n          }}\n          onDragStart={() => {\n            dragged.current = true;\n            setDragging(true);\n          }}\n          onDragEnd={onDragEnd}\n        >\n          {items.map((item, i) => (\n            <Slide\n              key={item.id ?? i}\n              item={item}\n              i={i}\n              count={count}\n              x={x}\n              step={step}\n              active={active}\n              aspectRatio={aspectRatio}\n              focusEffect={focusEffect}\n              reduce={reduce}\n              onPick={(n) => {\n                if (!dragged.current) go(n);\n              }}\n            />\n          ))}\n        </motion.div>\n      </div>\n\n      {showArrows || showDots || autoplay ? (\n        <div className=\"mt-4 flex items-center justify-center gap-3\">\n          {showArrows ? (\n            <button type=\"button\" className={arrow} onClick={() => go(active - 1)} disabled={!canPrev} aria-controls={`${autoId}-track`} aria-label=\"Previous slide\">\n              <svg viewBox=\"0 0 16 16\" className=\"size-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.8} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n                <path d=\"M10 3.5 5.5 8l4.5 4.5\" />\n              </svg>\n            </button>\n          ) : null}\n          {showDots ? (\n            <div className=\"flex items-center gap-1.5\">\n              {items.map((item, i) => (\n                <button\n                  key={item.id ?? i}\n                  type=\"button\"\n                  onClick={() => go(i)}\n                  aria-label={`Go to slide ${i + 1}${item.label ? `: ${item.label}` : \"\"}`}\n                  aria-current={i === active ? \"true\" : undefined}\n                  className=\"grid h-6 place-items-center px-0.5\"\n                >\n                  <motion.span\n                    className=\"block h-1.5 rounded-full\"\n                    initial={false}\n                    animate={{ width: i === active ? 22 : 6, backgroundColor: i === active ? color : \"#3d3631\" }}\n                    transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 420, damping: 30 }}\n                  />\n                </button>\n              ))}\n            </div>\n          ) : null}\n          {showArrows ? (\n            <button type=\"button\" className={arrow} onClick={() => go(active + 1)} disabled={!canNext} aria-controls={`${autoId}-track`} aria-label=\"Next slide\">\n              <svg viewBox=\"0 0 16 16\" className=\"size-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.8} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n                <path d=\"M6 3.5 10.5 8 6 12.5\" />\n              </svg>\n            </button>\n          ) : null}\n          {autoplay ? (\n            <button\n              type=\"button\"\n              className={`${arrow} ml-1 size-8`}\n              onClick={() => setPaused((p) => !p)}\n              aria-label={paused ? \"Start automatic slide show\" : \"Stop automatic slide show\"}\n            >\n              {paused ? (\n                <svg viewBox=\"0 0 16 16\" className=\"size-3.5\" fill=\"currentColor\" aria-hidden=\"true\">\n                  <path d=\"M5 3.5v9l7.5-4.5z\" />\n                </svg>\n              ) : (\n                <svg viewBox=\"0 0 16 16\" className=\"size-3.5\" fill=\"currentColor\" aria-hidden=\"true\">\n                  <rect x=\"4\" y=\"3.5\" width=\"2.6\" height=\"9\" rx=\"0.8\" />\n                  <rect x=\"9.4\" y=\"3.5\" width=\"2.6\" height=\"9\" rx=\"0.8\" />\n                </svg>\n              )}\n            </button>\n          ) : null}\n        </div>\n      ) : null}\n\n      {/* Announce slide changes, but stay quiet while the slide show runs on its own. */}\n      <div className=\"sr-only\" aria-live={playing ? \"off\" : \"polite\"} aria-atomic=\"true\">\n        {count ? `Slide ${active + 1} of ${count}${current?.label ? `: ${current.label}` : \"\"}` : \"\"}\n      </div>\n    </section>\n  );\n}\n"}]}