# Add the "Grain Blob CTA" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/grain-blob-cta) to this Pantheon Content Publisher (P1) Next.js project. Call-to-action panel over drifting brand-color blobs and heavy film grain, with light or dark text.

## 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/grain-blob-cta-block.tsx`, `components/puck/grain-blob-cta.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 { grainBlobCtaBlock } from "./components/puck/grain-blob-cta-block";`
4. Register it under `components` as `GrainBlobCtaBlock: grainBlobCtaBlock`.
5. Add `"GrainBlobCtaBlock"` 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/grain-blob-cta-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { GrainBlobCanvas } from "./grain-blob-cta.client";

/**
 * Grain Blob CTA — a call-to-action panel over soft drifting color blobs and heavy film
 * grain in your brand colors (vgpu / WebGPU). Content is server-rendered; browsers without
 * WebGPU get a matching CSS gradient with SVG grain. Needs `pnpm add vgpu` and
 * grain-blob-cta.client.tsx. Register: `GrainBlobCtaBlock: grainBlobCtaBlock` in puck.config.tsx.
 */

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

export type GrainBlobCtaProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  primaryLabel: string;
  primaryHref: string;
  secondaryLabel: string;
  secondaryHref: string;
  note: string;
  textTone: "light" | "dark";
  baseColor: string;
  color1: string;
  color2: string;
  color3: string;
  grain: "0.06" | "0.12" | "0.2";
  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 GRAIN_SVG =
  "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.35'/%3E%3C/svg%3E\")";

const TONES = {
  light: {
    scrim: "bg-black/30",
    eyebrow: "text-white/85",
    heading: "text-white",
    body: "text-white/85",
    note: "text-white/75",
    primary: "bg-white text-neutral-950 hover:bg-white/90 focus-visible:outline-white",
    secondary: "text-white ring-white/40 hover:bg-white/10 focus-visible:outline-white",
  },
  dark: {
    scrim: "bg-white/35",
    eyebrow: "text-neutral-800",
    heading: "text-neutral-950",
    body: "text-neutral-800",
    note: "text-neutral-700",
    primary: "bg-neutral-950 text-white hover:bg-neutral-800 focus-visible:outline-neutral-950",
    secondary: "text-neutral-950 ring-neutral-950/30 hover:bg-neutral-950/5 focus-visible:outline-neutral-950",
  },
} as const;

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

export const grainBlobCtaBlock: ComponentConfig<GrainBlobCtaProps> = {
  label: "Grain Blob CTA",
  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" },
    primaryLabel: { type: "text", label: "Primary button text" },
    primaryHref: { type: "text", label: "Primary button link" },
    secondaryLabel: { type: "text", label: "Secondary button text", metadata: { help: "Leave blank to hide it." } },
    secondaryHref: { type: "text", label: "Secondary button link" },
    note: { type: "text", label: "Fine print", metadata: { help: "A reassurance line under the buttons. Leave blank to hide it." } },
    textTone: {
      type: "radio",
      label: "Text",
      options: [
        { label: "Light (dark background)", value: "light" },
        { label: "Dark (light background)", value: "dark" },
      ],
      metadata: { help: "Match this to the background color so the copy stays readable." },
    },
    baseColor: { type: "text", label: "Background color", metadata: { help: colorHelp } },
    color1: { type: "text", label: "Blob color 1", metadata: { help: colorHelp } },
    color2: { type: "text", label: "Blob color 2", metadata: { help: colorHelp } },
    color3: { type: "text", label: "Blob color 3", metadata: { help: colorHelp } },
    grain: {
      type: "radio",
      label: "Grain",
      options: [
        { label: "Subtle", value: "0.06" },
        { label: "Film", value: "0.12" },
        { label: "Heavy", value: "0.2" },
      ],
    },
    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: "Become a monthly sustainer",
    heading: "$15 a month keeps the pantry shelves full",
    headingLevel: "h2",
    body: "Monthly gifts let us buy fresh produce in bulk from regional farms, so every dollar stretches further for the 2,300 families we serve each week.",
    primaryLabel: "Start a monthly gift",
    primaryHref: "/give/monthly",
    secondaryLabel: "Other ways to give",
    secondaryHref: "/give",
    note: "Change or cancel anytime. Gifts are tax-deductible to the extent allowed by law.",
    textTone: "light",
    baseColor: "#120f1a",
    color1: "#f97316",
    color2: "#6366f1",
    color3: "#e11d48",
    grain: "0.12",
    speed: "1",
  },
  render: ({ eyebrow, heading, headingLevel, body, primaryLabel, primaryHref, secondaryLabel, secondaryHref, note, textTone, baseColor, color1, color2, color3, grain, speed }) => {
    const H = headingLevel || "h2";
    const tone = TONES[textTone] ?? TONES.light;
    const base = hex(baseColor, "#120f1a");
    const c1 = hex(color1, "#f97316");
    const c2 = hex(color2, "#6366f1");
    const c3 = hex(color3, "#e11d48");
    // The CSS fallback approximates the shader: three soft radial blobs under an SVG grain tile.
    const fallback = {
      backgroundColor: base,
      backgroundImage: `${GRAIN_SVG}, radial-gradient(40% 70% at 20% 30%, ${c1}cc, transparent 70%), radial-gradient(45% 75% at 78% 70%, ${c2}cc, transparent 70%), radial-gradient(35% 60% at 52% 5%, ${c3}b3, transparent 70%)`,
    };
    return (
      <section className="bg-white px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24">
        <div className="relative isolate mx-auto max-w-7xl overflow-hidden rounded-3xl" style={fallback}>
          <GrainBlobCanvas colors={{ base, c1, c2, c3 }} speed={Number(speed) || 1} grain={Number(grain) || 0.12} />
          <div aria-hidden="true" className={`pointer-events-none absolute inset-0 ${tone.scrim}`} />
          <div className="relative grid grid-cols-1 gap-10 px-6 py-14 sm:px-12 sm:py-20 lg:grid-cols-12 lg:items-end lg:px-16 lg:py-24">
            <div className="lg:col-span-7">
              {eyebrow ? <p className={`text-sm font-semibold tracking-[0.2em] uppercase ${tone.eyebrow}`}>{eyebrow}</p> : null}
              {heading ? <H className={`mt-4 text-4xl font-semibold tracking-tight text-balance sm:text-5xl lg:text-6xl ${tone.heading}`}>{heading}</H> : null}
              {body ? <p className={`mt-6 max-w-xl text-lg leading-8 text-pretty ${tone.body}`}>{body}</p> : null}
            </div>
            {primaryLabel || secondaryLabel || note ? (
              <div className="lg:col-span-5 lg:justify-self-end">
                {primaryLabel || secondaryLabel ? (
                  <div className="flex flex-col gap-3 sm:flex-row lg:flex-col xl:flex-row">
                    {primaryLabel ? (
                      <a
                        href={primaryHref || "#"}
                        className={`inline-flex min-h-12 items-center justify-center rounded-full px-7 py-3 text-base font-semibold shadow-sm transition focus-visible:outline-2 focus-visible:outline-offset-2 ${tone.primary}`}
                      >
                        {primaryLabel}
                      </a>
                    ) : null}
                    {secondaryLabel ? (
                      <a
                        href={secondaryHref || "#"}
                        className={`inline-flex min-h-12 items-center justify-center rounded-full px-7 py-3 text-base font-semibold ring-1 transition ring-inset focus-visible:outline-2 focus-visible:outline-offset-2 ${tone.secondary}`}
                      >
                        {secondaryLabel}
                      </a>
                    ) : null}
                  </div>
                ) : null}
                {note ? <p className={`mt-4 max-w-sm text-sm leading-6 ${tone.note}`}>{note}</p> : null}
              </div>
            ) : null}
          </div>
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/grain-blob-cta.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 Grain Blob CTA: three soft color blobs drifting on slow Lissajous paths
 * under heavy, film-rate grain that also stipples their edges (vgpu / WebGPU). Decorative
 * only. The panel's content is server-rendered and the CSS fallback underneath is the final
 * look wherever WebGPU isn't available.
 */

const GRAIN_BLOB_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  grain: f32,
  base: 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 blob(p: vec2f, center: vec2f, radius: f32) -> f32 {
  let d = p - center;
  return exp(-dot(d, d) / (radius * radius));
}

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

  // Film grain, re-rolled ~16 times a second rather than every frame so it reads as film.
  let pix = floor(uv / max(fwidth(uv), vec2f(1e-5)));
  let tick = floor(t * 16.0);
  let g = hash(pix + vec2f(tick * 17.0, tick * 31.0)) - 0.5;
  let g2 = hash(pix * 1.31 + vec2f(tick * 7.0, 3.0)) - 0.5;

  // Three soft blobs on slow, out-of-phase Lissajous paths.
  let b1 = blob(p, vec2f(a * (0.22 + 0.12 * sin(t * 0.21)), 0.3 + 0.18 * cos(t * 0.17)), 0.46);
  let b2 = blob(p, vec2f(a * (0.72 + 0.14 * cos(t * 0.19 + 1.3)), 0.65 + 0.2 * sin(t * 0.23 + 0.4)), 0.5);
  let b3 = blob(p, vec2f(a * (0.5 + 0.22 * sin(t * 0.13 + 2.6)), 0.1 + 0.25 * sin(t * 0.16 + 4.0)), 0.4);

  // Grain dithers the blob edges too: that stippled falloff is the look.
  let jitter = g2 * params.grain * 1.6;
  var col = params.base;
  col = mix(col, params.c1, clamp(b1 + jitter, 0.0, 1.0) * 0.8);
  col = mix(col, params.c2, clamp(b2 + jitter, 0.0, 1.0) * 0.8);
  col = mix(col, params.c3, clamp(b3 * 0.9 + jitter, 0.0, 1.0) * 0.75);

  col += g * params.grain;
  return vec4f(clamp(col, vec3f(0.0), vec3f(1.0)), 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; c1: string; c2: string; c3: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };

const colorUniforms = (c: Colors) => ({
  base: hexToVec3(c.base, [0.07, 0.06, 0.1]),
  c1: hexToVec3(c.c1, [0.98, 0.45, 0.09]),
  c2: hexToVec3(c.c2, [0.39, 0.4, 0.95]),
  c3: hexToVec3(c.c3, [0.88, 0.11, 0.28]),
});

export function GrainBlobCanvas({ colors, speed, grain }: { colors: Colors; speed: number; grain: number }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const live = useRef({ colors, speed, grain });
  live.current = { colors, speed, grain };
  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, GRAIN_BLOB_WGSL, {
          label: "grain-blob",
          set: { params: { time: 20, aspect: aspect(), grain: live.current.grain, ...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 grain from the Puck sidebar without re-initializing.
  useEffect(() => {
    fxRef.current?.set({ params: { grain, ...colorUniforms(colors) } });
    redrawRef.current?.();
  }, [colors.base, colors.c1, colors.c2, colors.c3, grain]); // 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"}`}
    />
  );
}
```
