Skip to content

Commit b4dacbe

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 ab0f30d commit b4dacbe

File tree

5 files changed

+87
-13
lines changed

5 files changed

+87
-13
lines changed

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

+22
Original file line numberDiff line numberDiff line change
@@ -3456,6 +3456,28 @@ describe('CdkDrag', () => {
34563456
expect(dragItems.map(drag => drag.element.nativeElement.textContent!.trim()))
34573457
.toEqual(['One', 'Two', 'Zero', 'Three']);
34583458
}));
3459+
3460+
it('should stop dragging if the page is blurred', fakeAsync(() => {
3461+
const fixture = createComponent(DraggableInDropZone);
3462+
fixture.detectChanges();
3463+
const dragItems = fixture.componentInstance.dragItems;
3464+
3465+
expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled();
3466+
3467+
const item = dragItems.first;
3468+
const targetRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect();
3469+
3470+
startDraggingViaMouse(fixture, item.element.nativeElement);
3471+
dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1);
3472+
fixture.detectChanges();
3473+
3474+
dispatchFakeEvent(window, 'blur');
3475+
fixture.detectChanges();
3476+
flush();
3477+
3478+
expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1);
3479+
}));
3480+
34593481
});
34603482

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

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

+11
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

+31-9
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

+19-1
Original file line numberDiff line numberDiff line change
@@ -160,13 +160,19 @@ export class DragRef<T = any> {
160160
/** Subscription to the viewport being resized. */
161161
private _resizeSubscription = Subscription.EMPTY;
162162

163+
/** Subscription to the page being blurred. */
164+
private _blurSubscription = Subscription.EMPTY;
165+
163166
/**
164167
* Time at which the last touch event occurred. Used to avoid firing the same
165168
* events multiple times on touch devices where the browser will fire a fake
166169
* mouse event for each touch event, after a certain time.
167170
*/
168171
private _lastTouchEventTime: number;
169172

173+
/** Last pointer move event that was captured. */
174+
private _lastPointerMove: MouseEvent | TouchEvent | null;
175+
170176
/** Time at which the last dragging sequence was started. */
171177
private _dragStartTime: number;
172178

@@ -394,7 +400,7 @@ export class DragRef<T = any> {
394400
this._dropContainer = undefined;
395401
this._resizeSubscription.unsubscribe();
396402
this._boundaryElement = this._rootElement = this._placeholderTemplate =
397-
this._previewTemplate = this._nextSibling = null!;
403+
this._previewTemplate = this._nextSibling = this._lastPointerMove = null!;
398404
}
399405

400406
/** Checks whether the element is currently being dragged. */
@@ -476,6 +482,7 @@ export class DragRef<T = any> {
476482
this._pointerMoveSubscription.unsubscribe();
477483
this._pointerUpSubscription.unsubscribe();
478484
this._scrollSubscription.unsubscribe();
485+
this._blurSubscription.unsubscribe();
479486
}
480487

481488
/** Destroys the preview element and its ViewRef. */
@@ -565,6 +572,7 @@ export class DragRef<T = any> {
565572

566573
const constrainedPointerPosition = this._getConstrainedPointerPosition(event);
567574
this._hasMoved = true;
575+
this._lastPointerMove = event;
568576
event.preventDefault();
569577
this._updatePointerDirectionDelta(constrainedPointerPosition);
570578

@@ -734,6 +742,7 @@ export class DragRef<T = any> {
734742

735743
this._hasStartedDragging = this._hasMoved = false;
736744
this._initialContainer = this._dropContainer!;
745+
this._lastPointerMove = null;
737746

738747
// Avoid multiple subscriptions and memory leaks when multi touch
739748
// (isDragging check above isn't enough because of possible temporal and/or dimensional delays)
@@ -744,6 +753,15 @@ export class DragRef<T = any> {
744753
this._scrollPosition = this._viewportRuler.getViewportScrollPosition();
745754
});
746755

756+
// If the page is blurred while dragging (e.g. there was an `alert` or the browser window was
757+
// minimized) we won't get a mouseup/touchend so we need to use a different event to stop the
758+
// drag sequence. Use the last known location to figure out where the element should be dropped.
759+
this._blurSubscription = this._dragDropRegistry.pageBlurred.subscribe(() => {
760+
if (this._lastPointerMove) {
761+
this._endDragSequence(this._lastPointerMove);
762+
}
763+
});
764+
747765
if (this._boundaryElement) {
748766
this._boundaryRect = this._boundaryElement.getBoundingClientRect();
749767
}

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

+4-3
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,10 @@ export declare class DragDropModule {
201201
}
202202

203203
export declare class DragDropRegistry<I, C> implements OnDestroy {
204-
readonly pointerMove: Subject<TouchEvent | MouseEvent>;
205-
readonly pointerUp: Subject<TouchEvent | MouseEvent>;
206-
readonly scroll: Subject<Event>;
204+
pageBlurred: Subject<void>;
205+
pointerMove: Subject<TouchEvent | MouseEvent>;
206+
pointerUp: Subject<TouchEvent | MouseEvent>;
207+
scroll: Subject<Event>;
207208
constructor(_ngZone: NgZone, _document: any);
208209
isDragging(drag: I): boolean;
209210
ngOnDestroy(): void;

0 commit comments

Comments
 (0)