{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "carousel",
  "title": "Carousel",
  "description": "Slides on a native scroll-snap track, with keyboard steps, previous and next buttons, dots and an optional coverflow look.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/button"
  ],
  "files": [
    {
      "path": "registry/default/ui/carousel.tsx",
      "content": "\"use client\";\n\nimport { ChevronLeftIcon, ChevronRightIcon } from \"lucide-react\";\nimport {\n  Children,\n  createContext,\n  isValidElement,\n  useCallback,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type KeyboardEvent,\n  type Ref,\n} from \"react\";\n\nimport { cn } from \"@/registry/default/lib/utils\";\nimport { Button } from \"@/registry/default/ui/button\";\n\nfunction mergeRefs<T>(...refs: (Ref<T> | undefined)[]) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) ref.current = node;\n    }\n  };\n}\n\nfunction prefersReducedMotion() {\n  return window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches === true;\n}\n\nconst clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);\n\n// How much of a slide has to be visible before it can become the active one.\nconst VISIBLE = 0.6;\n\ntype CarouselAlign = \"start\" | \"center\";\ntype CarouselVariant = \"default\" | \"coverflow\";\n\ninterface CarouselApi {\n  /** The active slide. */\n  index: number;\n  /** How many slides there are. */\n  count: number;\n  /** Scrolls to a slide. */\n  scrollTo: (index: number) => void;\n  next: () => void;\n  previous: () => void;\n  canPrevious: boolean;\n  canNext: boolean;\n}\n\ninterface CarouselContextValue extends CarouselApi {\n  align: CarouselAlign;\n  variant: CarouselVariant;\n  setViewport: (node: HTMLDivElement | null) => void;\n  setCount: (count: number) => void;\n}\n\nconst CarouselContext = createContext<CarouselContextValue | null>(null);\nconst CarouselSlideContext = createContext<{ index: number; count: number } | null>(null);\n\nfunction useCarouselContext(part: string) {\n  const context = useContext(CarouselContext);\n  if (!context) throw new Error(`${part} has to be inside <Carousel>.`);\n  return context;\n}\n\n/**\n * The carousel's state and controls, for parts of your own inside `<Carousel>`.\n *\n * @example\n * const { index, count } = useCarousel();\n * return <p aria-hidden=\"true\">{index + 1} / {count}</p>;\n */\nfunction useCarousel(): CarouselApi {\n  const { index, count, scrollTo, next, previous, canPrevious, canNext } =\n    useCarouselContext(\"useCarousel\");\n  return { index, count, scrollTo, next, previous, canPrevious, canNext };\n}\n\n/**\n * Where a slide is and whether it is the active one, from inside a\n * `CarouselItem`. Handy to play a video only on the active slide.\n *\n * @example\n * const { active } = useCarouselItem();\n * return active ? <video autoPlay muted src=\"…\" /> : <img src=\"…\" alt=\"…\" />;\n */\nfunction useCarouselItem() {\n  const context = useCarouselContext(\"useCarouselItem\");\n  const slide = useContext(CarouselSlideContext);\n  if (!slide) throw new Error(\"useCarouselItem has to be inside <CarouselContent>.\");\n  return { index: slide.index, active: slide.index === context.index };\n}\n\n/**\n * Of the slides at least 60% visible, the one nearest the alignment point:\n * the viewport's left edge for \"start\", its middle for \"center\".\n */\nfunction mostVisible(\n  slides: HTMLElement[],\n  ratios: Map<Element, number>,\n  viewport: HTMLElement,\n  align: CarouselAlign\n) {\n  const candidates = slides\n    .map((slide, index) => ({ slide, index }))\n    .filter(({ slide }) => (ratios.get(slide) ?? 0) >= VISIBLE);\n  if (candidates.length <= 1) return candidates[0]?.index ?? -1;\n  const box = viewport.getBoundingClientRect();\n  const anchor = align === \"center\" ? box.left + box.width / 2 : box.left;\n  let best = -1;\n  let distance = Infinity;\n  for (const { slide, index } of candidates) {\n    const rect = slide.getBoundingClientRect();\n    const point = align === \"center\" ? rect.left + rect.width / 2 : rect.left;\n    const gap = Math.abs(point - anchor);\n    if (gap < distance) {\n      distance = gap;\n      best = index;\n    }\n  }\n  return best;\n}\n\ninterface CarouselProps extends ComponentProps<\"div\"> {\n  /** The active slide, for a controlled carousel. */\n  index?: number;\n  /** The slide it starts on. */\n  defaultIndex?: number;\n  /** Called when the active slide changes, by scrolling, swiping or the controls. */\n  onIndexChange?: (index: number) => void;\n  /** Previous on the first slide goes to the last one, and next on the last to the first. */\n  loop?: boolean;\n  /** Where slides come to rest: the left edge or the middle. */\n  align?: CarouselAlign;\n  /** \"coverflow\" centres the active slide and shrinks and dims the others. */\n  variant?: CarouselVariant;\n}\n\n/**\n * A row of slides on a native CSS scroll-snap track, so swiping, trackpads,\n * the mouse wheel and scroll bars all work as they do anywhere else, with no\n * dependency. The active slide is the one most in view (IntersectionObserver,\n * no scroll listener), shown in `data-active` and through `useCarousel`.\n *\n * It is a region named \"Carousel\" (`aria-label`) with each slide a group\n * named \"2 of 5\". The track takes focus and moves with the arrow keys, Home\n * and End; the previous/next buttons and dots are real buttons. With\n * `prefers-reduced-motion` the controls jump instead of gliding and the\n * coverflow effect does not animate.\n *\n * @example\n * <Carousel aria-label=\"Featured work\" loop>\n *   <CarouselContent trackClassName=\"gap-4\">\n *     <CarouselItem className=\"md:basis-1/3\">…</CarouselItem>\n *     <CarouselItem className=\"md:basis-1/3\">…</CarouselItem>\n *   </CarouselContent>\n *   <div className=\"mt-4 flex items-center justify-between\">\n *     <CarouselPrevious />\n *     <CarouselDots />\n *     <CarouselNext />\n *   </div>\n * </Carousel>\n */\nfunction Carousel({\n  index: indexProp,\n  defaultIndex = 0,\n  onIndexChange,\n  loop = false,\n  align = \"start\",\n  variant = \"default\",\n  \"aria-label\": label = \"Carousel\",\n  className,\n  ...props\n}: CarouselProps) {\n  const [viewport, setViewport] = useState<HTMLDivElement | null>(null);\n  const [count, setCount] = useState(0);\n  const [internal, setInternal] = useState(defaultIndex);\n  const raw = indexProp ?? internal;\n  const current = count > 0 ? clamp(raw, 0, count - 1) : Math.max(0, raw);\n  const alignment: CarouselAlign = variant === \"coverflow\" ? \"center\" : align;\n\n  const onIndexChangeRef = useRef(onIndexChange);\n  useEffect(() => {\n    onIndexChangeRef.current = onIndexChange;\n  });\n\n  // The slide the scroll position shows, or is gliding to.\n  const shown = useRef(0);\n  // While the controls glide to a slide, the slides passed on the way are ignored.\n  const pending = useRef<number | null>(null);\n  const pendingTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const settled = useRef(false);\n\n  const slides = useCallback(\n    () =>\n      viewport\n        ? Array.from(viewport.querySelectorAll<HTMLElement>(\"[data-slot=carousel-item]\")).filter(\n            (slide) => slide.closest(\"[data-slot=carousel-content]\") === viewport\n          )\n        : [],\n    [viewport]\n  );\n\n  const glideTo = useCallback(\n    (target: number, instant: boolean) => {\n      const slide = slides()[target];\n      if (!viewport || !slide) return;\n      pending.current = target;\n      clearTimeout(pendingTimer.current);\n      pendingTimer.current = setTimeout(() => {\n        pending.current = null;\n      }, 1000);\n      const left =\n        alignment === \"center\"\n          ? slide.offsetLeft - (viewport.clientWidth - slide.offsetWidth) / 2\n          : slide.offsetLeft;\n      viewport.scrollTo({\n        left,\n        behavior: instant || prefersReducedMotion() ? \"instant\" : \"smooth\",\n      });\n    },\n    [slides, viewport, alignment]\n  );\n\n  useEffect(() => () => clearTimeout(pendingTimer.current), []);\n\n  const scrollTo = useCallback(\n    (target: number) => {\n      if (count === 0) return;\n      const next = loop ? ((target % count) + count) % count : clamp(target, 0, count - 1);\n      shown.current = next;\n      glideTo(next, false);\n      setInternal(next);\n      if (next !== current) onIndexChangeRef.current?.(next);\n    },\n    [count, loop, glideTo, current]\n  );\n\n  // Follow `index` when the parent changes it, and start on `defaultIndex`.\n  useEffect(() => {\n    if (!viewport || count === 0) return;\n    const first = !settled.current;\n    settled.current = true;\n    if (current === shown.current) return;\n    shown.current = current;\n    glideTo(current, first);\n  }, [current, viewport, count, glideTo]);\n\n  // The active slide follows the scroll position.\n  useEffect(() => {\n    if (!viewport || count === 0 || typeof IntersectionObserver === \"undefined\") return;\n    const elements = slides();\n    const ratios = new Map<Element, number>();\n    const observer = new IntersectionObserver(\n      (entries) => {\n        for (const entry of entries) ratios.set(entry.target, entry.intersectionRatio);\n        const best = mostVisible(elements, ratios, viewport, alignment);\n        if (best < 0) return;\n        if (pending.current !== null) {\n          if (best !== pending.current) return;\n          pending.current = null;\n        }\n        if (best === shown.current) return;\n        shown.current = best;\n        setInternal(best);\n        onIndexChangeRef.current?.(best);\n      },\n      { root: viewport, threshold: [0, VISIBLE, 1] }\n    );\n    for (const element of elements) observer.observe(element);\n    // A swipe or a wheel takes over from a glide in progress.\n    const release = () => {\n      pending.current = null;\n    };\n    viewport.addEventListener(\"pointerdown\", release, { passive: true });\n    viewport.addEventListener(\"wheel\", release, { passive: true });\n    viewport.addEventListener(\"touchstart\", release, { passive: true });\n    return () => {\n      observer.disconnect();\n      viewport.removeEventListener(\"pointerdown\", release);\n      viewport.removeEventListener(\"wheel\", release);\n      viewport.removeEventListener(\"touchstart\", release);\n    };\n  }, [viewport, count, slides, alignment]);\n\n  const canPrevious = count > 1 && (loop || current > 0);\n  const canNext = count > 1 && (loop || current < count - 1);\n\n  const context = useMemo<CarouselContextValue>(\n    () => ({\n      index: current,\n      count,\n      scrollTo,\n      next: () => scrollTo(current + 1),\n      previous: () => scrollTo(current - 1),\n      canPrevious,\n      canNext,\n      align: alignment,\n      variant,\n      setViewport,\n      setCount,\n    }),\n    [current, count, scrollTo, canPrevious, canNext, alignment, variant]\n  );\n\n  return (\n    <CarouselContext.Provider value={context}>\n      <div\n        role=\"region\"\n        aria-roledescription=\"carousel\"\n        aria-label={label}\n        data-slot=\"carousel\"\n        data-variant={variant}\n        data-align={alignment}\n        className={cn(\"relative\", className)}\n        {...props}\n      />\n    </CarouselContext.Provider>\n  );\n}\n\ninterface CarouselContentProps extends ComponentProps<\"div\"> {\n  /** Classes for the flex row that holds the slides, e.g. a `gap-*`. */\n  trackClassName?: string;\n}\n\n/**\n * The scrolling viewport and the row of slides. Put the `CarouselItem`s\n * directly inside it. It takes keyboard focus: ArrowLeft and ArrowRight\n * move one slide, Home and End go to the first and last. The scroll bar is\n * hidden; swiping, the wheel and the keys still scroll it.\n */\nfunction CarouselContent({\n  className,\n  trackClassName,\n  children,\n  onKeyDown,\n  ref,\n  ...props\n}: CarouselContentProps) {\n  const { setViewport, setCount, scrollTo, index, count, variant } =\n    useCarouselContext(\"CarouselContent\");\n  const slides = Children.toArray(children).filter(isValidElement);\n  const total = slides.length;\n  useEffect(() => {\n    setCount(total);\n  }, [total, setCount]);\n  const mergedRef = useMemo(() => mergeRefs(ref, setViewport), [ref, setViewport]);\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event);\n    // Keys inside a slide (a form field, a link) keep their own meaning.\n    if (event.defaultPrevented || event.target !== event.currentTarget) return;\n    const target =\n      event.key === \"ArrowLeft\"\n        ? index - 1\n        : event.key === \"ArrowRight\"\n          ? index + 1\n          : event.key === \"Home\"\n            ? 0\n            : event.key === \"End\"\n              ? count - 1\n              : null;\n    if (target === null) return;\n    event.preventDefault();\n    scrollTo(target);\n  };\n\n  return (\n    // eslint-disable-next-line jsx-a11y/no-static-element-interactions -- the keys add slide steps to a scroll region that already scrolls with them\n    <div\n      ref={mergedRef}\n      data-slot=\"carousel-content\"\n      // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- a scrolling region has to be reachable from the keyboard\n      tabIndex={0}\n      onKeyDown={handleKeyDown}\n      className={cn(\n        \"relative snap-x snap-mandatory overflow-x-auto overscroll-x-contain rounded-md motion-safe:scroll-smooth\",\n        \"[scrollbar-width:none] [&::-webkit-scrollbar]:hidden\",\n        \"focus-visible:ring-ring/50 outline-none focus-visible:ring-[3px]\",\n        className\n      )}\n      {...props}\n    >\n      <div\n        data-slot=\"carousel-track\"\n        className={cn(\n          \"flex\",\n          // Room either side so the first and last slides can reach the middle.\n          variant === \"coverflow\" &&\n            \"before:shrink-0 before:basis-[20%] after:shrink-0 after:basis-[20%]\",\n          trackClassName\n        )}\n      >\n        {slides.map((slide, position) => (\n          <CarouselSlideContext.Provider\n            key={slide.key ?? position}\n            value={{ index: position, count: total }}\n          >\n            {slide}\n          </CarouselSlideContext.Provider>\n        ))}\n      </div>\n    </div>\n  );\n}\n\ninterface CarouselItemProps extends ComponentProps<\"div\"> {\n  /** Accessible name of the slide. Defaults to \"2 of 5\". */\n  slideLabel?: (index: number, count: number) => string;\n}\n\n/**\n * One slide. It fills the viewport by default; set its size with a `basis-*`\n * class (`md:basis-1/3`) to show several at once. `data-active` marks the\n * active slide.\n */\nfunction CarouselItem({\n  slideLabel = (index, count) => `${index + 1} of ${count}`,\n  className,\n  ...props\n}: CarouselItemProps) {\n  const { align, variant } = useCarouselContext(\"CarouselItem\");\n  const slide = useContext(CarouselSlideContext);\n  const { active } = useCarouselItem();\n  const index = slide?.index ?? 0;\n  return (\n    <div\n      role=\"group\"\n      aria-roledescription=\"slide\"\n      aria-label={slideLabel(index, slide?.count ?? 0)}\n      data-slot=\"carousel-item\"\n      data-active={active}\n      className={cn(\n        \"min-w-0 shrink-0 grow-0 basis-full\",\n        align === \"center\" ? \"snap-center\" : \"snap-start\",\n        variant === \"coverflow\" &&\n          \"basis-3/5 transition-[transform,opacity] duration-500 ease-out data-[active=false]:scale-[0.85] data-[active=false]:opacity-50 motion-reduce:transition-none\",\n        className\n      )}\n      {...props}\n    />\n  );\n}\n\ninterface CarouselButtonProps extends ComponentProps<typeof Button> {\n  /** Accessible name of the button. */\n  label?: string;\n}\n\n/** Goes back one slide. Disabled on the first slide unless the carousel loops. */\nfunction CarouselPrevious({\n  label = \"Previous slide\",\n  className,\n  onClick,\n  children,\n  ...props\n}: CarouselButtonProps) {\n  const { previous, canPrevious } = useCarouselContext(\"CarouselPrevious\");\n  return (\n    <Button\n      data-slot=\"carousel-previous\"\n      variant=\"outline\"\n      size=\"icon\"\n      aria-label={label}\n      disabled={!canPrevious}\n      className={cn(\"rounded-full\", className)}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) previous();\n      }}\n      {...props}\n    >\n      {children ?? <ChevronLeftIcon aria-hidden=\"true\" />}\n    </Button>\n  );\n}\n\n/** Goes forward one slide. Disabled on the last slide unless the carousel loops. */\nfunction CarouselNext({\n  label = \"Next slide\",\n  className,\n  onClick,\n  children,\n  ...props\n}: CarouselButtonProps) {\n  const { next, canNext } = useCarouselContext(\"CarouselNext\");\n  return (\n    <Button\n      data-slot=\"carousel-next\"\n      variant=\"outline\"\n      size=\"icon\"\n      aria-label={label}\n      disabled={!canNext}\n      className={cn(\"rounded-full\", className)}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) next();\n      }}\n      {...props}\n    >\n      {children ?? <ChevronRightIcon aria-hidden=\"true\" />}\n    </Button>\n  );\n}\n\ninterface CarouselDotsProps extends ComponentProps<\"div\"> {\n  /** Accessible name of the group of dots. */\n  label?: string;\n  /** Accessible name of each dot. Defaults to \"Go to slide 2\". */\n  dotLabel?: (index: number, count: number) => string;\n}\n\n/** One button per slide; the active one has `aria-current` and `data-active`. */\nfunction CarouselDots({\n  label = \"Choose a slide\",\n  dotLabel = (index) => `Go to slide ${index + 1}`,\n  className,\n  ...props\n}: CarouselDotsProps) {\n  const { index, count, scrollTo } = useCarouselContext(\"CarouselDots\");\n  return (\n    <div\n      role=\"group\"\n      aria-label={label}\n      data-slot=\"carousel-dots\"\n      className={cn(\"flex items-center justify-center gap-1\", className)}\n      {...props}\n    >\n      {Array.from({ length: count }, (_, dot) => (\n        <button\n          key={dot}\n          type=\"button\"\n          data-slot=\"carousel-dot\"\n          data-active={dot === index}\n          aria-label={dotLabel(dot, count)}\n          aria-current={dot === index ? \"true\" : undefined}\n          onClick={() => scrollTo(dot)}\n          className=\"group/dot focus-visible:ring-ring/50 grid size-6 cursor-pointer place-items-center rounded-full outline-none focus-visible:ring-[3px]\"\n        >\n          <span\n            aria-hidden=\"true\"\n            data-slot=\"carousel-dot-indicator\"\n            className=\"bg-foreground/25 group-data-[active=true]/dot:bg-foreground block size-2 rounded-full transition-colors motion-reduce:transition-none\"\n          />\n        </button>\n      ))}\n    </div>\n  );\n}\n\nexport {\n  Carousel,\n  CarouselContent,\n  CarouselDots,\n  CarouselItem,\n  CarouselNext,\n  CarouselPrevious,\n  useCarousel,\n  useCarouselItem,\n  type CarouselApi,\n  type CarouselContentProps,\n  type CarouselDotsProps,\n  type CarouselItemProps,\n  type CarouselProps,\n};\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}