# Add the "Spotlight Grid" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/spotlight-grid) to this Pantheon Content Publisher (P1) Next.js project. Program cards over a GPU dot field that swells and takes on your accent color wherever the pointer moves.

## 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/spotlight-grid-block.tsx`, `components/puck/spotlight-grid.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 { spotlightGridBlock } from "./components/puck/spotlight-grid-block";`
4. Register it under `components` as `SpotlightGridBlock: spotlightGridBlock`.
5. Add `"SpotlightGridBlock"` 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/spotlight-grid-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { SpotlightCanvas } from "./spotlight-grid.client";

/**
 * Spotlight Grid — program or feature cards over a GPU dot-matrix field that swells and
 * takes on your accent color under the pointer (vgpu / WebGPU). Cards are real links;
 * without WebGPU a CSS dot pattern stands in. Needs `pnpm add vgpu` and spotlight-grid.client.tsx.
 * Register: `SpotlightGridBlock: spotlightGridBlock` in puck.config.tsx.
 */

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

type Card = { title: string; description: string; href: string };

export type SpotlightGridProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  intro: string;
  cards: Card[];
  baseColor: string;
  dotColor: string;
  accentColor: string;
  spotlight: "small" | "medium" | "large";
};

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 RADIUS: Record<SpotlightGridProps["spotlight"], number> = { small: 0.18, medium: 0.28, large: 0.4 };
const NEXT_LEVEL: Record<Heading, "h2" | "h3" | "h4" | "h5"> = { h1: "h2", h2: "h3", h3: "h4", h4: "h5" };
// Every third card drops a step on desktop so the grid reads as placed, not generated.
const OFFSET = ["", "lg:translate-y-10", "lg:-translate-y-4"];

const colorHelp = "A hex color such as #818cf8.";

export const spotlightGridBlock: ComponentConfig<SpotlightGridProps> = {
  label: "Spotlight Grid",
  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", 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. Card titles sit one level below. The look doesn't change." },
    },
    intro: { type: "textarea", label: "Intro" },
    cards: {
      type: "array",
      label: "Cards",
      min: 1,
      max: 9,
      getItemSummary: (item) => item.title || "Card",
      defaultItemProps: { title: "New program", description: "One or two sentences on who it serves and what it does.", href: "#" },
      arrayFields: {
        title: { type: "text", label: "Title" },
        description: { type: "textarea", label: "Description" },
        href: { type: "text", label: "Link", metadata: { help: "Leave blank and the card won't be a link." } },
      },
    },
    baseColor: { type: "text", label: "Background color", metadata: { help: `${colorHelp} Keep it dark: the text is white.` } },
    dotColor: { type: "text", label: "Dot color", metadata: { help: `${colorHelp} The resting color of the dot field.` } },
    accentColor: { type: "text", label: "Spotlight color", metadata: { help: `${colorHelp} Dots near the pointer warm to this.` } },
    spotlight: {
      type: "radio",
      label: "Spotlight size",
      options: [
        { label: "Small", value: "small" },
        { label: "Medium", value: "medium" },
        { label: "Large", value: "large" },
      ],
      metadata: { help: "Visitors who ask their device for reduced motion see a still dot field with no spotlight." },
    },
  },
  defaultProps: {
    eyebrow: "Programs · 2026–27",
    heading: "Six ways we show up for families",
    headingLevel: "h2",
    intro: "Every program is free, open to any household in the county, and staffed by people who live here. Start with the one that fits where you are today.",
    cards: [
      { title: "Early literacy", description: "Weekly story hours and a free book every month for children under five, in English and Spanish.", href: "/programs/early-literacy" },
      { title: "Home repair grants", description: "Up to $8,000 for roofs, ramps and furnaces so older neighbors can stay in the homes they own.", href: "/programs/home-repair" },
      { title: "Youth employment", description: "Paid summer jobs for 16–21 year olds with local employers, plus a mentor who stays on all year.", href: "/programs/youth-jobs" },
      { title: "Food access", description: "Three mobile pantries, a Saturday market that doubles SNAP dollars, and grocery delivery for homebound residents.", href: "/programs/food-access" },
      { title: "Legal help", description: "Free consultations on eviction, benefits and immigration with volunteer attorneys, twice a week.", href: "/programs/legal-help" },
      { title: "Digital skills", description: "Laptops on loan and evening classes, from setting up email to applying for jobs online.", href: "/programs/digital-skills" },
    ],
    baseColor: "#0a0a0a",
    dotColor: "#737373",
    accentColor: "#818cf8",
    spotlight: "medium",
  },
  render: ({ eyebrow, heading, headingLevel, intro, cards, baseColor, dotColor, accentColor, spotlight }) => {
    const H = headingLevel || "h2";
    const CardHeading = NEXT_LEVEL[H] ?? "h3";
    const base = hex(baseColor, "#0a0a0a");
    const dots = hex(dotColor, "#737373");
    const accent = hex(accentColor, "#818cf8");
    const items = (cards ?? []).filter((c) => c?.title || c?.description);
    // The CSS fallback is a static dot field with a soft accent pool; it's all non-WebGPU browsers see.
    const fallback = {
      backgroundColor: base,
      backgroundImage: `radial-gradient(60% 50% at 70% 60%, ${accent}22, transparent 70%), radial-gradient(circle, ${dots}66 1.1px, transparent 1.6px)`,
      backgroundSize: "auto, 18px 18px",
    };
    return (
      <section className="relative isolate overflow-hidden px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24" style={fallback}>
        <SpotlightCanvas colors={{ base, dots, accent }} radius={RADIUS[spotlight] ?? RADIUS.medium} />
        <div className="mx-auto max-w-7xl">
          {eyebrow || heading || intro ? (
            <div className="grid gap-6 lg:grid-cols-12 lg:items-end">
              <div className="lg:col-span-7">
                {eyebrow ? <p className="text-xs font-semibold tracking-widest text-indigo-300 uppercase">{eyebrow}</p> : null}
                {heading ? (
                  <H className="mt-4 text-4xl font-semibold tracking-tight text-balance text-white sm:text-5xl lg:text-6xl">{heading}</H>
                ) : null}
              </div>
              {intro ? <p className="max-w-xl text-lg leading-8 text-pretty text-neutral-300 lg:col-span-5 lg:pb-2">{intro}</p> : null}
            </div>
          ) : null}
          {items.length ? (
            <ul role="list" className="mt-12 grid gap-4 sm:mt-16 sm:grid-cols-2 lg:grid-cols-3 lg:gap-6 lg:pb-10">
              {items.map((card, i) => {
                const body = (
                  <>
                    <span aria-hidden="true" className="font-mono text-xs tracking-widest text-neutral-400 tabular-nums">
                      {String(i + 1).padStart(2, "0")}
                    </span>
                    {card.title ? <CardHeading className="mt-6 text-xl font-semibold tracking-tight text-white">{card.title}</CardHeading> : null}
                    {card.description ? <p className="mt-3 text-base leading-7 text-neutral-300">{card.description}</p> : null}
                    {card.href ? (
                      <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="mt-6 size-5 text-indigo-300 transition group-hover:translate-x-1">
                        <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>
                    ) : null}
                  </>
                );
                const shell = "flex h-full flex-col rounded-2xl bg-neutral-950/75 p-6 ring-1 ring-white/10 backdrop-blur-md ring-inset sm:p-8";
                return (
                  <li key={i} className={OFFSET[i % 3]}>
                    {card.href ? (
                      <a
                        href={card.href}
                        className={`group ${shell} transition hover:-translate-y-1 hover:ring-indigo-300/40 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-300`}
                      >
                        {body}
                      </a>
                    ) : (
                      <div className={shell}>{body}</div>
                    )}
                  </li>
                );
              })}
            </ul>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/spotlight-grid.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 Spotlight Grid: a fine dot matrix that swells and warms toward the accent
 * color around the pointer, over a slow ambient ripple (vgpu / WebGPU). Decorative only; the
 * cards are server-rendered and the CSS dot pattern underneath is the look without WebGPU.
 */

const SPOTLIGHT_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  pitch: f32,
  presence: f32,
  radius: f32,
  res: vec2f,
  pointer: vec2f,
  base: vec3f,
  dots: vec3f,
  accent: 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,
  );
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let px = uv * params.res;
  let cell = floor(px / params.pitch);
  let center = (cell + 0.5) * params.pitch;
  // Work in height-normalised units so the spotlight stays round at any aspect.
  let cuv = center / params.res.y;
  let puv = params.pointer * params.res / params.res.y;

  let dp = length(cuv - puv);
  let glow = exp(-(dp * dp) / (params.radius * params.radius)) * params.presence;
  let halo = exp(-(dp * dp) / (params.radius * params.radius * 4.0)) * params.presence;

  // Ambient life: a broad drifting swell plus slow rings radiating from the lower left.
  let swell = noise(cuv * 2.2 + vec2f(t * 0.05, -t * 0.03));
  let rings = 0.5 + 0.5 * sin(length(cuv - vec2f(-0.2, 1.3)) * 11.0 - t * 0.6);
  let ambient = swell * 0.55 + rings * 0.45;

  let r = params.pitch * (0.085 + 0.06 * ambient + 0.19 * glow);
  let d = length(px - center);
  let mask = 1.0 - smoothstep(r - 0.75, r + 0.75, d);

  let bright = 0.3 + 0.45 * ambient * ambient + 0.9 * glow;
  let tint = mix(params.dots, params.accent, clamp(glow * 1.25 + halo * 0.25, 0.0, 1.0));
  var col = params.base + params.accent * halo * 0.07;
  col = mix(col, tint + vec3f(glow * glow * 0.18), mask * clamp(bright, 0.0, 1.0));

  // Quiet the field under the heading at the top so the type always wins.
  col = mix(col, params.base, (1.0 - smoothstep(0.0, 0.32, uv.y)) * 0.45 * (1.0 - glow));
  return vec4f(col, 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 = { base: string; dots: string; accent: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };

const uniforms = (c: Colors) => ({
  base: hexToVec3(c.base, [0.04, 0.04, 0.05]),
  dots: hexToVec3(c.dots, [0.45, 0.45, 0.5]),
  accent: hexToVec3(c.accent, [0.5, 0.55, 0.97]),
});

export function SpotlightCanvas({ colors, radius }: { colors: Colors; radius: number }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const live = useRef({ colors, radius });
  live.current = { colors, radius };
  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;

    // Pointer target (from events) and the eased value the shader sees.
    const aim = { x: 0.5, y: 0.5, on: 0 };
    const cur = { x: 0.5, y: 0.5, 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 = () => {
          const dpr = canvas.clientWidth ? target.size[0] / canvas.clientWidth : 1;
          return { res: [target.size[0], target.size[1]], pitch: 18 * dpr };
        };
        const fx = effect(gpu, SPOTLIGHT_WGSL, {
          label: "spotlight-grid",
          set: {
            params: {
              time: 4,
              presence: 0,
              radius: live.current.radius,
              pointer: [0.5, 0.5],
              ...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.5 + 0.32 * Math.sin(t * 0.21);
                aim.y = 0.55 + 0.22 * Math.sin(t * 0.17 + 1.3);
                aim.on = 0.75;
              }
              const k = 1 - Math.exp(-Math.min(time.deltaTime, 0.1) * 7);
              cur.x += (aim.x - cur.x) * k;
              cur.y += (aim.y - cur.y) * k;
              cur.on += (aim.on - cur.on) * k * 0.6;
              fx.set({ params: { time: 4 + t, pointer: [cur.x, cur.y], presence: cur.on, radius: live.current.radius } });
              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 from the Puck sidebar without re-initializing.
  useEffect(() => {
    fxRef.current?.set({ params: { ...uniforms(colors), radius } });
    redrawRef.current?.();
  }, [colors.base, colors.dots, colors.accent, radius]); // 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"}`}
    />
  );
}
```
