# Add the "Dither Hero" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/dither-hero) to this Pantheon Content Publisher (P1) Next.js project. A retro two-color ordered-dither hero whose light source follows the pointer. Bold for arts and campus pages.

## 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/dither-hero-block.tsx`, `components/puck/dither-hero.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 { ditherHeroBlock } from "./components/puck/dither-hero-block";`
4. Register it under `components` as `DitherHeroBlock: ditherHeroBlock`.
5. Add `"DitherHeroBlock"` 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/dither-hero-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { DitherCanvas } from "./dither-hero.client";

/**
 * Dither Hero — a hero over a two-color, retro ordered-dither light field whose light source
 * follows the pointer (vgpu / WebGPU). Copy sits on a solid panel so it stays legible; without
 * WebGPU a CSS gradient stands in. Needs `pnpm add vgpu` and dither-hero.client.tsx.
 * Register: `DitherHeroBlock: ditherHeroBlock` in puck.config.tsx.
 */

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

export type DitherHeroProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  primaryLabel: string;
  primaryHref: string;
  secondaryLabel: string;
  secondaryHref: string;
  darkColor: string;
  lightColor: string;
  pixelSize: "fine" | "medium" | "chunky";
};

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 PIXEL: Record<DitherHeroProps["pixelSize"], number> = { fine: 2, medium: 4, chunky: 7 };

export const ditherHeroBlock: ComponentConfig<DitherHeroProps> = {
  label: "Dither Hero",
  fields: {
    eyebrow: { type: "text", label: "Eyebrow", metadata: { help: "Small line above the heading. Leave blank to hide it." } },
    heading: { type: "textarea", label: "Heading" },
    headingLevel: {
      type: "select",
      label: "Heading level",
      options: [
        { label: "H1 (page title)", value: "h1" },
        { label: "H2", value: "h2" },
        { label: "H3", value: "h3" },
        { label: "H4", value: "h4" },
      ],
      metadata: { help: "Use H1 when this hero is the top of the page. The look doesn't change." },
    },
    body: { type: "textarea", label: "Body" },
    primaryLabel: { type: "text", label: "Primary button text" },
    primaryHref: { type: "text", label: "Primary button link" },
    secondaryLabel: { type: "text", label: "Secondary link text", metadata: { help: "Leave blank to hide it." } },
    secondaryHref: { type: "text", label: "Secondary link" },
    darkColor: {
      type: "text",
      label: "Shadow color",
      metadata: { help: "A hex color such as #16133a. Keep it dark: it's also the text panel, and the text is white." },
    },
    lightColor: {
      type: "text",
      label: "Light color",
      metadata: { help: "A hex color such as #ff8a3d. Also the button color, so keep it light against the shadow color." },
    },
    pixelSize: {
      type: "radio",
      label: "Pixel size",
      options: [
        { label: "Fine", value: "fine" },
        { label: "Medium", value: "medium" },
        { label: "Chunky", value: "chunky" },
      ],
      metadata: { help: "Visitors who ask their device for reduced motion see a still frame." },
    },
  },
  defaultProps: {
    eyebrow: "School of Art & Design · Spring Thesis Show",
    heading: "Forty-one artists. One very loud building.",
    headingLevel: "h1",
    body: "Painting, print, sound and code from this year's graduating class fill all four floors of the Hartley Gallery, April 9–27. Free and open to everyone.",
    primaryLabel: "Plan your visit",
    primaryHref: "/thesis-show",
    secondaryLabel: "Meet the artists",
    secondaryHref: "/thesis-show/artists",
    darkColor: "#16133a",
    lightColor: "#ff8a3d",
    pixelSize: "medium",
  },
  render: ({ eyebrow, heading, headingLevel, body, primaryLabel, primaryHref, secondaryLabel, secondaryHref, darkColor, lightColor, pixelSize }) => {
    const H = headingLevel || "h1";
    const dark = hex(darkColor, "#16133a");
    const light = hex(lightColor, "#ff8a3d");
    const pixel = PIXEL[pixelSize] ?? PIXEL.medium;
    // The CSS fallback is a coarse halftone glow in the same two colors; it's all non-WebGPU browsers see.
    const fallback = {
      backgroundColor: dark,
      backgroundImage: `radial-gradient(38% 55% at 66% 42%, ${light} 0 35%, transparent 75%), radial-gradient(circle, ${light}aa ${pixel * 0.35}px, transparent ${pixel * 0.5}px)`,
      backgroundSize: `auto, ${pixel * 2}px ${pixel * 2}px`,
    };
    return (
      <section className="relative isolate flex min-h-[40rem] items-end overflow-hidden lg:min-h-[44rem]" style={fallback}>
        <DitherCanvas colors={{ dark, light }} pixel={pixel} />
        <div className="mx-auto w-full max-w-7xl px-4 pt-48 pb-10 sm:px-6 sm:pb-16 lg:px-8 lg:pb-20">
          <div className="max-w-2xl p-6 sm:p-10" style={{ backgroundColor: dark }}>
            {eyebrow ? <p className="font-mono text-xs font-semibold tracking-widest text-white/80 uppercase">{eyebrow}</p> : null}
            {heading ? (
              <H className="mt-4 text-4xl leading-none font-semibold tracking-tight text-balance text-white sm:text-6xl">{heading}</H>
            ) : null}
            {body ? <p className="mt-6 text-lg leading-8 text-pretty text-white/85">{body}</p> : null}
            {primaryLabel || secondaryLabel ? (
              <div className="mt-8 flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-6">
                {primaryLabel ? (
                  <a
                    href={primaryHref || "#"}
                    style={{ backgroundColor: light, color: dark }}
                    className="inline-flex min-h-11 items-center justify-center px-5 py-3 font-mono text-sm font-bold tracking-wider uppercase transition hover:-translate-y-0.5 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-white"
                  >
                    {primaryLabel}
                  </a>
                ) : null}
                {secondaryLabel ? (
                  <a
                    href={secondaryHref || "#"}
                    className="group inline-flex min-h-11 items-center justify-center gap-1.5 px-1 text-base font-semibold text-white underline decoration-white/40 underline-offset-4 hover:decoration-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
                  >
                    {secondaryLabel}
                    <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="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}
          </div>
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/dither-hero.client.tsx`

```tsx
"use client";

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

/**
 * GPU half of the Dither Hero: a two-color, ordered-dither (8×8 Bayer) light field whose
 * light source follows the pointer (vgpu / WebGPU). Decorative only; the hero's content is
 * server-rendered and a CSS gradient underneath is the look without WebGPU.
 */

const DITHER_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  pixel: f32,
  presence: f32,
  res: vec2f,
  pointer: vec2f,
  dark: vec3f,
  light: 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,
  );
}

fn fbm(p0: vec2f) -> f32 {
  var p = p0;
  var amp = 0.5;
  var sum = 0.0;
  for (var i = 0; i < 4; i++) {
    sum += amp * noise(p);
    p = p * 2.03 + vec2f(3.1, 7.7);
    amp *= 0.5;
  }
  return sum;
}

// Recursive Bayer: 2x2 -> 4x4 -> 8x8 threshold in [0, 1).
fn bayer2(a: vec2f) -> f32 {
  let b = floor(a);
  return fract(b.x / 2.0 + b.y * b.y * 0.75);
}
fn bayer4(a: vec2f) -> f32 { return bayer2(0.5 * a) * 0.25 + bayer2(a); }
fn bayer8(a: vec2f) -> f32 { return bayer4(0.5 * a) * 0.25 + bayer2(a); }

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let aspect = params.res.x / max(params.res.y, 1.0);
  let cell = floor(uv * params.res / params.pixel);
  // Sample the light at the centre of each dither cell so every "pixel" is one flat value.
  let q = (cell + 0.5) * params.pixel / params.res;
  let p = vec2f(q.x * aspect, q.y);

  let rest = vec2f(0.74 + 0.05 * sin(t * 0.17), 0.36 + 0.05 * cos(t * 0.13));
  let lp = mix(rest, params.pointer, params.presence);
  let d = length((q - lp) * vec2f(aspect, 1.0));

  let key = exp(-d * d * 4.5);
  let core = exp(-d * d * 40.0);
  let clouds = fbm(p * 2.4 + vec2f(t * 0.035, -t * 0.02));
  let ridges = 1.0 - abs(2.0 * fbm(p * 1.3 - vec2f(t * 0.02, 0.0)) - 1.0);
  // Faint skylight from the top-right keeps the far side from going fully black.
  let sky = 0.18 * smoothstep(0.1, 1.0, q.x) * (1.0 - q.y);

  var lum = key * 0.55 + core * 0.3 + (clouds - 0.45) * 0.8 * (0.35 + key) + ridges * ridges * key * 0.3 + sky;
  // Sink the lower-left, where the copy panel sits, into the dark tone.
  lum *= mix(0.35, 1.0, smoothstep(0.0, 0.55, q.x + (1.0 - q.y) * 0.35));
  lum = pow(clamp(lum, 0.0, 1.0), 1.35);

  let on = step(bayer8(cell) + 0.5 / 64.0, lum);
  return vec4f(mix(params.dark, params.light, on), 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 = { dark: string; light: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };

const uniforms = (c: Colors) => ({
  dark: hexToVec3(c.dark, [0.08, 0.07, 0.2]),
  light: hexToVec3(c.light, [1, 0.55, 0.25]),
});

export function DitherCanvas({ colors, pixel }: { colors: Colors; pixel: number }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const dprRef = useRef(1);
  const live = useRef({ colors, pixel });
  live.current = { colors, pixel };
  const [ready, setReady] = useState(false);

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

    const aim = { x: 0.74, y: 0.36, on: 0 };
    const cur = { x: 0.74, y: 0.36, on: 0 };
    const onMove = (e: PointerEvent) => {
      if (e.pointerType === "touch") return;
      const r = canvas.getBoundingClientRect();
      if (!r.width || !r.height) return;
      aim.x = (e.clientX - r.left) / r.width;
      aim.y = (e.clientY - r.top) / r.height;
      aim.on = 1;
    };
    const onLeave = () => {
      aim.on = 0;
    };

    void (async () => {
      try {
        gpu = await init();
        if (disposed) return gpu.dispose();
        const target = surface(gpu, canvas, { dpr: [1, 2] });
        const sized = () => {
          dprRef.current = canvas.clientWidth ? target.size[0] / canvas.clientWidth : 1;
          return { res: [target.size[0], target.size[1]], pixel: live.current.pixel * dprRef.current };
        };
        const fx = effect(gpu, DITHER_WGSL, {
          label: "dither-hero",
          set: { params: { time: 3, presence: 0, pointer: [aim.x, aim.y], ...sized(), ...uniforms(live.current.colors) } },
        });
        fxRef.current = fx;
        const time = clock(gpu);
        const draw = () => gpu && !disposed && frame(gpu, (f) => f.pass(target, fx));
        redrawRef.current = still ? draw : null;
        target.onResize(() => {
          fx.set({ params: sized() });
          if (still) queueMicrotask(draw);
        });

        const start = () => {
          if (loop || disposed || !gpu) return;
          loop = frameLoop(
            gpu,
            (f) => {
              const t = time.time;
              if (touch) {
                aim.x = 0.62 + 0.26 * Math.sin(t * 0.19);
                aim.y = 0.4 + 0.2 * Math.sin(t * 0.14 + 0.8);
                aim.on = 1;
              }
              const k = 1 - Math.exp(-Math.min(time.deltaTime, 0.1) * 5);
              cur.x += (aim.x - cur.x) * k;
              cur.y += (aim.y - cur.y) * k;
              cur.on += (aim.on - cur.on) * k * 0.5;
              fx.set({ params: { time: 3 + t, pointer: [cur.x, cur.y], presence: cur.on } });
              f.pass(target, fx);
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };

        if (still) {
          draw();
        } else {
          host.addEventListener("pointermove", onMove, { passive: true });
          host.addEventListener("pointerleave", onLeave, { passive: true });
          observer = new IntersectionObserver(([entry]) => (entry?.isIntersecting ? start() : stop()));
          observer.observe(canvas);
        }
        setReady(true);
      } catch {
        // No adapter, blocked, or lost device: the CSS fallback is the look.
      }
    })();

    return () => {
      disposed = true;
      observer?.disconnect();
      host.removeEventListener("pointermove", onMove);
      host.removeEventListener("pointerleave", onLeave);
      loop?.stop();
      fxRef.current = null;
      redrawRef.current = null;
      gpu?.dispose();
    };
  }, []);

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

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