All files / src/components/PhotoChooser index.tsx

0% Statements 0/28
0% Branches 0/26
0% Functions 0/13
0% Lines 0/26

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                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import React, { type JSX, useEffect, useRef, useState } from 'react';
 
import { Box, Typography, useTheme } from '@mui/material';
 
import { useDeviceInfo } from '../../utils';
import Button from '../Button/Button';
import ErrorBox from '../ErrorBox/ErrorBox';
import FileChooser from '../FileChooser';
 
export type PhotoChooserErrorType = {
  title: string;
  text: string;
};
 
export type PhotoChooserProps = {
  title?: string;
  description?: string | string[];
  onPhotosChanged: (photos: File[]) => void;
  multipleSelection?: boolean;
  error?: PhotoChooserErrorType;
  selectedFile?: any;
  uploadText?: string;
  uploadDescription?: string;
  uploadMobileDescription?: string;
  photoSelectedText?: string;
  chooseFileText?: string;
  replaceFileText?: string;
  maxPhotos?: number;
  existingPhotos?: string[];
  onExistingPhotoRemoved?: (index: number) => void;
  existingImagesLabel?: string;
  newImagesLabel?: string;
};
 
export default function PhotoChooser(props: PhotoChooserProps): JSX.Element {
  const {
    title,
    description,
    onPhotosChanged,
    multipleSelection,
    error,
    selectedFile,
    uploadText,
    uploadMobileDescription,
    uploadDescription,
    photoSelectedText,
    chooseFileText,
    replaceFileText,
    maxPhotos,
    existingPhotos,
    onExistingPhotoRemoved,
    existingImagesLabel,
    newImagesLabel,
  } = props;
  const { isMobile } = useDeviceInfo();
  const [files, setFiles] = useState<File[]>([]);
  const [filesData, setFilesData] = useState<string[]>([]);
  const divRef = useRef<HTMLDivElement>(null);
  const theme = useTheme();
 
  const removeFileAtIndex = (index: number) => {
    const filesList = [...files];
    filesList.splice(index, 1);
    setFiles(filesList);
  };
 
  const onChoosingFiles = () => {
    divRef.current?.focus();
  };
 
  useEffect(() => {
    const filesDataList = files.map((file) => URL.createObjectURL(file));
 
    setFilesData(filesDataList);
    onPhotosChanged(files);
 
    return () => {
      // we need to clean this up to avoid a memory leak
      filesDataList.forEach((fileData) => URL.revokeObjectURL(fileData));
    };
  }, [files]);
 
  const renderThumbnail = ({
    src,
    alt,
    onRemove,
    id,
  }: {
    src: string;
    alt?: string;
    onRemove?: () => void;
    id?: string;
  }) => (
    <Box
      key={id ?? src}
      position='relative'
      height={122}
      width={122}
      marginRight={isMobile ? theme.spacing(2) : theme.spacing(3)}
      marginTop={theme.spacing(1)}
      border={`1px solid ${theme.palette.TwClrBrdrTertiary}`}
    >
      {onRemove && (
        <Button
          icon='iconTrashCan'
          id={id}
          onClick={onRemove}
          size='small'
          style={{
            position: 'absolute',
            top: -10,
            right: -10,
            backgroundColor: theme.palette.TwClrBgDanger,
          }}
        />
      )}
      <img
        height='120px'
        src={src}
        alt={alt}
        style={{
          margin: 'auto auto',
          objectFit: 'contain',
          display: 'flex',
          maxWidth: '120px',
          maxHeight: '120px',
        }}
      />
    </Box>
  );
 
  return (
    <Box
      ref={divRef}
      tabIndex={0}
      sx={{
        backgroundColor: theme.palette.TwClrBg,
        borderRadius: theme.spacing(4),
        padding: theme.spacing(3),
      }}
    >
      <Box>
        {title && (
          <Typography fontSize={20} fontWeight={600}>
            {title}
          </Typography>
        )}
        {description && (
          <Typography fontSize={14} fontWeight={400} marginTop={theme.spacing(1)} marginBottom={theme.spacing(2)}>
            {Array.isArray(description) ? description.map((txt, i) => <div key={i}>{txt}</div>) : description}
          </Typography>
        )}
        {error && (
          <ErrorBox
            title={error.title}
            text={error.text}
            sx={{
              width: 'auto',
              marginBottom: theme.spacing(2),
              '&.mobile': {
                width: 'auto',
              },
            }}
          />
        )}
        {existingPhotos && existingPhotos.length > 0 && (
          <Box marginBottom={theme.spacing(2)}>
            {existingImagesLabel && (
              <Typography fontSize={14} fontWeight={400} marginBottom={theme.spacing(1)}>
                {existingImagesLabel}
              </Typography>
            )}
            <Box display='flex' flexDirection='row' flexWrap='wrap'>
              {existingPhotos.map((url, index) =>
                renderThumbnail({
                  src: url,
                  alt: url,
                  id: `existing-photo-remove-${index}`,
                  onRemove: onExistingPhotoRemoved ? () => onExistingPhotoRemoved(index) : undefined,
                })
              )}
            </Box>
          </Box>
        )}
        {filesData.length > 0 && multipleSelection && (
          <Box marginBottom={theme.spacing(2)}>
            {newImagesLabel && (
              <Typography fontSize={14} fontWeight={400} marginBottom={theme.spacing(1)}>
                {newImagesLabel}
              </Typography>
            )}
            <Box display='flex' flexDirection='row' flexWrap='wrap'>
              {filesData.map((fileData, index) =>
                renderThumbnail({
                  src: fileData,
                  alt: files[index]?.name,
                  onRemove: () => removeFileAtIndex(index),
                })
              )}
            </Box>
          </Box>
        )}
      </Box>
      <FileChooser
        acceptFileType='image/jpeg,image/png'
        chooseFileText={chooseFileText}
        files={files}
        fileSelectedText={photoSelectedText}
        iconName='blobbyGrayIconImage'
        maxFiles={maxPhotos}
        multipleSelection={multipleSelection}
        onChoosingFiles={onChoosingFiles}
        replaceFileText={replaceFileText}
        selectedFile={selectedFile}
        setFiles={setFiles}
        uploadDescription={uploadDescription}
        uploadMobileDescription={uploadMobileDescription}
        uploadText={uploadText}
      />
    </Box>
  );
}