Skip to content

Commit d70faa0

Browse files
authored
fix(cdk/drag-drop): sorted event emitted multiple times for single-item list (#23589)
Fixes that the `sorted` event was being emitted when the item wasn't actually being sorted when it's inside of a list with a single item. Fixes #23575.
1 parent 4e3b72c commit d70faa0

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1861,6 +1861,29 @@ describe('CdkDrag', () => {
18611861
flush();
18621862
}));
18631863

1864+
it('should not dispatch the `sorted` event when an item is dragged inside ' +
1865+
'a single-item list', fakeAsync(() => {
1866+
const fixture = createComponent(DraggableInDropZone);
1867+
fixture.componentInstance.items = [fixture.componentInstance.items[0]];
1868+
fixture.detectChanges();
1869+
1870+
const draggedItem = fixture.componentInstance.dragItems.first.element.nativeElement;
1871+
const {top, left} = draggedItem.getBoundingClientRect();
1872+
1873+
startDraggingViaMouse(fixture, draggedItem, left, top);
1874+
1875+
for (let i = 0; i < 5; i++) {
1876+
dispatchMouseEvent(document, 'mousemove', left, top + 1);
1877+
fixture.detectChanges();
1878+
1879+
expect(fixture.componentInstance.sortedSpy).not.toHaveBeenCalled();
1880+
}
1881+
1882+
dispatchMouseEvent(document, 'mouseup');
1883+
fixture.detectChanges();
1884+
flush();
1885+
}));
1886+
18641887
it('should not move items in a vertical list if the pointer is too far away', fakeAsync(() => {
18651888
const fixture = createComponent(DraggableInDropZone);
18661889
fixture.detectChanges();

src/cdk/drag-drop/drop-list-ref.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -754,11 +754,10 @@ export class DropListRef<T = any> {
754754
private _getItemIndexFromPointerPosition(item: DragRef, pointerX: number, pointerY: number,
755755
delta?: {x: number, y: number}): number {
756756
const isHorizontal = this._orientation === 'horizontal';
757-
const index = this._itemPositions.findIndex(({drag, clientRect}, _, array) => {
757+
const index = this._itemPositions.findIndex(({drag, clientRect}) => {
758+
// Skip the item itself.
758759
if (drag === item) {
759-
// If there's only one item left in the container, it must be
760-
// the dragged item itself so we use it as a reference.
761-
return array.length < 2;
760+
return false;
762761
}
763762

764763
if (delta) {

0 commit comments

Comments
 (0)