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

95.16% Statements 59/62
82.85% Branches 29/35
95.45% Functions 21/22
96.55% Lines 56/58

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                    2x 2x 2x 2x     2x 2x 2x 2x   2x 2x   2x 2x 2x 2x 2x 2x 2x 2x           2x                           17x                         2x 73x 73x 73x     73x           73x 73x   73x                     4x                           3x       4x     4x         73x   4x             6x       73x   73x   73x                                               146x 146x 146x             19x     19x                                           20x                                               10x                               10x     304x     231x 231x                                                             84x   11x                                                                     84x               11x                                                                         73x   11x                           73x                                                      
import {
  Checkbox,
  FormControl,
  FormControlLabel,
  FormHelperText,
  FormLabel,
  InputLabel,
  Radio,
  RadioGroup,
  Typography,
} from "@material-ui/core";
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 } 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";
 
type SignupAccountInputs = {
  username: string;
  password: string;
  name: string;
  birthdate: Dayjs;
  gender: string;
  acceptTOS: boolean;
  optInToNewsletter: boolean;
  hostingStatus: HostingStatus;
  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, errors, watch } =
    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
      Iif (errors.location) window.scroll({ top: 0, behavior: "smooth" });
    }
  );
 
  const acceptTOS = watch("acceptTOS");
 
  const usernameInputRef = useRef<HTMLInputElement>();
 
  return (
    <>
      {errors.location && (
        //@ts-ignore - we register "location" but rhf thinks the error should be
        //under location.address
        <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
          className={authClasses.formField}
          variant="standard"
          id="username"
          name="username"
          fullWidth
          inputRef={(el: HTMLInputElement | null) => {
            if (!usernameInputRef.current) el?.focus();
            if (el) usernameInputRef.current = el;
            register(el, {
              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")
                );
              },
            });
          }}
          helperText={errors?.username?.message ?? " "}
          error={!!errors?.username?.message}
        />
        <InputLabel className={authClasses.formLabel} htmlFor="password">
          {t("auth:account_form.password.field_label")}
        </InputLabel>
        <TextField
          className={authClasses.formField}
          variant="standard"
          type="password"
          id="password"
          name="password"
          fullWidth
          inputRef={register({
            required: t("auth:account_form.password.required_error"),
            validate: (password) =>
              validatePassword(password) ||
              t("auth:account_form.password.validation_error"),
          })}
          helperText={errors?.password?.message ?? " "}
          error={!!errors?.password?.message}
        />
        <InputLabel className={authClasses.formLabel} htmlFor="birthdate">
          {t("auth:account_form.birthday.field_label")}
        </InputLabel>
        <Datepicker
          className={authClasses.formField}
          control={control}
          error={
            //@ts-ignore Dayjs type breaks this
            !!errors?.birthdate?.message
          }
          helperText={
            //@ts-ignore
            errors?.birthdate?.message ?? " "
          }
          id="birthdate"
          rules={{
            required: t("auth:account_form.birthday.required_error"),
            validate: (stringDate) =>
              validatePastDate(stringDate) ||
              t("auth:account_form.birthday.validation_error"),
          }}
          minDate={new Date(1899, 12, 1)}
          name="birthdate"
          openTo="year"
        />
        <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={({ onChange }) => (
          <EditLocationMap
            className={classes.locationMap}
            updateLocation={(location) => {
              if (location) {
                onChange({
                  address: location.address,
                  lat: location.lat,
                  lng: location.lng,
                  radius: location.radius,
                });
              } else E{
                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 className={authClasses.formField}>
          {errors?.hostingStatus?.message && (
            <FormHelperText error>
              {errors.hostingStatus.message}
            </FormHelperText>
          )}
          <Controller
            control={control}
            defaultValue={""}
            rules={{ required: t("global:required") }}
            name="hostingStatus"
            render={({ onChange, value }) => (
              <Select
                onChange={(event) => {
                  onChange(Number.parseInt(event.target.value as string) || "");
                }}
                value={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
          id="gender"
          control={control}
          name="gender"
          defaultValue=""
          rules={{ required: t("auth:account_form.gender.required_error") }}
          render={({ onChange, value }) => (
            <FormControl component="fieldset">
              <FormLabel component="legend" className={authClasses.formLabel}>
                {t("auth:account_form.gender.field_label")}
              </FormLabel>
              <RadioGroup
                row
                aria-label="gender"
                name="gender-radio"
                onChange={(e, value) => onChange(value)}
                value={value}
              >
                <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={({ onChange, value }) => (
                <Checkbox
                  value={value}
                  onChange={(event) => onChange(event.target.checked)}
                />
              )}
            />
          }
          label={t("auth:account_form.tos_accept_label")}
        />
        <FormControlLabel
          control={
            <Controller
              control={control}
              name="optInToNewsletter"
              defaultValue={true}
              render={({ onChange, value }) => (
                <Checkbox
                  value={value}
                  defaultChecked={true}
                  onChange={(event) => onChange(event.target.checked)}
                />
              )}
            />
          }
          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>
    </>
  );
}