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

90.47% Statements 57/63
75.75% Branches 25/33
93.33% Functions 14/15
93.22% Lines 55/59

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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415                    2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x           2x                                 11x                         11x 144x 144x 144x                 144x           144x 144x   144x                     3x                           2x       3x     3x         144x   3x             8x       144x   144x   144x 107x                                                           21x     21x                                               22x                                             114x 114x   114x 93x     21x 2x     19x       19x                                     11x               254x 254x                                                                 12x                                                                                                                                                                                                                                      
import {
  Checkbox,
  FormControl,
  FormControlLabel,
  FormHelperText,
  FormLabel,
  InputLabel,
  Radio,
  RadioGroup,
  Typography,
} from "@mui/material";
import Alert from "components/Alert";
import Button from "components/Button";
import Datepicker from "components/Datepicker";
import EditLocationMap, {
  ApproximateLocation,
} from "components/EditLocationMap";
import Select from "components/Select";
import TextField from "components/TextField";
import TOSLink from "components/TOSLink";
import dayjs, { Dayjs } from "dayjs";
import { useAuthContext } from "features/auth/AuthProvider";
import useAuthStyles from "features/auth/useAuthStyles";
import { RpcError } from "grpc-web";
import { Trans, useTranslation } from "i18n";
import { AUTH, GLOBAL } from "i18n/namespaces";
import { HostingStatus } from "proto/api_pb";
import { useRef } from "react";
import { Controller, useForm } from "react-hook-form";
import { useMutation } from "react-query";
import { service } from "service";
import makeStyles from "utils/makeStyles";
import {
  lowercaseAndTrimField,
  usernameValidationPattern,
  validatePassword,
  validatePastDate,
} from "utils/validation";
 
export type SignupAccountInputs = {
  username: string;
  password: string;
  name: string;
  birthdate: Dayjs;
  gender: string;
  acceptTOS: boolean;
  optInToNewsletter: boolean;
  hostingStatus:
    | HostingStatus.HOSTING_STATUS_CAN_HOST
    | HostingStatus.HOSTING_STATUS_MAYBE
    | HostingStatus.HOSTING_STATUS_CANT_HOST;
  location: ApproximateLocation;
};
 
const useStyles = makeStyles((theme) => ({
  locationMap: {
    "&&": { marginBottom: theme.spacing(2) },
    width: "100%",
  },
  firstForm: {
    paddingBottom: 0,
  },
  errorAlert: {
    marginTop: theme.spacing(2),
  },
}));
 
export default function AccountForm() {
  const { t } = useTranslation([AUTH, GLOBAL]);
  const { authState, authActions } = useAuthContext();
  const authLoading = authState.loading;
 
  const {
    control,
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<SignupAccountInputs>({
    defaultValues: { location: { address: "" } },
    mode: "onBlur",
    shouldUnregister: false,
  });
 
  const classes = useStyles();
  const authClasses = useAuthStyles();
 
  const mutation = useMutation<void, RpcError, SignupAccountInputs>(
    async ({
      username,
      password,
      birthdate,
      gender,
      acceptTOS,
      optInToNewsletter,
      hostingStatus,
      location,
    }) => {
      const state = await service.auth.signupFlowAccount({
        flowToken: authState.flowState!.flowToken,
        username: lowercaseAndTrimField(username),
        password: password,
        birthdate: birthdate.format().split("T")[0],
        gender,
        acceptTOS,
        optOutOfNewsletter: !optInToNewsletter,
        hostingStatus,
        city: location.address,
        lat: location.lat,
        lng: location.lng,
        radius: location.radius,
      });
      authActions.updateSignupState(state);
    },
    {
      onMutate() {
        authActions.clearError();
      },
      onSettled() {
        window.scroll({ top: 0, behavior: "smooth" });
      },
    }
  );
 
  const submit = handleSubmit(
    (data: SignupAccountInputs) => {
      mutation.mutate({
        ...data,
        username: lowercaseAndTrimField(data.username),
      });
    },
    () => {
      //location won't focus on error, so scroll to the top
      if (errors.location) window.scroll({ top: 0, behavior: "smooth" });
    }
  );
 
  const acceptTOS = watch("acceptTOS");
 
  const usernameInputRef = useRef<HTMLInputElement>();
 
  const handleBirthdateChange = (newBirthdate: Dayjs) => {
    setValue("birthdate", newBirthdate, {
      shouldDirty: true,
      shouldValidate: true,
    });
  };
 
  return (
    <>
      {errors.location && (
        <Alert severity="error">{errors.location?.message || ""}</Alert>
      )}
      {mutation.error && (
        <Alert severity="error">{mutation.error.message || ""}</Alert>
      )}
      <form
        className={`${authClasses.form} ${classes.firstForm}`}
        onSubmit={submit}
      >
        <InputLabel className={authClasses.formLabel} htmlFor="username">
          {t("auth:account_form.username.field_label")}
        </InputLabel>
        <TextField
          id="username"
          {...register("username", {
            pattern: {
              message: t("auth:account_form.username.validation_error"),
              value: usernameValidationPattern,
            },
            required: t("auth:account_form.username.required_error"),
            validate: async (username: string) => {
              const valid = await service.auth.validateUsername(
                lowercaseAndTrimField(username)
              );
              return (
                valid || t("auth:account_form.username.username_taken_error")
              );
            },
          })}
          className={authClasses.formField}
          variant="standard"
          fullWidth
          inputRef={(el: HTMLInputElement | null) => {
            Iif (!usernameInputRef.current) el?.focus();
            Iif (el) usernameInputRef.current = el;
          }}
          helperText={errors?.username?.message ?? " "}
          error={!!errors?.username?.message}
          autoComplete="username"
        />
        <InputLabel className={authClasses.formLabel} htmlFor="password">
          {t("auth:account_form.password.field_label")}
        </InputLabel>
        <TextField
          id="password"
          {...register("password", {
            required: t("auth:account_form.password.required_error"),
            validate: (password) =>
              validatePassword(password) ||
              t("auth:account_form.password.validation_error"),
          })}
          className={authClasses.formField}
          variant="standard"
          type="password"
          fullWidth
          helperText={errors?.password?.message ?? " "}
          error={!!errors?.password?.message}
          autoComplete="new-password"
        />
        <InputLabel className={authClasses.formLabel} htmlFor="birthdate">
          {t("auth:account_form.birthday.field_label")}
        </InputLabel>
        <Datepicker
          className={authClasses.formField}
          control={control}
          error={!!errors?.birthdate?.message}
          helperText={errors?.birthdate?.message}
          id="birthdate"
          rules={{
            required: t("auth:account_form.birthday.required_error"),
            validate: (stringBirthDate: string) => {
              const birthDate = dayjs(stringBirthDate);
              const age = Math.abs(dayjs().diff(birthDate, "year")); // confirmed dayjs does the difference correctyly by counting months and days
 
              if (age < 18) {
                return t("auth:account_form.birthday.too_young_error");
              }
 
              if (age > 120) {
                return t("auth:account_form.birthday.not_real_date_error");
              }
 
              Iif (!validatePastDate(stringBirthDate) || !stringBirthDate) {
                return t("auth:account_form.birthday.validation_error");
              }
 
              return true; // Validation passes
            },
          }}
          minDate={dayjs().subtract(120, "years")}
          maxDate={dayjs().subtract(18, "years")}
          defaultValue={null}
          openTo="year"
          name="birthdate"
          onPostChange={handleBirthdateChange}
        />
        <InputLabel className={authClasses.formLabel} htmlFor="location">
          {t("auth:location.field_label")}
        </InputLabel>
      </form>
      <Controller
        name="location"
        control={control}
        rules={{
          validate: (location) =>
            !!location.address || t("auth:location.validation_error"),
        }}
        render={({ field, fieldState: { error } }) => (
          <EditLocationMap
            inputFieldProps={field}
            inputFieldError={error}
            className={classes.locationMap}
            updateLocation={(location) => {
              if (location) {
                field.onChange({
                  address: location.address,
                  lat: location.lat,
                  lng: location.lng,
                  radius: location.radius,
                });
              } else E{
                field.onChange({
                  address: "",
                });
              }
            }}
          />
        )}
      />
      <form className={authClasses.form} onSubmit={submit}>
        <InputLabel className={authClasses.formLabel} htmlFor="hosting-status">
          {t("auth:account_form.hosting_status.field_label")}
        </InputLabel>
        <FormControl variant="standard" className={authClasses.formField}>
          {errors?.hostingStatus?.message && (
            <FormHelperText error>
              {errors.hostingStatus.message}
            </FormHelperText>
          )}
          <Controller
            control={control}
            rules={{ required: t("global:required") }}
            name="hostingStatus"
            render={({ field }) => (
              <Select
                {...field}
                onChange={(event) => {
                  field.onChange(
                    Number.parseInt(event.target.value as string) || ""
                  );
                }}
                value={field.value}
                id="hosting-status"
                fullWidth
                className={authClasses.formField}
                options={[
                  "",
                  HostingStatus.HOSTING_STATUS_CAN_HOST,
                  HostingStatus.HOSTING_STATUS_MAYBE,
                  HostingStatus.HOSTING_STATUS_CANT_HOST,
                ]}
                optionLabelMap={{
                  "": "",
                  [HostingStatus.HOSTING_STATUS_CAN_HOST]: t(
                    "auth:account_form.hosting_status.can_host"
                  ),
                  [HostingStatus.HOSTING_STATUS_MAYBE]: t(
                    "auth:account_form.hosting_status.maybe"
                  ),
                  [HostingStatus.HOSTING_STATUS_CANT_HOST]: t(
                    "auth:account_form.hosting_status.cant_host"
                  ),
                }}
              />
            )}
          />
        </FormControl>
        <Controller
          control={control}
          name="gender"
          defaultValue=""
          rules={{ required: t("auth:account_form.gender.required_error") }}
          render={({ field }) => (
            <FormControl variant="standard" component="fieldset">
              <FormLabel component="legend" className={authClasses.formLabel}>
                {t("auth:account_form.gender.field_label")}
              </FormLabel>
              <RadioGroup
                id="gender"
                {...field}
                row
                aria-label="gender"
                name="gender-radio"
              >
                <FormControlLabel
                  value="Woman"
                  control={<Radio />}
                  label={t("auth:account_form.gender.woman")}
                />
                <FormControlLabel
                  value="Man"
                  control={<Radio />}
                  label={t("auth:account_form.gender.man")}
                />
                <FormControlLabel
                  value="Non-binary"
                  control={<Radio />}
                  label={t("auth:account_form.gender.non_binary")}
                />
              </RadioGroup>
              <FormHelperText error={!!errors?.gender?.message}>
                {errors?.gender?.message ?? " "}
              </FormHelperText>
            </FormControl>
          )}
        />
        <Typography variant="body1">
          <Trans i18nKey="auth:account_form.tos_prompt">
            To continue, please read and accept the <TOSLink />.
          </Trans>
        </Typography>
        <FormControlLabel
          control={
            <Controller
              control={control}
              name="acceptTOS"
              defaultValue={false}
              render={({ field }) => <Checkbox {...field} />}
            />
          }
          label={t("auth:account_form.tos_accept_label")}
        />
        <FormControlLabel
          control={
            <Controller
              control={control}
              name="optInToNewsletter"
              defaultValue={true}
              render={({ field }) => (
                <Checkbox {...field} defaultChecked={true} />
              )}
            />
          }
          label={t("auth:account_form.opt_in_newsletter")}
        />
        <Button
          classes={{
            label: authClasses.buttonText,
            root: authClasses.button,
          }}
          onClick={submit}
          type="submit"
          loading={authLoading || mutation.isLoading}
          disabled={!acceptTOS}
          fullWidth
        >
          {t("global:sign_up")}
        </Button>
      </form>
    </>
  );
}