PageComment.tsx 7.9 KB

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