# Carousel Cards

> An editorial peeking card carousel with plain media panels, favorite toggles, tabular counter, and scroll-snap controls.

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

## Use when
- Readers browse a curated horizontal strip of travel, product, or editorial cards where the next card peeks in.
- Each card benefits from visual artwork, a quick-save toggle, and compact rating or pricing metadata.

## Avoid when
- Only one full-width slide should fill the viewport at a time. Use carousel instead.
- Users make binary keep-or-skip decisions on one card at a time. Use card-stack.

## Alternatives
- [carousel](https://hazeui.com/ui/carousel.md)
- [card-stack](https://hazeui.com/ui/card-stack.md)
- [bento-tile](https://hazeui.com/ui/bento-tile.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique ID for the horizontal scroll track. |
| eyebrow | `string` | "Picked for this autumn" | no | Small editorial eyebrow line above the carousel heading. |
| label | `string` | "Weekend escapes" | no | Visible heading naming the card carousel region. |
| items | `EscapeCard[]` |  | no | Card items with title, location, badge, rating, review count and price (scene is accepted but ignored). |
| previousLabel | `string` | "Previous card" | no | Accessible label for the previous card button. |
| nextLabel | `string` | "Next card" | no | Accessible label for the next card button. |
| headingLevel | `2 \| 3 \| 4` | 3 | no | Heading level for the carousel heading. |
| default slot | `slot` |  | no | Optional custom list items replacing the default items prop. |
| class | `string` |  | no | Additional classes on the outer carousel section. |

## Accessibility
- The track uses native CSS scroll-snap with tabindex=0 so keyboard and touch scrolling work inside the track without page overflow.
- Favorite toggle buttons expose descriptive aria-label names, aria-pressed state, and polite live announcements.
- Scroll stepping respects prefers-reduced-motion by switching to instant scrolling.
- Key Left / Right: Step to the previous or next card when the track is focused.
- Key Home / End: Jump to the first or last card in the carousel.
- Key Tab then Enter or Space: Activate previous/next controls or toggle save buttons on individual cards.

## Agent prompts

### Install and use

Install the Haze UI component "Carousel Cards" with `npx shadcn@latest add @haze/carousel-cards`. 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 CarouselCards from "@/components/haze/ui/carousel-cards.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-cards.md

### Customize with real content

Adapt the Haze carousel-cards ui for our product. Replace the demo values of these props with our real content: id, eyebrow, label, items, previousLabel, nextLabel, headingLevel, default slot, class. Keep the layout, the heading level rules and these accessibility details: The track uses native CSS scroll-snap with tabindex=0 so keyboard and touch scrolling work inside the track without page overflow. Favorite toggle buttons expose descriptive aria-label names, aria-pressed state, and polite live announcements. Scroll stepping respects prefers-reduced-motion by switching to instant scrolling. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using carousel-cards, check it fits: use it when readers browse a curated horizontal strip of travel, product, or editorial cards where the next card peeks in.; each card benefits from visual artwork, a quick-save toggle, and compact rating or pricing metadata.. Avoid it when only one full-width slide should fill the viewport at a time. use carousel instead.; users make binary keep-or-skip decisions on one card at a time. use card-stack.. Alternatives: @haze/carousel, @haze/card-stack, @haze/bento-tile.

## Example requests that should lead here
- Add an editorial weekend escapes peeking card carousel with plain media headers, save toggles, and 01 / 06 counter.
- Show a horizontal scroll-snap collection strip of travel cards with circular previous and next buttons.

## Source

```astro
---
import { ChevronLeft, ChevronRight, Heart, Star } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

type SceneKind = "coastal" | "alpine" | "mesa" | "forest" | "harbor" | "archipelago";

interface EscapeCard {
  title: string;
  location: string;
  badge: string;
  rating: string;
  reviews: number;
  price: string;
  /** Kept for API compatibility; the media area is a plain fill (owner decision 2026-11-24). */
  scene?: SceneKind;
}

interface Props {
  id: string;
  eyebrow?: string;
  label?: string;
  items?: EscapeCard[];
  previousLabel?: string;
  nextLabel?: string;
  headingLevel?: 2 | 3 | 4;
  class?: string;
}

const {
  id,
  eyebrow = "Picked for this autumn",
  label = "Weekend escapes",
  items = [
    {
      title: "Weekend in Lisbon",
      location: "Lisbon, Portugal",
      badge: "2 nights",
      rating: "4.92",
      reviews: 318,
      price: "€340",
    },
    {
      title: "Zermatt Chalet",
      location: "Valais, Switzerland",
      badge: "3 nights",
      rating: "4.96",
      reviews: 214,
      price: "€620",
    },
    {
      title: "Desert Quiet",
      location: "Sedona, Arizona",
      badge: "2 nights",
      rating: "4.89",
      reviews: 164,
      price: "€410",
    },
    {
      title: "Cedar Cabin",
      location: "Olympic, Washington",
      badge: "3 nights",
      rating: "4.94",
      reviews: 289,
      price: "€480",
    },
    {
      title: "Cliffside Lighthouse",
      location: "Acadia, Maine",
      badge: "2 nights",
      rating: "4.87",
      reviews: 142,
      price: "€365",
    },
    {
      title: "Nordic Fjord",
      location: "Lofoten, Norway",
      badge: "4 nights",
      rating: "4.98",
      reviews: 196,
      price: "€740",
    },
  ],
  previousLabel = "Previous card",
  nextLabel = "Next card",
  headingLevel = 3,
  class: className,
} = Astro.props;

const Heading = ({ 2: "h2", 3: "h3", 4: "h4" } as const)[headingLevel];
const hasCustomSlot = Astro.slots.has("default");
const totalFormatted = String(items.length).padStart(2, "0");
---

<section
  data-haze-carousel-cards
  aria-labelledby={`${id}-label`}
  class={cn("flex w-full max-w-full min-w-0 flex-col overflow-hidden", className)}
>
  <header class="mb-4 flex items-end justify-between gap-3">
    <div class="grid min-w-0 gap-0.5">
      {eyebrow && <p class="truncate text-xs/4 text-muted-foreground">{eyebrow}</p>}
      <Heading id={`${id}-label`} class="truncate text-lg/6 font-semibold tracking-tight text-foreground">
        {label}
      </Heading>
    </div>

    <div class="flex shrink-0 items-center gap-2">
      <span data-deck-counter class="text-xs/4 font-medium text-muted-foreground tabular-nums">
        01 / {totalFormatted}
      </span>
      <div class="flex items-center gap-1.5">
        <button
          type="button"
          data-deck-prev
          aria-label={previousLabel}
          aria-controls={id}
          aria-disabled="true"
          class="inline-flex size-8 cursor-pointer items-center justify-center rounded-full border border-frame bg-field text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-disabled:opacity-45"
        >
          <ChevronLeft aria-hidden="true" class="size-4 rtl:rotate-180" />
        </button>
        <button
          type="button"
          data-deck-next
          aria-label={nextLabel}
          aria-controls={id}
          class="inline-flex size-8 cursor-pointer items-center justify-center rounded-full border border-frame bg-field text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-disabled:opacity-45"
        >
          <ChevronRight aria-hidden="true" class="size-4 rtl:rotate-180" />
        </button>
      </div>
    </div>
  </header>

  <ol
    id={id}
    data-deck-track
    tabindex="0"
    aria-labelledby={`${id}-label`}
    class="flex w-full min-w-0 snap-x snap-mandatory gap-3.5 overflow-x-auto overscroll-x-contain rounded-2xl pb-2 motion-safe:scroll-smooth [scrollbar-width:none] [&::-webkit-scrollbar]:hidden focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
  >
    {hasCustomSlot ? (
      <slot />
    ) : (
      items.map((item) => {
        return (
          <li class="flex w-[210px] shrink-0 snap-start flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground sm:w-[230px]">
            <div class="relative h-40 w-full overflow-hidden bg-muted">
              <span class="absolute top-2.5 left-2.5 rounded-full border border-frame bg-card/90 px-2.5 py-0.5 text-[0.6875rem]/4 font-medium text-foreground">
                {item.badge}
              </span>

              <button
                type="button"
                data-deck-save
                data-save-title={item.title}
                aria-pressed="false"
                aria-label={`Save ${item.title}`}
                class="group absolute top-2.5 right-2.5 grid size-7 cursor-pointer place-items-center rounded-full border border-frame bg-card/90 text-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-card active:scale-95 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-pressed:border-destructive-border aria-pressed:text-destructive"
              >
                <Heart aria-hidden="true" class="size-3.5 group-aria-pressed:fill-current" />
              </button>
            </div>

            <div class="grid gap-1 p-3.5">
              <p class="truncate text-sm/5 font-semibold tracking-tight text-foreground">{item.title}</p>
              <p class="truncate text-xs/4 text-muted-foreground">{item.location}</p>
              <div class="mt-1.5 flex items-center justify-between gap-2 text-xs/4 tabular-nums">
                <span class="inline-flex items-center gap-1 font-medium text-foreground">
                  <Star aria-hidden="true" class="size-3 fill-foreground text-foreground" />
                  {item.rating}
                  <span class="font-normal text-muted-foreground">({item.reviews})</span>
                </span>
                <span class="font-medium text-foreground">
                  {item.price}
                  <span class="ml-0.5 font-normal text-muted-foreground">total</span>
                </span>
              </div>
            </div>
          </li>
        );
      })
    )}
  </ol>

  <p data-deck-status aria-live="polite" aria-atomic="true" class="sr-only"></p>
</section>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const track = root.querySelector<HTMLOListElement>("[data-deck-track]");
    const prevBtn = root.querySelector<HTMLButtonElement>("[data-deck-prev]");
    const nextBtn = root.querySelector<HTMLButtonElement>("[data-deck-next]");
    const counter = root.querySelector<HTMLElement>("[data-deck-counter]");
    const status = root.querySelector<HTMLElement>("[data-deck-status]");
    if (!track || !prevBtn || !nextBtn || !counter) return;

    const cards = Array.from(track.children).filter((child): child is HTMLLIElement => child instanceof HTMLLIElement);
    const saveButtons = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-deck-save]"));

    for (const btn of saveButtons) {
      btn.addEventListener("click", () => {
        const nextPressed = btn.getAttribute("aria-pressed") !== "true";
        btn.setAttribute("aria-pressed", String(nextPressed));
        const title = btn.dataset.saveTitle ?? "item";
        if (status) {
          status.textContent = nextPressed ? `Saved ${title}.` : `Removed ${title} from saved.`;
        }
      });
    }

    if (cards.length < 2) {
      root.setAttribute("data-enhanced", "");
      return;
    }

    const isRtl = () => getComputedStyle(track).direction === "rtl";
    const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const pad = (n: number) => String(n).padStart(2, "0");

    const offsetToCard = (card: HTMLElement) => {
      const trackRect = track.getBoundingClientRect();
      const cardRect = card.getBoundingClientRect();
      return isRtl() ? cardRect.right - trackRect.right : cardRect.left - trackRect.left;
    };

    let active = -1;
    let rafId = 0;

    const sync = (announce = false) => {
      rafId = 0;
      let nearest = 0;
      let best = Infinity;
      for (const [index, card] of cards.entries()) {
        const dist = Math.abs(offsetToCard(card));
        if (dist < best) {
          best = dist;
          nearest = index;
        }
      }
      if (active === nearest) return;
      active = nearest;
      prevBtn.setAttribute("aria-disabled", String(active === 0));
      nextBtn.setAttribute("aria-disabled", String(active === cards.length - 1));
      counter.textContent = `${pad(active + 1)} / ${pad(cards.length)}`;
      if (announce && status) status.textContent = `Card ${active + 1} of ${cards.length}.`;
    };

    const scrollToIndex = (index: number) => {
      const clamped = Math.max(0, Math.min(cards.length - 1, index));
      const target = cards[clamped];
      if (!target) return;
      track.scrollBy({
        left: offsetToCard(target),
        behavior: reducedMotion() ? "auto" : "smooth",
      });
      if (status) status.textContent = `Card ${clamped + 1} of ${cards.length}.`;
    };

    prevBtn.addEventListener("click", () => scrollToIndex(active - 1));
    nextBtn.addEventListener("click", () => scrollToIndex(active + 1));

    track.addEventListener("keydown", (event) => {
      if (event.key === "ArrowRight") {
        event.preventDefault();
        scrollToIndex(active + (isRtl() ? -1 : 1));
      } else if (event.key === "ArrowLeft") {
        event.preventDefault();
        scrollToIndex(active + (isRtl() ? 1 : -1));
      } else if (event.key === "Home") {
        event.preventDefault();
        scrollToIndex(0);
      } else if (event.key === "End") {
        event.preventDefault();
        scrollToIndex(cards.length - 1);
      }
    });

    track.addEventListener(
      "scroll",
      () => {
        if (!rafId) rafId = requestAnimationFrame(() => sync(false));
      },
      { passive: true },
    );

    root.setAttribute("data-enhanced", "");
    root.setAttribute("aria-roledescription", "carousel");
    new ResizeObserver(() => sync(false)).observe(track);
    sync(false);
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-carousel-cards]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-carousel-cards-listener")) {
    document.documentElement.setAttribute("data-haze-carousel-cards-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
