{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar-heatmap",
  "type": "registry:component",
  "title": "Calendar Heatmap",
  "description": "A value per day laid out as a calendar, a column for each week and a row for each weekday, coloured on one hue from faint to strong, with month and weekday names and arrow keys that move by day and by week.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/calendar-heatmap.tsx",
      "type": "registry:component",
      "target": "components/viz/calendar-heatmap.tsx",
      "content": "\"use client\";\n/**\n * @name calendar-heatmap\n * @category viz\n * @description A value per day laid out as a calendar, a column for each week and a row for each weekday, coloured on one hue from faint to strong, with month and weekday names and arrow keys that move by day and by week.\n * @when Showing a daily measure over months: activity, sales per day, rainfall, where the pattern by weekday and season matters. For a few weeks with exact values use bar-chart; for a trend use line-chart; to pick a day use calendar.\n * @example\n * <CalendarHeatmap\n *   label=\"Workouts per day\"\n *   data={[{ day: \"2026-01-05\", count: 1 }, { day: \"2026-01-06\", count: 2 }, { day: \"2026-01-09\", count: 1 }]}\n *   day=\"day\"\n *   value=\"count\"\n *   from=\"2026-01-01\"\n *   to=\"2026-03-31\"\n * />\n */\nimport { scaleLinear } from \"d3-scale\";\nimport { useMemo, type KeyboardEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { ChartContainer, ChartEmpty, chartSequential, ChartSvg, ChartTooltip, formatNumber, readNumber, useChartCursor, type ChartBaseProps } from \"@/components/viz/chart\";\n\nexport type CalendarHeatmapProps<T extends object> = ChartBaseProps & {\n  /** One object per day that has a value. Days without one are drawn empty. */\n  data: readonly T[];\n  /** The field holding the day as \"YYYY-MM-DD\". */\n  day: keyof T & string;\n  /** The field holding the day's number. */\n  value: keyof T & string;\n  /** The first and last day shown, \"YYYY-MM-DD\". Default: the first and last day in the data. */\n  from?: string;\n  to?: string;\n  /** The day a week starts on: 0 Sunday … 6 Saturday. Default 1 (Monday). */\n  weekStart?: number;\n  /** The name of the value in the tooltip and the table. Default: the field name. */\n  valueLabel?: string;\n  /** Said for a day without a value. Default \"No value\". */\n  noValue?: string;\n  /** The scale under the chart. Default true. */\n  showLegend?: boolean;\n};\n\nconst DAY = 86400000;\nconst ROUND = \"[rx:min(calc(var(--radius)*0.5),3px)] [ry:min(calc(var(--radius)*0.5),3px)]\";\nconst STEPS = [0, 0.25, 0.5, 0.75, 1];\n\nconst parse = (text: string): number | null => {\n  const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text);\n  return match ? Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])) : null;\n};\nconst iso = (ms: number): string => new Date(ms).toISOString().slice(0, 10);\n\nexport function CalendarHeatmap<T extends object>({\n  data,\n  day,\n  value,\n  from,\n  to,\n  weekStart = 1,\n  valueLabel,\n  noValue = \"No value\",\n  showLegend = true,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale = \"en-US\",\n  formatValue,\n  className,\n  ...props\n}: CalendarHeatmapProps<T>) {\n  const model = useMemo(() => {\n    const values = new Map<number, number>();\n    for (const row of data) {\n      const at = parse(String((row as Record<string, unknown>)[day] ?? \"\"));\n      const amount = readNumber(row, value);\n      if (at === null || amount === null) continue;\n      values.set(at, (values.get(at) ?? 0) + amount);\n    }\n    const keys = [...values.keys()];\n    const start = (from ? parse(from) : null) ?? (keys.length > 0 ? Math.min(...keys) : null);\n    const end = (to ? parse(to) : null) ?? (keys.length > 0 ? Math.max(...keys) : null);\n    if (start === null || end === null || end < start) return { days: [] as number[], values, offset: 0, low: 0, high: 0 };\n    const days: number[] = [];\n    for (let at = start; at <= end; at += DAY) days.push(at);\n    // Where the first day falls in its week, counted from the week's first day.\n    const offset = (new Date(start).getUTCDay() - weekStart + 7) % 7;\n    const amounts = days.flatMap((at) => (values.has(at) ? [values.get(at) ?? 0] : []));\n    return { days, values, offset, low: Math.min(0, ...amounts), high: Math.max(0, ...amounts) };\n  }, [data, day, value, from, to, weekStart]);\n\n  const { days, values, offset, low, high } = model;\n  const cursor = useChartCursor(days.length);\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const full = new Intl.DateTimeFormat(locale, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\", timeZone: \"UTC\" });\n  const monthName = new Intl.DateTimeFormat(locale, { month: \"short\", timeZone: \"UTC\" });\n  const weekdayName = new Intl.DateTimeFormat(locale, { weekday: \"narrow\", timeZone: \"UTC\" });\n  const level = scaleLinear()\n    .domain(low === high ? [low, low + 1] : [low, high])\n    .range([0, 1])\n    .clamp(true);\n  const weeks = Math.ceil((days.length + offset) / 7);\n  const textOf = (at: number): string => (values.has(at) ? number(values.get(at) ?? 0) : noValue);\n  const table = {\n    caption: label,\n    columns: [day, valueLabel ?? value],\n    rows: days.filter((at) => values.has(at)).map((at) => [iso(at), number(values.get(at) ?? 0)]),\n  };\n  const current = cursor.active === null ? undefined : days[cursor.active];\n  const onKeyDown = (event: KeyboardEvent<SVGSVGElement>): void => {\n    // Down is the next day, Right the same weekday a week on: the calendar's own geometry.\n    const steps: Record<string, number> = { ArrowDown: 1, ArrowUp: -1, ArrowRight: 7, ArrowLeft: -7, PageDown: 28, PageUp: -28 };\n    const step = steps[event.key];\n    if (step !== undefined) {\n      event.preventDefault();\n      cursor.select(cursor.active === null ? 0 : cursor.active + step);\n      return;\n    }\n    cursor.svgProps.onKeyDown(event);\n  };\n  const shape = aspect ?? Math.max(2.4, (weeks + 2.5) / 9);\n\n  return (\n    <div data-slot=\"calendar-heatmap\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer aspect={shape} height={height} table={table} announcement={cursor.keyboard && current !== undefined ? `${full.format(current)}: ${textOf(current)}` : \"\"}>\n        {({ width, height: plotHeight }) => {\n          if (days.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const left = 20;\n          const top = 18;\n          const cell = Math.max(3, Math.min((width - left) / weeks, (plotHeight - top) / 7));\n          const gap = cell > 8 ? 2 : 1;\n          const place = (index: number): { x: number; y: number } => {\n            const slot = index + offset;\n            return { x: left + Math.floor(slot / 7) * cell, y: top + (slot % 7) * cell };\n          };\n          const months = days.flatMap((at, index) => (new Date(at).getUTCDate() === 1 || index === 0 ? [{ at, x: place(index).x }] : []));\n          const shown = cursor.active === null ? undefined : place(cursor.active);\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps} onKeyDown={onKeyDown}>\n                <g aria-hidden=\"true\" className=\"fill-muted-foreground text-xs\">\n                  {months.map((month, index) => {\n                    const next = months[index + 1];\n                    return next && next.x - month.x < 28 ? null : (\n                      <text key={month.at} x={month.x} y={top - 6}>\n                        {monthName.format(month.at)}\n                      </text>\n                    );\n                  })}\n                  {[0, 2, 4, 6].map((row) => {\n                    // A day known to fall on the weekday of this row.\n                    const sample = Date.UTC(2026, 0, 4 + ((weekStart + row) % 7));\n                    return cell >= 8 ? (\n                      <text key={row} x={left - 6} y={top + row * cell + cell / 2} dy=\"0.32em\" textAnchor=\"end\">\n                        {weekdayName.format(sample)}\n                      </text>\n                    ) : null;\n                  })}\n                </g>\n                <g aria-hidden=\"true\">\n                  {days.map((at, index) => {\n                    const { x, y } = place(index);\n                    const has = values.has(at);\n                    return (\n                      <g key={at} onPointerEnter={() => cursor.point(index)}>\n                        <rect x={x} y={y} width={cell} height={cell} fill=\"transparent\" />\n                        {has ? (\n                          <rect x={x + gap / 2} y={y + gap / 2} width={cell - gap} height={cell - gap} className={ROUND} style={{ fill: chartSequential(level(values.get(at) ?? 0)) }} />\n                        ) : (\n                          <rect\n                            x={x + gap / 2 + 0.5}\n                            y={y + gap / 2 + 0.5}\n                            width={Math.max(0, cell - gap - 1)}\n                            height={Math.max(0, cell - gap - 1)}\n                            fill=\"none\"\n                            className={cn(\"stroke-border\", ROUND)}\n                          />\n                        )}\n                      </g>\n                    );\n                  })}\n                  {shown ? (\n                    <rect\n                      x={shown.x + gap / 2}\n                      y={shown.y + gap / 2}\n                      width={cell - gap}\n                      height={cell - gap}\n                      fill=\"none\"\n                      className={cn(\"pointer-events-none stroke-foreground\", ROUND)}\n                      strokeWidth={2}\n                    />\n                  ) : null}\n                </g>\n              </ChartSvg>\n              {shown && current !== undefined ? (\n                <ChartTooltip\n                  x={shown.x + cell / 2}\n                  y={shown.y + cell / 2}\n                  side={shown.x > width / 2 ? \"left\" : \"right\"}\n                  title={full.format(current)}\n                  rows={[{ label: valueLabel ?? value, value: textOf(current) }]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n      {showLegend && days.length > 0 ? (\n        <div data-slot=\"calendar-heatmap-legend\" aria-hidden=\"true\" className=\"flex items-center gap-2 self-end text-xs tabular-nums text-muted-foreground\">\n          <span>{number(low)}</span>\n          <span className=\"flex gap-0.5\">\n            {STEPS.map((step) => (\n              <span key={step} className=\"size-3 rounded-[min(calc(var(--radius)*0.5),3px)]\" style={{ backgroundColor: chartSequential(step) }} />\n            ))}\n          </span>\n          <span>{number(high)}</span>\n        </div>\n      ) : null}\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing a daily measure over months: activity, sales per day, rainfall, where the pattern by weekday and season matters. For a few weeks with exact values use bar-chart; for a trend use line-chart; to pick a day use calendar.",
    "example": "<CalendarHeatmap\n  label=\"Workouts per day\"\n  data={[{ day: \"2026-01-05\", count: 1 }, { day: \"2026-01-06\", count: 2 }, { day: \"2026-01-09\", count: 1 }]}\n  day=\"day\"\n  value=\"count\"\n  from=\"2026-01-01\"\n  to=\"2026-03-31\"\n/>",
    "client": true
  }
}
