From 18794a05bdd0e44f24c1761022807cf137894fa7 Mon Sep 17 00:00:00 2001 From: XDan <109234186+XDanfr@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:26:25 +0000 Subject: [PATCH] Decade and 4K filters, and sort and filters for local grids Library grids gain a Decade picker and, for film and video libraries, a 4K filter. The sort and filter row, pickers and A-Z rail move into a shared component, and local Movies and Shows use it too: every sort except rating, plus Unwatched, Favourites and Decade, remembered per profile. Shows sort by their newest episode and count as unwatched while any episode is. Filters are chips, so focus stays on them when toggled, and a new sort or filter starts the grid from the top. Video info names HDR formats the way people know them (Dolby Vision, HDR10+). --- .../aperture/data/jellyfin/JellyfinCatalog.kt | 34 +- .../me/xdan/aperture/di/SharedModule.kt | 7 +- .../aperture/domain/catalog/LibraryQuery.kt | 51 ++- .../aperture/ui/component/LibraryControls.kt | 310 ++++++++++++++++++ .../screen/jellyfin/JellyfinLibraryScreen.kt | 192 +---------- .../jellyfin/JellyfinLibraryViewModel.kt | 58 ++-- .../ui/screen/library/LibraryViewModel.kt | 60 +++- .../ui/screen/library/LocalLibraryQuery.kt | 101 ++++++ .../ui/screen/library/MoviesScreen.kt | 115 ++++--- .../aperture/ui/screen/library/ShowsScreen.kt | 112 +++++-- .../screen/library/LocalLibraryQueryTest.kt | 61 ++++ 11 files changed, 789 insertions(+), 312 deletions(-) create mode 100644 shared/src/commonMain/kotlin/me/xdan/aperture/ui/component/LibraryControls.kt create mode 100644 shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/LocalLibraryQuery.kt create mode 100644 shared/src/jvmTest/kotlin/me/xdan/aperture/ui/screen/library/LocalLibraryQueryTest.kt diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/data/jellyfin/JellyfinCatalog.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/data/jellyfin/JellyfinCatalog.kt index 3702e92f..95f96b83 100644 --- a/shared/src/commonMain/kotlin/me/xdan/aperture/data/jellyfin/JellyfinCatalog.kt +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/data/jellyfin/JellyfinCatalog.kt @@ -12,7 +12,6 @@ import me.xdan.aperture.data.local.entity.RemoteLibraryEntity import me.xdan.aperture.domain.catalog.CatalogItem import me.xdan.aperture.domain.catalog.JellyfinImages import me.xdan.aperture.domain.catalog.LibraryQuery -import me.xdan.aperture.platform.KeyValueStores import me.xdan.aperture.domain.catalog.MediaInfo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -26,11 +25,8 @@ import org.jellyfin.sdk.model.serializer.toUUIDOrNull /** Reads the active profile's Jellyfin index for the screens. */ class JellyfinCatalog( private val dao: JellyfinDao, - private val accounts: JellyfinAccounts, - stores: KeyValueStores + private val accounts: JellyfinAccounts ) { - private val queries = stores.open(QUERY_STORE) - val activeAccount: Flow = accounts.activeAccount /** Every library the user can see, in the server's order. */ @@ -138,7 +134,7 @@ class JellyfinCatalog( s.width?.let { w -> s.height?.let { h -> MediaInfo.resolutionLabel(w, h) } }, s.codec?.uppercase(), s.profile, - s.videoRangeType.takeIf { it != VideoRangeType.UNKNOWN && it != VideoRangeType.SDR }?.serialName, + rangeLabel(s.videoRangeType), s.bitDepth?.let { "$it-bit" }, s.realFrameRate?.let { "${"%.3f".format(it).trimEnd('0').trimEnd('.')} fps" } ).joinToString(" · ") @@ -170,13 +166,6 @@ class JellyfinCatalog( }.getOrDefault(emptyList()) } - fun savedQuery(profileId: Long, libraryId: String): LibraryQuery = - LibraryQuery.decode(queries.getString("$profileId:$libraryId", null)) - - fun saveQuery(profileId: Long, libraryId: String, query: LibraryQuery) { - queries.edit().putString("$profileId:$libraryId", query.encode()).apply() - } - private fun sql(accountId: Long, libraryId: String, query: LibraryQuery, seed: Int): RoomRawQuery { val where = buildList { add("accountId = ?") @@ -185,6 +174,8 @@ class JellyfinCatalog( if (query.unwatchedOnly) add("played = 0") if (query.favouritesOnly) add("isFavorite = 1") if (query.genre != null) add("instr('|' || COALESCE(genres, '') || '|', ?) > 0") + if (query.decade != null) add("year BETWEEN ? AND ?") + if (query.uhdOnly) add("(width >= 3800 OR height >= 2100)") }.joinToString(" AND ") val direction = if (query.descending) "DESC" else "ASC" val title = "COALESCE(sortName, name) COLLATE NOCASE" @@ -204,12 +195,27 @@ class JellyfinCatalog( statement.bindLong(index++, accountId) statement.bindText(index++, libraryId) query.genre?.let { statement.bindText(index++, "|$it|") } + query.decade?.let { + statement.bindLong(index++, it.toLong()) + statement.bindLong(index++, it + 9L) + } if (query.sort == LibraryQuery.Sort.RANDOM) statement.bindLong(index, (seed.toLong() and 0xFFFF) + 7919) } } companion object { const val ROW_LIMIT = 20 - private const val QUERY_STORE = "library_queries" + } + + /** HDR formats as people know them; SDR and unknown say nothing. */ + private fun rangeLabel(type: VideoRangeType): String? = when (type) { + VideoRangeType.HDR10 -> "HDR10" + VideoRangeType.HDR10_PLUS -> "HDR10+" + VideoRangeType.HLG -> "HLG" + VideoRangeType.DOVI, VideoRangeType.DOVI_WITH_SDR, VideoRangeType.DOVI_WITH_EL, VideoRangeType.DOVI_INVALID -> "Dolby Vision" + VideoRangeType.DOVI_WITH_HDR10 -> "Dolby Vision · HDR10" + VideoRangeType.DOVI_WITH_HDR10_PLUS, VideoRangeType.DOVI_WITH_ELHDR10_PLUS -> "Dolby Vision · HDR10+" + VideoRangeType.DOVI_WITH_HLG -> "Dolby Vision · HLG" + else -> null } } diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/di/SharedModule.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/di/SharedModule.kt index 1ed13cab..c1ace385 100644 --- a/shared/src/commonMain/kotlin/me/xdan/aperture/di/SharedModule.kt +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/di/SharedModule.kt @@ -101,7 +101,7 @@ val sharedModule = module { single { me.xdan.aperture.data.jellyfin.JellyfinAccounts(get(), get(), get(), get()) } single { me.xdan.aperture.data.jellyfin.JellyfinSync(get(), get()) } single { me.xdan.aperture.data.jellyfin.JellyfinLibraryWatcher(get(), get(), get(), get()) } - single { me.xdan.aperture.data.jellyfin.JellyfinCatalog(get(), get(), get()) } + single { me.xdan.aperture.data.jellyfin.JellyfinCatalog(get(), get()) } single { MediaRepositoryImpl(get(), get(), get(), get(), get(), get(), get()) } single { SponsorVerificationManager(get(), get()) } single { OpenSubtitlesSessionManager(get(), get()) } @@ -116,13 +116,14 @@ val sharedModule = module { viewModel { AmbientViewModel(get(), get(), get()) } viewModel { MediaDetailsViewModel(get(), get()) } viewModel { SearchViewModel(get(), get(), get()) } - viewModel { LibraryViewModel(get(), get()) } + viewModel { LibraryViewModel(get(), get(), get(), get()) } viewModel { MediaActionsViewModel(get()) } viewModel { PlayerViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get()) } viewModel { CompanionViewModel(get()) } viewModel { me.xdan.aperture.ui.screen.profiles.ProfilesViewModel(get()) } viewModel { me.xdan.aperture.ui.screen.jellyfin.JellyfinViewModel(get(), get(), get(), get(), get()) } - viewModel { params -> me.xdan.aperture.ui.screen.jellyfin.JellyfinLibraryViewModel(params.get(), get(), get()) } + single { me.xdan.aperture.domain.catalog.LibraryQueryStore(get()) } + viewModel { params -> me.xdan.aperture.ui.screen.jellyfin.JellyfinLibraryViewModel(params.get(), get(), get(), get()) } viewModel { me.xdan.aperture.ui.screen.jellyfin.JellyfinHomeViewModel(get()) } viewModel { params -> me.xdan.aperture.ui.screen.jellyfin.JellyfinDetailsViewModel(params.get(), get()) } } diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/domain/catalog/LibraryQuery.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/domain/catalog/LibraryQuery.kt index 532ae285..18c7bf8e 100644 --- a/shared/src/commonMain/kotlin/me/xdan/aperture/domain/catalog/LibraryQuery.kt +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/domain/catalog/LibraryQuery.kt @@ -6,7 +6,10 @@ data class LibraryQuery( val descending: Boolean = false, val unwatchedOnly: Boolean = false, val favouritesOnly: Boolean = false, - val genre: String? = null + val genre: String? = null, + /** The decade's first year, e.g. 1990 for the 1990s. */ + val decade: Int? = null, + val uhdOnly: Boolean = false ) { enum class Sort(val label: String, val defaultDescending: Boolean) { TITLE("Title", false), @@ -18,11 +21,14 @@ data class LibraryQuery( RANDOM("Random", false) } - val isFiltered: Boolean get() = unwatchedOnly || favouritesOnly || genre != null + val isFiltered: Boolean get() = unwatchedOnly || favouritesOnly || genre != null || decade != null || uhdOnly - fun encode(): String = listOf(sort.name, descending, unwatchedOnly, favouritesOnly, genre.orEmpty()).joinToString("\u001F") + fun encode(): String = listOf( + sort.name, descending, unwatchedOnly, favouritesOnly, genre.orEmpty(), decade?.toString().orEmpty(), uhdOnly + ).joinToString("\u001F") companion object { + /** Reads a saved query; fields added later fall back to their defaults. */ fun decode(value: String?): LibraryQuery { val parts = value?.split('\u001F') ?: return LibraryQuery() return runCatching { @@ -31,9 +37,46 @@ data class LibraryQuery( descending = parts[1].toBoolean(), unwatchedOnly = parts[2].toBoolean(), favouritesOnly = parts[3].toBoolean(), - genre = parts.getOrNull(4)?.takeIf { it.isNotBlank() } + genre = parts.getOrNull(4)?.takeIf { it.isNotBlank() }, + decade = parts.getOrNull(5)?.toIntOrNull(), + uhdOnly = parts.getOrNull(6)?.toBoolean() ?: false ) }.getOrDefault(LibraryQuery()) } + + fun decadeLabel(decade: Int): String = "${decade}s" + } +} + +/** Remembers each library's sort and filters, per profile. Local grids use ids like "local:movies". */ +class LibraryQueryStore(stores: me.xdan.aperture.platform.KeyValueStores) { + private val queries = stores.open("library_queries") + + fun load(profileId: Long, libraryId: String): LibraryQuery = + LibraryQuery.decode(queries.getString("$profileId:$libraryId", null)) + + fun save(profileId: Long, libraryId: String, query: LibraryQuery) { + queries.edit().putString("$profileId:$libraryId", query.encode()).apply() } } + +/** The letter a title files under, ignoring a leading "The"/"A"/"An" like Jellyfin's sort names. "#" covers the rest. */ +fun sortLetter(title: String): Char { + val trimmed = title.trim().replace(Regex("^(the|a|an)\\s+", RegexOption.IGNORE_CASE), "") + val first = trimmed.firstOrNull()?.uppercaseChar() ?: return '#' + return if (first in 'A'..'Z') first else '#' +} + +/** The first position of each letter in a title-sorted list, for the A–Z rail. */ +fun letterIndex(titles: List, descending: Boolean): Map { + val index = LinkedHashMap() + titles.forEachIndexed { position, title -> + val letter = sortLetter(title) + if (letter !in index) index[letter] = position + } + return if (descending) index else index.toSortedMap(compareBy { if (it == '#') ' ' else it }) +} + +/** Title order that files "The Matrix" under M, matching [sortLetter]. */ +fun sortableTitle(title: String): String = + title.trim().replace(Regex("^(the|a|an)\\s+", RegexOption.IGNORE_CASE), "").lowercase() diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/component/LibraryControls.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/component/LibraryControls.kt new file mode 100644 index 00000000..2b054dfc --- /dev/null +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/component/LibraryControls.kt @@ -0,0 +1,310 @@ +package me.xdan.aperture.ui.component + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.Sort +import androidx.compose.material.icons.rounded.ArrowDownward +import androidx.compose.material.icons.rounded.ArrowUpward +import androidx.compose.material.icons.rounded.CalendarMonth +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.FilterList +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.DialogProperties +import androidx.tv.material3.* +import kotlinx.coroutines.launch +import me.xdan.aperture.domain.catalog.LibraryQuery +import me.xdan.aperture.ui.platform.Dialog +import me.xdan.aperture.ui.theme.ApertureTheme + +/** Which sorts and filters a library can offer; local files have no ratings or genres, for example. */ +data class LibraryOptions( + val sorts: List = LibraryQuery.Sort.entries, + val genres: List = emptyList(), + val decades: List = emptyList(), + val offerUhd: Boolean = false +) + +/** + * The row above a library grid: sort, then filters. [firstModifier] goes on the sort button, so + * the screen can give it a focus requester and a way back to the sidebar. + */ +@Composable +fun LibraryControlsRow( + query: LibraryQuery, + options: LibraryOptions, + onSort: (LibraryQuery.Sort) -> Unit, + onUpdate: ((LibraryQuery) -> LibraryQuery) -> Unit, + firstModifier: Modifier = Modifier +) { + var showSort by remember { mutableStateOf(false) } + var showGenres by remember { mutableStateOf(false) } + var showDecades by remember { mutableStateOf(false) } + + Row(horizontalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.small)) { + OutlinedButton(onClick = { showSort = true }, modifier = firstModifier) { + Icon(Icons.AutoMirrored.Rounded.Sort, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text(query.sort.label) + if (query.sort != LibraryQuery.Sort.RANDOM) { + Spacer(Modifier.width(4.dp)) + Icon( + if (query.descending) Icons.Rounded.ArrowDownward else Icons.Rounded.ArrowUpward, + contentDescription = if (query.descending) "Descending" else "Ascending", + modifier = Modifier.size(16.dp) + ) + } + } + FilterToggle("Unwatched", query.unwatchedOnly) { onUpdate { it.copy(unwatchedOnly = !it.unwatchedOnly) } } + FilterToggle("Favourites", query.favouritesOnly) { onUpdate { it.copy(favouritesOnly = !it.favouritesOnly) } } + if (options.offerUhd) { + FilterToggle("4K", query.uhdOnly) { onUpdate { it.copy(uhdOnly = !it.uhdOnly) } } + } + if (options.genres.isNotEmpty() || query.genre != null) { + PickerButton(Icons.Rounded.FilterList, query.genre ?: "Genre", query.genre != null) { showGenres = true } + } + if (options.decades.size > 1 || query.decade != null) { + PickerButton( + Icons.Rounded.CalendarMonth, + query.decade?.let(LibraryQuery::decadeLabel) ?: "Decade", + query.decade != null + ) { showDecades = true } + } + } + + if (showSort) { + SortDialog(query, options.sorts, onSort = onSort, onDismiss = { showSort = false }) + } + if (showGenres) { + PickerDialog( + title = "Genre", + allLabel = "All genres", + options = options.genres.map { it to it }, + selected = query.genre, + onSelect = { genre -> + onUpdate { it.copy(genre = genre) } + showGenres = false + }, + onDismiss = { showGenres = false } + ) + } + if (showDecades) { + PickerDialog( + title = "Decade", + allLabel = "Any decade", + options = options.decades.map { it to LibraryQuery.decadeLabel(it) }, + selected = query.decade, + onSelect = { decade -> + onUpdate { it.copy(decade = decade) } + showDecades = false + }, + onDismiss = { showDecades = false } + ) + } +} + +/** + * Chips keep the same element when toggled, so focus stays put; swapping an outlined button for + * a filled one would drop it into the grid. + */ +@Composable +private fun FilterToggle(label: String, selected: Boolean, onClick: () -> Unit) { + FilterChip( + selected = selected, + onClick = onClick, + leadingIcon = if (selected) { + { Icon(Icons.Rounded.Check, contentDescription = null, modifier = Modifier.size(FilterChipDefaults.IconSize)) } + } else null + ) { Text(label) } +} + +@Composable +private fun PickerButton(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, active: Boolean, onClick: () -> Unit) { + FilterChip( + selected = active, + onClick = onClick, + leadingIcon = { Icon(icon, contentDescription = null, modifier = Modifier.size(FilterChipDefaults.IconSize)) } + ) { Text(label) } +} + +/** The A–Z rail beside a title-sorted grid. Only letters that have titles appear. */ +@Composable +fun LetterRail(letters: Map, onLetter: (Int) -> Unit) { + LazyColumn( + modifier = Modifier.width(44.dp).fillMaxHeight(), + contentPadding = PaddingValues(vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(2.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + items(letters.entries.toList(), key = { it.key }) { (letter, index) -> + Surface( + onClick = { onLetter(index) }, + shape = ClickableSurfaceDefaults.shape(CircleShape), + colors = ClickableSurfaceDefaults.colors( + containerColor = Color.Transparent, + focusedContainerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onSurfaceVariant, + focusedContentColor = MaterialTheme.colorScheme.onPrimary + ), + scale = ClickableSurfaceDefaults.scale(focusedScale = 1.15f), + modifier = Modifier.size(32.dp) + ) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text(letter.toString(), style = MaterialTheme.typography.labelLarge, textAlign = TextAlign.Center) + } + } + } + } +} + +/** Focuses [requester] once the dialog's window has focus. */ +@Composable +private fun FocusFirst(requester: FocusRequester) { + val windowInfo = LocalWindowInfo.current + LaunchedEffect(windowInfo.isWindowFocused) { + if (!windowInfo.isWindowFocused) return@LaunchedEffect + repeat(30) { + withFrameNanos { } + if (runCatching { requester.requestFocus() }.getOrDefault(false)) return@LaunchedEffect + } + } +} + +@Composable +private fun SortDialog( + query: LibraryQuery, + sorts: List, + onSort: (LibraryQuery.Sort) -> Unit, + onDismiss: () -> Unit +) { + val current = remember { FocusRequester() } + Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { + FocusFirst(current) + Surface( + modifier = Modifier.width(460.dp), + shape = ApertureTheme.shapes.dialog, + colors = SurfaceDefaults.colors(containerColor = MaterialTheme.colorScheme.surface) + ) { + Column(Modifier.padding(ApertureTheme.spacing.extraLarge)) { + Text("Sort by", style = MaterialTheme.typography.headlineSmall) + Text("Choose the current order again to reverse it.", color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.height(ApertureTheme.spacing.medium)) + sorts.forEach { sort -> + val selected = sort == query.sort + ListItem( + selected = selected, + onClick = { onSort(sort) }, + headlineContent = { Text(sort.label) }, + trailingContent = if (selected && sort != LibraryQuery.Sort.RANDOM) { + { + Icon( + if (query.descending) Icons.Rounded.ArrowDownward else Icons.Rounded.ArrowUpward, + contentDescription = if (query.descending) "Descending" else "Ascending" + ) + } + } else null, + modifier = if (selected) Modifier.focusRequester(current) else Modifier + ) + } + Spacer(Modifier.height(ApertureTheme.spacing.medium)) + Button(onClick = onDismiss, modifier = Modifier.align(Alignment.End)) { Text("Done") } + } + } + } +} + +@Composable +private fun PickerDialog( + title: String, + allLabel: String, + options: List>, + selected: T?, + onSelect: (T?) -> Unit, + onDismiss: () -> Unit +) { + val first = remember { FocusRequester() } + Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { + FocusFirst(first) + Surface( + modifier = Modifier.width(460.dp).heightIn(max = 600.dp), + shape = ApertureTheme.shapes.dialog, + colors = SurfaceDefaults.colors(containerColor = MaterialTheme.colorScheme.surface) + ) { + Column(Modifier.padding(ApertureTheme.spacing.extraLarge)) { + Text(title, style = MaterialTheme.typography.headlineSmall) + Spacer(Modifier.height(ApertureTheme.spacing.medium)) + LazyColumn(Modifier.weight(1f, fill = false), contentPadding = PaddingValues(4.dp)) { + item(key = "all") { + ListItem( + selected = selected == null, + onClick = { onSelect(null) }, + headlineContent = { Text(allLabel) }, + modifier = Modifier.focusRequester(first) + ) + } + items(options, key = { it.second }) { (value, label) -> + ListItem( + selected = value == selected, + onClick = { onSelect(value) }, + headlineContent = { Text(label) } + ) + } + } + } + } + } +} + +/** + * Moves a grid to a letter: scrolls to the position, then focuses that card once it's composed. + * Cards take their requester from [requesterFor]. + */ +@Stable +class GridJump internal constructor( + private val grid: androidx.compose.foundation.lazy.grid.LazyGridState, + private val scope: kotlinx.coroutines.CoroutineScope +) { + private val requesters = mutableMapOf() + internal var pending by mutableStateOf(null) + + /** The first card keeps the screen's entry requester, so the sidebar's Right still lands on it. */ + fun requesterFor(index: Int, entry: FocusRequester): FocusRequester = + if (index == 0) entry.also { requesters[0] = it } else requesters.getOrPut(index) { FocusRequester() } + + fun jumpTo(index: Int) { + scope.launch { + grid.scrollToItem(index) + pending = index + } + } + + internal fun requester(index: Int) = requesters[index] +} + +@Composable +fun rememberGridJump(grid: androidx.compose.foundation.lazy.grid.LazyGridState): GridJump { + val scope = rememberCoroutineScope() + val jump = remember(grid) { GridJump(grid, scope) } + LaunchedEffect(jump.pending) { + val index = jump.pending ?: return@LaunchedEffect + repeat(20) { + withFrameNanos { } + if (runCatching { jump.requester(index)?.requestFocus() }.getOrNull() == true) { + jump.pending = null + return@LaunchedEffect + } + } + jump.pending = null + } + return jump +} diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/jellyfin/JellyfinLibraryScreen.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/jellyfin/JellyfinLibraryScreen.kt index e250931a..881d5892 100644 --- a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/jellyfin/JellyfinLibraryScreen.kt +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/jellyfin/JellyfinLibraryScreen.kt @@ -29,6 +29,8 @@ import kotlinx.coroutines.launch import me.xdan.aperture.domain.catalog.CatalogItem import me.xdan.aperture.domain.catalog.LibraryQuery import me.xdan.aperture.ui.component.CatalogCard +import me.xdan.aperture.ui.component.LetterRail +import me.xdan.aperture.ui.component.LibraryControlsRow import me.xdan.aperture.ui.component.expressive.ExpressiveLoadingIndicator import me.xdan.aperture.ui.platform.Dialog import me.xdan.aperture.ui.theme.ApertureTheme @@ -45,11 +47,10 @@ fun JellyfinLibraryScreen( val state by viewModel.state.collectAsState() val items = state.items val gridState = rememberLazyGridState() + // A new sort or filter starts from the top; the grid would otherwise stay anchored to a title. + LaunchedEffect(state.query) { gridState.scrollToItem(0) } val scope = rememberCoroutineScope() val cardRequesters = remember { mutableMapOf() } - var showSort by remember { mutableStateOf(false) } - var showGenres by remember { mutableStateOf(false) } - val sortRequester = remember { FocusRequester() } // Where focus goes after a letter jump, once the target card has been composed. var pendingFocusIndex by remember { mutableStateOf(null) } @@ -81,36 +82,13 @@ fun JellyfinLibraryScreen( } } Spacer(Modifier.height(ApertureTheme.spacing.medium)) - Row(horizontalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.small)) { - val q = state.query - OutlinedButton( - onClick = { showSort = true }, - modifier = Modifier - .focusRequester(sortRequester) - .then(if (drawerFocusRequester != null) Modifier.focusProperties { left = drawerFocusRequester } else Modifier) - ) { - Icon(Icons.AutoMirrored.Rounded.Sort, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text(q.sort.label) - if (q.sort != LibraryQuery.Sort.RANDOM) { - Spacer(Modifier.width(4.dp)) - Icon( - if (q.descending) Icons.Rounded.ArrowDownward else Icons.Rounded.ArrowUpward, - contentDescription = if (q.descending) "Descending" else "Ascending", - modifier = Modifier.size(16.dp) - ) - } - } - FilterToggle("Unwatched", q.unwatchedOnly) { viewModel.update { it.copy(unwatchedOnly = !it.unwatchedOnly) } } - FilterToggle("Favourites", q.favouritesOnly) { viewModel.update { it.copy(favouritesOnly = !it.favouritesOnly) } } - if (state.genres.isNotEmpty()) { - OutlinedButton(onClick = { showGenres = true }) { - Icon(Icons.Rounded.FilterList, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text(q.genre ?: "Genre") - } - } - } + LibraryControlsRow( + query = state.query, + options = state.options, + onSort = viewModel::sortBy, + onUpdate = viewModel::update, + firstModifier = if (drawerFocusRequester != null) Modifier.focusProperties { left = drawerFocusRequester } else Modifier + ) Spacer(Modifier.height(ApertureTheme.spacing.medium)) when { @@ -160,152 +138,4 @@ fun JellyfinLibraryScreen( } } - if (showSort) { - SortDialog( - query = state.query, - onSort = viewModel::sortBy, - onDismiss = { showSort = false } - ) - } - if (showGenres) { - GenreDialog( - genres = state.genres, - selected = state.query.genre, - onSelect = { genre -> - viewModel.update { it.copy(genre = genre) } - showGenres = false - }, - onDismiss = { showGenres = false } - ) - } -} - -@Composable -private fun FilterToggle(label: String, selected: Boolean, onClick: () -> Unit) { - if (selected) { - Button(onClick = onClick) { - Icon(Icons.Rounded.Check, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text(label) - } - } else { - OutlinedButton(onClick = onClick) { Text(label) } - } -} - -@Composable -private fun LetterRail(letters: Map, onLetter: (Int) -> Unit) { - LazyColumn( - modifier = Modifier.width(44.dp).fillMaxHeight(), - contentPadding = PaddingValues(vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(2.dp), - horizontalAlignment = Alignment.CenterHorizontally - ) { - items(letters.entries.toList(), key = { it.key }) { (letter, index) -> - Surface( - onClick = { onLetter(index) }, - shape = ClickableSurfaceDefaults.shape(CircleShape), - colors = ClickableSurfaceDefaults.colors( - containerColor = androidx.compose.ui.graphics.Color.Transparent, - focusedContainerColor = MaterialTheme.colorScheme.primary, - contentColor = MaterialTheme.colorScheme.onSurfaceVariant, - focusedContentColor = MaterialTheme.colorScheme.onPrimary - ), - scale = ClickableSurfaceDefaults.scale(focusedScale = 1.15f), - modifier = Modifier.size(32.dp) - ) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Text(letter.toString(), style = MaterialTheme.typography.labelLarge, textAlign = TextAlign.Center) - } - } - } - } -} - -@Composable -private fun FocusFirst(requester: FocusRequester) { - val windowInfo = LocalWindowInfo.current - LaunchedEffect(windowInfo.isWindowFocused) { - if (!windowInfo.isWindowFocused) return@LaunchedEffect - repeat(30) { - withFrameNanos { } - if (runCatching { requester.requestFocus() }.getOrDefault(false)) return@LaunchedEffect - } - } -} - -@Composable -private fun SortDialog(query: LibraryQuery, onSort: (LibraryQuery.Sort) -> Unit, onDismiss: () -> Unit) { - val current = remember { FocusRequester() } - Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { - FocusFirst(current) - Surface( - modifier = Modifier.width(460.dp), - shape = ApertureTheme.shapes.dialog, - colors = SurfaceDefaults.colors(containerColor = MaterialTheme.colorScheme.surface) - ) { - Column(Modifier.padding(ApertureTheme.spacing.extraLarge)) { - Text("Sort by", style = MaterialTheme.typography.headlineSmall) - Text( - "Choose the current order again to reverse it.", - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Spacer(Modifier.height(ApertureTheme.spacing.medium)) - LibraryQuery.Sort.entries.forEach { sort -> - val selected = sort == query.sort - ListItem( - selected = selected, - onClick = { onSort(sort) }, - headlineContent = { Text(sort.label) }, - trailingContent = if (selected && sort != LibraryQuery.Sort.RANDOM) { - { - Icon( - if (query.descending) Icons.Rounded.ArrowDownward else Icons.Rounded.ArrowUpward, - contentDescription = if (query.descending) "Descending" else "Ascending" - ) - } - } else null, - modifier = if (selected) Modifier.focusRequester(current) else Modifier - ) - } - Spacer(Modifier.height(ApertureTheme.spacing.medium)) - Button(onClick = onDismiss, modifier = Modifier.align(Alignment.End)) { Text("Done") } - } - } - } -} - -@Composable -private fun GenreDialog(genres: List, selected: String?, onSelect: (String?) -> Unit, onDismiss: () -> Unit) { - val first = remember { FocusRequester() } - Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { - FocusFirst(first) - Surface( - modifier = Modifier.width(460.dp).heightIn(max = 600.dp), - shape = ApertureTheme.shapes.dialog, - colors = SurfaceDefaults.colors(containerColor = MaterialTheme.colorScheme.surface) - ) { - Column(Modifier.padding(ApertureTheme.spacing.extraLarge)) { - Text("Genre", style = MaterialTheme.typography.headlineSmall) - Spacer(Modifier.height(ApertureTheme.spacing.medium)) - LazyColumn(Modifier.weight(1f, fill = false), contentPadding = PaddingValues(4.dp)) { - item(key = "all") { - ListItem( - selected = selected == null, - onClick = { onSelect(null) }, - headlineContent = { Text("All genres") }, - modifier = Modifier.focusRequester(first) - ) - } - items(genres, key = { it }) { genre -> - ListItem( - selected = genre == selected, - onClick = { onSelect(genre) }, - headlineContent = { Text(genre) } - ) - } - } - } - } - } } diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/jellyfin/JellyfinLibraryViewModel.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/jellyfin/JellyfinLibraryViewModel.kt index 8af126cc..ad6542e3 100644 --- a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/jellyfin/JellyfinLibraryViewModel.kt +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/jellyfin/JellyfinLibraryViewModel.kt @@ -2,6 +2,7 @@ package me.xdan.aperture.ui.screen.jellyfin import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -15,22 +16,27 @@ import kotlinx.coroutines.launch import me.xdan.aperture.data.jellyfin.JellyfinCatalog import me.xdan.aperture.domain.catalog.CatalogItem import me.xdan.aperture.domain.catalog.LibraryQuery +import me.xdan.aperture.domain.catalog.LibraryQueryStore +import me.xdan.aperture.domain.catalog.letterIndex import me.xdan.aperture.domain.repository.ProfileRepository +import me.xdan.aperture.ui.component.LibraryOptions /** One server library as a grid: sorted, filtered and remembered per profile. */ +@OptIn(ExperimentalCoroutinesApi::class) class JellyfinLibraryViewModel( private val libraryId: String, private val catalog: JellyfinCatalog, - private val profiles: ProfileRepository + private val profiles: ProfileRepository, + private val queries: LibraryQueryStore ) : ViewModel() { data class State( val name: String = "", val items: List? = null, val query: LibraryQuery = LibraryQuery(), - /** First index for each letter, when sorted by title. "#" covers digits and symbols. */ + /** First index for each letter, when sorted by title. */ val letters: Map = emptyMap(), - val genres: List = emptyList() + val options: LibraryOptions = LibraryOptions() ) private val query = MutableStateFlow(LibraryQuery()) @@ -41,7 +47,7 @@ class JellyfinLibraryViewModel( init { viewModelScope.launch { profileId = profiles.activeProfileId.first() - query.value = catalog.savedQuery(profileId, libraryId) + query.value = queries.load(profileId, libraryId) } } @@ -50,20 +56,28 @@ class JellyfinLibraryViewModel( if (account == null) flowOf(emptyList()) else catalog.browse(account, libraryId, q, s) } - /** Genres come from the unfiltered library, so picking one doesn't hide the others. */ - private val genres = catalog.activeAccount.flatMapLatest { account -> - if (account == null) flowOf(emptyList()) - else catalog.browse(account, libraryId, LibraryQuery(), 0) - .map { all -> all.flatMap { it.genres }.distinct().sortedBy { it.lowercase() } } + /** Genres and decades come from the whole library, so picking one doesn't hide the others. */ + private val options = combine(catalog.activeAccount, catalog.libraries) { account, libraries -> + account to libraries.firstOrNull { it.id == libraryId }?.collectionType + }.flatMapLatest { (account, type) -> + if (account == null) flowOf(LibraryOptions()) + else catalog.browse(account, libraryId, LibraryQuery(), 0).map { all -> + LibraryOptions( + genres = all.flatMap { it.genres }.distinct().sortedBy { it.lowercase() }, + decades = all.mapNotNull { it.year?.let { year -> year / 10 * 10 } }.distinct().sortedDescending(), + // Shows have no single file to measure. + offerUhd = type != "tvshows" + ) + } } - val state: StateFlow = combine(catalog.libraries, items, query, genres) { libraries, list, q, allGenres -> + val state: StateFlow = combine(catalog.libraries, items, query, options) { libraries, list, q, opts -> State( name = libraries.firstOrNull { it.id == libraryId }?.name.orEmpty(), items = list, query = q, - letters = if (q.sort == LibraryQuery.Sort.TITLE) letterIndex(list, q.descending) else emptyMap(), - genres = allGenres + letters = if (q.sort == LibraryQuery.Sort.TITLE) letterIndex(list.map { it.title }, q.descending) else emptyMap(), + options = opts ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), State()) @@ -71,29 +85,11 @@ class JellyfinLibraryViewModel( val updated = transform(query.value) if (updated.sort == LibraryQuery.Sort.RANDOM) seed.value = (System.nanoTime() % 65_536).toInt() query.value = updated - catalog.saveQuery(profileId, libraryId, updated) + queries.save(profileId, libraryId, updated) } /** Picking the current sort again flips its direction. */ fun sortBy(sort: LibraryQuery.Sort) = update { q -> if (q.sort == sort) q.copy(descending = !q.descending) else q.copy(sort = sort, descending = sort.defaultDescending) } - - private fun letterIndex(items: List, descending: Boolean): Map { - val index = LinkedHashMap() - items.forEachIndexed { position, item -> - val letter = sortLetter(item.title) - if (letter !in index) index[letter] = position - } - return if (descending) index else index.toSortedMap(compareBy { if (it == '#') ' ' else it }) - } - - companion object { - /** The letter a title files under, ignoring a leading "The"/"A"/"An" like Jellyfin's sort names. */ - fun sortLetter(title: String): Char { - val trimmed = title.trim().replace(Regex("^(the|a|an)\\s+", RegexOption.IGNORE_CASE), "") - val first = trimmed.firstOrNull()?.uppercaseChar() ?: return '#' - return if (first in 'A'..'Z') first else '#' - } - } } diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/LibraryViewModel.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/LibraryViewModel.kt index 554bd91b..c90fdc08 100644 --- a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/LibraryViewModel.kt +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/LibraryViewModel.kt @@ -2,15 +2,26 @@ package me.xdan.aperture.ui.screen.library import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import me.xdan.aperture.data.local.entity.MediaEntity +import me.xdan.aperture.domain.catalog.LibraryQuery +import me.xdan.aperture.domain.catalog.LibraryQueryStore import me.xdan.aperture.domain.repository.MediaRepository +import me.xdan.aperture.domain.repository.ProfileRepository import me.xdan.aperture.domain.repository.UserPreferencesRepository -import me.xdan.aperture.data.local.entity.MediaEntity class LibraryViewModel constructor( repository: MediaRepository, - preferences: UserPreferencesRepository + preferences: UserPreferencesRepository, + profiles: ProfileRepository, + private val queries: LibraryQueryStore ) : ViewModel() { private val content = LibraryContent( repository.getMediaByType("MOVIE"), @@ -22,6 +33,51 @@ class LibraryViewModel constructor( val showPresentationMode = preferences.showPresentationMode .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "grouped") + + private val movieQuery = MutableStateFlow(LibraryQuery()) + private val showQuery = MutableStateFlow(LibraryQuery()) + /** Reseeded each time "Random" is picked, so the order only changes when asked to. */ + private val seed = MutableStateFlow((System.currentTimeMillis() % 65_536).toInt()) + private var profileId = 0L + + init { + viewModelScope.launch { + profileId = profiles.activeProfileId.first() + movieQuery.value = queries.load(profileId, MOVIES) + showQuery.value = queries.load(profileId, SHOWS) + } + } + + private val progress = repository.getAllProgress().map { list -> list.associateBy { it.mediaId } } + + val movieGrid: StateFlow> = combine(movies, progress, movieQuery, seed) { all, p, q, s -> + LocalLibraryQuery.movies(all, p, q, s) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), LocalGrid()) + + val showGrid: StateFlow> = combine(showGroups, progress, showQuery, seed) { all, p, q, s -> + LocalLibraryQuery.shows(all, p, q, s) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), LocalGrid()) + + fun updateMovies(transform: (LibraryQuery) -> LibraryQuery) = update(movieQuery, MOVIES, transform) + fun updateShows(transform: (LibraryQuery) -> LibraryQuery) = update(showQuery, SHOWS, transform) + fun sortMovies(sort: LibraryQuery.Sort) = updateMovies { it.toggled(sort) } + fun sortShows(sort: LibraryQuery.Sort) = updateShows { it.toggled(sort) } + + private fun update(state: MutableStateFlow, id: String, transform: (LibraryQuery) -> LibraryQuery) { + val updated = transform(state.value) + if (updated.sort == LibraryQuery.Sort.RANDOM) seed.value = (System.nanoTime() % 65_536).toInt() + state.value = updated + queries.save(profileId, id, updated) + } + + /** Picking the current sort again flips its direction. */ + private fun LibraryQuery.toggled(sort: LibraryQuery.Sort) = + if (this.sort == sort) copy(descending = !descending) else copy(sort = sort, descending = sort.defaultDescending) + + private companion object { + const val MOVIES = "local:movies" + const val SHOWS = "local:shows" + } } data class ShowGroup( diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/LocalLibraryQuery.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/LocalLibraryQuery.kt new file mode 100644 index 00000000..0a3a7350 --- /dev/null +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/LocalLibraryQuery.kt @@ -0,0 +1,101 @@ +package me.xdan.aperture.ui.screen.library + +import me.xdan.aperture.data.local.entity.MediaEntity +import me.xdan.aperture.data.local.entity.PlaybackProgressEntity +import me.xdan.aperture.domain.catalog.LibraryQuery +import me.xdan.aperture.domain.catalog.letterIndex +import me.xdan.aperture.domain.catalog.sortableTitle +import me.xdan.aperture.ui.component.LibraryOptions +import kotlin.random.Random + +/** A local grid after its query: what to show, and what the controls can offer. */ +data class LocalGrid( + val items: List = emptyList(), + /** Before filtering, so an empty filter result isn't mistaken for an empty library. */ + val total: Int = 0, + val query: LibraryQuery = LibraryQuery(), + val letters: Map = emptyMap(), + val options: LibraryOptions = LibraryOptions() +) + +/** + * Sorting and filtering for local files. Local titles have no ratings or genres, so those aren't + * offered; shows sort by their newest episode and count as unwatched while any episode is. + */ +internal object LocalLibraryQuery { + val movieSorts = listOf( + LibraryQuery.Sort.TITLE, LibraryQuery.Sort.DATE_ADDED, LibraryQuery.Sort.RELEASED, + LibraryQuery.Sort.RUNTIME, LibraryQuery.Sort.LAST_PLAYED, LibraryQuery.Sort.RANDOM + ) + val showSorts = movieSorts - LibraryQuery.Sort.RUNTIME + + fun watched(progress: PlaybackProgressEntity?): Boolean = progress != null && + (progress.isCompleted || (progress.duration > 0 && progress.position >= progress.duration * 0.95)) + + fun movies(all: List, progress: Map, query: LibraryQuery, seed: Int): LocalGrid { + val filtered = all.filter { media -> + (!query.unwatchedOnly || !watched(progress[media.id])) && + (!query.favouritesOnly || media.isFavorite) && + (query.decade == null || media.year?.let { it in query.decade..query.decade + 9 } == true) + } + val items = ordered(filtered, query, seed, title = { it.title }) { media -> + when (query.sort) { + LibraryQuery.Sort.DATE_ADDED -> media.dateAdded + LibraryQuery.Sort.RELEASED -> media.year?.toLong() + LibraryQuery.Sort.RUNTIME -> media.duration?.takeIf { it > 0 } + LibraryQuery.Sort.LAST_PLAYED -> progress[media.id]?.lastUpdated + else -> null + } + } + return LocalGrid( + items = items, + total = all.size, + query = query, + letters = letters(items.map { it.title }, query), + options = LibraryOptions(sorts = movieSorts, decades = decades(all.mapNotNull { it.year })) + ) + } + + fun shows(all: List, progress: Map, query: LibraryQuery, seed: Int): LocalGrid { + val filtered = all.filter { group -> + val year = group.episodes.mapNotNull { it.year }.minOrNull() + (!query.unwatchedOnly || group.episodes.any { !watched(progress[it.id]) }) && + (!query.favouritesOnly || group.episodes.any { it.isFavorite }) && + (query.decade == null || year?.let { it in query.decade..query.decade + 9 } == true) + } + val items = ordered(filtered, query, seed, title = { it.title }) { group -> + when (query.sort) { + LibraryQuery.Sort.DATE_ADDED -> group.episodes.maxOf { it.dateAdded } + LibraryQuery.Sort.RELEASED -> group.episodes.mapNotNull { it.year }.minOrNull()?.toLong() + LibraryQuery.Sort.LAST_PLAYED -> group.episodes.mapNotNull { progress[it.id]?.lastUpdated }.maxOrNull() + else -> null + } + } + return LocalGrid( + items = items, + total = all.size, + query = query, + letters = letters(items.map { it.title }, query), + options = LibraryOptions(sorts = showSorts, decades = decades(all.flatMap { g -> g.episodes.mapNotNull { it.year } })) + ) + } + + /** Titles without the sort value (no year, never played) go last either way, then by title. */ + private fun ordered(items: List, query: LibraryQuery, seed: Int, title: (T) -> String, key: (T) -> Long?): List { + val byTitle = compareBy { sortableTitle(title(it)) } + return when (query.sort) { + LibraryQuery.Sort.RANDOM -> items.sortedWith(byTitle).shuffled(Random(seed)) + LibraryQuery.Sort.TITLE, LibraryQuery.Sort.RATING -> items.sortedWith(if (query.descending) byTitle.reversed() else byTitle) + else -> { + val (known, unknown) = items.partition { key(it) != null } + val byKey = compareBy { key(it) } + known.sortedWith((if (query.descending) byKey.reversed() else byKey).then(byTitle)) + unknown.sortedWith(byTitle) + } + } + } + + private fun letters(titles: List, query: LibraryQuery): Map = + if (query.sort == LibraryQuery.Sort.TITLE) letterIndex(titles, query.descending) else emptyMap() + + private fun decades(years: List): List = years.map { it / 10 * 10 }.distinct().sortedDescending() +} diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/MoviesScreen.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/MoviesScreen.kt index 944c8976..482bcce9 100644 --- a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/MoviesScreen.kt +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/MoviesScreen.kt @@ -26,6 +26,10 @@ import androidx.compose.ui.zIndex import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text import me.xdan.aperture.ui.component.MediaCard +import me.xdan.aperture.ui.component.LetterRail +import me.xdan.aperture.ui.component.LibraryControlsRow +import me.xdan.aperture.ui.component.rememberGridJump +import androidx.compose.foundation.lazy.grid.rememberLazyGridState import me.xdan.aperture.ui.theme.ApertureTheme import me.xdan.aperture.data.local.entity.MediaEntity @@ -39,64 +43,93 @@ fun MoviesScreen( onContentFocused: (FocusRequester) -> Unit, onActiveMediaChanged: (Long) -> Unit ) { - val movies by viewModel.movies.collectAsState() - if (movies.isEmpty()) { + val grid by viewModel.movieGrid.collectAsState() + val movies = grid.items + if (grid.total == 0) { EmptyLibrary("No movies found.", drawerFocusRequester, contentEntryFocusRequester, onContentFocused) return } + val gridState = rememberLazyGridState() + // A new sort or filter starts from the top; the grid would otherwise stay anchored to a title. + LaunchedEffect(grid.query) { gridState.scrollToItem(0) } + val jump = rememberGridJump(gridState) + val controlsRequester = remember { FocusRequester() } - Column( - modifier = Modifier - .fillMaxSize() - .padding(horizontal = 32.dp, vertical = 24.dp) - .graphicsLayer { clip = false } - ) { - Text("Movies", style = MaterialTheme.typography.headlineLarge) - Spacer(Modifier.height(ApertureTheme.spacing.large)) - Box(Modifier.weight(1f).graphicsLayer { clip = false }) { - LazyVerticalGrid( - columns = GridCells.Fixed(5), - modifier = Modifier.fillMaxSize().graphicsLayer { clip = false }, - contentPadding = PaddingValues(top = ApertureTheme.spacing.large, bottom = ApertureTheme.spacing.large), - verticalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.large), - horizontalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.large) - ) { - itemsIndexed(movies, key = { _, item -> item.id }) { index, item -> - var isFocused by remember { mutableStateOf(false) } - Box(modifier = Modifier.zIndex(if (isFocused) 1f else 0f)) { - AnimatedMovieCard( - media = item, - isFirst = item.id == movies.first().id, - isLeftmost = index % 5 == 0, - onMediaClick = onMediaClick, - onMediaLongClick = onMediaLongClick, - drawerFocusRequester = drawerFocusRequester, - contentEntryFocusRequester = contentEntryFocusRequester, - onContentFocused = { - isFocused = true - onContentFocused(it) - }, - onActiveMediaChanged = onActiveMediaChanged - ) - } - DisposableEffect(Unit) { - onDispose { isFocused = false } + Row(Modifier.fillMaxSize().graphicsLayer { clip = false }) { + Column( + modifier = Modifier + .weight(1f) + .padding(start = 32.dp, end = 16.dp, top = 24.dp) + .graphicsLayer { clip = false } + ) { + Text("Movies", style = MaterialTheme.typography.headlineLarge) + Spacer(Modifier.height(ApertureTheme.spacing.medium)) + LibraryControlsRow( + query = grid.query, + options = grid.options, + onSort = viewModel::sortMovies, + onUpdate = viewModel::updateMovies, + // With no results, the controls are where the sidebar's Right lands. + firstModifier = Modifier + .then(if (movies.isEmpty()) Modifier.focusRequester(contentEntryFocusRequester) else Modifier.focusRequester(controlsRequester)) + .then(if (drawerFocusRequester != null) Modifier.focusProperties { left = drawerFocusRequester } else Modifier) + ) + Spacer(Modifier.height(ApertureTheme.spacing.small)) + if (movies.isEmpty()) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Nothing matches these filters.", color = MaterialTheme.colorScheme.onSurfaceVariant) + } + return@Column + } + Box(Modifier.weight(1f).graphicsLayer { clip = false }) { + LazyVerticalGrid( + state = gridState, + columns = GridCells.Fixed(5), + modifier = Modifier.fillMaxSize().graphicsLayer { clip = false }, + contentPadding = PaddingValues(top = ApertureTheme.spacing.large, bottom = ApertureTheme.spacing.large), + verticalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.large), + horizontalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.large) + ) { + itemsIndexed(movies, key = { _, item -> item.id }) { index, item -> + var isFocused by remember { mutableStateOf(false) } + Box(modifier = Modifier.zIndex(if (isFocused) 1f else 0f)) { + AnimatedMovieCard( + media = item, + focusRequester = jump.requesterFor(index, contentEntryFocusRequester), + isLeftmost = index % 5 == 0, + onMediaClick = onMediaClick, + onMediaLongClick = onMediaLongClick, + drawerFocusRequester = drawerFocusRequester, + onContentFocused = { + isFocused = true + onContentFocused(it) + }, + onActiveMediaChanged = onActiveMediaChanged + ) + } + DisposableEffect(Unit) { + onDispose { isFocused = false } + } } } } } + if (grid.letters.size > 1 && movies.isNotEmpty()) { + Box(Modifier.padding(top = 24.dp, end = 8.dp)) { + LetterRail(letters = grid.letters, onLetter = jump::jumpTo) + } + } } } @Composable private fun AnimatedMovieCard( media: MediaEntity, - isFirst: Boolean, + focusRequester: FocusRequester, isLeftmost: Boolean, onMediaClick: (Long, FocusRequester) -> Unit, onMediaLongClick: (MediaEntity, FocusRequester, Boolean, Boolean) -> Unit, drawerFocusRequester: FocusRequester?, - contentEntryFocusRequester: FocusRequester, onContentFocused: (FocusRequester) -> Unit, onActiveMediaChanged: (Long) -> Unit ) { @@ -110,7 +143,7 @@ private fun AnimatedMovieCard( media = media, onClick = { onMediaClick(media.id, it) }, modifier = Modifier.fillMaxWidth(), - focusRequester = contentEntryFocusRequester.takeIf { isFirst }, + focusRequester = focusRequester, drawerFocusRequester = drawerFocusRequester.takeIf { isLeftmost }, onFocused = { requester -> onContentFocused(requester) diff --git a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/ShowsScreen.kt b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/ShowsScreen.kt index e2e590fc..7cceb0cc 100644 --- a/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/ShowsScreen.kt +++ b/shared/src/commonMain/kotlin/me/xdan/aperture/ui/screen/library/ShowsScreen.kt @@ -1,5 +1,11 @@ package me.xdan.aperture.ui.screen.library +import androidx.compose.ui.focus.focusProperties + +import androidx.compose.ui.focus.focusRequester + +import androidx.compose.ui.Alignment + import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn @@ -51,8 +57,11 @@ fun ShowsScreen( onActiveMediaChanged = onActiveMediaChanged ) } else { + val grid by viewModel.showGrid.collectAsState() GroupedShowsGrid( - groups = groups, + grid = grid, + onSort = viewModel::sortShows, + onUpdate = viewModel::updateShows, onMediaClick = onMediaClick, onMediaLongClick = onMediaLongClick, drawerFocusRequester = drawerFocusRequester, @@ -65,7 +74,9 @@ fun ShowsScreen( @Composable private fun GroupedShowsGrid( - groups: List, + grid: LocalGrid, + onSort: (me.xdan.aperture.domain.catalog.LibraryQuery.Sort) -> Unit, + onUpdate: ((me.xdan.aperture.domain.catalog.LibraryQuery) -> me.xdan.aperture.domain.catalog.LibraryQuery) -> Unit, onMediaClick: (Long, FocusRequester, Boolean) -> Unit, onMediaLongClick: (MediaEntity, FocusRequester, Boolean, Boolean, Boolean) -> Unit, drawerFocusRequester: FocusRequester?, @@ -73,45 +84,74 @@ private fun GroupedShowsGrid( onContentFocused: (FocusRequester) -> Unit, onActiveMediaChanged: (Long) -> Unit ) { - Column(Modifier.fillMaxSize().padding(horizontal = 32.dp, vertical = 24.dp).graphicsLayer { clip = false }) { - Text("TV Shows", style = MaterialTheme.typography.headlineLarge) - Spacer(Modifier.height(ApertureTheme.spacing.large)) - Box(Modifier.weight(1f).graphicsLayer { clip = false }) { - LazyVerticalGrid( - columns = GridCells.Fixed(5), - modifier = Modifier.fillMaxSize().graphicsLayer { clip = false }, - contentPadding = PaddingValues(top = ApertureTheme.spacing.large, bottom = ApertureTheme.spacing.large), - verticalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.large), - horizontalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.large) - ) { - itemsIndexed(groups, key = { _, group -> group.title }) { index, group -> - val media = group.representative - var isFocused by remember { mutableStateOf(false) } - Box(modifier = Modifier.zIndex(if (isFocused) 1f else 0f)) { - AnimatedLibraryCard(media.id) { - MediaCard( - media = media, - onClick = { onMediaClick(media.id, it, false) }, - modifier = Modifier.fillMaxWidth(), - focusRequester = contentEntryFocusRequester.takeIf { index == 0 }, - drawerFocusRequester = drawerFocusRequester.takeIf { index % 5 == 0 }, - onFocused = { requester -> - isFocused = true - onContentFocused(requester) - onActiveMediaChanged(media.id) - }, - onLongClick = { requester, opensToRight -> - onMediaLongClick(media, requester, false, opensToRight, false) - } - ) + val groups = grid.items + val gridState = androidx.compose.foundation.lazy.grid.rememberLazyGridState() + // A new sort or filter starts from the top; the grid would otherwise stay anchored to a title. + LaunchedEffect(grid.query) { gridState.scrollToItem(0) } + val jump = me.xdan.aperture.ui.component.rememberGridJump(gridState) + Row(Modifier.fillMaxSize().graphicsLayer { clip = false }) { + Column(Modifier.weight(1f).padding(start = 32.dp, end = 16.dp, top = 24.dp).graphicsLayer { clip = false }) { + Text("TV Shows", style = MaterialTheme.typography.headlineLarge) + Spacer(Modifier.height(ApertureTheme.spacing.medium)) + me.xdan.aperture.ui.component.LibraryControlsRow( + query = grid.query, + options = grid.options, + onSort = onSort, + onUpdate = onUpdate, + firstModifier = Modifier + .then(if (groups.isEmpty()) Modifier.focusRequester(contentEntryFocusRequester) else Modifier) + .then(if (drawerFocusRequester != null) Modifier.focusProperties { left = drawerFocusRequester } else Modifier) + ) + Spacer(Modifier.height(ApertureTheme.spacing.small)) + if (groups.isEmpty()) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text("Nothing matches these filters.", color = MaterialTheme.colorScheme.onSurfaceVariant) + } + return@Column + } + Box(Modifier.weight(1f).graphicsLayer { clip = false }) { + LazyVerticalGrid( + state = gridState, + columns = GridCells.Fixed(5), + modifier = Modifier.fillMaxSize().graphicsLayer { clip = false }, + contentPadding = PaddingValues(top = ApertureTheme.spacing.large, bottom = ApertureTheme.spacing.large), + verticalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.large), + horizontalArrangement = Arrangement.spacedBy(ApertureTheme.spacing.large) + ) { + itemsIndexed(groups, key = { _, group -> group.title }) { index, group -> + val media = group.representative + var isFocused by remember { mutableStateOf(false) } + Box(modifier = Modifier.zIndex(if (isFocused) 1f else 0f)) { + AnimatedLibraryCard(media.id) { + MediaCard( + media = media, + onClick = { onMediaClick(media.id, it, false) }, + modifier = Modifier.fillMaxWidth(), + focusRequester = jump.requesterFor(index, contentEntryFocusRequester), + drawerFocusRequester = drawerFocusRequester.takeIf { index % 5 == 0 }, + onFocused = { requester -> + isFocused = true + onContentFocused(requester) + onActiveMediaChanged(media.id) + }, + onLongClick = { requester, opensToRight -> + onMediaLongClick(media, requester, false, opensToRight, false) + } + ) + } + } + DisposableEffect(Unit) { + onDispose { isFocused = false } } - } - DisposableEffect(Unit) { - onDispose { isFocused = false } } } } } + if (grid.letters.size > 1 && groups.isNotEmpty()) { + Box(Modifier.padding(top = 24.dp, end = 8.dp)) { + me.xdan.aperture.ui.component.LetterRail(letters = grid.letters, onLetter = jump::jumpTo) + } + } } } diff --git a/shared/src/jvmTest/kotlin/me/xdan/aperture/ui/screen/library/LocalLibraryQueryTest.kt b/shared/src/jvmTest/kotlin/me/xdan/aperture/ui/screen/library/LocalLibraryQueryTest.kt new file mode 100644 index 00000000..97236c5a --- /dev/null +++ b/shared/src/jvmTest/kotlin/me/xdan/aperture/ui/screen/library/LocalLibraryQueryTest.kt @@ -0,0 +1,61 @@ +package me.xdan.aperture.ui.screen.library + +import me.xdan.aperture.data.local.entity.MediaEntity +import me.xdan.aperture.data.local.entity.PlaybackProgressEntity +import me.xdan.aperture.domain.catalog.LibraryQuery +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class LocalLibraryQueryTest { + private fun movie(id: Long, title: String, year: Int? = null, added: Long = id, duration: Long? = null, favourite: Boolean = false) = + MediaEntity(id = id, filePath = "/m/$id.mkv", title = title, year = year, type = "MOVIE", duration = duration, isFavorite = favourite, dateAdded = added) + + private val films = listOf( + movie(1, "The Matrix", 1999, added = 10, duration = 8_160_000), + movie(2, "Alien", 1979, added = 30, duration = 7_020_000, favourite = true), + movie(3, "Zodiac", 2007, added = 20), + movie(4, "Untitled clip") + ) + + private fun titles(query: LibraryQuery, progress: Map = emptyMap()) = + LocalLibraryQuery.movies(films, progress, query, seed = 1).items.map { it.title } + + @Test + fun titleSortIgnoresLeadingArticle() { + assertEquals(listOf("Alien", "The Matrix", "Untitled clip", "Zodiac"), titles(LibraryQuery())) + assertEquals(listOf("Zodiac", "Untitled clip", "The Matrix", "Alien"), titles(LibraryQuery(descending = true))) + } + + @Test + fun missingValuesGoLastWhicheverDirection() { + val newest = LibraryQuery(sort = LibraryQuery.Sort.RELEASED, descending = true) + assertEquals(listOf("Zodiac", "The Matrix", "Alien", "Untitled clip"), titles(newest)) + val shortest = LibraryQuery(sort = LibraryQuery.Sort.RUNTIME) + assertEquals(listOf("Alien", "The Matrix", "Untitled clip", "Zodiac"), titles(shortest)) + } + + @Test + fun filtersByDecadeFavouritesAndWatched() { + assertEquals(listOf("The Matrix"), titles(LibraryQuery(decade = 1990))) + assertEquals(listOf("Alien"), titles(LibraryQuery(favouritesOnly = true))) + val watched = mapOf(1L to PlaybackProgressEntity(mediaId = 1, position = 100, duration = 100, isCompleted = true)) + assertEquals(listOf("Alien", "Untitled clip", "Zodiac"), titles(LibraryQuery(unwatchedOnly = true), watched)) + } + + @Test + fun offersDecadesAndNoRatingSort() { + val grid = LocalLibraryQuery.movies(films, emptyMap(), LibraryQuery(), seed = 1) + assertEquals(listOf(2000, 1990, 1970), grid.options.decades) + assertTrue(LibraryQuery.Sort.RATING !in grid.options.sorts) + assertEquals(setOf('A', 'M', 'U', 'Z'), grid.letters.keys) + } + + @Test + fun oldSavedQueriesStillDecode() { + val old = listOf("DATE_ADDED", "true", "false", "true", "Drama").joinToString("\u001F") + assertEquals(LibraryQuery(sort = LibraryQuery.Sort.DATE_ADDED, descending = true, favouritesOnly = true, genre = "Drama"), LibraryQuery.decode(old)) + val current = LibraryQuery(decade = 1980, uhdOnly = true) + assertEquals(current, LibraryQuery.decode(current.encode())) + } +}