All files / react-dropzone/src index.js

97.64% Statements 124/127
92.94% Branches 79/85
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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428            1x             1x       94x 12x   82x       49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x           47x 47x   47x 46x 46x     47x       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         28x 28x 28x 28x     28x     28x 28x   28x 50x 47x     50x 38x   12x       28x 26x     28x 11x     28x 14x       28x             9x 9x 7x 7x 7x 2x             2x 2x 2x     2x 1x   1x 1x 1x 1x             49x       67x       41x       14x       7x 7x 7x                         94x               94x   94x   94x   94x     94x       94x 91x               91x       91x             94x 11x       83x 3x         80x         94x         139x       94x 1x       94x                     94x 846x   94x                                             1x                 1x                                                                                                                                                
/* eslint prefer-template: 0 */
import React from 'react';
import accepts from 'attr-accept';
import { deprecate } from 'react-is-deprecated';
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();
  }
 
  static renderChildren(children, isDragActive, isDragReject) {
    if (typeof children === 'function') {
      return children({ isDragActive, isDragReject });
    }
    return children;
  }
 
  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
    };
  }
 
  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
    });
  }
 
  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) {
    return 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();
  }
 
  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}
      >
        {Dropzone.renderChildren(children, isDragActive, isDragReject)}
        <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,
 
  // Contents of the dropzone
  children: React.PropTypes.oneOfType([
    React.PropTypes.node,
    React.PropTypes.func
  ]),
 
  // CSS styles to apply
  style: deprecate(
    React.PropTypes.object,
    'Prop style is deprecated. Use function as children to style dropzone and its contents.'
  ),
 
  // CSS styles to apply when drop will be accepted
  activeStyle: deprecate(
    React.PropTypes.object,
    'Prop activeStyle is deprecated. Use function as children to style dropzone and its contents.'
  ),
 
  // CSS styles to apply when drop will be rejected
  rejectStyle: deprecate(
    React.PropTypes.object,
    'Prop rejectStyle is deprecated. Use function as children to style dropzone and its contents.'
  ),
 
  // Optional className
  className: deprecate(
    React.PropTypes.string,
    'Prop className is deprecated. Use function as children to style dropzone and its contents.'
  ),
 
  // className for accepted state
  activeClassName: deprecate(
    React.PropTypes.string,
    'Prop activeClassName is deprecated. Use function as children to style dropzone and its contents.'
  ),
 
  // className for rejected state
  rejectClassName: deprecate(
    React.PropTypes.string,
    'Prop rejectClassName is deprecated. Use function as children to style dropzone and its contents.'
  ),
 
  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: deprecate(
    React.PropTypes.number,
    'Prop maxSize is deprecated and will be removed in the next major release'
  ),
  minSize: deprecate(
    React.PropTypes.number,
    'Prop minSize is deprecated and will be removed in the next major release'
  )
};
 
export default Dropzone;