# Add the "Line Chart" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/line-chart) to this Pantheon Content Publisher (P1) Next.js project. Trend lines for up to three series with each series' latest value in the legend and a data table for screen readers.

## Steps

1. Create `components/puck/line-chart-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 { lineChartBlock } from "./components/puck/line-chart-block";`
3. Register it under `components` as `LineChartBlock: lineChartBlock`.
4. Add `"LineChartBlock"` 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/line-chart-block.tsx`

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

/**
 * Line Chart — one to three series over shared x labels, with a legend of each series'
 * latest value and a "View data table" fallback. Every value is a text field, so labels and
 * series can be bound to a P1 data source. Place inside a Dashboard Grid.
 * Register: `LineChartBlock: lineChartBlock` in puck.config.tsx.
 */

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

type Series = { name: string; values: string };

export type LineChartProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  xLabels: string;
  series: Series[];
  yPrefix: string;
  ySuffix: string;
  showArea: "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;
}

/** A comma-separated string (or a bound array) → trimmed parts. */
function splitList(raw: unknown): string[] {
  if (Array.isArray(raw)) return raw.map((v) => String(v ?? "").trim());
  if (raw == null || String(raw).trim() === "") return [];
  return String(raw)
    .split(",")
    .map((v) => v.trim());
}

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

const STYLES = [
  { line: "text-indigo-600", dot: "ring-indigo-600", key: "border-indigo-600", stop: "text-indigo-600", dash: undefined },
  { line: "text-indigo-400", dot: "ring-indigo-400", key: "border-indigo-400", stop: "text-indigo-400", dash: undefined },
  { line: "text-neutral-400", dot: "ring-neutral-400", key: "border-dashed border-neutral-400", stop: "text-neutral-400", dash: "4 3" },
] as const;

const CHART_HEIGHT = "h-44 @md:h-56";

export const lineChartBlock: ComponentConfig<LineChartProps> = {
  label: "Line Chart",
  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. Monthly, Oct 2025–Sep 2026. Leave blank to hide." } },
    xLabels: {
      type: "text",
      label: "X-axis labels",
      metadata: { help: "Comma-separated, oldest first, e.g. Jan, Feb, Mar. Or bind them, e.g. {{ visits.months }}." },
    },
    series: {
      type: "array",
      label: "Series",
      min: 1,
      max: 3,
      getItemSummary: (item) => item?.name || "Series",
      defaultItemProps: { name: "New series", values: "" },
      arrayFields: {
        name: { type: "text", label: "Name" },
        values: {
          type: "text",
          label: "Values",
          metadata: { help: "Comma-separated, one per x label, e.g. 12, 18, 9. Leave one blank (12, , 9) for a gap." },
        },
      },
    },
    yPrefix: { type: "text", label: "Value prefix", metadata: { help: "e.g. $. Leave blank for none." } },
    ySuffix: { type: "text", label: "Value suffix", metadata: { help: "e.g. % or visits. Leave blank for none." } },
    showArea: {
      type: "radio",
      label: "Shade under lines",
      options: [
        { label: "Yes", value: "yes" },
        { label: "No", value: "no" },
      ],
    },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Library visits",
    headingLevel: "h3",
    subtitle: "Monthly, Oct 2025–Sep 2026",
    xLabels: "Oct, Nov, Dec, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep",
    series: [
      { name: "In-person visits", values: "38420, 35110, 31890, 33240, 34980, 39120, 40310, 41870, 47260, 51940, 49380, 44610" },
      { name: "Digital checkouts", values: "21300, 22140, 24870, 26110, 25480, 26920, 27350, 28010, 30440, 31890, 32760, 33520" },
    ],
    yPrefix: "",
    ySuffix: "",
    showArea: "yes",
    footnote: "Sample data · Branch door counters and e-lending reports",
  },
  render: ({ id, title, headingLevel, subtitle, xLabels, series, yPrefix, ySuffix, showArea, footnote }) => {
    const H = headingLevel || "h3";
    const uid = String(id ?? "line-chart").replace(/[^a-zA-Z0-9_-]/g, "");
    const labels = splitList(xLabels);
    const rows = (Array.isArray(series) ? series : []).slice(0, 3).map((s, i) => ({
      id: `s${i}`,
      name: s?.name?.trim() || `Series ${i + 1}`,
      values: splitList(s?.values).map((v) => toNumber(v)),
      style: STYLES[i],
    }));
    const n = Math.max(labels.length, ...rows.map((r) => r.values.length), 0);
    const all = rows.flatMap((r) => r.values).filter((v): v is number => v !== null);
    const hasData = all.length > 0 && n > 0;

    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;

    if (!hasData) {
      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">
          {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" />
              <path d="m7 15 4-4 3 3 5-6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <p className="text-sm font-medium text-neutral-900">No data yet</p>
            <p className="text-xs text-neutral-500">The chart appears once values are entered or the data source returns them.</p>
          </div>
          {foot}
        </div>
      );
    }

    const min = Math.min(...all);
    const max = Math.max(...all);
    // Start at zero unless the data lives in a narrow band far above it.
    const floor = min >= 0 && max - min > max * 0.3 ? 0 : min;
    const ticks = niceTicks(floor, max, 4);
    const lo = ticks[0];
    const hi = ticks[ticks.length - 1];
    const span = hi - lo || 1;
    const x = (i: number) => (n > 1 ? (i / (n - 1)) * 100 : 50);
    const y = (v: number) => 100 - ((v - lo) / span) * 100;
    const axisSuffix = ySuffix && ySuffix.trim().length <= 1 ? ySuffix.trim() : "";

    const drawn = rows.map((r) => {
      const segments: [number, number][][] = [];
      let current: [number, number][] = [];
      for (let i = 0; i < n; i++) {
        const v = r.values[i] ?? null;
        if (v === null) {
          if (current.length) segments.push(current);
          current = [];
        } else current.push([x(i), y(v)]);
      }
      if (current.length) segments.push(current);
      const toPath = (pts: [number, number][]) => pts.map(([px, py], j) => `${j ? "L" : "M"}${px.toFixed(2)} ${py.toFixed(2)}`).join(" ");
      const line = segments.map(toPath).join(" ");
      const area = segments
        .filter((s) => s.length > 1)
        .map((s) => `${toPath(s)} L${s[s.length - 1][0].toFixed(2)} 100 L${s[0][0].toFixed(2)} 100 Z`)
        .join(" ");
      let lastIndex = -1;
      for (let i = n - 1; i >= 0; i--) if ((r.values[i] ?? null) !== null) { lastIndex = i; break; }
      const latest = lastIndex >= 0 ? (r.values[lastIndex] as number) : null;
      const nums = r.values.filter((v): v is number => v !== null);
      return { ...r, line, area, lastIndex, latest, nums };
    });

    // Label thinning: ~4 labels in a narrow card, ~7 in a wide one, always keeping the latest.
    const narrowStep = Math.max(1, Math.ceil(n / 4));
    const wideStep = Math.max(1, Math.ceil(n / 7));

    const first = labels[0] || "the first point";
    const last = labels[n - 1] || "the latest point";
    const summary = `${title ? `${title}. ` : ""}Line chart, ${n} points from ${first} to ${last}. ${drawn
      .map((r) =>
        r.nums.length
          ? `${r.name}: latest ${format(r.latest, yPrefix, ySuffix)}, low ${format(Math.min(...r.nums), yPrefix, ySuffix)}, high ${format(Math.max(...r.nums), yPrefix, ySuffix)}.`
          : `${r.name}: no data.`,
      )
      .join(" ")}`;

    return (
      <div className="@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">
        {header}

        <dl className="mt-4 flex flex-wrap gap-x-6 gap-y-3">
          {drawn.map((r) => (
            <div key={r.id} className="min-w-0">
              <dt className="flex items-center gap-2 text-xs text-neutral-600">
                <span aria-hidden="true" className={`w-3 shrink-0 border-t-2 ${r.style.key}`} />
                <span className="truncate">{r.name}</span>
              </dt>
              <dd className="mt-1 text-xl font-semibold tracking-tight text-neutral-950 tabular-nums">
                {format(r.latest, yPrefix, ySuffix)}
                {r.lastIndex >= 0 && labels[r.lastIndex] ? (
                  <span className="ml-1.5 text-xs font-normal tracking-normal text-neutral-500">{labels[r.lastIndex]}</span>
                ) : null}
              </dd>
            </div>
          ))}
        </dl>

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

          <div className="relative min-w-0 flex-1">
            <div className={`relative ${CHART_HEIGHT}`}>
              <svg viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true" className="absolute inset-0 size-full overflow-visible">
                <defs>
                  {drawn.map((r, i) => (
                    <linearGradient key={r.id} id={`${uid}-fill-${i}`} x1="0" y1="0" x2="0" y2="1" className={r.style.stop}>
                      <stop offset="0%" stopColor="currentColor" stopOpacity={i === 0 ? 0.22 : 0.12} />
                      <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
                    </linearGradient>
                  ))}
                </defs>
                {ticks.map((t, i) => (
                  <line
                    key={t}
                    x1="0"
                    x2="100"
                    y1={y(t)}
                    y2={y(t)}
                    className={i === 0 ? "stroke-neutral-300" : "stroke-neutral-200"}
                    strokeWidth="1"
                    vectorEffect="non-scaling-stroke"
                  />
                ))}
                {showArea !== "no"
                  ? drawn.map((r, i) => (r.area ? <path key={`a${r.id}`} d={r.area} fill={`url(#${uid}-fill-${i})`} /> : null))
                  : null}
                {[...drawn].reverse().map((r) => (
                  <path
                    key={r.id}
                    d={r.line}
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinejoin="round"
                    strokeLinecap="round"
                    strokeDasharray={r.style.dash}
                    vectorEffect="non-scaling-stroke"
                    className={r.style.line}
                  />
                ))}
              </svg>
              {drawn.map((r) =>
                r.latest !== null ? (
                  <span
                    key={r.id}
                    className={`absolute size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-white ring-2 ${r.style.dot}`}
                    style={{ left: `${x(r.lastIndex)}%`, top: `${y(r.latest)}%` }}
                  />
                ) : null,
              )}
            </div>

            <div className="relative mt-2 h-4">
              {Array.from({ length: n }, (_, i) => {
                const fromEnd = n - 1 - i;
                const narrow = fromEnd % narrowStep === 0;
                const wide = fromEnd % wideStep === 0;
                if ((!narrow && !wide) || !labels[i]) return null;
                const visibility = narrow && wide ? "" : narrow ? "@md:hidden" : "hidden @md:block";
                const align = n > 1 && i === n - 1 ? "-translate-x-full" : n > 1 && i === 0 ? "" : "-translate-x-1/2";
                return (
                  <span
                    key={i}
                    className={`absolute top-0 text-xs leading-4 whitespace-nowrap text-neutral-500 ${align} ${visibility}`}
                    style={{ left: `${x(i)}%` }}
                  >
                    {labels[i]}
                  </span>
                );
              })}
            </div>
          </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">
                    Period
                  </th>
                  {drawn.map((r) => (
                    <th key={r.id} scope="col" className="px-3 py-2 text-right font-medium">
                      {r.name}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {Array.from({ length: n }, (_, i) => (
                  <tr key={i}>
                    <th scope="row" className="px-3 py-2 font-normal whitespace-nowrap text-neutral-700">
                      {labels[i] || `Point ${i + 1}`}
                    </th>
                    {drawn.map((r) => (
                      <td key={r.id} className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">
                        {format(r.values[i] ?? null, yPrefix, ySuffix)}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </details>

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