# Activity Heatmap
*URL: https://www.grettech.com/components/activity-heatmap*

A contribution-style grid from any dated counts, with colour scales, month and weekday labels, a legend and a hover readout.

- Works with any { date, count } data
- Green, violet, blue and orange scales, or your own thresholds
- Month and weekday labels; weeks start on Sunday or Monday
- Renders the same on server and client: no clock reads during render

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/activity-heatmap
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/activity-heatmap-demo`

**Dependencies:** npm: clsx, tailwind-merge, class-variance-authority

## Manual installation
**Step 1: Install dependencies**
Install the packages this component uses and the shadcn/ui components it builds on. It also needs the `cn` helper in `lib/utils.ts`, which `npx shadcn@latest init` adds.

```bash
npm install clsx tailwind-merge class-variance-authority
```

**Step 2: Copy the source code**
Add these files to your project components directory.

File: `components/ui/activity-heatmap.tsx`
```tsx
"use client"

import { cn } from "@/lib/utils"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react"

export interface ActivityDay {
  /** "2026-10-14" */
  date: string
  count: number
}

const heatmapVariants = cva("w-full", {
  variants: {
    color: {
      green: "[--heat:var(--color-emerald-500)]",
      violet: "[--heat:var(--color-violet-500)]",
      blue: "[--heat:var(--color-sky-500)]",
      orange: "[--heat:var(--color-orange-500)]",
    },
  },
  defaultVariants: { color: "green" },
})

export interface ActivityHeatmapProps
  extends
    Omit<React.HTMLAttributes<HTMLDivElement>, "color">,
    VariantProps<typeof heatmapVariants> {
  data: ActivityDay[]
  /** Last day shown. Defaults to the latest date in data. */
  endDate?: string
  weeks?: number
  /** 0 starts weeks on Sunday, 1 on Monday */
  weekStart?: 0 | 1
  /** Counts at which levels 1–4 begin. Defaults to quarters of the maximum. */
  thresholds?: [number, number, number, number]
  /** Singular unit for labels, e.g. "commit" */
  unit?: string
  locale?: string
  showLegend?: boolean
}

const DAY_MS = 86_400_000
const parse = (iso: string) => Date.parse(`${iso}T00:00:00Z`)
const toIso = (ms: number) => new Date(ms).toISOString().slice(0, 10)
const LEVEL_MIX = [0, 30, 55, 78, 100]

export const ActivityHeatmap = React.forwardRef<
  HTMLDivElement,
  ActivityHeatmapProps
>(
  (
    {
      data,
      endDate,
      weeks = 26,
      weekStart = 0,
      thresholds,
      unit = "contribution",
      locale = "en-US",
      showLegend = true,
      color,
      className,
      ...props
    },
    ref
  ) => {
    const [hovered, setHovered] = React.useState<ActivityDay | null>(null)

    const { columns, total, levelOf, monthLabels } = React.useMemo(() => {
      const counts = new Map<string, number>()
      for (const d of data)
        counts.set(d.date, (counts.get(d.date) ?? 0) + d.count)
      const end = endDate ?? [...counts.keys()].sort().at(-1) ?? "1970-01-01"
      const endMs = parse(end)

      // The last column holds the days of the end date's week so far
      const endWeekday = new Date(endMs).getUTCDay()
      const lastColumn = ((endWeekday - weekStart + 7) % 7) + 1
      const days = (weeks - 1) * 7 + lastColumn
      const startMs = endMs - (days - 1) * DAY_MS

      const cells: ActivityDay[] = Array.from({ length: days }, (_, i) => {
        const date = toIso(startMs + i * DAY_MS)
        return { date, count: counts.get(date) ?? 0 }
      })
      const columns: ActivityDay[][] = []
      for (let i = 0; i < cells.length; i += 7)
        columns.push(cells.slice(i, i + 7))

      const max = Math.max(0, ...cells.map((c) => c.count))
      const limits = thresholds ?? [1, max * 0.25, max * 0.5, max * 0.75]
      const levelOf = (count: number) =>
        count <= 0 ? 0 : limits.filter((t) => count >= t).length || 1

      // A month label where a column starts a new month
      const monthFmt = new Intl.DateTimeFormat(locale, {
        month: "short",
        timeZone: "UTC",
      })
      const monthLabels = columns.map((col, i) => {
        const first = new Date(parse(col[0].date))
        const prev = i > 0 ? new Date(parse(columns[i - 1][0].date)) : null
        return !prev || prev.getUTCMonth() !== first.getUTCMonth()
          ? monthFmt.format(first)
          : ""
      })
      // A label needs about three columns, or it runs into the next label
      // (a month starting just after the first column) or past the grid's
      // edge (one starting in the last weeks): those are left out
      for (let i = 0; i < monthLabels.length; i++) {
        if (!monthLabels[i]) continue
        const next = monthLabels.findIndex((m, j) => j > i && m)
        if ((next === -1 ? monthLabels.length : next) - i < 3)
          monthLabels[i] = ""
      }

      return {
        columns,
        total: cells.reduce((sum, c) => sum + c.count, 0),
        levelOf,
        monthLabels,
      }
    }, [data, endDate, weeks, weekStart, thresholds, locale])

    const dayFmt = new Intl.DateTimeFormat(locale, {
      weekday: "short",
      day: "numeric",
      month: "short",
      year: "numeric",
      timeZone: "UTC",
    })
    const plural = (n: number) =>
      `${n.toLocaleString(locale)} ${unit}${n === 1 ? "" : "s"}`
    const summary = `${plural(total)} in the last ${weeks} weeks`

    const weekdayFmt = new Intl.DateTimeFormat(locale, {
      weekday: "short",
      timeZone: "UTC",
    })
    // Label rows 1, 3 and 5 (Mon/Wed/Fri when weeks start on Sunday)
    const weekdayLabels = Array.from({ length: 7 }, (_, row) =>
      row % 2 === 1
        ? weekdayFmt.format(new Date(Date.UTC(2023, 0, 1 + weekStart + row)))
        : ""
    )

    const swatch = (level: number) =>
      level === 0
        ? undefined
        : {
            backgroundColor: `color-mix(in oklab, var(--heat) ${LEVEL_MIX[level]}%, transparent)`,
          }

    return (
      <div
        ref={ref}
        className={cn(heatmapVariants({ color }), className)}
        {...props}
      >
        <div className="overflow-x-auto pb-1">
          <div
            role="img"
            aria-label={summary}
            className="grid w-full gap-0.75 text-[10px] text-muted-foreground"
            style={{
              gridTemplateColumns: `auto repeat(${columns.length}, minmax(10px, 1fr))`,
              minWidth: columns.length * 13 + 28,
            }}
            onPointerLeave={() => setHovered(null)}
          >
            <span />
            {monthLabels.map((m, i) => (
              <span
                key={i}
                aria-hidden="true"
                className="h-4 overflow-visible whitespace-nowrap"
              >
                {m}
              </span>
            ))}
            {weekdayLabels.map((label, row) => (
              <React.Fragment key={row}>
                <span
                  aria-hidden="true"
                  className="flex items-center pr-1.5 leading-none"
                >
                  {label}
                </span>
                {columns.map((col, c) => {
                  const day = col[row]
                  if (!day) return <span key={c} />
                  const level = levelOf(day.count)
                  return (
                    <span
                      key={c}
                      aria-hidden="true"
                      onPointerEnter={() => setHovered(day)}
                      className={cn(
                        "aspect-square rounded-[3px] outline-offset-1 transition-colors",
                        level === 0 && "bg-muted",
                        hovered?.date === day.date &&
                          "outline outline-foreground/60"
                      )}
                      style={swatch(level)}
                    />
                  )
                })}
              </React.Fragment>
            ))}
          </div>
        </div>

        <div className="mt-2 flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
          <p aria-live="polite" className="tabular-nums">
            {hovered
              ? `${plural(hovered.count)} on ${dayFmt.format(parse(hovered.date))}`
              : summary}
          </p>
          {showLegend && (
            <div aria-hidden="true" className="flex items-center gap-1">
              <span className="mr-1">Less</span>
              {[0, 1, 2, 3, 4].map((level) => (
                <span
                  key={level}
                  className={cn(
                    "size-2.5 rounded-[3px]",
                    level === 0 && "bg-muted"
                  )}
                  style={swatch(level)}
                />
              ))}
              <span className="ml-1">More</span>
            </div>
          )}
        </div>
      </div>
    )
  }
)
ActivityHeatmap.displayName = "ActivityHeatmap"

```

**Step 3: Framework Adjustments (Optional)**
If you are manually copying this code into a Vite or Remix project (without using the CLI), make sure to remove the `"use client";` directive from the very top of the file.

## Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| `data` | `ActivityDay[]` | - | Yes | Counts per day: { date: "YYYY-MM-DD", count: number }. Repeated dates are added together; missing dates count as 0. |
| `data.date` | `string` | - | Yes | "2026-10-14" |
| `data.count` | `number` | - | Yes | - |
| `endDate` | `string` | - | No | Last day shown, "YYYY-MM-DD". Defaults to the latest date in data. |
| `weeks` | `number` | `26` | No | Number of week columns. |
| `weekStart` | `0 \| 1` | `0` | No | 0 starts weeks on Sunday, 1 on Monday. |
| `thresholds` | `[number, number, number, number]` | - | No | Counts at which levels 1–4 begin. Defaults to 1 and quarters of the maximum. |
| `color` | `"green" \| "violet" \| "blue" \| "orange"` | `"green"` | No | Colour scale. |
| `unit` | `string` | `"contribution"` | No | Singular unit for labels, e.g. "commit". |
| `locale` | `string` | `"en-US"` | No | Locale for dates and numbers. |
| `showLegend` | `boolean` | `true` | No | Shows the Less–More legend. |
| `className` | `string` | - | No | Extra classes for the root element. |
| `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | No | Any other attributes, passed to the root element. |

## Usage
```tsx
"use client"

import { ActivityHeatmap, type ActivityDay } from "@/components/ui/activity-heatmap"

/**
 * Sample data from a seeded generator: the same on the server and in the
 * browser, so it hydrates cleanly. Busier on weekdays, quieter on weekends.
 */
function sampleData(end: string, days: number): ActivityDay[] {
  let seed = 7
  const random = () => {
    seed = (seed * 16807) % 2147483647
    return seed / 2147483647
  }
  const endMs = Date.parse(`${end}T00:00:00Z`)
  return Array.from({ length: days }, (_, i) => {
    const ms = endMs - (days - 1 - i) * 86_400_000
    const weekend = [0, 6].includes(new Date(ms).getUTCDay())
    const r = random()
    const count =
      r < (weekend ? 0.6 : 0.15) ? 0 : Math.round(r * (weekend ? 4 : 12))
    return { date: new Date(ms).toISOString().slice(0, 10), count }
  })
}

const DATA = sampleData("2026-10-10", 26 * 7)

export default function ActivityHeatmapDemo() {
  return (
    <div className="w-full max-w-2xl p-4">
      <ActivityHeatmap data={DATA} unit="commit" />
    </div>
  )
}

```
