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

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/waterfall-chart) to this Pantheon Content Publisher (P1) Next.js project. Walk from a starting value through each increase and decrease to a calculated ending total.

## Steps

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

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

/**
 * Waterfall Chart — walk from a starting value through each increase and decrease to a
 * computed ending total, e.g. how a budget changed year over year. Decreases are hatched and
 * signed, so they never rely on color. Every value is a text field, bindable to a P1 data
 * source. Place inside a Dashboard Grid.
 * Register: `WaterfallChartBlock: waterfallChartBlock` in puck.config.tsx.
 */

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

type Step = { label: string; value: string };

export type WaterfallChartProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  startLabel: string;
  startValue: string;
  steps: Step[];
  endLabel: string;
  valuePrefix: string;
  valueSuffix: 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;
}

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

type Bar = { key: string; label: string; kind: "total" | "up" | "down"; from: number; to: number; change: number | null };

const CHART_HEIGHT = "h-52 @md:h-64";

export const waterfallChartBlock: ComponentConfig<WaterfallChartProps> = {
  label: "Waterfall 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. FY2025 to FY2026, in thousands. Leave blank to hide." } },
    startLabel: { type: "text", label: "Starting bar label", metadata: { help: "e.g. FY25 budget." } },
    startValue: { type: "text", label: "Starting value", metadata: { help: "A number. Or bind it, e.g. {{ budget.prior_total }}." } },
    steps: {
      type: "array",
      label: "Changes",
      min: 1,
      max: 14,
      getItemSummary: (item) => (item?.label ? `${item.label}${item.value ? ` · ${item.value}` : ""}` : "Change"),
      defaultItemProps: { label: "New change", value: "" },
      arrayFields: {
        label: { type: "text", label: "Label" },
        value: { type: "text", label: "Change", metadata: { help: "Signed: 120 adds, -45 subtracts. Blank rows are skipped." } },
      },
    },
    endLabel: { type: "text", label: "Ending bar label", metadata: { help: "e.g. FY26 budget. The total is calculated for you." } },
    valuePrefix: { type: "text", label: "Value prefix", metadata: { help: "e.g. $. Leave blank for none." } },
    valueSuffix: { type: "text", label: "Value suffix", metadata: { help: "e.g. k or M. Leave blank for none." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Operating budget, year over year",
    headingLevel: "h3",
    subtitle: "FY2025 to FY2026, in thousands",
    startLabel: "FY25 budget",
    startValue: "2,400",
    steps: [
      { label: "Foundation grants", value: "320" },
      { label: "Individual giving", value: "145" },
      { label: "Event revenue", value: "-60" },
      { label: "Staff costs", value: "-210" },
      { label: "Facility lease", value: "-85" },
      { label: "Program expansion", value: "-140" },
      { label: "Earned revenue", value: "90" },
    ],
    endLabel: "FY26 budget",
    valuePrefix: "$",
    valueSuffix: "k",
    footnote: "Sample data · Source: board-approved FY2026 operating budget",
  },
  render: ({ id, title, headingLevel, subtitle, startLabel, startValue, steps, endLabel, valuePrefix, valueSuffix, footnote }) => {
    const H = headingLevel || "h3";
    const uid = String(id ?? "waterfall").replace(/[^a-zA-Z0-9_-]/g, "");
    const start = toNumber(startValue);
    const changes = (Array.isArray(steps) ? steps : [])
      .map((s, i) => ({ key: `s${i}`, label: s?.label?.trim() || `Change ${i + 1}`, value: toNumber(s?.value) }))
      .filter((s): s is { key: string; label: string; value: number } => s.value !== 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 (start === null && !changes.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 21h18M5 17V7h3v4M11 11V5h3v3M17 8v9h2" 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 a starting value and changes are entered.</p>
          </div>
          {foot}
        </div>
      );
    }

    const base = start ?? 0;
    const bars: Bar[] = [{ key: "start", label: startLabel?.trim() || "Start", kind: "total", from: 0, to: base, change: null }];
    let running = base;
    for (const c of changes) {
      bars.push({ key: c.key, label: c.label, kind: c.value >= 0 ? "up" : "down", from: running, to: running + c.value, change: c.value });
      running += c.value;
    }
    const end = running;
    bars.push({ key: "end", label: endLabel?.trim() || "End", kind: "total", from: 0, to: end, change: null });
    const m = bars.length;

    const levels = bars.flatMap((b) => [b.from, b.to]);
    const ticks = niceTicks(Math.min(0, ...levels), Math.max(0, ...levels), 4);
    const lo = ticks[0];
    const hi = ticks[ticks.length - 1];
    const y = (v: number) => 100 - ((v - lo) / (hi - lo || 1)) * 100;
    const axisSuffix = valueSuffix && valueSuffix.trim().length <= 1 ? valueSuffix.trim() : "";
    const net = end - base;
    const valueLabels = m <= 7 ? "block" : m <= 12 ? "hidden @md:block" : "hidden";

    const summary = `${title ? `${title}. ` : ""}Waterfall chart. Starts at ${format(base, valuePrefix, valueSuffix)} (${bars[0].label}). ${changes
      .map((c) => `${c.label} ${c.value >= 0 ? "adds" : "subtracts"} ${format(Math.abs(c.value), valuePrefix, valueSuffix)}`)
      .join("; ")}. Ends at ${format(end, valuePrefix, valueSuffix)} (${bars[m - 1].label}), a net change of ${format(net, valuePrefix, valueSuffix, false, true)}.`;

    const hatch = (key: string) => (
      <svg aria-hidden="true" className="absolute inset-0 size-full">
        <defs>
          <pattern id={`${uid}-hatch-${key}`} width="5" height="5" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="5" className="stroke-indigo-600" strokeWidth="2" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill={`url(#${uid}-hatch-${key})`} />
      </svg>
    );

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

        <div className="mt-4 flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
          <dl className="flex gap-6">
            <div>
              <dt className="text-xs text-neutral-600">{bars[m - 1].label}</dt>
              <dd className="mt-1 text-2xl font-semibold tracking-tight text-neutral-950 tabular-nums">{format(end, valuePrefix, valueSuffix)}</dd>
            </div>
            <div>
              <dt className="text-xs text-neutral-600">Net change</dt>
              <dd className="mt-1 text-2xl font-semibold tracking-tight text-neutral-950 tabular-nums">{format(net, valuePrefix, valueSuffix, false, true)}</dd>
            </div>
          </dl>
          <ul className="flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-neutral-600">
            <li className="flex items-center gap-1.5">
              <span aria-hidden="true" className="size-2.5 rounded-sm bg-indigo-400" />
              Increase (+)
            </li>
            <li className="flex items-center gap-1.5">
              <span aria-hidden="true" className="relative size-2.5 overflow-hidden rounded-sm bg-white ring-1 ring-indigo-600 ring-inset">
                {hatch("key")}
              </span>
              Decrease (−)
            </li>
            <li className="flex items-center gap-1.5">
              <span aria-hidden="true" className="size-2.5 rounded-sm bg-indigo-600" />
              Total
            </li>
          </ul>
        </div>

        <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, valuePrefix, 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, valuePrefix, axisSuffix, true)}
              </span>
            ))}
          </div>

          <div className="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">
                {ticks.map((t) => (
                  <line key={t} x1="0" x2="100" y1={y(t)} y2={y(t)} className={t === 0 ? "stroke-neutral-300" : "stroke-neutral-200"} strokeWidth="1" vectorEffect="non-scaling-stroke" />
                ))}
              </svg>
              <div className="absolute inset-0 flex">
                {bars.map((b, i) => {
                  const top = y(Math.max(b.from, b.to));
                  const bottom = 100 - y(Math.min(b.from, b.to));
                  const label = b.kind === "total" ? format(b.to, valuePrefix, axisSuffix, true) : format(b.change, valuePrefix, axisSuffix, true, true);
                  const below = b.kind === "down" || (b.kind === "total" && b.to < 0);
                  return (
                    <div key={b.key} className="relative min-w-0 flex-1 px-0.5 @md:px-1.5">
                      {i < m - 1 ? (
                        <span className="absolute left-1/2 w-full border-t border-dashed border-neutral-400" style={{ top: `${y(b.to)}%` }} />
                      ) : null}
                      <div
                        className={`absolute inset-x-0.5 mx-auto max-w-14 overflow-visible rounded-xs @md:inset-x-1.5 ${
                          b.kind === "total" ? "bg-indigo-600" : b.kind === "up" ? "bg-indigo-400" : "bg-white ring-1 ring-indigo-600 ring-inset"
                        }`}
                        style={{ top: `${top}%`, bottom: `${bottom}%`, minHeight: 2 }}
                      >
                        {b.kind === "down" ? <span className="absolute inset-0 overflow-hidden rounded-xs">{hatch(b.key)}</span> : null}
                        <span
                          className={`absolute left-1/2 -translate-x-1/2 text-xs font-medium whitespace-nowrap tabular-nums ${b.kind === "total" ? "text-neutral-950" : "text-neutral-700"} ${
                            below ? "top-full mt-1" : "bottom-full mb-1"
                          } ${valueLabels}`}
                        >
                          {label}
                        </span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            <div className="mt-2 flex">
              {bars.map((b, i) => (
                <span
                  key={b.key}
                  className={`min-w-0 flex-1 truncate px-0.5 text-center text-xs leading-4 ${b.kind === "total" ? "font-medium text-neutral-800" : "text-neutral-500"} ${
                    m > 7 && b.kind !== "total" && i % 2 === 0 ? "invisible @lg:visible" : ""
                  }`}
                >
                  {b.label}
                </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">
                    Step
                  </th>
                  <th scope="col" className="px-3 py-2 text-right font-medium">
                    Change
                  </th>
                  <th scope="col" className="px-3 py-2 text-right font-medium">
                    Running total
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {bars.map((b) => (
                  <tr key={b.key} className={b.kind === "total" ? "bg-neutral-50/60" : ""}>
                    <th scope="row" className={`px-3 py-2 text-neutral-700 ${b.kind === "total" ? "font-medium" : "font-normal"}`}>
                      {b.label}
                    </th>
                    <td className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">{format(b.change, valuePrefix, valueSuffix, false, true)}</td>
                    <td className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">{format(b.to, valuePrefix, valueSuffix)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </details>

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