# Add the "Card Carousel" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/card-carousel) to this Pantheon Content Publisher (P1) Next.js project. Story or program cards you can drag and flick with momentum, snapping card to card, with arrows and a progress rule.

## 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/card-carousel-block.tsx`, `components/puck/card-carousel.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 { cardCarouselBlock } from "./components/puck/card-carousel-block";`
4. Register it under `components` as `CardCarouselBlock: cardCarouselBlock`.
5. Add `"CardCarouselBlock"` 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/card-carousel-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { CardCarouselTrack } from "./card-carousel.client";

/**
 * Card Carousel — a row of story or program cards you can drag and flick, snapping card to
 * card (GSAP Draggable + Inertia). Without JavaScript it's a native swipeable scroll-snap row.
 * Needs `pnpm add gsap` and the companion card-carousel.client.tsx file.
 * Register: `CardCarouselBlock: cardCarouselBlock` in puck.config.tsx.
 */

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

type Card = { category: string; title: string; excerpt: string; imageUrl: string; imageAlt: string; href: string };

export type CardCarouselProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  intro: string;
  linkLabel: string;
  linkHref: string;
  cards: Card[];
};

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

export const cardCarouselBlock: ComponentConfig<CardCarouselProps> = {
  label: "Card Carousel",
  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", metadata: { help: "Optional sentence under the heading. Leave blank to hide it." } },
    linkLabel: { type: "text", label: "Link text", metadata: { help: "Optional link beside the heading, such as \"All stories\". Leave blank to hide it." } },
    linkHref: { type: "text", label: "Link" },
    cards: {
      type: "array",
      label: "Cards",
      min: 1,
      max: 12,
      getItemSummary: (item) => item?.title?.slice(0, 48) || "Card",
      defaultItemProps: {
        category: "Story",
        title: "New story",
        excerpt: "One or two sentences that make someone want to read more.",
        imageUrl: "https://picsum.photos/seed/story/800/1000",
        imageAlt: "",
        href: "#",
      },
      arrayFields: {
        category: { type: "text", label: "Category", metadata: { help: "Short label above the title. Leave blank to hide it." } },
        title: { type: "text", label: "Title" },
        excerpt: { type: "textarea", label: "Excerpt" },
        imageUrl: { type: "text", label: "Image URL", metadata: { help: "A portrait image (4:5) works best. Leave blank for a text-only card." } },
        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." } },
        href: { type: "text", label: "Link", metadata: { help: "Where the card goes. Leave blank for a card without a link." } },
      },
    },
  },
  defaultProps: {
    eyebrow: "Field notes",
    heading: "Stories from the watershed",
    headingLevel: "h2",
    intro: "What our volunteers, neighbors and partners saw, built and learned along the river this season.",
    linkLabel: "All stories",
    linkHref: "/stories",
    cards: [
      {
        category: "Restoration",
        title: "Twelve hundred willows in a single weekend",
        excerpt: "How 214 volunteers replanted a mile of eroded bank before the spring floods, and what came back first.",
        imageUrl: "https://picsum.photos/seed/willows/800/1000",
        imageAlt: "Volunteers in rain jackets planting saplings along a muddy riverbank",
        href: "/stories/willow-planting",
      },
      {
        category: "Youth programs",
        title: "The summer the creek became a classroom",
        excerpt: "Forty middle schoolers spent six weeks testing water quality, and their data now feeds the county's monitoring map.",
        imageUrl: "https://picsum.photos/seed/creekclass/800/1000",
        imageAlt: "Students in waders holding sample jars in a shallow creek",
        href: "/stories/creek-classroom",
      },
      {
        category: "Community",
        title: "A boat launch built by the people who use it",
        excerpt: "Anglers, paddlers and the parks department designed the new Mill Street access together over three town halls.",
        imageUrl: "https://picsum.photos/seed/boatlaunch/800/1000",
        imageAlt: "A wooden boat launch at the edge of a calm river at dawn",
        href: "/stories/mill-street-launch",
      },
      {
        category: "Science",
        title: "Counting mussels to measure a river's health",
        excerpt: "Freshwater mussels filter gallons a day. Our first full survey found them returning to stretches where they'd vanished.",
        imageUrl: "https://picsum.photos/seed/mussels/800/1000",
        imageAlt: "Hands holding a freshwater mussel above clear water",
        href: "/stories/mussel-survey",
      },
      {
        category: "Advocacy",
        title: "What the new stormwater ordinance means for you",
        excerpt: "A plain-language guide to the rules council passed in March, and the rebates now open to homeowners.",
        imageUrl: "https://picsum.photos/seed/stormwater/800/1000",
        imageAlt: "Rain garden with native grasses beside a residential sidewalk",
        href: "/stories/stormwater-ordinance",
      },
      {
        category: "Volunteers",
        title: "Thirty years of Saturday cleanups with Ruth Alvarez",
        excerpt: "She's hauled tires, shopping carts and one upright piano out of the river. She's not done yet.",
        imageUrl: "https://picsum.photos/seed/cleanup/800/1000",
        imageAlt: "An older woman in gloves smiling beside a pile of collected debris",
        href: "/stories/ruth-alvarez",
      },
    ],
  },
  render: ({ id, eyebrow, heading, headingLevel, intro, linkLabel, linkHref, cards }) => {
    const H = headingLevel || "h2";
    const T = NEXT_LEVEL[H] ?? "h3";
    const list = (cards ?? []).filter((c) => c?.title || c?.imageUrl);
    const headingId = `${id}-heading`;
    const hasHeader = Boolean(eyebrow || heading || intro || linkLabel);

    const slides = list.map((card, i) => {
      const inner = (
        <>
          {card.imageUrl ? (
            <div className="relative aspect-4/5 overflow-hidden rounded-2xl bg-neutral-100">
              <img
                src={card.imageUrl}
                alt={card.imageAlt || ""}
                draggable={false}
                loading={i > 2 ? "lazy" : undefined}
                className="size-full object-cover transition-transform duration-700 ease-out motion-safe:group-hover:scale-105"
              />
            </div>
          ) : null}
          <div className={card.imageUrl ? "mt-5" : "rounded-2xl bg-neutral-50 p-6 ring-1 ring-neutral-200 ring-inset"}>
            {card.category ? <p className="text-xs font-semibold tracking-widest text-indigo-700 uppercase">{card.category}</p> : null}
            {card.title ? (
              <T className="mt-2 text-xl font-semibold tracking-tight text-balance text-neutral-950 decoration-1 underline-offset-4 group-hover:underline sm:text-2xl">{card.title}</T>
            ) : null}
            {card.excerpt ? <p className="mt-3 text-base leading-7 text-pretty text-neutral-600">{card.excerpt}</p> : null}
          </div>
        </>
      );
      return (
        <div
          key={`${card.title}-${i}`}
          data-slide=""
          role="group"
          aria-roledescription="slide"
          aria-label={`${i + 1} of ${list.length}`}
          className="shrink-0 basis-4/5 snap-start sm:basis-5/12 lg:basis-3/10"
        >
          {card.href ? (
            <a href={card.href} draggable={false} className="group block rounded-2xl focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-indigo-600">
              {inner}
            </a>
          ) : (
            <div className="group">{inner}</div>
          )}
        </div>
      );
    });

    return (
      <section aria-labelledby={heading ? headingId : undefined} className="overflow-hidden bg-white px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24">
        <div className="mx-auto max-w-7xl">
          {hasHeader ? (
            <div className="flex flex-col gap-6 sm:flex-row sm:items-end sm:justify-between">
              <div className="max-w-2xl">
                {eyebrow ? <p className="text-sm font-semibold tracking-widest text-indigo-700 uppercase">{eyebrow}</p> : null}
                {heading ? (
                  <H id={headingId} className="mt-3 text-3xl font-semibold tracking-tight text-balance text-neutral-950 sm:text-5xl">
                    {heading}
                  </H>
                ) : null}
                {intro ? <p className="mt-5 text-lg leading-8 text-pretty text-neutral-600">{intro}</p> : null}
              </div>
              {linkLabel ? (
                <a
                  href={linkHref || "#"}
                  className="group inline-flex min-h-11 shrink-0 items-center gap-1.5 self-start rounded-md text-base font-semibold text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 sm:self-auto"
                >
                  {linkLabel}
                  <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-5 transition-transform motion-safe: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>
              ) : null}
            </div>
          ) : null}

          {slides.length > 0 ? (
            <div className={hasHeader ? "mt-10 sm:mt-14" : ""}>
              <CardCarouselTrack count={slides.length} label={heading || "Stories"}>
                {slides}
              </CardCarouselTrack>
            </div>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/card-carousel.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";
import { InertiaPlugin } from "gsap/InertiaPlugin";

/**
 * Interactive half of the Card Carousel. The cards arrive server-rendered as children inside
 * a native scroll-snap track; once hydrated, the track becomes a GSAP Draggable you can flick
 * with momentum, snapping card to card, with arrows, keys and a progress rule.
 */

type Api = { go: (to: number, announce?: boolean) => void; step: (dir: 1 | -1) => void };

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

const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v));
const FOCUSABLE = "a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex='-1'])";

export function CardCarouselTrack({ children, count, label }: CardCarouselTrackProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const viewportRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);
  const fillRef = useRef<HTMLSpanElement>(null);
  const api = useRef<Api | null>(null);
  const [enhanced, setEnhanced] = useState(false);
  const [edges, setEdges] = useState({ start: true, end: false });
  const [status, setStatus] = useState("");
  const interactive = enhanced && count > 1;

  useEffect(() => setEnhanced(true), []);

  useLayoutEffect(() => {
    const root = rootRef.current;
    const viewport = viewportRef.current;
    const track = trackRef.current;
    const fill = fillRef.current;
    if (!interactive || !root || !viewport || !track || !fill) return;

    gsap.registerPlugin(Draggable, InertiaPlugin);
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const slides = Array.from(track.querySelectorAll<HTMLElement>(":scope > [data-slide]"));
    if (slides.length < 2) return;

    let snaps: number[] = [0];
    let maxShift = 0;
    let index = 0;
    let pressIndex = 0;
    let draggable: Draggable | undefined;

    const measure = () => {
      maxShift = Math.max(0, track.scrollWidth - track.clientWidth);
      const raw = slides.map((s) => -Math.min(s.offsetLeft, maxShift));
      snaps = raw.filter((v, i) => i === 0 || Math.abs(v - raw[i - 1]) > 1);
    };
    const nearest = (x: number) => snaps.reduce((best, s, i) => (Math.abs(s - x) < Math.abs(snaps[best] - x) ? i : best), 0);

    // The rule fills from "how much you can see" to full as you travel the track.
    const paint = (x: number) => {
      const visible = track.scrollWidth ? track.clientWidth / track.scrollWidth : 1;
      const progress = maxShift ? clamp(-x / maxShift, 0, 1) : 1;
      gsap.set(fill, { scaleX: visible + (1 - visible) * progress });
    };

    const sync = (x: number, announce = false) => {
      const width = track.clientWidth;
      const focusedSlide = slides.find((s) => s.contains(document.activeElement));
      const shown: number[] = [];
      slides.forEach((s, i) => {
        const left = s.offsetLeft + x;
        if (left >= -2 && left + s.offsetWidth <= width + 2) shown.push(i);
      });
      if (!shown.length) shown.push(clamp(Math.round(-x / (slides[0].offsetWidth || 1)), 0, slides.length - 1));
      slides.forEach((s, i) => (s.inert = !shown.includes(i)));
      // Keep keyboard focus alive when the slide that held it slides out of view.
      if (focusedSlide?.inert) slides[shown[0]].querySelector<HTMLElement>(FOCUSABLE)?.focus({ preventScroll: true });
      setEdges({ start: index === 0, end: index === snaps.length - 1 });
      if (announce) {
        const a = shown[0] + 1;
        const b = shown[shown.length - 1] + 1;
        setStatus(a === b ? `Card ${a} of ${slides.length}` : `Cards ${a} to ${b} of ${slides.length}`);
      }
    };

    const ctx = gsap.context(() => {}, root);

    const go = ctx.add("go", (to: number, announce = false) => {
      index = clamp(to, 0, snaps.length - 1);
      const target = snaps[index];
      sync(target, announce);
      gsap.to(track, {
        x: target,
        duration: reduced ? 0 : 0.9,
        ease: "expo.out",
        overwrite: true,
        onUpdate: () => paint(Number(gsap.getProperty(track, "x"))),
        onComplete: () => void draggable?.update(),
      });
    }) as Api["go"];

    ctx.add(() => {
      // Pick up wherever a visitor had already scrolled the native track before hydration.
      const scrolled = viewport.scrollLeft;
      viewport.scrollLeft = 0;
      measure();
      index = nearest(-scrolled);
      gsap.set(track, { x: snaps[index] });
      paint(snaps[index]);
      sync(snaps[index]);

      draggable = Draggable.create(track, {
        type: "x",
        bounds: { minX: -maxShift, maxX: 0 },
        edgeResistance: 0.85,
        inertia: !reduced,
        throwResistance: 1800,
        minDuration: 0.4,
        maxDuration: 1.2,
        zIndexBoost: false,
        cursor: "grab",
        activeCursor: "grabbing",
        snap: {
          x: (v: number) => {
            let i = nearest(v);
            // A short, deliberate flick should still advance one card.
            const from = snaps[pressIndex];
            if (i === pressIndex && Math.abs(v - from) > 28) i = clamp(pressIndex + (v < from ? 1 : -1), 0, snaps.length - 1);
            index = i;
            sync(snaps[i]);
            return snaps[i];
          },
        },
        onPress: () => {
          gsap.killTweensOf(track);
          pressIndex = nearest(Number(gsap.getProperty(track, "x")));
        },
        onDrag: () => draggable && paint(draggable.x),
        onThrowUpdate: () => draggable && paint(draggable.x),
        onDragEnd: () => {
          if (reduced && draggable) go(nearest(draggable.x), true);
        },
        onThrowComplete: () => {
          if (!draggable) return;
          index = nearest(draggable.x);
          sync(draggable.x, true);
        },
        // Tapping a half-visible card brings it into view instead of doing nothing.
        onClick: (e: PointerEvent) => {
          const hit = slides.findIndex((s) => {
            const r = s.getBoundingClientRect();
            return s.inert && e.clientX >= r.left && e.clientX <= r.right;
          });
          if (hit >= 0) go(nearest(-Math.min(slides[hit].offsetLeft, maxShift)), true);
        },
      })[0];
    });

    api.current = { go, step: (dir) => go(index + dir, true) };

    const ro = new ResizeObserver(() => {
      measure();
      index = Math.min(index, snaps.length - 1);
      draggable?.applyBounds({ minX: -maxShift, maxX: 0 });
      gsap.set(track, { x: snaps[index] });
      draggable?.update();
      paint(snaps[index]);
      sync(snaps[index]);
    });
    ro.observe(track);

    // overflow:hidden still scrolls programmatically (find-in-page, focus); hold it at 0.
    const pin = () => {
      if (viewport.scrollLeft) viewport.scrollLeft = 0;
    };
    viewport.addEventListener("scroll", pin);

    return () => {
      ro.disconnect();
      viewport.removeEventListener("scroll", pin);
      draggable?.kill();
      ctx.revert();
      slides.forEach((s) => (s.inert = false));
      api.current = null;
    };
  }, [interactive, count]);

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    const a = api.current;
    if (!a) return;
    const keys: Record<string, () => void> = {
      ArrowRight: () => a.step(1),
      ArrowLeft: () => a.step(-1),
      Home: () => a.go(0, true),
      End: () => a.go(Number.MAX_SAFE_INTEGER, true),
    };
    const run = keys[e.key];
    if (!run) return;
    e.preventDefault();
    run();
  };

  const arrow = (dir: 1 | -1) => {
    const disabled = dir === 1 ? edges.end : edges.start;
    return (
      <button
        type="button"
        aria-label={dir === 1 ? "Next cards" : "Previous cards"}
        aria-disabled={disabled}
        onClick={() => !disabled && api.current?.step(dir)}
        className="group inline-flex size-11 items-center justify-center rounded-full text-neutral-900 ring-1 ring-neutral-300 transition-colors ring-inset hover:bg-neutral-950 hover:text-white hover:ring-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 aria-disabled:cursor-not-allowed aria-disabled:text-neutral-400 aria-disabled:ring-neutral-200 aria-disabled:hover:bg-transparent aria-disabled:hover:text-neutral-400 aria-disabled:hover:ring-neutral-200"
      >
        <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className={`size-5 transition-transform ${dir === 1 ? "motion-safe:group-hover:translate-x-0.5" : "rotate-180 motion-safe: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>
      </button>
    );
  };

  return (
    <div ref={rootRef} role="region" aria-roledescription="carousel" aria-label={label} onKeyDown={onKeyDown} className="relative">
      <div
        ref={viewportRef}
        className={
          interactive
            ? "-mx-2 overflow-hidden px-2 py-2"
            : "-mx-2 snap-x snap-mandatory scroll-px-2 relative overflow-x-auto overscroll-x-contain px-2 pt-2 pb-6"
        }
      >
        <div ref={trackRef} className="relative flex gap-4 sm:gap-6 lg:gap-8">
          {children}
        </div>
      </div>
      {interactive ? (
        <div className="mt-8 flex items-center gap-5 sm:mt-10 sm:gap-8">
          <div aria-hidden="true" className="relative h-0.5 flex-1 overflow-hidden rounded-full bg-neutral-200">
            <span ref={fillRef} className="absolute inset-0 origin-left rounded-full bg-indigo-600" />
          </div>
          <div className="flex shrink-0 gap-2">
            {arrow(-1)}
            {arrow(1)}
          </div>
          <p aria-live="polite" className="sr-only">
            {status}
          </p>
        </div>
      ) : null}
    </div>
  );
}
```
