PageComment.tsx 8.3 KB

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