Skip to content

Native Android client for Spotify, built with Jetpack Compose

A playlist of one's own in its own order can be put in another order by hand in both looks ("Move" puts a handle on each song, a drag on it moves the song): the list changes at once, Spotify is told the row goes before the one now after it, the songs kept for the playlist are read again, and a refusal puts the order back with "Spotify refused the change" (#83)

kota-zo8291bd34f211
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt
index 9122661a..078476e3 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt
@@ -36,6 +36,7 @@ import androidx.compose.material.icons.rounded.AutoAwesome
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.DeleteOutline
import androidx.compose.material.icons.rounded.Download
+import androidx.compose.material.icons.rounded.DragHandle
import androidx.compose.material.icons.rounded.Favorite
import androidx.compose.material.icons.rounded.FavoriteBorder
import androidx.compose.material.icons.rounded.MoreHoriz
@@ -130,7 +131,10 @@ import com.music.spotui.ui.navigation.albumRoute
import com.music.spotui.ui.navigation.artistRoute
import com.music.spotui.ui.navigation.profileRoute
import com.music.spotui.ui.screens.ContextViewModel
+import com.music.spotui.ui.screens.PlaylistReorder
import com.music.spotui.ui.screens.SmartShuffle
+import com.music.spotui.ui.screens.movableRow
+import com.music.spotui.ui.screens.rememberPlaylistDrag
import com.music.spotui.ui.screens.TrackOrder
import com.music.spotui.ui.screens.TrackSort
import com.music.spotui.ui.viewmodel.PlayerViewModel
@@ -375,13 +379,21 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVie
if (isLiked) p.tracks.filter { SongPlayer.library["spotify:track:${it.spotifyTrackId}"] != false } else p.tracks
}
}
+ // An own playlist in its own order: its songs can be moved by hand, a handle on each while
+ // "Move" is on, as on the Classic page.
+ var moving by remember(p.uri) { mutableStateOf(false) }
+ val canMove = remember(p, vm.editableContext.value, sort, find) {
+ PlaylistReorder.allowed(p.type, vm.editableContext.value, p.isBlend, sort.isCustom, p.complete, find, p.tracks.map { it.rowUid })
+ }
+ val reordering = moving && canMove
// The rows and their keys in one derived state: the list re-reads its rows outside composition
// (a search letter, the "×" of the search), and keys remembered apart from them were one list
- // behind (a list that grows on the "×" ran out of keys: a crash).
- val shown by remember(p, find, sort) {
+ // behind (a list that grows on the "×" ran out of keys: a crash). Rows that move are keyed by
+ // their own id, which goes with them wherever they are put.
+ val shown by remember(p, find, sort, reordering) {
derivedStateOf {
val found = if (findable) all.filter { matchesFind(find, it.title, it.singer, it.album) } else all
- withRowKeys(if (findable) sort.apply(found) else found) { it.id.toString() }
+ withRowKeys(if (findable) sort.apply(found) else found) { if (reordering) PlaylistReorder.key(it) else it.id.toString() }
}
}
val rows = shown.first
@@ -417,6 +429,15 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVie
}
val listState = rememberLazyListState()
+ val drag = rememberPlaylistDrag(listState)
+ drag.rows = rows
+ drag.onDrop = { move ->
+ vm.moveRow(move) { ok ->
+ if (!ok) Toast.makeText(context, context.getString(R.string.playlist_change_refused), Toast.LENGTH_SHORT).show()
+ }
+ }
+ // The page has the new order (or had it put back): its own rows are shown again.
+ LaunchedEffect(p, reordering) { drag.settle() }
val findFocus = remember { FocusRequester() }
val findStop = with(LocalDensity.current) { immersiveTopContentPadding().roundToPx() }
// Opening the search carries the page up to it, so the field lands just clear of the bar with
@@ -460,6 +481,8 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVie
onAskRemoveDownloads = { askRemoveDownloads = true },
members = crew,
onMembers = { showMembers = true },
+ moving = moving.takeIf { canMove },
+ onMove = { moving = !moving },
)
}
// Someone else's collaborative playlist this account was never invited to.
@@ -492,9 +515,18 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVie
if (rows.isEmpty() && find.isNotBlank()) item(key = "find-empty") {
ImmersiveMessageState(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, find.trim()))
}
+ if (reordering) item(key = "reorder-hint") {
+ Text(
+ stringResource(R.string.playlist_reorder_hint),
+ style = Immersive.Caption.copy(color = Immersive.TextSecondary),
+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp),
+ )
+ }
val numbered = p.type == "album"
- itemsIndexed(shown.first, key = { i, _ -> shown.second[i] }) { index, song ->
- Column {
+ // While a song is moved: the rows in the order under the finger.
+ val (listed, keys) = drag.order?.takeIf { reordering }?.let { o -> o to o.map(PlaylistReorder::key) } ?: shown
+ itemsIndexed(listed, key = { i, _ -> keys[i] }) { index, song ->
+ Column(if (reordering) movableRow(drag, song, Immersive.Raised) else Modifier) {
ImmersiveSwipeToQueue(song) {
ImmersiveSongRow(
song = song,
@@ -512,9 +544,18 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVie
// (what Spotify last reported, the list's one batch check, the downloads kept on the phone).
liked = com.music.spotui.di.trackSaved(song.spotifyTrackId, savedTracks),
offline = OfflineStore.statusOf(song.spotifyTrackId),
- // Collaborative: the small face of who added the song.
- trailing = vm.adders.value.let { a -> a["row:" + song.rowUid] ?: a["song:" + song.spotifyTrackId] }?.let { m ->
- { com.music.spotui.ui.components.ProfileAvatar(m.imageUrl, m.name, 22.dp) }
+ // Collaborative: the small face of who added the song. Being moved: its handle.
+ trailing = vm.adders.value.let { a -> a["row:" + song.rowUid] ?: a["song:" + song.spotifyTrackId] }.let { m ->
+ val face: @Composable () -> Unit = {
+ if (m != null) com.music.spotui.ui.components.ProfileAvatar(m.imageUrl, m.name, 22.dp)
+ if (reordering) Icon(
+ Icons.Rounded.DragHandle,
+ contentDescription = stringResource(R.string.edit_playlist_items_move_chip),
+ tint = Immersive.TextSecondary,
+ modifier = Modifier.padding(start = if (m != null) 8.dp else 0.dp).then(drag.handle(song.rowUid)).size(28.dp),
+ )
+ }
+ if (m == null && !reordering) null else face
},
)
}
@@ -640,6 +681,9 @@ private fun ContextHeader(
onAskRemoveDownloads: () -> Unit,
members: List<app.myspoti.api.PlaylistMember> = emptyList(),
onMembers: () -> Unit = {},
+ /** Whether the songs' handles are out; null: the songs cannot be moved here (no "Move" button). */
+ moving: Boolean? = null,
+ onMove: () -> Unit = {},
) {
val context = LocalContext.current
Column(
@@ -800,6 +844,13 @@ private fun ContextHeader(
onClick = onToggleSmart,
tint = if (smart) Immersive.Accent else Immersive.Text,
)
+ // "Move": a handle on each song, to put them in another order (again: done).
+ if (moving != null) ImmersiveCircleButton(
+ icon = Icons.Rounded.DragHandle,
+ contentDescription = stringResource(if (moving) R.string.done else R.string.edit_playlist_items_move_chip),
+ onClick = onMove,
+ tint = if (moving) Immersive.Accent else Immersive.Text,
+ )
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
index a425e4d5..bc17806d 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
@@ -9,6 +9,7 @@ import com.music.spotui.ui.theme.headerTint
import com.music.spotui.ui.theme.AppMuted
import androidx.compose.material.icons.filled.SwapVert
+import androidx.compose.material.icons.filled.DragHandle
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.ui.res.stringResource
@@ -101,6 +102,7 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.withContext
+import kotlinx.coroutines.sync.withLock
import androidx.compose.foundation.layout.offset
import androidx.compose.material.icons.filled.AutoAwesome
import app.myspoti.host.android.MyspotiRuntime
@@ -427,6 +429,44 @@ class ContextViewModel(
recent[k] = updated
}
+ // Moves are written one at a time, in the order they were made.
+ private val moveWrites = kotlinx.coroutines.sync.Mutex()
+
+ /**
+ * A row of this page's playlist moved by hand: the list takes its new order at once, then
+ * Spotify is told. A refusal puts the order back as it was and [onDone] gets false. Returns
+ * false when the page could not take the move (its rows changed under the drag).
+ */
+ fun moveRow(move: PlaylistReorder.RowMove, onDone: (Boolean) -> Unit): Boolean {
+ val k = key ?: return false
+ val current = (_page.value as? Response.Success)?.data ?: return false
+ val tracks = PlaylistReorder.applied(current.tracks, move) { it.rowUid } ?: return false
+ val updated = Response.Success(current.copy(tracks = tracks))
+ _page.value = updated
+ recent[k] = updated
+ viewModelScope.launch {
+ val ok = withContext(Dispatchers.IO) {
+ moveWrites.withLock {
+ runCatching { MyspotiRuntime.api.playlists.moveTracks(current.uri, listOf(move.uid), move.beforeUid) }.isSuccess
+ }
+ }
+ val id = current.uri.substringAfterLast(':')
+ if (ok) withContext(Dispatchers.IO) {
+ // The songs kept for this playlist (same count, so reused as they were) are read again,
+ // and its copies on storage take the new order.
+ Api.invalidatePlaylist(id)
+ val now = (_page.value as? Response.Success)?.data?.takeIf { it.uri == current.uri } ?: return@withContext
+ com.music.spotui.data.api.PagePrefetch.refreshed(id, now)
+ com.music.spotui.data.offline.OfflineCollections.sync(now)
+ } else if (_page.value === updated) {
+ _page.value = Response.Success(current)
+ recent[k] = Response.Success(current)
+ } else reload()
+ onDone(ok)
+ }
+ return true
+ }
+
/** A name or description just saved shows in the header at once; the page is read again behind it. */
fun showDetails(name: String, description: String) {
val k = key ?: return
@@ -676,19 +716,36 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
if (p.type == "liked" || p.type == "liked-artist") p.tracks.filter { SongPlayer.library["spotify:track:${it.spotifyTrackId}"] != false } else p.tracks
}
}
+ // An own playlist in its own order: its songs can be moved by hand, a handle on each while
+ // "Move" is on (asked on Discord).
+ var moving by remember(p.uri) { mutableStateOf(false) }
+ val canMove = remember(p, vm.editableContext.value, sort, find) {
+ PlaylistReorder.allowed(p.type, vm.editableContext.value, p.isBlend, sort.isCustom, p.complete, find, p.tracks.map { it.rowUid })
+ }
+ val reordering = moving && canMove
// Unique and stable for a given list: a playlist can hold the same song twice (the id alone
// is not unique) and the index changes at every sort (which would lose every item). Made with
// the rows in one derived state: the list re-reads its rows outside composition (a like, a
// search letter), and keys remembered apart from them could be one list behind (a crash).
- val shown by remember(p, find, sort) {
+ // Rows that move are keyed by their own id, which goes with them wherever they are put.
+ val shown by remember(p, find, sort, reordering) {
derivedStateOf {
val found = if (findable) all.filter { com.music.spotui.ui.components.matchesFind(find, it.title, it.singer, it.album) } else all
- com.music.spotui.ui.components.withRowKeys(if (findable) sort.apply(found) else found) { it.id.toString() }
+ com.music.spotui.ui.components.withRowKeys(if (findable) sort.apply(found) else found) { if (reordering) PlaylistReorder.key(it) else it.id.toString() }
}
}
val rows = shown.first
val listState = androidx.compose.foundation.lazy.rememberLazyListState()
+ val drag = rememberPlaylistDrag(listState)
+ drag.rows = rows
+ drag.onDrop = { move ->
+ vm.moveRow(move) { ok ->
+ if (!ok) android.widget.Toast.makeText(context, context.getString(R.string.playlist_change_refused), android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+ // The page has the new order (or had it put back): its own rows are shown again.
+ LaunchedEffect(p, reordering) { drag.settle() }
val pullState = androidx.compose.material3.pulltorefresh.rememberPullToRefreshState()
val refreshing by vm.refreshing
// The search field and the Blend line are folded away: the page opens on its songs. A pull
@@ -887,6 +944,14 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
Spacer(Modifier.width(16.dp))
TrackSortButton(sort) { sort = it; TrackOrder.save(ctx, p.uri, it) }
}
+ // "Move": a handle on each song, to put them in another order (again: done).
+ if (canMove) {
+ Spacer(Modifier.width(16.dp))
+ Icon(Icons.Default.DragHandle,
+ contentDescription = stringResource(if (moving) R.string.done else R.string.edit_playlist_items_move_chip),
+ tint = if (moving) SpotifyGreen else AppText.copy(alpha = 0.8f),
+ modifier = Modifier.size(26.dp).pressable(0.9f) { moving = !moving })
+ }
Spacer(Modifier.weight(1f))
val smart = SmartShuffle.on.value == p.uri
Box {
@@ -979,9 +1044,14 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
if (shown.first.isEmpty() && find.isNotBlank()) item(key = "find-empty") {
com.music.spotui.ui.components.FindInListEmpty(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, find.trim()))
}
- val (listed, keys) = shown
+ if (reordering) item(key = "reorder-hint") {
+ Text(stringResource(R.string.playlist_reorder_hint), color = AppMuted, fontSize = 13.sp,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp))
+ }
+ // While a song is moved: the rows in the order under the finger.
+ val (listed, keys) = drag.order?.takeIf { reordering }?.let { o -> o to o.map(PlaylistReorder::key) } ?: shown
itemsIndexed(listed, key = { i, _ -> keys[i] }) { _, song ->
- com.music.spotui.ui.components.SwipeToQueue(song, animatedRow()) { TrackRow(
+ com.music.spotui.ui.components.SwipeToQueue(song, if (reordering) movableRow(drag, song, tone(0xFF2A2A2A)) else animatedRow()) { TrackRow(
song = song,
showCover = p.type != "album",
isCurrent = song.id == currentSongId,
@@ -990,6 +1060,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
addedBy = vm.adders.value.let { a -> a["row:" + song.rowUid] ?: a["song:" + song.spotifyTrackId] },
onClick = { dismissKeyboard(); if (SmartShuffle.on.value == p.uri) vm.playSmart(p, song) else vm.play(p, song, sort) },
onMore = { menuSong = song },
+ handle = if (reordering) drag.handle(song.rowUid) else null,
) }
}
// "Recommended songs", as under an own playlist in the official apps (an empty one too).
@@ -1248,6 +1319,8 @@ private fun TrackRow(
onClick: () -> Unit,
onMore: () -> Unit,
addedBy: app.myspoti.api.PlaylistMember? = null,
+ /** The song can be moved: a drag on this handle carries it. */
+ handle: Modifier? = null,
) {
// A greyed row is still tried (see the click): the tap is followed by a check, not a refusal.
val scope = androidx.compose.runtime.rememberCoroutineScope()
@@ -1331,6 +1404,15 @@ private fun TrackRow(
.size(24.dp)
,
)
+ handle?.let { h ->
+ Spacer(Modifier.width(12.dp))
+ Icon(
+ Icons.Default.DragHandle,
+ contentDescription = stringResource(R.string.edit_playlist_items_move_chip),
+ tint = AppText.copy(alpha = 0.7f),
+ modifier = h.size(28.dp),
+ )
+ }
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlaylistReorder.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlaylistReorder.kt
new file mode 100644
index 00000000..d9af5eae
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlaylistReorder.kt
@@ -0,0 +1,198 @@
+package com.music.spotui.ui.screens
+
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.VisibilityThreshold
+import androidx.compose.animation.core.spring
+import androidx.compose.foundation.background
+import androidx.compose.foundation.gestures.detectDragGestures
+import androidx.compose.foundation.gestures.scrollBy
+import androidx.compose.foundation.lazy.LazyItemScope
+import androidx.compose.foundation.lazy.LazyListState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.withFrameNanos
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.hapticfeedback.HapticFeedback
+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.zIndex
+import com.music.spotui.data.entity.SongsModel
+
+/**
+ * Moving songs of a playlist by hand (asked on Discord, #83). Spotify takes a move as "these rows
+ * go just before that row" (the end when there is none), so a drop is said that way.
+ */
+object PlaylistReorder {
+ /** [uid] goes just before the row [beforeUid]; null: to the end of the playlist. */
+ data class RowMove(val uid: String, val beforeUid: String?)
+
+ /**
+ * The rows can be moved by hand: an own or collaborative playlist (not a Blend) shown whole, in
+ * its own order and from its start, with no search narrowing it, and every row known by its
+ * own id (the same song twice is two rows).
+ */
+ fun allowed(type: String, editable: Boolean, isBlend: Boolean, customOrder: Boolean, complete: Boolean, find: String, rowUids: List<String>): Boolean =
+ type == "playlist" && editable && !isBlend && customOrder && complete && find.isBlank() &&
+ rowUids.size > 1 && rowUids.none { it.isBlank() } && rowUids.toSet().size == rowUids.size
+
+ /**
+ * What a drag did to [moved], from the rows' ids before it ([before]) and after it ([after]):
+ * the row now right after it names the place; null when it is back where it was.
+ */
+ fun rowMove(before: List<String>, after: List<String>, moved: String): RowMove? {
+ val at = after.indexOf(moved)
+ if (at < 0 || moved !in before) return null
+ val next = after.getOrNull(at + 1)
+ if (next == before.getOrNull(before.indexOf(moved) + 1)) return null
+ return RowMove(moved, next)
+ }
+
+ /** [rows] with [move] made, as Spotify makes it; null when a row it names is not there. */
+ fun <T> applied(rows: List<T>, move: RowMove, uidOf: (T) -> String): List<T>? {
+ val from = rows.indexOfFirst { uidOf(it) == move.uid }
+ if (from < 0) return null
+ val out = rows.toMutableList()
+ val row = out.removeAt(from)
+ val to = if (move.beforeUid == null) out.size else out.indexOfFirst { uidOf(it) == move.beforeUid }
+ if (to < 0) return null
+ out.add(to, row)
+ return out
+ }
+
+ /** A row's key in the list while its rows can move: its own id, so it keeps its key wherever it goes. */
+ fun key(song: SongsModel) = "row:" + song.rowUid
+}
+
+/**
+ * The row being moved on a playlist page, for both looks: the rows as shown while it moves (moved
+ * live under the finger), its offset from its place, and the list scrolling by itself near its
+ * edges. A drag starts on a row's handle, as in the queue.
+ */
+class PlaylistDrag(private val listState: LazyListState, private val haptic: HapticFeedback) {
+ /** The rows as shown while one moves, and after the drop until the page has the new order. */
+ var order by mutableStateOf<List<SongsModel>?>(null)
+ /** The row under the finger, by its row id. */
+ var dragged by mutableStateOf<String?>(null)
+ private set
+ var offset by mutableFloatStateOf(0f)
+ private set
+ private var start: List<String> = emptyList()
+
+ /** Set at every composition by the page: the rows it shows now, and what a drop does. */
+ var rows: List<SongsModel> = emptyList()
+ var onDrop: (PlaylistReorder.RowMove) -> Boolean = { false }
+
+ private fun begin(uid: String) {
+ order = rows
+ start = rows.map { it.rowUid }
+ dragged = uid
+ offset = 0f
+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
+ }
+
+ /** Moves the dragged row to the row its centre is over (rows of the playlist only). */
+ fun follow() {
+ val key = "row:" + (dragged ?: return)
+ val info = listState.layoutInfo.visibleItemsInfo
+ val item = info.firstOrNull { it.key == key } ?: return
+ val centre = item.offset + offset + item.size / 2f
+ val target = info.firstOrNull { it.key != key && (it.key as? String)?.startsWith("row:") == true && centre.toInt() in it.offset until it.offset + it.size } ?: return
+ val current = order ?: return
+ val from = current.indexOfFirst { PlaylistReorder.key(it) == key }
+ val to = current.indexOfFirst { PlaylistReorder.key(it) == target.key }
+ if (from < 0 || to < 0) return
+ // Keeps the list still when the first visible row is involved.
+ if (listState.firstVisibleItemIndex == item.index || listState.firstVisibleItemIndex == target.index)
+ listState.requestScrollToItem(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset)
+ order = current.toMutableList().apply { add(to, removeAt(from)) }
+ offset += item.offset - target.offset
+ }
+
+ private fun end() {
+ val uid = dragged ?: return
+ dragged = null
+ offset = 0f
+ haptic.performHapticFeedback(HapticFeedbackType.GestureEnd)
+ val move = order?.let { PlaylistReorder.rowMove(start, it.map(SongsModel::rowUid), uid) }
+ // Back where it was, or the page could not take it: the rows as the page has them.
+ if (move == null || !onDrop(move)) order = null
+ }
+
+ private fun cancel() {
+ dragged = null
+ offset = 0f
+ order = null
+ }
+
+ /** The page has new rows (the move taken, put back, or read again): they are shown, unless a row is still held. */
+ fun settle() {
+ if (dragged == null) order = null
+ }
+
+ /** The handle of the row [uid]: a drag on it moves the row. */
+ fun handle(uid: String): Modifier = Modifier.pointerInput(this, uid) {
+ try {
+ detectDragGestures(
+ onDragStart = { begin(uid) },
+ onDragEnd = { end() },
+ onDragCancel = { cancel() },
+ ) { change, amount -> change.consume(); offset += amount.y; follow() }
+ } finally { if (dragged == uid) cancel() }
+ }
+
+ /** Near the top or bottom edge, the list scrolls by itself while a row is held. */
+ internal suspend fun autoScroll(edge: Float) {
+ while (dragged != null) {
+ val info = listState.layoutInfo
+ val item = info.visibleItemsInfo.firstOrNull { it.key == "row:" + dragged }
+ if (item != null) {
+ val top = item.offset + offset
+ val bottom = top + item.size
+ val speed = when {
+ bottom > info.viewportEndOffset - edge -> 18f
+ top < info.viewportStartOffset + edge -> -18f
+ else -> 0f
+ }
+ if (speed != 0f) {
+ offset += listState.scrollBy(speed)
+ follow()
+ }
+ }
+ withFrameNanos { }
+ }
+ }
+}
+
+@Composable
+fun rememberPlaylistDrag(listState: LazyListState): PlaylistDrag {
+ val haptic = androidx.compose.ui.platform.LocalHapticFeedback.current
+ val drag = remember(listState) { PlaylistDrag(listState, haptic) }
+ val edge = with(androidx.compose.ui.platform.LocalDensity.current) { 72.dp.toPx() }
+ LaunchedEffect(drag, drag.dragged) { if (drag.dragged != null) drag.autoScroll(edge) }
+ return drag
+}
+
+/**
+ * The item of a row that can move: the other rows slide aside, the held one rides over them on
+ * [lifted]. Same modifier chain held or not, so the handle's gesture is never rebuilt mid-drag.
+ */
+@Composable
+fun LazyItemScope.movableRow(drag: PlaylistDrag, song: SongsModel, lifted: Color): Modifier {
+ val held = drag.dragged == song.rowUid
+ val still = com.music.spotui.ui.look.rememberReduceMotion()
+ return Modifier
+ .animateItem(fadeInSpec = null, fadeOutSpec = null,
+ placementSpec = if (held || still) null else spring(stiffness = Spring.StiffnessMediumLow, visibilityThreshold = IntOffset.VisibilityThreshold))
+ .zIndex(if (held) 1f else 0f)
+ .graphicsLayer { translationY = if (held) drag.offset else 0f }
+ .background(if (held) lifted else Color.Transparent)
+}
diff --git a/base/app/src/test/java/com/music/spotui/ui/PlaylistReorderTest.kt b/base/app/src/test/java/com/music/spotui/ui/PlaylistReorderTest.kt
new file mode 100644
index 00000000..04b42cb6
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/ui/PlaylistReorderTest.kt
@@ -0,0 +1,73 @@
+package com.music.spotui.ui
+
+import com.music.spotui.ui.screens.PlaylistReorder
+import com.music.spotui.ui.screens.PlaylistReorder.RowMove
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class PlaylistReorderTest {
+ private val rows = listOf("a", "b", "c", "d")
+
+ @Test fun movedDownIsPutBeforeTheRowNowAfterIt() =
+ assertEquals(RowMove("a", "d"), PlaylistReorder.rowMove(rows, listOf("b", "c", "a", "d"), "a"))
+
+ @Test fun movedUpIsPutBeforeTheRowNowAfterIt() =
+ assertEquals(RowMove("c", "a"), PlaylistReorder.rowMove(rows, listOf("c", "a", "b", "d"), "c"))
+
+ @Test fun movedLastGoesToTheEnd() =
+ assertEquals(RowMove("b", null), PlaylistReorder.rowMove(rows, listOf("a", "c", "d", "b"), "b"))
+
+ @Test fun backWhereItWasIsNoMove() {
+ assertNull(PlaylistReorder.rowMove(rows, rows, "b"))
+ assertNull(PlaylistReorder.rowMove(rows, rows, "d"))
+ }
+
+ @Test fun unknownRowIsNoMove() = assertNull(PlaylistReorder.rowMove(rows, rows, "z"))
+
+ @Test fun appliedAsSpotifyDoes() {
+ assertEquals(listOf("b", "c", "a", "d"), PlaylistReorder.applied(rows, RowMove("a", "d")) { it })
+ assertEquals(listOf("c", "a", "b", "d"), PlaylistReorder.applied(rows, RowMove("c", "a")) { it })
+ assertEquals(listOf("a", "c", "d", "b"), PlaylistReorder.applied(rows, RowMove("b", null)) { it })
+ }
+
+ @Test fun everyDropAppliedGivesTheDroppedOrder() {
+ for (from in rows.indices) for (to in rows.indices) {
+ val after = rows.toMutableList().apply { add(to, removeAt(from)) }
+ val move = PlaylistReorder.rowMove(rows, after, rows[from])
+ if (from == to) assertNull(move)
+ else assertEquals(after, PlaylistReorder.applied(rows, move!!) { it })
+ }
+ }
+
+ @Test fun appliedNeedsBothRows() {
+ assertNull(PlaylistReorder.applied(rows, RowMove("z", "a")) { it })
+ assertNull(PlaylistReorder.applied(rows, RowMove("a", "z")) { it })
+ }
+
+ private fun allowed(
+ type: String = "playlist", editable: Boolean = true, isBlend: Boolean = false, custom: Boolean = true,
+ complete: Boolean = true, find: String = "", uids: List<String> = rows,
+ ) = PlaylistReorder.allowed(type, editable, isBlend, custom, complete, find, uids)
+
+ @Test fun ownPlaylistInItsOrderCanMove() = assertTrue(allowed())
+
+ @Test fun onlyWhereEveryConditionHolds() {
+ assertFalse(allowed(type = "album"))
+ assertFalse(allowed(type = "liked"))
+ assertFalse(allowed(editable = false))
+ assertFalse(allowed(isBlend = true))
+ assertFalse(allowed(custom = false))
+ assertFalse(allowed(complete = false))
+ assertFalse(allowed(find = "halo"))
+ assertTrue(allowed(find = " "))
+ }
+
+ @Test fun everyRowNeedsItsOwnId() {
+ assertFalse(allowed(uids = listOf("a", "", "c")))
+ assertFalse(allowed(uids = listOf("a", "b", "a")))
+ assertFalse(allowed(uids = listOf("a")))
+ }
+}