Skip to content

Commit 1437e12

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 658896f commit 1437e12

File tree

5 files changed

+86
-13
lines changed

5 files changed

+86
-13
lines changed

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

+21
Original file line numberDiff line numberDiff line change
@@ -3898,6 +3898,27 @@ describe('CdkDrag', () => {
38983898
expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1);
38993899
}));
39003900

3901+
it('should stop dragging if the page is blurred', fakeAsync(() => {
3902+
const fixture = createComponent(DraggableInDropZone);
3903+
fixture.detectChanges();
3904+
const dragItems = fixture.componentInstance.dragItems;
3905+
3906+
expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled();
3907+
3908+
const item = dragItems.first;
3909+
const targetRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect();
3910+
3911+
startDraggingViaMouse(fixture, item.element.nativeElement);
3912+
dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1);
3913+
fixture.detectChanges();
3914+
3915+
dispatchFakeEvent(window, 'blur');
3916+
fixture.detectChanges();
3917+
flush();
3918+
3919+
expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1);
3920+
}));
3921+
39013922
});
39023923

39033924
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
@@ -178,13 +178,19 @@ export class DragRef<T = any> {
178178
/** Subscription to the viewport being resized. */
179179
private _resizeSubscription = Subscription.EMPTY;
180180

181+
/** Subscription to the page being blurred. */
182+
private _blurSubscription = Subscription.EMPTY;
183+
181184
/**
182185
* Time at which the last touch event occurred. Used to avoid firing the same
183186
* events multiple times on touch devices where the browser will fire a fake
184187
* mouse event for each touch event, after a certain time.
185188
*/
186189
private _lastTouchEventTime: number;
187190

191+
/** Last pointer move event that was captured. */
192+
private _lastPointerMove: MouseEvent | TouchEvent | null;
193+
188194
/** Time at which the last dragging sequence was started. */
189195
private _dragStartTime: number;
190196

@@ -425,7 +431,7 @@ export class DragRef<T = any> {
425431
this._resizeSubscription.unsubscribe();
426432
this._parentPositions.clear();
427433
this._boundaryElement = this._rootElement = this._placeholderTemplate =
428-
this._previewTemplate = this._anchor = null!;
434+
this._previewTemplate = this._anchor = this._lastPointerMove = null!;
429435
}
430436

431437
/** Checks whether the element is currently being dragged. */
@@ -507,6 +513,7 @@ export class DragRef<T = any> {
507513
this._pointerMoveSubscription.unsubscribe();
508514
this._pointerUpSubscription.unsubscribe();
509515
this._scrollSubscription.unsubscribe();
516+
this._blurSubscription.unsubscribe();
510517
}
511518

512519
/** Destroys the preview element and its ViewRef. */
@@ -600,6 +607,7 @@ export class DragRef<T = any> {
600607

601608
const constrainedPointerPosition = this._getConstrainedPointerPosition(pointerPosition);
602609
this._hasMoved = true;
610+
this._lastPointerMove = event;
603611
this._updatePointerDirectionDelta(constrainedPointerPosition);
604612

605613
if (this._dropContainer) {
@@ -777,6 +785,7 @@ export class DragRef<T = any> {
777785
}
778786

779787
this._hasStartedDragging = this._hasMoved = false;
788+
this._lastPointerMove = null;
780789

781790
// Avoid multiple subscriptions and memory leaks when multi touch
782791
// (isDragging check above isn't enough because of possible temporal and/or dimensional delays)
@@ -787,6 +796,15 @@ export class DragRef<T = any> {
787796
this._updateOnScroll(scrollEvent);
788797
});
789798

799+
// If the page is blurred while dragging (e.g. there was an `alert` or the browser window was
800+
// minimized) we won't get a mouseup/touchend so we need to use a different event to stop the
801+
// drag sequence. Use the last known location to figure out where the element should be dropped.
802+
this._blurSubscription = this._dragDropRegistry.pageBlurred.subscribe(() => {
803+
if (this._lastPointerMove) {
804+
this._endDragSequence(this._lastPointerMove);
805+
}
806+
});
807+
790808
if (this._boundaryElement) {
791809
this._boundaryRect = getMutableClientRect(this._boundaryElement);
792810
}

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

+4-3
Original file line numberDiff line numberDiff line change
@@ -225,9 +225,10 @@ export declare class DragDropModule {
225225
}
226226

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

0 commit comments

Comments
 (0)