PageComment.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import React, {
  2. FC, useState, useMemo, memo, useCallback,
  3. } from 'react';
  4. import { IRevisionHasId, isPopulated, getIdForRef } from '@growi/core';
  5. import dynamic from 'next/dynamic';
  6. import { Button } from 'reactstrap';
  7. import { toastError } from '~/client/util/apiNotification';
  8. import { apiPost } from '~/client/util/apiv1-client';
  9. import { RendererOptions } from '~/services/renderer/renderer';
  10. import { useCommentForCurrentPageOptions } from '~/stores/renderer';
  11. import { ICommentHasId, ICommentHasIdList } from '../interfaces/comment';
  12. import { useSWRxPageComment } from '../stores/comment';
  13. import { Comment } from './PageComment/Comment';
  14. import { CommentEditorProps } from './PageComment/CommentEditor';
  15. import { DeleteCommentModalProps } from './PageComment/DeleteCommentModal';
  16. import { ReplyComments } from './PageComment/ReplyComments';
  17. import { PageCommentSkelton } from './PageCommentSkelton';
  18. import styles from './PageComment.module.scss';
  19. const CommentEditor = dynamic<CommentEditorProps>(() => import('./PageComment/CommentEditor').then(mod => mod.CommentEditor), { ssr: false });
  20. const DeleteCommentModal = dynamic<DeleteCommentModalProps>(
  21. () => import('./PageComment/DeleteCommentModal').then(mod => mod.DeleteCommentModal), { ssr: false },
  22. );
  23. export const ROOT_ELEM_ID = 'page-comments' as const;
  24. // Always render '#page-comments' for MutationObserver of SearchResultContent
  25. const PageCommentRoot = (props: React.HTMLAttributes<HTMLDivElement>): JSX.Element => (
  26. <div id={ROOT_ELEM_ID} {...props}>{props.children}</div>
  27. );
  28. export type PageCommentProps = {
  29. rendererOptions?: RendererOptions,
  30. pageId: string,
  31. revision: string | IRevisionHasId,
  32. currentUser: any,
  33. isReadOnly: boolean,
  34. titleAlign?: 'center' | 'left' | 'right',
  35. hideIfEmpty?: boolean,
  36. }
  37. export const PageComment: FC<PageCommentProps> = memo((props:PageCommentProps): JSX.Element => {
  38. const {
  39. rendererOptions: rendererOptionsByProps,
  40. pageId, revision, currentUser, isReadOnly, titleAlign, hideIfEmpty,
  41. } = props;
  42. const { data: comments, mutate } = useSWRxPageComment(pageId);
  43. const { data: rendererOptionsForCurrentPage } = useCommentForCurrentPageOptions();
  44. const [commentToBeDeleted, setCommentToBeDeleted] = useState<ICommentHasId | null>(null);
  45. const [isDeleteConfirmModalShown, setIsDeleteConfirmModalShown] = useState<boolean>(false);
  46. const [showEditorIds, setShowEditorIds] = useState<Set<string>>(new Set());
  47. const [errorMessageOnDelete, setErrorMessageOnDelete] = useState<string>('');
  48. const commentsFromOldest = useMemo(() => (comments != null ? [...comments].reverse() : null), [comments]);
  49. const commentsExceptReply: ICommentHasIdList | undefined = useMemo(
  50. () => commentsFromOldest?.filter(comment => comment.replyTo == null), [commentsFromOldest],
  51. );
  52. const allReplies = {};
  53. if (commentsFromOldest != null) {
  54. commentsFromOldest.forEach((comment) => {
  55. if (comment.replyTo != null) {
  56. allReplies[comment.replyTo] = allReplies[comment.replyTo] == null ? [comment] : [...allReplies[comment.replyTo], comment];
  57. }
  58. });
  59. }
  60. const onClickDeleteButton = useCallback((comment: ICommentHasId) => {
  61. setCommentToBeDeleted(comment);
  62. setIsDeleteConfirmModalShown(true);
  63. }, []);
  64. const onCancelDeleteComment = useCallback(() => {
  65. setCommentToBeDeleted(null);
  66. setIsDeleteConfirmModalShown(false);
  67. }, []);
  68. const onDeleteCommentAfterOperation = useCallback(() => {
  69. onCancelDeleteComment();
  70. mutate();
  71. }, [mutate, onCancelDeleteComment]);
  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. const previousShowEditorIds = new Set(...previousState);
  86. previousShowEditorIds.delete(commentId);
  87. return previousShowEditorIds;
  88. });
  89. }, []);
  90. if (hideIfEmpty && comments?.length === 0) {
  91. return <PageCommentRoot />;
  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. if (hideIfEmpty) {
  98. return <PageCommentRoot />;
  99. }
  100. return (
  101. <PageCommentSkelton commentTitleClasses={commentTitleClasses}/>
  102. );
  103. }
  104. const revisionId = getIdForRef(revision);
  105. const revisionCreatedAt = (isPopulated(revision)) ? revision.createdAt : undefined;
  106. const commentElement = (comment: ICommentHasId) => (
  107. <Comment
  108. rendererOptions={rendererOptions}
  109. comment={comment}
  110. revisionId={revisionId}
  111. revisionCreatedAt={revisionCreatedAt as Date}
  112. currentUser={currentUser}
  113. isReadOnly={isReadOnly}
  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. 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="text-right">
  147. <Button
  148. outline
  149. color="secondary"
  150. size="sm"
  151. className="btn-comment-reply"
  152. onClick={() => {
  153. setShowEditorIds(previousState => new Set(previousState.add(comment._id)));
  154. }}
  155. >
  156. <i className="icon-fw icon-action-undo"></i> Reply
  157. </Button>
  158. </div>
  159. )}
  160. {(!isReadOnly && showEditorIds.has(comment._id)) && (
  161. <CommentEditor
  162. pageId={pageId}
  163. replyTo={comment._id}
  164. onCancelButtonClicked={() => {
  165. removeShowEditorId(comment._id);
  166. }}
  167. onCommentButtonClicked={() => {
  168. removeShowEditorId(comment._id);
  169. mutate();
  170. }}
  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. </PageCommentRoot>
  189. );
  190. });
  191. PageComment.displayName = 'PageComment';