{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "carousel",
  "type": "registry:ui",
  "title": "Carousel",
  "description": "A row of cards the reader swipes through: today's updates, featured answers, the games to play next. On a phone it is the shape people already know from every feed; on a wide screen it shows several cards at once and two buttons page through the rest.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "data",
    "pattern"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/carousel.tsx",
      "target": "components/ui/patterns/carousel.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/carousel v1.0.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/carousel\n// What changed since: https://ds.interlace.tools/c/carousel#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Carousel\n *\n * A row of cards the reader swipes through: today's updates, featured\n * answers, the games to play next. On a phone it is the shape people already\n * know from every feed; on a wide screen it shows several cards at once and\n * two buttons page through the rest.\n *\n * ## How to use it\n *\n *   <Carousel aria-label=\"Featured answers\">\n *     <CarouselContent>\n *       {answers.map((a) => <CarouselItem key={a.id}><AnswerCard {...a} /></CarouselItem>)}\n *     </CarouselContent>\n *     <CarouselPrevious />\n *     <CarouselNext />\n *   </Carousel>\n *\n * The part names follow shadcn's carousel, so an app moving over finds them\n * where it expects. There is no carousel library underneath: the row is the\n * browser's own scroll with snap points, so touch, trackpad, wheel and the\n * keyboard all work as they do on any scrolling region, at the device's own\n * speed and friction.\n *\n * ## Content first\n *\n * Every card is in the server HTML, in order. Nothing rotates on\n * its own (WCAG 2.2.2), nothing is cloned to fake a loop, and no card is\n * hidden from a screen reader. The row is one tab stop that scrolls with the\n * arrow keys; Tab then walks through the links inside the cards, and the\n * browser brings each one into view as it takes focus. Each card is announced\n * as \"slide, 2 of 6\" inside a region announced as a carousel.\n *\n * ## Paging\n *\n * Previous and Next scroll by one view, and snap lands on the start of a\n * card. They switch off at either end and are not shown when every card fits, and they follow the reading\n * direction: in a right-to-left page Next moves left and the arrows turn\n * around. Under `prefers-reduced-motion: reduce` a page jumps instead of\n * gliding.\n *\n * ## Tokens\n *\n * `--carousel-item-size` sets how wide a card is (default `min(20rem, 85%)`,\n * so the next card always peeks in on a phone) and `--carousel-gap` the space\n * between cards (default `1rem`).\n *\n * ## MIN_VIEWPORT — 320\n *\n * ## Anatomy\n *\n *   Carousel                      (section — data-slot=\"carousel\", aria-roledescription=\"carousel\", data-min-viewport=320)\n *     ├─ CarouselContent          (div — data-slot=\"carousel-content\": the scrolling row, one tab stop)\n *     │   └─ CarouselItem × n     (div[role=group] — data-slot=\"carousel-item\", aria-roledescription=\"slide\", \"n of m\")\n *     ├─ CarouselPrevious         (Button — data-slot=\"carousel-previous\", disabled at the start)\n *     └─ CarouselNext             (Button — data-slot=\"carousel-next\", disabled at the end)\n *\n * | Rule | Concept                  | Where in this file                                  |\n * | ---- | ------------------------ | --------------------------------------------------- |\n * | R4   | Extends native el        | `section` / `div` / Button props                    |\n * | R6   | data-slot per part       | carousel / -content / -item / -previous / -next     |\n * | R7   | cn + ...rest             | `cn(BASE, className)` + `{...props}`                |\n * | R11  | Composition              | parts are children, not an `items` array prop       |\n * | R13  | Ecosystem first          | shadcn's part names; the browser's scroll snap      |\n * | R14  | Declares min viewport    | `data-min-viewport` + exported const                |\n * | R19  | Tokens only              | `--carousel-item-size`, `--carousel-gap`            |\n * | R25  | Client component         | the buttons read the scroll position                |\n * | R26  | A11y                     | APG carousel roles; no auto-rotation                |\n */\n\nimport { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { Button } from '@/components/ui/button';\n\n/** Smallest viable viewport (CSS px) for this pattern. */\nexport const MIN_VIEWPORT = 320 as const;\n\ntype Edges = { start: boolean; end: boolean };\n\ninterface CarouselContextValue {\n  contentId: string;\n  content: React.RefObject<HTMLDivElement | null>;\n  edges: Edges;\n  measure: (row: HTMLElement) => void;\n  page: (by: 1 | -1) => void;\n}\n\nconst CarouselContext = React.createContext<CarouselContextValue | null>(null);\n\nfunction useCarousel(part: string): CarouselContextValue {\n  const context = React.useContext(CarouselContext);\n  if (!context) throw new Error(`${part} must be used inside <Carousel>.`);\n  return context;\n}\n\nfunction isRtl(el: Element): boolean {\n  return el.closest('[dir]')?.getAttribute('dir') === 'rtl';\n}\n\n/** Where the row stands, from its start in the reading direction. Half a pixel of slack absorbs subpixel scroll. */\nfunction edgesOf(el: HTMLElement): Edges {\n  const travelled = Math.abs(el.scrollLeft);\n  const room = el.scrollWidth - el.clientWidth;\n  return { start: travelled <= 0.5, end: travelled >= room - 0.5 };\n}\n\nexport interface CarouselProps extends React.ComponentPropsWithoutRef<'section'> {\n  /** Names the carousel for a screen reader, e.g. \"Featured answers\". Required unless `aria-labelledby` is set. */\n  'aria-label'?: string;\n}\n\nexport function Carousel({ className, children, ...props }: CarouselProps) {\n  const reduced = useReducedMotion();\n  const content = React.useRef<HTMLDivElement>(null);\n  const contentId = `${React.useId()}-content`;\n  const [edges, setEdges] = React.useState<Edges>({ start: true, end: false });\n\n  const measure = React.useCallback((row: HTMLElement) => {\n    const next = edgesOf(row);\n    setEdges((prev) => (prev.start === next.start && prev.end === next.end ? prev : next));\n  }, []);\n\n  const page = React.useCallback(\n    (by: 1 | -1) => {\n      const el = content.current;\n      if (!el) return;\n      const sign = isRtl(el) ? -by : by;\n      el.scrollBy({ left: sign * el.clientWidth, behavior: reduced ? 'auto' : 'smooth' });\n    },\n    [reduced],\n  );\n\n  const value = React.useMemo(() => ({ contentId, content, edges, measure, page }), [contentId, edges, measure, page]);\n\n  return (\n    <CarouselContext.Provider value={value}>\n      <section\n        data-slot=\"carousel\"\n        aria-roledescription=\"carousel\"\n        data-min-viewport={String(MIN_VIEWPORT)}\n        className={cn(\n          'relative grid grid-cols-[1fr_auto_auto] items-center gap-x-2 gap-y-3 [--carousel-gap:1rem] [--carousel-item-size:min(20rem,85%)]',\n          className,\n        )}\n        {...props}\n      >\n        {children}\n      </section>\n    </CarouselContext.Provider>\n  );\n}\n\nexport type CarouselContentProps = React.ComponentPropsWithoutRef<'div'>;\n\nexport function CarouselContent({ className, children, onScroll, ...props }: CarouselContentProps) {\n  const { contentId, content, measure } = useCarousel('CarouselContent');\n\n  // Measure once laid out, and again whenever the row or its cards change size.\n  React.useEffect(() => {\n    // Effects run after the ref is attached, so the row is there.\n    const el = content.current!;\n    measure(el);\n    if (typeof ResizeObserver === 'undefined') return;\n    const observer = new ResizeObserver(() => measure(el));\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [content, measure]);\n\n  const count = React.Children.toArray(children).filter(React.isValidElement).length;\n  let index = 0;\n\n  return (\n    <div\n      ref={content}\n      id={contentId}\n      data-slot=\"carousel-content\"\n      // One tab stop, so a keyboard reader can scroll the row with the arrow keys (axe: scrollable-region-focusable).\n      tabIndex={0}\n      onScroll={(event) => {\n        measure(event.currentTarget);\n        onScroll?.(event);\n      }}\n      className={cn(\n        'col-span-3 row-start-2 -mx-1 flex snap-x snap-mandatory gap-(--carousel-gap) overflow-x-auto overscroll-x-contain px-1 py-2 scroll-px-1 motion-safe:scroll-smooth',\n        'rounded-lg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',\n        className,\n      )}\n      {...props}\n    >\n      {React.Children.map(children, (child) => {\n        if (!React.isValidElement<CarouselItemProps>(child)) return child;\n        index += 1;\n        return React.cloneElement(child, { position: child.props.position ?? { index, count } });\n      })}\n    </div>\n  );\n}\n\nexport interface CarouselItemProps extends React.ComponentPropsWithoutRef<'div'> {\n  /** Set by CarouselContent: this card's place in the row, announced as \"2 of 6\". */\n  position?: { index: number; count: number };\n  /** How the place is announced. @default (index, count) => `${index} of ${count}` */\n  positionLabel?: (index: number, count: number) => string;\n}\n\nexport function CarouselItem({ className, position, positionLabel, ...props }: CarouselItemProps) {\n  const label = position ? (positionLabel ?? ((i, n) => `${i} of ${n}`))(position.index, position.count) : undefined;\n  return (\n    <div\n      data-slot=\"carousel-item\"\n      role=\"group\"\n      aria-roledescription=\"slide\"\n      aria-label={label}\n      className={cn('min-w-0 shrink-0 grow-0 basis-(--carousel-item-size) snap-start', className)}\n      {...props}\n    />\n  );\n}\n\nexport interface CarouselButtonProps extends Omit<React.ComponentProps<typeof Button>, 'children'> {\n  /** The button's accessible name. */\n  label?: string;\n}\n\nfunction CarouselButton({\n  direction,\n  label,\n  className,\n  onClick,\n  ...props\n}: CarouselButtonProps & { direction: 1 | -1 }) {\n  const { contentId, edges, page } = useCarousel(direction === 1 ? 'CarouselNext' : 'CarouselPrevious');\n  const atEdge = direction === 1 ? edges.end : edges.start;\n  // Everything fits: there is nowhere to page, so neither button shows.\n  if (edges.start && edges.end) return null;\n  const Icon = direction === 1 ? ChevronRightIcon : ChevronLeftIcon;\n  return (\n    <Button\n      type=\"button\"\n      variant=\"outline\"\n      size=\"icon\"\n      data-slot={direction === 1 ? 'carousel-next' : 'carousel-previous'}\n      aria-controls={contentId}\n      aria-label={label}\n      disabled={atEdge}\n      className={cn('row-start-1', direction === 1 ? 'col-start-3' : 'col-start-2', className)}\n      onClick={(event) => {\n        page(direction);\n        onClick?.(event);\n      }}\n      {...props}\n    >\n      <Icon aria-hidden=\"true\" className=\"rtl:rotate-180\" />\n    </Button>\n  );\n}\n\n/** Pages back by one view. Sits at the inline end of the header row, before Next. */\nexport function CarouselPrevious({ label = 'Previous', ...props }: CarouselButtonProps) {\n  return <CarouselButton direction={-1} label={label} {...props} />;\n}\n\n/** Pages on by one view. */\nexport function CarouselNext({ label = 'Next', ...props }: CarouselButtonProps) {\n  return <CarouselButton direction={1} label={label} {...props} />;\n}\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/carousel\n\nInstalled to `components/ui/patterns/carousel.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/carousel';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/carousel\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
