PageComment.tsx 8.2 KB

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