PageComment.tsx 8.4 KB

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