# Add the "Voronoi Mosaic" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/voronoi-mosaic) to this Pantheon Content Publisher (P1) Next.js project. Stats section on solid cards over slowly shifting stained-glass panes in three brand colors.

## 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/voronoi-mosaic-block.tsx`, `components/puck/voronoi-mosaic.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 { voronoiMosaicBlock } from "./components/puck/voronoi-mosaic-block";`
4. Register it under `components` as `VoronoiMosaicBlock: voronoiMosaicBlock`.
5. Add `"VoronoiMosaicBlock"` 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/voronoi-mosaic-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { VoronoiCanvas } from "./voronoi-mosaic.client";

/**
 * Voronoi Mosaic — a stats or feature section set over slowly shifting stained-glass panes
 * in three brand colors (vgpu / WebGPU). Copy sits on solid panels, so it stays legible on
 * any pane. Needs `pnpm add vgpu` and voronoi-mosaic.client.tsx.
 * Register: `VoronoiMosaicBlock: voronoiMosaicBlock` in puck.config.tsx.
 */

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

type Stat = { value: string; label: string; detail: string };

export type VoronoiMosaicProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  stats: Stat[];
  footnote: string;
  leadColor: string;
  color1: string;
  color2: string;
  color3: string;
  cells: "3" | "5" | "8";
  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 #4338ca.";

export const voronoiMosaicBlock: ComponentConfig<VoronoiMosaicProps> = {
  label: "Voronoi Mosaic",
  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. The look doesn't change." },
    },
    body: { type: "textarea", label: "Body" },
    stats: {
      type: "array",
      label: "Figures",
      min: 0,
      max: 4,
      getItemSummary: (item) => [item?.value, item?.label].filter(Boolean).join(" · ") || "Figure",
      defaultItemProps: { value: "100", label: "New figure", detail: "" },
      arrayFields: {
        value: { type: "text", label: "Value", metadata: { help: "Keep it short, such as $4.2M or 312." } },
        label: { type: "text", label: "Label" },
        detail: { type: "textarea", label: "Detail", metadata: { help: "One sentence of context. Leave blank to hide it." } },
      },
    },
    footnote: { type: "text", label: "Source note", metadata: { help: "Where the figures come from. Leave blank to hide it." } },
    leadColor: { type: "text", label: "Leading color", metadata: { help: `${colorHelp} The thin lines between panes.` } },
    color1: { type: "text", label: "Glass color 1", metadata: { help: colorHelp } },
    color2: { type: "text", label: "Glass color 2", metadata: { help: colorHelp } },
    color3: { type: "text", label: "Glass color 3", metadata: { help: colorHelp } },
    cells: {
      type: "radio",
      label: "Pane size",
      options: [
        { label: "Large", value: "3" },
        { label: "Medium", value: "5" },
        { label: "Small", value: "8" },
      ],
    },
    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: {
    eyebrow: "Community Foundation · 2025 in review",
    heading: "Every neighborhood is a piece of the whole",
    headingLevel: "h2",
    body: "Grants from more than 4,000 local donors reached every ZIP code in the county last year, from after-school tutoring to tree canopy and tenant legal aid.",
    stats: [
      { value: "$14.2M", label: "Granted in 2025", detail: "Up 18% from 2024, with 61% going to groups led by the people they serve." },
      { value: "312", label: "Nonprofit partners", detail: "Including 74 first-time grantees with budgets under $250,000." },
      { value: "47", label: "Neighborhoods reached", detail: "Every ZIP code in the county received at least one grant." },
    ],
    footnote: "Source: Foundation 2025 annual report (sample figures).",
    leadColor: "#0d0d14",
    color1: "#4338ca",
    color2: "#0d9488",
    color3: "#eaa833",
    cells: "5",
    speed: "1",
  },
  render: ({ eyebrow, heading, headingLevel, body, stats, footnote, leadColor, color1, color2, color3, cells, speed }) => {
    const H = headingLevel || "h2";
    const lead = hex(leadColor, "#0d0d14");
    const c1 = hex(color1, "#4338ca");
    const c2 = hex(color2, "#0d9488");
    const c3 = hex(color3, "#eaa833");
    const figures = (stats ?? []).filter((s) => s?.value || s?.label);
    // The CSS fallback approximates the shader: a rose-window fan of the three glass colors.
    const fallback = {
      backgroundColor: lead,
      backgroundImage: `conic-gradient(from 20deg at 72% 38%, ${c1} 0 11%, ${lead} 0 11.4%, ${c2} 0 24%, ${lead} 0 24.4%, ${c3} 0 37%, ${lead} 0 37.4%, ${c1} 0 52%, ${lead} 0 52.4%, ${c2} 0 66%, ${lead} 0 66.4%, ${c3} 0 81%, ${lead} 0 81.4%, ${c2} 0 100%)`,
    };
    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}>
        <VoronoiCanvas colors={{ lead, c1, c2, c3 }} speed={Number(speed) || 1} cells={Number(cells) || 5} />
        <div className="relative mx-auto max-w-7xl">
          {eyebrow || heading || body ? (
            <div className="max-w-2xl rounded-2xl bg-neutral-950/90 p-6 shadow-xl ring-1 ring-white/10 sm:p-10">
              {eyebrow ? <p className="text-sm font-semibold tracking-[0.2em] text-white/75 uppercase">{eyebrow}</p> : null}
              {heading ? <H className="mt-3 text-3xl font-semibold tracking-tight text-balance text-white sm:text-5xl">{heading}</H> : null}
              {body ? <p className="mt-5 text-lg leading-8 text-pretty text-white/80">{body}</p> : null}
            </div>
          ) : null}
          {figures.length ? (
            <dl className="mt-8 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:mt-16 lg:grid-cols-3 lg:gap-6">
              {figures.map((s, i) => (
                <div key={i} className={`flex flex-col rounded-2xl bg-white p-6 shadow-xl ring-1 ring-neutral-950/5 sm:p-8 ${i % 2 === 1 ? "lg:translate-y-8" : ""}`}>
                  {s.label ? <dt className="text-sm font-semibold tracking-wide text-neutral-600 uppercase">{s.label}</dt> : null}
                  {s.value ? <dd className="order-first text-4xl font-semibold tracking-tight text-neutral-950 tabular-nums sm:text-5xl">{s.value}</dd> : null}
                  {s.detail ? <dd className="mt-3 text-base leading-7 text-pretty text-neutral-700">{s.detail}</dd> : null}
                </div>
              ))}
            </dl>
          ) : null}
          {footnote ? (
            <p className="mt-10 inline-block rounded-md bg-neutral-950/90 px-3 py-1.5 text-xs text-white/80 lg:mt-16">{footnote}</p>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/voronoi-mosaic.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 Voronoi Mosaic: slowly shifting stained-glass panes in three colors,
 * joined by thin even-width leading, with a faint sheen passing across (vgpu / WebGPU).
 * Decorative only. The section's content is server-rendered and the CSS fallback underneath
 * is the final look wherever WebGPU isn't available.
 */

const VORONOI_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  cells: f32,
  lead: vec3f,
  c1: vec3f,
  c2: vec3f,
  c3: 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 hash2(p: vec2f) -> vec2f {
  return vec2f(hash(p), hash(p + vec2f(19.19, 7.31)));
}

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 site(id: vec2f, t: f32) -> vec2f {
  let h = hash2(id);
  return 0.5 + 0.38 * sin(t * (0.25 + 0.3 * h) + 6.2831 * h);
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let p = vec2f(uv.x * params.aspect, uv.y) * params.cells;
  let ip = floor(p);
  let fp = fract(p);

  // Pass 1: nearest site (F1).
  var md = 8.0;
  var mr = vec2f(0.0);
  var mid = vec2f(0.0);
  for (var j = -1; j <= 1; j++) {
    for (var i = -1; i <= 1; i++) {
      let g = vec2f(f32(i), f32(j));
      let r = g + site(ip + g, t) - fp;
      let d = dot(r, r);
      if (d < md) { md = d; mr = r; mid = ip + g; }
    }
  }
  // Pass 2: exact distance to the nearest cell edge, for even-width leading.
  var edge = 8.0;
  for (var j = -2; j <= 2; j++) {
    for (var i = -2; i <= 2; i++) {
      let g = vec2f(f32(i), f32(j));
      let r = g + site(ip + g, t) - fp;
      let diff = r - mr;
      if (dot(diff, diff) > 1e-5) {
        edge = min(edge, dot(0.5 * (mr + r), normalize(diff)));
      }
    }
  }

  // Each pane takes one of the three glass colors, with its own tone and a hand-poured mottle.
  let pick = hash(mid + 3.3);
  var glass = params.c1;
  if (pick > 0.36) { glass = params.c2; }
  if (pick > 0.7) { glass = params.c3; }
  let tone = 0.62 + 0.5 * hash(mid + 8.8);
  let mottle = 0.82 + 0.3 * noise(p * 2.2 + mid * 1.7 + vec2f(t * 0.05, 0.0)) * noise(p * 7.0 - mid);
  // Light seems to pass through: panes glow toward their centers and dim at the leading.
  let lit = 0.62 + 0.48 * smoothstep(0.0, 0.32, edge);
  var col = glass * tone * mottle * lit;
  // A slow sheen sweeps across the window.
  let sheen = smoothstep(0.0, 1.0, sin(uv.x * 2.4 - uv.y * 1.6 + t * 0.22) * 0.5 + 0.5);
  col += vec3f(1.0, 0.97, 0.9) * pow(sheen, 6.0) * 0.12;

  let px = fwidth(p.y);
  let width = 0.008 + px * 0.55;
  let leading = 1.0 - smoothstep(width, width + px * 1.2, edge);
  col = mix(col, params.lead, leading);
  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 = { lead: string; c1: string; c2: string; c3: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };

const colorUniforms = (c: Colors) => ({
  lead: hexToVec3(c.lead, [0.04, 0.04, 0.06]),
  c1: hexToVec3(c.c1, [0.26, 0.22, 0.79]),
  c2: hexToVec3(c.c2, [0.05, 0.58, 0.53]),
  c3: hexToVec3(c.c3, [0.92, 0.66, 0.2]),
});

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

  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] });
        const aspect = () => (target.size[1] ? target.size[0] / target.size[1] : 1);
        const fx = effect(gpu, VORONOI_WGSL, {
          label: "voronoi-mosaic",
          set: { params: { time: 20, aspect: aspect(), cells: live.current.cells, ...colorUniforms(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: { aspect: aspect() } });
          if (still) queueMicrotask(draw);
        });

        const start = () => {
          if (loop || disposed || !gpu) return;
          loop = frameLoop(
            gpu,
            (f) => {
              fx.set({ params: { time: 20 + time.time * live.current.speed } });
              f.pass(target, fx);
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };

        if (still) {
          // Reduced motion: one settled frame, redrawn only when the editor changes a color.
          draw();
        } else {
          let onScreen = false;
          const sync = () => (onScreen && !document.hidden ? start() : 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;
      gpu?.dispose();
    };
  }, []);

  // Live-update colors and cell size from the Puck sidebar without re-initializing.
  useEffect(() => {
    fxRef.current?.set({ params: { cells, ...colorUniforms(colors) } });
    redrawRef.current?.();
  }, [colors.lead, colors.c1, colors.c2, colors.c3, cells]); // eslint-disable-line react-hooks/exhaustive-deps

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