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

81.81% Statements 54/66
60% Branches 24/40
47.82% Functions 11/23
82.25% Lines 51/62

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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 2781x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x   1x                   45x                           50x 50x 50x 50x   50x 50x   50x 50x                   50x   1x             1x       1x         50x   50x   6x 1x 1x 1x       5x 2x   3x       50x 1x                                                                                                                     3x                                   3x                                                                                                                       1x                                                                    
import { Skeleton, styled, useMediaQuery } from "@mui/material";
import CircularProgress from "components/CircularProgress";
import HeaderButton from "components/HeaderButton";
import { BackIcon, MuteIcon, OverflowMenuIcon } from "components/Icons";
import Menu, { MenuItem } from "components/Menu";
import PageTitle from "components/PageTitle";
import AdminsDialog from "features/messages/groupchats/AdminsDialog";
import GroupChatSettingsDialog from "features/messages/groupchats/GroupChatSettingsDialog";
import InviteDialog from "features/messages/groupchats/InviteDialog";
import LeaveDialog from "features/messages/groupchats/LeaveDialog";
import MembersDialog from "features/messages/groupchats/MembersDialog";
import MuteDialog from "features/messages/groupchats/MuteDialog";
import { getDmUsername } from "features/messages/utils";
import { groupChatKey } from "features/queryKeys";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { GLOBAL, MESSAGES } from "i18n/namespaces";
import Link from "next/link";
import { useRouter } from "next/router";
import { GroupChat } from "proto/conversations_pb";
import { useRef, useState } from "react";
import { useMutation, useQueryClient } from "react-query";
import { groupChatsRoute, routeToUser } from "routes";
import { service } from "service";
import { theme } from "theme";
 
const StyledTitleBox = styled("div")({
  flexGrow: 1,
  width: "100%",
  display: "flex",
  alignItems: "center",
  marginInlineEnd: theme.spacing(2),
  marginInlineStart: theme.spacing(2),
  "& > *": { marginInlineEnd: theme.spacing(2) },
});
 
export default function GroupChatHeaderBar({
  chatId,
  currentUserId,
  groupChat,
  groupChatMembersQuery,
  title,
}: {
  chatId: number;
  currentUserId: number;
  groupChat: GroupChat.AsObject | undefined;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  groupChatMembersQuery: any;
  title: string | undefined;
}) {
  const router = useRouter();
  const queryClient = useQueryClient();
  const { t } = useTranslation([GLOBAL, MESSAGES]);
  const username = getDmUsername(groupChatMembersQuery, currentUserId);
 
  const isChatAdmin = groupChat?.adminUserIdsList.includes(currentUserId);
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
 
  const menuAnchor = useRef<HTMLButtonElement>(null);
  const [isOpen, setIsOpen] = useState({
    admins: false,
    invite: false,
    leave: false,
    members: false,
    menu: false,
    mute: false,
    settings: false,
  });
 
  const unmuteMutation = useMutation<void, RpcError>(
    async () => {
      await service.conversations.muteChat({
        groupChatId: chatId,
        unmute: true,
      });
    },
    {
      onSuccess() {
        queryClient.setQueryData(groupChatKey(chatId), {
          ...groupChat,
          muteInfo: { muted: false },
        });
        queryClient.invalidateQueries(groupChatKey(chatId));
      },
    }
  );
 
  const handleBack = () => router.push(groupChatsRoute);
 
  const handleClick = (item: keyof typeof isOpen) => {
    //just unmute straight away with no dialog if muted
    if (item === "mute" && groupChat?.muteInfo?.muted) {
      unmuteMutation.mutate();
      setIsOpen((prev) => ({ ...prev, menu: false }));
      return;
    }
 
    //close the menu if a menu item was selected
    if (item !== "menu") {
      setIsOpen((prev) => ({ ...prev, [item]: true, menu: false }));
    } else {
      setIsOpen((prev) => ({ ...prev, [item]: true }));
    }
  };
 
  const handleClose = (item: keyof typeof isOpen) => {
    setIsOpen({ ...isOpen, [item]: false });
  };
 
  return (
    <>
      <HeaderButton
        onClick={handleBack}
        aria-label={t("messages:chat_view.back_button.a11y_label")}
        size={isMobile ? "small" : "medium"}
      >
        <BackIcon fontSize={isMobile ? "small" : "medium"} />
      </HeaderButton>
      {groupChat?.isDm ? (
        <StyledTitleBox>
          <Link href={username ? routeToUser(username) : ""}>
            <PageTitle
              sx={{
                [theme.breakpoints.down("sm")]: {
                  fontSize: "0.9rem",
                },
              }}
            >
              {title || <Skeleton width={100} />}
            </PageTitle>
          </Link>
          {unmuteMutation.isLoading ? (
            <CircularProgress size="1.5rem" />
          ) : (
            groupChat?.muteInfo?.muted && (
              <MuteIcon
                data-testid="mute-icon"
                titleAccess={t("messages:chat_view.muted_icon.a11y_label")}
                fontSize={isMobile ? "small" : "large"}
              />
            )
          )}
        </StyledTitleBox>
      ) : (
        <StyledTitleBox>
          <PageTitle
            sx={{
              [theme.breakpoints.down("sm")]: {
                fontSize: "0.9rem",
              },
            }}
          >
            {title || <Skeleton width={100} />}
          </PageTitle>
          {groupChat?.muteInfo?.muted && (
            <MuteIcon
              data-testid="mute-icon"
              titleAccess={t("messages:chat_view.muted_icon.a11y_label")}
              fontSize={isMobile ? "small" : "medium"}
            />
          )}
        </StyledTitleBox>
      )}
      <>
        <HeaderButton
          onClick={() => handleClick("menu")}
          aria-label={t("messages:chat_view.actions_menu.a11y_label")}
          aria-haspopup="true"
          aria-controls="more-menu"
          ref={menuAnchor}
          size={isMobile ? "small" : "medium"}
        >
          <OverflowMenuIcon sx={{ fontSize: isMobile ? "small" : "medium" }} />
        </HeaderButton>
        <Menu
          id="more-menu"
          anchorEl={menuAnchor.current}
          keepMounted
          open={isOpen.menu}
          onClose={() => handleClose("menu")}
        >
          {[
            groupChat ? (
              <MenuItem onClick={() => handleClick("mute")} key="mute">
                {!groupChat.muteInfo?.muted
                  ? t("messages:chat_view.mute.button_label")
                  : t("messages:chat_view.mute.unmute_button_label")}
              </MenuItem>
            ) : null,
            !groupChat?.isDm
              ? [
                  !groupChat?.onlyAdminsInvite || isChatAdmin ? (
                    <MenuItem
                      onClick={() => handleClick("invite")}
                      key="invite"
                    >
                      {t(
                        "messages:chat_view.actions_menu.items.invite_members"
                      )}
                    </MenuItem>
                  ) : null,
                  <MenuItem
                    onClick={() => handleClick("members")}
                    key="members"
                  >
                    {t(
                      "messages:chat_view.actions_menu.items.show_all_members"
                    )}
                  </MenuItem>,
                  isChatAdmin
                    ? [
                        <MenuItem
                          onClick={() => handleClick("admins")}
                          key="admins"
                        >
                          {t(
                            "messages:chat_view.actions_menu.items.manage_admins"
                          )}
                        </MenuItem>,
                        <MenuItem
                          onClick={() => handleClick("settings")}
                          key="settings"
                        >
                          {t(
                            "messages:chat_view.actions_menu.items.chat_settings"
                          )}
                        </MenuItem>,
                      ]
                    : null,
 
                  groupChat?.memberUserIdsList.includes(currentUserId) ? (
                    <MenuItem onClick={() => handleClick("leave")} key="leave">
                      {t("messages:chat_view.actions_menu.items.leave_chat")}
                    </MenuItem>
                  ) : null,
                ]
              : null,
          ]}
        </Menu>
        {groupChat && (
          <>
            <MuteDialog
              open={isOpen.mute}
              onClose={() => handleClose("mute")}
              groupChatId={chatId}
            />
            <InviteDialog
              open={isOpen.invite}
              onClose={() => handleClose("invite")}
              groupChat={groupChat}
            />
            <MembersDialog
              open={isOpen.members}
              onClose={() => handleClose("members")}
              groupChat={groupChat}
            />
            <AdminsDialog
              open={isOpen.admins}
              onClose={() => handleClose("admins")}
              groupChat={groupChat}
            />
            <GroupChatSettingsDialog
              open={isOpen.settings}
              onClose={() => handleClose("settings")}
              groupChat={groupChat}
            />
          </>
        )}
        <LeaveDialog
          open={isOpen.leave}
          onClose={() => handleClose("leave")}
          groupChatId={chatId}
        />
      </>
    </>
  );
}