Debian Codegraph @

packages/dragdrop/src/index.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 /*-----------------------------------------------------------------------------
4 | Copyright (c) 2014-2017, PhosphorJS Contributors
5 |
6 | Distributed under the terms of the BSD 3-Clause License.
7 |
8 | The full license is in the file LICENSE, distributed with this software.
9 |----------------------------------------------------------------------------*/
10 /**
11 * @packageDocumentation
12 * @module dragdrop
13 */
14 import { MimeData } from '@lumino/coreutils';
15
16 import { DisposableDelegate, IDisposable } from '@lumino/disposable';
17
18 /**
19 * @deprecated
20 *
21 * #### Notes
22 * This interface is deprecated. Use Drag.Event instead.
23 */
24 export interface IDragEvent extends Drag.Event {}
25
26 /**
27 * An object which manages a drag-drop operation.
28 *
29 * A drag object dispatches four different events to drop targets:
30 *
31 * - `'lm-dragenter'` - Dispatched when the mouse enters the target
32 * element. This event must be canceled in order to receive any
33 * of the other events.
34 *
35 * - `'lm-dragover'` - Dispatched when the mouse moves over the drop
36 * target. It must cancel the event and set the `dropAction` to one
37 * of the supported actions in order to receive drop events.
38 *
39 * - `'lm-dragleave'` - Dispatched when the mouse leaves the target
40 * element. This includes moving the mouse into child elements.
41 *
42 * - `'lm-drop'`- Dispatched when the mouse is released over the target
43 * element when the target indicates an appropriate drop action. If
44 * the event is canceled, the indicated drop action is returned to
45 * the initiator through the resolved promise.
46 *
47 * A drag operation can be terminated at any time by pressing `Escape`
48 * or by disposing the drag object.
49 *
50 * A drag object has the ability to automatically scroll a scrollable
51 * element when the mouse is hovered near one of its edges. To enable
52 * this, add the `data-lm-dragscroll` attribute to any element which
53 * the drag object should consider for scrolling.
54 *
55 * #### Notes
56 * This class is designed to be used when dragging and dropping custom
57 * data *within* a single application. It is *not* a replacement for
58 * the native drag-drop API. Instead, it provides an API which allows
59 * drag operations to be initiated programmatically and enables the
60 * transfer of arbitrary non-string objects; features which are not
61 * possible with the native drag-drop API.
62 */
63 export class Drag implements IDisposable {
64 /**
65 * Construct a new drag object.
66 *
67 * @param options - The options for initializing the drag.
68 */
69 constructor(options: Drag.IOptions) {
70 this.document = options.document || document;
71 this.mimeData = options.mimeData;
72 this.dragImage = options.dragImage || null;
73 this.proposedAction = options.proposedAction || 'copy';
74 this.supportedActions = options.supportedActions || 'all';
75 this.source = options.source || null;
76 }
77
78 /**
79 * Dispose of the resources held by the drag object.
80 *
81 * #### Notes
82 * This will cancel the drag operation if it is active.
83 */
84 dispose(): void {
85 // Do nothing if the drag object is already disposed.
86 if (this._disposed) {
87 return;
88 }
89 this._disposed = true;
90
91 // If there is a current target, dispatch a drag leave event.
92 if (this._currentTarget) {
93 let event = new PointerEvent('pointerup', {
94 bubbles: true,
95 cancelable: true,
96 clientX: -1,
97 clientY: -1
98 });
99 Private.dispatchDragLeave(this, this._currentTarget, null, event);
100 }
101
102 // Finalize the drag object with `'none'`.
103 this._finalize('none');
104 }
105
106 /**
107 * The mime data for the drag object.
108 */
109 readonly mimeData: MimeData;
110
111 /**
112 * The target document for dragging events.
113 */
114 readonly document: Document | ShadowRoot;
115
116 /**
117 * The drag image element for the drag object.
118 */
119 readonly dragImage: HTMLElement | null;
120
121 /**
122 * The proposed drop action for the drag object.
123 */
124 readonly proposedAction: Drag.DropAction;
125
126 /**
127 * The supported drop actions for the drag object.
128 */
129 readonly supportedActions: Drag.SupportedActions;
130
131 /**
132 * Get the drag source for the drag object.
133 */
134 readonly source: any;
135
136 /**
137 * Test whether the drag object is disposed.
138 */
139 get isDisposed(): boolean {
140 return this._disposed;
141 }
142
143 /**
144 * Start the drag operation at the specified client position.
145 *
146 * @param clientX - The client X position for the drag start.
147 *
148 * @param clientY - The client Y position for the drag start.
149 *
150 * @returns A promise which resolves to the result of the drag.
151 *
152 * #### Notes
153 * If the drag has already been started, the promise created by the
154 * first call to `start` is returned.
155 *
156 * If the drag operation has ended, or if the drag object has been
157 * disposed, the returned promise will resolve to `'none'`.
158 *
159 * The drag object will be automatically disposed when drag operation
160 * completes. This means `Drag` objects are for single-use only.
161 *
162 * This method assumes the left mouse button is already held down.
163 */
164 start(clientX: number, clientY: number): Promise<Drag.DropAction> {
165 // If the drag object is already disposed, resolve to `none`.
166 if (this._disposed) {
167 return Promise.resolve('none');
168 }
169
170 // If the drag has already been started, return the promise.
171 if (this._promise) {
172 return this._promise;
173 }
174
175 // Install the document listeners for the drag object.
176 this._addListeners();
177
178 // Attach the drag image at the specified client position.
179 this._attachDragImage(clientX, clientY);
180
181 // Create the promise which will be resolved on completion.
182 this._promise = new Promise<Drag.DropAction>(resolve => {
183 this._resolve = resolve;
184 });
185
186 // Trigger a fake move event to kick off the drag operation.
187 let event = new PointerEvent('pointermove', {
188 bubbles: true,
189 cancelable: true,
190 clientX,
191 clientY
192 });
193 document.dispatchEvent(event);
194
195 // Return the pending promise for the drag operation.
196 return this._promise;
197 }
198
199 /**
200 * Handle the DOM events for the drag operation.
201 *
202 * @param event - The DOM event sent to the drag object.
203 *
204 * #### Notes
205 * This method implements the DOM `EventListener` interface and is
206 * called in response to events on the document. It should not be
207 * called directly by user code.
208 */
209 handleEvent(event: Event): void {
210 switch (event.type) {
211 case 'pointermove':
212 this._evtPointerMove(event as PointerEvent);
213 break;
214 case 'pointerup':
215 this._evtPointerUp(event as PointerEvent);
216 break;
217 case 'keydown':
218 this._evtKeyDown(event as KeyboardEvent);
219 break;
220 default:
221 // Stop all other events during drag-drop.
222 event.preventDefault();
223 event.stopPropagation();
224 break;
225 }
226 }
227
228 /**
229 * Move the drag image element to the specified location.
230 *
231 * This is a no-op if there is no drag image element.
232 */
233 protected moveDragImage(clientX: number, clientY: number): void {
234 if (!this.dragImage) {
235 return;
236 }
237 let style = this.dragImage.style;
238 style.transform = `translate(${clientX}px, ${clientY}px)`;
239 }
240
241 /**
242 * Handle the `'pointermove'` event for the drag object.
243 */
244 private _evtPointerMove(event: PointerEvent): void {
245 // Stop all input events during drag-drop.
246 event.preventDefault();
247 event.stopPropagation();
248
249 // Update the current target node and dispatch enter/leave events.
250 this._updateCurrentTarget(event);
251
252 // Update the drag scroll element.
253 this._updateDragScroll(event);
254
255 // Move the drag image to the specified client position. This is
256 // performed *after* dispatching to prevent unnecessary reflows.
257 this.moveDragImage(event.clientX, event.clientY);
258 }
259
260 /**
261 * Handle the `'pointerup'` event for the drag object.
262 */
263 private _evtPointerUp(event: PointerEvent): void {
264 // Stop all input events during drag-drop.
265 event.preventDefault();
266 event.stopPropagation();
267
268 // Do nothing if the left button is not released.
269 if (event.button !== 0) {
270 return;
271 }
272
273 // Update the current target node and dispatch enter/leave events.
274 // This prevents a subtle issue where the DOM mutates under the
275 // cursor after the last move event but before the drop event.
276 this._updateCurrentTarget(event);
277
278 // If there is no current target, finalize with `'none'`.
279 if (!this._currentTarget) {
280 this._finalize('none');
281 return;
282 }
283
284 // If the last drop action was `'none'`, dispatch a leave event
285 // to the current target and finalize the drag with `'none'`.
286 if (this._dropAction === 'none') {
287 Private.dispatchDragLeave(this, this._currentTarget, null, event);
288 this._finalize('none');
289 return;
290 }
291
292 // Dispatch the drop event at the current target and finalize
293 // with the resulting drop action.
294 let action = Private.dispatchDrop(this, this._currentTarget, event);
295 this._finalize(action);
296 }
297
298 /**
299 * Handle the `'keydown'` event for the drag object.
300 */
301 private _evtKeyDown(event: KeyboardEvent): void {
302 // Stop all input events during drag-drop.
303 event.preventDefault();
304 event.stopPropagation();
305
306 // Cancel the drag if `Escape` is pressed.
307 if (event.keyCode === 27) {
308 this.dispose();
309 }
310 }
311
312 /**
313 * Add the document event listeners for the drag object.
314 */
315 private _addListeners(): void {
316 document.addEventListener('pointerdown', this, true);
317 document.addEventListener('pointermove', this, true);
318 document.addEventListener('pointerup', this, true);
319 document.addEventListener('pointerenter', this, true);
320 document.addEventListener('pointerleave', this, true);
321 document.addEventListener('pointerover', this, true);
322 document.addEventListener('pointerout', this, true);
323 document.addEventListener('keydown', this, true);
324 document.addEventListener('keyup', this, true);
325 document.addEventListener('keypress', this, true);
326 document.addEventListener('contextmenu', this, true);
327 }
328
329 /**
330 * Remove the document event listeners for the drag object.
331 */
332 private _removeListeners(): void {
333 document.removeEventListener('pointerdown', this, true);
334 document.removeEventListener('pointermove', this, true);
335 document.removeEventListener('pointerup', this, true);
336 document.removeEventListener('pointerenter', this, true);
337 document.removeEventListener('pointerleave', this, true);
338 document.removeEventListener('pointerover', this, true);
339 document.removeEventListener('pointerout', this, true);
340 document.removeEventListener('keydown', this, true);
341 document.removeEventListener('keyup', this, true);
342 document.removeEventListener('keypress', this, true);
343 document.removeEventListener('contextmenu', this, true);
344 }
345
346 /**
347 * Update the drag scroll element under the mouse.
348 */
349 private _updateDragScroll(event: PointerEvent): void {
350 // Find the scroll target under the mouse.
351 let target = Private.findScrollTarget(event);
352
353 // Bail if there is nothing to scroll.
354 if (!this._scrollTarget && !target) {
355 return;
356 }
357
358 // Start the scroll loop if needed.
359 if (!this._scrollTarget) {
360 setTimeout(this._onScrollFrame, 500);
361 }
362
363 // Update the scroll target.
364 this._scrollTarget = target;
365 }
366
367 /**
368 * Update the current target node using the given mouse event.
369 */
370 private _updateCurrentTarget(event: PointerEvent): void {
371 // Fetch common local state.
372 let prevTarget = this._currentTarget;
373 let currTarget = this._currentTarget;
374 let prevElem = this._currentElement;
375
376 // Find the current indicated element at the given position.
377 let currElem = Private.findElementBehindBackdrop(event, this.document);
378
379 // Update the current element reference.
380 this._currentElement = currElem;
381
382 // If the indicated element changes from the previous iteration,
383 // and is different from the current target, dispatch the exit
384 // event to the target.
385 if (currElem !== prevElem && currElem !== currTarget) {
386 Private.dispatchDragExit(this, currTarget, currElem, event);
387 }
388
389 // If the indicated element changes from the previous iteration,
390 // and is different from the current target, dispatch the enter
391 // event and compute the new target element.
392 if (currElem !== prevElem && currElem !== currTarget) {
393 currTarget = Private.dispatchDragEnter(this, currElem, currTarget, event);
394 }
395
396 // If the current target element has changed, update the current
397 // target reference and dispatch the leave event to the old target.
398 if (currTarget !== prevTarget) {
399 this._currentTarget = currTarget;
400 Private.dispatchDragLeave(this, prevTarget, currTarget, event);
401 }
402
403 // Dispatch the drag over event and update the drop action.
404 let action = Private.dispatchDragOver(this, currTarget, event);
405 this._setDropAction(action);
406 }
407
408 /**
409 * Attach the drag image element at the specified location.
410 *
411 * This is a no-op if there is no drag image element.
412 */
413 private _attachDragImage(clientX: number, clientY: number): void {
414 if (!this.dragImage) {
415 return;
416 }
417 this.dragImage.classList.add('lm-mod-drag-image');
418 let style = this.dragImage.style;
419 style.pointerEvents = 'none';
420 style.position = 'fixed';
421 style.transform = `translate(${clientX}px, ${clientY}px)`;
422 const body =
423 this.document instanceof Document
424 ? this.document.body
425 : (this.document.firstElementChild as HTMLElement);
426 body.appendChild(this.dragImage);
427 }
428
429 /**
430 * Detach the drag image element from the DOM.
431 *
432 * This is a no-op if there is no drag image element.
433 */
434 private _detachDragImage(): void {
435 if (!this.dragImage) {
436 return;
437 }
438 let parent = this.dragImage.parentNode;
439 if (!parent) {
440 return;
441 }
442 parent.removeChild(this.dragImage);
443 }
444
445 /**
446 * Set the internal drop action state and update the drag cursor.
447 */
448 private _setDropAction(action: Drag.DropAction): void {
449 action = Private.validateAction(action, this.supportedActions);
450 if (this._override && this._dropAction === action) {
451 return;
452 }
453 switch (action) {
454 case 'none':
455 this._dropAction = action;
456 this._override = Drag.overrideCursor('no-drop', this.document);
457 break;
458 case 'copy':
459 this._dropAction = action;
460 this._override = Drag.overrideCursor('copy', this.document);
461 break;
462 case 'link':
463 this._dropAction = action;
464 this._override = Drag.overrideCursor('alias', this.document);
465 break;
466 case 'move':
467 this._dropAction = action;
468 this._override = Drag.overrideCursor('move', this.document);
469 break;
470 }
471 }
472
473 /**
474 * Finalize the drag operation and resolve the drag promise.
475 */
476 private _finalize(action: Drag.DropAction): void {
477 // Store the resolve function as a temp variable.
478 let resolve = this._resolve;
479
480 // Remove the document event listeners.
481 this._removeListeners();
482
483 // Detach the drag image.
484 this._detachDragImage();
485
486 // Dispose of the cursor override.
487 if (this._override) {
488 this._override.dispose();
489 this._override = null;
490 }
491
492 // Clear the mime data.
493 this.mimeData.clear();
494
495 // Clear the rest of the internal drag state.
496 this._disposed = true;
497 this._dropAction = 'none';
498 this._currentTarget = null;
499 this._currentElement = null;
500 this._scrollTarget = null;
501 this._promise = null;
502 this._resolve = null;
503
504 // Finally, resolve the promise to the given drop action.
505 if (resolve) {
506 resolve(action);
507 }
508 }
509
510 /**
511 * The scroll loop handler function.
512 */
513 private _onScrollFrame = () => {
514 // Bail early if there is no scroll target.
515 if (!this._scrollTarget) {
516 return;
517 }
518
519 // Unpack the scroll target.
520 let { element, edge, distance } = this._scrollTarget;
521
522 // Calculate the scroll delta using nonlinear acceleration.
523 let d = Private.SCROLL_EDGE_SIZE - distance;
524 let f = Math.pow(d / Private.SCROLL_EDGE_SIZE, 2);
525 let s = Math.max(1, Math.round(f * Private.SCROLL_EDGE_SIZE));
526
527 // Scroll the element in the specified direction.
528 switch (edge) {
529 case 'top':
530 element.scrollTop -= s;
531 break;
532 case 'left':
533 element.scrollLeft -= s;
534 break;
535 case 'right':
536 element.scrollLeft += s;
537 break;
538 case 'bottom':
539 element.scrollTop += s;
540 break;
541 }
542
543 // Request the next cycle of the scroll loop.
544 requestAnimationFrame(this._onScrollFrame);
545 };
546
547 private _disposed = false;
548 private _dropAction: Drag.DropAction = 'none';
549 private _override: IDisposable | null = null;
550 private _currentTarget: Element | null = null;
551 private _currentElement: Element | null = null;
552 private _promise: Promise<Drag.DropAction> | null = null;
553 private _scrollTarget: Private.IScrollTarget | null = null;
554 private _resolve: ((value: Drag.DropAction) => void) | null = null;
555 }
556
557 /**
558 * The namespace for the `Drag` class statics.
559 */
560 export namespace Drag {
561 /**
562 * A type alias which defines the possible independent drop actions.
563 */
564 export type DropAction = 'none' | 'copy' | 'link' | 'move';
565
566 /**
567 * A type alias which defines the possible supported drop actions.
568 */
569 export type SupportedActions =
570 | DropAction
571 | 'copy-link'
572 | 'copy-move'
573 | 'link-move'
574 | 'all';
575
576 /**
577 * An options object for initializing a `Drag` object.
578 */
579 export interface IOptions {
580 /**
581 * The root element for dragging DOM artifacts (defaults to document).
582 */
583 document?: Document | ShadowRoot;
584
585 /**
586 * The populated mime data for the drag operation.
587 */
588 mimeData: MimeData;
589
590 /**
591 * An optional drag image which follows the mouse cursor.
592 *
593 * #### Notes
594 * The drag image can be any DOM element. It is not limited to
595 * image or canvas elements as with the native drag-drop APIs.
596 *
597 * If provided, this will be positioned at the mouse cursor on each
598 * mouse move event. A CSS transform can be used to offset the node
599 * from its specified position.
600 *
601 * The drag image will automatically have the `lm-mod-drag-image`
602 * class name added.
603 *
604 * The default value is `null`.
605 */
606 dragImage?: HTMLElement;
607
608 /**
609 * The optional proposed drop action for the drag operation.
610 *
611 * #### Notes
612 * This can be provided as a hint to the drop targets as to which
613 * drop action is preferred.
614 *
615 * The default value is `'copy'`.
616 */
617 proposedAction?: DropAction;
618
619 /**
620 * The drop actions supported by the drag initiator.
621 *
622 * #### Notes
623 * A drop target must indicate that it intends to perform one of the
624 * supported actions in order to receive a drop event. However, it is
625 * not required to *actually* perform that action when handling the
626 * drop event. Therefore, the initiator must be prepared to handle
627 * any drop action performed by a drop target.
628 *
629 * The default value is `'all'`.
630 */
631 supportedActions?: SupportedActions;
632
633 /**
634 * An optional object which indicates the source of the drag.
635 *
636 * #### Notes
637 * For advanced applications, the drag initiator may wish to expose
638 * a source object to the drop targets. That object can be specified
639 * here and will be carried along with the drag events.
640 *
641 * The default value is `null`.
642 */
643 source?: any;
644 }
645
646 /**
647 * A custom event used for drag-drop operations.
648 *
649 * #### Notes
650 * In order to receive `'lm-dragover'`, `'lm-dragleave'`, or `'lm-drop'`
651 * events, a drop target must cancel the `'lm-dragenter'` event by
652 * calling the event's `preventDefault()` method.
653 */
654 export class Event extends DragEvent {
655 constructor(event: PointerEvent, options: Event.IOptions) {
656 super(options.type, {
657 bubbles: true,
658 cancelable: true,
659 altKey: event.altKey,
660 button: event.button,
661 clientX: event.clientX,
662 clientY: event.clientY,
663 ctrlKey: event.ctrlKey,
664 detail: 0,
665 metaKey: event.metaKey,
666 relatedTarget: options.related,
667 screenX: event.screenX,
668 screenY: event.screenY,
669 shiftKey: event.shiftKey,
670 view: window
671 });
672
673 const { drag } = options;
674 this.dropAction = 'none';
675 this.mimeData = drag.mimeData;
676 this.proposedAction = drag.proposedAction;
677 this.supportedActions = drag.supportedActions;
678 this.source = drag.source;
679 }
680
681 /**
682 * The drop action supported or taken by the drop target.
683 *
684 * #### Notes
685 * At the start of each event, this value will be `'none'`. During a
686 * `'lm-dragover'` event, the drop target must set this value to one
687 * of the supported actions, or the drop event will not occur.
688 *
689 * When handling the drop event, the drop target should set this
690 * to the action which was *actually* taken. This value will be
691 * reported back to the drag initiator.
692 */
693 dropAction: DropAction;
694
695 /**
696 * The drop action proposed by the drag initiator.
697 *
698 * #### Notes
699 * This is the action which is *preferred* by the drag initiator. The
700 * drop target is not required to perform this action, but should if
701 * it all possible.
702 */
703 readonly proposedAction: DropAction;
704
705 /**
706 * The drop actions supported by the drag initiator.
707 *
708 * #### Notes
709 * If the `dropAction` is not set to one of the supported actions
710 * during the `'lm-dragover'` event, the drop event will not occur.
711 */
712 readonly supportedActions: SupportedActions;
713
714 /**
715 * The mime data associated with the event.
716 *
717 * #### Notes
718 * This is mime data provided by the drag initiator. Drop targets
719 * should use this data to determine if they can handle the drop.
720 */
721 readonly mimeData: MimeData;
722
723 /**
724 * The source object of the drag, as provided by the drag initiator.
725 *
726 * #### Notes
727 * For advanced applications, the drag initiator may wish to expose
728 * a source object to the drop targets. That will be provided here
729 * if given by the drag initiator, otherwise it will be `null`.
730 */
731 readonly source: any;
732 }
733
734 /**
735 * The namespace for the `Event` class statics.
736 */
737 export namespace Event {
738 /**
739 * An options object for initializing a `Drag` object.
740 */
741 export interface IOptions {
742 /**
743 * The drag object to use for seeding the drag data.
744 */
745 drag: Drag;
746
747 /**
748 * The related target for the event, or `null`.
749 */
750 related: Element | null;
751
752 /**
753 * The drag event type.
754 */
755 type:
756 | 'lm-dragenter'
757 | 'lm-dragexit'
758 | 'lm-dragleave'
759 | 'lm-dragover'
760 | 'lm-drop';
761 }
762 }
763
764 /**
765 * Override the cursor icon for the entire document.
766 *
767 * @param cursor - The string representing the cursor style.
768 *
769 * @returns A disposable which will clear the override when disposed.
770 *
771 * #### Notes
772 * The most recent call to `overrideCursor` takes precedence.
773 * Disposing an old override has no effect on the current override.
774 *
775 * This utility function is used by the `Drag` class to override the
776 * mouse cursor during a drag-drop operation, but it can also be used
777 * by other classes to fix the cursor icon during normal mouse drags.
778 *
779 * #### Example
780 * ```typescript
781 * import { Drag } from '@lumino/dragdrop';
782 *
783 * // Force the cursor to be 'wait' for the entire document.
784 * let override = Drag.overrideCursor('wait');
785 *
786 * // Clear the override by disposing the return value.
787 * override.dispose();
788 * ```
789 */
790 export function overrideCursor(
791 cursor: string,
792 doc: Document | ShadowRoot = document
793 ): IDisposable {
794 return Private.overrideCursor(cursor, doc);
795 }
796 }
797
798 /**
799 * The namespace for the module implementation details.
800 */
801 namespace Private {
802 /**
803 * The size of a drag scroll edge, in pixels.
804 */
805 export const SCROLL_EDGE_SIZE = 20;
806
807 /**
808 * Validate the given action is one of the supported actions.
809 *
810 * Returns the given action or `'none'` if the action is unsupported.
811 */
812 export function validateAction(
813 action: Drag.DropAction,
814 supported: Drag.SupportedActions
815 ): Drag.DropAction {
816 return actionTable[action] & supportedTable[supported] ? action : 'none';
817 }
818
819 /**
820 * An object which holds the scroll target data.
821 */
822 export interface IScrollTarget {
823 /**
824 * The element to be scrolled.
825 */
826 element: Element;
827
828 /**
829 * The scroll edge underneath the mouse.
830 */
831 edge: 'top' | 'left' | 'right' | 'bottom';
832
833 /**
834 * The distance from the mouse to the scroll edge.
835 */
836 distance: number;
837 }
838
839 /**
840 * Find the event target using pointer position if given, or otherwise
841 * the central position of the backdrop.
842 */
843 export function findElementBehindBackdrop(
844 event?: PointerEvent,
845 root: Document | ShadowRoot = document
846 ) {
847 if (event) {
848 // Check if we already cached element for this event.
849 if (lastElementEventSearch && event == lastElementEventSearch.event) {
850 return lastElementEventSearch.element;
851 }
852 Private.cursorBackdrop.style.zIndex = '-1000';
853 const element: Element | null = root.elementFromPoint(
854 event.clientX,
855 event.clientY
856 );
857 Private.cursorBackdrop.style.zIndex = '';
858 lastElementEventSearch = { event, element };
859 return element;
860 } else {
861 const transform = cursorBackdrop.style.transform;
862 if (lastElementSearch && transform === lastElementSearch.transform) {
863 return lastElementSearch.element;
864 }
865 const bbox = Private.cursorBackdrop.getBoundingClientRect();
866 Private.cursorBackdrop.style.zIndex = '-1000';
867 const element = root.elementFromPoint(
868 bbox.left + bbox.width / 2,
869 bbox.top + bbox.height / 2
870 );
871 Private.cursorBackdrop.style.zIndex = '';
872 lastElementSearch = { transform, element };
873 return element;
874 }
875 }
876
877 let lastElementEventSearch: {
878 event: PointerEvent;
879 element: Element | null;
880 } | null = null;
881 let lastElementSearch: {
882 transform: string;
883 element: Element | null;
884 } | null = null;
885
886 /**
887 * Find the drag scroll target under the mouse, if any.
888 */
889 export function findScrollTarget(event: PointerEvent): IScrollTarget | null {
890 // Look up the client mouse position.
891 let x = event.clientX;
892 let y = event.clientY;
893
894 // Get the element under the mouse.
895 let element: Element | null = findElementBehindBackdrop(event);
896
897 // Search for a scrollable target based on the mouse position.
898 // The null assert in third clause of for-loop is required due to:
899 // https://github.com/Microsoft/TypeScript/issues/14143
900 for (; element; element = element!.parentElement) {
901 // Ignore elements which are not marked as scrollable.
902 if (!element.hasAttribute('data-lm-dragscroll')) {
903 continue;
904 }
905
906 // Set up the coordinate offsets for the element.
907 let offsetX = 0;
908 let offsetY = 0;
909 if (element === document.body) {
910 offsetX = window.pageXOffset;
911 offsetY = window.pageYOffset;
912 }
913
914 // Get the element bounds in viewport coordinates.
915 let r = element.getBoundingClientRect();
916 let top = r.top + offsetY;
917 let left = r.left + offsetX;
918 let right = left + r.width;
919 let bottom = top + r.height;
920
921 // Skip the element if it's not under the mouse.
922 if (x < left || x >= right || y < top || y >= bottom) {
923 continue;
924 }
925
926 // Compute the distance to each edge.
927 let dl = x - left + 1;
928 let dt = y - top + 1;
929 let dr = right - x;
930 let db = bottom - y;
931
932 // Find the smallest of the edge distances.
933 let distance = Math.min(dl, dt, dr, db);
934
935 // Skip the element if the mouse is not within a scroll edge.
936 if (distance > SCROLL_EDGE_SIZE) {
937 continue;
938 }
939
940 // Set up the edge result variable.
941 let edge: 'top' | 'left' | 'right' | 'bottom';
942
943 // Find the edge for the computed distance.
944 switch (distance) {
945 case db:
946 edge = 'bottom';
947 break;
948 case dt:
949 edge = 'top';
950 break;
951 case dr:
952 edge = 'right';
953 break;
954 case dl:
955 edge = 'left';
956 break;
957 default:
958 throw 'unreachable';
959 }
960
961 // Compute how much the element can scroll in width and height.
962 let dsw = element.scrollWidth - element.clientWidth;
963 let dsh = element.scrollHeight - element.clientHeight;
964
965 // Determine if the element should be scrolled for the edge.
966 let shouldScroll: boolean;
967 switch (edge) {
968 case 'top':
969 shouldScroll = dsh > 0 && element.scrollTop > 0;
970 break;
971 case 'left':
972 shouldScroll = dsw > 0 && element.scrollLeft > 0;
973 break;
974 case 'right':
975 shouldScroll = dsw > 0 && element.scrollLeft < dsw;
976 break;
977 case 'bottom':
978 shouldScroll = dsh > 0 && element.scrollTop < dsh;
979 break;
980 default:
981 throw 'unreachable';
982 }
983
984 // Skip the element if it should not be scrolled.
985 if (!shouldScroll) {
986 continue;
987 }
988
989 // Return the drag scroll target.
990 return { element, edge, distance };
991 }
992
993 // No drag scroll target was found.
994 return null;
995 }
996
997 /**
998 * Dispatch a drag enter event to the indicated element.
999 *
1000 * @param drag - The drag object associated with the action.
1001 *
1002 * @param currElem - The currently indicated element, or `null`. This
1003 * is the "immediate user selection" from the whatwg spec.
1004 *
1005 * @param currTarget - The current drag target element, or `null`. This
1006 * is the "current target element" from the whatwg spec.
1007 *
1008 * @param event - The mouse event related to the action.
1009 *
1010 * @returns The element to use as the current drag target. This is the
1011 * "current target element" from the whatwg spec, and may be `null`.
1012 *
1013 * #### Notes
1014 * This largely implements the drag enter portion of the whatwg spec:
1015 * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
1016 */
1017 export function dispatchDragEnter(
1018 drag: Drag,
1019 currElem: Element | null,
1020 currTarget: Element | null,
1021 event: PointerEvent
1022 ): Element | null {
1023 // If the current element is null, return null as the new target.
1024 if (!currElem) {
1025 return null;
1026 }
1027
1028 // Dispatch a drag enter event to the current element.
1029 let dragEvent = new Drag.Event(event, {
1030 drag,
1031 related: currTarget,
1032 type: 'lm-dragenter'
1033 });
1034 let canceled = !currElem.dispatchEvent(dragEvent);
1035
1036 // If the event was canceled, use the current element as the new target.
1037 if (canceled) {
1038 return currElem;
1039 }
1040
1041 // If the current element is the document body, keep the original target.
1042 const body =
1043 drag.document instanceof Document
1044 ? drag.document.body
1045 : (drag.document.firstElementChild as HTMLElement);
1046
1047 if (currElem === body) {
1048 return currTarget;
1049 }
1050
1051 // Dispatch a drag enter event on the document body.
1052 dragEvent = new Drag.Event(event, {
1053 drag,
1054 related: currTarget,
1055 type: 'lm-dragenter'
1056 });
1057 body.dispatchEvent(dragEvent);
1058
1059 // Ignore the event cancellation, and use the body as the new target.
1060 return body;
1061 }
1062
1063 /**
1064 * Dispatch a drag exit event to the indicated element.
1065 *
1066 * @param drag - The drag object associated with the action.
1067 *
1068 * @param prevTarget - The previous target element, or `null`. This
1069 * is the previous "current target element" from the whatwg spec.
1070 *
1071 * @param currTarget - The current drag target element, or `null`. This
1072 * is the "current target element" from the whatwg spec.
1073 *
1074 * @param event - The mouse event related to the action.
1075 *
1076 * #### Notes
1077 * This largely implements the drag exit portion of the whatwg spec:
1078 * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
1079 */
1080 export function dispatchDragExit(
1081 drag: Drag,
1082 prevTarget: Element | null,
1083 currTarget: Element | null,
1084 event: PointerEvent
1085 ): void {
1086 // If the previous target is null, do nothing.
1087 if (!prevTarget) {
1088 return;
1089 }
1090
1091 // Dispatch the drag exit event to the previous target.
1092 let dragEvent = new Drag.Event(event, {
1093 drag,
1094 related: currTarget,
1095 type: 'lm-dragexit'
1096 });
1097 prevTarget.dispatchEvent(dragEvent);
1098 }
1099
1100 /**
1101 * Dispatch a drag leave event to the indicated element.
1102 *
1103 * @param drag - The drag object associated with the action.
1104 *
1105 * @param prevTarget - The previous target element, or `null`. This
1106 * is the previous "current target element" from the whatwg spec.
1107 *
1108 * @param currTarget - The current drag target element, or `null`. This
1109 * is the "current target element" from the whatwg spec.
1110 *
1111 * @param event - The mouse event related to the action.
1112 *
1113 * #### Notes
1114 * This largely implements the drag leave portion of the whatwg spec:
1115 * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
1116 */
1117 export function dispatchDragLeave(
1118 drag: Drag,
1119 prevTarget: Element | null,
1120 currTarget: Element | null,
1121 event: PointerEvent
1122 ): void {
1123 // If the previous target is null, do nothing.
1124 if (!prevTarget) {
1125 return;
1126 }
1127
1128 // Dispatch the drag leave event to the previous target.
1129 let dragEvent = new Drag.Event(event, {
1130 drag,
1131 related: currTarget,
1132 type: 'lm-dragleave'
1133 });
1134 prevTarget.dispatchEvent(dragEvent);
1135 }
1136
1137 /**
1138 * Dispatch a drag over event to the indicated element.
1139 *
1140 * @param drag - The drag object associated with the action.
1141 *
1142 * @param currTarget - The current drag target element, or `null`. This
1143 * is the "current target element" from the whatwg spec.
1144 *
1145 * @param event - The mouse event related to the action.
1146 *
1147 * @returns The `DropAction` result of the drag over event.
1148 *
1149 * #### Notes
1150 * This largely implements the drag over portion of the whatwg spec:
1151 * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
1152 */
1153 export function dispatchDragOver(
1154 drag: Drag,
1155 currTarget: Element | null,
1156 event: PointerEvent
1157 ): Drag.DropAction {
1158 // If there is no current target, the drop action is none.
1159 if (!currTarget) {
1160 return 'none';
1161 }
1162
1163 // Dispatch the drag over event to the current target.
1164 let dragEvent = new Drag.Event(event, {
1165 drag,
1166 related: null,
1167 type: 'lm-dragover'
1168 });
1169 let canceled = !currTarget.dispatchEvent(dragEvent);
1170
1171 // If the event was canceled, return the drop action result.
1172 if (canceled) {
1173 return dragEvent.dropAction;
1174 }
1175
1176 // Otherwise, the effective drop action is none.
1177 return 'none';
1178 }
1179
1180 /**
1181 * Dispatch a drop event to the indicated element.
1182 *
1183 * @param drag - The drag object associated with the action.
1184 *
1185 * @param currTarget - The current drag target element, or `null`. This
1186 * is the "current target element" from the whatwg spec.
1187 *
1188 * @param event - The mouse event related to the action.
1189 *
1190 * @returns The `DropAction` result of the drop event.
1191 *
1192 * #### Notes
1193 * This largely implements the drag over portion of the whatwg spec:
1194 * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
1195 */
1196 export function dispatchDrop(
1197 drag: Drag,
1198 currTarget: Element | null,
1199 event: PointerEvent
1200 ): Drag.DropAction {
1201 // If there is no current target, the drop action is none.
1202 if (!currTarget) {
1203 return 'none';
1204 }
1205
1206 // Dispatch the drop event to the current target.
1207 let dragEvent = new Drag.Event(event, {
1208 drag,
1209 related: null,
1210 type: 'lm-drop'
1211 });
1212 let canceled = !currTarget.dispatchEvent(dragEvent);
1213
1214 // If the event was canceled, return the drop action result.
1215 if (canceled) {
1216 return dragEvent.dropAction;
1217 }
1218
1219 // Otherwise, the effective drop action is none.
1220 return 'none';
1221 }
1222
1223 /**
1224 * A lookup table from drop action to bit value.
1225 */
1226 const actionTable: { [key: string]: number } = {
1227 none: 0x0,
1228 copy: 0x1,
1229 link: 0x2,
1230 move: 0x4
1231 };
1232
1233 /**
1234 * A lookup table from supported action to drop action bit mask.
1235 */
1236 const supportedTable: { [key: string]: number } = {
1237 none: actionTable['none'],
1238 copy: actionTable['copy'],
1239 link: actionTable['link'],
1240 move: actionTable['move'],
1241 'copy-link': actionTable['copy'] | actionTable['link'],
1242 'copy-move': actionTable['copy'] | actionTable['move'],
1243 'link-move': actionTable['link'] | actionTable['move'],
1244 all: actionTable['copy'] | actionTable['link'] | actionTable['move']
1245 };
1246
1247 /**
1248 * Implementation of `Drag.overrideCursor`.
1249 */
1250 export function overrideCursor(
1251 cursor: string,
1252 doc: Document | ShadowRoot = document
1253 ): IDisposable {
1254 let id = ++overrideCursorID;
1255 const body =
1256 doc instanceof Document
1257 ? doc.body
1258 : (doc.firstElementChild as HTMLElement);
1259 if (!cursorBackdrop.isConnected) {
1260 // Hide the backdrop until the pointer moves to avoid issues with
1261 // native double click detection, used in e.g. datagrid editing.
1262 cursorBackdrop.style.transform = 'scale(0)';
1263 body.appendChild(cursorBackdrop);
1264 resetBackdropScroll();
1265 document.addEventListener('pointermove', alignBackdrop, {
1266 capture: true,
1267 passive: true
1268 });
1269 cursorBackdrop.addEventListener('scroll', propagateBackdropScroll, {
1270 capture: true,
1271 passive: true
1272 });
1273 }
1274 cursorBackdrop.style.cursor = cursor;
1275 return new DisposableDelegate(() => {
1276 if (id === overrideCursorID && cursorBackdrop.isConnected) {
1277 document.removeEventListener('pointermove', alignBackdrop, true);
1278 cursorBackdrop.removeEventListener(
1279 'scroll',
1280 propagateBackdropScroll,
1281 true
1282 );
1283
1284 // Removing the element from the DOM also releases the pointer capture.
1285 body.removeChild(cursorBackdrop);
1286 }
1287 });
1288 }
1289
1290 /**
1291 * Move cursor backdrop to match cursor position.
1292 */
1293 function alignBackdrop(event: PointerEvent) {
1294 if (!cursorBackdrop) {
1295 return;
1296 }
1297 cursorBackdrop.style.transform = `translate(${event.clientX}px, ${event.clientY}px)`;
1298
1299 // Capture the pointer to the cursor backdrop, ensuring that the cursor
1300 // override and any other pointer listeners on the document are respected
1301 // even if the pointer drifts over an iframe. When the backdrop element is
1302 // removed from the DOM when the override dispose is called, any pointer
1303 // capture is released.
1304 try {
1305 if (!cursorBackdrop.hasPointerCapture(event.pointerId)) {
1306 cursorBackdrop.setPointerCapture(event.pointerId);
1307 }
1308 } catch (e) {
1309 // Ignore errors in pointer capture to guard defensively against failures,
1310 // e.g., older browsers or synthetic events in tests that don't have
1311 // active pointers.
1312 }
1313 }
1314
1315 /**
1316 * Propagate the scroll event from the backdrop element to the scroll target.
1317 * The scroll target is defined by presence of `data-lm-dragscroll` attribute.
1318 */
1319 function propagateBackdropScroll(_event: Event) {
1320 if (!cursorBackdrop) {
1321 return;
1322 }
1323 // Get the element under behind the centre of the cursor backdrop
1324 // (essentially behind the cursor, but possibly a few pixels off).
1325 let element: Element | null = findElementBehindBackdrop();
1326 if (!element) {
1327 return;
1328 }
1329 // Find scroll target.
1330 const scrollTarget = element.closest('[data-lm-dragscroll]');
1331 if (!scrollTarget) {
1332 return;
1333 }
1334 // Apply the scroll delta to the correct target.
1335 scrollTarget.scrollTop += cursorBackdrop.scrollTop - backdropScrollOrigin;
1336 scrollTarget.scrollLeft += cursorBackdrop.scrollLeft - backdropScrollOrigin;
1337
1338 // Center the scroll position.
1339 resetBackdropScroll();
1340 }
1341
1342 /**
1343 * Reset the backdrop scroll to allow further scrolling.
1344 */
1345 function resetBackdropScroll() {
1346 cursorBackdrop.scrollTop = backdropScrollOrigin;
1347 cursorBackdrop.scrollLeft = backdropScrollOrigin;
1348 }
1349
1350 /**
1351 * The center of the backdrop node scroll area.
1352 */
1353 const backdropScrollOrigin = 500;
1354
1355 /**
1356 * Create cursor backdrop node.
1357 */
1358 function createCursorBackdrop(): HTMLElement {
1359 const backdrop = document.createElement('div');
1360 backdrop.classList.add('lm-cursor-backdrop');
1361 return backdrop;
1362 }
1363
1364 /**
1365 * The internal id for the active cursor override.
1366 */
1367 let overrideCursorID = 0;
1368
1369 /**
1370 * A backdrop node overriding pointer cursor.
1371 *
1372 * #### Notes
1373 * We use a backdrop node rather than setting the cursor directly on the body
1374 * because setting it on body requires more extensive style recalculation for
1375 * reliable application of the cursor, this is the cursor not being overriden
1376 * when over child elements with another style like `cursor: other!important`.
1377 */
1378 export const cursorBackdrop: HTMLElement = createCursorBackdrop();
1379 }