{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "heat-calendar",
  "title": "Heat Calendar",
  "description": "A year of daily counts laid out as weeks, with a tooltip on every day and arrow keys that move through them.",
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/default/heat-calendar/heat-calendar.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport type HeatCalendarDay = {\n  /** A calendar day as YYYY-MM-DD, read in UTC. */\n  date: string\n  count: number\n}\n\nexport type HeatCalendarProps = Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"children\"\n> & {\n  data: readonly HeatCalendarDay[]\n  /** First day shown, YYYY-MM-DD. Defaults to 52 weeks before the end. */\n  start?: string\n  /** Last day shown, YYYY-MM-DD. Defaults to the latest day in the data. */\n  end?: string\n  /** 0 is Sunday. Defaults to the first day of the week in the locale. */\n  weekStart?: number\n  locale?: string\n  /** What is being counted, for the cell names and the tooltip. */\n  unit?: { one: string; other: string }\n  /** The accessible name of the grid. */\n  label?: string\n  /** Any CSS colour. Defaults to the theme's first chart colour, then primary. */\n  color?: string\n}\n\nconst DAY = 86_400_000\nconst LEVELS = [0, 30, 55, 80, 100]\n\nfunction parseDay(value: string) {\n  const [year, month, day] = value.split(\"-\").map(Number)\n  return Date.UTC(year ?? 1970, (month ?? 1) - 1, day ?? 1)\n}\n\nfunction dayKey(time: number) {\n  return new Date(time).toISOString().slice(0, 10)\n}\n\nfunction localeWeekStart(locale?: string) {\n  try {\n    const resolved = new Intl.Locale(\n      locale ?? new Intl.DateTimeFormat().resolvedOptions().locale\n    ) as Intl.Locale & {\n      getWeekInfo?: () => { firstDay: number }\n      weekInfo?: { firstDay: number }\n    }\n    const firstDay = (resolved.getWeekInfo?.() ?? resolved.weekInfo)?.firstDay\n    return firstDay ? firstDay % 7 : 0\n  } catch {\n    return 0\n  }\n}\n\nfunction levelOf(count: number, max: number) {\n  if (count <= 0 || max <= 0) return 0\n  return Math.max(1, Math.ceil((count / max) * (LEVELS.length - 1)))\n}\n\nfunction fillOf(level: number, color: string) {\n  return level === 0\n    ? \"var(--muted)\"\n    : `color-mix(in oklab, ${color} ${LEVELS[level]}%, var(--background))`\n}\n\nexport function HeatCalendar({\n  data,\n  start,\n  end,\n  weekStart,\n  locale,\n  unit = { one: \"contribution\", other: \"contributions\" },\n  label = \"Activity\",\n  color = \"var(--chart-1, var(--primary))\",\n  className,\n  ...rootProps\n}: HeatCalendarProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const scrollRef = React.useRef<HTMLDivElement>(null)\n  const [today] = React.useState(() => parseDay(dayKey(Date.now())))\n  const [focused, setFocused] = React.useState<number | null>(null)\n  const [tip, setTip] = React.useState<{\n    time: number\n    x: number\n    y: number\n    width: number\n  } | null>(null)\n\n  const counts = React.useMemo(() => {\n    const map = new Map<number, number>()\n    for (const day of data) {\n      const time = parseDay(day.date)\n      map.set(time, (map.get(time) ?? 0) + day.count)\n    }\n    return map\n  }, [data])\n\n  const last = end\n    ? parseDay(end)\n    : counts.size\n      ? Math.max(...counts.keys())\n      : today\n  const first = start ? Math.min(parseDay(start), last) : last - 364 * DAY\n  const firstWeekday = weekStart ?? localeWeekStart(locale)\n\n  const offset = (new Date(first).getUTCDay() - firstWeekday + 7) % 7\n  const totalDays = Math.round((last - first) / DAY) + 1\n  const weeks = Math.ceil((offset + totalDays) / 7)\n\n  let max = 0\n  for (const [time, count] of counts) {\n    if (time >= first && time <= last) max = Math.max(max, count)\n  }\n\n  const current =\n    focused !== null && focused >= first && focused <= last ? focused : last\n\n  const names = React.useMemo(() => {\n    const date = new Intl.DateTimeFormat(locale, {\n      weekday: \"long\",\n      month: \"long\",\n      day: \"numeric\",\n      year: \"numeric\",\n      timeZone: \"UTC\",\n    })\n    const short = new Intl.DateTimeFormat(locale, {\n      month: \"short\",\n      day: \"numeric\",\n      timeZone: \"UTC\",\n    })\n    const month = new Intl.DateTimeFormat(locale, {\n      month: \"short\",\n      timeZone: \"UTC\",\n    })\n    const weekday = new Intl.DateTimeFormat(locale, {\n      weekday: \"short\",\n      timeZone: \"UTC\",\n    })\n    const weekdayLong = new Intl.DateTimeFormat(locale, {\n      weekday: \"long\",\n      timeZone: \"UTC\",\n    })\n    const plural = new Intl.PluralRules(locale)\n    const number = new Intl.NumberFormat(locale)\n    return { date, short, month, weekday, weekdayLong, plural, number }\n  }, [locale])\n\n  const amount = (count: number) =>\n    `${names.number.format(count)} ${\n      names.plural.select(count) === \"one\" ? unit.one : unit.other\n    }`\n\n  const timeAt = (week: number, row: number) =>\n    first + (week * 7 + row - offset) * DAY\n\n  const months: { week: number; text: string }[] = []\n  for (let week = 0; week < weeks; week++) {\n    const time = Math.max(timeAt(week, 0), first)\n    const month = new Date(time).getUTCMonth()\n    const previous = months[months.length - 1]\n    const previousTime = week > 0 ? Math.max(timeAt(week - 1, 0), first) : null\n    if (\n      previousTime === null ||\n      new Date(previousTime).getUTCMonth() !== month\n    ) {\n      if (previous && week - previous.week < 3) months.pop()\n      months.push({ week, text: names.month.format(time) })\n    }\n  }\n\n  React.useLayoutEffect(() => {\n    const scroller = scrollRef.current\n    if (scroller) scroller.scrollLeft = scroller.scrollWidth\n  }, [])\n\n  function showTip(time: number, cell: HTMLElement) {\n    const root = rootRef.current\n    if (!root) return\n    const box = root.getBoundingClientRect()\n    const rect = cell.getBoundingClientRect()\n    setTip({\n      time,\n      x: rect.left + rect.width / 2 - box.left,\n      y: rect.top - box.top,\n      width: box.width,\n    })\n  }\n\n  function move(time: number) {\n    const next = Math.min(Math.max(time, first), last)\n    setFocused(next)\n    const cell = scrollRef.current?.querySelector<HTMLElement>(\n      `[data-date=\"${dayKey(next)}\"]`\n    )\n    if (!cell) return\n    cell.focus()\n    cell.scrollIntoView?.({ block: \"nearest\", inline: \"nearest\" })\n    showTip(next, cell)\n  }\n\n  function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {\n    const row = (new Date(current).getUTCDay() - firstWeekday + 7) % 7\n    const steps: Record<string, number | undefined> = {\n      ArrowUp: current - DAY,\n      ArrowDown: current + DAY,\n      ArrowLeft: current - 7 * DAY,\n      ArrowRight: current + 7 * DAY,\n      Home: event.ctrlKey ? first : timeAt(0, row),\n      End: event.ctrlKey ? last : timeAt(weeks - 1, row),\n    }\n    if (event.key === \"Escape\") {\n      setTip(null)\n      return\n    }\n    let target = steps[event.key]\n    if (target === undefined) return\n    event.preventDefault()\n    if (event.key === \"Home\" && target < first) target += 7 * DAY\n    if (event.key === \"End\" && target > last) target -= 7 * DAY\n    move(target)\n  }\n\n  const cell = \"size-[11px] shrink-0 rounded-[3px]\"\n  const tipCount = tip ? (counts.get(tip.time) ?? 0) : 0\n\n  return (\n    <div\n      data-slot=\"heat-calendar\"\n      ref={rootRef}\n      className={cn(\"relative max-w-full min-w-0 text-xs\", className)}\n      {...rootProps}\n    >\n      <div className=\"flex\">\n        <div\n          aria-hidden=\"true\"\n          className=\"text-muted-foreground flex w-8 shrink-0 flex-col gap-[3px] pt-[calc(1rem+5px)]\"\n        >\n          {Array.from({ length: 7 }, (_, row) => (\n            <span className=\"h-[11px] leading-[11px]\" key={row}>\n              {row % 2 === 1 ? names.weekday.format(timeAt(0, row)) : \"\"}\n            </span>\n          ))}\n        </div>\n        <div\n          ref={scrollRef}\n          className=\"min-w-0 flex-1 overflow-x-auto overscroll-x-contain pb-1\"\n          onScroll={() => setTip(null)}\n        >\n          <div className=\"inline-flex flex-col gap-[3px] p-0.5\">\n            <div aria-hidden=\"true\" className=\"flex gap-[3px]\">\n              {Array.from({ length: weeks }, (_, week) => {\n                const month = months.find((entry) => entry.week === week)\n                return (\n                  <span\n                    className=\"text-muted-foreground relative h-4 w-[11px] shrink-0\"\n                    key={week}\n                  >\n                    {month ? (\n                      <span className=\"absolute top-0 left-0 whitespace-nowrap\">\n                        {month.text}\n                      </span>\n                    ) : null}\n                  </span>\n                )\n              })}\n            </div>\n\n            <div\n              aria-label={label}\n              className=\"flex flex-col gap-[3px]\"\n              onKeyDown={handleKeyDown}\n              onPointerLeave={() => setTip(null)}\n              role=\"grid\"\n            >\n              {Array.from({ length: 7 }, (_, row) => {\n                const weekdayTime = timeAt(0, row)\n                return (\n                  <div className=\"flex gap-[3px]\" key={row} role=\"row\">\n                    <span className=\"sr-only\" role=\"rowheader\">\n                      {names.weekdayLong.format(weekdayTime)}\n                    </span>\n                    {Array.from({ length: weeks }, (_, week) => {\n                      const time = timeAt(week, row)\n                      if (time < first || time > last) {\n                        return (\n                          <span className={cell} key={week} role=\"gridcell\" />\n                        )\n                      }\n                      const count = counts.get(time) ?? 0\n                      const level = levelOf(count, max)\n                      return (\n                        <span\n                          aria-label={`${amount(count)} on ${names.date.format(time)}`}\n                          className={cn(\n                            cell,\n                            \"focus-visible:ring-ring focus-visible:ring-offset-background outline-none focus-visible:ring-2 focus-visible:ring-offset-1\"\n                          )}\n                          data-date={dayKey(time)}\n                          data-level={level}\n                          key={week}\n                          onFocus={(event) => {\n                            setFocused(time)\n                            showTip(time, event.currentTarget)\n                          }}\n                          onBlur={() => setTip(null)}\n                          onPointerEnter={(event) =>\n                            showTip(time, event.currentTarget)\n                          }\n                          role=\"gridcell\"\n                          style={{ background: fillOf(level, color) }}\n                          tabIndex={time === current ? 0 : -1}\n                        />\n                      )\n                    })}\n                  </div>\n                )\n              })}\n            </div>\n          </div>\n        </div>\n      </div>\n\n      <div\n        aria-hidden=\"true\"\n        className=\"text-muted-foreground mt-2 flex items-center justify-end gap-[3px]\"\n      >\n        <span className=\"mr-1\">Less</span>\n        {LEVELS.map((_, level) => (\n          <span\n            className={cell}\n            key={level}\n            style={{ background: fillOf(level, color) }}\n          />\n        ))}\n        <span className=\"ml-1\">More</span>\n      </div>\n\n      {tip ? (\n        <span\n          aria-hidden=\"true\"\n          data-slot=\"heat-calendar-tooltip\"\n          className=\"bg-popover text-popover-foreground border-border pointer-events-none absolute z-10 -translate-x-1/2 -translate-y-full rounded-md border px-2 py-1 whitespace-nowrap shadow-sm\"\n          style={{\n            left: Math.min(Math.max(tip.x, 64), tip.width - 64),\n            top: tip.y - 6,\n          }}\n        >\n          <span className=\"font-medium\">{amount(tipCount)}</span>\n          <span className=\"text-muted-foreground\">\n            {\" \"}\n            on {names.short.format(tip.time)}\n          </span>\n        </span>\n      ) : null}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "chart",
    "data",
    "statistic",
    "keyboard"
  ],
  "type": "registry:ui"
}