# Add the "Mesh Gradient CTA" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/mesh-gradient-cta) to this Pantheon Content Publisher (P1) Next.js project. A rounded call-to-action panel over a slowly morphing, grainy four-color mesh gradient in your 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/mesh-gradient-cta-block.tsx`, `components/puck/mesh-gradient-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 { meshGradientCtaBlock } from "./components/puck/mesh-gradient-cta-block";`
4. Register it under `components` as `MeshGradientCtaBlock: meshGradientCtaBlock`.
5. Add `"MeshGradientCtaBlock"` 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/mesh-gradient-cta-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { MeshGradientCanvas } from "./mesh-gradient-cta.client";

/**
 * Mesh Gradient CTA — a rounded call-to-action panel over a slowly morphing, grainy mesh
 * gradient built from four brand colors (vgpu / WebGPU). Content is server-rendered;
 * browsers without WebGPU get a matching CSS gradient. Needs `pnpm add vgpu` and the
 * companion mesh-gradient-cta.client.tsx file.
 * Register: `MeshGradientCtaBlock: meshGradientCtaBlock` in puck.config.tsx.
 */

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

export type MeshGradientCtaProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  primaryLabel: string;
  primaryHref: string;
  secondaryLabel: string;
  secondaryHref: string;
  color1: string;
  color2: string;
  color3: string;
  color4: string;
  textColor: "light" | "dark";
  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 #0e7490. The four colors blend toward the panel's corners.";

const TONES = {
  light: {
    scrim: "bg-gradient-to-r from-black/45 via-black/20 to-transparent",
    eyebrow: "text-white/85",
    heading: "text-white",
    body: "text-white/90",
    primary: "bg-white text-neutral-950 hover:bg-white/90 focus-visible:outline-white",
    secondary: "text-white ring-white/60 hover:bg-white/10 focus-visible:outline-white",
  },
  dark: {
    scrim: "bg-gradient-to-r from-white/60 via-white/30 to-transparent",
    eyebrow: "text-neutral-800",
    heading: "text-neutral-950",
    body: "text-neutral-900",
    primary: "bg-neutral-950 text-white hover:bg-neutral-800 focus-visible:outline-neutral-950",
    secondary: "text-neutral-950 ring-neutral-950/40 hover:bg-neutral-950/5 focus-visible:outline-neutral-950",
  },
} as const;

export const meshGradientCtaBlock: ComponentConfig<MeshGradientCtaProps> = {
  label: "Mesh Gradient 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" },
    color1: { type: "text", label: "Color 1 (top left)", metadata: { help: colorHelp } },
    color2: { type: "text", label: "Color 2 (top right)", metadata: { help: colorHelp } },
    color3: { type: "text", label: "Color 3 (bottom left)", metadata: { help: colorHelp } },
    color4: { type: "text", label: "Color 4 (bottom right)", metadata: { help: colorHelp } },
    textColor: {
      type: "radio",
      label: "Text color",
      options: [
        { label: "Light", value: "light" },
        { label: "Dark", value: "dark" },
      ],
      metadata: { help: "Light text needs deep colors; dark text needs pale ones. A soft scrim behind the copy helps either way." },
    },
    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: "Spring Planting Days · Saturdays in April",
    heading: "Help us plant 4,000 trees along the river this spring",
    headingLevel: "h2",
    body: "Join neighbors at a three-hour planting shift. We bring the saplings, tools, gloves and lunch. You bring boots and a friend. No experience needed, and kids 10 and up are welcome with an adult.",
    primaryLabel: "Pick a planting day",
    primaryHref: "/volunteer/planting",
    secondaryLabel: "Sponsor a tree",
    secondaryHref: "/give/trees",
    color1: "#14532d",
    color2: "#0e7490",
    color3: "#1e3a8a",
    color4: "#b45309",
    textColor: "light",
    speed: "1",
  },
  render: ({ eyebrow, heading, headingLevel, body, primaryLabel, primaryHref, secondaryLabel, secondaryHref, color1, color2, color3, color4, textColor, speed }) => {
    const H = headingLevel || "h2";
    const tone = TONES[textColor] ?? TONES.light;
    const c1 = hex(color1, "#14532d");
    const c2 = hex(color2, "#0e7490");
    const c3 = hex(color3, "#1e3a8a");
    const c4 = hex(color4, "#b45309");
    // The CSS fallback approximates the shader's four-corner blend.
    const fallback = {
      backgroundColor: c1,
      backgroundImage: `radial-gradient(70% 90% at 0% 0%, ${c1}, transparent 70%), radial-gradient(70% 90% at 100% 0%, ${c2}, transparent 70%), radial-gradient(70% 90% at 0% 100%, ${c3}, transparent 70%), radial-gradient(70% 90% at 100% 100%, ${c4}, 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 shadow-xl shadow-neutral-950/10" style={fallback}>
          <MeshGradientCanvas colors={{ c1, c2, c3, c4 }} speed={Number(speed) || 1} />
          <div aria-hidden="true" className={`pointer-events-none absolute inset-0 ${tone.scrim}`} />
          <div className="relative px-6 py-14 sm:px-12 sm:py-20 lg:px-16 lg:py-24">
            <div className="max-w-2xl">
              {eyebrow ? <p className={`text-sm font-semibold tracking-widest uppercase ${tone.eyebrow}`}>{eyebrow}</p> : null}
              {heading ? (
                <H className={`mt-4 text-3xl font-semibold tracking-tight text-balance sm:text-5xl ${tone.heading}`}>{heading}</H>
              ) : null}
              {body ? <p className={`mt-6 text-lg leading-8 text-pretty ${tone.body}`}>{body}</p> : null}
              {primaryLabel || secondaryLabel ? (
                <div className="mt-10 flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
                  {primaryLabel ? (
                    <a
                      href={primaryHref || "#"}
                      className={`inline-flex min-h-11 items-center justify-center rounded-full px-6 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-11 items-center justify-center rounded-full px-6 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}
            </div>
          </div>
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/mesh-gradient-cta.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 the Mesh Gradient CTA: four brand-colored control points drift on slow
 * orbits and blend into a soft, grainy mesh gradient (vgpu / WebGPU). Decorative only.
 * The panel's content is server-rendered and its CSS gradient is the fallback look.
 */

const MESH_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  c1: vec3f,
  c2: vec3f,
  c3: vec3f,
  c4: 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,
  );
}

// Each control point orbits its own corner on a slow Lissajous path.
fn anchor(k: f32, t: f32, aspect: f32) -> vec2f {
  let corner = vec2f(
    select(0.18, 0.82, k == 1.0 || k == 3.0) * aspect,
    select(0.2, 0.8, k >= 2.0),
  );
  let orbit = vec2f(
    sin(t * (0.11 + 0.03 * k) + k * 1.7) * 0.32 * aspect,
    cos(t * (0.09 + 0.02 * k) + k * 2.3) * 0.3,
  );
  return corner + orbit;
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  var p = vec2f(uv.x * params.aspect, uv.y);
  // Gentle domain warp so the blends bend like silk instead of meeting in straight seams.
  p += 0.12 * vec2f(
    noise(p * 1.6 + vec2f(t * 0.05, 0.0)) - 0.5,
    noise(p * 1.6 + vec2f(4.1, t * 0.04)) - 0.5,
  );

  var col = vec3f(0.0);
  var total = 0.0;
  for (var k = 0; k < 4; k++) {
    let fk = f32(k);
    let d = p - anchor(fk, t, params.aspect);
    let w = 1.0 / (dot(d, d) * 6.0 + 0.04);
    var c = params.c1;
    if (k == 1) { c = params.c2; }
    if (k == 2) { c = params.c3; }
    if (k == 3) { c = params.c4; }
    col += c * w * w;
    total += w * w;
  }
  col /= total;

  // A soft sheen that drifts across the panel, then film grain.
  let sheen = smoothstep(0.55, 1.0, noise(p * 0.9 + vec2f(t * 0.03, -t * 0.02)));
  col += sheen * 0.05;
  col += (hash(uv * vec2f(1931.0, 1093.0) + fract(t * 0.37)) - 0.5) * 0.06;
  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 = { c1: string; c2: string; c3: string; c4: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };

const uniforms = (c: Colors) => ({
  c1: hexToVec3(c.c1, [0.08, 0.33, 0.18]),
  c2: hexToVec3(c.c2, [0.05, 0.45, 0.56]),
  c3: hexToVec3(c.c3, [0.12, 0.23, 0.54]),
  c4: hexToVec3(c.c4, [0.71, 0.33, 0.04]),
});

export function MeshGradientCanvas({ colors, speed }: { colors: Colors; speed: number }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const live = useRef({ colors, speed });
  live.current = { colors, speed };
  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 cleanupVisibility: (() => 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, MESH_WGSL, {
          label: "mesh-gradient",
          set: { params: { time: 12, aspect: aspect(), ...uniforms(live.current.colors) } },
        });
        fxRef.current = fx;
        target.onResize(() => fx.set({ params: { aspect: aspect() } }));
        const time = clock(gpu);

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

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

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

  useEffect(() => {
    fxRef.current?.set({ params: uniforms(colors) });
  }, [colors.c1, colors.c2, colors.c3, colors.c4]); // 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"}`}
    />
  );
}
```
