{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "heatmap",
  "title": "Heatmap",
  "description": "Calendar (GitHub-style) or matrix heatmap on one hue with cells that pop in column by column, a tooltip, arrow-key navigation that scrolls the calendar along, and a Less–More scale.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/charts/heatmap.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens } from \"@/lib/goodui-motion\"\n\nconst CSS = `\n.pc-heatmap-cell{transform-box:fill-box;transform-origin:center}\n.pc-heatmap[data-inview=false] .pc-heatmap-cell{opacity:0}\n.pc-heatmap[data-inview=true] .pc-heatmap-cell{animation:pc-heatmap-in .45s var(--pc-ease-out) both;animation-delay:calc(var(--d) * 14ms)}\n@keyframes pc-heatmap-in{from{opacity:0;transform:scale(.55)}to{opacity:1;transform:none}}\n@media (prefers-reduced-motion:reduce){.pc-heatmap .pc-heatmap-cell{animation:none!important;opacity:1!important}}\n`\n\nexport type HeatmapCell = {\n  /** ISO date, e.g. \"2026-10-28\". */\n  date: string\n  value: number\n}\n\nexport type HeatmapLabels = {\n  less: string\n  more: string\n  /** Announced for the active cell. */\n  cell: (label: string, value: string) => string\n  summary: (name: string, cells: number, max: string) => string\n  noData: string\n}\nconst DEFAULT_LABELS: HeatmapLabels = {\n  less: \"Less\",\n  more: \"More\",\n  cell: (label, value) => `${label}: ${value}`,\n  summary: (name, cells, max) => `${name ? name + \": \" : \"\"}${cells} cells, highest ${max}`,\n  noData: \"No data\",\n}\n\nexport type HeatmapProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n  /** calendar: weeks as columns, weekdays as rows (needs data). matrix: rows × columns (needs rows, columns, values). */\n  mode?: \"calendar\" | \"matrix\"\n  /** Calendar values by ISO date. Days without an entry count as 0. */\n  data?: HeatmapCell[]\n  /** Last day of the calendar (ISO). Defaults to the latest date in data. */\n  end?: string\n  /** Weeks shown in calendar mode. */\n  weeks?: number\n  /** First weekday: 1 Monday (default) or 0 Sunday. */\n  weekStart?: 0 | 1\n  /** Matrix row labels. */\n  rows?: string[]\n  /** Matrix column labels. */\n  columns?: string[]\n  /** Matrix values, values[row][column]. */\n  values?: number[][]\n  /** Chart name for screen readers. */\n  title?: React.ReactNode\n  /** One hue; intensity is its opacity in `steps` levels. Defaults to the theme's first chart color. */\n  color?: string\n  /** Number of intensity levels above zero. */\n  steps?: number\n  /** linear splits 0..max evenly; quantile gives each level the same number of cells. */\n  scale?: \"linear\" | \"quantile\"\n  /** Cell size in px (calendar) or minimum cell size (matrix, cells stretch to the width). */\n  cellSize?: number\n  cellGap?: number\n  /** Less … More scale under the chart. */\n  legend?: boolean\n  format?: Intl.NumberFormatOptions\n  locale?: string\n  formatValue?: (value: number) => string\n  /** Formats calendar dates for the tooltip and screen readers. */\n  formatDate?: (date: Date) => string\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<HeatmapLabels>\n}\n\nfunction useReduce() {\n  const prefers = useReducedMotion()\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => setMounted(true), [])\n  return mounted && !!prefers\n}\n\nfunction useInView(ref: React.RefObject<Element | null>, threshold = 0.2) {\n  const [inView, setInView] = React.useState(false)\n  React.useEffect(() => {\n    const el = ref.current\n    if (!el || inView) return\n    if (typeof IntersectionObserver === \"undefined\") {\n      setInView(true)\n      return\n    }\n    const io = new IntersectionObserver(\n      ([e]) => {\n        if (e?.isIntersecting) {\n          setInView(true)\n          io.disconnect()\n        }\n      },\n      { threshold },\n    )\n    io.observe(el)\n    return () => io.disconnect()\n  }, [ref, inView, threshold])\n  return inView\n}\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState<number | null>(null)\n  React.useLayoutEffect(() => {\n    const el = ref.current\n    if (!el) return\n    // A hidden parent (display:none) measures 0: keep the last real width instead of collapsing the chart.\n    const measure = () => {\n      const w = Math.round(el.clientWidth)\n      if (w > 0) setWidth(Math.max(120, w))\n    }\n    measure()\n    const ro = new ResizeObserver(measure)\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [ref])\n  return width\n}\n\n// Local-time parsing of ISO dates, so \"2026-10-28\" is Oct 28 in every time zone.\nfunction parseDate(s: string) {\n  const m = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(s)\n  return m ? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])) : new Date(s)\n}\nconst pad = (n: number) => String(n).padStart(2, \"0\")\nconst iso = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`\nconst addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n)\n\ntype Cell = { id: number; col: number; row: number; value: number; label: string; has: boolean }\n\n/** Calendar (GitHub-style) or matrix heatmap on one hue, with cells that pop in by column, a tooltip, arrow-key navigation and a Less–More scale. */\nexport function Heatmap({\n  mode = \"calendar\",\n  data,\n  end,\n  weeks = 26,\n  weekStart = 1,\n  rows,\n  columns,\n  values,\n  title,\n  color = \"var(--chart-1)\",\n  steps = 4,\n  scale = \"linear\",\n  cellSize = 12,\n  cellGap = 3,\n  legend = true,\n  format,\n  locale = \"en-US\",\n  formatValue,\n  formatDate,\n  labels,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: HeatmapProps) {\n  const l = useLabels(\"heatmap\", DEFAULT_LABELS, labels)\n  const reduce = useReduce()\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const scrollRef = React.useRef<HTMLDivElement>(null)\n  const inView = useInView(rootRef)\n  const width = useWidth(rootRef)\n  const [active, setActive] = React.useState<number | null>(null)\n  const [scrollLeft, setScrollLeft] = React.useState(0)\n  const calendar = mode === \"calendar\"\n\n  const fmt = React.useMemo(() => formatValue ?? ((v: number) => new Intl.NumberFormat(locale, format).format(v)), [formatValue, locale, format])\n  const dateFmt = React.useMemo(() => formatDate ?? ((d: Date) => new Intl.DateTimeFormat(locale, { month: \"short\", day: \"numeric\", year: \"numeric\" }).format(d)), [formatDate, locale])\n  const monthFmt = React.useMemo(() => new Intl.DateTimeFormat(locale, { month: \"short\" }), [locale])\n  const dayFmt = React.useMemo(() => new Intl.DateTimeFormat(locale, { weekday: \"short\" }), [locale])\n\n  // Build the grid: one entry per cell with its column, row and value.\n  const built = React.useMemo(() => {\n    const cells: Cell[] = []\n    let cols = 0\n    let rowCount = 0\n    const colLabels: { col: number; text: string }[] = []\n    const rowLabels: { row: number; text: string }[] = []\n    if (calendar) {\n      const map = new Map<string, number>()\n      for (const d of data ?? []) map.set(d.date.slice(0, 10), (map.get(d.date.slice(0, 10)) ?? 0) + d.value)\n      const dates = [...map.keys()].sort()\n      const last = end ? parseDate(end) : dates.length ? parseDate(dates[dates.length - 1] ?? \"\") : null\n      if (last) {\n        const days = weeks * 7\n        const first = addDays(last, -(days - 1))\n        const lead = (first.getDay() - weekStart + 7) % 7\n        cols = Math.ceil((days + lead) / 7)\n        rowCount = 7\n        let prevMonth = -1\n        let lastLabelCol = -10\n        for (let i = 0; i < days; i++) {\n          const d = addDays(first, i)\n          const slot = i + lead\n          const col = Math.floor(slot / 7)\n          const row = slot % 7\n          const key = iso(d)\n          const v = map.get(key)\n          cells.push({ id: i, col, row, value: v ?? 0, label: dateFmt(d), has: v !== undefined })\n          if (d.getMonth() !== prevMonth) {\n            if (prevMonth !== -1 && col - lastLabelCol >= 3) {\n              colLabels.push({ col, text: monthFmt.format(d) })\n              lastLabelCol = col\n            } else if (prevMonth === -1 && col === 0 && d.getDate() <= 7) {\n              colLabels.push({ col, text: monthFmt.format(d) })\n              lastLabelCol = col\n            }\n            prevMonth = d.getMonth()\n          }\n        }\n        // Weekday names from a known week (Sunday Jan 7 2024); Mon, Wed and Fri keep the column from getting busy.\n        const ref = new Date(2024, 0, 7 + weekStart)\n        for (const row of weekStart === 1 ? [0, 2, 4] : [1, 3, 5]) rowLabels.push({ row, text: dayFmt.format(addDays(ref, row)) })\n      }\n    } else if (rows && columns && values) {\n      cols = columns.length\n      rowCount = rows.length\n      rows.forEach((r, ri) => {\n        columns.forEach((c, ci) => {\n          const v = values[ri]?.[ci]\n          cells.push({ id: ri * cols + ci, col: ci, row: ri, value: v ?? 0, label: `${r} · ${c}`, has: v !== undefined })\n        })\n        rowLabels.push({ row: ri, text: r })\n      })\n      columns.forEach((c, ci) => colLabels.push({ col: ci, text: c }))\n    }\n    return { cells, cols, rowCount, colLabels, rowLabels }\n  }, [calendar, data, end, weeks, weekStart, rows, columns, values, dateFmt, monthFmt, dayFmt])\n\n  const { cells, cols, rowCount, colLabels, rowLabels } = built\n  const max = cells.reduce((m, c) => Math.max(m, c.value), 0)\n  const thresholds = React.useMemo(() => {\n    if (scale === \"quantile\") {\n      const positive = cells.map((c) => c.value).filter((v) => v > 0).sort((a, b) => a - b)\n      return Array.from({ length: steps - 1 }, (_, i) => positive[Math.floor(((i + 1) / steps) * positive.length)] ?? 0)\n    }\n    return Array.from({ length: steps - 1 }, (_, i) => (max * (i + 1)) / steps)\n  }, [cells, steps, scale, max])\n  const levelOf = (v: number) => {\n    if (v <= 0) return 0\n    let lv = 1\n    for (const t of thresholds) if (v > t) lv++\n    return Math.min(steps, lv)\n  }\n  const opacityOf = (level: number) => (level === 0 ? 0 : steps <= 1 ? 1 : 0.22 + (0.78 * (level - 1)) / (steps - 1))\n\n  // Geometry. Calendar cells are fixed and scroll; matrix cells stretch to the container width.\n  const W = width ?? 0\n  const labelW = calendar ? 30 : Math.min(120, Math.max(40, (rows ?? []).reduce((m, r) => Math.max(m, r.length), 0) * 6.5 + 12))\n  const top = 18\n  const cw = calendar ? cellSize : Math.max(cellSize, (W - labelW - (cols - 1) * cellGap) / Math.max(1, cols))\n  const ch = calendar ? cellSize : Math.min(Math.max(cellSize, cw), 28)\n  const svgW = labelW + cols * (cw + cellGap) - cellGap\n  const svgH = top + rowCount * (ch + cellGap) - cellGap\n  const xOf = (col: number) => labelW + col * (cw + cellGap)\n  const yOf = (row: number) => top + row * (ch + cellGap)\n\n  // Start scrolled to the latest weeks.\n  React.useLayoutEffect(() => {\n    const el = scrollRef.current\n    if (el && calendar && width !== null) el.scrollLeft = el.scrollWidth\n  }, [calendar, svgW, width])\n\n  const activeCell = active !== null ? cells.find((c) => c.id === active) : undefined\n  const name = typeof title === \"string\" ? title : \"\"\n  const summary = ariaLabel ?? (cells.length ? l.summary(name, cells.length, fmt(max)) : l.noData)\n  const announce = activeCell ? l.cell(activeCell.label, fmt(activeCell.value)) : \"\"\n\n  const move = (dc: number, dr: number) => {\n    const from = active !== null ? cells.find((c) => c.id === active) : undefined\n    const base = from ?? cells[cells.length - 1]\n    if (!base) return\n    const next = cells.find((c) => c.col === base.col + dc && c.row === base.row + dr) ?? base\n    // Keep the active cell in view when the calendar scrolls.\n    const el = scrollRef.current\n    if (el && calendar) {\n      const x = xOf(next.col) - el.scrollLeft\n      if (x < labelW + 4) el.scrollLeft = xOf(next.col) - labelW - 4\n      else if (x + cw > el.clientWidth - 4) el.scrollLeft = xOf(next.col) + cw - el.clientWidth + 4\n    }\n    setActive(next.id)\n  }\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (!cells.length) return\n    const map: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }\n    const m = map[e.key]\n    if (m) {\n      e.preventDefault()\n      move(m[0], m[1])\n    } else if (e.key === \"Home\" || e.key === \"End\") {\n      e.preventDefault()\n      setActive((e.key === \"Home\" ? cells[0] : cells[cells.length - 1])?.id ?? null)\n    } else if (e.key === \"Escape\") setActive(null)\n  }\n  const onPointerMove = (e: React.PointerEvent) => {\n    const t = (e.target as Element).closest(\"[data-cell]\")\n    setActive(t ? Number(t.getAttribute(\"data-cell\")) : null)\n  }\n\n  const tipX = activeCell ? xOf(activeCell.col) + cw / 2 - (calendar ? scrollLeft : 0) : 0\n  const tipY = activeCell ? yOf(activeCell.row) : 0\n  const tipRight = tipX > W * 0.55\n  const ready = inView || reduce\n\n  return (\n    <div ref={rootRef} data-inview={ready} className={cn(\"pc-heatmap flex w-full min-w-0 flex-col gap-2\", className)} {...props}>\n      <GooduiTokens />\n      <style href=\"pc-heatmap\" precedence=\"default\">\n        {CSS}\n      </style>\n      <div\n        role=\"group\"\n        aria-roledescription=\"heatmap\"\n        aria-label={summary}\n        tabIndex={0}\n        onKeyDown={onKeyDown}\n        onFocus={() => setActive((i) => i ?? (cells[cells.length - 1]?.id ?? null))}\n        onBlur={() => setActive(null)}\n        className=\"relative rounded-md outline-none focus-visible:ring-3 focus-visible:ring-ring/50\"\n      >\n        <div ref={scrollRef} dir=\"ltr\" onScroll={(e) => setScrollLeft(e.currentTarget.scrollLeft)} className={cn(\"w-full\", calendar && \"overflow-x-auto overflow-y-hidden [scrollbar-width:thin]\")} onPointerMove={onPointerMove} onPointerLeave={() => setActive(null)}>\n          {width !== null && cells.length > 0 && (\n            <svg width={svgW} height={svgH} viewBox={`0 0 ${svgW} ${svgH}`} className=\"block shrink-0 touch-pan-y\" style={calendar ? undefined : { width: \"100%\" }} aria-hidden=\"true\">\n              {colLabels.map((c) => (\n                <text key={c.col} x={xOf(c.col) + (calendar ? 0 : cw / 2)} y={11} textAnchor={calendar ? \"start\" : \"middle\"} className=\"fill-muted-foreground text-[10px]\">\n                  {c.text}\n                </text>\n              ))}\n              {rowLabels.map((r) => (\n                <text key={r.row} x={labelW - 6} y={yOf(r.row) + ch / 2} dy=\".35em\" textAnchor=\"end\" className=\"fill-muted-foreground text-[10px]\">\n                  {r.text}\n                </text>\n              ))}\n              {cells.map((c) => {\n                const level = levelOf(c.value)\n                const isActive = active === c.id\n                return (\n                  <rect\n                    key={c.id}\n                    data-cell={c.id}\n                    className={cn(\"pc-heatmap-cell\", level === 0 && \"fill-muted\", isActive && \"stroke-foreground\")}\n                    style={{ [\"--d\" as string]: c.col, ...(level > 0 ? { fill: color, fillOpacity: opacityOf(level) } : {}) }}\n                    x={xOf(c.col)}\n                    y={yOf(c.row)}\n                    width={cw}\n                    height={ch}\n                    rx={Math.min(3, cw / 4)}\n                    strokeWidth={isActive ? 1.5 : 0}\n                  />\n                )\n              })}\n            </svg>\n          )}\n          {width !== null && cells.length === 0 && <div className=\"grid h-24 place-items-center text-sm text-muted-foreground\">{l.noData}</div>}\n        </div>\n        {activeCell && (\n          <div\n            className=\"pointer-events-none absolute z-10 flex flex-col gap-0.5 rounded-md border bg-popover px-2.5 py-1.5 text-xs whitespace-nowrap text-popover-foreground shadow-[var(--pc-e2)]\"\n            style={{ left: tipX, top: tipY, transform: `translate(${tipRight ? \"calc(-100% - 10px)\" : \"10px\"}, calc(-100% - 6px))` }}\n          >\n            <span className=\"text-muted-foreground\">{activeCell.label}</span>\n            <span className=\"flex items-center gap-1.5 font-semibold tabular-nums\">\n              <span className=\"inline-block size-2 rounded-[2px]\" style={{ background: color, opacity: Math.max(0.22, opacityOf(levelOf(activeCell.value))) }} />\n              {fmt(activeCell.value)}\n            </span>\n          </div>\n        )}\n        <span className=\"sr-only\" aria-live=\"polite\">\n          {announce}\n        </span>\n      </div>\n      {legend && cells.length > 0 && (\n        <div className=\"flex items-center justify-end gap-1.5 text-[10px] text-muted-foreground\" aria-hidden=\"true\">\n          <span>{l.less}</span>\n          {Array.from({ length: steps + 1 }, (_, i) => (\n            <span key={i} className={cn(\"inline-block size-2.5 rounded-[2px]\", i === 0 && \"bg-muted\")} style={i > 0 ? { background: color, opacity: opacityOf(i) } : undefined} />\n          ))}\n          <span>{l.more}</span>\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/heatmap.tsx"
    }
  ],
  "categories": [
    "components",
    "charts"
  ],
  "type": "registry:component"
}