React GitHub Contribution Graph Implementation

Basic implementation

interface PoopCountGraphProps {
  data: { date: string; count: number }[];
}
 
export function PoopCountGraph({ data }: PoopCountGraphProps) {
  const maxCount = Math.max(...data.map((d) => d.count));
  
  const getColor = (count: number) => {
    if (count === 0) return "bg-gray-100";
    const intensity = Math.ceil((count / maxCount) * 4);
    switch (intensity) {
      case 1:
        return "bg-amber-100";
      case 2:
        return "bg-amber-300";
      case 3:
        return "bg-amber-500";
      default:
        return "bg-amber-950";
    }
  };
 
  // Group data by week
  const weeks: { date: string; count: number }[][] = [];
  let currentWeek: { date: string; count: number }[] = [];
  const today = new Date();
  const oneYearAgo = new Date(today);
  oneYearAgo.setFullYear(today.getFullYear() - 1);
 
  // Create a map of date to count
  const dateCountMap = new Map(data.map((item) => [item.date, item.count]));
 
  // Fill in all dates for the past year
  for (let d = new Date(oneYearAgo); d <= today; d.setDate(d.getDate() + 1)) {
    const dateStr = d.toISOString().split("T")[0];
 
    currentWeek.unshift({
      date: dateStr,
      count: dateCountMap.get(dateStr) || 0,
    });
 
    if (currentWeek.length === 7 || d.getTime() === today.getTime()) {
      weeks.unshift(currentWeek);
      currentWeek = [];
    }
  }
 
  return (...);
}