All files / app/features/auth/signup Signup.tsx

98.24% Statements 56/57
55.26% Branches 21/38
87.5% Functions 7/8
100% Lines 54/54

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              1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x   1x       29x                   19x 32x 31x   31x 31x 31x   31x   31x 31x   31x   31x 16x     31x 17x     31x 17x 17x 2x 2x 2x       1x         1x     1x 1x   1x                     31x   2x               31x             31x   31x                                                                                                                                                                                                                                                                                        
import {
  alpha,
  Box,
  Container,
  Skeleton,
  styled,
  Typography,
} from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import Alert from "components/Alert";
import Avatar from "components/Avatar";
import CenteredSpinner from "components/CenteredSpinner/CenteredSpinner";
import HtmlMeta from "components/HtmlMeta";
import Redirect from "components/Redirect";
import StyledLink from "components/StyledLink";
import { RpcError } from "grpc-web";
import { Trans, useTranslation } from "i18n";
import { AUTH, GLOBAL } from "i18n/namespaces";
import { useRouter } from "next/router";
import { useIsNativeEmbed } from "platform/nativeLink";
import Sentry from "platform/sentry";
import { GetInviteCodeInfoRes } from "proto/auth_pb";
import { useEffect, useState } from "react";
import CouchersTextLogo from "resources/CouchersTextLogo";
import { dashboardRoute, loginRoute, signupRoute } from "routes";
import { service } from "service";
import isGrpcError from "service/utils/isGrpcError";
import { theme } from "theme";
import stringOrFirstString from "utils/stringOrFirstString";
 
import { useAuthContext } from "../AuthProvider";
import SignupFormContent from "./SignupFormContent";
 
const StyledMobileEmbed = styled("div")(({ theme }) => ({
  margin: theme.spacing(3),
}));
 
const StyledFormWrapper = styled("div")(({ theme }) => ({
  backgroundColor: alpha(theme.palette.primary.light, 0.1),
  borderRadius: theme.shape.borderRadius,
  padding: theme.spacing(2),
  width: "100%",
  maxWidth: "600px",
  border: `1px solid ${theme.palette.divider}`,
  marginTop: theme.spacing(2),
}));
 
export default function Signup() {
  const { t } = useTranslation([AUTH, GLOBAL]);
  const router = useRouter();
 
  const { authState, authActions } = useAuthContext();
  const authenticated = authState.authenticated;
  const error = authState.error;
 
  const [loading, setLoading] = useState(false);
 
  const urlToken = stringOrFirstString(router.query.token);
  const inviteCode = stringOrFirstString(router.query.code);
 
  const isNativeEmbed = useIsNativeEmbed();
 
  useEffect(() => {
    authActions.clearError();
  }, [authActions]);
 
  useEffect(() => {
    if (authState.error) window.scroll({ top: 0, behavior: "smooth" });
  }, [authState.error]);
 
  useEffect(() => {
    (async () => {
      if (urlToken) {
        setLoading(true);
        try {
          authActions.updateSignupState(
            await service.auth.signupFlowEmailToken(urlToken),
          );
        } catch (err) {
          Sentry.captureException(err, {
            tags: {
              component: "auth/signup/Signup",
            },
          });
          authActions.authError(
            isGrpcError(err) ? err.message : t("global:error.fatal_message"),
          );
          router.push(signupRoute);
          return;
        }
        setLoading(false);
      }
    })();
    // next-router-mock router isn't memoized, so putting router in the dependencies
    // causes infinite looping in tests
  }, [urlToken, authActions, t]); // eslint-disable-line react-hooks/exhaustive-deps
 
  const {
    data: inviteInfo,
    error: inviteInfoError,
    isPending: isInvitePending,
  } = useQuery<GetInviteCodeInfoRes.AsObject, RpcError>({
    queryKey: ["inviteCodeInfo", inviteCode],
    queryFn: () => service.auth.getInviteCodeInfo(inviteCode!),
    enabled: !!inviteCode,
    retry: false,
    staleTime: 1000 * 60 * 60, // 1h; invite creator data rarely changes
    refetchOnWindowFocus: false,
    refetchOnReconnect: false,
  });
 
  const inviter = inviteInfo
    ? {
        username: inviteInfo.username,
        name: inviteInfo.name || inviteInfo.username,
        avatarUrl: inviteInfo.avatarUrl,
      }
    : null;
  const inviteError = inviteInfoError?.message ?? null;
 
  Iif (isNativeEmbed) {
    return (
      <StyledMobileEmbed>
        {error && (
          <Alert severity="error" sx={{ width: "100%" }}>
            {error}
          </Alert>
        )}
        {inviter && inviteError && (
          <Alert severity="info" sx={{ width: "100%" }}>
            {t("global:error_loading_invite_codes")}
          </Alert>
        )}
        {inviteCode && !inviteError && (
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 1.5,
              padding: 1.25,
              border: `1px solid ${theme.palette.divider}`,
              borderRadius: 2,
              backgroundColor: theme.palette.background.paper,
              mb: 2,
            }}
          >
            {inviter && !isInvitePending && (
              <>
                <Avatar
                  user={{
                    username: inviter.username,
                    name: inviter.name,
                    avatarUrl: inviter.avatarUrl || "",
                  }}
                  highRes
                />
                <Typography>
                  {t("global:invited_you", { name: inviter.name })}
                </Typography>
              </>
            )}
 
            {inviter && isInvitePending && (
              <>
                <Skeleton variant="circular" sx={{ width: 48, height: 48 }} />
                <Skeleton variant="text" sx={{ width: "60%" }} />
              </>
            )}
          </Box>
        )}
        {loading ? (
          <CenteredSpinner />
        ) : (
          <SignupFormContent inviteCode={inviteCode || undefined} />
        )}
      </StyledMobileEmbed>
    );
  }
 
  return (
    <>
      {authenticated && <Redirect to={dashboardRoute} />}
      <HtmlMeta title={t("global:sign_up")} />
      <Container
        component="section"
        maxWidth="lg"
        sx={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          padding: theme.spacing(2),
          height: "100%",
        }}
      >
        <CouchersTextLogo />
        <StyledFormWrapper>
          {error && (
            <Alert severity="error" sx={{ width: "100%" }}>
              {error}
            </Alert>
          )}
          {inviteError && (
            <Alert severity="error" sx={{ width: "100%" }}>
              {t("global:error_loading_invite_codes")}
            </Alert>
          )}
          {inviteCode && !inviteError && (
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1.5,
                padding: 1.25,
                border: `1px solid ${theme.palette.divider}`,
                borderRadius: 2,
                backgroundColor: theme.palette.background.paper,
                mb: 2,
              }}
            >
              {inviter && !isInvitePending && (
                <>
                  <Avatar
                    user={{
                      username: inviter.username,
                      name: inviter.name,
                      avatarUrl: inviter.avatarUrl || "",
                    }}
                    highRes
                  />
                  <Typography>
                    {t("global:invited_you", { name: inviter.name })}
                  </Typography>
                </>
              )}
 
              {isInvitePending && (
                <>
                  <Skeleton variant="circular" sx={{ width: 48, height: 48 }} />
                  <Skeleton variant="text" sx={{ width: "60%" }} />
                </>
              )}
            </Box>
          )}
          {loading ? (
            <CenteredSpinner />
          ) : (
            <SignupFormContent inviteCode={inviteCode || undefined} />
          )}
          <Typography sx={{ marginTop: theme.spacing(2) }}>
            <Trans i18nKey="auth:basic_sign_up_form.existing_user_prompt">
              Already have an account?{" "}
              <StyledLink href={loginRoute}>Log in</StyledLink>
            </Trans>
          </Typography>
        </StyledFormWrapper>
      </Container>
    </>
  );
}