Connect, collaborate, and grow with a community of TypeScript developers
feat: implement comment ability on challenge page. (#158)
Ayush6135340ed714
diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex b7af3c38..3670cea3 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -38,6 +38,11 @@ enum ReportStatus {DISMISSED}+enum Visibility {+ VISIBLE+ HIDDEN+}+// Necessary for Next authmodel Account {id String @id @default(cuid())@@ -86,19 +91,23 @@ model User {status UserStatus @default(PENDING)banReason String? @db.MediumText- accounts Account[]- sessions Session[]- challenge Challenge[]- vote Vote[]- solution Solution[]- report Report[] @relation(name: "report_author")- moderatedReports Report[] @relation(name: "moderated_reports")- bookmark Bookmark[]- sharedSolution SharedSolution[]- comment ChallengeComment[]- reply ChallengeReply[]- solutionComment SolutionComment[]- solutionReply SolutionReply[]+ accounts Account[]+ sessions Session[]+ challenge Challenge[]+ vote Vote[]+ solution Solution[]++ challengeReports ChallengeReport[] @relation(name: "authored_challenge_reports")+ moderatedChallengeReports ChallengeReport[] @relation(name: "moderated_challenge_reports")+ commentReports CommentReport[] @relation(name: "authored_comment_reports")+ moderatedCommentReports CommentReport[] @relation(name: "moderated_comment_reports")++ bookmark Bookmark[]+ sharedSolution SharedSolution[]+ comment ChallengeComment[]+ reply ChallengeReply[]+ solutionComment SolutionComment[]+ solutionReply SolutionReply[]createdAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -121,7 +130,7 @@ model Challenge {description String @db.MediumTextshortDescription Stringprompt String @db.MediumText- disabled Boolean @default(false)+ visibility Visibility @default(VISIBLE)user User @relation(fields: [userId], references: [id])userId String@@ -129,7 +138,7 @@ model Challenge {vote Vote[]solution Solution[]comment ChallengeComment[]- report Report[]+ report ChallengeReport[]bookmark Bookmark[]sharedSolution SharedSolution[]@@ -186,14 +195,16 @@ model Solution {}model ChallengeComment {- id Int @id @default(autoincrement())- createdAt DateTime @default(now())- user User @relation(fields: [userId], references: [id])- userId String- challenge Challenge @relation(fields: [challengeId], references: [id])- challengeId Int- text String- replies ChallengeReply[]+ id Int @id @default(autoincrement())+ createdAt DateTime @default(now())+ user User @relation(fields: [userId], references: [id])+ userId String+ challenge Challenge @relation(fields: [challengeId], references: [id])+ challengeId Int+ text String+ visibility Visibility @default(VISIBLE)+ replies ChallengeReply[]+ CommentReport CommentReport[]@@index([userId])@@index([challengeId])@@ -220,7 +231,9 @@ model SolutionComment {solution SharedSolution @relation(fields: [solutionId], references: [id])solutionId Inttext String+ visibility Visibility @default(VISIBLE)solutionReply SolutionReply[]+ CommentReport CommentReport[]@@index([userId])@@index([solutionId])@@ -239,28 +252,69 @@ model SolutionReply {@@index([solutionId])}-model Report {+model ChallengeReport {id Int @id @default(autoincrement())- author User @relation(fields: [authorId], references: [id], name: "report_author")- authorId String+ // meta information+ text String @db.MediumText+ status ReportStatus @default(PENDING)++ // report types+ derogatory Boolean @default(false)+ unclear Boolean @default(false)+ // user infor+ author User @relation(fields: [authorId], references: [id], name: "authored_challenge_reports")+ authorId String+ moderator User? @relation(fields: [moderatorId], references: [id], name: "moderated_challenge_reports")+ moderatorId String?++ // attached challenge.challenge Challenge @relation(fields: [challengeId], references: [id])challengeId Int- text String @db.MediumText- derogatory Boolean @default(false)- unclear Boolean @default(false)- status ReportStatus @default(PENDING)+ // time+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([authorId])+ @@index([challengeId])+ @@index([moderatorId])+}- moderator User? @relation(fields: [moderatorId], references: [id], name: "moderated_reports")+model CommentReport {+ id Int @id @default(autoincrement())++ // meta information+ text String? @db.MediumText+ status ReportStatus @default(PENDING)++ // report types+ threats Boolean @default(false)+ hateSpeech Boolean @default(false)+ spam Boolean @default(false)+ bullying Boolean @default(false)++ // user info+ author User @relation(fields: [authorId], references: [id], name: "authored_comment_reports")+ authorId String+ moderator User? @relation(fields: [moderatorId], references: [id], name: "moderated_comment_reports")moderatorId String?+ // attached comments+ challengeComment ChallengeComment? @relation(fields: [challengeCommentId], references: [id])+ challengeCommentId Int?+ solutionComment SolutionComment? @relation(fields: [solutionCommendId], references: [id])+ solutionCommendId Int?++ // timecreatedAt DateTime @default(now())updatedAt DateTime @updatedAt+ @@index([moderatorId])@@index([authorId])- @@index([challengeId])+ @@index([challengeCommentId])+ @@index([solutionCommendId])}model Bookmark {diff --git a/src/app/admin/page.tsx b/src/app/admin/page.tsxindex 95944988..b7b0f47d 100644--- a/src/app/admin/page.tsx+++ b/src/app/admin/page.tsx@@ -1,6 +1,6 @@import { RoleTypes } from '@prisma/client';import { Lock } from 'lucide-react';-import { getBannedUsers, getReports } from '~/components/admin/admin.actions';+import { getBannedUsers, getChallengeReports } from '~/components/admin/admin.actions';import { ReportDetails } from '~/components/admin/reports';import { BannedUsers } from '~/components/admin/users';import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';@@ -37,7 +37,7 @@ async function Admin() {}const View = async () => {- const allReports = await getReports();+ const allReports = await getChallengeReports();const allBannedUsers = await getBannedUsers();return (diff --git a/src/components/admin/admin.actions.tsx b/src/components/admin/admin.actions.tsxindex d0ead649..724adb31 100644--- a/src/components/admin/admin.actions.tsx+++ b/src/components/admin/admin.actions.tsx@@ -4,14 +4,14 @@ import { getServerSession } from 'next-auth';import { authOptions } from '~/server/auth';import { prisma } from '~/server/db';-export type AdminReportDetails = Awaited<ReturnType<typeof getReports>>;+export type AdminReportDetails = Awaited<ReturnType<typeof getChallengeReports>>;/*** The function fetches all the reports along* with challenge and the user.*/-export async function getReports() {- return prisma.report.findMany({+export async function getChallengeReports() {+ return prisma.challengeReport.findMany({include: {challenge: {include: {@@ -54,10 +54,10 @@ export async function disableChallenge(challengeId: number, reportId: number) {id: challengeId,},data: {- disabled: true,+ visibility: 'HIDDEN',},}),- prisma.report.update({+ prisma.challengeReport.update({where: {id: reportId,},@@ -79,9 +79,9 @@ export async function disableChallenge(challengeId: number, reportId: number) {* @param reportId The id of the report.* @returns*/-export async function dismissReport(reportId: number) {+export async function dismissChallengeReport(reportId: number) {const session = await getServerSession(authOptions);- return prisma.report.update({+ return prisma.challengeReport.update({where: {id: reportId,},@@ -118,7 +118,7 @@ export async function banUser(userId: string, reportId: number, banReason?: striuserId: userId,},data: {- disabled: true,+ visibility: 'HIDDEN',},}),prisma.session.deleteMany({@@ -126,7 +126,7 @@ export async function banUser(userId: string, reportId: number, banReason?: striuserId: userId,},}),- prisma.report.update({+ prisma.challengeReport.update({where: {id: reportId,},@@ -154,7 +154,7 @@ export async function unbanUser(userId: string) {userId: userId,},data: {- disabled: false,+ visibility: 'VISIBLE',},}),prisma.user.update({diff --git a/src/components/admin/reports.tsx b/src/components/admin/reports.tsxindex fdf29225..6933c282 100644--- a/src/components/admin/reports.tsx+++ b/src/components/admin/reports.tsx@@ -8,7 +8,7 @@ import { useState } from 'react';import {banUser,disableChallenge,- dismissReport,+ dismissChallengeReport,type AdminReportDetails,} from '~/components/admin/admin.actions';import { Badge } from '../ui/badge';@@ -85,7 +85,7 @@ export const ReportDetails = ({ data }: ReportsProps) => {async function handleDismissReport() {try {if (selectedIssue) {- await dismissReport(selectedIssue.id);+ await dismissChallengeReport(selectedIssue.id);}} catch (e) {} finally {diff --git a/src/components/challenge/comments/comment.action.ts b/src/components/challenge/comments/comment.action.tsnew file mode 100644index 00000000..274ee21b--- /dev/null+++ b/src/components/challenge/comments/comment.action.ts@@ -0,0 +1,20 @@+'use server';++import { getServerSession } from 'next-auth';+import { authOptions } from '~/server/auth';+import { prisma } from '~/server/db';++export async function addChallengeComment(challengeId: number, text: string) {+ const session = await getServerSession(authOptions);++ if (!session?.user.id) return 'unauthorized';+ if (text.length === 0) return 'text_is_empty';++ return await prisma.challengeComment.create({+ data: {+ challengeId,+ text,+ userId: session.user.id,+ },+ });+}diff --git a/src/components/challenge/comments.tsx b/src/components/challenge/comments/index.tsxsimilarity index 52%rename from src/components/challenge/comments.tsxrename to src/components/challenge/comments/index.tsxindex a3e852fd..bdc5f70f 100644--- a/src/components/challenge/comments.tsx+++ b/src/components/challenge/comments/index.tsx@@ -1,21 +1,63 @@import clsx from 'clsx';+import { ChevronDown, MessageCircle } from 'lucide-react';+import { useRouter } from 'next/navigation';+import { useState } from 'react';+import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';import { Button } from '~/components/ui/button';import Comment from '~/components/ui/comment';-import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';-import { MessageCircle, ChevronDown } from 'lucide-react';-import { useState } from 'react';-import { Input } from '../ui/input';-import NoComments from './nocomments';+import { toast } from '~/components/ui/use-toast';+import { Input } from '../../ui/input';+import NoComments from '../nocomments';+import { addChallengeComment } from './comment.action';interface Props {challenge: ChallengeRouteData;}const Comments = ({ challenge }: Props) => {+ // Stateconst [showComments, setShowComments] = useState(false);+ const [text, setText] = useState('');+ const router = useRouter();++ // Functionsconst handleClick = () => {setShowComments(!showComments);};++ async function handleEnterKey(e: React.KeyboardEvent<HTMLInputElement>) {+ if (e.key === 'Enter') {+ await createChallengeComment();+ }+ }++ async function createChallengeComment() {+ try {+ const res = await addChallengeComment(challenge.id, text);+ console.log(challenge.id, text);+ 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>,+ });+ }+ setText('');+ } catch (e) {+ toast({+ title: 'Unauthorized',+ variant: 'destructive',+ description: <p>You need to be signed in to post a comment.</p>,+ });+ } finally {+ router.refresh();+ }+ }+return (<div className="relative"><button@@ -33,7 +75,7 @@ const Comments = ({ challenge }: Props) => {></ChevronDown></button><div- className={clsx('overscroll-contain duration-300', {+ className={clsx('flex flex-col flex-col-reverse overscroll-contain duration-300', {'h-64 overflow-y-auto': showComments,'h-0 overflow-y-hidden': !showComments,})}@@ -50,10 +92,22 @@ const Comments = ({ challenge }: Props) => {</div><div className="m-2 mt-0 flex items-center 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"><Input+ value={text}+ onChange={(e) => {+ setText(e.target.value);+ }}+ onKeyUp={(e) => {+ void handleEnterKey(e);+ }}className="border-0 focus-visible:ring-0 focus-visible:ring-offset-0"placeholder="Enter your comment here."/>- <Button 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">+ <Button+ onClick={() => {+ void 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>diff --git a/src/components/challenge/description/index.tsx b/src/components/challenge/description/index.tsxindex 88df01ba..6755756f 100644--- a/src/components/challenge/description/index.tsx+++ b/src/components/challenge/description/index.tsx@@ -30,11 +30,11 @@ import { Textarea } from '../../ui/textarea';import { TypographyLarge } from '../../ui/typography/large';import { ShareForm } from '../share-form';+import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';import { toast } from '../../ui/use-toast';import { addOrRemoveBookmark } from '../bookmark.action';import { incrementOrDecrementUpvote } from '../increment.action';-import { addReport } from '../report.action';-import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';+import { addChallengeReport } from '../report.action';interface Props {challenge: ChallengeRouteData;@@ -91,7 +91,11 @@ export function Description({ challenge }: Props) {async function onSubmit(data: FormValues) {try {- const response = await addReport(challenge.id, session?.data?.user?.id as string, data);+ const response = await addChallengeReport(+ challenge.id,+ session?.data?.user?.id as string,+ data,+ );if (response === 'created') {toast({title: 'Feedback Sent',diff --git a/src/components/challenge/left-panel.tsx b/src/components/challenge/left-panel.tsxindex 899a20de..427ac2d8 100644--- a/src/components/challenge/left-panel.tsx+++ b/src/components/challenge/left-panel.tsx@@ -1,12 +1,12 @@'use client';+import Link from 'next/link';+import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';+import { Description } from '~/components/challenge/description';import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';import Comments from './comments';-import { Description } from '~/components/challenge/description';import { Solutions } from './solutions';import { Submissions } from './submissions';-import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';-import Link from 'next/link';interface Props {challenge: ChallengeRouteData;diff --git a/src/components/challenge/report.action.ts b/src/components/challenge/report.action.tsindex 02970c49..483022cf 100644--- a/src/components/challenge/report.action.ts+++ b/src/components/challenge/report.action.ts@@ -8,10 +8,10 @@ export async function doTheThing() {return 'done';}-export async function addReport(challengeId: number, userId: string, data: FormValues) {+export async function addChallengeReport(challengeId: number, userId: string, data: FormValues) {if (userId === undefined) return 'not_logged_in';- const report = await prisma.report.findMany({+ const report = await prisma.challengeReport.findMany({where: {challengeId,authorId: userId,@@ -22,7 +22,7 @@ export async function addReport(challengeId: number, userId: string, data: FormVreturn 'report_already_made';}- await prisma.report.create({+ await prisma.challengeReport.create({data: {challengeId,authorId: userId,diff --git a/src/components/explore/index.tsx b/src/components/explore/index.tsxindex b4ad774c..94f5176a 100644--- a/src/components/explore/index.tsx+++ b/src/components/explore/index.tsx@@ -33,7 +33,7 @@ export type ExploreChallengeData = Awaited<ReturnType<typeof getExploreChallengeasync function getExploreChallengeData() {return prisma.challenge.findMany({where: {- disabled: false,+ visibility: 'VISIBLE',},include: {_count: {