# Add the "Stacked Bar Chart" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/stacked-bar-chart) to this Pantheon Content Publisher (P1) Next.js project. Break each category into up to four segments, shown as amounts or as a 100% share.

## Steps

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

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

/**
 * Stacked Bar Chart — break each category into up to four segments, as absolute amounts or as
 * a 100% share. Horizontal bars keep long labels readable at any card width. Every value is a
 * text field, bindable to a P1 data source. Place inside a Dashboard Grid.
 * Register: `StackedBarChartBlock: stackedBarChartBlock` in puck.config.tsx.
 */

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

type Category = { label: string; values: string };

export type StackedBarChartProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  segments: string;
  categories: Category[];
  mode: "absolute" | "percent";
  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;
}

/** 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());
}

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

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

const SWATCH = ["bg-indigo-600", "bg-indigo-400", "bg-indigo-200", "bg-neutral-400"] as const;

export const stackedBarChartBlock: ComponentConfig<StackedBarChartProps> = {
  label: "Stacked Bar 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. Fiscal year 2026. Leave blank to hide." } },
    segments: {
      type: "text",
      label: "Segment names",
      metadata: { help: "Comma-separated, up to four, in stacking order, e.g. Grants, Individual gifts, Events." },
    },
    categories: {
      type: "array",
      label: "Bars",
      min: 1,
      max: 16,
      getItemSummary: (item) => item?.label || "Bar",
      defaultItemProps: { label: "New category", values: "" },
      arrayFields: {
        label: { type: "text", label: "Label" },
        values: {
          type: "text",
          label: "Segment values",
          metadata: { help: "Comma-separated, one per segment name, in the same order, e.g. 120, 80, 30. Blank counts as zero." },
        },
      },
    },
    mode: {
      type: "radio",
      label: "Scale",
      options: [
        { label: "Amounts", value: "absolute" },
        { label: "100% share", value: "percent" },
      ],
      metadata: { help: "Amounts compares bar totals. 100% share compares the mix inside each bar." },
    },
    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 hrs. Leave blank for none." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Funding mix by program",
    headingLevel: "h3",
    subtitle: "Fiscal year 2026, in thousands",
    segments: "Grants, Individual gifts, Events, Earned revenue",
    categories: [
      { label: "Youth mentoring", values: "420, 186, 64, 22" },
      { label: "Adult literacy", values: "260, 142, 38, 51" },
      { label: "Food access", values: "310, 274, 92, 18" },
      { label: "Housing navigation", values: "455, 88, 20, 0" },
      { label: "Senior companions", values: "128, 165, 47, 36" },
    ],
    mode: "absolute",
    valuePrefix: "$",
    valueSuffix: "k",
    footnote: "Sample data · Source: FY2026 audited statement of activities",
  },
  render: ({ title, headingLevel, subtitle, segments, categories, mode, valuePrefix, valueSuffix, footnote }) => {
    const H = headingLevel || "h3";
    const names = splitList(segments).slice(0, 4);
    const rows = (Array.isArray(categories) ? categories : []).map((c, i) => {
      const raw = splitList(c?.values).map((v) => toNumber(v));
      const count = Math.max(names.length, Math.min(raw.length, 4));
      const values = Array.from({ length: count }, (_, k) => raw[k] ?? null);
      const total = values.reduce<number>((s, v) => s + Math.max(0, v ?? 0), 0);
      return { key: `c${i}`, label: c?.label?.trim() || `Item ${i + 1}`, values, total, any: values.some((v) => v !== null) };
    });
    const segCount = Math.min(4, Math.max(names.length, ...rows.map((r) => r.values.length), 0));
    const segs = Array.from({ length: segCount }, (_, k) => ({ key: `s${k}`, name: names[k] || `Segment ${k + 1}`, swatch: SWATCH[k] }));
    const hasData = rows.some((r) => r.any && r.total > 0);
    const percent = mode === "percent";

    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 (!hasData) {
      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 6h10m3 0h5M3 12h6m3 0h9M3 18h12m3 0h3" strokeLinecap="round" />
            </svg>
            <p className="text-sm font-medium text-neutral-900">No data yet</p>
            <p className="text-xs text-neutral-500">Bars appear once values are entered or the data source returns them.</p>
          </div>
          {foot}
        </div>
      );
    }

    const maxTotal = Math.max(...rows.map((r) => r.total), 0) || 1;
    const share = (v: number | null, total: number) => (total > 0 ? (Math.max(0, v ?? 0) / total) * 100 : 0);
    const segTotals = segs.map((_, k) => rows.reduce((s, r) => s + Math.max(0, r.values[k] ?? 0), 0));
    const grand = segTotals.reduce((s, v) => s + v, 0);

    const summary = `${title ? `${title}. ` : ""}Stacked bar chart${percent ? " showing each bar as 100%" : ""}. ${rows
      .map(
        (r) =>
          `${r.label}: ${segs
            .map((s, k) => `${s.name} ${percent ? `${pctFmt.format(share(r.values[k], r.total))}%` : format(r.values[k] ?? null, valuePrefix, valueSuffix)}`)
            .join(", ")}${percent ? "" : `; total ${format(r.total, valuePrefix, valueSuffix)}`}`,
      )
      .join(". ")}.`;

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

        <ul className="mt-4 flex flex-wrap gap-x-4 gap-y-2 text-xs text-neutral-600">
          {segs.map((s, k) => (
            <li key={s.key} className="flex items-center gap-1.5">
              <span aria-hidden="true" className={`size-2.5 shrink-0 rounded-sm ${s.swatch}`} />
              <span>{s.name}</span>
              <span className="text-neutral-500 tabular-nums">{percent ? `${pctFmt.format(grand ? (segTotals[k] / grand) * 100 : 0)}%` : format(segTotals[k], valuePrefix, valueSuffix)}</span>
            </li>
          ))}
        </ul>

        <div role="img" aria-label={summary} className="mt-5">
          <ul className="space-y-4">
            {rows.map((r) => (
              <li key={r.key}>
                <div className="flex items-baseline justify-between gap-3 text-sm">
                  <span className="min-w-0 text-pretty text-neutral-700">{r.label}</span>
                  <span className="shrink-0 font-semibold text-neutral-950 tabular-nums">
                    {percent ? (
                      <>
                        {pctFmt.format(share(r.values[0], r.total))}%<span className="ml-1 text-xs font-normal text-neutral-500">{segs[0]?.name}</span>
                      </>
                    ) : (
                      format(r.total, valuePrefix, valueSuffix)
                    )}
                  </span>
                </div>
                <div className="mt-1.5 h-3 rounded-sm bg-neutral-100">
                  <div className="flex h-full gap-0.5" style={{ width: `${percent ? (r.total > 0 ? 100 : 0) : (r.total / maxTotal) * 100}%` }}>
                    {segs.map((s, k) => {
                      const w = share(r.values[k], r.total);
                      return w > 0 ? <span key={s.key} className={`h-full min-w-0.5 first:rounded-l-sm last:rounded-r-sm ${s.swatch}`} style={{ flexGrow: w, flexBasis: 0 }} /> : null;
                    })}
                  </div>
                </div>
              </li>
            ))}
          </ul>
          <div aria-hidden="true" className="relative mt-3 h-4 text-xs text-neutral-500 tabular-nums">
            <span className="absolute left-0">0</span>
            {percent ? <span className="absolute left-1/2 -translate-x-1/2">50%</span> : null}
            <span className="absolute right-0">{percent ? "100%" : format(maxTotal, valuePrefix, valueSuffix)}</span>
          </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">
                    Category
                  </th>
                  {segs.map((s) => (
                    <th key={s.key} scope="col" className="px-3 py-2 text-right font-medium">
                      {s.name}
                    </th>
                  ))}
                  <th scope="col" className="px-3 py-2 text-right font-semibold text-neutral-900">
                    Total
                  </th>
                </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>
                    {segs.map((s, k) => (
                      <td key={s.key} className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">
                        {format(r.values[k] ?? null, valuePrefix, valueSuffix)}
                        {r.total > 0 ? <span className="ml-1.5 text-xs text-neutral-500">{pctFmt.format(share(r.values[k], r.total))}%</span> : null}
                      </td>
                    ))}
                    <td className="px-3 py-2 text-right font-semibold whitespace-nowrap text-neutral-950 tabular-nums">{format(r.total, valuePrefix, valueSuffix)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </details>

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