PageComment.tsx 7.9 KB

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