From 6a829c7ac73cf1099899952edb4652313a3ee32f Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Tue, 17 Mar 2026 10:47:02 +0100 Subject: [PATCH] fix(cdk/drag-drop): item returned to wrong index in initial container Fixes that when we return the item to its original container, we may end up putting it at the wrong index, because the logic that de-duplicates the item runs too late. Fixes #32940. --- .../sorting/single-axis-sort-strategy.ts | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts b/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts index 648f52cf6b5f..3f707ee0b1bd 100644 --- a/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts +++ b/src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts @@ -168,6 +168,17 @@ export class SingleAxisSortStrategy implements DropListSortStrategy { * out automatically. */ enter(item: DragRef, pointerX: number, pointerY: number, index?: number): void { + const activeDraggables = this._activeDraggables; + const currentIndex = activeDraggables.indexOf(item); + const placeholder = item.getPlaceholderElement(); + + // Since the item may be in the `activeDraggables` already (e.g. if the user dragged it + // into another container and back again), we have to ensure that it isn't duplicated. + // Note that we need to run this early so the code further below isn't thrown off. + if (currentIndex > -1) { + activeDraggables.splice(currentIndex, 1); + } + const newIndex = index == null || index < 0 ? // We use the coordinates of where the item entered the drop @@ -175,9 +186,6 @@ export class SingleAxisSortStrategy implements DropListSortStrategy { this._getItemIndexFromPointerPosition(item, pointerX, pointerY) : index; - const activeDraggables = this._activeDraggables; - const currentIndex = activeDraggables.indexOf(item); - const placeholder = item.getPlaceholderElement(); let newPositionReference: DragRef | undefined = activeDraggables[newIndex]; // If the item at the new position is the same as the item that is being dragged, @@ -197,12 +205,6 @@ export class SingleAxisSortStrategy implements DropListSortStrategy { newPositionReference = activeDraggables[0]; } - // Since the item may be in the `activeDraggables` already (e.g. if the user dragged it - // into another container and back again), we have to ensure that it isn't duplicated. - if (currentIndex > -1) { - activeDraggables.splice(currentIndex, 1); - } - // Don't use items that are being dragged as a reference, because // their element has been moved down to the bottom of the body. if (newPositionReference && !this._dragDropRegistry.isDragging(newPositionReference)) {