All files / app/features/auth CommunityGuidelines.tsx

88.09% Statements 37/42
61.53% Branches 8/13
100% Functions 6/6
87.8% Lines 36/41

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                2x 2x 2x 2x 2x   2x 2x 2x   2x 2x 2x 2x 2x 2x 2x   3x                                                 4x         11x 11x 11x 11x 11x           11x   3x     11x       11x   11x 2x 2x 2x                         11x           11x 3x     8x                                 16x                                                                 7x                                                            
import {
  Avatar,
  Checkbox,
  FormControl,
  FormControlLabel,
  FormHelperText,
  Typography,
  TypographyVariant,
} from "@mui/material";
import Alert from "components/Alert";
import Button from "components/Button";
import CenteredSpinner from "components/CenteredSpinner/CenteredSpinner";
import { communityGuidelinesQueryKey } from "features/queryKeys";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { AUTH, GLOBAL } from "i18n/namespaces";
import Sentry from "platform/sentry";
import { GetCommunityGuidelinesRes } from "proto/resources_pb";
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useQuery } from "react-query";
import { service } from "service";
import isGrpcError from "service/utils/isGrpcError";
import { useIsMounted, useSafeState } from "utils/hooks";
import makeStyles from "utils/makeStyles";
 
const useStyles = makeStyles((theme) => ({
  grid: {
    display: "grid",
    gridTemplateColumns: "auto 1fr",
    gap: theme.spacing(2, 2),
  },
  avatar: {
    backgroundColor: theme.palette.grey[300],
    "& img": {
      fill: "none",
      width: "2rem",
      objectFit: "unset",
    },
  },
  button: {
    marginBlockStart: theme.spacing(2),
  },
}));
 
interface CommunityGuidelinesProps {
  onSubmit: (accept: boolean) => Promise<void>;
  className?: string;
  title?: TypographyVariant;
}
 
export default function CommunityGuidelines({
  onSubmit,
  className,
  title,
}: CommunityGuidelinesProps) {
  const { t } = useTranslation([AUTH, GLOBAL]);
  const classes = useStyles();
  const isMounted = useIsMounted();
  const [completed, setCompleted] = useSafeState(isMounted, false);
  const [error, setError] = useState("");
 
  const {
    data,
    error: loadError,
    isLoading,
  } = useQuery<GetCommunityGuidelinesRes.AsObject, RpcError>({
    queryKey: communityGuidelinesQueryKey,
    queryFn: () => service.resources.getCommunityGuidelines(),
  });
 
  const { control, handleSubmit, formState } = useForm({
    mode: "onChange",
  });
 
  const { errors } = formState;
 
  const submit = handleSubmit(async () => {
    try {
      await onSubmit(true);
      setCompleted(true);
    } catch (e) {
      Sentry.captureException(e, {
        tags: {
          component: "component/communityGuidelines",
        },
      });
      Iif (isGrpcError(e)) {
        setError(isGrpcError(e) ? e.message : t("global:error.fatal_message"));
      }
    }
  });
 
  Iif (loadError) {
    // Re-throw error to trigger error boundary to encourage user to report it
    // if we can't load stuff
    throw loadError;
  }
 
  if (isLoading) {
    return <CenteredSpinner />;
  }
 
  Iif (!data) {
    return null;
  }
 
  return (
    <>
      <form onSubmit={submit} className={className}>
        {title && (
          <Typography variant={title} gutterBottom>
            {t("auth:community_guidelines_form.header")}
          </Typography>
        )}
        {error && <Alert severity="error">{error}</Alert>}
 
        <div className={classes.grid}>
          {data.communityGuidelinesList.map(
            ({ title, guideline, iconSvg }, index) => (
              <React.Fragment key={index}>
                <Avatar
                  className={classes.avatar}
                  src={`data:image/svg+xml,${encodeURIComponent(iconSvg)}`}
                />
                <div>
                  <Typography variant="h3" color="primary">
                    {title}
                  </Typography>
                  <Typography variant="body1">{guideline}</Typography>
                  <Controller
                    control={control}
                    name={`ok${index}`}
                    defaultValue={false}
                    rules={{
                      required: t(
                        "auth:community_guidelines_form.guideline.required_error"
                      ),
                    }}
                    render={({ field }) => (
                      <FormControl variant="standard">
                        <FormControlLabel
                          label={
                            <Typography variant="body1">
                              {t(
                                "auth:community_guidelines_form.guideline.checkbox_label"
                              )}
                            </Typography>
                          }
                          control={
                            <Checkbox
                              {...field}
                              checked={field.value}
                              onChange={(_, checked) => field.onChange(checked)}
                            />
                          }
                        />
 
                        {errors?.[`ok${index}`]?.message && (
                          <FormHelperText error={true}>
                            {String(errors[`ok${index}`]?.message)}
                          </FormHelperText>
                        )}
                      </FormControl>
                    )}
                  />
                </div>
              </React.Fragment>
            )
          )}
        </div>
 
        <Button
          onClick={submit}
          disabled={completed || !formState.isValid}
          className={classes.button}
        >
          {completed ? t("global:thanks") : t("global:continue")}
        </Button>
      </form>
    </>
  );
}