All files / app/features/messages/groupchats GroupChatView.tsx

98.07% Statements 51/52
56.25% Branches 9/16
100% Functions 14/14
97.95% Lines 48/49

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 212 213 2141x 1x 1x 1x 1x     1x 1x         1x 1x     1x 1x   1x           1x 1x   1x 1x 1x   45x                               45x                       45x                               13x 45x   45x   45x 13x 13x         13x 13x   13x 13x       45x     21x           45x 45x                     45x     17x       86x         45x 3x     3x 3x 3x         45x           2x     2x       45x         45x       45x                                                                                                    
import { styled } from "@mui/material";
import Alert from "components/Alert";
import HtmlMeta from "components/HtmlMeta";
import { useAuthContext } from "features/auth/AuthProvider";
import GroupChatSendField from "features/messages/groupchats/GroupChatSendField";
import useMarkLastSeen, {
  MarkLastSeenVariables,
} from "features/messages/useMarkLastSeen";
import { groupChatTitleText } from "features/messages/utils";
import {
  groupChatKey,
  groupChatMessagesKey,
  groupChatsListKey,
} from "features/queryKeys";
import { useLiteUsers } from "features/userQueries/useLiteUsers";
import { Empty } from "google-protobuf/google/protobuf/empty_pb";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { GLOBAL, MESSAGES } from "i18n/namespaces";
import { GetGroupChatMessagesRes, GroupChat } from "proto/conversations_pb";
import { useEffect } from "react";
import {
  useInfiniteQuery,
  useMutation,
  useQuery,
  useQueryClient,
} from "react-query";
import { service } from "service";
 
import ChatContent from "./ChatContent";
import { GROUP_CHAT_REFETCH_INTERVAL } from "./constants";
import GroupChatHeaderBar from "./GroupChatHeaderBar";
 
const StyledHeader = styled("div")(({ theme }) => ({
  padding: theme.spacing(1, 2),
  borderBottom: `1px solid ${theme.palette.divider}`,
  alignItems: "center",
  display: "flex",
  flexGrow: 0,
  "& > * + *": {
    marginInlineStart: theme.spacing(2),
  },
 
  [theme.breakpoints.down("md")]: {
    paddingLeft: theme.spacing(1),
    paddingRight: theme.spacing(1),
  },
}));
 
const StyledPageWrapper = styled("div")(({ theme }) => ({
  alignItems: "stretch",
  display: "flex",
  flexDirection: "column",
  overflow: "hidden",
  height: `calc(var(--vh, 1vh) * 100 - ${theme.shape.navPaddingXs})`,
 
  [theme.breakpoints.up("sm")]: {
    height: `calc(var(--vh, 1vh) * 100 - ${theme.shape.navPaddingSmUp})`,
  },
}));
 
const StyledFooter = styled("div")(({ theme }) => ({
  background: theme.palette.common.white,
  position: "sticky",
  bottom: 0,
  marginTop: "auto",
  flexGrow: 0,
  paddingBottom: theme.spacing(2),
  paddingLeft: theme.spacing(2),
  paddingRight: theme.spacing(2),
 
  [theme.breakpoints.down("md")]: {
    paddingLeft: theme.spacing(1),
    paddingRight: theme.spacing(1),
  },
}));
 
export default function GroupChatView({ chatId }: { chatId: number }) {
  const { t } = useTranslation([GLOBAL, MESSAGES]);
 
  const queryClient = useQueryClient();
 
  useEffect(() => {
    const scrollIntoView = () => {
      Iif (/Firefox/i.test(navigator.userAgent)) {
        document?.activeElement?.scrollIntoView({ behavior: "smooth" });
      }
    };
 
    scrollIntoView();
    window.addEventListener("resize", scrollIntoView);
 
    return () => {
      window.removeEventListener("resize", scrollIntoView);
    };
  }, []);
 
  const { data: groupChat, error: groupChatError } = useQuery<
    GroupChat.AsObject,
    RpcError
  >(groupChatKey(chatId), () => service.conversations.getGroupChat(chatId), {
    enabled: !!chatId,
    refetchInterval: GROUP_CHAT_REFETCH_INTERVAL,
  });
 
  //for title text
  const currentUserId = useAuthContext().authState.userId!;
  const groupChatMembersQuery = useLiteUsers(
    groupChat?.memberUserIdsList ?? []
  );
 
  const {
    data: messagesRes,
    isLoading: isMessagesLoading,
    error: messagesError,
    fetchNextPage,
    isFetchingNextPage,
    hasNextPage,
  } = useInfiniteQuery<GetGroupChatMessagesRes.AsObject, RpcError>(
    groupChatMessagesKey(chatId),
    ({ pageParam: lastMessageId }) =>
      service.conversations.getGroupChatMessages(chatId, lastMessageId),
    {
      enabled: !!chatId,
      getNextPageParam: (lastPage) =>
        lastPage.noMore ? undefined : lastPage.lastMessageId,
      refetchInterval: GROUP_CHAT_REFETCH_INTERVAL,
    }
  );
 
  const sendMutation = useMutation<Empty, RpcError, string>(
    (text) => service.conversations.sendMessage(chatId, text),
    {
      onSuccess: () => {
        queryClient.invalidateQueries(groupChatMessagesKey(chatId));
        queryClient.invalidateQueries([groupChatsListKey]);
        queryClient.invalidateQueries(groupChatKey(chatId));
      },
    }
  );
 
  const { mutate: markLastSeenGroupChat } = useMutation<
    Empty,
    RpcError,
    MarkLastSeenVariables
  >(
    (messageId) =>
      service.conversations.markLastSeenGroupChat(chatId, messageId),
    {
      onSuccess: () => {
        queryClient.invalidateQueries(groupChatKey(chatId));
      },
    }
  );
  const { markLastSeen } = useMarkLastSeen(
    markLastSeenGroupChat,
    groupChat?.lastSeenMessageId
  );
 
  const title = groupChat
    ? groupChatTitleText(groupChat, groupChatMembersQuery, currentUserId)
    : undefined;
 
  const hasError = groupChatError || messagesError || sendMutation.error;
 
  return (
    <>
      <HtmlMeta title={title} />
      {!chatId ? (
        <Alert severity="error">
          {t("messages:chat_view.invalid_id_error")}
        </Alert>
      ) : (
        <StyledPageWrapper>
          <StyledHeader>
            <GroupChatHeaderBar
              chatId={chatId}
              currentUserId={currentUserId}
              groupChat={groupChat}
              groupChatMembersQuery={groupChatMembersQuery}
              title={title}
            />
          </StyledHeader>
          {hasError && (
            <Alert severity="error">
              {groupChatError?.message ||
                messagesError?.message ||
                sendMutation.error?.message ||
                t("global:error.fallback.title")}
            </Alert>
          )}
          <ChatContent
            isHostRequest={false}
            isLoading={isMessagesLoading}
            messages={messagesRes}
            fetchNextPage={fetchNextPage}
            isFetchingNextPage={isFetchingNextPage}
            hasNextPage={!!hasNextPage}
            markLastSeen={markLastSeen}
            isError={!!messagesError}
          />
          <StyledFooter>
            <GroupChatSendField
              sendMutation={sendMutation}
              chatId={chatId}
              currentUserId={currentUserId}
            />
          </StyledFooter>
        </StyledPageWrapper>
      )}
    </>
  );
}