« get me outta code hell

mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/backend.js
diff options
context:
space:
mode:
Diffstat (limited to 'backend.js')
-rw-r--r--backend.js17
1 files changed, 15 insertions, 2 deletions
diff --git a/backend.js b/backend.js
index d88c779..0ddd15b 100644
--- a/backend.js
+++ b/backend.js
@@ -140,6 +140,10 @@ class Backend extends EventEmitter {
     // a whole group can be queued in order after a given item.
     let grouplikeOffset = 0
 
+    // Keeps track of how many tracks have been removed (times -1); this is
+    // used so we queue tracks at the intended spot.
+    let removeOffset = 0
+
     const recursivelyAddTracks = item => {
       // For groups, just queue all children.
       if (isGroup(item)) {
@@ -163,13 +167,22 @@ class Backend extends EventEmitter {
         if (!movePlayingTrack && item === this.playingTrack) {
           return
         }
-        items.splice(items.indexOf(item), 1)
+
+        const removeIndex = items.indexOf(item)
+        items.splice(removeIndex, 1)
+
+        // If the item we removed was positioned before the insertion index,
+        // we need to shift that index back one, so it's placed after the same
+        // intended track.
+        if (removeIndex <= afterIndex) {
+          removeOffset--
+        }
       }
 
       if (afterItem === 'FRONT') {
         items.unshift(item)
       } else if (afterItem) {
-        items.splice(afterIndex + 1 + grouplikeOffset, 0, item)
+        items.splice(afterIndex + 1 + grouplikeOffset + removeOffset, 0, item)
       } else {
         items.push(item)
       }