UpdatesScreen.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/UpdatesScreen.kt
1package eu.friedcutlet.yokan.ui.screens.activity23import androidx.compose.foundation.layout.Arrangement4import androidx.compose.foundation.layout.Box5import androidx.compose.foundation.layout.Column6import androidx.compose.foundation.layout.PaddingValues7import androidx.compose.foundation.layout.Row8import androidx.compose.foundation.layout.Spacer9import androidx.compose.foundation.layout.fillMaxSize10import androidx.compose.foundation.layout.fillMaxWidth11import androidx.compose.foundation.layout.height12import androidx.compose.foundation.layout.heightIn13import androidx.compose.foundation.layout.offset14import androidx.compose.foundation.layout.padding15import androidx.compose.foundation.layout.size16import androidx.compose.foundation.layout.width17import androidx.compose.foundation.lazy.LazyColumn18import androidx.compose.foundation.lazy.items19import androidx.compose.foundation.pager.HorizontalPager20import androidx.compose.foundation.pager.rememberPagerState21import androidx.compose.foundation.shape.RoundedCornerShape22import androidx.compose.material.icons.Icons23import androidx.compose.material.icons.filled.ArrowDownward24import androidx.compose.material.icons.filled.DownloadDone25import androidx.compose.material.icons.filled.ErrorOutline26import androidx.compose.material.icons.filled.NewReleases27import androidx.compose.material.icons.filled.Refresh28import androidx.compose.material.icons.filled.Search29import androidx.compose.material.icons.filled.FilterList30import eu.friedcutlet.yokan.data.toDb31import eu.friedcutlet.yokan.database.DbUpdatesFilter32import org.jetbrains.compose.resources.stringResource33import yokan.composeapp.generated.resources.Res34import yokan.composeapp.generated.resources.action_cancel35import yokan.composeapp.generated.resources.action_remove36import yokan.composeapp.generated.resources.activity_filters37import yokan.composeapp.generated.resources.delete38import yokan.composeapp.generated.resources.ok39import androidx.compose.material.icons.outlined.DeleteSweep as DeleteSweepOutlined40import androidx.compose.material.icons.outlined.Refresh as RefreshOutlined41import androidx.compose.material3.CircularProgressIndicator42import androidx.compose.material3.DropdownMenu43import androidx.compose.material3.DropdownMenuItem44import androidx.compose.material3.ExperimentalMaterial3Api45import androidx.compose.material3.Icon46import androidx.compose.material3.IconButton47import androidx.compose.material3.MaterialTheme48import androidx.compose.material3.Text49import androidx.compose.material3.TopAppBar50import androidx.compose.material3.TopAppBarDefaults51import androidx.compose.material3.pulltorefresh.PullToRefreshBox52import androidx.compose.runtime.Composable53import androidx.compose.runtime.LaunchedEffect54import androidx.compose.runtime.mutableStateOf55import androidx.compose.runtime.remember56import androidx.compose.runtime.rememberCoroutineScope57import androidx.compose.runtime.snapshotFlow58import androidx.compose.ui.Alignment59import androidx.compose.ui.Modifier60import androidx.compose.ui.draw.clip61import androidx.compose.ui.graphics.Color62import androidx.compose.ui.text.font.FontStyle63import androidx.compose.ui.text.style.TextOverflow64import androidx.compose.ui.unit.dp65import androidx.compose.ui.unit.sp66import androidx.lifecycle.compose.collectAsStateWithLifecycle67import androidx.lifecycle.viewmodel.compose.viewModel68import eu.friedcutlet.yokan.app.YokanRuntime69import eu.friedcutlet.yokan.database.DbDownload70import eu.friedcutlet.yokan.domain.Chapter71import eu.friedcutlet.yokan.domain.ItemType72import eu.friedcutlet.yokan.domain.Manga73import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold74import kotlinx.coroutines.launch75import androidx.compose.runtime.getValue76import androidx.compose.runtime.setValue77import eu.friedcutlet.yokan.ui.formatTimestamp78import eu.friedcutlet.yokan.ui.components.AppBarSearchField79import eu.friedcutlet.yokan.ui.components.CoverImage80import eu.friedcutlet.yokan.ui.components.hoverHighlight81import eu.friedcutlet.yokan.ui.components.EmptyState82import eu.friedcutlet.yokan.ui.navigation.Navigator83import eu.friedcutlet.yokan.ui.navigation.Route8485@Composable86internal fun UpdatesRoute(nav: Navigator) {87 val viewModel = viewModel {88 UpdatesViewModel(89 repository = YokanRuntime.repository,90 settings = YokanRuntime.settings,91 libraryIndex = YokanRuntime.libraryIndex,92 libraryUpdates = YokanRuntime.libraryUpdates,93 downloads = YokanRuntime.chapterDownloads,94 )95 }96 val state by viewModel.state.collectAsStateWithLifecycle()97 val hidden by nav.hiddenSections.collectAsStateWithLifecycle()98 val itemType by nav.itemType.collectAsStateWithLifecycle()99 UpdatesScreen(100 state = state,101 visibleTypes = remember(hidden) { visibleItemTypes(hidden) },102 initialItemType = itemType,103 onItemTypeSettled = nav::selectItemType,104 onOpenUpdateErrors = { nav.navigate(Route.UpdateErrors) },105 onRefresh = viewModel::refresh,106 onDismissFailedUpdates = viewModel::dismissFailedUpdates,107 onClearUpdates = viewModel::clearUpdates,108 onOpenChapter = { manga, chapter -> nav.navigate(Route.Reader(manga.id, chapter.id)) },109 onOpenDetail = { manga -> nav.navigate(Route.Detail(manga.id)) },110 onDownload = viewModel::download,111 onCancelDownload = viewModel::cancelDownload,112 onRemoveDownload = viewModel::removeDownload,113 onOpenDownloadLocation = viewModel::openDownloadLocation,114 onUpdateFilters = viewModel::updateFilters,115 )116}117118/** Callbacks of one Updates row, bundled so pages and rows take a single parameter. */119private class UpdateRowActions(120 val onOpenChapter: (Manga, Chapter) -> Unit,121 val onOpenDetail: (Manga) -> Unit,122 val onDownload: (UpdateRowModel) -> Unit,123 val onCancelDownload: (downloadId: Long) -> Unit,124 val onRemoveDownload: (downloadId: Long) -> Unit,125 val onOpenDownloadLocation: (downloadId: Long) -> Unit,126)127128@OptIn(ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class)129@Composable130fun UpdatesScreen(131 state: UpdatesState,132 visibleTypes: List<ItemType>,133 initialItemType: ItemType,134 onItemTypeSettled: (ItemType) -> Unit,135 onOpenUpdateErrors: () -> Unit,136 onRefresh: (ItemType) -> Unit,137 onDismissFailedUpdates: () -> Unit,138 onClearUpdates: (ItemType) -> Unit,139 onOpenChapter: (Manga, Chapter) -> Unit,140 onOpenDetail: (Manga) -> Unit,141 onDownload: (UpdateRowModel) -> Unit,142 onCancelDownload: (downloadId: Long) -> Unit,143 onRemoveDownload: (downloadId: Long) -> Unit,144 onOpenDownloadLocation: (downloadId: Long) -> Unit,145 onUpdateFilters: (ItemType, (DbUpdatesFilter) -> DbUpdatesFilter) -> Unit = { _, _ -> },146) {147 if (visibleTypes.isEmpty()) {148 Scaffold(149 topBar = {150 TopAppBar(151 title = { Text("Updates") },152 expandedHeight = 56.dp,153 colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),154 )155 },156 ) { padding ->157 EmptyState(158 modifier = Modifier.fillMaxSize().padding(padding),159 icon = Icons.Filled.NewReleases,160 title = "No updates yet",161 )162 }163 return164 }165166 val initialPage = remember(visibleTypes, initialItemType) {167 visibleTypes.indexOf(initialItemType).takeIf { it >= 0 } ?: 0168 }169 val pagerState = rememberPagerState(initialPage = initialPage, pageCount = { visibleTypes.size })170 val selectedPage = pagerState.currentPage.coerceIn(visibleTypes.indices)171 val selectedTab = visibleTypes[selectedPage]172173 var searching by remember { mutableStateOf(false) }174 var query by remember { mutableStateOf("") }175 var clearAllOpen by remember { mutableStateOf(false) }176 var filtersOpen by remember { mutableStateOf(false) }177 val scope = rememberCoroutineScope()178 val rowActions = remember(onOpenChapter, onOpenDetail, onDownload, onCancelDownload, onRemoveDownload, onOpenDownloadLocation) {179 UpdateRowActions(onOpenChapter, onOpenDetail, onDownload, onCancelDownload, onRemoveDownload, onOpenDownloadLocation)180 }181182 LaunchedEffect(visibleTypes.size) {183 if (pagerState.currentPage > visibleTypes.lastIndex) {184 pagerState.scrollToPage(visibleTypes.lastIndex)185 }186 }187188 LaunchedEffect(pagerState, visibleTypes) {189 snapshotFlow { pagerState.settledPage }.collect { page ->190 val type = visibleTypes.getOrNull(page) ?: return@collect191 onItemTypeSettled(type)192 query = ""193 searching = false194 }195 }196197 val entries = remember(state.rowsByType, selectedTab, query) {198 updateRows(state.rowsByType, selectedTab, query)199 }200 val refreshing = state.refreshing201 val triggerRefresh: () -> Unit = { onRefresh(selectedTab) }202203 Scaffold(204 topBar = {205 TopAppBar(206 expandedHeight = 56.dp,207 colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),208 title = {209 if (searching) {210 AppBarSearchField(211 query = query,212 placeholder = "Search updates",213 onQueryChange = { query = it },214 onClose = {215 searching = false216 query = ""217 },218 )219 } else {220 Text("Updates")221 }222 },223 actions = {224 IconButton(onClick = { filtersOpen = true }) {225 Icon(Icons.Filled.FilterList, stringResource(Res.string.activity_filters),226 tint = if (state.filters.updates(selectedTab.toDb()).active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant)227 }228 if (!searching) {229 if (state.hasUpdateErrors) {230 IconButton(231 modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp),232 onClick = onOpenUpdateErrors,233 ) {234 Icon(235 imageVector = Icons.Filled.ErrorOutline,236 contentDescription = "Update errors",237 tint = MaterialTheme.colorScheme.error,238 )239 }240 }241 IconButton(modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = { searching = true }) {242 Icon(Icons.Filled.Search, contentDescription = "Search updates")243 }244 }245 IconButton(modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = triggerRefresh, enabled = !refreshing) {246 Icon(Icons.Outlined.RefreshOutlined, contentDescription = "Refresh library")247 }248 IconButton(249 modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp),250 onClick = { clearAllOpen = true },251 enabled = entries.isNotEmpty(),252 ) {253 Icon(Icons.Outlined.DeleteSweepOutlined, contentDescription = "Clear all updates")254 }255 },256 )257 },258 ) { padding ->259 Column(260 modifier = Modifier261 .fillMaxSize()262 .padding(padding),263 ) {264 ItemTypePagerTabRow(265 types = visibleTypes,266 pagerState = pagerState,267 unreadCounts = remember(state.rowsByType) {268 state.rowsByType.mapValues { (_, rows) -> rows.size }269 },270 onSelect = { index ->271 if (index != pagerState.currentPage) query = ""272 scope.launch { pagerState.animateScrollToPage(index) }273 },274 )275 PullToRefreshBox(276 modifier = Modifier.fillMaxSize(),277 isRefreshing = refreshing,278 onRefresh = triggerRefresh,279 ) {280 HorizontalPager(281 state = pagerState,282 beyondViewportPageCount = 1,283 modifier = Modifier.fillMaxSize(),284 ) { page ->285 val type = visibleTypes[page]286 val pageEntries = remember(state.rowsByType, type, query) {287 updateRows(state.rowsByType, type, query)288 }289 UpdatesPage(290 entries = pageEntries,291 query = query,292 lastUpdatedAt = state.lastUpdatedAt[type],293 formatTimestamp = { millis -> formatTimestamp(millis, state.dateFormat, state.relativeTimestamps) },294 actions = rowActions,295 )296 }297 }298 }299 }300301 if (filtersOpen) {302 val filter = state.filters.updates(selectedTab.toDb())303 ActivityFilterDialog(state.categoriesByType[selectedTab].orEmpty(), filter.categories,304 onCategoryFilter = { change -> onUpdateFilters(selectedTab) { it.copy(categories = change(it.categories)) } },305 onDismiss = { filtersOpen = false }, updatesFilter = filter,306 onUpdatesFilter = { change -> onUpdateFilters(selectedTab, change) })307 }308 if (clearAllOpen) {309 eu.friedcutlet.yokan.ui.components.ConfirmDialog(310 title = "Remove everything",311 message = "Remove all updates for ${selectedTab.label}?",312 confirmLabel = stringResource(Res.string.action_remove),313 danger = true,314 onConfirm = { onClearUpdates(selectedTab) },315 onDismiss = { clearAllOpen = false },316 )317 }318319 state.failedUpdates?.let { errors ->320 if (errors.isNotEmpty()) {321 val plural = if (errors.size == 1) selectedTab.label.lowercase() else "${selectedTab.label.lowercase()}s"322 androidx.compose.material3.AlertDialog(323 onDismissRequest = onDismissFailedUpdates,324 title = { Text("Failed to update ${errors.size} $plural") },325 text = {326 Box(modifier = Modifier.fillMaxWidth().heightIn(max = 240.dp)) {327 LazyColumn(modifier = Modifier.fillMaxWidth()) {328 items(errors, key = { it.mangaId }) { err ->329 Text(330 text = "• ${err.name}",331 style = MaterialTheme.typography.bodyMedium,332 modifier = Modifier.padding(vertical = 2.dp),333 )334 }335 }336 }337 },338 confirmButton = {339 androidx.compose.material3.TextButton(onClick = onDismissFailedUpdates) {340 Text(stringResource(Res.string.ok))341 }342 },343 )344 }345 }346}347348private fun updateRows(349 rowsByType: Map<ItemType, List<UpdateRowModel>>,350 type: ItemType,351 query: String,352): List<UpdateRowModel> {353 val rows = rowsByType[type].orEmpty()354 return if (query.isBlank()) rows else rows.filter { it.update.title.contains(query, ignoreCase = true) }355}356357@Composable358private fun UpdatesPage(359 entries: List<UpdateRowModel>,360 query: String,361 lastUpdatedAt: Long?,362 formatTimestamp: (Long) -> String,363 actions: UpdateRowActions,364) {365 if (entries.isEmpty()) {366 EmptyState(367 modifier = Modifier.fillMaxSize(),368 icon = Icons.Filled.NewReleases,369 title = if (query.isNotEmpty()) "No matches" else "No recent updates",370 )371 return372 }373 val grouped = remember(entries) { groupByDayBucket(entries) { it.update.updatedAt } }374 LazyColumn(375 modifier = Modifier.fillMaxSize(),376 contentPadding = PaddingValues(top = 11.dp),377 ) {378 lastUpdatedAt?.let { updatedAt ->379 item(key = "last-updated") {380 Text(381 text = "Library last updated: ${formatTimestamp(updatedAt)}",382 style = MaterialTheme.typography.bodyMedium,383 fontStyle = FontStyle.Italic,384 color = MaterialTheme.colorScheme.secondary,385 modifier = Modifier.padding(386 start = 10.dp,387 end = 10.dp,388 top = 10.dp,389 bottom = 20.dp,390 ),391 )392 }393 }394 grouped.forEach { (bucket, items) ->395 item(key = "u-$bucket") {396 DateGroupHeader(bucket)397 }398 items(items, key = { it.update.id }) { row ->399 UpdateRow(row, actions)400 }401 }402 }403}404405@Composable406private fun UpdateRow(row: UpdateRowModel, actions: UpdateRowActions) {407 val manga = row.manga408 val chapter = row.chapter409 val title = row.title410 val chapterName = row.chapterName411 val isRead = row.isRead412413 Row(414 modifier = Modifier415 .fillMaxWidth()416 .height(55.dp)417 .hoverHighlight(onClick = {418 if (manga != null && chapter != null) actions.onOpenChapter(manga, chapter)419 })420 .padding(horizontal = 13.dp, vertical = 5.dp),421 verticalAlignment = Alignment.CenterVertically,422 ) {423 CoverImage(424 model = manga?.let { it.customCoverImage ?: it.customCoverFromTracker ?: it.imageUrl },425 contentDescription = "$title cover",426 modifier = Modifier427 .size(width = 40.dp, height = 45.dp)428 .clip(RoundedCornerShape(5.dp))429 .then(430 if (manga != null) {431 Modifier.hoverHighlight(onClick = { actions.onOpenDetail(manga) })432 } else {433 Modifier434 },435 ),436 shape = RoundedCornerShape(5.dp),437 fallbackInitials = title.split(" ").take(2)438 .joinToString("") { it.firstOrNull()?.uppercase() ?: "" },439 )440 Column(441 modifier = Modifier442 .weight(1f)443 .padding(horizontal = 10.dp),444 verticalArrangement = Arrangement.Center,445 ) {446 Text(447 text = title,448 fontSize = 14.sp,449 maxLines = 1,450 overflow = TextOverflow.Ellipsis,451 )452 Text(453 text = chapterName,454 fontSize = 11.sp,455 maxLines = 1,456 overflow = TextOverflow.Ellipsis,457 color = if (isRead) {458 Color.Gray459 } else {460 MaterialTheme.colorScheme.onSurface461 },462 )463 }464 if (manga != null && chapter != null) {465 DownloadStatusIcon(466 download = row.download,467 actions = actions,468 onDownload = { actions.onDownload(row) },469 )470 } else {471 Spacer(Modifier.width(35.dp))472 }473 }474}475476@Composable477private fun DownloadStatusIcon(478 download: DbDownload?,479 actions: UpdateRowActions,480 onDownload: () -> Unit,481) {482 var menuExpanded by remember(download?.id) { mutableStateOf(false) }483 val indicatorColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)484485 Box(486 modifier = Modifier487 .width(35.dp)488 .height(41.dp)489 .padding(vertical = 3.dp),490 contentAlignment = Alignment.Center,491 ) {492 if (download == null) {493 IconButton(494 modifier = Modifier.size(35.dp),495 onClick = onDownload,496 ) {497 Icon(498 imageVector = Icons.Filled.ArrowDownward,499 contentDescription = "Download",500 modifier = Modifier.size(18.dp),501 tint = indicatorColor,502 )503 }504 CircularProgressIndicator(505 progress = { 1f },506 modifier = Modifier.size(20.dp),507 color = indicatorColor,508 strokeWidth = 2.dp,509 )510 } else {511 val completed = download.isDownload == true512 val succeeded = download.succeeded ?: 0513 val total = download.total ?: 0514 val progress = if (total > 0) {515 (succeeded.toFloat() / total.coerceAtLeast(1)).coerceIn(0f, 1f)516 } else {517 0f518 }519 val running = download.isStartDownload == true520521 IconButton(522 modifier = Modifier.size(35.dp),523 onClick = { menuExpanded = true },524 ) {525 when {526 completed -> Icon(527 imageVector = Icons.Filled.DownloadDone,528 contentDescription = "Downloaded",529 modifier = Modifier.size(25.dp),530 tint = indicatorColor,531 )532 succeeded > 0 -> {533 Icon(534 imageVector = Icons.Filled.ArrowDownward,535 contentDescription = "Download in progress",536 modifier = Modifier.size(18.dp),537 tint = indicatorColor,538 )539 CircularProgressIndicator(540 progress = { progress },541 modifier = Modifier.size(20.dp),542 color = indicatorColor,543 strokeWidth = 2.dp,544 )545 }546 running -> {547 Icon(548 imageVector = Icons.Filled.ArrowDownward,549 contentDescription = "Download queued",550 modifier = Modifier.size(18.dp),551 tint = indicatorColor,552 )553 CircularProgressIndicator(554 modifier = Modifier.size(20.dp),555 color = indicatorColor,556 strokeWidth = 2.dp,557 )558 }559 else -> Icon(560 imageVector = Icons.Filled.Refresh,561 contentDescription = "Download stopped",562 modifier = Modifier.size(22.dp),563 tint = MaterialTheme.colorScheme.error,564 )565 }566 }567 DropdownMenu(568 expanded = menuExpanded,569 onDismissRequest = { menuExpanded = false },570 ) {571 if (completed) {572 DropdownMenuItem(573 text = { Text("Send") },574 onClick = {575 menuExpanded = false576 actions.onOpenDownloadLocation(download.id)577 },578 )579 DropdownMenuItem(580 text = { Text(stringResource(Res.string.delete)) },581 onClick = {582 menuExpanded = false583 actions.onRemoveDownload(download.id)584 },585 )586 } else {587 DropdownMenuItem(588 text = { Text("Start downloading") },589 onClick = {590 menuExpanded = false591 actions.onCancelDownload(download.id)592 onDownload()593 },594 )595 DropdownMenuItem(596 text = { Text(stringResource(Res.string.action_cancel)) },597 onClick = {598 menuExpanded = false599 actions.onCancelDownload(download.id)600 },601 )602 }603 }604 }605 }606}607