# Add the "Data Wave Bars" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/data-wave-bars) to this Pantheon Content Publisher (P1) Next.js project. Showcase chart of up to 12 bindable values as glowing, breathing bars, with every figure listed as 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/data-wave-bars-block.tsx`, `components/puck/data-wave-bars.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 { dataWaveBarsBlock } from "./components/puck/data-wave-bars-block";`
4. Register it under `components` as `DataWaveBarsBlock: dataWaveBarsBlock`.
5. Add `"DataWaveBarsBlock"` 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/data-wave-bars-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { DataWaveCanvas } from "./data-wave-bars.client";

/**
 * Data Wave Bars — a showcase bar chart for up to 12 values: glowing, rounded bars that breathe in
 * a slow wave, with the peak lit (vgpu / WebGPU). Values and labels are comma-separated text fields,
 * so they bind to P1 data sources; every figure is server-rendered as a list, and non-WebGPU
 * browsers get matching CSS bars. Needs `pnpm add vgpu` and data-wave-bars.client.tsx.
 * Register: `DataWaveBarsBlock: dataWaveBarsBlock` in puck.config.tsx.
 */

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

export type DataWaveBarsProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  values: string;
  labels: string;
  unit: string;
  totalLabel: string;
  footnote: string;
  baseColor: string;
  barColor: string;
  accentColor: string;
  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 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 splitList = (value: string | undefined) =>
  String(value ?? "")
    .split(/[,;\n]/)
    .map((s) => s.trim());

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

export const dataWaveBarsBlock: ComponentConfig<DataWaveBarsProps> = {
  label: "Data Wave Bars",
  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" },
    values: {
      type: "text",
      label: "Values",
      metadata: { help: "Up to 12 numbers separated by commas, like 4210, 4830, 6900. Don't use thousands separators. Bind a data source with {{ }}." },
    },
    labels: { type: "text", label: "Labels", metadata: { help: "One short label per value, separated by commas, like Jan, Feb, Mar." } },
    unit: { type: "text", label: "Unit", metadata: { help: "Added after each value, like % or visits. Leave blank for plain numbers." } },
    totalLabel: { type: "text", label: "Total label", metadata: { help: "Label for the summed total, like Visits this year. Leave blank to hide the total." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Source or note under the chart. Leave blank to hide it." } },
    baseColor: { type: "text", label: "Panel color", metadata: { help: `${colorHelp} Keep it dark: the labels are white.` } },
    barColor: { type: "text", label: "Bar color", metadata: { help: colorHelp } },
    accentColor: { type: "text", label: "Peak color", metadata: { help: `${colorHelp} Lights the highest bar.` } },
    speed: {
      type: "radio",
      label: "Motion",
      options: [
        { label: "Slow", value: "0.5" },
        { label: "Gentle", value: "1" },
        { label: "Lively", value: "1.6" },
      ],
      metadata: { help: "Visitors who ask their device for reduced motion see the bars at rest, at their true heights." },
    },
  },
  defaultProps: {
    eyebrow: "Riverside Greenway · Trail counters",
    heading: "Summer more than tripled weekday trail use",
    headingLevel: "h2",
    body: "Automated counters at four trailheads log every walker and cyclist. July's peak followed the opening of the Mill Creek connector and the free bike-share pilot.",
    values: "4210, 4830, 6920, 9140, 12380, 14820, 16240, 15710, 12930, 10340, 6110, 4590",
    labels: "Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec",
    unit: "",
    totalLabel: "Trail visits in 2025",
    footnote: "Sample data · Parks department trail counters, 2025",
    baseColor: "#0b1026",
    barColor: "#6366f1",
    accentColor: "#c7d2fe",
    speed: "1",
  },
  render: ({ id, eyebrow, heading, headingLevel, body, values, labels, unit, totalLabel, footnote, baseColor, barColor, accentColor, speed }) => {
    const H = headingLevel || "h2";
    const base = hex(baseColor, "#0b1026");
    const bar = hex(barColor, "#6366f1");
    const accent = hex(accentColor, "#c7d2fe");
    const suffix = (unit ?? "").trim();
    const nums = splitList(values)
      .filter((s, i, all) => s !== "" || i < all.length - 1)
      .slice(0, 12)
      .map(toNumber);
    const names = splitList(labels);
    const rows = nums.map((n, i) => ({ label: names[i] || `#${i + 1}`, value: n }));
    const known = rows.filter((r): r is { label: string; value: number } => r.value !== null);
    const max = known.reduce((m, r) => Math.max(m, r.value), 0);
    const peak = max > 0 ? rows.findIndex((r) => r.value === max) : -1;
    const levels = rows.map((r) => (max > 0 && r.value !== null ? Math.max(r.value, 0) / max : 0));
    const total = known.reduce((s, r) => s + r.value, 0);
    const fmt = (n: number | null) => (n === null ? "—" : `${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}${suffix ? (suffix.length > 1 ? ` ${suffix}` : suffix) : ""}`);
    const cols = { gridTemplateColumns: `repeat(${Math.max(rows.length, 1)}, minmax(0, 1fr))` };
    const listId = `${id}-wave-data`;

    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 max-w-6xl">
          <div className="grid grid-cols-1 gap-8 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-end">
            <div className="max-w-2xl">
              {eyebrow ? <p className="text-sm font-semibold tracking-widest text-indigo-700 uppercase">{eyebrow}</p> : null}
              {heading ? <H 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}
            </div>
            {rows.length ? (
              <dl className="flex flex-wrap gap-x-10 gap-y-4 lg:justify-end lg:text-right">
                {totalLabel && known.length ? (
                  <div>
                    <dt className="text-sm text-neutral-600">{totalLabel}</dt>
                    <dd className="mt-1 text-3xl font-semibold tracking-tight text-neutral-900 tabular-nums">{fmt(total)}</dd>
                  </div>
                ) : null}
                {peak >= 0 ? (
                  <div>
                    <dt className="text-sm text-neutral-600">Peak · {rows[peak].label}</dt>
                    <dd className="mt-1 text-3xl font-semibold tracking-tight text-neutral-900 tabular-nums">{fmt(max)}</dd>
                  </div>
                ) : null}
              </dl>
            ) : null}
          </div>

          {rows.length ? (
            <figure className="mt-10 overflow-hidden rounded-3xl p-4 shadow-xl ring-1 ring-neutral-950/10 sm:p-8" style={{ backgroundColor: base }}>
              <div aria-hidden="true" className="relative isolate h-56 sm:h-72 lg:h-80">
                <div className="absolute inset-0 grid items-end" style={cols}>
                  {levels.map((level, i) => (
                    <div key={i} className="mx-auto w-1/2 rounded-t-full" style={{ height: `${Math.max(level * 90, 2)}%`, backgroundColor: i === peak ? accent : bar }} />
                  ))}
                </div>
                <DataWaveCanvas levels={levels} peak={peak} colors={{ base, bar, accent }} speed={Number(speed) || 1} />
              </div>
              <ol id={listId} aria-label={heading || "Chart data"} className="mt-3 grid border-t border-white/15 pt-3 text-center" style={cols}>
                {rows.map((r, i) => (
                  <li key={i} className="min-w-0">
                    <span className={`block truncate text-xs font-medium sm:text-sm ${i === peak ? "text-white" : "text-white/80"}`}>{r.label}</span>
                    <span className="sr-only sm:not-sr-only sm:mt-0.5 sm:block sm:truncate sm:text-xs sm:text-white/70 sm:tabular-nums lg:text-sm">
                      <span className="sr-only">: </span>
                      {fmt(r.value)}
                      {i === peak ? <span className="sr-only"> (peak)</span> : null}
                    </span>
                  </li>
                ))}
              </ol>
              {footnote ? <figcaption className="mt-5 text-xs text-white/70">{footnote}</figcaption> : null}
            </figure>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/data-wave-bars.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 Data Wave Bars: up to 12 glowing, rounded bars that breathe in a slow wave, with a
 * sheen that rolls across them and the peak bar lit in the highlight color (vgpu / WebGPU).
 * The data itself is server-rendered as a list; the CSS bars underneath are the fallback.
 */

const DATA_WAVE_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  count: f32,
  peak: f32,
  css: vec2f,
  v0: vec4f,
  v1: vec4f,
  v2: vec4f,
  base: vec3f,
  bar: vec3f,
  accent: vec3f,
}
@group(0) @binding(0) var<uniform> params: Params;

const HEADROOM = 0.9;

fn value(i: i32) -> f32 {
  let c = i % 4;
  var v = params.v0;
  if (i >= 8) { v = params.v2; } else if (i >= 4) { v = params.v1; }
  return clamp(v[c], 0.0, 1.0);
}

// Signed distance (CSS px) to bar i, rounded on top. q is relative to the slot center at the baseline.
fn barSdf(q: vec2f, halfW: f32, h: f32) -> f32 {
  let r = halfW;
  let c = vec2f(0.0, (h - r) * 0.5);
  let b = vec2f(halfW, (h + r) * 0.5);
  let d = abs(q - c) - b + r;
  return length(max(d, vec2f(0.0))) + min(max(d.x, d.y), 0.0) - r;
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let n = max(params.count, 1.0);
  let slotW = params.css.x / n;
  let halfW = slotW * 0.25;
  let y = (1.0 - uv.y) * params.css.y;
  let slot = floor(uv.x * n);

  // Faint guide lines at quarter steps of the tallest bar.
  var col = params.base;
  for (var k = 1; k <= 4; k++) {
    let gy = params.css.y * HEADROOM * f32(k) / 4.0;
    let dash = step(0.5, fract(uv.x * params.css.x / 8.0));
    col += vec3f(1.0) * smoothstep(0.9, 0.0, abs(y - gy)) * 0.05 * dash;
  }

  // Glow and body from this slot and its neighbors, since glow spills across gaps.
  var glow = vec3f(0.0);
  var body = vec4f(0.0);
  let sheenX = fract(t * 0.06) * 1.6 - 0.3;
  for (var j = -1; j <= 1; j++) {
    let i = slot + f32(j);
    if (i < 0.0 || i >= n) { continue; }
    let ii = i32(i);
    let breathe = 1.0 + 0.035 * sin(t * 1.1 - i * 0.55);
    let h = max(value(ii) * HEADROOM * params.css.y * breathe, halfW * 2.0);
    let q = vec2f(uv.x * params.css.x - (i + 0.5) * slotW, y);
    let sd = barSdf(q, halfW, h);
    let isPeak = 1.0 - step(0.5, abs(i - params.peak));
    let tint = mix(params.bar, params.accent, isPeak);
    let sheen = exp(-pow(((i + 0.5) / n - sheenX) * 5.0, 2.0));
    glow += tint * exp(-max(sd, 0.0) / (10.0 + 8.0 * isPeak)) * (0.22 + 0.2 * isPeak + 0.18 * sheen) * smoothstep(-2.0, 1.0, sd);
    let inside = smoothstep(0.75, -0.75, sd);
    if (inside > body.a) {
      let fill = clamp(y / h, 0.0, 1.0);
      var c = tint * mix(0.45, 1.05, fill);
      // Bright rim just inside the edge, and the sheen rolling across.
      c = mix(c, mix(tint, vec3f(1.0), 0.55), smoothstep(-3.0, -0.5, sd) * 0.6);
      c += vec3f(1.0) * sheen * 0.12;
      body = vec4f(c, inside);
    }
  }

  col += glow;
  col = mix(col, body.rgb, body.a);
  return vec4f(col, 1.0);
}
`;

type Vec3 = [number, number, number];
type Vec4 = [number, 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; bar: string; accent: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };
type DataWaveCanvasProps = {
  /** Bar heights already normalized to 0..1 (at most 12). */
  levels: number[];
  /** Index of the bar to light in the highlight color, or -1. */
  peak: number;
  colors: Colors;
  speed: number;
};

export function DataWaveCanvas({ levels, peak, colors, speed }: DataWaveCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const live = useRef({ levels, peak, colors, speed });
  live.current = { levels, peak, colors, speed };
  const [ready, setReady] = useState(false);
  const key = levels.join(",");

  const uniforms = (v: typeof live.current) => {
    const vals = Array.from({ length: 12 }, (_, i) => Math.min(Math.max(v.levels[i] ?? 0, 0), 1));
    return {
      count: Math.max(v.levels.length, 1),
      peak: v.peak,
      v0: vals.slice(0, 4) as Vec4,
      v1: vals.slice(4, 8) as Vec4,
      v2: vals.slice(8, 12) as Vec4,
      base: hexToVec3(v.colors.base, [0.04, 0.05, 0.12]),
      bar: hexToVec3(v.colors.bar, [0.39, 0.4, 0.95]),
      accent: hexToVec3(v.colors.accent, [0.65, 0.71, 0.99]),
    };
  };

  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] });
        // Bars are laid out in CSS pixels so corner radii and glow stay crisp at any size.
        const sized = () => ({ css: [canvas.clientWidth || target.size[0], canvas.clientHeight || target.size[1]] });
        const fx = effect(gpu, DATA_WAVE_WGSL, {
          label: "data-wave-bars",
          set: { params: { time: 0, ...sized(), ...uniforms(live.current) } },
        });
        fxRef.current = fx;
        const time = clock(gpu);

        const start = () => {
          if (loop || disposed || !gpu) return;
          loop = frameLoop(
            gpu,
            (frame) => {
              // Reduced motion freezes the wave at rest, where each bar sits at its true value.
              fx.set({ params: { time: still ? 0 : time.time * live.current.speed } });
              frame.pass(target, fx);
              if (still) stop();
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };
        redrawRef.current = still ? start : null;
        target.onResize(() => {
          fx.set({ params: sized() });
          if (still) start();
        });

        let onScreen = false;
        const sync = () => (onScreen && !document.hidden ? start() : still ? undefined : 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 bars are the look.
      }
    })();

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

  // Live-update data and colors from the Puck sidebar (or a refreshed data source) without re-initializing.
  useEffect(() => {
    fxRef.current?.set({ params: uniforms({ levels, peak, colors, speed }) });
    redrawRef.current?.();
  }, [key, peak, colors.base, colors.bar, colors.accent]); // 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"}`}
    />
  );
}
```
