# Add the "Halftone Band" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/halftone-band) to this Pantheon Content Publisher (P1) Next.js project. Full-width quote or announcement band framed by a moving two-color halftone dot screen.

## Steps

1. Install the dependency: `pnpm add vgpu` (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/halftone-band-block.tsx`, `components/puck/halftone-band.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 { halftoneBandBlock } from "./components/puck/halftone-band-block";`
4. Register it under `components` as `HalftoneBandBlock: halftoneBandBlock`.
5. Add `"HalftoneBandBlock"` to the best-fitting entry in `categories` (this block's library category is "GPU effects"). 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/halftone-band-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { HalftoneCanvas } from "./halftone-band.client";

/**
 * Halftone Band — a full-width divider for a pull quote or announcement, framed top and bottom by
 * a moving, print-style halftone dot screen in two colors (vgpu / WebGPU). Text is server-rendered;
 * non-WebGPU browsers get a static CSS dot fringe. Needs `pnpm add vgpu` and halftone-band.client.tsx.
 * Register: `HalftoneBandBlock: halftoneBandBlock` in puck.config.tsx.
 */

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

export type HalftoneBandProps = {
  mode: "quote" | "announcement";
  eyebrow: string;
  text: string;
  headingLevel: Heading;
  attribution: string;
  attributionRole: string;
  ctaLabel: string;
  ctaHref: string;
  inkColor: string;
  paperColor: string;
  dotSize: "8" | "11" | "15";
  speed: "0.5" | "1" | "1.6";
};

const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
const hex = (value: string | undefined, fallback: string) => (HEX.test((value ?? "").trim()) ? `#${value!.trim().replace(/^#/, "")}` : fallback);

const colorHelp = "A hex color such as #312e81.";

export const halftoneBandBlock: ComponentConfig<HalftoneBandProps> = {
  label: "Halftone Band",
  fields: {
    mode: {
      type: "radio",
      label: "Style",
      options: [
        { label: "Quote", value: "quote" },
        { label: "Announcement", value: "announcement" },
      ],
      metadata: { help: "A quote shows quotation marks and an attribution. An announcement shows the text as a heading." },
    },
    eyebrow: { type: "text", label: "Eyebrow", metadata: { help: "Small line above the text. Leave blank to hide it." } },
    text: { type: "textarea", label: "Text", metadata: { help: "Keep it to one or two sentences; it's set large." } },
    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: "Used in Announcement style only. Sets the page outline; the look doesn't change." },
    },
    attribution: { type: "text", label: "Attribution", metadata: { help: "Who said it. Quote style only; leave blank to hide it." } },
    attributionRole: { type: "text", label: "Attribution detail", metadata: { help: "Their role or context, like Volunteer since 2019." } },
    ctaLabel: { type: "text", label: "Button text", metadata: { help: "Leave blank to hide it." } },
    ctaHref: { type: "text", label: "Button link" },
    inkColor: { type: "text", label: "Ink color", metadata: { help: `${colorHelp} Used for the dots and the text, so it needs strong contrast with the paper color.` } },
    paperColor: { type: "text", label: "Paper color", metadata: { help: `${colorHelp} The band's background.` } },
    dotSize: {
      type: "radio",
      label: "Dot size",
      options: [
        { label: "Fine", value: "8" },
        { label: "Medium", value: "11" },
        { label: "Bold", value: "15" },
      ],
    },
    speed: {
      type: "radio",
      label: "Motion",
      options: [
        { label: "Drifting", value: "0.5" },
        { label: "Gentle", value: "1" },
        { label: "Lively", value: "1.6" },
      ],
      metadata: { help: "Visitors who ask their device for reduced motion always see a still frame." },
    },
  },
  defaultProps: {
    mode: "quote",
    eyebrow: "From the reading room",
    text: "The library card was the first thing in this country with my name on it. Now my daughter has one too.",
    headingLevel: "h2",
    attribution: "Amina Haddad",
    attributionRole: "ESL Conversation Circle, class of 2024",
    ctaLabel: "Read more patron stories",
    ctaHref: "/stories",
    inkColor: "#312e81",
    paperColor: "#eef2ff",
    dotSize: "11",
    speed: "1",
  },
  render: ({ mode, eyebrow, text, headingLevel, attribution, attributionRole, ctaLabel, ctaHref, inkColor, paperColor, dotSize, speed }) => {
    const H = headingLevel || "h2";
    const ink = hex(inkColor, "#312e81");
    const paper = hex(paperColor, "#eef2ff");
    const size = Number(dotSize) || 11;
    const isQuote = mode !== "announcement";
    // A static dot fringe at both edges: the look wherever WebGPU isn't available.
    const fringe = (toward: "bottom" | "top") => ({
      backgroundImage: `radial-gradient(circle, ${ink} 38%, transparent 42%)`,
      backgroundSize: `${size}px ${size}px`,
      maskImage: `linear-gradient(to ${toward}, black, transparent)`,
      WebkitMaskImage: `linear-gradient(to ${toward}, black, transparent)`,
    });
    const textClass = "text-3xl font-semibold tracking-tight text-balance sm:text-4xl lg:text-5xl lg:leading-tight";

    return (
      <section className="relative isolate overflow-hidden px-4 py-32 sm:px-6 sm:py-36 lg:px-8" style={{ backgroundColor: paper, color: ink }}>
        <div aria-hidden="true" className="absolute inset-x-0 top-0 h-24" style={fringe("bottom")} />
        <div aria-hidden="true" className="absolute inset-x-0 bottom-0 h-24" style={fringe("top")} />
        <HalftoneCanvas colors={{ ink, paper }} dotSize={size} speed={Number(speed) || 1} />

        <div className="relative mx-auto max-w-4xl text-center">
          {eyebrow ? <p className="text-sm font-semibold tracking-widest uppercase">{eyebrow}</p> : null}
          {text ? (
            isQuote ? (
              <figure className="mt-6">
                <blockquote>
                  <p className={textClass}>
                    <span aria-hidden="true">“</span>
                    {text}
                    <span aria-hidden="true">”</span>
                  </p>
                </blockquote>
                {attribution ? (
                  <figcaption className="mt-8 text-base">
                    <span className="font-semibold">{attribution}</span>
                    {attributionRole ? <span className="block opacity-90 sm:inline sm:before:mx-2 sm:before:content-['·']">{attributionRole}</span> : null}
                  </figcaption>
                ) : null}
              </figure>
            ) : (
              <H className={`mt-6 ${textClass}`}>{text}</H>
            )
          ) : null}
          {ctaLabel ? (
            <a
              href={ctaHref || "#"}
              className="mt-10 inline-flex min-h-11 items-center justify-center rounded-lg px-5 py-3 text-base font-semibold shadow-sm transition hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-4"
              style={{ backgroundColor: ink, color: paper, outlineColor: ink }}
            >
              {ctaLabel}
            </a>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/halftone-band.client.tsx`

```tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { clock, effect, frameLoop, init, surface } from "vgpu";
import type { FrameLoopHandle } from "vgpu";

/**
 * GPU half of Halftone Band: a 45° print-style dot screen that swells from the band's top and
 * bottom edges, its reach rolling across the width like a slow tide (vgpu / WebGPU). The middle
 * stays clear for the server-rendered text; the CSS dot fringe underneath is the fallback.
 */

const HALFTONE_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  pitch: f32,
  zone: f32,
  res: vec2f,
  ink: vec3f,
  paper: vec3f,
}
@group(0) @binding(0) var<uniform> params: Params;

fn hash(p: vec2f) -> f32 {
  return fract(sin(dot(p, vec2f(127.1, 311.7))) * 43758.5453);
}

fn noise(p: vec2f) -> f32 {
  let i = floor(p);
  let f = fract(p);
  let u = f * f * (3.0 - 2.0 * f);
  return mix(
    mix(hash(i), hash(i + vec2f(1.0, 0.0)), u.x),
    mix(hash(i + vec2f(0.0, 1.0)), hash(i + vec2f(1.0, 1.0)), u.x),
    u.y,
  );
}

// Ink coverage (0..1) at a point in device pixels: full at the band's edges, falling to zero
// within a reach that swells and recedes across the width.
fn coverage(q: vec2f, t: f32) -> f32 {
  let edge = min(q.y, params.res.y - q.y);
  let x = q.x / max(params.res.y, 1.0);
  let tide = 0.5 + 0.5 * sin(x * 2.4 - t * 0.55) * cos(x * 0.9 + t * 0.21);
  let grain = noise(q / (params.pitch * 7.0) + vec2f(t * 0.08, -t * 0.05));
  let reach = params.zone * (0.45 + 0.75 * tide + 0.45 * (grain - 0.5));
  let v = clamp(1.0 - edge / max(reach, 1.0), 0.0, 1.0);
  return v * v * (3.0 - 2.0 * v);
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let px = uv * params.res;
  // Classic 45° screen angle.
  let rot = mat2x2f(0.70710678, -0.70710678, 0.70710678, 0.70710678);
  let r = rot * px / params.pitch;
  let g = floor(r);
  let aa = 1.2 / params.pitch;

  // Dots grow past their cell to merge into solid ink, so check the 3x3 neighborhood.
  var ink = 0.0;
  for (var j = -1; j <= 1; j++) {
    for (var i = -1; i <= 1; i++) {
      let c = g + vec2f(f32(i), f32(j)) + 0.5;
      let center = transpose(rot) * c * params.pitch;
      let v = coverage(center, t);
      let radius = sqrt(v) * 0.78;
      let d = length(r - c);
      ink = max(ink, smoothstep(radius + aa, radius - aa, d) * step(0.004, v));
    }
  }

  return vec4f(mix(params.paper, params.ink, ink), 1.0);
}
`;

type Vec3 = [number, number, number];

function hexToVec3(hex: string | undefined, fallback: Vec3): Vec3 {
  const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((hex ?? "").trim());
  if (!m) return fallback;
  const h = m[1].length === 3 ? m[1].replace(/./g, "$&$&") : m[1];
  return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255) as Vec3;
}

type Colors = { ink: string; paper: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };
type HalftoneCanvasProps = { colors: Colors; dotSize: number; speed: number };

/** Reach of the dot fringe from each edge, in CSS pixels; the band's padding keeps text clear of it. */
const ZONE_CSS_PX = 92;

export function HalftoneCanvas({ colors, dotSize, speed }: HalftoneCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const resizeRef = useRef<(() => void) | null>(null);
  const live = useRef({ colors, dotSize, speed });
  live.current = { colors, dotSize, speed };
  const [ready, setReady] = useState(false);

  const uniforms = (c: Colors) => ({
    ink: hexToVec3(c.ink, [0.19, 0.18, 0.51]),
    paper: hexToVec3(c.paper, [0.93, 0.95, 1]),
  });

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !("gpu" in navigator)) return;
    let disposed = false;
    let loop: FrameLoopHandle | undefined;
    let gpu: Awaited<ReturnType<typeof init>> | undefined;
    let observer: IntersectionObserver | undefined;
    let removeVisibility: (() => void) | undefined;
    const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    void (async () => {
      try {
        gpu = await init();
        if (disposed) return gpu.dispose();
        const target = surface(gpu, canvas, { dpr: [1, 2] });
        // Pitch and reach are authored in CSS pixels and scaled to the backing store.
        const sized = () => {
          const dpr = canvas.clientWidth ? target.size[0] / canvas.clientWidth : 1;
          return { res: [target.size[0], target.size[1]], pitch: live.current.dotSize * dpr, zone: ZONE_CSS_PX * dpr };
        };
        const fx = effect(gpu, HALFTONE_WGSL, {
          label: "halftone-band",
          set: { params: { time: 3, ...sized(), ...uniforms(live.current.colors) } },
        });
        fxRef.current = fx;
        const time = clock(gpu);

        const start = () => {
          if (loop || disposed || !gpu) return;
          loop = frameLoop(
            gpu,
            (frame) => {
              fx.set({ params: { time: 3 + time.time * live.current.speed } });
              frame.pass(target, fx);
              if (still) stop();
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };
        redrawRef.current = still ? start : null;
        resizeRef.current = () => fx.set({ params: sized() });
        target.onResize(() => {
          fx.set({ params: sized() });
          if (still) start();
        });

        let onScreen = false;
        const sync = () => (onScreen && !document.hidden ? start() : still ? undefined : stop());
        observer = new IntersectionObserver(([entry]) => {
          onScreen = Boolean(entry?.isIntersecting);
          sync();
        });
        observer.observe(canvas);
        document.addEventListener("visibilitychange", sync);
        removeVisibility = () => document.removeEventListener("visibilitychange", sync);
        setReady(true);
      } catch {
        // No adapter, blocked, or lost device: the CSS fallback is the look.
      }
    })();

    return () => {
      disposed = true;
      observer?.disconnect();
      removeVisibility?.();
      loop?.stop();
      fxRef.current = null;
      redrawRef.current = null;
      resizeRef.current = null;
      gpu?.dispose();
    };
  }, []);

  // Live-update colors and dot size from the Puck sidebar without re-initializing.
  useEffect(() => {
    fxRef.current?.set({ params: uniforms(colors) });
    resizeRef.current?.();
    redrawRef.current?.();
  }, [colors.ink, colors.paper, dotSize]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <canvas
      ref={canvasRef}
      aria-hidden="true"
      className={`absolute inset-0 size-full transition-opacity duration-1000 ${ready ? "opacity-100" : "opacity-0"}`}
    />
  );
}
```
