# Add the "Topographic Section" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/topographic-section) to this Pantheon Content Publisher (P1) Next.js project. A content section with key figures over drifting contour lines. Built for land trusts, parks and trails.

## 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/topographic-section-block.tsx`, `components/puck/topographic-section.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 { topographicSectionBlock } from "./components/puck/topographic-section-block";`
4. Register it under `components` as `TopographicSectionBlock: topographicSectionBlock`.
5. Add `"TopographicSectionBlock"` 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/topographic-section-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { TopographicCanvas } from "./topographic-section.client";

/**
 * Topographic Section — an eyebrow, heading, body and key figures over slowly drifting,
 * GPU-drawn contour lines (vgpu / WebGPU). Made for land trusts, parks and trail systems.
 * Content is server-rendered; browsers without WebGPU get a CSS line pattern. Needs
 * `pnpm add vgpu` and the companion topographic-section.client.tsx file.
 * Register: `TopographicSectionBlock: topographicSectionBlock` in puck.config.tsx.
 */

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

type Stat = { value: string; label: string };

export type TopographicSectionProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  stats: Stat[];
  footnote: string;
  lineColor: string;
  backgroundColor: string;
  density: "sparse" | "medium" | "dense";
  speed: "0.5" | "1" | "1.6";
};

const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
const hex = (value: string | undefined, fallback: string) => {
  const v = (value ?? "").trim().replace(/^#/, "");
  if (!HEX.test(v)) return fallback;
  return `#${v.length === 3 ? v.replace(/./g, "$&$&") : v}`.toLowerCase();
};

// WCAG relative luminance, so text color follows the background the editor picks.
const luminance = (h: string) => {
  const [r, g, b] = [1, 3, 5].map((i) => {
    const c = parseInt(h.slice(i, i + 2), 16) / 255;
    return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
  });
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};

const DENSITY: Record<TopographicSectionProps["density"], number> = { sparse: 18, medium: 28, dense: 40 };

export const topographicSectionBlock: ComponentConfig<TopographicSectionProps> = {
  label: "Topographic Section",
  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" },
    stats: {
      type: "array",
      label: "Figures",
      min: 0,
      max: 4,
      arrayFields: {
        value: { type: "text", label: "Value", metadata: { help: "Keep it short, such as 18,400 or 62 mi." } },
        label: { type: "text", label: "Label" },
      },
      defaultItemProps: { value: "0", label: "New figure" },
      getItemSummary: (item) => [item?.value, item?.label].filter(Boolean).join(" · ") || "Figure",
    },
    footnote: { type: "text", label: "Source line", metadata: { help: "Where the figures come from. Leave blank to hide it." } },
    lineColor: { type: "text", label: "Contour color", metadata: { help: "A hex color such as #7c6d4f. Pick something a few shades off the background." } },
    backgroundColor: {
      type: "text",
      label: "Background color",
      metadata: { help: "A hex color such as #f6f2e9. Text switches between dark and light to match it." },
    },
    density: {
      type: "select",
      label: "Contour density",
      options: [
        { label: "Sparse (rolling hills)", value: "sparse" },
        { label: "Medium", value: "medium" },
        { label: "Dense (mountains)", value: "dense" },
      ],
    },
    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: "Land protected forever",
    heading: "Forty years of keeping the ridgeline wild and open to everyone",
    headingLevel: "h2",
    body: "Every acre we protect stays undeveloped in perpetuity through conservation easements and land we own outright. Most of it is open to the public, from creekside picnic meadows to backcountry routes along the Knobs.",
    stats: [
      { value: "18,400", label: "Acres under permanent protection" },
      { value: "62 mi", label: "Of public trail, free to use" },
      { value: "41", label: "Family farms kept in farming" },
      { value: "1,100", label: "Volunteers last year" },
    ],
    footnote: "Sample figures for illustration. Replace with your annual report numbers.",
    lineColor: "#7c6d4f",
    backgroundColor: "#f6f2e9",
    density: "medium",
    speed: "1",
  },
  render: ({ eyebrow, heading, headingLevel, body, stats, footnote, lineColor, backgroundColor, density, speed }) => {
    const H = headingLevel || "h2";
    const bg = hex(backgroundColor, "#f6f2e9");
    const line = hex(lineColor, "#7c6d4f");
    const dark = luminance(bg) < 0.18;
    const items = (stats ?? []).filter((s) => s?.value || s?.label);
    const text = dark
      ? { eyebrow: "text-white/80", heading: "text-white", body: "text-white/85", value: "text-white", label: "text-white/80", note: "text-white/70", rule: "border-white/20" }
      : { eyebrow: "text-neutral-700", heading: "text-neutral-950", body: "text-neutral-800", value: "text-neutral-950", label: "text-neutral-700", note: "text-neutral-600", rule: "border-neutral-950/15" };
    // Fallback: two offset rings of the contour color, a static nod to the live map.
    const fallback = {
      backgroundColor: bg,
      backgroundImage: `repeating-radial-gradient(circle at 18% 30%, transparent 0 22px, ${line}33 22px 23px), repeating-radial-gradient(circle at 85% 80%, transparent 0 28px, ${line}26 28px 29px)`,
    };
    // Scrim in the background color keeps copy legible where contours bunch up.
    const scrim = { backgroundImage: `linear-gradient(to right, ${bg}f2 0%, ${bg}cc 45%, ${bg}66 75%, ${bg}00 100%)` };
    const card = { backgroundColor: `${bg}d9` };
    return (
      <section className="relative isolate overflow-hidden px-4 py-16 sm:px-6 sm:py-20 lg:px-8 lg:py-24" style={fallback}>
        <TopographicCanvas line={line} bg={bg} density={DENSITY[density] ?? DENSITY.medium} speed={Number(speed) || 1} />
        <div aria-hidden="true" className="pointer-events-none absolute inset-0" style={scrim} />
        <div className="relative mx-auto grid max-w-7xl gap-12 lg:grid-cols-12 lg:items-end lg:gap-16">
          <div className="lg:col-span-6">
            {eyebrow ? <p className={`text-sm font-semibold tracking-widest uppercase ${text.eyebrow}`}>{eyebrow}</p> : null}
            {heading ? <H className={`mt-4 text-3xl font-semibold tracking-tight text-balance sm:text-5xl ${text.heading}`}>{heading}</H> : null}
            {body ? <p className={`mt-6 max-w-xl text-lg leading-8 text-pretty ${text.body}`}>{body}</p> : null}
          </div>
          {items.length || footnote ? (
            <div className="lg:col-span-6">
              {items.length ? (
                <dl className="grid grid-cols-1 gap-px overflow-hidden rounded-2xl sm:grid-cols-2">
                  {items.map((s, i) => (
                    <div key={i} className={`flex flex-col-reverse gap-2 border-t p-5 backdrop-blur-sm sm:p-6 ${text.rule}`} style={card}>
                      {s.label ? <dt className={`text-sm leading-6 ${text.label}`}>{s.label}</dt> : null}
                      {s.value ? <dd className={`text-4xl font-semibold tracking-tight tabular-nums ${text.value}`}>{s.value}</dd> : null}
                    </div>
                  ))}
                </dl>
              ) : null}
              {footnote ? <p className={`mt-4 text-xs ${text.note}`}>{footnote}</p> : null}
            </div>
          ) : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/topographic-section.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 Topographic Section: anti-aliased contour lines traced through slowly
 * drifting fbm terrain, with every fifth (index) contour drawn heavier, like a USGS quad
 * (vgpu / WebGPU). Decorative only; the CSS line pattern underneath is the fallback look.
 */

const TOPO_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  density: f32,
  line: vec3f,
  bg: 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 * f * (f * (f * 6.0 - 15.0) + 10.0);
  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 fbm(p0: vec2f) -> f32 {
  var p = p0;
  var amp = 0.5;
  var sum = 0.0;
  for (var i = 0; i < 4; i++) {
    sum += amp * noise(p);
    p = mat2x2f(0.8, -0.6, 0.6, 0.8) * p * 2.03 + vec2f(1.7, 9.2);
    amp *= 0.5;
  }
  return sum;
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let p = vec2f(uv.x * params.aspect, uv.y) * 1.6;
  // Terrain: fbm warped by a second, slower fbm so ridgelines meander rather than blob.
  let warp = vec2f(fbm(p * 0.7 + vec2f(t * 0.012, 3.1)), fbm(p * 0.7 + vec2f(8.3, -t * 0.01)));
  let h = fbm(p + warp * 1.1 + vec2f(t * 0.008, t * 0.005));

  let v = h * params.density;
  // Screen-space distance to the nearest contour, in pixels.
  let fw = max(fwidth(v), 1e-4);
  let f = fract(v);
  let d = min(f, 1.0 - f) / fw;

  let level = floor(v + 0.5);
  let isIndex = abs(level - 5.0 * floor(level / 5.0)) < 0.5;
  let halfWidth = select(0.55, 1.15, isIndex);
  var a = 1.0 - smoothstep(halfWidth - 0.5, halfWidth + 0.6, d);
  a *= select(0.42, 0.8, isIndex);
  // Where lines bunch tighter than a few pixels, fade them instead of letting them moire.
  a *= 1.0 - smoothstep(0.25, 0.5, fw);

  // A whisper of hillshade so the terrain reads as land, not just lines.
  var col = mix(params.bg, params.line, (h - 0.5) * 0.12);
  col = mix(col, params.line, a);
  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 Look = { line: string; bg: string; density: number };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };

const uniforms = (l: Look) => ({
  line: hexToVec3(l.line, [0.55, 0.47, 0.33]),
  bg: hexToVec3(l.bg, [0.96, 0.94, 0.9]),
  density: l.density || 28,
});

export function TopographicCanvas({ line, bg, density, speed }: Look & { speed: number }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const live = useRef({ look: { line, bg, density }, speed });
  live.current = { look: { line, bg, density }, 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, TOPO_WGSL, {
          label: "topographic",
          set: { params: { time: 20, aspect: aspect(), ...uniforms(live.current.look) } },
        });
        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: 20 + 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({ line, bg, density }) });
  }, [line, bg, density]);

  return (
    <canvas
      ref={canvasRef}
      aria-hidden="true"
      className={`absolute inset-0 size-full transition-opacity duration-1000 ${ready ? "opacity-100" : "opacity-0"}`}
    />
  );
}
```
