Connect, collaborate, and grow with a community of TypeScript developers
Add Comment Upvotes (#452)
Ben Asokanthanddfbc68aab58
diff --git a/apps/web/src/app/challenge/[id]/getChallengeRouteData.ts b/apps/web/src/app/challenge/[id]/getChallengeRouteData.tsindex 136e3670..2e892add 100644--- a/apps/web/src/app/challenge/[id]/getChallengeRouteData.ts+++ b/apps/web/src/app/challenge/[id]/getChallengeRouteData.ts@@ -1,7 +1,7 @@'use server';import { type Session } from '@repo/auth/server';-import { cache } from 'react';import { prisma } from '@repo/db';+import { cache } from 'react';export type ChallengeRouteData = NonNullable<Awaited<ReturnType<typeof getChallengeRouteData>>>;@@ -15,7 +15,13 @@ export const getChallengeRouteData = cache((id: string, session: Session | null)include: {user: true,_count: {- select: { vote: true },+ select: {+ vote: {+ where: {+ rootType: 'CHALLENGE',+ },+ },+ },},vote: {where: {diff --git a/apps/web/src/app/challenge/_components/comments/comment.action.ts b/apps/web/src/app/challenge/_components/comments/comment.action.tsindex 11da7740..3e7c7d52 100644--- a/apps/web/src/app/challenge/_components/comments/comment.action.ts+++ b/apps/web/src/app/challenge/_components/comments/comment.action.ts@@ -115,29 +115,3 @@ async function deleteCommentWithChildren(prisma: PrismaClient, node: Comment) {},});}--export type CommentsByChallengeId = NonNullable<- Awaited<ReturnType<typeof getCommentsByChallengeId>>->;-export async function getCommentsByChallengeId(id: number) {- return await prisma.comment.findMany({- where: {- rootType: 'CHALLENGE',- rootChallengeId: id,- visible: true,- },- include: {- user: true,- _count: {- select: {- replies: true,- },- },- },- orderBy: [- {- createdAt: 'desc',- },- ],- });-}diff --git a/apps/web/src/app/challenge/_components/comments/comment.tsx b/apps/web/src/app/challenge/_components/comments/comment.tsxindex daa49933..2bfe947c 100644--- a/apps/web/src/app/challenge/_components/comments/comment.tsx+++ b/apps/web/src/app/challenge/_components/comments/comment.tsx@@ -1,24 +1,25 @@'use client';+import { useSession } from '@repo/auth/react';import { type CommentRoot } from '@repo/db/types';-import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';+import { Tooltip, TooltipContent, TooltipTrigger, UserBadge, toast } from '@repo/ui';import { ChevronDown, ChevronUp, Pencil, Reply, Share, Trash2 } from '@repo/ui/icons';-import { useSession } from '@repo/auth/react';-import { useEffect, useRef, useState } from 'react';-import { z } from 'zod';+import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';import clsx from 'clsx';-import { Tooltip, TooltipContent, TooltipTrigger, toast, UserBadge } from '@repo/ui';import Link from 'next/link';-import { CommentInput } from './comment-input';-import { replyComment, updateComment, type CommentsByChallengeId } from './comment.action';-import { CommentDeleteDialog } from './delete';-import { getPaginatedComments } from './getCommentRouteData';+import { useEffect, useRef, useState } from 'react';+import { z } from 'zod';+import { ReportDialog } from '~/components/ReportDialog';import { Markdown } from '~/components/ui/markdown';import { getRelativeTime } from '~/utils/relativeTime';-import { ReportDialog } from '~/components/ReportDialog';+import { Vote } from '../vote';+import { CommentInput } from './comment-input';+import { replyComment, updateComment } from './comment.action';+import { CommentDeleteDialog } from './delete';+import { getPaginatedComments, type PaginatedComments } from './getCommentRouteData';interface SingleCommentProps {- comment: CommentsByChallengeId[number];+ comment: PaginatedComments['comments'][number];readonly?: boolean;isReply?: boolean;onClickReply?: () => void;@@ -63,7 +64,12 @@ export function Comment({ comment, readonly = false, rootId, type, queryKey }: Cconst { data, fetchNextPage, isFetching } = useInfiniteQuery({queryKey: replyQueryKey,queryFn: ({ pageParam = 1 }) =>- getPaginatedComments({ rootId, rootType: type, page: pageParam, parentId: comment.id }),+ getPaginatedComments({+ rootId,+ rootType: type,+ page: pageParam,+ parentId: comment.id,+ }),getNextPageParam: (_, pages) => pages.length + 1,staleTime: 5000,});@@ -174,6 +180,8 @@ function SingleComment({const [text, setText] = useState(comment.text);const [isEditing, setIsEditing] = useState(false);+ const session = useSession();+async function updateChallengeComment() {try {const res = await updateComment(text, comment.id);@@ -244,6 +252,23 @@ function SingleComment({<div className="my-auto flex items-center gap-4">{!readonly && (<>+ <Vote+ voteCount={comment._count.vote}+ initialHasVoted={comment.vote.length > 0}+ disabled={!session?.data?.user?.id || comment.userId === session?.data?.user?.id}+ rootType="COMMENT"+ rootId={comment.id}+ onVote={(didUpvote: boolean) => {+ comment.vote = didUpvote+ ? [+ {+ userId: session?.data?.user?.id ?? '',+ },+ ]+ : [];+ comment._count.vote += didUpvote ? 1 : -1;+ }}+ /><Reply className="absolute -left-6 h-4 w-4 opacity-50" /><divclassName="flex cursor-pointer items-center gap-1 text-neutral-500 duration-200 hover:text-neutral-400 dark:text-neutral-400 dark:hover:text-neutral-300"@@ -254,7 +279,6 @@ function SingleComment({<Share className="h-3 w-3" /><div className="hidden text-[0.8rem] sm:block">Share</div></div>- {/* TODO: make dis work */}{!isReply && (<buttonclassName="flex cursor-pointer items-center gap-1 text-neutral-500 duration-200 disabled:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-300"diff --git a/apps/web/src/app/challenge/_components/comments/delete/index.tsx b/apps/web/src/app/challenge/_components/comments/delete/index.tsxindex 149bbb8c..89bade47 100644--- a/apps/web/src/app/challenge/_components/comments/delete/index.tsx+++ b/apps/web/src/app/challenge/_components/comments/delete/index.tsx@@ -1,6 +1,4 @@import { type DialogTriggerProps } from '@radix-ui/react-dialog';-import { useState } from 'react';-import { useQueryClient } from '@tanstack/react-query';import {Button,Dialog,@@ -9,16 +7,19 @@ import {Tooltip,TooltipContent,TooltipTrigger,- TypographyP,TypographyLarge,+ TypographyP,toast,} from '@repo/ui';-import { deleteComment, type CommentsByChallengeId } from '../comment.action';-import { getRelativeTime } from '~/utils/relativeTime';+import { useQueryClient } from '@tanstack/react-query';+import { useState } from 'react';import { Markdown } from '~/components/ui/markdown';+import { getRelativeTime } from '~/utils/relativeTime';+import { deleteComment } from '../comment.action';+import { type PaginatedComments } from '../getCommentRouteData';interface CommentDeleteDialogProps extends DialogTriggerProps {- comment: CommentsByChallengeId[number];+ comment: PaginatedComments['comments'][number];queryKey?: (number | string)[];}diff --git a/apps/web/src/app/challenge/_components/comments/getCommentRouteData.ts b/apps/web/src/app/challenge/_components/comments/getCommentRouteData.tsindex 16087603..60aac2cb 100644--- a/apps/web/src/app/challenge/_components/comments/getCommentRouteData.ts+++ b/apps/web/src/app/challenge/_components/comments/getCommentRouteData.ts@@ -1,6 +1,7 @@'use server';-import type { CommentRoot } from '@repo/db/types';+import { getServerAuthSession } from '@repo/auth/server';import { prisma } from '@repo/db';+import type { CommentRoot } from '@repo/db/types';const PAGESIZE = 10;@@ -17,6 +18,7 @@ export async function getPaginatedComments({rootType: CommentRoot;parentId?: number | null;}) {+ const session = await getServerAuthSession();const totalComments = await prisma.comment.count({where: {rootType,@@ -43,10 +45,27 @@ export async function getPaginatedComments({_count: {select: {replies: true,+ vote: true,+ },+ },+ vote: {+ select: {+ userId: true,+ },+ where: {+ userId: session?.user.id || '',+ },+ },+ rootChallenge: {+ select: {+ name: true,+ },+ },+ rootSolution: {+ select: {+ title: true,},},- rootChallenge: true,- rootSolution: true,},});diff --git a/apps/web/src/app/challenge/_components/comments/index.tsx b/apps/web/src/app/challenge/_components/comments/index.tsxindex bc586914..a59a08e5 100644--- a/apps/web/src/app/challenge/_components/comments/index.tsx+++ b/apps/web/src/app/challenge/_components/comments/index.tsx@@ -1,17 +1,17 @@'use client';import type { CommentRoot } from '@repo/db/types';+import { Button, toast } from '@repo/ui';+import { ChevronDown, ChevronLeft, ChevronRight, MessageCircle } from '@repo/ui/icons';import { useQuery, useQueryClient } from '@tanstack/react-query';import clsx from 'clsx';-import { ChevronDown, ChevronLeft, ChevronRight, MessageCircle } from '@repo/ui/icons';import { useRef, useState } from 'react';-import { toast, Button } from '@repo/ui';+import { Comment } from './comment';import { CommentInput } from './comment-input';import { CommentSkeleton } from './comment-skeleton';import { addComment } from './comment.action';import { getPaginatedComments } from './getCommentRouteData';import NoComments from './nocomments';-import { Comment } from './comment';interface Props {rootId: number;@@ -23,7 +23,6 @@ export function Comments({ rootId, type }: Props) {const [text, setText] = useState('');const commentContainerRef = useRef<HTMLDivElement>(null);const queryClient = useQueryClient();-const [page, setPage] = useState(1);const queryKey = [`${type.toLowerCase()}-${rootId}-comments`, page];diff --git a/apps/web/src/app/challenge/_components/description/index.tsx b/apps/web/src/app/challenge/_components/description/index.tsxindex e07235b8..3eaed45a 100644--- a/apps/web/src/app/challenge/_components/description/index.tsx+++ b/apps/web/src/app/challenge/_components/description/index.tsx@@ -1,12 +1,8 @@'use client';-import { clsx } from 'clsx';-import { debounce } from 'lodash';import { useSession } from '@repo/auth/react';-import { useRouter } from 'next/navigation';-import { useRef, useState } from 'react';-import { Bookmark as BookmarkIcon, Flag, Share, ThumbsUp } from '@repo/ui/icons';import {+ ActionMenu,Dialog,DialogContent,DialogHeader,@@ -18,16 +14,19 @@ import {TooltipTrigger,TypographyH3,UserBadge,- ActionMenu,} from '@repo/ui';+import { Bookmark as BookmarkIcon, Flag, Share } from '@repo/ui/icons';+import { clsx } from 'clsx';+import { debounce } from 'lodash';import Link from 'next/link';-import { ShareForm } from '../share-form';-import { addOrRemoveBookmark } from '../bookmark.action';-import { incrementOrDecrementUpvote } from '../increment.action';-import { Markdown } from '~/components/ui/markdown';+import { useRef, useState } from 'react';import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';-import { getRelativeTime } from '~/utils/relativeTime';import { ReportDialog } from '~/components/ReportDialog';+import { Markdown } from '~/components/ui/markdown';+import { getRelativeTime } from '~/utils/relativeTime';+import { addOrRemoveBookmark } from '../bookmark.action';+import { ShareForm } from '../share-form';+import { Vote } from '../vote';interface Props {challenge: ChallengeRouteData;@@ -41,23 +40,9 @@ export interface FormValues {}export function Description({ challenge }: Props) {- const router = useRouter();- const [votes, setVotes] = useState(challenge._count.vote);- const [hasVoted, setHasVoted] = useState(challenge.vote.length > 0);const [hasBookmarked, setHasBookmarked] = useState(challenge.bookmark.length > 0);const session = useSession();- const debouncedSearch = useRef(- debounce(async (challengeId: number, userId: string, shouldIncrement: boolean) => {- const votes = await incrementOrDecrementUpvote(challengeId, userId, shouldIncrement);- if (votes !== undefined && votes !== null) {- setVotes(votes);- }-- router.refresh();- }, 500),- ).current;-const debouncedBookmark = useRef(debounce(async (challengeId: number, userId: string, shouldBookmark: boolean) => {try {@@ -161,58 +146,13 @@ export function Description({ challenge }: Props) {<p>{session.data?.user.id ? 'Bookmark' : 'Login to Bookmark'}</p></TooltipContent></Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <button- className="group flex h-6 items-center gap-1 rounded-full bg-zinc-200 pl-[0.675rem] pr-2 text-sm disabled:cursor-not-allowed disabled:bg-zinc-100 dark:bg-zinc-700 disabled:dark:bg-zinc-700/50"- disabled={!session.data?.user.id}- onClick={() => {- let shouldIncrement = false;- if (hasVoted) {- setVotes((v) => v - 1);- shouldIncrement = false;- setHasVoted(false);- } else {- setVotes((v) => v + 1);- shouldIncrement = true;- setHasVoted(true);- }- debouncedSearch(challenge.id, session.data?.user.id!, shouldIncrement)?.catch(- (e) => {- console.error(e);- },- );- }}- >- <ThumbsUp- className={clsx(- {- 'fill-emerald-600 stroke-emerald-600 group-hover:stroke-emerald-600 dark:fill-emerald-400 dark:stroke-emerald-400 group-hover:dark:stroke-emerald-400':- hasVoted,- 'stroke-zinc-500 group-hover:stroke-zinc-600 group-disabled:stroke-zinc-300 dark:stroke-zinc-300 group-hover:dark:stroke-zinc-100 group-disabled:dark:stroke-zinc-500/50':- !hasVoted,- },- 'h-4 w-4 duration-200',- )}- />- <span- className={clsx(- {- 'text-emerald-600 dark:text-emerald-400': hasVoted,- 'text-zinc-500 group-hover:text-zinc-600 group-disabled:text-zinc-300 dark:text-zinc-300 group-hover:dark:text-zinc-100 group-disabled:dark:text-zinc-500/50':- !hasVoted,- },- 'my-auto w-4 self-end duration-300',- )}- >- {votes}- </span>- </button>- </TooltipTrigger>- <TooltipContent>- <p>{session.data?.user.id ? 'Upvote' : 'Login to Upvote'}</p>- </TooltipContent>- </Tooltip>+ <Vote+ voteCount={challenge._count.vote}+ initialHasVoted={challenge.vote.length > 0}+ disabled={!session?.data?.user?.id}+ rootType="CHALLENGE"+ rootId={challenge?.id}+ /></div>{/* Challenge Description */}<div className="prose-invert prose-h3:text-xl mt-6 leading-8">diff --git a/apps/web/src/app/challenge/_components/increment.action.ts b/apps/web/src/app/challenge/_components/increment.action.tsdeleted file mode 100644index 2c3160d0..00000000--- a/apps/web/src/app/challenge/_components/increment.action.ts+++ /dev/null@@ -1,41 +0,0 @@-'use server';-import { prisma } from '@repo/db';--export async function incrementOrDecrementUpvote(- challengeId: number,- userId: string,- shouldIncrement: boolean,-) {- const voteExists = await prisma.vote.findFirst({- where: {- challengeId,- userId,- },- });- if (!voteExists && shouldIncrement) {- await prisma.vote.create({- data: {- challengeId,- userId,- },- });- }- if (voteExists && !shouldIncrement) {- await prisma.vote.delete({- where: {- id: voteExists.id,- },- });- }-- const count = await prisma.challenge.findFirst({- where: { id: challengeId },- include: {- _count: {- select: { vote: true },- },- },- });-- return count?._count.vote;-}diff --git a/apps/web/src/app/challenge/_components/vote.tsx b/apps/web/src/app/challenge/_components/vote.tsxnew file mode 100644index 00000000..311d17e6--- /dev/null+++ b/apps/web/src/app/challenge/_components/vote.tsx@@ -0,0 +1,99 @@+'use client';++import { useSession } from '@repo/auth/react';+import type { VoteType } from '@repo/db/types';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui';+import { ThumbsUp } from '@repo/ui/icons';+import clsx from 'clsx';+import { debounce } from 'lodash';+import { useRef, useState } from 'react';+import { incrementOrDecrementUpvote } from '../increment.action';++interface VoteProps {+ voteCount: number;+ initialHasVoted?: boolean;+ rootId: number;+ rootType: VoteType;+ disabled?: boolean;+ onVote?: (didUpvote: boolean) => void;+}++export function Vote({+ voteCount,+ initialHasVoted,+ rootId,+ rootType,+ disabled,+ onVote,+}: VoteProps) {+ const [votes, setVotes] = useState(voteCount);+ const [hasVoted, setHasVoted] = useState(initialHasVoted);+ const session = useSession();++ const debouncedIncrement = useRef(+ debounce(async (shouldIncrement: boolean) => {+ await incrementOrDecrementUpvote(rootId, rootType, shouldIncrement);+ }, 500),+ ).current;++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ className="group flex h-6 items-center gap-1 rounded-full bg-zinc-200 pl-[0.675rem] pr-2 text-sm disabled:cursor-not-allowed disabled:bg-zinc-100 dark:bg-zinc-700 disabled:dark:bg-zinc-700/50"+ disabled={disabled}+ onClick={() => {+ let shouldIncrement = false;+ const previousVotes = votes;++ if (hasVoted) {+ setVotes((v) => v - 1);+ shouldIncrement = false;+ setHasVoted(false);+ } else {+ setVotes((v) => v + 1);+ shouldIncrement = true;+ setHasVoted(true);+ }++ if (onVote) {+ onVote(shouldIncrement);+ }++ debouncedIncrement(shouldIncrement)?.catch((e) => {+ setVotes(previousVotes);+ console.error(e);+ });+ }}+ >+ <ThumbsUp+ className={clsx(+ {+ 'fill-emerald-600 stroke-emerald-600 group-hover:stroke-emerald-600 dark:fill-emerald-400 dark:stroke-emerald-400 group-hover:dark:stroke-emerald-400':+ hasVoted,+ 'stroke-zinc-500 group-hover:stroke-zinc-600 group-disabled:stroke-zinc-300 dark:stroke-zinc-300 group-hover:dark:stroke-zinc-100 group-disabled:dark:stroke-zinc-500/50':+ !hasVoted,+ },+ 'h-4 w-4 duration-200',+ )}+ />+ <span+ className={clsx(+ {+ 'text-emerald-600 dark:text-emerald-400': hasVoted,+ 'text-zinc-500 group-hover:text-zinc-600 group-disabled:text-zinc-300 dark:text-zinc-300 group-hover:dark:text-zinc-100 group-disabled:dark:text-zinc-500/50':+ !hasVoted,+ },+ 'my-auto w-4 self-end duration-300',+ )}+ >+ {votes}+ </span>+ </button>+ </TooltipTrigger>+ <TooltipContent>+ <p>{session.data?.user.id ? 'Upvote' : 'Login to Upvote'}</p>+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/apps/web/src/app/challenge/increment.action.ts b/apps/web/src/app/challenge/increment.action.tsnew file mode 100644index 00000000..c0d57298--- /dev/null+++ b/apps/web/src/app/challenge/increment.action.ts@@ -0,0 +1,43 @@+'use server';+import { getServerAuthSession } from '@repo/auth/server';+import { prisma } from '@repo/db';+import type { VoteType } from '@repo/db/types';++export async function incrementOrDecrementUpvote(+ id: number,+ rootType: VoteType,+ shouldIncrement: boolean,+) {+ const session = await getServerAuthSession();+ const voteExists = await prisma.vote.findFirst({+ where: {+ rootType,+ challengeId: rootType === 'CHALLENGE' ? id : undefined,+ commentId: rootType === 'COMMENT' ? id : undefined,+ sharedSolutionId: rootType === 'SHAREDSOLUTION' ? id : undefined,+ submissionId: rootType === 'SUBMISSION' ? id : undefined,+ userId: session?.user.id,+ },+ });++ if (session?.user && !voteExists && shouldIncrement) {+ await prisma.vote.create({+ data: {+ rootType,+ challengeId: rootType === 'CHALLENGE' ? id : undefined,+ commentId: rootType === 'COMMENT' ? id : undefined,+ sharedSolutionId: rootType === 'SHAREDSOLUTION' ? id : undefined,+ submissionId: rootType === 'SUBMISSION' ? id : undefined,+ userId: session?.user.id,+ },+ });+ }++ if (session?.user && voteExists && !shouldIncrement) {+ await prisma.vote.delete({+ where: {+ id: voteExists.id,+ },+ });+ }+}diff --git a/packages/db/mocks/comment.mock.ts b/packages/db/mocks/comment.mock.tsindex 83476483..8e1ec2b2 100644--- a/packages/db/mocks/comment.mock.ts+++ b/packages/db/mocks/comment.mock.ts@@ -5,9 +5,14 @@ import { trashId } from '../seed';** @returns Creates a mock user.*/-export default function CommentMock(parentId?: number): Prisma.CommentCreateManyInput {+export default function CommentMock(+ commentNumber: number,+ parentId?: number,+): Prisma.CommentCreateManyInput {return {- text: 'here is a comment',+ text: `here is a comment ${+ !parentId ? commentNumber : `reply ${commentNumber} to parent ${parentId}`+ }`,userId: trashId,parentId,};diff --git a/packages/db/mocks/vote.mock.ts b/packages/db/mocks/vote.mock.tsindex 27280a41..0060db3c 100644--- a/packages/db/mocks/vote.mock.ts+++ b/packages/db/mocks/vote.mock.ts@@ -1,8 +1,10 @@-import { type Prisma } from '@prisma/client';import { faker } from '@faker-js/faker';+import { type Prisma } from '@prisma/client';export function VoteMock(userIds: string[]): Prisma.VoteCreateManyInput {return {userId: faker.helpers.arrayElement(userIds),+ rootType: 'CHALLENGE',+ challengeId: 2,};}diff --git a/packages/db/schema.prisma b/packages/db/schema.prismaindex 3eb80967..12a443df 100644--- a/packages/db/schema.prisma+++ b/packages/db/schema.prisma@@ -177,19 +177,34 @@ model Challenge {@@index([userId])}+enum VoteType {+ CHALLENGE+ COMMENT+ SUBMISSION+ SHAREDSOLUTION+}+model Vote {- id Int @id @default(autoincrement())- user User @relation(fields: [userId], references: [id])- userId String- challenge Challenge? @relation(fields: [challengeId], references: [id])- challengeId Int?- submission Submission? @relation(fields: [submissionId], references: [id])- submissionId Int?+ id Int @id @default(autoincrement())+ user User @relation(fields: [userId], references: [id])+ userId String+ rootType VoteType++ challenge Challenge? @relation(fields: [challengeId], references: [id])+ challengeId Int?++ comment Comment? @relation(fields: [commentId], references: [id])+ commentId Int?++ submission Submission? @relation(fields: [submissionId], references: [id])+ submissionId Int?+sharedSolution SharedSolution? @relation(fields: [sharedSolutionId], references: [id])sharedSolutionId Int?@@index([userId])@@index([challengeId])+ @@index([commentId])@@index([submissionId])@@index([sharedSolutionId])}@@ -336,6 +351,7 @@ model Comment {createdAt DateTime @default(now())updatedAt DateTime @updatedAt+ vote Vote[]@@index([rootSolutionId])@@index([rootChallengeId])diff --git a/packages/db/seed/index.ts b/packages/db/seed/index.tsindex 50b59ac7..4972a35e 100644--- a/packages/db/seed/index.ts+++ b/packages/db/seed/index.ts@@ -59,7 +59,8 @@ try {},});- const comments = Array.from({ length: 50 }, () => CommentMock());+ let commentNum = 0;+ const comments = Array.from({ length: 50 }, () => CommentMock(++commentNum));const replies: Prisma.CommentCreateManyInput[] = [];@@ -76,7 +77,7 @@ try {});for (const comment of createdComments) {- replies.push(CommentMock(comment.id), CommentMock(comment.id));+ replies.push(CommentMock(++commentNum, comment.id), CommentMock(++commentNum, comment.id));}await prisma.challenge.update({