PageComment.tsx 7.8 KB

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