PageComment.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 type PageCommentProps = {
  24. rendererOptions?: RendererOptions,
  25. pageId: string,
  26. revision: string | IRevisionHasId,
  27. currentUser: any,
  28. isReadOnly: boolean,
  29. titleAlign?: 'center' | 'left' | 'right',
  30. highlightKeywords?: string[],
  31. hideIfEmpty?: boolean,
  32. }
  33. export const PageComment: FC<PageCommentProps> = memo((props:PageCommentProps): JSX.Element => {
  34. const {
  35. rendererOptions: rendererOptionsByProps,
  36. pageId, revision, currentUser, highlightKeywords, 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 <></>;
  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 <></>;
  95. }
  96. return (
  97. <PageCommentSkelton commentTitleClasses={commentTitleClasses}/>
  98. );
  99. }
  100. const revisionId = getIdForRef(revision);
  101. const revisionCreatedAt = (isPopulated(revision)) ? revision.createdAt : undefined;
  102. const generateCommentElement = (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. highlightKeywords={highlightKeywords}
  111. deleteBtnClicked={onClickDeleteButton}
  112. onComment={mutate}
  113. />
  114. );
  115. const generateReplyCommentsElement = (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. deleteBtnClicked={onClickDeleteButton}
  124. onComment={mutate}
  125. />
  126. );
  127. return (
  128. <>
  129. <div className={`${styles['page-comment-styles']} page-comments-row comment-list`}>
  130. <div className="container-lg">
  131. <div className="page-comments">
  132. <h2 className={commentTitleClasses}><i className="icon-fw icon-bubbles"></i>Comments</h2>
  133. <div className="page-comments-list" id="page-comments-list">
  134. { commentsExceptReply.map((comment) => {
  135. const defaultCommentThreadClasses = 'page-comment-thread pb-5';
  136. const hasReply: boolean = Object.keys(allReplies).includes(comment._id);
  137. let commentThreadClasses = '';
  138. commentThreadClasses = hasReply ? `${defaultCommentThreadClasses} page-comment-thread-no-replies` : defaultCommentThreadClasses;
  139. return (
  140. <div key={comment._id} className={commentThreadClasses}>
  141. {generateCommentElement(comment)}
  142. {hasReply && generateReplyCommentsElement(allReplies[comment._id])}
  143. {(!isReadOnly && !showEditorIds.has(comment._id)) && (
  144. <div className="text-right">
  145. <Button
  146. outline
  147. color="secondary"
  148. size="sm"
  149. className="btn-comment-reply"
  150. onClick={() => {
  151. setShowEditorIds(previousState => new Set(previousState.add(comment._id)));
  152. }}
  153. >
  154. <i className="icon-fw icon-action-undo"></i> Reply
  155. </Button>
  156. </div>
  157. )}
  158. {(!isReadOnly && showEditorIds.has(comment._id)) && (
  159. <CommentEditor
  160. pageId={pageId}
  161. replyTo={comment._id}
  162. onCancelButtonClicked={() => {
  163. removeShowEditorId(comment._id);
  164. }}
  165. onCommentButtonClicked={() => {
  166. removeShowEditorId(comment._id);
  167. mutate();
  168. }}
  169. />
  170. )}
  171. </div>
  172. );
  173. })}
  174. </div>
  175. </div>
  176. </div>
  177. </div>
  178. {!isReadOnly && (
  179. <DeleteCommentModal
  180. isShown={isDeleteConfirmModalShown}
  181. comment={commentToBeDeleted}
  182. errorMessage={errorMessageOnDelete}
  183. cancelToDelete={onCancelDeleteComment}
  184. confirmToDelete={onDeleteComment}
  185. />
  186. )}
  187. </>
  188. );
  189. });
  190. PageComment.displayName = 'PageComment';