import React, { FC, useState, useMemo, memo, useCallback, } from 'react'; import { isPopulated, getIdForRef } from '@growi/core/dist/interfaces/common'; import { type IRevisionHasId } from '@growi/core/dist/interfaces/revision'; import { Button } from 'reactstrap'; import { apiPost } from '~/client/util/apiv1-client'; import { toastError } from '~/client/util/toastr'; import { RendererOptions } from '~/interfaces/renderer-options'; import { useSWRMUTxPageInfo } from '~/stores/page'; import { useCommentForCurrentPageOptions } from '~/stores/renderer'; import { ICommentHasId, ICommentHasIdList } from '../interfaces/comment'; import { useSWRxPageComment } from '../stores/comment'; import { NotAvailableForGuest } from './NotAvailableForGuest'; import { NotAvailableForReadOnlyUser } from './NotAvailableForReadOnlyUser'; import { Comment } from './PageComment/Comment'; import { CommentEditor } from './PageComment/CommentEditor'; import { DeleteCommentModal } from './PageComment/DeleteCommentModal'; import { ReplyComments } from './PageComment/ReplyComments'; import styles from './PageComment.module.scss'; export const ROOT_ELEM_ID = 'page-comments' as const; // Always render '#page-comments' for MutationObserver of SearchResultContent const PageCommentRoot = (props: React.HTMLAttributes): JSX.Element => (
{props.children}
); export type PageCommentProps = { rendererOptions?: RendererOptions, pageId: string, pagePath: string, revision: string | IRevisionHasId, currentUser: any, isReadOnly: boolean, titleAlign?: 'center' | 'left' | 'right', hideIfEmpty?: boolean, } export const PageComment: FC = memo((props: PageCommentProps): JSX.Element => { const { rendererOptions: rendererOptionsByProps, pageId, pagePath, revision, currentUser, isReadOnly, titleAlign, hideIfEmpty, } = props; const { data: comments, mutate } = useSWRxPageComment(pageId); const { data: rendererOptionsForCurrentPage } = useCommentForCurrentPageOptions(); const [commentToBeDeleted, setCommentToBeDeleted] = useState(null); const [isDeleteConfirmModalShown, setIsDeleteConfirmModalShown] = useState(false); const [showEditorIds, setShowEditorIds] = useState>(new Set()); const [errorMessageOnDelete, setErrorMessageOnDelete] = useState(''); const { trigger: mutatePageInfo } = useSWRMUTxPageInfo(pageId); const commentsFromOldest = useMemo(() => (comments != null ? [...comments].reverse() : null), [comments]); const commentsExceptReply: ICommentHasIdList | undefined = useMemo( () => commentsFromOldest?.filter(comment => comment.replyTo == null), [commentsFromOldest], ); const allReplies = {}; if (commentsFromOldest != null) { commentsFromOldest.forEach((comment) => { if (comment.replyTo != null) { allReplies[comment.replyTo] = allReplies[comment.replyTo] == null ? [comment] : [...allReplies[comment.replyTo], comment]; } }); } const onClickDeleteButton = useCallback((comment: ICommentHasId) => { setCommentToBeDeleted(comment); setIsDeleteConfirmModalShown(true); }, []); const onCancelDeleteComment = useCallback(() => { setCommentToBeDeleted(null); setIsDeleteConfirmModalShown(false); }, []); const onDeleteCommentAfterOperation = useCallback(() => { onCancelDeleteComment(); mutate(); mutatePageInfo(); }, [mutate, onCancelDeleteComment, mutatePageInfo]); const onDeleteComment = useCallback(async() => { if (commentToBeDeleted == null) return; try { await apiPost('/comments.remove', { comment_id: commentToBeDeleted._id }); onDeleteCommentAfterOperation(); } catch (error: unknown) { setErrorMessageOnDelete(error as string); toastError(`error: ${error}`); } }, [commentToBeDeleted, onDeleteCommentAfterOperation]); const removeShowEditorId = useCallback((commentId: string) => { setShowEditorIds((previousState) => { return new Set([...previousState].filter(id => id !== commentId)); }); }, []); const onReplyButtonClickHandler = useCallback((commentId: string) => { setShowEditorIds(previousState => new Set([...previousState, commentId])); }, []); const onCommentButtonClickHandler = useCallback((commentId: string) => { removeShowEditorId(commentId); mutate(); mutatePageInfo(); }, [removeShowEditorId, mutate, mutatePageInfo]); if (hideIfEmpty && comments?.length === 0) { return ; } let commentTitleClasses = 'border-bottom py-3 mb-3'; commentTitleClasses = titleAlign != null ? `${commentTitleClasses} text-${titleAlign}` : `${commentTitleClasses} text-center`; const rendererOptions = rendererOptionsByProps ?? rendererOptionsForCurrentPage; if (commentsFromOldest == null || commentsExceptReply == null || rendererOptions == null) { if (hideIfEmpty) { return ; } return ( <> ); } const revisionId = getIdForRef(revision); const revisionCreatedAt = (isPopulated(revision)) ? revision.createdAt : undefined; const commentElement = (comment: ICommentHasId) => ( ); const replyCommentsElement = (replyComments: ICommentHasIdList) => ( ); return (

Comments

{commentsExceptReply.map((comment) => { const defaultCommentThreadClasses = 'page-comment-thread pb-5'; const hasReply: boolean = Object.keys(allReplies).includes(comment._id); let commentThreadClasses = ''; commentThreadClasses = hasReply ? `${defaultCommentThreadClasses} page-comment-thread-no-replies` : defaultCommentThreadClasses; return (
{commentElement(comment)} {hasReply && replyCommentsElement(allReplies[comment._id])} {(!isReadOnly && !showEditorIds.has(comment._id)) && (
)} {(!isReadOnly && showEditorIds.has(comment._id)) && ( { removeShowEditorId(comment._id); }} onCommentButtonClicked={() => onCommentButtonClickHandler(comment._id)} revisionId={revisionId} /> )}
); })}
{!isReadOnly && ( )}
); }); PageComment.displayName = 'PageComment';