All files / app/components/ContributorForm ContributorForm.tsx

88.09% Statements 37/42
80% Branches 16/20
91.66% Functions 11/12
87.17% Lines 34/39

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                        3x 3x 3x 3x         3x 3x 3x 3x                                   3x                     10x                                         3x       37x     37x         37x   6x 6x   1x 1x               6x                   54x         6x       37x 6x     37x 37x   37x                                           66x 66x 66x                                                                           33x               1x       99x                                   297x           297x                                                                                                                                                  
import {
  Checkbox,
  Collapse,
  FormControl,
  FormControlLabel,
  FormGroup,
  FormHelperText,
  FormLabel,
  makeStyles,
  Radio,
  RadioGroup,
  Typography,
} from "@material-ui/core";
import Alert from "components/Alert";
import Button from "components/Button";
import TextField from "components/TextField";
import { RpcError } from "grpc-web";
import {
  ContributeOption,
  ContributorForm as ContributorFormPb,
} from "proto/auth_pb";
import { useRef } from "react";
import { Controller, useForm } from "react-hook-form";
import { useMutation } from "react-query";
 
import {
  CONTRIBUTE_LABEL,
  CONTRIBUTE_OPTIONS,
  CONTRIBUTE_WAYS_LABEL,
  CONTRIBUTE_WAYS_OPTIONS,
  EXPERIENCE_HELPER,
  EXPERIENCE_LABEL,
  EXPERTISE_HELPER,
  EXPERTISE_LABEL,
  FEATURES_HELPER,
  FEATURES_LABEL,
  IDEAS_HELPER,
  IDEAS_LABEL,
  QUESTIONS_OPTIONAL,
  SUBMIT,
  SUCCESS_MSG,
} from "./constants";
 
type ContributorInputs = {
  ideas: string;
  features: string;
  experience: string;
  contribute: string;
  contributeWays: Record<string, boolean>;
  expertise: string;
};
 
const useStyles = makeStyles((theme) => ({
  contributeRadio: {
    marginBlockEnd: theme.spacing(3),
  },
  label: { display: "block" },
  textbox: {
    marginBlockEnd: theme.spacing(3),
    marginBlockStart: theme.spacing(1),
  },
  radioLabel: {
    ...theme.typography.body1,
    color: theme.palette.text.primary,
    marginBlockEnd: theme.spacing(1),
  },
}));
 
interface ContributorFormProps {
  processForm: (form: ContributorFormPb.AsObject) => Promise<void>;
  autofocus?: boolean;
}
 
export default function ContributorForm({
  processForm,
  autofocus = false,
}: ContributorFormProps) {
  const classes = useStyles();
 
  const { control, register, handleSubmit, errors, watch } =
    useForm<ContributorInputs>({
      mode: "onBlur",
      shouldUnregister: false,
    });
 
  const mutation = useMutation<void, RpcError, ContributorInputs>(
    async (data) => {
      let contribute = ContributeOption.CONTRIBUTE_OPTION_UNSPECIFIED;
      switch (data.contribute) {
        case "Yes":
          contribute = ContributeOption.CONTRIBUTE_OPTION_YES;
          break;
        case "Maybe":
          contribute = ContributeOption.CONTRIBUTE_OPTION_MAYBE;
          break;
        case "No":
          contribute = ContributeOption.CONTRIBUTE_OPTION_NO;
          break;
      }
      const form = new ContributorFormPb()
        .setIdeas(data.ideas)
        .setFeatures(data.features)
        .setExperience(data.experience)
        .setContribute(contribute)
        .setContributeWaysList(
          Object.entries(data.contributeWays).reduce<string[]>(
            //contributeWays is an object of "ways" as keys, and "checked" booleans as values
            //this reduces it to an array of the "ways" which were keys with "true" as a value
            (previous, [contributeWay, checked]) =>
              checked ? [...previous, contributeWay] : previous,
            []
          )
        )
        .setExpertise(data.expertise);
      await processForm(form.toObject());
    }
  );
 
  const submit = handleSubmit((data: ContributorInputs) => {
    mutation.mutate(data);
  });
 
  const watchContribute = watch("contribute");
  const ideasInputRef = useRef<HTMLInputElement>();
 
  return (
    <>
      {mutation.error && (
        <Alert severity="error">{mutation.error.message || ""}</Alert>
      )}
      {mutation.isSuccess ? (
        <Typography variant="body1">{SUCCESS_MSG}</Typography>
      ) : (
        <form onSubmit={submit}>
          <Typography variant="body2" paragraph>
            {QUESTIONS_OPTIONAL}
          </Typography>
          <Typography
            variant="body1"
            htmlFor="ideas"
            component="label"
            className={classes.label}
          >
            {IDEAS_LABEL}
          </Typography>
          <TextField
            inputRef={(el: HTMLInputElement | null) => {
              if (!ideasInputRef.current && autofocus) el?.focus();
              if (el) ideasInputRef.current = el;
              register(el);
            }}
            id="ideas"
            margin="normal"
            name="ideas"
            helperText={IDEAS_HELPER}
            fullWidth
            multiline
            minRows={4}
            maxRows={6}
            className={classes.textbox}
          />
          <Typography
            variant="body1"
            htmlFor="features"
            component="label"
            className={classes.label}
          >
            {FEATURES_LABEL}
          </Typography>
          <TextField
            inputRef={register}
            id="features"
            margin="normal"
            name="features"
            helperText={FEATURES_HELPER}
            fullWidth
            multiline
            minRows={4}
            maxRows={6}
            className={classes.textbox}
          />
          <Controller
            id="contribute"
            control={control}
            name="contribute"
            defaultValue=""
            render={({ onChange, value }) => (
              <FormControl component="fieldset">
                <FormLabel component="legend" className={classes.radioLabel}>
                  {CONTRIBUTE_LABEL}
                </FormLabel>
                <RadioGroup
                  className={classes.contributeRadio}
                  row
                  name="contribute-radio"
                  onChange={(e, value) => onChange(value)}
                  value={value}
                >
                  {CONTRIBUTE_OPTIONS.map((option) => (
                    <FormControlLabel
                      key={option}
                      value={option}
                      control={<Radio />}
                      label={option}
                    />
                  ))}
                </RadioGroup>
              </FormControl>
            )}
          />
          <Collapse in={watchContribute !== undefined}>
            <FormControl component="fieldset">
              <FormLabel component="legend" className={classes.radioLabel}>
                {CONTRIBUTE_WAYS_LABEL}
              </FormLabel>
              <FormGroup>
                {CONTRIBUTE_WAYS_OPTIONS.map(({ name, description }) => (
                  <Controller
                    key={name}
                    control={control}
                    name={`contributeWays.${name}`}
                    defaultValue={false}
                    render={({ onChange, value }) => (
                      <FormControlLabel
                        value={name}
                        control={
                          <Checkbox
                            checked={value}
                            onChange={(e, checked) => onChange(checked)}
                          />
                        }
                        label={description}
                      />
                    )}
                  />
                ))}
              </FormGroup>
              <FormHelperText error={!!errors?.contributeWays?.message}>
                {errors?.contributeWays?.message ?? " "}
              </FormHelperText>
            </FormControl>
            <Typography
              variant="body1"
              htmlFor="expertise"
              component="label"
              className={classes.label}
            >
              {EXPERTISE_LABEL}
            </Typography>
            <TextField
              inputRef={register}
              id="expertise"
              margin="normal"
              name="expertise"
              helperText={errors?.expertise?.message ?? EXPERTISE_HELPER}
              error={!!errors?.expertise?.message}
              fullWidth
              multiline
              minRows={4}
              maxRows={6}
              className={classes.textbox}
            />
            <Typography
              variant="body1"
              htmlFor="experience"
              component="label"
              className={classes.label}
            >
              {EXPERIENCE_LABEL}
            </Typography>
            <TextField
              inputRef={register}
              id="experience"
              margin="normal"
              name="experience"
              helperText={EXPERIENCE_HELPER}
              fullWidth
              multiline
              minRows={4}
              maxRows={6}
              className={classes.textbox}
            />
          </Collapse>
          <Button
            onClick={submit}
            type="submit"
            loading={mutation.isLoading}
            fullWidth
          >
            {SUBMIT}
          </Button>
        </form>
      )}
    </>
  );
}