All files / app/features/communities/discussions Comment.tsx

100% Statements 54/54
94.73% Branches 18/19
100% Functions 14/14
100% Lines 45/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211            6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x 6x 6x   6x 6x   157x                                     157x           157x                   157x           81x         121x                         6x       8x 6x             39x 157x 157x                     157x 157x 157x   157x 157x   157x 71x 2x             157x 157x                                                                       2x                                     1x           45x     46x             2x                      
import {
  Card,
  CircularProgress,
  Skeleton,
  styled,
  Typography,
} from "@mui/material";
import Avatar from "components/Avatar";
import Button from "components/Button";
import CenteredSpinner from "components/CenteredSpinner/CenteredSpinner";
import Markdown from "components/Markdown";
import FlagButton from "features/FlagButton";
import CopyOnClick from "features/mod/CopyOnClick";
import ModVisibleComponent from "features/mod/ModVisibleComponent";
import { useLiteUser } from "features/userQueries/useLiteUsers";
import { useTranslation } from "i18n";
import { COMMUNITIES, GLOBAL } from "i18n/namespaces";
import { Reply } from "proto/threads_pb";
import { useEffect, useRef, useState } from "react";
import { theme } from "theme";
import { timestamp2Date } from "utils/date";
import hasAtLeastOnePage from "utils/hasAtLeastOnePage";
import { timeAgo } from "utils/timeAgo";
 
import { useThread } from "../hooks";
import CommentForm from "./CommentForm";
 
const StyledCommentContainer = styled(Card)(() => ({
  alignItems: "start",
  columnGap: theme.spacing(2),
  display: "grid",
  gridTemplateAreas: `
      "avatar content content"
      ". . replyButton"
    `,
  [theme.breakpoints.up("md")]: {
    gridTemplateAreas: `
        "avatar content replyButton"
      `,
  },
  gridTemplateColumns: "3rem minmax(0, 9fr) 1fr",
  gridTemplateRows: "auto",
  padding: theme.spacing(2),
  width: "100%",
}));
 
const StyledButtonsContainer = styled("div")(() => ({
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
}));
 
const StyledCommentContent = styled("div")(() => ({
  "& > * + *": {
    marginBlockStart: theme.spacing(0.5),
  },
  display: "flex",
  flexDirection: "column",
  gridArea: "content",
  marginInlineStart: theme.spacing(1),
}));
 
const StyledAvatar = styled(Avatar)(() => ({
  height: "3rem",
  gridArea: "avatar",
  width: "3rem",
}));
 
const StyledReplyButton = styled(Button)(() => ({
  gridArea: "replyButton",
  placeSelf: "end",
}));
 
const StyledNestedCommentsContainer = styled("div")(() => ({
  "& > * + *": {
    marginBlockStart: theme.spacing(2),
  },
  display: "flex",
  flexDirection: "column",
  marginBlockStart: theme.spacing(2),
  marginInlineStart: theme.spacing(3),
  "&": {
    marginInlineStart: `clamp(${theme.spacing(2)}, 5vw, ${theme.spacing(5)})`,
  },
}));
 
const StyledLoadEarlierRepliesButton = styled(Button)(() => ({
  alignSelf: "center",
}));
 
export const COMMENT_TEST_ID = "comment";
export const REFETCH_LOADING_TEST_ID = "refetching";
 
interface CommentProps {
  comment: Reply.AsObject;
  topLevel?: boolean;
}
 
export default function Comment({ topLevel = false, comment }: CommentProps) {
  const { t } = useTranslation([GLOBAL, COMMUNITIES]);
  const { data: user, isLoading: isUserLoading } = useLiteUser(
    comment.authorUserId,
  );
 
  const {
    data: comments,
    fetchNextPage,
    hasNextPage,
    isLoading: isCommentsLoading,
    isFetching: isCommentsFetching,
    isFetchingNextPage,
  } = useThread(comment.threadId, { enabled: topLevel });
  const isCommentsRefetching = !isCommentsLoading && isCommentsFetching;
  const showLoadMoreButton = topLevel && hasNextPage;
 
  const [showCommentForm, setShowCommentForm] = useState(false);
  const commentFormRef = useRef<HTMLFormElement>(null);
 
  useEffect(() => {
    if (showCommentForm && commentFormRef.current) {
      commentFormRef.current.scrollIntoView({
        behavior: "smooth",
        block: "center",
      });
    }
  }, [showCommentForm]);
 
  const replyDate = timestamp2Date(comment.createdTime!);
  const postedTime = timeAgo(replyDate);
 
  return (
    <>
      <StyledCommentContainer data-testid={COMMENT_TEST_ID}>
        <StyledButtonsContainer>
          <StyledAvatar user={user} />
          <FlagButton
            contentRef={`comment/${comment.threadId}`}
            authorUser={comment.authorUserId}
          />
        </StyledButtonsContainer>
        <StyledCommentContent>
          {isUserLoading ? (
            <Skeleton />
          ) : (
            <Typography variant="body2">
              {t("communities:by_creator", {
                name: user?.name ?? t("communities:unknown_user"),
              })}
              {` • ${postedTime}`}
              <ModVisibleComponent>
                {" "}
                •{" "}
                <code>
                  threadId:
                  <CopyOnClick text={comment.threadId.toString()} />
                </code>
              </ModVisibleComponent>
            </Typography>
          )}
          {isUserLoading ? <Skeleton /> : <Markdown source={comment.content} />}
        </StyledCommentContent>
        {topLevel && (
          <StyledReplyButton
            onClick={() => {
              setShowCommentForm(true);
            }}
          >
            {t("global:reply")}
          </StyledReplyButton>
        )}
      </StyledCommentContainer>
      {isCommentsLoading ? (
        <CenteredSpinner />
      ) : (
        <StyledNestedCommentsContainer>
          {!showLoadMoreButton && isCommentsRefetching && (
            <CircularProgress data-testid={REFETCH_LOADING_TEST_ID} />
          )}
          {hasAtLeastOnePage(comments, "repliesList") && (
            <>
              {showLoadMoreButton && (
                <StyledLoadEarlierRepliesButton
                  loading={isFetchingNextPage}
                  onClick={() => fetchNextPage()}
                >
                  {t("communities:load_earlier_replies")}
                </StyledLoadEarlierRepliesButton>
              )}
              {comments.pages
                .flatMap((page) => page.repliesList)
                .reverse()
                .map((reply) => {
                  return <Comment key={reply.threadId} comment={reply} />;
                })}
            </>
          )}
          {topLevel && (
            <CommentForm
              hideable
              onClose={() => setShowCommentForm(false)}
              ref={commentFormRef}
              shown={showCommentForm}
              threadId={comment.threadId}
            />
          )}
        </StyledNestedCommentsContainer>
      )}
    </>
  );
}