Yokan / rebuild
Course 1 8624561

DetailScreen.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailScreen.kt

implementation772 lines
1package eu.friedcutlet.yokan.ui.screens.detail23import androidx.lifecycle.Lifecycle4import androidx.lifecycle.compose.LocalLifecycleOwner5import androidx.lifecycle.compose.collectAsStateWithLifecycle6import androidx.lifecycle.repeatOnLifecycle7import androidx.lifecycle.viewmodel.compose.viewModel8import androidx.compose.foundation.layout.Arrangement9import androidx.compose.foundation.layout.Box10import androidx.compose.foundation.layout.BoxWithConstraints11import androidx.compose.foundation.layout.Column12import androidx.compose.foundation.layout.PaddingValues13import androidx.compose.foundation.layout.Row14import androidx.compose.foundation.layout.Spacer15import androidx.compose.foundation.layout.calculateEndPadding16import androidx.compose.foundation.layout.calculateStartPadding17import androidx.compose.foundation.layout.fillMaxHeight18import androidx.compose.foundation.layout.fillMaxSize19import androidx.compose.foundation.layout.fillMaxWidth20import androidx.compose.foundation.layout.height21import androidx.compose.foundation.layout.padding22import androidx.compose.foundation.layout.size23import androidx.compose.foundation.lazy.LazyColumn24import androidx.compose.foundation.lazy.LazyListScope25import androidx.compose.foundation.lazy.items26import androidx.compose.foundation.lazy.rememberLazyListState27import androidx.compose.foundation.rememberScrollState28import androidx.compose.foundation.verticalScroll29import androidx.compose.material.icons.Icons30import androidx.compose.material.icons.filled.PlayArrow31import androidx.compose.material3.ExperimentalMaterial3Api32import androidx.compose.material3.ExtendedFloatingActionButton33import androidx.compose.material3.FloatingActionButtonDefaults34import androidx.compose.material3.Icon35import androidx.compose.material3.LinearProgressIndicator36import androidx.compose.material3.MaterialTheme37import androidx.compose.material3.SnackbarHost38import androidx.compose.material3.SnackbarHostState39import androidx.compose.material3.Text40import androidx.compose.material3.pulltorefresh.PullToRefreshBox41import androidx.compose.runtime.Composable42import androidx.compose.runtime.LaunchedEffect43import androidx.compose.runtime.derivedStateOf44import androidx.compose.runtime.getValue45import androidx.compose.runtime.mutableStateMapOf46import androidx.compose.runtime.mutableStateOf47import androidx.compose.runtime.remember48import androidx.compose.runtime.setValue49import androidx.compose.runtime.snapshotFlow50import androidx.compose.ui.Alignment51import androidx.compose.ui.Modifier52import androidx.compose.ui.platform.LocalDensity53import androidx.compose.ui.platform.LocalLayoutDirection54import androidx.compose.ui.text.font.FontWeight55import androidx.compose.ui.unit.Dp56import androidx.compose.ui.unit.dp57import eu.friedcutlet.yokan.app.YokanRuntime58import eu.friedcutlet.yokan.app.profiles.ProfileSession59import eu.friedcutlet.yokan.database.DbItemType60import eu.friedcutlet.yokan.database.DbLocalFolder61import eu.friedcutlet.yokan.database.configuredLocalFolders62import eu.friedcutlet.yokan.domain.Chapter63import eu.friedcutlet.yokan.domain.ItemType64import eu.friedcutlet.yokan.domain.Manga65import eu.friedcutlet.yokan.services.extensions.webViewUserAgent66import eu.friedcutlet.yokan.services.library.ChapterFilterKind67import eu.friedcutlet.yokan.services.library.chapterFilters68import eu.friedcutlet.yokan.services.library.scanlatorFilter69import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult70import eu.friedcutlet.yokan.ui.components.ErrorState71import eu.friedcutlet.yokan.ui.components.LoadingState72import eu.friedcutlet.yokan.ui.components.ScrollbarBox73import eu.friedcutlet.yokan.ui.navigation.MissingRoute74import eu.friedcutlet.yokan.ui.navigation.Navigator75import eu.friedcutlet.yokan.ui.navigation.Route76import eu.friedcutlet.yokan.ui.navigation.SettingsPage77import kotlinx.coroutines.CancellationException78import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold7980@Composable81internal fun DetailRoute(route: Route.Detail, nav: Navigator) {82    val owner = remember { YokanRuntime.activeSession }83    val viewModel = viewModel {84        DetailViewModel(85            mangaId = route.mangaId,86            repository = owner.repository,87            settings = owner.settings,88            libraryIndex = owner.libraryIndex,89            downloads = owner.chapterDownloads,90            metadata = owner.services.metadata,91            runtimeFactory = owner.services.extensionRuntimeFactory,92            database = owner.database,93            allTrackers = owner.services.trackers,94            files = owner.localFiles,95            together = owner.together,96            togetherHttp = owner.services.http,97        )98    }99    val snackbarHostState = remember { SnackbarHostState() }100    val lifecycleOwner = LocalLifecycleOwner.current101    LaunchedEffect(lifecycleOwner, viewModel) {102        lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {103            viewModel.effects.collect { effect ->104                when (effect) {105                    is DetailEffect.ShowMessage -> snackbarHostState.showSnackbar(effect.text)106                    DetailEffect.OpenTogetherSettings -> nav.navigate(Route.Settings(SettingsPage.Together))107                }108            }109        }110    }111    val state = viewModel.state.collectAsStateWithLifecycle().value ?: return MissingRoute("Title Detail", nav::back)112    DetailScreen(113        state = state,114        snackbarHostState = snackbarHostState,115        downloadRoot = owner.localFiles.downloadRoot,116        onEvent = viewModel::onEvent,117        onNavigate = nav::navigate,118        onLibrarySearch = { genre -> nav.showLibrary(state.content.manga.itemType, "genre:${genre.trim()}") },119        onBack = nav::back,120        onSaveCover = { manga -> ownedCoverAction(owner) { saveDetailCover(manga, owner) } },121        onShareCover = { manga -> ownedCoverAction(owner) { shareDetailCover(manga, owner) } },122        onChangeCover = { callback -> ownedCoverAction(owner) { changeDetailCover(callback, owner) } },123    )124}125126/** The one dialog or sheet the detail screen shows at a time; the note editor follows [DetailState.noteDraft]. */127private sealed interface DetailDialog {128    data object Cover : DetailDialog129    data object Filter : DetailDialog130    data object Tracker : DetailDialog131    data object SmartUpdate : DetailDialog132    /** [favoriteAfter] favourites the title once the categories are saved. */133    data class Categories(val favoriteAfter: Boolean) : DetailDialog134    data object Range : DetailDialog135    data object Delete : DetailDialog136    data class Destination(val request: PendingDownloadRequest) : DetailDialog137}138139/**140 * Detail screen for manga, anime, and novels. Its responsive title header,141 * flat chapter list, action strip, and selection controls mirror Mangayomi's142 * detail hierarchy; data and actions come from [DetailViewModel] as [state] and [onEvent].143 */144@OptIn(ExperimentalMaterial3Api::class)145@Composable146internal fun DetailScreen(147    state: DetailState,148    snackbarHostState: SnackbarHostState,149    /** The app's default download folder, offered by the destination picker. */150    downloadRoot: String,151    onEvent: (DetailEvent) -> Unit,152    onNavigate: (Route) -> Unit,153    onLibrarySearch: (genre: String) -> Unit,154    onBack: () -> Unit,155    onSaveCover: suspend (Manga) -> String,156    onShareCover: suspend (Manga) -> String,157    onChangeCover: suspend ((ByteArray) -> Unit) -> String,158) {159    val content = state.content160    val current = content.manga161    val settings = content.settings162    val isLocalEntry = current.isLocalArchive163    val source = content.source164    val showRemoteActions = !isLocalEntry165    val chapters = content.chapters166    val chapterFilters = settings.chapterFilters(current)167    val filteringActive = ChapterFilterKind.entries.any { chapterFilters.value(it) != 0 } ||168        settings.scanlatorFilter(current.id).isNotEmpty()169    val loading = state.loading170    val error = state.error171172    var dialog by remember(current.id) { mutableStateOf<DetailDialog?>(null) }173    val selectedChapters = state.selection.ids174    val selectionActions: @Composable () -> Unit = {175        ChapterSelectionMenu(176            enabled = chapters.isNotEmpty(), hasSelection = selectedChapters.isNotEmpty(),177            hasAnchor = state.selection.anchorId != null,178            onSelect = { onEvent(DetailEvent.Select(it)) }, onRange = { dialog = DetailDialog.Range },179        )180    }181    var descriptionExpanded by remember(current.id) { mutableStateOf(false) }182    var fabExpanded by remember(current.id) { mutableStateOf(true) }183184    val chapterListState = rememberLazyListState()185    val chapterItemSizes = remember(current.id) { mutableStateMapOf<Int, Int>() }186    val density = LocalDensity.current187    val appBarTitleThresholdPx = remember(density) {188        with(density) { 200.dp.roundToPx() }189    }190    val showAppBarTitle by remember(chapterListState, chapterItemSizes, appBarTitleThresholdPx) {191        derivedStateOf {192            val layoutInfo = chapterListState.layoutInfo193            val firstVisibleItem = layoutInfo.visibleItemsInfo.firstOrNull()194                ?: return@derivedStateOf false195            var scrollDistance =196                layoutInfo.viewportStartOffset - firstVisibleItem.offset197            var index = 0198            while (199                index < firstVisibleItem.index &&200                scrollDistance <= appBarTitleThresholdPx201            ) {202                val itemSize = chapterItemSizes[index]203                    ?: return@derivedStateOf true204                scrollDistance += itemSize205                index += 1206            }207            scrollDistance > appBarTitleThresholdPx208        }209    }210211    LaunchedEffect(current.id, chapterListState) {212        chapterListState.scrollToItem(0)213        snapshotFlow {214            chapterListState.layoutInfo.visibleItemsInfo.map { it.index to it.size }215        }.collect { visibleItemSizes ->216            visibleItemSizes.forEach { (index, size) ->217                chapterItemSizes[index] = size218            }219        }220    }221222    LaunchedEffect(current.id, chapterListState) {223        var previous = chapterListState.firstVisibleItemIndex to chapterListState.firstVisibleItemScrollOffset224        snapshotFlow {225            Triple(226                chapterListState.firstVisibleItemIndex,227                chapterListState.firstVisibleItemScrollOffset,228                chapterListState.isScrollInProgress,229            )230        }.collect { (index, offset, scrolling) ->231            val currentPosition = index to offset232            if (scrolling && currentPosition != previous) {233                fabExpanded = index < previous.first || (index == previous.first && offset < previous.second)234            }235            if (index == 0 && offset == 0) fabExpanded = true236            previous = currentPosition237        }238    }239240    LaunchedEffect(error) {241        error?.takeIf { it.isNotBlank() }?.let { msg -> snackbarHostState.showSnackbar(msg) }242    }243244    val unreadChapter = remember(chapters) { chapters.firstOrNull { !it.isRead } }245    val seasonTitles = content.seasonTitles246    // A Seasons-type title resumes in its first season with an unwatched episode.247    val resumeTarget = unreadChapter?.let { current.id to it.id }248        ?: seasonTitles.firstNotNullOfOrNull { season -> season.continueChapter?.let { season.title.id to it.id } }249    val hasReadingHistory = remember(chapters, seasonTitles) {250        chapters.any { it.isRead || it.lastPageRead.isNotBlank() } || seasonTitles.any { it.watchedCount > 0 }251    }252    val categories = content.categories253    val configuredDownloadFolders = remember(settings) { settings.configuredLocalFolders() }254255    fun shouldAskDownloadDestination(): Boolean =256        settings.askDownloadDestination && configuredDownloadFolders.isNotEmpty()257258    fun requestDownload(chapter: Chapter) {259        if (shouldAskDownloadDestination()) {260            dialog = DetailDialog.Destination(PendingDownloadRequest.Single(chapter))261        } else {262            onEvent(DetailEvent.Download(chapter, destinationRoot = null))263        }264    }265266    fun requestDownloads(targetChapters: List<Chapter>, option: DetailDownloadOption) {267        if (shouldAskDownloadDestination() && targetChapters.any { it.downloadSize == null }) {268            dialog = DetailDialog.Destination(PendingDownloadRequest.Bulk(targetChapters, option))269        } else {270            onEvent(DetailEvent.DownloadAll(targetChapters, option, destinationRoot = null))271        }272    }273274    fun toggleChapterSelection(chapter: Chapter) = onEvent(DetailEvent.ToggleSelection(chapter.id))275276    fun selectRangeTo(chapter: Chapter) = onEvent(DetailEvent.SelectRangeTo(chapter.id))277278    fun openWebView() {279        val webUrl = current.link.takeIf { it.startsWith("http", ignoreCase = true) }280            ?: source?.baseUrl?.takeIf { it.isNotBlank() }281            ?: return282        onNavigate(Route.InAppWebView(webUrl, current.name, settings.webViewUserAgent(source).takeIf { it.isNotBlank() }))283    }284285    val chapterRow: @Composable (Chapter) -> Unit = { chapter ->286        ChapterRow(287            chapter = chapter,288            itemType = current.itemType,289            uploadDate = formatChapterDate(chapter.dateUpload, settings),290            selected = chapter.id in selectedChapters,291            anySelected = selectedChapters.isNotEmpty(),292            onClick = {293                if (selectedChapters.isNotEmpty()) {294                    toggleChapterSelection(chapter)295                } else {296                    onNavigate(Route.Reader(current.id, chapter.id))297                }298            },299            onLongClick = { if (selectedChapters.isEmpty()) toggleChapterSelection(chapter) else selectRangeTo(chapter) },300            onSecondaryClick = { shiftPressed ->301                if (shiftPressed && selectedChapters.isNotEmpty()) {302                    selectRangeTo(chapter)303                } else {304                    toggleChapterSelection(chapter)305                }306            },307            onBookmark = { onEvent(DetailEvent.SetBookmarked(setOf(chapter.id), !chapter.isBookmarked)) },308            onReadToggle = { onEvent(DetailEvent.SetRead(setOf(chapter.id), !chapter.isRead)) },309            showDownload = showRemoteActions,310            onDownload = { requestDownload(chapter) },311        )312    }313314    fun editCategories() {315        if (categories.isEmpty()) return316        dialog = DetailDialog.Categories(favoriteAfter = !current.favorite)317    }318319    fun toggleFavorite() {320        val defaultId = settings.features.library.defaultCategory(321            when (current.itemType) {322                ItemType.Manga -> DbItemType.Manga323                ItemType.Anime -> DbItemType.Anime324                ItemType.Novel -> DbItemType.Novel325            },326        )327        val hasDefault = defaultId == 0L || categories.any { it.id == defaultId }328        if (!current.favorite && categories.isNotEmpty() && !hasDefault) {329            editCategories()330        } else {331            onEvent(DetailEvent.SetFavorite(!current.favorite))332        }333    }334335    val infoBlocks: @Composable (spacing: Dp) -> Unit = { spacing ->336        DetailInfoBlocks(337            content = content,338            loading = loading,339            error = error,340            showRemoteActions = showRemoteActions,341            descriptionExpanded = descriptionExpanded,342            spacing = spacing,343            onToggleDescription = { descriptionExpanded = !descriptionExpanded },344            onFavorite = ::toggleFavorite,345            onFavoriteLongClick = if (categories.isNotEmpty()) ::editCategories else null,346            onSmartUpdate = { dialog = DetailDialog.SmartUpdate },347            onTrack = { dialog = DetailDialog.Tracker },348            onWeb = ::openWebView,349            onEvent = onEvent,350            onNavigate = onNavigate,351            onLibrarySearch = onLibrarySearch,352        )353    }354    val chapterItems: LazyListScope.() -> Unit = {355        detailChapterItems(content, selectionActions, onEvent, onNavigate, chapterRow)356    }357358    Scaffold(359        topBar = {360            if (selectedChapters.isEmpty()) {361                DetailTopBar(362                    manga = current,363                    source = source,364                    showTitle = showAppBarTitle,365                    showRemoteActions = showRemoteActions,366                    filteringActive = filteringActive,367                    metadataEnabled = settings.metadataServerUrl.startsWith("http"),368                    canSetCategories = current.favorite && categories.isNotEmpty(),369                    togetherRoom = state.togetherRoom,370                    onBack = onBack,371                    onDownload = { option -> requestDownloads(chaptersForDownloadOption(chapters, option), option) },372                    onFilter = { dialog = DetailDialog.Filter },373                    onSetCategories = { dialog = DetailDialog.Categories(favoriteAfter = false) },374                    onEvent = onEvent,375                    onNavigate = onNavigate,376                )377            } else {378                ChapterSelectionTopBar(379                    selectedCount = selectedChapters.size,380                    onClear = { onEvent(DetailEvent.ClearSelection) },381                    selectionActions = selectionActions,382                )383            }384        },385        bottomBar = {386            if (selectedChapters.isNotEmpty()) {387                val selectedModels = chapters.filter { it.id in selectedChapters }388                val singleSelection = selectedModels.singleOrNull()389                ChapterSelectionBottomBar(390                    bookmarked = singleSelection?.isBookmarked == true,391                    read = singleSelection?.isRead == true,392                    showDownload = showRemoteActions &&393                        selectedModels.none { it.downloadSize != null || it.archivePath.isNotBlank() },394                    showDelete = isLocalEntry || selectedModels.any { it.downloadSize != null || it.archivePath.isNotBlank() },395                    filler = selectedModels.all { it.isFiller }.takeIf { current.itemType == ItemType.Anime },396                    showFillerReset = selectedModels.any { it.fillerOverride != null },397                    onBookmark = { onEvent(DetailEvent.ToggleSelectedBookmarks) },398                    onMarkRead = { onEvent(DetailEvent.ToggleSelectedRead) },399                    onFiller = {400                        onEvent(DetailEvent.SetFiller(selectedModels.map { it.id }.toSet(), !selectedModels.all { it.isFiller }))401                        onEvent(DetailEvent.ClearSelection)402                    },403                    onResetFiller = {404                        onEvent(DetailEvent.SetFiller(selectedModels.map { it.id }.toSet(), null))405                        onEvent(DetailEvent.ClearSelection)406                    },407                    onDownload = {408                        requestDownloads(selectedModels, DetailDownloadOption.Selected)409                        onEvent(DetailEvent.ClearSelection)410                    },411                    onDelete = { dialog = DetailDialog.Delete },412                )413            }414        },415        floatingActionButton = {416            if (resumeTarget != null && selectedChapters.isEmpty()) {417                ExtendedFloatingActionButton(418                    onClick = { onNavigate(Route.Reader(resumeTarget.first, resumeTarget.second)) },419                    expanded = fabExpanded,420                    icon = {421                        Icon(422                            Icons.Filled.PlayArrow,423                            contentDescription = null,424                            modifier = Modifier.size(22.dp),425                        )426                    },427                    text = {428                        Text(429                            if (hasReadingHistory) "Resume" else "Start",430                            style = MaterialTheme.typography.labelLarge,431                            fontWeight = FontWeight.SemiBold,432                        )433                    },434                    // The FAB defaults to MaterialTheme.shapes.large which now435                    // rounds to 20dp; bump to the extra-large 28dp so it reads436                    // as a clear primary CTA against the chapter list.437                    shape = MaterialTheme.shapes.extraLarge,438                    containerColor = MaterialTheme.colorScheme.primary,439                    contentColor = MaterialTheme.colorScheme.onPrimary,440                    elevation = FloatingActionButtonDefaults.elevation(441                        defaultElevation = 6.dp,442                        pressedElevation = 10.dp,443                        focusedElevation = 8.dp,444                        hoveredElevation = 10.dp,445                    ),446                )447            }448        },449        snackbarHost = { SnackbarHost(snackbarHostState) },450    ) { paddingValues ->451        BoxWithConstraints(Modifier.fillMaxSize()) {452            val usePhoneLayout = maxWidth < 720.dp453            // Phone layout: skip the top padding so the backdrop header draws454            // behind the transparent TopAppBar up to y=0 (Mangayomi parity).455            // Desktop layout has no backdrop, so it keeps the full padding.456            val layoutDirection = LocalLayoutDirection.current457            val contentModifier = Modifier.fillMaxSize().padding(458                if (usePhoneLayout) {459                    PaddingValues(460                        start = paddingValues.calculateStartPadding(layoutDirection),461                        end = paddingValues.calculateEndPadding(layoutDirection),462                        bottom = paddingValues.calculateBottomPadding(),463                    )464                } else {465                    paddingValues466                },467            )468            // Mangayomi refreshes the title with a swipe (RefreshIndicator around469            // the detail body); the overflow "Refresh" action stays for desktop.470            PullToRefreshBox(471                isRefreshing = loading,472                onRefresh = { onEvent(DetailEvent.Refresh) },473                modifier = contentModifier,474            ) {475                if (loading) {476                    LinearProgressIndicator(477                        modifier = Modifier.fillMaxWidth().align(Alignment.TopCenter),478                    )479                }480481                if (usePhoneLayout) {482                    ScrollbarBox(state = chapterListState, modifier = Modifier.fillMaxSize()) {483                        LazyColumn(state = chapterListState, modifier = Modifier.fillMaxSize()) {484                            item(key = "header") {485                                DetailBackdropHeader(486                                    manga = current,487                                    showSource = showRemoteActions,488                                    onTitleSelected = { title -> onEvent(DetailEvent.SetDisplayTitle(title)) },489                                    onCoverClick = { dialog = DetailDialog.Cover },490                                )491                            }492                            item(key = "info") { infoBlocks(0.dp) }493                            chapterItems()494                        }495                    }496                } else {497                    val detailScroll = rememberScrollState()498                    Row(modifier = Modifier.fillMaxSize()) {499                        ScrollbarBox(state = detailScroll, modifier = Modifier.weight(0.5f).fillMaxHeight()) {500                            Column(501                                modifier = Modifier502                                    .fillMaxSize()503                                    .verticalScroll(detailScroll)504                                    .padding(bottom = 96.dp),505                                verticalArrangement = Arrangement.spacedBy(6.dp),506                            ) {507                                DetailSideHeader(508                                    manga = current,509                                    showSource = showRemoteActions,510                                    onTitleSelected = { title -> onEvent(DetailEvent.SetDisplayTitle(title)) },511                                    onCoverClick = { dialog = DetailDialog.Cover },512                                )513                                infoBlocks(6.dp)514                            }515                        }516                        ScrollbarBox(state = chapterListState, modifier = Modifier.weight(0.5f).fillMaxHeight()) {517                            LazyColumn(state = chapterListState, modifier = Modifier.fillMaxSize()) {518                                chapterItems()519                            }520                        }521                    }522                }523            }524        }525    }526527    DetailDialogs(528        dialog = dialog,529        state = state,530        downloadRoot = downloadRoot,531        downloadFolders = configuredDownloadFolders,532        onDismiss = { dialog = null },533        onEvent = onEvent,534        onBack = onBack,535        onSaveCover = onSaveCover,536        onShareCover = onShareCover,537        onChangeCover = onChangeCover,538    )539}540541/** Title action strip, note, description, genres, related links, cast, and refresh status; shared by both layouts. */542@Composable543private fun DetailInfoBlocks(544    content: DetailContent,545    loading: Boolean,546    error: String?,547    showRemoteActions: Boolean,548    descriptionExpanded: Boolean,549    spacing: Dp,550    onToggleDescription: () -> Unit,551    onFavorite: () -> Unit,552    onFavoriteLongClick: (() -> Unit)?,553    onSmartUpdate: () -> Unit,554    onTrack: () -> Unit,555    onWeb: () -> Unit,556    onEvent: (DetailEvent) -> Unit,557    onNavigate: (Route) -> Unit,558    onLibrarySearch: (genre: String) -> Unit,559) {560    val manga = content.manga561    Column(verticalArrangement = Arrangement.spacedBy(spacing)) {562        DetailActionRow(563            manga = manga,564            trackCount = content.tracks.size,565            showWeb = showRemoteActions,566            onFavorite = onFavorite,567            onFavoriteLongClick = onFavoriteLongClick,568            automaticUpdateDays = content.automaticUpdateDays,569            onSmartUpdate = onSmartUpdate,570            onTrack = onTrack,571            onMigrate = { onNavigate(Route.Migrate(manga.id)) },572            onWeb = onWeb,573        )574        if (manga.favorite) {575            DetailNotePreview(note = manga.privateNote, onEdit = { onEvent(DetailEvent.EditNote) })576        }577        if (manga.description.isNotBlank()) {578            DetailDescription(text = manga.description, expanded = descriptionExpanded, onToggle = onToggleDescription)579        }580        if (manga.genres.isNotEmpty()) {581            Box(modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) {582                DetailGenreTags(583                    tags = manga.genres, sources = content.genreSources,584                    onLibrarySearch = onLibrarySearch,585                    onSourceSearch = { destination, tag -> onNavigate(Route.SourceHome(destination.id, tag)) },586                )587            }588        }589        DetailRelatedActions(590            itemType = manga.itemType,591            hasTracks = content.tracks.isNotEmpty(),592            onRecommendations = { onNavigate(Route.Recommendations(manga.id)) },593            onWatchOrder = { onNavigate(Route.WatchOrder(manga.id)) },594            onSequels = { onNavigate(Route.Sequels(manga.id)) },595        )596        if (manga.cast.isNotEmpty()) TitleCastCredits(manga.cast)597        if (loading) LoadingState(label = "Refreshing details…")598        if (!error.isNullOrBlank()) {599            ErrorState(600                message = error,601                onRetry = { onEvent(DetailEvent.Refresh) },602                openInBrowserUrl = content.source?.baseUrl,603            )604        }605    }606}607608/** Season records or the chapter heading, season filter, and chapter rows; shared by both layouts. */609private fun LazyListScope.detailChapterItems(610    content: DetailContent,611    selectionActions: @Composable () -> Unit,612    onEvent: (DetailEvent) -> Unit,613    onNavigate: (Route) -> Unit,614    chapterRow: @Composable (Chapter) -> Unit,615) {616    val manga = content.manga617    if (manga.fetchesSeasons) {618        item(key = "season-header") { DetailSeasonsHeader(content.seasonTitles.size) }619        items(content.seasonTitles, key = { "season-title-${it.title.id}" }, contentType = { "season-title" }) { season ->620            DetailSeasonRow(621                season,622                onOpen = { onNavigate(Route.Detail(season.title.id)) },623                onContinue = { season.continueChapter?.let { onNavigate(Route.Reader(season.title.id, it.id)) } },624            )625        }626    } else {627        // Sort and filters live in the app-bar sheet.628        item(key = "chapter-header") {629            ChaptersHeaderRow(630                label = chapterLabel(manga.itemType),631                selectionActions = selectionActions,632                count = content.chapters.size,633                missingCount = content.missingChapterCount,634                unnumberedCount = content.unnumberedChapterCount,635            )636        }637    }638    if (content.seasons.isNotEmpty()) item(key = "seasons") {639        EpisodeSeasonSelector(content.seasons, content.selectedSeason, { onEvent(DetailEvent.SelectSeason(it)) })640    }641    if (content.loaded && content.chapters.isEmpty() && !manga.fetchesSeasons) {642        item(key = "empty-chapters") { EmptyChaptersCard(manga.itemType) }643    }644    items(content.chapters, key = { it.id }) { chapter -> chapterRow(chapter) }645    // Trailing spacer so the last row clears the extended FAB.646    item(key = "trailing-spacer") { Spacer(Modifier.height(96.dp)) }647}648649@Composable650private fun DetailDialogs(651    dialog: DetailDialog?,652    state: DetailState,653    downloadRoot: String,654    downloadFolders: List<DbLocalFolder>,655    onDismiss: () -> Unit,656    onEvent: (DetailEvent) -> Unit,657    onBack: () -> Unit,658    onSaveCover: suspend (Manga) -> String,659    onShareCover: suspend (Manga) -> String,660    onChangeCover: suspend ((ByteArray) -> Unit) -> String,661) {662    val content = state.content663    val current = content.manga664    val settings = content.settings665    when (dialog) {666        null -> Unit667        DetailDialog.Cover -> current.detailCoverModel()?.let { model ->668            CoverInspectionDialog(669                title = current.name,670                identity = listOf(671                    current.id,672                    current.customCoverImage?.contentHashCode(),673                    current.customCoverFromTracker,674                    current.imageUrl,675                ),676                model = model,677                onDismiss = onDismiss,678                onSave = { onSaveCover(current) },679                onChange = { onChangeCover { bytes -> onEvent(DetailEvent.SetCustomCover(bytes)) } },680                onShare = { onShareCover(current) },681            )682        }683        DetailDialog.Filter -> ChapterFilterSheet(684            manga = current,685            settings = settings,686            scanlators = content.scanlators,687            onSort = { onEvent(DetailEvent.ToggleSort(it)) },688            onCycleFilter = { onEvent(DetailEvent.CycleFilter(it)) },689            onToggleScanlator = { onEvent(DetailEvent.ToggleScanlator(it)) },690            showAllReleases = state.showAllReleases,691            onShowAllReleases = { onEvent(DetailEvent.ShowAllReleases(it)) },692            onSkipDuplicates = { onEvent(DetailEvent.SetSkipDuplicates(it)) },693            onMoveScanlator = { name, direction -> onEvent(DetailEvent.MoveScanlator(name, direction)) },694            onResetReleaseOverride = { onEvent(DetailEvent.ResetReleaseOverride) },695            onSetAsDefault = { onEvent(DetailEvent.SetChapterListDefault(it)) },696            onDismiss = onDismiss,697        )698        DetailDialog.Tracker -> TrackerSearchDialog(699            manga = current,700            trackerNames = state.trackerNames,701            search = state.trackerSearch,702            onSearch = { trackerIndex, query -> onEvent(DetailEvent.SearchTracker(trackerIndex, query)) },703            onBind = { trackerIndex, result -> onEvent(DetailEvent.BindTrack(trackerIndex, result)) },704            onDismiss = {705                onDismiss()706                onEvent(DetailEvent.CloseTrackerSearch)707            },708        )709        DetailDialog.Range -> ChapterRangeDialog(content.chapters, onSelect = { first, last ->710            onEvent(DetailEvent.SelectRange(first, last))711            onDismiss()712        }, onDismiss = onDismiss)713        DetailDialog.SmartUpdate -> SmartUpdateDialog(714            manualDays = current.smartUpdateDays,715            automaticDays = content.automaticUpdateDays,716            onChange = { onEvent(DetailEvent.SetSmartUpdateDays(it)) },717            onDismiss = onDismiss,718        )719        is DetailDialog.Categories -> CategoryEditorSheet(720            manga = current,721            categories = content.categories,722            onSave = { categoryIds -> onEvent(DetailEvent.SetCategories(categoryIds, favorite = dialog.favoriteAfter)) },723            onDismiss = onDismiss,724        )725        is DetailDialog.Destination -> DownloadDestinationDialog(726            title = "Download destination",727            folders = downloadFolders,728            defaultRoot = downloadRoot,729            selectedName = settings.downloadLocalFolderName,730            onSelect = { folderName ->731                // Blank means the app's default root; null would mean the folder selected in settings.732                val folderPath = downloadFolders.firstOrNull { it.name == folderName }?.path.orEmpty()733                onDismiss()734                when (val request = dialog.request) {735                    is PendingDownloadRequest.Single -> onEvent(DetailEvent.Download(request.chapter, folderPath))736                    is PendingDownloadRequest.Bulk -> onEvent(DetailEvent.DownloadAll(request.chapters, request.option, folderPath))737                }738            },739            onDismiss = onDismiss,740        )741        DetailDialog.Delete -> {742            val selectedCount = state.selection.ids.size743            val isLocalLast = current.isLocalArchive && selectedCount >= content.chapters.size744            DeleteChaptersDialog(745                isLocalEntry = current.isLocalArchive,746                deletesEntry = isLocalLast,747                selectedCount = selectedCount,748                itemType = current.itemType,749                onConfirm = {750                    onDismiss()751                    onEvent(DetailEvent.DeleteSelected(removeEntry = isLocalLast))752                    if (isLocalLast) onBack()753                },754                onDismiss = onDismiss,755            )756        }757    }758    state.noteDraft?.takeIf { current.favorite }?.let { draft ->759        DetailNoteEditor(760            draft = draft,761            onChange = { onEvent(DetailEvent.ChangeNote(it)) },762            onSave = { onEvent(DetailEvent.SaveNote) },763            onCancel = { onEvent(DetailEvent.CancelNote) },764        )765    }766}767768private suspend fun ownedCoverAction(owner: ProfileSession, action: suspend () -> String): String =769    when (val result = owner.runBackgroundWork { action() }) {770        is ProfileWorkResult.Completed -> result.value771        else -> throw CancellationException("Cover owner has retired")772    }773

Search chapters, reference and source filenames.