PageComment.tsx 8.7 KB

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