# Carousel

A row of slides that scrolls by swipe, drag, arrow keys or buttons.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Card, CardContent } from "@/components/ui/card"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
import { leading, text, width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  carousel: { width: "100%", maxWidth: width.narrow },
  slide: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    aspectRatio: "1",
    fontSize: text.xl4,
    lineHeight: leading.xl4,
    fontWeight: 600,
  },
})

export default function CarouselDemo() {
  return (
    <Carousel xstyle={styles.carousel}>
      <CarouselContent>
        {[1, 2, 3, 4, 5].map((slide) => (
          <CarouselItem key={slide}>
            <Card>
              <CardContent xstyle={styles.slide}>{slide}</CardContent>
            </Card>
          </CarouselItem>
        ))}
      </CarouselContent>
      <CarouselPrevious />
      <CarouselNext />
    </Carousel>
  )
}
```

## Installation

**Command**

```bash
npx shadcn@latest add @arene/carousel
```

Needs the [arene setup](https://www.arene.style/docs/installation) first. Also adds [Button](https://www.arene.style/docs/components/button).

**Manual**

1. Install the packages it imports:

   ```bash
   npm install embla-carousel-react @base-ui/react @stylexjs/stylex clsx @phosphor-icons/react
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation). Carousel also needs the
   [Button](https://www.arene.style/docs/components/button) for its arrows, and `interop.css`, which
   sizes the arrow icons.

3. Paste this source into the file named in its title.

   ```tsx title="components/ui/carousel.tsx"
   "use client"

   import {
     createContext,
     use,
     useEffect,
     useState,
     type ComponentProps,
     type KeyboardEvent,
   } from "react"
   import { useRender } from "@base-ui/react/use-render"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"
   import useEmblaCarousel, { type UseEmblaCarouselType } from "embla-carousel-react"
   import { CaretDownIcon } from "@phosphor-icons/react/dist/csr/CaretDown"
   import { CaretLeftIcon } from "@phosphor-icons/react/dist/csr/CaretLeft"
   import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"
   import { CaretUpIcon } from "@phosphor-icons/react/dist/csr/CaretUp"

   import { Button } from "@/components/ui/button"
   import { radius, space } from "@/theme/tokens.stylex"

   type CarouselApi = NonNullable<UseEmblaCarouselType[1]>
   type CarouselOptions = Parameters<typeof useEmblaCarousel>[0]
   type CarouselPlugin = NonNullable<Parameters<typeof useEmblaCarousel>[1]>[number]
   type CarouselOrientation = "horizontal" | "vertical"

   type CarouselContextValue = {
     viewportRef: UseEmblaCarouselType[0]
     api: CarouselApi | undefined
     orientation: CarouselOrientation
     canScrollPrev: boolean
     canScrollNext: boolean
     scrollPrev: () => void
     scrollNext: () => void
   }

   const CarouselContext = createContext<CarouselContextValue | null>(null)

   function useCarousel() {
     const context = use(CarouselContext)
     if (!context) throw new Error("useCarousel must be used within a <Carousel />")
     return context
   }

   const gap = "var(--arene-carousel-gap)"
   const bleed = `min(${space.s1}, var(--arene-carousel-gap))`
   const buttonOffset = `calc(-1 * (${space.s8} + ${space.s4}))`

   const styles = stylex.create({
     root: { position: "relative", "--arene-carousel-gap": space.s4 },
     viewport: {
       overflow: "hidden",
       padding: bleed,
       margin: `calc(-1 * ${bleed})`,
     },
     content: { display: "flex" },
     item: { minWidth: 0, flexShrink: 0, flexGrow: 0, flexBasis: "100%" },
     button: { position: "absolute", "--arene-button-radius": radius.full },
   })

   const orientations = stylex.create({
     horizontal: { flexDirection: "row", marginInlineStart: `calc(-1 * ${gap})` },
     vertical: { flexDirection: "column", marginBlockStart: `calc(-1 * ${gap})` },
   })

   const itemOrientations = stylex.create({
     horizontal: { paddingInlineStart: gap },
     vertical: { paddingBlockStart: gap },
   })

   const buttonPlacements = stylex.create({
     horizontalPrevious: {
       insetBlockStart: "50%",
       insetInlineStart: buttonOffset,
       transform: "translateY(-50%)",
     },
     horizontalNext: {
       insetBlockStart: "50%",
       insetInlineEnd: buttonOffset,
       transform: "translateY(-50%)",
     },
     verticalPrevious: {
       insetBlockStart: buttonOffset,
       insetInlineStart: "50%",
       transform: "translateX(-50%)",
     },
     verticalNext: {
       insetBlockEnd: buttonOffset,
       insetInlineStart: "50%",
       transform: "translateX(-50%)",
     },
   })

   const carouselStyles = {
     root: styles.root,
     viewport: styles.viewport,
     content: styles.content,
     item: styles.item,
     button: styles.button,
     orientations,
     itemOrientations,
     buttonPlacements,
   }

   const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

   type Overrides = { xstyle?: StyleXStyles; className?: string }

   type CarouselProps = useRender.ComponentProps<"div"> &
     Overrides & {
       orientation?: CarouselOrientation
       opts?: CarouselOptions
       plugins?: ReadonlyArray<CarouselPlugin>
       setApi?: (api: CarouselApi) => void
     }

   function Carousel({
     orientation = "horizontal",
     opts,
     plugins,
     setApi,
     onKeyDownCapture,
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: CarouselProps) {
     const [viewportRef, api] = useEmblaCarousel(
       { ...opts, axis: orientation === "horizontal" ? "x" : "y" },
       plugins ? [...plugins] : undefined,
     )
     const [canScrollPrev, setCanScrollPrev] = useState(false)
     const [canScrollNext, setCanScrollNext] = useState(false)

     useEffect(() => {
       if (!api) return
       const update = () => {
         setCanScrollPrev(api.canScrollPrev())
         setCanScrollNext(api.canScrollNext())
       }
       update()
       api.on("reInit", update).on("select", update)
       return () => {
         api.off("reInit", update).off("select", update)
       }
     }, [api])

     useEffect(() => {
       if (api) setApi?.(api)
     }, [api, setApi])

     const scrollPrev = () => api?.scrollPrev(reducedMotion())
     const scrollNext = () => api?.scrollNext(reducedMotion())

     const previousKey = orientation === "horizontal" ? "ArrowLeft" : "ArrowUp"
     const nextKey = orientation === "horizontal" ? "ArrowRight" : "ArrowDown"

     const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
       onKeyDownCapture?.(event)
       if (event.defaultPrevented) return
       if (event.key === previousKey) {
         event.preventDefault()
         scrollPrev()
       } else if (event.key === nextKey) {
         event.preventDefault()
         scrollNext()
       }
     }

     const sx = stylex.props(styles.root, xstyle)
     const element = useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         role: "region",
         "aria-roledescription": "carousel",
         "data-slot": "carousel",
         "data-orientation": orientation,
         ...sx,
         ...props,
         onKeyDownCapture: handleKeyDown,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })

     return (
       <CarouselContext
         value={{
           viewportRef,
           api,
           orientation,
           canScrollPrev,
           canScrollNext,
           scrollPrev,
           scrollNext,
         }}
       >
         {element}
       </CarouselContext>
     )
   }

   type CarouselContentProps = useRender.ComponentProps<"div"> &
     Overrides & {
       viewportProps?: useRender.ComponentProps<"div"> & Overrides
     }

   function CarouselContent({
     render,
     ref,
     style,
     xstyle,
     className,
     viewportProps,
     ...props
   }: CarouselContentProps) {
     const { viewportRef, orientation } = useCarousel()
     const {
       xstyle: viewportXstyle,
       className: viewportClassName,
       style: viewportStyle,
       ...viewportRest
     } = viewportProps ?? {}
     const viewportSx = stylex.props(styles.viewport, viewportXstyle)
     const sx = stylex.props(styles.content, orientations[orientation], xstyle)
     const content = useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "carousel-content",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
     return (
       <div
         ref={viewportRef}
         data-slot="carousel-viewport"
         {...viewportSx}
         {...viewportRest}
         className={clsx(viewportSx.className, viewportClassName)}
         style={{ ...viewportSx.style, ...viewportStyle }}
       >
         {content}
       </div>
     )
   }

   function CarouselItem({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"div"> & Overrides) {
     const { orientation } = useCarousel()
     const sx = stylex.props(styles.item, itemOrientations[orientation], xstyle)
     return useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         role: "group",
         "aria-roledescription": "slide",
         "data-slot": "carousel-item",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   type CarouselButtonProps = Omit<ComponentProps<typeof Button>, "disabled">

   function CarouselPrevious({
     variant = "outline",
     size = "icon-sm",
     xstyle,
     onClick,
     children,
     ...props
   }: CarouselButtonProps) {
     const { orientation, canScrollPrev, scrollPrev } = useCarousel()
     const Icon = orientation === "horizontal" ? CaretLeftIcon : CaretUpIcon
     return (
       <Button
         data-slot="carousel-previous"
         variant={variant}
         size={size}
         aria-label="Previous slide"
         disabled={!canScrollPrev}
         xstyle={[styles.button, buttonPlacements[`${orientation}Previous`], xstyle]}
         onClick={(event) => {
           onClick?.(event)
           scrollPrev()
         }}
         {...props}
       >
         {children ?? <Icon aria-hidden="true" />}
       </Button>
     )
   }

   function CarouselNext({
     variant = "outline",
     size = "icon-sm",
     xstyle,
     onClick,
     children,
     ...props
   }: CarouselButtonProps) {
     const { orientation, canScrollNext, scrollNext } = useCarousel()
     const Icon = orientation === "horizontal" ? CaretRightIcon : CaretDownIcon
     return (
       <Button
         data-slot="carousel-next"
         variant={variant}
         size={size}
         aria-label="Next slide"
         disabled={!canScrollNext}
         xstyle={[styles.button, buttonPlacements[`${orientation}Next`], xstyle]}
         onClick={(event) => {
           onClick?.(event)
           scrollNext()
         }}
         {...props}
       >
         {children ?? <Icon aria-hidden="true" />}
       </Button>
     )
   }

   export {
     Carousel,
     CarouselContent,
     CarouselItem,
     CarouselNext,
     CarouselPrevious,
     carouselStyles,
     useCarousel,
     type CarouselApi,
     type CarouselOptions,
     type CarouselOrientation,
     type CarouselPlugin,
   }
   ```

4. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
```

```tsx
<Carousel>
  <CarouselContent>
    <CarouselItem>…</CarouselItem>
    <CarouselItem>…</CarouselItem>
    <CarouselItem>…</CarouselItem>
  </CarouselContent>
  <CarouselPrevious />
  <CarouselNext />
</Carousel>
```

Carousel is [Embla Carousel](https://www.embla-carousel.com) with arene's
parts around it. Embla handles dragging, swiping, snapping and looping. With
focus inside the carousel, the arrow keys move between slides.

## Composition

```text
Carousel                  region; context, keyboard arrows
├── CarouselContent       viewport that clips, and the track inside it
│   └── CarouselItem      one slide
├── CarouselPrevious
└── CarouselNext
```

The arrows sit outside the slides, `3rem` past the start and end edges, so leave
room for them or place them yourself through `xstyle`.

## Sizes

A slide is the full width of the carousel. Give `CarouselItem` a `flexBasis`
through `xstyle` to show several at once. These are half width, and a third from
the `lg` breakpoint. `opts={{ align: "start" }}` snaps each slide to the start
edge.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Card, CardContent } from "@/components/ui/card"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
import { breakpoints } from "@/theme/breakpoints.stylex"
import { leading, text, width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  carousel: { width: "100%", maxWidth: width.sm },
  item: { flexBasis: { default: "50%", [breakpoints.lg]: "33.333%" } },
  slide: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    aspectRatio: "1",
    fontSize: text.xl2,
    lineHeight: leading.xl2,
    fontWeight: 600,
  },
})

export default function CarouselSize() {
  return (
    <Carousel opts={{ align: "start" }} xstyle={styles.carousel}>
      <CarouselContent>
        {[1, 2, 3, 4, 5, 6, 7, 8].map((slide) => (
          <CarouselItem key={slide} xstyle={styles.item}>
            <Card>
              <CardContent xstyle={styles.slide}>{slide}</CardContent>
            </Card>
          </CarouselItem>
        ))}
      </CarouselContent>
      <CarouselPrevious />
      <CarouselNext />
    </Carousel>
  )
}
```

## Spacing

The gap between slides is `--arene-carousel-gap`, `1rem` by default. Set it on
the carousel through `xstyle`.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Card, CardContent } from "@/components/ui/card"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
import { leading, space, text, width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  carousel: { width: "100%", maxWidth: width.sm, "--arene-carousel-gap": space.s1 },
  item: { flexBasis: "33.333%" },
  slide: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    aspectRatio: "1",
    fontSize: text.xl2,
    lineHeight: leading.xl2,
    fontWeight: 600,
  },
})

export default function CarouselSpacing() {
  return (
    <Carousel opts={{ align: "start" }} xstyle={styles.carousel}>
      <CarouselContent>
        {[1, 2, 3, 4, 5, 6].map((slide) => (
          <CarouselItem key={slide} xstyle={styles.item}>
            <Card>
              <CardContent xstyle={styles.slide}>{slide}</CardContent>
            </Card>
          </CarouselItem>
        ))}
      </CarouselContent>
      <CarouselPrevious />
      <CarouselNext />
    </Carousel>
  )
}
```

## Orientation

`orientation="vertical"` stacks the slides and scrolls them up and down. The
track needs a height, and the arrows move above and below.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Card, CardContent } from "@/components/ui/card"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel"
import { leading, space, text, width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  carousel: {
    width: "100%",
    maxWidth: width.narrow,
    marginBlock: space.s12,
  },
  content: { height: "12.5rem" },
  item: { flexBasis: "50%" },
  slide: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    height: "100%",
    fontSize: text.xl2,
    lineHeight: leading.xl2,
    fontWeight: 600,
  },
  card: { height: "100%" },
})

export default function CarouselOrientation() {
  return (
    <Carousel orientation="vertical" opts={{ align: "start" }} xstyle={styles.carousel}>
      <CarouselContent xstyle={styles.content}>
        {[1, 2, 3, 4, 5].map((slide) => (
          <CarouselItem key={slide} xstyle={styles.item}>
            <Card xstyle={styles.card}>
              <CardContent xstyle={styles.slide}>{slide}</CardContent>
            </Card>
          </CarouselItem>
        ))}
      </CarouselContent>
      <CarouselPrevious />
      <CarouselNext />
    </Carousel>
  )
}
```

## API

`setApi` hands you the Embla instance once it exists. Subscribe to its events
to show the current slide, or call `scrollTo` to jump to one.

```tsx
"use client"

import { useEffect, useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Card, CardContent } from "@/components/ui/card"
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  type CarouselApi,
} from "@/components/ui/carousel"
import { VStack } from "@/components/ui/stack"
import { Text } from "@/components/ui/text"
import { leading, text, width } from "@/theme/tokens.stylex"

const slides = [1, 2, 3, 4, 5]

const styles = stylex.create({
  carousel: { width: "100%", maxWidth: width.narrow },
  slide: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    aspectRatio: "1",
    fontSize: text.xl4,
    lineHeight: leading.xl4,
    fontWeight: 600,
  },
})

export default function CarouselApiDemo() {
  const [api, setApi] = useState<CarouselApi>()
  const [current, setCurrent] = useState(0)

  useEffect(() => {
    if (!api) return
    const update = () => setCurrent(api.selectedScrollSnap())
    update()
    api.on("select", update)
    return () => {
      api.off("select", update)
    }
  }, [api])

  return (
    <VStack gap={3} align="center" width="100%">
      <Carousel setApi={setApi} xstyle={styles.carousel}>
        <CarouselContent>
          {slides.map((slide) => (
            <CarouselItem key={slide}>
              <Card>
                <CardContent xstyle={styles.slide}>{slide}</CardContent>
              </Card>
            </CarouselItem>
          ))}
        </CarouselContent>
        <CarouselPrevious />
        <CarouselNext />
      </Carousel>
      <Text size="sm" tone="muted" aria-live="polite">
        Slide {current + 1} of {slides.length}
      </Text>
    </VStack>
  )
}
```

## Options and plugins

`opts` takes [Embla's options](https://www.embla-carousel.com/api/options/),
except `axis`, which `orientation` sets. `plugins` takes Embla plugins, such as
autoplay:

```bash
npm install embla-carousel-autoplay
```

```tsx
import Autoplay from "embla-carousel-autoplay"

const autoplay = [Autoplay({ delay: 4000 })]

function Gallery() {
  return (
    <Carousel opts={{ loop: true }} plugins={autoplay}>
      …
    </Carousel>
  )
}
```

Keep `plugins` at module scope or in a `useMemo`. Embla compares them by their
options, but creating a plugin on every render starts it again each time.

> **Note**
>
> With reduced motion turned on, the buttons and arrow keys jump to the next
> slide instead of scrolling to it. Dragging still follows the pointer.

## API reference

Pass `render` to replace `Carousel`, `CarouselContent` or `CarouselItem` with
another element. Each part takes `xstyle` and `className`.

### Carousel

| Prop          | Type                            | Default        |
| ------------- | ------------------------------- | -------------- |
| `orientation` | `"horizontal" \| "vertical"`    | `"horizontal"` |
| `opts`        | `CarouselOptions`               | —              |
| `plugins`     | `ReadonlyArray<CarouselPlugin>` | —              |
| `setApi`      | `(api: CarouselApi) => void`    | —              |

It renders a `role="region"` with `aria-roledescription="carousel"`. Give it an
`aria-label` that says what the slides are.

### CarouselContent

| Prop            | Type                                                                    | Default |
| --------------- | ----------------------------------------------------------------------- | ------- |
| `viewportProps` | `ComponentProps<"div"> & { xstyle?: StyleXStyles; className?: string }` | —       |

`xstyle` styles the track. `viewportProps` reaches the clipping viewport around
it.

### CarouselItem

A `role="group"` with `aria-roledescription="slide"`. Its `flexBasis` sets how
much of the carousel one slide fills.

### CarouselPrevious, CarouselNext

[Buttons](https://www.arene.style/docs/components/button), `outline` and `icon-sm` by default, with
`aria-label` set. They disable themselves at the first and last slide unless
`opts.loop` is on. Pass children to replace the arrow.

### useCarousel

Returns `api`, `orientation`, `canScrollPrev`, `canScrollNext`, `scrollPrev`
and `scrollNext` inside a `Carousel`, for building your own controls.

### Data attributes

| Attribute                       | On           | Effect                |
| ------------------------------- | ------------ | --------------------- |
| `data-slot="carousel"`          | the root     | Carousel root         |
| `data-orientation`              | the root     | Which way it scrolls  |
| `data-slot="carousel-viewport"` | the viewport | The clipping viewport |
| `data-slot="carousel-content"`  | the track    | The track of slides   |
| `data-slot="carousel-item"`     | a slide      | One slide             |
| `data-slot="carousel-previous"` | a button     | Previous button       |
| `data-slot="carousel-next"`     | a button     | Next button           |
