All files / app/features/auth CommunityGuidelines.tsx

97.36% Statements 37/38
72.22% Branches 13/18
100% Functions 7/7
97.29% Lines 36/37

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                  2x 2x 2x 2x   2x 2x 2x   2x 2x 2x 2x 2x 2x 2x   6x                                                 2x         37x 37x 37x 37x 37x           37x   6x     37x       37x 3x 3x 2x   1x         1x 1x         37x           37x                             62x                                       68x                       6x                                                            
import {
  Avatar,
  Checkbox,
  CircularProgress,
  FormControl,
  FormControlLabel,
  FormHelperText,
  Typography,
  TypographyVariant,
} from "@material-ui/core";
import Alert from "components/Alert";
import Button from "components/Button";
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",
    gridGap: 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, errors, formState } = useForm({
    mode: "onChange",
  });
 
  const submit = handleSubmit(async () => {
    try {
      await onSubmit(true);
      setCompleted(true);
    } catch (e) {
      Sentry.captureException(e, {
        tags: {
          component: "component/communityGuidelines",
        },
      });
      if (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;
  }
 
  return isLoading ? (
    <CircularProgress />
  ) : data ? (
    <>
      <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={({ onChange, value }) => (
                      <FormControl>
                        <FormControlLabel
                          label={
                            <Typography variant="body1">
                              {t(
                                "auth:community_guidelines_form.guideline.checkbox_label"
                              )}
                            </Typography>
                          }
                          control={
                            <Checkbox
                              checked={value}
                              onChange={(_, checked) => onChange(checked)}
                            />
                          }
                        />
 
                        {errors?.[`ok${index}`]?.message && (
                          <FormHelperText error={true}>
                            {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>
    </>
  ) : null;
}