Connect, collaborate, and grow with a community of TypeScript developers
feat: authors can delete their solution (#818)
Ayush Kumar Yadav9e0a3c98a22a
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.tsindex b45232f4..71628e82 100644--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts@@ -2,7 +2,7 @@import { getServerAuthSession } from '@repo/auth/server';import { prisma } from '@repo/db';import { revalidateTag } from 'next/cache';-import { isAdminOrModerator } from '~/utils/auth-guards';+import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';interface Args {challengeId: number;@@ -11,6 +11,9 @@ interface Args {userId: string;}+export const createCacheKeyForSolutions = (challengeId: number) =>+ `challenge-${challengeId}-solutions`;+export async function postSolution({ challengeId, description, title, userId }: Args) {const session = await getServerAuthSession();if (!session) throw new Error('You must be logged in to submit a solution');@@ -23,10 +26,25 @@ export async function postSolution({ challengeId, description, title, userId }:userId,},});- revalidateTag(`challenge-${challengeId}-submissions`);+ revalidateTag(createCacheKeyForSolutions(challengeId));+}++export async function deleteSolution(id: number, challengeId: number) {+ const session = await getServerAuthSession();+ const solution = await prisma.sharedSolution.findUnique({+ where: { id },+ });+ if (!isAuthor(session, solution?.userId)) {+ throw new Error('Only author can delete their solution.');+ }++ await prisma.sharedSolution.delete({+ where: { id },+ });+ revalidateTag(createCacheKeyForSolutions(challengeId));}-export async function pinOrUnpinSolution(id: number, isPinned: boolean) {+export async function pinOrUnpinSolution(id: number, isPinned: boolean, challengeId: number) {const session = await getServerAuthSession();if (!isAdminOrModerator(session))@@ -36,5 +54,5 @@ export async function pinOrUnpinSolution(id: number, isPinned: boolean) {where: { id },data: { isPinned },});- revalidateTag(`challenge-${id}-submissions`);+ revalidateTag(createCacheKeyForSolutions(challengeId));}diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/delete/index.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/delete/index.tsxnew file mode 100644index 00000000..9898bb02--- /dev/null+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/delete/index.tsx@@ -0,0 +1,91 @@+import type { DialogTriggerProps } from '@radix-ui/react-dialog';+import { useState } from 'react';+import { Dialog, DialogContent, DialogTrigger } from '@repo/ui/components/dialog';+import { TypographyLarge } from '@repo/ui/components/typography/large';+import type { ChallengeSolution } from '~/app/[locale]/challenge/[id]/solutions/[solutionId]/page';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { getRelativeTime } from '~/utils/relativeTime';+import { Button } from '@repo/ui/components/button';+import { TypographyP } from '@repo/ui/components/paragraph';+import { Markdown } from '@repo/ui/components/markdown';+import { Label } from '@repo/ui/components/label';+import { deleteSolution } from '../_actions';+import { toast } from '@repo/ui/components/use-toast';+import { useRouter } from 'next/navigation';++interface SolutionDeleteDialogProps extends DialogTriggerProps {+ solution: ChallengeSolution;+}++export function SolutionDeleteDialog({ children, solution, ...props }: SolutionDeleteDialogProps) {+ const [isOpen, setIsOpen] = useState(false);+ const router = useRouter();++ async function handleDeleteSolution() {+ try {+ await deleteSolution(solution.id, solution.challengeId ?? 0);+ toast({+ title: 'Solution Deleted',+ variant: 'success',+ description: 'The solution was successfully deleted.',+ });+ router.back();+ } catch (e) {+ toast({+ title: 'Uh Oh!',+ variant: 'destructive',+ description: 'An error occurred while trying to delete the comment.',+ });+ }+ }++ return (+ <Dialog onOpenChange={() => setIsOpen(!isOpen)} open={isOpen}>+ <DialogTrigger {...props}>{children}</DialogTrigger>+ <DialogContent className="flex flex-col space-y-2">+ <TypographyLarge>Are you sure?</TypographyLarge>+ <div className="flex flex-col gap-1 p-3">+ <div className="flex items-start justify-between pr-[0.4rem]">+ <div className="mb-2 flex items-center gap-1">+ <span 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">+ @{solution?.user?.name}+ </span>+ <Tooltip delayDuration={0.05}>+ <TooltipTrigger asChild>+ <span className="mr-2 whitespace-nowrap text-sm text-neutral-500">+ {getRelativeTime(solution.createdAt)}+ </span>+ </TooltipTrigger>+ <TooltipContent align="start" className="rounded-xl">+ <span className="text-white-500 text-xs">+ {solution.createdAt.toLocaleString()}+ </span>+ </TooltipContent>+ </Tooltip>+ </div>+ </div>+ <Label className="mt-2 text-neutral-500">Title:</Label>+ <TypographyLarge>{solution.title}</TypographyLarge>+ <Label className="mt-2 text-neutral-500">Solution:</Label>+ <div className="max-h-48 overflow-y-scroll">+ <Markdown>{solution.description}</Markdown>+ </div>+ </div>+ <TypographyP>The following solution will be permanently deleted.</TypographyP>+ <div className="flex flex-row gap-2">+ <Button onClick={() => setIsOpen(!isOpen)} variant="outline">+ Cancel+ </Button>+ <Button+ onClick={() => {+ void handleDeleteSolution();+ }}+ variant="destructive"+ >+ Delete+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsxindex f518b8cf..c725b106 100644--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx@@ -9,7 +9,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooimport { TypographyLarge } from '@repo/ui/components/typography/large';import { toast } from '@repo/ui/components/use-toast';import { UserBadge } from '@repo/ui/components/user-badge';-import { Calendar, Flag, Pin, Share, X } from '@repo/ui/icons';+import { Calendar, Flag, Pin, Share, X, Trash } from '@repo/ui/icons';import clsx from 'clsx';import Link from 'next/link';import type { ChallengeSolution } from '~/app/[locale]/challenge/[id]/solutions/[solutionId]/page';@@ -17,7 +17,8 @@ import { ReportDialog } from '~/components/ReportDialog';import { getRelativeTime } from '~/utils/relativeTime';import { Vote } from '../../../_components/vote';import { pinOrUnpinSolution } from './_actions';-import { isAdminOrModerator } from '~/utils/auth-guards';+import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';+import { SolutionDeleteDialog } from './delete';interface Props {solution: ChallengeSolution;@@ -25,11 +26,10 @@ interface Props {export function SolutionDetails({ solution }: Props) {const { data: session } = useSession();-const showPin = isAdminOrModerator(session);const handlePinClick = async () => {- await pinOrUnpinSolution(solution.id, !solution.isPinned);+ await pinOrUnpinSolution(solution.id, !solution.isPinned, solution.challengeId ?? 0);};const handleShareClick = async () => {if (navigator.clipboard) {@@ -128,6 +128,20 @@ export function SolutionDetails({ solution }: Props) {<Pin className={clsx('h-4 w-4')} /></Button>) : null}+ {isAuthor(session, solution.userId) ? (+ <SolutionDeleteDialog solution={solution}>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="secondary" size="xs">+ <Trash className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Delete</p>+ </TooltipContent>+ </Tooltip>+ </SolutionDeleteDialog>+ ) : null}</div></div><Markdown>{solution.description || ''}</Markdown>diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsxindex 1afc6e1f..b77e77ba 100644--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx@@ -5,6 +5,7 @@ import { withUnstableCache } from '~/utils/withUnstableCache';import { getChallengeRouteData } from '../getChallengeRouteData';import { Solutions } from './_components';import { getSolutionsRouteData } from './getSolutionRouteData';+import { createCacheKeyForSolutions } from './_components/_actions';interface Props {params: {@@ -25,8 +26,8 @@ export default async function SolutionPage({ params: { id } }: Props) {const solutions = await withUnstableCache({fn: getSolutionsRouteData,args: [id, session],- keys: ['challenge-submissions'],- tags: [`challenge-${id}-submissions`],+ keys: ['challenge-solutions'],+ tags: [createCacheKeyForSolutions(Number(id))],});if (!solutions) {diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.tsindex 0e93261c..5c47bc4a 100644--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts+++ b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts@@ -17,4 +17,5 @@ export async function saveSubmission(},});revalidateTag(`${challengeId}-challenge-submissions`);+ revalidateTag(`challenge-${challengeId}-solutions`);}diff --git a/apps/web/src/utils/auth-guards.ts b/apps/web/src/utils/auth-guards.tsindex f9c97b5a..0b408093 100644--- a/apps/web/src/utils/auth-guards.ts+++ b/apps/web/src/utils/auth-guards.ts@@ -4,3 +4,7 @@ import { RoleTypes } from '@repo/db/types';export function isAdminOrModerator(session: Session | null) {return [RoleTypes.ADMIN, RoleTypes.MODERATOR].some((i) => session?.user.role.includes(i));}++export function isAuthor(session: Session | null, userId?: string | null) {+ return Boolean(userId && session?.user?.id && userId === session?.user?.id);+}diff --git a/packages/ui/src/icons.ts b/packages/ui/src/icons.tsindex 79e349b6..43b95e0e 100644--- a/packages/ui/src/icons.ts+++ b/packages/ui/src/icons.ts@@ -61,4 +61,5 @@ export {User,X,XCircle,+ Trash,} from 'lucide-react';