dnd.ts 1.9 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

B
Benjamin Pasero 已提交
8
import {$} from 'vs/base/browser/builder';
9
import URI from 'vs/base/common/uri';
E
Erich Gamma 已提交
10 11 12 13 14 15 16 17 18

/**
 * A helper that will execute a provided function when the provided HTMLElement receives
 *  dragover event for 800ms. If the drag is aborted before, the callback will not be triggered.
 */
export class DelayedDragHandler {

	private timeout: number;

B
Benjamin Pasero 已提交
19
	constructor(container: HTMLElement, callback: () => void) {
E
Erich Gamma 已提交
20 21 22 23 24
		$(container).on('dragover', () => {
			if (!this.timeout) {
				this.timeout = setTimeout(() => {
					callback();

B
Benjamin Pasero 已提交
25
					this.timeout = null;
E
Erich Gamma 已提交
26 27 28 29 30 31 32 33 34 35
				}, 800);
			}
		});

		$(container).on(['dragleave', 'drop', 'dragend'], () => this.clearDragTimeout());
	}

	private clearDragTimeout(): void {
		if (this.timeout) {
			clearTimeout(this.timeout);
B
Benjamin Pasero 已提交
36
			this.timeout = null;
E
Erich Gamma 已提交
37 38 39 40 41 42
		}
	}

	public dispose(): void {
		this.clearDragTimeout();
	}
43 44
}

45
export function extractResources(e: DragEvent, externalOnly?: boolean): URI[] {
46 47 48 49
	const resources: URI[] = [];
	if (e.dataTransfer.types.length > 0) {

		// Check for in-app DND
50 51 52 53 54 55 56 57
		if (!externalOnly) {
			const rawData = e.dataTransfer.getData(e.dataTransfer.types[0]);
			if (rawData) {
				try {
					resources.push(URI.parse(rawData));
				} catch (error) {
					// Invalid URI
				}
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
			}
		}

		// Check for native file transfer
		if (e.dataTransfer && e.dataTransfer.files) {
			for (let i = 0; i < e.dataTransfer.files.length; i++) {
				if (e.dataTransfer.files[i] && e.dataTransfer.files[i].path) {
					try {
						resources.push(URI.file(e.dataTransfer.files[i].path));
					} catch (error) {
						// Invalid URI
					}
				}
			}
		}
	}

	return resources;
E
Erich Gamma 已提交
76
}