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

100% Statements 41/41
96.29% Branches 26/27
100% Functions 8/8
100% Lines 38/38

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 1828x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x   8x 8x   10x                                                                                                           8x 8x             8x 198x 198x 198x                     198x 198x 198x   198x 198x   198x 87x 2x             198x 198x   198x                                         2x                                       1x           61x     62x             2x                      
import { Card, CircularProgress, Typography } from "@material-ui/core";
import { Skeleton } from "@material-ui/lab";
import Avatar from "components/Avatar";
import Button from "components/Button";
import Markdown from "components/Markdown";
import { useUser } from "features/userQueries/useUsers";
import { useTranslation } from "i18n";
import { COMMUNITIES, GLOBAL } from "i18n/namespaces";
import { Reply } from "proto/threads_pb";
import { useEffect, useRef, useState } from "react";
import { timestamp2Date } from "utils/date";
import hasAtLeastOnePage from "utils/hasAtLeastOnePage";
import makeStyles from "utils/makeStyles";
import { timeAgo } from "utils/timeAgo";
 
import { useThread } from "../hooks";
import CommentForm from "./CommentForm";
 
const useStyles = makeStyles((theme) => ({
  commentContainer: {
    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%",
  },
  commentContent: {
    "& > * + *": {
      marginBlockStart: theme.spacing(0.5),
    },
    display: "flex",
    flexDirection: "column",
    gridArea: "content",
    marginInlineStart: theme.spacing(1),
  },
  replyButton: {
    gridArea: "replyButton",
    placeSelf: "end",
  },
  avatar: {
    height: "3rem",
    gridArea: "avatar",
    width: "3rem",
  },
  nestedCommentsContainer: {
    "& > * + *": {
      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)})`,
    },
  },
  loadEarlierRepliesButton: {
    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 classes = useStyles();
  const { data: user, isLoading: isUserLoading } = useUser(
    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 (
    <>
      <Card className={classes.commentContainer} data-testid={COMMENT_TEST_ID}>
        <Avatar user={user} className={classes.avatar} />
        <div className={classes.commentContent}>
          {isUserLoading ? (
            <Skeleton />
          ) : (
            <Typography variant="body2">
              {t("communities:by_creator", {
                name: user?.name ?? t("communities:unknown_user"),
              })}
              {` • ${postedTime}`}
            </Typography>
          )}
          {isUserLoading ? <Skeleton /> : <Markdown source={comment.content} />}
        </div>
        {topLevel && (
          <Button
            className={classes.replyButton}
            onClick={() => {
              setShowCommentForm(true);
            }}
          >
            {t("global:reply")}
          </Button>
        )}
      </Card>
      {isCommentsLoading ? (
        <CircularProgress />
      ) : (
        <div className={classes.nestedCommentsContainer}>
          {!showLoadMoreButton && isCommentsRefetching && (
            <CircularProgress data-testid={REFETCH_LOADING_TEST_ID} />
          )}
          {hasAtLeastOnePage(comments, "repliesList") && (
            <>
              {showLoadMoreButton && (
                <Button
                  className={classes.loadEarlierRepliesButton}
                  loading={isFetchingNextPage}
                  onClick={() => fetchNextPage()}
                >
                  {t("communities:load_earlier_replies")}
                </Button>
              )}
              {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}
            />
          )}
        </div>
      )}
    </>
  );
}