All files / app/features FlagButton.tsx

83.33% Statements 40/48
52.38% Branches 11/21
78.57% Functions 11/14
85.1% Lines 40/47

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 25915x 15x 15x 15x 15x 15x 15x 15x     15x 15x 15x 15x 15x   15x                     972x               1342x   1342x             1342x   1342x 1342x 1342x 460x         1342x 462x 462x                   1342x 2x   2x       1342x             1342x   2x                                                       2x     1342x 2x 2x                                                       6x                                                   2x                                                       80x                               2x     2x                                                                                    
import { FormControl, IconButton, IconButtonProps, InputLabel, Portal, Select } from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import Alert from "components/Alert";
import Button from "components/Button";
import { Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle } from "components/Dialog";
import { FlagIcon } from "components/Icons";
import Snackbar from "components/Snackbar";
import TextField from "components/TextField";
import { Empty } from "google-protobuf/google/protobuf/empty_pb";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { GLOBAL } from "i18n/namespaces";
import React, { useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { service } from "service";
import { ReportInput } from "service/reporting";
import { theme } from "theme";
 
interface FlagButtonProps {
  contentRef: string;
  authorUser: string | number;
  ariaLabel?: string;
  className?: string;
  size?: IconButtonProps["size"];
  renderButton?: (onClick: (event: React.MouseEvent) => void) => React.ReactNode;
}
 
export default function FlagButton({
  contentRef,
  authorUser,
  ariaLabel,
  className,
  size = "large",
  renderButton,
}: FlagButtonProps) {
  const { t } = useTranslation(GLOBAL);
 
  const [isOpen, setIsOpen] = useState(false);
  const {
    control,
    handleSubmit,
    reset: resetForm,
    formState: { errors },
    watch,
  } = useForm<ReportInput>();
 
  const reason = watch("reason");
  const description = watch("description");
  const requiredReasons = useMemo(
    () => [t("report.flag.reason.other"), t("report.flag.reason.safety"), t("report.flag.reason.guidelines_breach")],
    [t],
  );
 
  // Reset errors when reason changes
  useEffect(() => {
    Eif (!requiredReasons.includes(reason)) {
      resetForm({ description: "", reason: "" }, { keepValues: true, keepErrors: false, keepDirty: false });
    }
  }, [reason, requiredReasons, resetForm]);
 
  const {
    data: report,
    error,
    isPending,
    mutate: reportContent,
    reset: resetMutation,
  } = useMutation<Empty, RpcError, ReportInput>({
    mutationFn: (formData) => service.reporting.reportContent({ ...formData, contentRef, authorUser }),
    onSuccess: () => {
      setIsOpen(false);
    },
  });
 
  const handleClose = (event: unknown, reason: "backdropClick" | "escapeKeyDown" | "button") => {
    if (reason !== "button") return;
    resetForm();
    resetMutation();
    setIsOpen(false);
  };
 
  const onSubmit = handleSubmit((data) => {
    // Use English version to send to backend
    const reasonMap: Record<string, string> = {
      [t("report.flag.reason.dating")]: t("report.flag.reason.dating", {
        lng: "en",
      }),
      [t("report.flag.reason.sexualized")]: t("report.flag.reason.sexualized", {
        lng: "en",
      }),
      [t("report.flag.reason.safety")]: t("report.flag.reason.safety", {
        lng: "en",
      }),
      [t("report.flag.reason.scam")]: t("report.flag.reason.scam", {
        lng: "en",
      }),
      [t("report.flag.reason.spam")]: t("report.flag.reason.spam", {
        lng: "en",
      }),
      [t("report.flag.reason.external")]: t("report.flag.reason.external", {
        lng: "en",
      }),
      [t("report.flag.reason.harassment")]: t("report.flag.reason.harassment", {
        lng: "en",
      }),
      [t("report.flag.reason.guidelines_breach")]: t("report.flag.reason.guidelines_breach", { lng: "en" }),
      [t("report.flag.reason.other")]: t("report.flag.reason.other", {
        lng: "en",
      }),
    };
 
    reportContent({ ...data, reason: reasonMap[data.reason] });
  });
 
  const handleButtonClick = (event: React.MouseEvent) => {
    event.preventDefault();
    setIsOpen(true);
  };
 
  return (
    <>
      {report && (
        <Portal>
          <Snackbar severity="success">{t("report.content.success_message")}</Snackbar>
        </Portal>
      )}
      {renderButton ? (
        renderButton(handleButtonClick)
      ) : (
        <IconButton
          aria-label={ariaLabel ?? t("report.flag.button_aria_label")}
          className={className}
          onClick={handleButtonClick}
          color="primary"
          size={size}
        >
          <FlagIcon />
        </IconButton>
      )}
      <Dialog
        aria-labelledby="content-reporter"
        open={isOpen}
        onClose={handleClose}
        onClick={(event) => {
          event.stopPropagation();
        }}
        onKeyDown={(event) => {
          event.stopPropagation();
        }}
      >
        <DialogTitle id="content-reporter">{t("report.flag.title")}</DialogTitle>
        <form onSubmit={onSubmit}>
          <DialogContent>
            {error && <Alert severity="error">{error.message}</Alert>}
            <DialogContentText>{t("report.flag.explainer")}</DialogContentText>
            <FormControl
              variant="outlined"
              fullWidth
              margin="normal"
              sx={{
                "& .MuiOutlinedInput-root": {
                  borderRadius: theme.shape.borderRadius * 3,
                },
              }}
            >
              <InputLabel htmlFor="content-report-reason">{t("report.flag.reason_label")}</InputLabel>
              <Controller
                control={control}
                defaultValue={""}
                rules={{
                  validate: (v) => !!v || t("report.flag.reason_required"),
                }}
                name="reason"
                render={({ field }) => (
                  <Select
                    {...field}
                    variant="outlined"
                    native
                    label={t("report.flag.reason_label")}
                    id="content-report-reason"
                    sx={{
                      "& + &": {
                        marginBlockStart: theme.spacing(2),
                      },
                    }}
                  >
                    {[
                      "",
                      t("report.flag.reason.dating"),
                      t("report.flag.reason.sexualized"),
                      t("report.flag.reason.safety"),
                      t("report.flag.reason.scam"),
                      t("report.flag.reason.spam"),
                      t("report.flag.reason.external"),
                      t("report.flag.reason.harassment"),
                      t("report.flag.reason.guidelines_breach"),
                      t("report.flag.reason.other"),
                    ].map((option) => (
                      <option value={option} key={option}>
                        {option}
                      </option>
                    ))}
                  </Select>
                )}
              />
            </FormControl>
            <Controller
              control={control}
              defaultValue={""}
              name="description"
              rules={{
                required: requiredReasons.includes(reason),
                validate: (value) => {
                  // Only require description if reason is in requiredReasons
                  Iif (requiredReasons.includes(reason)) {
                    return !!value || t("report.flag.description_required");
                  }
                  return true;
                },
              }}
              render={({ field }) => (
                <TextField
                  id="content-report-description"
                  {...field}
                  error={!!errors?.description?.message}
                  helperText={!errors?.description?.message ? t("report.flag.description_helper") : undefined}
                  label={t("report.flag.description_label")}
                  fullWidth
                  multiline
                  minRows={4}
                  maxRows={6}
                  sx={{
                    marginTop: theme.spacing(2),
                    "& + &": {
                      marginBlockStart: theme.spacing(2),
                    },
                  }}
                />
              )}
            />
          </DialogContent>
          <DialogActions>
            <Button onClick={() => handleClose({}, "button")} variant="outlined">
              {t("cancel")}
            </Button>
            <Button
              type="submit"
              disabled={!reason || (requiredReasons.includes(reason) && !description)}
              loading={isPending}
              onClick={onSubmit}
            >
              {t("submit")}
            </Button>
          </DialogActions>
        </form>
      </Dialog>
    </>
  );
}