PageComment.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import React, {
  2. FC, useState, useMemo, memo, useCallback,
  3. } from 'react';
  4. import { isPopulated, getIdForRef, type IRevisionHasId } from '@growi/core';
  5. import { Button } from 'reactstrap';
  6. import { apiPost } from '~/client/util/apiv1-client';
  7. import { toastError } from '~/client/util/toastr';
  8. import { RendererOptions } from '~/interfaces/renderer-options';
  9. import { useSWRMUTxPageInfo } from '~/stores/page';
  10. import { useCommentForCurrentPageOptions } from '~/stores/renderer';
  11. import { ICommentHasId, ICommentHasIdList } from '../interfaces/comment';
  12. import { useSWRxPageComment } from '../stores/comment';
  13. import { NotAvailableForGuest } from './NotAvailableForGuest';
  14. import { NotAvailableForReadOnlyUser } from './NotAvailableForReadOnlyUser';
  15. import { Comment } from './PageComment/Comment';
  16. import { CommentEditor } from './PageComment/CommentEditor';
  17. import { DeleteCommentModal } from './PageComment/DeleteCommentModal';
  18. import { ReplyComments } from './PageComment/ReplyComments';
  19. import styles from './PageComment.module.scss';
  20. export const ROOT_ELEM_ID = 'page-comments' as const;
  21. // Always render '#page-comments' for MutationObserver of SearchResultContent
  22. const PageCommentRoot = (props: React.HTMLAttributes<HTMLDivElement>): JSX.Element => (
  23. <div id={ROOT_ELEM_ID} {...props}>{props.children}</div>
  24. );
  25. export type PageCommentProps = {
  26. rendererOptions?: RendererOptions,
  27. pageId: string,
  28. pagePath: string,
  29. revision: string | IRevisionHasId,
  30. currentUser: any,
  31. isReadOnly: boolean,
  32. titleAlign?: 'center' | 'left' | 'right',
  33. hideIfEmpty?: boolean,
  34. }
  35. export const PageComment: FC<PageCommentProps> = memo((props: PageCommentProps): JSX.Element => {
  36. const {
  37. rendererOptions: rendererOptionsByProps,
  38. pageId, pagePath, revision, currentUser, isReadOnly, titleAlign, hideIfEmpty,
  39. } = props;
  40. const { data: comments, mutate } = useSWRxPageComment(pageId);
  41. const { data: rendererOptionsForCurrentPage } = useCommentForCurrentPageOptions();
  42. const [commentToBeDeleted, setCommentToBeDeleted] = useState<ICommentHasId | null>(null);
  43. const [isDeleteConfirmModalShown, setIsDeleteConfirmModalShown] = useState<boolean>(false);
  44. const [showEditorIds, setShowEditorIds] = useState<Set<string>>(new Set());
  45. const [errorMessageOnDelete, setErrorMessageOnDelete] = useState<string>('');
  46. const { trigger: mutatePageInfo } = useSWRMUTxPageInfo(pageId);
  47. const commentsFromOldest = useMemo(() => (comments != null ? [...comments].reverse() : null), [comments]);
  48. const commentsExceptReply: ICommentHasIdList | undefined = useMemo(
  49. () => commentsFromOldest?.filter(comment => comment.replyTo == null), [commentsFromOldest],
  50. );
  51. const allReplies = {};
  52. if (commentsFromOldest != null) {
  53. commentsFromOldest.forEach((comment) => {
  54. if (comment.replyTo != null) {
  55. allReplies[comment.replyTo] = allReplies[comment.replyTo] == null ? [comment] : [...allReplies[comment.replyTo], comment];
  56. }
  57. });
  58. }
  59. const onClickDeleteButton = useCallback((comment: ICommentHasId) => {
  60. setCommentToBeDeleted(comment);
  61. setIsDeleteConfirmModalShown(true);
  62. }, []);
  63. const onCancelDeleteComment = useCallback(() => {
  64. setCommentToBeDeleted(null);
  65. setIsDeleteConfirmModalShown(false);
  66. }, []);
  67. const onDeleteCommentAfterOperation = useCallback(() => {
  68. onCancelDeleteComment();
  69. mutate();
  70. mutatePageInfo();
  71. }, [mutate, onCancelDeleteComment, mutatePageInfo]);
  72. const onDeleteComment = useCallback(async() => {
  73. if (commentToBeDeleted == null) return;
  74. try {
  75. await apiPost('/comments.remove', { comment_id: commentToBeDeleted._id });
  76. onDeleteCommentAfterOperation();
  77. }
  78. catch (error: unknown) {
  79. setErrorMessageOnDelete(error as string);
  80. toastError(`error: ${error}`);
  81. }
  82. }, [commentToBeDeleted, onDeleteCommentAfterOperation]);
  83. const removeShowEditorId = useCallback((commentId: string) => {
  84. setShowEditorIds((previousState) => {
  85. return new Set([...previousState].filter(id => id !== commentId));
  86. });
  87. }, []);
  88. const onReplyButtonClickHandler = useCallback((commentId: string) => {
  89. setShowEditorIds(previousState => new Set([...previousState, commentId]));
  90. }, []);
  91. const onCommentButtonClickHandler = useCallback((commentId: string) => {
  92. removeShowEditorId(commentId);
  93. mutate();
  94. mutatePageInfo();
  95. }, [removeShowEditorId, mutate, mutatePageInfo]);
  96. if (hideIfEmpty && comments?.length === 0) {
  97. return <PageCommentRoot />;
  98. }
  99. let commentTitleClasses = 'border-bottom py-3 mb-3';
  100. commentTitleClasses = titleAlign != null ? `${commentTitleClasses} text-${titleAlign}` : `${commentTitleClasses} text-center`;
  101. const rendererOptions = rendererOptionsByProps ?? rendererOptionsForCurrentPage;
  102. if (commentsFromOldest == null || commentsExceptReply == null || rendererOptions == null) {
  103. if (hideIfEmpty) {
  104. return <PageCommentRoot />;
  105. }
  106. return (
  107. <></>
  108. );
  109. }
  110. const revisionId = getIdForRef(revision);
  111. const revisionCreatedAt = (isPopulated(revision)) ? revision.createdAt : undefined;
  112. const commentElement = (comment: ICommentHasId) => (
  113. <Comment
  114. rendererOptions={rendererOptions}
  115. comment={comment}
  116. revisionId={revisionId}
  117. revisionCreatedAt={revisionCreatedAt as Date}
  118. currentUser={currentUser}
  119. isReadOnly={isReadOnly}
  120. pageId={pageId}
  121. pagePath={pagePath}
  122. deleteBtnClicked={onClickDeleteButton}
  123. onComment={mutate}
  124. />
  125. );
  126. const replyCommentsElement = (replyComments: ICommentHasIdList) => (
  127. <ReplyComments
  128. rendererOptions={rendererOptions}
  129. isReadOnly={isReadOnly}
  130. revisionId={revisionId}
  131. revisionCreatedAt={revisionCreatedAt as Date}
  132. currentUser={currentUser}
  133. replyList={replyComments}
  134. pageId={pageId}
  135. pagePath={pagePath}
  136. deleteBtnClicked={onClickDeleteButton}
  137. onComment={mutate}
  138. />
  139. );
  140. return (
  141. <PageCommentRoot className={`${styles['page-comment-styles']} page-comments-row comment-list`}>
  142. <div className="container-lg">
  143. <div className="page-comments">
  144. <h2 className={commentTitleClasses}><i className="icon-fw icon-bubbles"></i>Comments</h2>
  145. <div className="page-comments-list" id="page-comments-list">
  146. {commentsExceptReply.map((comment) => {
  147. const defaultCommentThreadClasses = 'page-comment-thread pb-5';
  148. const hasReply: boolean = Object.keys(allReplies).includes(comment._id);
  149. let commentThreadClasses = '';
  150. commentThreadClasses = hasReply ? `${defaultCommentThreadClasses} page-comment-thread-no-replies` : defaultCommentThreadClasses;
  151. return (
  152. <div key={comment._id} className={commentThreadClasses}>
  153. {commentElement(comment)}
  154. {hasReply && replyCommentsElement(allReplies[comment._id])}
  155. {(!isReadOnly && !showEditorIds.has(comment._id)) && (
  156. <div className="d-flex flex-row-reverse">
  157. <NotAvailableForGuest>
  158. <NotAvailableForReadOnlyUser>
  159. <Button
  160. data-testid="comment-reply-button"
  161. outline
  162. color="secondary"
  163. size="sm"
  164. className="btn-comment-reply"
  165. onClick={() => onReplyButtonClickHandler(comment._id)}
  166. >
  167. <i className="icon-fw icon-action-undo"></i> Reply
  168. </Button>
  169. </NotAvailableForReadOnlyUser>
  170. </NotAvailableForGuest>
  171. </div>
  172. )}
  173. {(!isReadOnly && showEditorIds.has(comment._id)) && (
  174. <CommentEditor
  175. pageId={pageId}
  176. replyTo={comment._id}
  177. onCancelButtonClicked={() => {
  178. removeShowEditorId(comment._id);
  179. }}
  180. onCommentButtonClicked={() => onCommentButtonClickHandler(comment._id)}
  181. revisionId={revisionId}
  182. />
  183. )}
  184. </div>
  185. );
  186. })}
  187. </div>
  188. </div>
  189. </div>
  190. {!isReadOnly && (
  191. <DeleteCommentModal
  192. isShown={isDeleteConfirmModalShown}
  193. comment={commentToBeDeleted}
  194. errorMessage={errorMessageOnDelete}
  195. cancelToDelete={onCancelDeleteComment}
  196. confirmToDelete={onDeleteComment}
  197. />
  198. )}
  199. </PageCommentRoot>
  200. );
  201. });
  202. PageComment.displayName = 'PageComment';