PageComment.tsx 8.8 KB

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