Skip to content

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

[Feat] Refactor comments CRUD (#1103)

__aadamwe1f005a4c9c4
diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/comment-input.tsx b/apps/web/src/app/[locale]/challenge/_components/comments/comment-input.tsx
index bf17ab78..93839150 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/comment-input.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/comment-input.tsx
@@ -2,8 +2,6 @@ import { Loader2 } from '@repo/ui/icons';
import { useSession } from '@repo/auth/react';
import { useEffect, useRef, useState, type RefObject } from 'react';
import { Button } from '@repo/ui/components/button';
-import { useToast } from '@repo/ui/components/use-toast';
-import { ToastAction } from '@repo/ui/components/toast';
import { Textarea } from '@repo/ui/components/textarea';
import { Markdown } from '@repo/ui/components/markdown';
import { useForm } from 'react-hook-form';
@@ -14,65 +12,38 @@ import { singleFieldSchema, type SingleFieldSchema } from '~/utils/zodSingleStri
interface Props {
mode: 'create' | 'edit' | 'reply';
onCancel?: () => void;
- onChange: (text: string) => void;
- value: string;
placeholder?: string;
- onSubmit: () => Promise<void>;
+ onSubmit: (text: string) => Promise<void>;
+ defaultValue?: string;
}
-export function CommentInput({ mode, onCancel, onChange, value, placeholder, onSubmit }: Props) {
+export function CommentInput({ mode, onCancel, placeholder, onSubmit, defaultValue }: Props) {
const { data: session } = useSession();
- const { toast } = useToast();
const [commentMode, setCommentMode] = useState<'editor' | 'preview'>('editor');
- const [isSubmitting, setIsSubmitting] = useState(false);
+
const textAreaRef = useRef<HTMLTextAreaElement>(null);
const form = useForm<SingleFieldSchema>({
resolver: zodResolver(singleFieldSchema),
- defaultValues: { text: '' },
+ defaultValues: { text: defaultValue ?? '' },
});
const formValid = form.formState.isValid;
-
+ const value = form.watch('text');
useAutosizeTextArea(textAreaRef, value, commentMode);
- const handleEnterKey = async () => {
- if (!session?.user) {
- toast({
- variant: 'destructive',
- title: 'You need to be logged in to comment.',
- action: <ToastAction altText="Dismiss">Dismiss</ToastAction>,
- });
-
- return;
- }
- setIsSubmitting(true);
- await onSubmit();
- setIsSubmitting(false);
- };
-
- const submitComment = async () => {
+ const submitComment = async ({ text }: { text: string }) => {
try {
- if (!session?.user) {
- toast({
- variant: 'destructive',
- title: 'You need to be logged in to comment.',
- action: <ToastAction altText="Dismiss">Dismiss</ToastAction>,
- });
-
- return;
- }
-
- setIsSubmitting(true);
-
- await onSubmit();
+ await onSubmit(text);
} catch (e) {
console.error(e);
} finally {
- setIsSubmitting(false);
+ form.reset();
setCommentMode('editor');
}
};
+ const isSubmitting = form.formState.isSubmitting;
+
return (
<div className="relative flex flex-col">
{commentMode === 'editor' && (
@@ -89,7 +60,6 @@ export function CommentInput({ mode, onCancel, onChange, value, placeholder, onS
className="resize-none border-0 px-3 py-2 focus-visible:ring-0 md:max-h-[calc(100vh_-_232px)]"
onChange={(e) => {
field.onChange(e);
- onChange(e.target.value);
form.trigger();
}}
onKeyDown={(e) => {
@@ -98,7 +68,7 @@ export function CommentInput({ mode, onCancel, onChange, value, placeholder, onS
return;
}
if (e.key === 'Enter' && e.shiftKey) {
- form.handleSubmit(handleEnterKey)();
+ form.handleSubmit(submitComment);
e.preventDefault();
}
}}
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 3e36b3f5..199fe64f 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx
@@ -17,7 +17,6 @@ import {
Trash2,
MoreHorizontal,
} from '@repo/ui/icons';
-import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query';
import clsx from 'clsx';
import Link from 'next/link';
import { useParams, useSearchParams } from 'next/navigation';
@@ -27,17 +26,13 @@ import { ReportDialog } from '~/components/ReportDialog';
import { getRelativeTime } from '~/utils/relativeTime';
import { Vote } from '../vote';
import { CommentInput } from './comment-input';
-import { replyComment, updateComment } from './comment.action';
import { CommentDeleteDialog } from './delete';
-import {
- getAllComments,
- type PaginatedComments,
- type PreselectedCommentMetadata,
-} from './getCommentRouteData';
+import { type PaginatedComments, type PreselectedCommentMetadata } from './getCommentRouteData';
import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/avatar';
import { Button } from '@repo/ui/components/button';
import { CommentSkeleton } from './comment-skeleton';
import { isAdminOrModerator } from '~/utils/auth-guards';
+import { useCommentsReplies } from './comments.hooks';
interface SingleCommentProps {
comment: PaginatedComments['comments'][number];
@@ -46,15 +41,17 @@ interface SingleCommentProps {
isToggleReply?: boolean;
onClickReply?: () => void;
onClickToggleReply?: () => void;
- queryKey?: (number | string)[];
- replyQueryKey?: (number | string)[];
preselectedCommentMetadata?: PreselectedCommentMetadata;
+ deleteComment: (commentId: number) => Promise<void>;
+ updateComment: (text: string, commentId: number) => Promise<void>;
}
type CommentProps = SingleCommentProps & {
preselectedCommentMetadata?: PreselectedCommentMetadata;
rootId: number;
type: CommentRoot;
+ deleteComment: (commentId: number) => Promise<void>;
+ updateComment: (text: string, commentId: number) => Promise<void>;
};
const commentReportSchema = z
@@ -78,8 +75,6 @@ const commentReportSchema = z
export type CommentReportSchemaType = z.infer<typeof commentReportSchema>;
-const REPLIES_PAGESIZE = 5;
-
// million-ignore
export function Comment({
comment,
@@ -87,7 +82,8 @@ export function Comment({
readonly = false,
rootId,
type,
- queryKey,
+ deleteComment,
+ updateComment,
}: CommentProps) {
const params = useSearchParams();
const replyId = params.get('replyId');
@@ -96,96 +92,23 @@ export function Comment({
preselectedCommentMetadata?.selectedComment?.id === comment.id && Boolean(replyId);
const [showReplies, setShowReplies] = useState(hasPreselectedReply);
-
const [isReplying, setIsReplying] = useState(false);
- const [replyText, setReplyText] = useState('');
- const queryClient = useQueryClient();
-
- const replyQueryKey = [`comment-${comment.id}-replies`];
-
- const {
- data: replies,
- fetchStatus,
- isPending: isLoadingReplies,
- } = useQuery({
- queryKey: replyQueryKey,
- queryFn: () => getAllComments({ rootId, rootType: type, parentId: comment.id }),
- staleTime: 5000,
- enabled: showReplies,
- });
const {
- data: paginatedReplies,
+ status,
+ data,
fetchNextPage,
- isFetching: isFetchingMoreReplies,
- hasNextPage: hasMoreReplies,
- refetch,
- } = useInfiniteQuery({
- initialPageParam: 0,
- queryKey: [...replyQueryKey, 'paginated'],
- queryFn: ({ pageParam }) => {
- // `cursor` is the start index of the current page
- const cursor = Number(pageParam);
-
- let take = REPLIES_PAGESIZE;
- if (hasPreselectedReply && cursor === 0) {
- const preselectedReplyIndex = replies!.findIndex((reply) => Number(replyId) === reply.id);
- take = Math.ceil((preselectedReplyIndex + 1) / REPLIES_PAGESIZE) * REPLIES_PAGESIZE;
- }
-
- // `end` is exclusive, and therefore also the next cursor
- const end = cursor + take;
-
- return {
- // if the current page is the last, don't return the next cursor
- cursor: end < replies!.length ? end : undefined,
- replies: replies!.slice(cursor, end),
- };
- },
- enabled: Boolean(replies),
- getNextPageParam: (_, pages) => pages.at(-1)?.cursor,
+ addReplyComment,
+ updateReplyComment,
+ deleteReplyComment,
+ showLoadMoreRepliesBtn,
+ } = useCommentsReplies({
+ enabled: showReplies,
+ rootId,
+ type,
+ parentCommentId: comment.id,
});
- useEffect(() => {
- if (replies) {
- refetch();
- }
- }, [replies, refetch]);
-
- async function createChallengeCommentReply() {
- try {
- const res = await replyComment(
- {
- text: replyText,
- rootId,
- rootType: type,
- },
- 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>,
- });
- }
- setReplyText('');
- queryClient.invalidateQueries({ queryKey: replyQueryKey });
- queryClient.invalidateQueries({ queryKey });
- setShowReplies(true);
- } catch (e) {
- toast({
- title: 'Unauthorized',
- variant: 'destructive',
- description: <p>You need to be signed in to post a comment.</p>,
- });
- }
- }
-
const toggleReplies = () => setShowReplies(!showReplies);
const toggleIsReplying = () => setIsReplying(!isReplying);
@@ -198,6 +121,8 @@ export function Comment({
onClickReply={toggleIsReplying}
onClickToggleReply={toggleReplies}
readonly={readonly}
+ deleteComment={deleteComment}
+ updateComment={updateComment}
/>
{isReplying ? (
<div className="relative mt-2 pb-2 pl-8">
@@ -207,34 +132,34 @@ export function Comment({
onCancel={() => {
setIsReplying(false);
}}
- onChange={setReplyText}
- onSubmit={async () => {
- await createChallengeCommentReply();
+ onSubmit={async (text) => {
+ await addReplyComment(text);
+ setShowReplies(true);
setIsReplying(false);
}}
- value={replyText}
/>
</div>
) : null}
- {isLoadingReplies && fetchStatus !== 'idle' ? <CommentSkeleton /> : null}
+ {showReplies && status === 'pending' ? <CommentSkeleton /> : null}
{showReplies ? (
<>
<div className="flex flex-col gap-1 pl-6 pt-1">
- {paginatedReplies?.pages.flatMap((page) =>
+ {data?.pages.flatMap((page) =>
page.replies.map((reply) => (
// this is a reply
<SingleComment
comment={reply}
isReply
key={reply.id}
- replyQueryKey={replyQueryKey}
preselectedCommentMetadata={preselectedCommentMetadata}
+ deleteComment={deleteReplyComment}
+ updateComment={updateReplyComment}
/>
)),
)}
</div>
- {hasMoreReplies && !isFetchingMoreReplies ? (
+ {showLoadMoreRepliesBtn ? (
<Button
variant="ghost"
className="gap-1 text-xs text-neutral-500 duration-200 hover:text-neutral-400 dark:text-neutral-400 dark:hover:text-neutral-300"
@@ -260,16 +185,14 @@ function SingleComment({
isToggleReply,
onClickReply,
onClickToggleReply,
- queryKey,
readonly = false,
- replyQueryKey,
preselectedCommentMetadata,
+ deleteComment,
+ updateComment,
}: SingleCommentProps) {
const { slug } = useParams();
const searchParams = useSearchParams();
const replyId = searchParams.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();
@@ -278,31 +201,6 @@ function SingleComment({
? Number(replyId) === comment.id
: preselectedCommentMetadata?.selectedComment?.id === comment.id;
- 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({ queryKey });
- queryClient.invalidateQueries({ queryKey: replyQueryKey });
- } catch (e) {
- toast({
- title: 'Unauthorized',
- variant: 'destructive',
- description: <p>You need to be signed in to post a comment.</p>,
- });
- }
- }
-
async function copyPathNotifyUser(isReply: boolean, slug: string) {
try {
await copyCommentUrlToClipboard(isReply, slug);
@@ -410,15 +308,14 @@ function SingleComment({
<div className="mb-2">
<CommentInput
mode="edit"
+ defaultValue={comment.text}
onCancel={() => {
setIsEditing(false);
}}
- onChange={setText}
- onSubmit={async () => {
- await updateChallengeComment();
+ onSubmit={async (text) => {
+ await updateComment(text, comment.id);
setIsEditing(false);
}}
- value={text}
/>
</div>
) : null}
@@ -488,7 +385,7 @@ function SingleComment({
) : null}
{isAuthor || isAdminAndModerator ? (
<Tooltip>
- <CommentDeleteDialog asChild comment={comment}>
+ <CommentDeleteDialog asChild comment={comment} deleteComment={deleteComment}>
<TooltipTrigger asChild>
<Button variant="secondary" size="xs">
<Trash2 className="h-3 w-3" />
diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/comments.constants.ts b/apps/web/src/app/[locale]/challenge/_components/comments/comments.constants.ts
new file mode 100644
index 00000000..5f943ed5
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/comments.constants.ts
@@ -0,0 +1,36 @@
+export const sortKeys = [
+ {
+ label: 'Newest Comments',
+ value: 'newest',
+ key: 'createdAt',
+ order: 'desc',
+ },
+ {
+ label: 'Oldest Comments',
+ value: 'oldest',
+ key: 'createdAt',
+ order: 'asc',
+ },
+ {
+ label: 'Most Votes',
+ value: 'votes',
+ key: 'vote',
+ order: 'desc',
+ },
+ {
+ label: 'Most Replies',
+ value: 'replies',
+ key: 'replies',
+ order: 'desc',
+ },
+] as const;
+
+export const commentErrors = {
+ empty: { title: 'Empty Comment', description: 'You cannot post an empty comment.' },
+ unauthorized: { title: 'Unauthorized', description: 'You must be logged in to post a comment.' },
+ unexpected: {
+ title: 'Uh Oh!',
+ description: 'An error occurred while trying to delete the comment.',
+ },
+ invalidId: { title: 'Invalid Comment', description: 'The comment id is invalid.' },
+};
diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/comments.hooks.tsx b/apps/web/src/app/[locale]/challenge/_components/comments/comments.hooks.tsx
new file mode 100644
index 00000000..97dbf302
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/comments.hooks.tsx
@@ -0,0 +1,294 @@
+import {
+ keepPreviousData,
+ useInfiniteQuery,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query';
+import { useReducer } from 'react';
+
+import { commentErrors, sortKeys } from './comments.constants';
+import { getPaginatedComments } from './getCommentRouteData';
+import type { CommentRoot } from '@repo/db/types';
+import {
+ addComment as addCommentAction,
+ deleteComment as deleteCommentAction,
+ replyComment,
+ updateComment as updateCommentAction,
+} from './comment.action';
+import { toast } from '@repo/ui/components/use-toast';
+
+const getRootQueryKey = (rootId: number, type: CommentRoot) =>
+ `${type.toLowerCase()}-${rootId}-comments`;
+
+export type SortItem = (typeof sortKeys)[number];
+
+interface CommentsMeta {
+ page: number;
+ sort: SortItem;
+}
+
+interface DefaultCommentsProps {
+ rootId: number;
+ type: CommentRoot;
+}
+
+interface UseCommentsProps extends DefaultCommentsProps {
+ initialPage?: number;
+}
+
+export function useComments({ type, rootId, initialPage }: UseCommentsProps) {
+ const queryClient = useQueryClient();
+ const [commentsMeta, updateCommentsMeta] = useReducer(
+ (state: CommentsMeta, action: Partial<CommentsMeta>) => ({ ...state, ...action }),
+ {
+ page: initialPage ?? 1,
+ sort: sortKeys[0],
+ },
+ );
+
+ const getQueryKey = ({ sort, page }: { sort: string; page: number }) => [
+ getRootQueryKey(rootId, type),
+ sort,
+ page,
+ ];
+
+ const { status, data } = useQuery({
+ queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: commentsMeta.page }),
+ queryFn: () => {
+ return getPaginatedComments({
+ rootId,
+ page: commentsMeta.page,
+ rootType: type,
+ sortKey: commentsMeta.sort.key,
+ sortOrder: commentsMeta.sort.order,
+ });
+ },
+ placeholderData: keepPreviousData,
+ staleTime: 60000, // one minute
+ refetchOnWindowFocus: false,
+ });
+
+ const changePage = (page: number) => {
+ updateCommentsMeta({ page });
+ };
+
+ const changeSorting = (sort: string) => {
+ updateCommentsMeta({
+ sort: sortKeys.find((key) => key.value === sort) ?? sortKeys[0],
+ page: 1,
+ });
+ };
+
+ const deleteComment = async (commentId: number) => {
+ try {
+ const res = await deleteCommentAction(commentId);
+ if (res === 'unauthorized') {
+ toast(commentErrors.unauthorized);
+ } else if (res === 'invalid_comment') {
+ toast(commentErrors.invalidId);
+ } else {
+ toast({
+ title: 'Comment Deleted',
+ variant: 'success',
+ description: 'The comment was successfully deleted.',
+ });
+ }
+ const newPage = data?.comments.length === 1 ? commentsMeta.page - 1 : commentsMeta.page;
+ changePage(newPage);
+ queryClient.invalidateQueries({
+ queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: newPage }),
+ });
+ } catch (e) {
+ toast({
+ ...commentErrors.unexpected,
+ variant: 'destructive',
+ });
+ }
+ };
+
+ const addComment = async (text: string) => {
+ try {
+ const res = await addCommentAction({
+ text,
+ rootId,
+ rootType: type,
+ });
+ if (res === 'text_is_empty') {
+ toast(commentErrors.empty);
+ } else if (res === 'unauthorized') {
+ toast({
+ ...commentErrors.unauthorized,
+ variant: 'destructive',
+ });
+ }
+ const newPage = 1;
+ changePage(newPage);
+ queryClient.invalidateQueries({
+ queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: newPage }),
+ });
+ } catch (e) {
+ toast({
+ ...commentErrors.unauthorized,
+ variant: 'destructive',
+ });
+ }
+ };
+
+ const updateComment = async (text: string, commentId: number) => {
+ try {
+ const res = await updateCommentAction(text, commentId);
+ if (res === 'text_is_empty') {
+ toast(commentErrors.empty);
+ } else if (res === 'unauthorized') {
+ toast(commentErrors.unauthorized);
+ }
+ queryClient.invalidateQueries({
+ queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: commentsMeta.page }),
+ });
+ } catch (e) {
+ toast({
+ ...commentErrors.unauthorized,
+ variant: 'destructive',
+ });
+ }
+ };
+
+ return {
+ data,
+ status,
+ commentsMeta,
+ changePage,
+ changeSorting,
+ deleteComment,
+ addComment,
+ updateComment,
+ };
+}
+
+interface UseCommentRepliesProps extends DefaultCommentsProps {
+ parentCommentId: number;
+ enabled: boolean;
+}
+
+const REPLIES_PAGESIZE = 5;
+
+export function useCommentsReplies({
+ rootId,
+ type,
+ parentCommentId,
+ enabled,
+}: UseCommentRepliesProps) {
+ const queryClient = useQueryClient();
+ const rootQueryKey = [getRootQueryKey(rootId, type)];
+ const queryKey = [...rootQueryKey, `comment-${parentCommentId}-replies`];
+
+ const {
+ data,
+ fetchNextPage,
+ isFetching: isFetchingMoreReplies,
+ hasNextPage: hasMoreReplies,
+ status,
+ } = useInfiniteQuery({
+ enabled,
+ placeholderData: keepPreviousData,
+ initialPageParam: 1,
+ queryKey,
+ queryFn: async ({ pageParam }) => {
+ // `page` is the start index of the current page
+ const page = Number(pageParam);
+
+ const comments = await getPaginatedComments({
+ rootId,
+ page,
+ take: REPLIES_PAGESIZE,
+ rootType: type,
+ parentId: parentCommentId,
+ });
+
+ return {
+ // if the current page is the last, don't return the next cursor
+ page: comments.hasMore ? page + 1 : undefined,
+ replies: comments.comments,
+ };
+ },
+ getNextPageParam: (_, pages) => pages.at(-1)?.page,
+ });
+
+ const addReplyComment = async (text: string) => {
+ try {
+ const res = await replyComment(
+ {
+ text,
+ rootId,
+ rootType: type,
+ },
+ parentCommentId,
+ );
+ if (res === 'text_is_empty') {
+ toast(commentErrors.empty);
+ } else if (res === 'unauthorized') {
+ toast(commentErrors.unauthorized);
+ }
+ //Invalidate the root query to refetch the comments
+ queryClient.invalidateQueries({ queryKey: rootQueryKey });
+ } catch (e) {
+ toast({
+ ...commentErrors.unauthorized,
+ variant: 'destructive',
+ });
+ }
+ };
+
+ const updateReplyComment = async (text: string, commentId: number) => {
+ try {
+ const res = await updateCommentAction(text, commentId);
+ if (res === 'text_is_empty') {
+ toast(commentErrors.empty);
+ } else if (res === 'unauthorized') {
+ toast(commentErrors.unauthorized);
+ }
+ queryClient.invalidateQueries({ queryKey });
+ } catch (e) {
+ toast({
+ ...commentErrors.unauthorized,
+ variant: 'destructive',
+ });
+ }
+ };
+
+ const deleteReplyComment = async (commentId: number) => {
+ try {
+ const res = await deleteCommentAction(commentId);
+ if (res === 'unauthorized') {
+ toast(commentErrors.unauthorized);
+ } else if (res === 'invalid_comment') {
+ toast(commentErrors.invalidId);
+ } else {
+ toast({
+ title: 'Comment Deleted',
+ variant: 'success',
+ description: 'The comment was successfully deleted.',
+ });
+ }
+ //Invalidate the root query to refetch the comments
+ queryClient.invalidateQueries({ queryKey: rootQueryKey });
+ } catch (e) {
+ toast({
+ ...commentErrors.unexpected,
+ variant: 'destructive',
+ });
+ }
+ };
+
+ const showLoadMoreRepliesBtn = hasMoreReplies || isFetchingMoreReplies;
+
+ return {
+ data,
+ status,
+ fetchNextPage,
+ addReplyComment,
+ updateReplyComment,
+ deleteReplyComment,
+ showLoadMoreRepliesBtn,
+ };
+}
diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/delete/index.tsx b/apps/web/src/app/[locale]/challenge/_components/comments/delete/index.tsx
index 436c4747..2f98cdd8 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/delete/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/delete/index.tsx
@@ -5,59 +5,28 @@ import { Markdown } from '@repo/ui/components/markdown';
import { TypographyP } from '@repo/ui/components/paragraph';
import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
import { TypographyLarge } from '@repo/ui/components/typography/large';
-import { toast } from '@repo/ui/components/use-toast';
-import { useQueryClient } from '@tanstack/react-query';
+
import { useState } from 'react';
import { getRelativeTime } from '~/utils/relativeTime';
-import { deleteComment } from '../comment.action';
+
import { type PaginatedComments } from '../getCommentRouteData';
interface CommentDeleteDialogProps extends DialogTriggerProps {
comment: PaginatedComments['comments'][number];
- queryKey?: (number | string)[];
+ deleteComment: (commentId: number) => Promise<void>;
}
export function CommentDeleteDialog({
children,
comment,
- queryKey,
+ deleteComment,
...props
}: CommentDeleteDialogProps) {
- const queryClient = useQueryClient();
const [isOpen, setIsOpen] = useState(false);
async function handleDeleteComment() {
- try {
- const res = await deleteComment(comment.id);
- if (res === 'unauthorized') {
- toast({
- title: 'Unauthorized',
- description: <p>You need to be signed in to post a comment.</p>,
- });
- } else if (res === 'invalid_comment') {
- toast({
- title: 'Invalid Comment',
- description: 'The comment id is invalid.',
- });
- } else {
- toast({
- title: 'Comment Deleted',
- variant: 'success',
- description: 'The comment was successfully deleted.',
- });
- }
- } catch (e) {
- // todo: log on a dump service.
- console.log(e);
- toast({
- title: 'Uh Oh!',
- variant: 'destructive',
- description: 'An error occurred while trying to delete the comment.',
- });
- } finally {
- queryClient.invalidateQueries({ queryKey });
- setIsOpen(!isOpen);
- }
+ await deleteComment(comment.id);
+ setIsOpen(!isOpen);
}
return (
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 f4572169..97cd8926 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts
@@ -82,6 +82,25 @@ export async function getPreselectedSolutionCommentMetadata(
};
}
+async function getCommentsCount({
+ rootType,
+ rootId,
+ parentId = null,
+}: {
+ rootType: CommentRoot;
+ rootId: number;
+ parentId?: number | null;
+}) {
+ return prisma.comment.count({
+ where: {
+ rootType,
+ parentId,
+ visible: true,
+ ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),
+ },
+ });
+}
+
export async function getPaginatedComments({
page,
rootId,
@@ -89,6 +108,7 @@ export async function getPaginatedComments({
parentId = null,
sortKey = 'createdAt',
sortOrder = 'desc',
+ take = PAGESIZE,
}: {
page: number;
rootId: number;
@@ -96,17 +116,11 @@ export async function getPaginatedComments({
parentId?: number | null;
sortKey?: SortKey;
sortOrder?: SortOrder;
+ take?: number;
}) {
const session = await getServerAuthSession();
- const totalComments = await prisma.comment.count({
- where: {
- rootType,
- parentId,
- visible: true,
- ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),
- },
- });
+ const totalComments = await getCommentsCount({ rootType, rootId, parentId });
const totalReplies = await prisma.comment.count({
where: {
@@ -120,8 +134,8 @@ export async function getPaginatedComments({
});
const comments = await prisma.comment.findMany({
- skip: (page - 1) * PAGESIZE,
- take: PAGESIZE,
+ skip: (page - 1) * take,
+ take,
where: {
rootType,
parentId,
@@ -164,7 +178,7 @@ export async function getPaginatedComments({
},
});
- const totalPages = Math.ceil(totalComments / PAGESIZE);
+ const totalPages = Math.ceil(totalComments / take);
return {
totalComments: totalReplies + totalComments,
@@ -173,64 +187,3 @@ export async function getPaginatedComments({
comments,
};
}
-
-export async function getAllComments({
- rootId,
- rootType,
- parentId = null,
- sortKey = 'createdAt',
- sortOrder = 'desc',
-}: {
- rootId: number;
- rootType: CommentRoot;
- parentId?: number | null;
- sortKey?: SortKey;
- sortOrder?: SortOrder;
-}) {
- const session = await getServerAuthSession();
-
- const comments = await prisma.comment.findMany({
- where: {
- rootType,
- parentId,
- ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),
- visible: true,
- },
- orderBy: orderBy(sortKey, sortOrder),
- include: {
- user: {
- select: {
- id: true,
- name: true,
- image: true,
- },
- },
- _count: {
- select: {
- replies: true,
- vote: true,
- },
- },
- vote: {
- select: {
- userId: true,
- },
- where: {
- userId: session?.user.id || '',
- },
- },
- rootChallenge: {
- select: {
- name: true,
- },
- },
- rootSolution: {
- select: {
- title: true,
- },
- },
- },
- });
-
- return comments;
-}
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 8d341a05..4b8a8f19 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx
@@ -1,19 +1,18 @@
'use client';
import type { CommentRoot } from '@repo/db/types';
-import { toast } from '@repo/ui/components/use-toast';
import { ChevronDown, MessageCircle } from '@repo/ui/icons';
-import { useQuery, useQueryClient } from '@tanstack/react-query';
import clsx from 'clsx';
import { useRef, useState } from 'react';
import { Comment } from './comment';
import { CommentInput } from './comment-input';
import { CommentSkeleton } from './comment-skeleton';
-import { addComment } from './comment.action';
import { getPaginatedComments, type PreselectedCommentMetadata } from './getCommentRouteData';
import NoComments from './nocomments';
import { Pagination } from '../pagination';
import { SortSelect } from '../sort-select';
+import { useComments } from './comments.hooks';
+import { sortKeys } from './comments.constants';
interface Props {
preselectedCommentMetadata?: PreselectedCommentMetadata;
@@ -22,98 +21,32 @@ interface Props {
type: CommentRoot;
}
-const sortKeys = [
- {
- label: 'Newest Comments',
- value: 'newest',
- key: 'createdAt',
- order: 'desc',
- },
- {
- label: 'Oldest Comments',
- value: 'oldest',
- key: 'createdAt',
- order: 'asc',
- },
- {
- label: 'Most Votes',
- value: 'votes',
- key: 'vote',
- order: 'desc',
- },
- {
- label: 'Most Replies',
- value: 'replies',
- key: 'replies',
- order: 'desc',
- },
-] as const;
-
// million-ignore
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(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: () =>
- getPaginatedComments({
- rootId,
- page,
- rootType: type,
- sortKey: sortKey.key,
- sortOrder: sortKey.order,
- }),
- staleTime: 60000, // one minute
- refetchOnWindowFocus: false,
+ const {
+ data,
+ addComment,
+ commentsMeta,
+ status,
+ changePage,
+ changeSorting,
+ deleteComment,
+ updateComment,
+ } = useComments({
+ type,
+ rootId,
});
- async function createChallengeComment() {
- try {
- const res = await addComment({
- text,
- rootId,
- rootType: type,
- });
- 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>,
- });
- }
- setText('');
- queryClient.invalidateQueries({ queryKey: [`${type.toLowerCase()}-${rootId}-comments`] });
- } catch (e) {
- toast({
- title: 'Unauthorized',
- variant: 'destructive',
- description: <p>You need to be signed in to post a comment.</p>,
- });
- }
- }
-
const handleChangePage = (page: number) => {
- setPage(page);
+ changePage(page);
commentContainerRef.current?.scroll({
top: 128,
behavior: 'smooth',
});
};
- const handleValueChange = (value: string) => {
- setSortKey(sortKeys.find((sk) => sk.value === value) ?? sortKeys[0]);
- setPage(1);
- };
-
return (
<div
className={clsx(
@@ -133,7 +66,7 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =
<div className="flex items-center gap-2">
<MessageCircle className="h-5 w-5" />
Comments
- {data?.totalComments != null && <span>({data.totalComments})</span>}
+ {data?.totalComments != null ? <span>({data.totalComments})</span> : null}
</div>
<ChevronDown
className={clsx('h-4 w-4 duration-300', {
@@ -153,34 +86,30 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =
ref={commentContainerRef}
>
<div className="m-2 mb-4 mt-0">
- <CommentInput
- mode="create"
- onChange={setText}
- onSubmit={createChallengeComment}
- value={text}
- />
+ <CommentInput mode="create" onSubmit={addComment} />
</div>
{(data?.comments.length ?? 0) > 0 && (
<SortSelect
- currentSortKey={sortKey}
+ currentSortKey={commentsMeta.sort}
totalSortKeys={sortKeys}
- onValueChange={handleValueChange}
+ onValueChange={changeSorting}
/>
)}
{status === 'pending' && <CommentSkeleton />}
<div className="flex-1">
{status === 'success' &&
- (data.comments.length === 0 ? (
+ (data?.comments.length === 0 ? (
<NoComments />
) : (
- data.comments.map((comment) => (
+ data?.comments.map((comment) => (
<Comment
+ key={comment.id}
preselectedCommentMetadata={preselectedCommentMetadata}
comment={comment}
- key={comment.id}
- queryKey={queryKey}
rootId={rootId}
type={type}
+ deleteComment={deleteComment}
+ updateComment={updateComment}
/>
))
))}
@@ -188,7 +117,7 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =
{(data?.totalPages ?? 0) > 1 && (
<div className="mt-2 flex justify-center">
<Pagination
- currentPage={page}
+ currentPage={commentsMeta.page}
onClick={handleChangePage}
totalPages={data?.totalPages ?? 0}
/>