Skip to content

Commit cc54183

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 9343d08 commit cc54183

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
@@ -3696,6 +3696,27 @@ describe('CdkDrag', () => {
36963696
expect(styles.scrollSnapType || styles.msScrollSnapType).toBe('block');
36973697
}));
36983698

3699+
it('should stop dragging if the page is blurred', fakeAsync(() => {
3700+
const fixture = createComponent(DraggableInDropZone);
3701+
fixture.detectChanges();
3702+
const dragItems = fixture.componentInstance.dragItems;
3703+
3704+
expect(fixture.componentInstance.droppedSpy).not.toHaveBeenCalled();
3705+
3706+
const item = dragItems.first;
3707+
const targetRect = dragItems.toArray()[2].element.nativeElement.getBoundingClientRect();
3708+
3709+
startDraggingViaMouse(fixture, item.element.nativeElement);
3710+
dispatchMouseEvent(document, 'mousemove', targetRect.left + 1, targetRect.top + 1);
3711+
fixture.detectChanges();
3712+
3713+
dispatchFakeEvent(window, 'blur');
3714+
fixture.detectChanges();
3715+
flush();
3716+
3717+
expect(fixture.componentInstance.droppedSpy).toHaveBeenCalledTimes(1);
3718+
}));
3719+
36993720
});
37003721

37013722
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
@@ -174,13 +174,19 @@ export class DragRef<T = any> {
174174
/** Subscription to the viewport being resized. */
175175
private _resizeSubscription = Subscription.EMPTY;
176176

177+
/** Subscription to the page being blurred. */
178+
private _blurSubscription = Subscription.EMPTY;
179+
177180
/**
178181
* Time at which the last touch event occurred. Used to avoid firing the same
179182
* events multiple times on touch devices where the browser will fire a fake
180183
* mouse event for each touch event, after a certain time.
181184
*/
182185
private _lastTouchEventTime: number;
183186

187+
/** Last pointer move event that was captured. */
188+
private _lastPointerMove: MouseEvent | TouchEvent | null;
189+
184190
/** Time at which the last dragging sequence was started. */
185191
private _dragStartTime: number;
186192

@@ -417,7 +423,7 @@ export class DragRef<T = any> {
417423
this._dropContainer = undefined;
418424
this._resizeSubscription.unsubscribe();
419425
this._boundaryElement = this._rootElement = this._placeholderTemplate =
420-
this._previewTemplate = this._anchor = null!;
426+
this._previewTemplate = this._anchor = this._lastPointerMove = null!;
421427
}
422428

423429
/** Checks whether the element is currently being dragged. */
@@ -499,6 +505,7 @@ export class DragRef<T = any> {
499505
this._pointerMoveSubscription.unsubscribe();
500506
this._pointerUpSubscription.unsubscribe();
501507
this._scrollSubscription.unsubscribe();
508+
this._blurSubscription.unsubscribe();
502509
}
503510

504511
/** Destroys the preview element and its ViewRef. */
@@ -592,6 +599,7 @@ export class DragRef<T = any> {
592599

593600
const constrainedPointerPosition = this._getConstrainedPointerPosition(event);
594601
this._hasMoved = true;
602+
this._lastPointerMove = event;
595603
this._updatePointerDirectionDelta(constrainedPointerPosition);
596604

597605
if (this._dropContainer) {
@@ -763,6 +771,7 @@ export class DragRef<T = any> {
763771
}
764772

765773
this._hasStartedDragging = this._hasMoved = false;
774+
this._lastPointerMove = null;
766775

767776
// Avoid multiple subscriptions and memory leaks when multi touch
768777
// (isDragging check above isn't enough because of possible temporal and/or dimensional delays)
@@ -773,6 +782,15 @@ export class DragRef<T = any> {
773782
this._scrollPosition = this._viewportRuler.getViewportScrollPosition();
774783
});
775784

785+
// If the page is blurred while dragging (e.g. there was an `alert` or the browser window was
786+
// minimized) we won't get a mouseup/touchend so we need to use a different event to stop the
787+
// drag sequence. Use the last known location to figure out where the element should be dropped.
788+
this._blurSubscription = this._dragDropRegistry.pageBlurred.subscribe(() => {
789+
if (this._lastPointerMove) {
790+
this._endDragSequence(this._lastPointerMove);
791+
}
792+
});
793+
776794
if (this._boundaryElement) {
777795
this._boundaryRect = this._boundaryElement.getBoundingClientRect();
778796
}

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)