PageComment.tsx 7.8 KB

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