PageComment.tsx 8.1 KB

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