Yokan / rebuild
Course 1 8624561

HomeScreen.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeScreen.kt

implementation271 lines
1package eu.friedcutlet.yokan.ui.screens.home23import androidx.compose.foundation.background4import androidx.compose.foundation.layout.*5import androidx.compose.foundation.lazy.LazyColumn6import androidx.compose.foundation.lazy.LazyRow7import androidx.compose.foundation.lazy.items8import androidx.compose.foundation.pager.HorizontalPager9import androidx.compose.foundation.pager.rememberPagerState10import androidx.compose.foundation.shape.RoundedCornerShape11import androidx.compose.material.icons.Icons12import androidx.compose.material.icons.automirrored.filled.ArrowBack13import androidx.compose.material.icons.automirrored.filled.ArrowForward14import androidx.compose.material.icons.filled.Refresh15import androidx.compose.material.icons.filled.Explore16import androidx.compose.material.icons.filled.Search17import androidx.compose.material.icons.filled.Star18import androidx.compose.material.icons.filled.Tune19import androidx.compose.material3.*20import androidx.compose.runtime.*21import androidx.compose.ui.Alignment22import androidx.compose.ui.Modifier23import androidx.compose.ui.MotionDurationScale24import androidx.compose.ui.draw.clip25import androidx.compose.ui.graphics.Brush26import androidx.compose.ui.graphics.Color27import androidx.compose.ui.text.font.FontWeight28import androidx.compose.ui.text.style.TextOverflow29import androidx.compose.ui.unit.dp30import eu.friedcutlet.yokan.database.*31import eu.friedcutlet.yokan.services.discovery.DiscoveryIssue32import eu.friedcutlet.yokan.ui.components.CoverImage33import eu.friedcutlet.yokan.ui.components.EmptyState34import eu.friedcutlet.yokan.ui.theme.LocalEinkMode35import kotlinx.coroutines.delay36import kotlinx.coroutines.launch37import kotlin.math.roundToInt38import org.jetbrains.compose.resources.stringResource39import yokan.composeapp.generated.resources.*40import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold4142@OptIn(ExperimentalMaterial3Api::class)43@Composable44internal fun HomeScreen(45    state: HomeState,46    onOpen: (HomeCard) -> Unit,47    onRefresh: () -> Unit,48    onCustomize: (Boolean) -> Unit,49    onSearch: (Boolean) -> Unit,50    onQuery: (String) -> Unit,51    onSearchSubmit: () -> Unit,52    onPreferences: ((DbHomePreferences) -> DbHomePreferences) -> Unit,53    onToken: (String) -> Unit,54    onAddFeed: (DbHomeSourceFeed) -> Unit,55    onRemoveFeed: (String) -> Unit,56    onMoveFeed: (String, Int) -> Unit,57    onBrowse: () -> Unit,58    onDismissIssue: () -> Unit = {},59) {60    state.openIssue?.let { issue -> AlertDialog(onDismissRequest = onDismissIssue,61        text = { Text(homeIssueLabel(issue)) },62        confirmButton = { TextButton(onClick = onDismissIssue) { Text(stringResource(Res.string.action_cancel)) } }) }63    if (state.customizeOpen) HomeCustomizeSheet(state, onPreferences, onToken, onAddFeed, onRemoveFeed, onMoveFeed) { onCustomize(false) }64    if (state.searchOpen) AlertDialog(65        onDismissRequest = { onSearch(false) },66        title = { Text(stringResource(Res.string.home_search)) },67        text = { OutlinedTextField(value = state.searchQuery, onValueChange = onQuery, singleLine = true,68            label = { Text(stringResource(Res.string.home_search_query)) }, modifier = Modifier.fillMaxWidth()) },69        confirmButton = { TextButton(onClick = onSearchSubmit, enabled = state.searchQuery.isNotBlank()) { Text(stringResource(Res.string.home_find_sources)) } },70        dismissButton = { TextButton(onClick = { onSearch(false) }) { Text(stringResource(Res.string.action_cancel)) } },71    )72    Scaffold(topBar = {73        TopAppBar(title = { Text(stringResource(Res.string.nav_home)) }, actions = {74            IconButton(onClick = { onSearch(true) }) { Icon(Icons.Filled.Search, stringResource(Res.string.home_search)) }75            IconButton(onClick = onRefresh, enabled = !state.refreshing) { Icon(Icons.Filled.Refresh, stringResource(Res.string.home_refresh)) }76            IconButton(onClick = { onCustomize(true) }) { Icon(Icons.Filled.Tune, stringResource(Res.string.home_customize)) }77        })78    }) { padding ->79        BoxWithConstraints(Modifier.fillMaxSize().padding(padding)) {80            val wide = maxWidth >= 840.dp81            val cardWidth = if (wide) 172.dp else 136.dp82            LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(24.dp)) {83                item(key = "filters", contentType = "filters") {84                    LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {85                        items(HomeMediaFilter.entries, key = { it.name }) { filter ->86                            FilterChip(selected = state.preferences.filter == filter,87                                onClick = { onPreferences { it.copy(filter = filter) } }, label = { Text(homeFilterLabel(filter)) })88                        }89                    }90                }91                if (state.featured.isNotEmpty()) item(key = "featured", contentType = "featured") {92                    HomeFeatured(state.featured, state.preferences.autoAdvanceFeatured, wide, onOpen)93                }94                items(state.shelves, key = { it.id }, contentType = { "shelf" }) { shelf ->95                    if (shelf.cards.isNotEmpty() || shelf.loading || shelf.issue != null || shelf.section == HomeSection.Continue) {96                        HomeShelfContent(shelf, state.seedTitle, cardWidth, onOpen, onRefresh) { onCustomize(true) }97                    }98                }99                if (state.feeds.isEmpty() && HomeSection.Sources !in state.preferences.hiddenSections) item(key = "sources-empty", contentType = "empty") {100                    Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {101                        Text(stringResource(Res.string.home_source_feeds), style = MaterialTheme.typography.titleLarge)102                        Text(stringResource(Res.string.home_sources_hint), color = MaterialTheme.colorScheme.onSurfaceVariant)103                        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {104                            OutlinedButton(onClick = { onCustomize(true) }) { Text(stringResource(Res.string.home_add_feed)) }105                            TextButton(onClick = onBrowse) { Text(stringResource(Res.string.home_browse)) }106                        }107                    }108                }109                if (state.shelves.none { it.loading || it.cards.isNotEmpty() || it.issue != null } && state.featured.isEmpty()) item(key = "empty", contentType = "empty") {110                    EmptyState(icon = Icons.Filled.Explore, title = stringResource(Res.string.home_empty), subtitle = stringResource(Res.string.home_empty_hint),111                        modifier = Modifier.fillMaxWidth().padding(24.dp))112                }113                if (state.preferences.enableTmdb) item(key = "tmdb-credit", contentType = "credit") {114                    Text(stringResource(Res.string.home_tmdb_credit), style = MaterialTheme.typography.bodySmall,115                        color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 20.dp))116                }117            }118        }119    }120}121122@Composable123private fun HomeShelfContent(shelf: HomeShelf, seed: String?, cardWidth: androidx.compose.ui.unit.Dp,124    onOpen: (HomeCard) -> Unit, onRefresh: () -> Unit, onCustomize: () -> Unit) {125    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {126        Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically) {127            Text(if (shelf.section == HomeSection.BecauseYouRead && seed != null) stringResource(Res.string.home_because_title, seed)128                else shelf.sourceName?.takeIf { it.isNotBlank() } ?: homeSectionLabel(shelf.section),129                style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))130            if (shelf.loading) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)131        }132        if (shelf.issue != null) Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically) {133            Text(homeIssueLabel(shelf.issue), style = MaterialTheme.typography.bodyMedium,134                color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f))135            TextButton(onClick = if (shelf.issue == DiscoveryIssue.Credentials || shelf.issue == DiscoveryIssue.PresetChanged) onCustomize else onRefresh) {136                Text(stringResource(if (shelf.issue == DiscoveryIssue.Credentials || shelf.issue == DiscoveryIssue.PresetChanged) Res.string.home_customize else Res.string.home_retry))137            }138        }139        if (shelf.cards.isNotEmpty()) LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) {140            items(shelf.cards, key = { it.media.key }, contentType = { "media" }) { card -> HomePoster(card, cardWidth) { onOpen(card) } }141        } else if (shelf.section == HomeSection.Continue) Text(stringResource(Res.string.home_continue_empty),142            modifier = Modifier.padding(horizontal = 20.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)143        else if (shelf.loading) LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) {144            items(4, key = { "placeholder:$it" }) {145                Box(Modifier.width(cardWidth).aspectRatio(0.68f).clip(MaterialTheme.shapes.medium).background(MaterialTheme.colorScheme.surfaceContainerHighest))146            }147        }148    }149}150151@Composable152private fun HomePoster(card: HomeCard, width: androidx.compose.ui.unit.Dp, onOpen: () -> Unit) {153    Surface(onClick = onOpen, color = Color.Transparent, shape = MaterialTheme.shapes.medium, modifier = Modifier.width(width)) {154        Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {155            Box {156                CoverImage(card.coverBytes ?: card.media.coverUrl, card.media.title,157                    Modifier.fillMaxWidth().aspectRatio(0.68f), fallbackInitials = card.media.title.take(2))158                card.media.rating?.let { rating ->159                    Surface(color = MaterialTheme.colorScheme.inverseSurface, shape = RoundedCornerShape(6.dp),160                        modifier = Modifier.align(Alignment.BottomEnd).padding(6.dp)) {161                        Row(Modifier.padding(horizontal = 6.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {162                            Icon(Icons.Filled.Star, null, Modifier.size(14.dp))163                            Text(formatHomeRating(rating), style = MaterialTheme.typography.labelMedium)164                        }165                    }166                }167            }168            Text(card.media.title, style = MaterialTheme.typography.titleSmall, maxLines = 2, overflow = TextOverflow.Ellipsis)169            Text(homeFilterLabel(card.media.kind), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)170            if (card.chapterId != null) {171                Text(card.chapterName.orEmpty(), style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis)172                Text(homeProgressLabel(card), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)173                card.progress?.let { LinearProgressIndicator(progress = { it }, modifier = Modifier.fillMaxWidth()) }174            }175        }176    }177}178179@Composable180private fun HomeFeatured(cards: List<HomeCard>, autoAdvance: Boolean, wide: Boolean, onOpen: (HomeCard) -> Unit) {181    val pager = rememberPagerState(pageCount = { cards.size })182    val scope = rememberCoroutineScope()183    val eink = LocalEinkMode.current184    LaunchedEffect(cards.map { it.media.key }, autoAdvance, eink) {185        if (autoAdvance && !eink && cards.size > 1) while (true) {186            delay(7_000)187            if (!pager.isScrollInProgress && (coroutineContext[MotionDurationScale]?.scaleFactor ?: 1f) > 0f)188                pager.animateScrollToPage((pager.currentPage + 1) % cards.size)189        }190    }191    Column(Modifier.padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {192        HorizontalPager(state = pager, key = { cards[it].media.key }) { page ->193            val card = cards[page]194            Box(Modifier.fillMaxWidth().height(if (wide) 340.dp else 320.dp).clip(MaterialTheme.shapes.large)195                .background(MaterialTheme.colorScheme.surfaceContainerHighest)) {196                CoverImage(card.media.backdropUrl ?: card.coverBytes ?: card.media.coverUrl, null,197                    Modifier.matchParentSize(), fallbackInitials = card.media.title.take(2))198                Box(Modifier.matchParentSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.12f), Color.Black.copy(alpha = 0.94f)))))199                Column(Modifier.align(Alignment.BottomStart).padding(24.dp).widthIn(max = 680.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {200                    Text(card.media.title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.SemiBold,201                        color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis)202                    Text(homeFilterLabel(card.media.kind), style = MaterialTheme.typography.labelLarge, color = Color.White)203                    if (card.media.description.isNotBlank()) Text(card.media.description, style = MaterialTheme.typography.bodyMedium,204                        color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis)205                    Button(onClick = { onOpen(card) }) { Text(homeActionLabel(card)) }206                }207            }208        }209        if (cards.size > 1) Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) {210            IconButton(onClick = { scope.launch { pager.animateScrollToPage((pager.currentPage - 1 + cards.size) % cards.size) } }) {211                Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(Res.string.home_previous))212            }213            Text(stringResource(Res.string.home_featured_page, pager.currentPage + 1, cards.size), style = MaterialTheme.typography.labelLarge)214            IconButton(onClick = { scope.launch { pager.animateScrollToPage((pager.currentPage + 1) % cards.size) } }) {215                Icon(Icons.AutoMirrored.Filled.ArrowForward, stringResource(Res.string.home_next))216            }217        }218    }219}220221internal fun formatHomeRating(rating: Double): String {222    val tenths = (rating.coerceIn(0.0, 10.0) * 10).roundToInt()223    return "${tenths / 10}.${tenths % 10}"224}225226@Composable227private fun homeActionLabel(card: HomeCard): String = stringResource(when {228    card.chapterId != null -> Res.string.home_resume229    card.mangaId != null || card.media.sourceId != null -> Res.string.home_open_title230    else -> Res.string.home_find_sources231})232233@Composable234private fun homeProgressLabel(card: HomeCard): String = if (card.media.kind == HomeMediaFilter.Anime) {235    val seconds = card.position / 1_000236    stringResource(Res.string.home_video_position, "${seconds / 60}:${(seconds % 60).toString().padStart(2, '0')}")237} else if (card.media.kind == HomeMediaFilter.Novel) stringResource(Res.string.home_novel_position, "${((card.novelProgress ?: 0f) * 100).toInt()}%")238else stringResource(Res.string.home_page_position, card.position + 1)239240@Composable241internal fun homeFilterLabel(filter: HomeMediaFilter): String = stringResource(when (filter) {242    HomeMediaFilter.All -> Res.string.home_all243    HomeMediaFilter.Anime -> Res.string.home_anime244    HomeMediaFilter.Manga -> Res.string.home_manga245    HomeMediaFilter.Novel -> Res.string.home_novels246    HomeMediaFilter.Movie -> Res.string.home_movies247    HomeMediaFilter.Series -> Res.string.home_series248})249250@Composable251internal fun homeSectionLabel(section: HomeSection): String = stringResource(when (section) {252    HomeSection.Continue -> Res.string.home_continue253    HomeSection.Recommended -> Res.string.home_recommended254    HomeSection.BecauseYouRead -> Res.string.home_because255    HomeSection.PopularAnime -> Res.string.home_popular_anime256    HomeSection.PopularManga -> Res.string.home_popular_manga257    HomeSection.PopularNovels -> Res.string.home_popular_novels258    HomeSection.PopularMovies -> Res.string.home_popular_movies259    HomeSection.PopularSeries -> Res.string.home_popular_series260    HomeSection.Sources -> Res.string.home_source_feeds261    HomeSection.TmdbRecommended -> Res.string.home_tmdb_recommended262})263264@Composable265private fun homeIssueLabel(issue: DiscoveryIssue): String = stringResource(when (issue) {266    DiscoveryIssue.Credentials -> Res.string.home_credentials_error267    DiscoveryIssue.RateLimited -> Res.string.home_rate_error268    DiscoveryIssue.PresetChanged -> Res.string.home_preset_error269    DiscoveryIssue.SourceUnavailable -> Res.string.home_source_error270    DiscoveryIssue.Network -> Res.string.home_network_error271})272

Search chapters, reference and source filenames.