# Carousel

> A swipeable ordered list with snap points, previous and next buttons, and a live position indicator.

- Kind: ui · Category: Layout and media · Interactivity: script
- Install: `npx shadcn@latest add @haze/carousel`
- File: `src/components/haze/ui/carousel.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/utils
- Docs page: https://hazeui.com/ui/carousel

## Use when
- Readers browse a small ordered set of product highlights
- Cards should be available as a regular list when scripting is unavailable

## Avoid when
- Each option chooses a view in the same workspace. Use tabs.
- The items need side-by-side comparison.

## Alternatives
- [tabs](https://hazeui.com/ui/tabs.md)
- [marquee](https://hazeui.com/ui/marquee.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique ID for the scroll viewport. |
| label | `string` | "Project highlights" | no | Visible heading and name of the region. |
| previousLabel | `string` | "Previous slide" | no | Accessible name of the previous button. |
| nextLabel | `string` | "Next slide" | no | Accessible name of the next button. |
| headingLevel | `2 \| 3 \| 4 \| 5 \| 6` | 2 | no | Heading level for the title. |
| default slot | `slot` |  | no | One direct list item per slide. |
| class | `string` |  | no | Additional classes on the carousel section. |

## Accessibility
- Slides start as a regular ordered list and gain horizontal scrolling when enhanced.
- The component keeps focus on the navigation button and announces the slide position.
- Motion follows the user's reduced-motion preference. Slides never advance automatically.
- Key Tab then Enter or Space: Use the previous or next button.
- Key Left or Right: Scroll with focus on the slide viewport.

## Agent prompts

### Install and use

Install the Haze UI component "Carousel" with `npx shadcn@latest add @haze/carousel`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Carousel from "@/components/haze/ui/carousel.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/carousel.md

### Customize with real content

Adapt the Haze carousel ui for our product. Replace the demo values of these props with our real content: id, label, previousLabel, nextLabel, headingLevel, default slot, class. Keep the layout, the heading level rules and these accessibility details: Slides start as a regular ordered list and gain horizontal scrolling when enhanced. The component keeps focus on the navigation button and announces the slide position. Motion follows the user's reduced-motion preference. Slides never advance automatically. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using carousel, check it fits: use it when readers browse a small ordered set of product highlights; cards should be available as a regular list when scripting is unavailable. Avoid it when each option chooses a view in the same workspace. use tabs.; the items need side-by-side comparison.. Alternatives: @haze/tabs, @haze/marquee.

## Example requests that should lead here
- Place three product feature cards in a user-controlled carousel with keyboard navigation.

## Source

```astro
---
import { ChevronLeft, ChevronRight } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";

interface Props {
  id: string;
  label?: string;
  previousLabel?: string;
  nextLabel?: string;
  headingLevel?: 2 | 3 | 4 | 5 | 6;
  class?: string;
}

const {
  id, label = "Project highlights", previousLabel = "Previous slide", nextLabel = "Next slide",
  headingLevel = 2, class: className,
} = Astro.props;
const Heading = `h${headingLevel}` as const;
---

<section data-haze-carousel aria-labelledby={`${id}-label`} class={cn("grid min-w-0 gap-3", className)}>
  <div class="flex min-h-9 items-center justify-between gap-3">
    <Heading id={`${id}-label`} class="min-w-0 wrap-anywhere text-[0.8125rem]/5 font-medium text-foreground">{label}</Heading>
    <div class="hidden shrink-0 items-center gap-1 [[data-haze-carousel][data-enhanced]_&]:flex">
      <Button data-slide-prev size="icon" variant="secondary" aria-label={previousLabel} aria-controls={id} class="size-8 rounded-lg focus-visible:z-10">
        <ChevronLeft aria-hidden="true" class="rtl:rotate-180" />
      </Button>
      <Button data-slide-next size="icon" variant="secondary" aria-label={nextLabel} aria-controls={id} class="size-8 rounded-lg focus-visible:z-10">
        <ChevronRight aria-hidden="true" class="rtl:rotate-180" />
      </Button>
    </div>
  </div>
  <ol id={id} data-slide-viewport class={cn(
    "grid min-w-0 gap-2 rounded-xl [&>li]:min-w-0",
    "[[data-haze-carousel][data-enhanced]_&]:auto-cols-[100%] [[data-haze-carousel][data-enhanced]_&]:grid-flow-col [[data-haze-carousel][data-enhanced]_&]:overflow-x-auto",
    "snap-x snap-mandatory overscroll-x-contain motion-safe:scroll-smooth [&>li]:snap-start",
    "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
  )}>
    <slot>
      <li class="rounded-xl border border-border bg-card p-4.5 text-[0.8125rem]/5 text-card-foreground">Invite reviewers to your project.</li>
      <li class="rounded-xl border border-border bg-card p-4.5 text-[0.8125rem]/5 text-card-foreground">Publish an update after the review.</li>
    </slot>
  </ol>
  <p data-slide-status aria-live="polite" aria-atomic="true" class="hidden text-center text-[0.8125rem]/5 text-muted-foreground tabular-nums [[data-haze-carousel][data-enhanced]_&]:block"></p>
</section>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const viewport = root.querySelector<HTMLOListElement>("[data-slide-viewport]");
    const previous = root.querySelector<HTMLButtonElement>("[data-slide-prev]");
    const next = root.querySelector<HTMLButtonElement>("[data-slide-next]");
    const status = root.querySelector<HTMLElement>("[data-slide-status]");
    if (!viewport || !previous || !next || !status) return;
    const slides = Array.from(viewport.children).filter((child) => child instanceof HTMLLIElement);
    if (slides.length < 2) return;

    const rtl = getComputedStyle(viewport).direction === "rtl";
    const distanceTo = (slide: HTMLElement) => {
      const viewportBounds = viewport.getBoundingClientRect();
      const slideBounds = slide.getBoundingClientRect();
      return rtl ? slideBounds.right - viewportBounds.right : slideBounds.left - viewportBounds.left;
    };
    let current = -1;
    let frame = 0;
    const sync = () => {
      frame = 0;
      let nearest = 0;
      let distance = Infinity;
      for (const [index, slide] of slides.entries()) {
        const offset = Math.abs(distanceTo(slide));
        if (offset >= distance) continue;
        distance = offset;
        nearest = index;
      }
      if (current === nearest) return;
      current = nearest;
      previous.setAttribute("aria-disabled", String(current === 0));
      next.setAttribute("aria-disabled", String(current === slides.length - 1));
      status.textContent = `Slide ${current + 1} of ${slides.length}`;
    };

    const go = (step: number) => {
      const slide = slides[current + step];
      if (slide) viewport.scrollBy({ left: distanceTo(slide) });
    };
    previous.addEventListener("click", () => go(-1));
    next.addEventListener("click", () => go(1));
    viewport.addEventListener("scroll", () => {
      if (!frame) frame = requestAnimationFrame(sync);
    }, { passive: true });
    root.setAttribute("data-enhanced", "");
    root.setAttribute("aria-roledescription", "carousel");
    viewport.tabIndex = 0;
    new ResizeObserver(sync).observe(viewport);
    sync();
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-carousel]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-carousel-listener")) {
    document.documentElement.setAttribute("data-haze-carousel-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
