{"name":"carousel","type":"registry:ui","files":[{"path":"carousel.tsx","type":"registry:ui","content":"\"use client\"\n\nimport * as React from \"react\"\nimport {\n  ChevronDown as ChevronDownIcon,\n  ChevronLeft as ChevronLeftIcon,\n  ChevronRight as ChevronRightIcon,\n  ChevronUp as ChevronUpIcon,\n} from \"honestui/icons\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\n\ntype CarouselOrientation = \"horizontal\" | \"vertical\"\n\ntype CarouselApi = {\n  /** Index of the slide aligned to the start edge. */\n  index: number\n  /** Number of slides. */\n  count: number\n  canScrollPrev: boolean\n  canScrollNext: boolean\n  scrollTo: (index: number) => void\n  scrollPrev: () => void\n  scrollNext: () => void\n}\n\ntype CarouselContextValue = CarouselApi & {\n  orientation: CarouselOrientation\n  viewportRef: React.RefCallback<HTMLDivElement>\n  registerItem: (node: HTMLElement) => () => void\n  items: HTMLElement[]\n}\n\nconst CarouselContext = React.createContext<CarouselContextValue | null>(null)\n\nfunction useCarousel() {\n  const context = React.useContext(CarouselContext)\n  if (!context) {\n    throw new Error(\"useCarousel must be used within a <Carousel />\")\n  }\n  return context\n}\n\nfunction prefersReducedMotion() {\n  return (\n    typeof window !== \"undefined\" &&\n    window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches\n  )\n}\n\ntype CarouselProps = Omit<React.ComponentProps<\"div\">, \"aria-label\"> & {\n  /** Names the carousel for assistive technology, such as \"Featured templates\". */\n  \"aria-label\": string\n  orientation?: CarouselOrientation\n  /** Wrap from the last slide to the first, and back, with the buttons and keys. */\n  loop?: boolean\n  /** Receives the carousel API whenever its state changes. */\n  setApi?: (api: CarouselApi) => void\n  onIndexChange?: (index: number) => void\n}\n\nfunction Carousel({\n  orientation = \"horizontal\",\n  loop = false,\n  setApi,\n  onIndexChange,\n  className,\n  children,\n  onKeyDown,\n  ...props\n}: CarouselProps) {\n  const [viewport, setViewport] = React.useState<HTMLDivElement | null>(null)\n  const [items, setItems] = React.useState<HTMLElement[]>([])\n  const [index, setIndex] = React.useState(0)\n  const [edges, setEdges] = React.useState({ atStart: true, atEnd: true })\n  const vertical = orientation === \"vertical\"\n\n  // Items register in document order so labels and dots stay correct when\n  // slides are added or removed.\n  const registerItem = React.useCallback((node: HTMLElement) => {\n    setItems((current) =>\n      [...current, node].sort((a, b) =>\n        a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1\n      )\n    )\n    return () => setItems((current) => current.filter((item) => item !== node))\n  }, [])\n\n  // Reads the scroll position once per frame. The active slide is the one\n  // whose start edge is closest to the viewport's start edge, which also\n  // works for several slides per view and for RTL, where scrollLeft is\n  // negative.\n  React.useEffect(() => {\n    if (!viewport) return\n    let frame = 0\n    const measure = () => {\n      frame = 0\n      const rtl = !vertical && getComputedStyle(viewport).direction === \"rtl\"\n      const scroll = vertical ? viewport.scrollTop : Math.abs(viewport.scrollLeft)\n      const max = vertical\n        ? viewport.scrollHeight - viewport.clientHeight\n        : viewport.scrollWidth - viewport.clientWidth\n      setEdges({ atStart: scroll <= 1, atEnd: scroll >= max - 1 })\n\n      if (items.length === 0) return\n      const box = viewport.getBoundingClientRect()\n      let closest = 0\n      let closestDistance = Infinity\n      items.forEach((item, itemIndex) => {\n        const rect = item.getBoundingClientRect()\n        const distance = vertical\n          ? Math.abs(rect.top - box.top)\n          : rtl\n            ? Math.abs(rect.right - box.right)\n            : Math.abs(rect.left - box.left)\n        if (distance < closestDistance) {\n          closestDistance = distance\n          closest = itemIndex\n        }\n      })\n      // At the end edge the last slide may never reach the start edge when\n      // several slides share the view, so the last one counts as active.\n      setIndex(scroll >= max - 1 && max > 0 ? items.length - 1 : closest)\n    }\n    const schedule = () => {\n      if (!frame) frame = requestAnimationFrame(measure)\n    }\n    measure()\n    viewport.addEventListener(\"scroll\", schedule, { passive: true })\n    const resizeObserver = new ResizeObserver(schedule)\n    resizeObserver.observe(viewport)\n    return () => {\n      cancelAnimationFrame(frame)\n      viewport.removeEventListener(\"scroll\", schedule)\n      resizeObserver.disconnect()\n    }\n  }, [viewport, items, vertical])\n\n  const scrollTo = React.useCallback(\n    (target: number) => {\n      if (!viewport || items.length === 0) return\n      const clamped = Math.max(0, Math.min(items.length - 1, target))\n      const item = items[clamped]\n      const box = viewport.getBoundingClientRect()\n      const rect = item.getBoundingClientRect()\n      const behavior: ScrollBehavior = prefersReducedMotion() ? \"auto\" : \"smooth\"\n      if (vertical) {\n        viewport.scrollBy({ top: rect.top - box.top, behavior })\n      } else {\n        const rtl = getComputedStyle(viewport).direction === \"rtl\"\n        viewport.scrollBy({\n          left: rtl ? rect.right - box.right : rect.left - box.left,\n          behavior,\n        })\n      }\n    },\n    [viewport, items, vertical]\n  )\n\n  const count = items.length\n  const canScrollPrev = loop ? count > 1 : !edges.atStart\n  const canScrollNext = loop ? count > 1 : !edges.atEnd\n\n  const scrollPrev = React.useCallback(() => {\n    if (loop && edges.atStart) scrollTo(count - 1)\n    else scrollTo(index - 1)\n  }, [loop, edges.atStart, scrollTo, count, index])\n\n  const scrollNext = React.useCallback(() => {\n    if (loop && edges.atEnd) scrollTo(0)\n    else scrollTo(index + 1)\n  }, [loop, edges.atEnd, scrollTo, index])\n\n  const api = React.useMemo<CarouselApi>(\n    () => ({ index, count, canScrollPrev, canScrollNext, scrollTo, scrollPrev, scrollNext }),\n    [index, count, canScrollPrev, canScrollNext, scrollTo, scrollPrev, scrollNext]\n  )\n\n  React.useEffect(() => {\n    setApi?.(api)\n  }, [api, setApi])\n\n  const lastReportedIndex = React.useRef(index)\n  React.useEffect(() => {\n    if (lastReportedIndex.current === index) return\n    lastReportedIndex.current = index\n    onIndexChange?.(index)\n  }, [index, onIndexChange])\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event)\n    if (event.defaultPrevented) return\n    // Typing in a field inside a slide keeps its own arrow keys.\n    const target = event.target as HTMLElement\n    if (target.closest(\"input, textarea, select, [contenteditable='true'], [role='slider']\")) {\n      return\n    }\n    const rtl = !vertical && getComputedStyle(event.currentTarget).direction === \"rtl\"\n    const prevKey = vertical ? \"ArrowUp\" : rtl ? \"ArrowRight\" : \"ArrowLeft\"\n    const nextKey = vertical ? \"ArrowDown\" : rtl ? \"ArrowLeft\" : \"ArrowRight\"\n    if (event.key === prevKey) {\n      event.preventDefault()\n      scrollPrev()\n    } else if (event.key === nextKey) {\n      event.preventDefault()\n      scrollNext()\n    }\n  }\n\n  return (\n    <CarouselContext.Provider\n      value={{ ...api, orientation, viewportRef: setViewport, registerItem, items }}\n    >\n      <div\n        role=\"region\"\n        aria-roledescription=\"carousel\"\n        data-slot=\"carousel\"\n        data-orientation={orientation}\n        className={cn(\"relative\", className)}\n        onKeyDown={handleKeyDown}\n        {...props}\n      >\n        {children}\n        {/* Announces the new position after a button, key, or swipe moves\n            the carousel. It is polite, so it waits for the user to pause. */}\n        <span data-slot=\"carousel-status\" aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n          {count > 0 ? `Slide ${index + 1} of ${count}` : \"\"}\n        </span>\n      </div>\n    </CarouselContext.Provider>\n  )\n}\n\nfunction CarouselContent({\n  className,\n  children,\n  ...props\n}: React.ComponentProps<\"div\">) {\n  const { viewportRef, orientation } = useCarousel()\n  const vertical = orientation === \"vertical\"\n\n  return (\n    <div\n      ref={viewportRef}\n      data-slot=\"carousel-content\"\n      data-orientation={orientation}\n      className={cn(\n        // Native scroll snapping does the paging, so touch, trackpad, and\n        // wheel gestures behave like the platform without a script.\n        // The scrollbar is hidden with !important because apps often style\n        // `* { scrollbar-width }` outside a cascade layer, which beats utilities.\n        \"flex gap-[var(--hui-carousel-gap,var(--hui-space-4))] overscroll-contain [scrollbar-width:none]! [&::-webkit-scrollbar]:hidden! motion-safe:scroll-smooth focus-visible:[outline:var(--hui-focus-ring)] focus-visible:outline-offset-[var(--hui-focus-ring-offset-accent)] rounded-[var(--hui-radius-2)]\",\n        vertical\n          ? \"h-full flex-col overflow-y-auto overflow-x-hidden snap-y snap-mandatory\"\n          : \"overflow-x-auto overflow-y-hidden snap-x snap-mandatory\",\n        className\n      )}\n      {...props}\n    >\n      {children}\n    </div>\n  )\n}\n\nfunction CarouselItem({\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: React.ComponentProps<\"div\">) {\n  const { registerItem, items, count } = useCarousel()\n  const [node, setNode] = React.useState<HTMLDivElement | null>(null)\n\n  React.useEffect(() => {\n    if (!node) return\n    return registerItem(node)\n  }, [node, registerItem])\n\n  const position = node ? items.indexOf(node) + 1 : 0\n\n  return (\n    <div\n      ref={setNode}\n      role=\"group\"\n      aria-roledescription=\"slide\"\n      aria-label={ariaLabel ?? (position > 0 ? `${position} of ${count}` : undefined)}\n      data-slot=\"carousel-item\"\n      className={cn(\"min-w-0 shrink-0 grow-0 basis-full snap-start\", className)}\n      {...props}\n    />\n  )\n}\n\ntype CarouselButtonProps = React.ComponentProps<typeof Button>\n\nfunction CarouselPrevious({\n  className,\n  variant = \"outline\",\n  size = \"icon-sm\",\n  onClick,\n  ...props\n}: CarouselButtonProps) {\n  const { orientation, canScrollPrev, scrollPrev } = useCarousel()\n\n  return (\n    <Button\n      data-slot=\"carousel-previous\"\n      variant={variant}\n      size={size}\n      disabled={!canScrollPrev}\n      aria-label=\"Previous slide\"\n      className={cn(\"rounded-full\", className)}\n      onClick={(event) => {\n        onClick?.(event)\n        if (!event.defaultPrevented) scrollPrev()\n      }}\n      {...props}\n    >\n      {orientation === \"vertical\" ? (\n        <ChevronUpIcon aria-hidden=\"true\" />\n      ) : (\n        <ChevronLeftIcon aria-hidden=\"true\" className=\"rtl:rotate-180\" />\n      )}\n    </Button>\n  )\n}\n\nfunction CarouselNext({\n  className,\n  variant = \"outline\",\n  size = \"icon-sm\",\n  onClick,\n  ...props\n}: CarouselButtonProps) {\n  const { orientation, canScrollNext, scrollNext } = useCarousel()\n\n  return (\n    <Button\n      data-slot=\"carousel-next\"\n      variant={variant}\n      size={size}\n      disabled={!canScrollNext}\n      aria-label=\"Next slide\"\n      className={cn(\"rounded-full\", className)}\n      onClick={(event) => {\n        onClick?.(event)\n        if (!event.defaultPrevented) scrollNext()\n      }}\n      {...props}\n    >\n      {orientation === \"vertical\" ? (\n        <ChevronDownIcon aria-hidden=\"true\" />\n      ) : (\n        <ChevronRightIcon aria-hidden=\"true\" className=\"rtl:rotate-180\" />\n      )}\n    </Button>\n  )\n}\n\nfunction CarouselDots({ className, ...props }: React.ComponentProps<\"div\">) {\n  const { count, index, scrollTo, orientation } = useCarousel()\n\n  return (\n    <div\n      data-slot=\"carousel-dots\"\n      className={cn(\n        \"flex items-center justify-center gap-[var(--hui-space-1)]\",\n        orientation === \"vertical\" && \"flex-col\",\n        className\n      )}\n      {...props}\n    >\n      {Array.from({ length: count }, (_, dotIndex) => {\n        const active = dotIndex === index\n        return (\n          <button\n            key={dotIndex}\n            type=\"button\"\n            data-slot=\"carousel-dot\"\n            data-active={active ? \"\" : undefined}\n            aria-label={`Go to slide ${dotIndex + 1}`}\n            aria-current={active ? \"true\" : undefined}\n            onClick={() => scrollTo(dotIndex)}\n            className=\"group relative inline-flex size-[var(--hui-space-5)] cursor-pointer items-center justify-center rounded-full border-0 bg-transparent p-0 outline-none focus-visible:[outline:var(--hui-focus-ring)] focus-visible:outline-offset-[-2px] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-6\"\n          >\n            <span\n              aria-hidden=\"true\"\n              className=\"block size-1.5 rounded-full bg-[var(--hui-color-foreground-base-tertiary)] motion-safe:[transition:background-color_var(--hui-duration-fast)_var(--hui-ease-out),width_var(--hui-duration-fast)_var(--hui-ease-out)] group-hover:bg-[var(--hui-color-foreground-base-secondary)] group-data-active:w-3.5 group-data-active:bg-[var(--hui-color-foreground-base-primary)] forced-colors:bg-[GrayText] forced-colors:group-data-active:bg-[Highlight]\"\n            />\n          </button>\n        )\n      })}\n    </div>\n  )\n}\n\nexport {\n  Carousel,\n  CarouselContent,\n  CarouselItem,\n  CarouselPrevious,\n  CarouselNext,\n  CarouselDots,\n  useCarousel,\n  type CarouselApi,\n  type CarouselProps,\n}\n","target":"components/ui/carousel.tsx"}],"dependencies":["honestui"],"registryDependencies":["https://www.honestui.com/r/button.json"]}