All files / app/components/ContributorForm ContributorForm.tsx

79.48% Statements 31/39
61.11% Branches 11/18
90% Functions 9/10
83.33% Lines 30/36

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                      3x 3x 3x 3x 3x         3x 3x 3x 3x                                   3x                     6x                                         8x       12x               12x         12x   4x 4x   1x 1x               4x                   36x         4x       12x 4x     12x 12x                                                                                                                                             1x       27x                                   81x                       2x                                                                                                                                    
import {
  Checkbox,
  Collapse,
  FormControl,
  FormControlLabel,
  FormGroup,
  FormHelperText,
  FormLabel,
  Radio,
  RadioGroup,
  Typography,
} from "@mui/material";
import makeStyles from "@mui/styles/makeStyles";
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,
    watch,
    formState: { errors },
  } = 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
            id="ideas"
            {...register("ideas")}
            inputRef={(el: HTMLInputElement | null) => {
              Iif (!ideasInputRef.current && autofocus) el?.focus();
              Iif (el) ideasInputRef.current = el;
            }}
            margin="normal"
            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
            id="features"
            {...register("features")}
            margin="normal"
            helperText={FEATURES_HELPER}
            fullWidth
            multiline
            minRows={4}
            maxRows={6}
            className={classes.textbox}
          />
          <Controller
            control={control}
            name="contribute"
            defaultValue=""
            render={({ field }) => (
              <FormControl variant="standard" component="fieldset">
                <FormLabel component="legend" className={classes.radioLabel}>
                  {CONTRIBUTE_LABEL}
                </FormLabel>
                <RadioGroup
                  id="contribute"
                  {...field}
                  className={classes.contributeRadio}
                  row
                  name="contribute-radio"
                  onChange={(e, value) => field.onChange(value)}
                  value={field.value}
                >
                  {CONTRIBUTE_OPTIONS.map((option) => (
                    <FormControlLabel
                      key={option}
                      value={option}
                      control={<Radio />}
                      label={option}
                    />
                  ))}
                </RadioGroup>
              </FormControl>
            )}
          />
          <Collapse in={watchContribute !== undefined}>
            <FormControl variant="standard" 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={({ field }) => (
                      <FormControlLabel
                        value={name}
                        control={
                          <Checkbox
                            {...field}
                            checked={field.value}
                            onChange={(e, checked) => field.onChange(checked)}
                          />
                        }
                        label={description}
                      />
                    )}
                  />
                ))}
              </FormGroup>
              <FormHelperText error={!!errors?.contributeWays?.message}>
                {errors?.contributeWays?.message?.toString() ?? " "}
              </FormHelperText>
            </FormControl>
            <Typography
              variant="body1"
              htmlFor="expertise"
              component="label"
              className={classes.label}
            >
              {EXPERTISE_LABEL}
            </Typography>
            <TextField
              id="expertise"
              {...register("expertise")}
              margin="normal"
              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
              id="experience"
              {...register("experience")}
              margin="normal"
              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>
      )}
    </>
  );
}