Yokan / rebuild
Course 1 8624561

ChapterList.kt

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

implementation512 lines
1package eu.friedcutlet.yokan.ui.screens.detail23import yokan.composeapp.generated.resources.detail_selected_count4import androidx.compose.foundation.ExperimentalFoundationApi5import androidx.compose.foundation.background6import androidx.compose.foundation.clickable7import androidx.compose.foundation.combinedClickable8import androidx.compose.foundation.layout.Arrangement9import androidx.compose.foundation.layout.Box10import androidx.compose.foundation.layout.Column11import androidx.compose.foundation.layout.Row12import androidx.compose.foundation.layout.Spacer13import androidx.compose.foundation.layout.fillMaxSize14import androidx.compose.foundation.layout.fillMaxWidth15import androidx.compose.foundation.layout.height16import androidx.compose.foundation.layout.padding17import androidx.compose.foundation.layout.size18import androidx.compose.foundation.layout.width19import androidx.compose.foundation.shape.RoundedCornerShape20import androidx.compose.material.icons.Icons21import androidx.compose.material.icons.filled.Bookmark22import androidx.compose.material.icons.filled.BookmarkBorder23import androidx.compose.material.icons.filled.CheckCircle24import androidx.compose.material.icons.filled.Close25import androidx.compose.material.icons.filled.DeleteSweep26import androidx.compose.material.icons.filled.Download27import androidx.compose.material.icons.filled.DownloadDone28import androidx.compose.material.icons.filled.Downloading29import androidx.compose.material.icons.outlined.CheckCircle30import androidx.compose.material.icons.filled.Flag31import androidx.compose.material.icons.filled.Restore32import androidx.compose.material.icons.outlined.Flag33import yokan.composeapp.generated.resources.filler_mark34import yokan.composeapp.generated.resources.filler_reset35import yokan.composeapp.generated.resources.filler_unmark36import androidx.compose.material3.ExperimentalMaterial3Api37import androidx.compose.material3.Icon38import androidx.compose.material3.IconButton39import androidx.compose.material3.MaterialTheme40import androidx.compose.material3.Surface41import androidx.compose.material3.SwipeToDismissBox42import androidx.compose.material3.SwipeToDismissBoxValue43import androidx.compose.material3.Text44import androidx.compose.material3.TopAppBar45import androidx.compose.material3.TopAppBarDefaults46import androidx.compose.material3.rememberSwipeToDismissBoxState47import androidx.compose.runtime.Composable48import androidx.compose.runtime.getValue49import androidx.compose.runtime.remember50import androidx.compose.runtime.rememberCoroutineScope51import androidx.compose.runtime.rememberUpdatedState52import androidx.compose.ui.Alignment53import androidx.compose.ui.Modifier54import androidx.compose.ui.draw.clip55import androidx.compose.ui.graphics.Color56import androidx.compose.ui.input.key.type57import androidx.compose.ui.input.pointer.PointerEventType58import androidx.compose.ui.input.pointer.isSecondaryPressed59import androidx.compose.ui.input.pointer.isShiftPressed60import androidx.compose.ui.input.pointer.pointerInput61import androidx.compose.ui.layout.ContentScale62import androidx.compose.ui.text.font.FontWeight63import androidx.compose.ui.text.style.TextOverflow64import androidx.compose.ui.unit.dp65import eu.friedcutlet.yokan.database.DbSettings66import eu.friedcutlet.yokan.domain.Chapter67import eu.friedcutlet.yokan.domain.ItemType68import eu.friedcutlet.yokan.domain.Manga69import kotlinx.coroutines.launch70import org.jetbrains.compose.resources.stringResource71import yokan.composeapp.generated.resources.Res72import yokan.composeapp.generated.resources.ui_bookmark73import yokan.composeapp.generated.resources.ui_mark_read74import yokan.composeapp.generated.resources.ui_mark_unread75import yokan.composeapp.generated.resources.ui_unbookmark76import eu.friedcutlet.yokan.ui.components.CoverImage77import eu.friedcutlet.yokan.ui.formatAbsoluteDate78import eu.friedcutlet.yokan.ui.parseDateToEpochMillis79import eu.friedcutlet.yokan.ui.screens.novel.parseNovelProgressRatio80import eu.friedcutlet.yokan.ui.components.hoverHighlight81import androidx.compose.material.icons.filled.HourglassEmpty82import eu.friedcutlet.yokan.ui.components.EmptyState8384@Composable85internal fun ChaptersHeaderRow(86    label: String,87    count: Int,88    missingCount: Int = 0,89    unnumberedCount: Int = 0,90    selectionActions: @Composable () -> Unit = {},91) {92    Row(93        modifier = Modifier94            .fillMaxWidth()95            .padding(horizontal = 16.dp, vertical = 12.dp),96        verticalAlignment = Alignment.CenterVertically,97        horizontalArrangement = Arrangement.SpaceBetween,98    ) {99        Column(Modifier.weight(1f)) {100            Text(101                text = "$count ${label.lowercase()}",102                style = MaterialTheme.typography.bodyLarge,103                fontWeight = FontWeight.Bold,104            )105            if (missingCount > 0 || unnumberedCount > 0) {106                Row(107                    horizontalArrangement = Arrangement.spacedBy(8.dp),108                    verticalAlignment = Alignment.CenterVertically,109                ) {110                    if (missingCount > 0) {111                        androidx.compose.material3.Surface(112                            color = MaterialTheme.colorScheme.errorContainer,113                            shape = MaterialTheme.shapes.small,114                        ) {115                            Text(116                                text = if (missingCount == 1) "1 missing" else "$missingCount missing",117                                style = MaterialTheme.typography.labelSmall,118                                color = MaterialTheme.colorScheme.onErrorContainer,119                                modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),120                            )121                        }122                    }123                    if (unnumberedCount > 0) {124                        androidx.compose.material3.Surface(125                            color = MaterialTheme.colorScheme.surfaceVariant,126                            shape = MaterialTheme.shapes.small,127                        ) {128                            Text(129                                text = if (unnumberedCount == 1) "1 unnumbered" else "$unnumberedCount unnumbered",130                                style = MaterialTheme.typography.labelSmall,131                                color = MaterialTheme.colorScheme.onSurfaceVariant,132                                modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),133                            )134                        }135                    }136                }137            }138        }139        selectionActions()140    }141}142143internal fun formatAnimeProgress(positionMs: Long): String {144    val totalSeconds = positionMs.coerceAtLeast(0L) / 1000L145    val hours = totalSeconds / 3600L146    val minutes = (totalSeconds % 3600L) / 60L147    val seconds = totalSeconds % 60L148    return "$hours:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}"149}150151internal suspend fun completeChapterSwipeDismiss(152    direction: SwipeToDismissBoxValue,153    onBookmark: () -> Unit,154    onReadToggle: () -> Unit,155    reset: suspend () -> Unit,156) {157    when (direction) {158        SwipeToDismissBoxValue.StartToEnd -> onBookmark()159        SwipeToDismissBoxValue.EndToStart -> onReadToggle()160        SwipeToDismissBoxValue.Settled -> return161    }162    reset()163}164165@OptIn(ExperimentalFoundationApi::class)166@Composable167internal fun ChapterRow(168    chapter: Chapter,169    itemType: ItemType,170    uploadDate: String?,171    selected: Boolean,172    anySelected: Boolean,173    showDownload: Boolean,174    onClick: () -> Unit,175    onLongClick: () -> Unit,176    onSecondaryClick: (Boolean) -> Unit,177    onBookmark: () -> Unit,178    onReadToggle: () -> Unit,179    onDownload: () -> Unit,180) {181    val titleColor = if (chapter.isRead) {182        MaterialTheme.colorScheme.onSurface.copy(alpha = 0.4f)183    } else {184        MaterialTheme.colorScheme.onSurface185    }186    val supportingColor = if (chapter.isRead) {187        MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f)188    } else {189        MaterialTheme.colorScheme.onSurfaceVariant190    }191    val subtitle = listOfNotNull(192        if (chapter.isFiller) "Filler" else null,193        uploadDate,194        chapter.lastPageRead195            .takeIf { it.isNotBlank() && it != "1" && !chapter.isRead }196            ?.let { progress ->197                when (itemType) {198                    ItemType.Anime -> progress.toLongOrNull()?.let { "episode ${formatAnimeProgress(it)}" }199                    ItemType.Novel -> "${(parseNovelProgressRatio(progress) * 100).toInt()} %"200                    ItemType.Manga -> "page $progress"201                }202            },203        chapter.scanlator.takeIf { it.isNotBlank() },204        chapter.downloadSize,205    ).joinToString(" • ")206    val rowColor = when {207        selected -> MaterialTheme.colorScheme.primary.copy(alpha = 0.4f)208        chapter.isFiller -> MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)209        else -> Color.Transparent210    }211    val swipeScope = rememberCoroutineScope()212    val swipeState = rememberSwipeToDismissBoxState(213        positionalThreshold = { distance -> distance * 0.25f },214    )215    val currentOnBookmark by rememberUpdatedState(onBookmark)216    val currentOnReadToggle by rememberUpdatedState(onReadToggle)217    val onSwipeDismiss: (SwipeToDismissBoxValue) -> Unit = remember(swipeState, swipeScope) {218        { direction ->219            swipeScope.launch {220                completeChapterSwipeDismiss(221                    direction = direction,222                    onBookmark = { currentOnBookmark() },223                    onReadToggle = { currentOnReadToggle() },224                    reset = { swipeState.reset() },225                )226            }227        }228    }229    SwipeToDismissBox(230        state = swipeState,231        backgroundContent = {232            val bookmarking = swipeState.dismissDirection == SwipeToDismissBoxValue.StartToEnd233            Box(234                modifier = Modifier235                    .fillMaxSize()236                    .background(237                        if (bookmarking) {238                            MaterialTheme.colorScheme.primary239                        } else if (chapter.isRead) {240                            MaterialTheme.colorScheme.onSurfaceVariant241                        } else {242                            Color(0xFF2E7D32)243                        },244                    )245                    .padding(horizontal = 20.dp),246                contentAlignment = if (bookmarking) Alignment.CenterStart else Alignment.CenterEnd,247            ) {248                Icon(249                    imageVector = if (bookmarking) {250                        if (chapter.isBookmarked) Icons.Filled.Bookmark else Icons.Filled.BookmarkBorder251                    } else {252                        if (chapter.isRead) Icons.Outlined.CheckCircle else Icons.Filled.CheckCircle253                    },254                    contentDescription = if (bookmarking) {255                        if (chapter.isBookmarked) "Remove bookmark" else "Add bookmark"256                    } else {257                        if (chapter.isRead) "Mark unread" else "Mark read"258                    },259                    tint = Color.White,260                )261            }262        },263        onDismiss = onSwipeDismiss,264        content = {265            Row(266                modifier = Modifier267            .background(MaterialTheme.colorScheme.surface)268            .background(rowColor)269            .hoverHighlight(onClick = null)270            .onSecondaryClick(onSecondaryClick)271            .combinedClickable(272                onClickLabel = "Open ${chapterLabel(itemType).lowercase().removeSuffix("s")}",273                onLongClickLabel = "Select ${chapterLabel(itemType).lowercase().removeSuffix("s")}",274                onClick = onClick,275                onLongClick = onLongClick,276            )277            .padding(horizontal = 15.dp),278        verticalAlignment = Alignment.CenterVertically,279    ) {280        Box(281            modifier = Modifier282                .width(2.dp)283                .height(40.dp)284                .clip(RoundedCornerShape(10.dp))285                .background(286                    if (chapter.isRead) {287                        MaterialTheme.colorScheme.onSurface.copy(alpha = 0.16f)288                    } else {289                        MaterialTheme.colorScheme.primary290                    },291                ),292        )293        Spacer(Modifier.width(13.dp))294        chapter.thumbnailUrl?.takeIf { it.isNotBlank() }?.let { thumbnail ->295            Spacer(Modifier.width(5.dp))296            CoverImage(297                model = thumbnail,298                contentDescription = "${chapter.name} preview",299                contentScale = ContentScale.Crop,300                modifier = Modifier301                    .size(width = 50.dp, height = 65.dp)302                    .clip(RoundedCornerShape(5.dp)),303            )304            Spacer(Modifier.width(5.dp))305        }306        Column(307            modifier = Modifier.weight(1f).padding(vertical = 8.dp),308            verticalArrangement = Arrangement.spacedBy(3.dp),309        ) {310            Row(311                verticalAlignment = Alignment.CenterVertically,312                horizontalArrangement = Arrangement.spacedBy(4.dp),313            ) {314                if (chapter.isBookmarked) {315                    Icon(316                        Icons.Filled.Bookmark,317                        contentDescription = "Remove bookmark",318                        tint = MaterialTheme.colorScheme.primary,319                        modifier = Modifier320                            .size(16.dp)321                            .clickable(enabled = !anySelected, onClick = onBookmark),322                    )323                }324                Text(325                    text = chapter.name,326                    style = MaterialTheme.typography.bodyMedium,327                    color = titleColor,328                    maxLines = 1,329                    overflow = TextOverflow.Ellipsis,330                )331            }332            chapter.description?.takeIf { it.isNotBlank() }?.let { description ->333                Text(334                    text = description,335                    color = titleColor,336                    maxLines = 1,337                    overflow = TextOverflow.Ellipsis,338                    style = MaterialTheme.typography.labelSmall,339                )340            }341            if (subtitle.isNotBlank()) {342                Text(343                    text = subtitle,344                    color = supportingColor,345                    maxLines = 1,346                    overflow = TextOverflow.Ellipsis,347                    style = MaterialTheme.typography.labelSmall,348                )349            }350        }351        if (showDownload) {352            val (icon, tint, label) = when {353                chapter.downloadSize != null -> Triple(354                    Icons.Filled.DownloadDone,355                    MaterialTheme.colorScheme.primary,356                    "Downloaded",357                )358                chapter.archivePath.isNotBlank() -> Triple(359                    Icons.Filled.Downloading,360                    MaterialTheme.colorScheme.tertiary,361                    "In progress",362                )363                else -> Triple(364                    Icons.Filled.Download,365                    MaterialTheme.colorScheme.onSurfaceVariant,366                    "Download",367                )368            }369            IconButton(370                onClick = onDownload,371                enabled = !anySelected && chapter.downloadSize == null,372            ) {373                Icon(icon, contentDescription = label, tint = tint)374            }375        }376    }377    }378    )379}380381@OptIn(ExperimentalMaterial3Api::class)382@Composable383internal fun ChapterSelectionTopBar(384    selectedCount: Int,385    onClear: () -> Unit,386    selectionActions: @Composable () -> Unit,387) {388    TopAppBar(389        title = { Text(stringResource(Res.string.detail_selected_count, selectedCount)) },390        navigationIcon = {391            IconButton(onClick = onClear) {392                Icon(Icons.Filled.Close, contentDescription = "Clear selection")393            }394        },395        actions = { selectionActions() },396        colors = TopAppBarDefaults.topAppBarColors(397            containerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),398        ),399    )400}401402@Composable403internal fun ChapterSelectionBottomBar(404    bookmarked: Boolean,405    read: Boolean,406    showDownload: Boolean,407    showDelete: Boolean,408    /** Null hides the filler actions (non-anime); true when every selected episode is filler. */409    filler: Boolean?,410    showFillerReset: Boolean,411    onBookmark: () -> Unit,412    onMarkRead: () -> Unit,413    onFiller: () -> Unit,414    onResetFiller: () -> Unit,415    onDownload: () -> Unit,416    onDelete: () -> Unit,417) {418    Surface(419        color = MaterialTheme.colorScheme.surface,420        shadowElevation = 8.dp,421    ) {422        Row(423            modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),424            horizontalArrangement = Arrangement.SpaceEvenly,425            verticalAlignment = Alignment.CenterVertically,426        ) {427            IconButton(onClick = onBookmark) {428                Icon(429                    if (bookmarked) Icons.Filled.Bookmark else Icons.Filled.BookmarkBorder,430                    contentDescription = if (bookmarked) {431                        stringResource(Res.string.ui_unbookmark)432                    } else {433                        stringResource(Res.string.ui_bookmark)434                    },435                )436            }437            IconButton(onClick = onMarkRead) {438                Icon(439                    if (read) Icons.Outlined.CheckCircle else Icons.Filled.CheckCircle,440                    contentDescription = if (read) {441                        stringResource(Res.string.ui_mark_unread)442                    } else {443                        stringResource(Res.string.ui_mark_read)444                    },445                )446            }447            if (filler != null) {448                IconButton(onClick = onFiller) {449                    Icon(450                        if (filler) Icons.Filled.Flag else Icons.Outlined.Flag,451                        contentDescription = stringResource(if (filler) Res.string.filler_unmark else Res.string.filler_mark),452                    )453                }454                if (showFillerReset) {455                    IconButton(onClick = onResetFiller) {456                        Icon(Icons.Filled.Restore, contentDescription = stringResource(Res.string.filler_reset))457                    }458                }459            }460            if (showDownload) {461                IconButton(onClick = onDownload) {462                    Icon(Icons.Filled.Download, contentDescription = "Download selected")463                }464            }465            if (showDelete) {466                IconButton(onClick = onDelete) {467                    Icon(Icons.Filled.DeleteSweep, contentDescription = "Delete downloads")468                }469            }470        }471    }472}473474@Composable475internal fun EmptyChaptersCard(itemType: ItemType) {476    EmptyState(477        icon = Icons.Filled.HourglassEmpty,478        title = "No ${chapterLabel(itemType).lowercase()} available",479        subtitle = "Refresh the title to load data from the source runtime.",480        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 24.dp),481    )482}483484internal fun formatChapterDate(raw: String, settings: DbSettings): String? {485    val value = raw.trim()486    if (value.isEmpty()) return null487    val millis = parseDateToEpochMillis(value)488    return if (millis != null && millis > 0L) {489        formatAbsoluteDate(millis, settings.dateFormat)490    } else {491        value492    }493}494495private fun Modifier.onSecondaryClick(onClick: (shiftPressed: Boolean) -> Unit): Modifier =496    pointerInput(onClick) {497        awaitPointerEventScope {498            while (true) {499                val event = awaitPointerEvent()500                if (event.type == PointerEventType.Press && event.buttons.isSecondaryPressed) {501                    event.changes.forEach { it.consume() }502                    onClick(event.keyboardModifiers.isShiftPressed)503                }504            }505        }506    }507508internal fun chapterLabel(itemType: ItemType): String = when (itemType) {509    ItemType.Anime -> "Episodes"510    ItemType.Novel -> "Chapters"511    ItemType.Manga -> "Chapters"512}513

Search chapters, reference and source filenames.