Skip to content

Commit 688deda

Browse files
committed
fix(cdk/drag-drop): item returned to wrong index in initial container (#32944)
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. (cherry picked from commit 0767a3c)
1 parent 21bca7d commit 688deda

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/cdk/drag-drop/sorting/single-axis-sort-strategy.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -168,16 +168,24 @@ export class SingleAxisSortStrategy implements DropListSortStrategy {
168168
* out automatically.
169169
*/
170170
enter(item: DragRef, pointerX: number, pointerY: number, index?: number): void {
171+
const activeDraggables = this._activeDraggables;
172+
const currentIndex = activeDraggables.indexOf(item);
173+
const placeholder = item.getPlaceholderElement();
174+
175+
// Since the item may be in the `activeDraggables` already (e.g. if the user dragged it
176+
// into another container and back again), we have to ensure that it isn't duplicated.
177+
// Note that we need to run this early so the code further below isn't thrown off.
178+
if (currentIndex > -1) {
179+
activeDraggables.splice(currentIndex, 1);
180+
}
181+
171182
const newIndex =
172183
index == null || index < 0
173184
? // We use the coordinates of where the item entered the drop
174185
// zone to figure out at which index it should be inserted.
175186
this._getItemIndexFromPointerPosition(item, pointerX, pointerY)
176187
: index;
177188

178-
const activeDraggables = this._activeDraggables;
179-
const currentIndex = activeDraggables.indexOf(item);
180-
const placeholder = item.getPlaceholderElement();
181189
let newPositionReference: DragRef | undefined = activeDraggables[newIndex];
182190

183191
// 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 {
197205
newPositionReference = activeDraggables[0];
198206
}
199207

200-
// Since the item may be in the `activeDraggables` already (e.g. if the user dragged it
201-
// into another container and back again), we have to ensure that it isn't duplicated.
202-
if (currentIndex > -1) {
203-
activeDraggables.splice(currentIndex, 1);
204-
}
205-
206208
// Don't use items that are being dragged as a reference, because
207209
// their element has been moved down to the bottom of the body.
208210
if (newPositionReference && !this._dragDropRegistry.isDragging(newPositionReference)) {

0 commit comments

Comments
 (0)