/* From Wensity UI (https://ui.wensity.com/components/github-activity-grid), a free component released under the MIT License. Kept as published; only the motion import points at this app's "motion" package. */ import * as React from "react"; import { motion, useSpring, useMotionValue, useReducedMotion } from "motion/react"; import { cn } from "@/lib/utils"; /* ────────────────────────────────────────────────────────────────────────── */ /* Types */ /* ────────────────────────────────────────────────────────────────────────── */ export interface ActivityDay { /** ISO date string (YYYY-MM-DD). */ date: string; /** 0..n raw count (will be bucketed into 5 levels). */ count: number; } export interface GitHubActivityGridProps { /** * Days, oldest-first. Length should be exactly the visible window * (typically 365 or 371 for a clean 53-week grid). */ days: ActivityDay[]; /** * Maximum count used to compute level buckets. Defaults to the max in * `days` (so colors are always relative to the dataset). */ maxCount?: number; /** Cell size in px. Default 11. */ cellSize?: number; /** Gap between cells in px. Default 3. */ cellGap?: number; className?: string; } // Contribution-density buckets. We use EMERALD (not the brand chili) because: // 1. Universally — including GitHub itself — green = "growth / activity". // 2. Painting commits in chili-red turns the entire grid into a "blood // splatter" that reads as alarms, not progress. That's the canonical // example of using the brand colour where a semantic colour should live. // 3. The card header text + focus ring still carry the brand, so the // surface remains identifiably Wensity. const LEVEL_BG = [ "bg-[var(--surface-muted)]", "bg-emerald-500/15 dark:bg-emerald-900/60", "bg-emerald-500/35 dark:bg-emerald-700", "bg-emerald-500/65 dark:bg-emerald-500", "bg-emerald-500 dark:bg-emerald-400", ] as const; const WEEKDAYS = ["", "Mon", "", "Wed", "", "Fri", ""] as const; const MONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; const ACTIVITY_MATTE_NOISE = `url("data:image/svg+xml;utf8,")`; const WEEKDAY_LABEL_WIDTH = 22; const WEEKDAY_LABEL_GAP = 4; /* ────────────────────────────────────────────────────────────────────────── */ /* Component */ /* ────────────────────────────────────────────────────────────────────────── */ export function GitHubActivityGrid({ days, maxCount, cellSize = 11, cellGap = 3, className, }: GitHubActivityGridProps) { const reduce = useReducedMotion(); /* ---------------- bucketise into 0..4 levels --------------------------- */ const max = React.useMemo(() => { if (typeof maxCount === "number" && maxCount > 0) return maxCount; return Math.max(1, ...days.map((d) => d.count)); }, [days, maxCount]); function level(count: number) { if (count <= 0) return 0; const ratio = count / max; if (ratio < 0.25) return 1; if (ratio < 0.5) return 2; if (ratio < 0.75) return 3; return 4; } /* ---------------- group into [week][weekday] grid ---------------------- */ // Day 0 = first cell. We pad the start to align Sunday=0 of week 0. const grid = React.useMemo(() => { if (days.length === 0) return { weeks: [] as (ActivityDay | null)[][], monthLabels: [] as { col: number; label: string }[] }; const first = new Date(days[0].date + "T00:00:00"); const startWeekday = first.getDay(); // 0..6 const flat: (ActivityDay | null)[] = [ ...Array.from({ length: startWeekday }, () => null), ...days, ]; // pad tail so each week is full while (flat.length % 7 !== 0) flat.push(null); const weeks: (ActivityDay | null)[][] = []; for (let i = 0; i < flat.length; i += 7) { weeks.push(flat.slice(i, i + 7)); } // month labels per week column (label appears at first week containing day 1..7 of month) const monthLabels: { col: number; label: string }[] = []; let lastMonth = -1; weeks.forEach((wk, col) => { const firstReal = wk.find(Boolean) as ActivityDay | undefined; if (!firstReal) return; const m = new Date(firstReal.date + "T00:00:00").getMonth(); if (m !== lastMonth) { monthLabels.push({ col, label: MONTHS[m] }); lastMonth = m; } }); return { weeks, monthLabels }; }, [days]); /* ---------------- single global tooltip — springed position ----------- */ const containerRef = React.useRef(null); const tooltipX = useMotionValue(0); const tooltipY = useMotionValue(0); const springX = useSpring(tooltipX, { stiffness: 480, damping: 40, mass: 0.5 }); const springY = useSpring(tooltipY, { stiffness: 480, damping: 40, mass: 0.5 }); const [hover, setHover] = React.useState(null); const gridViewportRef = React.useRef(null); const [gridViewportWidth, setGridViewportWidth] = React.useState(0); React.useEffect(() => { const node = gridViewportRef.current; if (!node) return; const measure = () => setGridViewportWidth(node.clientWidth); measure(); if (typeof ResizeObserver === "undefined") { window.addEventListener("resize", measure); return () => window.removeEventListener("resize", measure); } const observer = new ResizeObserver(measure); observer.observe(node); return () => observer.disconnect(); }, []); function onCellEnter( e: React.PointerEvent, day: ActivityDay ) { const cont = containerRef.current; if (!cont) return; const r = e.currentTarget.getBoundingClientRect(); const cr = cont.getBoundingClientRect(); // Center-top of the cell, relative to container tooltipX.set(r.left - cr.left + r.width / 2); tooltipY.set(r.top - cr.top - 6); setHover(day); } function onLeave() { setHover(null); } const totalContributions = React.useMemo( () => days.reduce((s, d) => s + d.count, 0), [days] ); const weekCount = grid.weeks.length; const baseGridWidth = weekCount * cellSize + Math.max(0, weekCount - 1) * cellGap; const availableGridWidth = Math.max( 0, gridViewportWidth - WEEKDAY_LABEL_WIDTH - WEEKDAY_LABEL_GAP ); const fitScale = gridViewportWidth > 0 && baseGridWidth > availableGridWidth ? availableGridWidth / baseGridWidth : 1; const fittedCellSize = cellSize * fitScale; const fittedCellGap = cellGap * fitScale; const fittedGridWidth = weekCount * fittedCellSize + Math.max(0, weekCount - 1) * fittedCellGap; return (
{/* Header */}
{totalContributions.toLocaleString()} contributions in the last year
{/* Grid */}
{/* Month labels row */}
{grid.monthLabels.map((m) => ( {m.label} ))}
{/* Weekday labels */}
{WEEKDAYS.map((wd, i) => ( {wd} ))}
{/* Cells */}
{grid.weeks.map((week, wIdx) => (
{week.map((day, dIdx) => { if (!day) { return ( ); } const lvl = level(day.count); // index back from the end → most recent day first const fromEnd = days.length - 1 - days.indexOf(day); const delay = fromEnd * 0.002; return ( onCellEnter(e, day)} onFocus={(e) => { // Synthesise a pointer-style enter for keyboard nav const cont = containerRef.current; if (!cont) return; const r = ( e.currentTarget as HTMLButtonElement ).getBoundingClientRect(); const cr = cont.getBoundingClientRect(); tooltipX.set(r.left - cr.left + r.width / 2); tooltipY.set(r.top - cr.top - 6); setHover(day); }} onBlur={onLeave} aria-label={`${day.count} contributions on ${day.date}`} className={cn( "block rounded-[3px] outline-none transition-colors", "ring-0 focus-visible:ring-2 focus-visible:ring-chili-500/60", LEVEL_BG[lvl], lvl === 0 && "ring-1 ring-inset ring-[var(--border)]/60" )} style={{ width: fittedCellSize, height: fittedCellSize, willChange: "transform", }} /> ); })}
))}
{/* ONE global tooltip — springs to the hovered cell */} {hover ? ( <> {hover.count}{" "} {hover.count === 1 ? "contribution" : "contributions"} · {formatDate(hover.date)} ) : null}
); } /* ────────────────────────────────────────────────────────────────────────── */ /* Helpers */ /* ────────────────────────────────────────────────────────────────────────── */ function Legend() { return (
Less {LEVEL_BG.map((bg, i) => ( ))} More
); } function formatDate(iso: string) { const d = new Date(iso + "T00:00:00"); return d.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric", }); } /* ────────────────────────────────────────────────────────────────────────── */ /* Convenience: deterministic mock generator (handy for previews) */ /* ────────────────────────────────────────────────────────────────────────── */ /** * Deterministic seeded mock generator. Returns 371 days (53 full weeks) * ending on `endDate` (default = today). */ export function mockActivityYear( seed = 42, endDate: Date = new Date() ): ActivityDay[] { const total = 371; const days: ActivityDay[] = []; let s = seed; function rand() { s = (s * 9301 + 49297) % 233280; return s / 233280; } const end = new Date(endDate); end.setHours(0, 0, 0, 0); for (let i = total - 1; i >= 0; i--) { const d = new Date(end); d.setDate(end.getDate() - i); const wd = d.getDay(); // weekends quieter, midweek busier const base = wd === 0 || wd === 6 ? 0.18 : 0.55; const r = rand(); let count = 0; if (r < 0.35) count = 0; else if (r < 0.6) count = Math.floor(rand() * 3) + 1; else if (r < 0.85) count = Math.floor(rand() * 6) + 3; else count = Math.floor(rand() * 10) + 8; if (rand() > base) count = Math.max(0, count - 2); days.push({ date: d.toISOString().slice(0, 10), count, }); } return days; }