Skip to content

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

Adds functionality to reply to replies (#1640)

Aquib Baig7a4029834a47
diff --git a/apps/web/src/app/challenge/_components/comments/comment-input.tsx b/apps/web/src/app/challenge/_components/comments/comment-input.tsx
index c5ab8cac..df102696 100644
--- a/apps/web/src/app/challenge/_components/comments/comment-input.tsx
+++ b/apps/web/src/app/challenge/_components/comments/comment-input.tsx
@@ -1,13 +1,20 @@
-import { Loader2 } from '@repo/ui/icons';
+import { zodResolver } from '@hookform/resolvers/zod';
import { useSession } from '@repo/auth/react';
-import { useEffect, useRef, useState, type RefObject } from 'react';
import { Button } from '@repo/ui/components/button';
+import { Form, FormField, FormItem, FormMessage } from '@repo/ui/components/form';
import { Markdown } from '@repo/ui/components/markdown';
+import { Loader2 } from '@repo/ui/icons';
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+ type RefObject,
+} from 'react';
import { useForm } from 'react-hook-form';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { Form, FormField, FormItem, FormMessage } from '@repo/ui/components/form';
-import { singleFieldSchema, type SingleFieldSchema } from '~/utils/zodSingleStringField';
import { MentionInput } from '~/components/mention/mention-input';
+import { singleFieldSchema, type SingleFieldSchema } from '~/utils/zodSingleStringField';
interface Props {
mode: 'create' | 'edit' | 'reply';
@@ -17,103 +24,122 @@ interface Props {
defaultValue?: string;
}
-export function CommentInput({ mode, onCancel, placeholder, onSubmit, defaultValue }: Props) {
- const { data: session } = useSession();
- const [commentMode, setCommentMode] = useState<'editor' | 'preview'>('editor');
+interface CommentInputRefProps {
+ textarea: HTMLTextAreaElement;
+ setInputValue: (value: string) => void;
+}
+
+export const CommentInput = forwardRef<CommentInputRefProps, Props>(
+ ({ mode, onCancel, placeholder, onSubmit, defaultValue }: Props, ref) => {
+ const { data: session } = useSession();
+ const [commentMode, setCommentMode] = useState<'editor' | 'preview'>('editor');
- const textAreaRef = useRef<HTMLTextAreaElement>(null);
+ const textAreaRef = useRef<HTMLTextAreaElement>(null);
- const form = useForm<SingleFieldSchema>({
- resolver: zodResolver(singleFieldSchema),
- defaultValues: { text: defaultValue ?? '' },
- });
- const formValid = form.formState.isValid;
- const value = form.watch('text');
- useAutosizeTextArea(textAreaRef, value, commentMode);
+ const form = useForm<SingleFieldSchema>({
+ resolver: zodResolver(singleFieldSchema),
+ defaultValues: { text: defaultValue ?? '' },
+ });
- const submitComment = async ({ text }: { text: string }) => {
- try {
- await onSubmit(text);
- } catch (e) {
- console.error(e);
- } finally {
- form.reset();
- setCommentMode('editor');
- }
- };
+ // We need to control the textarea element from parent component.
+ useImperativeHandle(ref, () => ({
+ textarea: textAreaRef?.current!,
+ setInputValue: (value: string) => {
+ form.setValue('text', value);
+ form.trigger();
+ },
+ }));
+
+ const formValid = form.formState.isValid;
+ const value = form.watch('text');
+
+ useAutosizeTextArea(textAreaRef, value, commentMode);
+
+ const submitComment = async ({ text }: { text: string }) => {
+ try {
+ await onSubmit(text);
+ } catch (e) {
+ console.error(e);
+ } finally {
+ form.reset();
+ setCommentMode('editor');
+ }
+ };
- const isSubmitting = form.formState.isSubmitting;
+ const isSubmitting = form.formState.isSubmitting;
- return (
- <div className="relative flex flex-col">
- {commentMode === 'editor' && (
- <div className="rounded-xl rounded-br-lg bg-neutral-100 backdrop-blur-sm dark:border-zinc-700 dark:bg-zinc-700/90">
- <Form {...form}>
- <FormField
- control={form.control}
- name="text"
- render={({ field }) => (
- <FormItem>
- <MentionInput
- disabled={!session?.user}
- autoFocus
- className="resize-none border-0 px-3 py-2 focus-visible:ring-0 md:max-h-[calc(100vh_-_232px)]"
- onChange={(e) => {
- field.onChange(e);
- form.trigger();
- }}
- onKeyDown={(e) => {
- if (isSubmitting) {
- e.preventDefault();
+ return (
+ <div className="relative flex flex-col">
+ {commentMode === 'editor' && (
+ <div className="rounded-xl rounded-br-lg bg-neutral-100 backdrop-blur-sm dark:border-zinc-700 dark:bg-zinc-700/90">
+ <Form {...form}>
+ <FormField
+ control={form.control}
+ name="text"
+ render={({ field }) => (
+ <FormItem>
+ <MentionInput
+ disabled={!session?.user}
+ autoFocus
+ className="resize-none border-0 px-3 py-2 focus-visible:ring-0 md:max-h-[calc(100vh_-_232px)]"
+ onChange={(e) => {
+ field.onChange(e);
+ form.trigger();
+ }}
+ onKeyDown={(e) => {
+ if (isSubmitting) {
+ e.preventDefault();
+ }
+ }}
+ placeholder={
+ placeholder ?? !session?.user
+ ? 'You need to be logged in to comment.'
+ : 'Enter your comment here.'
}
- }}
- placeholder={
- placeholder ?? !session?.user
- ? 'You need to be logged in to comment.'
- : 'Enter your comment here.'
- }
- forwardedref={textAreaRef}
- value={value}
- />
- <FormMessage className="absolute h-8 pl-3 leading-8" />
- </FormItem>
- )}
- />
- </Form>
- </div>
- )}
- {commentMode === 'preview' && (
- <div className="min-h-[5rem] overflow-y-auto break-words px-3 pt-2 text-sm md:max-h-[calc(100vh_-_232px)]">
- <Markdown>{value}</Markdown>
- </div>
- )}
- <div className="flex justify-end">
- <div className="flex gap-2 p-2 pl-0">
- <Button
- className="h-8"
- disabled={isSubmitting || value.length === 0}
- onClick={() => setCommentMode(commentMode === 'editor' ? 'preview' : 'editor')}
- variant={mode === 'create' ? 'secondary' : 'ghost'}
- >
- {commentMode === 'editor' ? 'Preview' : 'Edit'}
- </Button>
- {mode !== 'create' && (
- <Button className="h-8" onClick={() => onCancel?.()} variant="secondary">
- Cancel
+ forwardedref={textAreaRef}
+ value={value}
+ />
+ <FormMessage className="absolute h-8 pl-3 leading-8" />
+ </FormItem>
+ )}
+ />
+ </Form>
+ </div>
+ )}
+ {commentMode === 'preview' && (
+ <div className="min-h-[5rem] overflow-y-auto break-words px-3 pt-2 text-sm md:max-h-[calc(100vh_-_232px)]">
+ <Markdown>{value}</Markdown>
+ </div>
+ )}
+ <div className="flex justify-end">
+ <div className="flex gap-2 p-2 pl-0">
+ <Button
+ className="h-8"
+ disabled={isSubmitting || value.length === 0}
+ onClick={() => setCommentMode(commentMode === 'editor' ? 'preview' : 'editor')}
+ variant={mode === 'create' ? 'secondary' : 'ghost'}
+ >
+ {commentMode === 'editor' ? 'Preview' : 'Edit'}
</Button>
- )}
- <Button
- className="h-8 w-[5.5rem] rounded-lg rounded-br-sm"
- disabled={value.length === 0 || isSubmitting || !formValid}
- onClick={form.handleSubmit(submitComment)}
- >
- {isSubmitting ? <Loader2 className="h-5 w-5 animate-spin" /> : 'Comment'}
- </Button>
+ {mode !== 'create' && (
+ <Button className="h-8" onClick={() => onCancel?.()} variant="secondary">
+ Cancel
+ </Button>
+ )}
+ <Button
+ className="h-8 w-[5.5rem] rounded-lg rounded-br-sm"
+ disabled={value.length === 0 || isSubmitting || !formValid}
+ onClick={form.handleSubmit(submitComment)}
+ >
+ {isSubmitting ? <Loader2 className="h-5 w-5 animate-spin" /> : 'Comment'}
+ </Button>
+ </div>
</div>
</div>
- </div>
- );
-}
+ );
+ },
+);
+CommentInput.displayName = `CommentInput`;
function useAutosizeTextArea(
textAreaRef: RefObject<HTMLTextAreaElement>,
diff --git a/apps/web/src/app/challenge/_components/comments/comment.tsx b/apps/web/src/app/challenge/_components/comments/comment.tsx
index 009a09b6..d86e64af 100644
--- a/apps/web/src/app/challenge/_components/comments/comment.tsx
+++ b/apps/web/src/app/challenge/_components/comments/comment.tsx
@@ -40,7 +40,7 @@ interface SingleCommentProps {
readonly?: boolean;
isReply?: boolean;
isToggleReply?: boolean;
- onClickReply?: () => void;
+ onClickReply?: (replyingTo: string) => void;
onClickToggleReply?: () => void;
preselectedCommentMetadata?: PreselectedCommentMetadata;
deleteComment: (commentId: number) => Promise<void>;
@@ -89,6 +89,8 @@ export function Comment({
const params = useSearchParams();
const replyId = params.get('replyId');
+ const timeoutRef = useRef<NodeJS.Timeout>();
+
const hasPreselectedReply =
preselectedCommentMetadata?.selectedComment?.id === comment.id && Boolean(replyId);
@@ -112,9 +114,52 @@ export function Comment({
preselectedReplyId: hasPreselectedReply ? Number(replyId) : undefined,
});
- const toggleReplies = () => setShowReplies(!showReplies);
+ const toggleReplies = () => {
+ if (showReplies) {
+ setIsReplying(false);
+ }
+
+ setShowReplies(!showReplies);
+ };
const toggleIsReplying = () => setIsReplying(!isReplying);
+ const commentInputRef = useRef<{
+ textarea: HTMLTextAreaElement;
+ setInputValue: (value: string) => void;
+ }>(null);
+
+ useEffect(() => {
+ return () => clearTimeout(timeoutRef.current);
+ }, []);
+
+ function prefillReplyInput(replyingTo: string) {
+ if (commentInputRef?.current) {
+ const name = `@${replyingTo} `;
+ commentInputRef.current.setInputValue(name);
+ commentInputRef.current.textarea?.setSelectionRange(name.length, name.length);
+ commentInputRef.current.textarea?.focus();
+ window.requestAnimationFrame(
+ () =>
+ commentInputRef.current?.textarea?.scrollIntoView({
+ block: 'nearest',
+ behavior: 'smooth',
+ }),
+ );
+ }
+ }
+
+ const showReplyInput = (replyingTo: string) => {
+ setIsReplying(true);
+ clearTimeout(timeoutRef.current);
+
+ timeoutRef.current = setTimeout(() => prefillReplyInput(replyingTo));
+ };
+
+ const hideReplyInput = () => {
+ setIsReplying(false);
+ clearTimeout(timeoutRef.current);
+ };
+
return (
<div className="flex flex-col px-2 py-1">
<SingleComment
@@ -127,22 +172,6 @@ export function Comment({
deleteComment={deleteComment}
updateComment={updateComment}
/>
- {isReplying ? (
- <div className="relative mt-2 pb-2 pl-8">
- <Reply className="absolute left-2 top-2 h-4 w-4 opacity-50" />
- <CommentInput
- mode="edit"
- onCancel={() => {
- setIsReplying(false);
- }}
- onSubmit={async (text) => {
- await addReplyComment(text);
- setShowReplies(true);
- setIsReplying(false);
- }}
- />
- </div>
- ) : null}
{showReplies && status === 'pending' ? <CommentSkeleton /> : null}
{showReplies ? (
@@ -158,6 +187,7 @@ export function Comment({
preselectedCommentMetadata={preselectedCommentMetadata}
deleteComment={deleteReplyComment}
updateComment={updateReplyComment}
+ onClickReply={(replyingTo) => showReplyInput(replyingTo)}
/>
)),
)}
@@ -175,6 +205,22 @@ export function Comment({
) : null}
</>
) : null}
+
+ {isReplying ? (
+ <div className="relative mt-2 pb-2 pl-8">
+ <Reply className="absolute left-2 top-2 h-4 w-4 opacity-50" />
+ <CommentInput
+ mode="edit"
+ onCancel={() => hideReplyInput()}
+ onSubmit={async (text) => {
+ await addReplyComment(text);
+ hideReplyInput();
+ setShowReplies(true);
+ }}
+ ref={commentInputRef}
+ />
+ </div>
+ ) : null}
</div>
);
}
@@ -298,7 +344,7 @@ function SingleComment({
<div className="flex gap-3">
<ExpandableContent content={comment.text} />
- <div className="flex flex-col items-end gap-2">
+ <div className="flex flex-col items-end">
{!readonly && (
<>
<div className="flex gap-1">
@@ -323,132 +369,132 @@ function SingleComment({
}}
/>
- {!isReply && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="secondary" size="xs" onClick={onClickReply}>
- <Reply className="h-3 w-3" />
- <span className="sr-only">Create a reply</span>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Reply</p>
- </TooltipContent>
- </Tooltip>
- )}
- </div>
-
- <div className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
- <div>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="secondary"
- size="xs"
- className="gap-2"
- onClick={() => {
- copyPathNotifyUser(Boolean(isReply), slug as string);
- }}
- >
- <Share className="h-3 w-3" />
- <span className="sr-only">Share this comment</span>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Share</p>
- </TooltipContent>
- </Tooltip>
- </div>
-
- <div>
- {isAuthor ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="secondary"
- size="xs"
- onClick={() => setIsEditing(!isEditing)}
- >
- <Pencil className="h-3 w-3" />
- <span className="sr-only">Edit this comment</span>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Edit</p>
- </TooltipContent>
- </Tooltip>
- ) : null}
- </div>
-
- <div>
- {isAuthor || isAdminAndModerator ? (
- <Tooltip>
- <CommentDeleteDialog asChild comment={comment} deleteComment={deleteComment}>
- <TooltipTrigger asChild>
- <Button variant="secondary" size="xs">
- <Trash2 className="h-3 w-3" />
- <span className="sr-only">Delete this comment</span>
- </Button>
- </TooltipTrigger>
- </CommentDeleteDialog>
- <TooltipContent>
- <p>Delete</p>
- </TooltipContent>
- </Tooltip>
- ) : (
- <Tooltip>
- <ReportDialog triggerAsChild commentId={comment.id} reportType="COMMENT">
- <TooltipTrigger asChild>
- <Button variant="secondary" size="xs">
- <Flag className="h-3 w-3" />
- <span className="sr-only">Report this comment</span>
- </Button>
- </TooltipTrigger>
- </ReportDialog>
- <TooltipContent>
- <p>Report</p>
- </TooltipContent>
- </Tooltip>
- )}
- </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="secondary"
+ size="xs"
+ onClick={() => onClickReply?.(comment?.user?.name)}
+ >
+ <Reply className="h-3 w-3" />
+ <span className="sr-only">Create a reply</span>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Reply</p>
+ </TooltipContent>
+ </Tooltip>
</div>
</>
)}
</div>
</div>
- {!isEditing && (
- <div className="mb-2 mt-1.5 flex justify-between">
- {hasBeenEdited ? (
- <div className="text-muted-foreground flex items-center gap-2 whitespace-nowrap text-xs">
- Last edited at{' '}
- {new Intl.DateTimeFormat(undefined, {
- timeStyle: 'short',
- dateStyle: 'short',
- }).format(comment.updatedAt)}
- </div>
- ) : null}
- {comment._count.replies > 0 && (
- <Button
- variant="ghost"
- size="xs"
- className="z-50 ml-auto gap-1"
- onClick={onClickToggleReply}
- >
- {isToggleReply ? (
- <ChevronDown className="h-4 w-4" />
- ) : (
- <ChevronUp className="h-4 w-4" />
- )}
-
- <div className="text-xs">
- {comment._count.replies === 1 ? '1 reply' : `${comment._count.replies} replies`}
+ <div className="mb-2 flex flex-row flex-wrap items-center justify-between">
+ {!isEditing && (
+ <div className="flex gap-4">
+ {comment._count.replies > 0 && (
+ <Button
+ variant="secondary"
+ size="xs"
+ className="z-50 gap-1"
+ onClick={onClickToggleReply}
+ >
+ {isToggleReply ? (
+ <ChevronDown className="h-4 w-4" />
+ ) : (
+ <ChevronUp className="h-4 w-4" />
+ )}
+
+ <div className="text-xs">
+ {comment._count.replies === 1 ? '1 reply' : `${comment._count.replies} replies`}
+ </div>
+ <span className="sr-only">Toggle replies view</span>
+ </Button>
+ )}
+ {hasBeenEdited ? (
+ <div className="text-muted-foreground flex items-center gap-2 whitespace-nowrap text-xs">
+ Last edited at{' '}
+ {new Intl.DateTimeFormat(undefined, {
+ timeStyle: 'short',
+ dateStyle: 'short',
+ }).format(comment.updatedAt)}
</div>
- <span className="sr-only">Toggle replies view</span>
- </Button>
- )}
+ ) : null}
+ </div>
+ )}
+ <div className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
+ <div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="secondary"
+ size="xs"
+ className="gap-2"
+ onClick={() => {
+ copyPathNotifyUser(Boolean(isReply), slug as string);
+ }}
+ >
+ <Share className="h-3 w-3" />
+ <span className="sr-only">Share this comment</span>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Share</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+
+ <div>
+ {isAuthor ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="secondary" size="xs" onClick={() => setIsEditing(!isEditing)}>
+ <Pencil className="h-3 w-3" />
+ <span className="sr-only">Edit this comment</span>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Edit</p>
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ </div>
+
+ <div>
+ {isAuthor || isAdminAndModerator ? (
+ <Tooltip>
+ <CommentDeleteDialog asChild comment={comment} deleteComment={deleteComment}>
+ <TooltipTrigger asChild>
+ <Button variant="secondary" size="xs">
+ <Trash2 className="h-3 w-3" />
+ <span className="sr-only">Delete this comment</span>
+ </Button>
+ </TooltipTrigger>
+ </CommentDeleteDialog>
+ <TooltipContent>
+ <p>Delete</p>
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <Tooltip>
+ <ReportDialog triggerAsChild commentId={comment.id} reportType="COMMENT">
+ <TooltipTrigger asChild>
+ <Button variant="secondary" size="xs">
+ <Flag className="h-3 w-3" />
+ <span className="sr-only">Report this comment</span>
+ </Button>
+ </TooltipTrigger>
+ </ReportDialog>
+ <TooltipContent>
+ <p>Report</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
</div>
- )}
+ </div>
+
{isEditing ? (
<div className="mb-2">
<CommentInput