Upload.tsx 5.54 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 * See the NOTICE file distributed with this work for additional information
 * regarding copyright ownership.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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
import React, { useState } from 'react';
import get from 'lodash/get';
import classNames from 'classnames';

import windowService from 'src/services/window-service';

import styles from './Upload.scss';

export type ReadFile = {
  filename: string;
  content: string | null | ArrayBuffer;
  error: string | null;
};

const fileReaderErrorMessages: { [key: number]: string } = {
  1: 'The file can not be found (NOT_FOUND_ERR).',
  2: 'The operation is insecure (SECURITY_ERR).',
  4: 'The I/O read operation failed (NOT_READABLE_ERR).'
};

const getFileReaderErrorMessage = (error_code: number) => {
  return fileReaderErrorMessages[error_code] || 'Unable to read the file.';
};

export enum FileReaderMethod {
  ARRAY_BUFFER = 'readAsArrayBuffer',
  BINARY_STRING = 'readAsBinaryString',
  DATA_URL = 'readAsDataURL',
  TEXT = 'readAsText'
}
type PropsForRespondingWithASingleFile = {
  onChange: (file: File) => void;
  callbackWithFiles: true;
  allowMultiple: false;
};

type PropsForRespondingWithMultipleFiles = {
  onChange: (files: FileList) => void;
  callbackWithFiles: true;
  allowMultiple: true;
};

type PropsForRespondingWithContent = {
  onChange: (files: ReadFile[]) => void;
  callbackWithFiles: false;
  fileReaderMethod: FileReaderMethod;
};

type OnChangeProps =
  | PropsForRespondingWithASingleFile
  | PropsForRespondingWithMultipleFiles
  | PropsForRespondingWithContent;

export type UploadProps = {
  name?: string;
  label: string;
  classNames?: {
    default?: string;
    active?: string;
Andrey Azov's avatar
Andrey Azov committed
76
    disabled?: string;
77 78
  };
  allowMultiple?: boolean;
Andrey Azov's avatar
Andrey Azov committed
79
  disabled?: boolean;
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
} & OnChangeProps;

const Upload = (props: UploadProps) => {
  const [drag, setDrag] = useState(false);

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };
  const handleDragIn = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (get(e, 'dataTransfer.items.length', 0) > 0) {
      setDrag(true);
    }
  };

  const handleDragOut = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDrag(false);
  };

  const handleSelectedFiles = async (
    e: React.ChangeEvent<HTMLInputElement> | React.DragEvent
  ) => {
    e.preventDefault();
    e.stopPropagation();
    const eventType = e.type;
    if (eventType === 'drop') {
      (e as React.DragEvent).dataTransfer.clearData();
    }
    setDrag(false);

    const files: FileList | null =
      get(e, 'target.files') || get(e, 'dataTransfer.files') || null;

Andrey Azov's avatar
Andrey Azov committed
117
    if (!files?.length) {
118 119 120 121
      return;
    }

    if (props.callbackWithFiles) {
Andrey Azov's avatar
Andrey Azov committed
122
      // Just pass the first file to the callback if allowMultiple is true
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
      if (!props.allowMultiple) {
        props.onChange(files[0]);
        return;
      }
      props.onChange(files);
      return;
    }

    const filesToRead = props.allowMultiple
      ? [...files]
      : [...files].slice(0, 1);

    const promises = filesToRead.map((file) => {
      const fileReader: FileReader = windowService.getFileReader();
      return new Promise((resolve) => {
        fileReader.onload = resolve;
        fileReader.onerror = resolve;
        fileReader[props.fileReaderMethod](file);
      }).then(() => ({
        filename: file.name,
        content: fileReader.result,
        error: fileReader.error
          ? getFileReaderErrorMessage(fileReader.error.code)
          : null
      }));
    });

    const results = await Promise.all(promises);
    props.onChange(results);
  };

  const getDefaultClassNames = () => {
    if (!props.classNames || !props.classNames.default) {
      return styles.defaultUpload;
    }

    return classNames(styles.defaultUpload, props.classNames.default);
  };

  const getActiveClassNames = () => {
    if (!drag) {
      return '';
    }

    if (!props.classNames || !props.classNames.active) {
      return styles.defaultUploadActive;
    }

    return classNames(styles.defaultUploadActive, props.classNames.active);
  };

Andrey Azov's avatar
Andrey Azov committed
174 175 176 177 178 179 180 181 182 183
  if (props.disabled) {
    const elementClasses = classNames(
      styles.disabledUpload,
      props.classNames?.disabled
    );
    // using the label html tag even though there is no input
    // to keep it the same as the label element of the enabled component (to support animations)
    return <label className={elementClasses}>{props.label}</label>;
  }

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  return (
    <label
      className={`${getDefaultClassNames()} ${getActiveClassNames()}`}
      onDragEnter={handleDragIn}
      onDragLeave={handleDragOut}
      onDragOver={handleDrag}
      onDrop={handleSelectedFiles}
    >
      <input
        type="file"
        name={props.name}
        className={styles.fileInput}
        onChange={(e) => handleSelectedFiles(e)}
        multiple={props.allowMultiple}
      />
      {props.label}
    </label>
  );
};

Upload.defaultProps = {
  callbackWithFiles: false,
  allowMultiple: true,
  fileReaderMethod: FileReaderMethod.TEXT,
208
  label: 'Click or drag file(s) here to upload'
209 210 211
};

export default Upload;