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

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/starfield-section) to this Pantheon Content Publisher (P1) Next.js project. Heading, body and key figures over a slow parallax starfield with twinkle and a soft nebula.

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

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

/**
 * Starfield Section — a content section with a heading, body and key figures over a slow
 * parallax starfield and soft nebula (vgpu / WebGPU). Built for observatories, planetariums
 * and science programs. Needs `pnpm add vgpu` and starfield-section.client.tsx.
 * Register: `StarfieldSectionBlock: starfieldSectionBlock` in puck.config.tsx.
 */

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

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

export type StarfieldSectionProps = {
  eyebrow: string;
  heading: string;
  headingLevel: Heading;
  body: string;
  ctaLabel: string;
  ctaHref: string;
  stats: Stat[];
  footnote: string;
  baseColor: string;
  color1: string;
  color2: 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 colorHelp = "A hex color such as #4338ca.";

export const starfieldSectionBlock: ComponentConfig<StarfieldSectionProps> = {
  label: "Starfield 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" },
    ctaLabel: { type: "text", label: "Link text", metadata: { help: "Leave blank to hide the link." } },
    ctaHref: { type: "text", label: "Link" },
    stats: {
      type: "array",
      label: "Figures",
      min: 0,
      max: 4,
      getItemSummary: (item) => [item?.value, item?.label].filter(Boolean).join(" · ") || "Figure",
      defaultItemProps: { value: "120", label: "Clear nights a year" },
      arrayFields: {
        value: { type: "text", label: "Value", metadata: { help: "Keep it short, such as 4.2M or 1,200." } },
        label: { type: "text", label: "Label" },
      },
    },
    footnote: { type: "text", label: "Source note", metadata: { help: "Where the figures come from. Leave blank to hide it." } },
    baseColor: { type: "text", label: "Sky color", metadata: { help: `${colorHelp} Keep it very dark: the text is white.` } },
    color1: { type: "text", label: "Nebula color (outer)", metadata: { help: colorHelp } },
    color2: { type: "text", label: "Nebula color (core)", metadata: { help: colorHelp } },
    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: "Mitchell Observatory & Planetarium",
    heading: "A public window on the universe, open since 1931",
    headingLevel: "h2",
    body: "Look through a century-old 16-inch refractor on clear Friday nights, catch a full-dome show in the planetarium, or bring a class for hands-on astronomy aligned to state science standards.",
    ctaLabel: "See this month's sky programs",
    ctaHref: "/programs",
    stats: [
      { value: "41,000", label: "Visitors last year" },
      { value: "380", label: "School field trips" },
      { value: "16-inch", label: "Historic refractor" },
      { value: "Free", label: "Public viewing nights" },
    ],
    footnote: "Source: Observatory 2025 annual report (sample figures).",
    baseColor: "#04050f",
    color1: "#4338ca",
    color2: "#c0508c",
    speed: "1",
  },
  render: ({ eyebrow, heading, headingLevel, body, ctaLabel, ctaHref, stats, footnote, baseColor, color1, color2, speed }) => {
    const H = headingLevel || "h2";
    const base = hex(baseColor, "#04050f");
    const c1 = hex(color1, "#4338ca");
    const c2 = hex(color2, "#c0508c");
    const figures = (stats ?? []).filter((s) => s?.value || s?.label);
    // The CSS fallback approximates the shader: tiled pin-prick stars under a soft nebula.
    const fallback = {
      backgroundColor: base,
      backgroundImage: [
        "radial-gradient(1.5px 1.5px at 23px 41px, rgba(255,255,255,0.9), transparent)",
        "radial-gradient(1px 1px at 87px 13px, rgba(255,255,255,0.7), transparent)",
        "radial-gradient(1px 1px at 141px 97px, rgba(255,255,255,0.6), transparent)",
        "radial-gradient(1px 1px at 61px 143px, rgba(220,230,255,0.7), transparent)",
        `radial-gradient(45% 55% at 85% 20%, ${c2}55, transparent 70%)`,
        `radial-gradient(65% 75% at 80% 25%, ${c1}40, transparent 75%)`,
      ].join(", "),
      backgroundSize: "170px 170px, 170px 170px, 170px 170px, 170px 170px, 100% 100%, 100% 100%",
    };
    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}>
        <StarfieldCanvas colors={{ base, c1, c2 }} speed={Number(speed) || 1} />
        <div aria-hidden="true" className="pointer-events-none absolute inset-0 bg-black/30 lg:bg-transparent lg:bg-gradient-to-r lg:from-black/50 lg:to-transparent" />
        <div className="relative mx-auto max-w-7xl">
          <div className="max-w-2xl">
            {eyebrow ? <p className="text-sm font-semibold tracking-[0.25em] text-white/80 uppercase">{eyebrow}</p> : null}
            {heading ? <H className="mt-4 text-3xl font-semibold tracking-tight text-balance text-white sm:text-5xl">{heading}</H> : null}
            {body ? <p className="mt-6 text-lg leading-8 text-pretty text-white/80">{body}</p> : null}
            {ctaLabel ? (
              <a
                href={ctaHref || "#"}
                className="group mt-8 inline-flex min-h-11 items-center gap-2 rounded-full bg-white/10 px-5 py-2.5 text-base font-semibold text-white ring-1 ring-white/25 backdrop-blur-sm transition ring-inset hover:bg-white/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
              >
                {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>
          {figures.length ? (
            <dl className="mt-16 grid grid-cols-1 gap-x-8 gap-y-10 border-t border-white/15 pt-10 sm:grid-cols-2 lg:mt-24 lg:grid-cols-4">
              {figures.map((s, i) => (
                <div key={i} className="flex flex-col-reverse gap-2">
                  {s.label ? <dt className="text-sm leading-6 text-white/75">{s.label}</dt> : null}
                  {s.value ? <dd className="text-4xl font-semibold tracking-tight text-white tabular-nums sm:text-5xl">{s.value}</dd> : null}
                </div>
              ))}
            </dl>
          ) : null}
          {footnote ? <p className="mt-10 text-xs text-white/65">{footnote}</p> : null}
        </div>
      </section>
    );
  },
};
```

## File: `components/puck/starfield-section.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 Starfield Section: four layers of stars drifting at different speeds for
 * parallax, a gentle twinkle, and a soft two-color nebula (vgpu / WebGPU). Decorative only.
 * The section's content is server-rendered and the CSS fallback underneath is the final
 * look wherever WebGPU isn't available.
 */

const STARFIELD_WGSL = /* wgsl */ `
struct Params {
  time: f32,
  aspect: f32,
  base: vec3f,
  c1: vec3f,
  c2: 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 hash2(p: vec2f) -> vec2f {
  return vec2f(hash(p), hash(p + vec2f(19.19, 7.31)));
}

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 fbm(p0: vec2f) -> f32 {
  var p = p0;
  var amp = 0.5;
  var sum = 0.0;
  for (var i = 0; i < 5; i++) {
    sum += amp * noise(p);
    p = p * 2.03 + vec2f(3.1, 1.7);
    amp *= 0.5;
  }
  return sum;
}

// One layer of stars: at most one per grid cell, sized in pixels so they stay crisp at any DPR.
fn stars(p: vec2f, scale: f32, px: f32, density: f32, seed: f32, t: f32) -> vec4f {
  let q = p * scale;
  let id = floor(q) + seed;
  let f = fract(q) - 0.5;
  let h = hash(id);
  let offs = (hash2(id * 1.37) - 0.5) * 0.6;
  let d = length(f - offs) / (px * scale);
  let big = pow(hash(id + 4.7), 8.0);
  let r = 0.55 + 1.6 * big;
  let core = 1.0 - smoothstep(r - 0.5, r + 0.6, d);
  let glow = exp(-d * d / (r * r * 6.0)) * (0.1 + 0.7 * big) * smoothstep(0.5, 0.15, length(f - offs));
  let tw = 0.6 + 0.4 * sin(t * (0.5 + 1.8 * hash(id + 9.1)) + h * 61.0);
  let lit = step(1.0 - density, h) * (core + glow) * tw * (0.55 + 0.45 * hash(id + 2.3));
  let hue = hash(id + 6.6);
  let tint = mix(mix(vec3f(0.72, 0.82, 1.0), vec3f(1.0), smoothstep(0.2, 0.6, hue)), vec3f(1.0, 0.86, 0.7), smoothstep(0.8, 1.0, hue));
  return vec4f(tint, lit);
}

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let t = params.time;
  let p = vec2f(uv.x * params.aspect, uv.y);
  let px = fwidth(p.y);

  // Nebula: warped fbm pooled toward the upper right, leaving the copy side darker.
  let w = vec2f(fbm(p * 1.3 + vec2f(t * 0.006, 0.0)), fbm(p * 1.3 + vec2f(5.2, -t * 0.005)));
  let cloud = fbm(p * 1.8 + w * 1.6 + vec2f(-t * 0.004, 0.0));
  let lane = fbm(p * 4.5 + w * 2.0 + 11.0);
  let toward = 1.0 - clamp(length((uv - vec2f(0.82, 0.22)) * vec2f(1.0, 1.25)) * 1.25, 0.0, 1.0);
  let mass = smoothstep(0.2, 0.9, cloud * (0.35 + 1.0 * toward)) * (1.0 - 0.5 * smoothstep(0.45, 0.75, lane));
  let neb = mix(params.c1, params.c2, smoothstep(0.15, 0.85, mass + (w.x - 0.5) * 0.6));

  var col = params.base;
  col = mix(col, neb, mass * 0.5);
  col += mix(neb, vec3f(1.0), 0.3) * pow(mass, 3.0) * 0.2;

  // Parallax: nearer layers are sparser, brighter and drift faster.
  let drift = vec2f(t * 0.012, t * 0.002);
  let l0 = stars(p + drift * 0.25, 80.0, px, 0.16, 0.0, t);
  let l1 = stars(p + drift * 0.5, 44.0, px, 0.14, 17.0, t);
  let l2 = stars(p + drift * 1.0, 22.0, px, 0.14, 41.0, t);
  let l3 = stars(p + drift * 1.8, 10.0, px, 0.18, 73.0, t);
  col += l0.rgb * l0.a * 0.4 + l1.rgb * l1.a * 0.6 + l2.rgb * l2.a * 0.85 + l3.rgb * l3.a;

  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; c1: string; c2: string };
type Fx = { set: (values: { params: Record<string, unknown> }) => void };

const colorUniforms = (c: Colors) => ({
  base: hexToVec3(c.base, [0.02, 0.02, 0.06]),
  c1: hexToVec3(c.c1, [0.3, 0.28, 0.75]),
  c2: hexToVec3(c.c2, [0.75, 0.3, 0.55]),
});

export function StarfieldCanvas({ colors, speed }: { colors: Colors; speed: number }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fxRef = useRef<Fx | null>(null);
  const redrawRef = useRef<(() => void) | null>(null);
  const live = useRef({ colors, speed });
  live.current = { colors, 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 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] });
        const aspect = () => (target.size[1] ? target.size[0] / target.size[1] : 1);
        const fx = effect(gpu, STARFIELD_WGSL, {
          label: "starfield",
          set: { params: { time: 20, aspect: aspect(), ...colorUniforms(live.current.colors) } },
        });
        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) => {
              fx.set({ params: { time: 20 + time.time * live.current.speed } });
              f.pass(target, fx);
            },
            { fps: 60 },
          );
        };
        const stop = () => {
          loop?.stop();
          loop = undefined;
        };

        if (still) {
          // Reduced motion: one settled frame, redrawn only when the editor changes a color.
          draw();
        } else {
          let onScreen = false;
          const sync = () => (onScreen && !document.hidden ? start() : 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 fallback is the look.
      }
    })();

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

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