Skip to content

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

feat: allow solution comments to be shared - Closes #648 (#661)

Mihai Badescu8a26d4ebe5fc
diff --git a/apps/web/src/app/[locale]/challenge/[id]/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/page.tsx
index d56502cb..85ad5ce3 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/page.tsx
@@ -19,9 +19,9 @@ export async function generateMetadata({ params: { id } }: Props) {
});
}
-export default async function Challenges({ params: { id } }: Props) {
+export default async function Challenges({ params: { id: challengeId } }: Props) {
const session = await getServerAuthSession();
- const challenge = await getChallengeRouteData(id, session);
+ const challenge = await getChallengeRouteData(challengeId, session);
return (
<div className="relative h-full">
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/comments/[commentId]/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/comments/[commentId]/page.tsx
new file mode 100644
index 00000000..29436e11
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/comments/[commentId]/page.tsx
@@ -0,0 +1,37 @@
+import { getServerAuthSession, type Session } from '@repo/auth/server';
+import { Comments } from '~/app/[locale]/challenge/_components/comments';
+import { SolutionDetails } from '~/app/[locale]/challenge/[id]/solutions/_components/solution-detail';
+import { getPreselectedSolutionCommentMetadata } from '~/app/[locale]/challenge/_components/comments/getCommentRouteData';
+import { getSolutionIdRouteData } from '../../getSolutionIdRouteData';
+
+interface Props {
+ params: {
+ id: string;
+ commentId: string;
+ solutionId: string;
+ };
+}
+
+export default async function SolutionPage({
+ params: { solutionId, commentId, id: challengeId },
+}: Props) {
+ const session = await getServerAuthSession();
+ const solution = await getSolutionIdRouteData(challengeId, solutionId, session);
+ const preselectedCommentMetadata = await getPreselectedSolutionCommentMetadata(
+ Number(solutionId),
+ Number(commentId),
+ Number(challengeId),
+ );
+
+ return (
+ <div className="relative h-full">
+ <SolutionDetails solution={solution} />
+ <Comments
+ rootId={Number(solutionId)}
+ type="SOLUTION"
+ preselectedCommentMetadata={preselectedCommentMetadata}
+ expanded
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/getSolutionIdRouteData.ts b/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/getSolutionIdRouteData.ts
new file mode 100644
index 00000000..606b85fe
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/getSolutionIdRouteData.ts
@@ -0,0 +1,40 @@
+import { cache } from 'react';
+import { prisma } from '@repo/db';
+import { type Session } from '@repo/auth/server';
+import { redirect } from 'next/navigation';
+
+export const getSolutionIdRouteData = cache(
+ async (challengeId: string, solutionId: string, session: Session | null) => {
+ const solution = await prisma.sharedSolution.findFirst({
+ where: {
+ id: Number(solutionId),
+ challengeId: Number(challengeId),
+ },
+ include: {
+ user: {
+ select: {
+ name: true,
+ image: true,
+ },
+ },
+ _count: {
+ select: { vote: true },
+ },
+ vote: {
+ where: {
+ userId: session?.user.id || '',
+ },
+ select: {
+ userId: true,
+ },
+ },
+ },
+ });
+
+ if (!solution) {
+ redirect(`/challenge/${challengeId}/solutions`);
+ }
+
+ return solution;
+ },
+);
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx
index 0a8b4489..8ec3f1cb 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx
@@ -1,20 +1,27 @@
import { prisma } from '@repo/db';
import { SolutionDetails } from '../_components/solution-detail';
-import { getServerAuthSession, type Session } from '@repo/auth/server';
-import { cache } from 'react';
+import { getServerAuthSession } from '@repo/auth/server';
+import { Comments } from '~/app/[locale]/challenge/_components/comments';
+import { getSolutionIdRouteData } from './getSolutionIdRouteData';
interface Props {
params: {
+ id: string;
solutionId: string;
};
}
-export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolution>>>;
-export default async function SolutionPage({ params: { solutionId } }: Props) {
+export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolutionIdRouteData>>>;
+export default async function SolutionPage({ params: { solutionId, id: challengeId } }: Props) {
const session = await getServerAuthSession();
- const solution = await getSolution(solutionId, session);
+ const solution = await getSolutionIdRouteData(challengeId, solutionId, session);
- return <SolutionDetails solution={solution} />;
+ return (
+ <div className="relative h-full">
+ <SolutionDetails solution={solution} />
+ <Comments rootId={solution.id!} type="SOLUTION" />
+ </div>
+ );
}
export async function generateMetadata({ params: { solutionId } }: Props) {
@@ -36,32 +43,3 @@ export async function generateMetadata({ params: { solutionId } }: Props) {
description: `View this solution to ${solution.challenge?.name} on TypeHero.`,
};
}
-
-const getSolution = cache(async (solutionId: string, session: Session | null) => {
- const solution = await prisma.sharedSolution.findFirstOrThrow({
- where: {
- id: Number(solutionId),
- },
- include: {
- user: {
- select: {
- name: true,
- image: true,
- },
- },
- _count: {
- select: { vote: true },
- },
- vote: {
- where: {
- userId: session?.user.id || '',
- },
- select: {
- userId: true,
- },
- },
- },
- });
-
- return solution;
-});
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx
index d79a9b30..5d0522a7 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx
@@ -6,12 +6,12 @@ import { useState } from 'react';
import { SolutionEditor } from './solution-editor';
import { NoSolutions } from './nosolutions';
import { SubmitSolution } from './submit-solution';
-import type { ChallengeSolutionsRouteData } from '~/app/[locale]/challenge/[id]/solutions/page';
+import type { ChallengeSolution } from '../getSolutionRouteData';
import { getRelativeTime } from '~/utils/relativeTime';
import { Button } from '@repo/ui/components/button';
interface Props {
- challenge: ChallengeSolutionsRouteData;
+ challenge: ChallengeSolution;
}
type View = 'details' | 'editor' | 'list';
export function Solutions({ challenge }: Props) {
@@ -63,7 +63,7 @@ function SolutionRow({
solution,
}: {
handleClick: (id: string) => void;
- solution: ChallengeSolutionsRouteData['sharedSolution'][0];
+ solution: ChallengeSolution['sharedSolution'][0];
}) {
return (
<Link
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.tsx
index 30a966ae..d412d724 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
@@ -2,7 +2,6 @@
import { Calendar, Flag, Share, X } from '@repo/ui/icons';
import Link from 'next/link';
-import { Comments } from '~/app/[locale]/challenge/_components/comments';
import type { ChallengeSolution } from '~/app/[locale]/challenge/[id]/solutions/[solutionId]/page';
import { ReportDialog } from '~/components/ReportDialog';
import { ActionMenu } from '@repo/ui/components/action-menu';
@@ -113,7 +112,6 @@ export function SolutionDetails({ solution }: Props) {
<Markdown>{solution.description || ''}</Markdown>
</div>
</div>
- <Comments rootId={solution.id!} type="SOLUTION" />
</div>
);
}
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
index 9dc4ee47..7f6b34a0 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
@@ -6,7 +6,7 @@ import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { postSolution } from './post-solution.action';
import { RichMarkdownEditor } from '~/components/ui/rich-markdown-editor';
-import type { ChallengeSolutionsRouteData } from '~/app/[locale]/challenge/[id]/solutions/page';
+import type { ChallengeSolution } from '../getSolutionRouteData';
import { Button } from '@repo/ui/components/button';
import { useToast } from '@repo/ui/components/use-toast';
import { Form, FormControl, FormField, FormItem, FormMessage } from '@repo/ui/components/form';
@@ -34,7 +34,7 @@ const formSchema = z.object({
export type FormSchema = z.infer<typeof formSchema>;
interface Props {
- challenge: ChallengeSolutionsRouteData;
+ challenge: ChallengeSolution;
dismiss: () => void;
}
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts b/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts
new file mode 100644
index 00000000..ac28705e
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts
@@ -0,0 +1,44 @@
+import { cache } from 'react';
+import { prisma } from '@repo/db';
+import type { Session } from '@repo/auth/server';
+
+export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolutionsRouteData>>>;
+export const getSolutionsRouteData = cache(async (challengeId: string, session: Session | null) => {
+ const data = await prisma.challenge.findFirst({
+ where: { id: Number(challengeId) },
+ select: {
+ id: true,
+ // we just want their most recent solution
+ submission: {
+ where: {
+ userId: session?.user.id || '',
+ },
+ orderBy: [
+ {
+ createdAt: 'desc',
+ },
+ ],
+ take: 1,
+ },
+ sharedSolution: {
+ orderBy: [
+ {
+ createdAt: 'desc',
+ },
+ ],
+ include: {
+ user: {
+ select: {
+ name: true,
+ },
+ },
+ _count: {
+ select: { vote: true, solutionComment: true },
+ },
+ },
+ },
+ },
+ });
+
+ return data;
+});
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx
index 62ccc808..3e4b73d2 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx
@@ -1,11 +1,9 @@
-import type { Session } from '@repo/auth/server';
import { getServerAuthSession } from '@repo/auth/server';
-import { prisma } from '@repo/db';
import { notFound } from 'next/navigation';
import { Solutions } from './_components';
import { getChallengeRouteData } from '../getChallengeRouteData';
import { buildMetaForChallenge } from '~/app/metadata';
-import { cache } from 'react';
+import { getSolutionsRouteData } from './getSolutionRouteData';
interface Props {
params: {
@@ -24,7 +22,7 @@ export async function generateMetadata({ params: { id } }: Props) {
export default async function SolutionPage({ params: { id } }: Props) {
const session = await getServerAuthSession();
- const solutions = await getSolutionsData(id, session);
+ const solutions = await getSolutionsRouteData(id, session);
if (!solutions) {
return notFound();
@@ -32,44 +30,3 @@ export default async function SolutionPage({ params: { id } }: Props) {
return <Solutions challenge={solutions} />;
}
-
-export type ChallengeSolutionsRouteData = NonNullable<Awaited<ReturnType<typeof getSolutionsData>>>;
-export const getSolutionsData = cache(async (challengeId: string, session: Session | null) => {
- const data = await prisma.challenge.findFirst({
- where: { id: Number(challengeId) },
- select: {
- id: true,
- // we just want their most recent solution
- submission: {
- where: {
- userId: session?.user.id || '',
- },
- orderBy: [
- {
- createdAt: 'desc',
- },
- ],
- take: 1,
- },
- sharedSolution: {
- orderBy: [
- {
- createdAt: 'desc',
- },
- ],
- include: {
- user: {
- select: {
- name: true,
- },
- },
- _count: {
- select: { vote: true, solutionComment: true },
- },
- },
- },
- },
- });
-
- return data;
-});
diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx b/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx
index e9637e3e..edd71788 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx
@@ -10,7 +10,7 @@ import { ChevronDown, ChevronUp, Pencil, Reply, Share, Trash2 } from '@repo/ui/i
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import clsx from 'clsx';
import Link from 'next/link';
-import { useSearchParams } from 'next/navigation';
+import { useParams, useSearchParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { z } from 'zod';
import { ReportDialog } from '~/components/ReportDialog';
@@ -206,8 +206,10 @@ function SingleComment({
replyQueryKey,
preselectedCommentMetadata,
}: SingleCommentProps) {
- const params = useSearchParams();
- const replyId = params.get('replyId');
+ const params = useParams();
+ const challengeId = params.id as string;
+ const searchParams = useSearchParams();
+ const replyId = searchParams.get('replyId');
const queryClient = useQueryClient();
const [text, setText] = useState(comment.text);
const [isEditing, setIsEditing] = useState(false);
@@ -243,9 +245,9 @@ function SingleComment({
}
}
- async function copyPathNotifyUser(isReply: boolean) {
+ async function copyPathNotifyUser(isReply: boolean, challengeId: string) {
try {
- await copyCommentUrlToClipboard(isReply);
+ await copyCommentUrlToClipboard(isReply, challengeId);
toast({
title: 'Success!',
variant: 'success',
@@ -261,15 +263,21 @@ function SingleComment({
}
}
- async function copyCommentUrlToClipboard(isReply: boolean) {
+ async function copyCommentUrlToClipboard(isReply: boolean, challengeId: string) {
const commentId = isReply ? comment.parentId : comment.id;
const paramsObj = { replyId: String(comment.id) };
const searchParams = new URLSearchParams(paramsObj);
- await navigator.clipboard.writeText(
- `${window.location.origin}/challenge/${comment.rootChallengeId}/comments/${commentId}${
- isReply ? `?${searchParams.toString()}` : ''
- }`,
- );
+
+ const { rootType, rootSolutionId } = comment;
+ const baseURL = `${window.location.origin}/challenge/${challengeId}`;
+ const hasGetParams = isReply ? `?${searchParams.toString()}` : '';
+
+ const shareUrl =
+ rootType === 'CHALLENGE'
+ ? `${baseURL}/comments/${commentId}${hasGetParams}`
+ : `${baseURL}/solutions/${rootSolutionId}/comments/${commentId}${hasGetParams}`;
+
+ await navigator.clipboard.writeText(shareUrl);
}
const loggedinUser = useSession();
@@ -365,7 +373,7 @@ function SingleComment({
<div
className="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"
onClick={() => {
- copyPathNotifyUser(Boolean(isReply));
+ copyPathNotifyUser(Boolean(isReply), challengeId);
}}
>
<Share className="h-3 w-3" />
diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts b/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts
index b39907ad..aa5c3e37 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts
@@ -33,9 +33,9 @@ function orderBy(sortKey: SortKey, sortOrder: SortOrder) {
}
export type PaginatedComments = NonNullable<Awaited<ReturnType<typeof getPaginatedComments>>>;
-export type PreselectedCommentMetadata = NonNullable<
- Awaited<ReturnType<typeof getPreselectedCommentMetadata>>
->;
+export type PreselectedCommentMetadata =
+ | NonNullable<Awaited<ReturnType<typeof getPreselectedCommentMetadata>>>
+ | NonNullable<Awaited<ReturnType<typeof getPreselectedSolutionCommentMetadata>>>;
export async function getPreselectedCommentMetadata(challengeId: number, commentId: number) {
const challengeComments = await prisma.comment.findMany({
@@ -65,6 +65,42 @@ export async function getPreselectedCommentMetadata(challengeId: number, comment
challengeComments: challengeComments.map((comment) => comment.id),
};
}
+
+export async function getPreselectedSolutionCommentMetadata(
+ solutionId: number,
+ commentId: number,
+ challengeId: number,
+) {
+ const solution = await prisma.sharedSolution.findFirst({
+ where: {
+ id: solutionId,
+ challengeId,
+ },
+ orderBy: {
+ createdAt: 'desc',
+ },
+ select: {
+ id: true,
+ solutionComment: true,
+ },
+ });
+
+ if (!solution || !solution.solutionComment) return;
+
+ const comments = solution.solutionComment;
+
+ const index = comments.findIndex((comment) => comment.id === commentId);
+ const selectedComment = comments[index];
+ const page = Math.ceil((index + 1) / PAGESIZE);
+
+ return {
+ page,
+ selectedComment,
+ index,
+ challengeComments: comments.map((comment) => comment.id),
+ };
+}
+
export async function getPaginatedComments({
page,
rootId,
diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx b/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx
index 4100a549..4755365f 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx
@@ -64,7 +64,6 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =
const [page, setPage] = useState(preselectedCommentMetadata?.page ?? 1);
const [sortKey, setSortKey] = useState<(typeof sortKeys)[number]>(sortKeys[0]);
const queryKey = [`${type.toLowerCase()}-${rootId}-comments`, sortKey.value, page];
-
const { status, data } = useQuery({
queryKey,
queryFn: () =>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3e79d33b..4c3935e9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -5164,7 +5164,7 @@ packages:
dev: false
- resolution: {integrity: sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=}
+ resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}
resolution: {integrity: sha512-P7X+QL9Hb9B/c8HI5BFFKmjgBu2XpQuF98WZ9XkO+dBGgk5XgwiQz7o1SmpglNWId3581UcS0SFAWfoIhMHPfg==}