# Add the "Density Map" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/density-map) to this Pantheon Content Publisher (P1) Next.js project. A stylized where-we-work heat map: weighted places glow with contour bands, mirrored as an accessible list.

## 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/density-map-block.tsx`, `components/puck/density-map.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 { densityMapBlock } from "./components/puck/density-map-block";`
4. Register it under `components` as `DensityMapBlock: densityMapBlock`.
5. Add `"DensityMapBlock"` 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/density-map-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { DensityMapCanvas } from "./density-map.client";

/**
 * Density Map — a stylized "where we work" plane (not a geographic map): editor-placed points
 * glow as heat fields with contour bands, and a pointer lens sharpens nearby hotspots (vgpu /
 * WebGPU). Every point is also a server-rendered list item and marker. Needs `pnpm add vgpu`
 * and density-map.client.tsx. Register: `DensityMapBlock: densityMapBlock` in puck.config.tsx.
 */

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

type Place = { label: string; x: number; y: number; weight: string };

export type DensityMapProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  intro: string;
  unit: string;
  points: Place[];
  source: string;
  baseColor: string;
  coolColor: string;
  hotColor: string;
};

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 pct = (v: unknown) => Math.min(100, Math.max(0, Number(v) || 0));
const toNumber = (v: unknown) => {
  const n = parseFloat(String(v ?? "").replace(/[^0-9.-]/g, ""));
  return Number.isFinite(n) && n > 0 ? n : 0;
};

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

export const densityMapBlock: ComponentConfig<DensityMapProps> = {
  label: "Density Map",
  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." },
    },
    intro: { type: "textarea", label: "Intro" },
    unit: { type: "text", label: "What the numbers count", metadata: { help: "Shown after each figure, e.g. \"homes repaired\"." } },
    points: {
      type: "array",
      label: "Places",
      min: 1,
      max: 8,
      getItemSummary: (item) => item.label || "Place",
      defaultItemProps: { label: "New neighborhood", x: 50, y: 50, weight: "50" },
      arrayFields: {
        label: { type: "text", label: "Name" },
        x: { type: "number", label: "Across (0–100)", min: 0, max: 100, metadata: { help: "0 is the left edge, 100 the right." } },
        y: { type: "number", label: "Down (0–100)", min: 0, max: 100, metadata: { help: "0 is the top edge, 100 the bottom." } },
        weight: { type: "text", label: "Figure", metadata: { help: "A number. Bigger figures glow larger and hotter. Data-source tokens work here." } },
      },
    },
    source: { type: "text", label: "Source line", metadata: { help: "Where the figures come from. Leave blank to hide it." } },
    baseColor: { type: "text", label: "Map color", metadata: { help: `${colorHelp} Keep it dark: the labels are white.` } },
    coolColor: { type: "text", label: "Glow color", metadata: { help: `${colorHelp} Used for lighter activity and contour lines.` } },
    hotColor: { type: "text", label: "Hotspot color", metadata: { help: "A hex color such as #f59e0b. The densest places warm to this." } },
  },
  defaultProps: {
    eyebrow: "Neighborhood Repair Program · FY2025",
    heading: "Where the repair crews went this year",
    headingLevel: "h2",
    intro: "The City of Larkspur fixed roofs, furnaces and porch steps in seven neighborhoods. The brighter the glow, the more homes we reached. Hover the map to look closer.",
    unit: "homes repaired",
    points: [
      { label: "Eastfield", x: 24, y: 30, weight: "212" },
      { label: "Westgate", x: 12, y: 72, weight: "134" },
      { label: "Old Mill", x: 62, y: 22, weight: "148" },
      { label: "Riverside", x: 78, y: 60, weight: "96" },
      { label: "Fairmount", x: 88, y: 30, weight: "77" },
      { label: "Hollins Park", x: 40, y: 64, weight: "61" },
      { label: "Cedar Heights", x: 56, y: 84, weight: "40" },
    ],
    source: "Sample data for illustration. Positions are schematic, not to scale.",
    baseColor: "#0b1020",
    coolColor: "#818cf8",
    hotColor: "#f59e0b",
  },
  render: ({ eyebrow, heading, headingLevel, intro, unit, points, source, baseColor, coolColor, hotColor }) => {
    const H = headingLevel || "h2";
    const base = hex(baseColor, "#0b1020");
    const cool = hex(coolColor, "#818cf8");
    const hot = hex(hotColor, "#f59e0b");
    const places = (points ?? [])
      .slice(0, 8)
      .filter((p) => p?.label)
      .map((p) => ({ label: p.label, x: pct(p.x), y: pct(p.y), value: toNumber(p.weight) }));
    const max = Math.max(1, ...places.map((p) => p.value));
    const shaderPoints = places.map((p) => ({ x: p.x / 100, y: p.y / 100, weight: p.value / max }));
    // The CSS fallback places one soft glow per point; it's all non-WebGPU browsers see.
    const fallback = {
      backgroundColor: base,
      backgroundImage:
        places
          .map((p) => {
            const w = p.value / max;
            return `radial-gradient(circle at ${p.x}% ${p.y}%, ${w > 0.75 ? hot : cool}${w > 0.4 ? "aa" : "66"} 0, transparent ${8 + 14 * Math.sqrt(w)}%)`;
          })
          .join(", ") || "none",
    };
    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-7xl gap-10 lg:grid-cols-3 lg:gap-12">
          <div className="lg:col-span-1">
            {eyebrow ? <p className="text-xs font-semibold tracking-widest text-indigo-700 uppercase">{eyebrow}</p> : null}
            {heading ? <H className="mt-3 text-3xl font-semibold tracking-tight text-balance text-neutral-900 sm:text-4xl">{heading}</H> : null}
            {intro ? <p className="mt-5 text-base leading-7 text-pretty text-neutral-600">{intro}</p> : null}
            {places.length ? (
              <ol role="list" className="mt-8 divide-y divide-neutral-200 border-y border-neutral-200">
                {places.map((p, i) => (
                  <li key={i} className="flex items-center gap-3 py-3">
                    <span aria-hidden="true" className="flex size-6 shrink-0 items-center justify-center rounded-full bg-neutral-900 font-mono text-xs text-white tabular-nums">
                      {i + 1}
                    </span>
                    <span className="min-w-0 flex-1">
                      <span className="block text-sm font-semibold text-neutral-900">{p.label}</span>
                      <span aria-hidden="true" className="mt-1.5 block h-1 rounded-full bg-neutral-100">
                        <span className="block h-1 rounded-full bg-indigo-500" style={{ width: `${(p.value / max) * 100}%` }} />
                      </span>
                    </span>
                    <span className="text-right text-sm text-neutral-600 tabular-nums">
                      <span className="font-semibold text-neutral-900">{p.value ? p.value.toLocaleString("en-US") : "—"}</span>
                      {unit ? <span className="sr-only"> {unit}</span> : null}
                    </span>
                  </li>
                ))}
              </ol>
            ) : null}
            {unit && places.length ? <p className="mt-3 text-xs text-neutral-500">Figures are {unit}.</p> : null}
            {source ? <p className="mt-1 text-xs text-neutral-500">{source}</p> : null}
          </div>

          <figure className="lg:col-span-2">
            <div className="relative isolate aspect-4/3 overflow-hidden rounded-2xl ring-1 ring-neutral-950/10 sm:aspect-16/10" style={fallback}>
              <DensityMapCanvas colors={{ base, cool, hot }} points={shaderPoints} />
              <div aria-hidden="true" className="pointer-events-none absolute inset-0">
                {places.map((p, i) => (
                  <span
                    key={i}
                    className={`absolute flex -translate-y-1/2 items-center gap-2 ${p.x > 70 ? "-translate-x-full flex-row-reverse" : ""}`}
                    style={{ left: `${p.x}%`, top: `${p.y}%` }}
                  >
                    <span className={`flex size-5 items-center justify-center rounded-full bg-white font-mono text-xs font-semibold text-neutral-900 tabular-nums shadow-sm ${p.x > 70 ? "translate-x-1/2" : "-translate-x-1/2"}`}>
                      {i + 1}
                    </span>
                    <span className="hidden rounded-md bg-neutral-950/75 px-2 py-1 text-xs font-medium whitespace-nowrap text-white backdrop-blur-sm md:inline">
                      {p.label}
                      <span className="ml-1.5 text-white/70 tabular-nums">{p.value ? p.value.toLocaleString("en-US") : "—"}</span>
                    </span>
                  </span>
                ))}
              </div>
            </div>
            <figcaption className="sr-only">Schematic heat map of the places listed alongside; brighter areas mean higher figures.</figcaption>
          </figure>
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/density-map.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 Density Map: up to eight weighted points drawn as glowing gaussian heat
 * fields with soft contour bands, and a pointer lens that sharpens nearby hotspots (vgpu /
 * WebGPU). The same points are server-rendered as a list and markers, so the canvas never
 * carries meaning on its own.
 */

const DENSITY_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  presence: f32,
  count: f32,
  aspect: f32,
  pointer: vec2f,
  base: vec3f,
  cool: vec3f,
  hot: vec3f,
  p0: vec4f,
  p1: vec4f,
  p2: vec4f,
  p3: vec4f,
  p4: vec4f,
  p5: vec4f,
  p6: vec4f,
  p7: vec4f,
}
@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,
  );
}

fn gridLine(v: f32, cells: f32) -> f32 {
  let g = v * cells;
  let e = abs(fract(g + 0.5) - 0.5);
  return 1.0 - smoothstep(0.0, fwidth(g) * 1.0, e);
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let a = params.aspect;
  let s = vec2f(a, 1.0);
  var pts = array<vec4f, 8>(params.p0, params.p1, params.p2, params.p3, params.p4, params.p5, params.p6, params.p7);
  let n = i32(clamp(params.count, 0.0, 8.0));

  let lens = exp(-dot((uv - params.pointer) * s, (uv - params.pointer) * s) / 0.03) * params.presence;

  // Organic edges: nudge the sample point with slow noise so contours read as terrain, not circles.
  let warp = vec2f(noise(uv * 6.0 + vec2f(t * 0.05, 0.0)), noise(uv * 6.0 + vec2f(5.2, -t * 0.04))) - 0.5;
  let q = uv + warp * 0.035;

  var field = 0.0;
  for (var i = 0; i < 8; i++) {
    if (i >= n) { break; }
    let pt = pts[i];
    let w = clamp(pt.z, 0.0, 1.0);
    let toP = (pt.xy - params.pointer) * s;
    let near = exp(-dot(toP, toP) / 0.05) * params.presence;
    let sigma = (0.055 + 0.095 * sqrt(w)) * (1.0 - 0.18 * near);
    let d = (q - pt.xy) * s;
    let breathe = 1.0 + 0.05 * sin(t * 0.7 + f32(i) * 1.9);
    field += w * (1.0 + 0.55 * near) * breathe * exp(-dot(d, d) / (2.0 * sigma * sigma));
  }
  let v = clamp(field, 0.0, 1.6);

  // Base plane: a quiet survey grid.
  var col = params.base;
  let grid = max(gridLine(uv.x * a, 14.0), gridLine(uv.y, 14.0));
  col = mix(col, params.cool, grid * 0.09);

  // Heat ramp: base -> cool -> hot -> warm white at the densest cores.
  let heat = mix(mix(params.base, params.cool, smoothstep(0.02, 0.6, v)), params.hot, smoothstep(0.55, 1.05, v));
  col = mix(col, heat, smoothstep(0.0, 0.25, v) * 0.9);
  col = mix(col, mix(params.hot, vec3f(1.0, 0.97, 0.9), 0.65), smoothstep(1.0, 1.5, v));

  // Contour bands, crisper and brighter under the lens.
  let bands = v * 10.0;
  let e = abs(fract(bands + 0.5) - 0.5);
  let width = fwidth(bands) * mix(1.6, 0.9, lens);
  let contour = (1.0 - smoothstep(0.0, width, e)) * smoothstep(0.03, 0.14, v);
  col = mix(col, mix(params.cool, vec3f(1.0), 0.35 + 0.4 * lens), contour * (0.32 + 0.5 * lens));

  // A soft lens rim so visitors can see where they're looking.
  col += params.cool * lens * 0.06;
  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 = { base: string; cool: string; hot: string };
/** x and y are 0–1 from the top-left; weight is 0–1, already normalised to the largest point. */
export type DensityPoint = { x: number; y: number; weight: number };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };

const colorUniforms = (c: Colors) => ({
  base: hexToVec3(c.base, [0.04, 0.06, 0.12]),
  cool: hexToVec3(c.cool, [0.4, 0.45, 0.95]),
  hot: hexToVec3(c.hot, [0.98, 0.75, 0.35]),
});

function pointUniforms(points: DensityPoint[]) {
  const out: Record<string, number[]> = {};
  for (let i = 0; i < 8; i++) {
    const p = points[i];
    out[`p${i}`] = p ? [p.x, p.y, p.weight, 0] : [0, 0, 0, 0];
  }
  return { ...out, count: Math.min(points.length, 8) };
}

export function DensityMapCanvas({ colors, points }: { colors: Colors; points: DensityPoint[] }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const live = useRef({ colors, points });
  live.current = { colors, points };
  const [ready, setReady] = useState(false);
  const pointsKey = JSON.stringify(points);

  useEffect(() => {
    const canvas = canvasRef.current;
    const host = canvas?.parentElement;
    if (!canvas || !host || !("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;
    const touch = window.matchMedia("(hover: none)").matches;

    const aim = { x: 0.5, y: 0.5, on: 0 };
    const cur = { x: 0.5, y: 0.5, on: 0 };
    const onMove = (e: PointerEvent) => {
      if (e.pointerType === "touch") return;
      const r = canvas.getBoundingClientRect();
      if (!r.width || !r.height) return;
      aim.x = (e.clientX - r.left) / r.width;
      aim.y = (e.clientY - r.top) / r.height;
      aim.on = 1;
    };
    const onLeave = () => {
      aim.on = 0;
    };

    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, DENSITY_WGSL, {
          label: "density-map",
          set: {
            params: {
              time: 2,
              presence: 0,
              aspect: aspect(),
              pointer: [0.5, 0.5],
              ...colorUniforms(live.current.colors),
              ...pointUniforms(live.current.points),
            },
          },
        });
        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) => {
              const t = time.time;
              if (touch) {
                aim.x = 0.5 + 0.3 * Math.sin(t * 0.16);
                aim.y = 0.5 + 0.25 * Math.sin(t * 0.23 + 2.1);
                aim.on = 0.8;
              }
              const k = 1 - Math.exp(-Math.min(time.deltaTime, 0.1) * 6);
              cur.x += (aim.x - cur.x) * k;
              cur.y += (aim.y - cur.y) * k;
              cur.on += (aim.on - cur.on) * k * 0.5;
              fx.set({ params: { time: 2 + t, pointer: [cur.x, cur.y], presence: cur.on } });
              f.pass(target, fx);
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };

        if (still) {
          draw();
        } else {
          host.addEventListener("pointermove", onMove, { passive: true });
          host.addEventListener("pointerleave", onLeave, { passive: true });
          observer = new IntersectionObserver(([entry]) => (entry?.isIntersecting ? start() : stop()));
          observer.observe(canvas);
        }
        setReady(true);
      } catch {
        // No adapter, blocked, or lost device: the CSS fallback is the look.
      }
    })();

    return () => {
      disposed = true;
      observer?.disconnect();
      host.removeEventListener("pointermove", onMove);
      host.removeEventListener("pointerleave", onLeave);
      loop?.stop();
      fxRef.current = null;
      redrawRef.current = null;
      gpu?.dispose();
    };
  }, []);

  // Live-update colors and points from the Puck sidebar without re-initializing.
  useEffect(() => {
    fxRef.current?.set({ params: { ...colorUniforms(colors), ...pointUniforms(points) } });
    redrawRef.current?.();
  }, [colors.base, colors.cool, colors.hot, pointsKey]); // 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"}`}
    />
  );
}
```
