Yokan / rebuild
Course 1 8624561

RootNavigationBars.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/RootNavigationBars.kt

implementation358 lines
1package eu.friedcutlet.yokan.ui.navigation23import androidx.compose.foundation.ExperimentalFoundationApi4import androidx.compose.foundation.focusGroup5import androidx.compose.foundation.layout.Box6import androidx.compose.foundation.layout.height7import androidx.compose.foundation.layout.offset8import androidx.compose.foundation.layout.padding9import androidx.compose.foundation.layout.width10import androidx.compose.foundation.shape.RoundedCornerShape11import androidx.compose.material.icons.Icons12import androidx.compose.material.icons.automirrored.filled.ArrowBack13import androidx.compose.material.icons.filled.Menu14import androidx.compose.material3.DropdownMenu15import androidx.compose.material3.DropdownMenuItem16import androidx.compose.material3.Badge17import androidx.compose.material3.BadgedBox18import androidx.compose.material3.Icon19import androidx.compose.material3.MaterialTheme20import androidx.compose.material3.NavigationBar21import androidx.compose.material3.NavigationBarItem22import androidx.compose.material3.NavigationRail23import androidx.compose.material3.NavigationRailItem24import androidx.compose.material3.NavigationRailItemDefaults25import androidx.compose.material3.Surface26import androidx.compose.material3.Text27import androidx.compose.runtime.Composable28import androidx.compose.runtime.getValue29import androidx.compose.runtime.mutableStateOf30import androidx.compose.runtime.remember31import androidx.compose.runtime.setValue32import androidx.compose.ui.ExperimentalComposeUiApi33import androidx.compose.ui.Modifier34import androidx.navigationevent.NavigationEventInfo35import androidx.navigationevent.compose.NavigationBackHandler36import androidx.navigationevent.compose.rememberNavigationEventState37import androidx.compose.ui.graphics.lerp38import androidx.compose.ui.graphics.vector.ImageVector39import androidx.compose.ui.text.font.FontWeight40import androidx.compose.ui.text.style.TextAlign41import androidx.compose.ui.text.style.TextOverflow42import androidx.compose.ui.unit.dp43import androidx.compose.ui.unit.sp44import androidx.lifecycle.compose.collectAsStateWithLifecycle45import eu.friedcutlet.yokan.data.YokanRepository46import eu.friedcutlet.yokan.domain.ItemType47import eu.friedcutlet.yokan.services.extensions.VersionComparison48import eu.friedcutlet.yokan.services.system.isTvDevice49import eu.friedcutlet.yokan.ui.screens.activity.HistoryNavigationActivation50import eu.friedcutlet.yokan.util.nowMillis51import kotlinx.coroutines.Dispatchers52import kotlinx.coroutines.flow.Flow53import kotlinx.coroutines.flow.combine54import kotlinx.coroutines.flow.distinctUntilChanged55import kotlinx.coroutines.flow.flowOn56import org.jetbrains.compose.resources.stringResource57import yokan.composeapp.generated.resources.Res58import yokan.composeapp.generated.resources.action_back59import yokan.composeapp.generated.resources.nothing_read_recently60import yokan.composeapp.generated.resources.nav_sections6162/**63 * Badge counts for the root navigation: unread updates and outdated active extensions of the visible64 * media types. Recomputed off the main thread only when the snapshot parts it reads change.65 */66internal fun navBadges(repository: YokanRepository, hidden: Flow<Set<NavSection>>): Flow<Map<NavSection, Int>> =67    combine(68        repository.snapshots.distinctUntilChanged { old, new ->69            old.updates === new.updates && old.chapters === new.chapters &&70                old.mangas === new.mangas && old.sources === new.sources71        },72        hidden,73    ) { _, hiddenSections ->74        val visibleTypes = ItemType.entries.filter { it.librarySection() !in hiddenSections }75        mapOf(76            NavSection.Updates to repository.updates().count { !it.isRead && it.itemType in visibleTypes },77            NavSection.Browse to visibleTypes.sumOf { type ->78                repository.sources(type).count { it.isActive && VersionComparison.isOutdated(it.version, it.versionLast) }79            },80        )81    }.flowOn(Dispatchers.Default)8283@Composable84private fun NavigationIcon(85    count: Int,86    imageVector: ImageVector,87    label: String,88) {89    if (count > 0) {90        BadgedBox(badge = { Badge { Text(count.toString()) } }) {91            Icon(imageVector = imageVector, contentDescription = label)92        }93    } else {94        Icon(imageVector = imageVector, contentDescription = label)95    }96}9798@Composable99@OptIn(ExperimentalFoundationApi::class)100internal fun RailNavigation(101    nav: Navigator,102    badges: Map<NavSection, Int>,103    onResumeLatestHistory: (ItemType, String) -> Unit,104    modifier: Modifier = Modifier,105) {106    val navigationOrder by nav.navigationOrder.collectAsStateWithLifecycle()107    val selectedSection by nav.section.collectAsStateWithLifecycle()108    val historyActivation = remember { HistoryNavigationActivation() }109    val emptyHistoryMessage = stringResource(Res.string.nothing_read_recently)110    val isTv = isTvDevice()111    NavigationRail(112        modifier = modifier113            .width(100.dp)114            .focusGroup(),115        header = if (isTv) {116            {117                Surface(118                    shape = RoundedCornerShape(6.dp),119                    color = MaterialTheme.colorScheme.primary,120                    modifier = Modifier.padding(vertical = 8.dp),121                ) {122                    Text(123                        text = "BETA",124                        color = MaterialTheme.colorScheme.onPrimary,125                        style = MaterialTheme.typography.labelSmall.copy(126                            fontSize = 10.sp,127                            fontWeight = FontWeight.Bold,128                            letterSpacing = 1.5.sp,129                        ),130                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),131                    )132                }133            }134        } else null,135    ) {136        navigationOrder.forEach { section ->137            val selected = selectedSection == section138            val navIcon = iconFor(section)139            val label = localizedTitle(section)140            val baseIndicatorColor = lerp(141                MaterialTheme.colorScheme.secondaryContainer,142                MaterialTheme.colorScheme.onSecondaryContainer,143                0.03f,144            )145            val indicatorColor = baseIndicatorColor.copy(146                red = (baseIndicatorColor.red + 2.5f / 255f).coerceAtMost(1f),147                blue = (baseIndicatorColor.blue - 2.5f / 255f).coerceAtLeast(0f),148            )149            NavigationRailItem(150                modifier = Modifier.height(65.dp).offset(y = 0.5.dp),151                selected = selected,152                onClick = {153                    if (section == NavSection.History) {154                        historyActivation.activate(155                            nowMillis(),156                            onSingle = { nav.select(section) },157                            onDouble = { nav.select(section); onResumeLatestHistory(nav.itemType.value, emptyHistoryMessage) },158                        )159                    } else nav.select(section)160                },161                colors = NavigationRailItemDefaults.colors(162                    indicatorColor = indicatorColor,163                ),164                icon = {165                    Box(Modifier.offset(y = (-0.5).dp)) {166                        NavigationIcon(167                            count = badges[section] ?: 0,168                            imageVector = if (selected) navIcon.selected else navIcon.unselected,169                            label = label,170                        )171                    }172                },173                label = {174                    Box(Modifier.offset(y = 5.5.dp)) {175                        NavLabel(label)176                    }177                },178            )179        }180    }181}182183@OptIn(ExperimentalComposeUiApi::class)184@Composable185internal fun BottomNavigation(186    nav: Navigator,187    badges: Map<NavSection, Int>,188    mergeLibraries: Boolean,189    onResumeLatestHistory: (ItemType, String) -> Unit,190) {191    val navigationOrder by nav.navigationOrder.collectAsStateWithLifecycle()192    val selectedSection by nav.section.collectAsStateWithLifecycle()193    val hidden by nav.hiddenSections.collectAsStateWithLifecycle()194    val historyActivation = remember { HistoryNavigationActivation() }195    val emptyHistoryMessage = stringResource(Res.string.nothing_read_recently)196    // Mirror the Flutter app's mobile nav:197    //  1. Pull from `navigationOrder`, which already drops anything in198    //     `dbSettings.hideItems`, so every enabled section is reachable.199    //  2. When `mergeLibraryNavMobile` is on, replace the first library entry200    //     in the order with a synthetic "Library" entry and remove the other201    //     two. Tapping the merged entry swaps the bar into a sub-navigation202    //     showing [Back] [Manga] [Anime] [Novel] limited to the visible203    //     library types; selecting one activates it and collapses back.204    val librarySections = setOf(NavSection.MangaLibrary, NavSection.AnimeLibrary, NavSection.NovelLibrary)205    val merge = mergeLibraries206    val visibleLibraries = remember(hidden) {207        listOf(NavSection.MangaLibrary, NavSection.AnimeLibrary, NavSection.NovelLibrary)208            .filterNot { it in hidden }209    }210    var libraryPickerOpen by remember(merge) { mutableStateOf(false) }211    // Picking is meaningful for any non-empty visible library list. Mangayomi212    // still shows Back + the one available type when only one remains visible.213    if (!merge || visibleLibraries.isEmpty()) libraryPickerOpen = false214215    if (libraryPickerOpen) {216        // Predictive back collapses the picker instead of falling through to217        // the root back handler (which would close the app from a root section).218        NavigationBackHandler(rememberNavigationEventState(NavigationEventInfo.None)) { libraryPickerOpen = false }219        LibraryPickerBar(220            selectedSection = selectedSection,221            options = visibleLibraries,222            onClose = { libraryPickerOpen = false },223            onSelect = nav::select,224        )225        return226    }227228    val collapsed = remember(navigationOrder, merge) {229        if (!merge) return@remember navigationOrder230        val result = mutableListOf<NavSection>()231        var placed = false232        navigationOrder.forEach { section ->233            if (section in librarySections) {234                if (!placed) {235                    result += section236                    placed = true237                }238            } else {239                result += section240            }241        }242        result243    }244245    var sectionsOpen by remember { mutableStateOf(false) }246    val primary = compactPrimarySections(collapsed)247    val overflow = collapsed.drop(primary.size)248    NavigationBar(modifier = Modifier.focusGroup()) {249        primary.forEach { section ->250            val isMergedLibrary = merge && section in librarySections251            val selected = if (isMergedLibrary) selectedSection in librarySections else selectedSection == section252            val navIcon = iconFor(if (isMergedLibrary) NavSection.MangaLibrary else section)253            val label = if (isMergedLibrary) "Library" else localizedTitle(section)254            NavigationBarItem(255                selected = selected,256                onClick = {257                    if (isMergedLibrary) {258                        if (visibleLibraries.isEmpty()) return@NavigationBarItem259                        libraryPickerOpen = true260                    } else if (section == NavSection.History) {261                        historyActivation.activate(262                            nowMillis(),263                            onSingle = { nav.select(section) },264                            onDouble = { nav.select(section); onResumeLatestHistory(nav.itemType.value, emptyHistoryMessage) },265                        )266                    } else {267                        nav.select(section)268                    }269                },270                icon = {271                    NavigationIcon(272                        count = badges[section] ?: 0,273                        imageVector = if (selected) navIcon.selected else navIcon.unselected,274                        label = label,275                    )276                },277                label = { NavLabel(label) },278            )279        }280        if (overflow.isNotEmpty()) {281            NavigationBarItem(282                selected = selectedSection in overflow,283                onClick = { sectionsOpen = true },284                icon = { Box {285                    NavigationIcon(overflow.sumOf { badges[it] ?: 0 }, Icons.Filled.Menu, stringResource(Res.string.nav_sections))286                    DropdownMenu(expanded = sectionsOpen, onDismissRequest = { sectionsOpen = false }) {287                        overflow.forEach { section ->288                            val merged = merge && section in librarySections289                            DropdownMenuItem(text = { Text(if (merged) "Library" else localizedTitle(section)) },290                                leadingIcon = { Icon(iconFor(section).unselected, null) },291                                onClick = {292                                    sectionsOpen = false293                                    if (merged) libraryPickerOpen = true else nav.select(section)294                                })295                        }296                    }297                } },298                label = { NavLabel(stringResource(Res.string.nav_sections)) },299            )300        }301    }302}303304/** Keep compact navigation usable as new destinations are added; every other section remains reachable. */305internal fun compactPrimarySections(sections: List<NavSection>): List<NavSection> =306    if (sections.size <= 5) sections else sections.take(4)307308@Composable309private fun NavLabel(text: String) {310    // Without an explicit center alignment, NavigationBarItem labels default311    // to TextAlign.Start, so labels of differing lengths drift left within312    // their slot and the icon/label column reads as off-center. Single line313    // with ellipsis keeps the slot height stable even on narrow screens.314    Text(315        text = text,316        textAlign = TextAlign.Center,317        maxLines = 1,318        overflow = TextOverflow.Ellipsis,319    )320}321322@Composable323private fun LibraryPickerBar(324    selectedSection: NavSection,325    options: List<NavSection>,326    onClose: () -> Unit,327    onSelect: (NavSection) -> Unit,328) {329    NavigationBar(modifier = Modifier.focusGroup()) {330        NavigationBarItem(331            selected = false,332            onClick = onClose,333            icon = {334                Icon(335                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,336                    contentDescription = stringResource(Res.string.action_back),337                )338            },339            label = { NavLabel(stringResource(Res.string.action_back)) },340        )341        options.forEach { section ->342            val selected = selectedSection == section343            val navIcon = iconFor(section)344            val label = localizedTitle(section)345            NavigationBarItem(346                selected = selected,347                onClick = { onSelect(section) },348                icon = {349                    Icon(350                        imageVector = if (selected) navIcon.selected else navIcon.unselected,351                        contentDescription = label,352                    )353                },354                label = { NavLabel(label) },355            )356        }357    }358}359

Search chapters, reference and source filenames.