PageComment.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import type { FC, JSX } from 'react';
  2. import React, {
  3. useState, useMemo, memo, useCallback,
  4. } from 'react';
  5. import type { IRevision, Ref } from '@growi/core';
  6. import {
  7. isPopulated, getIdStringForRef,
  8. } from '@growi/core';
  9. import { UserPicture } from '@growi/ui/dist/components';
  10. import { useTranslation } from 'next-i18next';
  11. import { apiPost } from '~/client/util/apiv1-client';
  12. import { toastError } from '~/client/util/toastr';
  13. import type { RendererOptions } from '~/interfaces/renderer-options';
  14. import { useSWRMUTxPageInfo } from '~/stores/page';
  15. import { useCommentForCurrentPageOptions } from '~/stores/renderer';
  16. import type { ICommentHasId, ICommentHasIdList } from '../../interfaces/comment';
  17. import { useSWRxPageComment } from '../../stores/comment';
  18. import { NotAvailableForGuest } from './NotAvailableForGuest';
  19. import { NotAvailableIfReadOnlyUserNotAllowedToComment } from './NotAvailableForReadOnlyUser';
  20. import { Comment } from './PageComment/Comment';
  21. import { CommentEditor } from './PageComment/CommentEditor';
  22. import { DeleteCommentModal } from './PageComment/DeleteCommentModal';
  23. import { ReplyComments } from './PageComment/ReplyComments';
  24. import styles from './PageComment.module.scss';
  25. type PageCommentProps = {
  26. rendererOptions?: RendererOptions,
  27. pageId: string,
  28. pagePath: string,
  29. revision: Ref<IRevision>,
  30. currentUser: any,
  31. isReadOnly: boolean,
  32. }
  33. export const PageComment: FC<PageCommentProps> = memo((props: PageCommentProps): JSX.Element => {
  34. const {
  35. rendererOptions: rendererOptionsByProps,
  36. pageId, pagePath, revision, currentUser, isReadOnly,
  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 { trigger: mutatePageInfo } = useSWRMUTxPageInfo(pageId);
  45. const { t } = useTranslation('');
  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. mutatePageInfo();
  70. }, [mutate, onCancelDeleteComment, mutatePageInfo]);
  71. const onDeleteComment = useCallback(async() => {
  72. if (commentToBeDeleted == null) return;
  73. try {
  74. await apiPost('/comments.remove', { comment_id: commentToBeDeleted._id });
  75. onDeleteCommentAfterOperation();
  76. }
  77. catch (error: unknown) {
  78. const message = error instanceof Error
  79. ? error.message
  80. : (error as any).toString();
  81. setErrorMessageOnDelete(message);
  82. toastError(message);
  83. }
  84. }, [commentToBeDeleted, onDeleteCommentAfterOperation]);
  85. const removeShowEditorId = useCallback((commentId: string) => {
  86. setShowEditorIds((previousState) => {
  87. return new Set([...previousState].filter(id => id !== commentId));
  88. });
  89. }, []);
  90. const onReplyButtonClickHandler = useCallback((commentId: string) => {
  91. setShowEditorIds(previousState => new Set([...previousState, commentId]));
  92. }, []);
  93. const onCommentButtonClickHandler = useCallback((commentId: string) => {
  94. removeShowEditorId(commentId);
  95. mutate();
  96. mutatePageInfo();
  97. }, [removeShowEditorId, mutate, mutatePageInfo]);
  98. if (comments?.length === 0) {
  99. return <></>;
  100. }
  101. const rendererOptions = rendererOptionsByProps ?? rendererOptionsForCurrentPage;
  102. if (commentsFromOldest == null || commentsExceptReply == null || rendererOptions == null) {
  103. return <></>;
  104. }
  105. const revisionId = getIdStringForRef(revision);
  106. const revisionCreatedAt = (isPopulated(revision)) ? revision.createdAt : undefined;
  107. const commentElement = (comment: ICommentHasId) => (
  108. <Comment
  109. rendererOptions={rendererOptions}
  110. comment={comment}
  111. revisionId={revisionId}
  112. revisionCreatedAt={revisionCreatedAt as Date}
  113. currentUser={currentUser}
  114. isReadOnly={isReadOnly}
  115. pageId={pageId}
  116. pagePath={pagePath}
  117. deleteBtnClicked={onClickDeleteButton}
  118. onComment={mutate}
  119. />
  120. );
  121. const replyCommentsElement = (replyComments: ICommentHasIdList) => (
  122. <ReplyComments
  123. rendererOptions={rendererOptions}
  124. isReadOnly={isReadOnly}
  125. revisionId={revisionId}
  126. revisionCreatedAt={revisionCreatedAt as Date}
  127. currentUser={currentUser}
  128. replyList={replyComments}
  129. pageId={pageId}
  130. pagePath={pagePath}
  131. deleteBtnClicked={onClickDeleteButton}
  132. onComment={mutate}
  133. />
  134. );
  135. return (
  136. <div className={`${styles['page-comment-styles']} page-comments-row comment-list`}>
  137. <div className="page-comments">
  138. <div className="page-comments-list mb-3" id="page-comments-list">
  139. {commentsExceptReply.map((comment) => {
  140. const defaultCommentThreadClasses = 'page-comment-thread mb-2';
  141. const hasReply: boolean = Object.keys(allReplies).includes(comment._id);
  142. let commentThreadClasses = '';
  143. commentThreadClasses = hasReply ? `${defaultCommentThreadClasses} page-comment-thread-no-replies` : defaultCommentThreadClasses;
  144. return (
  145. <div key={comment._id} className={commentThreadClasses}>
  146. {/* Comment */}
  147. {commentElement(comment)}
  148. {/* Reply comments */}
  149. {hasReply && replyCommentsElement(allReplies[comment._id])}
  150. {(!isReadOnly && !showEditorIds.has(comment._id)) && (
  151. <div className="d-flex flex-row-reverse">
  152. <NotAvailableForGuest>
  153. <NotAvailableIfReadOnlyUserNotAllowedToComment>
  154. <button
  155. type="button"
  156. data-testid="comment-reply-button"
  157. className="btn btn-secondary btn-comment-reply text-start w-100 ms-5"
  158. onClick={() => onReplyButtonClickHandler(comment._id)}
  159. >
  160. <UserPicture user={currentUser} noLink noTooltip className="me-2" />
  161. <span className="material-symbols-outlined me-1 fs-5 pb-1">reply</span><small>{t('page_comment.reply')}...</small>
  162. </button>
  163. </NotAvailableIfReadOnlyUserNotAllowedToComment>
  164. </NotAvailableForGuest>
  165. </div>
  166. )}
  167. {/* Editor to reply */}
  168. {(!isReadOnly && showEditorIds.has(comment._id)) && (
  169. <CommentEditor
  170. pageId={pageId}
  171. replyTo={comment._id}
  172. onCanceled={() => {
  173. removeShowEditorId(comment._id);
  174. }}
  175. onCommented={() => onCommentButtonClickHandler(comment._id)}
  176. revisionId={revisionId}
  177. />
  178. )}
  179. </div>
  180. );
  181. })}
  182. </div>
  183. </div>
  184. {!isReadOnly && (
  185. <DeleteCommentModal
  186. isShown={isDeleteConfirmModalShown}
  187. comment={commentToBeDeleted}
  188. errorMessage={errorMessageOnDelete}
  189. cancelToDelete={onCancelDeleteComment}
  190. confirmToDelete={onDeleteComment}
  191. />
  192. )}
  193. </div>
  194. );
  195. });
  196. PageComment.displayName = 'PageComment';