-
Notifications
You must be signed in to change notification settings - Fork 30.2k
/
Copy pathdnd.ts
731 lines (617 loc) · 24.1 KB
/
dnd.ts
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { hasWorkspaceFileExtension, IWorkspaceFolderCreationData, IRecentFile, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { normalize } from 'vs/base/common/path';
import { basename } from 'vs/base/common/resources';
import { IFileService } from 'vs/platform/files/common/files';
import { IWindowOpenable } from 'vs/platform/windows/common/windows';
import { URI } from 'vs/base/common/uri';
import { ITextFileService, stringToSnapshot } from 'vs/workbench/services/textfile/common/textfiles';
import { Schemas } from 'vs/base/common/network';
import { IEditorViewState } from 'vs/editor/common/editorCommon';
import { DataTransfers, IDragAndDropData } from 'vs/base/browser/dnd';
import { DragMouseEvent } from 'vs/base/browser/mouseEvent';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { MIME_BINARY } from 'vs/base/common/mime';
import { isWindows, isWeb } from 'vs/base/common/platform';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { IEditorIdentifier, GroupIdentifier } from 'vs/workbench/common/editor';
import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService';
import { Disposable, IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { addDisposableListener, EventType, asDomUri } from 'vs/base/browser/dom';
import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IWorkspaceEditingService } from 'vs/workbench/services/workspaces/common/workspaceEditing';
import { withNullAsUndefined } from 'vs/base/common/types';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { isStandalone } from 'vs/base/browser/browser';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { Emitter } from 'vs/base/common/event';
export interface IDraggedResource {
resource: URI;
isExternal: boolean;
}
export class DraggedEditorIdentifier {
constructor(private _identifier: IEditorIdentifier) { }
get identifier(): IEditorIdentifier {
return this._identifier;
}
}
export class DraggedEditorGroupIdentifier {
constructor(private _identifier: GroupIdentifier) { }
get identifier(): GroupIdentifier {
return this._identifier;
}
}
export interface IDraggedEditor extends IDraggedResource {
content?: string;
encoding?: string;
mode?: string;
viewState?: IEditorViewState;
}
export interface ISerializedDraggedEditor {
resource: string;
content?: string;
encoding?: string;
mode?: string;
viewState?: IEditorViewState;
}
export const CodeDataTransfers = {
EDITORS: 'CodeEditors',
FILES: 'CodeFiles'
};
export function extractResources(e: DragEvent, externalOnly?: boolean): Array<IDraggedResource | IDraggedEditor> {
const resources: Array<IDraggedResource | IDraggedEditor> = [];
if (e.dataTransfer && e.dataTransfer.types.length > 0) {
// Check for window-to-window DND
if (!externalOnly) {
// Data Transfer: Code Editors
const rawEditorsData = e.dataTransfer.getData(CodeDataTransfers.EDITORS);
if (rawEditorsData) {
try {
const draggedEditors: ISerializedDraggedEditor[] = JSON.parse(rawEditorsData);
draggedEditors.forEach(draggedEditor => {
resources.push({
resource: URI.parse(draggedEditor.resource),
content: draggedEditor.content,
viewState: draggedEditor.viewState,
encoding: draggedEditor.encoding,
mode: draggedEditor.mode,
isExternal: false
});
});
} catch (error) {
// Invalid transfer
}
}
// Data Transfer: Resources
else {
try {
const rawResourcesData = e.dataTransfer.getData(DataTransfers.RESOURCES);
if (rawResourcesData) {
const uriStrArray: string[] = JSON.parse(rawResourcesData);
resources.push(...uriStrArray.map(uriStr => ({ resource: URI.parse(uriStr), isExternal: false })));
}
} catch (error) {
// Invalid transfer
}
}
}
// Check for native file transfer
if (e.dataTransfer && e.dataTransfer.files) {
for (let i = 0; i < e.dataTransfer.files.length; i++) {
const file = e.dataTransfer.files[i];
if (file?.path /* Electron only */ && !resources.some(r => r.resource.fsPath === file.path) /* prevent duplicates */) {
try {
resources.push({ resource: URI.file(file.path), isExternal: true });
} catch (error) {
// Invalid URI
}
}
}
}
// Check for CodeFiles transfer
const rawCodeFiles = e.dataTransfer.getData(CodeDataTransfers.FILES);
if (rawCodeFiles) {
try {
const codeFiles: string[] = JSON.parse(rawCodeFiles);
codeFiles.forEach(codeFile => {
if (!resources.some(r => r.resource.fsPath === codeFile) /* prevent duplicates */) {
resources.push({ resource: URI.file(codeFile), isExternal: true });
}
});
} catch (error) {
// Invalid transfer
}
}
}
return resources;
}
export interface IResourcesDropHandlerOptions {
/**
* Whether to open the actual workspace when a workspace configuration file is dropped
* or whether to open the configuration file within the editor as normal file.
*/
allowWorkspaceOpen: boolean;
}
/**
* Shared function across some components to handle drag & drop of resources. E.g. of folders and workspace files
* to open them in the window instead of the editor or to handle dirty editors being dropped between instances of Code.
*/
export class ResourcesDropHandler {
constructor(
private options: IResourcesDropHandlerOptions,
@IFileService private readonly fileService: IFileService,
@IWorkspacesService private readonly workspacesService: IWorkspacesService,
@ITextFileService private readonly textFileService: ITextFileService,
@IBackupFileService private readonly backupFileService: IBackupFileService,
@IEditorService private readonly editorService: IEditorService,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService,
@IHostService private readonly hostService: IHostService
) {
}
async handleDrop(event: DragEvent, resolveTargetGroup: () => IEditorGroup | undefined, afterDrop: (targetGroup: IEditorGroup | undefined) => void, targetIndex?: number): Promise<void> {
const untitledOrFileResources = extractResources(event).filter(r => this.fileService.canHandleResource(r.resource) || r.resource.scheme === Schemas.untitled);
if (!untitledOrFileResources.length) {
return;
}
// Make the window active to handle the drop properly within
await this.hostService.focus();
// Check for special things being dropped
const isWorkspaceOpening = await this.doHandleDrop(untitledOrFileResources);
if (isWorkspaceOpening) {
return; // return early if the drop operation resulted in this window changing to a workspace
}
// Add external ones to recently open list unless dropped resource is a workspace
const recentFiles: IRecentFile[] = untitledOrFileResources.filter(d => d.isExternal && d.resource.scheme === Schemas.file).map(d => ({ fileUri: d.resource }));
if (recentFiles.length) {
this.workspacesService.addRecentlyOpened(recentFiles);
}
const editors: IResourceEditorInputType[] = untitledOrFileResources.map(untitledOrFileResource => ({
resource: untitledOrFileResource.resource,
encoding: (untitledOrFileResource as IDraggedEditor).encoding,
mode: (untitledOrFileResource as IDraggedEditor).mode,
options: {
pinned: true,
index: targetIndex,
viewState: (untitledOrFileResource as IDraggedEditor).viewState
}
}));
// Open in Editor
const targetGroup = resolveTargetGroup();
await this.editorService.openEditors(editors, targetGroup);
// Finish with provided function
afterDrop(targetGroup);
}
private async doHandleDrop(untitledOrFileResources: Array<IDraggedResource | IDraggedEditor>): Promise<boolean> {
// Check for dirty editors being dropped
const resourcesWithContent: IDraggedEditor[] = untitledOrFileResources.filter(resource => !resource.isExternal && !!(resource as IDraggedEditor).content);
if (resourcesWithContent.length > 0) {
await Promise.all(resourcesWithContent.map(resourceWithContent => this.handleDirtyEditorDrop(resourceWithContent)));
return false;
}
// Check for workspace file being dropped if we are allowed to do so
if (this.options.allowWorkspaceOpen) {
const externalFileOnDiskResources = untitledOrFileResources.filter(d => d.isExternal && d.resource.scheme === Schemas.file).map(d => d.resource);
if (externalFileOnDiskResources.length > 0) {
return this.handleWorkspaceFileDrop(externalFileOnDiskResources);
}
}
return false;
}
private async handleDirtyEditorDrop(droppedDirtyEditor: IDraggedEditor): Promise<boolean> {
// Untitled: always ensure that we open a new untitled editor for each file we drop
if (droppedDirtyEditor.resource.scheme === Schemas.untitled) {
const untitledEditorResource = this.editorService.createEditorInput({ mode: droppedDirtyEditor.mode, encoding: droppedDirtyEditor.encoding, forceUntitled: true }).resource;
if (untitledEditorResource) {
droppedDirtyEditor.resource = untitledEditorResource;
}
}
// File: ensure the file is not dirty or opened already
else if (this.textFileService.isDirty(droppedDirtyEditor.resource) || this.editorService.isOpen({ resource: droppedDirtyEditor.resource })) {
return false;
}
// If the dropped editor is dirty with content we simply take that
// content and turn it into a backup so that it loads the contents
if (droppedDirtyEditor.content) {
try {
await this.backupFileService.backup(droppedDirtyEditor.resource, stringToSnapshot(droppedDirtyEditor.content));
} catch (e) {
// Ignore error
}
}
return false;
}
private async handleWorkspaceFileDrop(fileOnDiskResources: URI[]): Promise<boolean> {
const toOpen: IWindowOpenable[] = [];
const folderURIs: IWorkspaceFolderCreationData[] = [];
await Promise.all(fileOnDiskResources.map(async fileOnDiskResource => {
// Check for Workspace
if (hasWorkspaceFileExtension(fileOnDiskResource)) {
toOpen.push({ workspaceUri: fileOnDiskResource });
return;
}
// Check for Folder
try {
const stat = await this.fileService.resolve(fileOnDiskResource);
if (stat.isDirectory) {
toOpen.push({ folderUri: stat.resource });
folderURIs.push({ uri: stat.resource });
}
} catch (error) {
// Ignore error
}
}));
// Return early if no external resource is a folder or workspace
if (toOpen.length === 0) {
return false;
}
// Pass focus to window
this.hostService.focus();
// Open in separate windows if we drop workspaces or just one folder
if (toOpen.length > folderURIs.length || folderURIs.length === 1) {
await this.hostService.openWindow(toOpen);
}
// folders.length > 1: Multiple folders: Create new workspace with folders and open
else {
await this.workspaceEditingService.createAndEnterWorkspace(folderURIs);
}
return true;
}
}
export function fillResourceDataTransfers(accessor: ServicesAccessor, resources: (URI | { resource: URI, isDirectory: boolean })[], event: DragMouseEvent | DragEvent): void {
if (resources.length === 0 || !event.dataTransfer) {
return;
}
const sources = resources.map(obj => {
if (URI.isUri(obj)) {
return { resource: obj, isDirectory: false /* assume resource is not a directory */ };
}
return obj;
});
// Text: allows to paste into text-capable areas
const lineDelimiter = isWindows ? '\r\n' : '\n';
event.dataTransfer.setData(DataTransfers.TEXT, sources.map(source => source.resource.scheme === Schemas.file ? normalize(normalizeDriveLetter(source.resource.fsPath)) : source.resource.toString()).join(lineDelimiter));
// Download URL: enables support to drag a tab as file to desktop (only single file supported)
// Disabled for PWA web due to: https://github.com/microsoft/vscode/issues/83441
if (!sources[0].isDirectory && (!isWeb || !isStandalone)) {
event.dataTransfer.setData(DataTransfers.DOWNLOAD_URL, [MIME_BINARY, basename(sources[0].resource), asDomUri(sources[0].resource).toString()].join(':'));
}
// Resource URLs: allows to drop multiple resources to a target in VS Code (not directories)
const files = sources.filter(s => !s.isDirectory);
if (files.length) {
event.dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify(files.map(f => f.resource.toString())));
}
// Editors: enables cross window DND of tabs into the editor area
const textFileService = accessor.get(ITextFileService);
const editorService = accessor.get(IEditorService);
const draggedEditors: ISerializedDraggedEditor[] = [];
files.forEach(file => {
// Try to find editor view state from the visible editors that match given resource
let viewState: IEditorViewState | undefined = undefined;
const textEditorControls = editorService.visibleTextEditorControls;
for (const textEditorControl of textEditorControls) {
if (isCodeEditor(textEditorControl)) {
const model = textEditorControl.getModel();
if (model?.uri?.toString() === file.resource.toString()) {
viewState = withNullAsUndefined(textEditorControl.saveViewState());
break;
}
}
}
// Try to find encoding and mode from text model
let encoding: string | undefined = undefined;
let mode: string | undefined = undefined;
const model = file.resource.scheme === Schemas.untitled ? textFileService.untitled.get(file.resource) : textFileService.files.get(file.resource);
if (model) {
encoding = model.getEncoding();
mode = model.getMode();
}
// If the resource is dirty or untitled, send over its content
// to restore dirty state. Get that from the text model directly
let content: string | undefined = undefined;
if (model?.isDirty()) {
content = model.textEditorModel.getValue();
}
// Add as dragged editor
draggedEditors.push({ resource: file.resource.toString(), content, viewState, encoding, mode });
});
if (draggedEditors.length) {
event.dataTransfer.setData(CodeDataTransfers.EDITORS, JSON.stringify(draggedEditors));
}
}
/**
* A singleton to store transfer data during drag & drop operations that are only valid within the application.
*/
export class LocalSelectionTransfer<T> {
private static readonly INSTANCE = new LocalSelectionTransfer();
private data?: T[];
private proto?: T;
private constructor() {
// protect against external instantiation
}
static getInstance<T>(): LocalSelectionTransfer<T> {
return LocalSelectionTransfer.INSTANCE as LocalSelectionTransfer<T>;
}
hasData(proto: T): boolean {
return proto && proto === this.proto;
}
clearData(proto: T): void {
if (this.hasData(proto)) {
this.proto = undefined;
this.data = undefined;
}
}
getData(proto: T): T[] | undefined {
if (this.hasData(proto)) {
return this.data;
}
return undefined;
}
setData(data: T[], proto: T): void {
if (proto) {
this.data = data;
this.proto = proto;
}
}
}
export interface IDragAndDropObserverCallbacks {
onDragEnter: (e: DragEvent) => void;
onDragLeave: (e: DragEvent) => void;
onDrop: (e: DragEvent) => void;
onDragEnd: (e: DragEvent) => void;
onDragOver?: (e: DragEvent) => void;
}
export class DragAndDropObserver extends Disposable {
// A helper to fix issues with repeated DRAG_ENTER / DRAG_LEAVE
// calls see https://github.com/Microsoft/vscode/issues/14470
// when the element has child elements where the events are fired
// repeadedly.
private counter: number = 0;
constructor(private element: HTMLElement, private callbacks: IDragAndDropObserverCallbacks) {
super();
this.registerListeners();
}
private registerListeners(): void {
this._register(addDisposableListener(this.element, EventType.DRAG_ENTER, (e: DragEvent) => {
this.counter++;
this.callbacks.onDragEnter(e);
}));
this._register(addDisposableListener(this.element, EventType.DRAG_OVER, (e: DragEvent) => {
e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
if (this.callbacks.onDragOver) {
this.callbacks.onDragOver(e);
}
}));
this._register(addDisposableListener(this.element, EventType.DRAG_LEAVE, (e: DragEvent) => {
this.counter--;
if (this.counter === 0) {
this.callbacks.onDragLeave(e);
}
}));
this._register(addDisposableListener(this.element, EventType.DRAG_END, (e: DragEvent) => {
this.counter = 0;
this.callbacks.onDragEnd(e);
}));
this._register(addDisposableListener(this.element, EventType.DROP, (e: DragEvent) => {
this.counter = 0;
this.callbacks.onDrop(e);
}));
}
}
export function containsDragType(event: DragEvent, ...dragTypesToFind: string[]): boolean {
if (!event.dataTransfer) {
return false;
}
const dragTypes = event.dataTransfer.types;
const lowercaseDragTypes: string[] = [];
for (let i = 0; i < dragTypes.length; i++) {
lowercaseDragTypes.push(dragTypes[i].toLowerCase()); // somehow the types are lowercase
}
for (const dragType of dragTypesToFind) {
if (lowercaseDragTypes.indexOf(dragType.toLowerCase()) >= 0) {
return true;
}
}
return false;
}
export interface ICompositeDragAndDrop {
drop(data: IDragAndDropData, target: string | undefined, originalEvent: DragEvent, before?: boolean): void;
onDragOver(data: IDragAndDropData, target: string | undefined, originalEvent: DragEvent): boolean;
onDragEnter(data: IDragAndDropData, target: string | undefined, originalEvent: DragEvent): boolean;
}
export interface ICompositeDragAndDropObserverCallbacks {
onDragEnter?: (e: IDraggedCompositeData) => void;
onDragLeave?: (e: IDraggedCompositeData) => void;
onDrop?: (e: IDraggedCompositeData) => void;
onDragOver?: (e: IDraggedCompositeData) => void;
onDragStart?: (e: IDraggedCompositeData) => void;
onDragEnd?: (e: IDraggedCompositeData) => void;
}
export class CompositeDragAndDropData implements IDragAndDropData {
constructor(private type: 'view' | 'composite', private id: string) { }
update(dataTransfer: DataTransfer): void {
// no-op
}
getData(): {
type: 'view' | 'composite';
id: string;
} {
return { type: this.type, id: this.id };
}
}
export interface IDraggedCompositeData {
eventData: DragEvent;
dragAndDropData: CompositeDragAndDropData;
}
export class DraggedCompositeIdentifier {
constructor(private _compositeId: string) { }
get id(): string {
return this._compositeId;
}
}
export class DraggedViewIdentifier {
constructor(private _viewId: string) { }
get id(): string {
return this._viewId;
}
}
export type ViewType = 'composite' | 'view';
export class CompositeDragAndDropObserver extends Disposable {
private transferData: LocalSelectionTransfer<DraggedCompositeIdentifier | DraggedViewIdentifier>;
private _onDragStart = this._register(new Emitter<IDraggedCompositeData>());
private _onDragEnd = this._register(new Emitter<IDraggedCompositeData>());
private static _instance: CompositeDragAndDropObserver | undefined;
static get INSTANCE(): CompositeDragAndDropObserver {
if (!CompositeDragAndDropObserver._instance) {
CompositeDragAndDropObserver._instance = new CompositeDragAndDropObserver();
}
return CompositeDragAndDropObserver._instance;
}
private constructor() {
super();
this.transferData = LocalSelectionTransfer.getInstance<DraggedCompositeIdentifier | DraggedViewIdentifier>();
}
private readDragData(type: ViewType): CompositeDragAndDropData | undefined {
if (this.transferData.hasData(type === 'view' ? DraggedViewIdentifier.prototype : DraggedCompositeIdentifier.prototype)) {
const data = this.transferData.getData(type === 'view' ? DraggedViewIdentifier.prototype : DraggedCompositeIdentifier.prototype);
if (data && data[0]) {
return new CompositeDragAndDropData(type, data[0].id);
}
}
return undefined;
}
private writeDragData(id: string, type: ViewType): void {
this.transferData.setData([type === 'view' ? new DraggedViewIdentifier(id) : new DraggedCompositeIdentifier(id)], type === 'view' ? DraggedViewIdentifier.prototype : DraggedCompositeIdentifier.prototype);
}
registerTarget(element: HTMLElement, callbacks: ICompositeDragAndDropObserverCallbacks): IDisposable {
const disposableStore = new DisposableStore();
disposableStore.add(new DragAndDropObserver(element, {
onDragEnd: e => {
// no-op
},
onDragEnter: e => {
e.preventDefault();
if (callbacks.onDragEnter) {
const data = this.readDragData('composite') || this.readDragData('view');
if (data) {
callbacks.onDragEnter({ eventData: e, dragAndDropData: data! });
}
}
},
onDragLeave: e => {
const data = this.readDragData('composite') || this.readDragData('view');
if (callbacks.onDragLeave && data) {
callbacks.onDragLeave({ eventData: e, dragAndDropData: data! });
}
},
onDrop: e => {
if (callbacks.onDrop) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
callbacks.onDrop({ eventData: e, dragAndDropData: data! });
// Fire drag event in case drop handler destroys the dragged element
this._onDragEnd.fire({ eventData: e, dragAndDropData: data! });
}
},
onDragOver: e => {
e.preventDefault();
if (callbacks.onDragOver) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
callbacks.onDragOver({ eventData: e, dragAndDropData: data! });
}
}
}));
if (callbacks.onDragStart) {
this._onDragStart.event(e => {
callbacks.onDragStart!(e);
}, this, disposableStore);
}
if (callbacks.onDragEnd) {
this._onDragEnd.event(e => {
callbacks.onDragEnd!(e);
});
}
return this._register(disposableStore);
}
registerDraggable(element: HTMLElement, draggedItemProvider: () => { type: ViewType, id: string }, callbacks: ICompositeDragAndDropObserverCallbacks): IDisposable {
element.draggable = true;
const disposableStore = new DisposableStore();
disposableStore.add(addDisposableListener(element, EventType.DRAG_START, e => {
const { id, type } = draggedItemProvider();
this.writeDragData(id, type);
this._onDragStart.fire({ eventData: e, dragAndDropData: this.readDragData(type)! });
}));
disposableStore.add(new DragAndDropObserver(element, {
onDragEnd: e => {
const { id, type } = draggedItemProvider();
const data = this.readDragData(type);
if (data && data.getData().id === id) {
this.transferData.clearData(type === 'view' ? DraggedViewIdentifier.prototype : DraggedCompositeIdentifier.prototype);
}
if (!data) {
return;
}
this._onDragEnd.fire({ eventData: e, dragAndDropData: data! });
},
onDragEnter: e => {
if (callbacks.onDragEnter) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
if (data) {
callbacks.onDragEnter({ eventData: e, dragAndDropData: data! });
}
}
},
onDragLeave: e => {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
if (callbacks.onDragLeave) {
callbacks.onDragLeave({ eventData: e, dragAndDropData: data! });
}
},
onDrop: e => {
if (callbacks.onDrop) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
callbacks.onDrop({ eventData: e, dragAndDropData: data! });
// Fire drag event in case drop handler destroys the dragged element
this._onDragEnd.fire({ eventData: e, dragAndDropData: data! });
}
},
onDragOver: e => {
if (callbacks.onDragOver) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
callbacks.onDragOver({ eventData: e, dragAndDropData: data! });
}
}
}));
if (callbacks.onDragStart) {
this._onDragStart.event(e => {
callbacks.onDragStart!(e);
}, this, disposableStore);
}
if (callbacks.onDragEnd) {
this._onDragEnd.event(e => {
callbacks.onDragEnd!(e);
});
}
return this._register(disposableStore);
}
}