All files / app/components/ImageInput ImageInput.tsx

77.38% Statements 65/84
66.66% Branches 16/24
84.21% Functions 16/19
77.33% Lines 58/75

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 22510x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x   10x                                         227x           227x         10x 1599x 227x                           227x             227x         240x   240x 240x   240x 240x 240x   240x 8x   8x     4x 4x 4x 3x     5x       240x         15x       240x 10x 10x 10x 10x     10x 1x 1x     9x 9x 9x 9x 9x 9x   8x 8x   1x               1x         240x 240x 10x       240x                                                                                                                                                     32x  
import { styled } from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import Alert from "components/Alert";
import { useTranslation } from "i18n";
import { GLOBAL, PROFILE } from "i18n/namespaces";
import Sentry from "platform/sentry";
import React, { useCallback, useRef, useState } from "react";
import { Control, useController } from "react-hook-form";
import { service } from "service";
import { ImageInputValues } from "service/api";
import { IMAGE_TOO_LARGE } from "service/constants";
import { base64ToFile, useNativeImagePicker } from "utils/nativeLink";
 
import { DEFAULT_HEIGHT, DEFAULT_WIDTH, MAX_FILE_SIZE } 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 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 StyledLabel = styled("label")(({ theme }) => ({
  alignItems: "center",
  display: "flex",
  justifyContent: "center",
  width: "100%",
}));
 
const StyledInput = styled("input")(({ theme }) => ({
  display: "none",
}));
 
function ImageInput(props: RectImgInputProps) {
  const { className, control, id, initialPreviewSrc, name } = props;
 
  const { t } = useTranslation([GLOBAL, PROFILE]);
  const { isNative, pickImage } = useNativeImagePicker();
 
  const [imageUrl, setImageUrl] = useState(initialPreviewSrc);
  const [readerError, setReaderError] = useState("");
  const [fileSizeError, setFileSizeError] = 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(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("");
    setFileSizeError("");
    Iif (!event.target.files?.length) return;
    const file = event.target.files[0];
 
    // Check file size before uploading
    if (file.size > MAX_FILE_SIZE) {
      setFileSizeError(IMAGE_TOO_LARGE);
      return;
    }
 
    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(t("global:image_input.read_file_error_message"));
    }
  };
 
  //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 = "";
  };
 
  // Native app WebView file input is unreliable on iOS - use native image picker instead
  const handleNativeImagePick = useCallback(async () => {
    setReaderError("");
    setFileSizeError("");
    try {
      const result = await pickImage();
      Iif (result.success) {
        const dataUrl = `data:${result.mimeType};base64,${result.imageBase64}`;
        const extension = result.mimeType.split("/")[1] || "jpg";
        const file = base64ToFile(
          result.imageBase64,
          result.mimeType,
          `image.${extension}`,
        );
 
        // Check file size before uploading
        Iif (file.size > MAX_FILE_SIZE) {
          setFileSizeError(IMAGE_TOO_LARGE);
          return;
        }
 
        setImageUrl(dataUrl);
        mutation.mutate(file);
      }
    } catch (e) {
      Sentry.captureException(e, {
        tags: { component: "ImageInput", native: true },
      });
      setReaderError(t("global:image_input.read_file_error_message"));
    }
  }, [pickImage, mutation, t]);
 
  return (
    <StyledWrapper>
      {mutation.isError && (
        <Alert severity="error">{mutation.error?.message || ""}</Alert>
      )}
      {readerError && <Alert severity="error">{readerError}</Alert>}
      {fileSizeError && <Alert severity="error">{fileSizeError}</Alert>}
      <FlexWrapper>
        <StyledInput
          aria-label={t("global:image_input.select_button_a11y")}
          accept="image/jpeg,image/png,image/gif"
          id={id}
          type="file"
          onChange={handleChange}
          onClick={handleClick}
          ref={inputRef}
        />
        <StyledLabel
          htmlFor={id}
          ref={field.ref}
          onClick={
            isNative
              ? (e) => {
                  e.preventDefault();
                  handleNativeImagePick();
                }
              : undefined
          }
        >
          <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}
          />
        </StyledLabel>
      </FlexWrapper>
    </StyledWrapper>
  );
}
 
export default ImageInput;