# Add the "Live Metric" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/live-metric) to this Pantheon Content Publisher (P1) Next.js project. One number that refreshes in the visitor's browser from a public JSON endpoint, with a server-rendered fallback.

## Steps

1. Create these files with the exact contents below, in the same folder: `components/puck/live-metric-block.tsx`, `components/puck/live-metric.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`).
2. In `puck.config.tsx`, import it: `import { liveMetricBlock } from "./components/puck/live-metric-block";`
3. Register it under `components` as `LiveMetricBlock: liveMetricBlock`.
4. Add `"LiveMetricBlock"` to the best-fitting entry in `categories` (this block's library category is "Dashboards"). Create a category only if none fits.
5. Dashboard widgets are designed to sit inside the Dashboard Grid block (https://p1-blocks.prolificdigital.io/r/dashboard-grid.md). If the project doesn't have it yet, offer to add it too.
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-`.
- Data values are text fields on purpose: P1 data-source tokens (`{{ source.field }}`) only bind in text fields. Don't convert them to number fields.
- Don't change prop names in `defaultProps`. Content editors' saved pages depend on them.

## File: `components/puck/live-metric-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";
import { LiveMetricValue } from "./live-metric.client";

/**
 * Live Metric — one number that refreshes in the visitor's browser without a page reload,
 * polled from a public JSON endpoint. The initial value is server-rendered, so the card is
 * useful with JavaScript off. Needs the companion live-metric.client.tsx file.
 * Register: `LiveMetricBlock: liveMetricBlock` in puck.config.tsx.
 */

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

export type LiveMetricProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  value: string;
  prefix: string;
  suffix: string;
  dataUrl: string;
  valuePath: string;
  refresh: "15" | "30" | "60" | "300";
  footnote: string;
};

export const liveMetricBlock: ComponentConfig<LiveMetricProps> = {
  label: "Live Metric",
  fields: {
    title: { type: "text", label: "Metric name" },
    headingLevel: {
      type: "select",
      label: "Heading level",
      options: [
        { label: "H2", value: "h2" },
        { label: "H3 (recommended inside a dashboard)", value: "h3" },
        { label: "H4", value: "h4" },
        { label: "Not a heading", value: "p" },
      ],
      metadata: { help: "Sets the page outline for screen readers and search. The look doesn't change." },
    },
    subtitle: { type: "text", label: "Subtitle", metadata: { help: "e.g. Right now on the website. Leave blank to hide." } },
    value: {
      type: "text",
      label: "Initial value",
      metadata: { help: "Shown before the first refresh and to visitors without JavaScript. Type it or bind it, e.g. {{ live.visitors_now }}." },
    },
    prefix: { type: "text", label: "Prefix", metadata: { help: "e.g. $. Leave blank for none." } },
    suffix: { type: "text", label: "Suffix", metadata: { help: "e.g. people or %. Leave blank for none." } },
    dataUrl: {
      type: "text",
      label: "Live data URL",
      metadata: {
        help: "A JSON endpoint the visitor's browser calls directly. It must allow CORS from this site's domain and must not need an API key or any secret, since anyone can see it. Leave blank for a static card.",
      },
    },
    valuePath: {
      type: "text",
      label: "Value path",
      metadata: { help: "Where the number sits in the JSON, using dots, e.g. data.visitors_now or items.0.count." },
    },
    refresh: {
      type: "select",
      label: "Refresh every",
      options: [
        { label: "15 seconds", value: "15" },
        { label: "30 seconds", value: "30" },
        { label: "1 minute", value: "60" },
        { label: "5 minutes", value: "300" },
      ],
      metadata: { help: "Refreshing pauses while the card is off screen or the tab is hidden, and slows down if the endpoint fails." },
    },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the number comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Visitors on the site now",
    headingLevel: "h3",
    subtitle: "During tonight's Giving Day livestream",
    value: "128",
    prefix: "",
    suffix: "",
    dataUrl: "",
    valuePath: "data.visitors_now",
    refresh: "30",
    footnote: "Sample data · Source: site analytics, real-time view",
  },
  render: ({ title, headingLevel, subtitle, value, prefix, suffix, dataUrl, valuePath, refresh, footnote }) => {
    const H = headingLevel || "h3";
    return (
      <div className="flex h-full flex-col rounded-xl bg-white p-5 shadow-xs ring-1 ring-neutral-950/5 sm:p-6 not-in-data-[dashboard-grid]:mx-4 not-in-data-[dashboard-grid]:my-8 sm:not-in-data-[dashboard-grid]:mx-auto sm:not-in-data-[dashboard-grid]:max-w-2xl">
        {title ? <H className="text-sm font-medium text-neutral-600">{title}</H> : null}
        {subtitle ? <p className="mt-0.5 text-xs text-neutral-500">{subtitle}</p> : null}
        <div className="mt-2">
          <LiveMetricValue
            initial={value ?? ""}
            url={dataUrl ?? ""}
            path={valuePath ?? ""}
            intervalSeconds={Number(refresh) || 60}
            prefix={prefix ?? ""}
            suffix={suffix ?? ""}
            label={title ?? ""}
          />
        </div>
        {footnote ? <p className="mt-auto pt-4 text-xs text-neutral-500">{footnote}</p> : null}
      </div>
    );
  },
};
```

## File: `components/puck/live-metric.client.tsx`

```tsx
"use client";

import { useEffect, useRef, useState } from "react";

/**
 * Browser half of the Live Metric: polls a public JSON endpoint while the card is on screen
 * and the tab is visible, backs off on errors, and never throws. The server-rendered initial
 * value is what visitors without JavaScript (or before the first poll) see.
 */
// spec: status-colors

type Status = "idle" | "live" | "paused" | "offline";

export type LiveMetricValueProps = {
  initial: string;
  url: string;
  path: string;
  intervalSeconds: number;
  prefix: string;
  suffix: string;
  label: string;
};

const MAX_DELAY = 5 * 60_000;
const TIMEOUT = 10_000;
const ANNOUNCE_EVERY = 60_000;

/** Reads "data.visitors_now" or "items.0.count" without touching the prototype chain. */
function readPath(source: unknown, path: string): unknown {
  let node: unknown = source;
  for (const key of path.split(".").map((k) => k.trim()).filter(Boolean)) {
    if (node === null || typeof node !== "object" || !Object.prototype.hasOwnProperty.call(node, key)) return undefined;
    node = (node as Record<string, unknown>)[key];
  }
  return node;
}

function display(value: unknown): string | null {
  if (typeof value === "number" && Number.isFinite(value)) return value.toLocaleString("en-US", { maximumFractionDigits: 2 });
  if (typeof value === "string" && value.trim() && value.length < 40) return value.trim();
  return null;
}

/** Only absolute http(s) URLs or same-origin paths, and never an unbound {{ token }}. */
function usableUrl(url: string) {
  const u = (url ?? "").trim();
  if (!u || u.includes("{{")) return null;
  return /^https?:\/\//i.test(u) || u.startsWith("/") ? u : null;
}

function ago(ms: number) {
  const s = Math.max(0, Math.round(ms / 1000));
  if (s < 5) return "just now";
  if (s < 60) return `${s}s ago`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ago`;
  return `${Math.floor(m / 60)}h ago`;
}

export function LiveMetricValue({ initial, url, path, intervalSeconds, prefix, suffix, label }: LiveMetricValueProps) {
  const start = initial?.trim() ? initial.trim() : "—";
  const [value, setValue] = useState(start);
  const [status, setStatus] = useState<Status>("idle");
  const [updatedAt, setUpdatedAt] = useState<number | null>(null);
  const [now, setNow] = useState(0);
  const [announcement, setAnnouncement] = useState("");
  const rootRef = useRef<HTMLDivElement>(null);
  const valueRef = useRef(start);
  const lastAnnounce = useRef(0);
  const words = useRef({ label, prefix, suffix });
  words.current = { label, prefix, suffix };

  // An editor retyping the initial value in Puck should see it, until live data arrives.
  useEffect(() => {
    if (status === "idle") {
      setValue(start);
      valueRef.current = start;
    }
  }, [start]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    const endpoint = usableUrl(url);
    const el = rootRef.current;
    if (!endpoint || !el) return;

    const base = Math.max(15, intervalSeconds || 60) * 1000;
    let delay = base;
    let onScreen = true;
    let timer: ReturnType<typeof setTimeout> | undefined;
    let ticker: ReturnType<typeof setInterval> | undefined;
    let controller: AbortController | undefined;
    let lastAttempt = 0;
    let failed = false;
    let disposed = false;

    const active = () => onScreen && document.visibilityState === "visible";

    const schedule = (ms: number) => {
      clearTimeout(timer);
      timer = setTimeout(poll, ms);
    };

    async function poll() {
      timer = undefined;
      if (disposed) return;
      if (!active()) {
        setStatus("paused");
        return;
      }
      lastAttempt = Date.now();
      controller?.abort();
      const ctl = new AbortController();
      controller = ctl;
      const timeout = setTimeout(() => ctl.abort(), TIMEOUT);
      try {
        const res = await fetch(endpoint!, { signal: ctl.signal, cache: "no-store", credentials: "omit", headers: { Accept: "application/json" } });
        if (!res.ok) throw new Error(String(res.status));
        const next = display(readPath(await res.json(), path || ""));
        if (next === null) throw new Error("No usable value at that path");
        if (disposed) return;
        failed = false;
        delay = base;
        const at = Date.now();
        setUpdatedAt(at);
        setNow(at);
        setStatus("live");
        if (next !== valueRef.current) {
          valueRef.current = next;
          setValue(next);
          // Screen readers hear changes at most once a minute, not every poll.
          if (at - lastAnnounce.current >= ANNOUNCE_EVERY) {
            lastAnnounce.current = at;
            const w = words.current;
            setAnnouncement(`${w.label ? `${w.label}: ` : ""}${w.prefix ?? ""}${next}${w.suffix ? ` ${w.suffix}` : ""}`);
          }
        }
      } catch {
        // Aborted because the card left the screen: not an error.
        if (disposed || (ctl.signal.aborted && !active())) return;
        failed = true;
        delay = Math.min(delay * 2, MAX_DELAY);
        setStatus("offline");
      } finally {
        clearTimeout(timeout);
      }
      if (!disposed && active()) schedule(delay);
    }

    const tick = () => setNow(Date.now());

    const sync = () => {
      if (disposed) return;
      clearInterval(ticker);
      if (!active()) {
        clearTimeout(timer);
        timer = undefined;
        controller?.abort();
        setStatus((s) => (s === "idle" ? s : "paused"));
        return;
      }
      tick();
      ticker = setInterval(tick, 1000);
      if (failed) setStatus("offline");
      else setStatus((s) => (s === "paused" ? "live" : s));
      if (!timer) {
        const due = lastAttempt + delay - Date.now();
        if (due <= 0) void poll();
        else schedule(due);
      }
    };

    let observer: IntersectionObserver | undefined;
    try {
      observer = new IntersectionObserver(([entry]) => {
        onScreen = Boolean(entry?.isIntersecting);
        sync();
      });
      observer.observe(el);
    } catch {
      // No IntersectionObserver: poll whenever the tab is visible.
      sync();
    }
    document.addEventListener("visibilitychange", sync);

    return () => {
      disposed = true;
      observer?.disconnect();
      document.removeEventListener("visibilitychange", sync);
      clearTimeout(timer);
      clearInterval(ticker);
      controller?.abort();
    };
  }, [url, path, intervalSeconds]);

  const shown = value || "—";
  const since = updatedAt ? ago(now - updatedAt) : null;

  return (
    <div ref={rootRef}>
      <p className="text-3xl font-semibold tracking-tight text-neutral-950 tabular-nums sm:text-4xl">
        {shown !== "—" && prefix ? <span className="mr-0.5 text-neutral-500">{prefix}</span> : null}
        {shown}
        {shown !== "—" && suffix ? <span className="ml-1 text-xl text-neutral-500 sm:text-2xl">{suffix}</span> : null}
      </p>

      {status !== "idle" ? (
        <p className="mt-3 flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-neutral-600">
          {status === "live" ? (
            <span className="inline-flex items-center gap-2 font-medium text-emerald-800">
              <span aria-hidden="true" className="relative flex size-2">
                <span className="absolute inline-flex size-full animate-ping rounded-full bg-emerald-400 opacity-60 motion-reduce:animate-none" />
                <span className="relative inline-flex size-2 rounded-full bg-emerald-500" />
              </span>
              Live
            </span>
          ) : status === "paused" ? (
            <span className="inline-flex items-center gap-2 font-medium text-neutral-700">
              <span aria-hidden="true" className="size-2 rounded-full ring-2 ring-neutral-400 ring-inset" />
              Paused
            </span>
          ) : (
            <span className="inline-flex items-center gap-1.5 font-medium text-amber-800">
              <svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-4 shrink-0">
                <path
                  fillRule="evenodd"
                  d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495ZM10 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 10 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"
                  clipRule="evenodd"
                />
              </svg>
              Offline — showing last value
            </span>
          )}
          {since ? (
            <span className="text-neutral-500 tabular-nums">
              <span aria-hidden="true">· </span>Updated {since}
            </span>
          ) : null}
        </p>
      ) : null}

      <p aria-live="polite" aria-atomic="true" className="sr-only">
        {announcement}
      </p>
    </div>
  );
}
```
