All files / react-dropzone/src index.js

97.64% Statements 124/127
93.1% Branches 81/87
100% Functions 24/24
97.6% Lines 122/125
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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396          1x             1x       51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x               49x 49x   49x 48x 48x     49x       2x 2x 1x 1x     2x       2x   1x   1x 1x       2x 2x         14x     14x 12x     14x   14x         14x 2x         2x 2x 2x 2x         2x 1x   2x       3x     4x 3x       3x         3x 2x         31x 31x 31x 31x     31x     31x 31x   31x 53x 50x     53x 40x   13x       31x 27x     31x 11x     31x 15x       31x                 9x 9x 7x 7x 7x 2x             2x 2x 2x     2x 1x   1x 1x 1x 1x             51x           70x       43x       14x       7x 7x 7x       99x 15x   84x                         99x               99x   99x   99x   99x     99x       99x 96x               96x       96x             99x 11x       88x 3x         85x         99x         147x       99x 1x       99x                     99x 891x   99x                                             1x                 1x                                                                      
/* eslint prefer-template: 0 */
import React from 'react';
import accepts from 'attr-accept';
import getDataTransferItems from './getDataTransferItems';
 
const supportMultiple = (typeof document !== 'undefined' && document && document.createElement) ?
  'multiple' in document.createElement('input') :
  true;
 
class Dropzone extends React.Component {
  static onDocumentDragOver(e) {
    // allow the entire document to be a drag target
    e.preventDefault();
  }
 
  constructor(props, context) {
    super(props, context);
    this.onClick = this.onClick.bind(this);
    this.onDocumentDrop = this.onDocumentDrop.bind(this);
    this.onDragStart = this.onDragStart.bind(this);
    this.onDragEnter = this.onDragEnter.bind(this);
    this.onDragLeave = this.onDragLeave.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
    this.onDrop = this.onDrop.bind(this);
    this.onFileDialogCancel = this.onFileDialogCancel.bind(this);
    this.fileAccepted = this.fileAccepted.bind(this);
    this.setRef = this.setRef.bind(this);
    this.isFileDialogActive = false;
    this.state = {
      isDragActive: false,
      acceptedFiles: [],
      rejectedFiles: []
    };
  }
 
  componentDidMount() {
    const { preventDropOnDocument } = this.props;
    this.dragTargets = [];
 
    if (preventDropOnDocument) {
      document.addEventListener('dragover', Dropzone.onDocumentDragOver, false);
      document.addEventListener('drop', this.onDocumentDrop, false);
    }
    // Tried implementing addEventListener, but didn't work out
    document.body.onfocus = this.onFileDialogCancel;
  }
 
  componentWillUnmount() {
    const { preventDropOnDocument } = this.props;
    if (preventDropOnDocument) {
      document.removeEventListener('dragover', Dropzone.onDocumentDragOver);
      document.removeEventListener('drop', this.onDocumentDrop);
    }
    // Can be replaced with removeEventListener, if addEventListener works
    document.body.onfocus = null;
  }
 
  onDocumentDrop(e) {
    if (this.node.contains(e.target)) {
      // if we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
      return;
    }
    e.preventDefault();
    this.dragTargets = [];
  }
 
  onDragStart(e) {
    Eif (this.props.onDragStart) {
      this.props.onDragStart.call(this, e);
    }
  }
 
  onDragEnter(e) {
    e.preventDefault();
 
    // Count the dropzone and any children that are entered.
    if (this.dragTargets.indexOf(e.target) === -1) {
      this.dragTargets.push(e.target);
    }
 
    const allFilesAccepted = this.allFilesAccepted(getDataTransferItems(e, this.props.multiple));
 
    this.setState({
      isDragActive: allFilesAccepted,
      isDragReject: !allFilesAccepted
    });
 
    if (this.props.onDragEnter) {
      this.props.onDragEnter.call(this, e);
    }
  }
 
  onDragOver(e) { // eslint-disable-line class-methods-use-this
    e.preventDefault();
    e.stopPropagation();
    try {
      e.dataTransfer.dropEffect = 'copy'; // eslint-disable-line no-param-reassign
    } catch (err) {
      // continue regardless of error
    }
 
    if (this.props.onDragOver) {
      this.props.onDragOver.call(this, e);
    }
    return false;
  }
 
  onDragLeave(e) {
    e.preventDefault();
 
    // Only deactivate once the dropzone and all children have been left.
    this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
    Iif (this.dragTargets.length > 0) {
      return;
    }
 
    this.setState({
      isDragActive: false,
      isDragReject: false
    });
 
    if (this.props.onDragLeave) {
      this.props.onDragLeave.call(this, e);
    }
  }
 
  onDrop(e) {
    const { onDrop, onDropAccepted, onDropRejected, multiple, disablePreview } = this.props;
    const fileList = getDataTransferItems(e, multiple);
    const acceptedFiles = [];
    const rejectedFiles = [];
 
    // Stop default browser behavior
    e.preventDefault();
 
    // Reset the counter along with the drag on a drop.
    this.dragTargets = [];
    this.isFileDialogActive = false;
 
    fileList.forEach((file) => {
      if (!disablePreview) {
        file.preview = window.URL.createObjectURL(file); // eslint-disable-line no-param-reassign
      }
 
      if (this.fileAccepted(file) && this.fileMatchSize(file)) {
        acceptedFiles.push(file);
      } else {
        rejectedFiles.push(file);
      }
    });
 
    if (onDrop) {
      onDrop.call(this, acceptedFiles, rejectedFiles, e);
    }
 
    if (rejectedFiles.length > 0 && onDropRejected) {
      onDropRejected.call(this, rejectedFiles, e);
    }
 
    if (acceptedFiles.length > 0 && onDropAccepted) {
      onDropAccepted.call(this, acceptedFiles, e);
    }
 
    // Reset drag state
    this.setState({
      isDragActive: false,
      isDragReject: false,
      acceptedFiles,
      rejectedFiles
    });
  }
 
  onClick(e) {
    const { onClick, disableClick } = this.props;
    if (!disableClick) {
      e.stopPropagation();
      this.open();
      if (onClick) {
        onClick.call(this, e);
      }
    }
  }
 
  onFileDialogCancel() {
    // timeout will not recognize context of this method
    const { onFileDialogCancel } = this.props;
    const { fileInputEl } = this;
    let { isFileDialogActive } = this;
    // execute the timeout only if the onFileDialogCancel is defined and FileDialog
    // is opened in the browser
    if (onFileDialogCancel && isFileDialogActive) {
      setTimeout(() => {
        // Returns an object as FileList
        const FileList = fileInputEl.files;
        Eif (!FileList.length) {
          isFileDialogActive = false;
          onFileDialogCancel();
        }
      }, 300);
    }
  }
 
  setRef(ref) {
    this.node = ref;
  }
 
  fileAccepted(file) {
    // Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
    // that MIME type will always be accepted
    return file.type === 'application/x-moz-file' || accepts(file, this.props.accept);
  }
 
  fileMatchSize(file) {
    return file.size <= this.props.maxSize && file.size >= this.props.minSize;
  }
 
  allFilesAccepted(files) {
    return files.every(this.fileAccepted);
  }
 
  open() {
    this.isFileDialogActive = true;
    this.fileInputEl.value = null;
    this.fileInputEl.click();
  }
 
  renderChildren = (children) => {
    if (typeof children === 'function') {
      return children(this.state);
    }
    return children;
  }
 
  render() {
    const {
      accept,
      activeClassName,
      inputProps,
      multiple,
      name,
      rejectClassName,
      children,
      ...rest
    } = this.props;
 
    let {
      activeStyle,
      className,
      rejectStyle,
      style,
      ...props // eslint-disable-line prefer-const
    } = rest;
 
    const { isDragActive, isDragReject } = this.state;
 
    className = className || '';
 
    Iif (isDragActive && activeClassName) {
      className += ' ' + activeClassName;
    }
    Iif (isDragReject && rejectClassName) {
      className += ' ' + rejectClassName;
    }
 
    if (!className && !style && !activeStyle && !rejectStyle) {
      style = {
        width: 200,
        height: 200,
        borderWidth: 2,
        borderColor: '#666',
        borderStyle: 'dashed',
        borderRadius: 5
      };
      activeStyle = {
        borderStyle: 'solid',
        backgroundColor: '#eee'
      };
      rejectStyle = {
        borderStyle: 'solid',
        backgroundColor: '#ffdddd'
      };
    }
 
    let appliedStyle;
    if (activeStyle && isDragActive) {
      appliedStyle = {
        ...style,
        ...activeStyle
      };
    } else if (rejectStyle && isDragReject) {
      appliedStyle = {
        ...style,
        ...rejectStyle
      };
    } else {
      appliedStyle = {
        ...style
      };
    }
 
    const inputAttributes = {
      accept,
      type: 'file',
      style: { display: 'none' },
      multiple: supportMultiple && multiple,
      ref: el => this.fileInputEl = el, // eslint-disable-line
      onChange: this.onDrop
    };
 
    if (name && name.length) {
      inputAttributes.name = name;
    }
 
    // Remove custom properties before passing them to the wrapper div element
    const customProps = [
      'acceptedFiles',
      'preventDropOnDocument',
      'disablePreview',
      'disableClick',
      'onDropAccepted',
      'onDropRejected',
      'onFileDialogCancel',
      'maxSize',
      'minSize'
    ];
    const divProps = { ...props };
    customProps.forEach(prop => delete divProps[prop]);
 
    return (
      <div
        className={className}
        style={appliedStyle}
        {...divProps/* expand user provided props first so event handlers are never overridden */}
        onClick={this.onClick}
        onDragStart={this.onDragStart}
        onDragEnter={this.onDragEnter}
        onDragOver={this.onDragOver}
        onDragLeave={this.onDragLeave}
        onDrop={this.onDrop}
        ref={this.setRef}
      >
        {this.renderChildren(children)}
        <input
          {...inputProps/* expand user provided inputProps first so inputAttributes override them */}
          {...inputAttributes}
        />
      </div>
    );
  }
}
 
Dropzone.defaultProps = {
  preventDropOnDocument: true,
  disablePreview: false,
  disableClick: false,
  multiple: true,
  maxSize: Infinity,
  minSize: 0
};
 
Dropzone.propTypes = {
  onClick: React.PropTypes.func,
  onDrop: React.PropTypes.func,
  onDropAccepted: React.PropTypes.func,
  onDropRejected: React.PropTypes.func,
  onDragStart: React.PropTypes.func,
  onDragEnter: React.PropTypes.func,
  onDragOver: React.PropTypes.func,
  onDragLeave: React.PropTypes.func,
 
  children: React.PropTypes.oneOfType([
    React.PropTypes.node,
    React.PropTypes.func
  ]), // Contents of the dropzone
  style: React.PropTypes.object, // CSS styles to apply
  activeStyle: React.PropTypes.object, // CSS styles to apply when drop will be accepted
  rejectStyle: React.PropTypes.object, // CSS styles to apply when drop will be rejected
  className: React.PropTypes.string, // Optional className
  activeClassName: React.PropTypes.string, // className for accepted state
  rejectClassName: React.PropTypes.string, // className for rejected state
 
  preventDropOnDocument: React.PropTypes.bool, // If false, allow dropped items to take over the current browser window
  disablePreview: React.PropTypes.bool, // Enable/disable preview generation
  disableClick: React.PropTypes.bool, // Disallow clicking on the dropzone container to open file dialog
  onFileDialogCancel: React.PropTypes.func, // Provide a callback on clicking the cancel button of the file dialog
 
  inputProps: React.PropTypes.object, // Pass additional attributes to the <input type="file"/> tag
  multiple: React.PropTypes.bool, // Allow dropping multiple files
  accept: React.PropTypes.string, // Allow specific types of files. See https://github.com/okonet/attr-accept for more information
  name: React.PropTypes.string, // name attribute for the input tag
  maxSize: React.PropTypes.number,
  minSize: React.PropTypes.number
};
 
export default Dropzone;