# Add the "Scatter Plot" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/scatter-plot) to this Pantheon Content Publisher (P1) Next.js project. Plot items on two measures with optional dot sizes, a least-squares trend line and labelled outliers.

## Steps

1. Create `components/puck/scatter-plot-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 { scatterPlotBlock } from "./components/puck/scatter-plot-block";`
3. Register it under `components` as `ScatterPlotBlock: scatterPlotBlock`.
4. Add `"ScatterPlotBlock"` 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/scatter-plot-block.tsx`

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

/**
 * Scatter Plot — compare two measures across many items (sites, schools, programs), with an
 * optional least-squares trend line and automatic labels on the points furthest from it.
 * Every value is a text field, bindable to a P1 data source. Place inside a Dashboard Grid.
 * Register: `ScatterPlotBlock: scatterPlotBlock` in puck.config.tsx.
 */

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

type Point = { label: string; x: string; y: string; size: string };

export type ScatterPlotProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  points: Point[];
  xTitle: string;
  yTitle: string;
  xSuffix: string;
  ySuffix: string;
  sizeTitle: string;
  showTrend: "yes" | "no";
  labelOutliers: "yes" | "no";
  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;
}

/** Round, human-friendly axis ticks (1, 2, 2.5, 5 × 10ⁿ) covering lo..hi. */
function niceTicks(lo: number, hi: number, count = 4): number[] {
  if (lo === hi) {
    if (lo === 0) hi = 1;
    else if (lo > 0) lo = 0;
    else hi = 0;
  }
  const rough = (hi - lo) / count;
  const pow = Math.pow(10, Math.floor(Math.log10(rough)));
  const f = rough / pow;
  const step = (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * pow;
  const start = Math.floor(lo / step) * step;
  const end = Math.ceil(hi / step) * step;
  const ticks: number[] = [];
  for (let v = start; v <= end + step / 2 && ticks.length < 12; v += step) ticks.push(Number(v.toPrecision(12)));
  return ticks;
}

const compact = new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 });
const full = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });

function format(n: number | null, suffix = "", short = false) {
  if (n === null) return "—";
  const unit = suffix && /^[a-z]/i.test(suffix) ? ` ${suffix}` : suffix;
  return `${n < 0 ? "−" : ""}${(short ? compact : full).format(Math.abs(n))}${unit}`;
}

/** Least-squares fit y = a + b·x, with R² and each point's residual. */
function fit(pts: { x: number; y: number }[]) {
  const n = pts.length;
  const mx = pts.reduce((s, p) => s + p.x, 0) / n;
  const my = pts.reduce((s, p) => s + p.y, 0) / n;
  const sxx = pts.reduce((s, p) => s + (p.x - mx) ** 2, 0);
  const sxy = pts.reduce((s, p) => s + (p.x - mx) * (p.y - my), 0);
  const syy = pts.reduce((s, p) => s + (p.y - my) ** 2, 0);
  if (sxx === 0) return null;
  const b = sxy / sxx;
  const a = my - b * mx;
  const r2 = syy === 0 ? 1 : (sxy * sxy) / (sxx * syy);
  return { a, b, r2 };
}

const PLOT_HEIGHT = "h-56 @md:h-72";

export const scatterPlotBlock: ComponentConfig<ScatterPlotProps> = {
  label: "Scatter Plot",
  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. Partner schools, 2025–26. Leave blank to hide." } },
    points: {
      type: "array",
      label: "Points",
      min: 1,
      max: 60,
      getItemSummary: (item) => item?.label || "Point",
      defaultItemProps: { label: "New point", x: "", y: "", size: "" },
      arrayFields: {
        label: { type: "text", label: "Label" },
        x: { type: "text", label: "X value", metadata: { help: "A number. Or bind a list with {{ source.items }} and {{ item.hours }}." } },
        y: { type: "text", label: "Y value" },
        size: { type: "text", label: "Size (optional)", metadata: { help: "A third number, e.g. enrollment, shown as dot size. Leave blank for equal dots." } },
      },
    },
    xTitle: { type: "text", label: "X-axis title", metadata: { help: "What the horizontal position means, e.g. Tutoring hours per student." } },
    yTitle: { type: "text", label: "Y-axis title", metadata: { help: "What the vertical position means." } },
    xSuffix: { type: "text", label: "X unit", metadata: { help: "e.g. hrs or %. Leave blank for none." } },
    ySuffix: { type: "text", label: "Y unit", metadata: { help: "e.g. mo or %. Leave blank for none." } },
    sizeTitle: { type: "text", label: "Size means", metadata: { help: "e.g. Students enrolled. Shown in the key when sizes are set." } },
    showTrend: {
      type: "radio",
      label: "Trend line",
      options: [
        { label: "Show", value: "yes" },
        { label: "Hide", value: "no" },
      ],
      metadata: { help: "A straight least-squares fit through the points." },
    },
    labelOutliers: {
      type: "radio",
      label: "Label outliers",
      options: [
        { label: "Yes", value: "yes" },
        { label: "No", value: "no" },
      ],
      metadata: { help: "Names up to three points that sit furthest from the trend. Needs at least five points." },
    },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Tutoring hours and reading growth",
    headingLevel: "h3",
    subtitle: "Partner schools, 2025–26 school year",
    points: [
      { label: "Adams Elementary", x: "8", y: "4.1", size: "212" },
      { label: "Bellview Elementary", x: "12", y: "5.2", size: "340" },
      { label: "Lincoln Elementary", x: "13", y: "11.6", size: "188" },
      { label: "Carver Academy", x: "16", y: "6.4", size: "265" },
      { label: "Douglass Elementary", x: "19", y: "7.1", size: "410" },
      { label: "Eastside Elementary", x: "22", y: "7.9", size: "296" },
      { label: "Grant Middle", x: "24", y: "8.0", size: "520" },
      { label: "Highland Elementary", x: "27", y: "9.3", size: "230" },
      { label: "Jefferson Middle", x: "30", y: "9.6", size: "475" },
      { label: "Fairview Middle", x: "34", y: "4.6", size: "390" },
      { label: "Kennedy Elementary", x: "36", y: "11.2", size: "255" },
      { label: "Madison Middle", x: "40", y: "12.4", size: "505" },
    ],
    xTitle: "Tutoring hours per student",
    yTitle: "Reading growth",
    xSuffix: "hrs",
    ySuffix: "mo",
    sizeTitle: "Students enrolled",
    showTrend: "yes",
    labelOutliers: "yes",
    footnote: "Sample data · Source: district benchmark assessments and tutor logs",
  },
  render: ({ title, headingLevel, subtitle, points, xTitle, yTitle, xSuffix, ySuffix, sizeTitle, showTrend, labelOutliers, footnote }) => {
    const H = headingLevel || "h3";
    const rows = (Array.isArray(points) ? points : []).map((p, i) => ({
      key: `p${i}`,
      label: p?.label?.trim() || `Point ${i + 1}`,
      x: toNumber(p?.x),
      y: toNumber(p?.y),
      size: toNumber(p?.size),
    }));
    const plotted = rows.filter((r): r is typeof r & { x: number; y: number } => r.x !== null && r.y !== null);

    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 (!plotted.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 3v18h18" strokeLinecap="round" />
              <circle cx="8" cy="15" r="1.5" />
              <circle cx="12" cy="10" r="1.5" />
              <circle cx="17" cy="7" r="1.5" />
            </svg>
            <p className="text-sm font-medium text-neutral-900">No data yet</p>
            <p className="text-xs text-neutral-500">Points appear once X and Y values are entered or the data source returns them.</p>
          </div>
          {foot}
        </div>
      );
    }

    const xsAll = plotted.map((p) => p.x);
    const ysAll = plotted.map((p) => p.y);
    const xt = niceTicks(Math.min(...xsAll), Math.max(...xsAll), 4);
    const yt = niceTicks(Math.min(...ysAll), Math.max(...ysAll), 4);
    const [xlo, xhi] = [xt[0], xt[xt.length - 1]];
    const [ylo, yhi] = [yt[0], yt[yt.length - 1]];
    const px = (v: number) => ((v - xlo) / (xhi - xlo || 1)) * 100;
    const py = (v: number) => 100 - ((v - ylo) / (yhi - ylo || 1)) * 100;
    const xAxisSuffix = xSuffix && xSuffix.trim().length <= 1 ? xSuffix.trim() : "";
    const yAxisSuffix = ySuffix && ySuffix.trim().length <= 1 ? ySuffix.trim() : "";

    const model = plotted.length >= 2 ? fit(plotted) : null;
    const residuals = model ? plotted.map((p) => p.y - (model.a + model.b * p.x)) : [];
    const sd = model && plotted.length > 2 ? Math.sqrt(residuals.reduce((s, r) => s + r * r, 0) / (plotted.length - 2)) : 0;
    const outliers = new Map<string, "above" | "below">();
    if (labelOutliers !== "no" && model && plotted.length >= 5 && sd > 0) {
      plotted
        .map((p, i) => ({ key: p.key, r: residuals[i] }))
        .filter((o) => Math.abs(o.r) > 1.6 * sd)
        .sort((a, b) => Math.abs(b.r) - Math.abs(a.r))
        .slice(0, 3)
        .forEach((o) => outliers.set(o.key, o.r > 0 ? "above" : "below"));
    }

    const sizes = plotted.map((p) => p.size).filter((s): s is number => s !== null && s > 0);
    const maxSize = sizes.length ? Math.max(...sizes) : 0;
    const diameter = (s: number | null) => (maxSize && s && s > 0 ? Math.round(8 + Math.sqrt(s / maxSize) * 16) : 10);

    const trend = model && showTrend !== "no" ? { y1: py(model.a + model.b * xlo), y2: py(model.a + model.b * xhi) } : null;
    const slope = model ? `${model.b >= 0 ? "+" : "−"}${full.format(Math.abs(model.b))}${ySuffix ? ` ${ySuffix.trim()}` : ""} per ${xSuffix ? xSuffix.trim().replace(/s$/, "") : "unit"}` : "";

    const summary = `${title ? `${title}. ` : ""}Scatter plot of ${plotted.length} points. ${xTitle || "X"} ranges from ${format(Math.min(...xsAll), xSuffix)} to ${format(
      Math.max(...xsAll),
      xSuffix,
    )}; ${yTitle || "Y"} from ${format(Math.min(...ysAll), ySuffix)} to ${format(Math.max(...ysAll), ySuffix)}.${
      model ? ` Trend ${slope}, R² ${model.r2.toFixed(2)}.` : ""
    }${
      outliers.size
        ? ` Outliers: ${plotted
            .filter((p) => outliers.has(p.key))
            .map((p) => `${p.label} (${outliers.get(p.key)} trend)`)
            .join(", ")}.`
        : ""
    }`;

    return (
      <div className={card}>
        {header}

        <ul className="mt-4 flex flex-wrap gap-x-5 gap-y-2 text-xs text-neutral-600">
          {model && showTrend !== "no" ? (
            <li className="flex items-center gap-2">
              <span aria-hidden="true" className="w-4 shrink-0 border-t-2 border-dashed border-neutral-900" />
              <span className="tabular-nums">
                Trend {slope} · R² {model.r2.toFixed(2)}
              </span>
            </li>
          ) : null}
          {maxSize ? (
            <li className="flex items-center gap-2">
              <span aria-hidden="true" className="flex items-center gap-0.5">
                <span className="size-1.5 rounded-full bg-indigo-400" />
                <span className="size-3 rounded-full bg-indigo-400" />
              </span>
              <span>Dot size: {sizeTitle?.trim() || "size"}</span>
            </li>
          ) : null}
          {outliers.size ? (
            <li className="flex items-center gap-2">
              <span aria-hidden="true" className="size-2.5 shrink-0 rounded-full bg-indigo-600 ring-2 ring-indigo-200" />
              <span>Labelled: furthest from trend</span>
            </li>
          ) : null}
        </ul>

        {yTitle ? (
          <p aria-hidden="true" className="mt-5 text-xs font-medium text-neutral-700">
            {yTitle}
            {ySuffix ? <span className="font-normal text-neutral-500"> ({ySuffix.trim()})</span> : null}
          </p>
        ) : null}

        <div role="img" aria-label={summary} className={`${yTitle ? "mt-3" : "mt-6"} flex gap-3`}>
          <div className={`relative shrink-0 ${PLOT_HEIGHT}`}>
            {yt.map((t) => (
              <span key={`w${t}`} className="invisible block h-0 overflow-hidden text-xs tabular-nums">
                {format(t, yAxisSuffix, true)}
              </span>
            ))}
            {yt.map((t) => (
              <span key={t} className="absolute right-0 -translate-y-1/2 text-xs leading-none text-neutral-500 tabular-nums" style={{ top: `${py(t)}%` }}>
                {format(t, yAxisSuffix, true)}
              </span>
            ))}
          </div>

          <div className="relative min-w-0 flex-1">
            <div className={`relative ${PLOT_HEIGHT}`}>
              <svg viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true" className="absolute inset-0 size-full">
                {yt.map((t, i) => (
                  <line key={`y${t}`} x1="0" x2="100" y1={py(t)} y2={py(t)} className={i === 0 ? "stroke-neutral-300" : "stroke-neutral-200"} strokeWidth="1" vectorEffect="non-scaling-stroke" />
                ))}
                {xt.map((t, i) => (
                  <line key={`x${t}`} x1={px(t)} x2={px(t)} y1="0" y2="100" className={i === 0 ? "stroke-neutral-300" : "stroke-neutral-100"} strokeWidth="1" vectorEffect="non-scaling-stroke" />
                ))}
                {trend ? (
                  <line x1="0" x2="100" y1={trend.y1} y2={trend.y2} className="stroke-neutral-900" strokeWidth="1.5" strokeDasharray="5 4" vectorEffect="non-scaling-stroke" />
                ) : null}
              </svg>

              {plotted.map((p) => {
                const d = diameter(p.size);
                const flagged = outliers.has(p.key);
                return (
                  <span
                    key={p.key}
                    className={`absolute -translate-x-1/2 -translate-y-1/2 rounded-full ${flagged ? "z-10 bg-indigo-600 ring-2 ring-indigo-200" : "bg-indigo-500/55 ring-1 ring-white"}`}
                    style={{ left: `${px(p.x)}%`, top: `${py(p.y)}%`, width: d, height: d }}
                  />
                );
              })}

              {plotted
                .filter((p) => outliers.has(p.key))
                .map((p) => {
                  const right = px(p.x) > 55;
                  const gap = diameter(p.size) / 2 + 6;
                  return (
                    <span
                      key={`t${p.key}`}
                      className="absolute z-20 max-w-28 -translate-y-1/2 truncate rounded-sm bg-white/90 px-1 text-xs leading-4 font-medium text-neutral-900 @md:max-w-40"
                      style={right ? { right: `calc(${100 - px(p.x)}% + ${gap}px)`, top: `${py(p.y)}%` } : { left: `calc(${px(p.x)}% + ${gap}px)`, top: `${py(p.y)}%` }}
                    >
                      {p.label}
                    </span>
                  );
                })}
            </div>

            <div className="relative mt-2 h-4">
              {xt.map((t, i) => (
                <span
                  key={t}
                  className={`absolute top-0 text-xs leading-4 whitespace-nowrap text-neutral-500 tabular-nums ${
                    i === xt.length - 1 ? "-translate-x-full" : i === 0 ? "" : "-translate-x-1/2"
                  } ${xt.length > 5 && i % 2 === 1 && i !== xt.length - 1 ? "hidden @md:block" : ""}`}
                  style={{ left: `${px(t)}%` }}
                >
                  {format(t, xAxisSuffix, true)}
                </span>
              ))}
            </div>
            {xTitle ? (
              <p aria-hidden="true" className="mt-2 text-center text-xs font-medium text-neutral-700">
                {xTitle}
                {xSuffix ? <span className="font-normal text-neutral-500"> ({xSuffix.trim()})</span> : null}
              </p>
            ) : null}
          </div>
        </div>

        <details className="group mt-4">
          <summary className="inline-flex min-h-11 cursor-pointer list-none items-center gap-1.5 rounded-md text-sm font-medium text-indigo-700 hover:text-indigo-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 [&::-webkit-details-marker]:hidden">
            <svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" className="size-4 transition-transform group-open:rotate-90 motion-reduce:transition-none">
              <path d="M6.22 4.22a.75.75 0 0 1 1.06 0l3.25 3.25a.75.75 0 0 1 0 1.06l-3.25 3.25a.75.75 0 0 1-1.06-1.06L8.94 8 6.22 5.28a.75.75 0 0 1 0-1.06Z" />
            </svg>
            View data table
          </summary>
          <div className="mt-2 relative overflow-x-auto rounded-lg ring-1 ring-neutral-950/5">
            <table className="w-full text-left text-sm">
              {title ? <caption className="sr-only">{title}</caption> : null}
              <thead className="bg-neutral-50 text-xs text-neutral-600">
                <tr>
                  <th scope="col" className="px-3 py-2 font-medium">
                    Item
                  </th>
                  <th scope="col" className="px-3 py-2 text-right font-medium">
                    {xTitle || "X"}
                  </th>
                  <th scope="col" className="px-3 py-2 text-right font-medium">
                    {yTitle || "Y"}
                  </th>
                  {maxSize ? (
                    <th scope="col" className="px-3 py-2 text-right font-medium">
                      {sizeTitle || "Size"}
                    </th>
                  ) : null}
                  {outliers.size ? (
                    <th scope="col" className="px-3 py-2 font-medium">
                      Note
                    </th>
                  ) : null}
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {rows.map((r) => (
                  <tr key={r.key}>
                    <th scope="row" className="px-3 py-2 font-normal text-neutral-700">
                      {r.label}
                    </th>
                    <td className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">{format(r.x, xSuffix)}</td>
                    <td className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">{format(r.y, ySuffix)}</td>
                    {maxSize ? <td className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">{format(r.size)}</td> : null}
                    {outliers.size ? (
                      <td className="px-3 py-2 whitespace-nowrap text-neutral-700">{outliers.has(r.key) ? `Well ${outliers.get(r.key)} trend` : ""}</td>
                    ) : null}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </details>

        {foot}
      </div>
    );
  },
};
```
