{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar-pulse-heatmap",
  "title": "Calendar Pulse Heatmap",
  "description": "A year of activity in twelve dot calendars, with intensity levels, day-by-day replay, hover ripples and full keyboard navigation.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/calendar-pulse-heatmap/calendar-pulse-heatmap.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface PulseDay {\n  /** ISO date, YYYY-MM-DD. */\n  date: string;\n  value: number;\n}\n\nexport interface CalendarPulseHeatmapProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  subtitle?: string;\n  /** Days with activity. Days left out count as zero. */\n  data?: PulseDay[];\n  /** The calendar year on show. */\n  year?: number;\n  /** Colour of the busiest days. */\n  color?: string;\n  /** Seconds a replay of the year takes. */\n  replaySeconds?: number;\n  /** Words after the value in the readout. */\n  unit?: [singular: string, plural: string];\n  formatValue?: (value: number) => string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#08090A\",\n    surface: \"#0F1011\",\n    border: \"rgba(255,255,255,0.08)\",\n    grid: \"rgba(255,255,255,0.05)\",\n    text: \"#F7F8F8\",\n    soft: \"#D0D6E0\",\n    sub: \"#8A8F98\",\n    faint: \"#62666D\",\n    tip: \"#161718\",\n    tipShadow: \"0 4px 24px rgba(0,0,0,0.4)\",\n    chip: \"rgba(255,255,255,0.05)\",\n    chipOn: \"rgba(255,255,255,0.1)\",\n    accent: \"#5E6AD2\",\n    btn: \"#E5E5E6\",\n    btnText: \"#08090A\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    surface: \"#F7F8F8\",\n    border: \"rgba(8,9,10,0.08)\",\n    grid: \"rgba(8,9,10,0.06)\",\n    text: \"#08090A\",\n    soft: \"#3C3F44\",\n    sub: \"#62666D\",\n    faint: \"#8A8F98\",\n    tip: \"#FFFFFF\",\n    tipShadow: \"0 3px 12px rgba(8,9,10,0.09)\",\n    chip: \"rgba(8,9,10,0.04)\",\n    chipOn: \"#FFFFFF\",\n    accent: \"#5E6AD2\",\n    btn: \"#08090A\",\n    btnText: \"#F7F8F8\",\n  },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\n\nconst CARD_FONT =\n  '\"Inter Variable\", Inter, \"SF Pro Display\", -apple-system, BlinkMacSystemFont, sans-serif';\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** The chart is drawn at its real width, so its text stays the same size on a phone. */\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(700);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(Math.max(240, Math.round(entry.contentRect.width))),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\nfunction Stat({\n  value,\n  label,\n  pal,\n}: {\n  value: string;\n  label: string;\n  pal: Palette;\n}) {\n  return (\n    <div className=\"text-left sm:text-right\">\n      <p className=\"m-0 text-[18px] leading-[1.2] font-[510] tracking-[-0.018em] tabular-nums\">\n        {value}\n      </p>\n      <p\n        className=\"m-0 mt-0.5 text-[12px] tracking-[-0.011em]\"\n        style={{ color: pal.sub }}\n      >\n        {label}\n      </p>\n    </div>\n  );\n}\n\nfunction Tip({\n  x,\n  y,\n  width,\n  pal,\n  children,\n}: {\n  x: number;\n  y: number;\n  width: number;\n  pal: Palette;\n  children: React.ReactNode;\n}) {\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute z-10 -translate-x-1/2 rounded-lg px-2.5 py-1.5 text-[12px] tracking-[-0.011em] whitespace-nowrap\"\n      style={{\n        left: Math.max(110, Math.min(width - 110, x)),\n        top: Math.max(0, y - 42),\n        background: pal.tip,\n        color: pal.sub,\n        boxShadow: `inset 0 0 0 1px ${pal.border}, ${pal.tipShadow}`,\n      }}\n    >\n      {children}\n    </div>\n  );\n}\n\nconst MONTHS = [\n  \"Jan\",\n  \"Feb\",\n  \"Mar\",\n  \"Apr\",\n  \"May\",\n  \"Jun\",\n  \"Jul\",\n  \"Aug\",\n  \"Sep\",\n  \"Oct\",\n  \"Nov\",\n  \"Dec\",\n];\nconst DAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\nconst DAY = 86400000;\n\n/** A believable year: a slow season, quiet weekends and integer noise, so server and client agree. */\nfunction makeYear(year: number): PulseDay[] {\n  const season = [52, 60, 72, 80, 88, 70, 48, 44, 84, 96, 100, 66];\n  const start = Date.UTC(year, 0, 1);\n  const out: PulseDay[] = [];\n  let state = 73;\n  for (let t = start; t < Date.UTC(year + 1, 0, 1); t += DAY) {\n    const d = new Date(t);\n    state = (state * 9301 + 49297) % 233280;\n    const noise = state / 233280;\n    const weekend = d.getUTCDay() % 6 === 0 ? 0.2 : 1;\n    const value = season[d.getUTCMonth()] * weekend * (noise * 1.5 - 0.1);\n    if (value > 3) {\n      out.push({\n        date: d.toISOString().slice(0, 10),\n        value: Math.round(value),\n      });\n    }\n  }\n  return out;\n}\n\nconst YEAR = 2025;\nconst FORMAT = (n: number) => Math.round(n).toLocaleString(\"en-US\");\n\n/** Dot scale and strength for each of the five levels. */\nconst LEVELS = [\n  { scale: 0.34, opacity: 0.16 },\n  { scale: 0.5, opacity: 0.38 },\n  { scale: 0.68, opacity: 0.6 },\n  { scale: 0.84, opacity: 0.8 },\n  { scale: 1, opacity: 1 },\n];\n\ninterface Cell {\n  key: string;\n  label: string;\n  value: number;\n  level: number;\n  /** Position in the month grid, for the ripple. */\n  col: number;\n  row: number;\n  index: number;\n}\n\nexport function CalendarPulseHeatmap({\n  theme = \"dark\",\n  title = \"Year in sessions\",\n  subtitle = \"One dot per day. Point at a day, or replay the whole year.\",\n  data,\n  year: requestedYear = YEAR,\n  color,\n  replaySeconds = 4,\n  unit = [\"session\", \"sessions\"],\n  formatValue = FORMAT,\n  className,\n  style,\n  ...props\n}: CalendarPulseHeatmapProps) {\n  const pal = PALETTES[theme];\n  const year =\n    Number.isInteger(requestedYear) &&\n    requestedYear >= 100 &&\n    requestedYear < 9999\n      ? requestedYear\n      : YEAR;\n  const input = React.useMemo(() => data ?? makeYear(year), [data, year]);\n  const [focusedDate, setFocusedDate] = React.useState<string | null>(null);\n\n  const accent = color ?? pal.accent;\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(boxRef);\n  const dotRefs = React.useRef<(HTMLSpanElement | null)[]>([]);\n  const raf = React.useRef(0);\n  const [active, setActive] = React.useState<{\n    cell: Cell;\n    x: number;\n    y: number;\n  } | null>(null);\n  const [replaying, setReplaying] = React.useState(false);\n\n  const months = React.useMemo(() => {\n    const counts = new Map<string, number>();\n    for (const day of input) {\n      if (\n        !Number.isFinite(day.value) ||\n        day.value < 0 ||\n        !day.date.startsWith(`${year}-`) ||\n        !/^\\d{4}-\\d{2}-\\d{2}$/.test(day.date)\n      )\n        continue;\n      const parsed = new Date(`${day.date}T00:00:00Z`);\n      if (\n        !Number.isFinite(parsed.getTime()) ||\n        parsed.toISOString().slice(0, 10) !== day.date\n      )\n        continue;\n      counts.set(day.date, (counts.get(day.date) ?? 0) + day.value);\n    }\n    const sorted = [...counts.values()]\n      .filter((value) => value > 0)\n      .sort((a, b) => a - b);\n    const at = (p: number) => sorted[Math.floor(p * (sorted.length - 1))] ?? 0;\n    const cuts = [at(0.25), at(0.5), at(0.8)];\n    let index = 0;\n    return MONTHS.map((name, m) => {\n      const first = new Date(Date.UTC(year, m, 1));\n      const length = new Date(Date.UTC(year, m + 1, 0)).getUTCDate();\n      const lead = (first.getUTCDay() + 6) % 7;\n      const cells: Cell[] = Array.from({ length }, (_, d) => {\n        const when = new Date(Date.UTC(year, m, d + 1));\n        const key = when.toISOString().slice(0, 10);\n        const value = counts.get(key) ?? 0;\n        const slot = lead + d;\n        return {\n          key,\n          label: `${DAYS[when.getUTCDay()]}, ${name} ${d + 1}`,\n          value,\n          level: value ? 1 + cuts.filter((c) => value > c).length : 0,\n          col: slot % 7,\n          row: Math.floor(slot / 7),\n          index: index++,\n        };\n      });\n      return { name, lead, cells };\n    });\n  }, [input, year]);\n\n  const cells = React.useMemo(() => months.flatMap((m) => m.cells), [months]);\n  const total = cells.reduce((n, c) => n + c.value, 0);\n  const best = cells.reduce(\n    (top, c) => (c.value > top.value ? c : top),\n    cells[0],\n  );\n  const monthTotals = months.map((m) =>\n    m.cells.reduce((n, c) => n + c.value, 0),\n  );\n  const topMonth = monthTotals.indexOf(Math.max(...monthTotals));\n\n  const look = React.useCallback((cell: Cell) => {\n    const step = LEVELS[Math.min(cell.level, 4)];\n    return {\n      transform: `scale(${step.scale})`,\n      opacity: cell.level ? step.opacity : 0.14,\n    };\n  }, []);\n\n  // A ring of dots swells outward from the day under the pointer, within its month.\n  const ripple = (cell: Cell, month: Cell[]) => {\n    if (reduce) return;\n    month.forEach((c) => {\n      const el = dotRefs.current[c.index];\n      if (!el) return;\n      const distance = Math.sqrt(\n        (c.col - cell.col) ** 2 + (c.row - cell.row) ** 2,\n      );\n      if (distance > 4) return;\n      const base = look(c);\n      el.animate(\n        [\n          base,\n          {\n            transform: \"scale(1.25)\",\n            opacity: Math.min(1, base.opacity + 0.45),\n          },\n          base,\n        ],\n        { duration: 420, delay: distance * 55, easing: \"ease-out\" },\n      );\n    });\n  };\n\n  // A user-started sweep. Cleanup restores each dot on data changes or unmount.\n  React.useEffect(() => {\n    if (!replaying) return;\n    const length =\n      (Number.isFinite(replaySeconds) ? Math.max(0.2, replaySeconds) : 4) *\n      1000;\n    let start = 0;\n    const restore = () =>\n      cells.forEach((c) => {\n        const el = dotRefs.current[c.index];\n        if (!el) return;\n        const base = look(c);\n        el.style.transform = base.transform;\n        el.style.opacity = String(base.opacity);\n      });\n    const frame = (now: number) => {\n      start = start || now;\n      const p = reduce ? 1 : Math.min(1, (now - start) / length);\n      const front = p * (cells.length + 14);\n      cells.forEach((c) => {\n        const el = dotRefs.current[c.index];\n        if (!el) return;\n        const base = look(c);\n        const behind = front - c.index;\n        if (behind < 0) {\n          el.style.transform = \"scale(0.3)\";\n          el.style.opacity = \"0.08\";\n        } else if (behind < 14) {\n          const glow = 1 - behind / 14;\n          el.style.transform = `scale(${(1 + glow * 0.25).toFixed(3)})`;\n          el.style.opacity = `${Math.max(base.opacity, glow).toFixed(3)}`;\n        } else {\n          el.style.transform = base.transform;\n          el.style.opacity = String(base.opacity);\n        }\n      });\n      if (p < 1) raf.current = requestAnimationFrame(frame);\n      else {\n        restore();\n        setReplaying(false);\n      }\n    };\n    raf.current = requestAnimationFrame(frame);\n    return () => {\n      cancelAnimationFrame(raf.current);\n      restore();\n    };\n  }, [replaying, replaySeconds, cells, look, reduce]);\n\n  return (\n    <section\n      className={`w-full rounded-2xl p-5 sm:p-6 ${className ?? \"\"}`}\n      style={{\n        background: pal.card,\n        boxShadow: `inset 0 0 0 1px ${pal.border}`,\n        color: pal.text,\n        fontFamily: CARD_FONT,\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-x-8 gap-y-3\">\n        <div>\n          <h3 className=\"m-0 text-[17px] leading-[1.33] font-[590] tracking-[-0.012em]\">\n            {title}\n          </h3>\n          <p\n            className=\"m-0 mt-0.5 text-[13px] tracking-[-0.011em]\"\n            style={{ color: pal.sub }}\n          >\n            {subtitle}\n          </p>\n        </div>\n        <div className=\"flex flex-wrap gap-x-7 gap-y-3\">\n          <Stat\n            value={formatValue(total)}\n            label={`Total ${unit[1]}`}\n            pal={pal}\n          />\n          <Stat\n            value={best?.value > 0 ? best.label.split(\", \")[1] : \"—\"}\n            label=\"Best day\"\n            pal={pal}\n          />\n          <Stat\n            value={monthTotals[topMonth] > 0 ? months[topMonth].name : \"—\"}\n            label=\"Best month\"\n            pal={pal}\n          />\n        </div>\n      </div>\n\n      <div\n        ref={boxRef}\n        className=\"@container relative mt-5\"\n        onPointerLeave={() => setActive(null)}\n      >\n        <div className=\"grid grid-cols-3 gap-x-5 gap-y-3 @[640px]:grid-cols-6 @[640px]:gap-x-6\">\n          {months.map((m) => (\n            <div key={m.name}>\n              <p\n                className=\"m-0 mb-1.5 text-[11px] tracking-[-0.011em]\"\n                style={{ color: pal.faint }}\n              >\n                {m.name}\n              </p>\n              <div className=\"grid grid-cols-7 gap-px\">\n                {Array.from({ length: m.lead }, (_, i) => (\n                  <span key={i} />\n                ))}\n                {m.cells.map((c) => (\n                  <button\n                    key={c.key}\n                    type=\"button\"\n                    aria-label={`${c.label}: ${formatValue(c.value)} ${unit[c.value === 1 ? 0 : 1]}`}\n                    onPointerEnter={(e) => {\n                      const box = boxRef.current?.getBoundingClientRect();\n                      const r = e.currentTarget.getBoundingClientRect();\n                      setActive({\n                        cell: c,\n                        x: r.left + r.width / 2 - (box?.left ?? 0),\n                        y: r.top - (box?.top ?? 0),\n                      });\n                      ripple(c, m.cells);\n                    }}\n                    onFocus={(e) => {\n                      setFocusedDate(c.key);\n                      const box = boxRef.current?.getBoundingClientRect();\n                      const r = e.currentTarget.getBoundingClientRect();\n                      setActive({\n                        cell: c,\n                        x: r.left + r.width / 2 - (box?.left ?? 0),\n                        y: r.top - (box?.top ?? 0),\n                      });\n                    }}\n                    onBlur={() => setActive(null)}\n                    data-day-index={c.index}\n                    onClick={() => ripple(c, m.cells)}\n                    onKeyDown={(event) => {\n                      const delta: Record<string, number> = {\n                        ArrowLeft: -1,\n                        ArrowRight: 1,\n                        ArrowUp: -7,\n                        ArrowDown: 7,\n                      };\n                      if (\n                        !(event.key in delta) &&\n                        event.key !== \"Home\" &&\n                        event.key !== \"End\"\n                      )\n                        return;\n                      event.preventDefault();\n                      const next =\n                        event.key === \"Home\"\n                          ? 0\n                          : event.key === \"End\"\n                            ? cells.length - 1\n                            : Math.max(\n                                0,\n                                Math.min(\n                                  cells.length - 1,\n                                  c.index + delta[event.key],\n                                ),\n                              );\n                      event.currentTarget\n                        .closest(\"section\")\n                        ?.querySelector<HTMLButtonElement>(\n                          `[data-day-index=\"${next}\"]`,\n                        )\n                        ?.focus();\n                    }}\n                    tabIndex={\n                      focusedDate === c.key ||\n                      ((!focusedDate ||\n                        !cells.some((day) => day.key === focusedDate)) &&\n                        c.index === 0)\n                        ? 0\n                        : -1\n                    }\n                    className=\"grid aspect-square cursor-pointer place-items-center rounded-[3px] p-0 outline-none focus-visible:ring-2\"\n                    style={{\n                      boxShadow:\n                        active?.cell.key === c.key\n                          ? `inset 0 0 0 1px ${pal.text}`\n                          : undefined,\n                    }}\n                  >\n                    <span\n                      ref={(el) => {\n                        dotRefs.current[c.index] = el;\n                      }}\n                      className=\"block size-full rounded-full\"\n                      style={{\n                        background: c.level ? accent : pal.sub,\n                        ...look(c),\n                      }}\n                    />\n                  </button>\n                ))}\n              </div>\n            </div>\n          ))}\n        </div>\n\n        {active && (\n          <Tip x={active.x} y={active.y + 8} width={width} pal={pal}>\n            <span className=\"font-[510]\" style={{ color: pal.text }}>\n              {formatValue(active.cell.value)}{\" \"}\n              {unit[active.cell.value === 1 ? 0 : 1]}\n            </span>{\" \"}\n            on {active.cell.label}\n          </Tip>\n        )}\n      </div>\n\n      <div className=\"mt-4 flex flex-wrap items-center justify-between gap-2\">\n        <button\n          type=\"button\"\n          onClick={() => setReplaying(true)}\n          disabled={replaying}\n          className=\"flex h-8 min-w-[92px] cursor-pointer items-center justify-center gap-1.5 rounded-full px-3.5 text-[13px] font-[510] tracking-[-0.011em] transition-opacity hover:opacity-90 disabled:cursor-default disabled:opacity-60\"\n          style={{ background: pal.btn, color: pal.btnText }}\n        >\n          <svg\n            width=\"10\"\n            height=\"10\"\n            viewBox=\"0 0 10 10\"\n            fill=\"currentColor\"\n            aria-hidden=\"true\"\n          >\n            <path d=\"M2 1.1v7.8c0 .4.4.6.7.4l6-3.9c.3-.2.3-.6 0-.8l-6-3.9c-.3-.2-.7 0-.7.4Z\" />\n          </svg>\n          Replay {year}\n        </button>\n        <div\n          className=\"flex items-center gap-1 text-[12px]\"\n          style={{ color: pal.sub }}\n        >\n          <span className=\"mr-1\">Less</span>\n          {LEVELS.map((l) => (\n            <span\n              key={l.scale}\n              className=\"grid size-3 place-items-center\"\n              aria-hidden=\"true\"\n            >\n              <span\n                className=\"block size-full rounded-full\"\n                style={{\n                  background: accent,\n                  transform: `scale(${l.scale})`,\n                  opacity: l.opacity,\n                }}\n              />\n            </span>\n          ))}\n          <span className=\"ml-1\">More</span>\n        </div>\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}