All files / app/components/ImageInput ImageInput.tsx

94.66% Statements 71/75
83.33% Branches 30/36
90% Functions 18/20
98.43% Lines 63/64

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 24313x 13x 13x 13x 13x                 13x 13x 13x 13x 13x 13x 13x 13x     13x                                                 448x           448x         29x                 13x 1700x 241x                           448x             13x       448x         472x     472x 472x 472x 472x   472x   12x         7x 7x     7x 7x 7x       472x 472x         20x       472x 24x 24x 24x 24x 24x 24x 24x 24x 24x   22x 22x   2x               2x         472x 472x 24x     472x 6x   6x     6x 6x                                                       776x                                                     12x                       41x  
import { styled } from "@mui/material";
import Avatar from "@mui/material/Avatar";
import MuiIconButton from "@mui/material/IconButton";
import Alert from "components/Alert";
import CircularProgress from "components/CircularProgress";
import {
  CANCEL_UPLOAD,
  CONFIRM_UPLOAD,
  COULDNT_READ_FILE,
  getAvatarLabel,
  NO_VALID_FILE,
  SELECT_AN_IMAGE,
  UPLOAD_PENDING_ERROR,
} from "components/constants";
import IconButton from "components/IconButton";
import { CheckIcon, CrossIcon } from "components/Icons";
import Sentry from "platform/sentry";
import React, { useRef, useState } from "react";
import { Control, useController } from "react-hook-form";
import { useMutation } from "react-query";
import { service } from "service";
import { ImageInputValues } from "service/api";
 
import { DEFAULT_HEIGHT, DEFAULT_WIDTH } from "./constants";
 
interface ImageInputProps {
  className?: string;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  control: Control<any>;
  id: string;
  initialPreviewSrc?: string;
  name: string;
  onSuccess?(data: ImageInputValues): Promise<void>;
}
 
interface AvatarInputProps extends ImageInputProps {
  type: "avatar";
  userName: string;
}
 
interface RectImgInputProps extends ImageInputProps {
  type: "rect";
  alt: string;
  grow?: boolean;
  height?: string;
  width?: string;
}
 
const StyledWrapper = styled("div")(({ theme }) => ({
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
}));
 
const FlexWrapper = styled("div")(({ theme }) => ({
  display: "flex",
  width: "100%",
}));
 
const ConfirmationButtonContainer = styled("div")(({ theme }) => ({
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  "& > * + *": {
    marginTop: theme.spacing(1),
  },
}));
 
const StyledImage = styled("img", {
  shouldForwardProp: (prop) => prop !== "grow",
})<{ grow: boolean | undefined }>(({ theme, grow }) => ({
  height: 100,
  [theme.breakpoints.up("md")]: {
    height: 200,
  },
  width: "100%",
  objectFit: "cover",
  cursor: "pointer",
  "&:hover": {
    backgroundColor: theme.palette.action.hover,
  },
  ...(grow && { maxWidth: "100%", height: "auto" }),
}));
 
const StyledLabel = styled("label")(({ theme }) => ({
  alignItems: "center",
  display: "flex",
  justifyContent: "center",
  width: "100%",
}));
 
const StyledCircularProgress = styled(CircularProgress)(({ theme }) => ({
  position: "absolute",
}));
 
const StyledInput = styled("input")(({ theme }) => ({
  display: "none",
}));
 
export function ImageInput(props: AvatarInputProps | RectImgInputProps) {
  const { className, control, id, initialPreviewSrc, name } = props;
  //this ref handles the case where the user uploads an image, selects another image,
  //but then cancels - it should go to the previous image rather than the original
  const confirmedUpload = useRef<ImageInputValues>();
  const [imageUrl, setImageUrl] = useState(initialPreviewSrc);
  const [file, setFile] = useState<File | null>(null);
  const [readerError, setReaderError] = useState("");
 
  const mutation = useMutation<ImageInputValues, Error>(
    () =>
      file
        ? service.api.uploadFile(file)
        : Promise.reject(new Error(NO_VALID_FILE)),
    {
      onSuccess: async (data: ImageInputValues) => {
        field.onChange(data.key);
        setImageUrl(
          props.type === "avatar" ? data.thumbnail_url : data.full_url,
        );
        confirmedUpload.current = data;
        setFile(null);
        await props.onSuccess?.(data);
      },
    },
  );
  const isConfirming = !mutation.isLoading && file !== null;
  const { field } = useController({
    name,
    control,
    defaultValue: "",
    rules: {
      validate: () => !isConfirming || UPLOAD_PENDING_ERROR,
    },
  });
 
  const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    setReaderError("");
    Iif (!event.target.files?.length) return;
    const file = event.target.files[0];
    try {
      const base64 = await new Promise<string>((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
        reader.readAsDataURL(file);
      });
      setImageUrl(base64);
      setFile(file);
    } catch (e) {
      Sentry.captureException(
        new Error((e as ProgressEvent<FileReader>).toString()),
        {
          tags: {
            component: "component/ImageInput",
          },
        },
      );
      setReaderError(COULDNT_READ_FILE);
    }
  };
 
  //without this, onChange is not fired when the same file is selected after cancelling
  const inputRef = useRef<HTMLInputElement>(null);
  const handleClick = () => {
    if (inputRef.current) inputRef.current.value = "";
  };
 
  const handleCancel = () => {
    field.onChange(confirmedUpload.current?.key ?? "");
    const imageUrl =
      props.type === "avatar"
        ? confirmedUpload.current?.thumbnail_url
        : confirmedUpload.current?.full_url;
    setImageUrl(imageUrl ?? initialPreviewSrc);
    setFile(null);
  };
 
  return (
    <StyledWrapper>
      {mutation.isError && (
        <Alert severity="error">{mutation.error?.message || ""}</Alert>
      )}
      {readerError && <Alert severity="error">{readerError}</Alert>}
      <FlexWrapper>
        <StyledInput
          aria-label={SELECT_AN_IMAGE}
          accept="image/jpeg,image/png,image/gif"
          id={id}
          type="file"
          onChange={handleChange}
          onClick={handleClick}
          ref={inputRef}
        />
        <StyledLabel htmlFor={id} ref={field.ref}>
          {props.type === "avatar" ? (
            <MuiIconButton component="span">
              <Avatar
                className={className}
                src={imageUrl}
                alt={getAvatarLabel(props.userName ?? "")}
                sx={{ "& img": { objectFit: "cover" } }}
              >
                {props.userName?.split(/\s+/).map((name) => name[0])}
              </Avatar>
            </MuiIconButton>
          ) : (
            <StyledImage
              className={className}
              src={imageUrl ?? "/img/imagePlaceholder.svg"}
              style={{ objectFit: !imageUrl ? "contain" : undefined }}
              alt={props.alt}
              width={props.width ?? DEFAULT_WIDTH}
              height={props.height ?? DEFAULT_HEIGHT}
              grow={props.grow}
            />
          )}
          {mutation.isLoading && <StyledCircularProgress />}
        </StyledLabel>
        {isConfirming && (
          <ConfirmationButtonContainer>
            <IconButton
              aria-label={CANCEL_UPLOAD}
              onClick={handleCancel}
              size="small"
            >
              <CrossIcon />
            </IconButton>
            <IconButton
              aria-label={CONFIRM_UPLOAD}
              onClick={() => mutation.mutate()}
              size="small"
            >
              <CheckIcon />
            </IconButton>
          </ConfirmationButtonContainer>
        )}
      </FlexWrapper>
    </StyledWrapper>
  );
}
 
export default ImageInput;