package eu.friedcutlet.yokan.ui.screens.activity import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowDownward import androidx.compose.material.icons.filled.DownloadDone import androidx.compose.material.icons.filled.ErrorOutline import androidx.compose.material.icons.filled.NewReleases import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.FilterList import eu.friedcutlet.yokan.data.toDb import eu.friedcutlet.yokan.database.DbUpdatesFilter import org.jetbrains.compose.resources.stringResource import yokan.composeapp.generated.resources.Res import yokan.composeapp.generated.resources.action_cancel import yokan.composeapp.generated.resources.action_remove import yokan.composeapp.generated.resources.activity_filters import yokan.composeapp.generated.resources.delete import yokan.composeapp.generated.resources.ok import androidx.compose.material.icons.outlined.DeleteSweep as DeleteSweepOutlined import androidx.compose.material.icons.outlined.Refresh as RefreshOutlined import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.pulltorefresh.PullToRefreshBox import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontStyle 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 androidx.lifecycle.viewmodel.compose.viewModel import eu.friedcutlet.yokan.app.YokanRuntime import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold import kotlinx.coroutines.launch import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import eu.friedcutlet.yokan.ui.formatTimestamp import eu.friedcutlet.yokan.ui.components.AppBarSearchField import eu.friedcutlet.yokan.ui.components.CoverImage import eu.friedcutlet.yokan.ui.components.hoverHighlight import eu.friedcutlet.yokan.ui.components.EmptyState import eu.friedcutlet.yokan.ui.navigation.Navigator import eu.friedcutlet.yokan.ui.navigation.Route @Composable internal fun UpdatesRoute(nav: Navigator) { val viewModel = viewModel { UpdatesViewModel( repository = YokanRuntime.repository, settings = YokanRuntime.settings, libraryIndex = YokanRuntime.libraryIndex, libraryUpdates = YokanRuntime.libraryUpdates, downloads = YokanRuntime.chapterDownloads, ) } val state by viewModel.state.collectAsStateWithLifecycle() val hidden by nav.hiddenSections.collectAsStateWithLifecycle() val itemType by nav.itemType.collectAsStateWithLifecycle() UpdatesScreen( state = state, visibleTypes = remember(hidden) { visibleItemTypes(hidden) }, initialItemType = itemType, onItemTypeSettled = nav::selectItemType, onOpenUpdateErrors = { nav.navigate(Route.UpdateErrors) }, onRefresh = viewModel::refresh, onDismissFailedUpdates = viewModel::dismissFailedUpdates, onClearUpdates = viewModel::clearUpdates, onOpenChapter = { manga, chapter -> nav.navigate(Route.Reader(manga.id, chapter.id)) }, onOpenDetail = { manga -> nav.navigate(Route.Detail(manga.id)) }, onDownload = viewModel::download, onCancelDownload = viewModel::cancelDownload, onRemoveDownload = viewModel::removeDownload, onOpenDownloadLocation = viewModel::openDownloadLocation, onUpdateFilters = viewModel::updateFilters, ) } /** Callbacks of one Updates row, bundled so pages and rows take a single parameter. */ private class UpdateRowActions( val onOpenChapter: (Manga, Chapter) -> Unit, val onOpenDetail: (Manga) -> Unit, val onDownload: (UpdateRowModel) -> Unit, val onCancelDownload: (downloadId: Long) -> Unit, val onRemoveDownload: (downloadId: Long) -> Unit, val onOpenDownloadLocation: (downloadId: Long) -> Unit, ) @OptIn(ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable fun UpdatesScreen( state: UpdatesState, visibleTypes: List, initialItemType: ItemType, onItemTypeSettled: (ItemType) -> Unit, onOpenUpdateErrors: () -> Unit, onRefresh: (ItemType) -> Unit, onDismissFailedUpdates: () -> Unit, onClearUpdates: (ItemType) -> Unit, onOpenChapter: (Manga, Chapter) -> Unit, onOpenDetail: (Manga) -> Unit, onDownload: (UpdateRowModel) -> Unit, onCancelDownload: (downloadId: Long) -> Unit, onRemoveDownload: (downloadId: Long) -> Unit, onOpenDownloadLocation: (downloadId: Long) -> Unit, onUpdateFilters: (ItemType, (DbUpdatesFilter) -> DbUpdatesFilter) -> Unit = { _, _ -> }, ) { if (visibleTypes.isEmpty()) { Scaffold( topBar = { TopAppBar( title = { Text("Updates") }, expandedHeight = 56.dp, colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent), ) }, ) { padding -> EmptyState( modifier = Modifier.fillMaxSize().padding(padding), icon = Icons.Filled.NewReleases, title = "No updates yet", ) } return } val initialPage = remember(visibleTypes, initialItemType) { visibleTypes.indexOf(initialItemType).takeIf { it >= 0 } ?: 0 } val pagerState = rememberPagerState(initialPage = initialPage, pageCount = { visibleTypes.size }) val selectedPage = pagerState.currentPage.coerceIn(visibleTypes.indices) val selectedTab = visibleTypes[selectedPage] var searching by remember { mutableStateOf(false) } var query by remember { mutableStateOf("") } var clearAllOpen by remember { mutableStateOf(false) } var filtersOpen by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() val rowActions = remember(onOpenChapter, onOpenDetail, onDownload, onCancelDownload, onRemoveDownload, onOpenDownloadLocation) { UpdateRowActions(onOpenChapter, onOpenDetail, onDownload, onCancelDownload, onRemoveDownload, onOpenDownloadLocation) } LaunchedEffect(visibleTypes.size) { if (pagerState.currentPage > visibleTypes.lastIndex) { pagerState.scrollToPage(visibleTypes.lastIndex) } } LaunchedEffect(pagerState, visibleTypes) { snapshotFlow { pagerState.settledPage }.collect { page -> val type = visibleTypes.getOrNull(page) ?: return@collect onItemTypeSettled(type) query = "" searching = false } } val entries = remember(state.rowsByType, selectedTab, query) { updateRows(state.rowsByType, selectedTab, query) } val refreshing = state.refreshing val triggerRefresh: () -> Unit = { onRefresh(selectedTab) } Scaffold( topBar = { TopAppBar( expandedHeight = 56.dp, colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent), title = { if (searching) { AppBarSearchField( query = query, placeholder = "Search updates", onQueryChange = { query = it }, onClose = { searching = false query = "" }, ) } else { Text("Updates") } }, actions = { IconButton(onClick = { filtersOpen = true }) { Icon(Icons.Filled.FilterList, stringResource(Res.string.activity_filters), tint = if (state.filters.updates(selectedTab.toDb()).active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant) } if (!searching) { if (state.hasUpdateErrors) { IconButton( modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = onOpenUpdateErrors, ) { Icon( imageVector = Icons.Filled.ErrorOutline, contentDescription = "Update errors", tint = MaterialTheme.colorScheme.error, ) } } IconButton(modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = { searching = true }) { Icon(Icons.Filled.Search, contentDescription = "Search updates") } } IconButton(modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = triggerRefresh, enabled = !refreshing) { Icon(Icons.Outlined.RefreshOutlined, contentDescription = "Refresh library") } IconButton( modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = { clearAllOpen = true }, enabled = entries.isNotEmpty(), ) { Icon(Icons.Outlined.DeleteSweepOutlined, contentDescription = "Clear all updates") } }, ) }, ) { padding -> Column( modifier = Modifier .fillMaxSize() .padding(padding), ) { ItemTypePagerTabRow( types = visibleTypes, pagerState = pagerState, unreadCounts = remember(state.rowsByType) { state.rowsByType.mapValues { (_, rows) -> rows.size } }, onSelect = { index -> if (index != pagerState.currentPage) query = "" scope.launch { pagerState.animateScrollToPage(index) } }, ) PullToRefreshBox( modifier = Modifier.fillMaxSize(), isRefreshing = refreshing, onRefresh = triggerRefresh, ) { HorizontalPager( state = pagerState, beyondViewportPageCount = 1, modifier = Modifier.fillMaxSize(), ) { page -> val type = visibleTypes[page] val pageEntries = remember(state.rowsByType, type, query) { updateRows(state.rowsByType, type, query) } UpdatesPage( entries = pageEntries, query = query, lastUpdatedAt = state.lastUpdatedAt[type], formatTimestamp = { millis -> formatTimestamp(millis, state.dateFormat, state.relativeTimestamps) }, actions = rowActions, ) } } } } if (filtersOpen) { val filter = state.filters.updates(selectedTab.toDb()) ActivityFilterDialog(state.categoriesByType[selectedTab].orEmpty(), filter.categories, onCategoryFilter = { change -> onUpdateFilters(selectedTab) { it.copy(categories = change(it.categories)) } }, onDismiss = { filtersOpen = false }, updatesFilter = filter, onUpdatesFilter = { change -> onUpdateFilters(selectedTab, change) }) } if (clearAllOpen) { eu.friedcutlet.yokan.ui.components.ConfirmDialog( title = "Remove everything", message = "Remove all updates for ${selectedTab.label}?", confirmLabel = stringResource(Res.string.action_remove), danger = true, onConfirm = { onClearUpdates(selectedTab) }, onDismiss = { clearAllOpen = false }, ) } state.failedUpdates?.let { errors -> if (errors.isNotEmpty()) { val plural = if (errors.size == 1) selectedTab.label.lowercase() else "${selectedTab.label.lowercase()}s" androidx.compose.material3.AlertDialog( onDismissRequest = onDismissFailedUpdates, title = { Text("Failed to update ${errors.size} $plural") }, text = { Box(modifier = Modifier.fillMaxWidth().heightIn(max = 240.dp)) { LazyColumn(modifier = Modifier.fillMaxWidth()) { items(errors, key = { it.mangaId }) { err -> Text( text = "• ${err.name}", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(vertical = 2.dp), ) } } } }, confirmButton = { androidx.compose.material3.TextButton(onClick = onDismissFailedUpdates) { Text(stringResource(Res.string.ok)) } }, ) } } } private fun updateRows( rowsByType: Map>, type: ItemType, query: String, ): List { val rows = rowsByType[type].orEmpty() return if (query.isBlank()) rows else rows.filter { it.update.title.contains(query, ignoreCase = true) } } @Composable private fun UpdatesPage( entries: List, query: String, lastUpdatedAt: Long?, formatTimestamp: (Long) -> String, actions: UpdateRowActions, ) { if (entries.isEmpty()) { EmptyState( modifier = Modifier.fillMaxSize(), icon = Icons.Filled.NewReleases, title = if (query.isNotEmpty()) "No matches" else "No recent updates", ) return } val grouped = remember(entries) { groupByDayBucket(entries) { it.update.updatedAt } } LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(top = 11.dp), ) { lastUpdatedAt?.let { updatedAt -> item(key = "last-updated") { Text( text = "Library last updated: ${formatTimestamp(updatedAt)}", style = MaterialTheme.typography.bodyMedium, fontStyle = FontStyle.Italic, color = MaterialTheme.colorScheme.secondary, modifier = Modifier.padding( start = 10.dp, end = 10.dp, top = 10.dp, bottom = 20.dp, ), ) } } grouped.forEach { (bucket, items) -> item(key = "u-$bucket") { DateGroupHeader(bucket) } items(items, key = { it.update.id }) { row -> UpdateRow(row, actions) } } } } @Composable private fun UpdateRow(row: UpdateRowModel, actions: UpdateRowActions) { val manga = row.manga val chapter = row.chapter val title = row.title val chapterName = row.chapterName val isRead = row.isRead Row( modifier = Modifier .fillMaxWidth() .height(55.dp) .hoverHighlight(onClick = { if (manga != null && chapter != null) actions.onOpenChapter(manga, chapter) }) .padding(horizontal = 13.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically, ) { CoverImage( model = manga?.let { it.customCoverImage ?: it.customCoverFromTracker ?: it.imageUrl }, contentDescription = "$title cover", modifier = Modifier .size(width = 40.dp, height = 45.dp) .clip(RoundedCornerShape(5.dp)) .then( if (manga != null) { Modifier.hoverHighlight(onClick = { actions.onOpenDetail(manga) }) } else { Modifier }, ), shape = RoundedCornerShape(5.dp), fallbackInitials = title.split(" ").take(2) .joinToString("") { it.firstOrNull()?.uppercase() ?: "" }, ) Column( modifier = Modifier .weight(1f) .padding(horizontal = 10.dp), verticalArrangement = Arrangement.Center, ) { Text( text = title, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, ) Text( text = chapterName, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, color = if (isRead) { Color.Gray } else { MaterialTheme.colorScheme.onSurface }, ) } if (manga != null && chapter != null) { DownloadStatusIcon( download = row.download, actions = actions, onDownload = { actions.onDownload(row) }, ) } else { Spacer(Modifier.width(35.dp)) } } } @Composable private fun DownloadStatusIcon( download: DbDownload?, actions: UpdateRowActions, onDownload: () -> Unit, ) { var menuExpanded by remember(download?.id) { mutableStateOf(false) } val indicatorColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f) Box( modifier = Modifier .width(35.dp) .height(41.dp) .padding(vertical = 3.dp), contentAlignment = Alignment.Center, ) { if (download == null) { IconButton( modifier = Modifier.size(35.dp), onClick = onDownload, ) { Icon( imageVector = Icons.Filled.ArrowDownward, contentDescription = "Download", modifier = Modifier.size(18.dp), tint = indicatorColor, ) } CircularProgressIndicator( progress = { 1f }, modifier = Modifier.size(20.dp), color = indicatorColor, strokeWidth = 2.dp, ) } else { val completed = download.isDownload == true val succeeded = download.succeeded ?: 0 val total = download.total ?: 0 val progress = if (total > 0) { (succeeded.toFloat() / total.coerceAtLeast(1)).coerceIn(0f, 1f) } else { 0f } val running = download.isStartDownload == true IconButton( modifier = Modifier.size(35.dp), onClick = { menuExpanded = true }, ) { when { completed -> Icon( imageVector = Icons.Filled.DownloadDone, contentDescription = "Downloaded", modifier = Modifier.size(25.dp), tint = indicatorColor, ) succeeded > 0 -> { Icon( imageVector = Icons.Filled.ArrowDownward, contentDescription = "Download in progress", modifier = Modifier.size(18.dp), tint = indicatorColor, ) CircularProgressIndicator( progress = { progress }, modifier = Modifier.size(20.dp), color = indicatorColor, strokeWidth = 2.dp, ) } running -> { Icon( imageVector = Icons.Filled.ArrowDownward, contentDescription = "Download queued", modifier = Modifier.size(18.dp), tint = indicatorColor, ) CircularProgressIndicator( modifier = Modifier.size(20.dp), color = indicatorColor, strokeWidth = 2.dp, ) } else -> Icon( imageVector = Icons.Filled.Refresh, contentDescription = "Download stopped", modifier = Modifier.size(22.dp), tint = MaterialTheme.colorScheme.error, ) } } DropdownMenu( expanded = menuExpanded, onDismissRequest = { menuExpanded = false }, ) { if (completed) { DropdownMenuItem( text = { Text("Send") }, onClick = { menuExpanded = false actions.onOpenDownloadLocation(download.id) }, ) DropdownMenuItem( text = { Text(stringResource(Res.string.delete)) }, onClick = { menuExpanded = false actions.onRemoveDownload(download.id) }, ) } else { DropdownMenuItem( text = { Text("Start downloading") }, onClick = { menuExpanded = false actions.onCancelDownload(download.id) onDownload() }, ) DropdownMenuItem( text = { Text(stringResource(Res.string.action_cancel)) }, onClick = { menuExpanded = false actions.onCancelDownload(download.id) }, ) } } } } }