Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
Expand Down Expand Up @@ -92,7 +93,10 @@ fun LibraryAlbumsTab(
onAlbumLongPress: (Album) -> Unit = {},
onAlbumSelectionToggle: (Album) -> Unit = {},
getSelectionIndex: (Long) -> Int? = { null },
storageFilter: StorageFilter = StorageFilter.ALL
storageFilter: StorageFilter = StorageFilter.ALL,
// Null keeps the previous behaviour (scroll resets on return); LibraryScreen
// passes LibraryViewModel.libraryScrollPositions to preserve it (#2814).
libraryScrollPositions: com.theveloper.pixelplay.presentation.viewmodel.LibraryScrollPositionStore? = null
) {
val hasCurrentSong by remember(playerViewModel) {
playerViewModel.stablePlayerState
Expand All @@ -104,6 +108,58 @@ fun LibraryAlbumsTab(
val listState = rememberLazyListState()
val dummyListState = rememberLazyListState()
val dummyGridState = rememberLazyGridState()

// #2814: save both view modes on dispose, and restore the active one once
// when the tab next enters composition (e.g. back from an album page).
// Paging loads incrementally, so wait until the saved index is loaded or
// pagination has ended instead of clamping to the first partial page.
// A later sort change is not undone: the sort handler scrolls to item 0
// and this flag is already true by then, so the restore does not re-run.
DisposableEffect(Unit) {
onDispose {
libraryScrollPositions?.save(
"albums-list",
listState.firstVisibleItemIndex,
listState.firstVisibleItemScrollOffset,
)
libraryScrollPositions?.save(
"albums-grid",
gridState.firstVisibleItemIndex,
gridState.firstVisibleItemScrollOffset,
)
}
}
var albumsScrollRestored by remember { mutableStateOf(false) }
LaunchedEffect(
albums.itemCount,
albums.loadState.append.endOfPaginationReached,
isListView,
) {
if (albumsScrollRestored) return@LaunchedEffect
val store = libraryScrollPositions ?: run {
albumsScrollRestored = true
return@LaunchedEffect
}
val key = if (isListView) "albums-list" else "albums-grid"
val saved = store.saved(key) ?: run {
albumsScrollRestored = true
return@LaunchedEffect
}
val endReached = albums.loadState.append.endOfPaginationReached
if (albums.itemCount <= saved.firstVisibleItemIndex && !endReached) {
return@LaunchedEffect
}
val target = store.restore(key, albums.itemCount) ?: run {
albumsScrollRestored = true
return@LaunchedEffect
}
if (isListView) {
listState.scrollToItem(target.firstVisibleItemIndex, target.firstVisibleItemScrollOffset)
} else {
gridState.scrollToItem(target.firstVisibleItemIndex, target.firstVisibleItemScrollOffset)
}
albumsScrollRestored = true
}
val context = LocalContext.current
val imageLoader = context.imageLoader

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1563,7 +1563,8 @@ fun LibraryScreen(
onAlbumLongPress = onAlbumLongPress,
onAlbumSelectionToggle = onAlbumSelectionToggle,
getSelectionIndex = getAlbumSelectionIndex,
storageFilter = playerUiState.currentStorageFilter
storageFilter = playerUiState.currentStorageFilter,
libraryScrollPositions = libraryViewModel.libraryScrollPositions
)
}

Expand Down Expand Up @@ -1679,7 +1680,8 @@ fun LibraryScreen(
onRequestCrossFolderLocate = { folderPath ->
pendingFoldersLocatePath = folderPath
playerViewModel.navigateToFolder(folderPath)
}
},
libraryScrollPositions = libraryViewModel.libraryScrollPositions
)
}

Expand Down Expand Up @@ -2852,7 +2854,10 @@ fun LibraryFoldersTab(
onRegisterLocateCurrentSongAction: ((() -> Unit)?) -> Unit = {},
pendingLocatePath: String? = null,
onClearPendingLocate: () -> Unit = {},
onRequestCrossFolderLocate: (String) -> Unit = {}
onRequestCrossFolderLocate: (String) -> Unit = {},
// Null keeps the previous behaviour; LibraryScreen passes
// LibraryViewModel.libraryScrollPositions to preserve it (#2814).
libraryScrollPositions: com.theveloper.pixelplay.presentation.viewmodel.LibraryScrollPositionStore? = null
) {
// List state moved inside AnimatedContent to prevent state sharing issues during transitions

Expand All @@ -2876,8 +2881,20 @@ fun LibraryFoldersTab(
slideIn.togetherWith(slideOut)
}
) { (playlistMode, targetPath) ->
// Each navigation destination gets its own independant ListState
// Each navigation destination gets its own independant ListState.
// #2814: that is exactly why returning to a folder reset to the top,
// so save this destination's position on dispose, keyed by its path,
// and restore it below once its (fully in-memory) items are known.
val listState = rememberLazyListState()
DisposableEffect(playlistMode, targetPath) {
onDispose {
libraryScrollPositions?.save(
"folders:$playlistMode:$targetPath",
listState.firstVisibleItemIndex,
listState.firstVisibleItemScrollOffset,
)
}
}
val coroutineScope = rememberCoroutineScope()
val visibilityCallback by rememberUpdatedState(onLocateCurrentSongVisibilityChanged)
val registerActionCallback by rememberUpdatedState(onRegisterLocateCurrentSongAction)
Expand All @@ -2902,6 +2919,28 @@ fun LibraryFoldersTab(
val songsToShow = remember(activeFolder, currentSortOption) {
sortSongsForFolderView(activeFolder?.songs ?: emptyList(), currentSortOption)
}.toImmutableList()

// #2814 restore: runs once per folder destination. A later sort change
// is not undone, because the sort handler scrolls to item 0 and this
// flag is already true by then, so the restore does not re-run.
var foldersScrollRestored by remember(playlistMode, targetPath) { mutableStateOf(false) }
LaunchedEffect(playlistMode, targetPath, itemsToShow.size, songsToShow.size) {
if (foldersScrollRestored) return@LaunchedEffect
val store = libraryScrollPositions ?: run {
foldersScrollRestored = true
return@LaunchedEffect
}
val target = store.restore(
"folders:$playlistMode:$targetPath",
itemsToShow.size + songsToShow.size,
) ?: run {
foldersScrollRestored = true
return@LaunchedEffect
}
listState.scrollToItem(target.firstVisibleItemIndex, target.firstVisibleItemScrollOffset)
foldersScrollRestored = true
}

val currentSong by remember(playerViewModel) {
playerViewModel.stablePlayerState
.map { it.currentSong }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.theveloper.pixelplay.presentation.viewmodel

/**
* Pure, UI-framework-free store for library scroll positions.
*
* Why this exists (PixelPlayer #2814): the Albums and Folders tabs create their
* lazy list/grid states with plain `remember...State()`, so the state object
* dies with the composition. That happens in two places:
* - Albums: leaving the Library destination for an AlbumDetail destination
* disposes LibraryScreen, and returning creates a fresh state at item 0.
* - Folders: drilling into a folder swaps the AnimatedContent destination,
* disposing the previous destination's list state, so going back to the
* parent folder also starts at item 0.
*
* The store lives in [LibraryViewModel], which outlives both of those
* transitions (it is only cleared when the Library destination itself is
* popped), so a tab can save its position on dispose and restore it once
* when it next enters composition. It deliberately does not restore on
* every recomposition: sort changes already scroll to item 0 explicitly,
* and a restore flag in the UI ensures a sort (or a view-mode toggle) after
* the restore is not undone by re-running the restore.
*/
data class LibraryScrollPosition(
val firstVisibleItemIndex: Int,
val firstVisibleItemScrollOffset: Int,
)

class LibraryScrollPositionStore {
private val positions = mutableMapOf<String, LibraryScrollPosition>()

fun save(key: String, firstVisibleItemIndex: Int, firstVisibleItemScrollOffset: Int) {
if (firstVisibleItemIndex < 0) return
positions[key] = LibraryScrollPosition(
firstVisibleItemIndex = firstVisibleItemIndex,
firstVisibleItemScrollOffset = firstVisibleItemScrollOffset.coerceAtLeast(0),
)
}

fun saved(key: String): LibraryScrollPosition? = positions[key]

/**
* Returns the saved position clamped to [totalItems], or null when
* nothing was saved or the list is still empty. Clamping the index down
* also drops the pixel offset, since it belonged to a different item.
*/
fun restore(key: String, totalItems: Int): LibraryScrollPosition? {
val saved = positions[key] ?: return null
if (totalItems <= 0) return null
val index = saved.firstVisibleItemIndex.coerceIn(0, totalItems - 1)
return if (index == saved.firstVisibleItemIndex) {
saved
} else {
LibraryScrollPosition(firstVisibleItemIndex = index, firstVisibleItemScrollOffset = 0)
}
}

fun clear(key: String) {
positions.remove(key)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ class LibraryViewModel @Inject constructor(
private val libraryStateHolder: LibraryStateHolder
) : ViewModel() {

/**
* Scroll positions for the Albums and Folders tabs (PixelPlayer #2814).
* Held here, rather than in composition, so leaving for an album detail
* page or drilling into a folder does not lose the position: the
* ViewModel outlives both transitions and is only cleared when the
* Library destination itself is popped.
*/
val libraryScrollPositions = LibraryScrollPositionStore()

val songsPagingFlow = libraryStateHolder.songsPagingFlow.cachedIn(viewModelScope)

val albumsPagingFlow = libraryStateHolder.albumsPagingFlow.cachedIn(viewModelScope)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.theveloper.pixelplay.presentation.viewmodel

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test

class LibraryScrollPositionStoreTest {

@Test
fun `restore returns the saved position unchanged when it is in range`() {
val store = LibraryScrollPositionStore()
store.save("albums-grid", 42, 120)

assertEquals(
LibraryScrollPosition(firstVisibleItemIndex = 42, firstVisibleItemScrollOffset = 120),
store.restore("albums-grid", totalItems = 200),
)
}

@Test
fun `restore returns null when nothing was saved or the list is empty`() {
val store = LibraryScrollPositionStore()

assertNull(store.restore("albums-grid", totalItems = 200))
store.save("albums-grid", 5, 0)
assertNull(store.restore("albums-grid", totalItems = 0))
}

@Test
fun `restore clamps to the last item and drops the offset when items were removed`() {
val store = LibraryScrollPositionStore()
store.save("folders:/music", 90, 120)

assertEquals(
LibraryScrollPosition(firstVisibleItemIndex = 49, firstVisibleItemScrollOffset = 0),
store.restore("folders:/music", totalItems = 50),
)
}

@Test
fun `positions are kept independently per key`() {
val store = LibraryScrollPositionStore()
store.save("albums-list", 10, 0)
store.save("albums-grid", 20, 30)
store.save("folders:__folder_root__", 3, 0)

assertEquals(10, store.restore("albums-list", totalItems = 100)?.firstVisibleItemIndex)
assertEquals(20, store.restore("albums-grid", totalItems = 100)?.firstVisibleItemIndex)
assertEquals(3, store.restore("folders:__folder_root__", totalItems = 100)?.firstVisibleItemIndex)
assertNull(store.restore("albums-unknown", totalItems = 100))
}

@Test
fun `save ignores a negative index and clear removes the position`() {
val store = LibraryScrollPositionStore()
store.save("albums-grid", -1, 0)
assertNull(store.restore("albums-grid", totalItems = 100))

store.save("albums-grid", 7, 0)
store.clear("albums-grid")
assertNull(store.restore("albums-grid", totalItems = 100))
}
}