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

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/data-table) to this Pantheon Content Publisher (P1) Next.js project. A report table with auto right-aligned numeric columns, status badges, and a scrollable captioned layout.

## Steps

1. Create `components/puck/data-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 { dataTableBlock } from "./components/puck/data-table-block";`
3. Register it under `components` as `DataTableBlock: dataTableBlock`.
4. Add `"DataTableBlock"` 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/data-table-block.tsx`

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

/**
 * Data Table — a tabular report card. Headers are one comma-separated line and each row is
 * one pipe-delimited line, so both can be bound to a P1 data source. Numeric columns
 * right-align automatically; one column can render as status badges. Place inside a Dashboard Grid.
 * Register: `DataTableBlock: dataTableBlock` in puck.config.tsx.
 */
// spec: status-colors

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

export type DataTableProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  columns: string;
  rows: { cells: string }[];
  statusColumn: string;
  striped: "striped" | "lines";
  caption: 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;
}

const BLANK = /^(?:|—|–|-|n\/?a)$/i;
/** A figure like 1,204 · 12.5% · $4.2M · -3 · (120) — digits with at most a short unit. */
const FIGURE = /^[^A-Za-z]*\d[^A-Za-z]*[A-Za-z%]{0,3}\)?$/;

type Tone = "good" | "warn" | "bad" | "neutral";

const STATUS_WORDS: Record<Exclude<Tone, "neutral">, string[]> = {
  good: ["on track", "complete", "completed", "met", "done", "ahead", "healthy", "good"],
  warn: ["at risk", "watch", "delayed", "pending", "in review", "needs attention"],
  bad: ["off track", "behind", "missed", "blocked", "overdue", "critical"],
};

const TONE: Record<Tone, { badge: string; dot: string }> = {
  good: { badge: "bg-emerald-50 text-emerald-800 ring-emerald-600/20", dot: "bg-emerald-500" },
  warn: { badge: "bg-amber-50 text-amber-800 ring-amber-600/25", dot: "bg-amber-500" },
  bad: { badge: "bg-red-50 text-red-800 ring-red-600/20", dot: "bg-red-500" },
  neutral: { badge: "bg-neutral-50 text-neutral-700 ring-neutral-500/20", dot: "bg-neutral-400" },
};

function toneOf(value: string): Tone {
  const v = value.trim().toLowerCase();
  for (const tone of ["bad", "warn", "good"] as const) if (STATUS_WORDS[tone].includes(v)) return tone;
  return "neutral";
}

export const dataTableBlock: ComponentConfig<DataTableProps> = {
  label: "Data 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: "Period or subtitle", metadata: { help: "e.g. Jul–Sep 2026. Leave blank to hide." } },
    columns: {
      type: "text",
      label: "Column headers",
      metadata: { help: "Comma-separated, left to right, e.g. Branch, Enrolled, Goal, Status." },
    },
    rows: {
      type: "array",
      label: "Rows",
      min: 0,
      max: 50,
      getItemSummary: (item) => (item?.cells ? String(item.cells).split("|")[0].trim() : "") || "Row",
      defaultItemProps: { cells: "New row | 0 | 0 | On track" },
      arrayFields: {
        cells: {
          type: "text",
          label: "Cells",
          metadata: { help: "Separate cells with |, in column order, e.g. Riverside | 1,204 | 12.5% | On track. Bind with {{ item.field }}." },
        },
      },
    },
    statusColumn: {
      type: "text",
      label: "Status column number",
      metadata: { help: "Which column shows status badges (1 = first). Recognizes On track, At risk, Off track and similar. Leave blank for none." },
    },
    striped: {
      type: "radio",
      label: "Row style",
      options: [
        { label: "Striped", value: "striped" },
        { label: "Lines", value: "lines" },
      ],
    },
    caption: { type: "text", label: "Caption", metadata: { help: "Describes the table for screen readers and shows under it. Leave blank to use the title." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the numbers come from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Summer reading by branch",
    headingLevel: "h3",
    subtitle: "Jun 1 – Aug 31, 2026",
    columns: "Branch, Readers, Goal, Change, Status",
    rows: [
      { cells: "Riverside | 1,204 | 1,100 | 12.5% | On track" },
      { cells: "Northgate | 986 | 1,000 | 4.1% | On track" },
      { cells: "Old Market | 742 | 900 | -6.8% | At risk" },
      { cells: "Westend | 518 | 800 | -14.2% | Off track" },
      { cells: "Bellwood | 893 | 850 | 9.7% | On track" },
    ],
    statusColumn: "5",
    striped: "lines",
    caption: "Readers enrolled in the summer reading challenge, by library branch, against each branch's goal.",
    footnote: "Sample data · Source: Library registration system, Sep 1, 2026",
  },
  render: ({ title, headingLevel, subtitle, columns, rows, statusColumn, striped, caption, footnote }) => {
    const H = headingLevel || "h3";
    const headers = (columns ?? "").split(",").map((c) => c.trim());
    const body = (rows ?? [])
      .map((r) => String(r?.cells ?? "").split("|").map((c) => c.trim()))
      .filter((cells) => cells.some((c) => c !== ""));
    const width = Math.max(headers.filter(Boolean).length ? headers.length : 0, ...body.map((r) => r.length), 0);
    const statusN = toNumber(statusColumn);
    const statusIdx = statusN !== null && Number.isInteger(statusN) && statusN >= 1 && statusN <= width ? statusN - 1 : -1;
    const numeric = Array.from({ length: width }, (_, col) => {
      if (col === statusIdx || col === 0) return false;
      const filled = body.map((r) => r[col] ?? "").filter((c) => !BLANK.test(c));
      return filled.length > 0 && filled.every((c) => FIGURE.test(c));
    });
    const cols = Array.from({ length: width }, (_, i) => i);
    const isEmpty = width === 0 || body.length === 0;
    const label = title?.trim() || "Data table";
    const edge = "pr-4 first:pl-5 last:pr-5 sm:first:pl-6 sm:last:pr-6";
    const pad = `py-3 ${edge}`;

    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 || subtitle ? (
          <div>
            {title ? <H className="text-sm font-semibold text-neutral-950">{title}</H> : null}
            {subtitle ? <p className="mt-1 text-sm text-neutral-500">{subtitle}</p> : null}
          </div>
        ) : null}

        {isEmpty ? (
          <div className="mt-4 flex flex-1 flex-col items-center justify-center rounded-lg border border-dashed border-neutral-300 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 strokeLinecap="round" strokeLinejoin="round" d="M3.75 5.25h16.5v13.5H3.75zM3.75 9.75h16.5M9.75 9.75v9" />
            </svg>
            <p className="mt-2 text-sm font-medium text-neutral-900">No rows to show yet</p>
            <p className="mt-1 text-sm text-neutral-500">Add column headers and rows, or bind a data source.</p>
          </div>
        ) : (
          <div
            role="region"
            aria-label={`${label} (scrolls sideways on small screens)`}
            tabIndex={0}
            className="-mx-5 mt-4 relative overflow-x-auto focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 sm:-mx-6"
          >
            <table className="w-full min-w-full caption-bottom border-collapse text-left text-sm">
              <caption className={caption ? "px-5 pt-3 text-left text-xs leading-5 text-neutral-500 sm:px-6" : "sr-only"}>{caption || label}</caption>
              <thead>
                <tr className="border-b border-neutral-200">
                  {cols.map((c) => (
                    <th
                      key={c}
                      scope="col"
                      className={`${edge} pb-3 text-xs font-medium tracking-wide whitespace-nowrap text-neutral-500 uppercase ${numeric[c] ? "text-right" : ""}`}
                    >
                      {headers[c] || <span className="sr-only">Column {c + 1}</span>}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className={striped === "striped" ? "" : "divide-y divide-neutral-100"}>
                {body.map((cells, r) => (
                  <tr key={r} className={striped === "striped" ? "even:bg-neutral-50" : undefined}>
                    {cols.map((c) => {
                      const raw = cells[c] ?? "";
                      const text = raw === "" ? "—" : raw;
                      const align = numeric[c] ? "text-right tabular-nums whitespace-nowrap" : "";
                      if (c === 0) {
                        return (
                          <th key={c} scope="row" className={`${pad} font-medium text-neutral-950`}>
                            {text}
                          </th>
                        );
                      }
                      if (c === statusIdx && raw !== "") {
                        const t = TONE[toneOf(raw)];
                        return (
                          <td key={c} className={`${pad} whitespace-nowrap`}>
                            <span className={`inline-flex items-center gap-1.5 rounded-md px-2 py-0.5 text-xs font-medium ring-1 ring-inset ${t.badge}`}>
                              <span aria-hidden="true" className={`size-1.5 rounded-full ${t.dot}`} />
                              {raw}
                            </span>
                          </td>
                        );
                      }
                      return (
                        <td key={c} className={`${pad} text-neutral-700 ${align}`}>
                          {text}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {footnote ? <p className="mt-auto pt-4 text-xs text-neutral-500">{footnote}</p> : null}
      </div>
    );
  },
};
```
