# Card stack

> Review cards one at a time with swipe decisions, native form choices, keyboard actions and undo.

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

## Use when
- People are reviewing a small finite set of ideas and making a binary decision on each one.
- A deck should support touch gestures while retaining explicit radio choices for every card.

## Avoid when
- Use carousel for browsing content without recording a decision.
- Use sortable-list when people need to compare or rearrange the entire set simultaneously.

## Alternatives
- [carousel](https://hazeui.com/ui/carousel.md)
- [sortable-list](https://hazeui.com/ui/sortable-list.md)
- [card](https://hazeui.com/ui/card.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller supplied prefix for the control and its associated content. |
| name | `string` | id | no | Prefix for submitted fields in the form name[itemId]. |
| label | `string` | Review workspace ideas | no | Legend explaining the review task. |
| items | `{ id: string; title: string; description: string; eyebrow?: string; details?: string[] }[]` | Three workspace improvement ideas | no | Finite review items with stable identifiers. |
| skipLabel | `string` | Skip | no | Visible label for the negative decision. |
| saveLabel | `string` | Shortlist | no | Visible label for the positive decision. |
| headingLevel | `2 \| 3 \| 4` | 3 | no | Heading level for each card title. |
| class | `string` |  | no | Additional classes on this component's outer wrapper. |

## Accessibility
- Without enhancement every card and its native Later, Skip and Shortlist radios is available as a normal form.
- Enhancement shows one card at a time, keeps hidden radio decisions in the form, and exposes arrow actions on the focused deck group.
- Undo returns to the preceding card and resets that card to undecided; completion and decisions are announced in a live region.
- Swiping requires horizontal intent, leaves vertical page scroll available and discards canceled drags without recording a decision.
- Key Left / Right on the deck: Skip or shortlist the current card.
- Key Tab, Space: Choose the current card's native decision or activate Undo and Start again.

## Agent prompts

### Install and use

Install the Haze UI component "Card stack" with `npx shadcn@latest add @haze/card-stack`. 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 CardStack from "@/components/haze/ui/card-stack.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/card-stack.md

### Customize with real content

Adapt the Haze card-stack ui for our product. Replace the demo values of these props with our real content: id, name, label, items, skipLabel, saveLabel, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: Without enhancement every card and its native Later, Skip and Shortlist radios is available as a normal form. Enhancement shows one card at a time, keeps hidden radio decisions in the form, and exposes arrow actions on the focused deck group. Undo returns to the preceding card and resets that card to undecided; completion and decisions are announced in a live region. Swiping requires horizontal intent, leaves vertical page scroll available and discards canceled drags without recording a decision. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using card-stack, check it fits: use it when people are reviewing a small finite set of ideas and making a binary decision on each one.; a deck should support touch gestures while retaining explicit radio choices for every card.. Avoid it when use carousel for browsing content without recording a decision.; use sortable-list when people need to compare or rearrange the entire set simultaneously.. Alternatives: @haze/carousel, @haze/sortable-list, @haze/card.

## Example requests that should lead here
- Create a small card deck for shortlisting workflow ideas with Undo
- Let users review one proposal at a time with buttons, radio values and optional swipes

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Item { id: string; title: string; description: string; eyebrow?: string; details?: string[]; }
interface Props {
  id: string;
  name?: string;
  label?: string;
  items?: Item[];
  skipLabel?: string;
  saveLabel?: string;
  headingLevel?: 2 | 3 | 4;
  class?: string;
}
const { id, name = id, label = "Review workspace ideas", items = [{ id: "quiet-hours", title: "A calmer workday", description: "Pause nonessential notifications while your team is concentrating.", eyebrow: "Workflow idea", details: ["Set a shared focus window", "Let urgent messages through"] }, { id: "weekly-notes", title: "Weekly notes", description: "Collect short updates in one place before the next planning session.", eyebrow: "Team ritual", details: ["One update per project", "Keep decisions searchable"] }, { id: "clean-archive", title: "A lighter workspace", description: "Archive finished projects while keeping their decisions available.", eyebrow: "Workspace care", details: ["Review inactive projects", "Export before removing"] }], skipLabel = "Skip", saveLabel = "Shortlist", headingLevel = 3, class: className } = Astro.props;
const Heading = ({ 2: "h2", 3: "h3", 4: "h4" } as const)[headingLevel];
---
<fieldset data-haze-card-stack data-skip-label={skipLabel} data-save-label={saveLabel} aria-describedby={`${id}-hint`} class={cn("grid w-full min-w-0 gap-3", className)}>
  <legend class="mb-3 text-[0.8125rem]/5 font-medium text-foreground">{label}</legend>
  <p id={`${id}-hint`} class="text-[0.8125rem]/5 text-muted-foreground">Choose {skipLabel.toLowerCase()} or {saveLabel.toLowerCase()}. With scripting enabled, swipe sideways or use the arrow keys.</p>
  <div data-stack-stage class="relative min-w-0 overflow-hidden rounded-xl focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring">
    {items.map((item, index) => <article data-stack-card data-key={item.id} data-label={item.title} aria-label={`${item.title}, ${index + 1} of ${items.length}`} class="relative grid min-w-0 gap-5 rounded-xl border border-border bg-card p-4.5 text-card-foreground transition-[translate,rotate] duration-200 ease-snappy data-[dragging]:duration-75 [&+article]:mt-3">
      <div data-card-surface class="grid min-h-40 touch-pan-y content-start gap-3 select-none">
        {item.eyebrow && <p class="text-xs/4 font-medium text-muted-foreground">{item.eyebrow}</p>}
        <Heading class="text-[1.0625rem]/6 font-medium tracking-[-0.01em]">{item.title}</Heading>
        <p class="text-[0.8125rem]/5 text-muted-foreground">{item.description}</p>
        {item.details && <ul class="grid gap-1 text-[0.8125rem]/5 text-muted-foreground">{item.details.map((detail) => <li class="flex gap-2"><span aria-hidden="true">·</span><span>{detail}</span></li>)}</ul>}
      </div>
      <div class="flex flex-wrap gap-2">
        <label data-undecided class="flex min-h-9 cursor-pointer items-center gap-2 rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 text-muted-foreground has-checked:border-foreground has-checked:bg-accent motion-safe:transition-colors motion-safe:duration-150 hover:bg-accent has-focus-visible:outline-2 has-focus-visible:outline-offset-1 has-focus-visible:outline-ring"><input type="radio" name={`${name}[${item.id}]`} value="undecided" checked class="sr-only" />Later</label>
        {[{ value: "skip", label: skipLabel }, { value: "save", label: saveLabel }].map((action) => <label class="flex min-h-9 flex-1 cursor-pointer items-center justify-center gap-2 rounded-lg border border-frame bg-field px-3 has-checked:border-foreground has-checked:bg-accent text-[0.8125rem]/5 font-medium text-foreground transition-[background-color,box-shadow,scale] duration-150 ease-snappy hover:bg-accent hover:shadow-key has-focus-visible:outline-2 has-focus-visible:outline-offset-1 has-focus-visible:outline-ring active:scale-[0.97] active:duration-100"><input type="radio" name={`${name}[${item.id}]`} value={action.value} data-decision class="sr-only" />{action.label}</label>)}
      </div>
    </article>)}
    <p data-stack-complete hidden class="rounded-xl border border-border bg-card p-6 text-[0.8125rem]/5 text-muted-foreground">All cards reviewed. Your choices are ready to submit with the form.</p>
  </div>
  <div data-stack-tools hidden class="flex flex-wrap items-center gap-2">
    <button type="button" data-stack-undo disabled class="min-h-8 cursor-pointer rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 text-foreground transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-100 disabled:cursor-not-allowed disabled:opacity-50">Undo</button>
    <button type="button" data-stack-reset class="min-h-8 cursor-pointer rounded-lg px-3 text-[0.8125rem]/5 text-muted-foreground transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-100">Start again</button>
  </div>
  <p data-stack-status role="status" class="text-[0.8125rem]/5 text-muted-foreground">{items.length} cards to review.</p>
</fieldset>
<script>
  function enhance(root: HTMLFieldSetElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const cards = Array.from(root.querySelectorAll<HTMLElement>("[data-stack-card]"));
    const stage = root.querySelector<HTMLElement>("[data-stack-stage]");
    const undo = root.querySelector<HTMLButtonElement>("[data-stack-undo]");
    const status = root.querySelector<HTMLElement>("[data-stack-status]");
    const complete = root.querySelector<HTMLElement>("[data-stack-complete]");
    if (!stage || !undo || !status || !complete) return;
    let index = 0;
    let history: number[] = [];
    const render = (message?: string) => {
      cards.forEach((card, position) => { card.hidden = position !== index; card.style.marginTop = "0px"; card.style.translate = "0px"; card.style.rotate = "0deg"; });
      complete.hidden = index < cards.length; undo.disabled = history.length === 0;
      status.textContent = message || (index < cards.length ? `Card ${index + 1} of ${cards.length}.` : "Review complete.");
    };
    const decide = (decision: "skip" | "save", focus = false) => {
      const card = cards[index]; if (!card || root.closest("fieldset:disabled")) return;
      const input = card.querySelector<HTMLInputElement>(`input[value=${decision}]`)!;
      input.checked = true;
      const message = `${decision === "save" ? root.dataset.saveLabel : root.dataset.skipLabel}: ${card.dataset.label}.`;
      root.dispatchEvent(new CustomEvent("haze:card-decision", { bubbles: true, detail: { id: card.dataset.key, decision } }));
      history.push(index); index++;
      render(`${message} ${index < cards.length ? `Card ${index + 1} of ${cards.length}.` : "Review complete."}`);
      if (focus) stage.focus();
    };
    stage.tabIndex = 0;
    stage.setAttribute("role", "group"); stage.setAttribute("aria-label", `Card stack. Left arrow for ${root.dataset.skipLabel}, right arrow for ${root.dataset.saveLabel}.`);
    stage.addEventListener("keydown", (event) => {
      if (event.target !== stage || !["ArrowLeft", "ArrowRight"].includes(event.key)) return;
      event.preventDefault(); decide(event.key === "ArrowLeft" ? "skip" : "save");
    });
    cards.forEach((card) => {
      card.querySelector<HTMLElement>("[data-undecided]")!.hidden = true;
      card.querySelectorAll<HTMLInputElement>("[data-decision]").forEach((input) => input.addEventListener("change", () => { if (input.checked) decide(input.value as "skip" | "save", true); }));
      const surface = card.querySelector<HTMLElement>("[data-card-surface]")!;
      let drag: { id: number; x: number; y: number; locked: boolean } | null = null;
      surface.addEventListener("pointerdown", (event) => { if (!root.closest("fieldset:disabled") && event.isPrimary && event.button === 0) drag = { id: event.pointerId, x: event.clientX, y: event.clientY, locked: false }; });
      surface.addEventListener("pointermove", (event) => {
        if (!drag || drag.id !== event.pointerId) return;
        const dx = event.clientX - drag.x, dy = event.clientY - drag.y;
        if (!drag.locked && Math.abs(dy) > Math.abs(dx) && Math.abs(dy) > 6) { drag = null; return; }
        if (!drag.locked && Math.abs(dx) > 6) { drag.locked = true; surface.setPointerCapture(event.pointerId); card.setAttribute("data-dragging", ""); }
        if (drag.locked && !matchMedia("(prefers-reduced-motion: reduce)").matches) { card.style.translate = `${Math.max(-80, Math.min(80, dx))}px 0px`; card.style.rotate = `${Math.max(-6, Math.min(6, dx / 15))}deg`; }
      });
      const finish = (event: PointerEvent, canceled: boolean) => {
        if (!drag || drag.id !== event.pointerId) return;
        const saved = drag; drag = null; card.removeAttribute("data-dragging");
        if (surface.hasPointerCapture(event.pointerId)) surface.releasePointerCapture(event.pointerId);
        card.style.translate = "0px"; card.style.rotate = "0deg";
        if (!canceled && saved.locked && Math.abs(event.clientX - saved.x) > Math.min(64, card.clientWidth * 0.25)) decide(event.clientX > saved.x ? "save" : "skip");
      };
      surface.addEventListener("pointerup", (event) => finish(event, false));
      surface.addEventListener("pointercancel", (event) => finish(event, true));
      surface.addEventListener("lostpointercapture", (event) => { if (event.target === surface && drag) finish(event, true); });
    });
    undo.addEventListener("click", () => { const previous = history.pop(); if (previous === undefined) return; index = previous; cards[index].querySelector<HTMLInputElement>("input[value=undecided]")!.checked = true; render(`Restored ${cards[index].dataset.label}.`); stage.focus(); root.dispatchEvent(new CustomEvent("haze:card-undo", { bubbles: true, detail: { id: cards[index].dataset.key } })); });
    const reset = () => { index = 0; history = []; cards.forEach((card) => { card.querySelector<HTMLInputElement>("input[value=undecided]")!.checked = true; }); render("Review restarted."); };
    root.querySelector<HTMLButtonElement>("[data-stack-reset]")!.addEventListener("click", () => { reset(); stage.focus(); });
    root.form?.addEventListener("reset", () => queueMicrotask(reset));
    root.querySelector<HTMLElement>("[data-stack-tools]")!.hidden = false;
    root.setAttribute("data-enhanced", ""); render();
  }
  const init = () => document.querySelectorAll<HTMLFieldSetElement>("[data-haze-card-stack]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-card-stack-listener")) {
    document.documentElement.setAttribute("data-haze-card-stack-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
