| /******************************************************************************** |
| * Copyright (c) 2020 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0 |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ********************************************************************************/ |
| |
| import {Component, ElementRef, EventEmitter, HostListener, Input, Output, ViewChild} from "@angular/core"; |
| |
| @Component({ |
| selector: "app-file-drop", |
| templateUrl: "./file-drop.component.html", |
| styleUrls: ["./file-drop.component.scss"] |
| }) |
| export class FileDropComponent { |
| |
| private static id = 0; |
| |
| @Input() |
| public appDisabled: boolean; |
| |
| @Input() |
| public appId = `FileDropComponent-${FileDropComponent.id++}`; |
| |
| @Input() |
| public appPlaceholder: string; |
| |
| @Output() |
| public appFileDrop = new EventEmitter<File[]>(); |
| |
| @ViewChild("inputElement", {static: true}) |
| public inputElement: ElementRef<HTMLInputElement>; |
| |
| @HostListener("document:dragover", ["$event"]) |
| @HostListener("document:drop", ["$event"]) |
| public onDocumentDrag(event: Event) { |
| if (this.appDisabled) { |
| return; |
| } |
| // Disable default file drop to browser window: |
| event.preventDefault(); |
| } |
| |
| @HostListener("drop", ["$event"]) |
| public onDrop(event: DragEvent) { |
| const files = event?.dataTransfer?.files; |
| if (files != null) { |
| this.onInput(files); |
| } |
| } |
| |
| public openDialog(): void { |
| if (this.appDisabled) { |
| return; |
| } |
| this.inputElement.nativeElement.value = ""; |
| this.inputElement.nativeElement.click(); |
| } |
| |
| public onInput(fileList: FileList) { |
| if (this.appDisabled) { |
| return; |
| } |
| this.appFileDrop.emit(fileListToFileArray(fileList)); |
| } |
| |
| } |
| |
| function fileListToFileArray(fileList: FileList): File[] { |
| try { |
| const result: File[] = []; |
| for (let i = 0; i < fileList.length; i++) { |
| result.push(fileList.item(i)); |
| } |
| return result; |
| } catch (e) { |
| return []; |
| } |
| } |