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

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/donut-chart) to this Pantheon Content Publisher (P1) Next.js project. How a total breaks down, with the total in the center and values and percentages in the legend.

## Steps

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

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

/**
 * Donut Chart — how a whole breaks into parts, with a total in the center and a legend of
 * values and percentages. Past six segments the smallest collapse into "Other". Every value
 * is a text field, so rows can be bound to a P1 data source. Place inside a Dashboard Grid.
 * Register: `DonutChartBlock: donutChartBlock` in puck.config.tsx.
 */

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

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

export type DonutChartProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  segments: Segment[];
  centerValue: string;
  centerLabel: 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;
}

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}`;
}

function percent(share: number) {
  if (share <= 0) return "0%";
  if (share < 0.01) return "<1%";
  return `${Math.round(share * 100)}%`;
}

const MAX_SEGMENTS = 6;
const COLORS = [
  { arc: "stroke-indigo-700", key: "bg-indigo-700" },
  { arc: "stroke-indigo-600", key: "bg-indigo-600" },
  { arc: "stroke-indigo-400", key: "bg-indigo-400" },
  { arc: "stroke-indigo-300", key: "bg-indigo-300" },
  { arc: "stroke-indigo-200", key: "bg-indigo-200" },
  { arc: "stroke-neutral-300", key: "bg-neutral-300" },
] as const;

// r = 100 / 2π, so the circumference is 100 and dash lengths read as percentages.
const R = 15.9155;

export const donutChartBlock: ComponentConfig<DonutChartProps> = {
  label: "Donut 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. Fall 2026 census. Leave blank to hide." } },
    segments: {
      type: "array",
      label: "Segments",
      min: 1,
      max: 20,
      getItemSummary: (item) => (item?.label ? `${item.label}${item.value ? ` · ${item.value}` : ""}` : "Segment"),
      defaultItemProps: { label: "New segment", value: "" },
      arrayFields: {
        label: { type: "text", label: "Label" },
        value: { type: "text", label: "Value", metadata: { help: "A positive number, e.g. 2,466. Percentages are calculated for you." } },
      },
      metadata: { help: "Shown largest first. Past six, the smallest are combined into Other." },
    },
    centerValue: { type: "text", label: "Center value", metadata: { help: "Leave blank to show the computed total." } },
    centerLabel: { type: "text", label: "Center label", metadata: { help: "e.g. Students or Total spent." } },
    valuePrefix: { type: "text", label: "Value prefix", metadata: { help: "e.g. $. Leave blank for none." } },
    valueSuffix: { type: "text", label: "Value suffix", metadata: { help: "e.g. hrs. Leave blank for none." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Enrollment by college",
    headingLevel: "h3",
    subtitle: "Fall 2026 census, all students",
    segments: [
      { label: "Arts & Sciences", value: "6412" },
      { label: "Business", value: "3180" },
      { label: "Engineering", value: "2905" },
      { label: "Health Sciences", value: "2466" },
      { label: "Education", value: "1203" },
      { label: "Fine Arts", value: "642" },
      { label: "Law", value: "488" },
      { label: "Social Work", value: "371" },
    ],
    centerValue: "",
    centerLabel: "Students",
    valuePrefix: "",
    valueSuffix: "",
    footnote: "Sample data · Office of Institutional Research",
  },
  render: ({ title, headingLevel, subtitle, segments, centerValue, centerLabel, valuePrefix, valueSuffix, footnote }) => {
    const H = headingLevel || "h3";
    const parsed = (Array.isArray(segments) ? segments : [])
      .map((s, i) => ({ label: s?.label?.trim() || `Segment ${i + 1}`, value: toNumber(s?.value) }))
      .filter((s): s is { label: string; value: number } => s.value !== null && s.value > 0)
      .sort((a, b) => b.value - a.value);
    const shown =
      parsed.length > MAX_SEGMENTS
        ? [...parsed.slice(0, MAX_SEGMENTS - 1), { label: "Other", value: parsed.slice(MAX_SEGMENTS - 1).reduce((sum, s) => sum + s.value, 0) }]
        : parsed;
    const total = shown.reduce((sum, s) => sum + s.value, 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;
    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 (!shown.length || total <= 0) {
      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">
              <circle cx="12" cy="12" r="8" />
              <path d="M12 4a8 8 0 0 1 8 8h-8Z" 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 gap = shown.length > 1 ? 0.8 : 0;
    let cursor = 0;
    const arcs = shown.map((s, i) => {
      const len = (s.value / total) * 100;
      const start = cursor;
      cursor += len;
      const dash = Math.max(len - gap, Math.min(len, 0.3));
      return { ...s, i, share: s.value / total, dash, offset: 25 - start, color: COLORS[Math.min(i, COLORS.length - 1)] };
    });

    const center = centerValue?.trim() ? centerValue.trim() : format(total, valuePrefix, valueSuffix, total >= 100000);
    const summary = `${title ? `${title}. ` : ""}Donut chart, total ${format(total, valuePrefix, valueSuffix)}. ${arcs
      .map((a) => `${a.label}: ${format(a.value, valuePrefix, valueSuffix)}, ${percent(a.share)}`)
      .join("; ")}.`;

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

        <div className="mt-6 flex flex-col items-center gap-6 @md:flex-row @md:items-center @md:gap-8">
          <div className="relative size-40 shrink-0 @md:size-44">
            <svg viewBox="0 0 42 42" role="img" aria-label={summary} className="size-full">
              <circle cx="21" cy="21" r={R} fill="none" className="stroke-neutral-100" strokeWidth="5" />
              {arcs.map((a) => (
                <circle
                  key={a.i}
                  cx="21"
                  cy="21"
                  r={R}
                  fill="none"
                  strokeWidth="5"
                  strokeDasharray={`${a.dash.toFixed(3)} ${(100 - a.dash).toFixed(3)}`}
                  strokeDashoffset={a.offset.toFixed(3)}
                  className={a.color.arc}
                />
              ))}
            </svg>
            <div aria-hidden="true" className="absolute inset-0 flex flex-col items-center justify-center px-7 text-center">
              <span className="max-w-full text-2xl leading-tight font-semibold tracking-tight break-words text-neutral-950 tabular-nums">{center}</span>
              {centerLabel ? <span className="mt-0.5 max-w-full text-xs leading-tight text-neutral-500">{centerLabel}</span> : null}
            </div>
          </div>

          <ul className="w-full min-w-0 flex-1 divide-y divide-neutral-100">
            {arcs.map((a) => (
              <li key={a.i} className="flex items-center gap-3 py-2 text-sm">
                <span aria-hidden="true" className={`size-2.5 shrink-0 rounded-sm ${a.color.key}`} />
                <span className="min-w-0 flex-1 text-pretty text-neutral-700">{a.label}</span>
                <span className="shrink-0 font-medium text-neutral-950 tabular-nums">{format(a.value, valuePrefix, valueSuffix, a.value >= 100000)}</span>
                <span className="w-10 shrink-0 text-right text-neutral-500 tabular-nums">{percent(a.share)}</span>
              </li>
            ))}
          </ul>
        </div>

        {centerValue?.trim() || centerLabel ? (
          <p className="sr-only">
            {center}
            {centerLabel ? ` ${centerLabel}` : ""}
          </p>
        ) : null}

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