Skip to content

Native Android client for Spotify, built with Jetpack Compose

Queue drag on sh.calvin.reorderable; AutoMix mixes again after a seek; local rows found by song

kota-zoc3c4870c8f51
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index d6876b5a..c750b607 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -83,6 +83,12 @@ https://github.com/chrisbanes/haze
The frosted bars of the Immersive look (Gradle dependency `dev.chrisbanes.haze:haze`).
+## Reorderable — Apache-2.0
+
+`sh.calvin.reorderable:reorderable` 3.1.0 (https://github.com/Calvin-LL/Reorderable), Copyright Calvin Liang,
+used as a library (unmodified) for dragging the rows of the Immersive queue. Licence text in
+`base/licenses/Apache-2.0.txt`.
+
## Inter — SIL Open Font License 1.1
https://github.com/rsms/inter
diff --git a/base/app/build.gradle.kts b/base/app/build.gradle.kts
index 9d2b7c80..02caa75d 100644
--- a/base/app/build.gradle.kts
+++ b/base/app/build.gradle.kts
@@ -128,6 +128,8 @@ dependencies {
implementation("com.microsoft.onnxruntime:onnxruntime-android:1.23.2")
// Third-party extensions: the sandbox (Rhino), manifests, packages and catalogues.
implementation(project(":extensions"))
+ // The queue's drag and drop (Apache-2.0): the row carried stays in the list, auto-scroll at the edges.
+ implementation("sh.calvin.reorderable:reorderable:3.1.0")
// Jam: scan the invite QR code (Google code scanner, no camera permission).
implementation("com.google.android.gms:play-services-code-scanner:16.1.0")
testImplementation("junit:junit:4.13.2")
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index 45731fdc..1554038c 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -914,7 +914,11 @@ object LocalPlayer {
/** A user action (skip, seek, stop) during or after the mix: the deck plays on as the song, at its own speed. */
private fun endMix() {
val run = mix ?: return
- if (run.state < MixState.MIXING) return cancelMix("stopped")
+ // Before the mix the pair stays open: a seek comes through here first (seekTo → endFade), and
+ // marking it dropped (as a failed deck is) left the song to end on a plain fade, no mix and no
+ // animation (log 04/11 18:31: two seeks in "Nuit et jour", "deck dropped: stopped", then
+ // "crossfade: 2.991s out"). Prepared again from the new place if the end is still ahead.
+ if (run.state < MixState.MIXING) return cancelMix("stopped", again = true)
mix = null
run.eqA?.release()
run.eq?.neutral()
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index 9a220de0..72fe3b25 100644
--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
@@ -2924,7 +2924,8 @@ object SongPlayer {
}
fun skipTo(item: QueueItem) {
- if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let(LocalPlayer::skipTo); return }
+ // Its index found now: a row shown in a just-dragged order carries the index it had before (see localIndex).
+ if (item.provider == LOCAL) { localIndex(item)?.let(LocalPlayer::skipTo); return }
cancelBurst()
playedByHand = item.uri
val id = trackIdOf(item.uri)
@@ -3000,7 +3001,9 @@ object SongPlayer {
}
fun removeFromQueue(item: QueueItem) {
- if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let(LocalPlayer::remove); return }
+ // Found now, as for skipTo: with the index the row was reported with, a swipe right after a
+ // drag removed whichever song had taken that place.
+ if (item.provider == LOCAL) { localIndex(item)?.let(LocalPlayer::remove); return }
_queue.value = _queue.value.let { q -> q.copy(queued = q.queued - item, nextUp = q.nextUp - item) }
queueCommand {
val a = apiItem(item) ?: return@queueCommand
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt
index 44ef5624..1c26dc31 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt
@@ -6,7 +6,8 @@
* Changes: the sections (now playing, next in queue, next from the context), placement-only
* item motion and the fading edges, over Myspoti's SongPlayer.engineQueue. A row is removed
* by swiping it away, and shuffle and repeat sit in the header as in the queue sheet.
- * A handle on each upcoming row drags it within its section or between them (SongPlayer.reorder, moveIntoQueue); history and
+ * A handle on each upcoming row drags it within its section or between them (sh.calvin.reorderable,
+ * then SongPlayer.reorder / moveIntoQueue); history and
* the autoplay heading are left out for now.
*/
package com.music.spotui.ui.immersive.lyrics
@@ -16,8 +17,6 @@ import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
-import androidx.compose.foundation.gestures.detectDragGestures
-import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -33,10 +32,8 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.LazyItemScope
-import androidx.compose.foundation.lazy.LazyListScope
-import androidx.compose.foundation.lazy.LazyListState
-import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.layout.Column
import androidx.compose.material.icons.Icons
@@ -54,8 +51,6 @@ import androidx.compose.material3.Text
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.foundation.shape.RoundedCornerShape
-import kotlin.math.roundToInt
-import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -67,23 +62,11 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
-import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
-import androidx.compose.runtime.mutableFloatStateOf
import android.os.SystemClock
import app.myspoti.host.android.Logbook
-import androidx.compose.animation.core.animate
-import androidx.compose.runtime.rememberCoroutineScope
-import androidx.compose.ui.layout.onPlaced
-import androidx.compose.ui.layout.positionInParent
-import kotlinx.coroutines.launch
-import androidx.compose.runtime.derivedStateOf
-import androidx.compose.runtime.rememberUpdatedState
-import androidx.compose.runtime.withFrameNanos
import kotlinx.coroutines.delay
-import androidx.compose.ui.zIndex
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalLayoutDirection
@@ -95,6 +78,11 @@ import app.myspoti.engine.R
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import com.music.spotui.di.Graph
+import com.music.spotui.di.Haptics
+import sh.calvin.reorderable.ReorderableItem
+import sh.calvin.reorderable.rememberReorderableLazyListState
+import androidx.compose.foundation.lazy.rememberLazyListState
+import sh.calvin.reorderable.rememberScroller
import com.music.spotui.di.SongPlayer
import com.music.spotui.ui.components.RepeatIcons
import com.music.spotui.ui.immersive.Immersive
@@ -166,85 +154,86 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
}
}
val rows = shownRows(queue, pending, removed)
- val queued = rows.filter { it.queued }
- val nextUp = rows.filter { !it.queued }
- val drag = remember { QueueDrag() }
+
+ // While a row is dragged, the order on screen: each row or heading it passes swaps with it
+ // (sh.calvin.reorderable), and the engine's reports wait for the drop. The drag used to draw
+ // its row elsewhere and work out the place from its position: where the row was drawn, where
+ // its slot was and where it was dropped could disagree, and the row was lost or put back.
+ var dragOrder by remember { mutableStateOf<List<String>?>(null) }
+ var dragStart by remember { mutableStateOf<List<String>>(emptyList()) }
+ var dragRows by remember { mutableStateOf<Map<String, QRow>>(emptyMap()) }
+ val order = dragOrder ?: flatOrder(rows)
+ val byKey = if (dragOrder != null) dragRows else rows.associateBy { it.key }
+ val queuedKeys = QueueDragMath.queuedPart(order, HEADING_NEXT)
val listState = rememberLazyListState()
val keepScroll = remember(listState) { keepScrollInList(listState) }
val direction = LocalLayoutDirection.current
val current = queue.current
val hasCurrent = song.title.value.isNotBlank() || current != null
-
- val rowsNow by rememberUpdatedState(rows)
- val hover by remember { derivedStateOf { hoverOf(listState, rowsNow, drag) } }
- val hoverNow by rememberUpdatedState(hover)
- val onDrop: (QRow) -> Boolean = drop@{ row ->
- val (queuedNew, nextNew, call) = dropPlan(rowsNow, row, hoverNow) ?: return@drop false
- val before = pending?.detach()
+ val topPad = contentPadding.calculateTopPadding() + 8.dp
+ val bottomPad = contentPadding.calculateBottomPadding() + 24.dp
+ // A speed, not a jump: the list's height every 100 ms was dozens of songs flying by (seen in a recording).
+ val speed = with(LocalDensity.current) { 700.dp.toPx() }
+ val reorder = rememberReorderableLazyListState(
+ listState,
+ scrollThresholdPadding = PaddingValues(top = topPad, bottom = bottomPad),
+ scrollThreshold = 72.dp,
+ scroller = rememberScroller(listState, pixelPerSecond = speed),
+ ) { from, to ->
+ val o = dragOrder ?: return@rememberReorderableLazyListState
+ val f = from.key as? String ?: return@rememberReorderableLazyListState
+ val t = to.key as? String ?: return@rememberReorderableLazyListState
+ val row = dragRows[f] ?: return@rememberReorderableLazyListState
+ QueueDragMath.swap(o, f, t, HEADING_NEXT, canLeaveQueue = row.item.provider == SongPlayer.LOCAL)?.let { dragOrder = it }
+ }
+ val onDragStarted: (String) -> Unit = { k ->
+ dragStart = order; dragRows = byKey; dragOrder = order
+ Haptics.click()
+ }
+ val onDragStopped: (String) -> Unit = stop@{ k ->
+ val after = dragOrder ?: return@stop
+ val start = dragStart
+ val known = dragRows
+ dragOrder = null
+ val row = known[k] ?: return@stop
+ val move = QueueDragMath.moveFor(start, after, k, HEADING_NEXT)
+ val call: () -> Unit = when (move) {
+ QueueDragMath.Move.None -> return@stop
+ is QueueDragMath.Move.IntoQueue -> {
+ val target = move.target?.let { known[it]?.item }
+ if (target == null) ({ SongPlayer.moveToQueueFront(row.item) }) else ({ SongPlayer.moveIntoQueue(row.item, target, move.after) })
+ }
+ is QueueDragMath.Move.Beside -> {
+ val target = known[move.target]?.item ?: return@stop
+ ({ SongPlayer.reorder(row.item, target, move.after) })
+ }
+ }
+ val queuedNew = QueueDragMath.queuedPart(after, HEADING_NEXT).mapNotNull { known[it]?.copy(queued = true) }
+ val nextNew = QueueDragMath.nextPart(after, HEADING_NEXT).mapNotNull { known[it]?.copy(queued = false) }
pending = QueueDragMath.Pending(
queuedNew, nextNew,
- rowsNow.filter { it.queued }.map { it.item.uri }, rowsNow.filter { !it.queued }.map { it.item.uri },
+ QueueDragMath.queuedPart(start, HEADING_NEXT).mapNotNull { known[it]?.item?.uri },
+ QueueDragMath.nextPart(start, HEADING_NEXT).mapNotNull { known[it]?.item?.uri },
queuedNew.map { it.item.uri }, nextNew.map { it.item.uri },
- row.item.uri, queue.current?.url, SystemClock.elapsedRealtime(), before,
+ row.item.uri, queue.current?.url, SystemClock.elapsedRealtime(), pending?.detach(),
)
settling = false
- Logbook.log("queue order: set (${row.item.uri} to ${if (row.queued) "queue" else "next"}${if (queuedNew.any { it.key == row.key }) " -> queue" else " -> next"})")
+ Logbook.log("queue order: set (${row.item.uri}: $move)")
call()
- true
- }
- // Positions in the list container's coordinates (where the rows are placed, as positionInParent
- // says): an item's offset counts from the content's start, after the top padding.
- val offsetOf: (String) -> Int? = { k ->
- val info = listState.layoutInfo
- info.visibleItemsInfo.firstOrNull { it.key == k }?.let { it.offset - info.viewportStartOffset }
- }
- // After a drop the rows are where they were drawn, so none is moved again: see [QueueDrag.settling].
- LaunchedEffect(drag.settling) {
- if (!drag.settling) return@LaunchedEffect
- delay(300)
- drag.settling = false
- // Dropped where its new slot is out of sight: nothing to walk back once it scrolls in later.
- drag.awaitKey = null
}
- // The finger near the top or bottom edge scrolls the list, the row staying under it.
- val edge = with(LocalDensity.current) { 88.dp.toPx() }
- // A speed, not a step per frame: 14 dp a frame was 1,700 dp a second at 120 Hz, dozens of
- // songs flying by as soon as the finger neared the edge (seen in a recording).
- val maxSpeed = with(LocalDensity.current) { 700.dp.toPx() }
- val dragging = drag.key != null
- LaunchedEffect(dragging) {
- if (!dragging) return@LaunchedEffect
- var last = 0L
- while (true) {
- val now = withFrameNanos { it }
- val dt = if (last == 0L) 0f else ((now - last) / 1e9f).coerceAtMost(0.05f)
- last = now
- val info = listState.layoutInfo
- // The finger's place, not the row's slot: scrolling moves the slot (out of sight when far)
- // and never the finger.
- val y = drag.center ?: continue
- val step = QueueDragMath.edgeStep(y, info.viewportSize.height.toFloat(), edge, maxSpeed * dt)
- if (step != 0f) drag.offset += listState.scrollBy(step)
- }
- }
- val topPad = contentPadding.calculateTopPadding() + 8.dp
-
val startPad = Immersive.Gutter + contentPadding.calculateStartPadding(direction)
- val endPad = Immersive.Gutter + contentPadding.calculateEndPadding(direction)
- Box(modifier) {
LazyColumn(
state = listState,
- modifier = Modifier
- .matchParentSize()
+ modifier = modifier
.nestedScroll(keepScroll)
.fadingEdges(),
contentPadding = PaddingValues(
start = startPad,
top = topPad,
end = Immersive.Gutter + contentPadding.calculateEndPadding(direction),
- bottom = contentPadding.calculateBottomPadding() + 24.dp,
+ bottom = bottomPad,
),
) {
item(key = "header") {
@@ -277,7 +266,8 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
)
}
}
- if (queued.isNotEmpty()) {
+ // Not a place a row can go: the queued rows are under it.
+ if (queuedKeys.isNotEmpty()) {
item(key = "heading-queued") {
QueueHeading(
title = stringResource(R.string.next_in_queue),
@@ -294,22 +284,27 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
)
}
}
- queueSection(queued, rowsNow, removed, drag, { hoverNow }, onDrop, offsetOf)
}
- if (nextUp.isNotEmpty()) {
- item(key = HEADING_NEXT) {
- QueueHeading(
- title = if (contextName.isNotBlank()) {
- stringResource(R.string.next_from, contextName)
- } else {
- stringResource(R.string.next_up)
- },
- modifier = Modifier.padding(top = 16.dp, bottom = 6.dp).then(queueMotion()),
- )
+ // The queued rows, the context's heading and its rows: one list, so a row passing the
+ // heading only changes places with it (and so changes part).
+ items(order, key = { it }) { k ->
+ if (k == HEADING_NEXT) {
+ // A place the dragged row swaps with (it then changes part), never dragged itself.
+ ReorderableItem(reorder, key = k, animateItemModifier = queueMotion()) {
+ QueueHeading(
+ title = if (contextName.isNotBlank()) stringResource(R.string.next_from, contextName) else stringResource(R.string.next_up),
+ modifier = Modifier.padding(top = 16.dp, bottom = 6.dp),
+ )
+ }
+ return@items
+ }
+ val row = byKey[k] ?: return@items
+ ReorderableItem(reorder, key = k, animateItemModifier = queueMotion()) { dragging ->
+ QueueEntry(row, removed, dragging,
+ handle = Modifier.draggableHandle(onDragStarted = { onDragStarted(k) }, onDragStopped = { onDragStopped(k) }))
}
- queueSection(nextUp, rowsNow, removed, drag, { hoverNow }, onDrop, offsetOf)
}
- if (!hasCurrent && queued.isEmpty() && nextUp.isEmpty()) {
+ if (!hasCurrent && order.isEmpty()) {
item(key = "empty") {
Text(
text = stringResource(R.string.immersive_queue_empty),
@@ -320,39 +315,19 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
}
}
}
- // The dragged row, drawn over the list under the finger. Drawn in its own slot (translated) it
- // vanished once the edge scroll took that slot out of sight: the list stops placing a row
- // there, pinned or not (seen in a recording).
- val ghostRow = drag.key?.let { k -> rows.firstOrNull { it.key == k } }
- val ghostCenter = drag.center
- if (ghostRow != null && ghostCenter != null) {
- val half = with(LocalDensity.current) { Immersive.RowHeight.toPx() } / 2f
- QueueRow(
- title = ghostRow.item.song.title,
- artist = ghostRow.item.song.singer,
- cover = ghostRow.item.song.coverUri,
- isCurrent = false,
- explicit = ghostRow.item.song.explicit,
- onClick = {},
- modifier = Modifier
- .padding(start = (startPad - 8.dp).coerceAtLeast(0.dp), end = (endPad - 8.dp).coerceAtLeast(0.dp))
- .offset { IntOffset(0, (ghostCenter - half).roundToInt()) }
- .clip(RoundedCornerShape(14.dp))
- .background(Color.Black.copy(alpha = 0.45f))
- .padding(horizontal = 8.dp),
- handle = {
- Icon(Icons.Rounded.DragHandle, contentDescription = null, tint = Immersive.TextSecondary,
- modifier = Modifier.size(40.dp).padding(8.dp))
- },
- )
- }
- }
}
/** One queue row: [index] in the flat list (queued rows, then the context's), [key] stable across moves. */
private data class QRow(val key: String, val item: SongPlayer.QueueItem, val queued: Boolean, val index: Int)
private const val SLOW_REPORT_MS = 3_000L
+private const val HEADING_NEXT = "heading-next"
+
+/** The panel's flat order of keys: the queued rows, the context's heading (when it has rows), its rows. */
+private fun flatOrder(rows: List<QRow>): List<String> {
+ val next = rows.filter { !it.queued }.map { it.key }
+ return rows.filter { it.queued }.map { it.key } + (if (next.isEmpty()) emptyList() else listOf(HEADING_NEXT)) + next
+}
/**
* The rows to draw: the order just dropped while the engine has not reported it (its reports in
@@ -363,235 +338,73 @@ private const val SLOW_REPORT_MS = 3_000L
private fun shownRows(queue: SongPlayer.EngineQueue, pending: QueueDragMath.Pending<QRow>?, removed: List<String>): List<QRow> {
// The same keys whichever list is drawn, so swapping the pending order for the engine's moves nothing.
val all = if (pending != null) {
- (pending.queued + pending.next).map { Triple(it.item, it.queued, 0) }
+ (pending.queued + pending.next).map { it.item to it.queued }
} else {
- queue.queued.map { Triple(it, true, 0) } + queue.nextUp.map { Triple(it, false, 0) }
+ queue.queued.map { it to true } + queue.nextUp.map { it to false }
}
val seen = HashMap<String, Int>()
- return all.map { (item, queued, _) ->
+ return all.map { (item, queued) ->
val count = seen.merge(item.uri, 1, Int::plus)!!
Triple(if (count == 1) item.uri else "${item.uri}~$count", item, queued)
}.filter { it.first !in removed }.mapIndexed { i, (k, item, queued) -> QRow(k, item, queued, i) }
}
-/** The row being dragged by its handle: which one, and how far it is from its slot. */
-private class QueueDrag {
- var key by mutableStateOf<String?>(null)
- var offset by mutableFloatStateOf(0f)
- /**
- * The dragged row's centre in the list container's coordinates: where it was taken plus how far the finger
- * moved since, whatever the list scrolled. Where it hovers and the edge scroll are worked out
- * from it: from the row's slot, they were lost once the slot left the screen (the list
- * scrolling under a row dragged far), and the drag ended with the row back in its old place.
- */
- var center by mutableStateOf<Float?>(null)
- /**
- * Just dropped. The rows are drawn where they were (the dragged one under the finger, the others
- * stepped aside) and the list takes the new order in the same frame, so no row has to move: a
- * placement animation then would take each back to its old slot and bring it forth again.
- */
- var settling by mutableStateOf(false)
- /** The dropped row, and where it was drawn (list coordinates), until its new slot is laid out. */
- var awaitKey: String? = null
- var awaitVisual = 0f
-}
-
-/** Where the dragged row hovers: its flat index, the gap among the other rows, and which side of the context heading. */
-private data class Hover(val from: Int, val slot: Int, val aboveBoundary: Boolean)
-
-private const val HEADING_NEXT = "heading-next"
-
-private fun hoverOf(listState: LazyListState, rows: List<QRow>, drag: QueueDrag): Hover? {
- val key = drag.key ?: return null
- val from = rows.indexOfFirst { it.key == key }
- if (from < 0) return null
- val info = listState.layoutInfo
- val visible = info.visibleItemsInfo.associateBy { it.key }
- val center = drag.center ?: return null
- // The rows' middles in the container's coordinates, as [QueueDrag.center].
- val shift = -info.viewportStartOffset
- // A row out of sight is above the dragged one's centre if it comes before it in the list.
- val mids = rows.filter { it.index != from }.map { r ->
- visible[r.key]?.let { it.offset + shift + it.size / 2f } ?: if (r.index < from) Float.NEGATIVE_INFINITY else Float.POSITIVE_INFINITY
- }
- val heading = visible[HEADING_NEXT]
- val firstNext = rows.firstOrNull { !it.queued }
- val queuedOthers = rows.count { it.queued && it.index != from }
- // With no queued row the heading is the queue's drop target: the finger over the heading itself.
- // Higher up (the song playing, the panel's header, past the list's top) it is the top of
- // "next from": counted as the queue there, a row taken to the top of the list went into the
- // queue instead, the engine never reported that order and the row went back (looked cancelled).
- val boundary = heading?.let { if (queuedOthers == 0) (it.offset + shift + it.size).toFloat() else it.offset + shift + it.size / 2f }
- ?: firstNext?.let { visible[it.key]?.let { v -> (v.offset + shift).toFloat() } }
- var slot = QueueDragMath.slot(center, mids)
- val dragged = rows[from]
- // A row of "next from" with no queued row: the queue only when over the heading itself. The
- // queue's only row keeps the old rule (above the heading's foot it stays in the queue).
- val above = if (queuedOthers == 0 && !dragged.queued) {
- heading != null && center >= heading.offset + shift && center < heading.offset + shift + heading.size
- } else boundary == null || center < boundary
- // A Spotify queued song cannot go back into "next from": it stays at the end of the queue.
- if (dragged.queued && dragged.item.provider != SongPlayer.LOCAL) slot = minOf(slot, queuedOthers)
- return Hover(from, slot, above || (dragged.queued && dragged.item.provider != SongPlayer.LOCAL))
-}
-
-/** What dropping [row] at [hover] does: the new queued and next rows, and the engine call that makes it so. */
-private fun dropPlan(rows: List<QRow>, row: QRow, hover: Hover?): Triple<List<QRow>, List<QRow>, () -> Unit>? {
- hover ?: return null
- val oq = rows.filter { it.queued && it.key != row.key }
- val on = rows.filter { !it.queued && it.key != row.key }
- val local = row.item.provider == SongPlayer.LOCAL
- val place = QueueDragMath.held(QueueDragMath.place(hover.slot, oq.size, hover.aboveBoundary), oq.size, local, row.queued)
- val (q, n) = QueueDragMath.apply(oq, on, row.copy(queued = place.toQueue), place)
- if (q.map { it.key } == rows.filter { it.queued }.map { it.key } && n.map { it.key } == rows.filter { !it.queued }.map { it.key }) return null
- val into = if (place.toQueue) oq else on
- val (ti, after) = QueueDragMath.target(into.size, place.index) ?: (null to false)
- val target = ti?.let { into[it].item }
- val item = row.item
- val call: () -> Unit = when {
- place.toQueue && !row.queued ->
- if (target == null) ({ SongPlayer.moveToQueueFront(item) }) else ({ SongPlayer.moveIntoQueue(item, target, after) })
- target == null -> return null
- else -> ({ SongPlayer.reorder(item, target, after) })
- }
- return Triple(q, n, call)
-}
-
-/** One section's rows, each swiped away to remove it or dragged by its handle to move it. */
+/** One upcoming row: swiped away to remove it, dragged by its handle ([handle]) to move it. */
@OptIn(ExperimentalMaterial3Api::class)
-private fun LazyListScope.queueSection(
- section: List<QRow>,
- all: List<QRow>,
- removed: SnapshotStateList<String>,
- drag: QueueDrag,
- hover: () -> Hover?,
- onDrop: (QRow) -> Boolean,
- offsetOf: (String) -> Int?,
-) {
- items(section.size, key = { section[it].key }) { i ->
- val row = section[i]
- val key = row.key
- val item = row.item
- val rowPx = with(LocalDensity.current) { Immersive.RowHeight.toPx() }
- val dragged = key == drag.key
- // Kept composed while dragged: its slot scrolled out of sight, the list would drop the row
- // and its gesture with it (see QueueDrag.center).
- val pinnable = androidx.compose.ui.layout.LocalPinnableContainer.current
- androidx.compose.runtime.DisposableEffect(dragged, pinnable) {
- val handle = if (dragged) pinnable?.pin() else null
- onDispose { handle?.release() }
- }
- // Rows the dragged one passes step aside by one slot.
- val shift = hover()?.let { h -> if (dragged) 0 else QueueDragMath.step(row.index, h.from, h.slot) } ?: 0
- val dropNow by rememberUpdatedState(onDrop)
- val rowNow by rememberUpdatedState(row)
- // What is left of the drop to walk off: the row's drawn position less its slot's.
- val settle = remember { mutableFloatStateOf(0f) }
- // Hoisted: the drop's settle animates the float, and reading it here would recompose the
- // row on every frame of it (its translationY is already read in the layer).
- val settling by remember { derivedStateOf { settle.floatValue != 0f } }
- val scope = rememberCoroutineScope()
- fun settleBack(from: Float) {
- settle.floatValue = from
- scope.launch { animate(from, 0f, animationSpec = tween(180, easing = FastOutSlowInEasing)) { v, _ -> settle.floatValue = v } }
+@Composable
+private fun QueueEntry(row: QRow, removed: SnapshotStateList<String>, dragging: Boolean, handle: Modifier) {
+ val item = row.item
+ val dismiss = rememberSwipeToDismissBoxState(confirmValueChange = { value ->
+ if (value == SwipeToDismissBoxValue.EndToStart) {
+ removed += row.key
+ SongPlayer.removeFromQueue(item)
+ true
+ } else {
+ false
}
- val dismiss = rememberSwipeToDismissBoxState(confirmValueChange = { value ->
- if (value == SwipeToDismissBoxValue.EndToStart) {
- removed += key
- SongPlayer.removeFromQueue(item)
- true
- } else {
- false
- }
- })
- SwipeToDismissBox(
- state = dismiss,
- enableDismissFromStartToEnd = false,
- modifier = Modifier
- .onPlaced { coords ->
- // The dropped row's new slot is laid out: it was drawn elsewhere, and walks the difference.
- if (drag.awaitKey == key) {
- drag.awaitKey = null
- settleBack(drag.awaitVisual - coords.positionInParent().y)
- }
- }
- .then(if (dragged || drag.settling) Modifier else queueMotion())
- .zIndex(if (dragged || settling) 1f else 0f)
- // While dragged the row itself is not drawn: its copy over the list is (see the
- // panel), wherever the slot is. The row only keeps the gesture alive.
- .graphicsLayer {
- translationY = (if (dragged) drag.offset else shift * rowPx) + settle.floatValue
- alpha = if (dragged) 0f else 1f
- },
- backgroundContent = {
- // Drawn only while swiping: the row is transparent, so at rest this × showed
- // through behind the drag handle.
- if (dismiss.dismissDirection != SwipeToDismissBoxValue.Settled) {
- Box(
- Modifier.fillMaxSize().padding(end = 4.dp),
- contentAlignment = Alignment.CenterEnd,
- ) {
- Icon(
- Icons.Rounded.Close,
- contentDescription = stringResource(R.string.immersive_queue_remove),
- tint = Immersive.TextSecondary,
- modifier = Modifier.size(22.dp),
- )
- }
- }
- },
- ) {
- QueueRow(
- title = item.song.title,
- artist = item.song.singer,
- cover = item.song.coverUri,
- isCurrent = false,
- explicit = item.song.explicit,
- onClick = { SongPlayer.skipTo(item) },
- handle = {
+ })
+ SwipeToDismissBox(
+ state = dismiss,
+ enableDismissFromStartToEnd = false,
+ // No swipe while the row is carried.
+ gesturesEnabled = !dragging,
+ modifier = Modifier
+ .clip(RoundedCornerShape(14.dp))
+ .background(if (dragging) Color.Black.copy(alpha = 0.45f) else Color.Transparent),
+ backgroundContent = {
+ // Drawn only while swiping: the row is transparent, so at rest this × showed
+ // through behind the drag handle.
+ if (dismiss.dismissDirection != SwipeToDismissBoxValue.Settled) {
+ Box(
+ Modifier.fillMaxSize().padding(end = 4.dp),
+ contentAlignment = Alignment.CenterEnd,
+ ) {
Icon(
- Icons.Rounded.DragHandle,
- contentDescription = stringResource(R.string.immersive_queue_reorder),
+ Icons.Rounded.Close,
+ contentDescription = stringResource(R.string.immersive_queue_remove),
tint = Immersive.TextSecondary,
- modifier = Modifier
- .size(40.dp)
- .padding(8.dp)
- .pointerInput(key) {
- detectDragGestures(
- onDragStart = {
- drag.key = key; drag.offset = 0f
- drag.center = offsetOf(key)?.let { it + rowPx / 2f }
- },
- onDragEnd = {
- // Worked out while the row is still where it was dropped.
- if (drag.key == key) {
- // Where it was drawn: under the finger (QueueDrag.center), known even
- // when its old slot scrolled out of sight.
- val visual = drag.center?.let { it - rowPx / 2f }
- val dragOffset = drag.offset
- // The new order, the drawn positions and the end of the drag are
- // one change: no frame shows the old order or a row put back.
- val moved = dropNow(rowNow)
- drag.settling = true
- if (moved && visual != null) { drag.awaitKey = key; drag.awaitVisual = visual }
- else settleBack(dragOffset)
- }
- drag.key = null
- drag.offset = 0f
- drag.center = null
- },
- onDragCancel = { drag.key = null; drag.offset = 0f; drag.center = null },
- onDrag = { change, amount ->
- change.consume()
- drag.offset += amount.y
- drag.center = drag.center?.plus(amount.y)
- },
- )
- },
+ modifier = Modifier.size(22.dp),
)
- },
- )
- }
+ }
+ }
+ },
+ ) {
+ QueueRow(
+ title = item.song.title,
+ artist = item.song.singer,
+ cover = item.song.coverUri,
+ isCurrent = false,
+ explicit = item.song.explicit,
+ onClick = { SongPlayer.skipTo(item) },
+ handle = {
+ Icon(
+ Icons.Rounded.DragHandle,
+ contentDescription = stringResource(R.string.immersive_queue_reorder),
+ tint = Immersive.TextSecondary,
+ modifier = handle.size(40.dp).padding(8.dp),
+ )
+ },
+ )
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/QueueDragMath.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/QueueDragMath.kt
index 67b6a76e..078315b8 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/QueueDragMath.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/QueueDragMath.kt
@@ -1,71 +1,57 @@
package com.music.spotui.ui.immersive.lyrics
/**
- * The index arithmetic of dragging a queue row, kept free of Compose so it can be tested.
- * Rows are one flat list (the queued rows, then the context's); "others" is that list without
- * the dragged row, and a slot is a gap in it: 0 before the first, others.size after the last.
+ * The queue drag's rules, kept free of Compose so they can be tested. The panel's rows are one
+ * flat order of keys: the queued rows, the context's heading, then the context's rows (no heading
+ * when the context has none left). The row dragged swaps with the rows and the heading it passes
+ * (sh.calvin.reorderable), so the order on screen is always the one dropped.
*/
internal object QueueDragMath {
- /** The gap the dragged row's centre is in: how many of the other rows' midpoints lie above it. */
- fun slot(center: Float, otherMidpoints: List<Float>): Int = otherMidpoints.count { it < center }
+ fun queuedPart(order: List<String>, heading: String): List<String> = order.takeWhile { it != heading }
+ fun nextPart(order: List<String>, heading: String): List<String> = order.dropWhile { it != heading }.drop(1)
/**
- * How far the row at flat [index] steps aside (-1 up, 1 down, 0 stays) while the row at
- * [from] hovers over gap [slot] of the others.
+ * [order] with [from] moved to [to]'s place, or null when that move is not allowed: a song of
+ * Spotify's queue ([canLeaveQueue] false) cannot go back into "next from" (Spotify has no such
+ * move; it would come back to the queue's end). A local song goes anywhere.
*/
- fun step(index: Int, from: Int, slot: Int): Int = when {
- index == from -> 0
- index > from && index - 1 < slot -> -1
- index < from && index >= slot -> 1
- else -> 0
+ fun swap(order: List<String>, from: String, to: String, heading: String, canLeaveQueue: Boolean): List<String>? {
+ val fi = order.indexOf(from); val ti = order.indexOf(to)
+ if (fi < 0 || ti < 0 || fi == ti || from == heading) return null
+ val r = order.toMutableList().apply { add(ti, removeAt(fi)) }
+ if (!canLeaveQueue && from in queuedPart(order, heading) && from !in queuedPart(r, heading)) return null
+ return r
}
- /** Where a gap lands: in the queued rows ([queueSize] others) or the context's, and at which index there. */
- data class Place(val toQueue: Boolean, val index: Int)
-
- /**
- * Gap [slot] as a place. The gap between the two sections belongs to the queue when the row's
- * centre is above the context heading's midpoint ([aboveBoundary]), else to the context.
- */
- fun place(slot: Int, queueSize: Int, aboveBoundary: Boolean): Place = when {
- slot < queueSize -> Place(true, slot)
- slot > queueSize -> Place(false, slot - queueSize)
- aboveBoundary -> Place(true, queueSize)
- else -> Place(false, 0)
- }
-
- /** [list] with the element at [from] taken out and put at [to] of the rest. */
- fun <T> moved(list: List<T>, from: Int, to: Int): List<T> =
- list.toMutableList().apply { add(to, removeAt(from)) }
-
- /** Pixels to scroll this frame for a finger at [y] in a viewport of [height]: 0 outside the edge zones, growing towards the edge. */
- fun edgeStep(y: Float, height: Float, zone: Float, maxStep: Float): Float {
- val up = ((zone - y) / zone).coerceIn(0f, 1f)
- val down = ((y - (height - zone)) / zone).coerceIn(0f, 1f)
- return (down - up) * maxStep
- }
-
- /** Which of the section's other rows an engine call names for the drop at [index]: its position and whether to go after it; null when the section has no other row. */
- fun target(size: Int, index: Int): Pair<Int, Boolean>? = when {
- size == 0 -> null
- index < size -> index to false
- else -> size - 1 to true
- }
-
- /** The two sections after [dragged] (taken out of both) is dropped at [place]. */
- fun <T> apply(queued: List<T>, next: List<T>, dragged: T, place: Place): Pair<List<T>, List<T>> {
- val q = queued.filter { it != dragged }
- val n = next.filter { it != dragged }
- fun <E> List<E>.with(i: Int, e: E) = toMutableList().apply { add(i.coerceIn(0, size), e) }
- return if (place.toQueue) q.with(place.index, dragged) to n else q to n.with(place.index, dragged)
+ /** What a drop asks of the engine. */
+ sealed interface Move {
+ data object None : Move
+ /** Out of "next from" into the queue, beside [target] (null: first in the queue). */
+ data class IntoQueue(val target: String?, val after: Boolean) : Move
+ /** Before / [after] [target], in [target]'s part (only a local song changes part this way). */
+ data class Beside(val target: String, val after: Boolean) : Move
}
/**
- * Songs of the Spotify queue move between its two parts only one way: out of "next from" into
- * the queue (a song added to it). A queued song cannot go back, so its drop is held in the queue.
+ * The engine call for [dragged] going from [before] to [after]: named by the row it now
+ * follows (or, first of its part, the row it now precedes), as SongPlayer's moves take it.
*/
- fun held(place: Place, queueSize: Int, canLeaveQueue: Boolean, fromQueue: Boolean): Place =
- if (fromQueue && !canLeaveQueue && !place.toQueue) Place(true, queueSize) else place
+ fun moveFor(before: List<String>, after: List<String>, dragged: String, heading: String): Move {
+ if (before == after) return Move.None
+ val wasQueued = dragged in queuedPart(before, heading)
+ val q = queuedPart(after, heading)
+ val nowQueued = dragged in q
+ val part = if (nowQueued) q else nextPart(after, heading)
+ val j = part.indexOf(dragged)
+ if (j < 0) return Move.None
+ val prev = part.getOrNull(j - 1); val next = part.getOrNull(j + 1)
+ return when {
+ nowQueued && !wasQueued -> if (prev != null) Move.IntoQueue(prev, true) else Move.IntoQueue(next, false)
+ prev != null -> Move.Beside(prev, true)
+ next != null -> Move.Beside(next, false)
+ else -> Move.None
+ }
+ }
/** What the engine's latest report means for a [Pending] order. */
sealed interface Verdict {
diff --git a/base/app/src/test/java/com/music/spotui/ui/immersive/lyrics/QueueDragMathTest.kt b/base/app/src/test/java/com/music/spotui/ui/immersive/lyrics/QueueDragMathTest.kt
index 9f773a45..3673606f 100644
--- a/base/app/src/test/java/com/music/spotui/ui/immersive/lyrics/QueueDragMathTest.kt
+++ b/base/app/src/test/java/com/music/spotui/ui/immersive/lyrics/QueueDragMathTest.kt
@@ -2,45 +2,12 @@ package com.music.spotui.ui.immersive.lyrics
import com.music.spotui.di.LocalQueueOrder
import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class QueueDragMathTest {
- @Test fun slotCountsMidpointsAbove() {
- val mids = listOf(30f, 90f, 150f)
- assertEquals(0, QueueDragMath.slot(10f, mids))
- assertEquals(2, QueueDragMath.slot(100f, mids))
- assertEquals(3, QueueDragMath.slot(500f, mids))
- }
-
- @Test fun rowsStepAsideBetweenFromAndSlot() {
- // row 1 of 5 dragged down over gap 3 of the others: rows 2 and 3 step up
- assertEquals(listOf(0, 0, -1, -1, 0), (0..4).map { QueueDragMath.step(it, 1, 3) })
- // row 3 dragged up over gap 1: rows 1 and 2 step down
- assertEquals(listOf(0, 1, 1, 0, 0), (0..4).map { QueueDragMath.step(it, 3, 1) })
- assertEquals(listOf(0, 0, 0, 0, 0), (0..4).map { QueueDragMath.step(it, 2, 2) })
- }
-
- @Test fun placeSplitsAtTheSections() {
- assertEquals(QueueDragMath.Place(true, 1), QueueDragMath.place(1, 3, false))
- assertEquals(QueueDragMath.Place(false, 2), QueueDragMath.place(5, 3, true))
- assertEquals(QueueDragMath.Place(true, 3), QueueDragMath.place(3, 3, true))
- assertEquals(QueueDragMath.Place(false, 0), QueueDragMath.place(3, 3, false))
- }
-
- @Test fun movedKeepsTheDroppedOrder() {
- assertEquals(listOf("b", "c", "a"), QueueDragMath.moved(listOf("a", "b", "c"), 0, 2))
- assertEquals(listOf("c", "a", "b"), QueueDragMath.moved(listOf("a", "b", "c"), 2, 0))
- }
-
- @Test fun edgeStepGrowsTowardsTheEdge() {
- assertEquals(0f, QueueDragMath.edgeStep(500f, 1000f, 100f, 20f), 0f)
- assertEquals(-10f, QueueDragMath.edgeStep(50f, 1000f, 100f, 20f), 0.001f)
- assertEquals(20f, QueueDragMath.edgeStep(1000f, 1000f, 100f, 20f), 0.001f)
- assertTrue(QueueDragMath.edgeStep(20f, 1000f, 100f, 20f) < QueueDragMath.edgeStep(80f, 1000f, 100f, 20f))
- }
-
- // ── The panel's expected order against what the local player's move logic ends with ──
+ private val H = "heading"
/** cur, then [nq] queued songs q0.., then [nn] list songs n0.. */
private fun local(nq: Int, nn: Int): Triple<List<String>, Set<String>, Int> {
@@ -48,54 +15,62 @@ class QueueDragMathTest {
return Triple(listOf("cur") + queued + (0 until nn).map { "n$it" }, queued.toSet(), 0)
}
+ /** The panel's flat order: the queued rows, the heading (with a context row), the context's rows. */
+ private fun panel(order: List<String>, queued: Set<String>): List<String> {
+ val rows = order.drop(1)
+ val next = rows.filter { it !in queued }
+ return rows.filter { it in queued } + (if (next.isEmpty()) emptyList() else listOf(H)) + next
+ }
+
@Test fun everyDropEndsInThePanelsOrderOnTheLocalPlayer() {
var checked = 0
for (nq in 0..3) for (nn in 0..3) {
val (order, queuedSet, cur) = local(nq, nn)
- val rows = order.drop(1)
- for (dragged in rows) for (above in listOf(true, false)) {
- val oq = rows.filter { it in queuedSet && it != dragged }
- val on = rows.filter { it !in queuedSet && it != dragged }
- for (slot in 0..(oq.size + on.size)) {
- val place = QueueDragMath.place(slot, oq.size, above)
- val (eq, en) = QueueDragMath.apply(oq, on, dragged, place)
- if (eq == rows.filter { it in queuedSet } && en == rows.filter { it !in queuedSet }) continue
- val into = if (place.toQueue) oq else on
- val target = QueueDragMath.target(into.size, place.index)
- val from = order.indexOf(dragged)
- val wasQueued = dragged in queuedSet
- val result: Pair<List<String>, Boolean>? = when {
- place.toQueue && !wasQueued && target == null ->
- LocalQueueOrder.moveToFront(order, cur, from)?.let { it to true }
- target == null -> continue
- else -> LocalQueueOrder.moveBeside(order, cur, from, order.indexOf(into[target.first]), target.second) { it in queuedSet }
- }
- val (after, toQueue) = result!!
- val nowQueued = { x: String -> if (x == dragged) toQueue else x in queuedSet }
- val tail = after.drop(1)
- assertEquals("cur stays", "cur", after[0])
- assertEquals("queued part $dragged slot $slot nq=$nq nn=$nn above=$above", eq, tail.filter(nowQueued))
- assertEquals("list part $dragged slot $slot nq=$nq nn=$nn above=$above", en, tail.filterNot(nowQueued))
- assertEquals("queued songs come first", tail.filter(nowQueued), tail.take(eq.size))
- checked++
+ val before = panel(order, queuedSet)
+ for (dragged in order.drop(1)) for (to in before) {
+ // One swap with each row or the heading: every place the drag can reach in one step,
+ // and the result of a longer drag is a list that one step also gives.
+ val after = QueueDragMath.swap(before, dragged, to, H, canLeaveQueue = true) ?: continue
+ val move = QueueDragMath.moveFor(before, after, dragged, H)
+ val from = order.indexOf(dragged)
+ val result: Pair<List<String>, Boolean> = when (move) {
+ QueueDragMath.Move.None -> continue
+ is QueueDragMath.Move.IntoQueue -> if (move.target == null) LocalQueueOrder.moveToFront(order, cur, from)!! to true
+ else LocalQueueOrder.moveBeside(order, cur, from, order.indexOf(move.target), move.after) { it in queuedSet }!!
+ is QueueDragMath.Move.Beside -> LocalQueueOrder.moveBeside(order, cur, from, order.indexOf(move.target), move.after) { it in queuedSet }!!
}
+ val (played, toQueue) = result
+ val nowQueued = { x: String -> if (x == dragged) toQueue else x in queuedSet }
+ assertEquals("cur stays", "cur", played[0])
+ assertEquals("drag $dragged to $to nq=$nq nn=$nn: $move", QueueDragMath.queuedPart(after, H), played.drop(1).filter(nowQueued))
+ assertEquals("drag $dragged to $to nq=$nq nn=$nn: $move", QueueDragMath.nextPart(after, H), played.drop(1).filterNot(nowQueued))
+ assertEquals("queued songs come first", played.drop(1).filter(nowQueued), played.drop(1).take(QueueDragMath.queuedPart(after, H).size))
+ checked++
}
}
assertTrue(checked > 100)
}
- @Test fun targetNamesTheNeighbourToDropBesideOrNothing() {
- assertEquals(null, QueueDragMath.target(0, 0))
- assertEquals(0 to false, QueueDragMath.target(3, 0))
- assertEquals(1 to false, QueueDragMath.target(3, 1))
- assertEquals(2 to true, QueueDragMath.target(3, 3))
- }
-
@Test fun aQueuedSpotifySongStaysInTheQueue() {
- val into = QueueDragMath.Place(false, 2)
- assertEquals(QueueDragMath.Place(true, 3), QueueDragMath.held(into, 3, canLeaveQueue = false, fromQueue = true))
- assertEquals(into, QueueDragMath.held(into, 3, canLeaveQueue = true, fromQueue = true))
- assertEquals(into, QueueDragMath.held(into, 3, canLeaveQueue = false, fromQueue = false))
+ val order = listOf("q0", "q1", H, "n0", "n1")
+ assertNull(QueueDragMath.swap(order, "q1", H, H, canLeaveQueue = false))
+ assertNull(QueueDragMath.swap(order, "q0", "n0", H, canLeaveQueue = false))
+ assertEquals(listOf("q1", "q0", H, "n0", "n1"), QueueDragMath.swap(order, "q0", "q1", H, canLeaveQueue = false))
+ // A song of "next from" goes up into the queue past the heading.
+ assertEquals(listOf("q0", "q1", "n0", H, "n1"), QueueDragMath.swap(order, "n0", H, H, canLeaveQueue = false))
+ assertNull(QueueDragMath.swap(order, H, "n0", H, canLeaveQueue = true))
+ }
+
+ @Test fun theEngineCallNamesTheRowBeforeElseTheRowAfter() {
+ val before = listOf("q0", "q1", H, "n0", "n1")
+ val m = QueueDragMath.Move.IntoQueue("q1", true)
+ assertEquals(m, QueueDragMath.moveFor(before, listOf("q0", "q1", "n0", H, "n1"), "n0", H))
+ // With no queued row, over the heading: first in the queue.
+ assertEquals(QueueDragMath.Move.IntoQueue(null, false), QueueDragMath.moveFor(listOf(H, "n0", "n1"), listOf("n0", H, "n1"), "n0", H))
+ // Within "next from": after the row it now follows, else before the one it now precedes.
+ assertEquals(QueueDragMath.Move.Beside("n0", false), QueueDragMath.moveFor(listOf(H, "n0", "n1"), listOf(H, "n1", "n0"), "n1", H))
+ assertEquals(QueueDragMath.Move.Beside("n1", true), QueueDragMath.moveFor(listOf(H, "n0", "n1", "n2"), listOf(H, "n1", "n0", "n2"), "n0", H))
+ assertEquals(QueueDragMath.Move.None, QueueDragMath.moveFor(before, before, "q0", H))
}
// ── The Spotify queue's reports while a move is applied: stale, half-way, final ──
@@ -106,9 +81,13 @@ class QueueDragMathTest {
/** "n1" dragged from the list into the queue between q0 and q1. */
private val q0 = listOf("q0", "q1")
private val n0 = listOf("n0", "n1", "n2")
- private val place = QueueDragMath.Place(true, 1)
- private fun move(dragged: String = "n1", q: List<String> = q0, n: List<String> = n0, p: QueueDragMath.Place = place, at: Long = 0L, prev: QueueDragMath.Pending<String>? = null): QueueDragMath.Pending<String> {
- val (eq, en) = QueueDragMath.apply(q, n, dragged, p)
+ /** Where a drop lands: in the queue or the context's part, at that index of the other rows. */
+ private data class Place(val toQueue: Boolean, val index: Int)
+ private val place = Place(true, 1)
+ private fun move(dragged: String = "n1", q: List<String> = q0, n: List<String> = n0, p: Place = place, at: Long = 0L, prev: QueueDragMath.Pending<String>? = null): QueueDragMath.Pending<String> {
+ val oq = q - dragged; val on = n - dragged
+ val eq = if (p.toQueue) oq.toMutableList().apply { add(p.index, dragged) } else oq
+ val en = if (p.toQueue) on else on.toMutableList().apply { add(p.index, dragged) }
return QueueDragMath.Pending(eq, en, q, n, eq, en, dragged, "cur", at, prev)
}
private val finalQ = listOf("q0", "n1", "q1")
@@ -153,7 +132,7 @@ class QueueDragMathTest {
@Test fun aSameSectionMoveEndsOnItsFinalReportOnly() {
val n = listOf("n0", "n1", "n2", "n3")
- val p = move("n0", emptyList(), n, QueueDragMath.Place(false, 3))
+ val p = move("n0", emptyList(), n, Place(false, 3))
assertEquals(listOf("n1", "n2", "n3", "n0"), p.next)
assertEquals(Keep, p.report(emptyList(), n, "cur", 10))
assertEquals(Match, p.report(emptyList(), listOf("n1", "n2", "n3", "n0"), "cur", 20))
@@ -162,7 +141,7 @@ class QueueDragMathTest {
@Test fun quickDropsChainTheirReports() {
val first = move()
// A second drag, made before anything was reported: n2 into the queue, first.
- val second = move("n2", finalQ, finalN, QueueDragMath.Place(true, 0), at = 300, prev = first.detach())
+ val second = move("n2", finalQ, finalN, Place(true, 0), at = 300, prev = first.detach())
assertEquals(listOf("n2", "q0", "n1", "q1"), second.queued); assertEquals(listOf("n0"), second.next)
assertEquals(Keep, second.report(q0, n0, "cur", 400)) // before the first
assertEquals(Keep, second.report(q0, listOf("n0", "n2"), "cur", 500)) // half-way through the first
@@ -175,16 +154,4 @@ class QueueDragMathTest {
assertTrue(move().report(listOf("x"), listOf("y"), "other", 1) is QueueDragMath.Verdict.Drop)
}
- @Test fun steppedAsideRowsAreDrawnWhereTheNewOrderLaysThemOut() {
- // A row drawn shifted by step() rows from its slot must sit exactly at its slot in the new order:
- // then dropping needs no row to move.
- for (size in 2..6) for (from in 0 until size) for (slot in 0 until size) {
- val order = (0 until size).toList()
- val after = QueueDragMath.moved(order, from, slot)
- for (row in order) if (row != from) {
- assertEquals("size=$size from=$from slot=$slot row=$row", row + QueueDragMath.step(row, from, slot), after.indexOf(row))
- }
- assertEquals(slot, after.indexOf(from))
- }
- }
}