All files / app/features/messages AllMessagesTab.tsx

36.9% Statements 31/84
0% Branches 0/78
0% Functions 0/20
40.25% Lines 31/77

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 2671x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x   1x   1x   1x       1x       1x                                                         1x         1x         1x                                                                                                                                                                                                                                                                                                                                                                                          
import { useFeatureValue } from "@growthbook/growthbook-react";
import { Chip, List, styled } from "@mui/material";
import { useInfiniteQuery } from "@tanstack/react-query";
import Alert from "components/Alert";
import CenteredSpinner from "components/CenteredSpinner/CenteredSpinner";
import NotificationBadge from "components/NotificationBadge";
import TextBody from "components/TextBody";
import { messageFilterToRequest } from "features/messages/constants";
import CreateGroupChat from "features/messages/groupchats/CreateGroupChat";
import GroupChatListItem from "features/messages/groupchats/GroupChatListItem";
import MyPublicTripsMessages from "features/messages/MyPublicTripsMessages";
import HostRequestListItem from "features/messages/requests/HostRequestListItem";
import useMessageListsAutoRefetch from "features/messages/useMessageListsAutoRefetch";
import { messageThreadsListKey } from "features/queryKeys";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { MESSAGES } from "i18n/namespaces";
import Link from "next/link";
import { useRouter } from "next/router";
import { ListMessageThreadsRes, MessageThread } from "proto/conversations_pb";
import React from "react";
import { MessageFilterType, messageTypeStrings, routeToGroupChat, routeToHostRequest } from "routes";
import { service } from "service";
import { theme } from "theme";
import useOnVisibleEffect from "utils/useOnVisibleEffect";
 
import useNotifications from "../useNotifications";
 
const PAGE_SIZE = 25;
 
const StyledWrapper = styled("div")(() => ({
  padding: theme.spacing(0, 2),
}));
 
const StyledList = styled(List)(() => ({
  width: "100%",
}));
 
const StyledCreateGroupChatButton = styled(CreateGroupChat)(({ theme }) => ({
  marginBottom: theme.spacing(1.5),
  marginInline: `-${theme.spacing(2)}`,
  "& .MuiListItemButton-root": {
    padding: theme.spacing(0.75),
    paddingLeft: theme.spacing(2),
    paddingRight: theme.spacing(2),
    borderRadius: theme.shape.borderRadius,
    border: "1px dashed var(--mui-palette-grey-400)",
    backgroundColor: "var(--mui-palette-background-paper)",
    [theme.breakpoints.up("md")]: {
      padding: theme.spacing(1),
      paddingLeft: theme.spacing(2),
      paddingRight: theme.spacing(2),
    },
    "&:hover": {
      backgroundColor: "var(--mui-palette-grey-100)",
      borderColor: "var(--mui-palette-grey-600)",
    },
  },
  "& .MuiListItemAvatar-root": {
    minWidth: 40,
    marginLeft: 0,
    [theme.breakpoints.up("md")]: {
      minWidth: 56,
    },
  },
}));
 
const StyledGroupChatListItem = styled(GroupChatListItem)(() => ({
  marginInline: `-${theme.spacing(2)}`,
  paddingInline: `${theme.spacing(2)}`,
}));
 
const StyledHostRequestListItem = styled(HostRequestListItem)(() => ({
  marginInline: `-${theme.spacing(2)}`,
  paddingInline: `${theme.spacing(2)}`,
}));
 
const StyledFilterContainer = styled("div")(() => ({
  display: "flex",
  gap: theme.spacing(1),
  marginTop: theme.spacing(2),
  marginBottom: theme.spacing(2),
  flexWrap: "wrap",
}));
 
// clicking the overflow menu / its items shouldn't navigate into the thread
function guardMenuNavigation(e: React.MouseEvent) {
  const target = e.target as HTMLElement;
  if (target.closest("button") || target.closest('[role="menu"]')) {
    e.preventDefault();
  }
}
 
export default function AllMessagesTab() {
  const { t } = useTranslation(MESSAGES);
  const router = useRouter();
  const { data: notifications } = useNotifications();
  const isPublicTripsEnabled = useFeatureValue("public_trips_enabled", false);
 
  useMessageListsAutoRefetch();
 
  // Get filter from URL path, default to "all"
  const slugs =
    typeof router.query.slug === "undefined"
      ? ["all"]
      : typeof router.query.slug === "string"
        ? [router.query.slug]
        : router.query.slug;
 
  const filterFromPath = slugs[0] as MessageFilterType;
  const filter: MessageFilterType =
    messageTypeStrings.includes(filterFromPath) && (filterFromPath !== "public-trips" || isPublicTripsEnabled)
      ? filterFromPath
      : "all";
 
  const showArchived = filter === "archived";
  const isGroupedView = filter === "public-trips";
  const { categories, onlyUnread, onlyArchived } = messageFilterToRequest(filter);
 
  const handleFilterChange = (newFilter: MessageFilterType) => {
    router.push(`/messages/${newFilter}`);
  };
 
  const { data, isLoading, error, hasNextPage, fetchNextPage, isFetchingNextPage } = useInfiniteQuery<
    ListMessageThreadsRes.AsObject,
    RpcError
  >({
    queryKey: messageThreadsListKey(filter),
    queryFn: ({ pageParam }) =>
      service.conversations.listMessageThreads({
        categories,
        onlyUnread,
        onlyArchived,
        pageToken: pageParam as string | undefined,
        pageSize: PAGE_SIZE,
      }),
    getNextPageParam: (lastPage) => (lastPage.nextPageToken ? lastPage.nextPageToken : undefined),
    initialPageParam: undefined,
    enabled: !isGroupedView,
  });
 
  const threads = data?.pages.flatMap((page) => page.threadsList) ?? [];
 
  const { ref: loadMoreRef } = useOnVisibleEffect(hasNextPage && !isFetchingNextPage ? fetchNextPage : undefined);
 
  // Unread badge counts (role-based, from the ping). hosting + surfing already
  // include public-trip offers, so "all" is chats + hosting + surfing.
  const unseenChatsCount = notifications?.unseenMessageCount ?? 0;
  const unseenHostingCount = notifications?.unseenHostingHostRequestCount ?? 0;
  const unseenSurfingCount = notifications?.unseenSurfingHostRequestCount ?? 0;
  const unseenPublicTripsCount = notifications?.unseenPublicTripOfferCount ?? 0;
  const unseenAllCount = unseenChatsCount + unseenHostingCount + unseenSurfingCount;
 
  const renderThread = (thread: MessageThread.AsObject) => {
    if (thread.groupChat) {
      return (
        <Link
          key={`chat-${thread.groupChat.groupChatId}`}
          href={routeToGroupChat(thread.groupChat.groupChatId)}
          onClick={guardMenuNavigation}
        >
          <StyledGroupChatListItem groupChat={thread.groupChat} isArchived={showArchived} />
        </Link>
      );
    }
    if (thread.hostRequest) {
      return (
        <Link
          key={`request-${thread.hostRequest.hostRequestId}`}
          href={routeToHostRequest(thread.hostRequest.hostRequestId)}
          onClick={guardMenuNavigation}
        >
          <StyledHostRequestListItem hostRequest={thread.hostRequest} isArchived={showArchived} />
        </Link>
      );
    }
    return null;
  };
 
  const emptyStateText = showArchived ? t("archive.no_archived_messages") : t("all_messages_tab.no_messages");
 
  let messagesContent;
  if (isGroupedView) {
    messagesContent = <MyPublicTripsMessages />;
  } else if (error) {
    messagesContent = <Alert severity="error">{error.message}</Alert>;
  } else if (isLoading) {
    messagesContent = <CenteredSpinner />;
  } else {
    messagesContent = (
      <StyledList>
        {threads.length === 0 ? <TextBody>{emptyStateText}</TextBody> : threads.map(renderThread)}
        {hasNextPage && (
          <div ref={loadMoreRef}>
            <CenteredSpinner />
          </div>
        )}
      </StyledList>
    );
  }
 
  return (
    <StyledWrapper>
      {!showArchived && !isGroupedView && <StyledCreateGroupChatButton />}
      <StyledFilterContainer>
        <NotificationBadge count={unseenAllCount}>
          <Chip
            label={t("all_messages_tab.filter.all")}
            onClick={() => handleFilterChange("all")}
            color={filter === "all" ? "primary" : "default"}
            variant={filter === "all" ? "filled" : "outlined"}
          />
        </NotificationBadge>
        <NotificationBadge count={unseenAllCount}>
          <Chip
            label={t("messages_page.tabs.unread")}
            onClick={() => handleFilterChange("unread")}
            color={filter === "unread" ? "primary" : "default"}
            variant={filter === "unread" ? "filled" : "outlined"}
          />
        </NotificationBadge>
        <NotificationBadge count={unseenChatsCount}>
          <Chip
            label={t("messages_page.tabs.chats")}
            onClick={() => handleFilterChange("chats")}
            color={filter === "chats" ? "primary" : "default"}
            variant={filter === "chats" ? "filled" : "outlined"}
          />
        </NotificationBadge>
        <NotificationBadge count={unseenHostingCount}>
          <Chip
            label={t("messages_page.tabs.hosting")}
            onClick={() => handleFilterChange("hosting")}
            color={filter === "hosting" ? "primary" : "default"}
            variant={filter === "hosting" ? "filled" : "outlined"}
          />
        </NotificationBadge>
        <NotificationBadge count={unseenSurfingCount}>
          <Chip
            label={t("messages_page.tabs.surfing")}
            onClick={() => handleFilterChange("surfing")}
            color={filter === "surfing" ? "primary" : "default"}
            variant={filter === "surfing" ? "filled" : "outlined"}
          />
        </NotificationBadge>
        {isPublicTripsEnabled && (
          <NotificationBadge count={unseenPublicTripsCount}>
            <Chip
              label={t("messages_page.tabs.public_trips")}
              onClick={() => handleFilterChange("public-trips")}
              color={filter === "public-trips" ? "primary" : "default"}
              variant={filter === "public-trips" ? "filled" : "outlined"}
            />
          </NotificationBadge>
        )}
        <Chip
          label={t("archive.archived")}
          onClick={() => handleFilterChange(filter === "archived" ? "all" : "archived")}
          color={filter === "archived" ? "primary" : "default"}
          variant={filter === "archived" ? "filled" : "outlined"}
        />
      </StyledFilterContainer>
      {messagesContent}
    </StyledWrapper>
  );
}