# Add the "Thumbnail Gallery" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/gallery-thumbnails) to this Pantheon Content Publisher (P1) Next.js project. A large captioned photo stage over a thumbnail strip; each new photo rises out of its thumbnail. Shows a 3 / 12 count.

## 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/gallery-thumbnails-block.tsx`, `components/puck/gallery-thumbnails.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 { galleryThumbnailsBlock } from "./components/puck/gallery-thumbnails-block";`
4. Register it under `components` as `GalleryThumbnailsBlock: galleryThumbnailsBlock`.
5. Add `"GalleryThumbnailsBlock"` 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/gallery-thumbnails-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { GalleryThumbnailsStage } from "./gallery-thumbnails.client";

/**
 * Thumbnail Gallery — a large captioned image stage over a strip of thumbnails. Picking
 * a thumbnail raises the new image out of it. Swipeable, with jump links, without JavaScript.
 * Needs `pnpm add gsap` and the companion gallery-thumbnails.client.tsx file.
 * Register: `GalleryThumbnailsBlock: galleryThumbnailsBlock` in puck.config.tsx.
 */

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

type Photo = {
  imageUrl: string;
  imageAlt: string;
  caption: string;
  credit: string;
};

export type GalleryThumbnailsProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  intro: string;
  label: string;
  photos: Photo[];
};

export const galleryThumbnailsBlock: ComponentConfig<GalleryThumbnailsProps> = {
  label: "Thumbnail Gallery",
  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: "Gallery name",
      metadata: { help: "Read aloud by screen readers, e.g. \"Construction photos\". Not shown on the page." },
    },
    photos: {
      type: "array",
      label: "Photos",
      min: 1,
      max: 24,
      getItemSummary: (item) => item?.caption || "Photo",
      defaultItemProps: {
        imageUrl: "https://picsum.photos/seed/gallery/1600/1067",
        imageAlt: "",
        caption: "What's happening in this photo, in a sentence.",
        credit: "",
      },
      arrayFields: {
        imageUrl: { type: "text", label: "Image URL", metadata: { help: "A landscape photo (3:2) works best, at least 1600px wide." } },
        imageAlt: { type: "text", label: "Image description", metadata: { help: "Describe the photo for people who can't see it." } },
        caption: { type: "textarea", label: "Caption" },
        credit: { type: "text", label: "Credit or date", metadata: { help: "Optional, e.g. \"Photo: Ana Reyes, March 2026\"." } },
      },
    },
  },
  defaultProps: {
    eyebrow: "Eastside Branch Library",
    heading: "Building the new library, one season at a time",
    headingLevel: "h2",
    intro: "The Eastside Branch opens next fall. Until then, here's the view from the fence: every milestone, from the first shovel to the last shelf.",
    label: "Construction photos",
    photos: [
      { imageUrl: "https://picsum.photos/seed/groundbreak/1600/1067", imageAlt: "Neighbors in hard hats turning the first shovels of dirt on an empty lot", caption: "Groundbreaking day. More than two hundred neighbors came out in the rain to turn the first shovel.", credit: "March 2026" },
      { imageUrl: "https://picsum.photos/seed/foundation/1600/1067", imageAlt: "Concrete foundation forms and rebar across the site", caption: "Foundations poured, including the footing for the children's reading garden.", credit: "May 2026" },
      { imageUrl: "https://picsum.photos/seed/steelframe/1600/1067", imageAlt: "Steel beams rising against a clear sky", caption: "Steel goes up. The double-height reading room starts to take shape.", credit: "June 2026" },
      { imageUrl: "https://picsum.photos/seed/timberroof/1600/1067", imageAlt: "Workers fixing timber panels to the roof structure", caption: "Mass-timber roof panels, sourced from a regional mill, close in the building.", credit: "July 2026" },
      { imageUrl: "https://picsum.photos/seed/windows/1600/1067", imageAlt: "Tall windows being installed along the building's front", caption: "The long north windows go in, so the reading room gets steady daylight all afternoon.", credit: "August 2026" },
      { imageUrl: "https://picsum.photos/seed/muralwall/1600/1067", imageAlt: "Students painting a colorful mural on an interior wall", caption: "Students from Eastside Middle School begin the lobby mural they designed last winter.", credit: "September 2026" },
      { imageUrl: "https://picsum.photos/seed/bookshelves/1600/1067", imageAlt: "Empty wooden shelving in long rows awaiting books", caption: "Shelving arrives: room for sixty thousand books, plus a tool and seed lending library.", credit: "October 2026" },
      { imageUrl: "https://picsum.photos/seed/readingnook/1600/1067", imageAlt: "A sunlit reading nook with cushions beside a large window", caption: "A first look at the teen room's window seats. Furniture was chosen by our teen advisory board.", credit: "October 2026" },
    ],
  },
  render: ({ id, eyebrow, heading, headingLevel, intro, label, photos }) => {
    const H = headingLevel || "h2";
    const items = (photos ?? []).filter((p) => p && p.imageUrl);
    const many = items.length > 1;
    const slideId = (i: number) => `${id}-photo-${i + 1}`;
    return (
      <section className="bg-white px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24">
        <div className="mx-auto max-w-5xl">
          {eyebrow || heading || intro ? (
            <div className="max-w-3xl">
              {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-3xl font-semibold tracking-tight text-balance text-neutral-950 sm:text-5xl">{heading}</H> : null}
              {intro ? <p className="mt-5 text-base leading-7 text-pretty text-neutral-600 sm:text-lg sm:leading-8">{intro}</p> : null}
            </div>
          ) : null}
          {items.length ? (
            <div className="mt-10 sm:mt-14">
              <GalleryThumbnailsStage
                count={items.length}
                label={label || heading || "Photo gallery"}
                thumbs={
                  many ? (
                    <ol className="flex snap-x gap-2 relative overflow-x-auto overscroll-x-contain p-1 sm:gap-3">
                      {items.map((photo, i) => (
                        <li key={i} className="shrink-0 snap-start">
                          <a
                            href={`#${slideId(i)}`}
                            data-thumb=""
                            data-active={i === 0 ? "" : undefined}
                            aria-label={`Show photo ${i + 1} of ${items.length}`}
                            className="block aspect-4/3 w-20 overflow-hidden rounded-lg opacity-55 ring-2 ring-transparent ring-offset-2 transition duration-300 hover:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 data-active:opacity-100 data-active:ring-indigo-600 sm:w-28"
                          >
                            <img src={photo.imageUrl} alt="" draggable={false} loading="lazy" className="size-full object-cover" />
                          </a>
                        </li>
                      ))}
                    </ol>
                  ) : null
                }
              >
                {items.map((photo, i) => (
                  <figure
                    key={i}
                    id={slideId(i)}
                    data-slide=""
                    role={many ? "group" : undefined}
                    aria-roledescription={many ? "slide" : undefined}
                    aria-label={many ? `${i + 1} of ${items.length}` : undefined}
                    className="w-full shrink-0 snap-start"
                  >
                    <div data-frame="" className="relative aspect-4/3 overflow-hidden rounded-2xl bg-neutral-100 sm:aspect-3/2">
                      <img data-media="" src={photo.imageUrl} alt={photo.imageAlt || ""} draggable={false} className="size-full object-cover" />
                    </div>
                    {photo.caption || photo.credit ? (
                      <figcaption data-caption="" className="mt-5 grid grid-cols-1 gap-1 sm:grid-cols-12 sm:gap-8">
                        {photo.caption ? (
                          <p data-title="" className="text-base leading-7 text-pretty text-neutral-800 sm:col-span-9 sm:text-lg">
                            {photo.caption}
                          </p>
                        ) : null}
                        {photo.credit ? <p className="text-sm leading-7 text-neutral-500 sm:col-span-3 sm:text-right">{photo.credit}</p> : null}
                      </figcaption>
                    ) : null}
                  </figure>
                ))}
              </GalleryThumbnailsStage>
            </div>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/gallery-thumbnails.client.tsx`

```tsx
"use client";

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

/**
 * Motion half of the Thumbnail Gallery. Photos arrive server-rendered as a scroll-snap
 * strip and the thumbnails as jump links. Once mounted the photos stack into one stage and the
 * chosen photo rises out of its thumbnail's column, while the strip keeps the active thumb in view.
 */

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

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

type Api = { go: (index: number) => void; step: (delta: number) => void; thumbs: HTMLElement[] };

type GalleryThumbnailsStageProps = {
  count: number;
  label: string;
  thumbs?: ReactNode;
  children: ReactNode;
};

const clamp = (min: number, max: number, v: number) => Math.min(max, Math.max(min, v));

export function GalleryThumbnailsStage({ count, label, thumbs, children }: GalleryThumbnailsStageProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);
  const api = useRef<Api | null>(null);
  const [ready, setReady] = useState(false);
  const [index, setIndex] = useState(0);
  const [message, setMessage] = useState("");
  const many = count > 1;

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

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const thumbEls = Array.from(root.querySelectorAll<HTMLElement>("[data-thumb]"));
    const strip = thumbEls[0]?.closest("ol") ?? null;
    const part = (s: HTMLElement, name: string) => s.querySelector<HTMLElement>(`[data-${name}]`);
    const title = (s: HTMLElement) => part(s, "title")?.textContent?.trim();

    let current = Math.min(n - 1, Math.max(0, Math.round(track.scrollLeft / Math.max(1, track.clientWidth))));

    const markThumbs = () =>
      thumbEls.forEach((t, k) => {
        t.toggleAttribute("data-active", k === current);
        if (k === current) t.setAttribute("aria-current", "true");
        else t.removeAttribute("aria-current");
      });

    const revealThumb = (smooth: boolean) => {
      const t = thumbEls[current];
      if (!strip || !t) return;
      const sr = strip.getBoundingClientRect();
      const tr = t.getBoundingClientRect();
      strip.scrollTo({ left: strip.scrollLeft + (tr.left - sr.left) - (sr.width - tr.width) / 2, behavior: smooth ? "smooth" : "auto" });
    };

    const ctx = gsap.context(() => {
      gsap.set(track, { display: "grid", gridTemplateColumns: "minmax(0, 1fr)", overflow: "hidden", scrollSnapType: "none" });
      slides.forEach((s, k) => gsap.set(s, { gridArea: "1 / 1", zIndex: k === current ? 2 : 0, autoAlpha: k === current ? 1 : 0 }));

      // Swipe the stage on touch or with a mouse drag; vertical page scrolling stays native.
      Observer.create({
        target: track,
        type: "pointer,touch",
        dragMinimum: 6,
        onRelease: (self) => {
          const dx = (self.x ?? 0) - (self.startX ?? 0);
          const dy = (self.y ?? 0) - (self.startY ?? 0);
          if (Math.abs(dx) > 48 && Math.abs(dx) > Math.abs(dy) * 1.2) go(current + (dx < 0 ? 1 : -1));
        },
      });
    }, root);
    slides.forEach((s, k) => (s.inert = k !== current));
    track.scrollLeft = 0;
    markThumbs();
    revealThumb(false);

    const go = (target: number) => {
      const to = ((target % n) + n) % n;
      if (to === current) return;
      const from = current;
      current = to;
      const incoming = slides[to];
      const outgoing = slides[from];

      ctx.add(() => {
        slides.forEach((s, k) => {
          s.inert = k !== to;
          if (k === to || k === from) return;
          gsap.killTweensOf(s);
          gsap.set(s, { autoAlpha: 0, zIndex: 0 });
        });
        gsap.killTweensOf([incoming, outgoing]);
        gsap.set(outgoing, { zIndex: 1 });
        gsap.set(incoming, { zIndex: 2, autoAlpha: 1 });
        const hideOutgoing = () => gsap.set(outgoing, { autoAlpha: 0, zIndex: 0 });
        const frame = part(incoming, "frame");
        const media = part(incoming, "media");
        const inCaption = part(incoming, "caption");
        const outCaption = part(outgoing, "caption");

        if (reduced || !frame) {
          if (inCaption) gsap.set(inCaption, { autoAlpha: 1, y: 0 });
          gsap.fromTo(incoming, { autoAlpha: 0 }, { autoAlpha: 1, duration: 0.25, ease: "none", onComplete: hideOutgoing });
          return;
        }

        // The new photo grows up out of its thumbnail's column, then opens to full width.
        const fr = frame.getBoundingClientRect();
        const tr = thumbEls[to]?.getBoundingClientRect();
        const left = tr && fr.width ? clamp(0, 88, ((tr.left - fr.left) / fr.width) * 100) : 40;
        const right = tr && fr.width ? clamp(0, 100 - left - 6, ((fr.right - tr.right) / fr.width) * 100) : 40;

        gsap.fromTo(
          frame,
          { clipPath: `inset(100% ${right}% 0% ${left}% round 16px)` },
          { clipPath: "inset(0% 0% 0% 0% round 16px)", duration: 1.1, ease: "expo.inOut", overwrite: true, onComplete: hideOutgoing },
        );
        if (media) gsap.fromTo(media, { scale: 1.28, yPercent: 6 }, { scale: 1, yPercent: 0, duration: 1.5, ease: "expo.out", overwrite: true });
        if (outCaption) gsap.to(outCaption, { autoAlpha: 0, y: -6, duration: 0.25, ease: "power2.in", overwrite: true });
        if (inCaption) gsap.fromTo(inCaption, { autoAlpha: 0, y: 12 }, { autoAlpha: 1, y: 0, duration: 0.8, ease: "power3.out", delay: 0.5, overwrite: true });
      });

      markThumbs();
      revealThumb(!reduced);
      setIndex(to);
      const t = title(incoming);
      setMessage(`Photo ${to + 1} of ${n}${t ? `: ${t}` : ""}`);
    };

    api.current = { go, step: (d) => go(current + d), thumbs: thumbEls };
    setIndex(current);
    setReady(true);

    return () => {
      api.current = null;
      ctx.revert();
      slides.forEach((s) => (s.inert = false));
      thumbEls.forEach((t, k) => {
        t.toggleAttribute("data-active", k === 0);
        t.removeAttribute("aria-current");
      });
      setReady(false);
    };
  }, [count, many]);

  const onClick = (e: MouseEvent<HTMLDivElement>) => {
    const a = api.current;
    const thumb = (e.target as Element).closest<HTMLElement>("[data-thumb]");
    if (!a || !thumb) return;
    const k = a.thumbs.indexOf(thumb);
    if (k < 0) return;
    e.preventDefault();
    a.go(k);
  };

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    const a = api.current;
    if (!a || (e.target as HTMLElement).closest("[data-slide]")) return;
    const delta = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
    if (!delta) return;
    e.preventDefault();
    const fromThumb = a.thumbs.indexOf(e.target as HTMLElement);
    if (fromThumb >= 0) {
      const next = (fromThumb + delta + a.thumbs.length) % a.thumbs.length;
      a.go(next);
      a.thumbs[next]?.focus({ preventScroll: true });
    } else a.step(delta);
  };

  const btn =
    "group inline-flex size-11 items-center justify-center rounded-full text-neutral-900 ring-1 ring-neutral-300 transition 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";

  return (
    <div ref={rootRef} role="region" aria-roledescription="carousel" aria-label={label} onClick={onClick} onKeyDown={onKeyDown}>
      <div
        ref={trackRef}
        tabIndex={many ? 0 : undefined}
        className="flex snap-x snap-mandatory gap-4 relative overflow-x-auto overscroll-x-contain focus-visible:rounded-2xl focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-indigo-600"
      >
        {children}
      </div>
      {many ? (
        <div hidden={!ready} className="mt-6 flex items-center justify-between gap-4 border-t border-neutral-200 pt-5">
          <p aria-hidden="true" className="text-sm text-neutral-500 tabular-nums">
            <span className="text-2xl font-semibold tracking-tight text-neutral-950">{index + 1}</span> / {count}
          </p>
          <div className="flex gap-2">
            <button type="button" onClick={() => api.current?.step(-1)} aria-label="Previous photo" className={btn}>
              <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-5 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>
            </button>
            <button type="button" onClick={() => api.current?.step(1)} aria-label="Next photo" className={btn}>
              <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-5 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>
        </div>
      ) : null}
      {many && thumbs ? <div className="mt-5">{thumbs}</div> : null}
      {many ? (
        <p className="sr-only" aria-live="polite" aria-atomic="true">
          {message}
        </p>
      ) : null}
    </div>
  );
}
```
