Connect, collaborate, and grow with a community of TypeScript developers
feat: linkable comments (#615)
bautistaaa394275b89ffc
diff --git a/apps/web/src/app/[locale]/challenge/[id]/comments/[commentId]/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/comments/[commentId]/page.tsxnew file mode 100644index 00000000..70551faf--- /dev/null+++ b/apps/web/src/app/[locale]/challenge/[id]/comments/[commentId]/page.tsx@@ -0,0 +1,27 @@+import { Comments } from '../../../_components/comments';+import { getPreselectedCommentMetadata } from '../../../_components/comments/getCommentRouteData';++interface Props {+ params: {+ id: string;+ commentId: string;+ };+}++export default async function CommentPage({ params: { id, commentId } }: Props) {+ const preselectedCommentMetadata = await getPreselectedCommentMetadata(+ Number(id),+ Number(commentId),+ );++ return (+ <div className="relative h-full">+ <Comments+ rootId={Number(id)}+ preselectedCommentMetadata={preselectedCommentMetadata}+ type="CHALLENGE"+ expanded+ />+ </div>+ );+}diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx b/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsxindex 3788bfbd..2cd10a90 100644--- a/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx+++ b/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx@@ -2,10 +2,15 @@import { useSession } from '@repo/auth/react';import { type CommentRoot } from '@repo/db/types';+import { Markdown } from '@repo/ui/components/markdown';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { toast } from '@repo/ui/components/use-toast';+import { UserBadge } from '@repo/ui/components/user-badge';import { ChevronDown, ChevronUp, Pencil, Reply, Share, Trash2 } from '@repo/ui/icons';import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';import clsx from 'clsx';import Link from 'next/link';+import { useSearchParams } from 'next/navigation';import { useEffect, useRef, useState } from 'react';import { z } from 'zod';import { ReportDialog } from '~/components/ReportDialog';@@ -14,11 +19,11 @@ 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';-import { toast } from '@repo/ui/components/use-toast';-import { UserBadge } from '@repo/ui/components/user-badge';-import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';-import { Markdown } from '@repo/ui/components/markdown';+import {+ getPaginatedComments,+ type PaginatedComments,+ type PreselectedCommentMetadata,+} from './getCommentRouteData';interface SingleCommentProps {comment: PaginatedComments['comments'][number];@@ -29,9 +34,11 @@ interface SingleCommentProps {onClickToggleReply?: () => void;queryKey?: (number | string)[];replyQueryKey?: (number | string)[];+ preselectedCommentMetadata?: PreselectedCommentMetadata;}type CommentProps = SingleCommentProps & {+ preselectedCommentMetadata?: PreselectedCommentMetadata;rootId: number;type: CommentRoot;};@@ -58,8 +65,19 @@ const commentReportSchema = zexport type CommentReportSchemaType = z.infer<typeof commentReportSchema>;// million-ignore-export function Comment({ comment, readonly = false, rootId, type, queryKey }: CommentProps) {- const [showReplies, setShowReplies] = useState(false);+export function Comment({+ comment,+ preselectedCommentMetadata,+ readonly = false,+ rootId,+ type,+ queryKey,+}: CommentProps) {+ const params = useSearchParams();+ const replyId = params.get('replyId');+ const [showReplies, setShowReplies] = useState(+ preselectedCommentMetadata?.selectedComment?.id === comment.id && Boolean(replyId),+ );const [isReplying, setIsReplying] = useState(false);const [replyText, setReplyText] = useState('');@@ -119,6 +137,7 @@ export function Comment({ comment, readonly = false, rootId, type, queryKey }: Creturn (<div className="flex flex-col px-2 py-1"><SingleComment+ preselectedCommentMetadata={preselectedCommentMetadata}comment={comment}isToggleReply={showReplies}onClickReply={toggleIsReplying}@@ -148,7 +167,13 @@ export function Comment({ comment, readonly = false, rootId, type, queryKey }: C{data?.pages.flatMap((page) =>page.comments.map((reply) => (// this is a reply- <SingleComment comment={reply} isReply key={reply.id} replyQueryKey={replyQueryKey} />+ <SingleComment+ comment={reply}+ isReply+ key={reply.id}+ replyQueryKey={replyQueryKey}+ preselectedCommentMetadata={preselectedCommentMetadata}+ />)),)}</div>@@ -166,22 +191,31 @@ export function Comment({ comment, readonly = false, rootId, type, queryKey }: C);}+const SELECTED_CLASSES = 'rounded-md bg-sky-300/20';+function SingleComment({comment,- readonly = false,- onClickReply,- onClickToggleReply,isReply,isToggleReply,+ onClickReply,+ onClickToggleReply,queryKey,+ readonly = false,replyQueryKey,+ preselectedCommentMetadata,}: SingleCommentProps) {+ const params = useSearchParams();+ const replyId = params.get('replyId');const queryClient = useQueryClient();const [text, setText] = useState(comment.text);const [isEditing, setIsEditing] = useState(false);-+ const elRef = useRef<HTMLDivElement | null>(null);const session = useSession();+ const isHighlighted = replyId+ ? Number(replyId) === comment.id+ : preselectedCommentMetadata?.selectedComment?.id === comment.id;+async function updateChallengeComment() {try {const res = await updateComment(text, comment.id);@@ -207,9 +241,9 @@ function SingleComment({}}- async function copyPathNotifyUser() {+ async function copyPathNotifyUser(isReply: boolean) {try {- await copyCommentUrlToClipboard();+ await copyCommentUrlToClipboard(isReply);toast({title: 'Success!',variant: 'success',@@ -225,16 +259,43 @@ function SingleComment({}}- async function copyCommentUrlToClipboard() {- await navigator.clipboard.writeText(`${window.location.href}/comment/${comment.id}`);+ async function copyCommentUrlToClipboard(isReply: boolean) {+ 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 loggedinUser = useSession();const isAuthor = loggedinUser.data?.user.id === comment.user.id;+ useEffect(() => {+ if (!isHighlighted) return;+ const timeout = setTimeout(() => {+ elRef.current?.classList.remove(...SELECTED_CLASSES.split(' '));+ }, 5000);+ window.requestAnimationFrame(() => elRef.current?.scrollIntoView());+ return () => {+ clearTimeout(timeout);+ };+ }, [isHighlighted]);+return (- <div className="relative p-2 pl-3">+ <div+ id={`comment-${comment.id}`}+ className={clsx(+ 'relative p-2 pl-3',+ isHighlighted && SELECTED_CLASSES,+ 'transition-colors',+ 'duration-150',+ )}+ ref={elRef}+ ><div className="flex items-start justify-between gap-4 pr-[0.4rem]"><div className="flex w-full items-center justify-between gap-1"><UserBadge username={comment.user.name ?? ''} linkComponent={Link} />@@ -294,7 +355,7 @@ function SingleComment({<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"onClick={() => {- copyPathNotifyUser();+ copyPathNotifyUser(Boolean(isReply));}}><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.tsindex f361d6a4..82fee018 100644--- a/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts+++ b/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts@@ -33,7 +33,38 @@ function orderBy(sortKey: SortKey, sortOrder: SortOrder) {}export type PaginatedComments = NonNullable<Awaited<ReturnType<typeof getPaginatedComments>>>;+export type PreselectedCommentMetadata = NonNullable<+ Awaited<ReturnType<typeof getPreselectedCommentMetadata>>+>;+export async function getPreselectedCommentMetadata(challengeId: number, commentId: number) {+ const challengeComments = await prisma.comment.findMany({+ where: {+ rootType: 'CHALLENGE',+ rootChallengeId: challengeId,+ visible: true,+ parentId: null,+ },+ orderBy: {+ createdAt: 'desc',+ },+ select: {+ id: true,+ parentId: true,+ },+ });++ const index = challengeComments.findIndex((comment) => comment.id === commentId);+ const selectedComment = challengeComments[index];+ const page = Math.ceil((index + 1) / PAGESIZE);++ return {+ page,+ selectedComment,+ index,+ challengeComments: challengeComments.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.tsxindex ed7b5f7c..2a153e23 100644--- a/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx+++ b/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx@@ -1,13 +1,23 @@'use client';import type { CommentRoot } from '@repo/db/types';+import { Button } from '@repo/ui/components/button';import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@repo/ui/components/select';+import { Toggle } from '@repo/ui/components/toggle';+import { toast } from '@repo/ui/components/use-toast';+import {+ ArrowDownNarrowWide,+ ArrowUpNarrowWide,ChevronDown,ChevronLeft,ChevronRight,MessageCircle,- ArrowDownNarrowWide,- ArrowUpNarrowWide,} from '@repo/ui/icons';import { useQuery, useQueryClient } from '@tanstack/react-query';import clsx from 'clsx';@@ -16,18 +26,12 @@ import { Comment } from './comment';import { CommentInput } from './comment-input';import { CommentSkeleton } from './comment-skeleton';import { addComment } from './comment.action';-import { getPaginatedComments, type SortOrder } from './getCommentRouteData';-import NoComments from './nocomments';-import { Button } from '@repo/ui/components/button';-import { Toggle } from '@repo/ui/components/toggle';-import { toast } from '@repo/ui/components/use-toast';import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@repo/ui/components/select';+ getPaginatedComments,+ type PreselectedCommentMetadata,+ type SortOrder,+} from './getCommentRouteData';+import NoComments from './nocomments';const sortKeys = [{@@ -44,20 +48,21 @@ const sortKeys = [},] as const;interface Props {+ preselectedCommentMetadata?: PreselectedCommentMetadata;+ expanded?: boolean;rootId: number;type: CommentRoot;}// million-ignore-export function Comments({ rootId, type }: Props) {- const [showComments, setShowComments] = useState(false);+export function Comments({ preselectedCommentMetadata, rootId, type, expanded = false }: Props) {+ const [showComments, setShowComments] = useState(expanded);const [text, setText] = useState('');const commentContainerRef = useRef<HTMLDivElement>(null);const queryClient = useQueryClient();- const [page, setPage] = useState(1);+ const [page, setPage] = useState(preselectedCommentMetadata?.page ?? 1);const [sortKey, setSortKey] = useState<(typeof sortKeys)[number]>(sortKeys[0]);const [sortOrder, setSortOrder] = useState<SortOrder>('desc');-const queryKey = [`${type.toLowerCase()}-${rootId}-comments`, sortKey.value, sortOrder, page];const { status, data } = useQuery({@@ -65,7 +70,8 @@ export function Comments({ rootId, type }: Props) {queryFn: () =>getPaginatedComments({ rootId, page, rootType: type, sortKey: sortKey.value, sortOrder }),keepPreviousData: true,- staleTime: 5000,+ staleTime: 60000, // one minute+ refetchOnWindowFocus: false,});async function createChallengeComment() {@@ -117,7 +123,9 @@ export function Comments({ rootId, type }: Props) {<div className="relative"><buttonclassName="flex w-full items-center justify-between gap-2 p-3 font-medium text-neutral-500 duration-300 hover:text-neutral-700 focus:outline-none dark:hover:text-zinc-300"- onClick={() => setShowComments(!showComments)}+ onClick={() => {+ setShowComments(!showComments);+ }}><div className="flex items-center gap-2"><MessageCircle className="h-5 w-5" />@@ -136,7 +144,7 @@ export function Comments({ rootId, type }: Props) {{'h-64 pb-4 md:h-[calc(100vh_-_164px)]': showComments,'h-0 overflow-y-hidden': !showComments,- 'overflow-y-auto': showComments && data?.comments.length !== 0,+ 'overflow-y-auto': showComments && (data?.comments.length ?? 0) > 0,},)}ref={commentContainerRef}@@ -149,7 +157,7 @@ export function Comments({ rootId, type }: Props) {value={text}/></div>- {data?.comments.length !== 0 && (+ {(data?.comments.length ?? 0) > 0 && (<div className="flex items-center gap-2 px-3 py-2"><Selectvalue={sortKey.value}@@ -204,6 +212,7 @@ export function Comments({ rootId, type }: Props) {) : (data.comments.map((comment) => (<Comment+ preselectedCommentMetadata={preselectedCommentMetadata}comment={comment}key={comment.id}queryKey={queryKey}diff --git a/packages/db/mocks/comment.mock.ts b/packages/db/mocks/comment.mock.tsindex 8e1ec2b2..c3b2fbf4 100644--- a/packages/db/mocks/comment.mock.ts+++ b/packages/db/mocks/comment.mock.ts@@ -1,3 +1,4 @@+import { faker } from '@faker-js/faker';import { type Prisma } from '@prisma/client';import { trashId } from '../seed';@@ -15,5 +16,6 @@ export default function CommentMock(}`,userId: trashId,parentId,+ createdAt: faker.date.past(),};}diff --git a/packages/monaco/src/index.tsx b/packages/monaco/src/index.tsxindex 12382e75..d86a3b74 100644--- a/packages/monaco/src/index.tsx+++ b/packages/monaco/src/index.tsx@@ -44,7 +44,7 @@ export function CodePanel(props: CodePanelProps) {'',);- const showSubmitSpinner = props.submissionDisabled || tsErrors === undefined;+ const disabled = props.submissionDisabled || tsErrors === undefined;const defaultCode =lzstring.decompressFromEncodedURIComponent(params.get('code') ?? '') ?? localStorageCode;@@ -115,8 +115,6 @@ export function CodePanel(props: CodePanelProps) {tsWorker.getCompilerOptionsDiagnostics(TESTS_PATH),] as const);- console.log({ errors });-setTsErrors(errors);setTestEditorState(editor);},@@ -215,12 +213,11 @@ export function CodePanel(props: CodePanelProps) {<Tooltip><TooltipTrigger asChild><Button- disabled={showSubmitSpinner}+ disabled={disabled}size="sm"className="cursor-pointer rounded-lg bg-emerald-600 duration-300 hover:bg-emerald-500 dark:bg-emerald-400 dark:hover:bg-emerald-300"onClick={handleSubmit}>- {showSubmitSpinner && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}Submit{tsErrors === undefined && ' (open test cases)'}</Button></TooltipTrigger>