All files / app/components/ImageInput ImageInput.tsx

96.87% Statements 62/64
89.47% Branches 34/38
92.3% Functions 12/13
100% Lines 59/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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 24714x 14x 14x 14x 14x 14x                 14x 14x 14x 14x 14x 14x 14x 14x     14x   41x                                                                                                                                                 14x 288x 288x     288x 288x 288x 288x   288x   12x         7x 7x     7x 7x 7x       288x 288x         24x       288x 20x 20x 20x 20x 20x 20x 20x 20x 20x   18x 18x   2x               2x         288x 288x 20x     288x 4x   4x     4x 4x     288x                                                 256x                                                           12x                       14x  
import Avatar from "@material-ui/core/Avatar";
import MuiIconButton from "@material-ui/core/IconButton";
import makeStyles from "@material-ui/core/styles/makeStyles";
import classNames from "classnames";
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";
 
const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
  },
  inputRoot: {
    display: "flex",
    width: "100%",
  },
  avatar: {
    "& img": { objectFit: "cover" },
  },
  confirmationButtonContainer: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    "& > * + *": {
      marginTop: theme.spacing(1),
    },
  },
  image: {
    height: 100,
    [theme.breakpoints.up("md")]: {
      height: 200,
    },
    width: "100%",
    objectFit: "cover",
    cursor: "pointer",
    "&:hover": {
      backgroundColor: theme.palette.action.hover,
    },
  },
  imageGrow: {
    maxWidth: "100%",
    height: "auto",
  },
  input: {
    display: "none",
  },
  label: {
    alignItems: "center",
    display: "flex",
    justifyContent: "center",
    width: "100%",
  },
  loading: {
    position: "absolute",
  },
}));
 
interface ImageInputProps {
  className?: string;
  control: Control;
  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;
}
 
export function ImageInput(props: AvatarInputProps | RectImgInputProps) {
  const { className, control, id, initialPreviewSrc, name } = props;
  const classes = useStyles();
  //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 (
    <div className={classes.root}>
      {mutation.isError && (
        <Alert severity="error">{mutation.error?.message || ""}</Alert>
      )}
      {readerError && <Alert severity="error">{readerError}</Alert>}
      <div className={classes.inputRoot}>
        <input
          aria-label={SELECT_AN_IMAGE}
          className={classes.input}
          accept="image/jpeg,image/png,image/gif"
          id={id}
          type="file"
          onChange={handleChange}
          onClick={handleClick}
          ref={inputRef}
        />
        <label className={classes.label} htmlFor={id} ref={field.ref}>
          {props.type === "avatar" ? (
            <MuiIconButton component="span">
              <Avatar
                className={classNames(classes.avatar, className)}
                src={imageUrl}
                alt={getAvatarLabel(props.userName ?? "")}
              >
                {props.userName?.split(/\s+/).map((name) => name[0])}
              </Avatar>
            </MuiIconButton>
          ) : (
            <img
              className={classNames(classes.image, className, {
                [classes.imageGrow]: props.grow,
              })}
              src={imageUrl ?? "/img/imagePlaceholder.svg"}
              style={{ objectFit: !imageUrl ? "contain" : undefined }}
              alt={props.alt}
              width={props.width ?? DEFAULT_WIDTH}
              height={props.height ?? DEFAULT_HEIGHT}
            />
          )}
          {mutation.isLoading && (
            <CircularProgress className={classes.loading} />
          )}
        </label>
        {isConfirming && (
          <div className={classes.confirmationButtonContainer}>
            <IconButton
              aria-label={CANCEL_UPLOAD}
              onClick={handleCancel}
              size="small"
            >
              <CrossIcon />
            </IconButton>
            <IconButton
              aria-label={CONFIRM_UPLOAD}
              onClick={() => mutation.mutate()}
              size="small"
            >
              <CheckIcon />
            </IconButton>
          </div>
        )}
      </div>
    </div>
  );
}
 
export default ImageInput;