Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat : Added the Leetcode like heatmap feature for user's submissions #411

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions apps/web/app/profile/heatmap/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import React from 'react'
import { AreaChart } from "lucide-react"
import { getServerSession } from 'next-auth';
import { authOptions } from '../../../lib/auth';
import { redirect } from 'next/navigation';
import db from "@repo/db/client";
import CalendarRenderer from '../../../components/CalendarRenderer';

export default async function Heatmap() {

const session = await getServerSession(authOptions);
const monthData = ['January', 'February', 'March', 'April', 'May', 'June', 'July', "August", "September", "October", "November", "December"];

if (!session || !session?.user) {
redirect("/");
}

const getAllSubmissions = async () => {
if (!session || !session.user) {
return null;
}

const userId = session.user.id;
const submissions = await db.submission.findMany({
where: {
userId,
},
include: {
language: true,
},
orderBy: {
createdAt: "desc",
},
});
return submissions;
};

const submissions = await getAllSubmissions();

const acceptedSubmissions = submissions?.filter((submission: any) => submission.statusId <= 3);

return (
<>
<header className="border-b-2 p-3">
<div className="px-2 w-[70%]">
<h1 className="text-lg lg:text-2xl flex items-center gap-2 font-semibold w-fit">
<AreaChart color="#3b82f6" />
<span>Heatmap</span>
</h1>
<span className="text-xs leading-normal text-gray-400">
This page shows you your submissions visually in the form of heatmap
</span>
</div>
</header>

<CalendarRenderer
acceptedSubmissions={acceptedSubmissions}
monthData={monthData}
/>

</>
)
}
108 changes: 108 additions & 0 deletions apps/web/components/Calendar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import React, { useMemo } from 'react'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@repo/ui/tooltip"

interface CalendarProps {
childKey?: string;
type: string;
submissionDates: string[],
selectedMonth: number;
selectedYear: number;
isCurrentMonth: boolean;
monthData: string[],
}

function Calendar({ childKey, type, submissionDates, isCurrentMonth, monthData, selectedMonth, selectedYear }: CalendarProps) {

const date = new Date();
const currMonth = selectedMonth;
const currYear = selectedYear;
const currDate = date.getDate();
// const currDay = date.getDay();

let firstDayOfMonth = new Date(currYear, currMonth, 1).getDay();
let LastDateOfMonth = new Date(currYear, currMonth + 1, 0).getDate()
let LastDateOfLastMonth = new Date(currYear, currMonth, 0).getDate()

const getDatesOfLastMonth = (firstDayOfMonth: number, LastDateOfLastMonth: number) => {
return Array.from(
{ length: firstDayOfMonth },
(_, index) => LastDateOfLastMonth - firstDayOfMonth + index + 1
);
};

//getting the dates of current month
const getCurrMonthDates = (LastDateOfMonth: number): number[] => {
const dates: number[] = [];
for (let date = 1; date <= LastDateOfMonth; date++) {
dates.push(date);
}
return dates;
}

// getting the dates of last month
const datesOfLastMonth = useMemo<number[]>(() => {
return getDatesOfLastMonth(firstDayOfMonth, LastDateOfLastMonth)
}, [currMonth, currYear]);

const currMonthDateArray = useMemo<number[]>(() => {
return getCurrMonthDates(LastDateOfMonth);
}, [currMonth, currYear]);

const datesNumber: number[] = submissionDates.map((item: string) => Number(item?.split("/")[0]));
const dateFrequency = useMemo<number[]>(() => {
return datesNumber.reduce((acc: any, date: any) => {
acc[date] = (acc[date] || 0) + 1;
return acc;
}, {});
}, [submissionDates]);

const renderColorIntensity = (frequency: number) => {
if (frequency === 0) {
return 'bg-[#161b22]';
} else if (frequency > 0 && frequency <= 5) {
return 'bg-[#006d32]';
} else if (frequency > 5 && frequency <= 10) {
return 'bg-[#26a641]';
} else if (frequency > 10) {
return 'bg-[#39d353]';
}
}
return (
<div key={childKey} className='grid grid-rows-7 grid-flow-col gap-x-1 gap-y-1 mx-auto'>
{/* to add gaps before the new month starts */}
{datesOfLastMonth.map((date, index) => (
<div key={`empty-${index}`} className={`invisible row-span-1`} />
))}

<TooltipProvider>
{currMonthDateArray.map((x, dayIndex) => {
const isMatching: boolean = datesNumber.some((item: number) => Number(item) == x);
const frequency = dateFrequency[x] || 0;
return (
<React.Fragment key={`entire-box-with-tootltip-${dayIndex}`}>
<Tooltip>
<TooltipTrigger asChild>
<div
key={`box-${dayIndex + 1}`}
className={`${isMatching ? (renderColorIntensity(frequency)) : `bg-[#a2a2a2] dark:bg-[#393939]`} ${(currDate <= dayIndex && isCurrentMonth) && "opacity-25"} cursor-pointer row-span-1 ${type === 'single' ? "w-[1rem] h-[1rem] rounded-[3px]" : "w-[0.58rem] h-[0.58rem] rounded-[1px]"}`}
>
</div>
</TooltipTrigger>
<TooltipContent className='bg-[#202020] text-white'>
<p key={`box-title-${dayIndex + 1}`}>{frequency} submissions on {monthData[selectedMonth]} {x} , {selectedYear}</p>
</TooltipContent>
</Tooltip>
</React.Fragment>
);
})}
</TooltipProvider>
</div>
)
}

export default React.memo(Calendar);
122 changes: 122 additions & 0 deletions apps/web/components/CalendarRenderer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
'use client'
import React, { useState } from 'react'
import Calendar from './Calendar'
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@repo/ui/select';

interface CalendarRendererProps {
acceptedSubmissions: any;
monthData: string[];
}

export default function CalendarRenderer({ acceptedSubmissions, monthData }: CalendarRendererProps) {
const [selectedMonth, setSelectedMonth] = useState(String(new Date().getMonth()));
const [selectedYear, setSelectedYear] = useState(String(new Date().getFullYear()));
const selectedMonthSubmissionsDates: string[] = acceptedSubmissions?.map((x: any) => x.createdAt.toLocaleString("en-GB")).filter((date: any) => Number(date.split(',')[0].split("/")[1]) - 1 === Number(selectedMonth) && Number(date.split(',')[0].split('/')[2]) === new Date().getFullYear());
const yearWiseSubmissionDates: string[] = acceptedSubmissions?.map((x: any) => x.createdAt.toLocaleString("en-GB")).filter((date: any) => Number(date.split(',')[0].split('/')[2]) === Number(selectedYear));

const generateYearsData = (currentYear: number) => {
let finalYearsArray = [];
let it = 0;
while (currentYear >= 2023) {
finalYearsArray[it] = currentYear;
currentYear--;
it++;
}
return finalYearsArray;
}

return (
<div className='flex flex-col'>
<div className='flex flex-wrap gap-2 mb-2 items-center justify-between p-3'>
<div className='text-xl font-semibold'>{selectedMonthSubmissionsDates && selectedMonthSubmissionsDates.length} Submission(s) <span className='text-xs opacity-80'>in {monthData[Number(selectedMonth)]} {new Date().getFullYear()}</span></div>
<div>
<Select value={selectedMonth} onValueChange={(val) => setSelectedMonth(val)}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select month" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
{monthData.map((item: string, index: number) => {
if (index > new Date().getMonth()) {
return;
}
return (
<SelectItem key={`select-month-${index}`} className='cursor-pointer' value={String(index)}>{item}</SelectItem>
);
})}
</SelectGroup>
</SelectContent>
</Select>
</div>
</div>

{/* Rendering Single month Calendar */}
<main className='flex overflow-auto border-b-2 pb-4 items-center gap-2 pr-4 h-fit'>
<Calendar
submissionDates={selectedMonthSubmissionsDates}
selectedMonth={Number(selectedMonth)}
monthData={monthData}
type={"single"}
isCurrentMonth={new Date().getMonth() === Number(selectedMonth)}
selectedYear={new Date().getFullYear()}
/>
</main>

<div className='my-3 px-3 flex flex-wrap gap-2 mb-2 items-center justify-between text-xl font-semibold'>
<div>
{yearWiseSubmissionDates && yearWiseSubmissionDates.length} Submissions <span className='text-xs opacity-80'>in {selectedYear}</span>
</div>
<div>
<Select value={selectedYear} onValueChange={(val) => setSelectedYear(val)}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select month" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
{generateYearsData(new Date().getFullYear()).map((item, index) => (
<SelectItem className='cursor-pointer' value={String(item)}>{item}</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
</div>
</div>

{/* Rendering each month Calendar */}

<main className='flex max-w-full overflow-auto mt-10 items-center m-auto gap-2 px-4 h-fit'>
{
monthData.map((item: string, index: number) => {
const eachMonthSubmissionDates = acceptedSubmissions?.map((x: any) => x.createdAt.toLocaleString("en-GB")).filter((date: any) => Number(date.split("/")[1]) - 1 === Number(index) && Number(date.split(',')[0].split('/')[2]) === Number(selectedYear));
const isCurrentMonth = new Date().getMonth() === Number(index) && new Date().getFullYear() === Number(selectedYear);
return (
<div key={`each-month-render-${index}`} className={`${(index <= new Date().getMonth() && new Date().getFullYear() === Number(selectedYear)) ? "opacity-100" : "opacity-25"} flex flex-col gap-4 pb-4 items-center`}>
<Calendar
childKey={`each-month-render-calendar-${index}`}
selectedYear={Number(selectedYear)}
type={"multiple"}
isCurrentMonth={isCurrentMonth}
submissionDates={eachMonthSubmissionDates}
selectedMonth={index}
monthData={monthData}
/>
<div className={`${isCurrentMonth ? "bg-[#3b82f6]" : "border-none"} w-full flex items-center justify-center py-[0.125rem] text-xs rounded-md`}>
{item.slice(0, 3)}
</div>
</div>
);
})
}
</main>
<div className='flex items-center mt-4 justify-end px-4 h-[4rem]'>
<div className='flex gap-2 font-semibold items-center'>
<span>Less</span>
{['#161b22', '#006d32', '#26a641', '#39d353'].map((colorHash, index) => (
<span key={`color-hash-${index}`} className={`w-[0.8rem] h-[0.8rem] rounded-sm bg-[${colorHash}]`}></span>
))}
<span>More</span>
</div>
</div>
</div>
)
}
25 changes: 2 additions & 23 deletions packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,8 @@
"version": "0.0.0",
"private": true,
"exports": {
"./components": "./src/index.tsx",
"./button": "./src/shad/ui/button.tsx",
"./card": "./src/shad/ui/card.tsx",
"./code": "./src/code.tsx",
"./globals.css": "./app/globals.css",
"./utils": "./lib/utils.ts",
"./pages": "./src/pages/index.ts",
"./toast": "./src/shad/ui/toast.tsx",
"./toaster": "./src/shad/ui/toaster.tsx",
"./use-toast": "./src/shad/ui/use-toast.ts",
"./table": "./src/shad/ui/table.tsx",
"./badge": "./src/shad/ui/badge.tsx",
"./select": "./src/shad/ui/select.tsx",
"./input": "./src/shad/ui/input.tsx",
"./label": "./src/shad/ui/label.tsx",
"./checkbox": "./src/shad/ui/checkbox.tsx",
"./profileOptions": "./src/profile/ProfileOptions.tsx",
"./Blog": "./src/Blog.tsx",
"./CodeProblemRenderer": "./src/code/CodeProblemRenderer.tsx",
"./MCQQuestionRenderer": "./src/MCQQuestionRenderer.tsx",
"./MCQRenderer" : "./src/mcq/MCQRenderer.tsx",
"./RedirectToLoginCard": "./src/RedirectToLoginCard.tsx",
"./UserImage": "./src/UserImage.tsx"
".": "./src/index.ts",
"./utils": "./src/lib/utils.ts"
},
"scripts": {
"lint": "eslint . --max-warnings 0",
Expand Down
53 changes: 0 additions & 53 deletions packages/ui/src/profile/ProfileOptions.tsx

This file was deleted.

Loading