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

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/bar-chart) to this Pantheon Content Publisher (P1) Next.js project. Compare categories as columns or a labelled bar list, with optional sorting and a target line.

## Steps

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

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

/**
 * Bar Chart — compare categories as vertical columns or a labelled horizontal bar list
 * (best for long labels), with an optional target line. Every value is a text field, so
 * rows can be bound to a P1 data source. Place inside a Dashboard Grid.
 * Register: `BarChartBlock: barChartBlock` in puck.config.tsx.
 */

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

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

export type BarChartProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  categories: Category[];
  orientation: "vertical" | "horizontal";
  sort: "entered" | "desc";
  target: string;
  targetLabel: 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) {
  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 CHART_HEIGHT = "h-48 @md:h-60";

export const barChartBlock: ComponentConfig<BarChartProps> = {
  label: "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. July–September 2026. Leave blank to hide." } },
    categories: {
      type: "array",
      label: "Bars",
      min: 1,
      max: 24,
      getItemSummary: (item) => (item?.label ? `${item.label}${item.value ? ` · ${item.value}` : ""}` : "Bar"),
      defaultItemProps: { label: "New category", value: "" },
      arrayFields: {
        label: { type: "text", label: "Label" },
        value: { type: "text", label: "Value", metadata: { help: "A number, e.g. 1,284. Or bind a list with {{ source.items }} and {{ item.count }}." } },
      },
    },
    orientation: {
      type: "radio",
      label: "Orientation",
      options: [
        { label: "Vertical", value: "vertical" },
        { label: "Horizontal", value: "horizontal" },
      ],
      metadata: { help: "Horizontal is a labelled bar list. Use it for long labels or more than eight bars." },
    },
    sort: {
      type: "select",
      label: "Order",
      options: [
        { label: "As entered", value: "entered" },
        { label: "Largest first", value: "desc" },
      ],
      metadata: { help: "Keep 'As entered' for time periods, like months or years." },
    },
    target: { type: "text", label: "Target value", metadata: { help: "Draws a reference line, e.g. a goal or last year's average. Leave blank to hide." } },
    targetLabel: { type: "text", label: "Target label", metadata: { help: "e.g. Quarterly goal." } },
    valuePrefix: { type: "text", label: "Value prefix", metadata: { help: "e.g. $. Leave blank for none." } },
    valueSuffix: { type: "text", label: "Value suffix", metadata: { help: "e.g. % or hrs. Leave blank for none." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Volunteer hours by site",
    headingLevel: "h3",
    subtitle: "July–September 2026",
    categories: [
      { label: "Eastside Community Pantry", value: "842" },
      { label: "Riverside Senior Center", value: "615" },
      { label: "Northgate Youth Tutoring", value: "588" },
      { label: "Westend Tool Library", value: "377" },
      { label: "Mobile Market (all routes)", value: "702" },
      { label: "Hope Street Shelter Kitchen", value: "496" },
    ],
    orientation: "horizontal",
    sort: "desc",
    target: "600",
    targetLabel: "Quarterly goal per site",
    valuePrefix: "",
    valueSuffix: "hrs",
    footnote: "Sample data · Volunteer check-in records",
  },
  render: ({ title, headingLevel, subtitle, categories, orientation, sort, target, targetLabel, valuePrefix, valueSuffix, footnote }) => {
    const H = headingLevel || "h3";
    const rows = (Array.isArray(categories) ? categories : []).map((c, i) => ({
      key: `c${i}`,
      label: c?.label?.trim() || `Item ${i + 1}`,
      value: toNumber(c?.value),
    }));
    if (sort === "desc") rows.sort((a, b) => (b.value ?? -Infinity) - (a.value ?? -Infinity));
    const nums = rows.map((r) => r.value).filter((v): v is number => v !== null);
    const goal = toNumber(target);
    const goalText = goal !== null ? `${targetLabel?.trim() || "Target"}: ${format(goal, valuePrefix, valueSuffix)}` : "";
    const n = rows.length;

    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 (!nums.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 21h18M6 17v-5M11 17V7M16 17v-8" 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 goalKey =
      goal !== null ? (
        <p className="mt-3 flex items-center gap-2 text-xs text-neutral-600">
          {orientation === "horizontal" ? (
            <span aria-hidden="true" className="h-3 w-0.5 shrink-0 rounded-full bg-neutral-900" />
          ) : (
            <span aria-hidden="true" className="w-4 shrink-0 border-t-2 border-dashed border-neutral-900" />
          )}
          <span className="tabular-nums">{goalText}</span>
        </p>
      ) : null;

    if (orientation === "horizontal") {
      const top = Math.max(...nums, goal ?? 0, 0) || 1;
      const pct = (v: number | null) => (v === null || v <= 0 ? 0 : Math.min(100, (v / top) * 100));
      return (
        <div className={card}>
          {header}
          {goalKey}
          <ul className="mt-5 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">
                    {format(r.value, valuePrefix, valueSuffix)}
                    {goal !== null && r.value !== null ? (
                      <span className="sr-only">{r.value >= goal ? ", meets target" : ", below target"}</span>
                    ) : null}
                  </span>
                </div>
                <div aria-hidden="true" className="relative mt-1.5 h-2 rounded-full bg-neutral-100">
                  <div className="h-full rounded-full bg-indigo-600" style={{ width: `${pct(r.value)}%` }} />
                  {goal !== null ? (
                    <span className="absolute -inset-y-1 w-0.5 -translate-x-1/2 rounded-full bg-neutral-900 ring-2 ring-white" style={{ left: `${pct(goal)}%` }} />
                  ) : null}
                </div>
              </li>
            ))}
          </ul>
          {foot}
        </div>
      );
    }

    const ticks = niceTicks(Math.min(0, ...nums, goal ?? 0), Math.max(0, ...nums, goal ?? 0), 4);
    const lo = ticks[0];
    const hi = ticks[ticks.length - 1];
    const span = hi - lo || 1;
    const y = (v: number) => 100 - ((v - lo) / span) * 100;
    const axisSuffix = valueSuffix && valueSuffix.trim().length <= 1 ? valueSuffix.trim() : "";
    const valueLabels = n <= 6 ? "block" : n <= 12 ? "hidden @md:block" : "hidden";
    const summary = `${title ? `${title}. ` : ""}Bar chart. ${rows.map((r) => `${r.label}: ${format(r.value, valuePrefix, valueSuffix)}`).join("; ")}.${goalText ? ` ${goalText}.` : ""}`;

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

        <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 gap-1.5 @md:gap-3">
                {rows.map((r, i) => {
                  const v = r.value;
                  const isLast = i === n - 1 && sort !== "desc";
                  return (
                    <div key={r.key} className="relative min-w-0 flex-1">
                      {v !== null ? (
                        <div
                          className={`absolute left-1/2 w-full max-w-12 -translate-x-1/2 ${v < 0 ? "rounded-b-sm" : "rounded-t-sm"} ${isLast || sort === "desc" || n === 1 ? "bg-indigo-600" : "bg-indigo-400"}`}
                          style={{ top: `${y(Math.max(v, 0))}%`, bottom: `${100 - y(Math.min(v, 0))}%` }}
                        >
                          <span
                            className={`absolute left-1/2 -translate-x-1/2 text-xs font-medium whitespace-nowrap text-neutral-700 tabular-nums ${v < 0 ? "top-full mt-1" : "bottom-full mb-1"} ${valueLabels}`}
                          >
                            {format(v, valuePrefix, axisSuffix, true)}
                          </span>
                        </div>
                      ) : null}
                    </div>
                  );
                })}
              </div>
              {goal !== null ? (
                <>
                  <svg viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true" className="pointer-events-none absolute inset-0 size-full overflow-visible">
                    <line x1="0" x2="100" y1={y(goal)} y2={y(goal)} className="stroke-neutral-900" strokeWidth="1.5" strokeDasharray="5 4" vectorEffect="non-scaling-stroke" />
                  </svg>
                  <span
                    className="absolute right-0 -translate-y-full rounded-sm bg-white/90 px-1 pb-0.5 text-xs font-medium text-neutral-900 tabular-nums"
                    style={{ top: `${y(goal)}%` }}
                  >
                    {format(goal, valuePrefix, axisSuffix, true)}
                  </span>
                </>
              ) : null}
            </div>

            <div className="mt-2 flex gap-1.5 @md:gap-3">
              {rows.map((r, i) => (
                <span
                  key={r.key}
                  className={`min-w-0 flex-1 truncate text-center text-xs leading-4 text-neutral-500 ${n > 8 && (n - 1 - i) % 2 === 1 ? "invisible @md:visible" : ""}`}
                >
                  {r.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">
                    Category
                  </th>
                  <th scope="col" className="px-3 py-2 text-right font-medium">
                    Value
                  </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>
                    <td className="px-3 py-2 text-right whitespace-nowrap text-neutral-950 tabular-nums">{format(r.value, valuePrefix, valueSuffix)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </details>

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