All files / app/features/profile ProfileSheet.tsx

0% Statements 0/66
0% Branches 0/24
0% Functions 0/12
0% Lines 0/61

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { ArrowBack } from "@mui/icons-material";
import {
  Collapse,
  IconButton,
  Skeleton,
  styled,
  SwipeableDrawer,
} from "@mui/material";
import Snackbar from "components/Snackbar";
import BadgeDetail from "features/badges/BadgeDetail";
import GroupChatView from "features/messages/groupchats/GroupChatView";
import NewHostRequest from "features/profile/view/NewHostRequest";
import NewMessage from "features/profile/view/NewMessage";
import Overview from "features/profile/view/Overview";
import UserCard from "features/profile/view/UserCard";
import { useUser } from "features/userQueries/useUsers";
import { useTranslation } from "i18n";
import { CONNECTIONS, GLOBAL, PROFILE } from "i18n/namespaces";
import { useRouter } from "next/router";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { UserTab } from "routes";
import useIsScreenSizeOrSmaller from "utils/useIsScreenSizeOrSmaller";
 
import { ProfileUserProvider } from "./hooks/useProfileUser";
import { useProfileSheet } from "./ProfileSheetContext";
 
const iOS =
  typeof navigator !== "undefined" &&
  /iPad|iPhone|iPod/.test(navigator.userAgent);
 
const StyledDrawer = styled(SwipeableDrawer)({
  "& .MuiDrawer-paper": {
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    height: "90vh",
    display: "flex",
    flexDirection: "column",
    overflow: "hidden",
    backgroundColor: "var(--mui-palette-background-paper)",
  },
});
 
const Puller = styled("div")({
  width: 30,
  height: 6,
  backgroundColor: "var(--mui-palette-grey-300)",
  borderRadius: 3,
  position: "absolute",
  top: 8,
  left: "calc(50% - 15px)",
});
 
const SheetHeader = styled("div")(({ theme }) => ({
  display: "flex",
  justifyContent: "flex-end",
  padding: theme.spacing(1, 1, 0),
  minHeight: theme.spacing(4),
  flexShrink: 0,
  position: "relative",
  backgroundColor: "var(--mui-palette-background-paper)",
}));
 
const ScrollContent = styled("div")({
  overflowY: "auto",
  flexGrow: 1,
  WebkitOverflowScrolling: "touch",
});
 
const REQUEST_ID = "request";
 
function ProfileSheetSkeleton() {
  return (
    <ScrollContent>
      {/* Overview card */}
      <Skeleton
        variant="circular"
        width={120}
        height={120}
        sx={{ mx: "auto", mt: 2 }}
      />
      <Skeleton width="50%" height={32} sx={{ mx: "auto", mt: 1 }} />
      <Skeleton width="35%" height={20} sx={{ mx: "auto" }} />
      <Skeleton width="40%" height={20} sx={{ mx: "auto", mb: 2 }} />
      {/* Tab bar */}
      <Skeleton variant="rectangular" height={40} sx={{ mx: 2, mb: 1 }} />
      {/* Content lines */}
      <Skeleton width="90%" sx={{ mx: "auto", mt: 2 }} />
      <Skeleton width="80%" sx={{ mx: "auto" }} />
      <Skeleton width="85%" sx={{ mx: "auto" }} />
    </ScrollContent>
  );
}
 
export default function ProfileSheet() {
  const isMobile = useIsScreenSizeOrSmaller("mobile");
  const { t } = useTranslation([GLOBAL, PROFILE, CONNECTIONS]);
 
  const {
    openProfileUserId,
    closeProfileSheet,
    openGroupChatId,
    closeGroupChat,
    selectedBadgeId,
    closeBadge,
  } = useProfileSheet();
  const router = useRouter();
  const { data: user, isLoading } = useUser(openProfileUserId ?? undefined);
  const scrollRef = useRef<HTMLDivElement>(null);
  const [tab, setTab] = useState<UserTab>("about");
  const [isRequesting, setIsRequesting] = useState(false);
  const [isSuccessRequest, setIsSuccessRequest] = useState(false);
  const [isMessaging, setIsMessaging] = useState(false);
  const [isSuccessMessage, setIsSuccessMessage] = useState(false);
 
  useEffect(() => {
    setTab("about");
    setIsRequesting(false);
    setIsSuccessRequest(false);
    setIsMessaging(false);
    setIsSuccessMessage(false);
  }, [openProfileUserId]);
 
  useEffect(() => {
    const handleRouteChange = () => {
      // If the sheet pushed a history entry for the back-gesture handler,
      // replace it with a clean state now so the pushState cleanup effect
      // doesn't call history.back() and fight against the incoming navigation.
      Iif (window.history.state?.profileSheetOpen) {
        window.history.replaceState(null, "");
      }
      closeProfileSheet();
    };
    router.events.on("routeChangeStart", handleRouteChange);
    return () => router.events.off("routeChangeStart", handleRouteChange);
  }, [router.events, closeProfileSheet]);
 
  // On Android, the hardware back gesture triggers webview.goBack() in the native
  // layer. Push a history entry when the sheet opens so goBack() fires popstate
  // here instead of routing to the previous page.
  useEffect(() => {
    Iif (!isMobile || openProfileUserId === null) return;
 
    window.history.pushState({ profileSheetOpen: true }, "");
 
    const handlePopState = () => closeProfileSheet();
    window.addEventListener("popstate", handlePopState);
 
    return () => {
      window.removeEventListener("popstate", handlePopState);
      // Sheet closed via button — our pushed state is still on top, pop it.
      Iif (window.history.state?.profileSheetOpen) {
        window.history.back();
      }
    };
  }, [openProfileUserId, closeProfileSheet, isMobile]);
 
  useLayoutEffect(() => {
    Iif (isRequesting || isMessaging) {
      const el = scrollRef.current?.querySelector(`#${REQUEST_ID}`);
      el?.scrollIntoView();
    }
  }, [isRequesting, isMessaging]);
 
  Iif (!isMobile) return null;
 
  return (
    <StyledDrawer
      anchor="bottom"
      open={openProfileUserId !== null}
      onClose={closeProfileSheet}
      onOpen={() => {}}
      disableSwipeToOpen
      disableBackdropTransition={!iOS}
      disableDiscovery={iOS}
    >
      <SheetHeader>
        <Puller />
        {(openGroupChatId || selectedBadgeId) && (
          <IconButton
            onClick={selectedBadgeId ? closeBadge : closeGroupChat}
            aria-label={t("global:back")}
            size="small"
          >
            <ArrowBack />
          </IconButton>
        )}
      </SheetHeader>
      {openGroupChatId ? (
        <GroupChatView chatId={openGroupChatId} embedded />
      ) : selectedBadgeId ? (
        <ScrollContent sx={{ p: 2 }}>
          <BadgeDetail badgeId={selectedBadgeId} />
        </ScrollContent>
      ) : (
        <ScrollContent ref={scrollRef}>
          {isSuccessRequest && (
            <Snackbar severity="success">
              {t("profile:request_form.success")}
            </Snackbar>
          )}
          {isSuccessMessage && (
            <Snackbar severity="success">
              {t("profile:message_form.success")}
            </Snackbar>
          )}
          {isLoading && <ProfileSheetSkeleton />}
          {user && (
            <ProfileUserProvider user={user}>
              <Overview
                setIsRequesting={setIsRequesting}
                setIsMessaging={setIsMessaging}
                tab={tab}
                isInSheet
              />
              <UserCard
                tab={tab}
                onTabChange={setTab}
                top={
                  <>
                    <Collapse in={isRequesting}>
                      <NewHostRequest
                        setIsRequesting={setIsRequesting}
                        setIsRequestSuccess={setIsSuccessRequest}
                      />
                    </Collapse>
                    <Collapse in={isMessaging}>
                      <NewMessage
                        setIsMessaging={setIsMessaging}
                        setIsMessageSuccess={setIsSuccessMessage}
                      />
                    </Collapse>
                  </>
                }
              />
            </ProfileUserProvider>
          )}
        </ScrollContent>
      )}
    </StyledDrawer>
  );
}