PageComment.tsx 8.5 KB

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