package eu.friedcutlet.yokan.ui.navigation import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.focusGroup import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Badge import androidx.compose.material3.BadgedBox import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationRail import androidx.compose.material3.NavigationRailItem import androidx.compose.material3.NavigationRailItemDefaults import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.navigationevent.NavigationEventInfo import androidx.navigationevent.compose.NavigationBackHandler import androidx.navigationevent.compose.rememberNavigationEventState import androidx.compose.ui.graphics.lerp import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.services.extensions.VersionComparison import eu.friedcutlet.yokan.services.system.isTvDevice import eu.friedcutlet.yokan.ui.screens.activity.HistoryNavigationActivation import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import org.jetbrains.compose.resources.stringResource import yokan.composeapp.generated.resources.Res import yokan.composeapp.generated.resources.action_back import yokan.composeapp.generated.resources.nothing_read_recently import yokan.composeapp.generated.resources.nav_sections /** * Badge counts for the root navigation: unread updates and outdated active extensions of the visible * media types. Recomputed off the main thread only when the snapshot parts it reads change. */ internal fun navBadges(repository: YokanRepository, hidden: Flow>): Flow> = combine( repository.snapshots.distinctUntilChanged { old, new -> old.updates === new.updates && old.chapters === new.chapters && old.mangas === new.mangas && old.sources === new.sources }, hidden, ) { _, hiddenSections -> val visibleTypes = ItemType.entries.filter { it.librarySection() !in hiddenSections } mapOf( NavSection.Updates to repository.updates().count { !it.isRead && it.itemType in visibleTypes }, NavSection.Browse to visibleTypes.sumOf { type -> repository.sources(type).count { it.isActive && VersionComparison.isOutdated(it.version, it.versionLast) } }, ) }.flowOn(Dispatchers.Default) @Composable private fun NavigationIcon( count: Int, imageVector: ImageVector, label: String, ) { if (count > 0) { BadgedBox(badge = { Badge { Text(count.toString()) } }) { Icon(imageVector = imageVector, contentDescription = label) } } else { Icon(imageVector = imageVector, contentDescription = label) } } @Composable @OptIn(ExperimentalFoundationApi::class) internal fun RailNavigation( nav: Navigator, badges: Map, onResumeLatestHistory: (ItemType, String) -> Unit, modifier: Modifier = Modifier, ) { val navigationOrder by nav.navigationOrder.collectAsStateWithLifecycle() val selectedSection by nav.section.collectAsStateWithLifecycle() val historyActivation = remember { HistoryNavigationActivation() } val emptyHistoryMessage = stringResource(Res.string.nothing_read_recently) val isTv = isTvDevice() NavigationRail( modifier = modifier .width(100.dp) .focusGroup(), header = if (isTv) { { Surface( shape = RoundedCornerShape(6.dp), color = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(vertical = 8.dp), ) { Text( text = "BETA", color = MaterialTheme.colorScheme.onPrimary, style = MaterialTheme.typography.labelSmall.copy( fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.5.sp, ), modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp), ) } } } else null, ) { navigationOrder.forEach { section -> val selected = selectedSection == section val navIcon = iconFor(section) val label = localizedTitle(section) val baseIndicatorColor = lerp( MaterialTheme.colorScheme.secondaryContainer, MaterialTheme.colorScheme.onSecondaryContainer, 0.03f, ) val indicatorColor = baseIndicatorColor.copy( red = (baseIndicatorColor.red + 2.5f / 255f).coerceAtMost(1f), blue = (baseIndicatorColor.blue - 2.5f / 255f).coerceAtLeast(0f), ) NavigationRailItem( modifier = Modifier.height(65.dp).offset(y = 0.5.dp), selected = selected, onClick = { if (section == NavSection.History) { historyActivation.activate( nowMillis(), onSingle = { nav.select(section) }, onDouble = { nav.select(section); onResumeLatestHistory(nav.itemType.value, emptyHistoryMessage) }, ) } else nav.select(section) }, colors = NavigationRailItemDefaults.colors( indicatorColor = indicatorColor, ), icon = { Box(Modifier.offset(y = (-0.5).dp)) { NavigationIcon( count = badges[section] ?: 0, imageVector = if (selected) navIcon.selected else navIcon.unselected, label = label, ) } }, label = { Box(Modifier.offset(y = 5.5.dp)) { NavLabel(label) } }, ) } } } @OptIn(ExperimentalComposeUiApi::class) @Composable internal fun BottomNavigation( nav: Navigator, badges: Map, mergeLibraries: Boolean, onResumeLatestHistory: (ItemType, String) -> Unit, ) { val navigationOrder by nav.navigationOrder.collectAsStateWithLifecycle() val selectedSection by nav.section.collectAsStateWithLifecycle() val hidden by nav.hiddenSections.collectAsStateWithLifecycle() val historyActivation = remember { HistoryNavigationActivation() } val emptyHistoryMessage = stringResource(Res.string.nothing_read_recently) // Mirror the Flutter app's mobile nav: // 1. Pull from `navigationOrder`, which already drops anything in // `dbSettings.hideItems`, so every enabled section is reachable. // 2. When `mergeLibraryNavMobile` is on, replace the first library entry // in the order with a synthetic "Library" entry and remove the other // two. Tapping the merged entry swaps the bar into a sub-navigation // showing [Back] [Manga] [Anime] [Novel] limited to the visible // library types; selecting one activates it and collapses back. val librarySections = setOf(NavSection.MangaLibrary, NavSection.AnimeLibrary, NavSection.NovelLibrary) val merge = mergeLibraries val visibleLibraries = remember(hidden) { listOf(NavSection.MangaLibrary, NavSection.AnimeLibrary, NavSection.NovelLibrary) .filterNot { it in hidden } } var libraryPickerOpen by remember(merge) { mutableStateOf(false) } // Picking is meaningful for any non-empty visible library list. Mangayomi // still shows Back + the one available type when only one remains visible. if (!merge || visibleLibraries.isEmpty()) libraryPickerOpen = false if (libraryPickerOpen) { // Predictive back collapses the picker instead of falling through to // the root back handler (which would close the app from a root section). NavigationBackHandler(rememberNavigationEventState(NavigationEventInfo.None)) { libraryPickerOpen = false } LibraryPickerBar( selectedSection = selectedSection, options = visibleLibraries, onClose = { libraryPickerOpen = false }, onSelect = nav::select, ) return } val collapsed = remember(navigationOrder, merge) { if (!merge) return@remember navigationOrder val result = mutableListOf() var placed = false navigationOrder.forEach { section -> if (section in librarySections) { if (!placed) { result += section placed = true } } else { result += section } } result } var sectionsOpen by remember { mutableStateOf(false) } val primary = compactPrimarySections(collapsed) val overflow = collapsed.drop(primary.size) NavigationBar(modifier = Modifier.focusGroup()) { primary.forEach { section -> val isMergedLibrary = merge && section in librarySections val selected = if (isMergedLibrary) selectedSection in librarySections else selectedSection == section val navIcon = iconFor(if (isMergedLibrary) NavSection.MangaLibrary else section) val label = if (isMergedLibrary) "Library" else localizedTitle(section) NavigationBarItem( selected = selected, onClick = { if (isMergedLibrary) { if (visibleLibraries.isEmpty()) return@NavigationBarItem libraryPickerOpen = true } else if (section == NavSection.History) { historyActivation.activate( nowMillis(), onSingle = { nav.select(section) }, onDouble = { nav.select(section); onResumeLatestHistory(nav.itemType.value, emptyHistoryMessage) }, ) } else { nav.select(section) } }, icon = { NavigationIcon( count = badges[section] ?: 0, imageVector = if (selected) navIcon.selected else navIcon.unselected, label = label, ) }, label = { NavLabel(label) }, ) } if (overflow.isNotEmpty()) { NavigationBarItem( selected = selectedSection in overflow, onClick = { sectionsOpen = true }, icon = { Box { NavigationIcon(overflow.sumOf { badges[it] ?: 0 }, Icons.Filled.Menu, stringResource(Res.string.nav_sections)) DropdownMenu(expanded = sectionsOpen, onDismissRequest = { sectionsOpen = false }) { overflow.forEach { section -> val merged = merge && section in librarySections DropdownMenuItem(text = { Text(if (merged) "Library" else localizedTitle(section)) }, leadingIcon = { Icon(iconFor(section).unselected, null) }, onClick = { sectionsOpen = false if (merged) libraryPickerOpen = true else nav.select(section) }) } } } }, label = { NavLabel(stringResource(Res.string.nav_sections)) }, ) } } } /** Keep compact navigation usable as new destinations are added; every other section remains reachable. */ internal fun compactPrimarySections(sections: List): List = if (sections.size <= 5) sections else sections.take(4) @Composable private fun NavLabel(text: String) { // Without an explicit center alignment, NavigationBarItem labels default // to TextAlign.Start, so labels of differing lengths drift left within // their slot and the icon/label column reads as off-center. Single line // with ellipsis keeps the slot height stable even on narrow screens. Text( text = text, textAlign = TextAlign.Center, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } @Composable private fun LibraryPickerBar( selectedSection: NavSection, options: List, onClose: () -> Unit, onSelect: (NavSection) -> Unit, ) { NavigationBar(modifier = Modifier.focusGroup()) { NavigationBarItem( selected = false, onClick = onClose, icon = { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back), ) }, label = { NavLabel(stringResource(Res.string.action_back)) }, ) options.forEach { section -> val selected = selectedSection == section val navIcon = iconFor(section) val label = localizedTitle(section) NavigationBarItem( selected = selected, onClick = { onSelect(section) }, icon = { Icon( imageVector = if (selected) navIcon.selected else navIcon.unselected, contentDescription = label, ) }, label = { NavLabel(label) }, ) } } }