All files / app/components/ImageInput ImageInput.tsx

91.42% Statements 64/70
78.26% Branches 18/23
85.71% Functions 18/21
94.91% Lines 56/59

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  11x 11x 11x 11x 11x 11x         11x 11x 11x 11x 11x 11x 11x     11x                                                   654x           654x         11x 2048x 291x                           363x                     654x             11x       654x         678x   678x   678x 678x   678x 12x   12x     7x 7x 7x 5x     7x       678x         14x       678x 14x 14x 14x 14x 14x 14x 14x 14x 14x   12x 12x   2x               2x         678x 678x 14x                                                                       1416x                                                   46x  
import { Edit } from "@mui/icons-material";
import { styled, Tooltip } from "@mui/material";
import Avatar from "@mui/material/Avatar";
import MuiIconButton from "@mui/material/IconButton";
import { useMutation } from "@tanstack/react-query";
import Alert from "components/Alert";
import CircularProgress from "components/CircularProgress";
import {
  COULDNT_READ_FILE,
  getAvatarLabel,
  SELECT_AN_IMAGE,
} from "components/constants";
import { useTranslation } from "i18n";
import { PROFILE } from "i18n/namespaces";
import Sentry from "platform/sentry";
import React, { useRef, useState } from "react";
import { Control, useController } from "react-hook-form";
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>;
  onUploading?: (isUploading: boolean) => void; //new prop
}
 
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 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 EditIconButton = styled(MuiIconButton)(({ theme }) => ({
  position: "absolute",
  bottom: theme.spacing(1),
  right: theme.spacing(1),
  backgroundColor: theme.palette.primary.main,
  boxShadow: theme.shadows[1],
  "&:hover": {
    backgroundColor: theme.palette.grey[200],
  },
}));
 
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;
 
  const { t } = useTranslation([PROFILE]);
 
  const [imageUrl, setImageUrl] = useState(initialPreviewSrc);
  const [readerError, setReaderError] = useState("");
 
  const mutation = useMutation<ImageInputValues, Error, File>({
    mutationFn: (file) => service.api.uploadFile(file),
    onMutate: () => {
      props.onUploading?.(true); //notify form upload has started
    },
    onSuccess: async (data: ImageInputValues) => {
      field.onChange(data.key);
      setImageUrl(props.type === "avatar" ? data.thumbnail_url : data.full_url);
      await props.onSuccess?.(data);
      props.onUploading?.(false); //notify form upload has finished
    },
    onError: () => {
      props.onUploading?.(false); //notify form upload has failed
    },
  });
 
  const { field } = useController({
    name,
    control,
    defaultValue: "",
    rules: {
      validate: () => !mutation.isPending,
    },
  });
 
  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);
      mutation.mutate(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 = "";
  };
 
  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" ? (
            <Tooltip title={t("profile:click_replace_image")} placement="top">
              <MuiIconButton
                component="span"
                sx={{ position: "relative" }}
                onClick={(e) => {
                  e.preventDefault(); // prevent triggering label click again
                  inputRef.current?.click();
                }}
              >
                <Avatar
                  className={className}
                  src={imageUrl}
                  alt={getAvatarLabel(props.userName ?? "")}
                  sx={{ "& img": { objectFit: "cover" } }}
                >
                  {props.userName?.split(/\s+/).map((name) => name[0])}
                </Avatar>
 
                <EditIconButton size="small">
                  <Edit fontSize="small" sx={{ color: "common.white" }} />
                </EditIconButton>
              </MuiIconButton>
            </Tooltip>
          ) : (
            <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.isPending && <StyledCircularProgress />}
        </StyledLabel>
      </FlexWrapper>
    </StyledWrapper>
  );
}
 
export default ImageInput;