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

100% Statements 49/49
61.9% Branches 13/21
100% Functions 12/12
100% Lines 46/46

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 1841x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x   1x 1x   1x 1x 1x   47x                               1x     47x                                       47x                           14x         14x 47x 47x   47x   47x   21x           47x 47x                 47x   18x     91x       47x 3x   3x 3x 3x       47x 2x   2x 2x     47x   47x   47x                                                                                                  
import { styled } from "@mui/material";
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import Alert from "components/Alert";
import HtmlMeta from "components/HtmlMeta";
import { BOTTOM_NAV_BASE_HEIGHT } from "components/Navigation/constants";
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, pingQueryKey } 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 } from "proto/conversations_pb";
import { service } from "service";
import { useIsNativeEmbed } from "utils/nativeLink";
 
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",
  flexShrink: 0,
  "& > * + *": {
    marginInlineStart: theme.spacing(2),
  },
 
  [theme.breakpoints.down("md")]: {
    paddingLeft: theme.spacing(1),
    paddingRight: theme.spacing(1),
  },
}));
 
const StyledPageWrapper = styled("div")<{
  isNativeEmbed: boolean;
  embedded: boolean;
}>(({ theme, isNativeEmbed, embedded }) => ({
  display: "flex",
  flexDirection: "column",
  overflow: "hidden", // Prevent page scroll - only messages should scroll
  ...(embedded
    ? { flex: 1, minHeight: 0 }
    : {
        // Use dvh (dynamic viewport height) which adjusts for mobile keyboard
        // Use CSS custom property set by Navigation component for actual height
        height: isNativeEmbed
          ? "calc(100dvh - var(--nav-height, 3.5rem) - var(--cookie-banner-height, 0px))"
          : `calc(100dvh - var(--nav-height, 3.5rem) - ${BOTTOM_NAV_BASE_HEIGHT}px - env(safe-area-inset-bottom, 0px) - var(--cookie-banner-height, 0px))`,
 
        [theme.breakpoints.up("md")]: {
          height: "calc(100dvh - var(--nav-height, 4rem) - var(--cookie-banner-height, 0px))",
        },
      }),
}));
 
// Footer is fixed at bottom - never scrolls away
const StyledFooter = styled("div")(({ theme }) => ({
  background: "var(--mui-palette-background-default)",
  flexShrink: 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),
    paddingBottom: `calc(${theme.spacing(2)} + env(safe-area-inset-bottom, 0px))`,
  },
}));
 
const StyledCannotMessageText = styled("div")(({ theme }) => ({
  padding: theme.spacing(2),
  textAlign: "center",
}));
 
export default function GroupChatView({ chatId, embedded = false }: { chatId: number; embedded?: boolean }) {
  const { t } = useTranslation([GLOBAL, MESSAGES]);
  const isNativeEmbed = useIsNativeEmbed();
 
  const queryClient = useQueryClient();
 
  const { data: groupChat, error: groupChatError } = useQuery({
    queryKey: groupChatKey(chatId),
    queryFn: () => 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>({
    queryKey: groupChatMessagesKey(chatId),
    queryFn: ({ pageParam }) => service.conversations.getGroupChatMessages(chatId, pageParam as number | undefined),
    enabled: !!chatId,
    initialPageParam: undefined,
    getNextPageParam: (lastPage) => (lastPage.noMore ? undefined : lastPage.lastMessageId),
    refetchInterval: GROUP_CHAT_REFETCH_INTERVAL,
  });
 
  const sendMutation = useMutation<Empty, RpcError, string>({
    mutationFn: (text) => service.conversations.sendMessage(chatId, text),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: groupChatMessagesKey(chatId) });
      queryClient.invalidateQueries({ queryKey: [groupChatsListKey] });
      queryClient.invalidateQueries({ queryKey: groupChatKey(chatId) });
    },
  });
 
  const { mutate: markLastSeenGroupChat } = useMutation<Empty, RpcError, MarkLastSeenVariables>({
    mutationFn: (messageId) => service.conversations.markLastSeenGroupChat(chatId, messageId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: groupChatKey(chatId) });
      queryClient.invalidateQueries({ queryKey: [pingQueryKey] });
    },
  });
  const { markLastSeen } = useMarkLastSeen(markLastSeenGroupChat, groupChat?.lastSeenMessageId);
 
  const title = groupChat ? groupChatTitleText(groupChat, groupChatMembersQuery, currentUserId, t) : undefined;
 
  const hasError = groupChatError || messagesError || sendMutation.error;
 
  return (
    <>
      <HtmlMeta title={title} />
      {!chatId ? (
        <Alert severity="error">{t("messages:chat_view.invalid_id_error")}</Alert>
      ) : (
        <StyledPageWrapper isNativeEmbed={isNativeEmbed} embedded={embedded}>
          <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}
            isDm={groupChat?.isDm}
            isLoading={isMessagesLoading}
            messages={messagesRes}
            fetchNextPage={fetchNextPage}
            isFetchingNextPage={isFetchingNextPage}
            hasNextPage={!!hasNextPage}
            markLastSeen={markLastSeen}
            isError={!!messagesError}
          />
          <StyledFooter>
            {groupChat?.canMessage ? (
              <GroupChatSendField sendMutation={sendMutation} chatId={chatId} currentUserId={currentUserId} />
            ) : (
              <StyledCannotMessageText>{t("messages:chat_view.cannot_message_text")}</StyledCannotMessageText>
            )}
          </StyledFooter>
        </StyledPageWrapper>
      )}
    </>
  );
}