# Add the "Liquid Progress" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/liquid-progress) to this Pantheon Content Publisher (P1) Next.js project. A fundraising meter: a vessel filled to your goal with a live GPU liquid surface, bindable totals and full ARIA.

## 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/liquid-progress-block.tsx`, `components/puck/liquid-progress.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 { liquidProgressBlock } from "./components/puck/liquid-progress-block";`
4. Register it under `components` as `LiquidProgressBlock: liquidProgressBlock`.
5. Add `"LiquidProgressBlock"` 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/liquid-progress-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { LiquidProgressCanvas } from "./liquid-progress.client";

/**
 * Liquid Progress — a fundraising or goal meter: a glass vessel filled to raised ÷ goal with a
 * moving, GPU-rendered liquid surface (vgpu / WebGPU). Figures are text fields, so they bind to
 * P1 data sources; the numbers are always server-rendered text with a static CSS fill fallback.
 * Needs `pnpm add vgpu` and liquid-progress.client.tsx. Register: `LiquidProgressBlock: liquidProgressBlock`.
 */

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

export type LiquidProgressProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  raised: string;
  goal: string;
  currency: string;
  donors: string;
  deadline: string;
  ctaLabel: string;
  ctaHref: string;
  liquidColor: string;
  backgroundColor: string;
  speed: "0.6" | "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 toNumber = (value: string | undefined) => {
  const cleaned = String(value ?? "").replace(/[^0-9.-]/g, "");
  if (!cleaned) return null;
  const n = Number.parseFloat(cleaned);
  return Number.isFinite(n) ? n : null;
};

const colorHelp = "A hex color such as #6366f1.";
const dataHelp = "A number. Commas and symbols are ignored, so you can bind a data source with {{ }}.";

export const liquidProgressBlock: ComponentConfig<LiquidProgressProps> = {
  label: "Liquid Progress",
  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" },
    raised: { type: "text", label: "Amount raised", metadata: { help: dataHelp } },
    goal: { type: "text", label: "Goal", metadata: { help: dataHelp } },
    currency: { type: "text", label: "Currency symbol", metadata: { help: "Shown before each amount, like $ or €." } },
    donors: { type: "text", label: "Donors", metadata: { help: "Free text, like 612 donors. Leave blank to hide it." } },
    deadline: { type: "text", label: "Deadline", metadata: { help: "Free text, like Closes June 30. Leave blank to hide it." } },
    ctaLabel: { type: "text", label: "Button text", metadata: { help: "Leave blank to hide it." } },
    ctaHref: { type: "text", label: "Button link" },
    liquidColor: { type: "text", label: "Liquid color", metadata: { help: colorHelp } },
    backgroundColor: { type: "text", label: "Vessel color", metadata: { help: `${colorHelp} The empty part of the vessel; keep it light.` } },
    speed: {
      type: "radio",
      label: "Motion",
      options: [
        { label: "Still water", value: "0.6" },
        { 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 Campaign · Clean Water Fund",
    heading: "Bring safe drinking water to 40 rural schools",
    headingLevel: "h2",
    body: "Every gift funds filtration units, testing kits and two years of maintenance training for school staff. A local foundation is matching donations dollar for dollar until the deadline.",
    raised: "48250",
    goal: "75000",
    currency: "$",
    donors: "612 donors",
    deadline: "Closes June 30",
    ctaLabel: "Give to the fund",
    ctaHref: "/donate",
    liquidColor: "#6366f1",
    backgroundColor: "#eef2ff",
    speed: "1",
  },
  render: ({ id, eyebrow, heading, headingLevel, body, raised, goal, currency, donors, deadline, ctaLabel, ctaHref, liquidColor, backgroundColor, speed }) => {
    const H = headingLevel || "h2";
    const liquid = hex(liquidColor, "#6366f1");
    const vessel = hex(backgroundColor, "#eef2ff");
    const sym = (currency ?? "").trim();
    const raisedN = toNumber(raised);
    const goalN = toNumber(goal);
    const ratio = raisedN !== null && goalN !== null && goalN > 0 ? Math.max(raisedN, 0) / goalN : null;
    const level = ratio === null ? 0 : Math.min(ratio, 1);
    const money = (n: number | null) => (n === null ? "—" : `${sym}${Math.round(n).toLocaleString("en-US")}`);
    const pct = ratio === null ? "—" : `${Math.round(ratio * 100)}%`;
    const summary = `${money(raisedN)} of ${money(goalN)} · ${pct}`;
    const labelId = `${id}-liquid-label`;

    return (
      <section className="bg-white px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24">
        <div className="mx-auto grid max-w-6xl items-center gap-12 lg:grid-cols-[minmax(0,1fr)_20rem] lg:gap-20">
          <div className="max-w-2xl">
            {eyebrow ? <p className="text-sm font-semibold tracking-widest text-indigo-700 uppercase">{eyebrow}</p> : null}
            {heading ? (
              <H id={labelId} className="mt-4 text-3xl font-semibold tracking-tight text-balance text-neutral-900 sm:text-5xl">
                {heading}
              </H>
            ) : null}
            {body ? <p className="mt-5 text-lg leading-8 text-pretty text-neutral-600">{body}</p> : null}

            <p className="mt-10 flex flex-wrap items-baseline gap-x-3 gap-y-1 tabular-nums">
              <span className="text-5xl font-semibold tracking-tight text-neutral-900 sm:text-6xl">{money(raisedN)}</span>
              <span className="text-lg text-neutral-600">
                raised of <span className="font-semibold text-neutral-900">{money(goalN)}</span> goal
              </span>
            </p>

            <dl className="mt-6 flex flex-wrap gap-x-8 gap-y-3 border-t border-neutral-200 pt-6 text-sm">
              <div>
                <dt className="text-neutral-500">Funded</dt>
                <dd className="mt-0.5 text-base font-semibold text-neutral-900 tabular-nums">{pct}</dd>
              </div>
              {donors ? (
                <div>
                  <dt className="text-neutral-500">Supporters</dt>
                  <dd className="mt-0.5 text-base font-semibold text-neutral-900 tabular-nums">{donors}</dd>
                </div>
              ) : null}
              {deadline ? (
                <div>
                  <dt className="text-neutral-500">Deadline</dt>
                  <dd className="mt-0.5 text-base font-semibold text-neutral-900">{deadline}</dd>
                </div>
              ) : null}
            </dl>

            {ctaLabel ? (
              <a
                href={ctaHref || "#"}
                className="mt-10 inline-flex min-h-11 items-center justify-center rounded-lg bg-indigo-600 px-5 py-3 text-base font-semibold text-white shadow-sm transition hover:bg-indigo-500 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
              >
                {ctaLabel}
              </a>
            ) : null}
          </div>

          <figure className="mx-auto w-full max-w-[16rem] lg:max-w-none">
            <div
              role="progressbar"
              aria-labelledby={heading ? labelId : undefined}
              aria-label={heading ? undefined : "Fundraising progress"}
              aria-valuemin={0}
              aria-valuemax={goalN ?? undefined}
              aria-valuenow={raisedN !== null && goalN !== null ? Math.min(Math.max(raisedN, 0), goalN) : undefined}
              aria-valuetext={summary}
              className="relative isolate h-80 overflow-hidden rounded-[2.5rem] shadow-inner ring-1 ring-neutral-950/10 sm:h-96 lg:h-[28rem]"
              style={{ backgroundColor: vessel }}
            >
              <div aria-hidden="true" className="absolute inset-x-0 bottom-0" style={{ height: `${level * 100}%`, backgroundColor: liquid }} />
              <LiquidProgressCanvas level={level} liquid={liquid} background={vessel} speed={Number(speed) || 1} />
              <div aria-hidden="true" className="pointer-events-none absolute inset-0">
                {["75", "50", "25"].map((mark) => (
                  <span key={mark} className="absolute right-0 h-px w-4 bg-neutral-950/25" style={{ bottom: `${mark}%` }} />
                ))}
              </div>
            </div>
            <figcaption className="mt-4 text-center text-sm font-medium text-neutral-700 tabular-nums">{summary}</figcaption>
          </figure>
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/liquid-progress.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 Liquid Progress: a vessel filled to the goal level with a moving liquid surface,
 * caustic shimmer and rising bubbles, drawn with vgpu (WebGPU). Decorative: the progress value
 * is exposed by the server-rendered progressbar, and the CSS fill underneath is the fallback.
 */

const LIQUID_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  level: f32,
  liquid: vec3f,
  background: vec3f,
}
@group(0) @binding(0) var<uniform> params: Params;

fn hash1(n: f32) -> f32 {
  return fract(sin(n * 91.345) * 47453.5453);
}

fn caustic(p0: vec2f, t: f32) -> f32 {
  let p = p0 * 6.2832 - vec2f(250.0);
  var i = p;
  var c = 1.0;
  let inten = 0.006;
  for (var n = 0; n < 4; n++) {
    let tt = t * (1.0 - 3.5 / f32(n + 1));
    i = p + vec2f(cos(tt - i.x) + sin(tt + i.y), sin(tt - i.y) + cos(tt + i.x));
    c += 1.0 / length(vec2f(p.x / (sin(i.x + tt) / inten), p.y / (cos(i.y + tt) / inten)));
  }
  c = c / 4.0;
  c = 1.17 - pow(c, 1.4);
  return clamp(pow(abs(c), 8.0), 0.0, 1.0);
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let x = uv.x * params.aspect;
  let h = 1.0 - uv.y;
  let level = clamp(params.level, 0.0, 1.0);
  // Calm the waves as the vessel nears empty or full so the surface never clips the walls.
  let amp = smoothstep(0.0, 0.05, level) * (1.0 - smoothstep(0.97, 1.0, level));

  let front = level + amp * (0.020 * sin(x * 6.0 + t * 1.5) + 0.008 * sin(x * 14.0 - t * 2.2 + 1.3));
  let back = level + amp * (0.022 * sin(x * 4.3 - t * 1.1 + 2.4) + 0.008 * sin(x * 11.0 + t * 1.7));

  // Empty glass: the background with a faint vertical falloff and a soft reflection streak.
  var col = params.background * mix(1.02, 0.94, uv.y);
  let streak = exp(-pow((uv.x - 0.16) * 14.0, 2.0)) * 0.35 + exp(-pow((uv.x - 0.24) * 40.0, 2.0)) * 0.25;
  col = mix(col, vec3f(1.0), streak);

  // Back wave: a lighter, translucent layer visible just above the front surface.
  let backMask = smoothstep(back + 0.003, back - 0.003, h);
  col = mix(col, mix(params.liquid, vec3f(1.0), 0.45), backMask * 0.55);

  let frontMask = smoothstep(front + 0.003, front - 0.003, h);
  if (frontMask > 0.0) {
    let depth = max(front - h, 0.0);
    var liq = params.liquid * mix(1.08, 0.66, smoothstep(0.0, 0.9, depth));
    // Caustic shimmer, strongest near the surface and fading with depth.
    let cs = caustic(vec2f(x * 0.8, h * 1.1), t * 0.35);
    liq = mix(liq, vec3f(1.0), cs * 0.5 * (0.35 + 0.65 * exp(-depth * 2.5)));
    // Bubbles rising from the floor to the surface.
    for (var k = 0; k < 10; k++) {
      let fk = f32(k);
      let speed = 0.06 + 0.07 * hash1(fk + 3.1);
      let bx = (0.08 + 0.84 * hash1(fk)) * params.aspect + 0.015 * sin(t * 1.3 + fk * 2.0);
      let by = fract(t * speed + hash1(fk + 7.7)) * max(front - 0.03, 0.0);
      let r = 0.006 + 0.009 * hash1(fk + 11.3);
      let d = length(vec2f(x - bx, h - by));
      let ring = smoothstep(r, r - 0.003, d) * (0.35 + 0.65 * smoothstep(r - 0.004, r, d));
      let fade = smoothstep(0.0, 0.08, by) * smoothstep(front, front - 0.05, by);
      liq = mix(liq, vec3f(1.0), ring * fade * 0.55);
    }
    // Meniscus: a bright line riding the surface.
    let lip = exp(-pow((front - h) * 180.0, 2.0));
    liq = mix(liq, vec3f(1.0), lip * 0.45);
    col = mix(col, liq, frontMask);
  }

  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 Fx = { set: (values: { params: Record<string, unknown> }) => void };
type LiquidProgressCanvasProps = { level: number; liquid: string; background: string; speed: number };

export function LiquidProgressCanvas({ level, liquid, background, speed }: LiquidProgressCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const live = useRef({ level, liquid, background, speed });
  live.current = { level, liquid, background, speed };
  const [ready, setReady] = useState(false);

  const uniforms = (v: typeof live.current) => ({
    level: Math.min(Math.max(v.level, 0), 1),
    liquid: hexToVec3(v.liquid, [0.39, 0.4, 0.95]),
    background: hexToVec3(v.background, [0.93, 0.95, 1]),
  });

  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;
    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, LIQUID_WGSL, {
          label: "liquid-progress",
          set: { params: { time: 4, aspect: aspect(), ...uniforms(live.current) } },
        });
        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: 4 + time.time * live.current.speed } });
              frame.pass(target, fx);
              if (still) stop();
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };

        observer = new IntersectionObserver(([entry]) => (entry?.isIntersecting ? start() : still ? undefined : stop()));
        observer.observe(canvas);
        setReady(true);
      } catch {
        // No adapter, blocked, or lost device: the CSS fill is the look.
      }
    })();

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

  useEffect(() => {
    fxRef.current?.set({ params: uniforms({ level, liquid, background, speed }) });
  }, [level, liquid, background]); // 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"}`}
    />
  );
}
```
