All files / src/shared/FileUpload GiveUploadArea.tsx

88.23% Statements 30/34
84.31% Branches 43/51
100% Functions 8/8
90.62% Lines 29/32

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                                                                    103x                                         468x   468x 468x   468x       2x                   468x 18x     18x   18x 18x           468x   18x   18x             468x 20x 2x   20x         20x 2x 1x 1x 1x       20x 18x       468x                   468x 9x               459x                                                                                                                                                                                                                            
import { Box, Stack, SxProps, Theme } from "@mui/material";
import { UploadSimpleIcon } from "@phosphor-icons/react";
import { useUploadProgress } from "@redux/slices/uploadProgressSlice";
import GiveButton from "@shared/Button/GiveButton";
import GiveText from "@shared/Text/GiveText";
import { useAppTheme } from "@theme/v2/Provider";
import { getRandomNumber } from "@utils/helpers";
import React, { ReactNode } from "react";
import { Accept, ErrorCode, FileRejection, useDropzone } from "react-dropzone";
import useHEICConversion from "@components/UploadFile/hooks/useHEICConversion";
import { UploadDocumentTypes } from "@redux/slices/uploadProgressSlice/types";
 
interface Props {
  isMobile?: boolean;
  message?: string | ReactNode;
  disabled: boolean;
  uploadFunction: (file: File | File[]) => void;
  accept?: Accept;
  maxSizeInBytes?: number;
  maxFiles?: number;
  multiple?: boolean;
  customElement?: React.ReactNode;
  sx?: SxProps<Theme>;
  documentType?: UploadDocumentTypes;
  backgroundColor?: string;
  title?: string;
  showSelectFileButton?: boolean;
  warningText?: string;
  iconBg?: string;
  height?: string;
  children?: React.ReactNode;
  titleSx?: SxProps;
}
 
const GiveUploadArea = ({
  isMobile,
  message,
  disabled = false,
  uploadFunction,
  accept,
  maxSizeInBytes,
  maxFiles,
  multiple,
  customElement,
  sx,
  documentType,
  backgroundColor,
  title = "Drop files here",
  warningText,
  showSelectFileButton = true,
  iconBg = "transparent",
  height = "280px",
  children,
  titleSx,
}: Props) => {
  const { palette } = useAppTheme();
 
  const { setUploadProgress } = useUploadProgress();
  const { convertAndUploadHEICFiles } = useHEICConversion();
 
  const showErrorSnackbar = (
    file: FileRejection,
    error: "tooManyFiles" | "tooLarge" | "unsuported",
  ) => {
    setUploadProgress({
      key: `${getRandomNumber(1000000, 100000000)}`,
      data: {
        fileName: file.file.name,
        ...(error !== "tooManyFiles" && { size: file.file.size }),
        [error]: true,
      },
    });
  };
 
  const attemptUpload = (files: File | File[]) => {
    Iif (!files) return;
 
    // Normalize to array
    const fileArray = Array.isArray(files) ? files : [files];
 
    if (fileArray.length === 1) {
      uploadFunction(fileArray[0]); // single-file fallback
    } else E{
      uploadFunction(fileArray); // multi-file support
    }
  };
 
  const onHandleFileUpload = async (files: File[]) => {
    // If multiple allowed, upload all files, else only the first one
    const filesToUpload = multiple ? files : [files[0]];
 
    await convertAndUploadHEICFiles({
      files: filesToUpload,
      onComplete: attemptUpload,
      documentType,
    });
  };
 
  const onDrop = (acceptedFiles: File[], rejectedFiles: FileRejection[]) => {
    const hasTooManyFilesError = rejectedFiles.some((file) =>
      file.errors.some((error) => error.code === ErrorCode.TooManyFiles),
    );
    Iif (hasTooManyFilesError) {
      showErrorSnackbar(rejectedFiles[0], "tooManyFiles");
      return;
    }
 
    rejectedFiles.forEach((file) => {
      if (file.errors[0].code === ErrorCode.FileTooLarge) {
        showErrorSnackbar(file, "tooLarge");
      } else Eif (file.errors[0].code === ErrorCode.FileInvalidType) {
        showErrorSnackbar(file, "unsuported");
      }
    });
    // Call upload once with all valid files
    if (acceptedFiles.length) {
      onHandleFileUpload(acceptedFiles);
    }
  };
 
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    disabled,
    multiple,
    maxFiles,
    accept,
    // noClick: true,
    maxSize: maxSizeInBytes,
  });
 
  if (children) {
    return (
      <Box {...getRootProps({})}>
        {children}
        <input data-testid="file-upload-input" {...getInputProps()} />
      </Box>
    );
  }
 
  return (
    <Stack
      direction="column"
      justifyContent="center"
      alignItems="center"
      width="100%"
      borderRadius="20px"
      position="relative"
      display="flex"
      gap={isMobile ? "16px" : "16px"}
      height={isMobile ? undefined : height}
      sx={{
        backgroundColor: backgroundColor
          ? backgroundColor
          : isMobile
          ? "transparent"
          : isDragActive
          ? palette.primitive?.transparent["darken-10"]
          : palette.primitive?.transparent["darken-5"],
        transition: "background-color 0.2s",
        cursor: "pointer",
        ...(disabled && {
          cursor: "not-allowed",
          pointerEvents: "none",
          opacity: 0.7,
        }),
        ...(isMobile && {
          paddingTop: "20px",
        }),
        ...sx,
      }}
      aria-disabled={disabled}
      {...getRootProps({})}
    >
      {isMobile ? (
        <>
          <GiveButton
            variant="outline"
            size="large"
            label="Upload file"
            startIcon={<UploadSimpleIcon size={32} />}
          />
          {typeof message === "string" ? (
            <GiveText variant="bodyS" color="secondary">
              {message}
            </GiveText>
          ) : (
            message
          )}
        </>
      ) : (
        <>
          {customElement ? (
            customElement
          ) : (
            <Stack
              justifyContent="center"
              alignItems="center"
              width="100%"
              p={0}
              m={0}
              gap="16px"
            >
              <Stack
                bgcolor={iconBg}
                borderRadius="50%"
                justifyContent="center"
                alignItems="center"
                width="36px"
                height="36px"
              >
                <UploadSimpleIcon
                  size="32px"
                  color={palette.icon?.["icon-primary"]}
                />
              </Stack>
              <Stack direction="column" gap="8px" alignItems="center">
                <GiveText variant="bodyL" color="primary" sx={titleSx}>
                  {title}
                </GiveText>
                {warningText && (
                  <GiveText variant="bodyXS" color="error">
                    {warningText}
                  </GiveText>
                )}
                {typeof message === "string" ? (
                  <GiveText variant="bodyS" color="secondary">
                    {message}
                  </GiveText>
                ) : (
                  message
                )}
              </Stack>
              {showSelectFileButton && (
                <GiveButton
                  variant="outline"
                  size="large"
                  label="Select file"
                />
              )}
            </Stack>
          )}
        </>
      )}
      <input data-testid="file-upload-input" {...getInputProps()} />
    </Stack>
  );
};
 
export default GiveUploadArea;