Files

382 lines
12 KiB
TypeScript

import { m } from "framer-motion";
import { observer } from "mobx-react";
import { darken } from "polished";
import * as React from "react";
import { useTranslation } from "react-i18next";
import scrollIntoView from "scroll-into-view-if-needed";
import styled, { css } from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import { s, hover } from "@shared/styles";
import type { ProsemirrorData } from "@shared/types";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import type Comment from "~/models/Comment";
import type Document from "~/models/Document";
import { AvatarSize } from "~/components/Avatar";
import { useDocumentContext } from "~/components/DocumentContext";
import Facepile from "~/components/Facepile";
import Fade from "~/components/Fade";
import { ResizingHeightContainer } from "~/components/ResizingHeightContainer";
import useBoolean from "~/hooks/useBoolean";
import useOnClickOutside from "~/hooks/useOnClickOutside";
import usePersistedState from "~/hooks/usePersistedState";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import useCurrentUser from "~/hooks/useCurrentUser";
import { sidebarAppearDuration } from "~/styles/animations";
import CommentForm from "./CommentForm";
import CommentThreadItem from "./CommentThreadItem";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
type Props = {
/** The document that this comment thread belongs to */
document: Document;
/** The root comment to render */
comment: Comment;
/** Whether the thread is focused */
focused: boolean;
/** Whether the thread is displayed in a recessed/backgrounded state */
recessed: boolean;
/** Number of replies before collapsing */
collapseThreshold?: number;
/** Number of replies to display when collapsed */
collapseNumDisplayed?: number;
};
function CommentThread({
comment: thread,
document,
recessed,
focused,
collapseThreshold = 5,
collapseNumDisplayed = 3,
}: Props) {
const [scrollOnMount] = React.useState(focused && !window.location.hash);
// Whether to play the entrance animation, captured once at mount so that
// submitting the thread (which flips isNew) does not change the animation.
const [animateIn] = React.useState(thread.isNew);
const { editor, setFocusedCommentId } = useDocumentContext();
const { comments } = useStores();
const topRef = React.useRef<HTMLDivElement>(null);
const { t } = useTranslation();
const [autoFocus, setAutoFocusOn, setAutoFocusOff] = useBoolean(thread.isNew);
const user = useCurrentUser();
const can = usePolicy(document);
const [draft, onSaveDraft] = usePersistedState<ProsemirrorData | undefined>(
`draft-${document.id}-${thread.id}`,
undefined
);
// Track edit states for all comments in the thread
const [editingCommentIds, setEditingCommentIds] = React.useState<Set<string>>(
new Set()
);
const canReply = can.comment && !thread.isResolved;
const highlightedText =
ProsemirrorHelper.getAnchorTextForComment(
editor?.getComments() ?? [],
thread.id
) ?? thread.pendingAnchor?.anchorText;
const commentsInThread = comments
.inThread(thread.id)
.filter((comment) => !comment.isNew);
const [collapse, setCollapse] = React.useState(() => {
const numReplies = commentsInThread.length - 1;
if (numReplies >= collapseThreshold) {
return {
begin: 1,
final: commentsInThread.length - collapseNumDisplayed - 1,
};
}
return null;
});
useOnClickOutside(topRef, (event) => {
const target = event.target as HTMLElement;
if (
focused &&
!target.classList.contains("comment") &&
// Clicking another thread switches focus to it directly via its own
// click handler, so skip deselecting here to avoid a flash of the
// deselected state (and the new comment form) in between.
!target.closest("[data-comment-thread]") &&
!target.closest("." + EditorStyleHelper.commentGutter) &&
event.defaultPrevented === false
) {
setFocusedCommentId(null);
}
});
const handleSubmit = React.useCallback(() => {
editor?.updateComment(thread.id, { draft: false });
}, [editor, thread.id]);
const handleClickThread = () => {
setFocusedCommentId(thread.id);
};
const handleClickExpand = (ev: React.SyntheticEvent) => {
ev.stopPropagation();
setCollapse(null);
};
const handleUpArrowAtStart = React.useCallback(() => {
// Find the previous comment by the current user in reverse order
const userComments = commentsInThread
.filter((comment) => comment.createdById === user.id)
.reverse(); // Start from most recent
if (userComments.length > 0) {
const previousComment = userComments[0];
setEditingCommentIds((prev) => new Set(prev).add(previousComment.id));
}
}, [commentsInThread, user.id]);
const handleCommentEditStart = React.useCallback((commentId: string) => {
setEditingCommentIds((prev) => new Set(prev).add(commentId));
}, []);
const handleCommentEditEnd = React.useCallback((commentId: string) => {
setEditingCommentIds((prev) => {
const newSet = new Set(prev);
newSet.delete(commentId);
return newSet;
});
}, []);
const renderShowMore = (collapse: { begin: number; final: number }) => {
const count = collapse.final - collapse.begin + 1;
const createdBy = commentsInThread
.slice(collapse.begin, collapse.final + 1)
.map((c) => c.createdBy);
const users = Array.from(new Set(createdBy));
const limit = 3;
const overflow = users.length - limit;
return (
<ShowMore onClick={handleClickExpand} key="show-more">
{t("Show {{ count }} reply", { count })}
<Facepile
users={users}
limit={limit}
overflow={overflow}
size={AvatarSize.Medium}
/>
</ShowMore>
);
};
React.useEffect(() => {
if (!focused && autoFocus) {
setAutoFocusOff();
}
}, [focused, autoFocus, setAutoFocusOff]);
React.useEffect(() => {
if (focused) {
if (scrollOnMount) {
setTimeout(() => {
if (!topRef.current) {
return;
}
scrollIntoView(topRef.current, {
scrollMode: "if-needed",
behavior: "auto",
block: "nearest",
boundary: (parent) =>
// Prevents body and other parent elements from being scrolled
parent.id !== "comments",
});
}, sidebarAppearDuration);
} else {
setTimeout(() => {
if (!topRef.current) {
return;
}
// Scroll the whole into view when its mark is clicked
scrollIntoView(topRef.current, {
scrollMode: "if-needed",
behavior: "smooth",
block: "nearest",
boundary: (parent) =>
// Prevents body and other parent elements from being scrolled
parent.id !== "comments",
});
}, 0);
}
const getCommentMarkElement = () =>
window.document?.getElementById(`comment-${thread.id}`);
const isMarkVisible = !!getCommentMarkElement();
setTimeout(
() => {
editor?.revealComment(thread.id);
getCommentMarkElement()?.scrollIntoView({
behavior: "smooth",
block: "center",
});
},
isMarkVisible ? 0 : sidebarAppearDuration
);
}
}, [focused, scrollOnMount, thread.id, editor]);
return (
<Thread
ref={topRef}
data-comment-thread
layout="position"
transition={{ layout: { duration: 0.2, ease: "easeOut" } }}
$focused={focused}
$recessed={recessed}
onClick={handleClickThread}
>
{/* The entrance transform lives on an inner element so it does not
conflict with the layout projection transform on Thread, which
would otherwise skew the thread during layout animations. */}
<ThreadInner
initial={animateIn ? { opacity: 0, y: 10 } : false}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, ease: "easeOut" }}
>
{commentsInThread.map((comment, index) => {
if (collapse !== null) {
if (index === collapse.begin) {
return renderShowMore(collapse);
} else if (index > collapse.begin && index <= collapse.final) {
return null;
}
}
const firstOfAuthor =
index === 0 ||
(collapse && index === collapse.final + 1) ||
comment.createdById !== commentsInThread[index - 1].createdById;
const lastOfAuthor =
index === commentsInThread.length - 1 ||
comment.createdById !== commentsInThread[index + 1].createdById;
return (
<CommentThreadItem
highlightedText={index === 0 ? highlightedText : undefined}
comment={comment}
onDelete={editor?.removeComment}
onUpdate={editor?.updateComment}
key={comment.id}
firstOfThread={index === 0}
lastOfThread={index === commentsInThread.length - 1 && !draft}
canReply={focused && can.comment}
firstOfAuthor={firstOfAuthor}
lastOfAuthor={lastOfAuthor}
previousCommentCreatedAt={commentsInThread[index - 1]?.createdAt}
forceEdit={editingCommentIds.has(comment.id)}
onEditStart={() => handleCommentEditStart(comment.id)}
onEditEnd={() => handleCommentEditEnd(comment.id)}
/>
);
})}
<ResizingHeightContainer hideOverflow={false}>
{(focused || draft || commentsInThread.length === 0) && canReply && (
<Fade timing={100}>
<CommentForm
onSubmit={handleSubmit}
onSaveDraft={onSaveDraft}
draft={draft}
documentId={document.id}
thread={thread}
standalone={commentsInThread.length === 0}
autoFocus={autoFocus}
highlightedText={
commentsInThread.length === 0 ? highlightedText : undefined
}
onUpArrowAtStart={handleUpArrowAtStart}
/>
</Fade>
)}
</ResizingHeightContainer>
</ThreadInner>
{!focused && !recessed && !draft && canReply && (
<Reply onClick={setAutoFocusOn}>{t("Reply")}…</Reply>
)}
</Thread>
);
}
const Reply = styled.button`
border: 0;
padding: 8px;
margin: 0;
background: none;
color: ${s("textTertiary")};
font-size: 14px;
-webkit-appearance: none;
cursor: var(--pointer);
transition: opacity 100ms ease-out;
position: absolute;
text-align: start;
width: 100%;
bottom: -30px;
inset-inline-start: 32px;
${breakpoint("tablet")`
opacity: 0;
`}
`;
const ShowMore = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1px;
margin-inline-start: 32px;
padding: 8px 12px;
color: ${s("textTertiary")};
background: ${(props) => darken(0.015, props.theme.backgroundSecondary)};
cursor: var(--pointer);
font-size: 13px;
&: ${hover} {
color: ${s("textSecondary")};
background: ${s("backgroundTertiary")};
}
* {
border-color: ${(props) => darken(0.015, props.theme.backgroundSecondary)};
}
`;
const Thread = styled(m.div)<{
$focused: boolean;
$recessed: boolean;
}>`
margin: 12px 12px 32px;
margin-inline-end: 18px;
margin-inline-start: 12px;
position: relative;
transition: opacity 100ms ease-out;
&: ${hover} {
${Reply} {
opacity: 1;
}
}
${(props) =>
props.$recessed &&
css`
opacity: 0.35;
cursor: default;
`}
`;
const ThreadInner = styled(m.div)``;
export default observer(CommentThread);