{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "contribution-heatmap",
  "title": "Contribution Heatmap",
  "description": "A year-long activity calendar in the style of a contribution graph: one square per day in week columns, five colour levels from quartiles, month and weekday labels, longest and current streaks, a best-day stat, day tooltips and a grid that fits any width.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/contribution-heatmap/contribution-heatmap.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type ChartTheme = \"dark\" | \"light\";\n\nexport interface ContributionDay {\n  /** ISO date, YYYY-MM-DD. */\n  date: string;\n  count: number;\n}\n\nexport interface ContributionHeatmapProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: ChartTheme;\n  title?: string;\n  subtitle?: string;\n  /** One entry per day with activity; missing days count as zero. */\n  data?: ContributionDay[];\n  /** Last day shown (YYYY-MM-DD); the grid covers the 53 weeks up to it. */\n  endDate?: string;\n  /** Colour of the busiest cells; quieter days blend it toward the empty-cell colour. */\n  color?: string;\n  /** Week starts on Sunday (GitHub style) or Monday. */\n  weekStart?: \"sunday\" | \"monday\";\n  /** Word for one unit of activity, used in the tooltip and stats. */\n  unit?: [singular: string, plural: string];\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#0E0E0E\",\n    border: \"rgba(255,255,255,0.08)\",\n    text: \"#F4F5F7\",\n    sub: \"rgba(255,255,255,0.55)\",\n    axis: \"rgba(255,255,255,0.45)\",\n    empty: \"#1A1B1F\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    ring: \"#F4F5F7\",\n    accent: \"#2EE6A8\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.07)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    axis: \"rgba(17,19,23,0.5)\",\n    empty: \"#EEEFF1\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    ring: \"#111317\",\n    accent: \"#0E9F6E\",\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\"];\n\nconst iso = (d: Date) => d.toISOString().slice(0, 10);\nconst parse = (s: string) => {\n  const [y, m, d] = s.split(\"-\").map(Number);\n  return new Date(Date.UTC(y, (m || 1) - 1, d || 1));\n};\n\n// Deterministic sample year (same on server and client): busier on weekdays, quieter in August and December.\nfunction sampleData(end: string): ContributionDay[] {\n  let seed = 11;\n  const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;\n  const out: ContributionDay[] = [];\n  const d = parse(end);\n  d.setUTCDate(d.getUTCDate() - 370);\n  for (let i = 0; i <= 370; i++) {\n    const dow = d.getUTCDay();\n    const month = d.getUTCMonth();\n    const weekend = dow === 0 || dow === 6;\n    const season = month === 7 || month === 11 ? 0.45 : 1;\n    const burst = Math.sin(i / 23) > 0.6 ? 1.8 : 1;\n    const p = (weekend ? 0.3 : 0.82) * season;\n    // The last week is always active, so the sample shows a running streak.\n    if (i > 364 || rnd() < p)\n      out.push({\n        date: iso(d),\n        count: Math.max(\n          1,\n          Math.round(rnd() * rnd() * 14 * burst * (weekend ? 0.5 : 1)),\n        ),\n      });\n    d.setUTCDate(d.getUTCDate() + 1);\n  }\n  return out;\n}\n\nconst DEFAULT_END = \"2025-12-31\";\nconst DEFAULT_DATA = sampleData(DEFAULT_END);\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\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\n/** 0 → 1 (linear) once the element scrolls into view; 1 straight away with reduced motion. */\nfunction useReveal(\n  ref: React.RefObject<HTMLElement | null>,\n  reduce: boolean,\n  duration = 1000,\n) {\n  const [t, setT] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || reduce) return;\n    let raf = 0;\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        io.disconnect();\n        const start = performance.now();\n        const tick = (now: number) => {\n          const k = Math.min(1, (now - start) / duration);\n          setT(k);\n          if (k < 1) raf = requestAnimationFrame(tick);\n        };\n        raf = requestAnimationFrame(tick);\n      },\n      { threshold: 0.2 },\n    );\n    io.observe(el);\n    return () => {\n      io.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [ref, reduce, duration]);\n  return reduce ? 1 : t;\n}\n\nfunction mix(a: string, b: string, t: number) {\n  const p = (h: string) => {\n    const s = h.replace(\"#\", \"\");\n    const f =\n      s.length === 3\n        ? s\n            .split(\"\")\n            .map((c) => c + c)\n            .join(\"\")\n        : s;\n    return [0, 2, 4].map((i) => parseInt(f.slice(i, i + 2), 16));\n  };\n  const [x, y] = [p(a), p(b)];\n  return `rgb(${x.map((v, i) => Math.round(v + (y[i] - v) * t)).join(\",\")})`;\n}\n\nconst GAP = 3;\nconst LEFT = 30;\nconst TOP = 18;\n\nexport function ContributionHeatmap({\n  theme = \"dark\",\n  title = \"Contributions\",\n  subtitle,\n  data = DEFAULT_DATA,\n  endDate = DEFAULT_END,\n  color,\n  weekStart = \"sunday\",\n  unit = [\"contribution\", \"contributions\"],\n  className,\n  style,\n  ...props\n}: ContributionHeatmapProps) {\n  const pal = PALETTES[theme];\n  const accent = color ?? pal.accent;\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(boxRef);\n  const reveal = useReveal(boxRef, reduce);\n  const [active, setActive] = React.useState<{ w: number; d: number } | null>(\n    null,\n  );\n\n  const counts = React.useMemo(\n    () => new Map(data.map((d) => [d.date, d.count])),\n    [data],\n  );\n  // Cells fit the width between 10 and 15px; when even 10px won't fit, the oldest weeks drop off.\n  const maxWeeks = 53;\n  const fitCell = width ? (width - LEFT) / maxWeeks - GAP : 12;\n  const cell = Math.max(10, Math.min(15, fitCell));\n  const weeks = width\n    ? Math.min(maxWeeks, Math.floor((width - LEFT + GAP) / (cell + GAP)))\n    : maxWeeks;\n  const offset = weekStart === \"monday\" ? 1 : 0;\n\n  const grid = React.useMemo(() => {\n    const end = parse(endDate);\n    const endDow = (end.getUTCDay() - offset + 7) % 7;\n    const start = new Date(end);\n    start.setUTCDate(end.getUTCDate() - endDow - (weeks - 1) * 7);\n    const cols: {\n      date: string;\n      count: number;\n      month: number;\n      day: number;\n      future: boolean;\n    }[][] = [];\n    const d = new Date(start);\n    for (let w = 0; w < weeks; w++) {\n      const col = [];\n      for (let k = 0; k < 7; k++) {\n        const key = iso(d);\n        col.push({\n          date: key,\n          count: counts.get(key) ?? 0,\n          month: d.getUTCMonth(),\n          day: d.getUTCDate(),\n          future: d > end,\n        });\n        d.setUTCDate(d.getUTCDate() + 1);\n      }\n      cols.push(col);\n    }\n    return cols;\n  }, [endDate, weeks, offset, counts]);\n\n  const cellsIn = grid.flat().filter((c) => !c.future);\n  // Levels from quartiles of the active days, like GitHub, so one huge day doesn't wash out the rest.\n  const nonzero = cellsIn\n    .map((c) => c.count)\n    .filter((c) => c > 0)\n    .sort((a, b) => a - b);\n  const q = (p: number) =>\n    nonzero[Math.min(nonzero.length - 1, Math.floor(p * nonzero.length))] ?? 1;\n  const cuts = [q(0.25), q(0.5), q(0.75)];\n  const level = (c: number) =>\n    c <= 0 ? 0 : c <= cuts[0] ? 1 : c <= cuts[1] ? 2 : c <= cuts[2] ? 3 : 4;\n  const shades = [\n    pal.empty,\n    mix(pal.empty, accent, 0.3),\n    mix(pal.empty, accent, 0.52),\n    mix(pal.empty, accent, 0.76),\n    accent,\n  ];\n\n  const total = cellsIn.reduce((s, c) => s + c.count, 0);\n  let longest = 0;\n  let run = 0;\n  for (const c of cellsIn) {\n    run = c.count > 0 ? run + 1 : 0;\n    longest = Math.max(longest, run);\n  }\n  let current = 0;\n  for (let i = cellsIn.length - 1; i >= 0 && cellsIn[i].count > 0; i--)\n    current++;\n  const busiest = cellsIn.reduce(\n    (b, c) => (c.count > b.count ? c : b),\n    cellsIn[0] ?? { date: endDate, count: 0 },\n  );\n  const word = (n: number) => (n === 1 ? unit[0] : unit[1]);\n  const fmtDate = (s: string, long = false) => {\n    const d = parse(s);\n    return `${long ? `${DAYS[d.getUTCDay()]}, ` : \"\"}${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}${long ? `, ${d.getUTCFullYear()}` : \"\"}`;\n  };\n\n  const gridW = LEFT + weeks * (cell + GAP) - GAP;\n  const gridH = TOP + 7 * (cell + GAP) - GAP;\n  // A month label over the first week column that starts in that month; drop one that would crowd the next.\n  const starts = grid\n    .map((col, w) => ({ w, m: col[0].month }))\n    .filter((x, w, arr) => w === 0 || arr[w - 1].m !== x.m);\n  const monthLabels = starts.filter(\n    (x, i) => !(i === 0 && starts[1] && starts[1].w - x.w < 3),\n  );\n  const dayRows = weekStart === \"monday\" ? [0, 2, 4] : [1, 3, 5];\n\n  const onKey = (event: React.KeyboardEvent) => {\n    const moves: Record<string, [number, number]> = {\n      ArrowRight: [1, 0],\n      ArrowLeft: [-1, 0],\n      ArrowDown: [0, 1],\n      ArrowUp: [0, -1],\n    };\n    if (event.key === \"Escape\") return setActive(null);\n    const mv = moves[event.key];\n    if (!mv) return;\n    event.preventDefault();\n    setActive((a) => {\n      const base = a ?? { w: weeks - 1, d: 0 };\n      if (!a) return base;\n      const w = Math.max(0, Math.min(weeks - 1, base.w + mv[0]));\n      const d = Math.max(0, Math.min(6, base.d + mv[1]));\n      return grid[w][d].future ? base : { w, d };\n    });\n  };\n  const ac = active ? grid[active.w]?.[active.d] : null;\n  const ax = active ? LEFT + active.w * (cell + GAP) + cell / 2 : 0;\n  const ay = active ? TOP + active.d * (cell + GAP) : 0;\n  const summary = `${title}: ${total.toLocaleString(\"en-US\")} ${word(total)} from ${fmtDate(cellsIn[0]?.date ?? endDate, true)} to ${fmtDate(endDate, true)}. Longest streak ${longest} days, current streak ${current} days, busiest day ${fmtDate(busiest.date, true)} with ${busiest.count}.`;\n\n  return (\n    <div\n      className={cn(\n        \"w-full overflow-hidden rounded-[20px] p-5 sm:p-7\",\n        className,\n      )}\n      style={{\n        background: pal.card,\n        border: `1px solid ${pal.border}`,\n        color: pal.text,\n        fontFamily: \"Inter, -apple-system, BlinkMacSystemFont, sans-serif\",\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-4\">\n        <div className=\"min-w-0\">\n          <p className=\"text-[15px] font-semibold tracking-[-0.01em]\">\n            {title}\n          </p>\n          <p\n            className=\"mt-1 text-[12.5px] tabular-nums\"\n            style={{ color: pal.sub }}\n          >\n            {subtitle ??\n              `${total.toLocaleString(\"en-US\")} ${word(total)} in the last year`}\n          </p>\n        </div>\n        <div className=\"flex gap-6 text-right\">\n          {(\n            [\n              [`${longest} days`, \"Longest streak\"],\n              [`${current} days`, \"Current streak\"],\n              [`${busiest.count}`, `Best day · ${fmtDate(busiest.date)}`],\n            ] as const\n          ).map(([v, k]) => (\n            <div key={k}>\n              <p className=\"text-[18px] leading-tight font-semibold tracking-[-0.02em] tabular-nums\">\n                {v}\n              </p>\n              <p className=\"mt-0.5 text-[11px]\" style={{ color: pal.sub }}>\n                {k}\n              </p>\n            </div>\n          ))}\n        </div>\n      </div>\n\n      <div\n        ref={boxRef}\n        role=\"img\"\n        aria-label={summary}\n        tabIndex={0}\n        onKeyDown={onKey}\n        onBlur={() => setActive(null)}\n        onPointerLeave={(e) => e.pointerType === \"mouse\" && setActive(null)}\n        className=\"relative mt-5 w-full rounded-lg outline-none focus-visible:ring-2\"\n        style={{ height: gridH + 4 }}\n      >\n        {width > 0 && (\n          <svg\n            width={gridW}\n            height={gridH + 4}\n            className=\"block overflow-visible\"\n            aria-hidden=\"true\"\n          >\n            {monthLabels.map(({ w, m }) => (\n              <text\n                key={`m${w}`}\n                x={LEFT + w * (cell + GAP)}\n                y={11}\n                fontSize={11}\n                fill={pal.axis}\n              >\n                {MONTHS[m]}\n              </text>\n            ))}\n            {dayRows.map((d) => (\n              <text\n                key={`d${d}`}\n                x={0}\n                y={TOP + d * (cell + GAP) + cell - 2}\n                fontSize={10.5}\n                fill={pal.axis}\n              >\n                {DAYS[(d + offset) % 7]}\n              </text>\n            ))}\n            {grid.map((col, w) => {\n              // Weeks fade in from left to right.\n              const k = Math.min(\n                1,\n                Math.max(0, reveal * 1.6 - (w / weeks) * 0.6),\n              );\n              return col.map((c, d) =>\n                c.future ? null : (\n                  <rect\n                    key={c.date}\n                    x={LEFT + w * (cell + GAP)}\n                    y={TOP + d * (cell + GAP)}\n                    width={cell}\n                    height={cell}\n                    rx={Math.max(2, cell / 5)}\n                    fill={shades[level(c.count)]}\n                    opacity={\n                      k *\n                      (active && active.w === w && active.d === d\n                        ? 1\n                        : active\n                          ? 0.75\n                          : 1)\n                    }\n                    stroke={\n                      active && active.w === w && active.d === d\n                        ? pal.ring\n                        : \"none\"\n                    }\n                    strokeWidth={1.5}\n                    onPointerEnter={() => setActive({ w, d })}\n                    onPointerDown={() => setActive({ w, d })}\n                  />\n                ),\n              );\n            })}\n          </svg>\n        )}\n        {ac && (\n          <div\n            className=\"pointer-events-none absolute z-10 -translate-x-1/2 -translate-y-full rounded-lg px-2.5 py-1.5 text-[12px] whitespace-nowrap shadow-xl\"\n            style={{\n              left: Math.max(90, Math.min(width - 90, ax)),\n              top: ay - 6,\n              background: pal.tip,\n              border: `1px solid ${pal.tipBorder}`,\n              backdropFilter: \"blur(8px)\",\n            }}\n          >\n            <span className=\"font-semibold tabular-nums\">\n              {ac.count ? `${ac.count} ${word(ac.count)}` : `No ${unit[1]}`}\n            </span>\n            <span style={{ color: pal.sub }}> on {fmtDate(ac.date, true)}</span>\n          </div>\n        )}\n      </div>\n\n      <div\n        className=\"mt-3 flex flex-wrap items-center justify-between gap-3 text-[11.5px]\"\n        style={{ color: pal.sub }}\n      >\n        <span>\n          {weeks < maxWeeks\n            ? `Last ${weeks} weeks`\n            : `${fmtDate(cellsIn[0]?.date ?? endDate)}, ${parse(cellsIn[0]?.date ?? endDate).getUTCFullYear()} – ${fmtDate(endDate)}, ${parse(endDate).getUTCFullYear()}`}\n        </span>\n        <span className=\"flex items-center gap-1.5\">\n          Less\n          {shades.map((s, i) => (\n            <span\n              key={i}\n              className=\"inline-block rounded-[3px]\"\n              style={{ width: cell, height: cell, background: s }}\n            />\n          ))}\n          More\n        </span>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}