diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt index 5bb8a9a5..79d1c98e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt @@ -5,8 +5,11 @@ import com.fabledsword.minstrel.models.wire.PlaylistsListWire import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import retrofit2.http.Body +import retrofit2.http.DELETE import retrofit2.http.GET +import retrofit2.http.PATCH import retrofit2.http.POST +import retrofit2.http.PUT import retrofit2.http.Path import retrofit2.http.Query @@ -27,11 +30,41 @@ interface PlaylistsApi { suspend fun get(@Path("id") id: String): PlaylistDetailWire /** - * POST /api/playlists/{id}/tracks — append the given track IDs to - * the owner's playlist. Server is idempotent at the (playlist_id, - * track_id) pair level; re-firing the same payload yields no - * duplicates. + * POST /api/playlists — make a playlist under the id the app chose, + * so a create queued offline and sent again finds the same list. */ + @POST("api/playlists") + suspend fun create(@Body body: CreatePlaylistRequest) + + /** PATCH /api/playlists/{id} — rename, or make public or private. Null fields stay as they are. */ + @PATCH("api/playlists/{id}") + suspend fun update(@Path("id") id: String, @Body body: UpdatePlaylistRequest) + + @DELETE("api/playlists/{id}") + suspend fun delete(@Path("id") id: String) + + /** + * DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song + * expected there; if another song has moved into that place the server + * removes nothing and answers 409, so a removal sent twice takes out + * one song, not two. + */ + @DELETE("api/playlists/{id}/tracks/{position}") + suspend fun removeTrack( + @Path("id") id: String, + @Path("position") position: Int, + @Query("track_id") trackId: String?, + ) + + /** + * PUT /api/playlists/{id}/tracks with the songs in their new order. + * Entries not named keep their places, and the same order sent twice + * changes nothing the second time. + */ + @PUT("api/playlists/{id}/tracks") + suspend fun reorder(@Path("id") id: String, @Body body: ReorderTracksRequest) + + /** POST /api/playlists/{id}/tracks — append the given track IDs to the owner's playlist. */ @POST("api/playlists/{id}/tracks") suspend fun appendTracks( @Path("id") playlistId: String, @@ -77,3 +110,22 @@ data class AppendTracksRequest( data class RefreshSystemResponse( @SerialName("playlist_id") val playlistId: String? = null, ) + +@Serializable +data class CreatePlaylistRequest( + val id: String, + val name: String, + @SerialName("is_public") val isPublic: Boolean = false, +) + +/** PATCH body; a null field is left out, so the server leaves it alone. */ +@Serializable +data class UpdatePlaylistRequest( + val name: String? = null, + @SerialName("is_public") val isPublic: Boolean? = null, +) + +@Serializable +data class ReorderTracksRequest( + @SerialName("track_ids") val trackIds: List, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt index 88e78401..9ab89204 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt @@ -14,12 +14,12 @@ interface CachedPlaylistDao { @Query("SELECT * FROM cached_playlists ORDER BY name COLLATE NOCASE ASC") fun observeAll(): Flow> - /** User playlists only (systemVariant IS NULL) — for the add-to-playlist sheet. */ + /** [userId]'s own playlists, not mixes: the lists they can add a song to. */ @Query( "SELECT * FROM cached_playlists " + - "WHERE systemVariant IS NULL ORDER BY name COLLATE NOCASE ASC", + "WHERE systemVariant IS NULL AND userId = :userId ORDER BY name COLLATE NOCASE ASC", ) - fun observeUserPlaylists(): Flow> + fun observeOwnedUserPlaylists(userId: String): Flow> /** System playlists for the home screen. */ @Query( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt index eee08a39..aef499e5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt @@ -51,6 +51,16 @@ object MutationKind { // Per-kind notification channel. One row per (kind, channel) target // state, collapsed on that pair, so the newest choice is the one sent. const val NOTIFICATION_SETTING_SET: String = "notification_setting_set" + + // A listener's own playlists. Each is safe to send twice: a create + // carries the app's own id for the list, a removal names the song it + // expects at that place, and a reorder is the whole new order (a + // target state, so queued reorders of one list collapse to the last). + const val PLAYLIST_CREATE: String = "playlist_create" + const val PLAYLIST_UPDATE: String = "playlist_update" + const val PLAYLIST_DELETE: String = "playlist_delete" + const val PLAYLIST_REMOVE_TRACK: String = "playlist_remove_track" + const val PLAYLIST_REORDER: String = "playlist_reorder" } /** @@ -132,6 +142,45 @@ class MutationQueue @Inject constructor( ), ) + suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = insertUserDriven( + MutationKind.PLAYLIST_CREATE, + json.encodeToString(PlaylistCreatePayload.serializer(), payload), + ) + + suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long = insertUserDriven( + MutationKind.PLAYLIST_UPDATE, + json.encodeToString(PlaylistUpdatePayload.serializer(), payload), + ) + + suspend fun enqueuePlaylistDelete(playlistId: String): Long = insertUserDriven( + MutationKind.PLAYLIST_DELETE, + json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)), + ) + + suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long = insertUserDriven( + MutationKind.PLAYLIST_REMOVE_TRACK, + json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload), + ) + + suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long = insertUserDriven( + MutationKind.PLAYLIST_REORDER, + json.encodeToString(PlaylistReorderPayload.serializer(), payload), + ) + + /** + * Ids of playlists made on this device that the server hasn't been + * sent yet. A list refresh keeps them, so a playlist made offline + * doesn't vanish before its create goes out. + */ + suspend fun pendingPlaylistCreateIds(): Set = dao.getAll() + .asSequence() + .filter { it.kind == MutationKind.PLAYLIST_CREATE } + .mapNotNull { row -> + runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) } + .getOrNull()?.id + } + .toSet() + suspend fun enqueueQuarantineFlag( trackId: String, reason: String, @@ -209,18 +258,52 @@ class MutationQueue @Inject constructor( @Serializable data class QuarantineUnflagPayload(val trackId: String) -/** - * Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to - * append to one playlist. The server is idempotent at the - * (playlist_id, track_id) pair level — re-firing the same payload yields - * no duplicates. - */ +/** Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to append to one playlist. */ @Serializable data class PlaylistAppendPayload( val playlistId: String, val trackIds: List, ) +/** Persisted payload for `MutationKind.PLAYLIST_CREATE`; [id] is the one the app chose. */ +@Serializable +data class PlaylistCreatePayload( + val id: String, + val name: String, + val isPublic: Boolean = false, +) + +/** Persisted payload for `MutationKind.PLAYLIST_UPDATE`; a null field is left as it is. */ +@Serializable +data class PlaylistUpdatePayload( + val playlistId: String, + val name: String? = null, + val isPublic: Boolean? = null, +) + +/** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */ +@Serializable +data class PlaylistDeletePayload(val playlistId: String) + +/** + * Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is + * the song at [position] when the listener removed it; null for an entry + * whose song has left the library. + */ +@Serializable +data class PlaylistRemoveTrackPayload( + val playlistId: String, + val position: Int, + val trackId: String? = null, +) + +/** Persisted payload for `MutationKind.PLAYLIST_REORDER`: the songs in their new order. */ +@Serializable +data class PlaylistReorderPayload( + val playlistId: String, + val trackIds: List, +) + /** * Persisted payload for `MutationKind.QUARANTINE_FLAG`. The replayer * re-fires `POST /api/quarantine` with this body when the original diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt index 3d904359..31bfd54b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt @@ -3,6 +3,7 @@ package com.fabledsword.minstrel.cache.mutations import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest +import com.fabledsword.minstrel.api.endpoints.CreatePlaylistRequest import com.fabledsword.minstrel.api.endpoints.EventsApi import com.fabledsword.minstrel.api.endpoints.FlagRequest import com.fabledsword.minstrel.api.endpoints.LikesApi @@ -14,6 +15,8 @@ import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi import com.fabledsword.minstrel.api.endpoints.PlaylistsApi import com.fabledsword.minstrel.api.endpoints.QuarantineApi +import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest +import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.models.wire.PlayEndedRequest @@ -137,14 +140,23 @@ class MutationReplayer @Inject constructor( // differential retry could replay an older toggle last and invert the // final state — an unlike the user already made would be undone. val superseded = supersededToggleIds(rows, json) + // A playlist's changes go out in the order they were made: once one + // has to wait, the rest for that list wait behind it, so an add + // never reaches the server before the create of its list. + val waiting = HashSet() for (row in rows) { if (row.id in superseded) { dao.delete(row.id) continue } + val playlistId = playlistIdOf(row, json) + if (playlistId != null && playlistId in waiting) continue when (outcomeFor(row)) { Outcome.SENT, Outcome.DROP -> dao.delete(row.id) - Outcome.RETRY -> dao.recordAttempt(row.id, Clock.System.now()) + Outcome.RETRY -> { + dao.recordAttempt(row.id, Clock.System.now()) + playlistId?.let(waiting::add) + } } } } @@ -174,7 +186,13 @@ class MutationReplayer @Inject constructor( private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) { MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload) MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload) - MutationKind.PLAYLIST_APPEND -> dispatchPlaylistAppend(row.payload) + MutationKind.PLAYLIST_APPEND, + MutationKind.PLAYLIST_CREATE, + MutationKind.PLAYLIST_UPDATE, + MutationKind.PLAYLIST_DELETE, + MutationKind.PLAYLIST_REMOVE_TRACK, + MutationKind.PLAYLIST_REORDER, + -> dispatchPlaylist(row) MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload) MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload) MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload) @@ -218,12 +236,40 @@ class MutationReplayer @Inject constructor( return Outcome.SENT } - private suspend fun dispatchPlaylistAppend(payload: String): Outcome { - val decoded = json.decodeFromString(PlaylistAppendPayload.serializer(), payload) - playlistsApi.appendTracks( - playlistId = decoded.playlistId, - body = AppendTracksRequest(trackIds = decoded.trackIds), - ) + /** + * A listener's own playlists, split out to keep [dispatch] simple. A + * 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since, + * and nothing is left to do. + */ + private suspend fun dispatchPlaylist(row: CachedMutationEntity): Outcome { + val payload = row.payload + when (row.kind) { + MutationKind.PLAYLIST_APPEND -> { + val p = json.decodeFromString(PlaylistAppendPayload.serializer(), payload) + playlistsApi.appendTracks(p.playlistId, AppendTracksRequest(trackIds = p.trackIds)) + } + MutationKind.PLAYLIST_CREATE -> { + val p = json.decodeFromString(PlaylistCreatePayload.serializer(), payload) + playlistsApi.create(CreatePlaylistRequest(id = p.id, name = p.name, isPublic = p.isPublic)) + } + MutationKind.PLAYLIST_UPDATE -> { + val p = json.decodeFromString(PlaylistUpdatePayload.serializer(), payload) + playlistsApi.update(p.playlistId, UpdatePlaylistRequest(name = p.name, isPublic = p.isPublic)) + } + MutationKind.PLAYLIST_DELETE -> { + val p = json.decodeFromString(PlaylistDeletePayload.serializer(), payload) + playlistsApi.delete(p.playlistId) + } + MutationKind.PLAYLIST_REMOVE_TRACK -> { + val p = json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), payload) + playlistsApi.removeTrack(p.playlistId, p.position, p.trackId) + } + MutationKind.PLAYLIST_REORDER -> { + val p = json.decodeFromString(PlaylistReorderPayload.serializer(), payload) + playlistsApi.reorder(p.playlistId, ReorderTracksRequest(trackIds = p.trackIds)) + } + else -> return Outcome.DROP + } return Outcome.SENT } @@ -358,6 +404,11 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when ( json.decodeFromString(NotificationSettingPayload.serializer(), row.payload) }.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" } + // A reorder is the list's whole new order, so only the last one counts. + MutationKind.PLAYLIST_REORDER -> runCatching { + json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload) + }.getOrNull()?.let { "${row.kind}:${it.playlistId}" } + // One preference per user, so every normalization row shares one key. MutationKind.NORMALIZATION_SET -> runCatching { json.decodeFromString(NormalizationPrefs.serializer(), row.payload) @@ -365,3 +416,25 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when ( else -> null } + +/** + * The playlist a queued row changes, or null for a row that isn't a + * playlist change (or won't decode, which its dispatcher then DROPs). + */ +internal fun playlistIdOf(row: CachedMutationEntity, json: Json): String? = runCatching { + when (row.kind) { + MutationKind.PLAYLIST_APPEND -> + json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_CREATE -> + json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id + MutationKind.PLAYLIST_UPDATE -> + json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_DELETE -> + json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_REMOVE_TRACK -> + json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_REORDER -> + json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId + else -> null + } +}.getOrNull() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt index 40cc1d52..e74be1c4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt @@ -2,58 +2,38 @@ package com.fabledsword.minstrel.player.ui import androidx.compose.foundation.background import androidx.compose.foundation.clickable -import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.SwipeToDismissBox -import androidx.compose.material3.SwipeToDismissBoxValue import androidx.compose.material3.Text -import androidx.compose.material3.rememberSwipeToDismissBoxState import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.composed import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.ui.semantics.CustomAccessibilityAction -import androidx.compose.ui.semantics.customActions -import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp -import androidx.compose.ui.zIndex import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Music -import com.composables.icons.lucide.Trash2 import com.composables.icons.lucide.Volume2 import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.shared.formatDuration import com.fabledsword.minstrel.shared.widgets.LikeButton +import com.fabledsword.minstrel.shared.widgets.ReorderableRemovableRow import com.fabledsword.minstrel.shared.widgets.ServerImage -import com.fabledsword.minstrel.theme.LocalActionColors /* - * A single queue row, kept apart from QueueScreen.kt: the row carries two - * gestures, a swipe background, and its own accessibility surface, which - * is more behaviour than the screen that lists it. `internal` rather than - * `private` only because QueueList (still in QueueScreen.kt) is the caller. + * A single queue row. Its drag, swipe and screen-reader actions come from + * ReorderableRemovableRow, shared with playlist rows. `internal` rather than + * `private` only because QueueList (in QueueScreen.kt) is the caller. */ @Suppress("LongParameterList") // Compose row wiring — layout + queue callbacks, not logic. @@ -69,225 +49,55 @@ internal fun QueueRow( onRemove: () -> Unit, onMove: (Int, Int) -> Unit, ) { - var dragOffsetY by remember { mutableFloatStateOf(0f) } - var rowHeightPx by remember { mutableIntStateOf(0) } val highlight = if (isCurrent) { MaterialTheme.colorScheme.primary.copy(alpha = HIGHLIGHT_ALPHA) } else { Color.Transparent } - // Swipe left to remove. Only - // end-to-start is enabled: a right-swipe has no meaning here, and leaving it - // live would delete tracks on a mis-aimed gesture in either direction. - val dismissState = rememberSwipeToDismissBoxState( - confirmValueChange = { value -> - if (value == SwipeToDismissBoxValue.EndToStart) { - onRemove() - true - } else { - false - } - }, - ) - SwipeToDismissBox( - state = dismissState, - enableDismissFromStartToEnd = false, - backgroundContent = { RemoveSwipeBackground() }, - // The reorder lift lives out here so a row being dragged vertically - // carries its swipe container with it rather than sliding out of one. - modifier = Modifier - .onSizeChanged { rowHeightPx = it.height } - .zIndex(if (dragOffsetY != 0f) 1f else 0f) - .graphicsLayer { translationY = dragOffsetY }, - ) { - QueueRowContent( - track = track, - index = index, - queueSize = queueSize, - isCurrent = isCurrent, - liked = liked, - highlight = highlight, - rowHeightPx = rowHeightPx, - onClick = onClick, - onToggleLike = onToggleLike, - onRemove = onRemove, - onMove = onMove, - onDragOffset = { dragOffsetY = it }, - ) - } -} - -@Suppress("LongParameterList") // Compose row wiring — layout + queue callbacks, not logic. -@Composable -private fun QueueRowContent( - track: TrackRef, - index: Int, - queueSize: Int, - isCurrent: Boolean, - liked: Boolean, - highlight: Color, - rowHeightPx: Int, - onClick: () -> Unit, - onToggleLike: () -> Unit, - onRemove: () -> Unit, - onMove: (Int, Int) -> Unit, - onDragOffset: (Float) -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - // Opaque: this sits ON TOP of the red remove background, so a - // transparent row would show the fill through it at rest. - .background(MaterialTheme.colorScheme.surface) - .background(highlight) - .clickable(onClick = onClick) - .queueReorderActions( - index = index, - queueSize = queueSize, - onMove = onMove, - onRemove = onRemove, - ) - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - // The album art IS the grab surface: a separate grip icon would - // cost ~36dp of every row's width — icon plus its 12dp gap — on the - // narrowest surface in the app, competing with the title for space. - QueueRowThumbnail( - track = track, - dragModifier = Modifier.queueReorderDrag( - index = index, - queueSize = queueSize, - rowHeightPx = rowHeightPx, - onOffsetChange = onDragOffset, - onMove = onMove, - ), - ) - if (isCurrent) { - Icon( - Lucide.Volume2, - contentDescription = "Now playing", - tint = MaterialTheme.colorScheme.primary, - ) - } - QueueRowText(track = track, isCurrent = isCurrent, modifier = Modifier.weight(1f)) - if (track.durationSec > 0) { - Text( - text = formatDuration(track.durationSec), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - LikeButton(liked = liked, onToggle = onToggleLike) - } -} - -/** - * What the row slides off to reveal: the destructive colour with a trash glyph, - * pinned to the trailing edge because that is the edge the swipe uncovers. - * - * Oxblood (LocalActionColors.destructive), NOT colorScheme.error. The design - * system keeps those apart deliberately — an error is a failure that already - * happened, a destructive action is one about to happen — and using the error - * colour here would dress an intentional gesture as a fault report. - */ -@Composable -private fun RemoveSwipeBackground() { - val actions = LocalActionColors.current - Box( - modifier = Modifier - .fillMaxSize() - .background(actions.destructive) - .padding(horizontal = 24.dp), - contentAlignment = Alignment.CenterEnd, - ) { + ReorderableRemovableRow( + index = index, + count = queueSize, + removeLabel = "Remove from queue", + onRemove = onRemove, + onMove = onMove, + ) { handles -> Row( + modifier = Modifier + .fillMaxWidth() + // Opaque: this sits ON TOP of the red remove background, so a + // transparent row would show the fill through it at rest. + .background(MaterialTheme.colorScheme.surface) + .background(highlight) + .clickable(onClick = onClick) + .then(handles.actions) + .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Icon(Lucide.Trash2, contentDescription = null, tint = actions.onAction) - Text( - text = "Remove", - style = MaterialTheme.typography.labelLarge, - color = actions.onAction, - ) + // The album art IS the grab surface: a separate grip icon would + // cost ~36dp of every row's width — icon plus its 12dp gap — on the + // narrowest surface in the app, competing with the title for space. + QueueRowThumbnail(track = track, dragModifier = handles.drag) + if (isCurrent) { + Icon( + Lucide.Volume2, + contentDescription = "Now playing", + tint = MaterialTheme.colorScheme.primary, + ) + } + QueueRowText(track = track, isCurrent = isCurrent, modifier = Modifier.weight(1f)) + if (track.durationSec > 0) { + Text( + text = formatDuration(track.durationSec), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + LikeButton(liked = liked, onToggle = onToggleLike) } } } -/** - * Screen-reader reordering and removal for a queue row. - * - * Both gestures this row now relies on — long-press-drag to reorder, swipe to - * remove — are touch-only and unavailable under TalkBack, and each replaced a - * control that a screen reader COULD find (the grip's "Reorder track", the X's - * "Remove from queue"). Without these actions the row would have lost both - * capabilities for anyone not using touch. They're the Android counterpart to - * the web row's ArrowUp/ArrowDown keys and its still-present X button. - */ -private fun Modifier.queueReorderActions( - index: Int, - queueSize: Int, - onMove: (Int, Int) -> Unit, - onRemove: () -> Unit, -): Modifier = semantics { - customActions = listOf( - CustomAccessibilityAction("Move up") { - if (index > 0) { onMove(index, index - 1); true } else false - }, - CustomAccessibilityAction("Move down") { - if (index < queueSize - 1) { onMove(index, index + 1); true } else false - }, - CustomAccessibilityAction("Remove from queue") { onRemove(); true }, - ) -} - -/** - * Reorder-drag behaviour for a queue row, applied to whatever element is the - * grab surface — the album art. - * - * Uses **detectDragGesturesAfterLongPress**, not detectDragGestures, and that - * is the load-bearing detail. A 48dp thumbnail is a large chunk of every row, - * and with a plain drag detector any vertical pan starting on artwork would be - * swallowed as a row-reorder instead of scrolling the queue — the list would - * feel broken precisely where it's easiest to touch. - * Long-press-then-drag separates the two: pan scrolls, long-press reorders, - * Long-press-then-drag separates the two: pan scrolls, long-press reorders, - * tap still plays (the detector doesn't consume a plain tap, so it falls - * through to the row's clickable). - */ -private fun Modifier.queueReorderDrag( - index: Int, - queueSize: Int, - rowHeightPx: Int, - onOffsetChange: (Float) -> Unit, - onMove: (Int, Int) -> Unit, -): Modifier = composed { - // Mirrors the web queue: the row follows the finger during a drag, then on - // release we translate the accumulated offset into a row delta and reorder. - var offset by remember { mutableFloatStateOf(0f) } - pointerInput(index, queueSize, rowHeightPx) { - detectDragGesturesAfterLongPress( - onDrag = { change, dragAmount -> - change.consume() - offset += dragAmount.y - onOffsetChange(offset) - }, - onDragEnd = { - val target = queueDragTarget(index, offset, rowHeightPx, queueSize) - if (target != index) onMove(index, target) - offset = 0f - onOffsetChange(0f) - }, - onDragCancel = { - offset = 0f - onOffsetChange(0f) - }, - ) - } -} - @Composable private fun QueueRowThumbnail(track: TrackRef, dragModifier: Modifier = Modifier) { Box( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt new file mode 100644 index 00000000..294cfb49 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt @@ -0,0 +1,46 @@ +package com.fabledsword.minstrel.playlists.data + +/* + * How a playlist looks straight after the listener changes it, before the + * server's copy comes back. Pure, so the detail screen shows a change at + * once and the transforms are testable without a device. Positions are + * renumbered 0..n-1, as the server numbers them. + */ + +/** The playlist without its entry at [index]. */ +fun PlaylistDetailRef.withoutEntry(index: Int): PlaylistDetailRef { + if (index !in tracks.indices) return this + val kept = tracks.filterIndexed { i, _ -> i != index } + return copy( + playlist = playlist.copy(trackCount = kept.size), + tracks = kept.mapIndexed { i, row -> row.copy(position = i) }, + ) +} + +/** The playlist with its entry at [from] moved to [to]. */ +fun PlaylistDetailRef.withEntryMoved(from: Int, to: Int): PlaylistDetailRef { + if (from !in tracks.indices || to !in tracks.indices || from == to) return this + val moved = tracks.toMutableList().apply { add(to, removeAt(from)) } + return copy(tracks = moved.mapIndexed { i, row -> row.copy(position = i) }) +} + +/** + * The songs in list order, which is what a reorder sends. An entry whose + * song has left the library has no id; the server keeps it where it is. + */ +fun PlaylistDetailRef.trackOrder(): List = tracks.mapNotNull { it.trackId } + +/** + * A key per entry that stays with the entry when others move or go: the + * song's id, with a count after a song the list holds more than once. + * Keying rows by position would hand a removed row's swipe state to the + * row that slides into its place. + */ +fun PlaylistDetailRef.entryKeys(): List { + val seen = HashMap() + return tracks.map { row -> + val base = row.trackId ?: "gone" + val n = seen.merge(base, 1, Int::plus) ?: 1 + "$base#$n" + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt index c7a259c0..c0a75d2f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt @@ -1,7 +1,10 @@ package com.fabledsword.minstrel.playlists.data import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest +import com.fabledsword.minstrel.api.endpoints.CreatePlaylistRequest import com.fabledsword.minstrel.api.endpoints.PlaylistsApi +import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest +import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest import com.fabledsword.minstrel.auth.AuthController import retrofit2.HttpException import java.net.HttpURLConnection @@ -11,6 +14,10 @@ import com.fabledsword.minstrel.cache.db.dao.PlaylistCachedCount import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.PlaylistCreatePayload +import com.fabledsword.minstrel.cache.mutations.PlaylistRemoveTrackPayload +import com.fabledsword.minstrel.cache.mutations.PlaylistReorderPayload +import com.fabledsword.minstrel.cache.mutations.PlaylistUpdatePayload import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.models.PlaylistTrackRef import com.fabledsword.minstrel.models.TrackRef @@ -18,12 +25,16 @@ import com.fabledsword.minstrel.models.wire.PlaylistDetailWire import com.fabledsword.minstrel.models.wire.PlaylistTrackWire import com.fabledsword.minstrel.models.wire.PlaylistWire import com.fabledsword.minstrel.shared.resolveServerUrl +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import retrofit2.Retrofit import retrofit2.create import java.io.IOException +import java.util.UUID import javax.inject.Inject import javax.inject.Singleton @@ -39,6 +50,7 @@ import javax.inject.Singleton * persists offline at the ID level) AND keep the freshest detail * response in memory via the returned `PlaylistDetailRef`. */ +@Suppress("TooManyFunctions") // one method per playlist read or write @Singleton class PlaylistsRepository @Inject constructor( private val playlistDao: CachedPlaylistDao, @@ -62,9 +74,19 @@ class PlaylistsRepository @Inject constructor( playlistDao.observeCachedCounts(), ) { rows, counts -> mergePlaylistsWithCache(rows, counts) } - /** User-owned playlists only (systemVariant IS NULL). */ - fun observeUserPlaylists(): Flow> = - playlistDao.observeUserPlaylists().map { rows -> rows.map { it.toDomain() } } + /** + * The signed-in listener's own playlists, not mixes and not other + * people's public lists: the ones a song can be added to. + */ + @OptIn(ExperimentalCoroutinesApi::class) + fun observeOwnPlaylists(): Flow> = + authController.currentUser.flatMapLatest { user -> + if (user == null) { + flowOf(emptyList()) + } else { + playlistDao.observeOwnedUserPlaylists(user.id).map { rows -> rows.map { it.toDomain() } } + } + } /** Server-generated system playlists (for_you / discover / etc.). */ fun observeSystemPlaylists(): Flow> = @@ -87,9 +109,10 @@ class PlaylistsRepository @Inject constructor( // UUIDs every rebuild, so upsert alone leaves stale rows // whose detail fetch 404s ("That playlist no longer // exists"). + // A list made offline isn't on the server yet; keep it. playlistDao.replaceList( userId = userId, - freshOwnedIds = wire.owned.map { it.id }, + freshOwnedIds = wire.owned.map { it.id } + mutationQueue.pendingPlaylistCreateIds(), all = all, ) } else { @@ -134,19 +157,6 @@ class PlaylistsRepository @Inject constructor( ) } - /** - * Append a single track to a user-owned playlist. Follows the - * project's offline-first write contract: optimistic Room insert - * first (so the playlist detail screen shows the new row instantly), - * then fire `POST /api/playlists/{id}/tracks`. On transport failure - * the call is enqueued via MutationQueue for the next drain pass. - * - * The optimistic row's position is best-effort — server reasserts - * canonical position on the next playlist fetch. The (playlistId, - * trackId) composite PK guarantees no duplicate rows; if the track - * is already in the playlist, the IGNORE on conflict leaves the - * existing position unchanged. - */ /** * Rebuilds the caller's system playlist of [variant]. The server * rotates the playlist's UUID on rebuild — the returned id (null @@ -174,31 +184,115 @@ class PlaylistsRepository @Inject constructor( ) } - suspend fun appendTrack(playlistId: String, trackId: String): AppendOutcome { + // ── Writes to the listener's own playlists ─────────────────────── + // + // Each follows the offline-first write contract: change Room first so + // every screen shows it at once, send it, and on a transport failure + // queue it for MutationReplayer. Membership positions in Room are + // best-effort; the next detail fetch puts the server's back. + + /** + * Append a single track to a user-owned playlist. The (playlistId, + * trackId) key means a song already in the list keeps its place in + * Room. + */ + suspend fun appendTrack(playlistId: String, trackId: String): WriteOutcome { val nextPos = (playlistTrackDao.maxPosition(playlistId) ?: -1) + 1 playlistTrackDao.insertOrIgnore( - CachedPlaylistTrackEntity( - playlistId = playlistId, - trackId = trackId, - position = nextPos, - ), + CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = nextPos), ) - return try { - api.appendTracks( - playlistId = playlistId, - body = AppendTracksRequest(trackIds = listOf(trackId)), + return sendOrQueue( + send = { api.appendTracks(playlistId, AppendTracksRequest(trackIds = listOf(trackId))) }, + queue = { mutationQueue.enqueuePlaylistAppend(playlistId, listOf(trackId)) }, + ) + } + + /** + * Makes a private playlist called [name] and returns its id. The id is + * made here, so the list can be opened, filled and shown before the + * server has heard of it. + */ + suspend fun createPlaylist(name: String): Pair { + val id = UUID.randomUUID().toString() + val userId = authController.currentUser.value?.id.orEmpty() + playlistDao.upsertAll(listOf(CachedPlaylistEntity(id = id, userId = userId, name = name))) + val outcome = sendOrQueue( + send = { api.create(CreatePlaylistRequest(id = id, name = name)) }, + queue = { mutationQueue.enqueuePlaylistCreate(PlaylistCreatePayload(id = id, name = name)) }, + ) + return id to outcome + } + + /** Renames a playlist or makes it public or private; a null argument is left as it is. */ + suspend fun updatePlaylist(id: String, name: String? = null, isPublic: Boolean? = null): WriteOutcome { + playlistDao.getById(id)?.let { row -> + playlistDao.upsertAll( + listOf(row.copy(name = name ?: row.name, isPublic = isPublic ?: row.isPublic)), ) - AppendOutcome.Synced + } + return sendOrQueue( + send = { api.update(id, UpdatePlaylistRequest(name = name, isPublic = isPublic)) }, + queue = { mutationQueue.enqueuePlaylistUpdate(PlaylistUpdatePayload(id, name, isPublic)) }, + ) + } + + suspend fun deletePlaylist(id: String): WriteOutcome { + playlistTrackDao.deleteByPlaylist(id) + playlistDao.deleteByIds(listOf(id)) + return sendOrQueue( + send = { api.delete(id) }, + queue = { mutationQueue.enqueuePlaylistDelete(id) }, + ) + } + + /** + * Removes the entry at [position], which holds [trackId] (null for a + * song that has left the library). The server removes it only if that + * song is still there. + */ + suspend fun removeTrack(playlistId: String, position: Int, trackId: String?): WriteOutcome { + if (trackId != null) playlistTrackDao.deleteTracksFromPlaylist(playlistId, listOf(trackId)) + return sendOrQueue( + send = { api.removeTrack(playlistId, position, trackId) }, + queue = { + mutationQueue.enqueuePlaylistRemoveTrack(PlaylistRemoveTrackPayload(playlistId, position, trackId)) + }, + ) + } + + /** Puts the playlist's songs in the order [trackIds] gives. */ + suspend fun reorderTracks(playlistId: String, trackIds: List): WriteOutcome { + playlistTrackDao.replacePlaylistTracks( + playlistId = playlistId, + rows = trackIds.distinct().mapIndexed { i, trackId -> + CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = i) + }, + ) + return sendOrQueue( + send = { api.reorder(playlistId, ReorderTracksRequest(trackIds = trackIds)) }, + queue = { mutationQueue.enqueuePlaylistReorder(PlaylistReorderPayload(playlistId, trackIds)) }, + ) + } + + /** + * Sends a write, or queues it when the server can't be reached. An + * HTTP error is not queued: the server answered, and a replay would get + * the same answer. + */ + private suspend fun sendOrQueue(send: suspend () -> Unit, queue: suspend () -> Unit): WriteOutcome = + try { + send() + WriteOutcome.Synced } catch ( @Suppress("SwallowedException") _: IOException, ) { - mutationQueue.enqueuePlaylistAppend(playlistId, listOf(trackId)) - AppendOutcome.Queued + queue() + WriteOutcome.Queued } - } } -enum class AppendOutcome { Synced, Queued } +/** Whether a write reached the server or waits in the offline queue. */ +enum class WriteOutcome { Synced, Queued } /** * Snapshot of a playlist + its per-track display fields, as returned diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt index 5b7b4425..d1a0e625 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt @@ -17,9 +17,12 @@ 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.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon @@ -37,7 +40,10 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -51,12 +57,14 @@ import androidx.navigation.NavHostController import androidx.navigation.toRoute import coil3.compose.AsyncImage import com.composables.icons.lucide.ArrowLeft +import com.composables.icons.lucide.EllipsisVertical import com.composables.icons.lucide.ListMusic import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Play import com.composables.icons.lucide.RefreshCw import com.composables.icons.lucide.Shuffle import com.fabledsword.minstrel.api.ErrorCopy +import com.fabledsword.minstrel.auth.AuthController import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.events.EventsStream @@ -72,8 +80,17 @@ import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.playlists.data.PlaylistDetailRef import com.fabledsword.minstrel.playlists.data.PlaylistsRepository +import com.fabledsword.minstrel.playlists.data.WriteOutcome +import com.fabledsword.minstrel.playlists.data.entryKeys import com.fabledsword.minstrel.playlists.data.toPlayableTrackRefs +import com.fabledsword.minstrel.playlists.data.trackOrder +import com.fabledsword.minstrel.playlists.data.withEntryMoved +import com.fabledsword.minstrel.playlists.data.withoutEntry import com.fabledsword.minstrel.shared.formatDuration +import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog +import com.fabledsword.minstrel.shared.widgets.NameDialog +import com.fabledsword.minstrel.shared.widgets.ReorderHandles +import com.fabledsword.minstrel.shared.widgets.ReorderableRemovableRow import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.ErrorRetry @@ -92,6 +109,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @@ -118,6 +136,7 @@ class PlaylistDetailViewModel @Inject constructor( private val player: PlayerController, private val eventsStream: EventsStream, private val seedCache: DetailSeedCache, + private val authController: AuthController, networkStatus: NetworkStatusController, savedStateHandle: SavedStateHandle, ) : ViewModel() { @@ -154,6 +173,10 @@ class PlaylistDetailViewModel @Inject constructor( private val staleInternal = MutableStateFlow(false) val stale: StateFlow = staleInternal.asStateFlow() + /** A change the server refused, for the screen's snackbar. */ + private val messagesChannel = Channel(Channel.BUFFERED) + val messages: Flow = messagesChannel.receiveAsFlow() + val likedTrackIds: StateFlow> = likes.observeLikedTrackIds() .stateIn( @@ -215,24 +238,89 @@ class PlaylistDetailViewModel @Inject constructor( } } + /** + * Re-fetches the playlist. A list already on screen stays there while + * it loads, and stays if the fetch fails: a refresh after every change + * (the server's event for it) must not blank the list each time, and + * offline the list the listener just edited is the best one there is. + */ fun refresh(): Job = viewModelScope.launch { + val shown = internal.value is PlaylistDetailUiState.Success try { - val carried = when (val cur = internal.value) { - is PlaylistDetailUiState.Loading -> cur.seed - is PlaylistDetailUiState.Success -> cur.detail.playlist - is PlaylistDetailUiState.Error -> null + if (!shown) { + val carried = (internal.value as? PlaylistDetailUiState.Loading)?.seed + internal.value = PlaylistDetailUiState.Loading( + carried ?: seedCache.peekPlaylist(playlistId), + ) } - internal.value = PlaylistDetailUiState.Loading( - carried ?: seedCache.peekPlaylist(playlistId), - ) val detail = repository.refreshDetail(playlistId) internal.value = PlaylistDetailUiState.Success(detail) } catch ( @Suppress("TooGenericExceptionCaught") e: Throwable, ) { - internal.value = PlaylistDetailUiState.Error( - ErrorCopy.fromThrowable(e), - ) + if (!shown) internal.value = PlaylistDetailUiState.Error(ErrorCopy.fromThrowable(e)) + } + } + + // ─── The owner's edits ────────────────────────────────────────── + // + // Each shows at once, then goes to the repository, which sends it or + // queues it for when the server is back. A change the server refuses + // says so and re-fetches, so the screen shows what is really there. + + /** Only the owner edits a playlist, and nobody edits a mix. */ + fun canEdit(playlist: PlaylistRef): Boolean = + !playlist.isSystem && playlist.userId == authController.currentUser.value?.id + + fun rename(name: String) { + val d = shownDetail() ?: return + show(d.copy(playlist = d.playlist.copy(name = name))) + save { repository.updatePlaylist(playlistId, name = name) } + } + + fun setPublic(isPublic: Boolean) { + val d = shownDetail() ?: return + show(d.copy(playlist = d.playlist.copy(isPublic = isPublic))) + save { repository.updatePlaylist(playlistId, isPublic = isPublic) } + } + + /** Deletes the playlist and leaves the screen. */ + fun delete() { + viewModelScope.launch { + runCatching { repository.deletePlaylist(playlistId) } + .onSuccess { deletedChannel.trySend(Unit) } + .onFailure { messagesChannel.trySend("Couldn't delete: ${ErrorCopy.fromThrowable(it)}") } + } + } + + fun removeAt(index: Int) { + val d = shownDetail() ?: return + val row = d.tracks.getOrNull(index) ?: return + show(d.withoutEntry(index)) + save { repository.removeTrack(playlistId, row.position, row.trackId) } + } + + fun move(from: Int, to: Int) { + val d = shownDetail() ?: return + val moved = d.withEntryMoved(from, to) + if (moved === d) return + show(moved) + save { repository.reorderTracks(playlistId, moved.trackOrder()) } + } + + private fun shownDetail(): PlaylistDetailRef? = + (internal.value as? PlaylistDetailUiState.Success)?.detail + + private fun show(detail: PlaylistDetailRef) { + internal.value = PlaylistDetailUiState.Success(detail) + } + + private fun save(write: suspend () -> WriteOutcome) { + viewModelScope.launch { + runCatching { write() }.onFailure { + messagesChannel.trySend("Couldn't save: ${ErrorCopy.fromThrowable(it)}") + refresh() + } } } @@ -310,7 +398,10 @@ fun PlaylistDetailScreen( ) { val state by viewModel.uiState.collectAsState() LaunchedEffect(Unit) { - viewModel.deleted.collect { navController.popBackStack() } + // Once: deleting here also brings the server's "deleted" event, and + // a second pop would leave the screen behind this one too. + viewModel.deleted.first() + navController.popBackStack() } LaunchedEffect(Unit) { viewModel.regenerated.collect { newId -> @@ -326,6 +417,9 @@ fun PlaylistDetailScreen( // non-intrusive "refreshed → Refresh" snackbar; Refresh re-resolves the // rotated uuid (via the regenerated navigate-replace flow). val snackbarHostState = remember { SnackbarHostState() } + LaunchedEffect(Unit) { + viewModel.messages.collect { snackbarHostState.showSnackbar(it) } + } val stale by viewModel.stale.collectAsState() LaunchedEffect(stale) { if (stale) { @@ -350,6 +444,17 @@ fun PlaylistDetailScreen( Icon(Lucide.ArrowLeft, contentDescription = "Back") } }, + actions = { + val playlist = (state as? PlaylistDetailUiState.Success)?.detail?.playlist + if (playlist != null && viewModel.canEdit(playlist)) { + PlaylistOwnerMenu( + playlist = playlist, + onRename = viewModel::rename, + onSetPublic = viewModel::setPublic, + onDelete = viewModel::delete, + ) + } + }, ) }, ) { inner -> @@ -390,6 +495,9 @@ private fun PlaylistDetailContent( val playerState by playerViewModel.uiState.collectAsState() PlaylistDetailBody( detail = s.detail, + editable = viewModel.canEdit(s.detail.playlist), + onRemove = viewModel::removeAt, + onMove = viewModel::move, likedTrackIds = likedTrackIds, playingTrackId = playerState.currentTrack?.id, onPlayAll = { viewModel.play(s.detail.tracks, startTrackId = null) }, @@ -416,9 +524,13 @@ private fun currentTitle(state: PlaylistDetailUiState): String = when (state) { // ─── Body composables ──────────────────────────────────────────────── +@Suppress("LongParameterList") // Compose body wiring — state + callbacks, not logic. @Composable private fun PlaylistDetailBody( detail: PlaylistDetailRef, + editable: Boolean, + onRemove: (Int) -> Unit, + onMove: (Int, Int) -> Unit, likedTrackIds: Set, playingTrackId: String?, onPlayAll: () -> Unit, @@ -434,16 +546,31 @@ private fun PlaylistDetailBody( ) { item { PlaylistHeader(detail.playlist, onPlayAll, onShuffleAll, onRegenerate) } item { HorizontalDivider() } - items(items = detail.tracks, key = { it.position }) { row -> - TrackRow( - row = row, - liked = row.trackId != null && row.trackId in likedTrackIds, - nowPlaying = row.trackId != null && row.trackId == playingTrackId, - onClick = { row.trackId?.let(onTrackClick) }, - onToggleLike = { row.trackId?.let(onToggleTrackLike) }, - onNavigateToAlbum = onNavigateToAlbum, - onNavigateToArtist = onNavigateToArtist, - ) + val keys = detail.entryKeys() + itemsIndexed(items = detail.tracks, key = { i, _ -> keys[i] }) { index, row -> + val trackRow: @Composable (ReorderHandles?) -> Unit = { handles -> + TrackRow( + row = row, + handles = handles, + liked = row.trackId != null && row.trackId in likedTrackIds, + nowPlaying = row.trackId != null && row.trackId == playingTrackId, + onClick = { row.trackId?.let(onTrackClick) }, + onToggleLike = { row.trackId?.let(onToggleTrackLike) }, + onNavigateToAlbum = onNavigateToAlbum, + onNavigateToArtist = onNavigateToArtist, + ) + } + if (editable) { + ReorderableRemovableRow( + index = index, + count = detail.tracks.size, + removeLabel = "Remove from playlist", + onRemove = { onRemove(index) }, + onMove = onMove, + ) { handles -> trackRow(handles) } + } else { + trackRow(null) + } HorizontalDivider() } if (detail.tracks.isEmpty()) { @@ -565,9 +692,11 @@ private fun PlaylistCover(playlist: PlaylistRef) { } } +@Suppress("LongParameterList") // Compose row wiring — state + callbacks, not logic. @Composable private fun TrackRow( row: PlaylistTrackRef, + handles: ReorderHandles?, liked: Boolean, nowPlaying: Boolean, onClick: () -> Unit, @@ -589,14 +718,21 @@ private fun TrackRow( artist = artistLine, trackId = row.trackId.orEmpty(), onClick = onClick, + // An editable row is opaque: it sits on the swipe's remove colour. + modifier = if (handles == null) { + Modifier + } else { + Modifier.background(MaterialTheme.colorScheme.background).then(handles.actions) + }, nowPlaying = nowPlaying, enabled = enabled, contentAlpha = rowAlpha, leading = { + // The cover is the grab surface for a drag, as in the queue. TrackCoverThumb( coverUrl = row.coverUrl, contentDescription = row.title, - modifier = Modifier.padding(end = 12.dp), + modifier = Modifier.padding(end = 12.dp).then(handles?.drag ?: Modifier), ) }, trailing = { @@ -618,6 +754,51 @@ private fun TrackRow( ) } +/** + * The owner's menu in the top bar: rename, make public or private, and + * delete, which asks first. + */ +@Composable +private fun PlaylistOwnerMenu( + playlist: PlaylistRef, + onRename: (String) -> Unit, + onSetPublic: (Boolean) -> Unit, + onDelete: () -> Unit, +) { + var open by remember { mutableStateOf(false) } + var renaming by rememberSaveable { mutableStateOf(false) } + var deleting by rememberSaveable { mutableStateOf(false) } + IconButton(onClick = { open = true }) { + Icon(Lucide.EllipsisVertical, contentDescription = "Playlist options") + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + DropdownMenuItem(text = { Text("Rename") }, onClick = { open = false; renaming = true }) + DropdownMenuItem( + text = { Text(if (playlist.isPublic) "Make private" else "Make public") }, + onClick = { open = false; onSetPublic(!playlist.isPublic) }, + ) + DropdownMenuItem(text = { Text("Delete") }, onClick = { open = false; deleting = true }) + } + if (renaming) { + NameDialog( + title = "Rename playlist", + confirmLabel = "Rename", + initial = playlist.name, + onConfirm = { name -> renaming = false; onRename(name) }, + onDismiss = { renaming = false }, + ) + } + if (deleting) { + ConfirmDestructiveDialog( + title = "Delete playlist?", + text = "Delete \"${playlist.name}\"? The songs stay in your library.", + confirmLabel = "Delete", + onConfirm = { deleting = false; onDelete() }, + onDismiss = { deleting = false }, + ) + } +} + private const val SKELETON_PLAYLIST_ROWS = 8 @Composable diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt index 9b565c93..c5f57dee 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt @@ -11,6 +11,8 @@ import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost @@ -19,7 +21,10 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel @@ -27,6 +32,8 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController +import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Plus import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.ServerHealth @@ -37,6 +44,7 @@ import com.fabledsword.minstrel.nav.PlaylistDetail import com.fabledsword.minstrel.nav.Playlists import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.playlists.data.PlaylistsRepository +import com.fabledsword.minstrel.playlists.data.WriteOutcome import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.asCacheFirstStateFlow @@ -46,6 +54,7 @@ import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar +import com.fabledsword.minstrel.shared.widgets.NameDialog import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job @@ -81,6 +90,10 @@ class PlaylistsListViewModel @Inject constructor( /** Transient snackbar messages from playlist tile play taps. */ val transientMessages: Flow = poolMessages.receiveAsFlow() + /** The id of a playlist just made here, for the screen to open. */ + private val createdChannel = Channel(Channel.BUFFERED) + val created: Flow = createdChannel.receiveAsFlow() + /** Cache-only: no link OR server unreachable (Unstable stays calm). Greys tiles. */ val offline: StateFlow = networkStatus.state .map { it == ServerHealth.Offline || it == ServerHealth.ServerDown } @@ -116,6 +129,19 @@ class PlaylistsListViewModel @Inject constructor( .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } } + /** + * Makes an empty playlist called [name] and opens it. Made offline, it + * waits in the list instead: its page can't load until the server has + * it. + */ + fun createPlaylist(name: String) { + viewModelScope.launch { + runCatching { repository.createPlaylist(name) } + .onSuccess { (id, outcome) -> if (outcome == WriteOutcome.Synced) createdChannel.trySend(id) } + .onFailure { poolMessages.trySend("Couldn't make the playlist: ${ErrorCopy.fromThrowable(it)}") } + } + } + /** Tile play button: shuffle the playlist's tracks and start at index 0. */ suspend fun playPlaylist(playlist: PlaylistRef) { viewModelScope.launch { @@ -149,6 +175,18 @@ fun PlaylistsListScreen( LaunchedEffect(Unit) { viewModel.transientMessages.collect { snackbar.showSnackbar(it) } } + LaunchedEffect(Unit) { + viewModel.created.collect { id -> navController.navigate(PlaylistDetail(id)) } + } + var naming by rememberSaveable { mutableStateOf(false) } + if (naming) { + NameDialog( + title = "New playlist", + confirmLabel = "Create", + onConfirm = { name -> naming = false; viewModel.createPlaylist(name) }, + onDismiss = { naming = false }, + ) + } Scaffold( contentWindowInsets = ShellContentWindowInsets, modifier = Modifier.fillMaxSize(), @@ -157,6 +195,11 @@ fun PlaylistsListScreen( title = "Playlists", navController = navController, currentRouteName = Playlists::class.qualifiedName, + actions = { + IconButton(onClick = { naming = true }) { + Icon(Lucide.Plus, contentDescription = "New playlist") + } + }, ) }, snackbarHost = { SnackbarHost(snackbar) }, @@ -172,8 +215,8 @@ fun PlaylistsListScreen( UiState.Empty -> EmptyState( title = "No playlists yet", body = "System playlists (For You / Discover / Songs like…) " + - "appear once your library has enough plays. Create your " + - "own playlist from any album or track in the meantime.", + "appear once your library has enough plays. Make your own " + + "with + above, or from any track's Add to playlist.", ) is UiState.Error -> ErrorRetry( title = "Couldn't load playlists", diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt new file mode 100644 index 00000000..9381cb05 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt @@ -0,0 +1,92 @@ +package com.fabledsword.minstrel.shared.widgets + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import com.fabledsword.minstrel.theme.LocalActionColors + +/** + * Asks for a name: a playlist's when it is made or renamed. The confirm + * button stays off while the name is blank, and the keyboard's Done key + * confirms too. [onConfirm] gets the name trimmed. + */ +@Composable +fun NameDialog( + title: String, + confirmLabel: String, + onConfirm: (String) -> Unit, + onDismiss: () -> Unit, + initial: String = "", +) { + var name by rememberSaveable { mutableStateOf(initial) } + val trimmed = name.trim() + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + OutlinedTextField( + value = name, + onValueChange = { name = it }, + label = { Text("Name") }, + singleLine = true, + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.Sentences, + imeAction = ImeAction.Done, + ), + keyboardActions = KeyboardActions(onDone = { if (trimmed.isNotEmpty()) onConfirm(trimmed) }), + modifier = Modifier.fillMaxWidth(), + ) + }, + confirmButton = { + TextButton(onClick = { onConfirm(trimmed) }, enabled = trimmed.isNotEmpty()) { + Text(confirmLabel) + } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +/** + * Asks before an action that can't be undone. The confirm button is the + * destructive action colour (oxblood), not the error colour: an error is a + * failure that already happened, and this is a choice about to be made. + */ +@Composable +fun ConfirmDestructiveDialog( + title: String, + text: String, + confirmLabel: String, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + val actions = LocalActionColors.current + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { Text(text) }, + confirmButton = { + Button( + onClick = onConfirm, + colors = ButtonDefaults.buttonColors( + containerColor = actions.destructive, + contentColor = actions.onAction, + ), + ) { Text(confirmLabel) } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueDragMath.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt similarity index 51% rename from android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueDragMath.kt rename to android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt index 0c1e5c4f..556a6cd9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueDragMath.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt @@ -1,32 +1,33 @@ -package com.fabledsword.minstrel.player.ui +package com.fabledsword.minstrel.shared.widgets import kotlin.math.roundToInt /** * Drag offset to row delta, rounded to the nearest row boundary. The Android * half of web's `offsetToDelta` (web/src/lib/components/queue-row-math.ts): - * the two clients are meant to agree, and QueueDragMathTest mirrors web's + * the two clients are meant to agree, and ReorderDragMathTest mirrors web's * cases so both are held to it. * * Ties round toward positive infinity, as JS `Math.round` does: half a row * down moves one row, half a row up stays put. A row not yet measured * (height 0) moves nothing. */ -internal fun queueDragDelta(offsetPx: Float, rowHeightPx: Int): Int = +internal fun reorderDragDelta(offsetPx: Float, rowHeightPx: Int): Int = if (rowHeightPx > 0) (offsetPx / rowHeightPx).roundToInt() else 0 /** - * The queue index a row dragged from [index] lands on, clamped to the queue. - * A drag past either end stops at the first or last row. + * The index a row dragged from [index] lands on, in a list of [count] rows + * (the queue, or a playlist). A drag past either end stops at the first or + * last row. */ -internal fun queueDragTarget( +internal fun reorderDragTarget( index: Int, offsetPx: Float, rowHeightPx: Int, - queueSize: Int, + count: Int, ): Int { // coerceIn throws on an empty range; a row can't be dragged in an empty - // queue, but the composable's keys can briefly outlive the list. - if (queueSize <= 0) return index - return (index + queueDragDelta(offsetPx, rowHeightPx)).coerceIn(0, queueSize - 1) + // list, but the composable's keys can briefly outlive the list. + if (count <= 0) return index + return (index + reorderDragDelta(offsetPx, rowHeightPx)).coerceIn(0, count - 1) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt new file mode 100644 index 00000000..7f1f1863 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt @@ -0,0 +1,191 @@ +package com.fabledsword.minstrel.shared.widgets + +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SwipeToDismissBox +import androidx.compose.material3.SwipeToDismissBoxValue +import androidx.compose.material3.Text +import androidx.compose.material3.rememberSwipeToDismissBoxState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import androidx.compose.ui.zIndex +import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Trash2 +import com.fabledsword.minstrel.theme.LocalActionColors + +/** + * What a reorderable row's content applies: [drag] goes on the grab surface + * (the album art), [actions] on the row's clickable container, where a + * screen reader finds it. + */ +class ReorderHandles(val drag: Modifier, val actions: Modifier) + +/** + * A list row that can be dragged to a new place and swiped away: the queue's + * rows and the rows of a listener's own playlist. + * + * - **Long-press the grab surface, then drag** to move the row. On release + * the offset becomes a row delta ([reorderDragTarget]) and [onMove] gets + * (from, to). A long press, not a plain drag, so a pan that starts on the + * artwork still scrolls the list, and a tap still falls through to the + * row's click. + * - **Swipe left** to remove. Only end-to-start is live, so a mis-aimed swipe + * the other way removes nothing. + * - **Under TalkBack**, where both gestures are unavailable, the row offers + * "Move up", "Move down" and [removeLabel] as custom actions. + * + * The caller must key its list items by the entry, not by position: the + * swipe state is remembered per key, and a removed row's key taken by its + * neighbour would show the neighbour as swiped away. + */ +@Suppress("LongParameterList") // Compose row wiring — position, labels and callbacks, not logic. +@Composable +fun ReorderableRemovableRow( + index: Int, + count: Int, + removeLabel: String, + onRemove: () -> Unit, + onMove: (Int, Int) -> Unit, + content: @Composable (ReorderHandles) -> Unit, +) { + var dragOffsetY by remember { mutableFloatStateOf(0f) } + var rowHeightPx by remember { mutableIntStateOf(0) } + val dismissState = rememberSwipeToDismissBoxState( + confirmValueChange = { value -> + if (value == SwipeToDismissBoxValue.EndToStart) { + onRemove() + true + } else { + false + } + }, + ) + SwipeToDismissBox( + state = dismissState, + enableDismissFromStartToEnd = false, + backgroundContent = { RemoveSwipeBackground() }, + // The lift lives out here so a row being dragged vertically carries + // its swipe container with it rather than sliding out of one. + modifier = Modifier + .onSizeChanged { rowHeightPx = it.height } + .zIndex(if (dragOffsetY != 0f) 1f else 0f) + .graphicsLayer { translationY = dragOffsetY }, + ) { + content( + ReorderHandles( + drag = Modifier.reorderDrag(index, count, rowHeightPx, { dragOffsetY = it }, onMove), + actions = Modifier.reorderActions(index, count, removeLabel, onMove, onRemove), + ), + ) + } +} + +/** + * What the row slides off to reveal: the destructive colour with a trash glyph, + * pinned to the trailing edge because that is the edge the swipe uncovers. + * + * Oxblood (LocalActionColors.destructive), NOT colorScheme.error. The design + * system keeps those apart deliberately — an error is a failure that already + * happened, a destructive action is one about to happen — and using the error + * colour here would dress an intentional gesture as a fault report. + */ +@Composable +private fun RemoveSwipeBackground() { + val actions = LocalActionColors.current + Box( + modifier = Modifier + .fillMaxSize() + .background(actions.destructive) + .padding(horizontal = 24.dp), + contentAlignment = Alignment.CenterEnd, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon(Lucide.Trash2, contentDescription = null, tint = actions.onAction) + Text( + text = "Remove", + style = MaterialTheme.typography.labelLarge, + color = actions.onAction, + ) + } + } +} + +/** + * Screen-reader moving and removal. Both gestures are touch-only, so without + * these a TalkBack user could neither reorder nor remove. They are the + * Android counterpart to the web row's ArrowUp/ArrowDown keys and X button. + */ +private fun Modifier.reorderActions( + index: Int, + count: Int, + removeLabel: String, + onMove: (Int, Int) -> Unit, + onRemove: () -> Unit, +): Modifier = semantics { + customActions = listOf( + CustomAccessibilityAction("Move up") { + if (index > 0) { onMove(index, index - 1); true } else false + }, + CustomAccessibilityAction("Move down") { + if (index < count - 1) { onMove(index, index + 1); true } else false + }, + CustomAccessibilityAction(removeLabel) { onRemove(); true }, + ) +} + +/** + * The long-press drag. The row follows the finger during the drag, as on + * the web, and on release the accumulated offset becomes the move. + */ +private fun Modifier.reorderDrag( + index: Int, + count: Int, + rowHeightPx: Int, + onOffsetChange: (Float) -> Unit, + onMove: (Int, Int) -> Unit, +): Modifier = composed { + var offset by remember { mutableFloatStateOf(0f) } + pointerInput(index, count, rowHeightPx) { + detectDragGesturesAfterLongPress( + onDrag = { change, dragAmount -> + change.consume() + offset += dragAmount.y + onOffsetChange(offset) + }, + onDragEnd = { + val target = reorderDragTarget(index, offset, rowHeightPx, count) + if (target != index) onMove(index, target) + offset = 0f + onOffsetChange(0f) + }, + onDragCancel = { + offset = 0f + onOffsetChange(0f) + }, + ) + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt index df907560..457e102e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt @@ -18,6 +18,9 @@ import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow @@ -26,24 +29,38 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.composables.icons.lucide.ListMusic import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Plus import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.shared.UiState +import com.fabledsword.minstrel.shared.widgets.NameDialog /** - * ModalBottomSheet that lists the caller's user-owned playlists and - * pops back with the picked id via [onPick]. System playlists are - * filtered out — they're - * not appendable. + * ModalBottomSheet that lists the listener's own playlists and pops back + * with the picked id via [onPick]. Its first row makes a new playlist: + * [onCreate] gets the name typed for it. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddToPlaylistSheet( onPick: (playlistId: String) -> Unit, + onCreate: (name: String) -> Unit, onDismiss: () -> Unit, viewModel: AddToPlaylistViewModel = hiltViewModel(), ) { val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val state by viewModel.uiState.collectAsStateWithLifecycle() + var naming by rememberSaveable { mutableStateOf(false) } + if (naming) { + NameDialog( + title = "New playlist", + confirmLabel = "Create", + onConfirm = { name -> + naming = false + onCreate(name) + }, + onDismiss = { naming = false }, + ) + } ModalBottomSheet( onDismissRequest = onDismiss, sheetState = sheetState, @@ -55,16 +72,14 @@ fun AddToPlaylistSheet( color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp), ) + NewPlaylistRow(onClick = { naming = true }) when (val s = state) { UiState.Loading -> Box( modifier = Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center, ) { CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) } - UiState.Empty -> Text( - text = "You haven't created any playlists yet.", - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp), - ) + // The New playlist row above is the way forward. + UiState.Empty -> Unit is UiState.Error -> Text( text = s.message, color = MaterialTheme.colorScheme.error, @@ -80,6 +95,25 @@ fun AddToPlaylistSheet( } } +@Composable +private fun NewPlaylistRow(onClick: () -> Unit) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 20.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + Icon(Lucide.Plus, contentDescription = null, tint = MaterialTheme.colorScheme.primary) + Text( + text = "New playlist", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.primary, + ) + } +} + @Composable private fun PlaylistPickRow(playlist: PlaylistRef, onClick: () -> Unit) { Row( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt index 3175daed..c0f5f2b2 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt @@ -14,9 +14,8 @@ import kotlinx.coroutines.launch import javax.inject.Inject /** - * Backs [AddToPlaylistSheet] with the caller's user-owned playlists. - * System playlists (For You / Discover / etc.) are filtered out at - * the repository layer — they're not appendable. + * Backs [AddToPlaylistSheet] with the listener's own playlists. Mixes and + * other people's public lists are left out: neither can take a song. */ @HiltViewModel class AddToPlaylistViewModel @Inject constructor( @@ -24,7 +23,7 @@ class AddToPlaylistViewModel @Inject constructor( ) : ViewModel() { val uiState: StateFlow>> = repository - .observeUserPlaylists() + .observeOwnPlaylists() .map { list -> if (list.isEmpty()) UiState.Empty else UiState.Success(list) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt index 7609d195..3b81af88 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt @@ -164,6 +164,11 @@ private fun TrackActionSubSheets( onCloseAddToPlaylist() onDismissParent() }, + onCreate = { name -> + viewModel.addToNewPlaylist(name, track.id) + onCloseAddToPlaylist() + onDismissParent() + }, onDismiss = onCloseAddToPlaylist, ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt index feabb80e..cb5eda3e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt @@ -110,6 +110,20 @@ class TrackActionsViewModel @Inject constructor( } } + /** Makes a playlist called [name] holding just this song. */ + fun addToNewPlaylist(name: String, trackId: String) { + viewModelScope.launch { + runCatching { + val (playlistId, _) = playlists.createPlaylist(name) + playlists.appendTrack(playlistId, trackId) + } + .onSuccess { messages.tryEmit("Added to $name") } + .onFailure { + messages.tryEmit("Couldn't make the playlist: ${ErrorCopy.fromThrowable(it)}") + } + } + } + fun flag(track: TrackRef, reason: String, notes: String) { viewModelScope.launch { runCatching { quarantine.flag(track, reason, notes) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt index 425785ca..2480cf56 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt @@ -167,4 +167,45 @@ class SupersededToggleIdsTest { ) assertEquals(null, notificationSettingChange(NotificationSettingPayload("k", "pager", true))) } + + private fun reorderRow(id: Long, playlistId: String, order: List) = CachedMutationEntity( + id = id, + kind = MutationKind.PLAYLIST_REORDER, + payload = json.encodeToString( + PlaylistReorderPayload.serializer(), + PlaylistReorderPayload(playlistId, order), + ), + ) + + @Test + fun `only a playlist's last queued reorder is sent`() { + val rows = listOf( + reorderRow(1, "p1", listOf("a", "b")), + reorderRow(2, "p2", listOf("x", "y")), + reorderRow(3, "p1", listOf("b", "a")), + ) + assertEquals(setOf(1L), supersededToggleIds(rows, json)) + } + + @Test + fun `every playlist change names its playlist, so one list's changes wait in order`() { + val create = CachedMutationEntity( + id = 1, + kind = MutationKind.PLAYLIST_CREATE, + payload = json.encodeToString( + PlaylistCreatePayload.serializer(), + PlaylistCreatePayload("p1", "Road Songs"), + ), + ) + val append = CachedMutationEntity( + id = 2, + kind = MutationKind.PLAYLIST_APPEND, + payload = json.encodeToString( + PlaylistAppendPayload.serializer(), + PlaylistAppendPayload("p1", listOf("t1")), + ), + ) + val like = likeRow(3, "artist-1", desired = true) + assertEquals(listOf("p1", "p1", null), listOf(create, append, like).map { playlistIdOf(it, json) }) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/ui/QueueDragMathTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/ui/QueueDragMathTest.kt deleted file mode 100644 index deeb9c10..00000000 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/ui/QueueDragMathTest.kt +++ /dev/null @@ -1,78 +0,0 @@ -package com.fabledsword.minstrel.player.ui - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -/** - * The queue drag math. The delta cases mirror web's - * queue-row-math.test.ts one for one, so a change to either client's - * rounding shows up as a disagreement here rather than as a drop that lands - * one row off on one platform only. - */ -class QueueDragMathTest { - - @Test - fun `zero offset moves nothing`() { - assertEquals(0, queueDragDelta(0f, 64)) - } - - @Test - fun `a full row down moves one`() { - assertEquals(1, queueDragDelta(64f, 64)) - } - - @Test - fun `just under half a row rounds down`() { - assertEquals(0, queueDragDelta(31f, 64)) - } - - @Test - fun `half a row or more rounds up`() { - assertEquals(1, queueDragDelta(32f, 64)) - } - - @Test - fun `drag up is symmetric, with ties toward positive infinity as in JS`() { - assertEquals(-1, queueDragDelta(-64f, 64)) - assertEquals(0, queueDragDelta(-32f, 64)) - } - - @Test - fun `several rows`() { - assertEquals(3, queueDragDelta(192f, 64)) - assertEquals(-2, queueDragDelta(-128f, 64)) - } - - @Test - fun `a row not yet measured moves nothing`() { - assertEquals(0, queueDragDelta(100f, 0)) - assertEquals(0, queueDragDelta(100f, -1)) - } - - @Test - fun `the measured row height is what counts`() { - assertEquals(1, queueDragDelta(56f, 56)) - assertEquals(1, queueDragDelta(28f, 56)) - } - - @Test - fun `a drag past either end stops at the first or last row`() { - assertEquals(0, queueDragTarget(index = 1, offsetPx = -640f, rowHeightPx = 64, queueSize = 5)) - assertEquals(4, queueDragTarget(index = 3, offsetPx = 640f, rowHeightPx = 64, queueSize = 5)) - } - - @Test - fun `a sub-half-row drag lands where it started`() { - assertEquals(2, queueDragTarget(index = 2, offsetPx = 20f, rowHeightPx = 64, queueSize = 5)) - } - - @Test - fun `before the row is measured a drag lands where it started`() { - assertEquals(2, queueDragTarget(index = 2, offsetPx = 300f, rowHeightPx = 0, queueSize = 5)) - } - - @Test - fun `an empty queue does not throw`() { - assertEquals(0, queueDragTarget(index = 0, offsetPx = 64f, rowHeightPx = 64, queueSize = 0)) - } -} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt new file mode 100644 index 00000000..6a091be4 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt @@ -0,0 +1,64 @@ +package com.fabledsword.minstrel.playlists.data + +import com.fabledsword.minstrel.models.PlaylistRef +import com.fabledsword.minstrel.models.PlaylistTrackRef +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame + +/** How the playlist screen shows a change before the server's copy comes back. */ +class PlaylistEditsTest { + + private fun row(position: Int, trackId: String?) = PlaylistTrackRef( + position = position, + trackId = trackId, + title = trackId ?: "gone", + albumId = null, + artistId = null, + ) + + private fun detail(vararg ids: String?) = PlaylistDetailRef( + playlist = PlaylistRef(id = "p", userId = "me", name = "Road Songs", trackCount = ids.size), + tracks = ids.mapIndexed { i, id -> row(i, id) }, + ) + + private fun PlaylistDetailRef.ids() = tracks.map { it.trackId } + + private fun PlaylistDetailRef.positions() = tracks.map { it.position } + + @Test + fun `removing an entry closes the gap and counts one fewer`() { + val out = detail("a", "b", "c").withoutEntry(1) + assertEquals(listOf("a", "c"), out.ids()) + assertEquals(listOf(0, 1), out.positions()) + assertEquals(2, out.playlist.trackCount) + } + + @Test + fun `moving an entry down and back up`() { + val down = detail("a", "b", "c").withEntryMoved(0, 2) + assertEquals(listOf("b", "c", "a"), down.ids()) + assertEquals(listOf(0, 1, 2), down.positions()) + assertEquals(listOf("a", "b", "c"), down.withEntryMoved(2, 0).ids()) + } + + @Test + fun `a move nowhere or out of range changes nothing`() { + val d = detail("a", "b") + assertSame(d, d.withEntryMoved(1, 1)) + assertSame(d, d.withEntryMoved(0, 5)) + assertSame(d, d.withoutEntry(-1)) + } + + @Test + fun `the order sent leaves out an entry whose song has left the library`() { + assertEquals(listOf("a", "b"), detail("a", null, "b").trackOrder()) + } + + @Test + fun `entry keys stay with the entry when an earlier one goes`() { + val d = detail("a", "b", "a", null) + assertEquals(listOf("a#1", "b#1", "a#2", "gone#1"), d.entryKeys()) + assertEquals(listOf("a#1", "a#2", "gone#1"), d.withoutEntry(1).entryKeys()) + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt new file mode 100644 index 00000000..4df3a84f --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt @@ -0,0 +1,124 @@ +package com.fabledsword.minstrel.playlists.data + +import com.fabledsword.minstrel.api.endpoints.CreatePlaylistRequest +import com.fabledsword.minstrel.api.endpoints.PlaylistsApi +import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao +import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao +import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity +import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.PlaylistCreatePayload +import com.fabledsword.minstrel.cache.mutations.PlaylistRemoveTrackPayload +import com.fabledsword.minstrel.cache.mutations.PlaylistReorderPayload +import com.fabledsword.minstrel.models.UserRef +import com.fabledsword.minstrel.models.wire.PlaylistsListWire +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.runTest +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.jupiter.api.Test +import retrofit2.HttpException +import retrofit2.Response +import retrofit2.Retrofit +import java.io.IOException +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * A listener's playlist changes are offline-first: the device shows each at + * once, sends it, and queues it when the server can't be reached. + */ +class PlaylistsRepositoryWritesTest { + private val api: PlaylistsApi = mockk(relaxed = true) + private val playlistDao: CachedPlaylistDao = mockk(relaxed = true) + private val trackDao: CachedPlaylistTrackDao = mockk(relaxed = true) + private val queue: MutationQueue = mockk(relaxed = true) + private val auth: AuthController = mockk { + every { currentUser } returns MutableStateFlow(UserRef(id = "me", username = "me")) + } + private val retrofit: Retrofit = mockk { + every { create(PlaylistsApi::class.java) } returns api + } + private val repo = PlaylistsRepository(playlistDao, trackDao, queue, auth, retrofit) + + @Test + fun `a new playlist is shown at once and sent under the id the device made`() = runTest { + val sent = slot() + coEvery { api.create(capture(sent)) } returns Unit + val shown = slot>() + coEvery { playlistDao.upsertAll(capture(shown)) } returns Unit + + val (id, outcome) = repo.createPlaylist("Road Songs") + + assertEquals(WriteOutcome.Synced, outcome) + assertEquals(id, sent.captured.id) + assertEquals(listOf(id), shown.captured.map { it.id }) + assertEquals("me", shown.captured.single().userId) + coVerify(exactly = 0) { queue.enqueuePlaylistCreate(any()) } + } + + @Test + fun `a new playlist made offline is queued under the same id`() = runTest { + coEvery { api.create(any()) } throws IOException("offline") + val queued = slot() + coEvery { queue.enqueuePlaylistCreate(capture(queued)) } returns 1L + + val (id, outcome) = repo.createPlaylist("Road Songs") + + assertEquals(WriteOutcome.Queued, outcome) + assertEquals(PlaylistCreatePayload(id = id, name = "Road Songs"), queued.captured) + } + + @Test + fun `a removal made offline is queued with the song expected at that place`() = runTest { + coEvery { api.removeTrack(any(), any(), any()) } throws IOException("offline") + + repo.removeTrack("p1", position = 2, trackId = "t3") + + coVerify { trackDao.deleteTracksFromPlaylist("p1", listOf("t3")) } + coVerify { queue.enqueuePlaylistRemoveTrack(PlaylistRemoveTrackPayload("p1", 2, "t3")) } + } + + @Test + fun `a reorder sends the songs in their new order`() = runTest { + repo.reorderTracks("p1", listOf("t2", "t1")) + + coVerify { api.reorder("p1", ReorderTracksRequest(trackIds = listOf("t2", "t1"))) } + coVerify(exactly = 0) { queue.enqueuePlaylistReorder(any()) } + } + + @Test + fun `a reorder made offline is queued`() = runTest { + coEvery { api.reorder(any(), any()) } throws IOException("offline") + + repo.reorderTracks("p1", listOf("t2", "t1")) + + coVerify { queue.enqueuePlaylistReorder(PlaylistReorderPayload("p1", listOf("t2", "t1"))) } + } + + @Test + fun `a change the server refuses is not queued`() = runTest { + coEvery { api.delete("p1") } throws HttpException(Response.error(403, "".toResponseBody())) + + val result = runCatching { repo.deletePlaylist("p1") } + + assertTrue(result.exceptionOrNull() is HttpException) + + coVerify(exactly = 0) { queue.enqueuePlaylistDelete(any()) } + } + + @Test + fun `a list refresh keeps a playlist whose create hasn't been sent`() = runTest { + coEvery { api.list(any()) } returns PlaylistsListWire() + coEvery { queue.pendingPlaylistCreateIds() } returns setOf("made-offline") + + repo.refreshList() + + coVerify { playlistDao.replaceList("me", listOf("made-offline"), emptyList()) } + } +} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt new file mode 100644 index 00000000..6ac770bb --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt @@ -0,0 +1,78 @@ +package com.fabledsword.minstrel.shared.widgets + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +/** + * The drag-to-reorder math shared by the queue and playlists. The delta cases mirror web's + * queue-row-math.test.ts one for one, so a change to either client's + * rounding shows up as a disagreement here rather than as a drop that lands + * one row off on one platform only. + */ +class ReorderDragMathTest { + + @Test + fun `zero offset moves nothing`() { + assertEquals(0, reorderDragDelta(0f, 64)) + } + + @Test + fun `a full row down moves one`() { + assertEquals(1, reorderDragDelta(64f, 64)) + } + + @Test + fun `just under half a row rounds down`() { + assertEquals(0, reorderDragDelta(31f, 64)) + } + + @Test + fun `half a row or more rounds up`() { + assertEquals(1, reorderDragDelta(32f, 64)) + } + + @Test + fun `drag up is symmetric, with ties toward positive infinity as in JS`() { + assertEquals(-1, reorderDragDelta(-64f, 64)) + assertEquals(0, reorderDragDelta(-32f, 64)) + } + + @Test + fun `several rows`() { + assertEquals(3, reorderDragDelta(192f, 64)) + assertEquals(-2, reorderDragDelta(-128f, 64)) + } + + @Test + fun `a row not yet measured moves nothing`() { + assertEquals(0, reorderDragDelta(100f, 0)) + assertEquals(0, reorderDragDelta(100f, -1)) + } + + @Test + fun `the measured row height is what counts`() { + assertEquals(1, reorderDragDelta(56f, 56)) + assertEquals(1, reorderDragDelta(28f, 56)) + } + + @Test + fun `a drag past either end stops at the first or last row`() { + assertEquals(0, reorderDragTarget(index = 1, offsetPx = -640f, rowHeightPx = 64, count = 5)) + assertEquals(4, reorderDragTarget(index = 3, offsetPx = 640f, rowHeightPx = 64, count = 5)) + } + + @Test + fun `a sub-half-row drag lands where it started`() { + assertEquals(2, reorderDragTarget(index = 2, offsetPx = 20f, rowHeightPx = 64, count = 5)) + } + + @Test + fun `before the row is measured a drag lands where it started`() { + assertEquals(2, reorderDragTarget(index = 2, offsetPx = 300f, rowHeightPx = 0, count = 5)) + } + + @Test + fun `an empty queue does not throw`() { + assertEquals(0, reorderDragTarget(index = 0, offsetPx = 64f, rowHeightPx = 64, count = 0)) + } +}