1"use client";
2
3import type { Day as WeekDay } from "date-fns";
4import {
5 differenceInCalendarDays,
6 eachDayOfInterval,
7 formatISO,
8 getDay,
9 getMonth,
10 getYear,
11 nextDay,
12 parseISO,
13 subWeeks,
14} from "date-fns";
15import {
16 type CSSProperties,
17 createContext,
18 Fragment,
19 type HTMLAttributes,
20 type ReactNode,
21 useContext,
22 useMemo,
23} from "react";
24import { cn } from "@/lib/utils";
25
26export type Activity = {
27 date: string;
28 count: number;
29 level: number;
30};
31
32type Week = Array<Activity | undefined>;
33
34export type Labels = {
35 months?: string[];
36 weekdays?: string[];
37 totalCount?: string;
38 legend?: {
39 less?: string;
40 more?: string;
41 };
42};
43
44type MonthLabel = {
45 weekIndex: number;
46 label: string;
47};
48
49const DEFAULT_MONTH_LABELS = [
50 "Jan",
51 "Feb",
52 "Mar",
53 "Apr",
54 "May",
55 "Jun",
56 "Jul",
57 "Aug",
58 "Sep",
59 "Oct",
60 "Nov",
61 "Dec",
62];
63
64const DEFAULT_LABELS: Labels = {
65 months: DEFAULT_MONTH_LABELS,
66 weekdays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
67 totalCount: "{{count}} activities in {{year}}",
68 legend: {
69 less: "Less",
70 more: "More",
71 },
72};
73
74type ContributionGraphContextType = {
75 data: Activity[];
76 weeks: Week[];
77 blockMargin: number;
78 blockRadius: number;
79 blockSize: number;
80 fontSize: number;
81 labels: Labels;
82 labelHeight: number;
83 maxLevel: number;
84 totalCount: number;
85 weekStart: WeekDay;
86 year: number;
87 width: number;
88 height: number;
89};
90
91const ContributionGraphContext =
92 createContext<ContributionGraphContextType | null>(null);
93
94const useContributionGraph = () => {
95 const context = useContext(ContributionGraphContext);
96
97 if (!context) {
98 throw new Error(
99 "ContributionGraph components must be used within a ContributionGraph"
100 );
101 }
102
103 return context;
104};
105
106const fillHoles = (activities: Activity[]): Activity[] => {
107 if (activities.length === 0) {
108 return [];
109 }
110
111 // Sort activities by date to ensure correct date range
112 const sortedActivities = [...activities].sort((a, b) =>
113 a.date.localeCompare(b.date)
114 );
115
116 const calendar = new Map<string, Activity>(
117 activities.map((a) => [a.date, a])
118 );
119
120 const firstActivity = sortedActivities[0] as Activity;
121 const lastActivity = sortedActivities.at(-1);
122
123 if (!lastActivity) {
124 return [];
125 }
126
127 return eachDayOfInterval({
128 start: parseISO(firstActivity.date),
129 end: parseISO(lastActivity.date),
130 }).map((day) => {
131 const date = formatISO(day, { representation: "date" });
132
133 if (calendar.has(date)) {
134 return calendar.get(date) as Activity;
135 }
136
137 return {
138 date,
139 count: 0,
140 level: 0,
141 };
142 });
143};
144
145const groupByWeeks = (
146 activities: Activity[],
147 weekStart: WeekDay = 0
148): Week[] => {
149 if (activities.length === 0) {
150 return [];
151 }
152
153 const normalizedActivities = fillHoles(activities);
154 const firstActivity = normalizedActivities[0] as Activity;
155 const firstDate = parseISO(firstActivity.date);
156 const firstCalendarDate =
157 getDay(firstDate) === weekStart
158 ? firstDate
159 : subWeeks(nextDay(firstDate, weekStart), 1);
160
161 const paddedActivities = [
162 ...(new Array(differenceInCalendarDays(firstDate, firstCalendarDate)).fill(
163 undefined
164 ) as Activity[]),
165 ...normalizedActivities,
166 ];
167
168 const numberOfWeeks = Math.ceil(paddedActivities.length / 7);
169
170 return new Array(numberOfWeeks)
171 .fill(undefined)
172 .map((_, weekIndex) =>
173 paddedActivities.slice(weekIndex * 7, weekIndex * 7 + 7)
174 );
175};
176
177const getMonthLabels = (
178 weeks: Week[],
179 monthNames: string[] = DEFAULT_MONTH_LABELS
180): MonthLabel[] => {
181 return weeks
182 .reduce<MonthLabel[]>((labels, week, weekIndex) => {
183 const firstActivity = week.find((activity) => activity !== undefined);
184
185 if (!firstActivity) {
186 throw new Error(
187 `Unexpected error: Week ${weekIndex + 1} is empty: [${week}].`
188 );
189 }
190
191 const month = monthNames[getMonth(parseISO(firstActivity.date))];
192
193 if (!month) {
194 const monthName = new Date(firstActivity.date).toLocaleString("en-US", {
195 month: "short",
196 });
197 throw new Error(
198 `Unexpected error: undefined month label for ${monthName}.`
199 );
200 }
201
202 const prevLabel = labels.at(-1);
203
204 if (weekIndex === 0 || !prevLabel || prevLabel.label !== month) {
205 return labels.concat({ weekIndex, label: month });
206 }
207
208 return labels;
209 }, [])
210 .filter(({ weekIndex }, index, labels) => {
211 const minWeeks = 3;
212
213 if (index === 0) {
214 return labels[1] && labels[1].weekIndex - weekIndex >= minWeeks;
215 }
216
217 if (index === labels.length - 1) {
218 return weeks.slice(weekIndex).length >= minWeeks;
219 }
220
221 return true;
222 });
223};
224
225export type ContributionGraphProps = HTMLAttributes<HTMLDivElement> & {
226 data: Activity[];
227 blockMargin?: number;
228 blockRadius?: number;
229 blockSize?: number;
230 fontSize?: number;
231 labels?: Labels;
232 maxLevel?: number;
233 style?: CSSProperties;
234 totalCount?: number;
235 weekStart?: WeekDay;
236 children: ReactNode;
237 className?: string;
238};
239
240export const ContributionGraph = ({
241 data,
242 blockMargin = 4,
243 blockRadius = 2,
244 blockSize = 12,
245 fontSize = 14,
246 labels: labelsProp = undefined,
247 maxLevel: maxLevelProp = 4,
248 style = {},
249 totalCount: totalCountProp = undefined,
250 weekStart = 0,
251 className,
252 ...props
253}: ContributionGraphProps) => {
254 const maxLevel = Math.max(1, maxLevelProp);
255 const weeks = useMemo(() => groupByWeeks(data, weekStart), [data, weekStart]);
256 const LABEL_MARGIN = 8;
257
258 const labels = { ...DEFAULT_LABELS, ...labelsProp };
259 const labelHeight = fontSize + LABEL_MARGIN;
260
261 const year =
262 data.length > 0
263 ? getYear(parseISO(data[0].date))
264 : new Date().getFullYear();
265
266 const totalCount =
267 typeof totalCountProp === "number"
268 ? totalCountProp
269 : data.reduce((sum, activity) => sum + activity.count, 0);
270
271 const width = weeks.length * (blockSize + blockMargin) - blockMargin;
272 const height = labelHeight + (blockSize + blockMargin) * 7 - blockMargin;
273
274 if (data.length === 0) {
275 return null;
276 }
277
278 return (
279 <ContributionGraphContext.Provider
280 value={{
281 data,
282 weeks,
283 blockMargin,
284 blockRadius,
285 blockSize,
286 fontSize,
287 labels,
288 labelHeight,
289 maxLevel,
290 totalCount,
291 weekStart,
292 year,
293 width,
294 height,
295 }}
296 >
297 <div
298 className={cn("flex w-max max-w-full flex-col gap-2", className)}
299 style={{ fontSize, ...style }}
300 {...props}
301 />
302 </ContributionGraphContext.Provider>
303 );
304};
305
306export type ContributionGraphBlockProps = HTMLAttributes<SVGRectElement> & {
307 activity: Activity;
308 dayIndex: number;
309 weekIndex: number;
310};
311
312export const ContributionGraphBlock = ({
313 activity,
314 dayIndex,
315 weekIndex,
316 className,
317 ...props
318}: ContributionGraphBlockProps) => {
319 const { blockSize, blockMargin, blockRadius, labelHeight, maxLevel } =
320 useContributionGraph();
321
322 if (activity.level < 0 || activity.level > maxLevel) {
323 throw new RangeError(
324 `Provided activity level ${activity.level} for ${activity.date} is out of range. It must be between 0 and ${maxLevel}.`
325 );
326 }
327
328 return (
329 <rect
330 className={cn(
331 'data-[level="0"]:fill-muted',
332 'data-[level="1"]:fill-muted-foreground/20',
333 'data-[level="2"]:fill-muted-foreground/40',
334 'data-[level="3"]:fill-muted-foreground/60',
335 'data-[level="4"]:fill-muted-foreground/80',
336 className
337 )}
338 data-count={activity.count}
339 data-date={activity.date}
340 data-level={activity.level}
341 height={blockSize}
342 rx={blockRadius}
343 ry={blockRadius}
344 width={blockSize}
345 x={(blockSize + blockMargin) * weekIndex}
346 y={labelHeight + (blockSize + blockMargin) * dayIndex}
347 {...props}
348 />
349 );
350};
351
352export type ContributionGraphCalendarProps = Omit<
353 HTMLAttributes<HTMLDivElement>,
354 "children"
355> & {
356 hideMonthLabels?: boolean;
357 className?: string;
358 children: (props: {
359 activity: Activity;
360 dayIndex: number;
361 weekIndex: number;
362 }) => ReactNode;
363};
364
365export const ContributionGraphCalendar = ({
366 hideMonthLabels = false,
367 className,
368 children,
369 ...props
370}: ContributionGraphCalendarProps) => {
371 const { weeks, width, height, blockSize, blockMargin, labels } =
372 useContributionGraph();
373
374 const monthLabels = useMemo(
375 () => getMonthLabels(weeks, labels.months),
376 [weeks, labels.months]
377 );
378
379 return (
380 <div
381 className={cn("max-w-full overflow-x-auto overflow-y-hidden", className)}
382 {...props}
383 >
384 <svg
385 className="block overflow-visible"
386 height={height}
387 viewBox={`0 0 ${width} ${height}`}
388 width={width}
389 >
390 <title>Contribution Graph</title>
391 {!hideMonthLabels && (
392 <g className="fill-current">
393 {monthLabels.map(({ label, weekIndex }) => (
394 <text
395 dominantBaseline="hanging"
396 key={weekIndex}
397 x={(blockSize + blockMargin) * weekIndex}
398 >
399 {label}
400 </text>
401 ))}
402 </g>
403 )}
404 {weeks.map((week, weekIndex) =>
405 week.map((activity, dayIndex) => {
406 if (!activity) {
407 return null;
408 }
409
410 return (
411 <Fragment key={`${weekIndex}-${dayIndex}`}>
412 {children({ activity, dayIndex, weekIndex })}
413 </Fragment>
414 );
415 })
416 )}
417 </svg>
418 </div>
419 );
420};
421
422export type ContributionGraphFooterProps = HTMLAttributes<HTMLDivElement>;
423
424export const ContributionGraphFooter = ({
425 className,
426 ...props
427}: ContributionGraphFooterProps) => (
428 <div
429 className={cn(
430 "flex flex-wrap gap-1 whitespace-nowrap sm:gap-x-4",
431 className
432 )}
433 {...props}
434 />
435);
436
437export type ContributionGraphTotalCountProps = Omit<
438 HTMLAttributes<HTMLDivElement>,
439 "children"
440> & {
441 children?: (props: { totalCount: number; year: number }) => ReactNode;
442};
443
444export const ContributionGraphTotalCount = ({
445 className,
446 children,
447 ...props
448}: ContributionGraphTotalCountProps) => {
449 const { totalCount, year, labels } = useContributionGraph();
450
451 if (children) {
452 return <>{children({ totalCount, year })}</>;
453 }
454
455 return (
456 <div className={cn("text-muted-foreground", className)} {...props}>
457 {labels.totalCount
458 ? labels.totalCount
459 .replace("{{count}}", String(totalCount))
460 .replace("{{year}}", String(year))
461 : `${totalCount} activities in ${year}`}
462 </div>
463 );
464};
465
466export type ContributionGraphLegendProps = Omit<
467 HTMLAttributes<HTMLDivElement>,
468 "children"
469> & {
470 children?: (props: { level: number }) => ReactNode;
471};
472
473export const ContributionGraphLegend = ({
474 className,
475 children,
476 ...props
477}: ContributionGraphLegendProps) => {
478 const { labels, maxLevel, blockSize, blockRadius } = useContributionGraph();
479
480 return (
481 <div
482 className={cn("ml-auto flex items-center gap-[3px]", className)}
483 {...props}
484 >
485 <span className="mr-1 text-muted-foreground">
486 {labels.legend?.less || "Less"}
487 </span>
488 {new Array(maxLevel + 1).fill(undefined).map((_, level) =>
489 children ? (
490 <Fragment key={level}>{children({ level })}</Fragment>
491 ) : (
492 <svg height={blockSize} key={level} width={blockSize}>
493 <title>{`${level} contributions`}</title>
494 <rect
495 className={cn(
496 "stroke-[1px] stroke-border",
497 'data-[level="0"]:fill-muted',
498 'data-[level="1"]:fill-muted-foreground/20',
499 'data-[level="2"]:fill-muted-foreground/40',
500 'data-[level="3"]:fill-muted-foreground/60',
501 'data-[level="4"]:fill-muted-foreground/80'
502 )}
503 data-level={level}
504 height={blockSize}
505 rx={blockRadius}
506 ry={blockRadius}
507 width={blockSize}
508 />
509 </svg>
510 )
511 )}
512 <span className="ml-1 text-muted-foreground">
513 {labels.legend?.more || "More"}
514 </span>
515 </div>
516 );
517};
518