# Add the "Constellation Network" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/constellation-network) to this Pantheon Content Publisher (P1) Next.js project. Partner or community section beside a live network of drifting nodes that link up and brighten under the pointer.

## 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/constellation-network-block.tsx`, `components/puck/constellation-network.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 { constellationNetworkBlock } from "./components/puck/constellation-network-block";`
4. Register it under `components` as `ConstellationNetworkBlock: constellationNetworkBlock`.
5. Add `"ConstellationNetworkBlock"` 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/constellation-network-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { ConstellationCanvas } from "./constellation-network.client";

/**
 * Constellation Network — a partner or community section beside a live network of drifting
 * nodes that link up as they pass, brightening under the pointer (vgpu / WebGPU). Copy and the
 * partner count are server-rendered; non-WebGPU browsers get a CSS star field.
 * Needs `pnpm add vgpu` and constellation-network.client.tsx. Register: `ConstellationNetworkBlock: constellationNetworkBlock`.
 */

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

export type ConstellationNetworkProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  statValue: string;
  statLabel: string;
  statNote: string;
  ctaLabel: string;
  ctaHref: string;
  baseColor: string;
  nodeColor: string;
  accentColor: string;
  density: "4.5" | "6" | "8";
  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 #a5b4fc.";

export const constellationNetworkBlock: ComponentConfig<ConstellationNetworkProps> = {
  label: "Constellation Network",
  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" },
    statValue: { type: "text", label: "Stat number", metadata: { help: "Shown large over the network, like 140+. Bind a data source with {{ }} if you have one." } },
    statLabel: { type: "text", label: "Stat label", metadata: { help: "What the number counts, like partner organizations." } },
    statNote: { type: "text", label: "Stat note", metadata: { help: "Small print under the stat, like a source or date. Leave blank to hide it." } },
    ctaLabel: { type: "text", label: "Link text", metadata: { help: "Leave blank to hide it." } },
    ctaHref: { type: "text", label: "Link" },
    baseColor: { type: "text", label: "Night color", metadata: { help: `${colorHelp} The panel behind the network. Keep it dark: the stat is white.` } },
    nodeColor: { type: "text", label: "Node color", metadata: { help: colorHelp } },
    accentColor: { type: "text", label: "Highlight color", metadata: { help: `${colorHelp} Nodes near the pointer take on this color.` } },
    density: {
      type: "radio",
      label: "Density",
      options: [
        { label: "Sparse", value: "4.5" },
        { label: "Balanced", value: "6" },
        { label: "Dense", value: "8" },
      ],
    },
    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: "Community Partners",
    heading: "No one in this county does this work alone",
    headingLevel: "h2",
    body: "Food pantries, school districts, clinics, faith congregations and neighborhood associations share referrals, volunteers and data through one network, so a family who reaches any of us reaches all of us.",
    statValue: "140+",
    statLabel: "partner organizations",
    statNote: "Sample figure · Partner roster, 2026",
    ctaLabel: "Become a partner",
    ctaHref: "/partners/join",
    baseColor: "#0b1026",
    nodeColor: "#e0e7ff",
    accentColor: "#818cf8",
    density: "6",
    speed: "1",
  },
  render: ({ eyebrow, heading, headingLevel, body, statValue, statLabel, statNote, ctaLabel, ctaHref, baseColor, nodeColor, accentColor, density, speed }) => {
    const H = headingLevel || "h2";
    const base = hex(baseColor, "#0b1026");
    const node = hex(nodeColor, "#e0e7ff");
    const accent = hex(accentColor, "#818cf8");
    // A sparse CSS star field: the look wherever WebGPU isn't available.
    const fallback = {
      backgroundColor: base,
      backgroundImage: `radial-gradient(circle at 85% 10%, ${accent}33, transparent 55%), radial-gradient(${node}cc 1px, transparent 1.6px), radial-gradient(${node}66 1px, transparent 1.4px)`,
      backgroundSize: "auto, 46px 46px, 71px 71px",
      backgroundPosition: "0 0, 0 0, 23px 31px",
    };
    const hasStat = Boolean(statValue || statLabel);

    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 grid-cols-1 items-center gap-12 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)] lg:gap-16">
          <div className="max-w-xl">
            {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-6 text-lg leading-8 text-pretty text-neutral-600">{body}</p> : null}
            {ctaLabel ? (
              <a
                href={ctaHref || "#"}
                className="group mt-8 inline-flex min-h-11 items-center gap-1.5 rounded-lg text-base font-semibold text-indigo-700 hover:text-indigo-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
              >
                {ctaLabel}
                <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-5 transition group-hover:translate-x-0.5">
                  <path fillRule="evenodd" d="M3 10a.75.75 0 0 1 .75-.75h10.64l-3.22-3.22a.75.75 0 1 1 1.06-1.06l4.5 4.5a.75.75 0 0 1 0 1.06l-4.5 4.5a.75.75 0 1 1-1.06-1.06l3.22-3.22H3.75A.75.75 0 0 1 3 10Z" clipRule="evenodd" />
                </svg>
              </a>
            ) : null}
          </div>

          <div className="relative isolate aspect-4/5 overflow-hidden rounded-3xl shadow-xl ring-1 ring-neutral-950/10 sm:aspect-4/3" style={fallback}>
            <ConstellationCanvas colors={{ base, node, accent }} density={Number(density) || 6} speed={Number(speed) || 1} />
            {hasStat ? (
              <div className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-neutral-950/80 via-neutral-950/50 to-transparent px-6 pt-24 pb-6 sm:px-8 sm:pb-8">
                <p className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-white">
                  {statValue ? <span className="text-5xl font-semibold tracking-tight tabular-nums sm:text-6xl">{statValue}</span> : null}
                  {statLabel ? <span className="text-lg font-medium text-white/90">{statLabel}</span> : null}
                </p>
                {statNote ? <p className="mt-2 text-sm text-white/75">{statNote}</p> : null}
              </div>
            ) : null}
          </div>
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/constellation-network.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 Constellation Network: drifting nodes joined by lines that fade in as neighbors
 * come close, brightening around the pointer (vgpu / WebGPU). Decorative only; the section's
 * copy and partner count are server-rendered and the CSS star field underneath is the fallback.
 */

const CONSTELLATION_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  scale: f32,
  presence: f32,
  pointer: vec2f,
  base: vec3f,
  node: vec3f,
  accent: vec3f,
}
@group(0) @binding(0) var<uniform> params: Params;

fn hash2(p: vec2f) -> vec2f {
  let q = vec2f(dot(p, vec2f(127.1, 311.7)), dot(p, vec2f(269.5, 183.3)));
  return fract(sin(q) * 43758.5453);
}

// One node per grid cell, wandering inside a 0.3-cell radius. Keeping the wander under 0.3
// and the link length under 1.1 cells guarantees every visible segment has both endpoints
// inside the 3x3 neighborhood, so lines never clip at cell borders.
fn nodeAt(cell: vec2f, t: f32) -> vec2f {
  let h = hash2(cell);
  let k = hash2(cell + 17.0);
  let wobble = vec2f(sin(t * (0.25 + 0.35 * k.x) + h.x * 6.2832), cos(t * (0.2 + 0.3 * k.y) + h.y * 6.2832));
  return cell + 0.5 + 0.3 * wobble;
}

fn segDist(p: vec2f, a: vec2f, b: vec2f) -> f32 {
  let pa = p - a;
  let ba = b - a;
  let h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
  return length(pa - ba * h);
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let p = vec2f(uv.x * params.aspect, uv.y) * params.scale;
  let ptr = vec2f(params.pointer.x * params.aspect, params.pointer.y) * params.scale;
  let g = floor(p);
  let px = params.scale / 520.0;

  var pts: array<vec2f, 9>;
  for (var j = 0; j < 9; j++) {
    pts[j] = nodeAt(g + vec2f(f32(j % 3) - 1.0, f32(j / 3) - 1.0), t);
  }

  // Background: base color with a faint lift toward the upper right.
  var col = params.base * (1.0 + 0.35 * smoothstep(1.2, 0.0, length(uv - vec2f(0.85, 0.1))));

  var lines = 0.0;
  var hot = 0.0;
  for (var a = 0; a < 9; a++) {
    for (var b = a + 1; b < 9; b++) {
      let len = length(pts[a] - pts[b]);
      let reach = smoothstep(1.1, 0.72, len);
      if (reach <= 0.0) { continue; }
      let d = segDist(p, pts[a], pts[b]);
      let w = smoothstep(px * 2.2, 0.0, d) * reach;
      let mid = (pts[a] + pts[b]) * 0.5;
      let near = exp(-dot(mid - ptr, mid - ptr) * 0.9) * params.presence;
      lines = max(lines, w * (0.32 + 0.68 * near));
      hot = max(hot, w * near);
    }
  }
  col = mix(col, mix(params.node, params.accent, hot), lines * 0.75);

  for (var j = 0; j < 9; j++) {
    let q = pts[j];
    let d = length(p - q);
    let h = hash2(q * 3.1 + 5.0);
    let twinkle = 0.65 + 0.35 * sin(t * (0.8 + h.x) + h.y * 6.2832);
    let near = exp(-dot(q - ptr, q - ptr) * 0.7) * params.presence;
    let r = (0.035 + 0.03 * h.x) * (1.0 + 0.6 * near);
    let core = smoothstep(r, r * 0.4, d);
    let halo = exp(-d * d / (r * r * 7.0)) * (0.25 + 0.75 * near);
    let c = mix(params.node, params.accent, near);
    col = mix(col, c, clamp(core * twinkle + halo * 0.55, 0.0, 1.0));
  }

  // Soft cursor glow so the pointer reads even between nodes.
  let pg = exp(-dot(p - ptr, p - ptr) * 0.35) * params.presence;
  col += params.accent * pg * 0.08;

  col += (fract(sin(dot(uv, vec2f(12.9898, 78.233))) * 43758.5453) - 0.5) * 0.018;
  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; node: string; accent: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };
type ConstellationCanvasProps = { colors: Colors; density: number; speed: number };

export function ConstellationCanvas({ colors, density, speed }: ConstellationCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const live = useRef({ colors, density, speed });
  live.current = { colors, density, speed };
  const [ready, setReady] = useState(false);

  const uniforms = (c: Colors, d: number) => ({
    scale: d,
    base: hexToVec3(c.base, [0.04, 0.05, 0.12]),
    node: hexToVec3(c.node, [0.78, 0.82, 1]),
    accent: hexToVec3(c.accent, [0.65, 0.71, 0.99]),
  });

  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;
    let removeVisibility: (() => void) | undefined;
    const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    // Pointer target from events, eased toward on every frame.
    const aim = { x: 0.62, y: 0.4, on: 0 };
    const cur = { ...aim };
    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, CONSTELLATION_WGSL, {
          label: "constellation-network",
          set: {
            params: {
              time: 6,
              aspect: aspect(),
              presence: 0,
              pointer: [cur.x, cur.y],
              ...uniforms(live.current.colors, live.current.density),
            },
          },
        });
        fxRef.current = fx;
        const time = clock(gpu);

        const start = () => {
          if (loop || disposed || !gpu) return;
          loop = frameLoop(
            gpu,
            (frame) => {
              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.6;
              fx.set({ params: { time: 6 + time.time * live.current.speed, pointer: [cur.x, cur.y], presence: cur.on } });
              frame.pass(target, fx);
              // Reduced motion: one settled frame, then stop.
              if (still) stop();
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };
        redrawRef.current = still ? start : null;
        target.onResize(() => {
          fx.set({ params: { aspect: aspect() } });
          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);
        if (!still) {
          host.addEventListener("pointermove", onMove, { passive: true });
          host.addEventListener("pointerleave", onLeave, { passive: true });
        }
        removeVisibility = () => document.removeEventListener("visibilitychange", sync);
        setReady(true);
      } catch {
        // No adapter, blocked, or lost device: the CSS fallback is the look.
      }
    })();

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

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