Skip to content

Commit c0a1b15

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 198911f commit c0a1b15

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
@@ -3624,6 +3624,27 @@ describe('CdkDrag', () => {
36243624
expect(styles.scrollSnapType || styles.msScrollSnapType).toBe('block');
36253625
}));
36263626

3627+
it('should stop dragging if the page is blurred', fakeAsync(() => {
3628+
const fixture = createComponent(DraggableInDropZone);
3629+
fixture.detectChanges();
3630+
const dragItems = fixture.componentInstance.dragItems;
3631+
3632+
expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled();
3633+
3634+
const item = dragItems.first;
3635+
const targetRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect();
3636+
3637+
startDraggingViaMouse(fixture, item.element.nativeElement);
3638+
dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1);
3639+
fixture.detectChanges();
3640+
3641+
dispatchFakeEvent(window, 'blur');
3642+
fixture.detectChanges();
3643+
flush();
3644+
3645+
expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1);
3646+
}));
3647+
36273648
});
36283649

36293650
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
@@ -166,13 +166,19 @@ export class DragRef<T = any> {
166166
/** Subscription to the viewport being resized. */
167167
private _resizeSubscription = Subscription.EMPTY;
168168

169+
/** Subscription to the page being blurred. */
170+
private _blurSubscription = Subscription.EMPTY;
171+
169172
/**
170173
* Time at which the last touch event occurred. Used to avoid firing the same
171174
* events multiple times on touch devices where the browser will fire a fake
172175
* mouse event for each touch event, after a certain time.
173176
*/
174177
private _lastTouchEventTime: number;
175178

179+
/** Last pointer move event that was captured. */
180+
private _lastPointerMove: MouseEvent | TouchEvent | null;
181+
176182
/** Time at which the last dragging sequence was started. */
177183
private _dragStartTime: number;
178184

@@ -401,7 +407,7 @@ export class DragRef<T = any> {
401407
this._dropContainer = undefined;
402408
this._resizeSubscription.unsubscribe();
403409
this._boundaryElement = this._rootElement = this._placeholderTemplate =
404-
this._previewTemplate = this._anchor = null!;
410+
this._previewTemplate = this._anchor = this._lastPointerMove = null!;
405411
}
406412

407413
/** Checks whether the element is currently being dragged. */
@@ -483,6 +489,7 @@ export class DragRef<T = any> {
483489
this._pointerMoveSubscription.unsubscribe();
484490
this._pointerUpSubscription.unsubscribe();
485491
this._scrollSubscription.unsubscribe();
492+
this._blurSubscription.unsubscribe();
486493
}
487494

488495
/** Destroys the preview element and its ViewRef. */
@@ -576,6 +583,7 @@ export class DragRef<T = any> {
576583

577584
const constrainedPointerPosition = this._getConstrainedPointerPosition(event);
578585
this._hasMoved = true;
586+
this._lastPointerMove = event;
579587
this._updatePointerDirectionDelta(constrainedPointerPosition);
580588

581589
if (this._dropContainer) {
@@ -744,6 +752,7 @@ export class DragRef<T = any> {
744752

745753
this._hasStartedDragging = this._hasMoved = false;
746754
this._initialContainer = this._dropContainer!;
755+
this._lastPointerMove = null;
747756

748757
// Avoid multiple subscriptions and memory leaks when multi touch
749758
// (isDragging check above isn't enough because of possible temporal and/or dimensional delays)
@@ -754,6 +763,15 @@ export class DragRef<T = any> {
754763
this._scrollPosition = this._viewportRuler.getViewportScrollPosition();
755764
});
756765

766+
// If the page is blurred while dragging (e.g. there was an `alert` or the browser window was
767+
// minimized) we won't get a mouseup/touchend so we need to use a different event to stop the
768+
// drag sequence. Use the last known location to figure out where the element should be dropped.
769+
this._blurSubscription = this._dragDropRegistry.pageBlurred.subscribe(() => {
770+
if (this._lastPointerMove) {
771+
this._endDragSequence(this._lastPointerMove);
772+
}
773+
});
774+
757775
if (this._boundaryElement) {
758776
this._boundaryRect = this._boundaryElement.getBoundingClientRect();
759777
}

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

+4-3
Original file line numberDiff line numberDiff line change
@@ -220,9 +220,10 @@ export declare class DragDropModule {
220220
}
221221

222222
export declare class DragDropRegistry<I, C> implements OnDestroy {
223-
readonly pointerMove: Subject<TouchEvent | MouseEvent>;
224-
readonly pointerUp: Subject<TouchEvent | MouseEvent>;
225-
readonly scroll: Subject<Event>;
223+
pageBlurred: Subject<void>;
224+
pointerMove: Subject<TouchEvent | MouseEvent>;
225+
pointerUp: Subject<TouchEvent | MouseEvent>;
226+
scroll: Subject<Event>;
226227
constructor(_ngZone: NgZone, _document: any);
227228
isDragging(drag: I): boolean;
228229
ngOnDestroy(): void;

0 commit comments

Comments
 (0)