PageComment.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import React, {
  2. FC, useEffect, useState, useMemo, memo, useCallback,
  3. } from 'react';
  4. import dynamic from 'next/dynamic';
  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 { CommentEditorProps } from './PageComment/CommentEditor';
  15. import { DeleteCommentModalProps } from './PageComment/DeleteCommentModal';
  16. import { ReplyComments } from './PageComment/ReplyComments';
  17. import { PageCommentSkelton } from './PageCommentSkelton';
  18. import styles from './PageComment.module.scss';
  19. const CommentEditor = dynamic<CommentEditorProps>(() => import('./PageComment/CommentEditor').then(mod => mod.CommentEditor), { ssr: false });
  20. const DeleteCommentModal = dynamic<DeleteCommentModalProps>(
  21. () => import('./PageComment/DeleteCommentModal').then(mod => mod.DeleteCommentModal), { ssr: false },
  22. );
  23. type PageCommentProps = {
  24. pageId?: string,
  25. isReadOnly: boolean,
  26. titleAlign?: 'center' | 'left' | 'right',
  27. highlightKeywords?: string[],
  28. hideIfEmpty?: boolean,
  29. }
  30. export const PageComment: FC<PageCommentProps> = memo((props:PageCommentProps): JSX.Element => {
  31. const {
  32. pageId, highlightKeywords, isReadOnly, titleAlign, hideIfEmpty,
  33. } = props;
  34. const { data: comments, mutate } = useSWRxPageComment(pageId);
  35. const { data: rendererOptions } = useCommentPreviewOptions();
  36. const { data: currentPage } = useSWRxCurrentPage();
  37. const { data: currentPagePath } = useCurrentPagePath();
  38. const [commentToBeDeleted, setCommentToBeDeleted] = useState<ICommentHasId | null>(null);
  39. const [isDeleteConfirmModalShown, setIsDeleteConfirmModalShown] = useState<boolean>(false);
  40. const [showEditorIds, setShowEditorIds] = useState<Set<string>>(new Set());
  41. const [formatedComments, setFormatedComments] = useState<ICommentHasIdList | null>(null);
  42. const [errorMessageOnDelete, setErrorMessageOnDelete] = useState<string>('');
  43. const commentsFromOldest = useMemo(() => (formatedComments != null ? [...formatedComments].reverse() : null), [formatedComments]);
  44. const commentsExceptReply: ICommentHasIdList | undefined = useMemo(
  45. () => commentsFromOldest?.filter(comment => comment.replyTo == null), [commentsFromOldest],
  46. );
  47. const allReplies = {};
  48. const highlightComment = useCallback((comment: string):string => {
  49. if (highlightKeywords == null) return comment;
  50. let highlightedComment = '';
  51. highlightKeywords.forEach((highlightKeyword) => {
  52. highlightedComment = comment.replaceAll(highlightKeyword, '<em class="highlighted-keyword">$&</em>');
  53. });
  54. return highlightedComment;
  55. }, [highlightKeywords]);
  56. useEffect(() => {
  57. if (comments != null) {
  58. const preprocessedCommentList: string[] = comments.map((comment) => {
  59. const highlightedComment: string = highlightComment(comment.comment);
  60. return highlightedComment;
  61. });
  62. const preprocessedComments: ICommentHasIdList = comments.map((comment, index) => {
  63. return { ...comment, comment: preprocessedCommentList[index] };
  64. });
  65. setFormatedComments(preprocessedComments);
  66. }
  67. }, [comments, highlightComment]);
  68. if (commentsFromOldest != null) {
  69. commentsFromOldest.forEach((comment) => {
  70. if (comment.replyTo != null) {
  71. allReplies[comment.replyTo] = allReplies[comment.replyTo] == null ? [comment] : [...allReplies[comment.replyTo], comment];
  72. }
  73. });
  74. }
  75. const onClickDeleteButton = useCallback((comment: ICommentHasId) => {
  76. setCommentToBeDeleted(comment);
  77. setIsDeleteConfirmModalShown(true);
  78. }, []);
  79. const onCancelDeleteComment = useCallback(() => {
  80. setCommentToBeDeleted(null);
  81. setIsDeleteConfirmModalShown(false);
  82. }, []);
  83. const onDeleteCommentAfterOperation = useCallback(() => {
  84. onCancelDeleteComment();
  85. mutate();
  86. }, [mutate, onCancelDeleteComment]);
  87. const onDeleteComment = useCallback(async() => {
  88. if (commentToBeDeleted == null) return;
  89. try {
  90. await apiPost('/comments.remove', { comment_id: commentToBeDeleted._id });
  91. onDeleteCommentAfterOperation();
  92. }
  93. catch (error:unknown) {
  94. setErrorMessageOnDelete(error as string);
  95. toastError(`error: ${error}`);
  96. }
  97. }, [commentToBeDeleted, onDeleteCommentAfterOperation]);
  98. const removeShowEditorId = useCallback((commentId: string) => {
  99. setShowEditorIds((previousState) => {
  100. const previousShowEditorIds = new Set(...previousState);
  101. previousShowEditorIds.delete(commentId);
  102. return previousShowEditorIds;
  103. });
  104. }, []);
  105. if (hideIfEmpty && comments?.length === 0) {
  106. return <></>;
  107. }
  108. let commentTitleClasses = 'border-bottom py-3 mb-3';
  109. commentTitleClasses = titleAlign != null ? `${commentTitleClasses} text-${titleAlign}` : `${commentTitleClasses} text-center`;
  110. if (commentsFromOldest == null || commentsExceptReply == null || rendererOptions == null || currentPagePath == null || currentPage == null) {
  111. if (hideIfEmpty && comments?.length === 0) {
  112. return <></>;
  113. }
  114. return (
  115. <PageCommentSkelton commentTitleClasses={commentTitleClasses}/>
  116. );
  117. }
  118. if (currentPage.revision == null) {
  119. return <></>;
  120. }
  121. const generateCommentElement = (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 generateReplyCommentsElement = (replyComments: ICommentHasIdList) => (
  134. <ReplyComments
  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={`${styles['page-comment-styles']} page-comments-row comment-list`}>
  148. <div className="container-lg">
  149. <div className="page-comments">
  150. <h2 className={commentTitleClasses}><i className="icon-fw icon-bubbles"></i>Comments</h2>
  151. <div className="page-comments-list" id="page-comments-list">
  152. { commentsExceptReply.map((comment) => {
  153. const defaultCommentThreadClasses = 'page-comment-thread pb-5';
  154. const hasReply: boolean = Object.keys(allReplies).includes(comment._id);
  155. let commentThreadClasses = '';
  156. commentThreadClasses = hasReply ? `${defaultCommentThreadClasses} page-comment-thread-no-replies` : defaultCommentThreadClasses;
  157. return (
  158. <div key={comment._id} className={commentThreadClasses}>
  159. {generateCommentElement(comment)}
  160. {hasReply && generateReplyCommentsElement(allReplies[comment._id])}
  161. {(!isReadOnly && !showEditorIds.has(comment._id)) && (
  162. <div className="text-right">
  163. <Button
  164. outline
  165. color="secondary"
  166. size="sm"
  167. className="btn-comment-reply"
  168. onClick={() => {
  169. setShowEditorIds(previousState => new Set(previousState.add(comment._id)));
  170. }}
  171. >
  172. <i className="icon-fw icon-action-undo"></i> Reply
  173. </Button>
  174. </div>
  175. )}
  176. {(!isReadOnly && showEditorIds.has(comment._id)) && (
  177. <CommentEditor
  178. rendererOptions={rendererOptions}
  179. replyTo={comment._id}
  180. onCancelButtonClicked={() => {
  181. removeShowEditorId(comment._id);
  182. }}
  183. onCommentButtonClicked={() => {
  184. removeShowEditorId(comment._id);
  185. mutate();
  186. }}
  187. />
  188. )}
  189. </div>
  190. );
  191. })}
  192. </div>
  193. </div>
  194. </div>
  195. </div>
  196. {!isReadOnly && (
  197. <DeleteCommentModal
  198. isShown={isDeleteConfirmModalShown}
  199. comment={commentToBeDeleted}
  200. errorMessage={errorMessageOnDelete}
  201. cancelToDelete={onCancelDeleteComment}
  202. confirmToDelete={onDeleteComment}
  203. />
  204. )}
  205. </>
  206. );
  207. });
  208. PageComment.displayName = 'PageComment';