import React, { useState, useCallback, useEffect } from 'react'; import { useFetchGithubCommits } from '@/hooks/githubQueries/useFetchGithubCommits'; import { Tooltip } from 'primereact/tooltip'; const GithubContributionChart = ({ username }) => { const [contributionData, setContributionData] = useState({}); const [totalCommits, setTotalCommits] = useState(0); const handleNewCommit = useCallback(({ contributionData, totalCommits }) => { setContributionData(contributionData); setTotalCommits(totalCommits); }, []); const { data, isLoading, isFetching } = useFetchGithubCommits(username, handleNewCommit); // Initialize from cached data if available useEffect(() => { if (data && !isLoading) { setContributionData(data.contributionData); setTotalCommits(data.totalCommits); } }, [data, isLoading]); const getColor = useCallback((count) => { if (count === 0) return 'bg-gray-100'; if (count < 5) return 'bg-green-300'; if (count < 10) return 'bg-green-400'; if (count < 20) return 'bg-green-600'; return 'bg-green-700'; }, []); const generateCalendar = useCallback(() => { const today = new Date(); const oneYearAgo = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate()); const calendar = []; // Create 7 rows for days of the week for (let i = 0; i < 7; i++) { calendar[i] = []; } // Fill in the dates for (let d = new Date(oneYearAgo); d <= today; d.setDate(d.getDate() + 1)) { const dateString = d.toISOString().split('T')[0]; const count = contributionData[dateString] || 0; const dayOfWeek = d.getDay(); calendar[dayOfWeek].push({ date: new Date(d), count }); } return calendar; }, [contributionData]); const calendar = generateCalendar(); const weekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; const getMonthLabels = useCallback(() => { const today = new Date(); const oneYearAgo = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate()); const months = []; let currentMonth = -1; for (let d = new Date(oneYearAgo); d <= today; d.setDate(d.getDate() + 1)) { const month = d.getMonth(); if (month !== currentMonth) { months.push({ name: d.toLocaleString('default', { month: 'short' }), index: calendar[0].findIndex( (_, weekIndex) => calendar[0][weekIndex]?.date.getMonth() === month ) }); currentMonth = month; } } return months; }, [calendar]); return (
{(isLoading || isFetching) &&

Loading contribution data... ({totalCommits} commits fetched)

} {!isLoading && !isFetching &&

{totalCommits} contributions in the last year

}
{/* Days of week labels */}
{weekDays.map((day, index) => (
{index % 2 === 0 && day}
))}
{/* Calendar grid */}
{calendar[0].map((_, weekIndex) => (
{calendar.map((row, dayIndex) => ( row[weekIndex] && (
) ))}
))}
{/* Month labels moved to bottom */}
{getMonthLabels().map((month, index) => (
{month.name}
))}
Less
More
); }; export default GithubContributionChart;