PageComment.tsx 8.1 KB

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