Fix calculation when moving elements of different sizes.

This commit is contained in:
2026-05-03 15:00:29 +02:00
parent 6cedfef000
commit 0c618f2024
2 changed files with 8 additions and 9 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@tp/tp-sortable",
"version": "2.1.0",
"version": "2.1.1",
"description": "",
"main": "tp-sortable.js",
"scripts": {
+7 -8
View File
@@ -142,26 +142,22 @@ class TpSortable extends EventHelpers(LitElement) {
const itemsAfter = this._sortables.slice(targetIdx + 1);
// Dragging down: items after target shift up to fill the target's original slot.
// Each item's shift = distance from that item's original top to the preceding item's original top.
// All qualifying items shift up by the dragged item's full height.
for (let i = 0; i < itemsAfter.length; i++) {
const item = itemsAfter[i];
const prevTop = i === 0 ? this._rect.top : itemsAfter[i - 1].rect.top;
const shift = -(item.rect.top - prevTop);
if (targetTop + targetHeight > item.rect.top + item.rect.height * 0.5) {
this._translate3d('0px', shift + 'px', '0px', item.el);
this._translate3d('0px', -targetHeight + 'px', '0px', item.el);
} else {
this._translate3d('0px', '0px', '0px', item.el);
}
}
// Dragging up: items before target shift down to fill the target's original slot.
// Each item's shift = distance from that item's original top to the following item's original top.
// All qualifying items shift down by the dragged item's full height.
for (let i = 0; i < itemsBefore.length; i++) {
const item = itemsBefore[i];
const nextTop = i === itemsBefore.length - 1 ? this._rect.top : itemsBefore[i + 1].rect.top;
const shift = nextTop - item.rect.top;
if (targetTop - item.rect.height * 0.5 < item.rect.top) {
this._translate3d('0px', shift + 'px', '0px', item.el);
this._translate3d('0px', targetHeight + 'px', '0px', item.el);
} else {
this._translate3d('0px', '0px', '0px', item.el);
}
@@ -205,6 +201,9 @@ class TpSortable extends EventHelpers(LitElement) {
_registerSortableElements() {
this._sortables = [];
// Force layout so rects reflect the current rendered size of each item,
// even if items grew after they were first added to the DOM.
this.getBoundingClientRect();
let sortables = Array.from(this.querySelectorAll(this.selector));
for (let i = 0, li = sortables.length; i < li; ++i) {