Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

chore: consolidate solution + challenge comment UIs

bautistaaa8cb91c1a0e4c
diff --git a/src/app/challenge/[id]/page.tsx b/src/app/challenge/[id]/page.tsx
index cd8516cd..72b71184 100644
--- a/src/app/challenge/[id]/page.tsx
+++ b/src/app/challenge/[id]/page.tsx
@@ -21,7 +21,8 @@ export default async function Challenges({ params: { id } }: Props) {
return (
<div className="relative h-full">
<Description challenge={challenge}></Description>
- <Comments challengeId={challenge.id} commentCount={challenge.comment.length} />
+ {/* BUG: comment length wont update when adding/deleting a comment */}
+ <Comments rootId={challenge.id} commentCount={challenge.comment.length} type="CHALLENGE" />
</div>
);
}
diff --git a/src/components/challenge/comments/comment.action.ts b/src/components/challenge/comments/comment.action.ts
index 3f6c9a7b..a40adc3c 100644
--- a/src/components/challenge/comments/comment.action.ts
+++ b/src/components/challenge/comments/comment.action.ts
@@ -1,25 +1,20 @@
'use server';
-import { type Prisma } from '@prisma/client';
+import type { CommentRoot } from '@prisma/client';
import { getServerAuthSession } from '~/server/auth';
import { prisma } from '~/server/db';
-export type ChallengeComment = Omit<
- Prisma.CommentCreateManyInput,
- 'rootType' | 'rootSolutionId' | 'userId'
-> & { rootType: 'CHALLENGE' };
-
-export type SolutionComment = Omit<
- Prisma.CommentCreateManyInput,
- 'rootType' | 'rootChallengeId' | 'userId'
-> & { rootType: 'SOLUTION' };
-
/**
*
* @param comment a Challenge or Solution-based comment.
* @returns the prisma create response.
*/
-export async function addComment(comment: ChallengeComment | SolutionComment) {
+interface CommentToCreate {
+ text: string;
+ rootType: CommentRoot;
+ rootId: number;
+}
+export async function addComment(comment: CommentToCreate) {
const session = await getServerAuthSession();
if (!session?.user.id) return 'unauthorized';
@@ -27,9 +22,16 @@ export async function addComment(comment: ChallengeComment | SolutionComment) {
if (!session?.user.id) return 'unauthorized';
if (comment.text.length === 0) return 'text_is_empty';
+ const { rootId, ...commentToCreate } = {
+ ...comment,
+ ...(comment.rootType === 'CHALLENGE'
+ ? { rootChallengeId: comment.rootId }
+ : { rootSolutionId: comment.rootId }),
+ };
+
return await prisma.comment.create({
data: {
- ...comment,
+ ...commentToCreate,
userId: session.user.id,
},
});
diff --git a/src/components/challenge/comments/getCommentRouteData.ts b/src/components/challenge/comments/getCommentRouteData.ts
index 5ddc60a8..019835b5 100644
--- a/src/components/challenge/comments/getCommentRouteData.ts
+++ b/src/components/challenge/comments/getCommentRouteData.ts
@@ -1,20 +1,23 @@
'use server';
+import type { CommentRoot } from '@prisma/client';
import { prisma } from '~/server/db';
export type PaginatedComments = NonNullable<Awaited<ReturnType<typeof getPaginatedComments>>>;
export async function getPaginatedComments({
- challengeId,
page,
+ rootId,
+ rootType,
}: {
- challengeId: number;
+ rootId: number;
+ rootType: CommentRoot;
page: number;
}) {
const totalComments = await prisma.comment.count({
where: {
- rootType: 'CHALLENGE',
- rootChallengeId: challengeId,
+ rootType,
visible: true,
+ ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),
},
});
@@ -22,8 +25,8 @@ export async function getPaginatedComments({
skip: (page - 1) * 10,
take: 10,
where: {
- rootType: 'CHALLENGE',
- rootChallengeId: challengeId,
+ rootType,
+ ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),
visible: true,
},
orderBy: {
diff --git a/src/components/challenge/comments/index.tsx b/src/components/challenge/comments/index.tsx
index 5297eaba..97a34cb8 100644
--- a/src/components/challenge/comments/index.tsx
+++ b/src/components/challenge/comments/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { CommentRoot } from '@prisma/client';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import clsx from 'clsx';
import { ChevronDown, ChevronLeft, ChevronRight, MessageCircle } from 'lucide-react';
@@ -15,11 +16,12 @@ import { getPaginatedComments } from './getCommentRouteData';
import NoComments from './nocomments';
interface Props {
- challengeId: number;
+ rootId: number;
commentCount: number;
+ type: CommentRoot;
}
-export const Comments = ({ challengeId, commentCount }: Props) => {
+export const Comments = ({ rootId, commentCount, type }: Props) => {
const [showComments, setShowComments] = useState(false);
const [text, setText] = useState('');
const commentContainerRef = useRef<HTMLDivElement>(null);
@@ -28,9 +30,12 @@ export const Comments = ({ challengeId, commentCount }: Props) => {
const [page, setPage] = useState(1);
+ const queryKey =
+ type === 'CHALLENGE' ? `challenge-${rootId}-comments` : `solution-${rootId}-comments`;
+
const { status, data } = useQuery({
- queryKey: [`challenge-${challengeId}-comments`, page],
- queryFn: () => getPaginatedComments({ challengeId, page }),
+ queryKey: [queryKey, page],
+ queryFn: () => getPaginatedComments({ rootId, page, rootType: type }),
keepPreviousData: true,
staleTime: 5000,
});
@@ -46,8 +51,8 @@ export const Comments = ({ challengeId, commentCount }: Props) => {
try {
const res = await addComment({
text,
- rootChallengeId: challengeId,
- rootType: 'CHALLENGE',
+ rootId,
+ rootType: type,
});
if (res === 'text_is_empty') {
toast({
@@ -61,7 +66,7 @@ export const Comments = ({ challengeId, commentCount }: Props) => {
});
}
setText('');
- queryClient.invalidateQueries([`challenge-${challengeId}-comments`, page]);
+ queryClient.invalidateQueries([queryKey, page]);
} catch (e) {
toast({
title: 'Unauthorized',
diff --git a/src/components/challenge/solutions/getSolutionData.ts b/src/components/challenge/solutions/getSolutionData.ts
deleted file mode 100644
index 151a2abb..00000000
--- a/src/components/challenge/solutions/getSolutionData.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-'use server';
-import { prisma } from '~/server/db';
-
-export interface SolutionCommentQueryParams {
- solutionId: number;
- take?: number;
- lastCursor?: number;
-}
-
-export async function getInfiniteComments({
- solutionId,
- take = 10,
- lastCursor,
-}: SolutionCommentQueryParams) {
- const results = await prisma.comment.findMany({
- where: {
- rootType: 'SOLUTION',
- rootSolutionId: solutionId,
- },
- take,
- ...(lastCursor && {
- skip: 1,
- cursor: {
- id: lastCursor,
- },
- }),
- orderBy: {
- createdAt: 'desc',
- },
- include: {
- user: true,
- },
- });
-
- const last = results.at(-1);
- const hasNextPage =
- last && last.id
- ? await prisma.comment
- .findMany({
- where: {
- rootSolutionId: solutionId,
- },
- skip: 1,
- take: 1,
- cursor: {
- id: last.id,
- },
- })
- .then((f) => f.length > 0)
- : false;
-
- return {
- data: results,
- metaData: {
- lastCursor: last ? last.id : null,
- hasNextPage,
- },
- };
-}
diff --git a/src/components/challenge/solutions/index.tsx b/src/components/challenge/solutions/index.tsx
index 1abfecdf..1c65be6e 100644
--- a/src/components/challenge/solutions/index.tsx
+++ b/src/components/challenge/solutions/index.tsx
@@ -10,6 +10,7 @@ import { SolutionEditor } from './solution-editor';
import { UserBadge } from '~/components/ui/user-badge';
import NoSolutions from './nosolutions';
import SubmitSolution from './submit-solution';
+import { Button } from '~/components/ui/button';
interface Props {
challenge: ChallengeSolutionsRouteData;
@@ -73,7 +74,12 @@ function SolutionRow({
>
<h3 className="truncate font-bold">{solution.title}</h3>
<div className="flex items-center gap-1 text-neutral-600 dark:text-neutral-400">
- <UserBadge username={solution.user?.name ?? ''} />
+ <Button
+ className="-ml-[0.33rem] flex h-auto w-fit items-center rounded-full bg-transparent py-1 pl-[0.33rem] pr-2 text-xs font-bold text-neutral-700 hover:bg-black/10 dark:text-white dark:hover:bg-white/20"
+ size="sm"
+ >
+ @{solution.user?.name ?? ''}
+ </Button>
<div className="mr-auto text-sm text-neutral-500">
{getRelativeTime(solution.createdAt)}
</div>
diff --git a/src/components/challenge/solutions/solution-comments.tsx b/src/components/challenge/solutions/solution-comments.tsx
deleted file mode 100644
index 3add07f7..00000000
--- a/src/components/challenge/solutions/solution-comments.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-'use client';
-
-import clsx from 'clsx';
-import { ChevronDown, MessageCircle } from 'lucide-react';
-import { useRouter } from 'next/navigation';
-import { useEffect, useState } from 'react';
-import Comment from '~/components/challenge/comments/comment';
-import { Button } from '~/components/ui/button';
-import { toast } from '~/components/ui/use-toast';
-import NoComments from '../comments/nocomments';
-import { Textarea } from '~/components/ui/textarea';
-import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
-import { useInView } from 'react-intersection-observer';
-import { getInfiniteComments } from './getSolutionData';
-import { CommentSkeleton } from '../comments/comment-skeleton';
-import { addComment } from '../comments/comment.action';
-
-interface Props {
- solutionId: number;
- commentCount: number;
-}
-
-const Comments = ({ solutionId, commentCount }: Props) => {
- const [showComments, setShowComments] = useState(false);
- const [text, setText] = useState('');
- const [isCommenting, setIsCommenting] = useState(false);
- const router = useRouter();
- const { ref, inView } = useInView();
- const queryClient = useQueryClient();
-
- const { data, status, hasNextPage, fetchNextPage, isFetchingNextPage } = useInfiniteQuery({
- queryFn: ({ pageParam = '' }) =>
- getInfiniteComments({ solutionId, take: 10, lastCursor: pageParam }),
- queryKey: ['comments', solutionId],
- getNextPageParam: (lastPage) => lastPage.metaData.lastCursor,
- });
-
- const handleClick = () => {
- setShowComments(!showComments);
- };
-
- const handleEnterKey = async (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (!e.shiftKey && e.key === 'Enter' && !isCommenting) {
- await createChallengeComment();
- }
- };
-
- async function createChallengeComment() {
- try {
- setIsCommenting(true);
- const res = await addComment({
- text,
- rootSolutionId: solutionId,
- rootType: 'SOLUTION',
- });
- if (res === 'text_is_empty') {
- toast({
- title: 'Empty Comment',
- description: <p>You cannot post an empty comment.</p>,
- });
- } else if (res === 'unauthorized') {
- toast({
- title: 'Unauthorized',
- description: <p>You need to be signed in to post a comment.</p>,
- });
- }
- setIsCommenting(false);
- setText('');
- queryClient.invalidateQueries(['comments', solutionId]);
- } catch (e) {
- toast({
- title: 'Unauthorized',
- variant: 'destructive',
- description: <p>You need to be signed in to post a comment.</p>,
- });
- } finally {
- router.refresh();
- }
- }
-
- useEffect(() => {
- if (inView && hasNextPage) fetchNextPage();
- }, [hasNextPage, inView, fetchNextPage]);
-
- return (
- <div className="relative">
- <button
- className="flex w-full items-center justify-between gap-2 p-3 font-medium text-neutral-500 duration-300 hover:text-neutral-700 dark:hover:text-zinc-300"
- onClick={() => handleClick()}
- >
- <div className="flex items-center">
- <MessageCircle className="h-5 w-5"></MessageCircle>
- &nbsp; Comments ({commentCount})
- </div>
- <ChevronDown
- className={clsx('h-4 w-4 duration-300', {
- '-rotate-180': !showComments,
- })}
- ></ChevronDown>
- </button>
- <div
- className={clsx('flex flex-col-reverse overscroll-contain duration-300', {
- 'h-64 overflow-y-auto': showComments,
- 'h-0 overflow-y-hidden': !showComments,
- })}
- >
- {(status === 'loading' || isFetchingNextPage) && <CommentSkeleton />}
- {status === 'success' &&
- (data?.pages[0]?.data.length === 0 ? (
- <NoComments></NoComments>
- ) : (
- data?.pages.map((page) =>
- page.data.map((comment, index) =>
- page.data.length === index + 1 ? (
- <div ref={ref} key={`comment-${comment.id}`}>
- <Comment key={comment.id} comment={comment} />
- </div>
- ) : (
- <Comment key={comment.id} comment={comment} />
- ),
- ),
- )
- ))}
- </div>
- <div className="m-2 mt-0 flex items-end justify-between gap-2 rounded-xl bg-background/90 bg-neutral-100 p-1 pr-2 backdrop-blur-sm dark:border-zinc-700 dark:bg-zinc-700/90">
- <Textarea
- value={text}
- onChange={(e) => {
- setText(e.target.value);
- }}
- onKeyDown={handleEnterKey}
- rows={2}
- className="min-h-0 resize-none border-0 focus-visible:ring-0 focus-visible:ring-offset-0"
- placeholder="Enter your comment here."
- />
- <Button
- onClick={createChallengeComment}
- className="h-8 rounded-lg bg-emerald-600 px-3 py-2 hover:bg-emerald-500 dark:bg-emerald-400 dark:hover:bg-emerald-300"
- >
- Comment
- </Button>
- </div>
- </div>
- );
-};
-
-export default Comments;
diff --git a/src/components/challenge/solutions/solution-detail.tsx b/src/components/challenge/solutions/solution-detail.tsx
index 61b0c720..ffb90995 100644
--- a/src/components/challenge/solutions/solution-detail.tsx
+++ b/src/components/challenge/solutions/solution-detail.tsx
@@ -9,9 +9,10 @@ import { Markdown } from '~/components/ui/markdown';
import { TypographyLarge } from '~/components/ui/typography/large';
import { toast } from '~/components/ui/use-toast';
import { UserBadge } from '~/components/ui/user-badge';
-import Comment from './solution-comments';
import ReportDialog from '~/components/report';
import { ActionMenu } from '~/components/ui/action-menu';
+import { Comments } from '../comments';
+import { Tooltip, TooltipContent, TooltipTrigger } from '~/components/ui/tooltip';
interface Props {
solution: ChallengeSolution;
@@ -37,13 +38,29 @@ export function SolutionDetails({ solution }: Props) {
</div>
<div className="custom-scrollable-element flex-1 overflow-y-auto px-4 py-3">
<div className="mb-5 flex flex-col gap-3">
- <div className="flex items-center gap-2">
- <Avatar>
- <AvatarImage src={solution.user?.image ?? ''} alt="github profile picture" />
- <AvatarFallback>{solution.user?.name}</AvatarFallback>
- </Avatar>
- <TypographyLarge>{solution.title}</TypographyLarge>
- <div className="ml-auto">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Avatar>
+ <AvatarImage src={solution.user?.image ?? ''} alt="github profile picture" />
+ <AvatarFallback>{solution.user?.name}</AvatarFallback>
+ </Avatar>
+ <TypographyLarge>{solution.title}</TypographyLarge>
+ </div>
+ <div className="flex items-center gap-2">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ onClick={handleShareClick}
+ className="group p-0 text-gray-500 group-hover:text-gray-400"
+ >
+ <Share className="mr-2 h-4 w-4 stroke-gray-500 group-hover:stroke-gray-400" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Share challenge</p>
+ </TooltipContent>
+ </Tooltip>
<ReportDialog reportType="SOLUTION" solutionId={solution.id as number}>
<ActionMenu
items={[
@@ -70,17 +87,11 @@ export function SolutionDetails({ solution }: Props) {
</div>
<Markdown>{solution.description || ''}</Markdown>
</div>
- <div className="sticky bottom-0 -mx-[1px] overflow-hidden rounded-xl border border-zinc-300 border-b-background bg-background/90 shadow-[0_0_3rem_-0.25rem_#0004] backdrop-blur-sm duration-300 dark:border-zinc-700 dark:border-b-muted dark:bg-muted/90 dark:shadow-[0_0_3rem_-0.25rem_#0008]"></div>
- <Comment solutionId={solution.id as number} commentCount={solution.jimComments.length} />
- <div className="flex gap-2">
- <Button
- variant="ghost"
- onClick={handleShareClick}
- className="group text-gray-500 group-hover:text-gray-400"
- >
- <Share className="mr-2 h-4 w-4 stroke-gray-500 group-hover:stroke-gray-400" /> Share
- </Button>
- </div>
+ <Comments
+ rootId={solution.id as number}
+ commentCount={solution.jimComments.length}
+ type="SOLUTION"
+ />
</div>
);
}