# Card Stack

Layered stack of cards. Swipe, arrow keys, or buttons throw the top card away and the next one rises. Loops, with a position indicator.

- Category: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/card-stack.json
- CLI: `npx markasui@latest add card-stack`

## When to use

Showing a short set of equal-weight cards one at a time in a playful way: testimonials, feature highlights, tips, or profiles.

- Keep it to 3 to 7 cards with similar height
- Give label a description of the content
- Do not put the only copy of important actions on cards behind the top one
- Use Carousel instead when people need to see several items at once

## Code

### Blade

Save at `resources/views/components/markas/card-stack.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'label' => 'Card stack',
    'prevLabel' => 'Previous card',
    'nextLabel' => 'Next card',
    'cardLabel' => '{index} of {total}',
])

@php
    $root = 'w-full';
    $stack = 'relative grid touch-pan-y rounded-xl pb-4 select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary';
    $card = 'group col-start-1 row-start-1 origin-bottom overflow-hidden rounded-xl border border-line bg-surface transition-[translate,scale,opacity,background-color] duration-300 ease-out data-[depth=0]:z-30 data-[depth=0]:cursor-grab data-[depth=1]:z-20 data-[depth=1]:translate-y-2 data-[depth=1]:scale-[0.95] data-[depth=1]:bg-subtle data-[depth=2]:z-10 data-[depth=2]:translate-y-4 data-[depth=2]:scale-[0.9] data-[depth=2]:bg-subtle data-[depth=3]:translate-y-4 data-[depth=3]:scale-[0.9] data-[depth=3]:opacity-0 data-dragging:cursor-grabbing data-dragging:transition-none data-leaving:z-40 motion-reduce:transition-none';
    $content = 'h-full opacity-0 transition-opacity duration-300 ease-out group-data-leaving:opacity-100 group-data-[depth=0]:opacity-100 motion-reduce:transition-none';
    $controls = 'mt-3 flex items-center justify-between gap-3';
    $navButton = 'inline-flex size-9 items-center justify-center rounded-full border border-line bg-surface text-ink transition-[background-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none';
    $dots = 'flex items-center gap-1.5';
    $dot = 'h-1.5 w-1.5 rounded-full bg-primary-line transition-all duration-300 ease-out data-[state=active]:w-5 data-[state=active]:bg-primary motion-reduce:transition-none';
    $icon = 'size-4';
    $srOnly = 'sr-only';

    // Every named slot becomes one card, in the order they are written.
    $cards = array_values(array_filter(
        $__laravel_slots ?? [],
        fn ($value, $key) => $key !== '__default',
        ARRAY_FILTER_USE_BOTH,
    ));
    $total = count($cards);
    $format = fn (string $template, int $index) => str_replace(['{index}', '{total}'], [$index, $total], $template);
    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-card-stack|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $stackId = ($attributes->get('id') ?? 'markas-card-stack-'.hash('xxh32', $idKey.$idIndex)).'-cards';
@endphp

{{-- Arrow keys, the buttons, or a horizontal drag throw the top card; the next one rises. The stack loops. --}}
<div
    x-data="{
        index: 0,
        total: {{ $total }},
        drag: null,
        depth(i) {
            return Math.min((i - this.index + this.total) % this.total, 3);
        },
        card(i) {
            return this.$refs.stack.children[i];
        },
        away(direction) {
            return `translateX(${direction * 120}%) rotate(${direction * 14}deg)`;
        },
        play(el, keyframes, duration) {
            if (matchMedia('(prefers-reduced-motion: reduce)').matches || ! el.animate) return null;
            el.getAnimations().forEach((animation) => animation.finish());
            return el.animate(keyframes, { duration, easing: 'cubic-bezier(0.2, 0.8, 0.2, 1)' });
        },
        fling(el, direction) {
            const from = el.style.transform || 'none';
            el.style.transform = '';
            delete el.dataset.dragging;
            el.dataset.leaving = '';
            const animation = this.play(el, [{ transform: from, opacity: 1 }, { opacity: 1, offset: 0.5 }, { transform: this.away(direction), opacity: 0 }], 450);
            if (! animation) return delete el.dataset.leaving;
            animation.onfinish = () => {
                delete el.dataset.leaving;
                this.play(el, [{ opacity: 0, offset: 0 }], 250);
            };
        },
        settle(el) {
            const from = el.style.transform;
            el.style.transform = '';
            delete el.dataset.dragging;
            if (from) this.play(el, [{ transform: from }, { transform: 'none' }], 250);
        },
        go(step, direction = -1) {
            if (this.total < 2) return;
            const target = (this.index + step + this.total) % this.total;
            if (step === 1) this.fling(this.card(this.index), direction);
            if (step === -1) this.play(this.card(target), [{ transform: this.away(direction), opacity: 0 }, { transform: 'none', opacity: 1 }], 450);
            this.index = target;
        },
        down(event) {
            if (event.button !== 0 || this.total < 2) return;
            this.drag = { x: event.clientX, moved: false };
        },
        move(event) {
            if (! this.drag) return;
            const top = this.card(this.index);
            const dx = event.clientX - this.drag.x;
            if (! this.drag.moved) {
                if (Math.abs(dx) < 4) return;
                this.drag.moved = true;
                event.currentTarget.setPointerCapture(event.pointerId);
                top.dataset.dragging = '';
            }
            top.style.transform = `translateX(${dx}px) rotate(${dx / 20}deg)`;
        },
        up(event) {
            const state = this.drag;
            this.drag = null;
            if (! state?.moved) return;
            const dx = event.clientX - state.x;
            if (Math.abs(dx) > event.currentTarget.offsetWidth * 0.25) this.go(1, Math.sign(dx));
            else this.settle(this.card(this.index));
        },
        cancel() {
            if (this.drag?.moved) this.settle(this.card(this.index));
            this.drag = null;
        },
    }"
    x-on:keydown.right="if (! $event.defaultPrevented) { $event.preventDefault(); go(1); }"
    x-on:keydown.left="if (! $event.defaultPrevented) { $event.preventDefault(); go(-1); }"
    {{ $attributes->merge(['role' => 'region', 'aria-roledescription' => 'carousel', 'aria-label' => $label])->class([$root]) }}
>
    <div
        x-ref="stack"
        id="{{ $stackId }}"
        tabindex="0"
        x-on:pointerdown="down($event)"
        x-on:pointermove="move($event)"
        x-on:pointerup="up($event)"
        x-on:pointercancel="cancel()"
        class="{{ $stack }}"
    >
        @foreach ($cards as $index => $cardSlot)
            <div
                role="group"
                aria-roledescription="slide"
                aria-label="{{ $format($cardLabel, $index + 1) }}"
                data-depth="{{ min($index, 3) }}"
                @if ($index !== 0) inert @endif
                x-bind:data-depth="depth({{ $index }})"
                x-bind:inert="depth({{ $index }}) !== 0"
                class="{{ $card }}"
            ><div class="{{ $content }}">{{ $cardSlot }}</div></div>
        @endforeach
    </div>
    <div class="{{ $controls }}">
        <button
            type="button"
            aria-label="{{ $prevLabel }}"
            aria-controls="{{ $stackId }}"
            @if ($total < 2) disabled @endif
            x-on:click="go(-1)"
            class="{{ $navButton }}"
        >
            <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $icon }}"><path d="m15 18-6-6 6-6" /></svg>
        </button>
        <div aria-hidden="true" class="{{ $dots }}">
            @foreach ($cards as $index => $cardSlot)
                <span
                    data-state="{{ $index === 0 ? 'active' : 'inactive' }}"
                    x-bind:data-state="index === {{ $index }} ? 'active' : 'inactive'"
                    class="{{ $dot }}"
                ></span>
            @endforeach
        </div>
        <button
            type="button"
            aria-label="{{ $nextLabel }}"
            aria-controls="{{ $stackId }}"
            @if ($total < 2) disabled @endif
            x-on:click="go(1)"
            class="{{ $navButton }}"
        >
            <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $icon }}"><path d="m9 18 6-6-6-6" /></svg>
        </button>
    </div>
    <p aria-live="polite" class="{{ $srOnly }}" x-text="@js($cardLabel).replaceAll('{index}', index + 1).replaceAll('{total}', total)">{{ $format($cardLabel, 1) }}</p>
</div>
```

```blade
<x-markas.card-stack label="Customer testimonials">
    <x-slot:maya>
        <figure class="grid gap-6 p-5">
            <blockquote>Onboarding a new hire now takes an afternoon.</blockquote>
            <figcaption class="text-sm text-muted">Maya Putri, Kopiloka</figcaption>
        </figure>
    </x-slot:maya>
    <x-slot:daniel>
        <figure class="grid gap-6 p-5">
            <blockquote>The keyboard shortcuts alone save us hours.</blockquote>
            <figcaption class="text-sm text-muted">Daniel Reyes, Northwind</figcaption>
        </figure>
    </x-slot:daniel>
</x-markas.card-stack>
```

Needs Alpine.js. Every named slot becomes a card, in the order you write them. For a list, use `<x-slot :name="'card-'.$index">` inside `@foreach`.

### React

Save at `src/components/markas/CardStack.tsx`. No extra dependencies.

```tsx
"use client";

import {
  Children,
  useId,
  useRef,
  useState,
  type ComponentProps,
  type KeyboardEvent,
  type PointerEvent,
} from "react";

const root = "w-full";
const stack =
  "relative grid touch-pan-y rounded-xl pb-4 select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const card =
  "group col-start-1 row-start-1 origin-bottom overflow-hidden rounded-xl border border-line bg-surface transition-[translate,scale,opacity,background-color] duration-300 ease-out data-[depth=0]:z-30 data-[depth=0]:cursor-grab data-[depth=1]:z-20 data-[depth=1]:translate-y-2 data-[depth=1]:scale-[0.95] data-[depth=1]:bg-subtle data-[depth=2]:z-10 data-[depth=2]:translate-y-4 data-[depth=2]:scale-[0.9] data-[depth=2]:bg-subtle data-[depth=3]:translate-y-4 data-[depth=3]:scale-[0.9] data-[depth=3]:opacity-0 data-dragging:cursor-grabbing data-dragging:transition-none data-leaving:z-40 motion-reduce:transition-none";
const content =
  "h-full opacity-0 transition-opacity duration-300 ease-out group-data-leaving:opacity-100 group-data-[depth=0]:opacity-100 motion-reduce:transition-none";
const controls = "mt-3 flex items-center justify-between gap-3";
const navButton =
  "inline-flex size-9 items-center justify-center rounded-full border border-line bg-surface text-ink transition-[background-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const dots = "flex items-center gap-1.5";
const dot =
  "h-1.5 w-1.5 rounded-full bg-primary-line transition-all duration-300 ease-out data-[state=active]:w-5 data-[state=active]:bg-primary motion-reduce:transition-none";
const icon = "size-4";
const srOnly = "sr-only";

const FLING_MS = 450;
const SETTLE_MS = 250;
const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";
/** Share of the stack width a drag must pass to throw the card. */
const SWIPE_RATIO = 0.25;
/** Pixels of movement before a press becomes a drag, so clicks inside cards still work. */
const DRAG_START = 4;
const MAX_DEPTH = 3;

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const reducedMotion = () =>
  typeof matchMedia === "function" &&
  matchMedia("(prefers-reduced-motion: reduce)").matches;

/** Fill {index} and {total} in a label. */
export const formatLabel = (template: string, index: number, total: number) =>
  template
    .replaceAll("{index}", String(index))
    .replaceAll("{total}", String(total));

const away = (direction: number) =>
  `translateX(${direction * 120}%) rotate(${direction * 14}deg)`;

function play(el: HTMLElement, keyframes: Keyframe[], duration: number) {
  if (reducedMotion() || typeof el.animate !== "function") return undefined;
  el.getAnimations().forEach((animation) => animation.finish());
  return el.animate(keyframes, { duration, easing: EASE });
}

/** Throw the card off to one side; it then fades in at the back of the stack. */
function fling(el: HTMLElement, direction: number) {
  const from = el.style.transform || "none";
  el.style.transform = "";
  delete el.dataset.dragging;
  el.dataset.leaving = "";
  const animation = play(
    el,
    [
      { transform: from, opacity: 1 },
      { opacity: 1, offset: 0.5 },
      { transform: away(direction), opacity: 0 },
    ],
    FLING_MS,
  );
  if (!animation) {
    delete el.dataset.leaving;
    return;
  }
  animation.onfinish = () => {
    delete el.dataset.leaving;
    play(el, [{ opacity: 0, offset: 0 }], SETTLE_MS);
  };
}

/** Slide a card back in from one side. */
const arrive = (el: HTMLElement, direction: number) =>
  play(
    el,
    [
      { transform: away(direction), opacity: 0 },
      { transform: "none", opacity: 1 },
    ],
    FLING_MS,
  );

/** Spring a dragged card back to the middle. */
function settle(el: HTMLElement) {
  const from = el.style.transform;
  el.style.transform = "";
  delete el.dataset.dragging;
  if (from) play(el, [{ transform: from }, { transform: "none" }], SETTLE_MS);
}

export type CardStackProps = ComponentProps<"div"> & {
  /** Accessible name of the stack region. */
  label?: string;
  prevLabel?: string;
  nextLabel?: string;
  /** Name of each card and the live position text. Accepts {index} and {total}. */
  cardLabel?: string;
};

export function CardStack({
  label = "Card stack",
  prevLabel = "Previous card",
  nextLabel = "Next card",
  cardLabel = "{index} of {total}",
  id,
  className,
  children,
  onKeyDown,
  ...props
}: CardStackProps) {
  const generatedId = useId();
  const stackId = `${id ?? generatedId}-cards`;
  const cards = Children.toArray(children);
  const total = cards.length;
  const [index, setIndex] = useState(0);
  const stackRef = useRef<HTMLDivElement>(null);
  const drag = useRef<{ x: number; moved: boolean } | null>(null);

  const cardAt = (i: number) =>
    stackRef.current?.children[i] as HTMLElement | undefined;

  /** Step forward (throw the top card) or back (bring the last card in). */
  const go = (step: 1 | -1, direction = -1) => {
    if (total < 2) return;
    const target = (index + step + total) % total;
    const top = cardAt(index);
    const incoming = cardAt(target);
    if (step === 1 && top) fling(top, direction);
    if (step === -1 && incoming) arrive(incoming, direction);
    setIndex(target);
  };

  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(event);
    const steps: Record<string, 1 | -1 | undefined> = {
      ArrowRight: 1,
      ArrowLeft: -1,
    };
    const step = steps[event.key];
    if (step === undefined || event.defaultPrevented) return;
    event.preventDefault();
    go(step);
  };

  const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {
    if (event.button !== 0 || total < 2) return;
    drag.current = { x: event.clientX, moved: false };
  };
  const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {
    const state = drag.current;
    const top = cardAt(index);
    if (!state || !top) return;
    const dx = event.clientX - state.x;
    if (!state.moved) {
      if (Math.abs(dx) < DRAG_START) return;
      state.moved = true;
      event.currentTarget.setPointerCapture?.(event.pointerId);
      top.dataset.dragging = "";
    }
    top.style.transform = `translateX(${dx}px) rotate(${dx / 20}deg)`;
  };
  const handlePointerUp = (event: PointerEvent<HTMLDivElement>) => {
    const state = drag.current;
    drag.current = null;
    const top = cardAt(index);
    if (!state?.moved || !top) return;
    const dx = event.clientX - state.x;
    if (Math.abs(dx) > event.currentTarget.offsetWidth * SWIPE_RATIO)
      go(1, Math.sign(dx));
    else settle(top);
  };
  const handlePointerCancel = () => {
    const top = cardAt(index);
    if (drag.current?.moved && top) settle(top);
    drag.current = null;
  };

  return (
    <div
      id={id}
      role="region"
      aria-roledescription="carousel"
      aria-label={label}
      className={cx(root, className)}
      onKeyDown={handleKeyDown}
      {...props}
    >
      <div
        ref={stackRef}
        id={stackId}
        tabIndex={0}
        className={stack}
        onPointerDown={handlePointerDown}
        onPointerMove={handlePointerMove}
        onPointerUp={handlePointerUp}
        onPointerCancel={handlePointerCancel}
      >
        {cards.map((child, i) => {
          const depth = Math.min((i - index + total) % total, MAX_DEPTH);
          return (
            <div
              key={i}
              role="group"
              aria-roledescription="slide"
              aria-label={formatLabel(cardLabel, i + 1, total)}
              data-depth={depth}
              inert={depth !== 0}
              className={card}
            >
              <div className={content}>{child}</div>
            </div>
          );
        })}
      </div>
      <div className={controls}>
        <button
          type="button"
          aria-label={prevLabel}
          aria-controls={stackId}
          disabled={total < 2}
          className={navButton}
          onClick={() => go(-1)}
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            className={icon}
          >
            <path d="m15 18-6-6 6-6" />
          </svg>
        </button>
        <div aria-hidden="true" className={dots}>
          {cards.map((_, i) => (
            <span
              key={i}
              data-state={i === index ? "active" : "inactive"}
              className={dot}
            />
          ))}
        </div>
        <button
          type="button"
          aria-label={nextLabel}
          aria-controls={stackId}
          disabled={total < 2}
          className={navButton}
          onClick={() => go(1)}
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            className={icon}
          >
            <path d="m9 18 6-6-6-6" />
          </svg>
        </button>
      </div>
      <p aria-live="polite" className={srOnly}>
        {formatLabel(cardLabel, index + 1, total)}
      </p>
    </div>
  );
}
```

```tsx
import { CardStack } from "@/components/markas/CardStack";

<CardStack label="Customer testimonials">
  {testimonials.map((item) => (
    <figure key={item.name} className="grid gap-6 p-5">
      <blockquote>{item.quote}</blockquote>
      <figcaption className="text-sm text-muted">{item.name}</figcaption>
    </figure>
  ))}
</CardStack>;
```

### Vue

Save at `src/components/markas/CardStack.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import {
  Comment,
  Fragment,
  Text,
  computed,
  ref,
  useId,
  useSlots,
  useTemplateRef,
  type VNode,
} from "vue";

const props = withDefaults(
  defineProps<{
    /** Accessible name of the stack region. */
    label?: string;
    prevLabel?: string;
    nextLabel?: string;
    /** Name of each card and the live position text. Accepts {index} and {total}. */
    cardLabel?: string;
    id?: string;
  }>(),
  {
    label: "Card stack",
    prevLabel: "Previous card",
    nextLabel: "Next card",
    cardLabel: "{index} of {total}",
    id: undefined,
  },
);

const root = "w-full";
const stack =
  "relative grid touch-pan-y rounded-xl pb-4 select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const card =
  "group col-start-1 row-start-1 origin-bottom overflow-hidden rounded-xl border border-line bg-surface transition-[translate,scale,opacity,background-color] duration-300 ease-out data-[depth=0]:z-30 data-[depth=0]:cursor-grab data-[depth=1]:z-20 data-[depth=1]:translate-y-2 data-[depth=1]:scale-[0.95] data-[depth=1]:bg-subtle data-[depth=2]:z-10 data-[depth=2]:translate-y-4 data-[depth=2]:scale-[0.9] data-[depth=2]:bg-subtle data-[depth=3]:translate-y-4 data-[depth=3]:scale-[0.9] data-[depth=3]:opacity-0 data-dragging:cursor-grabbing data-dragging:transition-none data-leaving:z-40 motion-reduce:transition-none";
const content =
  "h-full opacity-0 transition-opacity duration-300 ease-out group-data-leaving:opacity-100 group-data-[depth=0]:opacity-100 motion-reduce:transition-none";
const controls = "mt-3 flex items-center justify-between gap-3";
const navButton =
  "inline-flex size-9 items-center justify-center rounded-full border border-line bg-surface text-ink transition-[background-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const dots = "flex items-center gap-1.5";
const dot =
  "h-1.5 w-1.5 rounded-full bg-primary-line transition-all duration-300 ease-out data-[state=active]:w-5 data-[state=active]:bg-primary motion-reduce:transition-none";
const icon = "size-4";
const srOnly = "sr-only";

const FLING_MS = 450;
const SETTLE_MS = 250;
const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";
/** Share of the stack width a drag must pass to throw the card. */
const SWIPE_RATIO = 0.25;
/** Pixels of movement before a press becomes a drag, so clicks inside cards still work. */
const DRAG_START = 4;
const MAX_DEPTH = 3;

const slots = useSlots();
const generatedId = useId();
const stackId = computed(() => `${props.id ?? generatedId}-cards`);
const stackEl = useTemplateRef<HTMLDivElement>("stackRef");
const index = ref(0);
let drag: { x: number; moved: boolean } | null = null;

/** Flatten fragments (v-for) and drop comments or blank text so each element is one card. */
function flatten(nodes: VNode[]): VNode[] {
  return nodes.flatMap((node) => {
    if (node.type === Fragment) return flatten(node.children as VNode[]);
    if (node.type === Comment) return [];
    if (node.type === Text && String(node.children).trim() === "") return [];
    return [node];
  });
}
const cards = (): VNode[] => flatten(slots.default?.() ?? []);
const total = () => cards().length;

const formatLabel = (template: string, i: number, count: number) =>
  template
    .replaceAll("{index}", String(i))
    .replaceAll("{total}", String(count));
const depthOf = (i: number) =>
  Math.min((i - index.value + total()) % total(), MAX_DEPTH);

const reducedMotion = () =>
  typeof matchMedia === "function" &&
  matchMedia("(prefers-reduced-motion: reduce)").matches;
const away = (direction: number) =>
  `translateX(${direction * 120}%) rotate(${direction * 14}deg)`;

type Frames = Parameters<HTMLElement["animate"]>[0];

function play(el: HTMLElement, keyframes: Frames, duration: number) {
  if (reducedMotion() || typeof el.animate !== "function") return undefined;
  el.getAnimations().forEach((animation) => animation.finish());
  return el.animate(keyframes, { duration, easing: EASE });
}

/** Throw the card off to one side; it then fades in at the back of the stack. */
function fling(el: HTMLElement, direction: number) {
  const from = el.style.transform || "none";
  el.style.transform = "";
  delete el.dataset.dragging;
  el.dataset.leaving = "";
  const animation = play(
    el,
    [
      { transform: from, opacity: 1 },
      { opacity: 1, offset: 0.5 },
      { transform: away(direction), opacity: 0 },
    ],
    FLING_MS,
  );
  if (!animation) {
    delete el.dataset.leaving;
    return;
  }
  animation.onfinish = () => {
    delete el.dataset.leaving;
    play(el, [{ opacity: 0, offset: 0 }], SETTLE_MS);
  };
}

/** Slide a card back in from one side. */
const arrive = (el: HTMLElement, direction: number) =>
  play(
    el,
    [
      { transform: away(direction), opacity: 0 },
      { transform: "none", opacity: 1 },
    ],
    FLING_MS,
  );

/** Spring a dragged card back to the middle. */
function settle(el: HTMLElement) {
  const from = el.style.transform;
  el.style.transform = "";
  delete el.dataset.dragging;
  if (from) play(el, [{ transform: from }, { transform: "none" }], SETTLE_MS);
}

const cardAt = (i: number) =>
  stackEl.value?.children[i] as HTMLElement | undefined;

/** Step forward (throw the top card) or back (bring the last card in). */
function go(step: 1 | -1, direction = -1) {
  const count = total();
  if (count < 2) return;
  const target = (index.value + step + count) % count;
  const top = cardAt(index.value);
  const incoming = cardAt(target);
  if (step === 1 && top) fling(top, direction);
  if (step === -1 && incoming) arrive(incoming, direction);
  index.value = target;
}

function onKeydown(event: KeyboardEvent) {
  const steps: Record<string, 1 | -1 | undefined> = {
    ArrowRight: 1,
    ArrowLeft: -1,
  };
  const step = steps[event.key];
  if (step === undefined || event.defaultPrevented) return;
  event.preventDefault();
  go(step);
}

function onPointerdown(event: PointerEvent) {
  if (event.button !== 0 || total() < 2) return;
  drag = { x: event.clientX, moved: false };
}
function onPointermove(event: PointerEvent) {
  const top = cardAt(index.value);
  if (!drag || !top) return;
  const dx = event.clientX - drag.x;
  if (!drag.moved) {
    if (Math.abs(dx) < DRAG_START) return;
    drag.moved = true;
    (event.currentTarget as HTMLElement).setPointerCapture?.(event.pointerId);
    top.dataset.dragging = "";
  }
  top.style.transform = `translateX(${dx}px) rotate(${dx / 20}deg)`;
}
function onPointerup(event: PointerEvent) {
  const state = drag;
  drag = null;
  const top = cardAt(index.value);
  if (!state?.moved || !top) return;
  const dx = event.clientX - state.x;
  const width = (event.currentTarget as HTMLElement).offsetWidth;
  if (Math.abs(dx) > width * SWIPE_RATIO) go(1, Math.sign(dx));
  else settle(top);
}
function onPointercancel() {
  const top = cardAt(index.value);
  if (drag?.moved && top) settle(top);
  drag = null;
}
</script>

<template>
  <div
    :id="props.id"
    role="region"
    aria-roledescription="carousel"
    :aria-label="props.label"
    :class="root"
    @keydown="onKeydown"
  >
    <div
      :id="stackId"
      ref="stackRef"
      tabindex="0"
      :class="stack"
      @pointerdown="onPointerdown"
      @pointermove="onPointermove"
      @pointerup="onPointerup"
      @pointercancel="onPointercancel"
    >
      <div
        v-for="(child, i) in cards()"
        :key="i"
        role="group"
        aria-roledescription="slide"
        :aria-label="formatLabel(props.cardLabel, i + 1, total())"
        :data-depth="depthOf(i)"
        :inert="depthOf(i) !== 0 || undefined"
        :class="card"
      >
        <div :class="content"><component :is="child" /></div>
      </div>
    </div>
    <div :class="controls">
      <button
        type="button"
        :aria-label="props.prevLabel"
        :aria-controls="stackId"
        :disabled="total() < 2"
        :class="navButton"
        @click="go(-1)"
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          :class="icon"
        >
          <path d="m15 18-6-6 6-6" />
        </svg>
      </button>
      <div aria-hidden="true" :class="dots">
        <span
          v-for="(_, i) in cards()"
          :key="i"
          :data-state="i === index ? 'active' : 'inactive'"
          :class="dot"
        />
      </div>
      <button
        type="button"
        :aria-label="props.nextLabel"
        :aria-controls="stackId"
        :disabled="total() < 2"
        :class="navButton"
        @click="go(1)"
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          :class="icon"
        >
          <path d="m9 18 6-6-6-6" />
        </svg>
      </button>
    </div>
    <p aria-live="polite" :class="srOnly">
      {{ formatLabel(props.cardLabel, index + 1, total()) }}
    </p>
  </div>
</template>
```

```vue
<template>
  <CardStack label="Customer testimonials">
    <figure
      v-for="item in testimonials"
      :key="item.name"
      class="grid gap-6 p-5"
    >
      <blockquote>{{ item.quote }}</blockquote>
      <figcaption class="text-sm text-muted">{{ item.name }}</figcaption>
    </figure>
  </CardStack>
</template>
```

### Svelte

Save at `src/lib/components/markas/CardStack.svelte`. No extra dependencies.

```svelte
<script lang="ts" module>
  /** Fill {index} and {total} in a label. */
  export const formatLabel = (template: string, index: number, total: number) =>
    template
      .replaceAll("{index}", String(index))
      .replaceAll("{total}", String(total));
</script>

<script lang="ts" generics="T">
  import type { Snippet } from "svelte";
  import type { HTMLAttributes } from "svelte/elements";

  const root = "w-full";
  const stack =
    "relative grid touch-pan-y rounded-xl pb-4 select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
  const card =
    "group col-start-1 row-start-1 origin-bottom overflow-hidden rounded-xl border border-line bg-surface transition-[translate,scale,opacity,background-color] duration-300 ease-out data-[depth=0]:z-30 data-[depth=0]:cursor-grab data-[depth=1]:z-20 data-[depth=1]:translate-y-2 data-[depth=1]:scale-[0.95] data-[depth=1]:bg-subtle data-[depth=2]:z-10 data-[depth=2]:translate-y-4 data-[depth=2]:scale-[0.9] data-[depth=2]:bg-subtle data-[depth=3]:translate-y-4 data-[depth=3]:scale-[0.9] data-[depth=3]:opacity-0 data-dragging:cursor-grabbing data-dragging:transition-none data-leaving:z-40 motion-reduce:transition-none";
  const content =
    "h-full opacity-0 transition-opacity duration-300 ease-out group-data-leaving:opacity-100 group-data-[depth=0]:opacity-100 motion-reduce:transition-none";
  const controls = "mt-3 flex items-center justify-between gap-3";
  const navButton =
    "inline-flex size-9 items-center justify-center rounded-full border border-line bg-surface text-ink transition-[background-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
  const dots = "flex items-center gap-1.5";
  const dot =
    "h-1.5 w-1.5 rounded-full bg-primary-line transition-all duration-300 ease-out data-[state=active]:w-5 data-[state=active]:bg-primary motion-reduce:transition-none";
  const icon = "size-4";
  const srOnly = "sr-only";

  const FLING_MS = 450;
  const SETTLE_MS = 250;
  const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";
  /** Share of the stack width a drag must pass to throw the card. */
  const SWIPE_RATIO = 0.25;
  /** Pixels of movement before a press becomes a drag, so clicks inside cards still work. */
  const DRAG_START = 4;
  const MAX_DEPTH = 3;

  const reducedMotion = () =>
    typeof matchMedia === "function" &&
    matchMedia("(prefers-reduced-motion: reduce)").matches;

  const away = (direction: number) =>
    `translateX(${direction * 120}%) rotate(${direction * 14}deg)`;

  function play(el: HTMLElement, keyframes: Keyframe[], duration: number) {
    if (reducedMotion() || typeof el.animate !== "function") return undefined;
    el.getAnimations().forEach((animation) => animation.finish());
    return el.animate(keyframes, { duration, easing: EASE });
  }

  /** Throw the card off to one side; it then fades in at the back of the stack. */
  function fling(el: HTMLElement, direction: number) {
    const from = el.style.transform || "none";
    el.style.transform = "";
    delete el.dataset.dragging;
    el.dataset.leaving = "";
    const animation = play(
      el,
      [
        { transform: from, opacity: 1 },
        { opacity: 1, offset: 0.5 },
        { transform: away(direction), opacity: 0 },
      ],
      FLING_MS,
    );
    if (!animation) {
      delete el.dataset.leaving;
      return;
    }
    animation.onfinish = () => {
      delete el.dataset.leaving;
      play(el, [{ opacity: 0, offset: 0 }], SETTLE_MS);
    };
  }

  /** Slide a card back in from one side. */
  const arrive = (el: HTMLElement, direction: number) =>
    play(
      el,
      [
        { transform: away(direction), opacity: 0 },
        { transform: "none", opacity: 1 },
      ],
      FLING_MS,
    );

  /** Spring a dragged card back to the middle. */
  function settle(el: HTMLElement) {
    const from = el.style.transform;
    el.style.transform = "";
    delete el.dataset.dragging;
    if (from) play(el, [{ transform: from }, { transform: "none" }], SETTLE_MS);
  }

  type Props = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
    /** One card per item, drawn by the card snippet. */
    items: T[];
    card: Snippet<[T, number]>;
    /** Accessible name of the stack region. */
    label?: string;
    prevLabel?: string;
    nextLabel?: string;
    /** Name of each card and the live position text. Accepts {index} and {total}. */
    cardLabel?: string;
  };

  let {
    items,
    card: cardSnippet,
    label = "Card stack",
    prevLabel = "Previous card",
    nextLabel = "Next card",
    cardLabel = "{index} of {total}",
    id,
    class: className,
    onkeydown,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const stackId = $derived(`${id ?? generatedId}-cards`);
  const total = $derived(items.length);
  let index = $state(0);
  let stackEl = $state<HTMLDivElement>();
  let drag: { x: number; moved: boolean } | null = null;

  const cardAt = (i: number) => stackEl?.children[i] as HTMLElement | undefined;
  const depthOf = (i: number) =>
    Math.min((i - index + total) % total, MAX_DEPTH);

  /** Step forward (throw the top card) or back (bring the last card in). */
  function go(step: 1 | -1, direction = -1) {
    if (total < 2) return;
    const target = (index + step + total) % total;
    const top = cardAt(index);
    const incoming = cardAt(target);
    if (step === 1 && top) fling(top, direction);
    if (step === -1 && incoming) arrive(incoming, direction);
    index = target;
  }

  function handleKeydown(
    event: KeyboardEvent & { currentTarget: HTMLDivElement },
  ) {
    onkeydown?.(event);
    const steps: Record<string, 1 | -1 | undefined> = {
      ArrowRight: 1,
      ArrowLeft: -1,
    };
    const step = steps[event.key];
    if (step === undefined || event.defaultPrevented) return;
    event.preventDefault();
    go(step);
  }

  function handlePointerdown(event: PointerEvent) {
    if (event.button !== 0 || total < 2) return;
    drag = { x: event.clientX, moved: false };
  }

  function handlePointermove(
    event: PointerEvent & { currentTarget: HTMLDivElement },
  ) {
    const top = cardAt(index);
    if (!drag || !top) return;
    const dx = event.clientX - drag.x;
    if (!drag.moved) {
      if (Math.abs(dx) < DRAG_START) return;
      drag.moved = true;
      event.currentTarget.setPointerCapture?.(event.pointerId);
      top.dataset.dragging = "";
    }
    top.style.transform = `translateX(${dx}px) rotate(${dx / 20}deg)`;
  }

  function handlePointerup(
    event: PointerEvent & { currentTarget: HTMLDivElement },
  ) {
    const state = drag;
    drag = null;
    const top = cardAt(index);
    if (!state?.moved || !top) return;
    const dx = event.clientX - state.x;
    if (Math.abs(dx) > event.currentTarget.offsetWidth * SWIPE_RATIO)
      go(1, Math.sign(dx));
    else settle(top);
  }

  function handlePointercancel() {
    const top = cardAt(index);
    if (drag?.moved && top) settle(top);
    drag = null;
  }
</script>

<div
  {id}
  role="region"
  aria-roledescription="carousel"
  aria-label={label}
  class={[root, className]}
  onkeydown={handleKeydown}
  {...rest}
>
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
  <!-- svelte-ignore a11y_no_static_element_interactions -->
  <div
    bind:this={stackEl}
    id={stackId}
    tabindex="0"
    class={stack}
    onpointerdown={handlePointerdown}
    onpointermove={handlePointermove}
    onpointerup={handlePointerup}
    onpointercancel={handlePointercancel}
  >
    {#each items as item, i (i)}
      <div
        role="group"
        aria-roledescription="slide"
        aria-label={formatLabel(cardLabel, i + 1, total)}
        data-depth={depthOf(i)}
        inert={depthOf(i) !== 0}
        class={card}
      >
        <div class={content}>{@render cardSnippet(item, i)}</div>
      </div>
    {/each}
  </div>
  <div class={controls}>
    <button
      type="button"
      aria-label={prevLabel}
      aria-controls={stackId}
      disabled={total < 2}
      class={navButton}
      onclick={() => go(-1)}
    >
      <svg
        aria-hidden="true"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        class={icon}
      >
        <path d="m15 18-6-6 6-6" />
      </svg>
    </button>
    <div aria-hidden="true" class={dots}>
      {#each items as _, i (i)}
        <span data-state={i === index ? "active" : "inactive"} class={dot}
        ></span>
      {/each}
    </div>
    <button
      type="button"
      aria-label={nextLabel}
      aria-controls={stackId}
      disabled={total < 2}
      class={navButton}
      onclick={() => go(1)}
    >
      <svg
        aria-hidden="true"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        class={icon}
      >
        <path d="m9 18 6-6-6-6" />
      </svg>
    </button>
  </div>
  <p aria-live="polite" class={srOnly}>
    {formatLabel(cardLabel, index + 1, total)}
  </p>
</div>
```

```svelte
<script lang="ts">
  import CardStack from "$lib/components/markas/CardStack.svelte";
</script>

<CardStack label="Customer testimonials" items={testimonials}>
  {#snippet card(item)}
    <figure class="grid gap-6 p-5">
      <blockquote>{item.quote}</blockquote>
      <figcaption class="text-sm text-muted">{item.name}</figcaption>
    </figure>
  {/snippet}
</CardStack>
```

Svelte, Astro, and Angular take the cards as `items` and draw each one with a snippet, a function child, or an `ng-template`. Svelte reads `{index}` in a plain attribute as an expression, so pass label templates in braces: `cardLabel={"Tip {index} of {total}"}`.

### Astro

Save at `src/components/markas/CardStack.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root = "w-full";
const stack =
  "relative grid touch-pan-y rounded-xl pb-4 select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const card =
  "group col-start-1 row-start-1 origin-bottom overflow-hidden rounded-xl border border-line bg-surface transition-[translate,scale,opacity,background-color] duration-300 ease-out data-[depth=0]:z-30 data-[depth=0]:cursor-grab data-[depth=1]:z-20 data-[depth=1]:translate-y-2 data-[depth=1]:scale-[0.95] data-[depth=1]:bg-subtle data-[depth=2]:z-10 data-[depth=2]:translate-y-4 data-[depth=2]:scale-[0.9] data-[depth=2]:bg-subtle data-[depth=3]:translate-y-4 data-[depth=3]:scale-[0.9] data-[depth=3]:opacity-0 data-dragging:cursor-grabbing data-dragging:transition-none data-leaving:z-40 motion-reduce:transition-none";
const content =
  "h-full opacity-0 transition-opacity duration-300 ease-out group-data-leaving:opacity-100 group-data-[depth=0]:opacity-100 motion-reduce:transition-none";
const controls = "mt-3 flex items-center justify-between gap-3";
const navButton =
  "inline-flex size-9 items-center justify-center rounded-full border border-line bg-surface text-ink transition-[background-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const dots = "flex items-center gap-1.5";
const dot =
  "h-1.5 w-1.5 rounded-full bg-primary-line transition-all duration-300 ease-out data-[state=active]:w-5 data-[state=active]:bg-primary motion-reduce:transition-none";
const icon = "size-4";
const srOnly = "sr-only";
const MAX_DEPTH = 3;

type Props = HTMLAttributes<"div"> & {
  /** One card per item, drawn by the function passed as the default slot. */
  items: unknown[];
  /** Accessible name of the stack region. */
  label?: string;
  prevLabel?: string;
  nextLabel?: string;
  /** Name of each card and the live position text. Accepts {index} and {total}. */
  cardLabel?: string;
};

const {
  items,
  label = "Card stack",
  prevLabel = "Previous card",
  nextLabel = "Next card",
  cardLabel = "{index} of {total}",
  id,
  class: className,
  ...rest
} = Astro.props;

/** Fill {index} and {total} in a label. */
const formatLabel = (template: string, index: number, total: number) =>
  template
    .replaceAll("{index}", String(index))
    .replaceAll("{total}", String(total));

const total = items.length;
const stackId = `${id ?? `markas-card-stack-${crypto.randomUUID().slice(0, 8)}`}-cards`;
const cards = await Promise.all(
  items.map((item, index) => Astro.slots.render("default", [item, index])),
);
---

<markas-card-stack class="contents" data-card-label={cardLabel}>
  <div
    id={id}
    role="region"
    aria-roledescription="carousel"
    aria-label={label}
    class:list={[root, className]}
    {...rest}
  >
    <div id={stackId} tabindex="0" class={stack} data-stack>
      {
        cards.map((html, index) => (
          <div
            role="group"
            aria-roledescription="slide"
            aria-label={formatLabel(cardLabel, index + 1, total)}
            data-depth={Math.min(index, MAX_DEPTH)}
            inert={index !== 0}
            class={card}
          >
            <div class={content} set:html={html} />
          </div>
        ))
      }
    </div>
    <div class={controls}>
      <button
        type="button"
        aria-label={prevLabel}
        aria-controls={stackId}
        disabled={total < 2}
        data-step="-1"
        class={navButton}
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          class={icon}
        >
          <path d="m15 18-6-6 6-6"></path>
        </svg>
      </button>
      <div aria-hidden="true" class={dots}>
        {
          cards.map((_, index) => (
            <span
              data-state={index === 0 ? "active" : "inactive"}
              data-dot
              class={dot}
            />
          ))
        }
      </div>
      <button
        type="button"
        aria-label={nextLabel}
        aria-controls={stackId}
        disabled={total < 2}
        data-step="1"
        class={navButton}
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          class={icon}
        >
          <path d="m9 18 6-6-6-6"></path>
        </svg>
      </button>
    </div>
    <p aria-live="polite" class={srOnly} data-live>
      {formatLabel(cardLabel, 1, total)}
    </p>
  </div>
</markas-card-stack>

<script>
  const FLING_MS = 450;
  const SETTLE_MS = 250;
  const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";
  /** Share of the stack width a drag must pass to throw the card. */
  const SWIPE_RATIO = 0.25;
  /** Pixels of movement before a press becomes a drag, so clicks inside cards still work. */
  const DRAG_START = 4;
  const MAX_DEPTH = 3;

  const away = (direction: number) =>
    `translateX(${direction * 120}%) rotate(${direction * 14}deg)`;

  function play(el: HTMLElement, keyframes: Keyframe[], duration: number) {
    if (
      matchMedia("(prefers-reduced-motion: reduce)").matches ||
      typeof el.animate !== "function"
    )
      return undefined;
    el.getAnimations().forEach((animation) => animation.finish());
    return el.animate(keyframes, { duration, easing: EASE });
  }

  /** Throw the card off to one side; it then fades in at the back of the stack. */
  function fling(el: HTMLElement, direction: number) {
    const from = el.style.transform || "none";
    el.style.transform = "";
    delete el.dataset.dragging;
    el.dataset.leaving = "";
    const animation = play(
      el,
      [
        { transform: from, opacity: 1 },
        { opacity: 1, offset: 0.5 },
        { transform: away(direction), opacity: 0 },
      ],
      FLING_MS,
    );
    if (!animation) {
      delete el.dataset.leaving;
      return;
    }
    animation.onfinish = () => {
      delete el.dataset.leaving;
      play(el, [{ opacity: 0, offset: 0 }], SETTLE_MS);
    };
  }

  /** Spring a dragged card back to the middle. */
  function settle(el: HTMLElement) {
    const from = el.style.transform;
    el.style.transform = "";
    delete el.dataset.dragging;
    if (from) play(el, [{ transform: from }, { transform: "none" }], SETTLE_MS);
  }

  // Each stack keeps its own position, so it is a custom element: it also works for markup
  // added later and for pages reached through view transitions.
  class MarkasCardStack extends HTMLElement {
    private index = 0;
    private drag: { x: number; moved: boolean } | null = null;
    private ready = false;

    connectedCallback() {
      const stack = this.querySelector<HTMLElement>("[data-stack]");
      if (this.ready || !stack) return;
      this.ready = true;
      this.addEventListener("click", (event) => {
        const button = (event.target as Element).closest<HTMLElement>(
          "[data-step]",
        );
        if (button) this.go(stack, Number(button.dataset.step) as 1 | -1);
      });
      this.addEventListener("keydown", (event) => {
        const steps: Record<string, 1 | -1 | undefined> = {
          ArrowRight: 1,
          ArrowLeft: -1,
        };
        const step = steps[event.key];
        if (step === undefined || event.defaultPrevented) return;
        event.preventDefault();
        this.go(stack, step);
      });
      stack.addEventListener("pointerdown", (event) => {
        if (event.button !== 0 || stack.children.length < 2) return;
        this.drag = { x: event.clientX, moved: false };
      });
      stack.addEventListener("pointermove", (event) => {
        const top = stack.children[this.index] as HTMLElement | undefined;
        if (!this.drag || !top) return;
        const dx = event.clientX - this.drag.x;
        if (!this.drag.moved) {
          if (Math.abs(dx) < DRAG_START) return;
          this.drag.moved = true;
          stack.setPointerCapture?.(event.pointerId);
          top.dataset.dragging = "";
        }
        top.style.transform = `translateX(${dx}px) rotate(${dx / 20}deg)`;
      });
      stack.addEventListener("pointerup", (event) => {
        const state = this.drag;
        this.drag = null;
        const top = stack.children[this.index] as HTMLElement | undefined;
        if (!state?.moved || !top) return;
        const dx = event.clientX - state.x;
        if (Math.abs(dx) > stack.offsetWidth * SWIPE_RATIO)
          this.go(stack, 1, Math.sign(dx));
        else settle(top);
      });
      stack.addEventListener("pointercancel", () => {
        const top = stack.children[this.index] as HTMLElement | undefined;
        if (this.drag?.moved && top) settle(top);
        this.drag = null;
      });
    }

    /** Step forward (throw the top card) or back (bring the last card in). */
    private go(stack: HTMLElement, step: 1 | -1, direction = -1) {
      const cards = Array.from(stack.children) as HTMLElement[];
      const total = cards.length;
      if (total < 2) return;
      const target = (this.index + step + total) % total;
      const top = cards[this.index];
      const incoming = cards[target];
      if (step === 1 && top) fling(top, direction);
      if (step === -1 && incoming)
        play(
          incoming,
          [
            { transform: away(direction), opacity: 0 },
            { transform: "none", opacity: 1 },
          ],
          FLING_MS,
        );
      this.index = target;
      cards.forEach((card, i) => {
        const depth = Math.min((i - target + total) % total, MAX_DEPTH);
        card.dataset.depth = String(depth);
        card.inert = depth !== 0;
      });
      this.querySelectorAll<HTMLElement>("[data-dot]").forEach((dot, i) => {
        dot.dataset.state = i === target ? "active" : "inactive";
      });
      const live = this.querySelector("[data-live]");
      if (live)
        live.textContent = (this.dataset.cardLabel ?? "")
          .replaceAll("{index}", String(target + 1))
          .replaceAll("{total}", String(total));
    }
  }

  if (!customElements.get("markas-card-stack"))
    customElements.define("markas-card-stack", MarkasCardStack);
</script>
```

```astro
---
import CardStack from "@/components/markas/CardStack.astro";
---

<CardStack label="Customer testimonials" items={testimonials}>
  {
    (item: Testimonial) => (
      <figure class="grid gap-6 p-5">
        <blockquote>{item.quote}</blockquote>
        <figcaption class="text-sm text-muted">{item.name}</figcaption>
      </figure>
    )
  }
</CardStack>
```

Each stack is a small custom element, so it keeps working after view transitions.

### Angular

Save at `src/app/markas/card-stack.component.ts`. No extra dependencies.

```ts
import { NgTemplateOutlet } from "@angular/common";
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  computed,
  contentChild,
  type ElementRef,
  inject,
  input,
  signal,
  TemplateRef,
  viewChild,
} from "@angular/core";

const root = "w-full";
const stack =
  "relative grid touch-pan-y rounded-xl pb-4 select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const card =
  "group col-start-1 row-start-1 origin-bottom overflow-hidden rounded-xl border border-line bg-surface transition-[translate,scale,opacity,background-color] duration-300 ease-out data-[depth=0]:z-30 data-[depth=0]:cursor-grab data-[depth=1]:z-20 data-[depth=1]:translate-y-2 data-[depth=1]:scale-[0.95] data-[depth=1]:bg-subtle data-[depth=2]:z-10 data-[depth=2]:translate-y-4 data-[depth=2]:scale-[0.9] data-[depth=2]:bg-subtle data-[depth=3]:translate-y-4 data-[depth=3]:scale-[0.9] data-[depth=3]:opacity-0 data-dragging:cursor-grabbing data-dragging:transition-none data-leaving:z-40 motion-reduce:transition-none";
const content =
  "h-full opacity-0 transition-opacity duration-300 ease-out group-data-leaving:opacity-100 group-data-[depth=0]:opacity-100 motion-reduce:transition-none";
const controls = "mt-3 flex items-center justify-between gap-3";
const navButton =
  "inline-flex size-9 items-center justify-center rounded-full border border-line bg-surface text-ink transition-[background-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const dots = "flex items-center gap-1.5";
const dot =
  "h-1.5 w-1.5 rounded-full bg-primary-line transition-all duration-300 ease-out data-[state=active]:w-5 data-[state=active]:bg-primary motion-reduce:transition-none";
const icon = "size-4";
const srOnly = "sr-only";

const FLING_MS = 450;
const SETTLE_MS = 250;
const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";
/** Share of the stack width a drag must pass to throw the card. */
const SWIPE_RATIO = 0.25;
/** Pixels of movement before a press becomes a drag, so clicks inside cards still work. */
const DRAG_START = 4;
const MAX_DEPTH = 3;

/** Fill {index} and {total} in a label. */
export const formatLabel = (template: string, index: number, total: number) =>
  template
    .replaceAll("{index}", String(index))
    .replaceAll("{total}", String(total));

const reducedMotion = () =>
  typeof matchMedia === "function" &&
  matchMedia("(prefers-reduced-motion: reduce)").matches;

const away = (direction: number) =>
  `translateX(${direction * 120}%) rotate(${direction * 14}deg)`;

function play(el: HTMLElement, keyframes: Keyframe[], duration: number) {
  if (reducedMotion() || typeof el.animate !== "function") return undefined;
  el.getAnimations().forEach((animation) => animation.finish());
  return el.animate(keyframes, { duration, easing: EASE });
}

/** Throw the card off to one side; it then fades in at the back of the stack. */
function fling(el: HTMLElement, direction: number) {
  const from = el.style.transform || "none";
  el.style.transform = "";
  delete el.dataset.dragging;
  el.dataset.leaving = "";
  const animation = play(
    el,
    [
      { transform: from, opacity: 1 },
      { opacity: 1, offset: 0.5 },
      { transform: away(direction), opacity: 0 },
    ],
    FLING_MS,
  );
  if (!animation) {
    delete el.dataset.leaving;
    return;
  }
  animation.onfinish = () => {
    delete el.dataset.leaving;
    play(el, [{ opacity: 0, offset: 0 }], SETTLE_MS);
  };
}

/** Slide a card back in from one side. */
const arrive = (el: HTMLElement, direction: number) =>
  play(
    el,
    [
      { transform: away(direction), opacity: 0 },
      { transform: "none", opacity: 1 },
    ],
    FLING_MS,
  );

/** Spring a dragged card back to the middle. */
function settle(el: HTMLElement) {
  const from = el.style.transform;
  el.style.transform = "";
  delete el.dataset.dragging;
  if (from) play(el, [{ transform: from }, { transform: "none" }], SETTLE_MS);
}

export type CardStackContext<T> = { $implicit: T; index: number };

let nextId = 0;

/**
 * One card per item, rendered by the projected `<ng-template let-item let-index="index">`.
 * Host stays out of layout; id and class move to the region.
 */
@Component({
  selector: "markas-card-stack",
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgTemplateOutlet],
  host: { class: "contents", "[attr.id]": "null" },
  template: `
    <div
      [attr.id]="id() ?? null"
      role="region"
      aria-roledescription="carousel"
      [attr.aria-label]="label()"
      [class]="rootClasses()"
      (keydown)="handleKeydown($event)"
    >
      <div
        #stackEl
        [id]="stackId()"
        tabindex="0"
        [class]="stack"
        (pointerdown)="handlePointerdown($event)"
        (pointermove)="handlePointermove($event)"
        (pointerup)="handlePointerup($event)"
        (pointercancel)="handlePointercancel()"
      >
        @for (item of items(); track $index) {
          <div
            role="group"
            aria-roledescription="slide"
            [attr.aria-label]="cardName($index + 1)"
            [attr.data-depth]="depthOf($index)"
            [attr.inert]="depthOf($index) !== 0 ? '' : null"
            [class]="card"
          >
            <div [class]="content">
              <ng-container
                [ngTemplateOutlet]="template() ?? null"
                [ngTemplateOutletContext]="{ $implicit: item, index: $index }"
              />
            </div>
          </div>
        }
      </div>
      <div [class]="controls">
        <button
          type="button"
          [attr.aria-label]="prevLabel()"
          [attr.aria-controls]="stackId()"
          [disabled]="total() < 2"
          [class]="navButton"
          (click)="go(-1)"
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            [class]="icon"
          >
            <path d="m15 18-6-6 6-6" />
          </svg>
        </button>
        <div aria-hidden="true" [class]="dots">
          @for (item of items(); track $index) {
            <span
              [attr.data-state]="$index === index() ? 'active' : 'inactive'"
              [class]="dot"
            ></span>
          }
        </div>
        <button
          type="button"
          [attr.aria-label]="nextLabel()"
          [attr.aria-controls]="stackId()"
          [disabled]="total() < 2"
          [class]="navButton"
          (click)="go(1)"
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            [class]="icon"
          >
            <path d="m9 18 6-6-6-6" />
          </svg>
        </button>
      </div>
      <p aria-live="polite" [class]="srOnly">{{ cardName(index() + 1) }}</p>
    </div>
  `,
})
export class CardStack<T = unknown> {
  readonly items = input.required<T[]>();
  /** Accessible name of the stack region. */
  readonly label = input("Card stack");
  readonly prevLabel = input("Previous card");
  readonly nextLabel = input("Next card");
  /** Name of each card and the live position text. Accepts {index} and {total}. */
  readonly cardLabel = input("{index} of {total}");
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly template =
    contentChild<TemplateRef<CardStackContext<T>>>(TemplateRef);
  protected readonly stack = stack;
  protected readonly card = card;
  protected readonly content = content;
  protected readonly controls = controls;
  protected readonly navButton = navButton;
  protected readonly dots = dots;
  protected readonly dot = dot;
  protected readonly icon = icon;
  protected readonly srOnly = srOnly;
  protected readonly index = signal(0);
  protected readonly total = computed(() => this.items().length);
  private readonly generatedId = `markas-card-stack-${nextId++}`;
  protected readonly stackId = computed(
    () => `${this.id() ?? this.generatedId}-cards`,
  );
  protected readonly rootClasses = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly stackEl =
    viewChild.required<ElementRef<HTMLDivElement>>("stackEl");
  private drag: { x: number; moved: boolean } | null = null;
  private readonly changes = inject(ChangeDetectorRef);

  protected cardName(position: number) {
    return formatLabel(this.cardLabel(), position, this.total());
  }

  protected depthOf(i: number) {
    const total = this.total();
    return Math.min((i - this.index() + total) % total, MAX_DEPTH);
  }

  private cardAt(i: number) {
    return this.stackEl().nativeElement.children[i] as HTMLElement | undefined;
  }

  /** Step forward (throw the top card) or back (bring the last card in). */
  protected go(step: 1 | -1, direction = -1) {
    const total = this.total();
    if (total < 2) return;
    const target = (this.index() + step + total) % total;
    const top = this.cardAt(this.index());
    const incoming = this.cardAt(target);
    if (step === 1 && top) fling(top, direction);
    if (step === -1 && incoming) arrive(incoming, direction);
    this.index.set(target);
    // Render the new depths now (like React's sync update), so rapid key presses and drags read fresh state.
    this.changes.detectChanges();
  }

  protected handleKeydown(event: KeyboardEvent) {
    const steps: Record<string, 1 | -1 | undefined> = {
      ArrowRight: 1,
      ArrowLeft: -1,
    };
    const step = steps[event.key];
    if (step === undefined || event.defaultPrevented) return;
    event.preventDefault();
    this.go(step);
  }

  protected handlePointerdown(event: PointerEvent) {
    if (event.button !== 0 || this.total() < 2) return;
    this.drag = { x: event.clientX, moved: false };
  }

  protected handlePointermove(event: PointerEvent) {
    const top = this.cardAt(this.index());
    if (!this.drag || !top) return;
    const dx = event.clientX - this.drag.x;
    if (!this.drag.moved) {
      if (Math.abs(dx) < DRAG_START) return;
      this.drag.moved = true;
      this.stackEl().nativeElement.setPointerCapture?.(event.pointerId);
      top.dataset.dragging = "";
    }
    top.style.transform = `translateX(${dx}px) rotate(${dx / 20}deg)`;
  }

  protected handlePointerup(event: PointerEvent) {
    const state = this.drag;
    this.drag = null;
    const top = this.cardAt(this.index());
    if (!state?.moved || !top) return;
    const dx = event.clientX - state.x;
    if (Math.abs(dx) > this.stackEl().nativeElement.offsetWidth * SWIPE_RATIO)
      this.go(1, Math.sign(dx));
    else settle(top);
  }

  protected handlePointercancel() {
    const top = this.cardAt(this.index());
    if (this.drag?.moved && top) settle(top);
    this.drag = null;
  }
}
```

```ts
import { Component } from "@angular/core";
import { CardStack } from "./markas/card-stack.component";

@Component({
  selector: "app-testimonials",
  imports: [CardStack],
  template: `
    <markas-card-stack label="Customer testimonials" [items]="testimonials">
      <ng-template let-item let-index="index">
        <figure class="grid gap-6 p-5">
          <blockquote>{{ item.quote }}</blockquote>
          <figcaption class="text-sm text-muted">{{ item.name }}</figcaption>
        </figure>
      </ng-template>
    </markas-card-stack>
  `,
})
export class Testimonials {
  testimonials = [{ quote: "Setup took ten minutes.", name: "Sari Wijaya" }];
}
```

Bind `cardLabel` with a property when it holds `{index}`: `[cardLabel]="tipLabel"`.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `cards` | `Blade: named slots · React: children · Vue: default slot` | - | Each named slot (Blade) or each child element (React and Vue) becomes one card, in order. The stack sizes itself to the tallest card. |
| `label` | `string` | Card stack | Accessible name of the stack region. Describe the content, for example Customer testimonials. |
| `prevLabel` | `string` | Previous card | Accessible name of the previous button. |
| `nextLabel` | `string` | Next card | Accessible name of the next button. |
| `cardLabel` | `string` | {index} of {total} | Name of each card and the position text announced after every move. Accepts {index} and {total}. |
| `id` | `string` | auto | Id of the region. The card list gets the same id with a -cards suffix. |
| `items` | `T[]` | - | Svelte, Astro, and Angular only. One card per entry, drawn by a card snippet (Svelte), a function child (Astro), or an ng-template with let-item and let-index (Angular). |

## Accessibility

- The stack is a region with aria-roledescription carousel and each card is a group named by cardLabel.
- Left and Right arrow keys move back and forward anywhere inside the stack, and the stack itself is focusable.
- Cards behind the top one are inert, so Tab never lands inside a hidden card.
- A polite live region announces the new position after each move.
- With reduced motion the cards swap instantly without the throw and rise animations.

## Notes

- The stack provides the card surface (border, background, radius). Add only padding and content inside each card.
- Next, the Right arrow key, or dragging the top card past a quarter of the width throws it away; it settles at the back. Previous brings the last card back from the left. The stack loops.
- A short drag springs back. Presses that move less than 4px stay clicks, so links inside the top card keep working.
- `cardLabel` accepts `{index}` and `{total}`, for example `Tip {index} of {total}`.
- With reduced motion the cards swap instantly.
