Skip to content

Commit a7a25cd

Browse files
committed
fix(drag-drop): not stopping drag if page is blurred
Currently the only way to stop a drag sequence is via a `mouseup`/`touchend` event or by destroying the instance, however if the page loses focus while dragging the events won't be dispatched anymore and user will have to click again to stop dragging. These changes add some extra code that listens for `blur` events on the `window` and stops dragging. Fixes #17537.
1 parent 0012121 commit a7a25cd

File tree

5 files changed

+86
-13
lines changed

5 files changed

+86
-13
lines changed

src/cdk/drag-drop/directives/drag.spec.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4090,6 +4090,27 @@ describe('CdkDrag', () => {
40904090
expect(placeholder).toBeTruthy();
40914091
}));
40924092

4093+
it('should stop dragging if the page is blurred', fakeAsync(() => {
4094+
const fixture = createComponent(DraggableInDropZone);
4095+
fixture.detectChanges();
4096+
const dragItems = fixture.componentInstance.dragItems;
4097+
4098+
expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled();
4099+
4100+
const item = dragItems.first;
4101+
const targetRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect();
4102+
4103+
startDraggingViaMouse(fixture, item.element.nativeElement);
4104+
dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1);
4105+
fixture.detectChanges();
4106+
4107+
dispatchFakeEvent(window, 'blur');
4108+
fixture.detectChanges();
4109+
flush();
4110+
4111+
expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1);
4112+
}));
4113+
40934114
});
40944115

40954116
describe('in a connected drop container', () => {

src/cdk/drag-drop/drag-drop-registry.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,17 @@ describe('DragDropRegistry', () => {
237237
subscription.unsubscribe();
238238
});
239239

240+
it('should dispatch an event if the window is blurred while scrolling', () => {
241+
const spy = jasmine.createSpy('blur spy');
242+
const subscription = registry.pageBlurred.subscribe(spy);
243+
244+
registry.startDragging(testComponent.dragItems.first, createMouseEvent('mousedown'));
245+
dispatchFakeEvent(window, 'blur');
246+
247+
expect(spy).toHaveBeenCalled();
248+
subscription.unsubscribe();
249+
});
250+
240251
});
241252

242253
@Component({

src/cdk/drag-drop/drag-drop-registry.ts

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ const activeCapturingEventOptions = normalizePassiveListenerOptions({
2828
@Injectable({providedIn: 'root'})
2929
export class DragDropRegistry<I, C> implements OnDestroy {
3030
private _document: Document;
31+
private _window: Window | null;
3132

3233
/** Registered drop container instances. */
3334
private _dropInstances = new Set<C>();
@@ -41,28 +42,36 @@ export class DragDropRegistry<I, C> implements OnDestroy {
4142
/** Keeps track of the event listeners that we've bound to the `document`. */
4243
private _globalListeners = new Map<string, {
4344
handler: (event: Event) => void,
45+
// The target needs to be `| null` because we bind either to `window` or `document` which
46+
// aren't available during SSR. There's an injection token for the document, but not one for
47+
// window so we fall back to not binding events to it.
48+
target: EventTarget | null,
4449
options?: AddEventListenerOptions | boolean
4550
}>();
4651

4752
/**
4853
* Emits the `touchmove` or `mousemove` events that are dispatched
4954
* while the user is dragging a drag item instance.
5055
*/
51-
readonly pointerMove: Subject<TouchEvent | MouseEvent> = new Subject<TouchEvent | MouseEvent>();
56+
pointerMove: Subject<TouchEvent | MouseEvent> = new Subject<TouchEvent | MouseEvent>();
5257

5358
/**
5459
* Emits the `touchend` or `mouseup` events that are dispatched
5560
* while the user is dragging a drag item instance.
5661
*/
57-
readonly pointerUp: Subject<TouchEvent | MouseEvent> = new Subject<TouchEvent | MouseEvent>();
62+
pointerUp: Subject<TouchEvent | MouseEvent> = new Subject<TouchEvent | MouseEvent>();
5863

5964
/** Emits when the viewport has been scrolled while the user is dragging an item. */
60-
readonly scroll: Subject<Event> = new Subject<Event>();
65+
scroll: Subject<Event> = new Subject<Event>();
66+
67+
/** Emits when the page has been blurred while the user is dragging an item. */
68+
pageBlurred: Subject<void> = new Subject<void>();
6169

6270
constructor(
6371
private _ngZone: NgZone,
6472
@Inject(DOCUMENT) _document: any) {
6573
this._document = _document;
74+
this._window = (typeof window !== 'undefined' && window.addEventListener) ? window : null;
6675
}
6776

6877
/** Adds a drop container to the registry. */
@@ -129,30 +138,40 @@ export class DragDropRegistry<I, C> implements OnDestroy {
129138
this._globalListeners
130139
.set(moveEvent, {
131140
handler: (e: Event) => this.pointerMove.next(e as TouchEvent | MouseEvent),
132-
options: activeCapturingEventOptions
141+
options: activeCapturingEventOptions,
142+
target: this._document
133143
})
134144
.set(upEvent, {
135145
handler: (e: Event) => this.pointerUp.next(e as TouchEvent | MouseEvent),
136-
options: true
146+
options: true,
147+
target: this._document
137148
})
138149
.set('scroll', {
139150
handler: (e: Event) => this.scroll.next(e),
140151
// Use capturing so that we pick up scroll changes in any scrollable nodes that aren't
141152
// the document. See https://github.com/angular/components/issues/17144.
142-
options: true
153+
options: true,
154+
target: this._document
143155
})
144156
// Preventing the default action on `mousemove` isn't enough to disable text selection
145157
// on Safari so we need to prevent the selection event as well. Alternatively this can
146158
// be done by setting `user-select: none` on the `body`, however it has causes a style
147159
// recalculation which can be expensive on pages with a lot of elements.
148160
.set('selectstart', {
149161
handler: this._preventDefaultWhileDragging,
150-
options: activeCapturingEventOptions
162+
options: activeCapturingEventOptions,
163+
target: this._document
164+
})
165+
.set('blur', {
166+
handler: () => this.pageBlurred.next(),
167+
target: this._window // Note that this event can only be bound on the window, not document
151168
});
152169

153170
this._ngZone.runOutsideAngular(() => {
154171
this._globalListeners.forEach((config, name) => {
155-
this._document.addEventListener(name, config.handler, config.options);
172+
if (config.target) {
173+
config.target.addEventListener(name, config.handler, config.options);
174+
}
156175
});
157176
});
158177
}
@@ -178,6 +197,7 @@ export class DragDropRegistry<I, C> implements OnDestroy {
178197
this._clearGlobalListeners();
179198
this.pointerMove.complete();
180199
this.pointerUp.complete();
200+
this.pageBlurred.complete();
181201
}
182202

183203
/**
@@ -193,7 +213,9 @@ export class DragDropRegistry<I, C> implements OnDestroy {
193213
/** Clears out the global event listeners from the `document`. */
194214
private _clearGlobalListeners() {
195215
this._globalListeners.forEach((config, name) => {
196-
this._document.removeEventListener(name, config.handler, config.options);
216+
if (config.target) {
217+
config.target.removeEventListener(name, config.handler, config.options);
218+
}
197219
});
198220

199221
this._globalListeners.clear();

src/cdk/drag-drop/drag-ref.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,13 +186,19 @@ export class DragRef<T = any> {
186186
/** Subscription to the viewport being resized. */
187187
private _resizeSubscription = Subscription.EMPTY;
188188

189+
/** Subscription to the page being blurred. */
190+
private _blurSubscription = Subscription.EMPTY;
191+
189192
/**
190193
* Time at which the last touch event occurred. Used to avoid firing the same
191194
* events multiple times on touch devices where the browser will fire a fake
192195
* mouse event for each touch event, after a certain time.
193196
*/
194197
private _lastTouchEventTime: number;
195198

199+
/** Last pointer move event that was captured. */
200+
private _lastPointerMove: MouseEvent | TouchEvent | null;
201+
196202
/** Time at which the last dragging sequence was started. */
197203
private _dragStartTime: number;
198204

@@ -437,7 +443,7 @@ export class DragRef<T = any> {
437443
this._resizeSubscription.unsubscribe();
438444
this._parentPositions.clear();
439445
this._boundaryElement = this._rootElement = this._ownerSVGElement = this._placeholderTemplate =
440-
this._previewTemplate = this._anchor = null!;
446+
this._previewTemplate = this._anchor = this._lastPointerMove = null!;
441447
}
442448

443449
/** Checks whether the element is currently being dragged. */
@@ -519,6 +525,7 @@ export class DragRef<T = any> {
519525
this._pointerMoveSubscription.unsubscribe();
520526
this._pointerUpSubscription.unsubscribe();
521527
this._scrollSubscription.unsubscribe();
528+
this._blurSubscription.unsubscribe();
522529
}
523530

524531
/** Destroys the preview element and its ViewRef. */
@@ -613,6 +620,7 @@ export class DragRef<T = any> {
613620
const constrainedPointerPosition = this._getConstrainedPointerPosition(pointerPosition);
614621
this._hasMoved = true;
615622
this._lastKnownPointerPosition = pointerPosition;
623+
this._lastPointerMove = event;
616624
this._updatePointerDirectionDelta(constrainedPointerPosition);
617625

618626
if (this._dropContainer) {
@@ -789,6 +797,7 @@ export class DragRef<T = any> {
789797
}
790798

791799
this._hasStartedDragging = this._hasMoved = false;
800+
this._lastPointerMove = null;
792801

793802
// Avoid multiple subscriptions and memory leaks when multi touch
794803
// (isDragging check above isn't enough because of possible temporal and/or dimensional delays)
@@ -799,6 +808,15 @@ export class DragRef<T = any> {
799808
this._updateOnScroll(scrollEvent);
800809
});
801810

811+
// If the page is blurred while dragging (e.g. there was an `alert` or the browser window was
812+
// minimized) we won't get a mouseup/touchend so we need to use a different event to stop the
813+
// drag sequence. Use the last known location to figure out where the element should be dropped.
814+
this._blurSubscription = this._dragDropRegistry.pageBlurred.subscribe(() => {
815+
if (this._lastPointerMove) {
816+
this._endDragSequence(this._lastPointerMove);
817+
}
818+
});
819+
802820
if (this._boundaryElement) {
803821
this._boundaryRect = getMutableClientRect(this._boundaryElement);
804822
}

tools/public_api_guard/cdk/drag-drop.d.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,9 +224,10 @@ export declare class DragDropModule {
224224
}
225225

226226
export declare class DragDropRegistry<I, C> implements OnDestroy {
227-
readonly pointerMove: Subject<TouchEvent | MouseEvent>;
228-
readonly pointerUp: Subject<TouchEvent | MouseEvent>;
229-
readonly scroll: Subject<Event>;
227+
pageBlurred: Subject<void>;
228+
pointerMove: Subject<TouchEvent | MouseEvent>;
229+
pointerUp: Subject<TouchEvent | MouseEvent>;
230+
scroll: Subject<Event>;
230231
constructor(_ngZone: NgZone, _document: any);
231232
isDragging(drag: I): boolean;
232233
ngOnDestroy(): void;

0 commit comments

Comments
 (0)