package eu.friedcutlet.yokan.ui.screens.detail import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.pulltorefresh.PullToRefreshBox import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import eu.friedcutlet.yokan.app.YokanRuntime import eu.friedcutlet.yokan.app.profiles.ProfileSession import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbLocalFolder import eu.friedcutlet.yokan.database.configuredLocalFolders import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.extensions.webViewUserAgent import eu.friedcutlet.yokan.services.library.ChapterFilterKind import eu.friedcutlet.yokan.services.library.chapterFilters import eu.friedcutlet.yokan.services.library.scanlatorFilter import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult import eu.friedcutlet.yokan.ui.components.ErrorState import eu.friedcutlet.yokan.ui.components.LoadingState import eu.friedcutlet.yokan.ui.components.ScrollbarBox import eu.friedcutlet.yokan.ui.navigation.MissingRoute import eu.friedcutlet.yokan.ui.navigation.Navigator import eu.friedcutlet.yokan.ui.navigation.Route import eu.friedcutlet.yokan.ui.navigation.SettingsPage import kotlinx.coroutines.CancellationException import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold @Composable internal fun DetailRoute(route: Route.Detail, nav: Navigator) { val owner = remember { YokanRuntime.activeSession } val viewModel = viewModel { DetailViewModel( mangaId = route.mangaId, repository = owner.repository, settings = owner.settings, libraryIndex = owner.libraryIndex, downloads = owner.chapterDownloads, metadata = owner.services.metadata, runtimeFactory = owner.services.extensionRuntimeFactory, database = owner.database, allTrackers = owner.services.trackers, files = owner.localFiles, together = owner.together, togetherHttp = owner.services.http, ) } val snackbarHostState = remember { SnackbarHostState() } val lifecycleOwner = LocalLifecycleOwner.current LaunchedEffect(lifecycleOwner, viewModel) { lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.effects.collect { effect -> when (effect) { is DetailEffect.ShowMessage -> snackbarHostState.showSnackbar(effect.text) DetailEffect.OpenTogetherSettings -> nav.navigate(Route.Settings(SettingsPage.Together)) } } } } val state = viewModel.state.collectAsStateWithLifecycle().value ?: return MissingRoute("Title Detail", nav::back) DetailScreen( state = state, snackbarHostState = snackbarHostState, downloadRoot = owner.localFiles.downloadRoot, onEvent = viewModel::onEvent, onNavigate = nav::navigate, onLibrarySearch = { genre -> nav.showLibrary(state.content.manga.itemType, "genre:${genre.trim()}") }, onBack = nav::back, onSaveCover = { manga -> ownedCoverAction(owner) { saveDetailCover(manga, owner) } }, onShareCover = { manga -> ownedCoverAction(owner) { shareDetailCover(manga, owner) } }, onChangeCover = { callback -> ownedCoverAction(owner) { changeDetailCover(callback, owner) } }, ) } /** The one dialog or sheet the detail screen shows at a time; the note editor follows [DetailState.noteDraft]. */ private sealed interface DetailDialog { data object Cover : DetailDialog data object Filter : DetailDialog data object Tracker : DetailDialog data object SmartUpdate : DetailDialog /** [favoriteAfter] favourites the title once the categories are saved. */ data class Categories(val favoriteAfter: Boolean) : DetailDialog data object Range : DetailDialog data object Delete : DetailDialog data class Destination(val request: PendingDownloadRequest) : DetailDialog } /** * Detail screen for manga, anime, and novels. Its responsive title header, * flat chapter list, action strip, and selection controls mirror Mangayomi's * detail hierarchy; data and actions come from [DetailViewModel] as [state] and [onEvent]. */ @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun DetailScreen( state: DetailState, snackbarHostState: SnackbarHostState, /** The app's default download folder, offered by the destination picker. */ downloadRoot: String, onEvent: (DetailEvent) -> Unit, onNavigate: (Route) -> Unit, onLibrarySearch: (genre: String) -> Unit, onBack: () -> Unit, onSaveCover: suspend (Manga) -> String, onShareCover: suspend (Manga) -> String, onChangeCover: suspend ((ByteArray) -> Unit) -> String, ) { val content = state.content val current = content.manga val settings = content.settings val isLocalEntry = current.isLocalArchive val source = content.source val showRemoteActions = !isLocalEntry val chapters = content.chapters val chapterFilters = settings.chapterFilters(current) val filteringActive = ChapterFilterKind.entries.any { chapterFilters.value(it) != 0 } || settings.scanlatorFilter(current.id).isNotEmpty() val loading = state.loading val error = state.error var dialog by remember(current.id) { mutableStateOf(null) } val selectedChapters = state.selection.ids val selectionActions: @Composable () -> Unit = { ChapterSelectionMenu( enabled = chapters.isNotEmpty(), hasSelection = selectedChapters.isNotEmpty(), hasAnchor = state.selection.anchorId != null, onSelect = { onEvent(DetailEvent.Select(it)) }, onRange = { dialog = DetailDialog.Range }, ) } var descriptionExpanded by remember(current.id) { mutableStateOf(false) } var fabExpanded by remember(current.id) { mutableStateOf(true) } val chapterListState = rememberLazyListState() val chapterItemSizes = remember(current.id) { mutableStateMapOf() } val density = LocalDensity.current val appBarTitleThresholdPx = remember(density) { with(density) { 200.dp.roundToPx() } } val showAppBarTitle by remember(chapterListState, chapterItemSizes, appBarTitleThresholdPx) { derivedStateOf { val layoutInfo = chapterListState.layoutInfo val firstVisibleItem = layoutInfo.visibleItemsInfo.firstOrNull() ?: return@derivedStateOf false var scrollDistance = layoutInfo.viewportStartOffset - firstVisibleItem.offset var index = 0 while ( index < firstVisibleItem.index && scrollDistance <= appBarTitleThresholdPx ) { val itemSize = chapterItemSizes[index] ?: return@derivedStateOf true scrollDistance += itemSize index += 1 } scrollDistance > appBarTitleThresholdPx } } LaunchedEffect(current.id, chapterListState) { chapterListState.scrollToItem(0) snapshotFlow { chapterListState.layoutInfo.visibleItemsInfo.map { it.index to it.size } }.collect { visibleItemSizes -> visibleItemSizes.forEach { (index, size) -> chapterItemSizes[index] = size } } } LaunchedEffect(current.id, chapterListState) { var previous = chapterListState.firstVisibleItemIndex to chapterListState.firstVisibleItemScrollOffset snapshotFlow { Triple( chapterListState.firstVisibleItemIndex, chapterListState.firstVisibleItemScrollOffset, chapterListState.isScrollInProgress, ) }.collect { (index, offset, scrolling) -> val currentPosition = index to offset if (scrolling && currentPosition != previous) { fabExpanded = index < previous.first || (index == previous.first && offset < previous.second) } if (index == 0 && offset == 0) fabExpanded = true previous = currentPosition } } LaunchedEffect(error) { error?.takeIf { it.isNotBlank() }?.let { msg -> snackbarHostState.showSnackbar(msg) } } val unreadChapter = remember(chapters) { chapters.firstOrNull { !it.isRead } } val seasonTitles = content.seasonTitles // A Seasons-type title resumes in its first season with an unwatched episode. val resumeTarget = unreadChapter?.let { current.id to it.id } ?: seasonTitles.firstNotNullOfOrNull { season -> season.continueChapter?.let { season.title.id to it.id } } val hasReadingHistory = remember(chapters, seasonTitles) { chapters.any { it.isRead || it.lastPageRead.isNotBlank() } || seasonTitles.any { it.watchedCount > 0 } } val categories = content.categories val configuredDownloadFolders = remember(settings) { settings.configuredLocalFolders() } fun shouldAskDownloadDestination(): Boolean = settings.askDownloadDestination && configuredDownloadFolders.isNotEmpty() fun requestDownload(chapter: Chapter) { if (shouldAskDownloadDestination()) { dialog = DetailDialog.Destination(PendingDownloadRequest.Single(chapter)) } else { onEvent(DetailEvent.Download(chapter, destinationRoot = null)) } } fun requestDownloads(targetChapters: List, option: DetailDownloadOption) { if (shouldAskDownloadDestination() && targetChapters.any { it.downloadSize == null }) { dialog = DetailDialog.Destination(PendingDownloadRequest.Bulk(targetChapters, option)) } else { onEvent(DetailEvent.DownloadAll(targetChapters, option, destinationRoot = null)) } } fun toggleChapterSelection(chapter: Chapter) = onEvent(DetailEvent.ToggleSelection(chapter.id)) fun selectRangeTo(chapter: Chapter) = onEvent(DetailEvent.SelectRangeTo(chapter.id)) fun openWebView() { val webUrl = current.link.takeIf { it.startsWith("http", ignoreCase = true) } ?: source?.baseUrl?.takeIf { it.isNotBlank() } ?: return onNavigate(Route.InAppWebView(webUrl, current.name, settings.webViewUserAgent(source).takeIf { it.isNotBlank() })) } val chapterRow: @Composable (Chapter) -> Unit = { chapter -> ChapterRow( chapter = chapter, itemType = current.itemType, uploadDate = formatChapterDate(chapter.dateUpload, settings), selected = chapter.id in selectedChapters, anySelected = selectedChapters.isNotEmpty(), onClick = { if (selectedChapters.isNotEmpty()) { toggleChapterSelection(chapter) } else { onNavigate(Route.Reader(current.id, chapter.id)) } }, onLongClick = { if (selectedChapters.isEmpty()) toggleChapterSelection(chapter) else selectRangeTo(chapter) }, onSecondaryClick = { shiftPressed -> if (shiftPressed && selectedChapters.isNotEmpty()) { selectRangeTo(chapter) } else { toggleChapterSelection(chapter) } }, onBookmark = { onEvent(DetailEvent.SetBookmarked(setOf(chapter.id), !chapter.isBookmarked)) }, onReadToggle = { onEvent(DetailEvent.SetRead(setOf(chapter.id), !chapter.isRead)) }, showDownload = showRemoteActions, onDownload = { requestDownload(chapter) }, ) } fun editCategories() { if (categories.isEmpty()) return dialog = DetailDialog.Categories(favoriteAfter = !current.favorite) } fun toggleFavorite() { val defaultId = settings.features.library.defaultCategory( when (current.itemType) { ItemType.Manga -> DbItemType.Manga ItemType.Anime -> DbItemType.Anime ItemType.Novel -> DbItemType.Novel }, ) val hasDefault = defaultId == 0L || categories.any { it.id == defaultId } if (!current.favorite && categories.isNotEmpty() && !hasDefault) { editCategories() } else { onEvent(DetailEvent.SetFavorite(!current.favorite)) } } val infoBlocks: @Composable (spacing: Dp) -> Unit = { spacing -> DetailInfoBlocks( content = content, loading = loading, error = error, showRemoteActions = showRemoteActions, descriptionExpanded = descriptionExpanded, spacing = spacing, onToggleDescription = { descriptionExpanded = !descriptionExpanded }, onFavorite = ::toggleFavorite, onFavoriteLongClick = if (categories.isNotEmpty()) ::editCategories else null, onSmartUpdate = { dialog = DetailDialog.SmartUpdate }, onTrack = { dialog = DetailDialog.Tracker }, onWeb = ::openWebView, onEvent = onEvent, onNavigate = onNavigate, onLibrarySearch = onLibrarySearch, ) } val chapterItems: LazyListScope.() -> Unit = { detailChapterItems(content, selectionActions, onEvent, onNavigate, chapterRow) } Scaffold( topBar = { if (selectedChapters.isEmpty()) { DetailTopBar( manga = current, source = source, showTitle = showAppBarTitle, showRemoteActions = showRemoteActions, filteringActive = filteringActive, metadataEnabled = settings.metadataServerUrl.startsWith("http"), canSetCategories = current.favorite && categories.isNotEmpty(), togetherRoom = state.togetherRoom, onBack = onBack, onDownload = { option -> requestDownloads(chaptersForDownloadOption(chapters, option), option) }, onFilter = { dialog = DetailDialog.Filter }, onSetCategories = { dialog = DetailDialog.Categories(favoriteAfter = false) }, onEvent = onEvent, onNavigate = onNavigate, ) } else { ChapterSelectionTopBar( selectedCount = selectedChapters.size, onClear = { onEvent(DetailEvent.ClearSelection) }, selectionActions = selectionActions, ) } }, bottomBar = { if (selectedChapters.isNotEmpty()) { val selectedModels = chapters.filter { it.id in selectedChapters } val singleSelection = selectedModels.singleOrNull() ChapterSelectionBottomBar( bookmarked = singleSelection?.isBookmarked == true, read = singleSelection?.isRead == true, showDownload = showRemoteActions && selectedModels.none { it.downloadSize != null || it.archivePath.isNotBlank() }, showDelete = isLocalEntry || selectedModels.any { it.downloadSize != null || it.archivePath.isNotBlank() }, filler = selectedModels.all { it.isFiller }.takeIf { current.itemType == ItemType.Anime }, showFillerReset = selectedModels.any { it.fillerOverride != null }, onBookmark = { onEvent(DetailEvent.ToggleSelectedBookmarks) }, onMarkRead = { onEvent(DetailEvent.ToggleSelectedRead) }, onFiller = { onEvent(DetailEvent.SetFiller(selectedModels.map { it.id }.toSet(), !selectedModels.all { it.isFiller })) onEvent(DetailEvent.ClearSelection) }, onResetFiller = { onEvent(DetailEvent.SetFiller(selectedModels.map { it.id }.toSet(), null)) onEvent(DetailEvent.ClearSelection) }, onDownload = { requestDownloads(selectedModels, DetailDownloadOption.Selected) onEvent(DetailEvent.ClearSelection) }, onDelete = { dialog = DetailDialog.Delete }, ) } }, floatingActionButton = { if (resumeTarget != null && selectedChapters.isEmpty()) { ExtendedFloatingActionButton( onClick = { onNavigate(Route.Reader(resumeTarget.first, resumeTarget.second)) }, expanded = fabExpanded, icon = { Icon( Icons.Filled.PlayArrow, contentDescription = null, modifier = Modifier.size(22.dp), ) }, text = { Text( if (hasReadingHistory) "Resume" else "Start", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold, ) }, // The FAB defaults to MaterialTheme.shapes.large which now // rounds to 20dp; bump to the extra-large 28dp so it reads // as a clear primary CTA against the chapter list. shape = MaterialTheme.shapes.extraLarge, containerColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.onPrimary, elevation = FloatingActionButtonDefaults.elevation( defaultElevation = 6.dp, pressedElevation = 10.dp, focusedElevation = 8.dp, hoveredElevation = 10.dp, ), ) } }, snackbarHost = { SnackbarHost(snackbarHostState) }, ) { paddingValues -> BoxWithConstraints(Modifier.fillMaxSize()) { val usePhoneLayout = maxWidth < 720.dp // Phone layout: skip the top padding so the backdrop header draws // behind the transparent TopAppBar up to y=0 (Mangayomi parity). // Desktop layout has no backdrop, so it keeps the full padding. val layoutDirection = LocalLayoutDirection.current val contentModifier = Modifier.fillMaxSize().padding( if (usePhoneLayout) { PaddingValues( start = paddingValues.calculateStartPadding(layoutDirection), end = paddingValues.calculateEndPadding(layoutDirection), bottom = paddingValues.calculateBottomPadding(), ) } else { paddingValues }, ) // Mangayomi refreshes the title with a swipe (RefreshIndicator around // the detail body); the overflow "Refresh" action stays for desktop. PullToRefreshBox( isRefreshing = loading, onRefresh = { onEvent(DetailEvent.Refresh) }, modifier = contentModifier, ) { if (loading) { LinearProgressIndicator( modifier = Modifier.fillMaxWidth().align(Alignment.TopCenter), ) } if (usePhoneLayout) { ScrollbarBox(state = chapterListState, modifier = Modifier.fillMaxSize()) { LazyColumn(state = chapterListState, modifier = Modifier.fillMaxSize()) { item(key = "header") { DetailBackdropHeader( manga = current, showSource = showRemoteActions, onTitleSelected = { title -> onEvent(DetailEvent.SetDisplayTitle(title)) }, onCoverClick = { dialog = DetailDialog.Cover }, ) } item(key = "info") { infoBlocks(0.dp) } chapterItems() } } } else { val detailScroll = rememberScrollState() Row(modifier = Modifier.fillMaxSize()) { ScrollbarBox(state = detailScroll, modifier = Modifier.weight(0.5f).fillMaxHeight()) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(detailScroll) .padding(bottom = 96.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { DetailSideHeader( manga = current, showSource = showRemoteActions, onTitleSelected = { title -> onEvent(DetailEvent.SetDisplayTitle(title)) }, onCoverClick = { dialog = DetailDialog.Cover }, ) infoBlocks(6.dp) } } ScrollbarBox(state = chapterListState, modifier = Modifier.weight(0.5f).fillMaxHeight()) { LazyColumn(state = chapterListState, modifier = Modifier.fillMaxSize()) { chapterItems() } } } } } } } DetailDialogs( dialog = dialog, state = state, downloadRoot = downloadRoot, downloadFolders = configuredDownloadFolders, onDismiss = { dialog = null }, onEvent = onEvent, onBack = onBack, onSaveCover = onSaveCover, onShareCover = onShareCover, onChangeCover = onChangeCover, ) } /** Title action strip, note, description, genres, related links, cast, and refresh status; shared by both layouts. */ @Composable private fun DetailInfoBlocks( content: DetailContent, loading: Boolean, error: String?, showRemoteActions: Boolean, descriptionExpanded: Boolean, spacing: Dp, onToggleDescription: () -> Unit, onFavorite: () -> Unit, onFavoriteLongClick: (() -> Unit)?, onSmartUpdate: () -> Unit, onTrack: () -> Unit, onWeb: () -> Unit, onEvent: (DetailEvent) -> Unit, onNavigate: (Route) -> Unit, onLibrarySearch: (genre: String) -> Unit, ) { val manga = content.manga Column(verticalArrangement = Arrangement.spacedBy(spacing)) { DetailActionRow( manga = manga, trackCount = content.tracks.size, showWeb = showRemoteActions, onFavorite = onFavorite, onFavoriteLongClick = onFavoriteLongClick, automaticUpdateDays = content.automaticUpdateDays, onSmartUpdate = onSmartUpdate, onTrack = onTrack, onMigrate = { onNavigate(Route.Migrate(manga.id)) }, onWeb = onWeb, ) if (manga.favorite) { DetailNotePreview(note = manga.privateNote, onEdit = { onEvent(DetailEvent.EditNote) }) } if (manga.description.isNotBlank()) { DetailDescription(text = manga.description, expanded = descriptionExpanded, onToggle = onToggleDescription) } if (manga.genres.isNotEmpty()) { Box(modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { DetailGenreTags( tags = manga.genres, sources = content.genreSources, onLibrarySearch = onLibrarySearch, onSourceSearch = { destination, tag -> onNavigate(Route.SourceHome(destination.id, tag)) }, ) } } DetailRelatedActions( itemType = manga.itemType, hasTracks = content.tracks.isNotEmpty(), onRecommendations = { onNavigate(Route.Recommendations(manga.id)) }, onWatchOrder = { onNavigate(Route.WatchOrder(manga.id)) }, onSequels = { onNavigate(Route.Sequels(manga.id)) }, ) if (manga.cast.isNotEmpty()) TitleCastCredits(manga.cast) if (loading) LoadingState(label = "Refreshing details…") if (!error.isNullOrBlank()) { ErrorState( message = error, onRetry = { onEvent(DetailEvent.Refresh) }, openInBrowserUrl = content.source?.baseUrl, ) } } } /** Season records or the chapter heading, season filter, and chapter rows; shared by both layouts. */ private fun LazyListScope.detailChapterItems( content: DetailContent, selectionActions: @Composable () -> Unit, onEvent: (DetailEvent) -> Unit, onNavigate: (Route) -> Unit, chapterRow: @Composable (Chapter) -> Unit, ) { val manga = content.manga if (manga.fetchesSeasons) { item(key = "season-header") { DetailSeasonsHeader(content.seasonTitles.size) } items(content.seasonTitles, key = { "season-title-${it.title.id}" }, contentType = { "season-title" }) { season -> DetailSeasonRow( season, onOpen = { onNavigate(Route.Detail(season.title.id)) }, onContinue = { season.continueChapter?.let { onNavigate(Route.Reader(season.title.id, it.id)) } }, ) } } else { // Sort and filters live in the app-bar sheet. item(key = "chapter-header") { ChaptersHeaderRow( label = chapterLabel(manga.itemType), selectionActions = selectionActions, count = content.chapters.size, missingCount = content.missingChapterCount, unnumberedCount = content.unnumberedChapterCount, ) } } if (content.seasons.isNotEmpty()) item(key = "seasons") { EpisodeSeasonSelector(content.seasons, content.selectedSeason, { onEvent(DetailEvent.SelectSeason(it)) }) } if (content.loaded && content.chapters.isEmpty() && !manga.fetchesSeasons) { item(key = "empty-chapters") { EmptyChaptersCard(manga.itemType) } } items(content.chapters, key = { it.id }) { chapter -> chapterRow(chapter) } // Trailing spacer so the last row clears the extended FAB. item(key = "trailing-spacer") { Spacer(Modifier.height(96.dp)) } } @Composable private fun DetailDialogs( dialog: DetailDialog?, state: DetailState, downloadRoot: String, downloadFolders: List, onDismiss: () -> Unit, onEvent: (DetailEvent) -> Unit, onBack: () -> Unit, onSaveCover: suspend (Manga) -> String, onShareCover: suspend (Manga) -> String, onChangeCover: suspend ((ByteArray) -> Unit) -> String, ) { val content = state.content val current = content.manga val settings = content.settings when (dialog) { null -> Unit DetailDialog.Cover -> current.detailCoverModel()?.let { model -> CoverInspectionDialog( title = current.name, identity = listOf( current.id, current.customCoverImage?.contentHashCode(), current.customCoverFromTracker, current.imageUrl, ), model = model, onDismiss = onDismiss, onSave = { onSaveCover(current) }, onChange = { onChangeCover { bytes -> onEvent(DetailEvent.SetCustomCover(bytes)) } }, onShare = { onShareCover(current) }, ) } DetailDialog.Filter -> ChapterFilterSheet( manga = current, settings = settings, scanlators = content.scanlators, onSort = { onEvent(DetailEvent.ToggleSort(it)) }, onCycleFilter = { onEvent(DetailEvent.CycleFilter(it)) }, onToggleScanlator = { onEvent(DetailEvent.ToggleScanlator(it)) }, showAllReleases = state.showAllReleases, onShowAllReleases = { onEvent(DetailEvent.ShowAllReleases(it)) }, onSkipDuplicates = { onEvent(DetailEvent.SetSkipDuplicates(it)) }, onMoveScanlator = { name, direction -> onEvent(DetailEvent.MoveScanlator(name, direction)) }, onResetReleaseOverride = { onEvent(DetailEvent.ResetReleaseOverride) }, onSetAsDefault = { onEvent(DetailEvent.SetChapterListDefault(it)) }, onDismiss = onDismiss, ) DetailDialog.Tracker -> TrackerSearchDialog( manga = current, trackerNames = state.trackerNames, search = state.trackerSearch, onSearch = { trackerIndex, query -> onEvent(DetailEvent.SearchTracker(trackerIndex, query)) }, onBind = { trackerIndex, result -> onEvent(DetailEvent.BindTrack(trackerIndex, result)) }, onDismiss = { onDismiss() onEvent(DetailEvent.CloseTrackerSearch) }, ) DetailDialog.Range -> ChapterRangeDialog(content.chapters, onSelect = { first, last -> onEvent(DetailEvent.SelectRange(first, last)) onDismiss() }, onDismiss = onDismiss) DetailDialog.SmartUpdate -> SmartUpdateDialog( manualDays = current.smartUpdateDays, automaticDays = content.automaticUpdateDays, onChange = { onEvent(DetailEvent.SetSmartUpdateDays(it)) }, onDismiss = onDismiss, ) is DetailDialog.Categories -> CategoryEditorSheet( manga = current, categories = content.categories, onSave = { categoryIds -> onEvent(DetailEvent.SetCategories(categoryIds, favorite = dialog.favoriteAfter)) }, onDismiss = onDismiss, ) is DetailDialog.Destination -> DownloadDestinationDialog( title = "Download destination", folders = downloadFolders, defaultRoot = downloadRoot, selectedName = settings.downloadLocalFolderName, onSelect = { folderName -> // Blank means the app's default root; null would mean the folder selected in settings. val folderPath = downloadFolders.firstOrNull { it.name == folderName }?.path.orEmpty() onDismiss() when (val request = dialog.request) { is PendingDownloadRequest.Single -> onEvent(DetailEvent.Download(request.chapter, folderPath)) is PendingDownloadRequest.Bulk -> onEvent(DetailEvent.DownloadAll(request.chapters, request.option, folderPath)) } }, onDismiss = onDismiss, ) DetailDialog.Delete -> { val selectedCount = state.selection.ids.size val isLocalLast = current.isLocalArchive && selectedCount >= content.chapters.size DeleteChaptersDialog( isLocalEntry = current.isLocalArchive, deletesEntry = isLocalLast, selectedCount = selectedCount, itemType = current.itemType, onConfirm = { onDismiss() onEvent(DetailEvent.DeleteSelected(removeEntry = isLocalLast)) if (isLocalLast) onBack() }, onDismiss = onDismiss, ) } } state.noteDraft?.takeIf { current.favorite }?.let { draft -> DetailNoteEditor( draft = draft, onChange = { onEvent(DetailEvent.ChangeNote(it)) }, onSave = { onEvent(DetailEvent.SaveNote) }, onCancel = { onEvent(DetailEvent.CancelNote) }, ) } } private suspend fun ownedCoverAction(owner: ProfileSession, action: suspend () -> String): String = when (val result = owner.runBackgroundWork { action() }) { is ProfileWorkResult.Completed -> result.value else -> throw CancellationException("Cover owner has retired") }