Skip to content

Commit

Permalink
fix(cdk/drag-drop): error if dragged item is destroyed as a result of…
Browse files Browse the repository at this point in the history
… the `entered` event (#22904)

When an item enters a new drop container, we dispatch an event and run some logic afterwards. The problem is that if the item is destroyed as a result of the event, the logic after the event will throw because dragging was interrupted.

Fixes #22813.
  • Loading branch information
crisbeto committed Jun 10, 2021
1 parent d5a5de2 commit 0431d81
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
22 changes: 22 additions & 0 deletions src/cdk/drag-drop/directives/drag.spec.ts
Expand Up @@ -5447,6 +5447,28 @@ describe('CdkDrag', () => {
expect(itemEnterEvent).toEqual(expectedEvent);
}));

it('should not throw if dragging was interrupted as a result of the entered event',
fakeAsync(() => {
const fixture = createComponent(ConnectedDropZones);
fixture.detectChanges();

const groups = fixture.componentInstance.groupedDragItems;
const item = groups[0][1];
const targetRect = groups[1][2].element.nativeElement.getBoundingClientRect();

fixture.componentInstance.enteredSpy.and.callFake(() => {
fixture.componentInstance.todo = [];
fixture.detectChanges();
});

expect(() => {
dragElementViaMouse(
fixture, item.element.nativeElement, targetRect.left + 1, targetRect.top + 1);
flush();
fixture.detectChanges();
}).not.toThrow();
}));

it('should be able to drop into a new container after scrolling into view', fakeAsync(() => {
const fixture = createComponent(ConnectedDropZones);
fixture.detectChanges();
Expand Down
13 changes: 8 additions & 5 deletions src/cdk/drag-drop/drag-ref.ts
Expand Up @@ -151,7 +151,7 @@ export class DragRef<T = any> {
* Whether the dragging sequence has been started. Doesn't
* necessarily mean that the element has been moved.
*/
private _hasStartedDragging: boolean;
private _hasStartedDragging = false;

/** Whether the element has moved since the user started dragging it. */
private _hasMoved: boolean;
Expand Down Expand Up @@ -982,10 +982,13 @@ export class DragRef<T = any> {
});
}

this._dropContainer!._startScrollingIfNecessary(rawX, rawY);
this._dropContainer!._sortItem(this, x, y, this._pointerDirectionDelta);
this._applyPreviewTransform(
x - this._pickupPositionInElement.x, y - this._pickupPositionInElement.y);
// Dragging may have been interrupted as a result of the events above.
if (this.isDragging()) {
this._dropContainer!._startScrollingIfNecessary(rawX, rawY);
this._dropContainer!._sortItem(this, x, y, this._pointerDirectionDelta);
this._applyPreviewTransform(
x - this._pickupPositionInElement.x, y - this._pickupPositionInElement.y);
}
}

/**
Expand Down

0 comments on commit 0431d81

Please sign in to comment.