PageComment.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import type { FC } from 'react';
  2. import React, {
  3. useState, useMemo, memo, useCallback,
  4. } from 'react';
  5. import {
  6. isPopulated, type IRevisionHasId, getIdStringForRef,
  7. } from '@growi/core';
  8. import { UserPicture } from '@growi/ui/dist/components';
  9. import { useTranslation } from 'next-i18next';
  10. import { apiPost } from '~/client/util/apiv1-client';
  11. import { toastError } from '~/client/util/toastr';
  12. import type { RendererOptions } from '~/interfaces/renderer-options';
  13. import type { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  14. import { useSWRMUTxPageInfo } from '~/stores/page';
  15. import { useCommentForCurrentPageOptions } from '~/stores/renderer';
  16. import type { ICommentHasId, ICommentHasIdList } from '../../interfaces/comment';
  17. import { useSWRxPageComment } from '../../stores/comment';
  18. import { NotAvailableForGuest } from './NotAvailableForGuest';
  19. import { NotAvailableForReadOnlyUser } from './NotAvailableForReadOnlyUser';
  20. import { Comment } from './PageComment/Comment';
  21. import { CommentEditor } from './PageComment/CommentEditor';
  22. import { DeleteCommentModal } from './PageComment/DeleteCommentModal';
  23. import { ReplyComments } from './PageComment/ReplyComments';
  24. import styles from './PageComment.module.scss';
  25. type PageCommentProps = {
  26. rendererOptions?: RendererOptions,
  27. pageId: string,
  28. pagePath: string,
  29. revision: ObjectIdLike | IRevisionHasId,
  30. currentUser: any,
  31. isReadOnly: boolean,
  32. }
  33. export const PageComment: FC<PageCommentProps> = memo((props: PageCommentProps): JSX.Element => {
  34. const {
  35. rendererOptions: rendererOptionsByProps,
  36. pageId, pagePath, revision, currentUser, isReadOnly,
  37. } = props;
  38. const { data: comments, mutate } = useSWRxPageComment(pageId);
  39. const { data: rendererOptionsForCurrentPage } = useCommentForCurrentPageOptions();
  40. const [commentToBeDeleted, setCommentToBeDeleted] = useState<ICommentHasId | null>(null);
  41. const [isDeleteConfirmModalShown, setIsDeleteConfirmModalShown] = useState<boolean>(false);
  42. const [showEditorIds, setShowEditorIds] = useState<Set<string>>(new Set());
  43. const [errorMessageOnDelete, setErrorMessageOnDelete] = useState<string>('');
  44. const { trigger: mutatePageInfo } = useSWRMUTxPageInfo(pageId);
  45. const { t } = useTranslation('');
  46. const commentsFromOldest = useMemo(() => (comments != null ? [...comments].reverse() : null), [comments]);
  47. const commentsExceptReply: ICommentHasIdList | undefined = useMemo(
  48. () => commentsFromOldest?.filter(comment => comment.replyTo == null), [commentsFromOldest],
  49. );
  50. const allReplies = {};
  51. if (commentsFromOldest != null) {
  52. commentsFromOldest.forEach((comment) => {
  53. if (comment.replyTo != null) {
  54. allReplies[comment.replyTo] = allReplies[comment.replyTo] == null ? [comment] : [...allReplies[comment.replyTo], comment];
  55. }
  56. });
  57. }
  58. const onClickDeleteButton = useCallback((comment: ICommentHasId) => {
  59. setCommentToBeDeleted(comment);
  60. setIsDeleteConfirmModalShown(true);
  61. }, []);
  62. const onCancelDeleteComment = useCallback(() => {
  63. setCommentToBeDeleted(null);
  64. setIsDeleteConfirmModalShown(false);
  65. }, []);
  66. const onDeleteCommentAfterOperation = useCallback(() => {
  67. onCancelDeleteComment();
  68. mutate();
  69. mutatePageInfo();
  70. }, [mutate, onCancelDeleteComment, mutatePageInfo]);
  71. const onDeleteComment = useCallback(async() => {
  72. if (commentToBeDeleted == null) return;
  73. try {
  74. await apiPost('/comments.remove', { comment_id: commentToBeDeleted._id });
  75. onDeleteCommentAfterOperation();
  76. }
  77. catch (error: unknown) {
  78. setErrorMessageOnDelete(error as string);
  79. toastError(`error: ${error}`);
  80. }
  81. }, [commentToBeDeleted, onDeleteCommentAfterOperation]);
  82. const removeShowEditorId = useCallback((commentId: string) => {
  83. setShowEditorIds((previousState) => {
  84. return new Set([...previousState].filter(id => id !== commentId));
  85. });
  86. }, []);
  87. const onReplyButtonClickHandler = useCallback((commentId: string) => {
  88. setShowEditorIds(previousState => new Set([...previousState, commentId]));
  89. }, []);
  90. const onCommentButtonClickHandler = useCallback((commentId: string) => {
  91. removeShowEditorId(commentId);
  92. mutate();
  93. mutatePageInfo();
  94. }, [removeShowEditorId, mutate, mutatePageInfo]);
  95. if (comments?.length === 0) {
  96. return <></>;
  97. }
  98. const rendererOptions = rendererOptionsByProps ?? rendererOptionsForCurrentPage;
  99. if (commentsFromOldest == null || commentsExceptReply == null || rendererOptions == null) {
  100. return <></>;
  101. }
  102. const revisionId = getIdStringForRef(revision);
  103. const revisionCreatedAt = (isPopulated(revision)) ? revision.createdAt : undefined;
  104. const commentElement = (comment: ICommentHasId) => (
  105. <Comment
  106. rendererOptions={rendererOptions}
  107. comment={comment}
  108. revisionId={revisionId}
  109. revisionCreatedAt={revisionCreatedAt as Date}
  110. currentUser={currentUser}
  111. isReadOnly={isReadOnly}
  112. pageId={pageId}
  113. pagePath={pagePath}
  114. deleteBtnClicked={onClickDeleteButton}
  115. onComment={mutate}
  116. />
  117. );
  118. const replyCommentsElement = (replyComments: ICommentHasIdList) => (
  119. <ReplyComments
  120. rendererOptions={rendererOptions}
  121. isReadOnly={isReadOnly}
  122. revisionId={revisionId}
  123. revisionCreatedAt={revisionCreatedAt as Date}
  124. currentUser={currentUser}
  125. replyList={replyComments}
  126. pageId={pageId}
  127. pagePath={pagePath}
  128. deleteBtnClicked={onClickDeleteButton}
  129. onComment={mutate}
  130. />
  131. );
  132. return (
  133. <div className={`${styles['page-comment-styles']} page-comments-row comment-list`}>
  134. <div className="page-comments">
  135. <div className="page-comments-list mb-3" id="page-comments-list">
  136. {commentsExceptReply.map((comment) => {
  137. const defaultCommentThreadClasses = 'page-comment-thread mb-2';
  138. const hasReply: boolean = Object.keys(allReplies).includes(comment._id);
  139. let commentThreadClasses = '';
  140. commentThreadClasses = hasReply ? `${defaultCommentThreadClasses} page-comment-thread-no-replies` : defaultCommentThreadClasses;
  141. return (
  142. <div key={comment._id} className={commentThreadClasses}>
  143. {/* Comment */}
  144. {commentElement(comment)}
  145. {/* Reply comments */}
  146. {hasReply && replyCommentsElement(allReplies[comment._id])}
  147. {(!isReadOnly && !showEditorIds.has(comment._id)) && (
  148. <div className="d-flex flex-row-reverse">
  149. <NotAvailableForGuest>
  150. <NotAvailableForReadOnlyUser>
  151. <button
  152. type="button"
  153. data-testid="comment-reply-button"
  154. className="btn btn-secondary btn-comment-reply text-start w-100 ms-5"
  155. onClick={() => onReplyButtonClickHandler(comment._id)}
  156. >
  157. <UserPicture user={currentUser} noLink noTooltip additionalClassName="me-2" />
  158. <span className="material-symbols-outlined me-1 fs-5 pb-1">reply</span><small>{t('page_comment.reply')}...</small>
  159. </button>
  160. </NotAvailableForReadOnlyUser>
  161. </NotAvailableForGuest>
  162. </div>
  163. )}
  164. {/* Editor to reply */}
  165. {(!isReadOnly && showEditorIds.has(comment._id)) && (
  166. <CommentEditor
  167. pageId={pageId}
  168. replyTo={comment._id}
  169. onCanceled={() => {
  170. removeShowEditorId(comment._id);
  171. }}
  172. onCommented={() => onCommentButtonClickHandler(comment._id)}
  173. revisionId={revisionId}
  174. />
  175. )}
  176. </div>
  177. );
  178. })}
  179. </div>
  180. </div>
  181. {!isReadOnly && (
  182. <DeleteCommentModal
  183. isShown={isDeleteConfirmModalShown}
  184. comment={commentToBeDeleted}
  185. errorMessage={errorMessageOnDelete}
  186. cancelToDelete={onCancelDeleteComment}
  187. confirmToDelete={onDeleteComment}
  188. />
  189. )}
  190. </div>
  191. );
  192. });
  193. PageComment.displayName = 'PageComment';