import { Prop, toNative } from 'vue-facing-decorator'; import TsxComponent, { Component } from '../../app/vuetsx'; interface FileDropZoneArgs { /** CSS class(es) of the zone's root element. The zone has no look of its own, the caller styles it. */ cssClass?: string; /** Class added to the root while a file is dragged over the zone. Defaults to `file-drop-zone--over`. */ overClass?: string; /** When true the zone ignores drags and drops altogether (the browser's default applies). */ disabled?: boolean; /** Raised with every file of a drop, never empty. A dragged link or text is not a file drop and raises nothing. */ filesDropped: (files: File[]) => void; } /** * A region that takes files dropped anywhere on it, children included (a button, a hint, an icon). * * The browser's default for a dropped file is to open it in the tab, replacing the page. A region only * becomes a drop target when its `dragenter` / `dragover` are cancelled, so this wrapper does exactly that * for file drags and hands the files over. Wrap the whole dashed box, not just the button inside it. * * Listens in the CAPTURE phase on purpose: `UploadButton` swallows the drag events on its own button * (`stopPropagation`), so a bubbling listener would neither see the drag enter the button nor * leave it, and would also let the button take the first dropped file a second time. */ @Component class FileDropZoneComponent extends TsxComponent implements FileDropZoneArgs { @Prop() cssClass?: string; @Prop() overClass?: string; @Prop() disabled?: boolean; @Prop() filesDropped!: (files: File[]) => void; private isOver: boolean = false; private get overCssClass(): string { return this.overClass || 'file-drop-zone--over'; } private isFileDrag(e: DragEvent): boolean { return this.disabled !== true && Array.from(e.dataTransfer?.types ?? []).includes('Files'); } private onDragOver(e: DragEvent): void { if (!this.isFileDrag(e)) { return; } e.preventDefault(); if (e.dataTransfer != null) { e.dataTransfer.dropEffect = 'copy'; } this.isOver = true; } private onDragLeave(e: DragEvent): void { // The pointer only moved on to a child of the zone (Safari reports no related target: the next dragenter restores it). if (e.relatedTarget != null && (this.$el as HTMLElement).contains(e.relatedTarget as Node)) { return; } this.isOver = false; } private onDrop(e: DragEvent): void { if (!this.isFileDrag(e)) { return; } e.preventDefault(); e.stopPropagation(); this.isOver = false; const files = Array.from(e.dataTransfer?.files ?? []); if (files.length > 0) { this.filesDropped?.(files); } } render() { return (
this.onDragOver(e)} onDragoverCapture={(e: DragEvent) => this.onDragOver(e)} onDragleaveCapture={(e: DragEvent) => this.onDragLeave(e)} onDropCapture={(e: DragEvent) => this.onDrop(e)} > {this.$slots.default?.()}
); } } const FileDropZone = toNative(FileDropZoneComponent); export default FileDropZone;