# Add the "Heatmap Calendar" block to this P1 project

Add a Puck component from P1 Blocks (https://p1-blocks.prolificdigital.io/blocks/heatmap-calendar) to this Pantheon Content Publisher (P1) Next.js project. A year of daily activity as a week-by-day grid, with total, active days and busiest day worked out.

## Steps

1. Create `components/puck/heatmap-calendar-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 { heatmapCalendarBlock } from "./components/puck/heatmap-calendar-block";`
3. Register it under `components` as `HeatmapCalendarBlock: heatmapCalendarBlock`.
4. Add `"HeatmapCalendarBlock"` 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/heatmap-calendar-block.tsx`

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

/**
 * Heatmap Calendar — a year of daily activity as a week-by-day grid (GitHub style), with a
 * computed summary: total, active days and busiest day. Values are one comma-separated text
 * field, so a P1 data source can fill it. Place inside a Dashboard Grid.
 * Register: `HeatmapCalendarBlock: heatmapCalendarBlock` in puck.config.tsx.
 */

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

export type HeatmapCalendarProps = {
  title: string;
  headingLevel: Heading;
  subtitle: string;
  startDate: string;
  values: string;
  unit: 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());
}

/** "2025-10-05" (or a full ISO timestamp) → UTC midnight in ms; anything else → null. */
function parseDate(raw: string | undefined): number | null {
  const m = /^\s*(\d{4})-(\d{2})-(\d{2})/.exec(raw ?? "");
  if (!m) return null;
  const t = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
  const d = new Date(t);
  return d.getUTCMonth() === Number(m[2]) - 1 && d.getUTCDate() === Number(m[3]) ? t : null;
}

const DAY = 86_400_000;
const MAX_DAYS = 371;
const full = new Intl.NumberFormat("en-US", { maximumFractionDigits: 1 });
const longDate = new Intl.DateTimeFormat("en-US", { timeZone: "UTC", weekday: "short", month: "short", day: "numeric", year: "numeric" });
const shortDate = new Intl.DateTimeFormat("en-US", { timeZone: "UTC", month: "short", day: "numeric" });
const monthName = new Intl.DateTimeFormat("en-US", { timeZone: "UTC", month: "short" });

const LEVELS = ["fill-neutral-100", "fill-indigo-200", "fill-indigo-400", "fill-indigo-600", "fill-indigo-800"] as const;
const KEYS = ["bg-neutral-100", "bg-indigo-200", "bg-indigo-400", "bg-indigo-600", "bg-indigo-800"] as const;

// Grid geometry in px: the SVG is drawn at 1:1 and scrolls inside the card when it won't fit.
const CELL = 11;
const STEP = 14;
const GUTTER = 30;
const TOP = 18;

/** Sample year for a volunteer program: busy Saturdays, tutoring Tue/Thu, a holiday surge. */
function sampleHours(): string {
  let seed = 11;
  const rand = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  const start = Date.UTC(2025, 9, 5);
  const out: number[] = [];
  for (let i = 0; i < 364; i++) {
    const d = new Date(start + i * DAY);
    const w = d.getUTCDay();
    const m = d.getUTCMonth();
    const date = d.getUTCDate();
    const base = w === 6 ? 22 : w === 0 ? 5 : w === 2 || w === 4 ? 11 : 6;
    const season = m === 10 || m === 11 ? 1.7 : m === 6 || m === 7 ? 0.75 : 1;
    const holiday = (m === 11 && date === 25) || (m === 0 && date === 1) || (m === 6 && date === 4);
    const closed = holiday || (w !== 6 && rand() < 0.14);
    out.push(closed ? 0 : Math.round(base * season * (0.55 + rand() * 0.9)));
  }
  return out.join(", ");
}

export const heatmapCalendarBlock: ComponentConfig<HeatmapCalendarProps> = {
  label: "Heatmap Calendar",
  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. Oct 2025–Oct 2026. Leave blank to hide." } },
    startDate: {
      type: "text",
      label: "First day",
      metadata: { help: "The date of the first value, as YYYY-MM-DD, e.g. 2025-10-05. Or bind it, e.g. {{ activity.start }}." },
    },
    values: {
      type: "textarea",
      label: "Daily values",
      metadata: { help: "One number per day, comma-separated, oldest first. Up to 371 days (53 weeks). Leave a day blank for no data." },
    },
    unit: { type: "text", label: "Unit", metadata: { help: "What each value counts, e.g. volunteer hours or check-ins." } },
    footnote: { type: "text", label: "Footnote", metadata: { help: "Where the data comes from. Leave blank to hide." } },
  },
  defaultProps: {
    title: "Volunteer activity",
    headingLevel: "h3",
    subtitle: "Oct 2025–Oct 2026, hours logged per day",
    startDate: "2025-10-05",
    values: sampleHours(),
    unit: "volunteer hours",
    footnote: "Sample data · Volunteer check-in kiosk",
  },
  render: ({ title, headingLevel, subtitle, startDate, values, unit, footnote }) => {
    const H = headingLevel || "h3";
    const start = parseDate(startDate);
    const days = splitList(values)
      .slice(0, MAX_DAYS)
      .map((v) => toNumber(v));
    const nums = days.filter((v): v is number => v !== null);
    const unitText = unit?.trim() || "";
    const withUnit = (n: number) => `${full.format(n)}${unitText ? ` ${unitText}` : ""}`;

    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 = "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">
              <rect x="3.5" y="5" width="17" height="15" rx="2" />
              <path d="M3.5 9.5h17M8 3v4M16 3v4" strokeLinecap="round" />
            </svg>
            <p className="text-sm font-medium text-neutral-900">No data yet</p>
            <p className="text-xs text-neutral-500">The calendar fills in once daily values are entered or the data source returns them.</p>
          </div>
          {foot}
        </div>
      );
    }

    const n = days.length;
    const offset = start !== null ? new Date(start).getUTCDay() : 0;
    const cols = Math.ceil((offset + n) / 7);
    const width = GUTTER + cols * STEP - (STEP - CELL);
    const height = TOP + 7 * STEP - (STEP - CELL);
    const max = Math.max(...nums, 0);
    const level = (v: number | null) => (v === null || v <= 0 || max <= 0 ? 0 : Math.min(4, Math.max(1, Math.ceil((v / max) * 4))));
    const dateOf = (i: number) => (start !== null ? new Date(start + i * DAY) : null);
    const describe = (i: number) => {
      const d = dateOf(i);
      return d ? longDate.format(d) : `Day ${i + 1}`;
    };

    const total = nums.reduce((sum, v) => sum + v, 0);
    const active = nums.filter((v) => v > 0).length;
    let busiest = -1;
    days.forEach((v, i) => {
      if (v !== null && (busiest < 0 || v > (days[busiest] as number))) busiest = i;
    });
    const busiestDate = dateOf(busiest);
    const busiestShort = busiestDate ? shortDate.format(busiestDate) : `Day ${busiest + 1}`;

    // Month labels sit over the week that holds each 1st; skip any that would crowd the last.
    const months: { col: number; text: string }[] = [];
    if (start !== null) {
      const firsts: { col: number; text: string }[] = [];
      for (let i = 0; i < n; i++) {
        const d = new Date(start + i * DAY);
        if (d.getUTCDate() === 1) firsts.push({ col: Math.floor((offset + i) / 7), text: monthName.format(d) });
      }
      if (!firsts.length || firsts[0].col >= 3) months.push({ col: 0, text: monthName.format(new Date(start)) });
      for (const f of firsts) if (f.col <= cols - 3 && (!months.length || f.col - months[months.length - 1].col >= 3)) months.push(f);
    }

    const first = start !== null ? shortDate.format(new Date(start)) : "day 1";
    const lastDate = dateOf(n - 1);
    const last = lastDate ? longDate.format(lastDate) : `day ${n}`;
    const summary = `${title ? `${title}. ` : ""}Calendar heatmap of ${n} days, ${first} to ${last}. Total ${withUnit(total)}; activity on ${active} of ${n} days; busiest day ${describe(busiest)} with ${withUnit(days[busiest] as number)}. Darker cells mean more activity.`;

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

        <dl className="mt-4 grid grid-cols-3 gap-4">
          <div className="min-w-0">
            <dt className="text-xs text-neutral-500">Total</dt>
            <dd className="mt-1 text-lg font-semibold tracking-tight text-neutral-950 tabular-nums sm:text-xl">{full.format(total)}</dd>
          </div>
          <div className="min-w-0">
            <dt className="text-xs text-neutral-500">Active days</dt>
            <dd className="mt-1 text-lg font-semibold tracking-tight text-neutral-950 tabular-nums sm:text-xl">
              {active}
              <span className="ml-1 text-xs font-normal tracking-normal text-neutral-500">of {n}</span>
            </dd>
          </div>
          <div className="min-w-0">
            <dt className="text-xs text-neutral-500">Busiest day</dt>
            <dd className="mt-1 text-lg font-semibold tracking-tight text-neutral-950 tabular-nums sm:text-xl">
              {busiestShort}
              <span className="ml-1 text-xs font-normal tracking-normal text-neutral-500">{full.format(days[busiest] as number)}</span>
            </dd>
          </div>
        </dl>
        {unitText ? <p className="mt-2 text-xs text-neutral-500">All figures in {unitText}.</p> : null}

        <div
          role="region"
          tabIndex={0}
          aria-label={`${title || "Activity"} calendar, scrolls sideways`}
          className="mt-5 -mx-1 flex flex-row-reverse relative overflow-x-auto rounded-md px-1 pb-2 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
        >
          <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} role="img" aria-label={summary} className="mr-auto max-w-none shrink-0">
            {months.map((m) => (
              <text key={`${m.col}${m.text}`} x={GUTTER + m.col * STEP} y={11} className="fill-neutral-500 text-xs">
                {m.text}
              </text>
            ))}
            {start !== null
              ? [
                  [1, "Mon"],
                  [3, "Wed"],
                  [5, "Fri"],
                ].map(([row, label]) => (
                  <text key={label} x={0} y={TOP + (row as number) * STEP + CELL - 1} className="fill-neutral-500 text-xs">
                    {label}
                  </text>
                ))
              : null}
            {days.map((v, i) => {
              const slot = offset + i;
              return (
                <rect
                  key={i}
                  x={GUTTER + Math.floor(slot / 7) * STEP}
                  y={TOP + (slot % 7) * STEP}
                  width={CELL}
                  height={CELL}
                  rx="2"
                  className={v === null ? "fill-white stroke-neutral-200" : LEVELS[level(v)]}
                >
                  <title>{`${describe(i)}: ${v === null ? "no data" : withUnit(v)}`}</title>
                </rect>
              );
            })}
          </svg>
        </div>

        <div className="mt-2 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-neutral-500">
          <p className="tabular-nums">
            {first} – {lastDate ? shortDate.format(lastDate) : `day ${n}`}
          </p>
          <div className="flex items-center gap-1.5" aria-hidden="true">
            <span className="mr-1">Less</span>
            {KEYS.map((k) => (
              <span key={k} className={`size-2.5 rounded-sm ${k}`} />
            ))}
            <span className="ml-1">More</span>
          </div>
        </div>
        <p className="sr-only">Darker cells mean more {unitText || "activity"}; the lightest cells are days with none.</p>

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