# Add the "Sparkline Table" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/sparkline-table) to this Pantheon Content Publisher (P1) Next.js project. A compact metrics table with each row's current value, percent change and an inline trend line.

## Steps

1. Create `components/puck/sparkline-table-block.tsx` with the exact file contents below. If `components/puck/` doesn't exist, find the folder where this project keeps its Puck components (look at the imports in `puck.config.tsx`) and put it there.
2. In `puck.config.tsx`, import it: `import { sparklineTableBlock } from "./components/puck/sparkline-table-block";`
3. Register it under `components` as `SparklineTableBlock: sparklineTableBlock`.
4. Add `"SparklineTableBlock"` 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

- Do not add dependencies. The block is self-contained by design: one type-only import from `@puckeditor/core`, Tailwind v4 classes, no client JavaScript.
- 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/sparkline-table-block.tsx`

```tsx
import type { ComponentConfig } from "@puckeditor/core";

/**
 * Sparkline Table — a compact metrics table: each row has its current value, percent change
 * and an inline trend line. Every value is a text field, bindable to a P1 data source.
 * Place inside a Dashboard Grid.
 * Register: `SparklineTableBlock: sparklineTableBlock` in puck.config.tsx.
 */
// spec: status-colors

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

type Row = { name: string; value: string; change: string; trend: string; goodWhen: "up" | "down" };

export type SparklineTableProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  rows: Row[];
  trendLabel: string;
  changeLabel: string;
  footnote: string;
};

/** "1,234.5", "$12k" or "-3.2%" → number; anything unparseable → null. */
function toNumber(raw: string | undefined): number | null {
  if (raw == null) return null;
  const cleaned = String(raw).replace(/[^0-9.\-]/g, "");
  if (cleaned === "" || cleaned === "-" || cleaned === ".") return null;
  const n = Number(cleaned);
  return Number.isFinite(n) ? n : null;
}

/** A comma-separated string (or a bound array) → numbers, skipping blanks. */
function series(raw: unknown): number[] {
  const parts = Array.isArray(raw) ? raw.map((v) => String(v ?? "")) : raw == null ? [] : String(raw).split(",");
  return parts.map((v) => toNumber(v)).filter((v): v is number => v !== null);
}

const W = 64;
const HT = 24;

function sparkPath(values: number[]) {
  const min = Math.min(...values);
  const max = Math.max(...values);
  const span = max - min || 1;
  const step = W / (values.length - 1);
  const pts = values.map((v, i) => [i * step, HT - 3 - ((v - min) / span) * (HT - 6)] as const);
  const line = pts.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)} ${y.toFixed(1)}`).join(" ");
  return { line, area: `${line} L${W} ${HT} L0 ${HT} Z`, last: pts[pts.length - 1] };
}

function Change({ value, goodWhen, label }: { value: number | null; goodWhen: "up" | "down"; label: string }) {
  if (value === null) return <span className="text-neutral-400">—</span>;
  const up = value > 0;
  const flat = value === 0;
  const good = flat ? null : up === (goodWhen !== "down");
  const tone = good === null ? "bg-neutral-100 text-neutral-700" : good ? "bg-emerald-50 text-emerald-800" : "bg-red-50 text-red-800";
  return (
    <span className={`inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 text-xs font-semibold whitespace-nowrap tabular-nums ${tone}`}>
      <svg aria-hidden="true" viewBox="0 0 12 12" fill="currentColor" className={`size-2.5 ${flat ? "hidden" : up ? "" : "rotate-180"}`}>
        <path d="M6 2.5 10 8H2l4-5.5Z" />
      </svg>
      <span className="sr-only">{flat ? "No change" : up ? "Up" : "Down"}</span>
      {up ? "+" : flat ? "" : "−"}
      {Math.abs(value)}%
      <span className="sr-only">
        {good === null ? "" : good ? ", better" : ", worse"}
        {label ? ` ${label}` : ""}
      </span>
    </span>
  );
}

export const sparklineTableBlock: ComponentConfig<SparklineTableProps> = {
  label: "Sparkline Table",
  fields: {
    title: { type: "text", label: "Title" },
    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 or period", metadata: { help: "e.g. Week ending Oct 4, 2026. Leave blank to hide." } },
    rows: {
      type: "array",
      label: "Metrics",
      min: 1,
      max: 12,
      getItemSummary: (item) => (item?.name ? `${item.name}${item.value ? ` · ${item.value}` : ""}` : "Metric"),
      defaultItemProps: { name: "New metric", value: "", change: "", trend: "", goodWhen: "up" },
      arrayFields: {
        name: { type: "text", label: "Metric name" },
        value: { type: "text", label: "Current value", metadata: { help: "Shown as written, e.g. $12,480 or 94%. Or bind it, e.g. {{ site.sessions }}." } },
        change: { type: "text", label: "Change (%)", metadata: { help: "e.g. 8.2 or -3. Leave blank to show a dash." } },
        trend: { type: "text", label: "Trend values", metadata: { help: "Comma-separated, oldest first, e.g. 12, 15, 14, 19. Needs at least two." } },
        goodWhen: {
          type: "radio",
          label: "An increase is",
          options: [
            { label: "Good", value: "up" },
            { label: "Bad", value: "down" },
          ],
        },
      },
    },
    trendLabel: { type: "text", label: "Trend column label", metadata: { help: "e.g. 12 weeks." } },
    changeLabel: { type: "text", label: "Change compared with", metadata: { help: "e.g. vs. prior 4 weeks. Read aloud with each change." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Digital services",
    headingLevel: "h3",
    subtitle: "Week ending Oct 4, 2026",
    rows: [
      { name: "Website sessions", value: "18,240", change: "6.8", trend: "14.1, 14.8, 15.2, 14.6, 15.9, 16.4, 16.1, 17.0, 16.8, 17.5, 17.1, 18.2", goodWhen: "up" },
      { name: "Online applications", value: "1,032", change: "12.1", trend: "702, 740, 768, 755, 801, 822, 860, 845, 902, 921, 954, 1032", goodWhen: "up" },
      { name: "Avg. response time", value: "4.2 hrs", change: "-18.5", trend: "7.1, 6.8, 6.9, 6.2, 5.8, 5.9, 5.4, 5.1, 5.2, 4.8, 4.6, 4.2", goodWhen: "down" },
      { name: "Newsletter open rate", value: "41.6%", change: "-2.3", trend: "44, 43.2, 43.8, 42.9, 43.1, 42.4, 42.8, 41.9, 42.6, 42.1, 41.8, 41.6", goodWhen: "up" },
      { name: "Online gifts", value: "$12,480", change: "3.4", trend: "9.8, 10.4, 10.1, 11.2, 10.9, 11.6, 11.3, 11.9, 12.2, 11.8, 12.1, 12.5", goodWhen: "up" },
    ],
    trendLabel: "12 weeks",
    changeLabel: "vs. prior 4 weeks",
    footnote: "Sample data · Source: web analytics and CRM exports",
  },
  render: ({ title, headingLevel, subtitle, rows, trendLabel, changeLabel, footnote }) => {
    const H = headingLevel || "h3";
    const items = (Array.isArray(rows) ? rows : [])
      .map((r, i) => ({
        key: `r${i}`,
        name: r?.name?.trim() || "",
        value: r?.value?.trim() || "",
        change: toNumber(r?.change),
        trend: series(r?.trend),
        goodWhen: r?.goodWhen === "down" ? ("down" as const) : ("up" as const),
      }))
      .filter((r) => r.name || r.value);

    const header = (
      <div>
        {title ? <H className="text-sm font-semibold text-neutral-950">{title}</H> : null}
        {subtitle ? <p className="mt-0.5 text-sm text-neutral-500">{subtitle}</p> : null}
      </div>
    );
    const foot = footnote ? <p className="mt-auto pt-4 text-xs text-neutral-500">{footnote}</p> : null;
    const card =
      "@container 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";

    if (!items.length) {
      return (
        <div className={card}>
          {header}
          <div className="mt-4 flex flex-1 flex-col items-center justify-center gap-1 rounded-lg border border-dashed border-neutral-200 px-4 py-10 text-center">
            <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="size-6 text-neutral-400">
              <path d="M3 6h18M3 12h18M3 18h18" strokeLinecap="round" />
            </svg>
            <p className="text-sm font-medium text-neutral-900">No data yet</p>
            <p className="text-xs text-neutral-500">Rows appear once metrics are entered or the data source returns them.</p>
          </div>
          {foot}
        </div>
      );
    }

    return (
      <div className={card}>
        {header}
        <div className="-mx-1 mt-4">
          <table className="w-full table-fixed text-left text-sm">
            {title ? <caption className="sr-only">{title}</caption> : null}
            <thead className="text-xs text-neutral-500">
              <tr className="border-b border-neutral-200">
                <th scope="col" className="px-1 pb-2 font-medium">
                  Metric
                </th>
                <th scope="col" className="w-20 px-1 pb-2 font-medium @md:w-28">
                  {trendLabel?.trim() || "Trend"}
                </th>
                <th scope="col" className="w-20 px-1 pb-2 text-right font-medium @md:w-28">
                  Current
                </th>
                <th scope="col" className="hidden w-24 px-1 pb-2 text-right font-medium @md:table-cell">
                  Change
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-100">
              {items.map((r) => {
                const spark = r.trend.length > 1 ? sparkPath(r.trend) : null;
                const chip = <Change value={r.change} goodWhen={r.goodWhen} label={changeLabel?.trim() || ""} />;
                return (
                  <tr key={r.key} className="align-middle">
                    <th scope="row" className="px-1 py-3 font-normal text-pretty text-neutral-700">
                      {r.name || "—"}
                    </th>
                    <td className="px-1 py-3">
                      {spark ? (
                        <svg
                          viewBox={`0 0 ${W} ${HT}`}
                          preserveAspectRatio="none"
                          role="img"
                          aria-label={`${r.name || "Metric"} trend, oldest to newest: ${r.trend.join(", ")}`}
                          className="h-6 w-16 overflow-visible text-indigo-600 @md:h-9 @md:w-24"
                        >
                          <path d={spark.area} className="fill-indigo-600/10" />
                          <path d={spark.line} fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
                          <circle cx={spark.last[0]} cy={spark.last[1]} r="2.25" fill="currentColor" />
                        </svg>
                      ) : (
                        <span className="text-neutral-400">—</span>
                      )}
                    </td>
                    <td className="px-1 py-3 text-right">
                      <span className="block font-semibold whitespace-nowrap text-neutral-950 tabular-nums">{r.value || "—"}</span>
                      <span className="mt-1 block @md:hidden">{chip}</span>
                    </td>
                    <td className="hidden px-1 py-3 text-right @md:table-cell">{chip}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {changeLabel ? <p className="mt-3 text-xs text-neutral-500">Change {changeLabel.trim()}</p> : null}
        {foot}
      </div>
    );
  },
};
```
