From 6af817e626da1435d485c349ec562b4c8aeea11c Mon Sep 17 00:00:00 2001 From: Sergey K <17836309+SergeiAK@users.noreply.github.com> Date: Tue, 15 Sep 2026 18:11:00 +0300 Subject: [PATCH] Show only the letters that have items in the alphabet bar The bar listed every letter of the UI language, so a Russian library scrolled through 60 letters to reach the 15 that had titles. The library view now counts the items per letter with the same request the pager uses (`nameStartsWith`, `limit=0`, so the server answers with a COUNT and no rows) and hands the bar only the letters with a non-zero count. `#` covers everything sorting before the first real letter, which is where jumping to it lands. Counts run five at a time and are cached per filter; if a filter cannot be counted (`/Persons`) or a request fails, the bar keeps every letter as before. The alphabet still comes from the UI language: the letter string is a resource resolved in the composition, so it follows the per-user UI language on every Android version. While the bar is data-driven, the current-letter highlight looks the letter up in the bar instead of a hardcoded `A`-`Z`, so it works for Cyrillic, Greek and Hebrew locales too; and the per-button focus state in `AlphabetButtons` is keyed on the letters, since they can now change. Favorites, genres, studios and collections keep the full alphabet. Co-Authored-By: Claude Fable 5.1 --- .../ui/components/CollectionFolderGrid.kt | 2 + .../ui/components/CollectionFolderList.kt | 14 +-- .../ui/components/CollectionFolderView.kt | 99 ++++++++++++++++++- .../wholphin/ui/detail/CardGrid.kt | 42 +++++--- .../wholphin/ui/detail/FavoritesViewModel.kt | 3 + .../ui/components/FilterPresentLettersTest.kt | 21 ++++ 6 files changed, 155 insertions(+), 26 deletions(-) create mode 100644 app/src/test/java/com/github/damontecres/wholphin/ui/components/FilterPresentLettersTest.kt diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderGrid.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderGrid.kt index 1d70553ee6..7664a89230 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderGrid.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderGrid.kt @@ -67,6 +67,7 @@ fun CollectionFolderGrid( initialPosition: Int, gridFocusRequester: FocusRequester, modifier: Modifier = Modifier, + jumpLetters: String? = null, positionCallback: ((columns: Int, position: Int) -> Unit)? = null, ) { Box(modifier = modifier) { @@ -97,6 +98,7 @@ fun CollectionFolderGrid( showJumpButtons = false, // TODO add preference showLetterButtons = sortAndDirection.sort == ItemSortBy.SORT_NAME, modifier = Modifier.fillMaxSize(), + jumpLetters = jumpLetters, initialPosition = initialPosition, positionCallback = positionCallback, cardContent = { (item, index, onClick, onLongClick, widthPx, mod) -> diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderList.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderList.kt index a048ed940e..a4d0073063 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderList.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderList.kt @@ -89,6 +89,7 @@ fun CollectionFolderList( initialPosition: Int, gridFocusRequester: FocusRequester, modifier: Modifier = Modifier, + jumpLetters: String? = null, positionCallback: ((columns: Int, position: Int) -> Unit)? = null, ) { val context = LocalContext.current @@ -172,21 +173,14 @@ fun CollectionFolderList( .weight(1f) .focusRequester(gridFocusRequester), ) - val letters = stringResource(R.string.jump_letters) + val letters = jumpLetters ?: stringResource(R.string.jump_letters) // Letters val currentLetter = - remember(focusedItem) { + remember(focusedItem, letters) { focusedItem ?.sortName ?.firstOrNull() - ?.uppercaseChar() - ?.let { - when (it) { - in '0'..'9' -> '#' - in 'A'..'Z' -> it - else -> null - } - } + ?.let { first -> letters.firstOrNull { it.equals(first, ignoreCase = true) } } ?: letters[0] } if (showLetterButtons && items.isNotEmpty()) { diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderView.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderView.kt index 52918e5779..53afb83b30 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderView.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/components/CollectionFolderView.kt @@ -56,6 +56,7 @@ import com.github.damontecres.wholphin.services.deleteItem import com.github.damontecres.wholphin.ui.SlimItemFields import com.github.damontecres.wholphin.ui.data.SortAndDirection import com.github.damontecres.wholphin.ui.detail.music.addToQueue +import com.github.damontecres.wholphin.ui.detail.rememberJumpLetters import com.github.damontecres.wholphin.ui.equalsNotNull import com.github.damontecres.wholphin.ui.launchDefault import com.github.damontecres.wholphin.ui.launchIO @@ -80,6 +81,9 @@ import dagger.assisted.AssistedInject import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch @@ -87,6 +91,8 @@ import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext import org.jellyfin.sdk.api.client.ApiClient import org.jellyfin.sdk.api.client.extensions.userLibraryApi @@ -102,6 +108,7 @@ import org.jellyfin.sdk.model.serializer.toUUID import org.jellyfin.sdk.model.serializer.toUUIDOrNull import timber.log.Timber import java.util.UUID +import java.util.concurrent.ConcurrentHashMap @HiltViewModel(assistedFactory = CollectionFolderViewModel.Factory::class) class CollectionFolderViewModel @@ -490,9 +497,69 @@ class CollectionFolderViewModel * The count must come from the same endpoint that [createPager] pages through, otherwise * the index refers to a different result set and lands past the end of the list. */ - override suspend fun positionOfLetter(letter: Char): Int? = + override suspend fun positionOfLetter(letter: Char): Int? = countItems(state.value.filter, nameLessThan = letter.toString()) + + /** + * One `limit=0` request per letter, so the server answers each with a COUNT and no rows. + * The first letter is the `#` bucket: everything sorting before the first real letter, + * which is also where jumping to it lands. + * + * Presence is checked with `nameStartsWith` rather than derived from `nameLessThan` + * offsets, so it does not depend on the order of [letters] matching the server's + * collation (`Ё` sorts after `Я` in binary order, for example). + * + * Results are cached per filter: reopening the library or changing the sort does not + * count again. + */ + override suspend fun presentLetters(letters: String): String? { + if (letters.length < 2) return null + val filter = state.value.filter + val key = filter to letters + presentLettersCache[key]?.let { return it } + return withContext(WholphinDispatchers.IO) { + try { + // Doubles as the probe for filters that cannot be counted at all + val hashCount = + countItems(filter, nameLessThan = letters[1].toString()) + ?: return@withContext null + val letterCounts = + coroutineScope { + val semaphore = Semaphore(LETTER_COUNT_CONCURRENCY) + letters + .drop(1) + .map { letter -> + async { + semaphore.withPermit { + countItems(filter, nameStartsWith = letter.toString()) + } + } + }.awaitAll() + } + if (letterCounts.any { it == null }) return@withContext null + letters + .filterPresent(listOf(hashCount) + letterCounts.filterNotNull()) + .also { presentLettersCache[key] = it } + } catch (ex: CancellationException) { + throw ex + } catch (ex: Exception) { + Timber.w(ex, "Error counting items per letter") + null + } + } + } + + private val presentLettersCache = ConcurrentHashMap, String>() + + /** + * Counts the items matching [filter], optionally narrowed to a name range, or null when + * the filter cannot be counted + */ + private suspend fun countItems( + filter: GetItemsFilter, + nameLessThan: String? = null, + nameStartsWith: String? = null, + ): Int? = withContext(WholphinDispatchers.IO) { - val filter = state.value.filter when (filter.override) { GetItemsFilterOverride.ARTIST -> { GetArtistsHandler.countMatching( @@ -501,7 +568,8 @@ class CollectionFolderViewModel createGetArtistsRequest(filter).copy( enableImageTypes = null, fields = null, - nameLessThan = letter.toString(), + nameLessThan = nameLessThan, + nameStartsWith = nameStartsWith, limit = 0, enableTotalRecordCount = true, enableUserData = false, @@ -526,7 +594,8 @@ class CollectionFolderViewModel ).copy( enableImageTypes = null, fields = null, - nameLessThan = letter.toString(), + nameLessThan = nameLessThan, + nameStartsWith = nameStartsWith, limit = 0, enableTotalRecordCount = true, enableUserData = false, @@ -786,6 +855,12 @@ interface CollectionFolderViewActions { suspend fun positionOfLetter(letter: Char): Int? + /** + * Narrows [letters] to the ones that have items under the current filter, or null to keep + * every letter + */ + suspend fun presentLetters(letters: String): String? + fun saveViewOptions(viewOptions: ViewOptions) /** @@ -910,6 +985,11 @@ fun CollectionFolderViewContent( var showHeader by rememberSaveable { mutableStateOf(true) } val gridFocusRequester = remember { FocusRequester() } val pager = remember(state.items) { state.items.successValue } + val jumpLetters = + rememberJumpLetters( + enabled = state.sortAndDirection.sort == ItemSortBy.SORT_NAME, + key = state.filter, + ) { viewActions.presentLetters(it) } val focusedItem = pager?.getOrNull(position) if (state.viewOptions.showBackdrop) { @@ -993,6 +1073,7 @@ fun CollectionFolderViewContent( positionCallback?.invoke(columns, pos) }, letterPosition = { viewActions.positionOfLetter(it) ?: -1 }, + jumpLetters = jumpLetters, viewOptions = state.viewOptions, onClickPlay = gridActions.onClickPlayRemoteButton!!, focusedItem = focusedItem, @@ -1014,6 +1095,7 @@ fun CollectionFolderViewContent( positionCallback?.invoke(columns, pos) }, letterPosition = { viewActions.positionOfLetter(it) ?: -1 }, + jumpLetters = jumpLetters, viewOptions = state.viewOptions, onClickPlay = gridActions.onClickPlayRemoteButton!!, focusedItem = focusedItem, @@ -1055,3 +1137,12 @@ fun CollectionFolderViewContent( ) } } + +/** + * Keeps the letters whose bucket in [counts] has items. Falls back to every letter when none + * has, so the bar never collapses to nothing. + */ +internal fun String.filterPresent(counts: List): String = filterIndexed { index, _ -> counts[index] > 0 }.ifEmpty { this } + +/** How many per-letter counts run at once; OkHttp allows 5 requests per host by default */ +private const val LETTER_COUNT_CONCURRENCY = 5 diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/CardGrid.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/CardGrid.kt index 00713ddb9d..33d92d7a1b 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/CardGrid.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/CardGrid.kt @@ -111,6 +111,8 @@ fun CardGrid( showJumpButtons: Boolean, showLetterButtons: Boolean, modifier: Modifier = Modifier, + // The letters of the alphabet bar; null shows every letter of the UI language + jumpLetters: String? = null, initialPosition: Int = 0, positionCallback: ((columns: Int, position: Int) -> Unit)? = null, cardContent: @Composable (GridItemDetails) -> Unit, @@ -426,22 +428,15 @@ fun CardGrid( } } } - val letters = stringResource(R.string.jump_letters) + val letters = jumpLetters ?: stringResource(R.string.jump_letters) // Letters val currentLetter = - remember(focusedIndex) { + remember(focusedIndex, letters) { pager .getOrNull(focusedIndex) ?.sortName ?.firstOrNull() - ?.uppercaseChar() - ?.let { - when (it) { - in '0'..'9' -> '#' - in 'A'..'Z' -> it - else -> null - } - } + ?.let { first -> letters.firstOrNull { it.equals(first, ignoreCase = true) } } ?: letters[0] } if (showLetterButtons && pager.isNotEmpty()) { @@ -529,8 +524,8 @@ fun AlphabetButtons( } } // Focus & interaction states for each letter button - val focusRequesters = remember { List(letters.length) { FocusRequester() } } - val interactionSources = remember { List(letters.length) { MutableInteractionSource() } } + val focusRequesters = remember(letters) { List(letters.length) { FocusRequester() } } + val interactionSources = remember(letters) { List(letters.length) { MutableInteractionSource() } } // Track if the entire alphabet picker component has focus var alphabetPickerFocused by remember { mutableStateOf(false) } @@ -618,3 +613,26 @@ fun AlphabetButtons( } } } + +/** + * The letters for [AlphabetButtons]: every letter of the UI language, narrowed by + * [presentLetters] to the ones that have items. [key] identifies the result set, so the + * narrowing is redone when it changes. Until it completes, and whenever it yields null, the bar + * keeps every letter. + */ +@Composable +fun rememberJumpLetters( + enabled: Boolean, + key: Any?, + presentLetters: suspend (String) -> String?, +): String { + val allLetters = stringResource(R.string.jump_letters) + var letters by remember(allLetters) { mutableStateOf(allLetters) } + val currentPresentLetters by rememberUpdatedState(presentLetters) + LaunchedEffect(allLetters, enabled, key) { + if (enabled) { + letters = currentPresentLetters.invoke(allLetters) ?: allLetters + } + } + return letters +} diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/FavoritesViewModel.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/FavoritesViewModel.kt index adbd9a44bd..2de9576157 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/FavoritesViewModel.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/FavoritesViewModel.kt @@ -692,6 +692,9 @@ class FavoritesViewModel } } + // Favorites keep the full alphabet: the per-letter counts are only wired for library folders + override suspend fun presentLetters(letters: String): String? = null + override fun saveViewOptions(viewOptions: ViewOptions) { saveViewOptions(type, viewOptions) } diff --git a/app/src/test/java/com/github/damontecres/wholphin/ui/components/FilterPresentLettersTest.kt b/app/src/test/java/com/github/damontecres/wholphin/ui/components/FilterPresentLettersTest.kt new file mode 100644 index 0000000000..91de3f525c --- /dev/null +++ b/app/src/test/java/com/github/damontecres/wholphin/ui/components/FilterPresentLettersTest.kt @@ -0,0 +1,21 @@ +package com.github.damontecres.wholphin.ui.components + +import org.junit.Assert.assertEquals +import org.junit.Test + +class FilterPresentLettersTest { + @Test + fun keepsOnlyLettersWithItems() { + assertEquals("#BD", "#ABCD".filterPresent(listOf(1, 0, 2, 0, 3))) + } + + @Test + fun dropsHashWhenNothingSortsBeforeFirstLetter() { + assertEquals("A", "#AB".filterPresent(listOf(0, 5, 0))) + } + + @Test + fun keepsEveryLetterWhenNoneHasItems() { + assertEquals("#AB", "#AB".filterPresent(listOf(0, 0, 0))) + } +}