mirror of
https://github.com/docmost/docmost.git
synced 2026-05-07 06:23:06 +08:00
feat: enhance comments (#1980)
* feat: non-inline comments support * enhance comments * fix types
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
useMutation,
|
useMutation,
|
||||||
useQueryClient,
|
useQueryClient,
|
||||||
|
InfiniteData,
|
||||||
} from "@tanstack/react-query";
|
} from "@tanstack/react-query";
|
||||||
import { resolveComment } from "@/features/comment/services/comment-service";
|
import { resolveComment } from "@/features/comment/services/comment-service";
|
||||||
import {
|
import {
|
||||||
@@ -10,41 +11,54 @@ import {
|
|||||||
import { notifications } from "@mantine/notifications";
|
import { notifications } from "@mantine/notifications";
|
||||||
import { IPagination } from "@/lib/types.ts";
|
import { IPagination } from "@/lib/types.ts";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useQueryEmit } from "@/features/websocket/use-query-emit";
|
|
||||||
import { RQ_KEY } from "@/features/comment/queries/comment-query";
|
import { RQ_KEY } from "@/features/comment/queries/comment-query";
|
||||||
|
|
||||||
|
function updateCommentInCache(
|
||||||
|
cache: InfiniteData<IPagination<IComment>>,
|
||||||
|
commentId: string,
|
||||||
|
updater: (comment: IComment) => IComment,
|
||||||
|
): InfiniteData<IPagination<IComment>> {
|
||||||
|
return {
|
||||||
|
...cache,
|
||||||
|
pages: cache.pages.map((page) => ({
|
||||||
|
...page,
|
||||||
|
items: page.items.map((comment) =>
|
||||||
|
comment.id === commentId ? updater(comment) : comment,
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function useResolveCommentMutation() {
|
export function useResolveCommentMutation() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const emit = useQueryEmit();
|
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (data: IResolveComment) => resolveComment(data),
|
mutationFn: (data: IResolveComment) => resolveComment(data),
|
||||||
onMutate: async (variables) => {
|
onMutate: async (variables) => {
|
||||||
await queryClient.cancelQueries({ queryKey: RQ_KEY(variables.pageId) });
|
await queryClient.cancelQueries({ queryKey: RQ_KEY(variables.pageId) });
|
||||||
const previousComments = queryClient.getQueryData(RQ_KEY(variables.pageId));
|
const previousCache = queryClient.getQueryData(RQ_KEY(variables.pageId));
|
||||||
queryClient.setQueryData(RQ_KEY(variables.pageId), (old: IPagination<IComment>) => {
|
|
||||||
if (!old || !old.items) return old;
|
const cache = previousCache as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
const updatedItems = old.items.map((comment) =>
|
if (cache) {
|
||||||
comment.id === variables.commentId
|
queryClient.setQueryData(
|
||||||
? {
|
RQ_KEY(variables.pageId),
|
||||||
...comment,
|
updateCommentInCache(cache, variables.commentId, (comment) => ({
|
||||||
resolvedAt: variables.resolved ? new Date() : null,
|
...comment,
|
||||||
resolvedById: variables.resolved ? 'optimistic-user' : null,
|
resolvedAt: variables.resolved ? new Date() : null,
|
||||||
resolvedBy: variables.resolved ? { id: 'optimistic-user', name: 'Resolving...', avatarUrl: null } : null
|
resolvedById: variables.resolved ? "optimistic" : null,
|
||||||
}
|
resolvedBy: variables.resolved
|
||||||
: comment,
|
? { id: "optimistic", name: "", avatarUrl: null }
|
||||||
|
: null,
|
||||||
|
})),
|
||||||
);
|
);
|
||||||
return {
|
}
|
||||||
...old,
|
|
||||||
items: updatedItems,
|
return { previousCache };
|
||||||
};
|
|
||||||
});
|
|
||||||
return { previousComments };
|
|
||||||
},
|
},
|
||||||
onError: (err, variables, context) => {
|
onError: (_err, variables, context) => {
|
||||||
if (context?.previousComments) {
|
if (context?.previousCache) {
|
||||||
queryClient.setQueryData(RQ_KEY(variables.pageId), context.previousComments);
|
queryClient.setQueryData(RQ_KEY(variables.pageId), context.previousCache);
|
||||||
}
|
}
|
||||||
notifications.show({
|
notifications.show({
|
||||||
message: t("Failed to resolve comment"),
|
message: t("Failed to resolve comment"),
|
||||||
@@ -52,35 +66,26 @@ export function useResolveCommentMutation() {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
onSuccess: (data: IComment, variables) => {
|
onSuccess: (data: IComment, variables) => {
|
||||||
const pageId = data.pageId;
|
const cache = queryClient.getQueryData(
|
||||||
const currentComments = queryClient.getQueryData(
|
RQ_KEY(data.pageId),
|
||||||
RQ_KEY(pageId),
|
) as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
) as IPagination<IComment>;
|
|
||||||
if (currentComments && currentComments.items) {
|
if (cache) {
|
||||||
const updatedComments = currentComments.items.map((comment) =>
|
queryClient.setQueryData(
|
||||||
comment.id === variables.commentId
|
RQ_KEY(data.pageId),
|
||||||
? { ...comment, resolvedAt: data.resolvedAt, resolvedById: data.resolvedById, resolvedBy: data.resolvedBy }
|
updateCommentInCache(cache, variables.commentId, (comment) => ({
|
||||||
: comment,
|
...comment,
|
||||||
|
resolvedAt: data.resolvedAt,
|
||||||
|
resolvedById: data.resolvedById,
|
||||||
|
resolvedBy: data.resolvedBy,
|
||||||
|
})),
|
||||||
);
|
);
|
||||||
queryClient.setQueryData(RQ_KEY(pageId), {
|
|
||||||
...currentComments,
|
|
||||||
items: updatedComments,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
emit({
|
|
||||||
operation: "resolveComment",
|
notifications.show({
|
||||||
pageId: pageId,
|
message: variables.resolved
|
||||||
commentId: variables.commentId,
|
? t("Comment resolved successfully")
|
||||||
resolved: variables.resolved,
|
: t("Comment re-opened successfully"),
|
||||||
resolvedAt: data.resolvedAt,
|
|
||||||
resolvedById: data.resolvedById,
|
|
||||||
resolvedBy: data.resolvedBy,
|
|
||||||
});
|
|
||||||
queryClient.invalidateQueries({ queryKey: RQ_KEY(pageId) });
|
|
||||||
notifications.show({
|
|
||||||
message: variables.resolved
|
|
||||||
? t("Comment resolved successfully")
|
|
||||||
: t("Comment re-opened successfully")
|
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-
|
|||||||
import { useEditor } from "@tiptap/react";
|
import { useEditor } from "@tiptap/react";
|
||||||
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useQueryEmit } from "@/features/websocket/use-query-emit";
|
|
||||||
|
|
||||||
interface CommentDialogProps {
|
interface CommentDialogProps {
|
||||||
editor: ReturnType<typeof useEditor>;
|
editor: ReturnType<typeof useEditor>;
|
||||||
@@ -37,8 +36,6 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
|
|||||||
const createCommentMutation = useCreateCommentMutation();
|
const createCommentMutation = useCreateCommentMutation();
|
||||||
const { isPending } = createCommentMutation;
|
const { isPending } = createCommentMutation;
|
||||||
|
|
||||||
const emit = useQueryEmit();
|
|
||||||
|
|
||||||
const handleDialogClose = () => {
|
const handleDialogClose = () => {
|
||||||
setShowCommentPopup(false);
|
setShowCommentPopup(false);
|
||||||
editor.chain().focus().unsetCommentDecoration().run();
|
editor.chain().focus().unsetCommentDecoration().run();
|
||||||
@@ -82,10 +79,6 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
|
|||||||
);
|
);
|
||||||
}, 400);
|
}, 400);
|
||||||
|
|
||||||
emit({
|
|
||||||
operation: "invalidateComment",
|
|
||||||
pageId: pageId,
|
|
||||||
});
|
|
||||||
} finally {
|
} finally {
|
||||||
setShowCommentPopup(false);
|
setShowCommentPopup(false);
|
||||||
setDraftCommentId("");
|
setDraftCommentId("");
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Group, Text, Box, Badge } from "@mantine/core";
|
|||||||
import React, { useEffect, useRef, useState } from "react";
|
import React, { useEffect, useRef, useState } from "react";
|
||||||
import classes from "./comment.module.css";
|
import classes from "./comment.module.css";
|
||||||
import { useAtom, useAtomValue } from "jotai";
|
import { useAtom, useAtomValue } from "jotai";
|
||||||
import { timeAgo } from "@/lib/time";
|
import { useTimeAgo } from "@/hooks/use-time-ago";
|
||||||
import CommentEditor from "@/features/comment/components/comment-editor";
|
import CommentEditor from "@/features/comment/components/comment-editor";
|
||||||
import { pageEditorAtom } from "@/features/editor/atoms/editor-atoms";
|
import { pageEditorAtom } from "@/features/editor/atoms/editor-atoms";
|
||||||
import CommentActions from "@/features/comment/components/comment-actions";
|
import CommentActions from "@/features/comment/components/comment-actions";
|
||||||
@@ -18,7 +18,6 @@ import { useResolveCommentMutation } from "@/ee/comment/queries/comment-query";
|
|||||||
import { IComment } from "@/features/comment/types/comment.types";
|
import { IComment } from "@/features/comment/types/comment.types";
|
||||||
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
|
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||||
import { useQueryEmit } from "@/features/websocket/use-query-emit";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
interface CommentListItemProps {
|
interface CommentListItemProps {
|
||||||
@@ -45,8 +44,8 @@ function CommentListItem({
|
|||||||
const deleteCommentMutation = useDeleteCommentMutation(comment.pageId);
|
const deleteCommentMutation = useDeleteCommentMutation(comment.pageId);
|
||||||
const resolveCommentMutation = useResolveCommentMutation();
|
const resolveCommentMutation = useResolveCommentMutation();
|
||||||
const [currentUser] = useAtom(currentUserAtom);
|
const [currentUser] = useAtom(currentUserAtom);
|
||||||
const emit = useQueryEmit();
|
|
||||||
const isCloudEE = useIsCloudEE();
|
const isCloudEE = useIsCloudEE();
|
||||||
|
const createdAtAgo = useTimeAgo(comment.createdAt);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setContent(comment.content);
|
setContent(comment.content);
|
||||||
@@ -65,11 +64,6 @@ function CommentListItem({
|
|||||||
editContentRef.current = null;
|
editContentRef.current = null;
|
||||||
}
|
}
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
|
|
||||||
emit({
|
|
||||||
operation: "invalidateComment",
|
|
||||||
pageId: pageId,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to update comment:", error);
|
console.error("Failed to update comment:", error);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -81,11 +75,6 @@ function CommentListItem({
|
|||||||
try {
|
try {
|
||||||
await deleteCommentMutation.mutateAsync(comment.id);
|
await deleteCommentMutation.mutateAsync(comment.id);
|
||||||
editor?.commands.unsetComment(comment.id);
|
editor?.commands.unsetComment(comment.id);
|
||||||
|
|
||||||
emit({
|
|
||||||
operation: "invalidateComment",
|
|
||||||
pageId: pageId,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to delete comment:", error);
|
console.error("Failed to delete comment:", error);
|
||||||
}
|
}
|
||||||
@@ -106,11 +95,6 @@ function CommentListItem({
|
|||||||
if (editor) {
|
if (editor) {
|
||||||
editor.commands.setCommentResolved(comment.id, !isResolved);
|
editor.commands.setCommentResolved(comment.id, !isResolved);
|
||||||
}
|
}
|
||||||
|
|
||||||
emit({
|
|
||||||
operation: "invalidateComment",
|
|
||||||
pageId: pageId,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to toggle resolved state:", error);
|
console.error("Failed to toggle resolved state:", error);
|
||||||
}
|
}
|
||||||
@@ -177,7 +161,7 @@ function CommentListItem({
|
|||||||
|
|
||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
<Text size="xs" fw={500} c="dimmed">
|
<Text size="xs" fw={500} c="dimmed">
|
||||||
{timeAgo(comment.createdAt)}
|
{createdAtAgo}
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
|||||||
import { IPagination } from "@/lib/types.ts";
|
import { IPagination } from "@/lib/types.ts";
|
||||||
import { extractPageSlugId } from "@/lib";
|
import { extractPageSlugId } from "@/lib";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useQueryEmit } from "@/features/websocket/use-query-emit";
|
|
||||||
import { useIsCloudEE } from "@/hooks/use-is-cloud-ee";
|
import { useIsCloudEE } from "@/hooks/use-is-cloud-ee";
|
||||||
import { useGetSpaceBySlugQuery } from "@/features/space/queries/space-query.ts";
|
import { useGetSpaceBySlugQuery } from "@/features/space/queries/space-query.ts";
|
||||||
import { IconArrowUp, IconMessageOff } from "@tabler/icons-react";
|
import { IconArrowUp, IconMessageOff } from "@tabler/icons-react";
|
||||||
@@ -27,10 +26,9 @@ function CommentListWithTabs() {
|
|||||||
data: comments,
|
data: comments,
|
||||||
isLoading: isCommentsLoading,
|
isLoading: isCommentsLoading,
|
||||||
isError,
|
isError,
|
||||||
} = useCommentsQuery({ pageId: page?.id, limit: 100 });
|
} = useCommentsQuery({ pageId: page?.id });
|
||||||
const createCommentMutation = useCreateCommentMutation();
|
const createCommentMutation = useCreateCommentMutation();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const emit = useQueryEmit();
|
|
||||||
const isCloudEE = useIsCloudEE();
|
const isCloudEE = useIsCloudEE();
|
||||||
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
||||||
|
|
||||||
@@ -67,11 +65,6 @@ function CommentListWithTabs() {
|
|||||||
content: JSON.stringify(content),
|
content: JSON.stringify(content),
|
||||||
});
|
});
|
||||||
|
|
||||||
emit({
|
|
||||||
operation: "invalidateComment",
|
|
||||||
pageId: page?.id,
|
|
||||||
});
|
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const selector = `div[data-comment-id="${createdComment.id}"]`;
|
const selector = `div[data-comment-id="${createdComment.id}"]`;
|
||||||
const commentElement = document.querySelector(selector);
|
const commentElement = document.querySelector(selector);
|
||||||
@@ -97,11 +90,6 @@ function CommentListWithTabs() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
await createCommentMutation.mutateAsync(commentData);
|
await createCommentMutation.mutateAsync(commentData);
|
||||||
|
|
||||||
emit({
|
|
||||||
operation: "invalidateComment",
|
|
||||||
pageId: page?.id,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to post comment:", error);
|
console.error("Failed to post comment:", error);
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import {
|
import {
|
||||||
|
useInfiniteQuery,
|
||||||
useMutation,
|
useMutation,
|
||||||
useQuery,
|
|
||||||
useQueryClient,
|
useQueryClient,
|
||||||
UseQueryResult,
|
InfiniteData,
|
||||||
} from "@tanstack/react-query";
|
} from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
createComment,
|
createComment,
|
||||||
@@ -17,17 +17,40 @@ import {
|
|||||||
import { notifications } from "@mantine/notifications";
|
import { notifications } from "@mantine/notifications";
|
||||||
import { IPagination } from "@/lib/types.ts";
|
import { IPagination } from "@/lib/types.ts";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useEffect, useMemo } from "react";
|
||||||
|
|
||||||
export const RQ_KEY = (pageId: string) => ["comments", pageId];
|
export const RQ_KEY = (pageId: string) => ["comments", pageId];
|
||||||
|
|
||||||
export function useCommentsQuery(
|
export function useCommentsQuery(params: ICommentParams) {
|
||||||
params: ICommentParams,
|
const query = useInfiniteQuery({
|
||||||
): UseQueryResult<IPagination<IComment>, Error> {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: RQ_KEY(params.pageId),
|
queryKey: RQ_KEY(params.pageId),
|
||||||
queryFn: () => getPageComments(params),
|
queryFn: ({ pageParam }) =>
|
||||||
|
getPageComments({ pageId: params.pageId, cursor: pageParam, limit: 100 }),
|
||||||
|
initialPageParam: undefined as string | undefined,
|
||||||
|
getNextPageParam: (lastPage) =>
|
||||||
|
lastPage.meta.hasNextPage ? lastPage.meta.nextCursor : undefined,
|
||||||
enabled: !!params.pageId,
|
enabled: !!params.pageId,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (query.hasNextPage && !query.isFetchingNextPage) {
|
||||||
|
query.fetchNextPage();
|
||||||
|
}
|
||||||
|
}, [query.hasNextPage, query.isFetchingNextPage, query.fetchNextPage]);
|
||||||
|
|
||||||
|
const data = useMemo<IPagination<IComment> | undefined>(() => {
|
||||||
|
if (!query.data) return undefined;
|
||||||
|
return {
|
||||||
|
items: query.data.pages.flatMap((p) => p.items),
|
||||||
|
meta: query.data.pages[query.data.pages.length - 1].meta,
|
||||||
|
};
|
||||||
|
}, [query.data]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
isLoading: query.isLoading || query.hasNextPage,
|
||||||
|
isError: query.isError,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCreateCommentMutation() {
|
export function useCreateCommentMutation() {
|
||||||
@@ -36,18 +59,26 @@ export function useCreateCommentMutation() {
|
|||||||
|
|
||||||
return useMutation<IComment, Error, Partial<IComment>>({
|
return useMutation<IComment, Error, Partial<IComment>>({
|
||||||
mutationFn: (data) => createComment(data),
|
mutationFn: (data) => createComment(data),
|
||||||
onSuccess: (data) => {
|
onSuccess: (newComment) => {
|
||||||
//const newComment = data;
|
const cache = queryClient.getQueryData(
|
||||||
// let comments = queryClient.getQueryData(RQ_KEY(data.pageId));
|
RQ_KEY(newComment.pageId),
|
||||||
// if (comments) {
|
) as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
//comments = prevComments => [...prevComments, newComment];
|
|
||||||
//queryClient.setQueryData(RQ_KEY(data.pageId), comments);
|
if (cache && cache.pages.length > 0) {
|
||||||
//}
|
const lastIdx = cache.pages.length - 1;
|
||||||
|
queryClient.setQueryData(RQ_KEY(newComment.pageId), {
|
||||||
|
...cache,
|
||||||
|
pages: cache.pages.map((page, i) =>
|
||||||
|
i === lastIdx
|
||||||
|
? { ...page, items: [...page.items, newComment] }
|
||||||
|
: page,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
queryClient.refetchQueries({ queryKey: RQ_KEY(data.pageId) });
|
|
||||||
notifications.show({ message: t("Comment created successfully") });
|
notifications.show({ message: t("Comment created successfully") });
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: () => {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
message: t("Error creating comment"),
|
message: t("Error creating comment"),
|
||||||
color: "red",
|
color: "red",
|
||||||
@@ -57,14 +88,31 @@ export function useCreateCommentMutation() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useUpdateCommentMutation() {
|
export function useUpdateCommentMutation() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation<IComment, Error, Partial<IComment>>({
|
return useMutation<IComment, Error, Partial<IComment>>({
|
||||||
mutationFn: (data) => updateComment(data),
|
mutationFn: (data) => updateComment(data),
|
||||||
onSuccess: (data) => {
|
onSuccess: (updatedComment) => {
|
||||||
|
const cache = queryClient.getQueryData(
|
||||||
|
RQ_KEY(updatedComment.pageId),
|
||||||
|
) as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
|
|
||||||
|
if (cache) {
|
||||||
|
queryClient.setQueryData(RQ_KEY(updatedComment.pageId), {
|
||||||
|
...cache,
|
||||||
|
pages: cache.pages.map((page) => ({
|
||||||
|
...page,
|
||||||
|
items: page.items.map((comment) =>
|
||||||
|
comment.id === updatedComment.id ? updatedComment : comment,
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
notifications.show({ message: t("Comment updated successfully") });
|
notifications.show({ message: t("Comment updated successfully") });
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: () => {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
message: t("Failed to update comment"),
|
message: t("Failed to update comment"),
|
||||||
color: "red",
|
color: "red",
|
||||||
@@ -79,25 +127,24 @@ export function useDeleteCommentMutation(pageId?: string) {
|
|||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (commentId: string) => deleteComment(commentId),
|
mutationFn: (commentId: string) => deleteComment(commentId),
|
||||||
onSuccess: (data, variables) => {
|
onSuccess: (_data, commentId) => {
|
||||||
const comments = queryClient.getQueryData(
|
const cache = queryClient.getQueryData(
|
||||||
RQ_KEY(pageId),
|
RQ_KEY(pageId),
|
||||||
) as IPagination<IComment>;
|
) as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
|
|
||||||
if (comments && comments.items) {
|
if (cache) {
|
||||||
const commentId = variables;
|
|
||||||
const newComments = comments.items.filter(
|
|
||||||
(comment) => comment.id !== commentId,
|
|
||||||
);
|
|
||||||
queryClient.setQueryData(RQ_KEY(pageId), {
|
queryClient.setQueryData(RQ_KEY(pageId), {
|
||||||
...comments,
|
...cache,
|
||||||
items: newComments,
|
pages: cache.pages.map((page) => ({
|
||||||
|
...page,
|
||||||
|
items: page.items.filter((comment) => comment.id !== commentId),
|
||||||
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
notifications.show({ message: t("Comment deleted successfully") });
|
notifications.show({ message: t("Comment deleted successfully") });
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: () => {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
message: t("Failed to delete comment"),
|
message: t("Failed to delete comment"),
|
||||||
color: "red",
|
color: "red",
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
import { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
||||||
import { IPage } from "@/features/page/types/page.types";
|
import { IPage } from "@/features/page/types/page.types";
|
||||||
|
import { IComment } from "@/features/comment/types/comment.types";
|
||||||
|
|
||||||
export type InvalidateEvent = {
|
export type InvalidateEvent = {
|
||||||
operation: "invalidate";
|
operation: "invalidate";
|
||||||
@@ -8,9 +9,28 @@ export type InvalidateEvent = {
|
|||||||
id?: string;
|
id?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type InvalidateCommentsEvent = {
|
export type CommentCreatedEvent = {
|
||||||
operation: "invalidateComment";
|
operation: "commentCreated";
|
||||||
pageId: string;
|
pageId: string;
|
||||||
|
comment: IComment;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CommentUpdatedEvent = {
|
||||||
|
operation: "commentUpdated";
|
||||||
|
pageId: string;
|
||||||
|
comment: IComment;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CommentDeletedEvent = {
|
||||||
|
operation: "commentDeleted";
|
||||||
|
pageId: string;
|
||||||
|
commentId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CommentResolvedEvent = {
|
||||||
|
operation: "commentResolved";
|
||||||
|
pageId: string;
|
||||||
|
comment: IComment;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type UpdateEvent = {
|
export type UpdateEvent = {
|
||||||
@@ -65,27 +85,15 @@ export type RefetchRootTreeNodeEvent = {
|
|||||||
spaceId: string;
|
spaceId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ResolveCommentEvent = {
|
|
||||||
operation: "resolveComment";
|
|
||||||
pageId: string;
|
|
||||||
commentId: string;
|
|
||||||
resolved: boolean;
|
|
||||||
resolvedAt?: Date;
|
|
||||||
resolvedById?: string;
|
|
||||||
resolvedBy?: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
avatarUrl?: string | null;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export type WebSocketEvent =
|
export type WebSocketEvent =
|
||||||
| InvalidateEvent
|
| InvalidateEvent
|
||||||
| InvalidateCommentsEvent
|
| CommentCreatedEvent
|
||||||
|
| CommentUpdatedEvent
|
||||||
|
| CommentDeletedEvent
|
||||||
|
| CommentResolvedEvent
|
||||||
| UpdateEvent
|
| UpdateEvent
|
||||||
| DeleteEvent
|
| DeleteEvent
|
||||||
| AddTreeNodeEvent
|
| AddTreeNodeEvent
|
||||||
| MoveTreeNodeEvent
|
| MoveTreeNodeEvent
|
||||||
| DeleteTreeNodeEvent
|
| DeleteTreeNodeEvent
|
||||||
| RefetchRootTreeNodeEvent
|
| RefetchRootTreeNodeEvent;
|
||||||
| ResolveCommentEvent;
|
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
invalidateOnUpdatePage,
|
invalidateOnUpdatePage,
|
||||||
} from "../page/queries/page-query";
|
} from "../page/queries/page-query";
|
||||||
import { RQ_KEY } from "../comment/queries/comment-query";
|
import { RQ_KEY } from "../comment/queries/comment-query";
|
||||||
import { queryClient } from "@/main.tsx";
|
|
||||||
import { IComment } from "@/features/comment/types/comment.types";
|
import { IComment } from "@/features/comment/types/comment.types";
|
||||||
|
|
||||||
export const useQuerySubscription = () => {
|
export const useQuerySubscription = () => {
|
||||||
@@ -32,11 +31,66 @@ export const useQuerySubscription = () => {
|
|||||||
queryKey: [...data.entity, data.id].filter(Boolean),
|
queryKey: [...data.entity, data.id].filter(Boolean),
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case "invalidateComment":
|
case "commentCreated": {
|
||||||
queryClient.invalidateQueries({
|
const createCache = queryClient.getQueryData(
|
||||||
queryKey: RQ_KEY(data.pageId),
|
RQ_KEY(data.pageId),
|
||||||
});
|
) as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
|
|
||||||
|
if (createCache && createCache.pages.length > 0) {
|
||||||
|
const alreadyExists = createCache.pages.some((page) =>
|
||||||
|
page.items.some((c) => c.id === data.comment.id),
|
||||||
|
);
|
||||||
|
if (alreadyExists) break;
|
||||||
|
|
||||||
|
const lastIdx = createCache.pages.length - 1;
|
||||||
|
queryClient.setQueryData(RQ_KEY(data.pageId), {
|
||||||
|
...createCache,
|
||||||
|
pages: createCache.pages.map((page, i) =>
|
||||||
|
i === lastIdx
|
||||||
|
? { ...page, items: [...page.items, data.comment] }
|
||||||
|
: page,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
case "commentUpdated":
|
||||||
|
case "commentResolved": {
|
||||||
|
const updateCache = queryClient.getQueryData(
|
||||||
|
RQ_KEY(data.pageId),
|
||||||
|
) as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
|
|
||||||
|
if (updateCache) {
|
||||||
|
queryClient.setQueryData(RQ_KEY(data.pageId), {
|
||||||
|
...updateCache,
|
||||||
|
pages: updateCache.pages.map((page) => ({
|
||||||
|
...page,
|
||||||
|
items: page.items.map((comment) =>
|
||||||
|
comment.id === data.comment.id ? data.comment : comment,
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "commentDeleted": {
|
||||||
|
const deleteCache = queryClient.getQueryData(
|
||||||
|
RQ_KEY(data.pageId),
|
||||||
|
) as InfiniteData<IPagination<IComment>> | undefined;
|
||||||
|
|
||||||
|
if (deleteCache) {
|
||||||
|
queryClient.setQueryData(RQ_KEY(data.pageId), {
|
||||||
|
...deleteCache,
|
||||||
|
pages: deleteCache.pages.map((page) => ({
|
||||||
|
...page,
|
||||||
|
items: page.items.filter(
|
||||||
|
(comment) => comment.id !== data.commentId,
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "addTreeNode":
|
case "addTreeNode":
|
||||||
invalidateOnCreatePage(data.payload.data);
|
invalidateOnCreatePage(data.payload.data);
|
||||||
break;
|
break;
|
||||||
@@ -103,30 +157,6 @@ export const useQuerySubscription = () => {
|
|||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "resolveComment": {
|
|
||||||
const currentComments = queryClient.getQueryData(
|
|
||||||
RQ_KEY(data.pageId),
|
|
||||||
) as IPagination<IComment>;
|
|
||||||
|
|
||||||
if (currentComments && currentComments.items) {
|
|
||||||
const updatedComments = currentComments.items.map((comment) =>
|
|
||||||
comment.id === data.commentId
|
|
||||||
? {
|
|
||||||
...comment,
|
|
||||||
resolvedAt: data.resolvedAt,
|
|
||||||
resolvedById: data.resolvedById,
|
|
||||||
resolvedBy: data.resolvedBy
|
|
||||||
}
|
|
||||||
: comment,
|
|
||||||
);
|
|
||||||
|
|
||||||
queryClient.setQueryData(RQ_KEY(data.pageId), {
|
|
||||||
...currentComments,
|
|
||||||
items: updatedComments,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, [queryClient, socket]);
|
}, [queryClient, socket]);
|
||||||
|
|||||||
@@ -1,16 +1,32 @@
|
|||||||
import { timeAgo } from "@/lib/time.ts";
|
import { timeAgo } from "@/lib/time.ts";
|
||||||
import { useEffect, useState } from "react";
|
import { useMemo, useSyncExternalStore } from "react";
|
||||||
|
|
||||||
|
let tick = 0;
|
||||||
|
let intervalId: ReturnType<typeof setInterval> | null = null;
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
function subscribe(callback: () => void) {
|
||||||
|
listeners.add(callback);
|
||||||
|
if (listeners.size === 1) {
|
||||||
|
intervalId = setInterval(() => {
|
||||||
|
tick++;
|
||||||
|
listeners.forEach((cb) => cb());
|
||||||
|
}, 60_000);
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
listeners.delete(callback);
|
||||||
|
if (listeners.size === 0 && intervalId) {
|
||||||
|
clearInterval(intervalId);
|
||||||
|
intervalId = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSnapshot() {
|
||||||
|
return tick;
|
||||||
|
}
|
||||||
|
|
||||||
export function useTimeAgo(date: Date | string) {
|
export function useTimeAgo(date: Date | string) {
|
||||||
const [value, setValue] = useState(() => timeAgo(new Date(date)));
|
const currentTick = useSyncExternalStore(subscribe, getSnapshot);
|
||||||
|
return useMemo(() => timeAgo(new Date(date)), [date, currentTick]);
|
||||||
useEffect(() => {
|
|
||||||
const interval = setInterval(() => {
|
|
||||||
setValue(timeAgo(new Date(date)));
|
|
||||||
}, 5 * 1000);
|
|
||||||
|
|
||||||
return () => clearInterval(interval);
|
|
||||||
}, [date]);
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {
|
|||||||
AUDIT_SERVICE,
|
AUDIT_SERVICE,
|
||||||
IAuditService,
|
IAuditService,
|
||||||
} from '../../integrations/audit/audit.service';
|
} from '../../integrations/audit/audit.service';
|
||||||
|
import { WsService } from '../../ws/ws.service';
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Controller('comments')
|
@Controller('comments')
|
||||||
@@ -41,6 +42,7 @@ export class CommentController {
|
|||||||
private readonly pageRepo: PageRepo,
|
private readonly pageRepo: PageRepo,
|
||||||
private readonly spaceAbility: SpaceAbilityFactory,
|
private readonly spaceAbility: SpaceAbilityFactory,
|
||||||
private readonly pageAccessService: PageAccessService,
|
private readonly pageAccessService: PageAccessService,
|
||||||
|
private readonly wsService: WsService,
|
||||||
@Inject(AUDIT_SERVICE) private readonly auditService: IAuditService,
|
@Inject(AUDIT_SERVICE) private readonly auditService: IAuditService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@@ -119,7 +121,10 @@ export class CommentController {
|
|||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@Post('update')
|
@Post('update')
|
||||||
async update(@Body() dto: UpdateCommentDto, @AuthUser() user: User) {
|
async update(@Body() dto: UpdateCommentDto, @AuthUser() user: User) {
|
||||||
const comment = await this.commentRepo.findById(dto.commentId);
|
const comment = await this.commentRepo.findById(dto.commentId, {
|
||||||
|
includeCreator: true,
|
||||||
|
includeResolvedBy: true,
|
||||||
|
});
|
||||||
if (!comment) {
|
if (!comment) {
|
||||||
throw new NotFoundException('Comment not found');
|
throw new NotFoundException('Comment not found');
|
||||||
}
|
}
|
||||||
@@ -170,6 +175,12 @@ export class CommentController {
|
|||||||
await this.commentRepo.deleteComment(comment.id);
|
await this.commentRepo.deleteComment(comment.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.wsService.emitCommentEvent(comment.spaceId, comment.pageId, {
|
||||||
|
operation: 'commentDeleted',
|
||||||
|
pageId: comment.pageId,
|
||||||
|
commentId: comment.id,
|
||||||
|
});
|
||||||
|
|
||||||
this.auditService.log({
|
this.auditService.log({
|
||||||
event: AuditEvent.COMMENT_DELETED,
|
event: AuditEvent.COMMENT_DELETED,
|
||||||
resourceType: AuditResource.COMMENT,
|
resourceType: AuditResource.COMMENT,
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { CursorPaginationResult } from '@docmost/db/pagination/cursor-pagination
|
|||||||
import { QueueJob, QueueName } from '../../integrations/queue/constants';
|
import { QueueJob, QueueName } from '../../integrations/queue/constants';
|
||||||
import { extractUserMentionIdsFromJson } from '../../common/helpers/prosemirror/utils';
|
import { extractUserMentionIdsFromJson } from '../../common/helpers/prosemirror/utils';
|
||||||
import { ICommentNotificationJob } from '../../integrations/queue/constants/queue.interface';
|
import { ICommentNotificationJob } from '../../integrations/queue/constants/queue.interface';
|
||||||
|
import { WsService } from '../../ws/ws.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CommentService {
|
export class CommentService {
|
||||||
@@ -25,6 +26,7 @@ export class CommentService {
|
|||||||
constructor(
|
constructor(
|
||||||
private commentRepo: CommentRepo,
|
private commentRepo: CommentRepo,
|
||||||
private pageRepo: PageRepo,
|
private pageRepo: PageRepo,
|
||||||
|
private wsService: WsService,
|
||||||
@InjectQueue(QueueName.GENERAL_QUEUE)
|
@InjectQueue(QueueName.GENERAL_QUEUE)
|
||||||
private generalQueue: Queue,
|
private generalQueue: Queue,
|
||||||
@InjectQueue(QueueName.NOTIFICATION_QUEUE)
|
@InjectQueue(QueueName.NOTIFICATION_QUEUE)
|
||||||
@@ -63,7 +65,7 @@ export class CommentService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const comment = await this.commentRepo.insertComment({
|
const inserted = await this.commentRepo.insertComment({
|
||||||
pageId: page.id,
|
pageId: page.id,
|
||||||
content: commentContent,
|
content: commentContent,
|
||||||
selection: createCommentDto?.selection?.substring(0, 250) ?? null,
|
selection: createCommentDto?.selection?.substring(0, 250) ?? null,
|
||||||
@@ -74,6 +76,11 @@ export class CommentService {
|
|||||||
spaceId: page.spaceId,
|
spaceId: page.spaceId,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const comment = await this.commentRepo.findById(inserted.id, {
|
||||||
|
includeCreator: true,
|
||||||
|
includeResolvedBy: true,
|
||||||
|
});
|
||||||
|
|
||||||
this.generalQueue
|
this.generalQueue
|
||||||
.add(QueueJob.ADD_PAGE_WATCHERS, {
|
.add(QueueJob.ADD_PAGE_WATCHERS, {
|
||||||
userIds: [userId],
|
userIds: [userId],
|
||||||
@@ -99,6 +106,12 @@ export class CommentService {
|
|||||||
createCommentDto.parentCommentId,
|
createCommentDto.parentCommentId,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.wsService.emitCommentEvent(page.spaceId, page.id, {
|
||||||
|
operation: 'commentCreated',
|
||||||
|
pageId: page.id,
|
||||||
|
comment,
|
||||||
|
});
|
||||||
|
|
||||||
return comment;
|
return comment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,6 +167,12 @@ export class CommentService {
|
|||||||
comment.editedAt = editedAt;
|
comment.editedAt = editedAt;
|
||||||
comment.updatedAt = editedAt;
|
comment.updatedAt = editedAt;
|
||||||
|
|
||||||
|
this.wsService.emitCommentEvent(comment.spaceId, comment.pageId, {
|
||||||
|
operation: 'commentUpdated',
|
||||||
|
pageId: comment.pageId,
|
||||||
|
comment,
|
||||||
|
});
|
||||||
|
|
||||||
return comment;
|
return comment;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
Submodule apps/server/src/ee updated: 7ef5900616...0b3a6f4af0
@@ -45,7 +45,7 @@ export class WsService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.broadcastToAuthorizedUsers(client, room, pageId, data);
|
await this.broadcastToAuthorizedUsers(room, client.data.userId, pageId, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
async invalidateSpaceRestrictionCache(spaceId: string): Promise<void> {
|
async invalidateSpaceRestrictionCache(spaceId: string): Promise<void> {
|
||||||
@@ -54,6 +54,29 @@ export class WsService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async emitCommentEvent(
|
||||||
|
spaceId: string,
|
||||||
|
pageId: string,
|
||||||
|
data: any,
|
||||||
|
): Promise<void> {
|
||||||
|
const room = getSpaceRoomName(spaceId);
|
||||||
|
|
||||||
|
const hasRestrictions = await this.spaceHasRestrictions(spaceId);
|
||||||
|
if (!hasRestrictions) {
|
||||||
|
this.server.to(room).emit('message', data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isRestricted =
|
||||||
|
await this.pagePermissionRepo.hasRestrictedAncestor(pageId);
|
||||||
|
if (!isRestricted) {
|
||||||
|
this.server.to(room).emit('message', data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.broadcastToAuthorizedUsers(room, null, pageId, data);
|
||||||
|
}
|
||||||
|
|
||||||
async emitToUsers(userIds: string[], data: any): Promise<void> {
|
async emitToUsers(userIds: string[], data: any): Promise<void> {
|
||||||
if (userIds.length === 0) return;
|
if (userIds.length === 0) return;
|
||||||
const rooms = userIds.map((id) => getUserRoomName(id));
|
const rooms = userIds.map((id) => getUserRoomName(id));
|
||||||
@@ -82,14 +105,16 @@ export class WsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async broadcastToAuthorizedUsers(
|
private async broadcastToAuthorizedUsers(
|
||||||
sender: Socket,
|
|
||||||
room: string,
|
room: string,
|
||||||
|
excludeUserId: string | null,
|
||||||
pageId: string,
|
pageId: string,
|
||||||
data: any,
|
data: any,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const sockets = await this.server.in(room).fetchSockets();
|
const sockets = await this.server.in(room).fetchSockets();
|
||||||
|
|
||||||
const otherSockets = sockets.filter((s) => s.id !== sender.id);
|
const otherSockets = excludeUserId
|
||||||
|
? sockets.filter((s) => s.data.userId !== excludeUserId)
|
||||||
|
: sockets;
|
||||||
if (otherSockets.length === 0) return;
|
if (otherSockets.length === 0) return;
|
||||||
|
|
||||||
const userSocketMap = new Map<string, typeof otherSockets>();
|
const userSocketMap = new Map<string, typeof otherSockets>();
|
||||||
|
|||||||
Reference in New Issue
Block a user