All files / app/features/auth CommunityGuidelines.tsx

88.63% Statements 39/44
61.53% Branches 8/13
100% Functions 8/8
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                  2x 2x 2x 2x 2x   2x 2x 2x   2x 2x 2x 2x 2x 2x               8x           16x                 8x       4x         11x 11x 11x 11x           11x   3x     11x       11x   11x 2x 2x 2x                         11x           11x 3x     8x                                 16x                                                               7x                                                          
import {
  Avatar,
  Checkbox,
  FormControl,
  FormControlLabel,
  FormHelperText,
  styled,
  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";
 
interface CommunityGuidelinesProps {
  onSubmit: (accept: boolean) => Promise<void>;
  className?: string;
  title?: TypographyVariant;
}
 
const StyledGrid = styled("div")(({ theme }) => ({
  display: "grid",
  gridTemplateColumns: "auto 1fr",
  gap: theme.spacing(2, 2),
}));
 
const StyledAvatar = styled(Avatar)(({ theme }) => ({
  backgroundColor: theme.palette.grey[300],
  "& img": {
    fill: "none",
    width: "2rem",
    objectFit: "unset",
  },
}));
 
const StyledButton = styled(Button)(({ theme }) => ({
  marginBlockStart: theme.spacing(2),
}));
 
export default function CommunityGuidelines({
  onSubmit,
  className,
  title,
}: CommunityGuidelinesProps) {
  const { t } = useTranslation([AUTH, GLOBAL]);
  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>}
 
        <StyledGrid>
          {data.communityGuidelinesList.map(
            ({ title, guideline, iconSvg }, index) => (
              <React.Fragment key={index}>
                <StyledAvatar
                  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>
            ),
          )}
        </StyledGrid>
 
        <StyledButton
          onClick={submit}
          disabled={completed || !formState.isValid}
        >
          {completed ? t("global:thanks") : t("global:continue")}
        </StyledButton>
      </form>
    </>
  );
}