All files / src/components/FileChooser index.tsx

0% Statements 0/30
0% Branches 0/46
0% Functions 0/7
0% Lines 0/29

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                                                                                                                                                                                                                                                                                                                                                   
import React, { useEffect, useRef, useState } from 'react';
import { Box, Link, Typography, useTheme } from '@mui/material';
 
import { useDeviceInfo } from '../../utils';
import Button from '../Button/Button';
import Icon from '../Icon/Icon';
import { IconName } from '../Icon/icons';
 
export type FileTemplate = {
  text: string;
  url: string;
};
 
export type FileChooserProps = {
  /** Optional comma-separated list of MIME types to accept in the chooser. */
  acceptFileType?: string;
  chooseFileText?: string;
  files?: File[];
  fileSelectedText?: string;
  iconName?: IconName;
  maxFiles?: number;
  multipleSelection?: boolean;
  onChoosingFiles?: () => void;
  replaceFileText?: string;
  selectedFile?: any;
  setFiles: (files: File[]) => void;
  template?: FileTemplate;
  uploadDescription?: string;
  uploadMobileDescription?: string;
  uploadText?: string;
};
 
export default function FileChooser(props: FileChooserProps): JSX.Element {
  const {
    acceptFileType,
    chooseFileText,
    files,
    fileSelectedText,
    iconName,
    maxFiles,
    multipleSelection,
    onChoosingFiles,
    replaceFileText,
    selectedFile,
    setFiles,
    template,
    uploadDescription,
    uploadMobileDescription,
    uploadText,
  } = props;
  const { isMobile } = useDeviceInfo();
  const inputRef = useRef<HTMLInputElement>(null);
  const theme = useTheme();
  const [editing, setEditing] = useState<boolean>(false);
 
  useEffect(() => {
    setEditing(!!selectedFile);
  }, [selectedFile]);
 
  const addFiles = (fileList: FileList) => {
    const newFiles: File[] = [];
 
    for (let i = 0; i < fileList.length; i++) {
      const fileItem = fileList.item(i);
      if (fileItem) {
        newFiles.push(fileItem);
      }
    }
 
    if (newFiles.length) {
      setFiles([...(files ?? []), ...newFiles].slice(0, maxFiles));
    }
  };
 
  const dropHandler = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    addFiles(event.dataTransfer.files);
  };
 
  const enableDropping = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
  };
 
  const onChooseFileHandler = () => {
    inputRef.current?.click();
    onChoosingFiles?.();
  };
 
  const onFileChosen = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (editing) {
      setEditing(false);
    }
    if (event.currentTarget.files) {
      addFiles(event.currentTarget.files);
    }
  };
 
  return (
    <Box
      onDrop={dropHandler}
      onDragOver={enableDropping}
      border={`1px dashed ${theme.palette.TwClrBrdrTertiary}`}
      borderRadius={theme.spacing(2)}
      display='flex'
      flexDirection='column'
      alignItems='center'
      padding={theme.spacing(3)}
      sx={{ background: theme.palette.TwClrBg }}
    >
      {iconName && (
        <Icon
          name={iconName}
          size='xlarge'
          style={{
            height: '120px',
            width: '120px',
          }}
        />
      )}
      <Typography color={theme.palette.TwClrTxt} fontSize={14} fontWeight={600} margin={theme.spacing(0, 0, 1)}>
        {!editing && ((files || []).length > 0 && !multipleSelection ? files?.[0].name : uploadText)}
      </Typography>
      <Typography color={theme.palette.TwClrTxt} fontSize={12} fontWeight={400} margin={0}>
        {(editing || (files || []).length > 0) && !multipleSelection
          ? fileSelectedText
          : isMobile && uploadMobileDescription
          ? uploadMobileDescription
          : uploadDescription}
      </Typography>
      <input
        type='file'
        ref={inputRef}
        onChange={onFileChosen}
        accept={acceptFileType}
        multiple={multipleSelection || false}
        value={''}
        style={{ display: 'none' }}
      />
      <Button
        onClick={onChooseFileHandler}
        disabled={maxFiles !== undefined ? (files || []).length >= maxFiles : false}
        label={!multipleSelection && ((files || []).length === 1 || editing) ? replaceFileText : chooseFileText}
        priority='secondary'
        type='passive'
        sx={{ marginTop: theme.spacing(3) }}
      />
      {template && (
        <Link
          href={template.url}
          target='_blank'
          sx={{
            color: theme.palette.TwClrTxtBrand,
            fontFamily: 'Inter',
            fontSize: '12px',
            fontWeight: 500,
            lineHeight: '16px',
            marginTop: theme.spacing(2),
            textDecoration: 'none',
            '&:hover': {
              textDecoration: 'underline',
            },
          }}
        >
          {template.text}
        </Link>
      )}
    </Box>
  );
}