# Add the "News Ticker" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/news-ticker) to this Pantheon Content Publisher (P1) Next.js project. A slim bar of linked headlines or alerts that roll vertically one at a time, with previous/next and optional rotation.

## 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/news-ticker-block.tsx`, `components/puck/news-ticker.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 { newsTickerBlock } from "./components/puck/news-ticker-block";`
4. Register it under `components` as `NewsTickerBlock: newsTickerBlock`.
5. Add `"NewsTickerBlock"` 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/news-ticker-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { NewsTickerStage } from "./news-ticker.client";

/**
 * News Ticker — a slim bar of linked headlines or alerts that roll vertically one at a time
 * (GSAP), with previous/next and optional rotation behind a Pause button. Reduced-motion and
 * no-JS visitors get the headlines as a plain list or swipeable row. Needs `pnpm add gsap` and
 * the companion news-ticker.client.tsx file. Register: `NewsTickerBlock: newsTickerBlock` in puck.config.tsx.
 */

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

type Headline = { text: string; href: string; meta: string };

export type NewsTickerProps = {
  label: string;
  headingLevel: Heading;
  headlines: Headline[];
  linkLabel: string;
  linkHref: string;
  autoplay: "off" | "on";
  interval: "5" | "7" | "10";
};

export const newsTickerBlock: ComponentConfig<NewsTickerProps> = {
  label: "News Ticker",
  fields: {
    label: { type: "text", label: "Label", metadata: { help: "The short tag at the start of the bar, such as \"Alerts\" or \"Latest\"." } },
    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." },
    },
    headlines: {
      type: "array",
      label: "Headlines",
      min: 1,
      max: 10,
      getItemSummary: (item) => item?.text?.slice(0, 48) || "Headline",
      defaultItemProps: { text: "New headline", href: "#", meta: "Today" },
      arrayFields: {
        text: { type: "text", label: "Headline", metadata: { help: "Keep it under about 80 characters so it fits on one line on most screens." } },
        href: { type: "text", label: "Link", metadata: { help: "Where the headline goes. Leave blank for plain text." } },
        meta: { type: "text", label: "Date or tag", metadata: { help: "Short, such as \"Today\" or \"Oct 6\". Leave blank to hide it." } },
      },
    },
    linkLabel: { type: "text", label: "Link text", metadata: { help: "Optional link at the end of the bar, such as \"All news\". Leave blank to hide it." } },
    linkHref: { type: "text", label: "Link" },
    autoplay: {
      type: "radio",
      label: "Rotate automatically",
      options: [
        { label: "Off", value: "off" },
        { label: "On", value: "on" },
      ],
      metadata: { help: "Adds a Pause button. Rotation stops on hover and focus, and never runs for visitors who ask for reduced motion." },
    },
    interval: {
      type: "select",
      label: "Time per headline",
      options: [
        { label: "5 seconds", value: "5" },
        { label: "7 seconds", value: "7" },
        { label: "10 seconds", value: "10" },
      ],
      metadata: { help: "Only used when rotation is on." },
    },
  },
  defaultProps: {
    label: "City news",
    headingLevel: "h2",
    linkLabel: "All news",
    linkHref: "/news",
    autoplay: "off",
    interval: "7",
    headlines: [
      { text: "Boil-water advisory lifted for the Eastgate neighborhood", href: "/news/eastgate-advisory-lifted", meta: "Today" },
      { text: "Council adopts 2027 budget with Sunday library hours at all branches", href: "/news/2027-budget", meta: "Oct 6" },
      { text: "Curbside leaf collection starts Monday, October 20. Find your zone", href: "/services/leaf-collection", meta: "Oct 3" },
      { text: "Winter utility assistance applications are open through November 14", href: "/assistance/utilities", meta: "Oct 1" },
      { text: "Riverside Park trail reopens after the footbridge rebuild", href: "/parks/riverside-trail", meta: "Sep 29" },
    ],
  },
  render: ({ id, label, headingLevel, headlines, linkLabel, linkHref, autoplay, interval }) => {
    const H = headingLevel || "h2";
    const list = (headlines ?? []).filter((h) => h?.text);
    if (!list.length) return <></>;
    const headingId = `${id}-label`;

    const badge = label ? (
      <H id={headingId} className="inline-flex shrink-0 items-center gap-2 rounded-full bg-indigo-600 px-3 py-1.5 text-xs font-semibold tracking-widest whitespace-nowrap text-white uppercase">
        <span aria-hidden="true" className="size-1.5 rounded-full bg-white" />
        {label}
      </H>
    ) : null;

    const slides = list.map((h, i) => {
      const body = (
        <>
          {h.meta ? <span className="shrink-0 text-xs font-semibold tracking-wide text-indigo-700 uppercase tabular-nums">{h.meta}</span> : null}
          <span className={`min-w-0 text-sm leading-6 font-medium text-pretty text-neutral-950 sm:text-base ${h.href ? "underline decoration-neutral-300 underline-offset-4 transition-colors group-hover:decoration-neutral-950" : ""}`}>{h.text}</span>
        </>
      );
      return (
        <div
          key={`${h.text}-${i}`}
          data-slide=""
          role="group"
          aria-roledescription="slide"
          aria-label={`${i + 1} of ${list.length}`}
          className="flex w-full shrink-0 snap-start items-center"
        >
          {h.href ? (
            <a
              href={h.href}
              className="group flex min-h-11 min-w-0 items-baseline gap-3 rounded-sm py-2 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
            >
              {body}
            </a>
          ) : (
            <p className="flex min-h-11 min-w-0 items-baseline gap-3 py-2">{body}</p>
          )}
        </div>
      );
    });

    return (
      <section aria-labelledby={label ? headingId : undefined} className="border-y border-neutral-200 bg-white px-4 sm:px-6 lg:px-8">
        <div className="mx-auto flex max-w-7xl flex-col gap-1 py-3 sm:flex-row sm:items-center sm:gap-6">
          <div className="min-w-0 flex-1">
            <NewsTickerStage count={slides.length} label={label || "Headlines"} badge={badge} autoplay={autoplay === "on"} interval={Number(interval) || 7}>
              {slides}
            </NewsTickerStage>
          </div>
          {linkLabel ? (
            <a
              href={linkHref || "#"}
              className="group inline-flex min-h-11 shrink-0 items-center gap-1 self-start rounded-md text-sm font-semibold whitespace-nowrap text-indigo-700 hover:text-indigo-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 sm:self-auto sm:border-l sm:border-neutral-200 sm:pl-6"
            >
              {linkLabel}
              <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-4 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>
      </section>
    );
  },
};
```

## File: `components/puck/news-ticker.client.tsx`

```tsx
"use client";

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

/**
 * Interactive half of the News Ticker. Headlines arrive server-rendered as children; once
 * hydrated they stack in one cell and roll vertically, like a departures board, with
 * previous/next and optional rotation (a hairline along the bar is its timer). Reduced-motion
 * visitors keep the plain stacked list the server rendered.
 */

type Api = { step: (dir: 1 | -1) => void };

export type NewsTickerStageProps = {
  children: ReactNode;
  count: number;
  label: string;
  badge: ReactNode;
  autoplay: boolean;
  interval: number;
};

export function NewsTickerStage({ children, count, label, badge, autoplay, interval }: NewsTickerStageProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const stageRef = useRef<HTMLDivElement>(null);
  const barRef = useRef<HTMLSpanElement>(null);
  const api = useRef<Api | null>(null);
  const userPausedRef = useRef(false);
  const rearmRef = useRef<(() => void) | null>(null);
  const [enhanced, setEnhanced] = useState(false);
  const [active, setActive] = useState(0);
  const [userPaused, setUserPaused] = useState(false);
  const [status, setStatus] = useState("");
  const interactive = enhanced && count > 1;
  const rotates = interactive && autoplay;
  const rotating = rotates && !userPaused;

  useEffect(() => {
    // Reduced motion: the stacked list is the final look, so there's nothing to enhance.
    setEnhanced(!window.matchMedia("(prefers-reduced-motion: reduce)").matches);
  }, []);

  useLayoutEffect(() => {
    const root = rootRef.current;
    const stage = stageRef.current;
    if (!interactive || !root || !stage) return;
    const slides = Array.from(stage.querySelectorAll<HTMLElement>(":scope > [data-slide]"));
    if (slides.length < 2) return;

    let current = 0;
    let hovered = false;
    let focused = false;
    let tl: gsap.core.Timeline | undefined;
    let timer: gsap.core.Tween | undefined;

    const ctx = gsap.context(() => {
      stage.scrollLeft = 0;
      gsap.set(slides, { gridArea: "1 / 1" });
      gsap.set(slides.slice(1), { autoAlpha: 0 });
      slides.forEach((s, i) => (s.inert = i !== 0));
    }, root);

    const arm = ctx.add("arm", () => {
      timer?.kill();
      const bar = barRef.current;
      if (!bar || !rotates || userPausedRef.current) {
        if (bar) gsap.to(bar, { scaleX: 0, duration: 0.3, ease: "power2.out" });
        return;
      }
      timer = gsap.fromTo(bar, { scaleX: 0 }, { scaleX: 1, duration: interval, ease: "none", onComplete: () => go(1, false) });
      if (hovered || focused || document.hidden) timer.pause();
    }) as () => void;

    const go = ctx.add("go", (dir: 1 | -1, announce = true) => {
      const next = (current + dir + slides.length) % slides.length;
      const out = slides[current];
      const inn = slides[next];
      tl?.progress(1);
      out.inert = true;
      inn.inert = false;
      // Keep keyboard focus on a headline link if it was on the one leaving.
      if (out.contains(document.activeElement)) inn.querySelector<HTMLElement>("a[href]")?.focus({ preventScroll: true });
      current = next;
      setActive(next);
      if (announce) setStatus(`Headline ${next + 1} of ${slides.length}`);
      tl = gsap
        .timeline({ defaults: { duration: 0.7, ease: "expo.inOut" } })
        .to(out, { yPercent: -110 * dir, autoAlpha: 0, filter: "blur(3px)" })
        .fromTo(inn, { yPercent: 110 * dir, autoAlpha: 0, filter: "blur(3px)" }, { yPercent: 0, autoAlpha: 1, filter: "blur(0px)", clearProps: "filter" }, "<0.06")
        .set(out, { yPercent: 0, filter: "none" });
      arm();
    }) as (dir: 1 | -1, announce?: boolean) => void;

    api.current = { step: (dir) => go(dir) };
    rearmRef.current = () => arm();
    arm();

    const sync = () => {
      if (!timer) return;
      if (hovered || focused || document.hidden) timer.pause();
      else timer.resume();
    };
    const onEnter = () => ((hovered = true), sync());
    const onLeave = () => ((hovered = false), sync());
    const onFocusIn = () => ((focused = true), sync());
    const onFocusOut = (e: FocusEvent) => {
      if (root.contains(e.relatedTarget as Node | null)) return;
      focused = false;
      sync();
    };
    root.addEventListener("pointerenter", onEnter);
    root.addEventListener("pointerleave", onLeave);
    root.addEventListener("focusin", onFocusIn);
    root.addEventListener("focusout", onFocusOut);
    document.addEventListener("visibilitychange", sync);

    return () => {
      root.removeEventListener("pointerenter", onEnter);
      root.removeEventListener("pointerleave", onLeave);
      root.removeEventListener("focusin", onFocusIn);
      root.removeEventListener("focusout", onFocusOut);
      document.removeEventListener("visibilitychange", sync);
      ctx.revert();
      slides.forEach((s) => (s.inert = false));
      api.current = null;
      rearmRef.current = null;
      setActive(0);
    };
  }, [interactive, rotates, interval, count]);

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    const keys: Record<string, 1 | -1> = { ArrowDown: 1, ArrowRight: 1, ArrowUp: -1, ArrowLeft: -1 };
    const dir = keys[e.key];
    if (!dir || !api.current) return;
    e.preventDefault();
    api.current.step(dir);
  };

  const togglePause = () => {
    userPausedRef.current = !userPausedRef.current;
    setUserPaused(userPausedRef.current);
    rearmRef.current?.();
  };

  const control =
    "inline-flex size-11 shrink-0 items-center justify-center rounded-full text-neutral-700 transition-colors hover:bg-neutral-100 hover:text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600";
  const chevron = (up: boolean) => (
    <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className={`size-5 ${up ? "rotate-180" : ""}`}>
      <path fillRule="evenodd" d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z" clipRule="evenodd" />
    </svg>
  );

  return (
    <div
      ref={rootRef}
      role="region"
      aria-roledescription="carousel"
      aria-label={label}
      onKeyDown={onKeyDown}
      className="relative flex flex-wrap items-center gap-x-3 gap-y-2 sm:flex-nowrap sm:gap-x-5"
    >
      <div className="flex shrink-0 items-center gap-1">
        {rotates ? (
          <button type="button" onClick={togglePause} className={control} aria-label={userPaused ? "Start rotating headlines" : "Pause rotating headlines"}>
            {userPaused ? (
              <svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" className="size-3.5">
                <path d="M4.5 2.8v10.4a.6.6 0 0 0 .9.5l8.3-5.2a.6.6 0 0 0 0-1L5.4 2.3a.6.6 0 0 0-.9.5Z" />
              </svg>
            ) : (
              <svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" className="size-3.5">
                <rect x="3.5" y="2.5" width="3" height="11" rx="0.75" />
                <rect x="9.5" y="2.5" width="3" height="11" rx="0.75" />
              </svg>
            )}
          </button>
        ) : null}
        {badge}
      </div>

      <div
        ref={stageRef}
        className={
          interactive
            ? "order-last -m-1 grid w-full min-w-0 grid-cols-1 overflow-hidden p-1 sm:order-none sm:w-auto sm:flex-1"
            : "order-last flex w-full min-w-0 snap-x snap-mandatory gap-6 relative overflow-x-auto overscroll-x-contain sm:order-none sm:w-auto sm:flex-1 motion-reduce:flex-col motion-reduce:gap-1 motion-reduce:overflow-visible"
        }
      >
        {children}
      </div>

      {interactive ? (
        <div className="ml-auto flex shrink-0 items-center gap-1">
          <p aria-hidden="true" className="mr-1 text-xs font-medium text-neutral-600 tabular-nums">
            {active + 1}/{count}
          </p>
          <button type="button" aria-label="Previous headline" onClick={() => api.current?.step(-1)} className={control}>
            {chevron(true)}
          </button>
          <button type="button" aria-label="Next headline" onClick={() => api.current?.step(1)} className={control}>
            {chevron(false)}
          </button>
        </div>
      ) : null}

      {rotates ? <span ref={barRef} aria-hidden="true" style={{ transform: "scaleX(0)" }} className="pointer-events-none absolute inset-x-0 -bottom-px h-0.5 origin-left bg-indigo-600" /> : null}
      {interactive ? (
        <p aria-live={rotating ? "off" : "polite"} className="sr-only">
          {status}
        </p>
      ) : null}
    </div>
  );
}
```
