All files / src/ui drag-drop-file.ts

0% Statements 0/17
0% Branches 0/6
0% Functions 0/4
0% Lines 0/17

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                                                                                                                                                                   
import * as dom from '../dom/dom';
import {DomWatcher} from '../dom/dom-watcher';
import * as is from '../is/is';
 
/**
 * A simple drag and drop file utility.
 * Allows you to drop file onto the screen and start loading the file.
 *
 * Note that this handles ONLY a single file.
 *
 *
 * ```
 *   this.drapDropFile = new DragDropFile(
 *       dropElement,  // The DOM element which a file can be dragged on top of.  "Drop zone" basically.
 *      // Handles drop event.
 *      (data) => {
 *          console.log(data.url); // The local blob url.
 *          console.log(data.file); // More detailed info on the file itself.
 *      }
 *   );
 *
 * ```
 *
 *
 */
export class DragDropFile {
  private dropElement: HTMLElement;
  private watcher: DomWatcher;
  private dropCallback: Function;
 
  constructor(dropzoneElement: HTMLElement, dropCallback: Function) {
    this.dropElement = dropzoneElement;
    this.dropCallback = dropCallback;
    this.watcher = new DomWatcher();
 
    if (!is.supportingFileApis()) {
      console.log('The file apis are not supported for this browser');
      return;
    }
    this.watcher.add({
      element: this.dropElement,
      on: 'dragover',
      callback: this.handleDragOver.bind(this),
    });
    this.watcher.add({
      element: this.dropElement,
      on: 'drop',
      callback: this.handleDrop.bind(this),
    });
  }
 
  private handleDragOver(e: Event): void {
    e.stopPropagation();
    e.preventDefault();
  }
 
  private handleDrop(e: DragEvent): void {
    e.stopPropagation();
    e.preventDefault();
 
    // Fire a drop start event.
    dom.event(this.dropElement, 'drop-start', {});
 
    // Currently support only 1 file.
    // let entries;
    if (e.dataTransfer?.items) {
      // entries = Array.from(e.dataTransfer.items).map(item =>
      //   item.webkitGetAsEntry()
      // );
      const file = e.dataTransfer.files[0];
      this.dropCallback({
        file: file,
        url: URL.createObjectURL(file),
      });
    }
  }
 
  dispose() {
    this.watcher && this.watcher.dispose();
  }
}