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

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/timeline-carousel) to this Pantheon Content Publisher (P1) Next.js project. Your history as a draggable panel of milestones synced to a year scrubber whose marker glides to the active year.

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

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

/**
 * Timeline Carousel — an organization's history as a draggable panel of milestones (photo,
 * year, story) synced to a year scrubber whose marker glides to the active year (GSAP). Without
 * JavaScript it's a swipeable scroll-snap row. Needs `pnpm add gsap` and the companion
 * timeline-carousel.client.tsx file. Register: `TimelineCarouselBlock: timelineCarouselBlock` in puck.config.tsx.
 */

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

type Milestone = { year: string; title: string; body: string; imageUrl: string; imageAlt: string };

export type TimelineCarouselProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  intro: string;
  milestones: Milestone[];
};

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

export const timelineCarouselBlock: ComponentConfig<TimelineCarouselProps> = {
  label: "Timeline 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." } },
    milestones: {
      type: "array",
      label: "Milestones",
      min: 1,
      max: 12,
      getItemSummary: (item) => [item?.year, item?.title].filter(Boolean).join(" · ").slice(0, 48) || "Milestone",
      defaultItemProps: {
        year: "2026",
        title: "New milestone",
        body: "What happened, and why it mattered to the people you serve.",
        imageUrl: "https://picsum.photos/seed/milestone/1200/900",
        imageAlt: "",
      },
      arrayFields: {
        year: { type: "text", label: "Year", metadata: { help: "Shown on the scrubber, so keep it short: \"1987\" or \"Spring 2020\"." } },
        title: { type: "text", label: "Title" },
        body: { type: "textarea", label: "Story" },
        imageUrl: { type: "text", label: "Image URL", metadata: { help: "A landscape photo (4:3) works best. Leave blank for a text-only milestone." } },
        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." } },
      },
    },
  },
  defaultProps: {
    eyebrow: "Our history",
    heading: "Forty years of open doors",
    headingLevel: "h2",
    intro: "From a folding table in a church basement to six neighborhood centers, a few of the moments that made us.",
    milestones: [
      {
        year: "1986",
        title: "A folding table and a coffee pot",
        body: "Three neighbors start a Tuesday-night drop-in at St. Brendan's for families new to the city. Eleven people come the first week.",
        imageUrl: "https://picsum.photos/seed/basement/1200/900",
        imageAlt: "A small group of people seated around a folding table in a church hall",
      },
      {
        year: "1994",
        title: "Our first building",
        body: "A retired grocer donates his storefront on Fourth Street. Volunteers spend a summer turning it into classrooms and a lending library.",
        imageUrl: "https://picsum.photos/seed/storefront/1200/900",
        imageAlt: "A brick storefront with a hand-painted sign above the door",
      },
      {
        year: "2003",
        title: "English classes go citywide",
        body: "Evening English and citizenship classes expand to four libraries, with free childcare so parents can attend.",
        imageUrl: "https://picsum.photos/seed/classroom/1200/900",
        imageAlt: "Adult students writing at desks while a teacher points to a whiteboard",
      },
      {
        year: "2012",
        title: "Legal help under one roof",
        body: "We open a free immigration legal clinic with two staff attorneys and a network of volunteer lawyers.",
        imageUrl: "https://picsum.photos/seed/legalclinic/1200/900",
        imageAlt: "An attorney reviewing documents with a family at a small office table",
      },
      {
        year: "2020",
        title: "Staying open when doors closed",
        body: "Classes move online in nine days, and staff deliver laptops and hotspots to 600 households who had no other way to connect.",
        imageUrl: "https://picsum.photos/seed/deliveries/1200/900",
        imageAlt: "A volunteer in a mask handing a boxed laptop to a resident at their door",
      },
      {
        year: "2025",
        title: "Six centers, one family",
        body: "The Westside center opens, our sixth, built with input from the 300 neighbors who answered our listening survey.",
        imageUrl: "https://picsum.photos/seed/westside/1200/900",
        imageAlt: "A bright community center lobby with families gathered for an opening celebration",
      },
    ],
  },
  render: ({ id, eyebrow, heading, headingLevel, intro, milestones }) => {
    const H = headingLevel || "h2";
    const T = NEXT_LEVEL[H] ?? "h3";
    const list = (milestones ?? []).filter((m) => m?.year || m?.title);
    const headingId = `${id}-heading`;
    const hasHeader = Boolean(eyebrow || heading || intro);

    const slides = list.map((m, i) => (
      <div
        key={`${m.year}-${i}`}
        data-slide=""
        role="group"
        aria-roledescription="slide"
        aria-label={`${m.year ? `${m.year}, ` : ""}${i + 1} of ${list.length}`}
        className="grid w-full shrink-0 snap-start grid-cols-1 gap-8 md:grid-cols-2 md:items-center md:gap-12 lg:gap-16"
      >
        {m.imageUrl ? (
          <div className="relative aspect-4/3 overflow-hidden rounded-2xl bg-neutral-100">
            <img data-media="" src={m.imageUrl} alt={m.imageAlt || ""} draggable={false} loading={i > 0 ? "lazy" : undefined} className="size-full object-cover" />
          </div>
        ) : null}
        <div className={m.imageUrl ? "" : "md:col-span-2 md:max-w-3xl"}>
          {m.year ? (
            <p data-anim="" className="font-serif text-6xl leading-none font-light tracking-tight text-indigo-600 tabular-nums sm:text-7xl lg:text-8xl">
              {m.year}
            </p>
          ) : null}
          {m.title ? (
            <T data-anim="" className="mt-6 text-2xl font-semibold tracking-tight text-balance text-neutral-950 sm:text-3xl">
              {m.title}
            </T>
          ) : null}
          {m.body ? (
            <p data-anim="" className="mt-4 max-w-xl text-lg leading-8 text-pretty text-neutral-600">
              {m.body}
            </p>
          ) : null}
        </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="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>
          ) : null}
          {slides.length > 0 ? (
            <div className={hasHeader ? "mt-12 sm:mt-16" : ""}>
              <TimelineStage label={heading || "Timeline"} items={list.map((m) => ({ year: m.year || "", title: m.title || "" }))}>
                {slides}
              </TimelineStage>
            </div>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/timeline-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 Timeline Carousel. Milestones arrive server-rendered as children in a
 * scroll-snap row; once hydrated they become a draggable panel (Draggable + Inertia) synced to
 * a year scrubber whose marker and filled rail glide to the active year.
 */

type Item = { year: string; title: string };
type Api = { go: (to: number, reveal?: boolean) => void; index: () => number };

export type TimelineStageProps = {
  children: ReactNode;
  items: Item[];
  label: string;
};

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

export function TimelineStage({ children, items, label }: TimelineStageProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const viewportRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);
  const scrubRef = useRef<HTMLDivElement>(null);
  const railRef = useRef<HTMLDivElement>(null);
  const fillRef = useRef<HTMLSpanElement>(null);
  const markerRef = useRef<HTMLSpanElement>(null);
  const api = useRef<Api | null>(null);
  const [enhanced, setEnhanced] = useState(false);
  const [active, setActive] = useState(0);
  const [status, setStatus] = useState("");
  const count = items.length;
  const interactive = enhanced && count > 1;

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

  useLayoutEffect(() => {
    const root = rootRef.current;
    const viewport = viewportRef.current;
    const track = trackRef.current;
    const scrub = scrubRef.current;
    const rail = railRef.current;
    const fill = fillRef.current;
    const marker = markerRef.current;
    if (!interactive || !root || !viewport || !track || !scrub || !rail || !fill || !marker) return;

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

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

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

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

    // Marker and filled rail follow the active year; the scrubber scrolls it into view on phones.
    const point = ctx.add("point", (i: number, instant = false) => {
      const btn = years[i];
      if (!btn) return;
      const center = btn.offsetLeft + btn.offsetWidth / 2;
      const duration = instant || reduced ? 0 : 0.8;
      gsap.to(marker, { x: center, duration, ease: "expo.out", overwrite: true });
      gsap.to(fill, { scaleX: rail.offsetWidth ? center / rail.offsetWidth : 0, duration, ease: "expo.out", overwrite: true });
      if (scrub.scrollWidth > scrub.clientWidth) {
        scrub.scrollTo({ left: center - scrub.clientWidth / 2, behavior: instant || reduced ? "auto" : "smooth" });
      }
    }) as (i: number, instant?: boolean) => void;

    const settle = (i: number, announce: boolean) => {
      const prev = index;
      index = i;
      slides.forEach((s, k) => (s.inert = k !== i));
      setActive(i);
      point(i);
      if (announce && prev !== i) setStatus(`${items[i]?.year ?? ""}${items[i]?.title ? `: ${items[i].title}` : ""}, ${i + 1} of ${slides.length}`);
    };

    // Arriving content rises in a beat behind the panel; the photo settles from a slight zoom.
    const reveal = ctx.add("reveal", (i: number) => {
      if (reduced) return;
      const slide = slides[i];
      gsap.fromTo(
        slide.querySelectorAll("[data-anim]"),
        { autoAlpha: 0, y: 18, filter: "blur(6px)" },
        { autoAlpha: 1, y: 0, filter: "blur(0px)", duration: 1.05, stagger: 0.12, delay: 0.25, ease: "power3.out", overwrite: true, clearProps: "filter" },
      );
      gsap.fromTo(slide.querySelectorAll("[data-media]"), { scale: 1.08 }, { scale: 1, duration: 1.4, ease: "power3.out", overwrite: true });
    }) as (i: number) => void;

    const go = ctx.add("go", (to: number, withReveal = true) => {
      const i = clamp(to, 0, slides.length - 1);
      if (i === index && Math.abs(Number(gsap.getProperty(track, "x")) - snaps[i]) < 1) return;
      const distance = Math.abs(i - index);
      settle(i, true);
      gsap.to(track, {
        x: snaps[i],
        duration: reduced ? 0 : Math.min(1.4, 0.8 + distance * 0.1),
        ease: "expo.inOut",
        overwrite: true,
        onComplete: () => void draggable?.update(),
      });
      if (withReveal) reveal(i);
    }) as Api["go"];

    ctx.add(() => {
      const scrolled = viewport.scrollLeft;
      viewport.scrollLeft = 0;
      measure();
      index = nearest(-scrolled);
      gsap.set(track, { x: snaps[index] });
      settle(index, false);
      point(index, true);

      draggable = Draggable.create(track, {
        type: "x",
        bounds: { minX: snaps[snaps.length - 1], maxX: 0 },
        edgeResistance: 0.85,
        inertia: !reduced,
        throwResistance: 2600,
        minDuration: 0.45,
        maxDuration: 1.1,
        zIndexBoost: false,
        cursor: "grab",
        activeCursor: "grabbing",
        snap: {
          x: (v: number) => {
            let i = nearest(v);
            const from = snaps[pressIndex];
            // A deliberate nudge turns the page even if it didn't cross the halfway line.
            if (i === pressIndex && Math.abs(v - from) > 40) i = clamp(pressIndex + (v < from ? 1 : -1), 0, snaps.length - 1);
            if (i !== index) settle(i, true);
            return snaps[i];
          },
        },
        onPress: () => {
          gsap.killTweensOf(track);
          pressIndex = nearest(Number(gsap.getProperty(track, "x")));
        },
        onDragEnd: () => {
          if (reduced && draggable) go(nearest(draggable.x), false);
        },
      })[0];
    });

    api.current = { go, index: () => index };

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

    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]); // eslint-disable-line react-hooks/exhaustive-deps

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    const a = api.current;
    if (!a) return;
    const keys: Record<string, number> = { ArrowRight: a.index() + 1, ArrowLeft: a.index() - 1, Home: 0, End: count - 1 };
    if (!(e.key in keys)) return;
    e.preventDefault();
    const to = clamp(keys[e.key], 0, count - 1);
    a.go(to);
    // Arrow keys on the scrubber walk focus along the years with the selection.
    if ((e.target as HTMLElement).hasAttribute("data-year")) railRef.current?.querySelectorAll<HTMLElement>("[data-year]")[to]?.focus({ preventScroll: true });
  };

  const arrow = (dir: 1 | -1) => {
    const disabled = dir === 1 ? active === count - 1 : active === 0;
    return (
      <button
        type="button"
        aria-label={dir === 1 ? "Next milestone" : "Previous milestone"}
        aria-disabled={disabled}
        onClick={() => !disabled && api.current?.go(active + dir)}
        className="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 ${dir === -1 ? "rotate-180" : ""}`}>
          <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}>
      {interactive ? (
        <div className="flex items-end gap-4 sm:gap-8">
          <div ref={scrubRef} className="min-w-0 flex-1 relative overflow-x-auto overscroll-x-contain pt-1 pb-3">
            <div ref={railRef} className="relative flex min-w-max justify-between gap-2 px-1 sm:min-w-0">
              <span aria-hidden="true" className="absolute inset-x-0 bottom-0 h-px bg-neutral-200" />
              <span ref={fillRef} aria-hidden="true" style={{ transform: "scaleX(0)" }} className="absolute inset-x-0 -bottom-px h-0.5 origin-left bg-indigo-600" />
              {items.map((item, i) => {
                const current = i === active;
                return (
                  <button
                    key={`${item.year}-${i}`}
                    type="button"
                    data-year=""
                    aria-current={current ? "step" : undefined}
                    onClick={() => api.current?.go(i)}
                    className={`group relative min-h-11 min-w-11 rounded-md px-2 pb-6 text-sm font-semibold tabular-nums transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 sm:text-base ${
                      current ? "text-indigo-700" : "text-neutral-600 hover:text-neutral-950"
                    }`}
                  >
                    {item.year || i + 1}
                    {item.title ? <span className="sr-only">: {item.title}</span> : null}
                    <span
                      aria-hidden="true"
                      className={`absolute bottom-0 left-1/2 size-2 -translate-x-1/2 translate-y-1/2 rounded-full transition-colors ${i <= active ? "bg-indigo-600" : "bg-neutral-300 group-hover:bg-neutral-500"}`}
                    />
                  </button>
                );
              })}
              <span
                ref={markerRef}
                aria-hidden="true"
                className="pointer-events-none absolute bottom-0 left-0 size-4 -translate-x-1/2 translate-y-1/2 rounded-full bg-white ring-2 ring-indigo-600"
              />
            </div>
          </div>
          <div className="mb-3 hidden shrink-0 gap-2 sm:flex">
            {arrow(-1)}
            {arrow(1)}
          </div>
        </div>
      ) : null}

      <div
        ref={viewportRef}
        className={interactive ? "mt-10 overflow-hidden sm:mt-14" : "snap-x snap-mandatory relative overflow-x-auto overscroll-x-contain pb-6"}
      >
        <div ref={trackRef} className="relative flex gap-8 lg:gap-16">
          {children}
        </div>
      </div>

      {interactive ? (
        <>
          <div className="mt-8 flex justify-end gap-2 sm:hidden">
            {arrow(-1)}
            {arrow(1)}
          </div>
          <p aria-live="polite" className="sr-only">
            {status}
          </p>
        </>
      ) : null}
    </div>
  );
}
```
