Connect, collaborate, and grow with a community of TypeScript developers
add: ability to edit comments (#311)
bautistaaafb6ed1bb7cf5
diff --git a/src/app/admin/challenge/[challengeId]/challenge-review.tsx b/src/app/admin/challenge/[challengeId]/challenge-review.tsxindex aea8729b..bbfd9ef8 100644--- a/src/app/admin/challenge/[challengeId]/challenge-review.tsx+++ b/src/app/admin/challenge/[challengeId]/challenge-review.tsx@@ -26,7 +26,6 @@ export function ChallengeReview({ challenge }: Props) {[session?.user.role],);const handleApproveChallenge = async () => {- console.log(challenge.id);try {await approveChallenge(challenge.id, challenge.userId, isUserACreator);toast({diff --git a/src/components/challenge/comments/comment-input.tsx b/src/components/challenge/comments/comment-input.tsxnew file mode 100644index 00000000..c8c14cfd--- /dev/null+++ b/src/components/challenge/comments/comment-input.tsx@@ -0,0 +1,99 @@+import { Loader2 } from 'lucide-react';+import { useEffect, useRef, useState, type RefObject } from 'react';+import { Button } from '~/components/ui/button';+import { Markdown } from '~/components/ui/markdown';+import { Textarea } from '~/components/ui/textarea';++interface Props {+ mode: 'edit' | 'create';+ onCancel?: () => void;+ onChange: (text: string) => void;+ onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;+ value: string;+ onSubmit: () => Promise<void>;+}++export function CommentInput({ mode, onCancel, onChange, onKeyDown, value, onSubmit }: Props) {+ const [commentMode, setCommentMode] = useState<'editor' | 'preview'>('editor');+ const [isSubmitting, setIsSubmitting] = useState(false);+ const textAreaRef = useRef<HTMLTextAreaElement>(null);++ useAutosizeTextArea(textAreaRef, value, commentMode);++ return (+ <div className="m-2 mt-0 flex flex-col rounded-xl rounded-br-lg bg-background/90 bg-neutral-100 backdrop-blur-sm dark:border-zinc-700 dark:bg-zinc-700/90">+ <div>+ {commentMode === 'editor' && (+ <Textarea+ ref={textAreaRef}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={(e) => {+ if (isSubmitting) return;+ onKeyDown(e);+ }}+ className="resize-none border-0 px-3 py-2 focus-visible:ring-0 focus-visible:ring-offset-0"+ placeholder="Enter your comment here."+ />+ )}+ {commentMode === 'preview' && (+ <div className="p-2">+ <Markdown>{value}</Markdown>+ </div>+ )}+ </div>+ <div className="flex justify-end">+ <div className="flex gap-2 p-2">+ <Button+ variant={mode === 'create' ? 'secondary' : 'ghost'}+ className="h-8"+ onClick={() => setCommentMode(commentMode === 'editor' ? 'preview' : 'editor')}+ >+ {commentMode === 'editor' ? 'Preview' : 'Edit'}+ </Button>+ {mode === 'edit' && (+ <Button variant="secondary" className="h-8" onClick={() => onCancel?.()}>+ Cancel+ </Button>+ )}+ <Button+ disabled={value.length === 0 || isSubmitting}+ onClick={async () => {+ try {+ setIsSubmitting(true);++ await onSubmit();+ } catch (e) {+ console.error(e);+ } finally {+ setIsSubmitting(false);+ }+ }}+ className="h-8 w-[5.5rem] rounded-lg rounded-br-sm bg-emerald-600 hover:bg-emerald-500 dark:bg-emerald-400 dark:hover:bg-emerald-300"+ >+ {isSubmitting ? <Loader2 className="h-5 w-5 animate-spin" /> : 'Comment'}+ </Button>+ </div>+ </div>+ </div>+ );+}++function useAutosizeTextArea(+ textAreaRef: RefObject<HTMLTextAreaElement>,+ value: string,+ commentMode: string,+) {+ useEffect(() => {+ if (textAreaRef.current) {+ // We need to reset the height momentarily to get the correct scrollHeight for the textarea+ textAreaRef.current.style.height = '0px';+ const scrollHeight = textAreaRef.current.scrollHeight;++ // We then set the height directly, outside of the render loop+ // Trying to set this with state or a ref will product an incorrect value.+ textAreaRef.current.style.height = scrollHeight + 'px';+ }+ // eslint-disable-next-line+ }, [textAreaRef.current, value, commentMode]);+}diff --git a/src/components/challenge/comments/comment.action.ts b/src/components/challenge/comments/comment.action.tsindex 79237869..3f6c9a7b 100644--- a/src/components/challenge/comments/comment.action.ts+++ b/src/components/challenge/comments/comment.action.ts@@ -34,6 +34,24 @@ export async function addComment(comment: ChallengeComment | SolutionComment) {},});}++export async function updateComment(text: string, id: number) {+ const session = await getServerAuthSession();++ if (!session?.user.id) return 'unauthorized';+ if (text.length === 0) return 'text_is_empty';+ if (!session?.user.id) return 'unauthorized';++ return await prisma.comment.update({+ where: {+ id,+ },+ data: {+ text,+ userId: session.user.id,+ },+ });+}/*** Delete's a comment given a comment id. It must* be your own comment.diff --git a/src/components/challenge/comments/comment.tsx b/src/components/challenge/comments/comment.tsxindex c562bad3..5e07487c 100644--- a/src/components/challenge/comments/comment.tsx+++ b/src/components/challenge/comments/comment.tsx@@ -3,7 +3,7 @@import clsx from 'clsx';import { Pencil, Reply, Share, Trash2 } from 'lucide-react';import { useSession } from 'next-auth/react';-import { useState } from 'react';+import { useEffect, useState } from 'react';import { z } from 'zod';import type { ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';import ReportDialog from '~/components/report';@@ -13,6 +13,9 @@ import { toast } from '~/components/ui/use-toast';import { UserBadge } from '~/components/ui/user-badge';import { getRelativeTime } from '~/utils/relativeTime';import { CommentDeleteDialog } from './delete';+import { CommentInput } from './comment-input';+import { updateComment } from './comment.action';+import { useQueryClient } from '@tanstack/react-query';interface CommentProps {comment: ChallengeRouteData['comment'][number];@@ -41,8 +44,16 @@ const commentReportSchema = zexport type CommentReportSchemaType = z.infer<typeof commentReportSchema>;const Comment = ({ comment, readonly = false }: CommentProps) => {+ const queryClient = useQueryClient();+ const [text, setText] = useState(comment.text);+ const [isEditing, setIsEditing] = useState(false);const isTooManyLines = comment.text.split('\n').length > 15;const [showReadMore, setShowReadMore] = useState(isTooManyLines); // take some default value from the calculation of characters++ useEffect(() => {+ setShowReadMore(isTooManyLines);+ }, [isTooManyLines]);+async function copyPathNotifyUser() {try {await copyCommentUrlToClipboard();@@ -60,6 +71,36 @@ const Comment = ({ comment, readonly = false }: CommentProps) => {});}}+ const handleEnterKey = async (e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (e.shiftKey && e.key === 'Enter') {+ e.preventDefault();+ await updateChallengeComment();+ }+ };++ async function updateChallengeComment() {+ try {+ const res = await updateComment(text, comment.id);+ 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>,+ });+ }+ queryClient.invalidateQueries([`challenge-${comment.rootChallengeId}-comments`]);+ } catch (e) {+ toast({+ title: 'Unauthorized',+ variant: 'destructive',+ description: <p>You need to be signed in to post a comment.</p>,+ });+ }+ }async function copyCommentUrlToClipboard() {await navigator.clipboard.writeText(`${window.location.href}/comment/${comment.id}`);@@ -88,24 +129,43 @@ const Comment = ({ comment, readonly = false }: CommentProps) => {</Tooltip></div></div>- <p- className={clsx(- { 'h-full': !showReadMore, 'max-h-[300px]': showReadMore },- 'relative w-full overflow-hidden break-words pl-[1px] text-sm',- )}- >- <Markdown>{comment.text}</Markdown>- {showReadMore && (- <div- className="absolute top-0 flex h-full w-full cursor-pointer items-end bg-gradient-to-b from-transparent to-white dark:to-zinc-800"- onClick={() => setShowReadMore(false)}+ <div>+ {!isEditing && (+ <p+ className={clsx(+ { 'h-full': !showReadMore, 'max-h-[300px]': showReadMore },+ 'relative w-full overflow-hidden break-words pl-[1px] text-sm',+ )}>- <div className="text-md text-label-1 dark:text-dark-label-1 flex w-full items-center justify-center hover:bg-transparent">- Read more- </div>- </div>+ <Markdown>{comment.text}</Markdown>+ {showReadMore && (+ <div+ className="absolute top-0 flex h-full w-full cursor-pointer items-end bg-gradient-to-b from-transparent to-white dark:to-zinc-800"+ onClick={() => setShowReadMore(false)}+ >+ <div className="text-md text-label-1 dark:text-dark-label-1 flex w-full items-center justify-center hover:bg-transparent">+ Read more+ </div>+ </div>+ )}+ </p>)}- </p>+ {isEditing && (+ <CommentInput+ value={text}+ onCancel={() => {+ setIsEditing(false);+ }}+ onChange={setText}+ onKeyDown={handleEnterKey}+ onSubmit={async () => {+ await updateChallengeComment();+ setIsEditing(false);+ }}+ mode="edit"+ />+ )}+ </div><>{!readonly && (<div className="flex items-center gap-4 py-4">@@ -124,7 +184,10 @@ const Comment = ({ comment, readonly = false }: CommentProps) => {<div className="text-xs">Reply</div></button>{isAuthor && (- <button 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">+ <button+ onClick={() => setIsEditing(!isEditing)}+ 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"+ ><Pencil size={16} /><div className="text-xs">Edit</div></button>diff --git a/src/components/challenge/comments/index.tsx b/src/components/challenge/comments/index.tsxindex 75013c6a..ed27e634 100644--- a/src/components/challenge/comments/index.tsx+++ b/src/components/challenge/comments/index.tsx@@ -4,12 +4,11 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';import clsx from 'clsx';import { ChevronDown, ChevronLeft, ChevronRight, Loader2, MessageCircle } from 'lucide-react';import { useRouter } from 'next/navigation';-import { useEffect, useRef, useState, type RefObject } from 'react';+import { useRef, useState } from 'react';import Comment from '~/components/challenge/comments/comment';import { Button } from '~/components/ui/button';-import { Markdown } from '~/components/ui/markdown';-import { Textarea } from '~/components/ui/textarea';import { toast } from '~/components/ui/use-toast';+import { CommentInput } from './comment-input';import { CommentSkeleton } from './comment-skeleton';import { addComment } from './comment.action';import { getPaginatedComments } from './getCommentRouteData';@@ -23,17 +22,12 @@ interface Props {export const Comments = ({ challengeId, commentCount }: Props) => {const [showComments, setShowComments] = useState(false);const [text, setText] = useState('');- const [commentMode, setCommentMode] = useState<'editor' | 'preview'>('editor');- const [isSubmitting, setIsSubmitting] = useState(false);- const textAreaRef = useRef<HTMLTextAreaElement>(null);const commentContainerRef = useRef<HTMLDivElement>(null);const queryClient = useQueryClient();const router = useRouter();const [page, setPage] = useState(1);- useAutosizeTextArea(textAreaRef, text, commentMode);-const { status, data } = useQuery({queryKey: [`challenge-${challengeId}-comments`, page],queryFn: () => getPaginatedComments({ challengeId, page }),@@ -42,7 +36,7 @@ export const Comments = ({ challengeId, commentCount }: Props) => {});const handleEnterKey = async (e: React.KeyboardEvent<HTMLTextAreaElement>) => {- if (e.shiftKey && e.key === 'Enter' && !isSubmitting) {+ if (e.shiftKey && e.key === 'Enter') {e.preventDefault();await createChallengeComment();}@@ -50,7 +44,6 @@ export const Comments = ({ challengeId, commentCount }: Props) => {async function createChallengeComment() {try {- setIsSubmitting(true);const res = await addComment({text,rootChallengeId: challengeId,@@ -67,7 +60,6 @@ export const Comments = ({ challengeId, commentCount }: Props) => {description: <p>You need to be signed in to post a comment.</p>,});}- setIsSubmitting(false);setText('');queryClient.invalidateQueries([`challenge-${challengeId}-comments`, page]);} catch (e) {@@ -77,7 +69,6 @@ export const Comments = ({ challengeId, commentCount }: Props) => {description: <p>You need to be signed in to post a comment.</p>,});} finally {- setCommentMode('editor');router.refresh();}}@@ -125,45 +116,13 @@ export const Comments = ({ challengeId, commentCount }: Props) => {},)}>- <div className="m-2 mt-0 flex flex-col rounded-xl rounded-br-lg bg-background/90 bg-neutral-100 backdrop-blur-sm dark:border-zinc-700 dark:bg-zinc-700/90">- <div>- {commentMode === 'editor' && (- <Textarea- ref={textAreaRef}- value={text}- onChange={(e) => {- setText(e.target.value);- }}- onKeyDown={handleEnterKey}- className="resize-none border-0 px-3 py-2 focus-visible:ring-0 focus-visible:ring-offset-0"- placeholder="Enter your comment here."- />- )}- {commentMode === 'preview' && (- <div className="p-2">- <Markdown>{text}</Markdown>- </div>- )}- </div>- <div className="flex justify-end">- <div className="flex gap-2 p-2">- <Button- variant="ghost"- className="h-8"- onClick={() => setCommentMode(commentMode === 'editor' ? 'preview' : 'editor')}- >- {commentMode === 'editor' ? 'Preview' : 'Edit'}- </Button>- <Button- disabled={text.length === 0 || isSubmitting}- onClick={createChallengeComment}- className="h-8 w-[5.5rem] rounded-lg rounded-br-sm bg-emerald-600 hover:bg-emerald-500 dark:bg-emerald-400 dark:hover:bg-emerald-300"- >- {isSubmitting ? <Loader2 className="h-5 w-5 animate-spin" /> : 'Comment'}- </Button>- </div>- </div>- </div>+ <CommentInput+ onChange={setText}+ value={text}+ onKeyDown={handleEnterKey}+ onSubmit={createChallengeComment}+ mode="create"+ />{status === 'loading' && <CommentSkeleton />}<div className="flex-1">{status === 'success' &&@@ -186,25 +145,6 @@ export const Comments = ({ challengeId, commentCount }: Props) => {);};-function useAutosizeTextArea(- textAreaRef: RefObject<HTMLTextAreaElement>,- value: string,- commentMode: string,-) {- useEffect(() => {- if (textAreaRef.current) {- // We need to reset the height momentarily to get the correct scrollHeight for the textarea- textAreaRef.current.style.height = '0px';- const scrollHeight = textAreaRef.current.scrollHeight;-- // We then set the height directly, outside of the render loop- // Trying to set this with state or a ref will product an incorrect value.- textAreaRef.current.style.height = scrollHeight + 'px';- }- // eslint-disable-next-line- }, [textAreaRef.current, value, commentMode]);-}-function Pagination({currentPage,totalPages,diff --git a/src/components/challenge/solutions/solution-comments.tsx b/src/components/challenge/solutions/solution-comments.tsxindex e714ff45..3add07f7 100644--- a/src/components/challenge/solutions/solution-comments.tsx+++ b/src/components/challenge/solutions/solution-comments.tsx@@ -8,12 +8,12 @@ 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 { addComment } from '../comments/comment.action';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;