PageComment.tsx 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 { ReplayComments } from './PageComment/ReplayComments';
  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. let commentTitleClasses = 'border-bottom py-3 mb-3';
  102. commentTitleClasses = titleAlign != null ? `${commentTitleClasses} text-${titleAlign}` : `${commentTitleClasses} text-center`;
  103. if (commentsFromOldest == null || commentsExceptReply == null || rendererOptions == null || currentPagePath == null || currentPage == null
  104. || (hideIfEmpty && comments?.length === 0)) {
  105. return (
  106. <>
  107. <div className="page-comments-row comment-list mt-5 py-4 d-edit-none d-print-none">
  108. {/* TODO: container-lg expected global import, _override.scss */}
  109. <div className="container-lg">
  110. <div className={`${styles['page-comments']} page-comments`}>
  111. <h2 className={commentTitleClasses}><i className="icon-fw icon-bubbles"></i>Comments</h2>
  112. <div className="text-muted text-center mt-3">
  113. <i className="fa fa-lg fa-spinner fa-pulse mr-1"></i>
  114. </div>
  115. </div>
  116. </div>
  117. </div>
  118. </>
  119. );
  120. }
  121. const generateCommentInnerElement = (comment: ICommentHasId) => (
  122. <Comment
  123. comment={comment}
  124. isReadOnly={isReadOnly}
  125. deleteBtnClicked={onClickDeleteButton}
  126. onComment={mutate}
  127. rendererOptions={rendererOptions}
  128. currentPagePath={currentPagePath}
  129. currentRevisionId={currentPage.revision._id}
  130. currentRevisionCreatedAt={currentPage.revision.createdAt}
  131. />
  132. );
  133. const generateAllRepliesElement = (replyComments: ICommentHasIdList) => (
  134. <ReplayComments
  135. isReadOnly={isReadOnly}
  136. replyList={replyComments}
  137. deleteBtnClicked={onClickDeleteButton}
  138. onComment={mutate}
  139. rendererOptions={rendererOptions}
  140. currentPagePath={currentPagePath}
  141. currentRevisionId={currentPage.revision._id}
  142. currentRevisionCreatedAt={currentPage.revision.createdAt}
  143. />
  144. );
  145. return (
  146. <>
  147. <div className="page-comments-row comment-list mt-5 py-4 d-edit-none d-print-none">
  148. {/* TODO: container-lg expected global import, _override.scss */}
  149. <div className="container-lg">
  150. <div className={`${styles['page-comments']} page-comments`}>
  151. <h2 className={commentTitleClasses}><i className="icon-fw icon-bubbles"></i>Comments</h2>
  152. <div className="page-comments-list" id="page-comments-list">
  153. { commentsExceptReply.map((comment) => {
  154. const defaultCommentThreadClasses = 'page-comment-thread pb-5';
  155. const hasReply: boolean = Object.keys(allReplies).includes(comment._id);
  156. let commentThreadClasses = '';
  157. commentThreadClasses = hasReply ? `${defaultCommentThreadClasses} page-comment-thread-no-replies` : defaultCommentThreadClasses;
  158. return (
  159. <div key={comment._id} className={commentThreadClasses}>
  160. {/* display comment */}
  161. {generateCommentInnerElement(comment)}
  162. {/* display reply comment */}
  163. {hasReply && generateAllRepliesElement(allReplies[comment._id])}
  164. {/* display reply button */}
  165. {(!isReadOnly && !showEditorIds.has(comment._id)) && (
  166. <div className="text-right">
  167. <Button
  168. outline
  169. color="secondary"
  170. size="sm"
  171. className={`${styles['btn-comment-reply']} btn-comment-reply`}
  172. onClick={() => {
  173. setShowEditorIds(previousState => new Set(previousState.add(comment._id)));
  174. }}
  175. >
  176. <i className="icon-fw icon-action-undo"></i> Reply
  177. </Button>
  178. </div>
  179. )}
  180. {/* display reply editor */}
  181. {(!isReadOnly && showEditorIds.has(comment._id)) && (
  182. <CommentEditor
  183. rendererOptions={rendererOptions}
  184. replyTo={comment._id}
  185. onCancelButtonClicked={() => {
  186. removeShowEditorId(comment._id);
  187. }}
  188. onCommentButtonClicked={() => {
  189. removeShowEditorId(comment._id);
  190. mutate();
  191. }}
  192. />
  193. )}
  194. </div>
  195. );
  196. })}
  197. </div>
  198. {/* TODO: Check if identical-page */}
  199. <CommentEditorLazyRenderer pageId={pageId} rendererOptions={rendererOptions}/>
  200. </div>
  201. </div>
  202. </div>
  203. {(!isReadOnly && commentToBeDeleted != null) && (
  204. <DeleteCommentModal
  205. isShown={isDeleteConfirmModalShown}
  206. comment={commentToBeDeleted}
  207. errorMessage={errorMessageOnDelete}
  208. cancel={onCancelDeleteComment}
  209. confirmedToDelete={onDeleteComment}
  210. />
  211. )}
  212. </>
  213. );
  214. });
  215. PageComment.displayName = 'PageComment';