# Add the "Stacked Cards" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/stacked-cards) to this Pantheon Content Publisher (P1) Next.js project. A hand-dealt pile of cards: fling the top one aside or press next to toss it to the back while the rest spring up.

## Steps

1. Install the dependency: `pnpm add gsap` (use the project's package manager if it isn't pnpm).
2. Create these files with the exact contents below, in the same folder: `components/puck/stacked-cards-block.tsx`, `components/puck/stacked-cards.client.tsx`. If `components/puck/` doesn't exist, use the folder where this project keeps its Puck components (look at the imports in `puck.config.tsx`).
3. In `puck.config.tsx`, import it: `import { stackedCardsBlock } from "./components/puck/stacked-cards-block";`
4. Register it under `components` as `StackedCardsBlock: stackedCardsBlock`.
5. Add `"StackedCardsBlock"` to the best-fitting entry in `categories` (this block's library category is "Carousels"). Create a category only if none fits.
6. Run the project's type check (usually `pnpm typecheck`) and resolve anything project-specific.
7. If `package.json` has a `sync:registry` script, tell the user it must run (or that CI will run it) before the new component appears in the P1 editor.

## Rules

- The block is two files: a server-safe Puck config and a `"use client"` island it imports by relative path. Keep both files in the same folder and keep the island's file name unchanged.
- WebGPU effects are progressive enhancement: content is server-rendered and a CSS fallback shows wherever WebGPU is unavailable. Don't move content into the client file.
- Keep the files as-is unless the user asks for changes. The accent color is `indigo-*`; if the project has brand colors, offer to swap them with a find-and-replace on `indigo-`.
- Images are plain `imageUrl` + `imageAlt` text fields. If this project defines a P1 media-library field (search for `"p1-media"`), offer to switch to it.
- Don't change prop names in `defaultProps`. Content editors' saved pages depend on them.

## File: `components/puck/stacked-cards-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { StackedCardsDeck } from "./stacked-cards.client";

/**
 * Stacked Cards — a hand-dealt deck of cards. Fling the top card away (drag, buttons or arrow
 * keys) and it tosses to the back of the pile. A swipeable row without JavaScript.
 * Needs `pnpm add gsap` and the companion stacked-cards.client.tsx file.
 * Register: `StackedCardsBlock: stackedCardsBlock` in puck.config.tsx.
 */

type Heading = "h1" | "h2" | "h3" | "h4";

type Card = {
  imageUrl: string;
  imageAlt: string;
  tag: string;
  title: string;
  body: string;
  ctaLabel: string;
  ctaHref: string;
};

export type StackedCardsProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  intro: string;
  label: string;
  cards: Card[];
};

const SUB: Record<Heading, "h2" | "h3" | "h4" | "h5"> = { h1: "h2", h2: "h3", h3: "h4", h4: "h5" };

export const stackedCardsBlock: ComponentConfig<StackedCardsProps> = {
  label: "Stacked Cards",
  fields: {
    eyebrow: { type: "text", label: "Eyebrow", metadata: { help: "Small line above the heading. Leave blank to hide it." } },
    heading: { type: "text", label: "Heading" },
    headingLevel: {
      type: "select",
      label: "Heading level",
      options: [
        { label: "H1", value: "h1" },
        { label: "H2", value: "h2" },
        { label: "H3", value: "h3" },
        { label: "H4", value: "h4" },
      ],
      metadata: { help: "Sets the page outline for screen readers and search. The look doesn't change." },
    },
    intro: { type: "textarea", label: "Intro" },
    label: {
      type: "text",
      label: "Deck name",
      metadata: { help: "Read aloud by screen readers, e.g. \"Volunteer roles\". Not shown on the page." },
    },
    cards: {
      type: "array",
      label: "Cards",
      min: 1,
      max: 10,
      getItemSummary: (item) => item?.title || "Card",
      defaultItemProps: {
        imageUrl: "https://picsum.photos/seed/helping/800/600",
        imageAlt: "",
        tag: "Flexible hours",
        title: "A way to help",
        body: "A sentence or two on what this involves and who it's a good fit for.",
        ctaLabel: "Sign up",
        ctaHref: "#",
      },
      arrayFields: {
        imageUrl: { type: "text", label: "Image URL", metadata: { help: "A landscape photo (4:3), at least 800px wide." } },
        imageAlt: { type: "text", label: "Image description", metadata: { help: "Describe the photo for people who can't see it. Leave blank if it's purely decorative." } },
        tag: { type: "text", label: "Tag", metadata: { help: "A short detail such as the time commitment. Leave blank to hide it." } },
        title: { type: "text", label: "Title" },
        body: { type: "textarea", label: "Body" },
        ctaLabel: { type: "text", label: "Link text", metadata: { help: "Leave blank to hide the link." } },
        ctaHref: { type: "text", label: "Link" },
      },
    },
  },
  defaultProps: {
    eyebrow: "Volunteer",
    heading: "Five ways to give an hour",
    headingLevel: "h2",
    intro: "Not sure where you fit? Flip through the deck. Every role comes with training, a buddy for your first shift, and no minimum commitment.",
    label: "Volunteer roles",
    cards: [
      {
        imageUrl: "https://picsum.photos/seed/sortingroom/800/600",
        imageAlt: "Volunteers sorting donated canned goods at a long table",
        tag: "Saturdays · 3 hours",
        title: "Sort and stock",
        body: "Unpack donations, check dates and keep the shelves full. Good with a friend, a teen, or a coworker team.",
        ctaLabel: "Pick a Saturday",
        ctaHref: "/volunteer/sort",
      },
      {
        imageUrl: "https://picsum.photos/seed/deliverydrive/800/600",
        imageAlt: "A volunteer handing a grocery bag through a car window",
        tag: "Weekday mornings · 2 hours",
        title: "Deliver to homebound neighbors",
        body: "Bring groceries to seniors and neighbors who can't get to us. You'll need a car and a friendly hello.",
        ctaLabel: "Join a route",
        ctaHref: "/volunteer/deliver",
      },
      {
        imageUrl: "https://picsum.photos/seed/welcomedesk/800/600",
        imageAlt: "A smiling volunteer greeting a family at a welcome desk",
        tag: "Evenings · 3 hours",
        title: "Welcome desk",
        body: "Be the first face people see. Spanish, Arabic or Swahili speakers are especially needed on Tuesday nights.",
        ctaLabel: "Greet with us",
        ctaHref: "/volunteer/welcome",
      },
      {
        imageUrl: "https://picsum.photos/seed/gardenbeds/800/600",
        imageAlt: "Raised garden beds with tomato plants and a watering can",
        tag: "Seasonal · your schedule",
        title: "Tend the pantry garden",
        body: "Water, weed and harvest the raised beds that supply fresh herbs and greens all summer.",
        ctaLabel: "Grow with us",
        ctaHref: "/volunteer/garden",
      },
      {
        imageUrl: "https://picsum.photos/seed/laptopdesk/800/600",
        imageAlt: "A laptop open on a desk beside a stack of handwritten thank-you cards",
        tag: "From home · 1 hour",
        title: "Write and call",
        body: "Send thank-you notes to donors or make friendly check-in calls. Perfect for a lunch break.",
        ctaLabel: "Help from home",
        ctaHref: "/volunteer/remote",
      },
    ],
  },
  render: ({ eyebrow, heading, headingLevel, intro, label, cards }) => {
    const H = headingLevel || "h2";
    const Sub = SUB[H] ?? "h3";
    const items = (cards ?? []).filter((c) => c && (c.title || c.body || c.imageUrl));
    const many = items.length > 1;
    return (
      <section className="overflow-hidden bg-neutral-100 px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24">
        <div className="mx-auto grid max-w-6xl grid-cols-1 gap-12 lg:grid-cols-12 lg:items-center lg:gap-16">
          {eyebrow || heading || intro ? (
            <div className="lg:col-span-5">
              {eyebrow ? <p className="text-xs font-semibold tracking-widest text-indigo-700 uppercase sm:text-sm">{eyebrow}</p> : null}
              {heading ? <H className="mt-3 text-4xl font-semibold tracking-tight text-balance text-neutral-950 sm:text-5xl">{heading}</H> : null}
              {intro ? <p className="mt-5 max-w-md text-base leading-7 text-pretty text-neutral-600 sm:text-lg sm:leading-8">{intro}</p> : null}
            </div>
          ) : null}
          {items.length ? (
            <div className={eyebrow || heading || intro ? "lg:col-span-7" : "lg:col-span-12"}>
              <StackedCardsDeck count={items.length} label={label || heading || "Cards"}>
                {items.map((card, i) => (
                  <article
                    key={i}
                    data-slide=""
                    role={many ? "group" : undefined}
                    aria-roledescription={many ? "slide" : undefined}
                    aria-label={many ? `${i + 1} of ${items.length}` : undefined}
                    className="flex w-72 shrink-0 snap-center flex-col overflow-hidden rounded-3xl bg-white shadow-xl ring-1 shadow-neutral-900/10 ring-neutral-950/5 sm:w-80"
                  >
                    {card.imageUrl ? (
                      <div className="aspect-4/3 overflow-hidden bg-neutral-200">
                        <img src={card.imageUrl} alt={card.imageAlt || ""} draggable={false} className="size-full object-cover" />
                      </div>
                    ) : null}
                    <div className="flex flex-1 flex-col p-6">
                      {card.tag ? (
                        <p className="self-start rounded-full bg-indigo-50 px-3 py-1 text-xs font-semibold text-indigo-700 ring-1 ring-indigo-100 ring-inset">{card.tag}</p>
                      ) : null}
                      {card.title ? (
                        <Sub data-title="" className="mt-4 text-xl font-semibold tracking-tight text-balance text-neutral-950">
                          {card.title}
                        </Sub>
                      ) : null}
                      {card.body ? <p className="mt-2 text-sm leading-6 text-pretty text-neutral-600">{card.body}</p> : null}
                      {card.ctaLabel ? (
                        <div className="mt-auto pt-4">
                        <a
                          href={card.ctaHref || "#"}
                          className="group inline-flex min-h-11 items-center gap-1.5 text-sm font-semibold text-indigo-700 hover:text-indigo-900 focus-visible:rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
                        >
                          {card.ctaLabel}
                          <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-4 transition group-hover:translate-x-0.5">
                            <path fillRule="evenodd" d="M3 10a.75.75 0 0 1 .75-.75h10.64l-3.22-3.22a.75.75 0 1 1 1.06-1.06l4.5 4.5a.75.75 0 0 1 0 1.06l-4.5 4.5a.75.75 0 1 1-1.06-1.06l3.22-3.22H3.75A.75.75 0 0 1 3 10Z" clipRule="evenodd" />
                          </svg>
                        </a>
                        </div>
                      ) : null}
                    </div>
                  </article>
                ))}
              </StackedCardsDeck>
            </div>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/stacked-cards.client.tsx`

```tsx
"use client";

import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { KeyboardEvent, ReactNode } from "react";
import { gsap } from "gsap";
import { Draggable } from "gsap/Draggable";

/**
 * Motion half of Stacked Cards. The cards arrive server-rendered as a scroll-snap row; once
 * mounted they gather into a hand-dealt pile. The top card can be dragged and flung, or sent
 * to the back with the buttons and arrow keys; the rest of the pile springs up to meet it.
 */

if (typeof window !== "undefined") gsap.registerPlugin(Draggable);

const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;

// Each card keeps its own resting tilt, so the pile looks dealt by hand rather than stacked by a machine.
const TILT = [-4, 3, -2.5, 4.5, -3.5, 2, -5, 3.5];
const VISIBLE = 4;

type Api = { next: () => void; prev: () => void };

type StackedCardsDeckProps = {
  count: number;
  label: string;
  children: ReactNode;
};

const pad = (n: number) => String(n).padStart(2, "0");

export function StackedCardsDeck({ count, label, children }: StackedCardsDeckProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const deckRef = useRef<HTMLDivElement>(null);
  const api = useRef<Api | null>(null);
  const [ready, setReady] = useState(false);
  const [top, setTop] = useState(0);
  const [message, setMessage] = useState("");
  const many = count > 1;

  useIsoLayoutEffect(() => {
    const root = rootRef.current;
    const deck = deckRef.current;
    if (!root || !deck || !many) return;
    const cards = Array.from(deck.children).filter((el): el is HTMLElement => el instanceof HTMLElement && el.hasAttribute("data-slide"));
    const n = cards.length;
    if (n < 2) return;

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const title = (c: HTMLElement) => c.querySelector("[data-title]")?.textContent?.trim();
    let order = cards.map((_, k) => k);
    let busy: gsap.core.Timeline | null = null;
    let w = cards[0].offsetWidth;

    const rest = (k: number, depth: number) => ({
      x: 0,
      y: -depth * 18,
      scale: 1 - Math.min(depth, VISIBLE) * 0.055,
      rotation: depth === 0 ? 0 : TILT[k % TILT.length],
      autoAlpha: depth < VISIBLE ? 1 : 0,
    });
    const stackZ = () => order.forEach((k, d) => gsap.set(cards[k], { zIndex: n - d }));

    let drags: Draggable[] = [];
    const sync = (announce: boolean) => {
      const k = order[0];
      cards.forEach((c, i) => (c.inert = i !== k));
      drags.forEach((d, i) => (i === k ? d.enable() : d.disable()));
      setTop(k);
      if (announce) {
        const t = title(cards[k]);
        setMessage(`${t ? `${t}, ` : ""}card ${k + 1} of ${n}`);
      }
    };

    const ctx = gsap.context(() => {
      gsap.set(deck, {
        display: "grid",
        gridTemplateColumns: "minmax(0, 1fr)",
        justifyItems: "center",
        overflow: "visible",
        scrollSnapType: "none",
        paddingTop: 72,
        paddingBottom: 16,
        paddingLeft: 0,
        paddingRight: 0,
      });
      cards.forEach((c, k) => gsap.set(c, { gridArea: "1 / 1", transformOrigin: "50% 0%", ...rest(k, k) }));
      stackZ();
    }, root);
    deck.scrollLeft = 0;

    const settle = () => {
      busy = null;
      sync(true);
    };

    // Fling the top card off to one side, tuck it under the pile, and let the rest spring up.
    const toss = (dir: number) => {
      busy?.progress(1);
      const k = order[0];
      const card = cards[k];
      order = [...order.slice(1), k];
      ctx.add(() => {
        if (reduced) {
          stackZ();
          order.forEach((kk, d) => gsap.set(cards[kk], rest(kk, d)));
          gsap.fromTo(cards[order[0]], { autoAlpha: 0.4 }, { autoAlpha: 1, duration: 0.2, ease: "none" });
          settle();
          return;
        }
        gsap.set(card, { zIndex: n + 1 });
        order.slice(0, -1).forEach((kk, d) => gsap.set(cards[kk], { zIndex: n - d }));
        const tl = gsap.timeline({ onComplete: settle });
        tl.to(card, { x: dir * w * 1.08, y: "-=28", rotation: dir * 18, duration: 0.42, ease: "power2.out" }, 0)
          .set(card, { zIndex: 0 }, 0.36)
          .to(card, { ...rest(k, n - 1), duration: 0.65, ease: "power3.inOut" }, 0.42);
        order.slice(0, -1).forEach((kk, d) => tl.to(cards[kk], { ...rest(kk, d), duration: 0.75, ease: "back.out(1.6)" }, 0.12 + d * 0.05));
        busy = tl;
      });
      sync(false);
    };

    // Pull the bottom card out from behind the pile and lay it on top.
    const bringBack = () => {
      busy?.progress(1);
      const k = order[n - 1];
      const card = cards[k];
      order = [k, ...order.slice(0, -1)];
      ctx.add(() => {
        if (reduced) {
          stackZ();
          order.forEach((kk, d) => gsap.set(cards[kk], rest(kk, d)));
          gsap.fromTo(card, { autoAlpha: 0.4 }, { autoAlpha: 1, duration: 0.2, ease: "none" });
          settle();
          return;
        }
        const tl = gsap.timeline({ onComplete: settle });
        tl.to(card, { x: -w * 1.08, y: -40, rotation: -16, scale: 1, autoAlpha: 1, duration: 0.4, ease: "power2.out" }, 0)
          .add(stackZ, 0.36)
          .to(card, { ...rest(k, 0), duration: 0.7, ease: "back.out(1.3)" }, 0.4);
        order.slice(1).forEach((kk, d) => tl.to(cards[kk], { ...rest(kk, d + 1), duration: 0.6, ease: "power3.out" }, 0.3 + d * 0.04));
        busy = tl;
      });
      sync(false);
    };

    ctx.add(() => {
      drags = cards.map((card) => {
        let lastX = 0;
        let lastT = 0;
        let vx = 0;
        const inst: Draggable = Draggable.create(card, {
          type: "x",
          zIndexBoost: false,
          onPress: () => {
            busy?.progress(1);
            gsap.killTweensOf(card);
            lastX = inst.x;
            lastT = performance.now();
            vx = 0;
          },
          onDrag: () => {
            const now = performance.now();
            vx = (inst.x - lastX) / Math.max(1, now - lastT);
            lastX = inst.x;
            lastT = now;
            gsap.set(card, { rotation: inst.x * 0.06, y: -Math.abs(inst.x) * 0.05 });
          },
          onRelease: () => {
            const flung = Math.abs(vx) > 0.6 && Math.abs(inst.x) > 24;
            if (Math.abs(inst.x) > w * 0.3 || flung) toss(Math.sign(inst.x) || 1);
            else ctx.add(() => gsap.to(card, { x: 0, y: 0, rotation: 0, duration: reduced ? 0 : 0.9, ease: "elastic.out(1, 0.5)" }));
          },
        })[0];
        return inst;
      });
    });

    const onResize = () => {
      w = cards[0].offsetWidth;
    };
    window.addEventListener("resize", onResize);

    api.current = { next: () => toss(1), prev: bringBack };
    sync(false);
    setReady(true);

    return () => {
      window.removeEventListener("resize", onResize);
      api.current = null;
      busy = null;
      drags.forEach((d) => d.kill());
      ctx.revert();
      cards.forEach((c) => (c.inert = false));
      setReady(false);
    };
  }, [count, many]);

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    if (!api.current || (e.target as HTMLElement).closest("[data-slide]")) return;
    if (e.key === "ArrowRight") api.current.next();
    else if (e.key === "ArrowLeft") api.current.prev();
    else return;
    e.preventDefault();
  };

  const btn =
    "group inline-flex min-h-11 items-center gap-2 rounded-full bg-white px-4 text-sm font-semibold text-neutral-900 shadow-sm ring-1 ring-neutral-950/10 transition hover:-translate-y-0.5 hover:shadow-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600";

  return (
    <div ref={rootRef} role="region" aria-roledescription="carousel" aria-label={label} onKeyDown={onKeyDown}>
      <div
        ref={deckRef}
        tabIndex={many ? 0 : undefined}
        className={`flex snap-x snap-mandatory gap-4 relative overflow-x-auto overscroll-x-contain p-2 pb-6 focus-visible:rounded-3xl focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-indigo-600 ${many ? "" : "justify-center"}`}
      >
        {children}
      </div>
      {many ? (
        <div hidden={!ready} className="mt-8">
          <div className="flex items-center justify-center gap-3 sm:gap-5">
            <button type="button" onClick={() => api.current?.prev()} className={btn}>
              <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-4 transition group-hover:-translate-x-0.5">
                <path fillRule="evenodd" d="M11.78 5.22a.75.75 0 0 1 0 1.06L8.06 10l3.72 3.72a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z" clipRule="evenodd" />
              </svg>
              <span>
                Back<span className="sr-only"> to previous card</span>
              </span>
            </button>
            <p aria-hidden="true" className="w-16 text-center text-sm text-neutral-600 tabular-nums">
              <span className="font-semibold text-neutral-950">{pad(top + 1)}</span> / {pad(count)}
            </p>
            <button type="button" onClick={() => api.current?.next()} className={btn}>
              <span>
                Next<span className="sr-only"> card</span>
              </span>
              <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-4 transition group-hover:translate-x-0.5">
                <path fillRule="evenodd" d="M8.22 5.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06-1.06L11.94 10 8.22 6.28a.75.75 0 0 1 0-1.06Z" clipRule="evenodd" />
              </svg>
            </button>
          </div>
          <p className="mt-4 text-center text-xs text-neutral-600">Drag the top card aside, or use the arrow keys.</p>
          <p className="sr-only" aria-live="polite" aria-atomic="true">
            {message}
          </p>
        </div>
      ) : null}
    </div>
  );
}
```
