Implementation chapter · Coverage index
Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.
Pinned baseline for comparison. Use the reviewed listings in the implementation chapters and the reviewed source archive when reconstructing the app. See the architecture review for changes.
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MassMigrationProgress.kt
- Source · implementation · 57 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: enum class MigrationPhase { Searching, Reviewing, Migrating, Completed, Cancelled }
8: enum class MigrationItemStatus { Pending, Ready, Unmatched, Failed, Skipped, Migrated }
9: enum class MigrationMatchReason { ExactTitle, KnownAlias, SimilarTitle }
10: enum class MigrationSearchIssue { Failed, TimedOut, Truncated, DetailFailed }
12: data class MigrationCandidateKey(val sourceId: Long, val url: String)
14: data class MigrationCandidate(
24: data class MigrationSourceResult(
30: data class MigrationReviewItem(
42: data class MassMigrationProgress(
Exact file bytes / download · SHA-256 4b295bd2b5cb0376e26d5d5e42aebc17ecdc61f8bff1268219ea5629403bd796.
Complete file
package eu.friedcutlet.yokan.services.migration
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
enum class MigrationPhase { Searching, Reviewing, Migrating, Completed, Cancelled }
enum class MigrationItemStatus { Pending, Ready, Unmatched, Failed, Skipped, Migrated }
enum class MigrationMatchReason { ExactTitle, KnownAlias, SimilarTitle }
enum class MigrationSearchIssue { Failed, TimedOut, Truncated, DetailFailed }
data class MigrationCandidateKey(val sourceId: Long, val url: String)
data class MigrationCandidate(
val source: Source,
val detail: RemoteDetail,
val effectiveChapters: Int,
val rawChapters: Int,
val reason: MigrationMatchReason,
) {
val key: MigrationCandidateKey get() = MigrationCandidateKey(source.id, detail.url)
}
data class MigrationSourceResult(
val source: Source,
val candidates: List<MigrationCandidate>,
val issues: Set<MigrationSearchIssue> = emptySet(),
)
data class MigrationReviewItem(
val original: Manga,
val originalChapterCount: Int,
val sources: List<MigrationSourceResult> = emptyList(),
val candidates: List<MigrationCandidate> = emptyList(),
val selected: MigrationCandidateKey? = null,
val status: MigrationItemStatus = MigrationItemStatus.Pending,
) {
val hasIncompleteSearch: Boolean get() = sources.any { it.issues.isNotEmpty() }
}
/** One database-owned run. Discovery never mutates the library; transfer requires review. */
data class MassMigrationProgress(
val sourceId: Long,
val destinationIds: List<Long>,
val mangaIds: List<Long>,
val items: List<MigrationReviewItem>,
val phase: MigrationPhase,
) {
val total: Int get() = items.size
val migrated: Int get() = items.count { it.status == MigrationItemStatus.Migrated }
val skipped: Int get() = items.count { it.status == MigrationItemStatus.Skipped }
val unmatched: Int get() = items.count { it.status == MigrationItemStatus.Unmatched }
val failed: Int get() = items.count { it.status == MigrationItemStatus.Failed }
val reviewed: Int get() = items.count { it.status != MigrationItemStatus.Pending }
val selectedCount: Int get() = items.count { it.status == MigrationItemStatus.Ready && it.selected != null }
val running: Boolean get() = phase == MigrationPhase.Searching || phase == MigrationPhase.Migrating
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MigrationPlanner.kt
- Source · implementation · 162 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
26: data class MigrationSearchLimits(
41: fun normalizeMigrationTitle(title: String): String = title.lowercase().replace(titleSeparators, " ").trim()
44: fun migrationMatchReason(original: Manga, title: String): MigrationMatchReason? {
63: fun migrationSourceCompatible(original: Manga, destination: Source): Boolean =
69: fun migrationChapterCoverage(detail: RemoteDetail): Int = detail.chapters.mapIndexed { index, chapter ->
73: internal class MigrationPlanner(
81: suspend fun discover(original: Manga, destinations: List<Source>): List<MigrationSourceResult> = coroutineScope {
86: private suspend fun search(original: Manga, destination: Source): MigrationSourceResult {
156: internal fun rankedMigrationCandidates(results: List<MigrationSourceResult>): List<MigrationCandidate> {
Exact file bytes / download · SHA-256 baabff13c637811b067cd5ec690581de8f486896d894929496482ddb24f51daf.
Complete file
package eu.friedcutlet.yokan.services.migration
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.chapterReleaseIdentity
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withTimeout
/** Bounds apply per title/source, including all alias searches and detail fetches. */
data class MigrationSearchLimits(
val parallelSources: Int = 3,
val sourceTimeoutMillis: Long = 60_000,
val maxQueries: Int = 3,
val maxPagesPerQuery: Int = 3,
val maxResults: Int = 100,
val maxDetails: Int = 12,
) {
init {
require(parallelSources > 0 && sourceTimeoutMillis > 0)
require(maxQueries > 0 && maxPagesPerQuery > 0 && maxResults > 0 && maxDetails > 0)
}
}
private val titleSeparators = Regex("[^\\p{L}\\p{N}]+")
fun normalizeMigrationTitle(title: String): String = title.lowercase().replace(titleSeparators, " ").trim()
/** Weak single-word matches, different numbered sequels and side stories never pass by count. */
fun migrationMatchReason(original: Manga, title: String): MigrationMatchReason? {
val normalized = normalizeMigrationTitle(title)
if (normalized.isBlank()) return null
val primary = normalizeMigrationTitle(original.name)
if (primary == normalized) return MigrationMatchReason.ExactTitle
val aliases = original.alternativeTitles.map(::normalizeMigrationTitle).filter { it.isNotBlank() }
if (normalized in aliases) return MigrationMatchReason.KnownAlias
val candidate = normalized.split(' ').toSet()
val qualifiers = setOf("special", "story", "stories", "side", "sequel", "season", "part", "volume", "vol", "extra", "remake", "novel")
val plausible = (listOf(primary) + aliases).any { name ->
val tokens = name.split(' ').filter { it.isNotBlank() }.toSet()
tokens.size >= 3 && candidate.size >= 3 &&
tokens.filter { it.any(Char::isDigit) }.toSet() == candidate.filter { it.any(Char::isDigit) }.toSet() &&
tokens.intersect(qualifiers) == candidate.intersect(qualifiers) &&
tokens.intersect(candidate).size.toDouble() / tokens.union(candidate).size >= 0.8
}
return MigrationMatchReason.SimilarTitle.takeIf { plausible }
}
fun migrationSourceCompatible(original: Manga, destination: Source): Boolean =
destination.isAdded && destination.isActive && destination.itemType == original.itemType &&
(original.lang.isBlank() || destination.lang.isBlank() || destination.lang.equals("all", true) ||
destination.lang.equals(original.lang, true))
/** Uncertain/unnumbered entries stay independent, even when their display names repeat. */
fun migrationChapterCoverage(detail: RemoteDetail): Int = detail.chapters.mapIndexed { index, chapter ->
chapterReleaseIdentity(detail.title, chapter.title) ?: index
}.toSet().size
internal class MigrationPlanner(
private val database: YokanDatabase,
private val runtimeFactory: ExtensionRuntimeFactory,
private val limits: MigrationSearchLimits,
) {
private val detailCache = mutableMapOf<MigrationCandidateKey, RemoteDetail>()
private val cacheMutex = Mutex()
suspend fun discover(original: Manga, destinations: List<Source>): List<MigrationSourceResult> = coroutineScope {
val semaphore = Semaphore(limits.parallelSources)
destinations.map { destination -> async { semaphore.withPermit { search(original, destination) } } }.awaitAll()
}
private suspend fun search(original: Manga, destination: Source): MigrationSourceResult {
val candidates = mutableListOf<MigrationCandidate>()
val issues = mutableSetOf<MigrationSearchIssue>()
val installed = database.source(destination.id)?.toDomain()
if (installed == null || !migrationSourceCompatible(original, installed) || installed.name != destination.name ||
installed.baseUrl != destination.baseUrl || installed.lang != destination.lang || installed.sourceCodeLanguage != destination.sourceCodeLanguage) {
return MigrationSourceResult(destination, emptyList(), setOf(MigrationSearchIssue.Failed))
}
try {
withTimeout(limits.sourceTimeoutMillis) {
val allQueries = (listOf(original.name) + original.alternativeTitles)
.filter { it.isNotBlank() }.distinctBy(::normalizeMigrationTitle)
if (allQueries.size > limits.maxQueries) issues += MigrationSearchIssue.Truncated
val plausible = linkedMapOf<String, Pair<RemoteManga, MigrationMatchReason>>()
var resultCount = 0
for (query in allQueries.take(limits.maxQueries)) {
for (page in 1..limits.maxPagesPerQuery) {
val listing = runtimeFactory.withSourceRuntime(database, destination.id) { it.search(query, page, emptyList()) }
val remaining = (limits.maxResults - resultCount).coerceAtLeast(0)
if (listing.items.size > remaining) issues += MigrationSearchIssue.Truncated
listing.items.take(remaining).forEach { item ->
val reason = migrationMatchReason(original, item.title) ?: return@forEach
if (item.url.isNotBlank() && item.url !in plausible) plausible[item.url] = item to reason
}
resultCount += listing.items.size
if (!listing.hasNextPage) break
if (page == limits.maxPagesPerQuery || resultCount >= limits.maxResults) {
issues += MigrationSearchIssue.Truncated
break
}
}
if (resultCount >= limits.maxResults) {
if (query != allQueries.take(limits.maxQueries).last()) issues += MigrationSearchIssue.Truncated
break
}
}
// Exact/alias details first when the detail budget is exhausted, then stable URL.
val ordered = plausible.values.sortedWith(compareBy<Pair<RemoteManga, MigrationMatchReason>> { it.second.ordinal }.thenBy { it.first.url })
if (ordered.size > limits.maxDetails) issues += MigrationSearchIssue.Truncated
for ((item, _) in ordered.take(limits.maxDetails)) {
try {
val key = MigrationCandidateKey(destination.id, item.url)
val detail = cacheMutex.withLock { detailCache[key] }
?: runtimeFactory.withSourceRuntime(database, destination.id) { it.detail(item.url) }
.also { fetched -> cacheMutex.withLock { detailCache[key] = fetched } }
val reason = migrationMatchReason(original, detail.title)
if (reason == null || detail.url.isBlank()) {
issues += MigrationSearchIssue.DetailFailed
continue
}
candidates += MigrationCandidate(destination, detail, migrationChapterCoverage(detail), detail.chapters.size, reason)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (_: Exception) {
issues += MigrationSearchIssue.DetailFailed
}
}
}
} catch (_: TimeoutCancellationException) {
currentCoroutineContext().ensureActive()
issues += MigrationSearchIssue.TimedOut
} catch (cancelled: CancellationException) {
throw cancelled
} catch (_: Exception) {
issues += MigrationSearchIssue.Failed
}
return MigrationSourceResult(destination, candidates.distinctBy { it.key }, issues)
}
}
internal fun rankedMigrationCandidates(results: List<MigrationSourceResult>): List<MigrationCandidate> {
val sourceOrder = results.withIndex().associate { it.value.source.id to it.index }
return results.flatMap { it.candidates }.distinctBy { it.key }.sortedWith(
compareByDescending<MigrationCandidate> { it.effectiveChapters }
.thenBy { it.reason.ordinal }.thenBy { sourceOrder.getValue(it.source.id) }.thenBy { it.detail.url },
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MigrationService.kt
- Source · implementation · 195 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
33: class MigrationService(
54: suspend fun migrate(from: Manga, destination: Source, candidate: RemoteManga): Long? = catchingNonCancellation {
60: private suspend fun migratePrepared(from: Manga, destination: Source, detail: RemoteDetail): Long? = catchingNonCancellation {
92: fun start(sourceId: Long, destinationIds: List<Long>, mangaIds: List<Long>): Boolean {
123: private suspend fun discover(mangaId: Long, destinations: List<Source>, planner: MigrationPlanner = MigrationPlanner(database, runtimeFactory, searchLimits)) {
137: fun select(mangaId: Long, key: MigrationCandidateKey?) {
148: fun retry(mangaId: Long) {
168: fun commitSelected() {
187: fun cancel() {
192: private fun updateItem(mangaId: Long, transform: (MigrationReviewItem) -> MigrationReviewItem) {
Exact file bytes / download · SHA-256 b9aa46cf4aeebb337ee7d5164db0beee38be1be9a6db2a7aa2ca642fa19fdc7c.
Complete file
package eu.friedcutlet.yokan.services.migration
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.mergePrivateNotes
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
import eu.friedcutlet.yokan.services.library.withoutUpdateError
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.Job
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.update
/**
* Moves library titles to another source. Single and mass migration share [migrate]; a mass run
* lives in the app [scope], so it keeps going after its screen is left.
*/
class MigrationService(
private val repository: YokanRepository,
private val database: YokanDatabase,
private val runtimeFactory: ExtensionRuntimeFactory,
private val settings: SettingsStore,
private val scope: CoroutineScope,
private val searchLimits: MigrationSearchLimits = MigrationSearchLimits(),
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) {
private var job: Job? = null
private val _progress = MutableStateFlow<MassMigrationProgress?>(null)
/** The latest mass run; stays at its final value until the next [start]. */
val progress: StateFlow<MassMigrationProgress?> = _progress.asStateFlow()
/**
* Fetches [candidate]'s detail from [destination] (which stores its chapters), copies read and
* bookmark state where chapter names align, transfers categories, unfavorites [from] and
* clears its update error. Returns the new title id, or null when the destination is no longer
* installed or the fetch fails.
*/
suspend fun migrate(from: Manga, destination: Source, candidate: RemoteManga): Long? = catchingNonCancellation {
val detail = runtimeFactory.withSourceRuntime(database, destination.id) { it.detail(candidate.url) }
migratePrepared(from, destination, detail)
}.getOrNull()
/** The reviewed detail is reused; applying a proposal never performs a fresh network fetch. */
private suspend fun migratePrepared(from: Manga, destination: Source, detail: RemoteDetail): Long? = catchingNonCancellation {
val installed = repository.source(destination.id) ?: return@catchingNonCancellation null
check(installed.isAdded && installed.isActive && installed.itemType == destination.itemType &&
installed.name == destination.name && installed.lang == destination.lang && installed.baseUrl == destination.baseUrl &&
installed.sourceCodeLanguage == destination.sourceCodeLanguage)
val original = repository.manga(from.id) ?: return@catchingNonCancellation null
check(original.favorite && original.link == from.link && original.sourceId == from.sourceId)
currentCoroutineContext().ensureActive()
val newManga = repository.upsertRemoteDetail(destination, detail, favorite = true)
check(newManga.id != from.id)
val oldChapters = repository.chapters(from.id)
repository.chapters(newManga.id).forEach { newChapter ->
val match = oldChapters.firstOrNull { old ->
old.name.equals(newChapter.name, ignoreCase = true) ||
old.url.endsWith(newChapter.url.substringAfterLast('/'))
} ?: return@forEach
if (match.isRead || match.isBookmarked) {
repository.setChaptersRead(setOf(newChapter.id), match.isRead, match.lastPageRead.takeIf { it.isNotBlank() }, 0)
repository.setChaptersBookmarked(setOf(newChapter.id), match.isBookmarked)
}
}
val oldNote = repository.manga(from.id)?.privateNote.orEmpty()
checkNotNull(repository.setMangaPrivateNote(newManga.id, mergePrivateNotes(newManga.privateNote, oldNote)))
repository.setMangaCategories(newManga.id, from.categories)
settings.updateDb { it.withoutUpdateError(from.id) }
currentCoroutineContext().ensureActive()
repository.setMangaFavorite(from.id, false)
newManga.id
}.onFailure { AppLogger.warn("[migration] title ${from.id} to ${destination.name} failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
.getOrNull()
/** Starts discovery only. Re-entering the same route attaches to its existing run. */
fun start(sourceId: Long, destinationIds: List<Long>, mangaIds: List<Long>): Boolean {
val ids = destinationIds.distinct()
val titles = mangaIds.distinct()
val current = _progress.value
if (current?.sourceId == sourceId && current.destinationIds == ids && current.mangaIds == titles) return true
if (current?.running == true || current?.phase == MigrationPhase.Reviewing || job?.isActive == true) return false
val source = repository.source(sourceId) ?: return false
val destinations = ids.mapNotNull(repository::source)
if (destinations.size != ids.size || destinations.isEmpty() || destinations.any {
it.id == source.id || !it.isAdded || !it.isActive || it.itemType != source.itemType
}) return false
val targets = titles.mapNotNull(repository::manga).filter {
it.favorite && it.itemType == source.itemType && (it.sourceId == source.id ||
(it.sourceId == null && it.source == source.name && (it.lang.isBlank() || it.lang == source.lang)))
}
val started = MassMigrationProgress(sourceId, ids, titles, targets.map {
MigrationReviewItem(it, repository.chapters(it.id).size)
}, MigrationPhase.Searching)
if (!_progress.compareAndSet(current, started)) return false
job = scope.launch(workDispatcher) {
try {
val planner = MigrationPlanner(database, runtimeFactory, searchLimits)
for (target in targets) discover(target.id, destinations, planner)
_progress.update { it?.copy(phase = MigrationPhase.Reviewing) }
} finally {
if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) }
}
}
return true
}
private suspend fun discover(mangaId: Long, destinations: List<Source>, planner: MigrationPlanner = MigrationPlanner(database, runtimeFactory, searchLimits)) {
val original = _progress.value?.items?.firstOrNull { it.original.id == mangaId }?.original ?: return
val results = planner.discover(original, destinations)
val candidates = rankedMigrationCandidates(results)
updateItem(mangaId) { item -> item.copy(
sources = results, candidates = candidates, selected = candidates.firstOrNull()?.key,
status = when {
candidates.isNotEmpty() -> MigrationItemStatus.Ready
results.any { it.issues.isNotEmpty() } -> MigrationItemStatus.Failed
else -> MigrationItemStatus.Unmatched
},
) }
}
fun select(mangaId: Long, key: MigrationCandidateKey?) {
_progress.update { run ->
if (run?.phase != MigrationPhase.Reviewing) run else run.copy(items = run.items.map { item ->
if (item.original.id != mangaId || item.status == MigrationItemStatus.Migrated || item.status == MigrationItemStatus.Pending ||
(key != null && item.candidates.none { it.key == key })) item
else item.copy(selected = key, status = if (key == null) MigrationItemStatus.Skipped else MigrationItemStatus.Ready)
})
}
}
/** Retry is explicit and refreshes search/details; other reviewed rows stay intact. */
fun retry(mangaId: Long) {
val current = _progress.value ?: return
if (current.running || job?.isActive == true) return
val item = current.items.firstOrNull { it.original.id == mangaId } ?: return
if (item.status == MigrationItemStatus.Migrated) return
val destinations = current.destinationIds.mapNotNull { id -> repository.source(id)
?: current.items.flatMap { it.sources }.firstOrNull { it.source.id == id }?.source }
if (!_progress.compareAndSet(current, current.copy(phase = MigrationPhase.Searching,
items = current.items.map { if (it.original.id == mangaId) it.copy(status = MigrationItemStatus.Pending, selected = null) else it }))) return
job = scope.launch(workDispatcher) {
try {
discover(mangaId, destinations)
_progress.update { it?.copy(phase = MigrationPhase.Reviewing) }
} finally {
if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) }
}
}
}
/** Called only from review. Incomplete source results stay visible beside the chosen winner. */
fun commitSelected() {
val current = _progress.value ?: return
if (current.phase != MigrationPhase.Reviewing || current.selectedCount == 0 || current.items.any { it.status == MigrationItemStatus.Pending } || job?.isActive == true) return
if (!_progress.compareAndSet(current, current.copy(phase = MigrationPhase.Migrating))) return
job = scope.launch(workDispatcher) {
try {
for (item in current.items.filter { it.status == MigrationItemStatus.Ready && it.selected != null }) {
currentCoroutineContext().ensureActive()
val candidate = item.candidates.firstOrNull { it.key == item.selected } ?: continue
val migrated = migratePrepared(item.original, candidate.source, candidate.detail) != null
updateItem(item.original.id) { it.copy(status = if (migrated) MigrationItemStatus.Migrated else MigrationItemStatus.Failed) }
}
_progress.update { it?.copy(phase = MigrationPhase.Completed) }
} finally {
if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) }
}
}
}
fun cancel() {
if (job?.isActive == true) job?.cancel()
else _progress.update { it?.copy(phase = MigrationPhase.Cancelled) }
}
private fun updateItem(mangaId: Long, transform: (MigrationReviewItem) -> MigrationReviewItem) {
_progress.update { run -> run?.copy(items = run.items.map { if (it.original.id == mangaId) transform(it) else it }) }
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/BrowseScreen.kt
- Source · implementation · 845 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
91: internal fun BrowseRoute(
118: private enum class BrowseMode { Sources, Extensions }
120: private data class BrowseTab(
127: internal fun BrowseScreen(
339: private fun SourcesPane(
412: private fun LocalLibraryTile(itemType: ItemType, onClick: () -> Unit) {
444: private fun ExtensionsPane(
560: private fun SectionHeader(
605: private fun SourceRow(source: Source, onOpen: (Source) -> Unit, onTogglePinned: (Source) -> Unit) {
658: private enum class ExtensionRowMode { Update, Installed, NotInstalled }
661: private fun ExtensionRow(
803: private fun SourceIcon(source: Source) {
831: private fun NsfwBadge(modifier: Modifier = Modifier) {
Exact file bytes / download · SHA-256 c309bcfd998c8521cb20b2febb4b1de37f0ae72a66fcecedfa026fded635ce19.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
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.rememberLazyListState
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.Add
import androidx.compose.material.icons.filled.Extension
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.Language
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.TravelExplore
import androidx.compose.material.icons.outlined.DeleteOutline
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.PushPin
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.SystemUpdateAlt
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Badge
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.PrimaryScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
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.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil3.compose.AsyncImage
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import kotlinx.coroutines.launch
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_open
import yokan.composeapp.generated.resources.action_refresh
import yokan.composeapp.generated.resources.nav_browse
import yokan.composeapp.generated.resources.ok
import yokan.composeapp.generated.resources.ui_search_dots
import eu.friedcutlet.yokan.ui.navigation.NavSection
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.app.YokanRuntime
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.AppBarSearchField
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.services.extensions.languageName
@Composable
internal fun BrowseRoute(
nav: Navigator,
onAddSignedCatalog: (() -> Unit)?,
signedCatalogSheet: @Composable () -> Unit,
) {
val vm = viewModel { BrowseViewModel(YokanRuntime.repository, YokanRuntime.settings, YokanRuntime.sourceInstall) }
val state by vm.state.collectAsStateWithLifecycle()
val rootItemType by nav.itemType.collectAsStateWithLifecycle()
val hiddenSections by nav.hiddenSections.collectAsStateWithLifecycle()
BrowseScreen(
state = state,
rootItemType = rootItemType,
hiddenSections = hiddenSections,
onItemTypeSettled = nav::selectItemType,
onNavigate = nav::navigate,
onTogglePinned = vm::togglePinned,
onRefresh = vm::refresh,
onUpdateAll = vm::updateAll,
onInstall = vm::install,
onUninstall = vm::uninstall,
onAddSignedCatalog = onAddSignedCatalog,
addSignedCatalogLabel = onAddSignedCatalog?.let { "Add signed catalog" },
signedCatalogSheet = signedCatalogSheet,
)
}
/** Top-level mode within the Browse tab: installed sources vs. extension catalogue. */
private enum class BrowseMode { Sources, Extensions }
private data class BrowseTab(
val itemType: ItemType,
val mode: BrowseMode,
)
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
internal fun BrowseScreen(
state: BrowseUiState,
rootItemType: ItemType,
hiddenSections: Set<NavSection>,
onItemTypeSettled: (ItemType) -> Unit,
onNavigate: (Route) -> Unit,
onTogglePinned: (Source) -> Unit,
onRefresh: (ItemType) -> Unit,
onUpdateAll: (ItemType, List<Long>) -> Unit,
onInstall: (sourceId: Long) -> Unit,
onUninstall: (sourceId: Long) -> Unit,
onAddSignedCatalog: (() -> Unit)? = null,
addSignedCatalogLabel: String? = null,
signedCatalogSheet: @Composable () -> Unit = {},
) {
val itemTypes = remember(hiddenSections) {
listOf(ItemType.Manga, ItemType.Anime, ItemType.Novel).filter { type ->
when (type) {
ItemType.Manga -> NavSection.MangaLibrary !in hiddenSections
ItemType.Anime -> NavSection.AnimeLibrary !in hiddenSections
ItemType.Novel -> NavSection.NovelLibrary !in hiddenSections
}
}
}
if (itemTypes.isEmpty()) return
// Mangayomi uses one continuous, scrollable tab hierarchy: all source tabs
// first, followed by the matching extension catalogues.
val browseTabs = remember(itemTypes) {
itemTypes.map { BrowseTab(it, BrowseMode.Sources) } +
itemTypes.map { BrowseTab(it, BrowseMode.Extensions) }
}
val initialPage = remember(browseTabs, rootItemType) {
browseTabs.indexOfFirst {
it.itemType == rootItemType && it.mode == BrowseMode.Sources
}.takeIf { it >= 0 } ?: 0
}
val pagerState = rememberPagerState(initialPage = initialPage, pageCount = { browseTabs.size })
val scope = rememberCoroutineScope()
val selectedPage = pagerState.currentPage.coerceIn(browseTabs.indices)
val currentTab = browseTabs[selectedPage]
var searching by remember { mutableStateOf(false) }
var query by remember { mutableStateOf("") }
LaunchedEffect(browseTabs.size) {
if (pagerState.currentPage > browseTabs.lastIndex) {
pagerState.scrollToPage(browseTabs.lastIndex)
}
}
LaunchedEffect(pagerState, browseTabs) {
snapshotFlow { pagerState.settledPage }.collect { page ->
val tab = browseTabs.getOrNull(page) ?: return@collect
onItemTypeSettled(tab.itemType)
query = ""
searching = false
}
}
Scaffold(
topBar = {
Column {
TopAppBar(
title = {
Text(
text = stringResource(Res.string.nav_browse),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
actions = {
when (currentTab.mode) {
BrowseMode.Sources -> {
if (onAddSignedCatalog != null && !addSignedCatalogLabel.isNullOrBlank()) {
IconButton(onClick = onAddSignedCatalog) {
Icon(Icons.Filled.Add, contentDescription = addSignedCatalogLabel)
}
}
IconButton(
onClick = { onNavigate(Route.GlobalSearch(currentTab.itemType)) },
) {
Icon(Icons.Filled.TravelExplore, contentDescription = "Global search")
}
IconButton(
onClick = { onNavigate(Route.SourceFilters(currentTab.itemType)) },
) {
Icon(Icons.Filled.FilterList, contentDescription = "Filter sources")
}
}
BrowseMode.Extensions -> {
if (searching) {
AppBarSearchField(
query = query,
placeholder = stringResource(Res.string.ui_search_dots),
onQueryChange = { query = it },
onClose = {
query = ""
searching = false
},
modifier = Modifier.width(220.dp),
)
} else {
IconButton(
onClick = { onNavigate(Route.CreateExtension(currentTab.itemType)) },
) {
Icon(Icons.Filled.Add, contentDescription = "Create extension")
}
IconButton(onClick = { searching = true }) {
Icon(Icons.Filled.Search, contentDescription = "Search extensions")
}
}
IconButton(
onClick = { onNavigate(Route.ExtensionLanguages(currentTab.itemType)) },
) {
Icon(Icons.Filled.Language, contentDescription = "Extension languages")
}
}
}
},
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),
)
PrimaryScrollableTabRow(
selectedTabIndex = selectedPage,
edgePadding = 0.dp,
modifier = Modifier.fillMaxWidth(),
containerColor = Color.Transparent,
divider = {},
) {
browseTabs.forEachIndexed { index, tab ->
val updateCount = if (tab.mode == BrowseMode.Extensions) {
state.sources[tab.itemType]?.updateCount ?: 0
} else {
0
}
Tab(
selected = index == selectedPage,
onClick = {
if (index != selectedPage) {
query = ""
searching = false
scope.launch { pagerState.animateScrollToPage(index) }
}
},
text = {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
"${tab.itemType.label} ${
if (tab.mode == BrowseMode.Extensions) "Extensions" else "Sources"
}",
)
if (updateCount > 0) {
Badge(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
) {
Text(updateCount.toString())
}
}
}
},
)
}
}
}
},
) { padding ->
HorizontalPager(
state = pagerState,
beyondViewportPageCount = 1,
modifier = Modifier.fillMaxSize().padding(padding),
) { page ->
val tab = browseTabs[page]
when (tab.mode) {
BrowseMode.Sources -> SourcesPane(
sources = state.sources[tab.itemType] ?: BrowseSources(),
itemType = tab.itemType,
onOpenSource = { source -> onNavigate(Route.SourceHome(source.id)) },
onTogglePinned = onTogglePinned,
onOpenLocal = { onNavigate(Route.LocalLibraryBrowse(tab.itemType)) },
onShowExtensions = {
val extensionPage = browseTabs.indexOfFirst {
it.itemType == tab.itemType && it.mode == BrowseMode.Extensions
}
if (extensionPage >= 0) {
scope.launch { pagerState.animateScrollToPage(extensionPage) }
}
},
)
BrowseMode.Extensions -> ExtensionsPane(
catalog = state.sources[tab.itemType]?.catalog.orEmpty(),
query = if (page == selectedPage) query else "",
refreshing = tab.itemType in state.refreshing,
refreshFailed = tab.itemType in state.refreshFailed,
updatingAll = tab.itemType in state.updatingAll,
installing = state.installing,
installFailed = state.installFailed,
onRefresh = { onRefresh(tab.itemType) },
onUpdateAll = { ids -> onUpdateAll(tab.itemType, ids) },
onInstall = onInstall,
onUninstall = onUninstall,
onOpenSettings = { source -> onNavigate(Route.ExtensionDetail(source.id)) },
)
}
}
}
// One caller-owned sheet, never one instance per composed pager page.
signedCatalogSheet()
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun SourcesPane(
sources: BrowseSources,
itemType: ItemType,
onShowExtensions: () -> Unit,
onOpenSource: (Source) -> Unit,
onTogglePinned: (Source) -> Unit,
onOpenLocal: () -> Unit,
) {
val lastUsed = sources.lastUsed
val pinned = sources.pinned
val byLanguage = sources.byLanguage
if (sources.visible.isEmpty()) {
Column(
modifier = Modifier.fillMaxSize().padding(top = 10.dp),
verticalArrangement = Arrangement.Center,
) {
EmptyState(
icon = Icons.Filled.Extension,
title = "No sources installed",
modifier = Modifier.fillMaxWidth(),
action = {
ElevatedButton(onClick = onShowExtensions) {
Icon(Icons.Filled.Extension, contentDescription = null)
Text(
text = "Show extensions",
modifier = Modifier.padding(start = 8.dp),
)
}
},
)
SectionHeader("Other")
LocalLibraryTile(itemType = itemType, onClick = onOpenLocal)
}
return
}
val listState = rememberLazyListState()
ScrollbarBox(state = listState, modifier = Modifier.fillMaxSize()) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize().padding(top = 10.dp),
) {
if (lastUsed.isNotEmpty()) {
item(key = "src-header-last-used") { SectionHeader("Last used") }
items(lastUsed.size, key = { "last-${lastUsed[it].id}" }) { index ->
SourceRow(lastUsed[index], onOpenSource, onTogglePinned)
}
}
if (pinned.isNotEmpty()) {
item(key = "src-header-pinned") { SectionHeader("Pinned") }
items(pinned.size, key = { "pin-${pinned[it].id}" }) { index ->
SourceRow(pinned[index], onOpenSource, onTogglePinned)
}
}
byLanguage.forEach { (language, rows) ->
item(key = "src-header-$language") { SectionHeader(language) }
items(rows.size, key = { "src-$language-${rows[it].id}" }) { index ->
SourceRow(rows[index], onOpenSource, onTogglePinned)
}
}
item(key = "src-header-other") { SectionHeader("Other") }
item(key = "local-library-tile") {
LocalLibraryTile(
itemType = itemType,
onClick = onOpenLocal,
)
}
}
}
}
@Composable
private fun LocalLibraryTile(itemType: ItemType, onClick: () -> Unit) {
ListItem(
modifier = Modifier
.fillMaxWidth()
.hoverHighlight(onClick = onClick),
headlineContent = { Text("Local source ${itemType.label}") },
supportingContent = {
Text(
text = "",
style = MaterialTheme.typography.bodySmall,
)
},
leadingContent = {
Box(
modifier = Modifier
.size(37.dp)
.clip(RoundedCornerShape(5.dp))
.background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Extension, contentDescription = null)
}
},
trailingContent = {
TextButton(onClick = onClick) { Text(stringResource(Res.string.action_open)) }
},
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
)
}
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
private fun ExtensionsPane(
catalog: List<Source>,
query: String,
refreshing: Boolean,
refreshFailed: Boolean,
updatingAll: Boolean,
installing: Set<Long>,
installFailed: Set<Long>,
onRefresh: () -> Unit,
onUpdateAll: (List<Long>) -> Unit,
onInstall: (sourceId: Long) -> Unit,
onUninstall: (sourceId: Long) -> Unit,
onOpenSettings: (Source) -> Unit,
) {
val sections = remember(catalog, query) { extensionSections(catalog, query) }
val updates = sections.updates
val installed = sections.installed
val availableByLanguage = sections.availableByLanguage
val listState = rememberLazyListState()
PullToRefreshBox(
modifier = Modifier.fillMaxSize(),
isRefreshing = refreshing,
onRefresh = onRefresh,
) {
ScrollbarBox(state = listState, modifier = Modifier.fillMaxSize()) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize().padding(top = 10.dp),
) {
if (updates.isNotEmpty()) {
item(key = "ext-header-updates") {
SectionHeader(
label = "Update pending",
updating = updatingAll,
onUpdateAll = { onUpdateAll(updates.map { it.id }) },
)
}
items(updates.size, key = { "upd-${updates[it].id}" }) { index ->
ExtensionRow(
source = updates[index],
mode = ExtensionRowMode.Update,
working = updates[index].id in installing,
failed = updates[index].id in installFailed,
onInstall = onInstall,
onUninstall = onUninstall,
onOpenSettings = onOpenSettings,
)
}
}
if (installed.isNotEmpty()) {
item(key = "ext-header-installed") { SectionHeader("Installed") }
items(installed.size, key = { "ins-${installed[it].id}" }) { index ->
ExtensionRow(
source = installed[index],
mode = ExtensionRowMode.Installed,
working = installed[index].id in installing,
failed = installed[index].id in installFailed,
onInstall = onInstall,
onUninstall = onUninstall,
onOpenSettings = onOpenSettings,
)
}
}
availableByLanguage.forEach { (language, rows) ->
item(key = "ext-available-$language") { SectionHeader(language) }
items(rows.size, key = { "av-$language-${rows[it].id}" }) { index ->
ExtensionRow(
source = rows[index],
mode = ExtensionRowMode.NotInstalled,
working = rows[index].id in installing,
failed = rows[index].id in installFailed,
onInstall = onInstall,
onUninstall = onUninstall,
onOpenSettings = onOpenSettings,
)
}
}
if (sections.isEmpty) {
item(key = "ext-empty") {
Box(
modifier = Modifier.fillMaxWidth().padding(24.dp),
contentAlignment = Alignment.Center,
) {
when {
refreshing -> CircularProgressIndicator()
refreshFailed && query.isBlank() -> Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "Unable to refresh extensions",
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
ElevatedButton(onClick = onRefresh) {
Text(stringResource(Res.string.action_refresh))
}
}
else -> Text(
text = if (query.isBlank()) {
"No extensions available"
} else {
"No extensions match \"$query\""
},
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
}
}
}
}
@Composable
private fun SectionHeader(
label: String,
updating: Boolean = false,
onUpdateAll: (() -> Unit)? = null,
) {
if (onUpdateAll == null) {
Text(
text = label,
fontWeight = FontWeight.Bold,
fontSize = 13.sp,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.fillMaxWidth().padding(start = 12.dp, top = 8.dp, end = 12.dp),
)
return
}
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = label,
fontWeight = FontWeight.Bold,
fontSize = 13.sp,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f),
)
ElevatedButton(
enabled = !updating,
onClick = onUpdateAll,
) {
if (updating) {
CircularProgressIndicator(
modifier = Modifier.size(16.dp),
strokeWidth = 2.dp,
)
} else {
Text("Update all")
}
}
}
}
@Composable
private fun SourceRow(source: Source, onOpen: (Source) -> Unit, onTogglePinned: (Source) -> Unit) {
val openSource = { onOpen(source) }
ListItem(
modifier = Modifier
.fillMaxWidth()
.hoverHighlight(onClick = openSource),
headlineContent = {
Text(
text = source.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
},
supportingContent = {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = languageName(source.lang),
fontSize = 12.sp,
fontWeight = FontWeight.Light,
)
if (source.isNsfw) {
NsfwBadge(modifier = Modifier.padding(start = 4.dp))
}
}
},
leadingContent = { SourceIcon(source) },
trailingContent = {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
if (source.supportLatest) {
TextButton(onClick = openSource) {
Text("Latest")
}
}
IconButton(onClick = { onTogglePinned(source) }) {
Icon(
imageVector = Icons.Outlined.PushPin,
contentDescription = if (source.isPinned) "Unpin source" else "Pin source",
tint = if (source.isPinned) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
}
},
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
)
}
private enum class ExtensionRowMode { Update, Installed, NotInstalled }
@Composable
private fun ExtensionRow(
source: Source,
mode: ExtensionRowMode,
working: Boolean,
failed: Boolean,
onInstall: (sourceId: Long) -> Unit,
onUninstall: (sourceId: Long) -> Unit,
onOpenSettings: (Source) -> Unit,
) {
var showUninstallDialog by remember(source.id) { mutableStateOf(false) }
val installOrUpdate: () -> Unit = { onInstall(source.id) }
val openSettings: () -> Unit = { onOpenSettings(source) }
val rowAction: (() -> Unit)? = when {
working -> null
source.isAdded -> openSettings
else -> installOrUpdate
}
ListItem(
modifier = Modifier
.fillMaxWidth()
.hoverHighlight(onClick = rowAction),
headlineContent = {
Text(
text = source.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
},
supportingContent = {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = languageName(source.lang),
fontSize = 12.sp,
fontWeight = FontWeight.Light,
)
Text(
text = source.version,
fontSize = 12.sp,
fontWeight = FontWeight.Light,
modifier = Modifier.padding(start = 4.dp),
)
if (source.isNsfw) {
NsfwBadge(modifier = Modifier.padding(start = 4.dp))
}
source.repo?.name?.takeIf { it.isNotBlank() }?.let { repoName ->
Text(
text = "- $repoName",
fontSize = 12.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 4.dp).weight(1f, fill = false),
)
}
if (source.isObsolete) {
Text(
text = "OBSOLETE",
color = MaterialTheme.colorScheme.primary,
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 4.dp),
)
}
when {
failed -> Text(
text = "FAILED",
color = MaterialTheme.colorScheme.error,
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(start = 4.dp),
)
}
}
},
leadingContent = { SourceIcon(source) },
trailingContent = {
if (working) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
strokeWidth = 2.dp,
)
} else {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(2.dp),
) {
when (mode) {
ExtensionRowMode.Update -> {
IconButton(
onClick = installOrUpdate,
) {
Icon(Icons.Outlined.SystemUpdateAlt, contentDescription = "Update extension")
}
}
ExtensionRowMode.Installed -> {
IconButton(onClick = openSettings) {
Icon(Icons.Outlined.Settings, contentDescription = "Extension settings")
}
}
ExtensionRowMode.NotInstalled -> {
IconButton(
onClick = installOrUpdate,
) {
Icon(Icons.Outlined.Download, contentDescription = "Install extension")
}
}
}
if (source.isAdded) {
IconButton(onClick = { showUninstallDialog = true }) {
Icon(Icons.Outlined.DeleteOutline, contentDescription = "Uninstall extension")
}
}
}
}
},
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
)
if (showUninstallDialog) {
AlertDialog(
onDismissRequest = { showUninstallDialog = false },
title = { Text(source.name) },
text = { Text("Uninstall extension ${source.name}?") },
dismissButton = {
TextButton(onClick = { showUninstallDialog = false }) { Text(stringResource(Res.string.action_cancel)) }
},
confirmButton = {
TextButton(
onClick = {
showUninstallDialog = false
onUninstall(source.id)
},
) {
Text(stringResource(Res.string.ok))
}
},
)
}
}
@Composable
private fun SourceIcon(source: Source) {
val iconUrl = source.iconUrl?.takeIf { it.isNotBlank() }
var loadFailed by remember(iconUrl) { mutableStateOf(false) }
Box(
modifier = Modifier
.size(37.dp)
.clip(RoundedCornerShape(5.dp))
.background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = Icons.Filled.Extension,
contentDescription = null,
modifier = Modifier.size(24.dp),
)
if (iconUrl != null && !loadFailed) {
AsyncImage(
model = iconUrl,
contentDescription = "${source.name} icon",
contentScale = ContentScale.Fit,
modifier = Modifier.fillMaxSize(),
onError = { loadFailed = true },
)
}
}
}
@Composable
private fun NsfwBadge(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.clip(RoundedCornerShape(4.dp))
.background(Color.Red.copy(alpha = 0.8f))
.padding(horizontal = 4.dp, vertical = 1.dp),
) {
Text(
text = "NSFW",
color = Color.White,
fontSize = 8.sp,
fontWeight = FontWeight.Bold,
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/BrowseViewModel.kt
- Source · implementation · 177 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
28: internal data class BrowseSources(
40: internal data class BrowseUiState(
50: private fun needsUpdate(source: Source): Boolean = VersionComparison.isOutdated(source.version, source.versionLast)
52: private fun sortedByLanguage(sources: List<Source>): List<Pair<String, List<Source>>> = sources
59: internal fun extensionSections(catalog: List<Source>, query: String): ExtensionSections {
69: internal data class ExtensionSections(
76: private fun browseSources(type: ItemType, all: List<Source>, db: DbSettings): BrowseSources {
99: private fun allBrowseSources(all: Map<ItemType, List<Source>>, db: DbSettings): Map<ItemType, BrowseSources> =
103: internal class BrowseViewModel(
129: fun togglePinned(source: Source) = repository.setSourcePinned(source.id, !source.isPinned)
132: fun refresh(itemType: ItemType) {
152: fun updateAll(itemType: ItemType, sourceIds: List<Long>) {
160: fun install(sourceId: Long) {
174: fun uninstall(sourceId: Long) {
Exact file bytes / download · SHA-256 3a62dc3cead83bde8cfc0d64b4a224c1a6a257904d80b7f9637d15e1d453f673.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.SourceInstallService
import eu.friedcutlet.yokan.services.extensions.VersionComparison
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.services.extensions.languageName
/** One item type's Browse panes, grouped off the main thread. */
internal data class BrowseSources(
/** Added, active sources (NSFW-filtered); empty shows the "no sources" state. */
val visible: List<Source> = emptyList(),
val lastUsed: List<Source> = emptyList(),
val pinned: List<Source> = emptyList(),
val byLanguage: List<Pair<String, List<Source>>> = emptyList(),
/** Active extensions (NSFW-filtered, hidden repositories dropped) before the search query. */
val catalog: List<Source> = emptyList(),
/** Active sources with a newer version, for the Extensions tab badge. */
val updateCount: Int = 0,
)
internal data class BrowseUiState(
val sources: Map<ItemType, BrowseSources> = emptyMap(),
val refreshing: Set<ItemType> = emptySet(),
val refreshFailed: Set<ItemType> = emptySet(),
val updatingAll: Set<ItemType> = emptySet(),
/** Source ids with an install or update in flight. */
val installing: Set<Long> = emptySet(),
val installFailed: Set<Long> = emptySet(),
)
private fun needsUpdate(source: Source): Boolean = VersionComparison.isOutdated(source.version, source.versionLast)
private fun sortedByLanguage(sources: List<Source>): List<Pair<String, List<Source>>> = sources
.groupBy { languageName(it.lang.ifBlank { "other" }) }
.toList()
.sortedBy { (language, _) -> language }
.map { (language, rows) -> language to rows.sortedBy { it.name.lowercase() } }
/** Update, installed and per-language available sections of the extension catalogue matching [query]. */
internal fun extensionSections(catalog: List<Source>, query: String): ExtensionSections {
val filtered = if (query.isBlank()) catalog else catalog.filter { it.name.contains(query, ignoreCase = true) }
return ExtensionSections(
isEmpty = filtered.isEmpty(),
updates = filtered.filter(::needsUpdate).sortedBy { it.name.lowercase() },
installed = filtered.filter { it.isAdded && it.version == it.versionLast }.sortedBy { it.name.lowercase() },
availableByLanguage = sortedByLanguage(filtered.filter { !it.isAdded && it.version == it.versionLast }),
)
}
internal data class ExtensionSections(
val isEmpty: Boolean,
val updates: List<Source>,
val installed: List<Source>,
val availableByLanguage: List<Pair<String, List<Source>>>,
)
private fun browseSources(type: ItemType, all: List<Source>, db: DbSettings): BrowseSources {
val hiddenRepoUrls = when (type) {
ItemType.Manga -> db.mangaExtensionsRepo
ItemType.Anime -> db.animeExtensionsRepo
ItemType.Novel -> db.novelExtensionsRepo
}.orEmpty()
.filter { it.hidden == true }
.mapNotNull { it.jsonUrl?.trim() }
.toSet()
val visible = all.filter { it.isActive && it.isAdded && (db.showNsfw || !it.isNsfw) }
return BrowseSources(
visible = visible,
lastUsed = visible.filter { it.lastUsed }.sortedBy { it.name.lowercase() },
pinned = visible.filter { it.isPinned }.sortedBy { it.name.lowercase() },
byLanguage = sortedByLanguage(visible.filterNot { it.isPinned }),
catalog = all.filter { source ->
source.isActive && (db.showNsfw || !source.isNsfw) &&
source.repo?.jsonUrl?.trim()?.let { it !in hiddenRepoUrls } != false
},
updateCount = all.count { it.isActive && needsUpdate(it) },
)
}
private fun allBrowseSources(all: Map<ItemType, List<Source>>, db: DbSettings): Map<ItemType, BrowseSources> =
all.mapValues { (type, sources) -> browseSources(type, sources, db) }
/** Browse root: installed sources and the extension catalogue for every item type. */
internal class BrowseViewModel(
private val repository: YokanRepository,
settings: SettingsStore,
private val sourceInstall: SourceInstallService,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
// Seeded synchronously so the first frame never flashes "No sources installed".
private val _state = MutableStateFlow(
BrowseUiState(sources = allBrowseSources(ItemType.entries.associateWith(repository::sources), settings.db.value)),
)
val state: StateFlow<BrowseUiState> = _state.asStateFlow()
init {
viewModelScope.launch {
combine(
repository.observe({ it.sources }, workDispatcher) { ItemType.entries.associateWith { sources(it) } },
settings.db.distinctUntilChanged { old, new ->
old.showNsfw == new.showNsfw && old.mangaExtensionsRepo == new.mangaExtensionsRepo &&
old.animeExtensionsRepo == new.animeExtensionsRepo && old.novelExtensionsRepo == new.novelExtensionsRepo
},
) { all, db -> allBrowseSources(all, db) }
.flowOn(workDispatcher)
.collect { sources -> _state.update { it.copy(sources = sources) } }
}
}
fun togglePinned(source: Source) = repository.setSourcePinned(source.id, !source.isPinned)
/** Re-reads every visible repository of [itemType]. */
fun refresh(itemType: ItemType) {
if (itemType in _state.value.refreshing) return
_state.update { it.copy(refreshing = it.refreshing + itemType, refreshFailed = it.refreshFailed - itemType) }
viewModelScope.launch {
val result = catchingNonCancellation {
withContext(workDispatcher) {
repository.repositories(itemType)
.filter { it.hidden != true }
.forEach { sourceInstall.refreshRepository(itemType, it) }
}
}
_state.update {
it.copy(
refreshing = it.refreshing - itemType,
refreshFailed = if (result.isFailure) it.refreshFailed + itemType else it.refreshFailed,
)
}
}
}
fun updateAll(itemType: ItemType, sourceIds: List<Long>) {
viewModelScope.launch {
_state.update { it.copy(updatingAll = it.updatingAll + itemType) }
sourceIds.forEach { id -> catchingNonCancellation { sourceInstall.installOrUpdate(id) } }
_state.update { it.copy(updatingAll = it.updatingAll - itemType) }
}
}
fun install(sourceId: Long) {
if (sourceId in _state.value.installing) return
_state.update { it.copy(installing = it.installing + sourceId, installFailed = it.installFailed - sourceId) }
viewModelScope.launch {
val succeeded = catchingNonCancellation { sourceInstall.installOrUpdate(sourceId) }.getOrDefault(false)
_state.update {
it.copy(
installing = it.installing - sourceId,
installFailed = if (succeeded) it.installFailed else it.installFailed + sourceId,
)
}
}
}
fun uninstall(sourceId: Long) {
sourceInstall.uninstall(sourceId)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/CatalogEnrollmentViewModel.kt
- Source · implementation · 280 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
23: interface CatalogEnrollmentActions {
24: suspend fun enroll(proposal: CatalogEnrollmentCode): RecipeCatalogEnrollmentServiceResult
25: suspend fun refresh(proposal: CatalogEnrollmentCode): RecipeCatalogRefreshResult
26: suspend fun install(proposal: CatalogEnrollmentCode, stableId: String): RecipeCatalogInstallServiceResult
29: private class InstallationServiceActions(private val service: RecipeCatalogInstallationService) : CatalogEnrollmentActions {
30: override suspend fun enroll(proposal: CatalogEnrollmentCode) = service.enroll(proposal)
31: override suspend fun refresh(proposal: CatalogEnrollmentCode) = service.refresh(proposal)
32: override suspend fun install(proposal: CatalogEnrollmentCode, stableId: String) = service.install(proposal, stableId)
35: enum class CatalogEnrollmentOperation { Enrolling, Refreshing, Installing }
36: enum class CatalogEnrollmentDisplayError { InvalidCode, ConfirmationRequired, EnrollmentRejected, RefreshRejected, InstallRejected, RefreshRequired, InvalidSelection }
38: sealed interface CatalogEnrollmentRetry {
39: data object Enroll : CatalogEnrollmentRetry
40: data object Refresh : CatalogEnrollmentRetry
41: data class Install(val stableId: String) : CatalogEnrollmentRetry
45: class CatalogEnrollmentReview internal constructor(
53: data class CatalogEnrollmentUiState(
69: class CatalogEnrollmentViewModel(
79: fun updateDraft(code: String) {
99: fun reviewDraft() {
110: fun editDraft() {
126: fun setTrustConfirmed(confirmed: Boolean) {
132: fun enroll() {
167: fun refresh() {
194: fun install(stableId: String) {
226: fun dismissError() {
230: fun retry() {
239: private fun begin(operation: CatalogEnrollmentOperation, retry: CatalogEnrollmentRetry, stableId: String? = null): OperationRequest? {
258: private fun complete(request: OperationRequest, transform: (CatalogEnrollmentUiState) -> CatalogEnrollmentUiState) {
264: private fun review(proposal: CatalogEnrollmentCode): CatalogEnrollmentReview = CatalogEnrollmentReview(
272: private fun copyPreview(preview: RecipeCatalogPreview): RecipeCatalogPreview = RecipeCatalogPreview(
279: private data class OperationRequest(val proposal: CatalogEnrollmentCode, val draftRevision: Long)
Exact file bytes / download · SHA-256 70556fa331927b105cf1259605a17d249beec3cb8130fcd64f67246a170d8ed1.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.extensions.recipe.CatalogEnrollmentCode
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogEnrollmentServiceResult
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogInstallServiceResult
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogInstallationService
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogPreview
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogPreviewArtifact
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogRefreshResult
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
/** Small seam for lifecycle-safe UI tests; production uses [RecipeCatalogInstallationService]. */
interface CatalogEnrollmentActions {
suspend fun enroll(proposal: CatalogEnrollmentCode): RecipeCatalogEnrollmentServiceResult
suspend fun refresh(proposal: CatalogEnrollmentCode): RecipeCatalogRefreshResult
suspend fun install(proposal: CatalogEnrollmentCode, stableId: String): RecipeCatalogInstallServiceResult
}
private class InstallationServiceActions(private val service: RecipeCatalogInstallationService) : CatalogEnrollmentActions {
override suspend fun enroll(proposal: CatalogEnrollmentCode) = service.enroll(proposal)
override suspend fun refresh(proposal: CatalogEnrollmentCode) = service.refresh(proposal)
override suspend fun install(proposal: CatalogEnrollmentCode, stableId: String) = service.install(proposal, stableId)
}
enum class CatalogEnrollmentOperation { Enrolling, Refreshing, Installing }
enum class CatalogEnrollmentDisplayError { InvalidCode, ConfirmationRequired, EnrollmentRejected, RefreshRejected, InstallRejected, RefreshRequired, InvalidSelection }
sealed interface CatalogEnrollmentRetry {
data object Enroll : CatalogEnrollmentRetry
data object Refresh : CatalogEnrollmentRetry
data class Install(val stableId: String) : CatalogEnrollmentRetry
}
/** Review-safe proposal fields only; the raw signing key remains inside [proposal]. */
class CatalogEnrollmentReview internal constructor(
internal val proposal: CatalogEnrollmentCode,
val catalogId: String,
val catalogEnvelopeUrl: String,
val keyId: String,
val publicKeyFingerprint: String,
)
data class CatalogEnrollmentUiState(
val draftCode: String = "",
val review: CatalogEnrollmentReview? = null,
val reviewing: Boolean = false,
val enrolled: Boolean = false,
val alreadyEnrolled: Boolean = false,
val trustConfirmed: Boolean = false,
val preview: RecipeCatalogPreview? = null,
val installedRecipes: Map<String, SignedCatalogRecipeStatus> = emptyMap(),
val operation: CatalogEnrollmentOperation? = null,
val error: CatalogEnrollmentDisplayError? = null,
val retry: CatalogEnrollmentRetry? = null,
internal val draftRevision: Long = 0,
)
/** Explicit-only catalog enrollment state. No service operation runs while draft text is parsed. */
class CatalogEnrollmentViewModel(
private val actions: CatalogEnrollmentActions,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
constructor(service: RecipeCatalogInstallationService) : this(InstallationServiceActions(service))
private val _state = MutableStateFlow(CatalogEnrollmentUiState())
val state: StateFlow<CatalogEnrollmentUiState> = _state.asStateFlow()
private val operationMutex = Mutex()
fun updateDraft(code: String) {
_state.update { previous ->
if (previous.draftCode == code) return@update previous
val proposal = CatalogEnrollmentCode.parse(code)
previous.copy(
draftCode = code,
review = proposal?.let(::review),
reviewing = false,
enrolled = false,
alreadyEnrolled = false,
trustConfirmed = false,
preview = null,
installedRecipes = emptyMap(),
error = if (code.isNotEmpty() && proposal == null) CatalogEnrollmentDisplayError.InvalidCode else null,
retry = null,
draftRevision = previous.draftRevision + 1,
)
}
}
fun reviewDraft() {
_state.update { previous ->
val proposal = CatalogEnrollmentCode.parse(previous.draftCode)
if (proposal == null) {
previous.copy(review = null, reviewing = false, error = CatalogEnrollmentDisplayError.InvalidCode, retry = null)
} else {
previous.copy(review = review(proposal), reviewing = true, error = null, retry = null)
}
}
}
fun editDraft() {
_state.update { previous ->
previous.copy(
review = null,
reviewing = false,
enrolled = false,
alreadyEnrolled = false,
trustConfirmed = false,
preview = null,
installedRecipes = emptyMap(),
error = null,
retry = null,
)
}
}
fun setTrustConfirmed(confirmed: Boolean) {
_state.update { previous ->
if (previous.review == null) previous else previous.copy(trustConfirmed = confirmed, error = null, retry = null)
}
}
fun enroll() {
val request = begin(CatalogEnrollmentOperation.Enrolling, CatalogEnrollmentRetry.Enroll) ?: return
viewModelScope.launch(workDispatcher) {
try {
val result = actions.enroll(request.proposal)
complete(request) { current ->
when (result) {
RecipeCatalogEnrollmentServiceResult.Created -> current.copy(
enrolled = true,
alreadyEnrolled = false,
error = null,
retry = null,
preview = null,
)
RecipeCatalogEnrollmentServiceResult.AlreadyEnrolled -> current.copy(
enrolled = true,
alreadyEnrolled = true,
error = null,
retry = null,
preview = null,
)
is RecipeCatalogEnrollmentServiceResult.Rejected -> current.copy(error = CatalogEnrollmentDisplayError.EnrollmentRejected, retry = CatalogEnrollmentRetry.Enroll)
}
}
} catch (error: CancellationException) {
complete(request) { it }
throw error
} catch (_: Throwable) {
complete(request) { it.copy(error = CatalogEnrollmentDisplayError.EnrollmentRejected, retry = CatalogEnrollmentRetry.Enroll) }
} finally {
operationMutex.unlock()
}
}
}
fun refresh() {
val request = begin(CatalogEnrollmentOperation.Refreshing, CatalogEnrollmentRetry.Refresh) ?: return
viewModelScope.launch(workDispatcher) {
try {
val result = actions.refresh(request.proposal)
complete(request) { current ->
when (result) {
is RecipeCatalogRefreshResult.Available -> current.copy(
preview = copyPreview(result.preview),
installedRecipes = emptyMap(),
error = null,
retry = null,
)
is RecipeCatalogRefreshResult.Rejected -> current.copy(preview = null, error = CatalogEnrollmentDisplayError.RefreshRejected, retry = CatalogEnrollmentRetry.Refresh)
}
}
} catch (error: CancellationException) {
complete(request) { it.copy(preview = null) }
throw error
} catch (_: Throwable) {
complete(request) { it.copy(preview = null, error = CatalogEnrollmentDisplayError.RefreshRejected, retry = CatalogEnrollmentRetry.Refresh) }
} finally {
operationMutex.unlock()
}
}
}
fun install(stableId: String) {
val request = begin(CatalogEnrollmentOperation.Installing, CatalogEnrollmentRetry.Install(stableId), stableId) ?: return
viewModelScope.launch(workDispatcher) {
try {
val result = actions.install(request.proposal, stableId)
complete(request) { current ->
when (result) {
is RecipeCatalogInstallServiceResult.Applied -> current.copy(
installedRecipes = current.installedRecipes + (stableId to SignedCatalogRecipeStatus.Installed),
error = null,
retry = null,
)
is RecipeCatalogInstallServiceResult.Unchanged -> current.copy(
installedRecipes = current.installedRecipes + (stableId to SignedCatalogRecipeStatus.AlreadyInstalled),
error = null,
retry = null,
)
RecipeCatalogInstallServiceResult.Conflict -> current.copy(preview = null, error = CatalogEnrollmentDisplayError.RefreshRequired, retry = CatalogEnrollmentRetry.Refresh)
is RecipeCatalogInstallServiceResult.Rejected -> current.copy(error = CatalogEnrollmentDisplayError.InstallRejected, retry = CatalogEnrollmentRetry.Install(stableId))
}
}
} catch (error: CancellationException) {
complete(request) { it }
throw error
} catch (_: Throwable) {
complete(request) { it.copy(error = CatalogEnrollmentDisplayError.InstallRejected, retry = CatalogEnrollmentRetry.Install(stableId)) }
} finally {
operationMutex.unlock()
}
}
}
fun dismissError() {
_state.update { it.copy(error = null, retry = null) }
}
fun retry() {
when (val retry = _state.value.retry) {
CatalogEnrollmentRetry.Enroll -> enroll()
CatalogEnrollmentRetry.Refresh -> refresh()
is CatalogEnrollmentRetry.Install -> install(retry.stableId)
null -> Unit
}
}
private fun begin(operation: CatalogEnrollmentOperation, retry: CatalogEnrollmentRetry, stableId: String? = null): OperationRequest? {
if (!operationMutex.tryLock()) return null
var request: OperationRequest? = null
_state.update { current ->
val review = current.review
when {
review == null -> current.copy(error = CatalogEnrollmentDisplayError.InvalidCode, retry = null)
!current.trustConfirmed -> current.copy(error = CatalogEnrollmentDisplayError.ConfirmationRequired, retry = null)
stableId != null && current.preview?.artifacts?.none { it.stableId == stableId } != false ->
current.copy(error = CatalogEnrollmentDisplayError.InvalidSelection, retry = null)
else -> OperationRequest(review.proposal, current.draftRevision).also { request = it }.let {
current.copy(operation = operation, error = null, retry = retry)
}
}
}
if (request == null) operationMutex.unlock()
return request
}
private fun complete(request: OperationRequest, transform: (CatalogEnrollmentUiState) -> CatalogEnrollmentUiState) {
_state.update { current ->
if (current.draftRevision == request.draftRevision) transform(current).copy(operation = null) else current.copy(operation = null)
}
}
private fun review(proposal: CatalogEnrollmentCode): CatalogEnrollmentReview = CatalogEnrollmentReview(
proposal,
proposal.catalogId,
proposal.catalogEnvelopeUrl,
proposal.keyId,
proposal.publicKeyFingerprint,
)
private fun copyPreview(preview: RecipeCatalogPreview): RecipeCatalogPreview = RecipeCatalogPreview(
preview.catalogId,
preview.revision,
preview.expiresAtEpochSeconds,
preview.artifacts.map { RecipeCatalogPreviewArtifact(it.stableId, it.releaseVersion, it.sizeBytes) },
)
private data class OperationRequest(val proposal: CatalogEnrollmentCode, val draftRevision: Long)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GenreSearch.kt
- Source · implementation · 34 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: data class GenreSearchRequest(val query: String, val selections: Map<String, FilterSelection>)
10: fun genreSearchRequest(genre: String, filters: List<SourceFilter>): GenreSearchRequest {
Exact file bytes / download · SHA-256 667b5b015f401465e2a318aca276ae8d1c5808297824e40050304dbb9f1cdcd4.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceFilterKind
data class GenreSearchRequest(val query: String, val selections: Map<String, FilterSelection>)
/** Use the extension's outbound filter values, never the displayed genre label as a value. */
fun genreSearchRequest(genre: String, filters: List<SourceFilter>): GenreSearchRequest {
val tag = genre.trim()
val candidates = filters.mapNotNull { filter ->
// Some extensions expose the same labels in include and exclude groups.
if (filter.id.contains("exclude", ignoreCase = true) ||
excludedGroup.containsMatchIn(filter.name)) return@mapNotNull null
val name = filter.name.substringAfterLast(':').substringAfterLast('/').trim()
val entry = filter.entries.firstOrNull { it.label.trim().equals(tag, ignoreCase = true) }
val selection = when (filter.kind) {
SourceFilterKind.MultiSelect -> entry?.let { FilterSelection.Multi(setOf(it.value)) }
SourceFilterKind.SingleSelect -> entry?.let { FilterSelection.Single(it.value) }
SourceFilterKind.Toggle -> if (name.equals(tag, ignoreCase = true)) FilterSelection.Toggle(true) else null
SourceFilterKind.TriState -> if (name.equals(tag, ignoreCase = true)) FilterSelection.TriState(1) else null
SourceFilterKind.Text, SourceFilterKind.Sort -> null
}
selection?.let { filter to it }
}
val candidate = candidates.firstOrNull { (filter, _) ->
filter.name.contains("genre", ignoreCase = true) || filter.name.contains("tag", ignoreCase = true)
} ?: candidates.firstOrNull()
val selections = candidate?.let { (filter, selection) -> mapOf(filter.id to selection) }.orEmpty()
return GenreSearchRequest(query = if (selections.isEmpty()) tag else "", selections = selections)
}
private val excludedGroup = Regex("\\b(exclude|excluded|excluding|without)\\b", RegexOption.IGNORE_CASE)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GlobalSearchScreen.kt
- Source · implementation · 186 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
49: internal fun GlobalSearchRoute(route: Route.GlobalSearch, nav: Navigator) {
69: internal fun GlobalSearchScreen(
135: internal fun SearchSourceSection(source: Source, state: SourceSearchState, onOpenRemote: (RemoteManga) -> Unit) {
155: private fun RemoteMangaCard(remote: RemoteManga, source: Source, onClick: () -> Unit) {
Exact file bytes / download · SHA-256 3200a3c2da28c4e4c99599e7a2be6092e23b4a3326e4208f7a91dda733e0508e.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_search
import yokan.composeapp.generated.resources.ui_search_active_sources
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.ui.components.DefaultContentPadding
import eu.friedcutlet.yokan.ui.components.AppBarSearchField
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 GlobalSearchRoute(route: Route.GlobalSearch, nav: Navigator) {
val vm = viewModel {
val owner = YokanRuntime.activeSession
val loader = SourceListingLoader(owner.services)
GlobalSearchViewModel(route.itemType, route.query, owner.repository, owner.settings,
searchSource = { source, query -> loader.loadSourceListing(source, SourceTab.Search, query, 1, loader.loadSourceFilters(source)) })
}
val state by vm.state.collectAsStateWithLifecycle()
GlobalSearchScreen(
state = state,
itemType = route.itemType,
onQueryChange = vm::setQuery,
onSubmit = vm::submit,
onOpenRemote = { source, remote -> nav.navigate(Route.Detail(vm.cacheRemote(source, remote))) },
onBack = nav::back,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun GlobalSearchScreen(
state: GlobalSearchUiState,
itemType: ItemType,
onQueryChange: (String) -> Unit,
onSubmit: () -> Unit,
onOpenRemote: (Source, RemoteManga) -> Unit,
onBack: () -> Unit,
) {
val sources = state.sources
Scaffold(
topBar = {
TopAppBar(
title = {
AppBarSearchField(
query = state.query,
placeholder = stringResource(Res.string.ui_search_active_sources),
onQueryChange = onQueryChange,
onClose = onBack,
onSearch = onSubmit,
)
},
actions = {
Button(onClick = onSubmit) { Text(stringResource(Res.string.action_search)) }
},
)
},
) { paddingValues ->
eu.friedcutlet.yokan.ui.components.ScrollableLazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(DefaultContentPadding),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
if (state.submittedQuery.isBlank()) {
item(key = "empty") {
EmptyState(
icon = Icons.Filled.Search,
title = "Enter a query",
subtitle = "Search runs across installed, active ${itemType.label.lowercase()} sources.",
modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp),
)
}
} else if (sources.isEmpty()) {
item(key = "empty") {
EmptyState(
icon = Icons.Filled.Search,
title = "No active sources",
subtitle = "Enable or install sources from Browse first.",
modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp),
)
}
}
items(sources, key = { it.id }) { source ->
SearchSourceSection(
source = source,
state = state.results[source.id] ?: SourceSearchState(loading = true),
onOpenRemote = { remote -> onOpenRemote(source, remote) },
)
}
}
}
}
@Composable
internal fun SearchSourceSection(source: Source, state: SourceSearchState, onOpenRemote: (RemoteManga) -> Unit) {
ElevatedCard {
Column(Modifier.fillMaxWidth().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(source.name, modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
if (state.results.isNotEmpty()) Text("${state.results.size} results", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
when {
state.loading -> eu.friedcutlet.yokan.ui.components.LoadingState(label = "Searching ${source.name}…")
!state.error.isNullOrBlank() -> eu.friedcutlet.yokan.ui.components.ErrorState(message = state.error, openInBrowserUrl = source.baseUrl)
state.results.isEmpty() -> Text("No results", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
state.results.take(8).forEach { remote ->
RemoteMangaCard(remote = remote, source = source, onClick = { onOpenRemote(remote) })
}
}
}
}
@Composable
private fun RemoteMangaCard(remote: RemoteManga, source: Source, onClick: () -> Unit) {
ElevatedCard(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.medium)
.hoverHighlight(onClick = onClick),
) {
ListItem(
headlineContent = {
Text(remote.title, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
},
supportingContent = {
Text(
text = remote.description?.takeIf { it.isNotBlank() } ?: source.name,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
},
leadingContent = {
eu.friedcutlet.yokan.ui.components.CoverImage(
model = remote.thumbnailUrl,
contentDescription = "${remote.title} cover",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(width = 54.dp, height = 76.dp)
.clip(RoundedCornerShape(6.dp)),
fallbackInitials = remote.title.split(" ").take(2).joinToString("") { it.firstOrNull()?.uppercase() ?: "" },
)
},
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GlobalSearchViewModel.kt
- Source · implementation · 98 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
26: internal data class SourceSearchState(
32: internal data class GlobalSearchUiState(
41: internal class GlobalSearchViewModel(
72: private suspend fun search(query: String, sources: List<Source>) {
92: fun setQuery(query: String) = _state.update { it.copy(query = query) }
94: fun submit() = _state.update { it.copy(submittedQuery = it.query.trim()) }
97: fun cacheRemote(source: Source, remote: RemoteManga): Long = repository.upsertRemoteTitle(source, remote).id
Exact file bytes / download · SHA-256 33d31b91b08124f8f316c03f93243c1fd1561b9d790d54e56eb917d0f63c31eb.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.services.extensions.SourceListing
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
internal data class SourceSearchState(
val loading: Boolean = false,
val results: List<RemoteManga> = emptyList(),
val error: String? = null,
)
internal data class GlobalSearchUiState(
val query: String = "",
val submittedQuery: String = "",
/** Installed, active sources of the item type, narrowed by the pinned-only and NSFW settings. */
val sources: List<Source> = emptyList(),
val results: Map<Long, SourceSearchState> = emptyMap(),
)
/** Searches every eligible source of [itemType] one after another for the submitted query. */
internal class GlobalSearchViewModel(
private val itemType: ItemType,
initialQuery: String,
private val repository: YokanRepository,
settings: SettingsStore,
private val searchSource: suspend (Source, String) -> RuntimeLoad<SourceListing>,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(GlobalSearchUiState(query = initialQuery, submittedQuery = initialQuery.trim()))
val state: StateFlow<GlobalSearchUiState> = _state.asStateFlow()
init {
viewModelScope.launch {
// Only these settings re-pick the sources; source rows changing mid-search do not restart it.
settings.db.map { it.onlyIncludePinnedSources to it.showNsfw }
.distinctUntilChanged()
.collect { (pinnedOnly, showNsfw) ->
val sources = repository.sources(itemType)
.filter { it.isActive && it.isAdded }
.filter { !pinnedOnly || it.isPinned }
.filter { showNsfw || !it.isNsfw }
_state.update { it.copy(sources = sources) }
}
}
viewModelScope.launch {
_state.map { it.submittedQuery to it.sources }
.distinctUntilChanged()
.collectLatest { (query, sources) -> search(query, sources) }
}
}
private suspend fun search(query: String, sources: List<Source>) {
if (query.isBlank()) {
_state.update { it.copy(results = emptyMap()) }
return
}
delay(250)
_state.update { it.copy(results = sources.associate { source -> source.id to SourceSearchState(loading = true) }) }
sources.forEach { source ->
val result = catchingNonCancellation {
withContext(workDispatcher) {
searchSource(source, query)
}
}.fold(
onSuccess = { SourceSearchState(results = it.value.items, error = it.warning) },
onFailure = { SourceSearchState(error = it.message.orEmpty().ifBlank { it::class.simpleName.orEmpty() }) },
)
_state.update { it.copy(results = it.results + (source.id to result)) }
}
}
fun setQuery(query: String) = _state.update { it.copy(query = query) }
fun submit() = _state.update { it.copy(submittedQuery = it.query.trim()) }
/** Caches [remote] as a browsed title and returns its id for the Detail route. */
fun cacheRemote(source: Source, remote: RemoteManga): Long = repository.upsertRemoteTitle(source, remote).id
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SavedSourcePresets.kt
- Source · implementation · 158 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
58: internal fun SourcePresetEditor(editor: PresetEditor, onEvent: (SourcePresetEvent) -> Unit, modifier: Modifier = Modifier) {
94: internal fun SavedSourcePresetsSheet(
126: internal fun SourcePresetReview(review: PresetReview, onEvent: (SourcePresetEvent) -> Unit, modifier: Modifier = Modifier) {
149: private fun presetIssueText(issue: PresetIssue): String = stringResource(when (issue.reason) {
Exact file bytes / download · SHA-256 93594c94a70a6de6930ddb735776e544443b15b077b4d31fd618054d11e8c071.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.services.extensions.PresetIssue
import eu.friedcutlet.yokan.services.extensions.PresetIssueReason
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.preset_delete
import yokan.composeapp.generated.resources.preset_empty
import yokan.composeapp.generated.resources.preset_filter_only
import yokan.composeapp.generated.resources.preset_issue_changed
import yokan.composeapp.generated.resources.preset_issue_duplicate
import yokan.composeapp.generated.resources.preset_issue_invalid
import yokan.composeapp.generated.resources.preset_issue_loading
import yokan.composeapp.generated.resources.preset_issue_unavailable
import yokan.composeapp.generated.resources.preset_issue_removed
import yokan.composeapp.generated.resources.preset_issue_source
import yokan.composeapp.generated.resources.preset_issue_version
import yokan.composeapp.generated.resources.preset_name
import yokan.composeapp.generated.resources.preset_name_duplicate
import yokan.composeapp.generated.resources.preset_name_required
import yokan.composeapp.generated.resources.preset_rename
import yokan.composeapp.generated.resources.preset_replace
import yokan.composeapp.generated.resources.preset_replace_warning
import yokan.composeapp.generated.resources.preset_review_available
import yokan.composeapp.generated.resources.preset_review_description
import yokan.composeapp.generated.resources.preset_review_title
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.preset_save_current
import yokan.composeapp.generated.resources.preset_saved
import yokan.composeapp.generated.resources.preset_update
import yokan.composeapp.generated.resources.preset_update_warning
@Composable
internal fun SourcePresetEditor(editor: PresetEditor, onEvent: (SourcePresetEvent) -> Unit, modifier: Modifier = Modifier) {
val replacing = editor.conflictId != null && editor.mode != PresetEditMode.Rename
val duplicateName = editor.conflictId != null && editor.mode == PresetEditMode.Rename
AlertDialog(
modifier = modifier,
onDismissRequest = { onEvent(SourcePresetEvent.CancelEdit) },
title = { Text(stringResource(when (editor.mode) {
PresetEditMode.Save -> Res.string.preset_save_current
PresetEditMode.Rename -> Res.string.preset_rename
PresetEditMode.Update -> Res.string.preset_update
})) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
OutlinedTextField(value = editor.name,
onValueChange = { onEvent(SourcePresetEvent.NameChanged(it)) },
label = { Text(stringResource(Res.string.preset_name)) },
enabled = editor.mode != PresetEditMode.Update,
isError = editor.invalidName || duplicateName,
singleLine = true, modifier = Modifier.fillMaxWidth())
when {
editor.invalidName -> Text(stringResource(Res.string.preset_name_required), color = MaterialTheme.colorScheme.error)
duplicateName -> Text(stringResource(Res.string.preset_name_duplicate), color = MaterialTheme.colorScheme.error)
replacing -> Text(stringResource(Res.string.preset_replace_warning, editor.name.trim()))
editor.mode == PresetEditMode.Update -> Text(stringResource(Res.string.preset_update_warning))
}
}
},
confirmButton = { TextButton(enabled = !duplicateName, onClick = { onEvent(SourcePresetEvent.Commit(replace = replacing)) }) {
Text(stringResource(if (replacing) Res.string.preset_replace else Res.string.action_save))
} },
dismissButton = { TextButton(onClick = { onEvent(SourcePresetEvent.CancelEdit) }) { Text(stringResource(Res.string.action_cancel)) } },
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SavedSourcePresetsSheet(
presets: List<DbSavedSearch>,
canUpdate: Boolean,
onEvent: (SourcePresetEvent) -> Unit,
onDismiss: () -> Unit,
modifier: Modifier = Modifier,
) {
ModalBottomSheet(onDismissRequest = onDismiss, modifier = modifier.compactSheetWidth()) {
Text(stringResource(Res.string.preset_saved), style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(horizontal = 24.dp, vertical = 12.dp))
if (presets.isEmpty()) Text(stringResource(Res.string.preset_empty), modifier = Modifier.padding(24.dp))
LazyColumn(modifier = Modifier.fillMaxWidth().heightIn(max = 520.dp).padding(bottom = 24.dp)) {
items(presets.distinctBy { it.id }, key = { it.id }, contentType = { "preset" }) { preset ->
Column {
ListItem(
headlineContent = { Text(preset.name) },
supportingContent = { Text(preset.query.ifEmpty { stringResource(Res.string.preset_filter_only) },
maxLines = 2, overflow = TextOverflow.Ellipsis) },
modifier = Modifier.clickable { onEvent(SourcePresetEvent.Apply(preset.id)) },
)
FlowRow(modifier = Modifier.padding(horizontal = 16.dp)) {
TextButton(onClick = { onEvent(SourcePresetEvent.Rename(preset.id)) }) { Text(stringResource(Res.string.preset_rename)) }
TextButton(enabled = canUpdate, onClick = { onEvent(SourcePresetEvent.Update(preset.id)) }) { Text(stringResource(Res.string.preset_update)) }
TextButton(onClick = { onEvent(SourcePresetEvent.Delete(preset.id)) }) { Text(stringResource(Res.string.preset_delete)) }
}
}
}
}
}
}
@Composable
internal fun SourcePresetReview(review: PresetReview, onEvent: (SourcePresetEvent) -> Unit, modifier: Modifier = Modifier) {
AlertDialog(
modifier = modifier,
onDismissRequest = { onEvent(SourcePresetEvent.CancelReview) },
title = { Text(stringResource(Res.string.preset_review_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(Res.string.preset_review_description))
LazyColumn(modifier = Modifier.heightIn(max = 240.dp)) {
items(review.validation.issues.distinct(), key = { "${it.filterName}:${it.reason}" }, contentType = { "issue" }) {
Text(presetIssueText(it), modifier = Modifier.padding(vertical = 4.dp), style = MaterialTheme.typography.bodySmall)
}
}
}
},
confirmButton = { if (review.validation.canReview) TextButton(onClick = { onEvent(SourcePresetEvent.ReviewFilters) }) {
Text(stringResource(Res.string.preset_review_available))
} },
dismissButton = { TextButton(onClick = { onEvent(SourcePresetEvent.CancelReview) }) { Text(stringResource(Res.string.action_cancel)) } },
)
}
@Composable
private fun presetIssueText(issue: PresetIssue): String = stringResource(when (issue.reason) {
PresetIssueReason.SourceChanged -> Res.string.preset_issue_source
PresetIssueReason.Version -> Res.string.preset_issue_version
PresetIssueReason.Removed -> Res.string.preset_issue_removed
PresetIssueReason.Changed -> Res.string.preset_issue_changed
PresetIssueReason.InvalidSelection -> Res.string.preset_issue_invalid
PresetIssueReason.DuplicateId -> Res.string.preset_issue_duplicate
PresetIssueReason.SchemaNotReady -> Res.string.preset_issue_loading
PresetIssueReason.SchemaUnavailable -> Res.string.preset_issue_unavailable
}, issue.filterName)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogEnrollment.kt
- Source · implementation · 56 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: internal class SignedCatalogSheetSlot(
24: internal fun rememberSignedCatalogSheet(
Exact file bytes / download · SHA-256 d948d3688d0b52717e1775f57315ce504d9dd3a687e6ad9a88cc6ec9733fff08.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogInstallationService
/** The "add signed catalog" entry point: [onAdd] opens [sheet]; null when enrollment is unavailable. */
internal class SignedCatalogSheetSlot(
val onAdd: (() -> Unit)?,
val sheet: @Composable () -> Unit,
)
/** Catalog enrollment sheet whose ViewModel lives in [viewModelStoreOwner] (the root sections' store). */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun rememberSignedCatalogSheet(
viewModelStoreOwner: ViewModelStoreOwner,
installation: RecipeCatalogInstallationService,
enabled: Boolean,
): SignedCatalogSheetSlot {
val model: CatalogEnrollmentViewModel = viewModel(viewModelStoreOwner = viewModelStoreOwner, key = "catalog-enrollment") {
CatalogEnrollmentViewModel(installation)
}
val state by model.state.collectAsStateWithLifecycle()
var visible by remember { mutableStateOf(false) }
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
return SignedCatalogSheetSlot(
onAdd = if (enabled) ({ visible = true }) else null,
sheet = {
if (visible) {
SignedCatalogSheet(
state = state.toSignedCatalogSheetState(),
sheetState = sheetState,
text = ::signedCatalogText,
errorText = ::signedCatalogErrorText,
onDismiss = { visible = false },
onCodeChange = model::updateDraft,
onReview = model::reviewDraft,
onEditCode = model::editDraft,
onTrustChange = model::setTrustConfirmed,
onEnroll = model::enroll,
onRefresh = model::refresh,
onInstall = model::install,
)
}
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogSheet.kt
- Source · implementation · 203 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
46: fun SignedCatalogSheet(
179: private fun CatalogIdentity(identity: SignedCatalogIdentity, text: (SignedCatalogText) -> String) {
189: private fun CatalogValue(label: String, value: String, monospace: Boolean = false) {
200: private fun CatalogError(error: SignedCatalogError, errorText: (SignedCatalogError) -> String) {
Exact file bytes / download · SHA-256 d2cd0afc8882307ff2e1a78fa786b57a01c550ce4f9eebcccf1e29cb21663441.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SheetState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
/**
* Host once outside the Browse pager. Visibility, SheetState, localized text and all business
* state belong to the caller. Callbacks must also guard duplicate operations in their owner.
* Editing must clear the proposal/confirmation; dismissing is not rollback of a committed install.
*
* Suggested copy: "Add signed catalog", "Review catalog", "Enroll catalog", "Refresh catalog".
* ReviewExplanation should ask users to compare the fingerprint with an independent publisher
* source. TrustConfirmation: "I trust this signing key for this catalog". VerifiedExplanation:
* "Signature verified with your trusted key" — not a claim that the publisher or recipe is safe.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SignedCatalogSheet(
state: SignedCatalogSheetState,
sheetState: SheetState,
text: (SignedCatalogText) -> String,
errorText: (SignedCatalogError) -> String,
onDismiss: () -> Unit,
onCodeChange: (String) -> Unit,
onReview: () -> Unit,
onEditCode: () -> Unit,
onTrustChange: (Boolean) -> Unit,
onEnroll: () -> Unit,
onRefresh: () -> Unit,
onInstall: (String) -> Unit,
modifier: Modifier = Modifier,
) {
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, modifier = modifier) {
LazyColumn(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(20.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 24.dp, end = 24.dp, bottom = 32.dp),
) {
item(key = "header", contentType = "header") {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(text(SignedCatalogText.Title), Modifier.weight(1f).semantics { heading() }, style = MaterialTheme.typography.headlineSmall)
TextButton(onClick = onDismiss) { Text(text(SignedCatalogText.Close)) }
}
}
when (val stage = state.stage) {
is SignedCatalogStage.Paste -> item(key = "paste", contentType = "form") {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text(text(SignedCatalogText.PasteExplanation), style = MaterialTheme.typography.bodyMedium)
OutlinedTextField(
value = stage.code,
onValueChange = onCodeChange,
enabled = !state.busy,
label = { Text(text(SignedCatalogText.ShareCode)) },
modifier = Modifier.fillMaxWidth(),
minLines = 3,
maxLines = 5,
isError = stage.error != null,
)
stage.error?.let { CatalogError(it, errorText) }
Button(onClick = onReview, enabled = state.canReview, modifier = Modifier.fillMaxWidth()) {
Text(text(SignedCatalogText.ReviewCatalog))
}
}
}
is SignedCatalogStage.Review -> {
item(key = "identity", contentType = "identity") { CatalogIdentity(stage.identity, text) }
item(key = "trust", contentType = "form") {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(text(SignedCatalogText.ReviewExplanation), style = MaterialTheme.typography.bodyMedium)
Row(
modifier = Modifier.fillMaxWidth().toggleable(
value = stage.trustConfirmed, enabled = !state.busy,
role = Role.Checkbox, onValueChange = onTrustChange,
).padding(vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Checkbox(checked = stage.trustConfirmed, onCheckedChange = null, enabled = !state.busy)
Text(text(SignedCatalogText.TrustConfirmation), style = MaterialTheme.typography.bodyLarge)
}
stage.error?.let { CatalogError(it, errorText) }
Button(onClick = onEnroll, enabled = state.canEnroll, modifier = Modifier.fillMaxWidth()) {
Text(text(SignedCatalogText.EnrollCatalog))
}
TextButton(onClick = onEditCode, enabled = !state.busy) { Text(text(SignedCatalogText.EditCode)) }
}
}
}
is SignedCatalogStage.Enrolled -> {
item(key = "identity", contentType = "identity") { CatalogIdentity(stage.identity, text) }
item(key = "refresh", contentType = "form") {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(text(if (stage.alreadyEnrolled) SignedCatalogText.AlreadyEnrolled else SignedCatalogText.Enrolled), Modifier.semantics { liveRegion = LiveRegionMode.Polite })
stage.refreshError?.let { CatalogError(it, errorText) }
Button(onClick = onRefresh, enabled = !state.busy, modifier = Modifier.fillMaxWidth()) {
Text(text(SignedCatalogText.RefreshCatalog))
}
}
}
}
}
if (state.busy) item(key = "progress", contentType = "status") {
val label = when (state.operation) {
SignedCatalogOperation.Enrolling -> SignedCatalogText.Enrolling
SignedCatalogOperation.Refreshing -> SignedCatalogText.Refreshing
else -> SignedCatalogText.Installing
}
Row(
Modifier.semantics(mergeDescendants = true) { liveRegion = LiveRegionMode.Polite },
horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically,
) {
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
Text(text(label), style = MaterialTheme.typography.bodyMedium)
}
}
state.verifiedPreview?.let { preview ->
item(key = "verified", contentType = "status") {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
HorizontalDivider()
Text(text(SignedCatalogText.VerifiedExplanation), style = MaterialTheme.typography.titleMedium)
CatalogValue(text(SignedCatalogText.Revision), preview.revisionLabel)
CatalogValue(text(SignedCatalogText.Expires), preview.expiryLabel)
if (preview.size == 0) Text(text(SignedCatalogText.EmptyRecipes))
}
}
items(preview.size, key = { "recipe:${preview.recipeAt(it).stableId}" }, contentType = { "recipe" }) { index ->
val recipe = preview.recipeAt(index)
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
SelectionContainer { Text(recipe.stableId, style = MaterialTheme.typography.titleMedium) }
CatalogValue(text(SignedCatalogText.Version), recipe.version)
CatalogValue(text(SignedCatalogText.Size), recipe.sizeLabel)
recipe.error?.let { CatalogError(it, errorText) }
val label = when {
(state.operation as? SignedCatalogOperation.Installing)?.stableId == recipe.stableId -> SignedCatalogText.Installing
recipe.status == SignedCatalogRecipeStatus.Installed -> SignedCatalogText.Installed
recipe.status == SignedCatalogRecipeStatus.AlreadyInstalled -> SignedCatalogText.AlreadyInstalled
else -> SignedCatalogText.Install
}
Button(onClick = { onInstall(recipe.stableId) }, enabled = state.canInstall(recipe.stableId)) {
Text(text(label))
}
HorizontalDivider()
}
}
}
}
}
}
@Composable
private fun CatalogIdentity(identity: SignedCatalogIdentity, text: (SignedCatalogText) -> String) {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
CatalogValue(text(SignedCatalogText.CatalogId), identity.catalogId)
CatalogValue(text(SignedCatalogText.CatalogUrl), identity.url)
CatalogValue(text(SignedCatalogText.KeyId), identity.keyId)
CatalogValue(text(SignedCatalogText.Fingerprint), identity.fingerprint, monospace = true)
}
}
@Composable
private fun CatalogValue(label: String, value: String, monospace: Boolean = false) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
SelectionContainer {
Text(value, modifier = Modifier.fillMaxWidth(), style = MaterialTheme.typography.bodyMedium,
fontFamily = if (monospace) FontFamily.Monospace else null, softWrap = true)
}
}
}
@Composable
private fun CatalogError(error: SignedCatalogError, errorText: (SignedCatalogError) -> String) {
Text(errorText(error), modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite },
color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogSheetState.kt
- Source · implementation · 153 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
7: data class SignedCatalogIdentity(
14: enum class SignedCatalogError {
20: enum class SignedCatalogRecipeStatus { Available, Installed, AlreadyInstalled }
23: data class SignedCatalogRecipe(
33: class SignedCatalogPreview(
41: fun recipeAt(index: Int): SignedCatalogRecipe = rows[index]
45: sealed interface SignedCatalogStage {
46: data class Paste(val code: String = "", val error: SignedCatalogError? = null) : SignedCatalogStage
47: data class Review(
52: data class Enrolled(
61: sealed interface SignedCatalogOperation {
62: data object Idle : SignedCatalogOperation
63: data object Enrolling : SignedCatalogOperation
64: data object Refreshing : SignedCatalogOperation
65: data class Installing(val stableId: String) : SignedCatalogOperation
69: data class SignedCatalogSheetState(
83: fun canInstall(stableId: String): Boolean {
95: enum class SignedCatalogText {
103: internal fun CatalogEnrollmentUiState.toSignedCatalogSheetState(): SignedCatalogSheetState {
145: private fun CatalogEnrollmentDisplayError.toSignedCatalogError(): SignedCatalogError = when (this) {
Exact file bytes / download · SHA-256 e2dfd2e76d67e3ab1e5cbe0e63dd22195892c3768c12ea9cc2ce3de56de5b316.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.compose.runtime.Immutable
/** Display data only. The owner retains the parsed proposal and performs all trust checks. */
@Immutable
data class SignedCatalogIdentity(
val catalogId: String,
val url: String,
val keyId: String,
val fingerprint: String,
)
enum class SignedCatalogError {
InvalidCode, TrustConfirmationRequired, NotEnrolled, TrustMismatch, StorageFailure, StorageRejected,
Timeout, DownloadFailed, CatalogRejected, ArtifactPolicyRejected,
ArtifactUnavailable, ArtifactRejected, Conflict,
}
enum class SignedCatalogRecipeStatus { Available, Installed, AlreadyInstalled }
@Immutable
data class SignedCatalogRecipe(
val stableId: String,
val version: String,
val sizeLabel: String,
val status: SignedCatalogRecipeStatus = SignedCatalogRecipeStatus.Available,
val error: SignedCatalogError? = null,
)
/** Owns a snapshot, without exposing a mutable list to callers. IDs must be unique. */
@Immutable
class SignedCatalogPreview(
val revisionLabel: String,
val expiryLabel: String,
recipes: List<SignedCatalogRecipe>,
) {
private val rows = recipes.toList()
init { require(rows.map { it.stableId }.distinct().size == rows.size) }
val size: Int get() = rows.size
fun recipeAt(index: Int): SignedCatalogRecipe = rows[index]
}
@Immutable
sealed interface SignedCatalogStage {
data class Paste(val code: String = "", val error: SignedCatalogError? = null) : SignedCatalogStage
data class Review(
val identity: SignedCatalogIdentity,
val trustConfirmed: Boolean = false,
val error: SignedCatalogError? = null,
) : SignedCatalogStage
data class Enrolled(
val identity: SignedCatalogIdentity,
val alreadyEnrolled: Boolean = false,
val preview: SignedCatalogPreview? = null,
val refreshError: SignedCatalogError? = null,
) : SignedCatalogStage
}
@Immutable
sealed interface SignedCatalogOperation {
data object Idle : SignedCatalogOperation
data object Enrolling : SignedCatalogOperation
data object Refreshing : SignedCatalogOperation
data class Installing(val stableId: String) : SignedCatalogOperation
}
@Immutable
data class SignedCatalogSheetState(
val stage: SignedCatalogStage = SignedCatalogStage.Paste(),
val operation: SignedCatalogOperation = SignedCatalogOperation.Idle,
) {
val busy: Boolean get() = operation != SignedCatalogOperation.Idle
val canReview: Boolean get() = !busy && (stage as? SignedCatalogStage.Paste)?.code?.isNotBlank() == true
val canEnroll: Boolean get() = !busy && (stage as? SignedCatalogStage.Review)?.let {
it.trustConfirmed && it.error != SignedCatalogError.TrustMismatch
} == true
// A failed refresh invalidates even a retained preview. Never render it as verified.
val verifiedPreview: SignedCatalogPreview? get() = (stage as? SignedCatalogStage.Enrolled)
?.takeIf { it.refreshError == null && operation != SignedCatalogOperation.Refreshing }?.preview
fun canInstall(stableId: String): Boolean {
if (busy) return false
val preview = verifiedPreview ?: return false
return (0 until preview.size).any { index ->
val row = preview.recipeAt(index)
row.stableId == stableId && row.status == SignedCatalogRecipeStatus.Available &&
(row.error == null || row.error == SignedCatalogError.DownloadFailed || row.error == SignedCatalogError.Timeout)
}
}
}
/** Localized by the host; no raw exceptions or service messages should be shown. */
enum class SignedCatalogText {
Title, Close, PasteExplanation, ShareCode, ReviewCatalog, ReviewExplanation,
CatalogId, CatalogUrl, KeyId, Fingerprint, TrustConfirmation, EnrollCatalog,
EditCode, Enrolling, Enrolled, AlreadyEnrolled, RefreshCatalog, Refreshing,
VerifiedExplanation, Revision, Expires, EmptyRecipes, Version, Size,
Install, Installing, Installed, AlreadyInstalled,
}
internal fun CatalogEnrollmentUiState.toSignedCatalogSheetState(): SignedCatalogSheetState {
val displayError = error?.toSignedCatalogError()
val review = review
val identity = review?.let {
SignedCatalogIdentity(it.catalogId, it.catalogEnvelopeUrl, it.keyId, it.publicKeyFingerprint)
}
val stage = when {
review == null || !reviewing -> SignedCatalogStage.Paste(draftCode, displayError)
enrolled -> SignedCatalogStage.Enrolled(
identity = requireNotNull(identity),
alreadyEnrolled = alreadyEnrolled,
preview = preview?.let { catalog ->
SignedCatalogPreview(
revisionLabel = catalog.revision.toString(),
expiryLabel = catalog.expiresAtEpochSeconds.toString(),
recipes = catalog.artifacts.map { artifact ->
SignedCatalogRecipe(
stableId = artifact.stableId,
version = artifact.releaseVersion,
sizeLabel = artifact.sizeBytes.toString(),
status = installedRecipes[artifact.stableId] ?: SignedCatalogRecipeStatus.Available,
)
},
)
},
refreshError = displayError,
)
else -> SignedCatalogStage.Review(
identity = requireNotNull(identity),
trustConfirmed = trustConfirmed,
error = displayError,
)
}
val signedOperation = when (operation) {
CatalogEnrollmentOperation.Enrolling -> SignedCatalogOperation.Enrolling
CatalogEnrollmentOperation.Refreshing -> SignedCatalogOperation.Refreshing
CatalogEnrollmentOperation.Installing -> SignedCatalogOperation.Installing((retry as? CatalogEnrollmentRetry.Install)?.stableId.orEmpty())
null -> SignedCatalogOperation.Idle
}
return SignedCatalogSheetState(stage, signedOperation)
}
private fun CatalogEnrollmentDisplayError.toSignedCatalogError(): SignedCatalogError = when (this) {
CatalogEnrollmentDisplayError.InvalidCode -> SignedCatalogError.InvalidCode
CatalogEnrollmentDisplayError.ConfirmationRequired -> SignedCatalogError.TrustConfirmationRequired
CatalogEnrollmentDisplayError.EnrollmentRejected -> SignedCatalogError.StorageRejected
CatalogEnrollmentDisplayError.RefreshRejected -> SignedCatalogError.CatalogRejected
CatalogEnrollmentDisplayError.InstallRejected -> SignedCatalogError.ArtifactRejected
CatalogEnrollmentDisplayError.RefreshRequired -> SignedCatalogError.Conflict
CatalogEnrollmentDisplayError.InvalidSelection -> SignedCatalogError.ArtifactUnavailable
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogText.kt
- Source · implementation · 48 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: internal fun signedCatalogText(text: SignedCatalogText): String = when (text) {
34: internal fun signedCatalogErrorText(error: SignedCatalogError): String = when (error) {
Exact file bytes / download · SHA-256 985d4634adb4e5a528167024637b9f1018811f3db3ffad1ff98cdf057635e463.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
internal fun signedCatalogText(text: SignedCatalogText): String = when (text) {
SignedCatalogText.Title -> "Add signed catalog"
SignedCatalogText.Close -> "Close"
SignedCatalogText.PasteExplanation -> "Paste a catalog share code from a trusted publisher."
SignedCatalogText.ShareCode -> "Share code"
SignedCatalogText.ReviewCatalog -> "Review catalog"
SignedCatalogText.ReviewExplanation -> "Compare this fingerprint with the publisher before trusting the signing key."
SignedCatalogText.CatalogId -> "Catalog ID"
SignedCatalogText.CatalogUrl -> "Catalog URL"
SignedCatalogText.KeyId -> "Key ID"
SignedCatalogText.Fingerprint -> "Fingerprint"
SignedCatalogText.TrustConfirmation -> "I trust this signing key for this catalog"
SignedCatalogText.EnrollCatalog -> "Enroll catalog"
SignedCatalogText.EditCode -> "Edit code"
SignedCatalogText.Enrolling -> "Enrolling catalog"
SignedCatalogText.Enrolled -> "Catalog enrolled"
SignedCatalogText.AlreadyEnrolled -> "Catalog already enrolled"
SignedCatalogText.RefreshCatalog -> "Refresh catalog"
SignedCatalogText.Refreshing -> "Refreshing catalog"
SignedCatalogText.VerifiedExplanation -> "Catalog signature verified with your trusted key."
SignedCatalogText.Revision -> "Revision"
SignedCatalogText.Expires -> "Expires"
SignedCatalogText.EmptyRecipes -> "No recipes are available."
SignedCatalogText.Version -> "Version"
SignedCatalogText.Size -> "Size"
SignedCatalogText.Install -> "Install"
SignedCatalogText.Installing -> "Installing"
SignedCatalogText.Installed -> "Installed"
SignedCatalogText.AlreadyInstalled -> "Already installed"
}
internal fun signedCatalogErrorText(error: SignedCatalogError): String = when (error) {
SignedCatalogError.InvalidCode -> "Enter a valid catalog share code."
SignedCatalogError.TrustConfirmationRequired -> "Confirm that you trust the signing key before enrolling."
SignedCatalogError.NotEnrolled -> "Enroll the catalog before refreshing it."
SignedCatalogError.TrustMismatch -> "The catalog signing key does not match the enrolled trust policy."
SignedCatalogError.StorageFailure -> "Catalog storage is unavailable."
SignedCatalogError.StorageRejected -> "The catalog could not be enrolled."
SignedCatalogError.Timeout -> "The catalog request timed out."
SignedCatalogError.DownloadFailed -> "The catalog could not be downloaded."
SignedCatalogError.CatalogRejected -> "The catalog was rejected."
SignedCatalogError.ArtifactPolicyRejected -> "A catalog artifact violates the installation policy."
SignedCatalogError.ArtifactUnavailable -> "The selected artifact is unavailable."
SignedCatalogError.ArtifactRejected -> "The selected artifact was rejected."
SignedCatalogError.Conflict -> "Catalog data changed. Refresh before installing."
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceFilterSheet.kt
- Source · implementation · 310 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
47: internal fun SourceFilterSheet(
76: private fun FilterSheetContent(
132: private fun FilterRow(
291: private fun FilterChoiceRow(
Exact file bytes / download · SHA-256 2edf97eb69d1f636f15aedd1a137c9a4772d20d1c4f32eb058c839549feaa218.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
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.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
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.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceFilterKind
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_reset
import yokan.composeapp.generated.resources.preset_save_current
import yokan.composeapp.generated.resources.preset_sort_ascending
import yokan.composeapp.generated.resources.preset_sort_descending
/** Bottom sheet editing a source's filter schema; [onApply] commits the pending [selections]. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SourceFilterSheet(
filters: List<SourceFilter>,
selections: Map<String, FilterSelection>,
onSelectionChange: (String, FilterSelection?) -> Unit,
onReset: () -> Unit,
onApply: () -> Unit,
onDismiss: () -> Unit,
onSavePreset: () -> Unit,
canSavePreset: Boolean,
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
ModalBottomSheet(
onDismissRequest = onDismiss,
modifier = Modifier.compactSheetWidth(),
sheetState = sheetState,
) {
FilterSheetContent(
filters = filters,
selections = selections,
onSelectionChange = onSelectionChange,
onReset = onReset,
onApply = onApply,
onSavePreset = onSavePreset,
canSavePreset = canSavePreset,
)
}
}
@Composable
private fun FilterSheetContent(
filters: List<SourceFilter>,
selections: Map<String, FilterSelection>,
onSelectionChange: (String, FilterSelection?) -> Unit,
onReset: () -> Unit,
onApply: () -> Unit,
onSavePreset: () -> Unit,
canSavePreset: Boolean,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onReset) { Text(stringResource(Res.string.action_reset)) }
Box(modifier = Modifier.fillMaxWidth().padding(start = 8.dp), contentAlignment = Alignment.CenterEnd) {
Button(onClick = onApply) { Text("Filter") }
}
}
TextButton(onClick = onSavePreset, enabled = canSavePreset) {
Text(stringResource(Res.string.preset_save_current))
}
if (filters.isEmpty()) {
Text(
"This source does not expose any filters.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(vertical = 12.dp),
)
} else {
val listState = rememberLazyListState()
eu.friedcutlet.yokan.ui.components.ScrollableLazyColumn(
modifier = Modifier.fillMaxWidth().heightIn(max = 540.dp),
state = listState,
verticalArrangement = Arrangement.spacedBy(16.dp),
contentPadding = PaddingValues(vertical = 4.dp, horizontal = 0.dp),
) {
items(filters, key = { it.id }) { filter ->
FilterRow(
filter = filter,
selection = selections[filter.id],
onChange = { value -> onSelectionChange(filter.id, value) },
)
}
}
}
}
}
@Composable
private fun FilterRow(
filter: SourceFilter,
selection: FilterSelection?,
onChange: (FilterSelection?) -> Unit,
) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
Text(
filter.name,
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
when (filter.kind) {
SourceFilterKind.Toggle -> {
val checked = (selection as? FilterSelection.Toggle)?.checked ?: false
FilterChoiceRow(
selected = checked,
onClick = { onChange(FilterSelection.Toggle(!checked)) },
) {
androidx.compose.material3.Checkbox(checked = checked, onCheckedChange = { onChange(FilterSelection.Toggle(it)) })
Spacer(Modifier.width(8.dp))
Text(
filter.entries.firstOrNull()?.label ?: filter.name,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.weight(1f),
)
}
}
SourceFilterKind.MultiSelect -> {
val checked: Set<String> = (selection as? FilterSelection.Multi)?.values ?: emptySet()
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
filter.entries.forEach { entry ->
val isSelected = entry.value in checked
FilterChoiceRow(
selected = isSelected,
onClick = {
val next = if (isSelected) checked - entry.value else checked + entry.value
onChange(if (next.isEmpty()) null else FilterSelection.Multi(next))
},
) {
androidx.compose.material3.Checkbox(
checked = isSelected,
onCheckedChange = {
val next = if (it) checked + entry.value else checked - entry.value
onChange(if (next.isEmpty()) null else FilterSelection.Multi(next))
},
)
Spacer(Modifier.width(8.dp))
Text(entry.label, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f))
}
}
}
}
SourceFilterKind.SingleSelect -> {
val current = (selection as? FilterSelection.Single)?.value
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
filter.entries.forEach { entry ->
val isSelected = current == entry.value
FilterChoiceRow(
selected = isSelected,
onClick = { onChange(if (isSelected) null else FilterSelection.Single(entry.value)) },
) {
androidx.compose.material3.RadioButton(
selected = isSelected,
onClick = { onChange(if (isSelected) null else FilterSelection.Single(entry.value)) },
)
Spacer(Modifier.width(8.dp))
Text(entry.label, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f))
}
}
}
}
SourceFilterKind.Sort -> {
val current = selection as? FilterSelection.Sort
val value = current?.value ?: filter.defaultValue ?: filter.entries.firstOrNull()?.value
val ascending = current?.ascending ?: filter.defaultAscending
Column {
filter.entries.forEach { entry ->
FilterChoiceRow(selected = value == entry.value, onClick = {
onChange(FilterSelection.Sort(entry.value, ascending))
}) {
androidx.compose.material3.RadioButton(selected = value == entry.value,
onClick = { onChange(FilterSelection.Sort(entry.value, ascending)) })
Spacer(Modifier.width(8.dp))
Text(entry.label, style = MaterialTheme.typography.bodyLarge)
}
}
Row {
TextButton(enabled = value != null, onClick = {
value?.let { onChange(FilterSelection.Sort(it, true)) }
}) { Text(stringResource(Res.string.preset_sort_ascending)) }
TextButton(enabled = value != null, onClick = {
value?.let { onChange(FilterSelection.Sort(it, false)) }
}) { Text(stringResource(Res.string.preset_sort_descending)) }
}
Text(stringResource(if (ascending) Res.string.preset_sort_ascending else Res.string.preset_sort_descending),
style = MaterialTheme.typography.labelSmall)
}
}
SourceFilterKind.TriState -> {
val state = (selection as? FilterSelection.TriState)?.state ?: 0
val label = when (state) {
1 -> "Include"
-1 -> "Exclude"
else -> "Ignore"
}
FilterChoiceRow(
selected = state != 0,
onClick = {
val next = ((state + 2) % 3 - 1) // cycles 0 → 1 → -1 → 0
onChange(if (next == 0) null else FilterSelection.TriState(next))
},
) {
androidx.compose.material3.Checkbox(
checked = state == 1,
onCheckedChange = { included ->
val next = if (included) 1 else if (state == 1) -1 else 0
onChange(if (next == 0) null else FilterSelection.TriState(next))
},
)
Spacer(Modifier.width(8.dp))
Column(modifier = Modifier.weight(1f)) {
Text(filter.entries.firstOrNull()?.label ?: filter.name, style = MaterialTheme.typography.bodyLarge)
Text(
label,
style = MaterialTheme.typography.labelSmall,
color = if (state == 0) MaterialTheme.colorScheme.onSurfaceVariant
else MaterialTheme.colorScheme.primary,
)
}
}
}
SourceFilterKind.Text -> {
val text = (selection as? FilterSelection.Text)?.value ?: filter.defaultValue.orEmpty()
androidx.compose.material3.OutlinedTextField(
value = text,
onValueChange = { onChange(if (it.isEmpty()) null else FilterSelection.Text(it)) },
label = { Text(filter.name) },
singleLine = true,
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
)
}
}
}
}
/**
* Common row container for the filter-sheet entries — rounded surface that
* tints `primaryContainer` when selected, picks up the desktop hover tint,
* and lays the leading control + label out consistently across Toggle /
* MultiSelect / SingleSelect / TriState.
*/
@Composable
private fun FilterChoiceRow(
selected: Boolean,
onClick: () -> Unit,
content: @Composable RowScope.() -> Unit,
) {
androidx.compose.material3.Surface(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.large)
.hoverHighlight(onClick = onClick),
shape = MaterialTheme.shapes.large,
color = if (selected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f) else androidx.compose.ui.graphics.Color.Transparent,
) {
Row(
modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
content = content,
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeScreen.kt
- Source · implementation · 575 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
97: internal fun SourceHomeRoute(route: Route.SourceHome, nav: Navigator) {
138: private fun healMissingPayload(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession, sourceId: Long) {
149: internal fun SourceHomeScreen(
450: private fun SourceCoverCell(
522: private fun LoadMoreTile(
Exact file bytes / download · SHA-256 cf09a1780ba6825432ecc14917a5638d1c9ee36a356bfe79922d468346fa2f64.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsHoveredAsState
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.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.NewReleases
import androidx.compose.material.icons.filled.Public
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Checkbox
import androidx.compose.material.icons.outlined.DeleteOutline
import androidx.compose.material3.Button
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
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.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.AppBarSearchField
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
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.theme.YokanScaffold as Scaffold
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.action_search
import yokan.composeapp.generated.resources.detail_genre_fallback
import yokan.composeapp.generated.resources.latest
import yokan.composeapp.generated.resources.preset_save_current
import yokan.composeapp.generated.resources.preset_saved
import yokan.composeapp.generated.resources.hide_library_all_hidden
import yokan.composeapp.generated.resources.hide_library_entries
@Composable
internal fun SourceHomeRoute(route: Route.SourceHome, nav: Navigator) {
val owner = remember(nav) { YokanRuntime.activeSession }
val loader = remember(owner) { SourceListingLoader(owner.services) }
val vm = viewModel {
SourceHomeViewModel(
sourceId = route.sourceId,
genre = route.genre,
repository = owner.repository,
settings = owner.settings,
healPayload = { healMissingPayload(owner, it) },
cache = owner.sourceHomeCache,
loadListing = loader::loadSourceListing,
loadFilters = loader::loadSourceFilters,
loadLatestSupport = loader::loadSupportsLatest,
)
}
val state by vm.state.collectAsStateWithLifecycle()
if (state.source == null) return MissingRoute("Source Home", nav::back)
SourceHomeScreen(
state = state,
onBack = nav::back,
onSearchQueryChange = vm::setSearchQuery,
onSubmitSearch = vm::submitSearch,
onEnterSearch = vm::enterSearchMode,
onClearSearch = vm::clearSearch,
onBackFromSearch = vm::backFromSearch,
onSelectListing = vm::selectListing,
onRetry = vm::retry,
onLoadMore = vm::loadMore,
onFilterSelectionChange = vm::setFilterSelection,
onResetFilters = vm::resetFilters,
onApplyFilters = vm::applyFilters,
onPresetEvent = vm::onPresetEvent,
onOpenRemote = { remote -> vm.cacheRemote(remote)?.let { nav.navigate(Route.Detail(it)) } },
onOpenWebView = { vm.webViewRoute()?.let(nav::navigate) },
onOpenSourceSettings = { sourceId -> nav.navigate(Route.ExtensionDetail(sourceId)) },
onHideLibraryChange = vm::setHideLibrary,
)
}
/** Fetches the payload of sources flagged added before their code was downloaded (legacy flag flip). */
private fun healMissingPayload(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession, sourceId: Long) {
val dbSource = owner.database.source(sourceId) ?: return
if (dbSource.sourceCode.isBlank() && dbSource.sourceCodeUrl.isNotBlank()) {
owner.scope.launch {
catchingNonCancellation { owner.sourceInstall.installOrUpdate(sourceId) }
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SourceHomeScreen(
state: SourceHomeUiState,
onBack: () -> Unit,
onSearchQueryChange: (String) -> Unit,
onSubmitSearch: () -> Unit,
onEnterSearch: () -> Unit,
onClearSearch: () -> Unit,
onBackFromSearch: () -> Unit,
onSelectListing: (SourceTab) -> Unit,
onRetry: () -> Unit,
onLoadMore: () -> Unit,
onFilterSelectionChange: (String, FilterSelection?) -> Unit,
onResetFilters: () -> Unit,
onApplyFilters: () -> Unit,
onPresetEvent: (SourcePresetEvent) -> Unit,
onOpenRemote: (RemoteManga) -> Unit,
onOpenWebView: () -> Unit,
onOpenSourceSettings: (sourceId: Long) -> Unit,
onHideLibraryChange: (Boolean) -> Unit,
) {
val source: Source = state.source ?: return
val selectedTab = state.selectedTab
val items = state.visibleItems
val error = state.error
val initialGenre = state.genre
var filterSheetOpen by remember { mutableStateOf(false) }
var overflowOpen by remember { mutableStateOf(false) }
var savedSearchesSheetOpen by remember { mutableStateOf(false) }
val gridState = rememberLazyGridState()
Scaffold(
topBar = {
Column {
TopAppBar(
title = {
if (state.isSearchMode) {
AppBarSearchField(
query = state.searchQuery,
placeholder = "Search ${source.name}",
onQueryChange = onSearchQueryChange,
// Back arrow and Escape: first clear the text, then leave search mode.
onClose = onBackFromSearch,
onSearch = onSubmitSearch,
onClear = onClearSearch,
)
} else {
Column {
Text(source.name, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
text = "v${source.version} · ${source.lang.uppercase()}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
},
navigationIcon = {
// In search mode the field's own back arrow leaves search.
if (!state.isSearchMode) {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
}
}
},
actions = {
if (state.isSearchMode) {
Button(
onClick = onSubmitSearch,
) { Text(stringResource(Res.string.action_search)) }
} else {
IconButton(onClick = onEnterSearch) {
Icon(Icons.Filled.Search, contentDescription = stringResource(Res.string.action_search))
}
IconButton(onClick = onOpenWebView) {
Icon(Icons.Filled.Public, contentDescription = "Open in WebView")
}
Box {
IconButton(onClick = { overflowOpen = true }) {
Icon(Icons.Filled.MoreVert, contentDescription = "More")
}
DropdownMenu(
expanded = overflowOpen,
onDismissRequest = { overflowOpen = false },
) {
DropdownMenuItem(
text = { Text("Source settings") },
leadingIcon = { Icon(Icons.Filled.Settings, contentDescription = null) },
onClick = {
overflowOpen = false
onOpenSourceSettings(source.id)
},
)
if (source.baseUrl.isNotBlank()) {
DropdownMenuItem(
text = { Text("Open in browser") },
leadingIcon = { Icon(Icons.Filled.Public, contentDescription = null) },
onClick = {
overflowOpen = false
onOpenWebView()
},
)
}
DropdownMenuItem(
text = { Text(stringResource(Res.string.preset_save_current)) },
enabled = state.filterSchemaReady,
leadingIcon = { Icon(Icons.Filled.Bookmark, contentDescription = null) },
onClick = {
overflowOpen = false
onPresetEvent(SourcePresetEvent.SaveCurrent)
},
)
DropdownMenuItem(
text = { Text(stringResource(Res.string.preset_saved)) },
leadingIcon = { Icon(Icons.Filled.Bookmark, contentDescription = null) },
onClick = {
overflowOpen = false
savedSearchesSheetOpen = true
},
)
DropdownMenuItem(
text = { Text(stringResource(Res.string.hide_library_entries)) },
leadingIcon = { Icon(Icons.Filled.VisibilityOff, contentDescription = null) },
trailingIcon = { Checkbox(checked = state.hideLibrary, onCheckedChange = null) },
onClick = {
overflowOpen = false
onHideLibraryChange(!state.hideLibrary)
},
)
}
}
}
},
)
// Mode chips: Popular / Latest / Filter — mirrors the Flutter
// `MangasCardSelector` row pinned under the AppBar.
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
FilterChip(
selected = selectedTab == SourceTab.Popular,
onClick = { onSelectListing(SourceTab.Popular) },
label = { Text("Popular") },
leadingIcon = { Icon(Icons.Filled.Star, contentDescription = null) },
)
if (state.supportsLatest) {
FilterChip(
selected = selectedTab == SourceTab.Latest,
onClick = { onSelectListing(SourceTab.Latest) },
label = { Text(stringResource(Res.string.latest)) },
leadingIcon = { Icon(Icons.Filled.NewReleases, contentDescription = null) },
)
}
if (state.filters.isNotEmpty()) {
FilterChip(
selected = selectedTab == SourceTab.Search &&
(state.filtersApplied || state.selectedFilterValues.isNotEmpty()),
onClick = { filterSheetOpen = true },
label = { Text("Filter") },
leadingIcon = { Icon(Icons.Filled.FilterList, contentDescription = null) },
)
}
}
if (initialGenre != null && state.filtersReady && selectedTab == SourceTab.Search &&
state.submittedQuery == initialGenre && state.appliedFilterValues.isEmpty()) {
Text(
stringResource(Res.string.detail_genre_fallback, initialGenre),
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
},
) { paddingValues ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
) {
when {
(!state.filtersReady || state.loading || state.loadingMore) && items.isEmpty() -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}
}
error != null && items.isEmpty() -> {
eu.friedcutlet.yokan.ui.components.ErrorState(
message = error,
onRetry = onRetry,
openInBrowserUrl = source.baseUrl,
modifier = Modifier.padding(top = 32.dp),
)
}
items.isEmpty() -> {
EmptyState(
icon = Icons.Filled.Search,
title = "No titles",
subtitle = if (state.items.isEmpty()) "The selected source returned no results." else stringResource(Res.string.hide_library_all_hidden),
modifier = Modifier.fillMaxWidth().padding(16.dp),
)
}
else -> {
eu.friedcutlet.yokan.ui.components.ScrollableLazyVerticalGrid(
state = gridState,
columns = GridCells.Adaptive(120.dp),
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
items(items, key = { it.url }) { remote ->
SourceCoverCell(
remote = remote,
inLibrary = remote.url in state.libraryLinks,
onClick = { onOpenRemote(remote) },
)
}
val showLoadMore = state.loadingMore || state.hasNextPage ||
(items.isNotEmpty() && !state.appendExhausted && selectedTab != SourceTab.Popular)
if (showLoadMore) {
item(key = "load-more") {
LoadMoreTile(
loading = state.loadingMore,
onClick = onLoadMore,
)
}
}
if (error != null && items.isNotEmpty()) {
item(key = "error", span = { GridItemSpan(maxLineSpan) }) {
Text(
text = error,
color = MaterialTheme.colorScheme.tertiary,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 4.dp),
textAlign = TextAlign.Center,
)
}
}
}
}
}
}
}
if (filterSheetOpen || state.reviewFiltersRequested) {
SourceFilterSheet(
filters = state.filters,
selections = state.selectedFilterValues,
onSelectionChange = onFilterSelectionChange,
onReset = onResetFilters,
onApply = {
onApplyFilters()
filterSheetOpen = false
},
onDismiss = {
filterSheetOpen = false
onPresetEvent(SourcePresetEvent.CloseReviewFilters)
},
onSavePreset = {
filterSheetOpen = false
onPresetEvent(SourcePresetEvent.CloseReviewFilters)
onPresetEvent(SourcePresetEvent.SaveCurrent)
},
canSavePreset = state.filterSchemaReady,
)
}
state.presetEditor?.let { editor ->
SourcePresetEditor(editor = editor, onEvent = onPresetEvent)
}
state.presetReview?.let { review ->
SourcePresetReview(review = review, onEvent = onPresetEvent)
}
if (savedSearchesSheetOpen) {
SavedSourcePresetsSheet(
presets = state.savedSearches,
canUpdate = state.filterSchemaReady,
onEvent = { event ->
if (event !is SourcePresetEvent.Delete) savedSearchesSheetOpen = false
onPresetEvent(event)
},
onDismiss = { savedSearchesSheetOpen = false },
)
}
}
@Composable
private fun SourceCoverCell(
remote: RemoteManga,
inLibrary: Boolean,
onClick: () -> Unit,
) {
val interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hovered by interactionSource.collectIsHoveredAsState()
val elevation by androidx.compose.animation.core.animateDpAsState(if (hovered) 8.dp else 0.dp)
Column(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.medium)
.hoverable(interactionSource = interactionSource)
.clickable(interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Surface(
shape = MaterialTheme.shapes.medium,
shadowElevation = elevation,
tonalElevation = 0.dp,
color = androidx.compose.ui.graphics.Color.Transparent,
) {
Box(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(0.7f)
.clip(MaterialTheme.shapes.medium),
) {
eu.friedcutlet.yokan.ui.components.CoverImage(
model = remote.thumbnailUrl,
contentDescription = "${remote.title} cover",
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
fallbackInitials = remote.title.split(" ")
.take(2)
.joinToString("") { it.firstOrNull()?.uppercase() ?: "" },
)
if (inLibrary) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.4f)),
)
Surface(
color = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary,
shape = RoundedCornerShape(topStart = 8.dp, bottomEnd = 8.dp),
modifier = Modifier.align(Alignment.TopStart),
) {
Icon(
imageVector = Icons.Filled.Bookmark,
contentDescription = "In library",
modifier = Modifier
.padding(horizontal = 4.dp, vertical = 4.dp)
.size(16.dp),
)
}
}
}
}
Text(
text = remote.title,
style = MaterialTheme.typography.bodySmall,
fontWeight = FontWeight.Medium,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 2.dp),
)
}
}
@Composable
private fun LoadMoreTile(
loading: Boolean,
onClick: () -> Unit,
) {
ElevatedCard(
onClick = onClick,
enabled = !loading,
colors = CardDefaults.elevatedCardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f),
),
modifier = Modifier
.fillMaxWidth()
.aspectRatio(0.7f),
) {
Column(
modifier = Modifier.fillMaxSize().padding(12.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
if (loading) {
CircularProgressIndicator(
modifier = Modifier.size(28.dp),
strokeWidth = 3.dp,
)
Text(
"Loading…",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.padding(top = 10.dp),
)
} else {
Icon(
imageVector = Icons.Filled.NewReleases,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(32.dp),
)
Text(
"Load more",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.padding(top = 10.dp),
)
Text(
"Next page",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.72f),
textAlign = TextAlign.Center,
)
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeViewModel.kt
- Source · implementation · 452 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
38: internal data class SourceHomeLoadKey(
47: internal data class SourceHomeUiState(
91: internal fun List<RemoteManga>.withoutLibrary(hide: Boolean, libraryLinks: Set<String>): List<RemoteManga> =
101: internal class SourceHomeCache(private val capacity: Int) {
105: fun get(sourceId: Long, genre: String?): SourceHomeUiState? = lock.withLock {
109: fun put(sourceId: Long, genre: String?, state: SourceHomeUiState) = lock.withLock {
121: internal class SourceHomeViewModel(
172: private fun collectSourceData(initial: Source) {
207: private suspend fun fillHiddenPages() {
223: private suspend fun initialize(source: Source, restored: Boolean) {
250: private suspend fun loadPage(targetPage: Int, append: Boolean): Boolean {
285: fun retry() {
289: fun loadMore() {
297: fun setHideLibrary(hide: Boolean) {
302: fun setSearchQuery(query: String) = _state.update { it.copy(searchQuery = query) }
304: fun enterSearchMode() = _state.update { it.copy(isSearchMode = true, searchQuery = it.submittedQuery) }
306: fun submitSearch() = _state.update {
316: fun clearSearch() = _state.update { it.clearedSearch() }
319: fun backFromSearch() = _state.update {
332: fun selectListing(tab: SourceTab) = _state.update {
336: fun setFilterSelection(filterId: String, selection: FilterSelection?) = _state.update {
346: fun resetFilters() {
356: fun applyFilters() = _state.update {
362: private fun savedPreset(id: String): DbSavedSearch? = settings.db.value.sourcePreset(sourceId, id)
364: private fun sourceRow(): DbSource? = repository.snapshots.value.sources.firstOrNull { it.id == sourceId }
366: fun onPresetEvent(event: SourcePresetEvent) {
417: private fun commitPresetEdit(replace: Boolean) {
424: private fun applyPreset(preset: DbSavedSearch) {
430: fun cacheRemote(remote: RemoteManga): Long? =
433: fun webViewRoute(): Route.InAppWebView? {
439: override fun onCleared() {
448: private fun SourceHomeUiState.clearedSearch() = copy(
Exact file bytes / download · SHA-256 606fb8cedfaaba4136198a9cba6c7a58007f18bb8ffb5f37ce95373692c31b04.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.presetIdentity
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceListing
import eu.friedcutlet.yokan.services.extensions.webViewUserAgent
import eu.friedcutlet.yokan.services.extensions.PresetIssue
import eu.friedcutlet.yokan.services.extensions.PresetIssueReason
import eu.friedcutlet.yokan.services.extensions.PresetValidation
import eu.friedcutlet.yokan.services.extensions.validateSourcePreset
import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlinx.coroutines.Job
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
internal data class SourceHomeLoadKey(
val sourceId: Long,
val tab: SourceTab,
val query: String,
val filterSelections: Map<String, FilterSelection>,
val filtersApplied: Boolean,
val revision: Long,
)
internal data class SourceHomeUiState(
val source: Source?,
val genre: String? = null,
// Match the Flutter source-home modes: Popular (0), Latest (1), Filter/Search (2).
val selectedTab: SourceTab = SourceTab.Popular,
val supportsLatest: Boolean = false,
val isSearchMode: Boolean = false,
val searchQuery: String = "",
val submittedQuery: String = "",
val filters: List<SourceFilter> = emptyList(),
val selectedFilterValues: Map<String, FilterSelection> = emptyMap(),
val appliedFilterValues: Map<String, FilterSelection> = emptyMap(),
val filtersApplied: Boolean = false,
val items: List<RemoteManga> = emptyList(),
val page: Int = 1,
val hasNextPage: Boolean = false,
val appendExhausted: Boolean = false,
val loading: Boolean = false,
val loadingMore: Boolean = false,
val error: String? = null,
val loadedKey: SourceHomeLoadKey? = null,
/** False while a genre request waits for the source's filter schema. */
val filtersReady: Boolean = true,
/** Links of favourited titles from this source (matched by source name and language). */
val libraryLinks: Set<String> = emptySet(),
val savedSearches: List<DbSavedSearch> = emptyList(),
val filterSchemaReady: Boolean = false,
val requestRevision: Long = 0,
val presetEditor: PresetEditor? = null,
val presetReview: PresetReview? = null,
val reviewFiltersRequested: Boolean = false,
/** "Hide entries already in library" for this source's media type ([DbBrowsePreferences]). */
val hideLibrary: Boolean = false,
) {
internal val loadKey: SourceHomeLoadKey?
get() = source?.let {
SourceHomeLoadKey(it.id, selectedTab, submittedQuery, appliedFilterValues, filtersApplied, requestRevision)
}
/** [items] as shown: re-derived from the loaded pages, so toggling or library changes never refetch. */
val visibleItems: List<RemoteManga> by lazy { items.withoutLibrary(hideLibrary, libraryLinks) }
}
/** Drops listing entries whose url is a favourite of the same source (the "in library" badge key). */
internal fun List<RemoteManga>.withoutLibrary(hide: Boolean, libraryLinks: Set<String>): List<RemoteManga> =
if (hide && libraryLinks.isNotEmpty()) filterNot { it.url in libraryLinks } else this
/** Bound on consecutive pages fetched automatically because every entry was hidden as in-library. */
internal const val MaxHiddenPageFills = 5
/**
* Last listing of recently closed Source Homes, so re-opening a source after a pop restores it.
* Written only from [SourceHomeViewModel.onCleared]; entries are immutable states.
*/
internal class SourceHomeCache(private val capacity: Int) {
private val lock = PlatformLock()
private val entries = LinkedHashMap<Long, Pair<String?, SourceHomeUiState>>()
fun get(sourceId: Long, genre: String?): SourceHomeUiState? = lock.withLock {
entries[sourceId]?.takeIf { it.first == genre }?.second
}
fun put(sourceId: Long, genre: String?, state: SourceHomeUiState) = lock.withLock {
entries.remove(sourceId)
entries[sourceId] = genre to state
while (entries.size > capacity) entries.remove(entries.keys.first())
}
}
/**
* Listing, search and filter state of one Source Home entry. Opening marks the source as last used
* and heals a missing payload through [healPayload].
*/
internal class SourceHomeViewModel(
private val sourceId: Long,
genre: String?,
private val repository: YokanRepository,
private val settings: SettingsStore,
healPayload: (sourceId: Long) -> Unit,
private val cache: SourceHomeCache,
private val loadListing: suspend (Source, SourceTab, String, Int, List<SourceFilter>) -> RuntimeLoad<SourceListing>,
private val loadFilters: suspend (Source) -> List<SourceFilter>,
private val loadLatestSupport: suspend (Source) -> Boolean,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val genre = genre?.trim()?.takeIf(String::isNotEmpty)
private val _state: MutableStateFlow<SourceHomeUiState>
val state: StateFlow<SourceHomeUiState>
private var appendJob: Job? = null
private var presetApplyJob: Job? = null
init {
repository.markSourceUsed(sourceId)
val source = repository.source(sourceId)
val cached = cache.get(sourceId, this.genre)
_state = MutableStateFlow(
(cached?.copy(source = source)
?: SourceHomeUiState(
source = source,
genre = this.genre,
supportsLatest = source?.supportLatest ?: false,
filtersReady = this.genre == null,
)).copy(hideLibrary = source != null && settings.db.value.features.browse.hidesLibrary(source.itemType)),
)
state = _state.asStateFlow()
if (source != null) {
healPayload(sourceId)
collectSourceData(source)
viewModelScope.launch { initialize(source, restored = cached != null) }
viewModelScope.launch {
// Re-fetch page 1 whenever the mode, the submitted query, or applied filters change.
_state.map { if (it.filtersReady) it.loadKey else null }
.distinctUntilChanged()
.collectLatest { key ->
appendJob?.cancel()
if (key == null || _state.value.loadedKey == key) return@collectLatest
_state.update { it.copy(items = emptyList(), page = 1, hasNextPage = false, appendExhausted = false) }
if (loadPage(targetPage = 1, append = false)) _state.update { if (it.loadKey == key) it.copy(loadedKey = key) else it }
}
}
viewModelScope.launch { fillHiddenPages() }
}
}
private fun collectSourceData(initial: Source) {
viewModelScope.launch {
repository.observe({ it.sources }, workDispatcher) { source(sourceId) }.collect { source ->
_state.update { it.copy(source = source) }
}
}
viewModelScope.launch {
// Mirror Flutter's library overlay: match favourites by source name + lang.
repository.observe({ it.mangas }, workDispatcher) {
allTitles(initial.itemType).asSequence()
.filter {
it.favorite && it.source.equals(initial.name, ignoreCase = true) &&
it.lang.equals(initial.lang, ignoreCase = true)
}
.map { it.link }
.toSet()
}.collect { links -> _state.update { it.copy(libraryLinks = links) } }
}
viewModelScope.launch {
settings.db.map { db -> db.savedSearches.orEmpty().filter { it.sourceId == sourceId } }
.distinctUntilChanged()
.collect { saved -> _state.update { it.copy(savedSearches = saved) } }
}
viewModelScope.launch {
settings.db.map { it.features.browse.hidesLibrary(initial.itemType) }
.distinctUntilChanged()
.collect { hide -> _state.update { it.copy(hideLibrary = hide) } }
}
}
/**
* Loading is manual (Load more tile), so a page whose entries are all in the library would leave
* an empty screen without that tile: fetch following pages until something shows, at most
* [MaxHiddenPageFills] in a row. A failed fetch keeps [SourceHomeUiState.page], which stops the run.
*/
private suspend fun fillHiddenPages() {
var filled = 0
var lastPage = 0
_state.collect { s ->
if (!s.hideLibrary || s.items.isEmpty() || s.visibleItems.isNotEmpty()) {
filled = 0
lastPage = 0
return@collect
}
if (s.loading || s.loadingMore || !s.hasNextPage || s.page == lastPage || filled >= MaxHiddenPageFills) return@collect
filled++
lastPage = s.page
loadMore()
}
}
private suspend fun initialize(source: Source, restored: Boolean) {
val latest = withContext(workDispatcher) { loadLatestSupport(source) }
_state.update {
it.copy(
supportsLatest = latest,
selectedTab = if (!latest && it.selectedTab == SourceTab.Latest) SourceTab.Popular else it.selectedTab,
)
}
val fetched = catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } }
val filters = fetched.getOrDefault(emptyList())
_state.update { current ->
val withFilters = current.copy(filters = filters, filtersReady = true, filterSchemaReady = fetched.isSuccess)
// A restored home keeps its own search instead of re-running the genre request.
if (genre == null || restored) return@update withFilters
val request = genreSearchRequest(genre, filters)
withFilters.copy(
selectedFilterValues = request.selections,
appliedFilterValues = request.selections,
submittedQuery = request.query,
searchQuery = request.query,
selectedTab = SourceTab.Search,
filtersApplied = request.selections.isNotEmpty(),
isSearchMode = request.query.isNotEmpty(),
)
}
}
private suspend fun loadPage(targetPage: Int, append: Boolean): Boolean {
val current = _state.value
val source = current.source ?: return false
if (append && (current.loadingMore || current.loading)) return false
_state.update { if (append) it.copy(loadingMore = true, error = null) else it.copy(loading = true, error = null) }
return try {
// Applied schema = schema with the user's selections folded in; the runtime receives it.
val appliedFilters = current.filters.map { it.copy(selection = current.appliedFilterValues[it.id]) }
val load = withContext(workDispatcher) {
loadListing(source, current.selectedTab, current.submittedQuery, targetPage, appliedFilters)
}
_state.update { s ->
if (s.loadKey != current.loadKey) return@update s
val combined = if (append) s.items + load.value.items else load.value.items
val seen = HashSet<String>(combined.size)
val items = combined.filter { seen.add(it.url) }
s.copy(
items = items,
page = targetPage,
hasNextPage = load.value.hasNextPage,
appendExhausted = append && items.size == s.items.size && !load.value.hasNextPage,
error = load.warning,
)
}
true
} catch (throwable: Throwable) {
if (throwable is CancellationException) throw throwable
val message = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() }
_state.update { if (it.loadKey == current.loadKey) it.copy(items = if (append) it.items else emptyList(), error = message) else it }
false
} finally {
_state.update { if (it.loadKey == current.loadKey) it.copy(loading = false, loadingMore = false) else it }
}
}
fun retry() {
viewModelScope.launch { loadPage(1, append = false) }
}
fun loadMore() {
val current = _state.value
if (!current.loadingMore && (current.hasNextPage || current.selectedTab != SourceTab.Popular)) {
appendJob = viewModelScope.launch { loadPage(current.page + 1, append = true) }
}
}
/** Per media type, shared with Home source feeds; the settings collector re-filters loaded pages. */
fun setHideLibrary(hide: Boolean) {
val type = _state.value.source?.itemType ?: return
settings.updateDb { it.copy(features = it.features.copy(browse = it.features.browse.withHideLibrary(type, hide))) }
}
fun setSearchQuery(query: String) = _state.update { it.copy(searchQuery = query) }
fun enterSearchMode() = _state.update { it.copy(isSearchMode = true, searchQuery = it.submittedQuery) }
fun submitSearch() = _state.update {
val trimmed = it.searchQuery.trim()
if (trimmed.isEmpty()) {
it.copy(selectedTab = SourceTab.Popular, submittedQuery = "")
} else {
it.copy(selectedTab = SourceTab.Search, submittedQuery = trimmed)
}
}
/** Clears the query; a running search falls back to Popular. */
fun clearSearch() = _state.update { it.clearedSearch() }
/** Back arrow or Escape inside search mode: first clear the text, then leave search mode. */
fun backFromSearch() = _state.update {
if (it.searchQuery.isBlank()) {
it.copy(
isSearchMode = false,
submittedQuery = "",
selectedTab = if (it.selectedTab == SourceTab.Search) SourceTab.Popular else it.selectedTab,
)
} else {
it.copy(searchQuery = "")
}
}
/** Popular / Latest chips. */
fun selectListing(tab: SourceTab) = _state.update {
it.copy(selectedTab = tab, submittedQuery = "", searchQuery = "", isSearchMode = false)
}
fun setFilterSelection(filterId: String, selection: FilterSelection?) = _state.update {
it.copy(
selectedFilterValues = if (selection == null) {
it.selectedFilterValues - filterId
} else {
it.selectedFilterValues + (filterId to selection)
},
)
}
fun resetFilters() {
_state.update { it.copy(selectedFilterValues = emptyMap()) }
val source = _state.value.source ?: return
viewModelScope.launch {
catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } }
.onSuccess { filters -> _state.update { it.copy(filters = filters, filterSchemaReady = true) } }
.onFailure { failure -> _state.update { it.copy(filterSchemaReady = false, error = failure.message) } }
}
}
fun applyFilters() = _state.update {
it.copy(appliedFilterValues = it.selectedFilterValues, submittedQuery = it.searchQuery.trim(),
selectedTab = SourceTab.Search, filtersApplied = !it.filtersApplied,
reviewFiltersRequested = false)
}
private fun savedPreset(id: String): DbSavedSearch? = settings.db.value.sourcePreset(sourceId, id)
private fun sourceRow(): DbSource? = repository.snapshots.value.sources.firstOrNull { it.id == sourceId }
fun onPresetEvent(event: SourcePresetEvent) {
val current = _state.value
when (event) {
SourcePresetEvent.SaveCurrent -> if (current.filterSchemaReady) _state.update {
it.copy(presetEditor = PresetEditor(PresetEditMode.Save, it.searchQuery.trim()))
}
is SourcePresetEvent.Rename -> savedPreset(event.id)?.let { saved -> _state.update {
it.copy(presetEditor = PresetEditor(PresetEditMode.Rename, saved.name, saved.id))
} }
is SourcePresetEvent.Update -> if (current.filterSchemaReady) savedPreset(event.id)?.let { saved -> _state.update {
it.copy(presetEditor = PresetEditor(PresetEditMode.Update, saved.name, saved.id))
} }
is SourcePresetEvent.NameChanged -> _state.update { it.copy(presetEditor = it.presetEditor?.copy(
name = event.name, conflictId = null, invalidName = false)) }
is SourcePresetEvent.Commit -> commitPresetEdit(event.replace)
SourcePresetEvent.CancelEdit -> _state.update { it.copy(presetEditor = null) }
is SourcePresetEvent.Apply -> {
presetApplyJob?.cancel()
presetApplyJob = viewModelScope.launch {
val saved = savedPreset(event.id) ?: return@launch
val source = _state.value.source ?: return@launch
if (saved.sourceIdentity != null && sourceRow()?.presetIdentity() != saved.sourceIdentity) {
applyPreset(saved)
return@launch
}
val fetched = catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } }
fetched.onSuccess { filters ->
_state.update { it.copy(filters = filters, filterSchemaReady = true) }
// Read the current stored row again in case it was deleted or renamed during fetch.
savedPreset(event.id)?.let(::applyPreset)
}.onFailure {
_state.update { it.copy(presetReview = PresetReview(saved, PresetValidation(emptyMap(),
listOf(PresetIssue(saved.name, PresetIssueReason.SchemaUnavailable))))) }
}
}
}
is SourcePresetEvent.Delete -> settings.updateDb { it.withoutSourcePreset(sourceId, event.id) }
SourcePresetEvent.CancelReview -> _state.update { it.copy(presetReview = null) }
SourcePresetEvent.CloseReviewFilters -> _state.update { it.copy(reviewFiltersRequested = false) }
SourcePresetEvent.ReviewFilters -> {
val saved = current.presetReview?.preset ?: return
val source = sourceRow() ?: return
val checked = validateSourcePreset(saved, source, current.filters)
if (!current.filterSchemaReady || !checked.canReview) return
// Only stage the recoverable combination. No request runs until Filter is pressed.
_state.update { it.copy(presetReview = null, searchQuery = saved.query, isSearchMode = true,
selectedFilterValues = checked.selections, reviewFiltersRequested = true) }
}
}
}
private fun commitPresetEdit(replace: Boolean) {
val source = sourceRow() ?: return
val commit = commitPreset(_state.value, settings.db.value, source, replace) ?: return
commit.save?.let { preset -> settings.updateDb { it.withSourcePreset(preset) } }
_state.update { it.copy(presetEditor = commit.editor) }
}
private fun applyPreset(preset: DbSavedSearch) {
val source = sourceRow() ?: return
_state.update { it.withPresetApplied(preset, source) }
}
/** Caches [remote] as a browsed title and returns its id for the Detail route. */
fun cacheRemote(remote: RemoteManga): Long? =
_state.value.source?.let { repository.upsertRemoteTitle(it, remote).id }
fun webViewRoute(): Route.InAppWebView? {
val source = _state.value.source?.takeIf { it.baseUrl.isNotBlank() } ?: return null
val userAgent = settings.db.value.webViewUserAgent(source).takeIf { it.isNotBlank() }
return Route.InAppWebView(source.baseUrl, source.name, userAgent)
}
override fun onCleared() {
val current = _state.value
// Do not restore an interrupted genre request as an already initialized home.
if (current.filtersReady && current.source != null) {
cache.put(sourceId, genre, current.copy(loading = false, loadingMore = false, presetEditor = null, presetReview = null, reviewFiltersRequested = false))
}
}
}
private fun SourceHomeUiState.clearedSearch() = copy(
searchQuery = "",
submittedQuery = "",
selectedTab = if (selectedTab == SourceTab.Search) SourceTab.Popular else selectedTab,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceListingLoader.kt
- Source · implementation · 77 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: internal enum class SourceTab(val label: String) {
18: internal data class RuntimeLoad<T>(val value: T, val warning: String? = null)
20: internal class SourceListingLoader(private val services: eu.friedcutlet.yokan.app.YokanServices) {
21: internal suspend fun loadSourceListing(
35: internal suspend fun loadSourceFilters(source: Source): List<SourceFilter> {
48: internal suspend fun loadSupportsLatest(source: Source): Boolean {
56: private suspend fun <T> withRuntimeFallback(source: Source, block: suspend (ExtensionRuntimeService) -> T): RuntimeLoad<T> {
Exact file bytes / download · SHA-256 aa6696ba260299d9964ea3097e78c6098a2bcd5b98ca8a66fc82d686a5c36ec7.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.extensions.ExtensionLogger
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceListing
import kotlinx.coroutines.CancellationException
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
internal enum class SourceTab(val label: String) {
Popular("Popular"),
Latest("Latest"),
Search("Search"),
}
internal data class RuntimeLoad<T>(val value: T, val warning: String? = null)
internal class SourceListingLoader(private val services: eu.friedcutlet.yokan.app.YokanServices) {
internal suspend fun loadSourceListing(
source: Source,
tab: SourceTab,
query: String,
page: Int,
filters: List<SourceFilter>,
): RuntimeLoad<SourceListing> = withRuntimeFallback(source) { runtime ->
when (tab) {
SourceTab.Popular -> runtime.popular(page)
SourceTab.Latest -> runtime.latest(page)
SourceTab.Search -> runtime.search(query, page, filters)
}
}
internal suspend fun loadSourceFilters(source: Source): List<SourceFilter> {
return catchingNonCancellation {
services.extensionRuntimeFactory.withSourceRuntime(
database = services.database,
sourceId = source.id,
onFallback = { ExtensionLogger.error(source.name, "filterList", it) },
) { it.filterList() }
}
.onFailure { fallbackError -> ExtensionLogger.error(source.name, "filterList fallback", fallbackError) }
.getOrThrow()
}
/** Whether the runtime offers a Latest listing; falls back to the stored flag when the runtime fails. */
internal suspend fun loadSupportsLatest(source: Source): Boolean {
return catchingNonCancellation {
services.extensionRuntimeFactory.withSourceRuntime(services.database, source.id) { it.supportsLatest() }
}
.onFailure { ExtensionLogger.error(source.name, "supportsLatest", it) }
.getOrDefault(source.supportLatest)
}
private suspend fun <T> withRuntimeFallback(source: Source, block: suspend (ExtensionRuntimeService) -> T): RuntimeLoad<T> {
var warning: String? = null
return try {
val value = services.extensionRuntimeFactory.withSourceRuntime(
database = services.database,
sourceId = source.id,
onFallback = { error ->
ExtensionLogger.error(source.name, "runtime call", error)
warning = "Runtime fallback for ${source.name}: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}"
},
block = block,
)
RuntimeLoad(value, warning)
} catch (fallbackError: Throwable) {
val fallbackWarning = warning
if (fallbackError is CancellationException || fallbackWarning == null) throw fallbackError
ExtensionLogger.error(source.name, "runtime fallback", fallbackError)
throw IllegalStateException(fallbackWarning, fallbackError)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresetState.kt
- Source · implementation · 27 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: internal enum class PresetEditMode { Save, Rename, Update }
7: internal data class PresetEditor(
14: internal data class PresetReview(val preset: DbSavedSearch, val validation: PresetValidation)
15: internal sealed interface SourcePresetEvent {
16: data object SaveCurrent : SourcePresetEvent
17: data class Rename(val id: String) : SourcePresetEvent
18: data class Update(val id: String) : SourcePresetEvent
19: data class NameChanged(val name: String) : SourcePresetEvent
20: data class Commit(val replace: Boolean = false) : SourcePresetEvent
21: data object CancelEdit : SourcePresetEvent
22: data class Apply(val id: String) : SourcePresetEvent
23: data class Delete(val id: String) : SourcePresetEvent
24: data object CancelReview : SourcePresetEvent
25: data object ReviewFilters : SourcePresetEvent
26: data object CloseReviewFilters : SourcePresetEvent
Exact file bytes / download · SHA-256 442eaacba8599b94eafd4189ac1b2d7b8f7691bc1f50380da4e855823bdbddd2.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.services.extensions.PresetValidation
internal enum class PresetEditMode { Save, Rename, Update }
internal data class PresetEditor(
val mode: PresetEditMode,
val name: String,
val targetId: String? = null,
val conflictId: String? = null,
val invalidName: Boolean = false,
)
internal data class PresetReview(val preset: DbSavedSearch, val validation: PresetValidation)
internal sealed interface SourcePresetEvent {
data object SaveCurrent : SourcePresetEvent
data class Rename(val id: String) : SourcePresetEvent
data class Update(val id: String) : SourcePresetEvent
data class NameChanged(val name: String) : SourcePresetEvent
data class Commit(val replace: Boolean = false) : SourcePresetEvent
data object CancelEdit : SourcePresetEvent
data class Apply(val id: String) : SourcePresetEvent
data class Delete(val id: String) : SourcePresetEvent
data object CancelReview : SourcePresetEvent
data object ReviewFilters : SourcePresetEvent
data object CloseReviewFilters : SourcePresetEvent
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresets.kt
- Source · implementation · 75 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
14: internal fun DbSettings.withSourcePreset(preset: DbSavedSearch): DbSettings = copy(
18: internal fun DbSettings.withoutSourcePreset(sourceId: Long, id: String): DbSettings = copy(
22: internal fun DbSettings.sourcePreset(sourceId: Long, id: String): DbSavedSearch? =
25: internal fun newPresetId(): String = "preset:" + Random.nextBytes(16).toHexString()
28: internal data class PresetCommit(val editor: PresetEditor?, val save: DbSavedSearch? = null)
35: internal fun commitPreset(
65: internal fun SourceHomeUiState.withPresetApplied(preset: DbSavedSearch, source: DbSource): SourceHomeUiState {
Exact file bytes / download · SHA-256 9ed9365684c75dbf812f570d4d035399a5fa1ecd4f321924460d9559e01d4e7f.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.presetIdentity
import eu.friedcutlet.yokan.services.extensions.PresetIssue
import eu.friedcutlet.yokan.services.extensions.PresetIssueReason
import eu.friedcutlet.yokan.services.extensions.PresetValidation
import eu.friedcutlet.yokan.services.extensions.capturePresetFilters
import eu.friedcutlet.yokan.services.extensions.validateSourcePreset
import kotlin.random.Random
internal fun DbSettings.withSourcePreset(preset: DbSavedSearch): DbSettings = copy(
savedSearches = savedSearches.orEmpty().filterNot { it.sourceId == preset.sourceId && it.id == preset.id } + preset,
)
internal fun DbSettings.withoutSourcePreset(sourceId: Long, id: String): DbSettings = copy(
savedSearches = savedSearches.orEmpty().filterNot { it.sourceId == sourceId && it.id == id },
)
internal fun DbSettings.sourcePreset(sourceId: Long, id: String): DbSavedSearch? =
savedSearches.orEmpty().firstOrNull { it.sourceId == sourceId && it.id == id }
internal fun newPresetId(): String = "preset:" + Random.nextBytes(16).toHexString()
/** Result of committing the open [PresetEditor]: the editor to show next and the preset to store, if any. */
internal data class PresetCommit(val editor: PresetEditor?, val save: DbSavedSearch? = null)
/**
* Commits [state]'s preset editor for [source]. Returns null when nothing changes (no editor, or the
* filter schema is not ready for a save/update); otherwise the next editor (kept open with an error or
* conflict, or closed) and the preset to store.
*/
internal fun commitPreset(
state: SourceHomeUiState,
db: DbSettings,
source: DbSource,
replace: Boolean,
newId: () -> String = ::newPresetId,
): PresetCommit? {
val editor = state.presetEditor ?: return null
val name = editor.name.trim()
if (name.isEmpty()) return PresetCommit(editor.copy(invalidName = true))
val target = editor.targetId?.let { db.sourcePreset(source.id, it) }
if (editor.targetId != null && target == null) return PresetCommit(null)
val conflict = db.savedSearches.orEmpty().firstOrNull {
it.sourceId == source.id && it.name == name && it.id != editor.targetId
}
if (conflict != null && (!replace || editor.conflictId != conflict.id || editor.mode == PresetEditMode.Rename)) {
return PresetCommit(editor.copy(conflictId = conflict.id))
}
if (editor.mode != PresetEditMode.Rename && !state.filterSchemaReady) return null
val preset = if (editor.mode == PresetEditMode.Rename && target != null) target.copy(name = name) else DbSavedSearch(
sourceId = source.id, name = name, query = state.searchQuery.trim(),
id = target?.id ?: conflict?.id ?: newId(),
sourceIdentity = source.presetIdentity(),
filters = capturePresetFilters(state.filters, state.selectedFilterValues),
filterSchemaRecorded = true,
)
return PresetCommit(null, preset)
}
/** Runs [preset] as a search when it validates against the loaded filters; otherwise opens its review. */
internal fun SourceHomeUiState.withPresetApplied(preset: DbSavedSearch, source: DbSource): SourceHomeUiState {
val validation = if (filterSchemaReady) validateSourcePreset(preset, source, filters)
else PresetValidation(emptyMap(), listOf(PresetIssue(preset.name, PresetIssueReason.SchemaNotReady)))
if (validation.issues.isNotEmpty()) return copy(presetReview = PresetReview(preset, validation))
return copy(isSearchMode = true, selectedTab = SourceTab.Search, searchQuery = preset.query,
submittedQuery = preset.query, selectedFilterValues = validation.selections,
appliedFilterValues = validation.selections, filtersApplied = validation.selections.isNotEmpty(),
page = 1, items = emptyList(), hasNextPage = false, appendExhausted = false,
loading = false, loadingMore = false, loadedKey = null,
requestRevision = requestRevision + 1, presetReview = null)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/CategoryEditorSheet.kt
- Source · implementation · 153 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
47: internal fun CategoryEditorSheet(
Exact file bytes / download · SHA-256 bee88fa205ce7ab5e60f97079a21305c3eaa8a2831939773f29c5ce432c9561f.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.Manga
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.ui_clear
import yokan.composeapp.generated.resources.ui_close
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import eu.friedcutlet.yokan.ui.components.hoverHighlight
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun CategoryEditorSheet(
manga: Manga,
categories: List<Category>,
onSave: (categoryIds: List<Long>) -> Unit,
onDismiss: () -> Unit,
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
var selected by remember(manga.id, manga.categories) { mutableStateOf(manga.categories.toSet()) }
ModalBottomSheet(
onDismissRequest = onDismiss,
modifier = Modifier.compactSheetWidth(),
sheetState = sheetState,
) {
val sheetScroll = rememberScrollState()
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 640.dp),
) {
eu.friedcutlet.yokan.ui.components.ScrollbarBox(
state = sheetScroll,
modifier = Modifier
.fillMaxWidth()
.weight(1f, fill = false),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 8.dp)
.verticalScroll(sheetScroll),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
Text(
text = "Categories",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
Text(
text = manga.name,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (categories.isEmpty()) {
Text(
"No categories exist for ${manga.itemType.label.lowercase()} yet.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
categories.forEach { category ->
val checked = category.id in selected
Row(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.medium)
.hoverHighlight(onClick = {
selected = if (checked) selected - category.id else selected + category.id
})
.padding(horizontal = 8.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Checkbox(
checked = checked,
onCheckedChange = { isChecked ->
selected = if (isChecked) selected + category.id else selected - category.id
},
)
Column(modifier = Modifier.weight(1f)) {
Text(category.name, fontWeight = FontWeight.Medium)
Text(
if (category.hidden) "Hidden in library" else "Visible in library",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
}
Spacer(Modifier.height(6.dp))
}
}
Surface(tonalElevation = 3.dp) {
Row(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.padding(horizontal = 20.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = { selected = emptySet() }) { Text(stringResource(Res.string.ui_clear)) }
TextButton(onClick = onDismiss) { Text(stringResource(Res.string.ui_close)) }
FilledTonalButton(
onClick = {
onSave(selected.toList())
onDismiss()
},
) { Text(stringResource(Res.string.action_save)) }
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterFilterSheet.kt
- Source · implementation · 232 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
59: internal fun ChapterFilterSheet(
188: private fun SetChapterListDefaultDialog(onDismiss: () -> Unit, onConfirm: (applyToLibrary: Boolean) -> Unit) {
212: private fun chapterSortLabel(index: Int, itemType: ItemType, selected: Boolean, reverse: Boolean): String {
222: private fun chapterFilterLabel(kind: ChapterFilterKind, itemType: ItemType, type: Int): String {
Exact file bytes / download · SHA-256 726f2ca2884c910ed3a58d1c38df9674bf9990b50c3d40c55b4cf80938c344cb.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.chapterReleasePreference
import eu.friedcutlet.yokan.domain.normalizeScanlator
import androidx.compose.material3.Switch
import androidx.compose.material3.TextButton
import androidx.compose.foundation.layout.Row
import androidx.compose.ui.Alignment
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import org.jetbrains.compose.resources.stringResource
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.semantics.Role
import yokan.composeapp.generated.resources.*
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import eu.friedcutlet.yokan.services.library.ChapterFilterKind
import eu.friedcutlet.yokan.services.library.chapterFilters
import eu.friedcutlet.yokan.services.library.chapterSort
import eu.friedcutlet.yokan.services.library.scanlatorFilter
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ChapterFilterSheet(
manga: Manga,
settings: DbSettings,
scanlators: List<String>,
onSort: (index: Int) -> Unit,
onCycleFilter: (ChapterFilterKind) -> Unit,
onToggleScanlator: (String) -> Unit,
showAllReleases: Boolean,
onShowAllReleases: (Boolean) -> Unit,
onSkipDuplicates: (Boolean) -> Unit,
onMoveScanlator: (String, Int) -> Unit,
onResetReleaseOverride: () -> Unit,
onSetAsDefault: (applyToLibrary: Boolean) -> Unit,
onDismiss: () -> Unit,
) {
var setDefaultOpen by rememberSaveable { mutableStateOf(false) }
if (setDefaultOpen) SetChapterListDefaultDialog({ setDefaultOpen = false }, onSetAsDefault)
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
ModalBottomSheet(
onDismissRequest = onDismiss,
modifier = Modifier.compactSheetWidth(),
sheetState = sheetState,
) {
val sheetScroll = androidx.compose.foundation.rememberScrollState()
eu.friedcutlet.yokan.ui.components.ScrollbarBox(
state = sheetScroll,
modifier = Modifier.fillMaxWidth(),
) {
Column(
Modifier
.fillMaxWidth()
.animateContentSize(
animationSpec = tween(
durationMillis = 300,
easing = CubicBezierEasing(0.35f, 0.91f, 0.33f, 0.97f),
),
)
.padding(horizontal = 20.dp, vertical = 8.dp)
.verticalScroll(sheetScroll),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
Text(
text = "Chapters",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
Text(
"Sort",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
val sort = settings.chapterSort(manga)
for (index in 0..3) {
FilterChip(
selected = sort.index == index,
onClick = { onSort(index) },
label = { Text(chapterSortLabel(index, manga.itemType, sort.index == index, sort.reverse)) },
)
}
}
Text(
"Filter",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ChapterFilterKind.entries.filter { it != ChapterFilterKind.Filler || manga.itemType == ItemType.Anime }.forEach { kind ->
val type = settings.chapterFilters(manga).value(kind)
FilterChip(
selected = type != 0,
onClick = { onCycleFilter(kind) },
label = { Text(chapterFilterLabel(kind, manga.itemType, type)) },
leadingIcon = { Icon(Icons.Filled.FilterList, contentDescription = null) },
)
}
}
TextButton(onClick = { setDefaultOpen = true }) { Text(stringResource(Res.string.chapter_list_set_default)) }
if (scanlators.isNotEmpty()) {
Text(
"Scanlators",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
val hidden = settings.scanlatorFilter(manga.id)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
scanlators.forEach { scanlator ->
FilterChip(
selected = normalizeScanlator(scanlator) in hidden,
onClick = { onToggleScanlator(scanlator) },
label = {
val label = scanlator.ifBlank { stringResource(Res.string.releases_unknown_group) }
Text(if (normalizeScanlator(scanlator) in hidden) stringResource(Res.string.releases_hidden_group, label) else label)
},
)
}
}
}
val preference = settings.chapterReleasePreference(manga.id)
ScanlatorPriorityControls(preference.scanlatorPriority, scanlators, preference.skipDuplicateReleases,
onSkipDuplicates, onMoveScanlator)
Row(verticalAlignment = Alignment.CenterVertically) {
val showAllLabel = stringResource(Res.string.releases_show_all)
Text(showAllLabel, modifier = Modifier.weight(1f))
Switch(checked = showAllReleases, onCheckedChange = onShowAllReleases, modifier = Modifier.semantics { contentDescription = showAllLabel })
}
Text(stringResource(Res.string.releases_show_all_description), style = MaterialTheme.typography.bodySmall)
if (settings.chapterReleasePreferences.any { it.mangaId == manga.id }) {
TextButton(onClick = onResetReleaseOverride) { Text(stringResource(Res.string.releases_use_default)) }
} else Text(stringResource(Res.string.releases_using_default), style = MaterialTheme.typography.bodySmall)
Spacer(Modifier.height(8.dp))
}
} // end ScrollbarBox
}
}
@Composable
private fun SetChapterListDefaultDialog(onDismiss: () -> Unit, onConfirm: (applyToLibrary: Boolean) -> Unit) {
var applyToLibrary by rememberSaveable { mutableStateOf(false) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(Res.string.chapter_list_set_default)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(Res.string.chapter_list_set_default_message))
Row(
Modifier.fillMaxWidth().toggleable(applyToLibrary, role = Role.Checkbox, onValueChange = { applyToLibrary = it }),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(checked = applyToLibrary, onCheckedChange = null)
Text(stringResource(Res.string.chapter_list_set_default_apply_library))
}
}
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
confirmButton = {
TextButton(onClick = { onConfirm(applyToLibrary); onDismiss() }) { Text(stringResource(Res.string.ok)) }
},
)
}
private fun chapterSortLabel(index: Int, itemType: ItemType, selected: Boolean, reverse: Boolean): String {
val base = when (index) {
0 -> "Scanlator"
2 -> "Upload date"
3 -> "Name"
else -> if (itemType == ItemType.Anime) "Episode" else "Chapter"
}
return if (selected) "$base ${if (reverse) "desc" else "asc"}" else base
}
private fun chapterFilterLabel(kind: ChapterFilterKind, itemType: ItemType, type: Int): String {
val base = when (kind) {
ChapterFilterKind.Unread -> if (itemType == ItemType.Anime) "Unwatched" else "Unread"
else -> kind.label
}
return when (type) {
1 -> "$base: include"
2 -> "$base: exclude"
else -> base
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterList.kt
- Source · implementation · 512 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
85: internal fun ChaptersHeaderRow(
143: internal fun formatAnimeProgress(positionMs: Long): String {
151: internal suspend fun completeChapterSwipeDismiss(
167: internal fun ChapterRow(
383: internal fun ChapterSelectionTopBar(
403: internal fun ChapterSelectionBottomBar(
475: internal fun EmptyChaptersCard(itemType: ItemType) {
484: internal fun formatChapterDate(raw: String, settings: DbSettings): String? {
495: private fun Modifier.onSecondaryClick(onClick: (shiftPressed: Boolean) -> Unit): Modifier =
508: internal fun chapterLabel(itemType: ItemType): String = when (itemType) {
Exact file bytes / download · SHA-256 353db33f31283f17fb773cc97d5f7cc832a20d6434ccbeaad0cd4314bb350719.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import yokan.composeapp.generated.resources.detail_selected_count
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DeleteSweep
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.DownloadDone
import androidx.compose.material.icons.filled.Downloading
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material.icons.filled.Flag
import androidx.compose.material.icons.filled.Restore
import androidx.compose.material.icons.outlined.Flag
import yokan.composeapp.generated.resources.filler_mark
import yokan.composeapp.generated.resources.filler_reset
import yokan.composeapp.generated.resources.filler_unmark
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
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.input.key.type
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.isSecondaryPressed
import androidx.compose.ui.input.pointer.isShiftPressed
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.ui_bookmark
import yokan.composeapp.generated.resources.ui_mark_read
import yokan.composeapp.generated.resources.ui_mark_unread
import yokan.composeapp.generated.resources.ui_unbookmark
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.formatAbsoluteDate
import eu.friedcutlet.yokan.ui.parseDateToEpochMillis
import eu.friedcutlet.yokan.ui.screens.novel.parseNovelProgressRatio
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import androidx.compose.material.icons.filled.HourglassEmpty
import eu.friedcutlet.yokan.ui.components.EmptyState
@Composable
internal fun ChaptersHeaderRow(
label: String,
count: Int,
missingCount: Int = 0,
unnumberedCount: Int = 0,
selectionActions: @Composable () -> Unit = {},
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Column(Modifier.weight(1f)) {
Text(
text = "$count ${label.lowercase()}",
style = MaterialTheme.typography.bodyLarge,
fontWeight = FontWeight.Bold,
)
if (missingCount > 0 || unnumberedCount > 0) {
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (missingCount > 0) {
androidx.compose.material3.Surface(
color = MaterialTheme.colorScheme.errorContainer,
shape = MaterialTheme.shapes.small,
) {
Text(
text = if (missingCount == 1) "1 missing" else "$missingCount missing",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onErrorContainer,
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
}
if (unnumberedCount > 0) {
androidx.compose.material3.Surface(
color = MaterialTheme.colorScheme.surfaceVariant,
shape = MaterialTheme.shapes.small,
) {
Text(
text = if (unnumberedCount == 1) "1 unnumbered" else "$unnumberedCount unnumbered",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
}
}
}
}
selectionActions()
}
}
internal fun formatAnimeProgress(positionMs: Long): String {
val totalSeconds = positionMs.coerceAtLeast(0L) / 1000L
val hours = totalSeconds / 3600L
val minutes = (totalSeconds % 3600L) / 60L
val seconds = totalSeconds % 60L
return "$hours:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}"
}
internal suspend fun completeChapterSwipeDismiss(
direction: SwipeToDismissBoxValue,
onBookmark: () -> Unit,
onReadToggle: () -> Unit,
reset: suspend () -> Unit,
) {
when (direction) {
SwipeToDismissBoxValue.StartToEnd -> onBookmark()
SwipeToDismissBoxValue.EndToStart -> onReadToggle()
SwipeToDismissBoxValue.Settled -> return
}
reset()
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun ChapterRow(
chapter: Chapter,
itemType: ItemType,
uploadDate: String?,
selected: Boolean,
anySelected: Boolean,
showDownload: Boolean,
onClick: () -> Unit,
onLongClick: () -> Unit,
onSecondaryClick: (Boolean) -> Unit,
onBookmark: () -> Unit,
onReadToggle: () -> Unit,
onDownload: () -> Unit,
) {
val titleColor = if (chapter.isRead) {
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.4f)
} else {
MaterialTheme.colorScheme.onSurface
}
val supportingColor = if (chapter.isRead) {
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f)
} else {
MaterialTheme.colorScheme.onSurfaceVariant
}
val subtitle = listOfNotNull(
if (chapter.isFiller) "Filler" else null,
uploadDate,
chapter.lastPageRead
.takeIf { it.isNotBlank() && it != "1" && !chapter.isRead }
?.let { progress ->
when (itemType) {
ItemType.Anime -> progress.toLongOrNull()?.let { "episode ${formatAnimeProgress(it)}" }
ItemType.Novel -> "${(parseNovelProgressRatio(progress) * 100).toInt()} %"
ItemType.Manga -> "page $progress"
}
},
chapter.scanlator.takeIf { it.isNotBlank() },
chapter.downloadSize,
).joinToString(" • ")
val rowColor = when {
selected -> MaterialTheme.colorScheme.primary.copy(alpha = 0.4f)
chapter.isFiller -> MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
else -> Color.Transparent
}
val swipeScope = rememberCoroutineScope()
val swipeState = rememberSwipeToDismissBoxState(
positionalThreshold = { distance -> distance * 0.25f },
)
val currentOnBookmark by rememberUpdatedState(onBookmark)
val currentOnReadToggle by rememberUpdatedState(onReadToggle)
val onSwipeDismiss: (SwipeToDismissBoxValue) -> Unit = remember(swipeState, swipeScope) {
{ direction ->
swipeScope.launch {
completeChapterSwipeDismiss(
direction = direction,
onBookmark = { currentOnBookmark() },
onReadToggle = { currentOnReadToggle() },
reset = { swipeState.reset() },
)
}
}
}
SwipeToDismissBox(
state = swipeState,
backgroundContent = {
val bookmarking = swipeState.dismissDirection == SwipeToDismissBoxValue.StartToEnd
Box(
modifier = Modifier
.fillMaxSize()
.background(
if (bookmarking) {
MaterialTheme.colorScheme.primary
} else if (chapter.isRead) {
MaterialTheme.colorScheme.onSurfaceVariant
} else {
Color(0xFF2E7D32)
},
)
.padding(horizontal = 20.dp),
contentAlignment = if (bookmarking) Alignment.CenterStart else Alignment.CenterEnd,
) {
Icon(
imageVector = if (bookmarking) {
if (chapter.isBookmarked) Icons.Filled.Bookmark else Icons.Filled.BookmarkBorder
} else {
if (chapter.isRead) Icons.Outlined.CheckCircle else Icons.Filled.CheckCircle
},
contentDescription = if (bookmarking) {
if (chapter.isBookmarked) "Remove bookmark" else "Add bookmark"
} else {
if (chapter.isRead) "Mark unread" else "Mark read"
},
tint = Color.White,
)
}
},
onDismiss = onSwipeDismiss,
content = {
Row(
modifier = Modifier
.background(MaterialTheme.colorScheme.surface)
.background(rowColor)
.hoverHighlight(onClick = null)
.onSecondaryClick(onSecondaryClick)
.combinedClickable(
onClickLabel = "Open ${chapterLabel(itemType).lowercase().removeSuffix("s")}",
onLongClickLabel = "Select ${chapterLabel(itemType).lowercase().removeSuffix("s")}",
onClick = onClick,
onLongClick = onLongClick,
)
.padding(horizontal = 15.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = Modifier
.width(2.dp)
.height(40.dp)
.clip(RoundedCornerShape(10.dp))
.background(
if (chapter.isRead) {
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.16f)
} else {
MaterialTheme.colorScheme.primary
},
),
)
Spacer(Modifier.width(13.dp))
chapter.thumbnailUrl?.takeIf { it.isNotBlank() }?.let { thumbnail ->
Spacer(Modifier.width(5.dp))
CoverImage(
model = thumbnail,
contentDescription = "${chapter.name} preview",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(width = 50.dp, height = 65.dp)
.clip(RoundedCornerShape(5.dp)),
)
Spacer(Modifier.width(5.dp))
}
Column(
modifier = Modifier.weight(1f).padding(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(3.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
if (chapter.isBookmarked) {
Icon(
Icons.Filled.Bookmark,
contentDescription = "Remove bookmark",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier
.size(16.dp)
.clickable(enabled = !anySelected, onClick = onBookmark),
)
}
Text(
text = chapter.name,
style = MaterialTheme.typography.bodyMedium,
color = titleColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
chapter.description?.takeIf { it.isNotBlank() }?.let { description ->
Text(
text = description,
color = titleColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.labelSmall,
)
}
if (subtitle.isNotBlank()) {
Text(
text = subtitle,
color = supportingColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.labelSmall,
)
}
}
if (showDownload) {
val (icon, tint, label) = when {
chapter.downloadSize != null -> Triple(
Icons.Filled.DownloadDone,
MaterialTheme.colorScheme.primary,
"Downloaded",
)
chapter.archivePath.isNotBlank() -> Triple(
Icons.Filled.Downloading,
MaterialTheme.colorScheme.tertiary,
"In progress",
)
else -> Triple(
Icons.Filled.Download,
MaterialTheme.colorScheme.onSurfaceVariant,
"Download",
)
}
IconButton(
onClick = onDownload,
enabled = !anySelected && chapter.downloadSize == null,
) {
Icon(icon, contentDescription = label, tint = tint)
}
}
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ChapterSelectionTopBar(
selectedCount: Int,
onClear: () -> Unit,
selectionActions: @Composable () -> Unit,
) {
TopAppBar(
title = { Text(stringResource(Res.string.detail_selected_count, selectedCount)) },
navigationIcon = {
IconButton(onClick = onClear) {
Icon(Icons.Filled.Close, contentDescription = "Clear selection")
}
},
actions = { selectionActions() },
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
),
)
}
@Composable
internal fun ChapterSelectionBottomBar(
bookmarked: Boolean,
read: Boolean,
showDownload: Boolean,
showDelete: Boolean,
/** Null hides the filler actions (non-anime); true when every selected episode is filler. */
filler: Boolean?,
showFillerReset: Boolean,
onBookmark: () -> Unit,
onMarkRead: () -> Unit,
onFiller: () -> Unit,
onResetFiller: () -> Unit,
onDownload: () -> Unit,
onDelete: () -> Unit,
) {
Surface(
color = MaterialTheme.colorScheme.surface,
shadowElevation = 8.dp,
) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = onBookmark) {
Icon(
if (bookmarked) Icons.Filled.Bookmark else Icons.Filled.BookmarkBorder,
contentDescription = if (bookmarked) {
stringResource(Res.string.ui_unbookmark)
} else {
stringResource(Res.string.ui_bookmark)
},
)
}
IconButton(onClick = onMarkRead) {
Icon(
if (read) Icons.Outlined.CheckCircle else Icons.Filled.CheckCircle,
contentDescription = if (read) {
stringResource(Res.string.ui_mark_unread)
} else {
stringResource(Res.string.ui_mark_read)
},
)
}
if (filler != null) {
IconButton(onClick = onFiller) {
Icon(
if (filler) Icons.Filled.Flag else Icons.Outlined.Flag,
contentDescription = stringResource(if (filler) Res.string.filler_unmark else Res.string.filler_mark),
)
}
if (showFillerReset) {
IconButton(onClick = onResetFiller) {
Icon(Icons.Filled.Restore, contentDescription = stringResource(Res.string.filler_reset))
}
}
}
if (showDownload) {
IconButton(onClick = onDownload) {
Icon(Icons.Filled.Download, contentDescription = "Download selected")
}
}
if (showDelete) {
IconButton(onClick = onDelete) {
Icon(Icons.Filled.DeleteSweep, contentDescription = "Delete downloads")
}
}
}
}
}
@Composable
internal fun EmptyChaptersCard(itemType: ItemType) {
EmptyState(
icon = Icons.Filled.HourglassEmpty,
title = "No ${chapterLabel(itemType).lowercase()} available",
subtitle = "Refresh the title to load data from the source runtime.",
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 24.dp),
)
}
internal fun formatChapterDate(raw: String, settings: DbSettings): String? {
val value = raw.trim()
if (value.isEmpty()) return null
val millis = parseDateToEpochMillis(value)
return if (millis != null && millis > 0L) {
formatAbsoluteDate(millis, settings.dateFormat)
} else {
value
}
}
private fun Modifier.onSecondaryClick(onClick: (shiftPressed: Boolean) -> Unit): Modifier =
pointerInput(onClick) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
if (event.type == PointerEventType.Press && event.buttons.isSecondaryPressed) {
event.changes.forEach { it.consume() }
onClick(event.keyboardModifiers.isShiftPressed)
}
}
}
}
internal fun chapterLabel(itemType: ItemType): String = when (itemType) {
ItemType.Anime -> "Episodes"
ItemType.Novel -> "Chapters"
ItemType.Manga -> "Chapters"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterSelection.kt
- Source · implementation · 55 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: internal enum class ChapterSelectionOption {
10: internal data class ChapterSelectionState(
14: fun toggle(id: Long) = copy(ids = if (id in ids) ids - id else ids + id, anchorId = id)
16: fun retainVisible(chapters: List<Chapter>): ChapterSelectionState {
21: fun rangeTo(chapters: List<Chapter>, id: Long): ChapterSelectionState {
30: fun selectRange(chapters: List<Chapter>, first: Int, last: Int): ChapterSelectionState {
36: fun select(chapters: List<Chapter>, option: ChapterSelectionOption): ChapterSelectionState {
Exact file bytes / download · SHA-256 0730fa1b78ba482489443b9dda3371cd23480db1465b43302f12b5e2b252b780.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import eu.friedcutlet.yokan.domain.Chapter
internal enum class ChapterSelectionOption {
All, Invert, Unread, Read, Downloaded, NotDownloaded, Bookmarked, Above, Below,
}
/** Selected chapter ids; [anchorId] is where range selections start. Chapter lists are in display order. */
internal data class ChapterSelectionState(
val ids: Set<Long> = emptySet(),
val anchorId: Long? = null,
) {
fun toggle(id: Long) = copy(ids = if (id in ids) ids - id else ids + id, anchorId = id)
fun retainVisible(chapters: List<Chapter>): ChapterSelectionState {
val visible = chapters.map { it.id }.toSet()
return copy(ids = ids intersect visible, anchorId = anchorId?.takeIf(visible::contains))
}
fun rangeTo(chapters: List<Chapter>, id: Long): ChapterSelectionState {
val from = chapters.indexOfFirst { it.id == anchorId }
val to = chapters.indexOfFirst { it.id == id }
return if (to < 0) this
else if (from < 0) copy(ids = ids + id, anchorId = id)
else copy(ids = ids + chapters.subList(minOf(from, to), maxOf(from, to) + 1).map { it.id })
}
/** Adds display rows [first]..[last] (1-based); invalid bounds change nothing. */
fun selectRange(chapters: List<Chapter>, first: Int, last: Int): ChapterSelectionState {
if (first !in 1..chapters.size || last !in first..chapters.size) return this
val range = chapters.subList(first - 1, last)
return copy(ids = ids + range.map(Chapter::id), anchorId = range.first().id)
}
fun select(chapters: List<Chapter>, option: ChapterSelectionOption): ChapterSelectionState {
val anchor = chapters.indexOfFirst { it.id == anchorId }
val selected = when (option) {
ChapterSelectionOption.All -> chapters.map(Chapter::id).toSet()
ChapterSelectionOption.Invert -> chapters.map(Chapter::id).toSet() - ids
ChapterSelectionOption.Above -> if (anchor < 0) ids else ids + chapters.take(anchor + 1).map(Chapter::id)
ChapterSelectionOption.Below -> if (anchor < 0) ids else ids + chapters.drop(anchor).map(Chapter::id)
else -> chapters.filter {
when (option) {
ChapterSelectionOption.Unread -> !it.isRead
ChapterSelectionOption.Read -> it.isRead
ChapterSelectionOption.Downloaded -> it.downloadSize != null || it.archivePath.isNotBlank()
ChapterSelectionOption.NotDownloaded -> it.downloadSize == null && it.archivePath.isBlank()
ChapterSelectionOption.Bookmarked -> it.isBookmarked
}
}.map(Chapter::id).toSet()
}
return copy(ids = selected, anchorId = anchorId?.takeIf(selected::contains) ?: chapters.firstOrNull { it.id in selected }?.id)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/CoverInspection.kt
- Source · implementation · 747 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
124: internal data class CoverTransform(val scale: Float, val offset: Offset)
126: internal enum class CoverInspectionKeyAction { Dismiss, ToggleControls, None }
128: internal fun coverInspectionKeyAction(key: Key): CoverInspectionKeyAction = when (key) {
135: internal data class CoverInspectionUiState(
146: internal class CoverInspectionViewModel : ViewModel() {
150: fun updateViewport(size: IntSize) = _state.update { current ->
164: fun imageLoading() = _state.update { it.copy(loadState = CoverLoadState.Loading) }
166: fun imageReady(size: IntSize) = _state.update { current ->
181: fun imageFailed() = _state.update { it.copy(loadState = CoverLoadState.Error) }
183: fun retry() = _state.update {
191: fun toggleControls() = _state.update { it.copy(controlsVisible = !it.controlsVisible) }
193: fun resetTransform() = _state.update { it.copy(transform = CoverTransform(MinCoverZoom, Offset.Zero)) }
195: fun transform(focal: Offset, pan: Offset, zoom: Float) = _state.update { current ->
208: fun doubleTap(focal: Offset) {
214: fun zoomAtCenter(factor: Float) {
219: fun runAction(action: suspend () -> String) {
237: internal fun fittedCoverSize(imageSize: IntSize, viewportSize: IntSize): Size {
248: internal fun constrainCoverOffset(
265: internal fun transformCover(
286: internal fun CoverInspectionDialog(
296: object : ViewModelStoreOwner {
336: internal fun CoverInspectionContent(
488: private fun CoverInspectionTopBar(
530: private fun CoverInspectionActions(
577: private fun RowScope.CoverAction(icon: ImageVector, label: String, enabled: Boolean, onClick: () -> Unit) {
587: private fun CoverLoadingState() {
603: private fun CoverErrorState(onRetry: () -> Unit) {
620: private fun IntSize.center(): Offset = Offset(width / 2f, height / 2f)
622: internal enum class CoverLoadState { Loading, Ready, Error }
631: private data class DetailCoverAsset(
637: internal fun Manga.detailCoverModel(): Any? =
642: private suspend fun resolveDetailCoverAsset(manga: Manga, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession): DetailCoverAsset? =
660: private fun ByteArray.toDetailCoverAsset(sourceHint: String? = null): DetailCoverAsset {
681: private fun Manga.coverFileName(extension: String): String {
691: internal suspend fun saveDetailCover(manga: Manga, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession): String = try {
708: internal suspend fun changeDetailCover(onCoverPicked: (ByteArray) -> Unit, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession): String = try {
727: internal suspend fun shareDetailCover(manga: Manga, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession): String = try {
Exact file bytes / download · SHA-256 fd7c720c5b46d20a61bae644d389b5084870f9bf941b0670f2913984ce3ac81a.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CenterFocusStrong
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.SaveAlt
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.ZoomIn
import androidx.compose.material.icons.filled.ZoomOut
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Immutable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import coil3.compose.AsyncImage
import coil3.compose.LocalPlatformContext
import coil3.request.ImageRequest
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.cover_inspection_change
import yokan.composeapp.generated.resources.cover_inspection_close
import yokan.composeapp.generated.resources.cover_inspection_error
import yokan.composeapp.generated.resources.cover_inspection_hint
import yokan.composeapp.generated.resources.cover_inspection_loading
import yokan.composeapp.generated.resources.cover_inspection_reset_zoom
import yokan.composeapp.generated.resources.cover_inspection_retry
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.cover_inspection_share
import yokan.composeapp.generated.resources.cover_inspection_title
import yokan.composeapp.generated.resources.cover_inspection_toggle_controls
import yokan.composeapp.generated.resources.cover_inspection_zoom_in
import yokan.composeapp.generated.resources.cover_inspection_zoom_out
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.ui.screens.reader.readerImageFormat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.getString
import eu.friedcutlet.yokan.services.files.pickFile
import eu.friedcutlet.yokan.ui.screens.reader.shareImage
import yokan.composeapp.generated.resources.cover_inspection_change_failed
import yokan.composeapp.generated.resources.cover_inspection_empty
import yokan.composeapp.generated.resources.cover_inspection_save_failed
import yokan.composeapp.generated.resources.cover_inspection_saved
import yokan.composeapp.generated.resources.cover_inspection_share_failed
import yokan.composeapp.generated.resources.cover_inspection_share_opened
import yokan.composeapp.generated.resources.cover_inspection_share_unavailable
import yokan.composeapp.generated.resources.cover_inspection_unchanged
import yokan.composeapp.generated.resources.cover_inspection_unavailable
import yokan.composeapp.generated.resources.cover_inspection_unknown_error
import yokan.composeapp.generated.resources.cover_inspection_updated
internal data class CoverTransform(val scale: Float, val offset: Offset)
internal enum class CoverInspectionKeyAction { Dismiss, ToggleControls, None }
internal fun coverInspectionKeyAction(key: Key): CoverInspectionKeyAction = when (key) {
Key.Escape -> CoverInspectionKeyAction.Dismiss
Key.Spacebar, Key.Enter -> CoverInspectionKeyAction.ToggleControls
else -> CoverInspectionKeyAction.None
}
@Immutable
internal data class CoverInspectionUiState(
val transform: CoverTransform = CoverTransform(MinCoverZoom, Offset.Zero),
val viewportSize: IntSize = IntSize.Zero,
val imageSize: IntSize = IntSize.Zero,
val loadState: CoverLoadState = CoverLoadState.Loading,
val retryAttempt: Int = 0,
val controlsVisible: Boolean = true,
val busy: Boolean = false,
val notice: String? = null,
)
internal class CoverInspectionViewModel : ViewModel() {
private val _state = MutableStateFlow(CoverInspectionUiState())
val state = _state.asStateFlow()
fun updateViewport(size: IntSize) = _state.update { current ->
current.copy(
viewportSize = size,
transform = current.transform.copy(
offset = constrainCoverOffset(
current.transform.offset,
current.transform.scale,
current.imageSize,
size,
),
),
)
}
fun imageLoading() = _state.update { it.copy(loadState = CoverLoadState.Loading) }
fun imageReady(size: IntSize) = _state.update { current ->
current.copy(
imageSize = size,
loadState = CoverLoadState.Ready,
transform = current.transform.copy(
offset = constrainCoverOffset(
current.transform.offset,
current.transform.scale,
size,
current.viewportSize,
),
),
)
}
fun imageFailed() = _state.update { it.copy(loadState = CoverLoadState.Error) }
fun retry() = _state.update {
it.copy(
transform = CoverTransform(MinCoverZoom, Offset.Zero),
loadState = CoverLoadState.Loading,
retryAttempt = it.retryAttempt + 1,
)
}
fun toggleControls() = _state.update { it.copy(controlsVisible = !it.controlsVisible) }
fun resetTransform() = _state.update { it.copy(transform = CoverTransform(MinCoverZoom, Offset.Zero)) }
fun transform(focal: Offset, pan: Offset, zoom: Float) = _state.update { current ->
current.copy(
transform = transformCover(
current.transform,
focal,
pan,
zoom,
current.imageSize,
current.viewportSize,
),
)
}
fun doubleTap(focal: Offset) {
val current = _state.value
val target = if (current.transform.scale > MinCoverZoom + 0.01f) MinCoverZoom else DoubleTapCoverZoom
transform(focal, Offset.Zero, target / current.transform.scale)
}
fun zoomAtCenter(factor: Float) {
val current = _state.value
transform(current.viewportSize.center(), Offset.Zero, factor)
}
fun runAction(action: suspend () -> String) {
if (_state.value.busy) return
viewModelScope.launch {
_state.update { it.copy(busy = true, notice = null) }
try {
val result = action()
_state.update { it.copy(notice = result) }
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Throwable) {
_state.update { it.copy(notice = error.message.orEmpty()) }
} finally {
_state.update { it.copy(busy = false) }
}
}
}
}
internal fun fittedCoverSize(imageSize: IntSize, viewportSize: IntSize): Size {
if (imageSize.width <= 0 || imageSize.height <= 0 || viewportSize.width <= 0 || viewportSize.height <= 0) {
return Size.Zero
}
val ratio = minOf(
viewportSize.width.toFloat() / imageSize.width,
viewportSize.height.toFloat() / imageSize.height,
)
return Size(imageSize.width * ratio, imageSize.height * ratio)
}
internal fun constrainCoverOffset(
offset: Offset,
scale: Float,
imageSize: IntSize,
viewportSize: IntSize,
): Offset {
if (scale <= MinCoverZoom) return Offset.Zero
val fitted = fittedCoverSize(imageSize, viewportSize)
if (fitted == Size.Zero) return Offset.Zero
val maxX = ((fitted.width * scale - viewportSize.width) / 2f).coerceAtLeast(0f)
val maxY = ((fitted.height * scale - viewportSize.height) / 2f).coerceAtLeast(0f)
return Offset(
x = if (maxX == 0f) 0f else offset.x.coerceIn(-maxX, maxX),
y = if (maxY == 0f) 0f else offset.y.coerceIn(-maxY, maxY),
)
}
internal fun transformCover(
current: CoverTransform,
focalPoint: Offset,
pan: Offset,
zoomChange: Float,
imageSize: IntSize,
viewportSize: IntSize,
): CoverTransform {
val nextScale = (current.scale * zoomChange).coerceIn(MinCoverZoom, MaxCoverZoom)
if (nextScale == MinCoverZoom) return CoverTransform(MinCoverZoom, Offset.Zero)
val viewportCenter = Offset(viewportSize.width / 2f, viewportSize.height / 2f)
val ratio = nextScale / current.scale
val focalOffset = (focalPoint - viewportCenter) * (1f - ratio)
val nextOffset = current.offset * ratio + pan + focalOffset
return CoverTransform(
scale = nextScale,
offset = constrainCoverOffset(nextOffset, nextScale, imageSize, viewportSize),
)
}
@Composable
internal fun CoverInspectionDialog(
title: String,
identity: Any,
model: Any?,
onDismiss: () -> Unit,
onSave: suspend () -> String,
onChange: suspend () -> String,
onShare: suspend () -> String,
) {
val owner = remember(identity) {
object : ViewModelStoreOwner {
override val viewModelStore = ViewModelStore()
}
}
DisposableEffect(owner) {
onDispose { owner.viewModelStore.clear() }
}
val viewModel = viewModel<CoverInspectionViewModel>(
viewModelStoreOwner = owner,
key = "cover-inspection",
) { CoverInspectionViewModel() }
val state by viewModel.state.collectAsStateWithLifecycle()
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
CoverInspectionContent(
title = title,
identity = identity,
model = model,
state = state,
onDismiss = onDismiss,
onViewportChanged = viewModel::updateViewport,
onImageLoading = viewModel::imageLoading,
onImageReady = viewModel::imageReady,
onImageFailed = viewModel::imageFailed,
onRetry = viewModel::retry,
onToggleControls = viewModel::toggleControls,
onTransform = viewModel::transform,
onDoubleTap = viewModel::doubleTap,
onZoomAtCenter = viewModel::zoomAtCenter,
onReset = viewModel::resetTransform,
onSave = { viewModel.runAction(onSave) },
onChange = { viewModel.runAction(onChange) },
onShare = { viewModel.runAction(onShare) },
)
}
}
@Composable
internal fun CoverInspectionContent(
title: String,
identity: Any,
model: Any?,
state: CoverInspectionUiState,
onDismiss: () -> Unit,
onViewportChanged: (IntSize) -> Unit,
onImageLoading: () -> Unit,
onImageReady: (IntSize) -> Unit,
onImageFailed: () -> Unit,
onRetry: () -> Unit,
onToggleControls: () -> Unit,
onTransform: (Offset, Offset, Float) -> Unit,
onDoubleTap: (Offset) -> Unit,
onZoomAtCenter: (Float) -> Unit,
onReset: () -> Unit,
onSave: () -> Unit,
onChange: () -> Unit,
onShare: () -> Unit,
) {
val context = LocalPlatformContext.current
val focusRequester = remember { FocusRequester() }
val toggleControlsLabel = stringResource(Res.string.cover_inspection_toggle_controls)
val request = remember(model, identity, state.retryAttempt, context) {
ImageRequest.Builder(context)
.data(model)
.size(MaxCoverDecodeSize, MaxCoverDecodeSize)
.build()
}
LaunchedEffect(Unit) { runCatching { focusRequester.requestFocus() } }
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
.clipToBounds()
.onSizeChanged(onViewportChanged)
.focusRequester(focusRequester)
.focusable()
.semantics {
onClick(label = toggleControlsLabel) {
onToggleControls()
true
}
}
.onKeyEvent { event ->
if (event.type != KeyEventType.KeyDown) return@onKeyEvent false
when (coverInspectionKeyAction(event.key)) {
CoverInspectionKeyAction.Dismiss -> onDismiss()
CoverInspectionKeyAction.ToggleControls -> onToggleControls()
CoverInspectionKeyAction.None -> return@onKeyEvent false
}
true
}
.pointerInput(identity, state.viewportSize, state.imageSize) {
detectTransformGestures { centroid, pan, zoom, _ ->
onTransform(centroid, pan, zoom)
}
}
.pointerInput(identity, state.viewportSize, state.imageSize) {
detectTapGestures(
onTap = { onToggleControls() },
onDoubleTap = onDoubleTap,
)
}
.pointerInput(identity, state.viewportSize, state.imageSize) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Main)
if (event.type != PointerEventType.Scroll) continue
val change = event.changes.firstOrNull() ?: continue
val delta = change.scrollDelta.y
if (delta == 0f) continue
onTransform(
change.position,
Offset.Zero,
if (delta < 0f) WheelZoomStep else 1f / WheelZoomStep,
)
change.consume()
}
}
},
) {
key(state.retryAttempt) {
AsyncImage(
model = request,
contentDescription = stringResource(Res.string.cover_inspection_title, title),
contentScale = ContentScale.Fit,
onLoading = { onImageLoading() },
onSuccess = { success ->
val intrinsic = success.painter.intrinsicSize
if (intrinsic.width.isFinite() && intrinsic.height.isFinite()) {
onImageReady(IntSize(intrinsic.width.toInt(), intrinsic.height.toInt()))
} else {
onImageReady(IntSize.Zero)
}
},
onError = { onImageFailed() },
modifier = Modifier
.fillMaxSize()
.graphicsLayer {
scaleX = state.transform.scale
scaleY = state.transform.scale
translationX = state.transform.offset.x
translationY = state.transform.offset.y
},
)
}
when (state.loadState) {
CoverLoadState.Loading -> CoverLoadingState()
CoverLoadState.Error -> CoverErrorState(
onRetry = onRetry,
)
CoverLoadState.Ready -> Unit
}
AnimatedVisibility(
visible = state.controlsVisible,
enter = fadeIn(),
exit = fadeOut(),
modifier = Modifier.align(Alignment.TopCenter),
) {
CoverInspectionTopBar(
title = title,
scale = state.transform.scale,
onDismiss = onDismiss,
onZoomOut = { onZoomAtCenter(1f / ButtonZoomStep) },
onReset = onReset,
onZoomIn = { onZoomAtCenter(ButtonZoomStep) },
)
}
AnimatedVisibility(
visible = state.controlsVisible,
enter = fadeIn(),
exit = fadeOut(),
modifier = Modifier.align(Alignment.BottomCenter),
) {
CoverInspectionActions(
busy = state.busy,
notice = state.notice,
onSave = onSave,
onChange = onChange,
onShare = onShare,
)
}
}
}
@Composable
private fun CoverInspectionTopBar(
title: String,
scale: Float,
onDismiss: () -> Unit,
onZoomOut: () -> Unit,
onReset: () -> Unit,
onZoomIn: () -> Unit,
) {
Surface(
modifier = Modifier.fillMaxWidth().statusBarsPadding(),
color = Color.Black.copy(alpha = 0.72f),
contentColor = Color.White,
) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = onDismiss) {
Icon(Icons.Filled.Close, stringResource(Res.string.cover_inspection_close))
}
Text(
text = stringResource(Res.string.cover_inspection_title, title),
style = MaterialTheme.typography.titleMedium,
color = Color.White,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
IconButton(onClick = onZoomOut, enabled = scale > MinCoverZoom) {
Icon(Icons.Filled.ZoomOut, stringResource(Res.string.cover_inspection_zoom_out))
}
IconButton(onClick = onReset, enabled = scale > MinCoverZoom) {
Icon(Icons.Filled.CenterFocusStrong, stringResource(Res.string.cover_inspection_reset_zoom))
}
IconButton(onClick = onZoomIn, enabled = scale < MaxCoverZoom) {
Icon(Icons.Filled.ZoomIn, stringResource(Res.string.cover_inspection_zoom_in))
}
}
}
}
@Composable
private fun CoverInspectionActions(
busy: Boolean,
notice: String?,
onSave: () -> Unit,
onChange: () -> Unit,
onShare: () -> Unit,
) {
Surface(
modifier = Modifier
.navigationBarsPadding()
.padding(16.dp)
.widthIn(max = 560.dp)
.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.96f),
tonalElevation = 6.dp,
) {
Column(
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
CoverAction(Icons.Filled.SaveAlt, stringResource(Res.string.action_save), !busy, onSave)
CoverAction(Icons.Filled.Edit, stringResource(Res.string.cover_inspection_change), !busy, onChange)
CoverAction(Icons.Filled.Share, stringResource(Res.string.cover_inspection_share), !busy, onShare)
}
when {
busy -> CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
!notice.isNullOrBlank() -> Text(
text = notice,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
else -> Text(
text = stringResource(Res.string.cover_inspection_hint),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
}
}
}
}
@Composable
private fun RowScope.CoverAction(icon: ImageVector, label: String, enabled: Boolean, onClick: () -> Unit) {
TextButton(onClick = onClick, enabled = enabled, modifier = Modifier.weight(1f)) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(icon, contentDescription = null, modifier = Modifier.size(22.dp))
Text(label, style = MaterialTheme.typography.labelMedium)
}
}
}
@Composable
private fun CoverLoadingState() {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
CircularProgressIndicator(color = Color.White)
Text(
stringResource(Res.string.cover_inspection_loading),
color = Color.White,
modifier = Modifier.padding(top = 12.dp),
)
}
}
@Composable
private fun CoverErrorState(onRetry: () -> Unit) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
stringResource(Res.string.cover_inspection_error),
color = Color.White,
style = MaterialTheme.typography.titleMedium,
)
Button(onClick = onRetry, modifier = Modifier.padding(top = 12.dp)) {
Text(stringResource(Res.string.cover_inspection_retry))
}
}
}
private fun IntSize.center(): Offset = Offset(width / 2f, height / 2f)
internal enum class CoverLoadState { Loading, Ready, Error }
private const val MinCoverZoom = 1f
private const val MaxCoverZoom = 5f
private const val DoubleTapCoverZoom = 2.5f
private const val WheelZoomStep = 1.15f
private const val ButtonZoomStep = 1.3f
private const val MaxCoverDecodeSize = 4096
private data class DetailCoverAsset(
val bytes: ByteArray,
val extension: String,
val mimeType: String,
)
internal fun Manga.detailCoverModel(): Any? =
customCoverImage
?: customCoverFromTracker?.takeIf { it.isNotBlank() }
?: imageUrl?.takeIf { it.isNotBlank() }
private suspend fun resolveDetailCoverAsset(manga: Manga, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession): DetailCoverAsset? =
withContext(Dispatchers.Default) {
manga.customCoverImage?.takeIf { it.isNotEmpty() }?.let { bytes ->
return@withContext bytes.toDetailCoverAsset()
}
val location = manga.customCoverFromTracker?.takeIf { it.isNotBlank() }
?: manga.imageUrl?.takeIf { it.isNotBlank() }
?: return@withContext null
val bytes = if (location.startsWith("http://", true) || location.startsWith("https://", true)) {
val response = owner.services.http.request(HttpRequest(url = location))
if (response.statusCode !in 200..299) return@withContext null
response.bodyBytes
} else {
owner.localFiles.readBytes(location)
}
bytes.takeIf { it.isNotEmpty() }?.toDetailCoverAsset(location)
}
private fun ByteArray.toDetailCoverAsset(sourceHint: String? = null): DetailCoverAsset {
val format = readerImageFormat(this)
// readerImageFormat reports unknown bytes as PNG; only those fall back to the URL extension.
if (format.extension != "png" || firstOrNull() == 0x89.toByte()) return DetailCoverAsset(this, format.extension, format.mimeType)
val extension = sourceHint
?.substringBefore('?')
?.substringBefore('#')
?.substringAfterLast('.', missingDelimiterValue = "")
?.lowercase()
?.takeIf { it in setOf("jpg", "jpeg", "png", "gif", "webp") }
?.let { if (it == "jpeg") "jpg" else it }
?: "jpg"
val mimeType = when (extension) {
"png" -> "image/png"
"gif" -> "image/gif"
"webp" -> "image/webp"
else -> "image/jpeg"
}
return DetailCoverAsset(this, extension, mimeType)
}
private fun Manga.coverFileName(extension: String): String {
val safeTitle = name
.replace(Regex("[^\\p{L}\\p{N}._-]+"), "_")
.trim('_')
.take(80)
.ifBlank { "yokan-cover" }
return "$safeTitle-cover.$extension"
}
/** Saves [manga]'s cover under the download root and returns the user-facing outcome. */
internal suspend fun saveDetailCover(manga: Manga, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession): String = try {
val asset = resolveDetailCoverAsset(manga, owner)
?: return getString(Res.string.cover_inspection_unavailable)
val files = owner.localFiles
val path = files.downloadRoot.trimEnd('/') + "/saved-covers/${manga.coverFileName(asset.extension)}"
withContext(Dispatchers.Default) { files.writeBytes(path, asset.bytes) }
getString(Res.string.cover_inspection_saved, path)
} catch (cancelled: kotlinx.coroutines.CancellationException) {
throw cancelled
} catch (throwable: Throwable) {
getString(
Res.string.cover_inspection_save_failed,
throwable.message.orEmpty().ifBlank { getString(Res.string.cover_inspection_unknown_error) },
)
}
/** Lets the user pick a replacement cover image, hands its bytes to [onCoverPicked], and returns the outcome. */
internal suspend fun changeDetailCover(onCoverPicked: (ByteArray) -> Unit, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession): String = try {
val selectedPath = pickFile(
extensions = listOf("jpg", "jpeg", "png", "webp", "gif"),
initial = null,
) ?: return getString(Res.string.cover_inspection_unchanged)
val bytes = withContext(Dispatchers.Default) { owner.localFiles.readBytes(selectedPath) }
if (bytes.isEmpty()) return getString(Res.string.cover_inspection_empty)
onCoverPicked(bytes)
getString(Res.string.cover_inspection_updated)
} catch (cancelled: kotlinx.coroutines.CancellationException) {
throw cancelled
} catch (throwable: Throwable) {
getString(
Res.string.cover_inspection_change_failed,
throwable.message.orEmpty().ifBlank { getString(Res.string.cover_inspection_unknown_error) },
)
}
/** Opens the platform share sheet for [manga]'s cover and returns the outcome. */
internal suspend fun shareDetailCover(manga: Manga, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession): String = try {
val asset = resolveDetailCoverAsset(manga, owner)
?: return getString(Res.string.cover_inspection_unavailable)
val shared = shareImage(
bytes = asset.bytes,
fileName = manga.coverFileName(asset.extension),
mimeType = asset.mimeType,
)
if (shared) {
getString(Res.string.cover_inspection_share_opened)
} else {
getString(Res.string.cover_inspection_share_unavailable)
}
} catch (cancelled: kotlinx.coroutines.CancellationException) {
throw cancelled
} catch (throwable: Throwable) {
getString(
Res.string.cover_inspection_share_failed,
throwable.message.orEmpty().ifBlank { getString(Res.string.cover_inspection_unknown_error) },
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailDownloads.kt
- Source · implementation · 268 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
42: internal fun DownloadDestinationDialog(
97: private fun DownloadDestinationRow(
154: internal fun DeleteChaptersDialog(
218: internal sealed class PendingDownloadRequest {
219: data class Single(val chapter: Chapter) : PendingDownloadRequest()
220: data class Bulk(val chapters: List<Chapter>, val option: DetailDownloadOption) : PendingDownloadRequest()
223: internal enum class DetailDownloadOption {
233: internal fun downloadOptionLabel(option: DetailDownloadOption, itemType: ItemType): String {
246: internal fun chaptersForDownloadOption(chapters: List<Chapter>, option: DetailDownloadOption): List<Chapter> =
Exact file bytes / download · SHA-256 c21414af4c5c5b96655307cc586e4af817fea6265911c11f679d495de2292c13.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.SaveAlt
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.delete
@Composable
internal fun DownloadDestinationDialog(
title: String,
folders: List<DbLocalFolder>,
defaultRoot: String,
selectedName: String?,
onSelect: (String?) -> Unit,
onDismiss: () -> Unit,
) {
val listState = rememberLazyListState()
val resolvedSelectedName = selectedName?.takeIf { selected -> folders.any { it.name == selected } }
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
},
text = {
eu.friedcutlet.yokan.ui.components.ScrollbarBox(
state = listState,
modifier = Modifier.fillMaxWidth(),
) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxWidth().heightIn(max = 360.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
item(key = "default") {
DownloadDestinationRow(
title = "Default app folder",
subtitle = defaultRoot,
selected = resolvedSelectedName == null,
onClick = { onSelect(null) },
)
}
items(folders, key = { it.name }) { folder ->
DownloadDestinationRow(
title = folder.name,
subtitle = folder.path,
selected = resolvedSelectedName == folder.name,
onClick = { onSelect(folder.name) },
)
}
}
}
},
confirmButton = {},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) }
},
)
}
@Composable
private fun DownloadDestinationRow(
title: String,
subtitle: String,
selected: Boolean,
onClick: () -> Unit,
) {
Surface(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.large)
.clickable(onClick = onClick),
shape = MaterialTheme.shapes.large,
color = if (selected) {
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.62f)
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.34f)
},
) {
Row(
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = if (selected) Icons.Filled.CheckCircle else Icons.Filled.SaveAlt,
contentDescription = null,
tint = if (selected) {
MaterialTheme.colorScheme.onPrimaryContainer
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
Column(modifier = Modifier.weight(1f)) {
Text(
title,
style = MaterialTheme.typography.bodyLarge,
fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
color = if (selected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
)
Text(
subtitle,
style = MaterialTheme.typography.bodySmall,
color = if (selected) {
MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.76f)
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
/** Confirms deleting downloaded files, or local chapters when [isLocalEntry]; [deletesEntry] warns the whole title goes. */
@Composable
internal fun DeleteChaptersDialog(
isLocalEntry: Boolean,
deletesEntry: Boolean,
selectedCount: Int,
itemType: ItemType,
onConfirm: () -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(
if (isLocalEntry) {
"Delete chapters"
} else {
"Delete downloads"
},
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (deletesEntry) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Icon(
Icons.Filled.Info,
contentDescription = "Warning",
tint = MaterialTheme.colorScheme.error,
)
Text(
"Are you sure you want to delete all chapters? This will delete the entire entry from the library.",
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodyMedium,
)
}
} else {
Text(
if (isLocalEntry) {
"Delete $selectedCount selected local " +
"${chapterLabel(itemType).lowercase()}${if (selectedCount == 1) "" else "s"}?"
} else {
"Delete downloaded files for $selectedCount selected " +
"${chapterLabel(itemType).lowercase()}${if (selectedCount == 1) "" else "s"}?"
},
style = MaterialTheme.typography.bodyMedium,
)
}
}
},
confirmButton = {
TextButton(onClick = onConfirm) {
Text(stringResource(Res.string.delete), color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(Res.string.action_cancel))
}
},
)
}
internal sealed class PendingDownloadRequest {
data class Single(val chapter: Chapter) : PendingDownloadRequest()
data class Bulk(val chapters: List<Chapter>, val option: DetailDownloadOption) : PendingDownloadRequest()
}
internal enum class DetailDownloadOption {
Next,
Next5,
Next10,
Next25,
Unread,
All,
Selected,
}
internal fun downloadOptionLabel(option: DetailDownloadOption, itemType: ItemType): String {
val unit = if (itemType == ItemType.Anime) "episode" else "chapter"
return when (option) {
DetailDownloadOption.Next -> "Next $unit"
DetailDownloadOption.Next5 -> "Next 5 ${unit}s"
DetailDownloadOption.Next10 -> "Next 10 ${unit}s"
DetailDownloadOption.Next25 -> "Next 25 ${unit}s"
DetailDownloadOption.Unread -> if (itemType == ItemType.Anime) "Unwatched" else "Unread"
DetailDownloadOption.All -> "All ${unit}s"
DetailDownloadOption.Selected -> "Selected ${unit}s"
}
}
internal fun chaptersForDownloadOption(chapters: List<Chapter>, option: DetailDownloadOption): List<Chapter> =
when (option) {
DetailDownloadOption.Unread -> chapters.filter { !it.isRead }
DetailDownloadOption.All -> chapters
DetailDownloadOption.Selected -> chapters
DetailDownloadOption.Next,
DetailDownloadOption.Next5,
DetailDownloadOption.Next10,
DetailDownloadOption.Next25 -> {
val count = when (option) {
DetailDownloadOption.Next -> 1
DetailDownloadOption.Next5 -> 5
DetailDownloadOption.Next10 -> 10
DetailDownloadOption.Next25 -> 25
DetailDownloadOption.Unread,
DetailDownloadOption.All,
DetailDownloadOption.Selected -> 1
}
val lastReadIndex = chapters.indexOfLast { it.isRead }
val startIndex = if (lastReadIndex < 0 || chapters.size == 1) 0 else lastReadIndex + 1
chapters.drop(startIndex).take(count)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailHeader.kt
- Source · implementation · 354 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
54: internal fun DetailBackdropHeader(
184: internal fun DetailSideHeader(
283: private fun TitleOptionsMenu(
307: internal fun DetailDescription(text: String, expanded: Boolean, onToggle: () -> Unit) {
350: private fun String.initials(): String = split(" ")
Exact file bytes / download · SHA-256 552edcb57cdbb50f94fff58cb1937af6ab882c0b896d295ceb853602b3e1e6fa.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
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.layout.statusBars
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.ui.components.CoverImage
@Composable
internal fun DetailBackdropHeader(
manga: Manga,
showSource: Boolean,
onTitleSelected: (String) -> Unit,
onCoverClick: () -> Unit,
) {
val coverModel: Any? = manga.customCoverImage
?: manga.customCoverFromTracker?.takeIf { it.isNotBlank() }
?: manga.imageUrl?.takeIf { it.isNotBlank() }
val titleOptions = manga.alternativeTitles.ifEmpty { listOf(manga.name) }
var titleMenuOpen by remember(manga.id, titleOptions) { mutableStateOf(false) }
// The header underlaps the transparent app bar (content skips the top
// scaffold padding), so grow it by status-bar inset + 64.dp app-bar height:
// the backdrop fills from y=0 while the bottom-aligned content keeps the
// same 300.dp of space clear of the app bar.
val appBarOffset = WindowInsets.statusBars.asPaddingValues().calculateTopPadding() + 64.dp
Box(modifier = Modifier.fillMaxWidth().height(300.dp + appBarOffset)) {
// Mangayomi keeps the cover barely visible beneath a scaffold-colored scrim.
if (coverModel != null) {
CoverImage(
model = coverModel,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxSize()
.alpha(0.16f),
)
}
// Scrim gradient so foreground text remains readable
Box(
modifier = Modifier
.fillMaxSize()
.background(
Brush.verticalGradient(
colors = listOf(
Color.Transparent,
eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor.current.copy(alpha = 0.55f),
eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor.current,
),
),
),
)
// Bottom row: thumbnail + title block
Row(
modifier = Modifier
.align(Alignment.BottomStart)
.fillMaxWidth()
.padding(horizontal = 13.dp, vertical = 20.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(13.dp),
) {
CoverImage(
model = coverModel,
contentDescription = "${manga.name} cover",
contentScale = ContentScale.Crop,
fallbackInitials = manga.name.initials(),
modifier = Modifier
.size(width = 98.dp, height = 150.dp)
.clip(RoundedCornerShape(5.dp))
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.16f))
.clickable(onClickLabel = "View full-size cover", onClick = onCoverClick),
)
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Box {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(enabled = titleOptions.size > 1) { titleMenuOpen = true },
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
SelectionContainer(Modifier.weight(1f, fill = false)) {
Text(
manga.name,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Normal,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
if (titleOptions.size > 1) {
Icon(Icons.Filled.ArrowDropDown, contentDescription = "Select title")
}
}
TitleOptionsMenu(
expanded = titleMenuOpen,
titleOptions = titleOptions,
onDismiss = { titleMenuOpen = false },
onSelect = {
titleMenuOpen = false
onTitleSelected(it)
},
)
}
Text(
text = manga.author?.takeIf { it.isNotBlank() } ?: "Unknown",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
Icon(
Icons.Filled.Info,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
text = if (showSource) {
"${manga.status.label} • ${manga.source} (${manga.lang.uppercase()})"
} else {
manga.status.label
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
}
@Composable
internal fun DetailSideHeader(
manga: Manga,
showSource: Boolean,
onTitleSelected: (String) -> Unit,
onCoverClick: () -> Unit,
) {
val coverModel: Any? = manga.customCoverImage
?: manga.customCoverFromTracker?.takeIf { it.isNotBlank() }
?: manga.imageUrl?.takeIf { it.isNotBlank() }
val titleOptions = manga.alternativeTitles.ifEmpty { listOf(manga.name) }
var titleMenuOpen by remember(manga.id, titleOptions) { mutableStateOf(false) }
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 13.dp, vertical = 20.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(13.dp),
) {
CoverImage(
model = coverModel,
contentDescription = "${manga.name} cover",
contentScale = ContentScale.Crop,
fallbackInitials = manga.name.initials(),
modifier = Modifier
.size(width = 98.dp, height = 150.dp)
.clip(RoundedCornerShape(5.dp))
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.16f))
.clickable(onClickLabel = "View full-size cover", onClick = onCoverClick),
)
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Box {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(enabled = titleOptions.size > 1) { titleMenuOpen = true },
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
SelectionContainer(Modifier.weight(1f, fill = false)) {
Text(
manga.name,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Normal,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
)
}
if (titleOptions.size > 1) {
Icon(Icons.Filled.ArrowDropDown, contentDescription = "Select title")
}
}
TitleOptionsMenu(
expanded = titleMenuOpen,
titleOptions = titleOptions,
onDismiss = { titleMenuOpen = false },
onSelect = {
titleMenuOpen = false
onTitleSelected(it)
},
)
}
Text(
text = manga.author?.takeIf { it.isNotBlank() } ?: "Unknown",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
Icon(
Icons.Filled.Info,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
text = if (showSource) {
"${manga.status.label} • ${manga.source} (${manga.lang.uppercase()})"
} else {
manga.status.label
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
@Composable
private fun TitleOptionsMenu(
expanded: Boolean,
titleOptions: List<String>,
onDismiss: () -> Unit,
onSelect: (String) -> Unit,
) {
DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {
titleOptions.forEach { title ->
DropdownMenuItem(
text = {
Text(
title,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
},
onClick = { onSelect(title) },
)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun DetailDescription(text: String, expanded: Boolean, onToggle: () -> Unit) {
var collapsedOverflows by remember(text) { mutableStateOf(false) }
Column(
modifier = Modifier
.fillMaxWidth()
.animateContentSize(
animationSpec = tween(
durationMillis = 500,
easing = CubicBezierEasing(0.18f, 1f, 0.04f, 1f),
),
)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
SelectionContainer {
Text(
text = text.trim(),
style = MaterialTheme.typography.bodyMedium,
maxLines = if (expanded) Int.MAX_VALUE else 3,
overflow = TextOverflow.Ellipsis,
onTextLayout = { layout ->
if (!expanded) collapsedOverflows = layout.hasVisualOverflow
},
modifier = Modifier
.fillMaxWidth()
.combinedClickable(onClick = {
if (collapsedOverflows || expanded) onToggle()
}),
)
}
if (collapsedOverflows || expanded) {
IconButton(
onClick = onToggle,
modifier = Modifier.align(Alignment.CenterHorizontally).size(32.dp),
) {
Icon(
imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
contentDescription = if (expanded) "Collapse description" else "Expand description",
)
}
}
}
}
private fun String.initials(): String = split(" ")
.filter { it.isNotBlank() }
.take(2)
.joinToString("") { it.first().uppercase() }
.ifBlank { "?" }
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailNotes.kt
- Source · implementation · 74 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
27: internal fun DetailNotePreview(
43: internal fun DetailNoteEditor(
Exact file bytes / download · SHA-256 f941260a7958ae56e31d3771f3ba1fd14ae296f7efffa277fa1668fc5b588568.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
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_save
import yokan.composeapp.generated.resources.detail_notes
import yokan.composeapp.generated.resources.detail_notes_add
import yokan.composeapp.generated.resources.detail_notes_edit
import yokan.composeapp.generated.resources.detail_notes_privacy
import yokan.composeapp.generated.resources.ui_clear
@Composable
internal fun DetailNotePreview(
note: String,
onEdit: () -> Unit,
modifier: Modifier = Modifier,
) {
Column(modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
TextButton(onClick = onEdit) {
Text(stringResource(if (note.isEmpty()) Res.string.detail_notes_add else Res.string.detail_notes_edit))
}
if (note.isNotEmpty()) {
Text(note, style = MaterialTheme.typography.bodyMedium, maxLines = 3, overflow = TextOverflow.Ellipsis)
}
}
}
@Composable
internal fun DetailNoteEditor(
draft: String,
onChange: (String) -> Unit,
onSave: () -> Unit,
onCancel: () -> Unit,
modifier: Modifier = Modifier,
) {
AlertDialog(
modifier = modifier,
onDismissRequest = onCancel,
title = { Text(stringResource(Res.string.detail_notes)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(Res.string.detail_notes_privacy), style = MaterialTheme.typography.bodySmall)
OutlinedTextField(
value = draft,
onValueChange = onChange,
label = { Text(stringResource(Res.string.detail_notes)) },
modifier = Modifier.fillMaxWidth(),
minLines = 4,
maxLines = 10,
)
// Clear changes the draft; Save commits it and Cancel discards it.
TextButton(onClick = { onChange("") }, enabled = draft.isNotEmpty()) {
Text(stringResource(Res.string.ui_clear))
}
}
},
confirmButton = { TextButton(onClick = onSave) { Text(stringResource(Res.string.action_save)) } },
dismissButton = { TextButton(onClick = onCancel) { Text(stringResource(Res.string.action_cancel)) } },
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailQuickActions.kt
- Source · implementation · 350 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
42: internal fun DetailRelatedActions(
93: private fun RelatedAction(label: String, icon: ImageVector, onClick: () -> Unit, modifier: Modifier, compact: Boolean = false) {
114: internal fun ChapterSelectionMenu(
160: internal fun ChapterRangeDialog(chapters: List<Chapter>, onSelect: (Int, Int) -> Unit, onDismiss: () -> Unit) {
198: internal fun DetailGenreTags(
241: internal fun DetailActionRow(
310: private fun DetailActionButton(
Exact file bytes / download · SHA-256 6ab74789923eec816576bad582794786bd39907e1c8ad72f934d6dbbe76446f5.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.Public
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.HourglassEmpty
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.ui.graphics.Color
import eu.friedcutlet.yokan.domain.Manga
@Composable
internal fun DetailRelatedActions(
itemType: ItemType,
hasTracks: Boolean,
onRecommendations: () -> Unit,
onWatchOrder: () -> Unit,
onSequels: () -> Unit,
) {
Surface(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
color = MaterialTheme.colorScheme.surfaceContainerLow,
shape = MaterialTheme.shapes.medium,
) {
Column {
BoxWithConstraints {
val stacked = maxWidth < 300.dp || LocalDensity.current.fontScale > 1.2f
val compact = maxWidth < 420.dp
if (stacked) {
Column {
RelatedAction(stringResource(Res.string.recommendations), Icons.Filled.AutoAwesome, onRecommendations, Modifier.fillMaxWidth())
if (itemType == ItemType.Anime) {
HorizontalDivider(Modifier.padding(horizontal = 12.dp))
RelatedAction(stringResource(Res.string.watch_order), Icons.Filled.AccountTree, onWatchOrder, Modifier.fillMaxWidth())
}
}
} else Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
RelatedAction(
stringResource(Res.string.recommendations), Icons.Filled.AutoAwesome,
onRecommendations, Modifier.weight(1f).fillMaxHeight(), compact,
)
if (itemType == ItemType.Anime) {
VerticalDivider(Modifier.padding(vertical = 12.dp))
RelatedAction(
stringResource(Res.string.watch_order), Icons.Filled.AccountTree,
onWatchOrder, Modifier.weight(1f).fillMaxHeight(), compact,
)
}
}
}
if (itemType == ItemType.Anime && hasTracks) {
HorizontalDivider(Modifier.padding(horizontal = 12.dp))
TextButton(onClick = onSequels, modifier = Modifier.align(Alignment.End)) {
Text(stringResource(Res.string.sequels))
Spacer(Modifier.width(8.dp))
Icon(Icons.AutoMirrored.Filled.ArrowForward, null, Modifier.size(18.dp))
}
}
}
}
}
@Composable
private fun RelatedAction(label: String, icon: ImageVector, onClick: () -> Unit, modifier: Modifier, compact: Boolean = false) {
Surface(onClick = onClick, modifier = modifier, color = MaterialTheme.colorScheme.surfaceContainerLow) {
if (compact) Column(
Modifier.heightIn(min = 76.dp).padding(horizontal = 8.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Icon(icon, null, Modifier.size(20.dp), tint = MaterialTheme.colorScheme.primary)
Text(label, style = MaterialTheme.typography.labelLarge, textAlign = TextAlign.Center)
} else Row(
Modifier.heightIn(min = 56.dp).padding(horizontal = 12.dp, vertical = 12.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(icon, null, Modifier.size(20.dp), tint = MaterialTheme.colorScheme.primary)
Text(label, style = MaterialTheme.typography.labelLarge, maxLines = 3, overflow = TextOverflow.Ellipsis)
}
}
}
@Composable
internal fun ChapterSelectionMenu(
enabled: Boolean,
hasSelection: Boolean,
hasAnchor: Boolean,
onSelect: (ChapterSelectionOption) -> Unit,
onRange: () -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
Box {
TextButton(onClick = { expanded = true }, enabled = enabled) {
Text(stringResource(Res.string.detail_select))
Icon(Icons.Filled.ArrowDropDown, null, Modifier.size(18.dp))
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }, modifier = Modifier.heightIn(max = 440.dp)) {
DropdownMenuItem(
text = { Text(stringResource(Res.string.detail_select_range)) },
onClick = { expanded = false; onRange() },
)
ChapterSelectionOption.entries.forEach { option ->
if (option == ChapterSelectionOption.Unread || option == ChapterSelectionOption.Above) HorizontalDivider()
val label = when (option) {
ChapterSelectionOption.All -> Res.string.detail_select_all
ChapterSelectionOption.Invert -> Res.string.detail_select_invert
ChapterSelectionOption.Unread -> Res.string.detail_select_unread
ChapterSelectionOption.Read -> Res.string.detail_select_read
ChapterSelectionOption.Downloaded -> Res.string.detail_select_downloaded
ChapterSelectionOption.NotDownloaded -> Res.string.detail_select_not_downloaded
ChapterSelectionOption.Bookmarked -> Res.string.detail_select_bookmarked
ChapterSelectionOption.Above -> Res.string.detail_select_above
ChapterSelectionOption.Below -> Res.string.detail_select_below
}
DropdownMenuItem(
text = { Text(stringResource(label)) },
enabled = when (option) {
ChapterSelectionOption.Above, ChapterSelectionOption.Below -> hasAnchor
ChapterSelectionOption.Invert -> hasSelection
else -> true
},
onClick = { expanded = false; onSelect(option) },
)
}
}
}
}
@Composable
internal fun ChapterRangeDialog(chapters: List<Chapter>, onSelect: (Int, Int) -> Unit, onDismiss: () -> Unit) {
var first by remember { mutableStateOf("1") }
var last by remember { mutableStateOf(chapters.size.toString()) }
val start = first.toIntOrNull()
val end = last.toIntOrNull()
val valid = start != null && end != null && start in 1..chapters.size && end in start..chapters.size
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
title = { Text(stringResource(Res.string.detail_select_range)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(Res.string.detail_range_hint), style = MaterialTheme.typography.bodySmall)
OutlinedTextField(
value = first, onValueChange = { first = it }, singleLine = true,
label = { Text(stringResource(Res.string.detail_range_from)) },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
supportingText = { Text(chapters.getOrNull((start ?: 0) - 1)?.name.orEmpty(), maxLines = 2) },
)
OutlinedTextField(
value = last, onValueChange = { last = it }, singleLine = true,
label = { Text(stringResource(Res.string.detail_range_through)) },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
supportingText = { Text(chapters.getOrNull((end ?: 0) - 1)?.name.orEmpty(), maxLines = 2) },
)
if (!valid) Text(stringResource(Res.string.detail_range_error, chapters.size), color = MaterialTheme.colorScheme.error)
}
},
confirmButton = {
TextButton(enabled = valid, onClick = { if (start != null && end != null) onSelect(start, end) }) {
Text(stringResource(Res.string.detail_select))
}
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
)
}
@Composable
internal fun DetailGenreTags(
tags: List<String>,
sources: List<Source>,
onLibrarySearch: (String) -> Unit,
onSourceSearch: (Source, String) -> Unit,
) {
var expandedTag by remember(tags) { mutableStateOf<String?>(null) }
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
tags.map(String::trim).filter(String::isNotEmpty).distinct().forEach { tag ->
key(tag) {
Box {
Surface(onClick = { expandedTag = tag }, shape = MaterialTheme.shapes.small, color = MaterialTheme.colorScheme.surfaceContainerHighest) {
Row(Modifier.heightIn(min = 48.dp).padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically) {
Text(tag, style = MaterialTheme.typography.labelLarge)
Icon(Icons.Filled.ArrowDropDown, null, Modifier.size(16.dp))
}
}
DropdownMenu(expanded = expandedTag == tag, onDismissRequest = { expandedTag = null }, modifier = Modifier.widthIn(max = 320.dp).heightIn(max = 380.dp)) {
DropdownMenuItem(
text = { Text(stringResource(Res.string.detail_genre_library)) },
leadingIcon = { Icon(Icons.Filled.Search, null) },
onClick = { expandedTag = null; onLibrarySearch(tag) },
)
HorizontalDivider()
Text(stringResource(Res.string.detail_genre_extensions), modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.SemiBold)
if (sources.isEmpty()) {
Text(stringResource(Res.string.detail_genre_no_extensions), modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.bodySmall)
}
sources.forEach { source ->
DropdownMenuItem(
text = { Text("${source.name} · ${source.lang.uppercase()}", maxLines = 2, overflow = TextOverflow.Ellipsis) },
leadingIcon = { Icon(Icons.Filled.Public, null) },
onClick = { expandedTag = null; onSourceSearch(source, tag) },
)
}
}
}
}
}
}
}
@Composable
internal fun DetailActionRow(
manga: Manga,
trackCount: Int,
showWeb: Boolean,
onFavorite: () -> Unit,
onFavoriteLongClick: (() -> Unit)?,
automaticUpdateDays: Int?,
onSmartUpdate: () -> Unit,
onTrack: () -> Unit,
onWeb: () -> Unit,
onMigrate: () -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surface),
verticalAlignment = Alignment.Top,
) {
DetailActionButton(
modifier = Modifier.weight(1f),
icon = if (manga.favorite) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder,
label = if (manga.favorite) "In library" else "Add to library",
active = manga.favorite,
onClick = onFavorite,
onLongClick = onFavoriteLongClick,
)
if (showWeb) {
DetailActionButton(
modifier = Modifier.weight(1f),
icon = Icons.Filled.HourglassEmpty,
label = when (val days = manga.smartUpdateDays) {
null -> automaticUpdateDays?.let { stringResource(Res.string.detail_smart_auto_days, it) }
?: stringResource(Res.string.detail_smart_auto_short)
0 -> stringResource(Res.string.detail_smart_always)
else -> stringResource(Res.string.detail_smart_days, days)
},
onClick = onSmartUpdate,
)
}
DetailActionButton(
modifier = Modifier.weight(1f),
icon = if (trackCount > 0) Icons.Filled.CheckCircle else Icons.Filled.StarBorder,
label = when (trackCount) {
0 -> stringResource(Res.string.ui_track)
1 -> "1 tracker"
else -> "$trackCount trackers"
},
active = trackCount > 0,
onClick = onTrack,
)
if (showWeb) {
DetailActionButton(
modifier = Modifier.weight(1f),
icon = Icons.Filled.Public,
label = "WebView",
onClick = onWeb,
)
}
DetailActionButton(
modifier = Modifier.weight(1f),
icon = Icons.Filled.Add,
label = stringResource(Res.string.migrate),
onClick = onMigrate,
)
}
}
@Composable
@OptIn(ExperimentalFoundationApi::class)
private fun DetailActionButton(
modifier: Modifier,
icon: ImageVector,
label: String,
active: Boolean = false,
onClick: () -> Unit,
onLongClick: (() -> Unit)? = null,
) {
Surface(
modifier = modifier
.heightIn(min = 64.dp)
.combinedClickable(
onClick = onClick,
onLongClick = onLongClick,
),
color = Color.Transparent,
contentColor = if (active) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
shape = ButtonDefaults.shape,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 12.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Icon(icon, contentDescription = null, modifier = Modifier.size(20.dp))
Text(
text = label,
style = MaterialTheme.typography.labelSmall,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center,
)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailScreen.kt
- Source · implementation · 772 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
81: internal fun DetailRoute(route: Route.Detail, nav: Navigator) {
127: private sealed interface DetailDialog {
128: data object Cover : DetailDialog
129: data object Filter : DetailDialog
130: data object Tracker : DetailDialog
131: data object SmartUpdate : DetailDialog
133: data class Categories(val favoriteAfter: Boolean) : DetailDialog
134: data object Range : DetailDialog
135: data object Delete : DetailDialog
136: data class Destination(val request: PendingDownloadRequest) : DetailDialog
146: internal fun DetailScreen(
255: fun shouldAskDownloadDestination(): Boolean =
258: fun requestDownload(chapter: Chapter) {
266: fun requestDownloads(targetChapters: List<Chapter>, option: DetailDownloadOption) {
274: fun toggleChapterSelection(chapter: Chapter) = onEvent(DetailEvent.ToggleSelection(chapter.id))
276: fun selectRangeTo(chapter: Chapter) = onEvent(DetailEvent.SelectRangeTo(chapter.id))
278: fun openWebView() {
314: fun editCategories() {
319: fun toggleFavorite() {
543: private fun DetailInfoBlocks(
609: private fun LazyListScope.detailChapterItems(
650: private fun DetailDialogs(
768: private suspend fun ownedCoverAction(owner: ProfileSession, action: suspend () -> String): String =
Exact file bytes / download · SHA-256 ff870f53cae6b5e0615c71a5f2bf70f85fd75adc69885a130b7cdd75ae435bd0.
Complete file
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<DetailDialog?>(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<Int, Int>() }
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<Chapter>, 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<DbLocalFolder>,
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")
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailSeasonList.kt
- Source · implementation · 71 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
33: internal fun DetailSeasonsHeader(count: Int, modifier: Modifier = Modifier) {
43: internal fun DetailSeasonRow(season: DetailSeasonTitle, onOpen: () -> Unit, onContinue: () -> Unit, modifier: Modifier = Modifier) {
Exact file bytes / download · SHA-256 88e8fb50cb134154a71aa3655ddb2b22af7da332ef188f5b07b8e82492dc6f08.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.components.CoverImage
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.detail_season_continue
import yokan.composeapp.generated.resources.detail_season_progress
import yokan.composeapp.generated.resources.detail_seasons
import yokan.composeapp.generated.resources.episodes_season_number
@Composable
internal fun DetailSeasonsHeader(count: Int, modifier: Modifier = Modifier) {
Text(
"${stringResource(Res.string.detail_seasons)} · $count",
style = MaterialTheme.typography.titleMedium,
modifier = modifier.padding(horizontal = 16.dp, vertical = 12.dp),
)
}
/** One season record: opening it shows that season's own detail page; the button resumes its next episode. */
@Composable
internal fun DetailSeasonRow(season: DetailSeasonTitle, onOpen: () -> Unit, onContinue: () -> Unit, modifier: Modifier = Modifier) {
val title = season.title
Row(
modifier.fillMaxWidth().heightIn(min = 72.dp).clickable(onClick = onOpen).padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
CoverImage(title.detailCoverModel(), contentDescription = null, fallbackInitials = title.name.take(1).uppercase(),
shape = MaterialTheme.shapes.small, modifier = Modifier.size(48.dp, 64.dp))
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(title.name, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, maxLines = 2, overflow = TextOverflow.Ellipsis)
val number = title.seasonNumber?.takeIf { it % 1.0 == 0.0 }?.toInt()
val progress = stringResource(Res.string.detail_season_progress, season.watchedCount, season.episodeCount)
Text(
number?.let { "${stringResource(Res.string.episodes_season_number, it)} · $progress" } ?: progress,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (season.episodeCount > 0) {
LinearProgressIndicator(progress = { season.watchedCount.toFloat() / season.episodeCount }, modifier = Modifier.fillMaxWidth())
}
}
if (season.continueChapter != null) {
FilledTonalIconButton(onClick = onContinue, modifier = Modifier.size(48.dp)) {
Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(Res.string.detail_season_continue, title.name))
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailTopBar.kt
- Source · implementation · 170 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
49: internal fun DetailTopBar(
125: fun Entry(label: String, icon: ImageVector?, enabled: Boolean = true, onClick: () -> Unit) = DropdownMenuItem(
Exact file bytes / download · SHA-256 b7549d9f3a387b34421197f50d712d93c27db833ff73f281cab66617745fb605.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.Box
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Label
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.Groups
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.SaveAlt
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.SyncAlt
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.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.together.RoomState
import eu.friedcutlet.yokan.ui.navigation.Route
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.action_refresh
import yokan.composeapp.generated.resources.detail_notes
import yokan.composeapp.generated.resources.source_related_entries
/** The detail app bar: back, bulk-download menu, chapter filter sheet, and the title's overflow actions. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun DetailTopBar(
manga: Manga,
source: Source?,
showTitle: Boolean,
showRemoteActions: Boolean,
filteringActive: Boolean,
metadataEnabled: Boolean,
canSetCategories: Boolean,
togetherRoom: RoomState?,
onBack: () -> Unit,
onDownload: (DetailDownloadOption) -> Unit,
onFilter: () -> Unit,
onSetCategories: () -> Unit,
onEvent: (DetailEvent) -> Unit,
onNavigate: (Route) -> Unit,
) {
var downloadMenuOpen by remember { mutableStateOf(false) }
var overflowOpen by remember { mutableStateOf(false) }
TopAppBar(
title = {
if (showTitle) {
Text(
manga.name,
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
},
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
}
},
actions = {
if (showRemoteActions) {
Box {
IconButton(onClick = { downloadMenuOpen = true }) {
Icon(Icons.Filled.Download, contentDescription = "Download")
}
DropdownMenu(
expanded = downloadMenuOpen,
onDismissRequest = { downloadMenuOpen = false },
) {
DetailDownloadOption.entries
.filterNot { it == DetailDownloadOption.Selected }
.forEach { option ->
DropdownMenuItem(
text = { Text(downloadOptionLabel(option, manga.itemType)) },
leadingIcon = { Icon(Icons.Filled.Download, contentDescription = null) },
onClick = {
downloadMenuOpen = false
onDownload(option)
},
)
}
}
}
}
IconButton(onClick = onFilter) {
Icon(
Icons.Filled.FilterList,
contentDescription = "Filter chapters",
tint = if (filteringActive) Color(0xFFFFEB3B) else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Box {
IconButton(onClick = { overflowOpen = true }) {
Icon(Icons.Filled.MoreVert, contentDescription = "More")
}
DropdownMenu(
expanded = overflowOpen,
onDismissRequest = { overflowOpen = false },
) {
// Every entry closes the menu before acting.
@Composable
fun Entry(label: String, icon: ImageVector?, enabled: Boolean = true, onClick: () -> Unit) = DropdownMenuItem(
text = { Text(label) },
leadingIcon = icon?.let { { Icon(it, contentDescription = null) } },
enabled = enabled,
onClick = {
overflowOpen = false
onClick()
},
)
if (showRemoteActions) Entry(stringResource(Res.string.action_refresh), Icons.Filled.Refresh) { onEvent(DetailEvent.Refresh) }
Entry("Refresh metadata", Icons.Filled.Info, enabled = metadataEnabled) { onEvent(DetailEvent.RefreshMetadata) }
if (canSetCategories) Entry("Set categories", Icons.AutoMirrored.Filled.Label, onClick = onSetCategories)
if (manga.favorite) Entry(stringResource(Res.string.detail_notes), null) { onEvent(DetailEvent.EditNote) }
if (showRemoteActions) {
Entry(stringResource(Res.string.source_related_entries), null) { onNavigate(Route.SourceRelated(manga.id)) }
Entry("Share", Icons.Filled.Share) { onEvent(DetailEvent.Share) }
}
Entry(
when {
togetherRoom == null -> if (manga.itemType == ItemType.Anime) "Watch together" else "Read together"
togetherRoom.canAddToPlaylist -> "Add to room playlist"
else -> "Suggest to room"
},
Icons.Filled.Groups,
) { onEvent(DetailEvent.Together) }
Entry("Mass migrate", Icons.Filled.SyncAlt) {
onNavigate(source?.let { Route.MassMigrationPreview(it.id) } ?: Route.MassMigration(manga.itemType))
}
if (showRemoteActions) {
Entry("Extension settings", Icons.Filled.Settings, enabled = source != null) {
source?.let { onNavigate(Route.ExtensionDetail(it.id)) }
}
}
Entry("Export metadata", Icons.Filled.SaveAlt) { onEvent(DetailEvent.ExportMetadata) }
}
}
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = if (showTitle) {
MaterialTheme.colorScheme.surface.copy(alpha = 0.96f)
} else {
Color.Transparent
},
),
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailViewModel.kt
- Source · implementation · 611 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
76: internal data class DetailContent(
102: internal data class DetailSeasonTitle(
109: internal data class TrackerSearchState(
115: internal data class DetailState(
131: internal sealed interface DetailEvent {
132: data object Refresh : DetailEvent
133: data object RefreshMetadata : DetailEvent
134: data object Share : DetailEvent
135: data object ExportMetadata : DetailEvent
136: data object EditNote : DetailEvent
137: data class ChangeNote(val text: String) : DetailEvent
138: data object SaveNote : DetailEvent
139: data object CancelNote : DetailEvent
140: data class SetFavorite(val favorite: Boolean) : DetailEvent
142: data class SetCategories(val categoryIds: List<Long>, val favorite: Boolean) : DetailEvent
143: data class SetDisplayTitle(val title: String) : DetailEvent
144: class SetCustomCover(val bytes: ByteArray) : DetailEvent
145: data class SetSmartUpdateDays(val days: Int?) : DetailEvent
146: data class SetRead(val chapterIds: Set<Long>, val read: Boolean) : DetailEvent
147: data class SetBookmarked(val chapterIds: Set<Long>, val bookmarked: Boolean) : DetailEvent
149: data object ToggleSelectedBookmarks : DetailEvent
151: data object ToggleSelectedRead : DetailEvent
153: data class SetFiller(val chapterIds: Set<Long>, val filler: Boolean?) : DetailEvent
155: data class Download(val chapter: Chapter, val destinationRoot: String?) : DetailEvent
156: data class DownloadAll(val chapters: List<Chapter>, val option: DetailDownloadOption, val destinationRoot: String?) : DetailEvent
158: data class DeleteSelected(val removeEntry: Boolean) : DetailEvent
159: data class ToggleSort(val index: Int) : DetailEvent
160: data class CycleFilter(val kind: ChapterFilterKind) : DetailEvent
162: data class SetChapterListDefault(val applyToLibrary: Boolean) : DetailEvent
163: data class ToggleScanlator(val scanlator: String) : DetailEvent
164: data class SetSkipDuplicates(val enabled: Boolean) : DetailEvent
165: data class MoveScanlator(val scanlator: String, val direction: Int) : DetailEvent
166: data object ResetReleaseOverride : DetailEvent
167: data class ShowAllReleases(val enabled: Boolean) : DetailEvent
168: data class SelectSeason(val season: Int?) : DetailEvent
169: data class Select(val option: ChapterSelectionOption) : DetailEvent
170: data class ToggleSelection(val chapterId: Long) : DetailEvent
171: data class SelectRangeTo(val chapterId: Long) : DetailEvent
172: data class SelectRange(val first: Int, val last: Int) : DetailEvent
173: data object ClearSelection : DetailEvent
174: data class SearchTracker(val trackerIndex: Int, val query: String) : DetailEvent
175: data class BindTrack(val trackerIndex: Int, val search: DbTrackSearch) : DetailEvent
176: data object CloseTrackerSearch : DetailEvent
178: data object Together : DetailEvent
181: internal sealed interface DetailEffect {
182: data class ShowMessage(val text: String) : DetailEffect
183: data object OpenTogetherSettings : DetailEffect
187: internal class DetailViewModel(
254: fun onEvent(event: DetailEvent) {
334: private fun refresh() {
353: private fun refreshMetadata(manga: Manga) {
372: private fun autoRefreshMetadata(manga: Manga) {
378: private suspend fun applyMetadata(manga: Manga): MetadataApplyResult {
390: private fun releaseActionIds(ids: Set<Long>): Set<Long> {
396: private fun downloadAll(content: DetailContent, event: DetailEvent.DownloadAll) {
408: private fun deleteSelected(removeEntry: Boolean) {
438: private fun exportMetadata(manga: Manga) {
449: private fun searchTracker(manga: Manga, event: DetailEvent.SearchTracker) {
475: private fun together(content: DetailContent) {
492: private fun toggleSelected(content: DetailContent, flag: (Chapter) -> Boolean, apply: (Set<Long>, Boolean) -> Unit) {
500: private fun updateSelection(transform: (ChapterSelectionState) -> ChapterSelectionState) =
503: private fun showMessage(text: String) {
508: private class TitleData(
517: private fun YokanRepository.titleData(mangaId: Long): TitleData? {
535: private fun detailContent(title: TitleData, index: LibraryIndex, db: DbSettings, showAllReleases: Boolean, selectedSeason: Int?): DetailContent {
567: private fun Chapter.detailSeason(): Int? = season?.takeIf { it >= 0 }
570: private fun Throwable.displayMessage(): String = message.orEmpty().ifBlank { this::class.simpleName.orEmpty() }
572: private fun shareUrl(manga: Manga, source: Source?): String {
578: private fun Manga.toMetadataJson(): String =
591: private fun String?.jsonStringOrNull(): String =
594: private fun String.jsonEscaped(): String = buildString {
607: private fun String.safeFileSegment(): String =
Exact file bytes / download · SHA-256 38bbaf1694baa5b7e66f1a1ebd3ecfab19beaa04eb8219a2d8a86a923f37df69.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import kotlinx.coroutines.CoroutineDispatcher
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.chapterReleasePreference
import eu.friedcutlet.yokan.database.withChapterReleasePreference
import eu.friedcutlet.yokan.database.withoutChapterReleaseOverride
import eu.friedcutlet.yokan.database.movedScanlator
import eu.friedcutlet.yokan.domain.equivalentReleaseIds
import eu.friedcutlet.yokan.domain.normalizeScanlator
import eu.friedcutlet.yokan.domain.selectChapterReleases
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ChapterRecognition
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.Track
import eu.friedcutlet.yokan.domain.meanChapterUpdateDays
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.download.ChapterDownloads
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.extensions.ExtensionLogger
import eu.friedcutlet.yokan.services.metadata.MetadataApplyResult
import eu.friedcutlet.yokan.services.metadata.MetadataService
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.services.together.RoomState
import eu.friedcutlet.yokan.services.together.ProfileTogetherSession
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.tracking.EnhancedTracker
import eu.friedcutlet.yokan.services.tracking.TrackerService
import eu.friedcutlet.yokan.services.tracking.trackerSearchId
import eu.friedcutlet.yokan.ui.screens.together.TogetherActions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.services.library.ChapterFilterKind
import eu.friedcutlet.yokan.services.library.filterChapters
import eu.friedcutlet.yokan.services.library.scanlatorFilter
import eu.friedcutlet.yokan.services.library.sortedChapters
import eu.friedcutlet.yokan.services.library.withChapterFilterCycled
import eu.friedcutlet.yokan.services.library.withChapterListDefaultFrom
import eu.friedcutlet.yokan.services.library.withChapterSortToggled
import eu.friedcutlet.yokan.services.library.withScanlatorToggled
/** What the detail screen shows about the title, rebuilt off the main thread when its data changes. */
internal data class DetailContent(
val manga: Manga,
val settings: DbSettings,
val source: Source? = null,
/** The title's chapters after its filters, in its sort order. */
val chapters: List<Chapter> = emptyList(),
/** First unread selected release in sort order, ignoring status filters; null when none are available. */
val continueChapter: Chapter? = null,
val scanlators: List<String> = emptyList(),
val automaticUpdateDays: Int? = null,
val missingChapterCount: Int = 0,
val unnumberedChapterCount: Int = 0,
val tracks: List<Track> = emptyList(),
val categories: List<Category> = emptyList(),
/** Installed, active sources of the title's type, its own source first. */
val genreSources: List<Source> = emptyList(),
/** False until the chapters were read once. */
val loaded: Boolean = false,
val seasons: List<Int> = emptyList(),
/** Null selects all episodes, including episodes without a recognized season. */
val selectedSeason: Int? = null,
/** Season records of an Animetail Seasons-type title, in season order. */
val seasonTitles: List<DetailSeasonTitle> = emptyList(),
)
/** One season record with its own progress; [continueChapter] is its first unwatched episode. */
internal data class DetailSeasonTitle(
val title: Manga,
val episodeCount: Int,
val watchedCount: Int,
val continueChapter: Chapter?,
)
internal data class TrackerSearchState(
val loading: Boolean = false,
val error: String? = null,
val results: List<DbTrackSearch> = emptyList(),
)
internal data class DetailState(
val content: DetailContent,
val trackerNames: List<String> = emptyList(),
val selection: ChapterSelectionState = ChapterSelectionState(),
val showAllReleases: Boolean = false,
/** A detail or metadata refresh is running. */
val loading: Boolean = false,
val error: String? = null,
val trackerSearch: TrackerSearchState = TrackerSearchState(),
/** Null means closed; the draft is committed only by SaveNote. */
val noteDraft: String? = null,
/** The Together room the user is in, if any. */
val togetherRoom: RoomState? = null,
val selectedSeason: Int? = null,
)
internal sealed interface DetailEvent {
data object Refresh : DetailEvent
data object RefreshMetadata : DetailEvent
data object Share : DetailEvent
data object ExportMetadata : DetailEvent
data object EditNote : DetailEvent
data class ChangeNote(val text: String) : DetailEvent
data object SaveNote : DetailEvent
data object CancelNote : DetailEvent
data class SetFavorite(val favorite: Boolean) : DetailEvent
/** Saves the title's categories, then favourites it when [favorite]. */
data class SetCategories(val categoryIds: List<Long>, val favorite: Boolean) : DetailEvent
data class SetDisplayTitle(val title: String) : DetailEvent
class SetCustomCover(val bytes: ByteArray) : DetailEvent
data class SetSmartUpdateDays(val days: Int?) : DetailEvent
data class SetRead(val chapterIds: Set<Long>, val read: Boolean) : DetailEvent
data class SetBookmarked(val chapterIds: Set<Long>, val bookmarked: Boolean) : DetailEvent
/** Unbookmarks the selected bookmarked chapters, bookmarks the rest, and clears the selection. */
data object ToggleSelectedBookmarks : DetailEvent
/** Marks the selected read chapters unread, the rest read, and clears the selection. */
data object ToggleSelectedRead : DetailEvent
/** Manual filler mark; null clears it so the source value applies again. */
data class SetFiller(val chapterIds: Set<Long>, val filler: Boolean?) : DetailEvent
/** A null [destinationRoot] means the download folder selected in settings. */
data class Download(val chapter: Chapter, val destinationRoot: String?) : DetailEvent
data class DownloadAll(val chapters: List<Chapter>, val option: DetailDownloadOption, val destinationRoot: String?) : DetailEvent
/** Deletes the selected chapters' downloads, or the local chapters; [removeEntry] removes the local title. */
data class DeleteSelected(val removeEntry: Boolean) : DetailEvent
data class ToggleSort(val index: Int) : DetailEvent
data class CycleFilter(val kind: ChapterFilterKind) : DetailEvent
/** Makes this title's sort and filters its media type's default; [applyToLibrary] resets library titles to it. */
data class SetChapterListDefault(val applyToLibrary: Boolean) : DetailEvent
data class ToggleScanlator(val scanlator: String) : DetailEvent
data class SetSkipDuplicates(val enabled: Boolean) : DetailEvent
data class MoveScanlator(val scanlator: String, val direction: Int) : DetailEvent
data object ResetReleaseOverride : DetailEvent
data class ShowAllReleases(val enabled: Boolean) : DetailEvent
data class SelectSeason(val season: Int?) : DetailEvent
data class Select(val option: ChapterSelectionOption) : DetailEvent
data class ToggleSelection(val chapterId: Long) : DetailEvent
data class SelectRangeTo(val chapterId: Long) : DetailEvent
data class SelectRange(val first: Int, val last: Int) : DetailEvent
data object ClearSelection : DetailEvent
data class SearchTracker(val trackerIndex: Int, val query: String) : DetailEvent
data class BindTrack(val trackerIndex: Int, val search: DbTrackSearch) : DetailEvent
data object CloseTrackerSearch : DetailEvent
/** Adds the title to the current Together room, or starts a room and emits [DetailEffect.OpenTogetherSettings]. */
data object Together : DetailEvent
}
internal sealed interface DetailEffect {
data class ShowMessage(val text: String) : DetailEffect
data object OpenTogetherSettings : DetailEffect
}
/** State and actions of one title's detail page. */
internal class DetailViewModel(
private val mangaId: Long,
private val repository: YokanRepository,
private val settings: SettingsStore,
libraryIndex: LibraryIndexStore,
private val downloads: ChapterDownloads,
private val metadata: MetadataService,
private val runtimeFactory: ExtensionRuntimeFactory,
private val database: YokanDatabase,
allTrackers: List<TrackerService>,
private val files: LocalFileService,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
private val together: ProfileTogetherSession? = null,
private val togetherHttp: HttpService? = null,
) : ViewModel() {
/** Trackers for this title's media type; [TrackerSearchState] indexes refer to this list. */
private val trackers = repository.manga(mangaId)?.itemType.let { type ->
allTrackers.filter { it.supports(isManga = type != ItemType.Anime) }
}
private val trackerNames = trackers.map { it.name }
private val _state = MutableStateFlow(
repository.manga(mangaId)?.let { DetailState(DetailContent(it, settings.db.value), trackerNames) },
)
/** Null when the title does not exist (any more). */
val state: StateFlow<DetailState?> = _state.asStateFlow()
private val _effects = Channel<DetailEffect>(capacity = Channel.BUFFERED)
val effects: Flow<DetailEffect> = _effects.receiveAsFlow()
private var trackerSearchJob: Job? = null
init {
val title = repository.observe({ listOf(it.mangas, it.sources, it.categories, it.tracks) }, workDispatcher) { titleData(mangaId) }
// The empty placeholder index would briefly show a title without chapters.
combine(title, libraryIndex.index.filter { it !== LibraryIndex.Empty }, settings.db,
_state.map { (it?.showAllReleases ?: false) to it?.selectedSeason }.distinctUntilChanged()) { data, index, db, options ->
data?.let { detailContent(it, index, db, options.first, options.second) }
}
.flowOn(workDispatcher)
.onEach { content ->
_state.update { current ->
content ?: return@update null
current?.copy(
content = content,
selection = current.selection.retainVisible(content.chapters),
noteDraft = current.noteDraft.takeIf { content.manga.favorite },
selectedSeason = current.selectedSeason?.takeIf { it in content.seasons },
)
?: DetailState(content, trackerNames)
}
}
.launchIn(viewModelScope)
together?.state
?.onEach { room -> _state.update { it?.copy(togetherRoom = room) } }
?.launchIn(viewModelScope)
// Remote trackers report progress made elsewhere; server (enhanced) trackers sync it both ways.
repository.refreshTracks(mangaId)
_state.value?.content?.manga?.let { autoRefreshMetadata(it) }
viewModelScope.launch {
// Titles opened from a source listing have no chapters until their detail is fetched.
val first = _state.filterNotNull().first { it.content.loaded }.content
if (first.continueChapter == null && first.seasonTitles.isEmpty() && first.source != null) refresh()
}
}
fun onEvent(event: DetailEvent) {
val content = _state.value?.content ?: return
val manga = content.manga
when (event) {
DetailEvent.Refresh -> refresh()
DetailEvent.RefreshMetadata -> refreshMetadata(manga)
DetailEvent.Share -> showMessage(
if (openSystemBrowser(shareUrl(manga, content.source))) "Opened share URL." else "Could not open share URL.",
)
DetailEvent.ExportMetadata -> exportMetadata(manga)
DetailEvent.EditNote -> {
val saved = repository.manga(mangaId)?.takeIf { it.favorite } ?: return
_state.update { it?.copy(noteDraft = saved.privateNote) }
}
is DetailEvent.ChangeNote -> _state.update { current ->
current?.takeIf { it.noteDraft != null }?.copy(noteDraft = event.text) ?: current
}
DetailEvent.CancelNote -> _state.update { it?.copy(noteDraft = null) }
DetailEvent.SaveNote -> {
val draft = _state.value?.noteDraft ?: return
repository.setMangaPrivateNote(mangaId, draft)
_state.update { it?.copy(noteDraft = null) }
}
is DetailEvent.SetFavorite -> repository.setMangaFavorite(mangaId, event.favorite)
is DetailEvent.SetCategories -> {
// Explicit selections, including Uncategorized, always override an automatic default.
repository.setMangaCategories(mangaId, event.categoryIds, favorite = event.favorite)
}
is DetailEvent.SetDisplayTitle -> repository.setMangaDisplayTitle(mangaId, event.title)
is DetailEvent.SetCustomCover -> repository.setMangaCustomCover(mangaId, event.bytes)
is DetailEvent.SetSmartUpdateDays -> repository.setMangaSmartUpdateDays(mangaId, event.days)
is DetailEvent.SetRead -> if (event.chapterIds.isNotEmpty()) repository.setChaptersRead(releaseActionIds(event.chapterIds), event.read)
is DetailEvent.SetBookmarked -> if (event.chapterIds.isNotEmpty()) repository.setChaptersBookmarked(releaseActionIds(event.chapterIds), event.bookmarked)
DetailEvent.ToggleSelectedBookmarks -> toggleSelected(content, Chapter::isBookmarked) { ids, on -> repository.setChaptersBookmarked(ids, on) }
DetailEvent.ToggleSelectedRead -> toggleSelected(content, Chapter::isRead) { ids, on -> repository.setChaptersRead(ids, on) }
is DetailEvent.SetFiller -> if (event.chapterIds.isNotEmpty()) repository.setChaptersFillerOverride(releaseActionIds(event.chapterIds), event.filler)
is DetailEvent.Download -> {
downloads.enqueue(manga, event.chapter, event.destinationRoot)
showMessage("Enqueued ${event.chapter.name}.")
}
is DetailEvent.DownloadAll -> downloadAll(content, event)
is DetailEvent.DeleteSelected -> deleteSelected(event.removeEntry)
is DetailEvent.ToggleSort -> settings.updateDb { it.withChapterSortToggled(manga, event.index) }
is DetailEvent.CycleFilter -> settings.updateDb { it.withChapterFilterCycled(manga, event.kind) }
is DetailEvent.SetChapterListDefault -> {
val library = if (event.applyToLibrary) repository.library(manga.itemType) else emptyList()
settings.updateDb { it.withChapterListDefaultFrom(manga, library) }
}
is DetailEvent.ToggleScanlator -> settings.updateDb { it.withScanlatorToggled(mangaId, event.scanlator) }
is DetailEvent.SetSkipDuplicates -> settings.updateDb { db ->
db.withChapterReleasePreference(db.chapterReleasePreference(mangaId).copy(skipDuplicateReleases = event.enabled))
}
is DetailEvent.MoveScanlator -> settings.updateDb { db ->
val current = db.chapterReleasePreference(mangaId)
db.withChapterReleasePreference(current.copy(scanlatorPriority = movedScanlator(current.scanlatorPriority,
content.scanlators, event.scanlator, event.direction)))
}
DetailEvent.ResetReleaseOverride -> settings.updateDb { it.withoutChapterReleaseOverride(mangaId) }
is DetailEvent.ShowAllReleases -> _state.update { it?.copy(showAllReleases = event.enabled) }
is DetailEvent.SelectSeason -> if (event.season == null || event.season in content.seasons) {
_state.update { it?.copy(selectedSeason = event.season) }
}
is DetailEvent.Select -> updateSelection { it.select(content.chapters, event.option) }
is DetailEvent.ToggleSelection -> updateSelection { it.toggle(event.chapterId) }
is DetailEvent.SelectRangeTo -> updateSelection { it.rangeTo(content.chapters, event.chapterId) }
is DetailEvent.SelectRange -> updateSelection { it.selectRange(content.chapters, event.first, event.last) }
DetailEvent.ClearSelection -> updateSelection { ChapterSelectionState() }
is DetailEvent.SearchTracker -> searchTracker(manga, event)
is DetailEvent.BindTrack -> {
val tracker = trackers.getOrNull(event.trackerIndex) ?: return
repository.bindTrack(mangaId, event.search.copy(syncId = tracker.syncId), manga.itemType)
}
DetailEvent.CloseTrackerSearch -> {
trackerSearchJob?.cancel()
_state.update { it?.copy(trackerSearch = TrackerSearchState()) }
}
DetailEvent.Together -> together(content)
}
}
private fun refresh() {
val content = _state.value?.content ?: return
val source = content.source ?: return
val manga = content.manga
if (manga.link.isBlank()) return
viewModelScope.launch {
_state.update { it?.copy(loading = true, error = null) }
catchingNonCancellation {
val detail = runtimeFactory.withSourceRuntime(
database = database,
sourceId = source.id,
onFallback = { ExtensionLogger.error(source.name, "detail", it) },
) { it.detail(manga.link) }
withContext(workDispatcher) { repository.upsertRemoteDetail(source, detail, favorite = manga.favorite) }
}.onFailure { error -> _state.update { it?.copy(error = error.displayMessage()) } }
_state.update { it?.copy(loading = false) }
}
}
private fun refreshMetadata(manga: Manga) {
viewModelScope.launch {
_state.update { it?.copy(loading = true, error = null) }
catchingNonCancellation { applyMetadata(manga) }
.onSuccess { result ->
showMessage(
if (result.applied && result.media != null) {
"Metadata updated from ${result.media.source.ifBlank { "server" }}."
} else {
result.message ?: "No metadata match found."
},
)
}
.onFailure { error -> _state.update { it?.copy(error = error.displayMessage()) } }
_state.update { it?.copy(loading = false) }
}
}
// Opening a title with incomplete metadata fetches it once, silently, when a metadata server is on.
private fun autoRefreshMetadata(manga: Manga) {
if (!settings.db.value.metadataServerEnabled) return
if (manga.metadataUpdatedAt > 0L && manga.alternativeTitles.size > 1 && manga.genres.isNotEmpty()) return
viewModelScope.launch { catchingNonCancellation { applyMetadata(manga) } }
}
private suspend fun applyMetadata(manga: Manga): MetadataApplyResult {
val baseUrl = settings.db.value.metadataServerUrl.trim()
if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
return MetadataApplyResult(manga.id, matched = false, message = "Metadata server URL must start with http:// or https://.")
}
val match = metadata.bestMatch(baseUrl, manga.name, manga.itemType.toDb())
?: return MetadataApplyResult(manga.id, matched = false, message = "No metadata match found.")
withContext(workDispatcher) { repository.applyMetadata(manga.id, match) }
?: return MetadataApplyResult(manga.id, matched = true, media = match, message = "Title no longer exists.")
return MetadataApplyResult(manga.id, matched = true, media = match, applied = true)
}
private fun releaseActionIds(ids: Set<Long>): Set<Long> {
val current = _state.value ?: return ids
if (current.showAllReleases || !settings.db.value.chapterReleasePreference(mangaId).skipDuplicateReleases) return ids
return equivalentReleaseIds(current.content.manga.name, repository.chapters(mangaId), ids)
}
private fun downloadAll(content: DetailContent, event: DetailEvent.DownloadAll) {
val itemType = content.manga.itemType
val label = chapterLabel(itemType).lowercase()
val visibleIds = content.chapters.mapTo(HashSet()) { it.id }
val queueable = event.chapters.distinctBy { it.id }.filter { it.id in visibleIds && it.downloadSize == null && it.archivePath.isBlank() }
if (queueable.isEmpty()) return showMessage("No $label to download.")
queueable.forEach { downloads.enqueue(content.manga, it, event.destinationRoot) }
showMessage("Enqueued ${queueable.size} $label for ${downloadOptionLabel(event.option, itemType).lowercase()}.")
}
// Synchronous on purpose: the local-title path is followed by leaving the screen, which cancels
// the scope, and must not stop between deleting the files and removing the entry.
private fun deleteSelected(removeEntry: Boolean) {
val current = _state.value ?: return
val content = current.content
val ids = current.selection.ids
val label = chapterLabel(content.manga.itemType).lowercase()
if (content.manga.isLocalArchive) {
content.chapters
.filter { it.id in ids && it.archivePath.isNotBlank() }
.forEach { files.deleteRecursively(it.archivePath) }
if (removeEntry) {
repository.removeLibraryEntries(setOf(mangaId))
} else {
repository.deleteChapters(ids)
showMessage("Deleted ${ids.size} $label.")
}
} else {
viewModelScope.launch {
val removed = downloads.deleteForChaptersAwait(ids)
showMessage(
if (removed > 0) {
"Removed downloads for $removed $label" + if (removed == 1) "." else "s."
} else {
"No downloads removed. Check storage access if files remain."
},
)
}
}
updateSelection { ChapterSelectionState() }
}
private fun exportMetadata(manga: Manga) {
val path = "${files.downloadRoot.trimEnd('/')}/metadata/${manga.name.safeFileSegment()}/metadata.json"
viewModelScope.launch {
catchingNonCancellation {
withContext(workDispatcher) { files.writeBytes(path, manga.toMetadataJson().encodeToByteArray()) }
}
.onSuccess { showMessage("Exported metadata to $path") }
.onFailure { showMessage("Export metadata failed: ${it.displayMessage()}") }
}
}
private fun searchTracker(manga: Manga, event: DetailEvent.SearchTracker) {
val tracker = trackers.getOrNull(event.trackerIndex) ?: return
if (_state.value?.trackerSearch?.loading == true || event.query.isBlank()) return
_state.update { it?.copy(trackerSearch = it.trackerSearch.copy(loading = true, error = null)) }
trackerSearchJob = viewModelScope.launch {
val result = catchingNonCancellation {
val dbManga = database.manga(mangaId)
if (tracker is EnhancedTracker && trackerSearchId(event.query) == null) {
// Server trackers are not searched: they resolve this title's own source entry.
listOfNotNull(dbManga?.let { tracker.match(it) })
} else {
tracker.search(event.query, isManga = manga.itemType != ItemType.Anime)
}
}
_state.update { current ->
current?.copy(
trackerSearch = current.trackerSearch.copy(
loading = false,
results = result.getOrDefault(current.trackerSearch.results),
error = result.exceptionOrNull()?.let { it.message ?: "Search failed" },
),
)
}
}
}
private fun together(content: DetailContent) {
val controller = together ?: return
val room = _state.value?.togetherRoom
val client = controller.client.value
if (room != null && client != null) {
showMessage(TogetherActions.addToRoom(content.manga, content.continueChapter, room, client))
} else {
viewModelScope.launch {
val http = togetherHttp ?: return@launch
showMessage(TogetherActions.startRoom(controller, http, content.manga, content.continueChapter) {
_effects.trySend(DetailEffect.OpenTogetherSettings)
})
}
}
}
/** Turns the flag off for the selected chapters that have it and on for the rest. */
private fun toggleSelected(content: DetailContent, flag: (Chapter) -> Boolean, apply: (Set<Long>, Boolean) -> Unit) {
val ids = _state.value?.selection?.ids ?: return
val (on, off) = content.chapters.filter { it.id in ids }.partition(flag)
if (on.isNotEmpty()) apply(releaseActionIds(on.mapTo(HashSet()) { it.id }), false)
if (off.isNotEmpty()) apply(releaseActionIds(off.mapTo(HashSet()) { it.id }), true)
updateSelection { ChapterSelectionState() }
}
private fun updateSelection(transform: (ChapterSelectionState) -> ChapterSelectionState) =
_state.update { it?.copy(selection = transform(it.selection)) }
private fun showMessage(text: String) {
_effects.trySend(DetailEffect.ShowMessage(text))
}
}
private class TitleData(
val manga: Manga,
val source: Source?,
val genreSources: List<Source>,
val categories: List<Category>,
val tracks: List<Track>,
val seasonTitles: List<Manga>,
)
private fun YokanRepository.titleData(mangaId: Long): TitleData? {
val manga = manga(mangaId) ?: return null
val titleSource = if (manga.isLocalArchive) null else manga.sourceId?.let { this.source(it) }
return TitleData(
manga = manga,
source = titleSource,
genreSources = sources(manga.itemType)
.filter { it.isAdded && it.isActive }
.sortedWith(compareBy<Source> { it.id != titleSource?.id }.thenBy { it.name.lowercase() }.thenBy { it.lang }),
categories = categories(manga.itemType),
tracks = tracks().filter { it.mangaId == mangaId },
// Only Seasons-type titles own season records; skip the full title scan for everything else.
seasonTitles = if (!manga.fetchesSeasons) emptyList() else allTitles(manga.itemType)
.filter { it.parentId == mangaId }
.sortedWith(compareBy<Manga>({ it.seasonNumber ?: Double.MAX_VALUE }, { it.name.lowercase() })),
)
}
private fun detailContent(title: TitleData, index: LibraryIndex, db: DbSettings, showAllReleases: Boolean, selectedSeason: Int?): DetailContent {
val manga = title.manga
val all = sortedChapters(manga, index.chapters(manga.id), db)
val seasons = if (manga.itemType == eu.friedcutlet.yokan.domain.ItemType.Anime) all.mapNotNull { it.detailSeason() }.distinct().sorted() else emptyList()
val effectiveSeason = selectedSeason?.takeIf { it in seasons }
val seasonChapters = if (effectiveSeason == null) all else all.filter { it.detailSeason() == effectiveSeason }
val visible = filterChapters(manga, seasonChapters, db, index.downloadedChapterIds, showAllReleases)
val winners = sortedChapters(manga, selectChapterReleases(manga.name, seasonChapters, db.chapterReleasePreference(manga.id).toPolicy(),
db.scanlatorFilter(manga.id), index.downloadedChapterIds, offlineOnly = db.downloadedOnlyMode), db)
return DetailContent(
manga = manga,
settings = db,
source = title.source,
chapters = visible,
continueChapter = winners.firstOrNull { !it.isRead } ?: winners.firstOrNull(),
scanlators = all.map { it.scanlator }.distinctBy(::normalizeScanlator).sortedBy(::normalizeScanlator),
automaticUpdateDays = meanChapterUpdateDays(all.map { it.dateUpload }),
missingChapterCount = ChapterRecognition.missingChapterCount(manga.name, visible),
unnumberedChapterCount = ChapterRecognition.unrecognizedChapterNumberCount(manga.name, visible),
tracks = title.tracks,
categories = title.categories,
genreSources = title.genreSources,
loaded = true,
seasons = seasons,
selectedSeason = effectiveSeason,
seasonTitles = title.seasonTitles.map { season ->
val episodes = sortedChapters(season, index.chapters(season.id), db)
DetailSeasonTitle(season, episodes.size, episodes.count { it.isRead }, episodes.firstOrNull { !it.isRead })
},
)
}
private fun Chapter.detailSeason(): Int? = season?.takeIf { it >= 0 }
?: ChapterRecognition.parseSeasonNumber(numberingName?.takeIf(String::isNotBlank) ?: name)
private fun Throwable.displayMessage(): String = message.orEmpty().ifBlank { this::class.simpleName.orEmpty() }
private fun shareUrl(manga: Manga, source: Source?): String {
if (manga.link.startsWith("http", ignoreCase = true)) return manga.link
val base = source?.baseUrl?.takeIf { it.isNotBlank() } ?: return manga.link
return "${base.trimEnd('/')}/${manga.link.trimStart('/')}"
}
private fun Manga.toMetadataJson(): String =
buildString {
appendLine("{")
appendLine(" \"name\": \"${name.jsonEscaped()}\",")
appendLine(" \"description\": \"${description.jsonEscaped()}\",")
appendLine(" \"artist\": ${artist.jsonStringOrNull()},")
appendLine(" \"author\": ${author.jsonStringOrNull()},")
appendLine(" \"genre\": [${genres.joinToString(", ") { "\"${it.jsonEscaped()}\"" }}],")
appendLine(" \"cast\": ${eu.friedcutlet.yokan.database.DatabaseJson.encodeToString(kotlinx.serialization.builtins.ListSerializer(eu.friedcutlet.yokan.domain.TitleCredit.serializer()), cast)},")
appendLine(" \"status\": \"${status.name.jsonEscaped()}\"")
appendLine("}")
}
private fun String?.jsonStringOrNull(): String =
this?.let { "\"${it.jsonEscaped()}\"" } ?: "null"
private fun String.jsonEscaped(): String = buildString {
this@jsonEscaped.forEach { char ->
when (char) {
'\\' -> append("\\\\")
'"' -> append("\\\"")
'\n' -> append("\\n")
'\r' -> append("\\r")
'\t' -> append("\\t")
else -> append(char)
}
}
}
private fun String.safeFileSegment(): String =
replace(Regex("""[\\/:*?"<>|]+"""), "_")
.trim()
.take(80)
.ifBlank { "metadata" }
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/EpisodeSeasonSelector.kt
- Source · implementation · 59 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
22: internal fun EpisodeSeasonSelector(
Exact file bytes / download · SHA-256 2938c70a5f093d49e2a442a1aae998639bbe3170d707b5308bcfdba480cf9821.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.episodes_all_seasons
import yokan.composeapp.generated.resources.episodes_season_number
@Composable
internal fun EpisodeSeasonSelector(
seasons: List<Int>,
selectedSeason: Int?,
onSelect: (Int?) -> Unit,
modifier: Modifier = Modifier,
) {
if (seasons.isEmpty()) return
val row = rememberLazyListState()
LaunchedEffect(seasons, selectedSeason) {
val index = if (selectedSeason == null) 0 else seasons.indexOf(selectedSeason).let { if (it < 0) 0 else it + 1 }
val layout = row.layoutInfo
val item = layout.visibleItemsInfo.firstOrNull { it.index == index }
if (item == null || item.offset < layout.viewportStartOffset || item.offset + item.size > layout.viewportEndOffset) {
row.scrollToItem(index)
}
}
LazyRow(
modifier = modifier.fillMaxWidth(),
state = row,
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
item(key = "all", contentType = "season") {
FilterChip(
selected = selectedSeason == null, onClick = { onSelect(null) },
label = { Text(stringResource(Res.string.episodes_all_seasons)) },
modifier = Modifier.heightIn(min = 48.dp),
)
}
items(seasons, key = { "season-$it" }, contentType = { "season" }) { season ->
FilterChip(
selected = selectedSeason == season, onClick = { onSelect(season) },
label = { Text(stringResource(Res.string.episodes_season_number, season)) },
modifier = Modifier.heightIn(min = 48.dp),
)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ScanlatorPriorityControls.kt
- Source · implementation · 64 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
31: internal fun ScanlatorPriorityControls(
Exact file bytes / download · SHA-256 2ec04ef992fe77a20a969afb4f3bf296971a80585a8123018dd863dfcac3010c.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import eu.friedcutlet.yokan.database.orderedScanlators
import eu.friedcutlet.yokan.domain.normalizeScanlator
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
@Composable
internal fun ScanlatorPriorityControls(
priority: List<String>,
available: List<String>,
skipDuplicates: Boolean,
onSkipDuplicates: (Boolean) -> Unit,
onMove: (String, Int) -> Unit,
modifier: Modifier = Modifier,
) {
val groups = androidx.compose.runtime.remember(priority, available) { orderedScanlators(priority, available) }
val skipLabel = stringResource(Res.string.releases_skip_duplicates)
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(skipLabel, modifier = Modifier.weight(1f))
Switch(checked = skipDuplicates, onCheckedChange = onSkipDuplicates, modifier = Modifier.semantics { contentDescription = skipLabel })
}
Text(stringResource(Res.string.releases_priority), style = MaterialTheme.typography.titleSmall)
Text(stringResource(Res.string.releases_priority_description), style = MaterialTheme.typography.bodySmall)
LazyColumn(modifier = Modifier.fillMaxWidth().heightIn(max = 300.dp)) {
itemsIndexed(groups, key = { _, group -> group }, contentType = { _, _ -> "scanlator-priority" }) { index, group ->
val label = available.firstOrNull { normalizeScanlator(it) == group }?.takeIf { it.isNotBlank() }
?: group.ifEmpty { stringResource(Res.string.releases_unknown_group) }
Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {
Text(label, modifier = Modifier.weight(1f))
IconButton(enabled = index > 0, onClick = { onMove(group, -1) }) {
Icon(Icons.Filled.ArrowUpward, contentDescription = stringResource(Res.string.releases_move_up, label))
}
IconButton(enabled = index < groups.lastIndex, onClick = { onMove(group, 1) }) {
Icon(Icons.Filled.ArrowDownward, contentDescription = stringResource(Res.string.releases_move_down, label))
}
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/SmartUpdateDialog.kt
- Source · implementation · 61 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
27: internal fun SmartUpdateDialog(
Exact file bytes / download · SHA-256 a260a72860faa63f72ba73a5dd1af9beb2264ea5278355fdedca4b81167959b8.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import yokan.composeapp.generated.resources.detail_smart_auto
import yokan.composeapp.generated.resources.detail_smart_always
import yokan.composeapp.generated.resources.detail_smart_days
import yokan.composeapp.generated.resources.detail_smart_update
import yokan.composeapp.generated.resources.detail_smart_explanation
import yokan.composeapp.generated.resources.detail_smart_estimate
import yokan.composeapp.generated.resources.detail_smart_insufficient
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.FilterChip
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.ui_close
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
@Composable
internal fun SmartUpdateDialog(
manualDays: Int?,
automaticDays: Int?,
onChange: (Int?) -> Unit,
onDismiss: () -> Unit,
) {
androidx.compose.material3.AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.ui_close)) } },
title = { Text(stringResource(Res.string.detail_smart_update)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(Res.string.detail_smart_explanation), style = MaterialTheme.typography.bodySmall)
Text(
automaticDays?.let { stringResource(Res.string.detail_smart_estimate, it) }
?: stringResource(Res.string.detail_smart_insufficient),
style = MaterialTheme.typography.bodyMedium,
)
FilterChip(
selected = manualDays == null, onClick = { onChange(null) },
label = { Text(stringResource(Res.string.detail_smart_auto)) },
)
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
listOf(0, 1, 3, 7, 14, 30).forEach { days ->
FilterChip(
selected = manualDays == days, onClick = { onChange(days) },
label = { Text(if (days == 0) stringResource(Res.string.detail_smart_always) else stringResource(Res.string.detail_smart_days, days)) },
)
}
}
}
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/TitleCastCredits.kt
- Source · implementation · 56 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
29: internal fun TitleCastCredits(cast: List<TitleCredit>, modifier: Modifier = Modifier) {
Exact file bytes / download · SHA-256 1342669892fe2532efa6d4bd58c5a78790b0eb8ea576cee1ecf2176273a41ec2.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.TitleCredit
import eu.friedcutlet.yokan.ui.components.CoverImage
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.detail_cast
import yokan.composeapp.generated.resources.detail_cast_character
@Composable
internal fun TitleCastCredits(cast: List<TitleCredit>, modifier: Modifier = Modifier) {
if (cast.isEmpty()) return
Column(modifier.fillMaxWidth().padding(vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(Res.string.detail_cast), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 16.dp))
LazyRow(
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
// Position also disambiguates repeated credits supplied by older backups/sources.
itemsIndexed(cast, key = { index, credit -> "$index:${credit.name}:${credit.role}:${credit.character}" }, contentType = { _, _ -> "credit" }) { _, credit ->
val initials = remember(credit.name) {
credit.name.split(' ').filter(String::isNotBlank).take(2).joinToString("") { it.take(1) }.uppercase()
}
Column(Modifier.width(144.dp).semantics(mergeDescendants = true) {}, verticalArrangement = Arrangement.spacedBy(4.dp)) {
CoverImage(credit.imageUrl, contentDescription = null, fallbackInitials = initials,
shape = MaterialTheme.shapes.small, modifier = Modifier.size(64.dp, 80.dp))
Text(credit.name, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium,
minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(credit.character?.let { stringResource(Res.string.detail_cast_character, it) }.orEmpty(),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant,
minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(credit.role.orEmpty(), style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/TrackerSearchDialog.kt
- Source · implementation · 174 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
47: internal fun TrackerSearchDialog(
61: fun submitTrackerSearch() {
Exact file bytes / download · SHA-256 04869222b352bf8b77e974028a12f85af551e658615fad1771c243a791d55530.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.domain.Manga
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_search
import yokan.composeapp.generated.resources.ui_close
import yokan.composeapp.generated.resources.ui_search_tracker
import yokan.composeapp.generated.resources.ui_title_field
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.autoFocusOnMount
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import eu.friedcutlet.yokan.ui.components.compactSearchField
import eu.friedcutlet.yokan.ui.components.searchOnEnter
@Composable
internal fun TrackerSearchDialog(
manga: Manga,
trackerNames: List<String>,
search: TrackerSearchState,
onSearch: (trackerIndex: Int, query: String) -> Unit,
onBind: (trackerIndex: Int, result: DbTrackSearch) -> Unit,
onDismiss: () -> Unit,
) {
var serviceIndex by remember { mutableStateOf(0) }
var query by remember { mutableStateOf(manga.name) }
val loading = search.loading
val error = search.error
val results = search.results
fun submitTrackerSearch() {
if (loading || query.isBlank() || trackerNames.isEmpty()) return
onSearch(serviceIndex, query)
}
androidx.compose.material3.AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
confirmButton = {
TextButton(onClick = onDismiss) { Text(stringResource(Res.string.ui_close)) }
},
title = {
Text(
stringResource(Res.string.ui_search_tracker),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
// Tracker search can return a long result list; without a scroll
// wrapper the AlertDialog body clips at the bottom and the
// "Add" buttons for lower results aren't reachable. Cap height
// so short result lists still hug their content.
val dialogScroll = androidx.compose.foundation.rememberScrollState()
eu.friedcutlet.yokan.ui.components.ScrollbarBox(
state = dialogScroll,
modifier = Modifier.fillMaxWidth().heightIn(max = 520.dp),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(dialogScroll),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (trackerNames.isEmpty()) {
Text(
"No trackers configured.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
trackerNames.forEachIndexed { index, trackerName ->
FilterChip(
selected = serviceIndex == index,
onClick = { serviceIndex = index },
label = { Text(trackerName) },
)
}
}
OutlinedTextField(
value = query,
onValueChange = { query = it },
placeholder = { Text(stringResource(Res.string.ui_title_field)) },
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { submitTrackerSearch() }),
modifier = Modifier
.fillMaxWidth()
.autoFocusOnMount()
.compactSearchField()
.searchOnEnter { submitTrackerSearch() },
)
FilledTonalButton(
onClick = { submitTrackerSearch() },
enabled = !loading && query.isNotBlank(),
) { Text(if (loading) "Searching…" else stringResource(Res.string.action_search)) }
error?.let {
Text(
it,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
}
if (results.isEmpty() && !loading && error == null) {
Text(
"Type a title and tap Search.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
results.forEach { result ->
Surface(
modifier = Modifier.fillMaxWidth(),
tonalElevation = 1.dp,
shape = RoundedCornerShape(8.dp),
) {
Column(modifier = Modifier.padding(10.dp)) {
Text(result.title.orEmpty(), fontWeight = FontWeight.SemiBold)
Text(
"Chapters: ${result.totalChapter ?: "?"} • ${result.status}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedButton(
onClick = {
onBind(serviceIndex, result)
onDismiss()
},
modifier = Modifier.padding(top = 6.dp),
) { Text("Bind") }
}
}
}
}
}
} // end ScrollbarBox
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CodeEditorScreen.kt
- Source · implementation · 244 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
59: internal fun CodeEditorRoute(route: Route.CodeEditor, nav: Navigator) {
72: internal fun CodeEditorScreen(source: DbSource, onSave: (code: String) -> Unit, onBack: () -> Unit) {
Exact file bytes / download · SHA-256 5b1de27710dd45f8bb415009463fab7e511cc25c62056e93e096c1129f6ab919.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.BugReport
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSource
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.theme.YokanScaffold as Scaffold
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.action_reset
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.ui_source_code
import eu.friedcutlet.yokan.services.extensions.languageName
@Composable
internal fun CodeEditorRoute(route: Route.CodeEditor, nav: Navigator) {
val vm = viewModel { CodeEditorViewModel(route.sourceId, YokanRuntime.repository) }
val source = vm.source.collectAsStateWithLifecycle().value
?: return MissingRoute("Extension Code Editor", nav::back)
CodeEditorScreen(
source = source,
onSave = vm::save,
onBack = nav::back,
)
}
@Composable
@OptIn(ExperimentalMaterial3Api::class)
internal fun CodeEditorScreen(source: DbSource, onSave: (code: String) -> Unit, onBack: () -> Unit) {
var code by remember(source.id) { mutableStateOf(source.sourceCode) }
var menuOpen by remember { mutableStateOf(false) }
var status by remember { mutableStateOf<String?>(null) }
// Phone variant: a single console-log panel sits below the editor and can
// be cleared. The runner / filter buttons from the tablet wireframe are
// intentionally omitted on the phone layout.
var consoleLines by remember { mutableStateOf<List<String>>(emptyList()) }
Scaffold(
topBar = {
TopAppBar(
title = {
Column {
Text(
source.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.titleMedium,
)
Text(
languageName(source.lang),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
}
},
actions = {
IconButton(
onClick = {
onSave(code)
status = "Saved"
consoleLines = consoleLines + "Saved ${source.name} (${code.length} chars)"
},
) {
Icon(Icons.Filled.Save, contentDescription = stringResource(Res.string.action_save))
}
IconButton(
onClick = {
code = source.sourceCode
status = "Reset to last saved version"
consoleLines = consoleLines + "Reset to last saved version"
},
) {
Icon(Icons.Filled.RestartAlt, contentDescription = stringResource(Res.string.action_reset))
}
Box {
IconButton(onClick = { menuOpen = true }) {
Icon(Icons.Filled.MoreVert, contentDescription = "More")
}
androidx.compose.material3.DropdownMenu(
expanded = menuOpen,
onDismissRequest = { menuOpen = false },
) {
androidx.compose.material3.DropdownMenuItem(
text = { Text("Filter") },
leadingIcon = { Icon(Icons.Filled.FilterList, contentDescription = null) },
onClick = {
menuOpen = false
consoleLines = consoleLines +
"Filter sheet is only available for search services."
},
)
androidx.compose.material3.DropdownMenuItem(
text = { Text("Execute") },
leadingIcon = { Icon(Icons.Filled.PlayArrow, contentDescription = null) },
onClick = {
menuOpen = false
consoleLines = consoleLines +
"Execute requires the tablet layout's service runner."
},
)
androidx.compose.material3.DropdownMenuItem(
text = { Text(stringResource(Res.string.action_reset)) },
leadingIcon = { Icon(Icons.Filled.RestartAlt, contentDescription = null) },
onClick = {
menuOpen = false
code = source.sourceCode
consoleLines = consoleLines + "Reset to last saved version"
},
)
}
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
// Full-height editor — flex so the console panel always sits at
// the bottom of the viewport.
OutlinedTextField(
value = code,
onValueChange = { code = it },
modifier = Modifier
.fillMaxWidth()
.weight(1f, fill = true),
label = { Text(stringResource(Res.string.ui_source_code)) },
singleLine = false,
textStyle = MaterialTheme.typography.bodySmall.copy(
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
),
)
status?.let {
Text(it, color = MaterialTheme.colorScheme.tertiary, style = MaterialTheme.typography.bodySmall)
}
// Optional console panel: shows the most recent log lines and a
// clear button. Empty by default.
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth().padding(10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Filled.BugReport, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(
"Console Logs",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.weight(1f),
)
IconButton(
onClick = { consoleLines = emptyList() },
enabled = consoleLines.isNotEmpty(),
) {
Icon(Icons.Filled.Clear, contentDescription = "Clear logs")
}
}
eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider()
if (consoleLines.isEmpty()) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(80.dp),
contentAlignment = Alignment.Center,
) {
Text(
"No logs yet",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
} else {
LazyColumn(
modifier = Modifier.fillMaxWidth().height(120.dp),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
itemsIndexed(consoleLines, key = { index, _ -> index }) { _, line ->
Text(
line,
style = MaterialTheme.typography.bodySmall.copy(
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
),
)
}
}
}
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CodeEditorViewModel.kt
- Source · implementation · 20 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
12: internal class CodeEditorViewModel(
19: fun save(code: String) = repository.updateSourceCode(sourceId, code)
Exact file bytes / download · SHA-256 dc673ea5bb5802784b54ea0fb75db5c95da3117945c776677a5ab9440c221751.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbSource
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
/** The stored source row behind the code editor; edits stay in the screen until saved. */
internal class CodeEditorViewModel(
private val sourceId: Long,
private val repository: YokanRepository,
) : ViewModel() {
val source: StateFlow<DbSource?> = repository.observeDbSource(sourceId)
.stateIn(viewModelScope, SharingStarted.Eagerly, repository.currentDbSource(sourceId))
fun save(code: String) = repository.updateSourceCode(sourceId, code)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CreateExtensionScreen.kt
- Source · implementation · 197 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
44: internal fun CreateExtensionRoute(route: Route.CreateExtension, nav: Navigator) {
51: internal fun CreateExtensionScreen(
178: private fun sourceCodeLanguageLabel(lang: DbSourceCodeLanguage): String = when (lang) {
185: private fun javaScriptExtensionTemplate(name: String, baseUrl: String): String = """
186: class DefaultExtension extends MProvider {
Exact file bytes / download · SHA-256 31ba65007a57377e91bd3ee26bc29154b95db3d5036a0bbe7033898591eae822.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Extension
import androidx.compose.material3.Button
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.language
@Composable
internal fun CreateExtensionRoute(route: Route.CreateExtension, nav: Navigator) {
val vm = viewModel { CreateExtensionViewModel(YokanRuntime.services.database) }
val state by vm.state.collectAsStateWithLifecycle()
CreateExtensionScreen(state, route.itemType, onCreate = vm::create, onBack = nav::back)
}
@Composable
internal fun CreateExtensionScreen(
state: CreateExtensionUiState,
itemType: ItemType,
onCreate: (DbSource) -> Unit,
onBack: () -> Unit,
) {
var name by remember { mutableStateOf("") }
var lang by remember { mutableStateOf("en") }
var baseUrl by remember { mutableStateOf("https://example.org") }
var apiUrl by remember { mutableStateOf("") }
var iconUrl by remember { mutableStateOf("") }
var notes by remember { mutableStateOf("") }
var codeLang by remember { mutableStateOf(DbSourceCodeLanguage.JavaScript) }
var type by remember { mutableStateOf(itemType) }
RouteScaffold("Create Extension", onBack = onBack) {
// "Choose extension language" — code language dropdown (JS / Dart / LNReader compiled).
item {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("Choose extension language", fontWeight = FontWeight.SemiBold)
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
DbSourceCodeLanguage.entries.forEach { entry ->
FilterChip(
selected = codeLang == entry,
onClick = { codeLang = entry },
label = { Text(sourceCodeLanguageLabel(entry)) },
)
}
}
}
}
// Free-text input fields, one per row.
item {
OutlinedTextField(
value = name, onValueChange = { name = it },
modifier = Modifier.fillMaxWidth(), singleLine = true,
label = { Text("Name") }, placeholder = { Text("ex: myAnime") },
)
}
item {
OutlinedTextField(
value = lang, onValueChange = { lang = it.take(8) },
modifier = Modifier.fillMaxWidth(), singleLine = true,
label = { Text(stringResource(Res.string.language)) }, placeholder = { Text("ex: en") },
)
}
item {
OutlinedTextField(
value = baseUrl, onValueChange = { baseUrl = it },
modifier = Modifier.fillMaxWidth(), singleLine = true,
label = { Text("BaseUrl") }, placeholder = { Text("ex: https://example.com") },
)
}
item {
OutlinedTextField(
value = apiUrl, onValueChange = { apiUrl = it },
modifier = Modifier.fillMaxWidth(), singleLine = true,
label = { Text("ApiUrl (optional)") }, placeholder = { Text("ex: https://api.example.com") },
)
}
item {
OutlinedTextField(
value = iconUrl, onValueChange = { iconUrl = it },
modifier = Modifier.fillMaxWidth(), singleLine = true,
label = { Text("iconUrl") }, placeholder = { Text("Source icon url") },
)
}
item {
OutlinedTextField(
value = notes, onValueChange = { notes = it },
modifier = Modifier.fillMaxWidth(),
label = { Text("notes") }, placeholder = { Text("ex: this extension requires login") },
)
}
// Target (manga / anime / novel) — choice chip set mirroring `ItemTypeSelector`.
item {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("Target", fontWeight = FontWeight.SemiBold)
ItemTypeSelector(type, onSelect = { type = it })
}
}
item {
Button(
onClick = {
val effectiveName = name.ifBlank { "Local ${type.label} extension" }
onCreate(
DbSource(
name = effectiveName,
baseUrl = baseUrl,
lang = lang.ifBlank { "en" },
apiUrl = apiUrl,
iconUrl = iconUrl,
itemType = type.toDb(),
isActive = true,
isAdded = true,
isLocal = true,
sourceCodeLanguage = codeLang,
sourceCode = javaScriptExtensionTemplate(effectiveName, baseUrl),
version = "0.0.1-local",
notes = notes.ifBlank { "Generated by the KMP create-extension wizard." },
),
)
},
enabled = baseUrl.startsWith("http") && name.isNotBlank(),
modifier = Modifier.fillMaxWidth(),
) {
Icon(Icons.Filled.Add, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(stringResource(Res.string.action_save))
}
}
state.error?.let { msg ->
item { Text(msg, color = MaterialTheme.colorScheme.error) }
}
state.created?.let { source ->
item {
ElevatedCard {
ListItem(
headlineContent = { Text(source.name, fontWeight = FontWeight.SemiBold) },
supportingContent = { Text("Created and installed for ${source.itemType.label}") },
leadingContent = { Icon(Icons.Filled.Extension, contentDescription = null) },
)
}
}
}
}
}
private fun sourceCodeLanguageLabel(lang: DbSourceCodeLanguage): String = when (lang) {
DbSourceCodeLanguage.JavaScript -> "JavaScript"
DbSourceCodeLanguage.Mihon -> "Mihon"
DbSourceCodeLanguage.LnReader -> "LNReader"
DbSourceCodeLanguage.Aidoku -> "Aidoku"
}
private fun javaScriptExtensionTemplate(name: String, baseUrl: String): String = """
class DefaultExtension extends MProvider {
get supportsLatest() { return true; }
getHeaders(url) { return {}; }
getPopular(page) { return { list: [], hasNextPage: false }; }
getLatestUpdates(page) { return { list: [], hasNextPage: false }; }
search(query, page, filters) { return { list: [], hasNextPage: false }; }
getDetail(url) { return { title: "$name", url: url, chapters: [] }; }
getPageList(url) { return []; }
}
// Base URL: $baseUrl
""".trimIndent()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CreateExtensionViewModel.kt
- Source · implementation · 28 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
13: internal data class CreateExtensionUiState(
19: internal class CreateExtensionViewModel(private val database: YokanDatabase) : ViewModel() {
23: fun create(source: DbSource) {
Exact file bytes / download · SHA-256 74591c8f8096ad8b1565edc80be1ae2e73d7029a316184579d801f1ac561b028.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.lifecycle.ViewModel
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Source
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
internal data class CreateExtensionUiState(
val created: Source? = null,
val error: String? = null,
)
/** Saves a locally authored extension source. */
internal class CreateExtensionViewModel(private val database: YokanDatabase) : ViewModel() {
private val _state = MutableStateFlow(CreateExtensionUiState())
val state: StateFlow<CreateExtensionUiState> = _state.asStateFlow()
fun create(source: DbSource) {
runCatching { database.upsertSource(source) }
.onSuccess { saved -> _state.value = CreateExtensionUiState(created = saved.toDomain()) }
.onFailure { err -> _state.update { it.copy(error = err.message ?: "Could not create extension") } }
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionDetailScreen.kt
- Source · implementation · 273 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
50: internal fun ExtensionDetailRoute(route: Route.ExtensionDetail, nav: Navigator) {
76: internal fun ExtensionDetailScreen(
268: private fun ExtensionStat(value: String, label: String) {
Exact file bytes / download · SHA-256 d945be0e6536535d2fa855f404c428973a2b98a0eddbdd8d56a60aad7032fb8b.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Code
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Extension
import androidx.compose.material.icons.filled.Public
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.navigation.MissingRoute
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_remove
import yokan.composeapp.generated.resources.edit_code
import yokan.composeapp.generated.resources.ui_open_repo
import eu.friedcutlet.yokan.services.extensions.languageName
@Composable
internal fun ExtensionDetailRoute(route: Route.ExtensionDetail, nav: Navigator) {
val vm = viewModel {
ExtensionDetailViewModel(
sourceId = route.sourceId,
repository = YokanRuntime.repository,
settings = YokanRuntime.settings,
sourceInstall = YokanRuntime.sourceInstall,
runtimeFactory = YokanRuntime.services.extensionRuntimeFactory,
database = YokanRuntime.services.database,
)
}
val state by vm.state.collectAsStateWithLifecycle()
val source = state.source ?: return MissingRoute("Extension Detail", nav::back)
ExtensionDetailScreen(
state = state,
source = source,
onEditCode = { nav.navigate(Route.CodeEditor(source.id)) },
onDeleteCookies = vm::deleteCookies,
onUninstall = vm::uninstall,
onRefreshPreferences = vm::refreshPreferences,
onPreferenceChange = vm::setPreference,
onBack = nav::back,
)
}
@Composable
internal fun ExtensionDetailScreen(
state: ExtensionDetailUiState,
source: Source,
onEditCode: () -> Unit,
onDeleteCookies: () -> Unit,
onUninstall: () -> Unit,
onRefreshPreferences: () -> Unit,
onPreferenceChange: (key: String, value: String) -> Unit,
onBack: () -> Unit,
) {
val dbSource = state.dbSource
var confirmUninstall by remember { mutableStateOf(false) }
if (confirmUninstall) {
eu.friedcutlet.yokan.ui.components.ConfirmDialog(
title = source.name,
message = "Uninstall ${source.name}? This will remove the bundled JS payload, drop saved extension preferences, and unpin the source.",
confirmLabel = "Uninstall",
danger = true,
onConfirm = {
onUninstall()
confirmUninstall = false
},
onDismiss = { confirmUninstall = false },
)
}
RouteScaffold(source.name, onBack = onBack) {
// Header card: large source icon centered, source name underneath.
item {
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.fillMaxWidth().padding(vertical = 20.dp, horizontal = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Surface(
modifier = Modifier.size(140.dp),
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.5f),
) {
Box(contentAlignment = Alignment.Center) {
val iconUrl = dbSource?.iconUrl?.takeIf { it.isNotBlank() }
if (iconUrl != null) {
eu.friedcutlet.yokan.ui.components.CoverImage(
model = iconUrl,
contentDescription = "${source.name} icon",
modifier = Modifier.size(140.dp),
fallbackInitials = source.name.split(" ")
.take(2)
.joinToString("") { it.firstOrNull()?.uppercase() ?: "" },
)
} else {
Icon(
Icons.Filled.Extension,
contentDescription = null,
modifier = Modifier.size(96.dp),
)
}
}
}
Text(
source.name,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
)
Text(
text = "${languageName(source.lang)} • v${source.version}",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
)
// Stats row: LANG · v<ver> · code-language.
Row(
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
ExtensionStat(
value = source.lang.ifBlank { "—" }.uppercase(),
label = "Language",
)
ExtensionStat(
value = "v${source.version}",
label = "Version",
)
ExtensionStat(
value = source.sourceCodeLanguage.label,
label = "Runtime",
)
}
}
}
}
// Repo / status notes (kept compact above the action row).
item {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
dbSource?.repo?.name?.takeIf { it.isNotBlank() }?.let { repoName ->
Text(
"Repository: $repoName",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
dbSource?.appMinVerReq?.takeIf { it.isNotBlank() }?.let { minVersion ->
Text(
"Requires app $minVersion or newer",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
if (dbSource?.isObsolete == true) {
Text(
"This extension is no longer listed by its repository.",
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
}
state.actionMessage?.let {
Text(
it,
color = MaterialTheme.colorScheme.tertiary,
style = MaterialTheme.typography.bodySmall,
)
}
if (source.notes.isNotBlank()) {
Text(source.notes, style = MaterialTheme.typography.bodySmall)
}
}
}
// Action row: Edit code · Delete cookies · Uninstall.
item {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedButton(
onClick = onEditCode,
modifier = Modifier.weight(1f),
) {
Icon(Icons.Filled.Code, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(stringResource(Res.string.edit_code))
}
OutlinedButton(
onClick = onDeleteCookies,
modifier = Modifier.weight(1f),
) {
Icon(Icons.Filled.Delete, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Delete cookies")
}
FilledTonalButton(
onClick = { confirmUninstall = true },
modifier = Modifier.weight(1f),
) {
Icon(Icons.Filled.Delete, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(if (dbSource?.isObsolete == true) stringResource(Res.string.action_remove) else "Uninstall")
}
}
}
// Optional "Open repo" affordance — keeps the existing affordance
// when the source's repository carries a public website.
dbSource?.repo?.website?.takeIf { it.isNotBlank() }?.let { website ->
item {
OutlinedButton(
onClick = { eu.friedcutlet.yokan.services.system.openSystemBrowser(website) },
modifier = Modifier.fillMaxWidth(),
) {
Icon(Icons.Filled.Public, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(stringResource(Res.string.ui_open_repo))
}
}
}
dbSource?.let {
item(key = "preferences") {
SourcePreferencesCard(
dbSource = it,
preferences = state.preferences,
loading = state.preferencesLoading,
storedValues = state.storedPreferences,
onRefresh = onRefreshPreferences,
onValueChange = onPreferenceChange,
)
}
}
}
}
@Composable
private fun ExtensionStat(value: String, label: String) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(value, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium)
Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.labelSmall)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionDetailViewModel.kt
- Source · implementation · 119 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
33: internal fun YokanRepository.observeDbSource(sourceId: Long): Flow<DbSource?> = snapshots
38: internal fun YokanRepository.currentDbSource(sourceId: Long): DbSource? =
41: internal data class ExtensionDetailUiState(
53: internal class ExtensionDetailViewModel(
85: private suspend fun loadPreferences(refresh: Boolean) {
102: fun refreshPreferences() = preferenceReloads.update { it + 1 }
104: fun setPreference(key: String, value: String) = settings.updateDb { it.withSourcePreference(sourceId, key, value) }
106: fun uninstall() {
114: fun deleteCookies() {
Exact file bytes / download · SHA-256 9de08df3a25567dc735128ec9ee4020c68b8cb338185e8b264726997c8ebb1e6.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.SourceInstallService
import eu.friedcutlet.yokan.services.extensions.SourcePreferenceValue
import eu.friedcutlet.yokan.services.extensions.mihon.MihonExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** The source row, re-read only when the sources table changes. */
internal fun YokanRepository.observeDbSource(sourceId: Long): Flow<DbSource?> = snapshots
.distinctUntilChangedBy { it.sources }
.map { snapshot -> snapshot.sources.firstOrNull { it.id == sourceId } }
.distinctUntilChanged()
internal fun YokanRepository.currentDbSource(sourceId: Long): DbSource? =
snapshots.value.sources.firstOrNull { it.id == sourceId }
internal data class ExtensionDetailUiState(
val dbSource: DbSource?,
val actionMessage: String? = null,
val preferences: List<SourcePreferenceValue> = emptyList(),
val preferencesLoading: Boolean = false,
/** Stored preference values for this source, by key. */
val storedPreferences: Map<String, String> = emptyMap(),
) {
val source: Source? = dbSource?.toDomain()
}
/** Extension detail: metadata, uninstall, cookies and the runtime's preference list. */
internal class ExtensionDetailViewModel(
private val sourceId: Long,
repository: YokanRepository,
private val settings: SettingsStore,
private val sourceInstall: SourceInstallService,
private val runtimeFactory: ExtensionRuntimeFactory,
private val database: YokanDatabase,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(ExtensionDetailUiState(repository.currentDbSource(sourceId)))
val state: StateFlow<ExtensionDetailUiState> = _state.asStateFlow()
private val preferenceReloads = MutableStateFlow(0)
init {
viewModelScope.launch {
repository.observeDbSource(sourceId).collect { db -> _state.update { it.copy(dbSource = db) } }
}
val storedPreferences = settings.db.map { it.sourcePreferences.orEmpty() }.distinctUntilChanged()
viewModelScope.launch {
storedPreferences.collect { stored ->
_state.update { state ->
state.copy(storedPreferences = stored.filter { it.sourceId == sourceId }.associate { it.key to it.value })
}
}
}
viewModelScope.launch {
// The runtime reads stored values, so every preference write reloads the list.
combine(storedPreferences, preferenceReloads) { _, reload -> reload }
.collectLatest { reload -> loadPreferences(refresh = reload > 0) }
}
}
private suspend fun loadPreferences(refresh: Boolean) {
_state.update { it.copy(preferencesLoading = true) }
val preferences = catchingNonCancellation {
withContext(workDispatcher) {
runtimeFactory.withSourceRuntime(database, sourceId) { service ->
if (refresh && service is MihonExtensionRuntimeService) {
service.refreshSourcePreferences()
} else {
service.sourcePreferences()
}
}
}
}.getOrDefault(emptyList())
_state.update { it.copy(preferences = preferences, preferencesLoading = false) }
}
/** Mihon only: asks the extension to rebuild its preference screen. */
fun refreshPreferences() = preferenceReloads.update { it + 1 }
fun setPreference(key: String, value: String) = settings.updateDb { it.withSourcePreference(sourceId, key, value) }
fun uninstall() {
val source = _state.value.source ?: return
val deleted = sourceInstall.uninstall(sourceId)
_state.update {
it.copy(actionMessage = if (deleted) "${source.name} was removed (obsolete)." else "${source.name} uninstalled.")
}
}
fun deleteCookies() {
val source = _state.value.source ?: return
sourceInstall.deleteCookies(source)
_state.update { it.copy(actionMessage = "Cookies deleted for ${source.baseUrl}.") }
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionLanguagesScreen.kt
- Source · implementation · 173 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
48: internal fun ExtensionLanguagesRoute(route: Route.ExtensionLanguages, nav: Navigator) {
62: internal fun ExtensionLanguagesScreen(
Exact file bytes / download · SHA-256 77a78b6c47cc7bff5ef3a0f3dc56e80e42fdf8941a8c5ec70292492cb622c9f8.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Language
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.ItemType
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import eu.friedcutlet.yokan.services.extensions.languageName
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
@Composable
internal fun ExtensionLanguagesRoute(route: Route.ExtensionLanguages, nav: Navigator) {
val vm = viewModel { SourceLanguagesViewModel(route.itemType, YokanRuntime.repository) }
val state by vm.state.collectAsStateWithLifecycle()
ExtensionLanguagesScreen(
state = state,
onSelectType = vm::selectType,
onSetLanguageActive = vm::setLanguageActive,
onSetAllActive = vm::setAllActive,
onBack = nav::back,
)
}
@Composable
@OptIn(ExperimentalMaterial3Api::class)
internal fun ExtensionLanguagesScreen(
state: SourceLanguagesUiState,
onSelectType: (ItemType) -> Unit,
onSetLanguageActive: (lang: String, active: Boolean) -> Unit,
onSetAllActive: (Boolean) -> Unit,
onBack: () -> Unit,
) {
var menuOpen by remember { mutableStateOf(false) }
// Sources grouped by language, sorted alphabetically by human label.
val groups = state.groups
Scaffold(
topBar = {
TopAppBar(
title = { Text("Extension Languages", maxLines = 1, overflow = TextOverflow.Ellipsis) },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
}
},
actions = {
Box {
IconButton(onClick = { menuOpen = true }) {
Icon(Icons.Filled.MoreVert, contentDescription = "More")
}
androidx.compose.material3.DropdownMenu(
expanded = menuOpen,
onDismissRequest = { menuOpen = false },
) {
androidx.compose.material3.DropdownMenuItem(
text = { Text("Enable all") },
onClick = {
menuOpen = false
onSetAllActive(true)
},
)
androidx.compose.material3.DropdownMenuItem(
text = { Text("Disable all") },
onClick = {
menuOpen = false
onSetAllActive(false)
},
)
}
}
},
)
},
) { padding ->
LazyColumn(modifier = Modifier.fillMaxSize().padding(padding)) {
item(key = "item-type") {
Box(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
ItemTypeSelector(state.itemType, onSelect = onSelectType)
}
}
if (groups.isEmpty()) return@LazyColumn
items(groups, key = { it.first }) { (lang, rows) ->
val active = rows.any { it.isActive }
androidx.compose.material3.Surface(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 2.dp)
.clip(MaterialTheme.shapes.large)
.hoverHighlight(onClick = { onSetLanguageActive(lang, !active) }),
color = MaterialTheme.colorScheme.surface,
) {
ListItem(
headlineContent = {
Text(
languageName(lang),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
)
},
supportingContent = {
Text(
"${rows.count { it.isAdded }} installed • ${rows.size} available",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
leadingContent = {
Box(
modifier = Modifier
.size(40.dp)
.clip(androidx.compose.foundation.shape.CircleShape)
.background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f)),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.Language,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(20.dp),
)
}
},
trailingContent = {
Switch(
checked = active,
onCheckedChange = { onSetLanguageActive(lang, it) },
)
},
colors = androidx.compose.material3.ListItemDefaults.colors(
containerColor = androidx.compose.ui.graphics.Color.Transparent,
),
)
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ItemTypeSelector.kt
- Source · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: internal fun ItemTypeSelector(selected: ItemType, onSelect: (ItemType) -> Unit) {
Exact file bytes / download · SHA-256 0d88638ef5f3cec27e896f7ddef87275ef5d295f5df343b5935d5b894999d72d.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.ItemType
@Composable
internal fun ItemTypeSelector(selected: ItemType, onSelect: (ItemType) -> Unit) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ItemType.entries.forEach { type ->
FilterChip(selected = selected == type, onClick = { onSelect(type) }, label = { Text(type.label) })
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourceFiltersScreen.kt
- Source · implementation · 95 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
25: internal fun SourceFiltersRoute(route: Route.SourceFilters, nav: Navigator) {
38: internal fun SourceFiltersScreen(
Exact file bytes / download · SHA-256 c68eae9a7d8975b161262967f43b9e9bec409e7b69eee90c513a06a49c3f8e40.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.services.extensions.languageName
@Composable
internal fun SourceFiltersRoute(route: Route.SourceFilters, nav: Navigator) {
val vm = viewModel { SourceLanguagesViewModel(route.itemType, YokanRuntime.repository) }
val state by vm.state.collectAsStateWithLifecycle()
SourceFiltersScreen(
state = state,
onSelectType = vm::selectType,
onSetLanguageActive = vm::setLanguageActive,
onSetAdded = vm::setAdded,
onBack = nav::back,
)
}
@Composable
internal fun SourceFiltersScreen(
state: SourceLanguagesUiState,
onSelectType: (ItemType) -> Unit,
onSetLanguageActive: (lang: String, active: Boolean) -> Unit,
onSetAdded: (Source, Boolean) -> Unit,
onBack: () -> Unit,
) {
RouteScaffold("Source Filters", onBack = onBack) {
item(key = "item-type") { ItemTypeSelector(state.itemType, onSelect = onSelectType) }
state.groups.forEach { (lang, rows) ->
val active = rows.any { it.isActive }
item(key = "lang-header-$lang") {
ListItem(
headlineContent = {
Text(
languageName(lang),
fontWeight = FontWeight.SemiBold,
style = MaterialTheme.typography.titleSmall,
)
},
trailingContent = {
Switch(
checked = active,
onCheckedChange = { onSetLanguageActive(lang, it) },
)
},
modifier = Modifier
.clip(MaterialTheme.shapes.large)
.hoverHighlight(onClick = { onSetLanguageActive(lang, !active) }),
)
}
// Per-spec: when the language switch is OFF, hide the rows entirely.
if (active) {
items(rows, key = { "src-${it.id}" }) { source ->
ListItem(
headlineContent = { Text(source.name) },
leadingContent = {
androidx.compose.material3.Checkbox(
checked = source.isAdded,
onCheckedChange = { onSetAdded(source, it) },
)
},
supportingContent = {
Text(
"${source.lang} • ${source.version}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
},
modifier = Modifier
.clip(MaterialTheme.shapes.large)
.hoverHighlight(onClick = { onSetAdded(source, !source.isAdded) }),
)
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourceLanguagesViewModel.kt
- Source · implementation · 64 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
18: internal data class SourceLanguagesUiState(
25: private fun languageGroups(sources: List<Source>): List<Pair<String, List<Source>>> = sources
33: internal class SourceLanguagesViewModel(
49: fun selectType(type: ItemType) {
54: fun setLanguageActive(lang: String, active: Boolean) {
59: fun setAllActive(active: Boolean) {
63: fun setAdded(source: Source, added: Boolean) = repository.setSourceAdded(source.id, added)
Exact file bytes / download · SHA-256 8e64ef7302b37866d862ff0fde5c252b604242bfaef641f06719f5ba42189156.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.launch
import eu.friedcutlet.yokan.services.extensions.languageName
import eu.friedcutlet.yokan.services.extensions.normalizedLanguageCode
internal data class SourceLanguagesUiState(
val itemType: ItemType,
/** Sources grouped by normalized language code, groups by display name, rows by name. */
val groups: List<Pair<String, List<Source>>> = emptyList(),
)
// Normalized codes stop duplicate repos from emitting repeated "All languages" or case-variant rows.
private fun languageGroups(sources: List<Source>): List<Pair<String, List<Source>>> = sources
.groupBy { normalizedLanguageCode(it.lang) }
.toList()
.sortedBy { languageName(it.first).lowercase() }
.map { (lang, rows) -> lang to rows.sortedBy { it.name.lowercase() } }
/** Per-language source toggles behind Extension Languages and Source Filters. */
@OptIn(ExperimentalCoroutinesApi::class)
internal class SourceLanguagesViewModel(
itemType: ItemType,
private val repository: YokanRepository,
) : ViewModel() {
private val _state = MutableStateFlow(SourceLanguagesUiState(itemType, languageGroups(repository.sources(itemType))))
val state: StateFlow<SourceLanguagesUiState> = _state.asStateFlow()
private val selectedType = MutableStateFlow(itemType)
init {
viewModelScope.launch {
selectedType.flatMapLatest { type ->
repository.observe({ it.sources }) { SourceLanguagesUiState(type, languageGroups(sources(type))) }
}.collect { next -> if (next.itemType == selectedType.value) _state.value = next }
}
}
fun selectType(type: ItemType) {
selectedType.value = type
_state.value = SourceLanguagesUiState(type, languageGroups(repository.sources(type)))
}
fun setLanguageActive(lang: String, active: Boolean) {
_state.value.groups.firstOrNull { it.first == lang }?.second.orEmpty()
.forEach { repository.setSourceActive(it.id, active) }
}
fun setAllActive(active: Boolean) {
_state.value.groups.forEach { (_, rows) -> rows.forEach { repository.setSourceActive(it.id, active) } }
}
fun setAdded(source: Source, added: Boolean) = repository.setSourceAdded(source.id, added)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourcePreferencesCard.kt
- Source · implementation · 156 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
39: internal fun DbSettings.withSourcePreference(sourceId: Long, key: String, value: String): DbSettings = copy(
45: internal fun SourcePreferencesCard(
106: private fun SourcePreferenceField(
Exact file bytes / download · SHA-256 5526616fd7c55b77dc7656bba507bf606c1bed7a6981fb7e3b14fcdaa7834779.
Complete file
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.DbSourcePreference
import eu.friedcutlet.yokan.services.extensions.SourcePreferenceValue
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.ui_source_preferences
/** Stores [value] for the source's preference [key], replacing the previous value. */
internal fun DbSettings.withSourcePreference(sourceId: Long, key: String, value: String): DbSettings = copy(
sourcePreferences = sourcePreferences.orEmpty().filterNot { it.sourceId == sourceId && it.key == key } +
DbSourcePreference(sourceId = sourceId, key = key, value = value),
)
@Composable
internal fun SourcePreferencesCard(
dbSource: DbSource,
preferences: List<SourcePreferenceValue>,
loading: Boolean,
storedValues: Map<String, String>,
onRefresh: () -> Unit,
onValueChange: (key: String, value: String) -> Unit,
) {
val isMihon = dbSource.sourceCodeLanguage == DbSourceCodeLanguage.Mihon
if (preferences.isEmpty() && !isMihon && !loading) return
ElevatedCard {
Column(Modifier.fillMaxWidth().padding(14.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
stringResource(Res.string.ui_source_preferences),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
if (isMihon) {
IconButton(
onClick = onRefresh,
enabled = !loading,
) {
if (loading) {
androidx.compose.material3.CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
} else {
Icon(Icons.Filled.Refresh, contentDescription = "Refresh preferences", modifier = Modifier.size(18.dp))
}
}
}
}
if (preferences.isEmpty()) {
Text(
if (loading) "Loading preferences..." else "No customizable preferences found for this source.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
preferences.forEach { pref ->
val storedValue = storedValues[pref.key] ?: pref.value
Column(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
Text(pref.title, fontWeight = FontWeight.Medium)
Text(
"${pref.type}: $storedValue",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SourcePreferenceField(pref, storedValue) { value -> onValueChange(pref.key, value) }
}
}
}
}
}
}
@Composable
private fun SourcePreferenceField(
preference: SourcePreferenceValue,
currentValue: String,
onValueChange: (String) -> Unit,
) {
when (preference.type.lowercase()) {
"switchpreference", "switchpreferencecompat", "checkboxpreference" -> {
val checked = currentValue.equals("true", ignoreCase = true)
Row(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.medium)
.hoverHighlight(onClick = { onValueChange((!checked).toString()) })
.padding(horizontal = 6.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Switch(checked = checked, onCheckedChange = { value -> onValueChange(value.toString()) })
Spacer(Modifier.width(8.dp))
Text(if (checked) "Enabled" else "Disabled")
}
}
"listpreference", "multiselectlistpreference" -> {
if (preference.values.isEmpty()) {
OutlinedTextField(
value = currentValue,
onValueChange = onValueChange,
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
} else {
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
preference.values.forEach { entry ->
FilterChip(
selected = currentValue == entry,
onClick = { onValueChange(entry) },
label = { Text(entry) },
)
}
}
}
}
else -> {
OutlinedTextField(
value = currentValue,
onValueChange = onValueChange,
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationDestinationScreen.kt
- Source · implementation · 73 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
25: internal fun MassMigrationDestinationRoute(route: Route.MassMigrationDestination, nav: Navigator) {
34: internal fun MassMigrationDestinationScreen(
Exact file bytes / download · SHA-256 88c9652ea47364c97a4f51a5862c4ee853f3ac53c176ced156ec9f5a7c8e3e62.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.contentDescription
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
@Composable
internal fun MassMigrationDestinationRoute(route: Route.MassMigrationDestination, nav: Navigator) {
val vm = viewModel { MassMigrationDestinationViewModel(route.sourceId, YokanRuntime.repository) }
val state by vm.state.collectAsStateWithLifecycle()
MassMigrationDestinationScreen(state, vm::toggle, vm::move, {
nav.navigate(Route.MassMigrationRunner(sourceId = route.sourceId, destinationIds = state.selectedIds, mangaIds = route.mangaIds))
}, nav::back)
}
@Composable
internal fun MassMigrationDestinationScreen(
state: MassMigrationDestinationState,
onToggle: (Long) -> Unit,
onMove: (Long, Int) -> Unit,
onContinue: () -> Unit,
onBack: () -> Unit,
) {
RouteScaffold(stringResource(Res.string.migration_destinations), onBack = onBack) {
item("instructions") { Text(stringResource(Res.string.migration_destination_help)) }
if (state.destinations?.isEmpty() == true) {
item("empty") { Text(stringResource(Res.string.migration_no_destinations)) }
}
items(state.destinations.orEmpty(), key = { it.id }, contentType = { "source" }) { destination ->
val position = state.selectedIds.indexOf(destination.id)
ListItem(
headlineContent = { Text(destination.name) },
supportingContent = { Text(if (position < 0) destination.lang else stringResource(Res.string.migration_source_order, position + 1, destination.lang)) },
leadingContent = {
val label = stringResource(Res.string.mass_migration_select_destination_action, destination.name)
Checkbox(position >= 0, { onToggle(destination.id) }, Modifier.semantics { contentDescription = label })
},
trailingContent = {
if (position >= 0) Row {
IconButton({ onMove(destination.id, -1) }, enabled = position > 0) {
Icon(Icons.Filled.ArrowUpward, stringResource(Res.string.releases_move_up, destination.name))
}
IconButton({ onMove(destination.id, 1) }, enabled = position < state.selectedIds.lastIndex) {
Icon(Icons.Filled.ArrowDownward, stringResource(Res.string.releases_move_down, destination.name))
}
}
},
)
}
item("continue") {
Button(onContinue, enabled = state.selectedIds.isNotEmpty(), modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Text(stringResource(Res.string.migration_find_matches))
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationDestinationViewModel.kt
- Source · implementation · 54 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
14: internal data class MassMigrationDestinationState(
25: internal class MassMigrationDestinationViewModel(sourceId: Long, repository: YokanRepository) : ViewModel() {
41: fun toggle(id: Long) = _state.update { state ->
47: fun move(id: Long, direction: Int) = _state.update { state ->
Exact file bytes / download · SHA-256 c66b911924a5729cb7c4928cc47cd3e865bc9ab099062fdef67655747f25ec37.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.domain.Source
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
internal data class MassMigrationDestinationState(
val source: Source?,
/** Null until the sources have been read. */
val destinations: List<Source>? = null,
val selectedIds: List<Long> = emptyList(),
)
/**
* Installed (`isAdded`) sources of the migrated source's type, excluding itself; migrating to an
* uninstalled extension would just fail at the runtime step.
*/
internal class MassMigrationDestinationViewModel(sourceId: Long, repository: YokanRepository) : ViewModel() {
private val _state = MutableStateFlow(MassMigrationDestinationState(source = repository.source(sourceId)))
val state: StateFlow<MassMigrationDestinationState> = _state.asStateFlow()
init {
_state.value.source?.let { source ->
viewModelScope.launch {
repository.observe({ it.sources }) {
sources(source.itemType).filter { it.isActive && it.isAdded && it.id != source.id &&
(source.lang.isBlank() || it.lang.isBlank() || it.lang.equals("all", true) || it.lang.equals(source.lang, true)) }
}.collect { destinations -> _state.update { it.copy(destinations = destinations,
selectedIds = it.selectedIds.filter { id -> destinations.any { source -> source.id == id } }) } }
}
}
}
fun toggle(id: Long) = _state.update { state ->
if (state.destinations.orEmpty().none { it.id == id }) state else state.copy(
selectedIds = if (id in state.selectedIds) state.selectedIds - id else state.selectedIds + id,
)
}
fun move(id: Long, direction: Int) = _state.update { state ->
val index = state.selectedIds.indexOf(id)
val next = index + direction
if (index < 0 || next !in state.selectedIds.indices) state else state.copy(selectedIds = state.selectedIds.toMutableList().apply {
this[index] = this[next].also { this[next] = this[index] }
})
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationPreviewScreen.kt
- Source · implementation · 368 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
67: internal fun MassMigrationPreviewRoute(route: Route.MassMigrationPreview, nav: Navigator) {
86: internal fun MassMigrationPreviewScreen(
199: private fun MassMigrationPreviewCard(
Exact file bytes / download · SHA-256 4a2401f58caa3c115d167c5f3d4da8f6f2bd41ce44214d7341f578318ce57e34.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.Extension
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.components.hoverHighlight
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.services.extensions.languageName
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.accessibility_collapsed
import yokan.composeapp.generated.resources.accessibility_expanded
import yokan.composeapp.generated.resources.mass_migration_collapse_source_chapters
import yokan.composeapp.generated.resources.mass_migration_expand_source_chapters
@Composable
internal fun MassMigrationPreviewRoute(route: Route.MassMigrationPreview, nav: Navigator) {
val vm = viewModel {
MassMigrationPreviewViewModel(route.sourceId, YokanRuntime.repository, YokanRuntime.settings, YokanRuntime.libraryIndex)
}
val state by vm.state.collectAsStateWithLifecycle()
val source = state.source ?: return MissingRoute("Mass Migration Preview", nav::back)
MassMigrationPreviewScreen(
source = source,
state = state,
onToggle = vm::toggle,
onLongPress = vm::selectRangeTo,
onToggleAll = vm::toggleAll,
onContinue = { nav.navigate(Route.MassMigrationDestination(source.id, state.selectedMangaIds)) },
onBack = nav::back,
)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun MassMigrationPreviewScreen(
source: Source,
state: MassMigrationPreviewState,
onToggle: (index: Int) -> Unit,
onLongPress: (index: Int) -> Unit,
onToggleAll: () -> Unit,
onContinue: () -> Unit,
onBack: () -> Unit,
) {
val items = state.items.orEmpty()
val totalCount = items.size
val selectedCount = state.selectedCount
val allSelected = state.allSelected
RouteScaffold(
title = "Mass Migration Preview",
onBack = onBack,
actions = {
if (totalCount > 0) {
TextButton(onClick = onToggleAll) {
Text(
if (allSelected) "Deselect all" else "Select all",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
)
}
}
},
) {
// Header source tile — same rounded-surface idiom as the rest of the
// ported screens; no clickable so it reads as a banner, not nav row.
item {
androidx.compose.material3.Surface(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 2.dp),
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainer,
border = androidx.compose.foundation.BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f)),
) {
ListItem(
headlineContent = {
Text(
source.name,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
)
},
supportingContent = {
Text(
"${languageName(source.lang)} • $selectedCount/$totalCount selected",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
leadingContent = {
Box(
modifier = Modifier
.size(40.dp)
.clip(androidx.compose.foundation.shape.CircleShape)
.background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f)),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.Extension,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(20.dp),
)
}
},
colors = androidx.compose.material3.ListItemDefaults.colors(
containerColor = androidx.compose.ui.graphics.Color.Transparent,
),
)
}
}
// Per-manga preview cards w/ selectable checkbox & expandable chapter section.
itemsIndexed(items, key = { _, it -> it.manga.id }) { index, item ->
MassMigrationPreviewCard(
item = item,
index = index + 1,
selected = item.manga.id in state.selectedIds,
onToggle = { onToggle(index) },
onLongClick = { onLongPress(index) },
)
}
// Bottom CTA — picks the destination next.
item {
Button(
onClick = onContinue,
modifier = Modifier.fillMaxWidth().height(50.dp),
enabled = selectedCount > 0,
shape = RoundedCornerShape(50),
) {
Icon(
Icons.AutoMirrored.Filled.ArrowForward,
contentDescription = null,
modifier = Modifier.size(18.dp),
)
Spacer(Modifier.width(8.dp))
Text(
"Select destination source",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
)
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MassMigrationPreviewCard(
item: MassMigrationPreviewItem,
index: Int,
selected: Boolean,
onToggle: () -> Unit,
onLongClick: () -> Unit,
) {
val title = item.manga
var expanded by remember(title.id) { mutableStateOf(false) }
val cardColor = if (selected) {
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.35f)
} else {
MaterialTheme.colorScheme.surfaceContainer
}
val borderColor = if (selected) {
MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f)
}
androidx.compose.material3.Surface(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 2.dp),
shape = MaterialTheme.shapes.large,
color = cardColor,
border = androidx.compose.foundation.BorderStroke(if (selected) 1.5.dp else 1.dp, borderColor),
) {
Column(Modifier.fillMaxWidth().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(2.dp)
.clip(MaterialTheme.shapes.medium)
.combinedClickable(
onClick = onToggle,
onLongClick = onLongClick,
)
.semantics {
role = Role.Checkbox
this.selected = selected
},
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(
checked = selected,
onCheckedChange = null,
modifier = Modifier.size(20.dp),
)
// Index in a small tonal disc — keeps numbering legible while
// matching the rest of the modernised badges.
Box(
modifier = Modifier
.size(28.dp)
.clip(androidx.compose.foundation.shape.CircleShape)
.background(
if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.85f)
else MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f),
),
contentAlignment = Alignment.Center,
) {
Text(
"$index",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
color = if (selected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onPrimaryContainer,
)
}
Box(
modifier = Modifier
.size(width = 60.dp, height = 84.dp)
.clip(MaterialTheme.shapes.medium),
) {
eu.friedcutlet.yokan.ui.components.CoverImage(
model = title.imageUrl,
contentDescription = title.name,
modifier = Modifier.fillMaxSize(),
fallbackInitials = title.name.take(2).uppercase(),
)
}
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
title.name,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
listOfNotNull(title.author?.takeIf { it.isNotBlank() }, "${item.chapterCount} chapters")
.joinToString(" • "),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
// Expansion toggle — rounded clickable row with chevron that
// rotates between collapsed/expanded states.
val expansionActionLabel = stringResource(
if (expanded) Res.string.mass_migration_collapse_source_chapters
else Res.string.mass_migration_expand_source_chapters,
title.name,
)
val expansionStateDescription = stringResource(
if (expanded) Res.string.accessibility_expanded else Res.string.accessibility_collapsed,
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 6.dp, vertical = 6.dp)
.clip(MaterialTheme.shapes.large)
.hoverHighlight(onClick = { expanded = !expanded })
.semantics {
role = Role.Button
contentDescription = expansionActionLabel
stateDescription = expansionStateDescription
},
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.width(8.dp))
Text(
"Source chapters (${item.chapterCount})",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Medium,
)
}
if (expanded) {
val shown = item.previewChapterNames
androidx.compose.material3.Surface(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
) {
Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
shown.forEach { chapterName ->
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(
Icons.AutoMirrored.Filled.MenuBook,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(14.dp),
)
Text(
chapterName,
style = MaterialTheme.typography.bodySmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
val remaining = item.chapterCount - shown.size
if (remaining > 0) {
Text(
"and $remaining more chapters",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium,
)
}
}
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationPreviewViewModel.kt
- Source · implementation · 121 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
23: internal data class MassMigrationPreviewItem(
30: internal data class MassMigrationPreviewState(
48: internal class MassMigrationPreviewViewModel(
87: fun toggle(index: Int) {
95: fun selectRangeTo(index: Int) {
105: fun toggleAll() {
113: internal fun Set<Long>.toggled(id: Long): Set<Long> = if (id in this) this - id else this + id
116: internal fun Set<Long>.plusRange(from: Int, to: Int, ids: List<Long>): Set<Long> {
Exact file bytes / download · SHA-256 061b8c59a4c6f7d6b8a6a35c7a1cfeb32d811b4b15428ea30d239f80f7995238.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import kotlinx.coroutines.CoroutineDispatcher
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.library.sortedChapters
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/** A library title of the migrated source with the chapters shown in its expandable section. */
internal data class MassMigrationPreviewItem(
val manga: Manga,
val chapterCount: Int,
/** The first [PREVIEW_CHAPTER_COUNT] chapter names in the title's chapter sort order. */
val previewChapterNames: List<String>,
)
internal data class MassMigrationPreviewState(
val source: Source?,
/** Null until the library has been read. */
val items: List<MassMigrationPreviewItem>? = null,
val selectedIds: Set<Long> = emptySet(),
/** The last toggled row; a long press selects the range from it. */
val anchorIndex: Int? = null,
) {
val selectedCount: Int get() = items.orEmpty().count { it.manga.id in selectedIds }
val allSelected: Boolean get() = !items.isNullOrEmpty() && selectedCount == items.size
/** The selected titles in list order. */
val selectedMangaIds: List<Long> get() = items.orEmpty().map { it.manga.id }.filter { it in selectedIds }
}
private const val PREVIEW_CHAPTER_COUNT = 12
/** Favorite titles of [sourceId] to migrate; every title starts selected. */
internal class MassMigrationPreviewViewModel(
sourceId: Long,
repository: YokanRepository,
settings: SettingsStore,
libraryIndex: LibraryIndexStore,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(MassMigrationPreviewState(source = repository.source(sourceId)))
val state: StateFlow<MassMigrationPreviewState> = _state.asStateFlow()
init {
_state.value.source?.let { source ->
val titles = repository.observe({ it.mangas }, workDispatcher) {
allTitles(source.itemType).filter { it.favorite && it.source == source.name }
}
viewModelScope.launch {
combine(titles, libraryIndex.index, settings.db) { mangas, index, db ->
mangas.map { manga ->
val chapters = index.chapters(manga.id)
MassMigrationPreviewItem(
manga = manga,
chapterCount = chapters.size,
previewChapterNames = sortedChapters(manga, chapters, db).take(PREVIEW_CHAPTER_COUNT).map { it.name },
)
}
}
.flowOn(workDispatcher)
.collect { items ->
_state.update { state ->
state.copy(
items = items,
selectedIds = if (state.items == null) items.mapTo(HashSet()) { it.manga.id } else state.selectedIds,
)
}
}
}
}
}
fun toggle(index: Int) {
_state.update { state ->
val id = state.items?.getOrNull(index)?.manga?.id ?: return@update state
state.copy(selectedIds = state.selectedIds.toggled(id), anchorIndex = index)
}
}
/** Selects the range from the anchor to [index], or toggles [index] when nothing is anchored. */
fun selectRangeTo(index: Int) {
_state.update { state ->
val ids = state.items.orEmpty().map { it.manga.id }
val id = ids.getOrNull(index) ?: return@update state
val anchor = state.anchorIndex
val selectedIds = if (anchor == null) state.selectedIds.toggled(id) else state.selectedIds.plusRange(anchor, index, ids)
state.copy(selectedIds = selectedIds, anchorIndex = index)
}
}
fun toggleAll() {
_state.update { state ->
val selectedIds = if (state.allSelected) emptySet() else state.items.orEmpty().mapTo(HashSet()) { it.manga.id }
state.copy(selectedIds = selectedIds, anchorIndex = null)
}
}
}
internal fun Set<Long>.toggled(id: Long): Set<Long> = if (id in this) this - id else this + id
/** Adds the ids between [from] and [to] (inclusive, either order, clamped to [ids]). */
internal fun Set<Long>.plusRange(from: Int, to: Int, ids: List<Long>): Set<Long> {
if (ids.isEmpty()) return this
val start = minOf(from, to).coerceIn(0, ids.lastIndex)
val end = maxOf(from, to).coerceIn(0, ids.lastIndex)
return this + ids.subList(start, end + 1)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationRunnerScreen.kt
- Source · implementation · 155 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
23: internal fun MassMigrationRunnerRoute(route: Route.MassMigrationRunner, nav: Navigator) {
32: internal fun MassMigrationRunnerScreen(
79: private fun MigrationReviewCard(
124: private fun phaseLabel(phase: MigrationPhase): String = stringResource(when (phase) {
133: private fun itemStatusLabel(status: MigrationItemStatus): String = stringResource(when (status) {
143: private fun matchLabel(reason: MigrationMatchReason): String = stringResource(when (reason) {
150: private fun issueLabel(issue: MigrationSearchIssue): String = stringResource(when (issue) {
Exact file bytes / download · SHA-256 70522dd812de47aa45477531ac8fed5ca8b46cef7c3ad7a32386a5082060639e.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.services.migration.*
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
@Composable
internal fun MassMigrationRunnerRoute(route: Route.MassMigrationRunner, nav: Navigator) {
val vm = viewModel {
MassMigrationRunnerViewModel(route.sourceId, route.destinationIds.ifEmpty { listOfNotNull(route.destinationId) }, route.mangaIds, YokanRuntime.migration)
}
val state by vm.state.collectAsStateWithLifecycle()
MassMigrationRunnerScreen(state, vm::select, vm::retry, vm::commit, vm::cancel, nav::back)
}
@Composable
internal fun MassMigrationRunnerScreen(
state: MassMigrationRunnerState,
onSelect: (Long, MigrationCandidateKey?) -> Unit,
onRetry: (Long) -> Unit,
onCommit: () -> Unit,
onCancel: () -> Unit,
onBack: () -> Unit,
) {
val run = state.progress
RouteScaffold(stringResource(Res.string.migration_review_title), onBack = onBack) {
if (state.busyWithAnotherRun) {
item("busy") { Text(stringResource(Res.string.migration_busy)) }
return@RouteScaffold
}
if (run == null) return@RouteScaffold
item("summary") {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(phaseLabel(run.phase), style = MaterialTheme.typography.titleMedium)
Text(stringResource(Res.string.migration_totals, run.total, run.migrated, run.unmatched, run.failed, run.skipped))
if (run.phase == MigrationPhase.Searching) {
LinearProgressIndicator(progress = { if (run.total == 0) 1f else run.reviewed.toFloat() / run.total }, modifier = Modifier.fillMaxWidth())
}
Text(stringResource(Res.string.migration_review_help))
if (run.phase == MigrationPhase.Reviewing && run.items.any { it.hasIncompleteSearch }) {
Text(stringResource(Res.string.migration_incomplete_warning), color = MaterialTheme.colorScheme.error)
}
}
}
item("actions") {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (run.phase == MigrationPhase.Reviewing) {
Button(onCommit, enabled = run.selectedCount > 0 && run.items.none { it.status == MigrationItemStatus.Pending }) {
Text(stringResource(Res.string.migration_commit_selected, run.selectedCount))
}
}
if (run.running || run.phase == MigrationPhase.Reviewing) {
OutlinedButton(onCancel) { Text(stringResource(Res.string.migration_cancel)) }
}
}
}
items(run.items, key = { it.original.id }, contentType = { "review" }) { item ->
MigrationReviewCard(item, run.phase, onSelect, onRetry)
}
}
}
@Composable
private fun MigrationReviewCard(
item: MigrationReviewItem,
phase: MigrationPhase,
onSelect: (Long, MigrationCandidateKey?) -> Unit,
onRetry: (Long) -> Unit,
) {
val reviewing = phase == MigrationPhase.Reviewing
val idle = phase != MigrationPhase.Searching && phase != MigrationPhase.Migrating
OutlinedCard(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(item.original.name, style = MaterialTheme.typography.titleMedium)
Text(stringResource(Res.string.migration_original_info, item.original.source, item.originalChapterCount))
Text(itemStatusLabel(item.status), color = if (item.status == MigrationItemStatus.Failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant)
item.sources.filter { it.issues.isNotEmpty() }.forEach { result ->
val issues = result.issues.sortedBy { it.ordinal }.map { issueLabel(it) }.joinToString(", ")
Text(stringResource(Res.string.migration_source_issue, result.source.name, issues), color = MaterialTheme.colorScheme.error)
}
item.candidates.forEach { candidate ->
ListItem(
headlineContent = { Text(candidate.detail.title) },
supportingContent = {
Column {
Text(stringResource(Res.string.migration_candidate_info, candidate.source.name, candidate.effectiveChapters, candidate.rawChapters))
Text(matchLabel(candidate.reason))
}
},
leadingContent = {
val label = stringResource(Res.string.migration_select_candidate, candidate.detail.title, candidate.source.name)
RadioButton(item.selected == candidate.key, { onSelect(item.original.id, candidate.key) },
enabled = reviewing && item.status != MigrationItemStatus.Migrated,
modifier = Modifier.semantics { contentDescription = label })
},
)
}
if (item.status != MigrationItemStatus.Migrated) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (reviewing) TextButton({ onSelect(item.original.id, null) }, enabled = item.status != MigrationItemStatus.Pending) {
Text(stringResource(Res.string.migration_skip))
}
TextButton({ onRetry(item.original.id) }, enabled = idle) { Text(stringResource(Res.string.migration_retry)) }
}
}
}
}
@Composable
private fun phaseLabel(phase: MigrationPhase): String = stringResource(when (phase) {
MigrationPhase.Searching -> Res.string.migration_searching
MigrationPhase.Reviewing -> Res.string.migration_reviewing
MigrationPhase.Migrating -> Res.string.migration_transferring
MigrationPhase.Completed -> Res.string.migration_completed
MigrationPhase.Cancelled -> Res.string.migration_cancelled
})
@Composable
private fun itemStatusLabel(status: MigrationItemStatus): String = stringResource(when (status) {
MigrationItemStatus.Pending -> Res.string.migration_pending
MigrationItemStatus.Ready -> Res.string.migration_ready
MigrationItemStatus.Unmatched -> Res.string.migration_unmatched
MigrationItemStatus.Failed -> Res.string.migration_failed
MigrationItemStatus.Skipped -> Res.string.migration_skipped
MigrationItemStatus.Migrated -> Res.string.migration_migrated
})
@Composable
private fun matchLabel(reason: MigrationMatchReason): String = stringResource(when (reason) {
MigrationMatchReason.ExactTitle -> Res.string.migration_match_exact
MigrationMatchReason.KnownAlias -> Res.string.migration_match_alias
MigrationMatchReason.SimilarTitle -> Res.string.migration_match_similar
})
@Composable
private fun issueLabel(issue: MigrationSearchIssue): String = stringResource(when (issue) {
MigrationSearchIssue.Failed -> Res.string.migration_search_failed
MigrationSearchIssue.TimedOut -> Res.string.migration_search_timeout
MigrationSearchIssue.Truncated -> Res.string.migration_search_truncated
MigrationSearchIssue.DetailFailed -> Res.string.migration_detail_failed
})
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationRunnerViewModel.kt
- Source · implementation · 42 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
11: internal data class MassMigrationRunnerState(
17: internal class MassMigrationRunnerViewModel(
38: fun select(id: Long, key: MigrationCandidateKey?) = migration.select(id, key)
39: fun retry(id: Long) = migration.retry(id)
40: fun commit() = migration.commitSelected()
41: fun cancel() = migration.cancel()
Exact file bytes / download · SHA-256 bd11b1239fad16eed67eb1c6d1f8e70c6826ea727f3f7c83b02c3309483edbad.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.migration.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
internal data class MassMigrationRunnerState(
val progress: MassMigrationProgress? = null,
val busyWithAnotherRun: Boolean = false,
)
/** Mirrors the run owned by this repository/session; route recreation does not restart it. */
internal class MassMigrationRunnerViewModel(
sourceId: Long,
destinationIds: List<Long>,
mangaIds: List<Long>,
private val migration: MigrationService,
) : ViewModel() {
private val _state = MutableStateFlow(MassMigrationRunnerState())
val state = _state.asStateFlow()
init {
val accepted = migration.start(sourceId, destinationIds, mangaIds)
_state.update { it.copy(busyWithAnotherRun = !accepted) }
if (accepted) viewModelScope.launch {
migration.progress.collect { progress ->
if (progress?.sourceId == sourceId && progress.destinationIds == destinationIds.distinct() && progress.mangaIds == mangaIds.distinct()) {
_state.update { it.copy(progress = progress) }
}
}
}
}
fun select(id: Long, key: MigrationCandidateKey?) = migration.select(id, key)
fun retry(id: Long) = migration.retry(id)
fun commit() = migration.commitSelected()
fun cancel() = migration.cancel()
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationSourceScreen.kt
- Source · implementation · 104 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
44: internal fun MassMigrationRoute(route: Route.MassMigration, nav: Navigator) {
56: internal fun MassMigrationSourceScreen(rows: List<MassMigrationSourceRow>?, onSelect: (Source) -> Unit, onBack: () -> Unit) {
Exact file bytes / download · SHA-256 f4d83d3c83c87499fd9ebadeaf5251477d4eb0d5d0528a617dcf976acad6eb9c.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.Extension
import androidx.compose.material.icons.filled.SyncAlt
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.services.extensions.languageName
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.mass_migration_select_source_action
@Composable
internal fun MassMigrationRoute(route: Route.MassMigration, nav: Navigator) {
val vm = viewModel { MassMigrationSourceViewModel(route.itemType, YokanRuntime.repository) }
val rows by vm.state.collectAsStateWithLifecycle()
MassMigrationSourceScreen(
rows = rows,
onSelect = { source -> nav.navigate(Route.MassMigrationPreview(source.id)) },
onBack = nav::back,
)
}
/** [rows] is null while loading. */
@Composable
internal fun MassMigrationSourceScreen(rows: List<MassMigrationSourceRow>?, onSelect: (Source) -> Unit, onBack: () -> Unit) {
RouteScaffold("Mass Migration Source Selection", onBack = onBack) {
if (rows == null) return@RouteScaffold
if (rows.isEmpty()) {
item {
EmptyState(
icon = Icons.Filled.SyncAlt,
title = "No library items",
modifier = Modifier.fillMaxWidth().padding(vertical = 48.dp),
subtitle = "Library has no favorite titles attached to an installed source.",
)
}
return@RouteScaffold
}
items(rows, key = { it.source.id }) { (source, libraryCount) ->
val actionLabel = stringResource(Res.string.mass_migration_select_source_action, source.name)
ListItem(
headlineContent = { Text(source.name, fontWeight = FontWeight.SemiBold) },
supportingContent = {
Text("${languageName(source.lang)} • $libraryCount items")
},
leadingContent = {
Box(
modifier = Modifier
.size(40.dp)
.background(
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
RoundedCornerShape(6.dp),
),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Extension, contentDescription = null)
}
},
trailingContent = {
Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null)
},
modifier = Modifier
.clip(MaterialTheme.shapes.large)
.hoverHighlight(onClick = { onSelect(source) })
.semantics {
role = Role.Button
contentDescription = actionLabel
},
)
eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider()
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationSourceViewModel.kt
- Source · implementation · 29 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
14: internal data class MassMigrationSourceRow(val source: Source, val libraryCount: Int)
17: internal class MassMigrationSourceViewModel(itemType: ItemType, repository: YokanRepository) : ViewModel() {
Exact file bytes / download · SHA-256 96bf777605d9641a2038befaa1b97b45b555f0e7af56924691f43932a911d447.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
internal data class MassMigrationSourceRow(val source: Source, val libraryCount: Int)
/** Sources of [itemType] that have favorite titles; null until the library has been read. */
internal class MassMigrationSourceViewModel(itemType: ItemType, repository: YokanRepository) : ViewModel() {
private val _state = MutableStateFlow<List<MassMigrationSourceRow>?>(null)
val state: StateFlow<List<MassMigrationSourceRow>?> = _state.asStateFlow()
init {
viewModelScope.launch {
repository.observe({ it.mangas to it.sources }) {
val counts = allTitles(itemType).filter { it.favorite }.groupingBy { it.source }.eachCount()
sources(itemType).mapNotNull { source -> counts[source.name]?.let { MassMigrationSourceRow(source, it) } }
}.collect { _state.value = it }
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationPreviewSheet.kt
- Source · implementation · 240 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
47: internal fun MigrationPreviewSheet(
Exact file bytes / download · SHA-256 04a30e3121a2458896c30f61731fef2e7c53da776eed93bca2b898d0b41cfdd8.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import eu.friedcutlet.yokan.services.extensions.languageName
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
/**
* Bottom-sheet preview of the remote detail (cover, description and chapters) that lets the user
* confirm a per-manga migration.
*
* Keeps the user on the migration screen — the sheet itself dismisses on
* success and the parent screen closes back to the previous detail page.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun MigrationPreviewSheet(
preview: MigrationPreview,
onDismiss: () -> Unit,
onMigrate: () -> Unit,
) {
val sheetState = androidx.compose.material3.rememberModalBottomSheetState(skipPartiallyExpanded = false)
val candidate = preview.candidate
val destSource = preview.source
val loading = preview.loading
val error = preview.error
val migrating = preview.migrating
androidx.compose.material3.ModalBottomSheet(
onDismissRequest = onDismiss,
modifier = Modifier.compactSheetWidth(),
sheetState = sheetState,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
// Header: cover + title + source line.
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(14.dp),
) {
Box(
modifier = Modifier
.size(width = 88.dp, height = 124.dp)
.clip(MaterialTheme.shapes.medium),
) {
eu.friedcutlet.yokan.ui.components.CoverImage(
model = candidate.thumbnailUrl,
contentDescription = candidate.title,
modifier = Modifier.fillMaxSize(),
fallbackInitials = candidate.title.take(2).uppercase(),
)
}
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
candidate.title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
Text(
"${destSource.name} • ${languageName(destSource.lang)}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
if (loading) {
androidx.compose.material3.LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(4.dp)
.clip(RoundedCornerShape(50)),
)
}
}
}
error?.let { message ->
androidx.compose.material3.Surface(
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.errorContainer,
) {
Text(
message,
modifier = Modifier.padding(12.dp),
color = MaterialTheme.colorScheme.onErrorContainer,
style = MaterialTheme.typography.bodySmall,
)
}
}
preview.detail?.let { d ->
if (d.description.isNotBlank()) {
Text(
d.description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
)
}
Text(
"Chapters (${d.chapters.size})",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold,
)
val previewState = androidx.compose.foundation.lazy.rememberLazyListState()
eu.friedcutlet.yokan.ui.components.ScrollableLazyColumn(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 280.dp),
state = previewState,
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
if (d.chapters.isEmpty()) {
item {
Text(
"This source returned no chapters for the candidate.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(vertical = 8.dp),
)
}
} else {
items(d.chapters, key = { it.url }) { chapter ->
Row(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.large)
.padding(horizontal = 8.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Icon(
Icons.AutoMirrored.Filled.MenuBook,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(16.dp),
)
Column(modifier = Modifier.weight(1f)) {
Text(
chapter.title,
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val sub = listOfNotNull(
chapter.scanlator.takeIf { it.isNotBlank() },
chapter.dateUpload.takeIf { it.isNotBlank() },
).joinToString(" • ")
if (sub.isNotEmpty()) {
Text(
sub,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
}
}
}
// Action row at the bottom: Cancel + Migrate pill.
Row(
modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
androidx.compose.material3.OutlinedButton(
onClick = onDismiss,
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp),
) {
Text(stringResource(Res.string.action_cancel), style = MaterialTheme.typography.labelLarge)
}
Spacer(Modifier.weight(1f))
androidx.compose.material3.Button(
onClick = onMigrate,
enabled = !loading && !migrating && error == null,
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 22.dp, vertical = 8.dp),
) {
if (migrating) {
androidx.compose.material3.CircularProgressIndicator(
strokeWidth = 2.dp,
modifier = Modifier.size(18.dp),
color = MaterialTheme.colorScheme.onPrimary,
)
} else {
Icon(Icons.Filled.SwapHoriz, contentDescription = null, modifier = Modifier.size(18.dp))
}
Spacer(Modifier.width(8.dp))
Text(
if (migrating) "Migrating…" else "Migrate",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
)
}
}
Spacer(Modifier.height(8.dp))
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationScreen.kt
- Source · implementation · 249 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
52: internal fun MigrateRoute(route: Route.Migrate, nav: Navigator) {
77: internal fun MigrationScreen(
200: private fun MigrationResultCard(remote: RemoteManga, isFavorite: Boolean, onClick: () -> Unit) {
Exact file bytes / download · SHA-256 5f2a635de6744c8b1085762ea1f15474a4be60c1be9b371664c5d824ccdf8930.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.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.material.icons.Icons
import androidx.compose.material.icons.filled.CollectionsBookmark
import androidx.compose.material.icons.filled.SyncAlt
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
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.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.ui.components.DefaultContentPadding
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.AppBarSearchField
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.services.extensions.languageName
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
@Composable
internal fun MigrateRoute(route: Route.Migrate, nav: Navigator) {
val vm = viewModel {
MigrationViewModel(
route.mangaId,
YokanRuntime.repository,
YokanRuntime.services.database,
YokanRuntime.services.extensionRuntimeFactory,
YokanRuntime.migration,
)
}
val state by vm.state.collectAsStateWithLifecycle()
MigrationScreen(
state = state,
onQueryChange = vm::changeQuery,
onSearch = vm::submit,
onClear = vm::clear,
onCandidate = vm::openPreview,
onDismissPreview = vm::dismissPreview,
onMigrate = { vm.migrate(onMigrated = nav::back) },
onBack = nav::back,
)
}
@Composable
@OptIn(ExperimentalMaterial3Api::class)
internal fun MigrationScreen(
state: MigrationState,
onQueryChange: (String) -> Unit,
onSearch: () -> Unit,
onClear: () -> Unit,
onCandidate: (Source, RemoteManga) -> Unit,
onDismissPreview: () -> Unit,
onMigrate: () -> Unit,
onBack: () -> Unit,
) {
val manga = state.manga
val query = state.query
val submittedQuery = state.submittedQuery
if (manga != null) {
state.preview?.let { preview ->
MigrationPreviewSheet(preview = preview, onDismiss = onDismissPreview, onMigrate = onMigrate)
}
}
Scaffold(
topBar = {
// Wireframe AppBar = a search field (prefix = back, suffix = clear).
TopAppBar(
title = {
AppBarSearchField(
query = query,
placeholder = "Search title across sources",
onQueryChange = onQueryChange,
onClose = onBack,
onSearch = onSearch,
onClear = onClear,
)
},
)
},
) { padding ->
if (manga == null) {
EmptyState(
icon = Icons.Filled.SyncAlt,
title = "No title selected",
modifier = Modifier.fillMaxSize().padding(padding).padding(DefaultContentPadding),
subtitle = "Open migration from a detail page or mass migration source picker.",
)
return@Scaffold
}
LazyColumn(
modifier = Modifier.fillMaxSize().padding(padding),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (submittedQuery.isBlank()) {
item {
Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {
Text(
"Type a title and press search to query every installed source.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
return@LazyColumn
}
items(state.sources, key = { it.id }) { source ->
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Box(
modifier = Modifier
.size(8.dp)
.clip(androidx.compose.foundation.shape.CircleShape)
.background(MaterialTheme.colorScheme.primary),
)
Text(
source.name,
fontWeight = FontWeight.SemiBold,
style = MaterialTheme.typography.titleSmall,
)
Text(
"•",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.labelMedium,
)
Text(
languageName(source.lang),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Spacer(Modifier.height(8.dp))
val isLoading = source.id in state.loadingSourceIds
val listing = state.listings[source.id]
when {
isLoading -> Box(Modifier.fillMaxWidth().height(180.dp), contentAlignment = Alignment.Center) {
androidx.compose.material3.CircularProgressIndicator()
}
listing == null || listing.items.isEmpty() ->
Box(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Text(
"No result",
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
else -> androidx.compose.foundation.lazy.LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
items(listing.items, key = { it.url }) { remote ->
MigrationResultCard(
remote = remote,
isFavorite = remote.title.lowercase() in state.libraryTitleNames,
onClick = { onCandidate(source, remote) },
)
}
}
}
}
eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider()
}
}
}
}
@Composable
private fun MigrationResultCard(remote: RemoteManga, isFavorite: Boolean, onClick: () -> Unit) {
val interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hovered by interactionSource.collectIsHoveredAsState()
val elevation by androidx.compose.animation.core.animateDpAsState(if (hovered) 6.dp else 0.dp)
Column(
modifier = Modifier
.width(110.dp)
.clip(MaterialTheme.shapes.medium)
.hoverable(interactionSource = interactionSource)
.clickable(interactionSource = interactionSource, indication = null) { onClick() },
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
androidx.compose.material3.Surface(
shape = MaterialTheme.shapes.medium,
shadowElevation = elevation,
color = androidx.compose.ui.graphics.Color.Transparent,
) {
Box(modifier = Modifier.size(width = 110.dp, height = 150.dp).clip(MaterialTheme.shapes.medium)) {
eu.friedcutlet.yokan.ui.components.CoverImage(
model = remote.thumbnailUrl,
contentDescription = remote.title,
modifier = Modifier.fillMaxSize(),
fallbackInitials = remote.title.take(2).uppercase(),
)
if (isFavorite) {
// Dark overlay + bookmark icon when the candidate already exists in library.
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.55f)),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.CollectionsBookmark,
contentDescription = "Already in library",
tint = MaterialTheme.colorScheme.primary,
)
}
}
}
}
Text(
remote.title,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Medium,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationViewModel.kt
- Source · implementation · 151 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
25: internal data class MigrationPreview(
34: internal data class MigrationState(
48: internal class MigrationViewModel(
73: fun changeQuery(query: String) {
77: fun submit() {
84: fun clear() {
89: fun openPreview(source: Source, candidate: RemoteManga) {
106: fun dismissPreview() {
112: fun migrate(onMigrated: () -> Unit) {
128: private fun search() {
148: private fun updatePreview(transform: (MigrationPreview) -> MigrationPreview) {
Exact file bytes / download · SHA-256 7ab200cec8100b6a541279277fa04badcc3f34078f78940fa39cfcd3c5fe935c.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceListing
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
import eu.friedcutlet.yokan.services.migration.MigrationService
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/** The candidate the user tapped, with its destination detail. */
internal data class MigrationPreview(
val source: Source,
val candidate: RemoteManga,
val detail: RemoteDetail? = null,
val loading: Boolean = true,
val error: String? = null,
val migrating: Boolean = false,
)
internal data class MigrationState(
val manga: Manga?,
val query: String,
val submittedQuery: String,
/** The installed sources the submitted query ran on. */
val sources: List<Source> = emptyList(),
val listings: Map<Long, SourceListing?> = emptyMap(),
val loadingSourceIds: Set<Long> = emptySet(),
/** Lower-cased names of favorite titles of the title's type, for the "already in library" badge. */
val libraryTitleNames: Set<String> = emptySet(),
val preview: MigrationPreview? = null,
)
/** Searches every installed source for [mangaId]'s replacement and migrates it to the chosen candidate. */
internal class MigrationViewModel(
mangaId: Long,
private val repository: YokanRepository,
private val database: YokanDatabase,
private val runtimeFactory: ExtensionRuntimeFactory,
private val migration: MigrationService,
) : ViewModel() {
private val _state = MutableStateFlow(
repository.manga(mangaId).let { MigrationState(manga = it, query = it?.name.orEmpty(), submittedQuery = it?.name.orEmpty()) },
)
val state: StateFlow<MigrationState> = _state.asStateFlow()
private var searchJob: Job? = null
private var previewJob: Job? = null
init {
_state.value.manga?.let { manga ->
viewModelScope.launch {
repository.observe({ it.mangas }) {
allTitles(manga.itemType).filter { it.favorite }.mapTo(HashSet()) { it.name.lowercase() }
}.collect { names -> _state.update { it.copy(libraryTitleNames = names) } }
}
search()
}
}
fun changeQuery(query: String) {
_state.update { it.copy(query = query) }
}
fun submit() {
val state = _state.value
if (state.query == state.submittedQuery) return
_state.update { it.copy(submittedQuery = state.query) }
search()
}
fun clear() {
searchJob?.cancel()
_state.update { it.copy(query = "", submittedQuery = "", listings = emptyMap(), loadingSourceIds = emptySet()) }
}
fun openPreview(source: Source, candidate: RemoteManga) {
previewJob?.cancel()
_state.update { it.copy(preview = MigrationPreview(source, candidate)) }
previewJob = viewModelScope.launch {
catchingNonCancellation {
runtimeFactory.withSourceRuntime(database, source.id) { it.detail(candidate.url) }
}.fold(
onSuccess = { detail -> updatePreview { it.copy(detail = detail, loading = false) } },
onFailure = { error ->
val message = error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }
updatePreview { it.copy(error = message, loading = false) }
},
)
}
}
/** Also cancels a migration in flight, as closing the sheet always did. */
fun dismissPreview() {
previewJob?.cancel()
_state.update { it.copy(preview = null) }
}
/** Migrates to the previewed candidate; [onMigrated] runs once the new title exists. */
fun migrate(onMigrated: () -> Unit) {
val state = _state.value
val manga = state.manga ?: return
val preview = state.preview ?: return
if (preview.migrating) return
updatePreview { it.copy(migrating = true) }
previewJob = viewModelScope.launch {
val newId = migration.migrate(manga, preview.source, preview.candidate)
updatePreview { it.copy(migrating = false) }
if (newId != null) {
_state.update { it.copy(preview = null) }
onMigrated()
}
}
}
private fun search() {
searchJob?.cancel()
val state = _state.value
val manga = state.manga ?: return
val query = state.submittedQuery
if (query.isBlank()) return
val sources = repository.sources(manga.itemType).filter { it.isActive && it.isAdded }
_state.update { it.copy(sources = sources, listings = emptyMap(), loadingSourceIds = sources.mapTo(HashSet()) { source -> source.id }) }
searchJob = viewModelScope.launch {
sources.forEach { source ->
launch {
val listing = catchingNonCancellation {
runtimeFactory.withSourceRuntime(database, source.id) { it.search(query, 1, emptyList()) }
}.getOrNull()
_state.update { it.copy(listings = it.listings + (source.id to listing), loadingSourceIds = it.loadingSourceIds - source.id) }
}
}
}
}
private fun updatePreview(transform: (MigrationPreview) -> MigrationPreview) {
_state.update { state -> state.preview?.let { state.copy(preview = transform(it)) } ?: state }
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/migration/MigrationServiceTest.kt
- Source · test / fixture · 137 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
33: class MigrationServiceTest {
63: private fun TestScope.service() = MigrationService(
73: fun migrateMovesTheTitleAndClearsItsUpdateError() = runTest {
92: fun migrationRetainsDifferingDestinationNotes() = runTest {
105: fun startReviewsTheMatchBeforeMigratingThroughTheSamePath() = runTest {
123: private object FakeRuntimeFactory : ExtensionRuntimeFactory {
124: override fun create(source: DbSource): ExtensionRuntimeService = FakeRuntime(source)
128: private class FakeRuntime(source: DbSource) : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {
129: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>) = SourceListing(
133: override suspend fun detail(url: String): RemoteDetail {
Exact file bytes / download · SHA-256 90ccfd431555a746fddf867d5f5641a4c1bb0fb60baf38fa2a241a3ed3b4aaf6.
Complete file
package eu.friedcutlet.yokan.services.migration
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.DbUpdateError
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.extensions.DatabaseFallbackRuntimeService
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceListing
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.ExperimentalCoroutinesApi
@OptIn(ExperimentalCoroutinesApi::class)
class MigrationServiceTest {
private val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().let { seed ->
seed.copy(
settings = seed.settings.copy(
updateErrors = listOf(
DbUpdateError(mangaId = 1, name = "Title", error = "HTTP 404"),
DbUpdateError(mangaId = 3, name = "Other", error = "HTTP 502"),
),
),
sources = listOf(
DbSource(id = 1, name = "Old", lang = "en", itemType = DbItemType.Manga, isAdded = true),
DbSource(
id = 2,
name = "New",
lang = "en",
itemType = DbItemType.Manga,
isAdded = true,
sourceCodeLanguage = DbSourceCodeLanguage.JavaScript,
),
),
mangas = listOf(
DbManga(id = 1, name = "Title", link = "/old", source = "Old", sourceId = 1, itemType = DbItemType.Manga, favorite = true),
),
chapters = listOf(DbChapter(id = 10, mangaId = 1, url = "/old/ch1", name = "Chapter 1", isRead = true)),
)
},
)
private val repository = DefaultYokanRepository(database)
private fun TestScope.service() = MigrationService(
repository = repository,
database = database,
runtimeFactory = FakeRuntimeFactory,
settings = SettingsStore(repository, backgroundScope, onSchedulingChanged = {}),
scope = backgroundScope,
workDispatcher = StandardTestDispatcher(testScheduler),
)
@Test
fun migrateMovesTheTitleAndClearsItsUpdateError() = runTest {
val service = service()
val newId = checkNotNull(
service.migrate(
from = checkNotNull(repository.manga(1)),
destination = checkNotNull(repository.source(2)),
candidate = RemoteManga(title = "Title", url = "/new"),
),
)
assertNotEquals(1L, newId)
assertEquals(listOf(3L), database.settings().updateErrors?.map { it.mangaId })
assertEquals(false, repository.manga(1)?.favorite)
assertEquals(true, repository.manga(newId)?.favorite)
assertTrue(repository.chapters(newId).single().isRead)
}
@Test
fun migrationRetainsDifferingDestinationNotes() = runTest {
val sourceNote = "Original 🌙\nsecond line"
repository.setMangaPrivateNote(1, sourceNote)
val destination = checkNotNull(repository.source(2))
val target = repository.upsertRemoteTitle(destination, RemoteManga("Title", "/new"), favorite = true)
repository.setMangaPrivateNote(target.id, "Destination note")
val id = service().migrate(checkNotNull(repository.manga(1)), destination, RemoteManga("Title", "/new"))
assertEquals(target.id, id)
assertEquals("Destination note\n\n---\n\n$sourceNote", repository.manga(target.id)?.privateNote)
assertEquals(sourceNote, repository.manga(1)?.privateNote)
}
@Test
fun startReviewsTheMatchBeforeMigratingThroughTheSamePath() = runTest {
val service = service()
service.start(sourceId = 1, destinationIds = listOf(2), mangaIds = listOf(1))
runCurrent()
assertEquals(MigrationPhase.Reviewing, service.progress.value?.phase)
assertEquals(true, repository.manga(1)?.favorite)
service.commitSelected()
val finished = service.progress.first { it?.phase == MigrationPhase.Completed }
assertEquals(1, finished?.total)
assertEquals(1, finished?.migrated)
assertEquals(0, finished?.failed)
assertEquals(listOf(3L), database.settings().updateErrors?.map { it.mangaId })
assertEquals(false, repository.manga(1)?.favorite)
}
}
private object FakeRuntimeFactory : ExtensionRuntimeFactory {
override fun create(source: DbSource): ExtensionRuntimeService = FakeRuntime(source)
}
/** Search offers a near miss before the exact title; detail serves "/new". */
private class FakeRuntime(source: DbSource) : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {
override suspend fun search(query: String, page: Int, filters: List<SourceFilter>) = SourceListing(
items = listOf(RemoteManga(title = "Title Side Story", url = "/side"), RemoteManga(title = "title", url = "/new")),
hasNextPage = false,
)
override suspend fun detail(url: String): RemoteDetail {
check(url == "/new") { "Unexpected detail $url" }
return RemoteDetail(title = "Title", url = url, chapters = listOf(RemoteChapter(title = "Chapter 1", url = "/new/ch1")))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/migration/SmarterMigrationTest.kt
- Source · test / fixture · 288 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
14: class SmarterMigrationTest {
15: private fun database(names: List<String> = listOf("Title")): InMemoryYokanDatabase = InMemoryYokanDatabase(
24: private fun TestScope.service(db: InMemoryYokanDatabase, factory: MigrationTestFactory, limits: MigrationSearchLimits = MigrationSearchLimits()): MigrationService {
31: fun matchingUsesNormalizedTitlesAliasesAndConservativeSimilarity() {
47: fun coverageKeepsVolumesFractionsLanguagesSpecialsAndUncertainEntries() {
55: fun laterSourceWithMoreDistinctChaptersWinsAndCommitReusesReviewedDetails() = runTest {
88: fun explicitOverrideAndSkipPreserveAccurateTotalsIncludingUnmatchedAndFailures() = runTest {
115: fun rankingBreaksCoverageTiesByConfidenceSourceOrderAndUrl() {
119: fun candidate(source: eu.friedcutlet.yokan.domain.Source, url: String, reason: MigrationMatchReason) =
130: fun paginationLimitsAndDetailErrorsAreVisibleAndRetryRefreshesTheProposal() = runTest {
157: fun searchesEveryCompatibleSourceWithBoundedConcurrencyAndIndependentTimeouts() = runTest {
183: fun cancellationStopsDiscoveryAndNeverStartsTransfer() = runTest {
201: fun unavailableDestinationAtCommitFailsWithoutUnfavoritingTheOriginal() = runTest {
221: fun failedOrCancelledTransferLeavesTheOriginalFavoriteAndItsProgressIntact() = runTest {
227: override fun setMangaCategories(mangaId: Long, categories: List<Long>, favorite: Boolean) {
247: fun parentDeadlinePropagatesInsteadOfBecomingAnOrdinarySourceTimeout() = runTest {
258: fun aliasesDeduplicateCandidateFetchesAndCacheDetailsForTheRun() = runTest {
272: internal class MigrationTestFactory(
278: override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {
279: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing {
283: override suspend fun detail(url: String): RemoteDetail {
Exact file bytes / download · SHA-256 c2acc28b7634ac9b7a5e66503ca51d88a4950caf05d6b90a898b21cbf998ec33.
Complete file
package eu.friedcutlet.yokan.services.migration
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.extensions.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*
@OptIn(ExperimentalCoroutinesApi::class)
class SmarterMigrationTest {
private fun database(names: List<String> = listOf("Title")): InMemoryYokanDatabase = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
sources = (1L..6L).map { DbSource(id = it, name = if (it == 1L) "Old" else "Source $it", lang = "en", itemType = DbItemType.Manga, isAdded = true) },
mangas = names.mapIndexed { index, name -> DbManga(id = index + 10L, name = name, link = "/old/$index", sourceId = 1, source = "Old", lang = "en", itemType = DbItemType.Manga, favorite = true, privateNote = "Private $name") },
chapters = listOf(DbChapter(id = 101, mangaId = 10, name = "Chapter 1", url = "/old/ch1", isRead = true, isBookmarked = true)),
downloads = emptyList(),
),
)
private fun TestScope.service(db: InMemoryYokanDatabase, factory: MigrationTestFactory, limits: MigrationSearchLimits = MigrationSearchLimits()): MigrationService {
val repository = DefaultYokanRepository(db)
return MigrationService(repository, db, factory, SettingsStore(repository, backgroundScope, {}), backgroundScope,
limits, StandardTestDispatcher(testScheduler))
}
@Test
fun matchingUsesNormalizedTitlesAliasesAndConservativeSimilarity() {
val title = checkNotNull(DefaultYokanRepository(database()).manga(10)).copy(name = "A Journey into Light", alternativeTitles = listOf("光の旅", "Light Journey"))
assertEquals(MigrationMatchReason.ExactTitle, migrationMatchReason(title, "A JOURNEY—INTO LIGHT!"))
assertEquals(MigrationMatchReason.KnownAlias, migrationMatchReason(title, "光の旅"))
assertEquals(MigrationMatchReason.SimilarTitle, migrationMatchReason(title, "A Journey into the Light"))
listOf("Light", "A Journey into Light 2", "A Journey into Light Side Story", "A Journey into Light Novel", "Unrelated Light").forEach {
assertNull(migrationMatchReason(title, it), it)
}
val source = checkNotNull(DefaultYokanRepository(database()).source(2))
assertTrue(migrationSourceCompatible(title, source))
assertFalse(migrationSourceCompatible(title, source.copy(lang = "fr")))
assertFalse(migrationSourceCompatible(title, source.copy(itemType = ItemType.Anime)))
assertTrue(migrationSourceCompatible(title, source.copy(lang = "all")))
}
@Test
fun coverageKeepsVolumesFractionsLanguagesSpecialsAndUncertainEntries() {
val names = listOf("Chapter 1", "Chapter 1", "Chapter 0", "Chapter 1.5", "Volume 2 Chapter 1", "Chapter 1 Special", "Chapter 1 [fr]", "Bonus", "Bonus", "Chapter 1-2")
val detail = RemoteDetail("Title", "/title", chapters = names.mapIndexed { index, name -> RemoteChapter(name, "/$index", scanlator = "$index") })
assertEquals(9, migrationChapterCoverage(detail))
assertEquals(10, detail.chapters.size)
}
@Test
fun laterSourceWithMoreDistinctChaptersWinsAndCommitReusesReviewedDetails() = runTest {
val db = database()
val factory = MigrationTestFactory(detail = { source, url ->
val chapters = if (source.id == 2L) listOf(RemoteChapter("Chapter 1", "$url/ch1"), RemoteChapter("Chapter 1", "$url/alt"))
else listOf(RemoteChapter("Chapter 1", "$url/ch1"), RemoteChapter("Chapter 2", "$url/ch2"))
RemoteDetail("Title", url, chapters = chapters)
})
val service = service(db, factory)
assertTrue(service.start(1, listOf(2, 3), listOf(10, 10)))
runCurrent()
val run = checkNotNull(service.progress.value)
assertEquals(MigrationPhase.Reviewing, run.phase)
assertEquals(listOf(3L, 2L), run.items.single().candidates.map { it.source.id })
assertEquals(1, run.items.single().candidates.last().effectiveChapters)
assertEquals(2, run.items.single().candidates.last().rawChapters)
assertTrue(checkNotNull(db.manga(10)).favorite)
assertEquals(1, db.mangas().size)
assertTrue(service.start(1, listOf(2, 3), listOf(10)))
assertFalse(service.start(1, listOf(4), listOf(10)))
service.commitSelected()
runCurrent()
assertEquals(MigrationPhase.Completed, service.progress.value?.phase)
assertEquals(1, service.progress.value?.migrated)
assertEquals(2, factory.detailCalls.size)
assertFalse(checkNotNull(db.manga(10)).favorite)
val migrated = db.mangas().single { it.favorite }
assertEquals(3L, migrated.sourceId)
assertEquals("Private Title", migrated.privateNote)
assertTrue(db.chapters(migrated.id).first { it.name == "Chapter 1" }.isRead)
assertTrue(db.chapters(migrated.id).first { it.name == "Chapter 1" }.isBookmarked)
}
@Test
fun explicitOverrideAndSkipPreserveAccurateTotalsIncludingUnmatchedAndFailures() = runTest {
val db = database(listOf("Title", "Missing", "Broken", "Skip"))
val factory = MigrationTestFactory(search = { _, query, _ -> when (query) {
"Missing" -> SourceListing(listOf(RemoteManga("Unrelated", "/unrelated")), false)
"Broken" -> error("Source failed")
else -> SourceListing(listOf(RemoteManga(query, "/$query")), false)
} }, detail = { _, url -> RemoteDetail(url.removePrefix("/"), url) })
val service = service(db, factory)
service.start(1, listOf(2, 3), listOf(10, 11, 12, 13))
runCurrent()
val title = checkNotNull(service.progress.value).items.first()
service.select(10, title.candidates.first { it.source.id == 3L }.key)
service.select(13, null)
service.commitSelected()
runCurrent()
val run = checkNotNull(service.progress.value)
assertEquals(4, run.total)
assertEquals(1, run.migrated)
assertEquals(1, run.unmatched)
assertEquals(1, run.failed)
assertEquals(1, run.skipped)
assertEquals(3L, db.mangas().single { it.favorite && it.id !in 11L..13L }.sourceId)
assertTrue((11L..13L).all { db.manga(it)?.favorite == true })
assertTrue(factory.detailCalls.none { it.second == "/unrelated" })
}
@Test
fun rankingBreaksCoverageTiesByConfidenceSourceOrderAndUrl() {
val repository = DefaultYokanRepository(database())
val a = checkNotNull(repository.source(2))
val b = checkNotNull(repository.source(3))
fun candidate(source: eu.friedcutlet.yokan.domain.Source, url: String, reason: MigrationMatchReason) =
MigrationCandidate(source, RemoteDetail("Title", url), 2, 10, reason)
val results = listOf(
MigrationSourceResult(a, listOf(candidate(a, "/weak", MigrationMatchReason.SimilarTitle), candidate(a, "/z", MigrationMatchReason.ExactTitle), candidate(a, "/a", MigrationMatchReason.ExactTitle))),
MigrationSourceResult(b, listOf(candidate(b, "/b", MigrationMatchReason.ExactTitle))),
)
assertEquals(listOf("/a", "/z", "/b", "/weak"), rankedMigrationCandidates(results).map { it.detail.url })
assertEquals("/b", rankedMigrationCandidates(results.reversed()).first().detail.url)
}
@Test
fun paginationLimitsAndDetailErrorsAreVisibleAndRetryRefreshesTheProposal() = runTest {
val db = database()
var broken = true
val factory = MigrationTestFactory(search = { _, query, page ->
SourceListing(listOf(RemoteManga(query, "/$page")), true)
}, detail = { _, url ->
if (broken && url == "/1") error("Detail unavailable")
RemoteDetail("Title", url, chapters = listOf(RemoteChapter("Chapter $url", "$url/ch")))
})
val service = service(db, factory, MigrationSearchLimits(maxPagesPerQuery = 2))
service.start(1, listOf(2), listOf(10))
runCurrent()
val item = checkNotNull(service.progress.value).items.single()
assertEquals(listOf(1, 2), factory.searchCalls.map { it.third })
assertEquals(setOf(MigrationSearchIssue.Truncated, MigrationSearchIssue.DetailFailed), item.sources.single().issues)
assertEquals(listOf("/2"), item.candidates.map { it.detail.url })
assertTrue(db.manga(10)?.favorite == true)
broken = false
service.retry(10)
runCurrent()
val retried = checkNotNull(service.progress.value).items.single()
assertEquals(2, retried.candidates.size)
assertEquals(setOf(MigrationSearchIssue.Truncated), retried.sources.single().issues)
assertEquals(4, factory.detailCalls.size)
}
@Test
fun searchesEveryCompatibleSourceWithBoundedConcurrencyAndIndependentTimeouts() = runTest {
val db = database()
var active = 0
var peak = 0
val factory = MigrationTestFactory(search = { source, query, _ ->
active++
peak = maxOf(peak, active)
try {
delay(if (source.id == 2L) 100 else 5)
SourceListing(listOf(RemoteManga(query, "/title")), false)
} finally { active-- }
})
val service = service(db, factory, MigrationSearchLimits(parallelSources = 2, sourceTimeoutMillis = 20))
service.start(1, listOf(2, 3, 4, 5, 6), listOf(10))
runCurrent()
advanceTimeBy(21)
runCurrent()
val item = checkNotNull(service.progress.value).items.single()
assertEquals(2, peak)
assertEquals(5, factory.searchCalls.size)
assertEquals(setOf(MigrationSearchIssue.TimedOut), item.sources.first().issues)
assertEquals(4, item.candidates.size)
assertTrue(db.manga(10)?.favorite == true)
}
@Test
fun cancellationStopsDiscoveryAndNeverStartsTransfer() = runTest {
val db = database()
val factory = MigrationTestFactory(search = { _, _, _ -> delay(1000); SourceListing(emptyList(), false) })
val service = service(db, factory)
service.start(1, listOf(2, 3), listOf(10))
runCurrent()
service.cancel()
runCurrent()
assertEquals(MigrationPhase.Cancelled, service.progress.value?.phase)
assertTrue(db.manga(10)?.favorite == true)
assertEquals("Private Title", db.manga(10)?.privateNote)
assertTrue(factory.detailCalls.isEmpty())
service.commitSelected()
runCurrent()
assertEquals(1, db.mangas().size)
}
@Test
fun unavailableDestinationAtCommitFailsWithoutUnfavoritingTheOriginal() = runTest {
val db = database()
val service = service(db, MigrationTestFactory())
service.start(1, listOf(2), listOf(10))
runCurrent()
db.upsertSource(checkNotNull(db.source(2)).copy(isAdded = false))
service.commitSelected()
runCurrent()
assertEquals(1, service.progress.value?.failed)
assertEquals(0, service.progress.value?.migrated)
assertTrue(db.manga(10)?.favorite == true)
assertEquals(1, db.mangas().size)
service.retry(10)
runCurrent()
val retried = checkNotNull(service.progress.value).items.single()
assertTrue(retried.candidates.isEmpty())
assertEquals(setOf(MigrationSearchIssue.Failed), retried.sources.single().issues)
}
@Test
fun failedOrCancelledTransferLeavesTheOriginalFavoriteAndItsProgressIntact() = runTest {
for (cancel in listOf(false, true)) {
val db = database()
val delegate = DefaultYokanRepository(db)
lateinit var service: MigrationService
val repository = object : YokanRepository by delegate {
override fun setMangaCategories(mangaId: Long, categories: List<Long>, favorite: Boolean) {
if (cancel) service.cancel() else error("Cannot transfer categories")
}
}
service = MigrationService(repository, db, MigrationTestFactory(), SettingsStore(repository, backgroundScope, {}), backgroundScope,
workDispatcher = StandardTestDispatcher(testScheduler))
service.start(1, listOf(2), listOf(10))
runCurrent()
service.commitSelected()
runCurrent()
assertEquals(if (cancel) MigrationPhase.Cancelled else MigrationPhase.Completed, service.progress.value?.phase)
assertEquals(0, service.progress.value?.migrated)
assertTrue(db.manga(10)?.favorite == true)
assertEquals("Private Title", db.manga(10)?.privateNote)
assertTrue(db.chapters(10).single().isRead)
assertTrue(db.chapters(10).single().isBookmarked)
}
}
@Test
fun parentDeadlinePropagatesInsteadOfBecomingAnOrdinarySourceTimeout() = runTest {
val db = database()
val repository = DefaultYokanRepository(db)
val factory = MigrationTestFactory(search = { _, _, _ -> delay(1000); SourceListing(emptyList(), false) })
val planner = MigrationPlanner(db, factory, MigrationSearchLimits(sourceTimeoutMillis = 500))
assertFailsWith<TimeoutCancellationException> {
withTimeout(5) { planner.discover(checkNotNull(repository.manga(10)), listOf(checkNotNull(repository.source(2)))) }
}
}
@Test
fun aliasesDeduplicateCandidateFetchesAndCacheDetailsForTheRun() = runTest {
val db = database()
val repository = DefaultYokanRepository(db)
val factory = MigrationTestFactory()
val planner = MigrationPlanner(db, factory, MigrationSearchLimits())
val original = checkNotNull(repository.manga(10)).copy(alternativeTitles = listOf("Alias", "TITLE"))
val destinations = listOf(checkNotNull(repository.source(2)))
planner.discover(original, destinations)
planner.discover(original, destinations)
assertEquals(4, factory.searchCalls.size)
assertEquals(1, factory.detailCalls.size)
}
}
internal class MigrationTestFactory(
private val search: suspend (DbSource, String, Int) -> SourceListing = { _, query, _ -> SourceListing(listOf(RemoteManga(query, "/title")), false) },
private val detail: suspend (DbSource, String) -> RemoteDetail = { _, url -> RemoteDetail("Title", url) },
) : ExtensionRuntimeFactory {
val searchCalls = mutableListOf<Triple<Long, String, Int>>()
val detailCalls = mutableListOf<Pair<Long, String>>()
override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {
override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing {
searchCalls += Triple(source.id, query, page)
return this@MigrationTestFactory.search(source, query, page)
}
override suspend fun detail(url: String): RemoteDetail {
detailCalls += source.id to url
return this@MigrationTestFactory.detail(source, url)
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/CatalogEnrollmentViewModelTest.kt
- Source · test / fixture · 182 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
24: class CatalogEnrollmentViewModelTest {
34: private fun TestScope.model(actions: FakeActions) =
38: fun draftParsingNeverStartsEnrollment() = runTest {
51: fun confirmationAndValidCodeGateEnrollment() = runTest {
72: fun sheetProjectionOnlyReviewsAfterExplicitReviewAction() = runTest {
89: fun explicitSuccessTransitionsFromEnrollmentToPreviewToInstall() = runTest {
106: fun refreshFailureClearsPreviewAndProvidesTypedRetry() = runTest {
123: fun conflictInvalidatesPreviewAndRequiresRefresh() = runTest {
138: fun cancellationIsNotMappedToAnError() = runTest {
149: private fun TestScope.confirmed(actions: FakeActions): CatalogEnrollmentViewModel = model(actions).also {
154: private class FakeActions(
166: override suspend fun enroll(proposal: CatalogEnrollmentCode): RecipeCatalogEnrollmentServiceResult {
171: override suspend fun refresh(proposal: CatalogEnrollmentCode): RecipeCatalogRefreshResult {
177: override suspend fun install(proposal: CatalogEnrollmentCode, stableId: String): RecipeCatalogInstallServiceResult {
Exact file bytes / download · SHA-256 abc8e6a7e9693c64c07bc51bf2c65073c8771009f1e135ce57dd4e755318e755.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.services.extensions.recipe.CatalogEnrollmentCode
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogEnrollmentServiceResult
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogInstallServiceResult
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogPreview
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogPreviewArtifact
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogRefreshError
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogRefreshResult
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.TestScope
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNull
@OptIn(ExperimentalCoroutinesApi::class)
class CatalogEnrollmentViewModelTest {
private companion object {
const val code = "yokan-catalog:v1:catalog.primary:aHR0cHM6Ly9jYXRhbG9nLmV4YW1wbGUudGVzdC9jYXRhbG9nLnlyYw:key-01:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"
val preview = RecipeCatalogPreview("catalog.primary", 1, 1_700_000_600, listOf(RecipeCatalogPreviewArtifact("recipe.one", "1.0", 42)))
}
private val host = ViewModelTestHost()
@AfterTest fun tearDown() = host.close()
private fun TestScope.model(actions: FakeActions) =
host.create { CatalogEnrollmentViewModel(actions, StandardTestDispatcher(testScheduler)) }
@Test
fun draftParsingNeverStartsEnrollment() = runTest {
val actions = FakeActions()
val model = model(actions)
model.updateDraft(code)
assertEquals(0, actions.enrollCalls)
assertEquals(0, actions.refreshCalls)
assertEquals("catalog.primary", model.state.value.review?.catalogId)
assertEquals(false, model.state.value.trustConfirmed)
}
@Test
fun confirmationAndValidCodeGateEnrollment() = runTest {
val actions = FakeActions()
val model = model(actions)
model.enroll()
assertEquals(CatalogEnrollmentDisplayError.InvalidCode, model.state.value.error)
model.updateDraft("not a code")
assertEquals(CatalogEnrollmentDisplayError.InvalidCode, model.state.value.error)
model.updateDraft(code)
model.enroll()
assertEquals(CatalogEnrollmentDisplayError.ConfirmationRequired, model.state.value.error)
assertEquals(0, actions.enrollCalls)
model.setTrustConfirmed(true)
model.enroll()
advanceUntilIdle()
assertEquals(1, actions.enrollCalls)
assertNull(model.state.value.error)
}
@Test
fun sheetProjectionOnlyReviewsAfterExplicitReviewAction() = runTest {
val actions = FakeActions()
val model = model(actions)
model.updateDraft(code)
assertIs<SignedCatalogStage.Paste>(model.state.value.toSignedCatalogSheetState().stage)
model.reviewDraft()
model.setTrustConfirmed(true)
assertIs<SignedCatalogStage.Review>(model.state.value.toSignedCatalogSheetState().stage)
assertEquals(0, actions.enrollCalls)
model.enroll(); advanceUntilIdle()
assertIs<SignedCatalogStage.Enrolled>(model.state.value.toSignedCatalogSheetState().stage)
}
@Test
fun explicitSuccessTransitionsFromEnrollmentToPreviewToInstall() = runTest {
val actions = FakeActions()
val model = confirmed(actions)
model.enroll(); advanceUntilIdle()
model.refresh(); advanceUntilIdle()
assertEquals(preview, model.state.value.preview)
model.install("recipe.one"); advanceUntilIdle()
assertEquals(1, actions.enrollCalls)
assertEquals(1, actions.refreshCalls)
assertEquals(listOf("recipe.one"), actions.installs)
assertNull(model.state.value.error)
assertNull(model.state.value.operation)
}
@Test
fun refreshFailureClearsPreviewAndProvidesTypedRetry() = runTest {
val actions = FakeActions()
val model = confirmed(actions)
model.refresh(); advanceUntilIdle()
actions.refreshResult = RecipeCatalogRefreshResult.Rejected(RecipeCatalogRefreshError.DownloadFailed)
model.refresh(); advanceUntilIdle()
assertNull(model.state.value.preview)
assertEquals(CatalogEnrollmentDisplayError.RefreshRejected, model.state.value.error)
assertEquals(CatalogEnrollmentRetry.Refresh, model.state.value.retry)
model.dismissError()
assertNull(model.state.value.error)
assertNull(model.state.value.retry)
}
@Test
fun conflictInvalidatesPreviewAndRequiresRefresh() = runTest {
val actions = FakeActions(installResult = RecipeCatalogInstallServiceResult.Conflict)
val model = confirmed(actions)
model.refresh(); advanceUntilIdle()
model.install("recipe.one"); advanceUntilIdle()
assertNull(model.state.value.preview)
assertEquals(CatalogEnrollmentDisplayError.RefreshRequired, model.state.value.error)
assertEquals(CatalogEnrollmentRetry.Refresh, model.state.value.retry)
model.retry(); advanceUntilIdle()
assertEquals(2, actions.refreshCalls)
}
@Test
fun cancellationIsNotMappedToAnError() = runTest {
val actions = FakeActions().also { it.cancelRefresh = true }
val model = confirmed(actions)
model.refresh(); advanceUntilIdle()
assertNull(model.state.value.error)
assertNull(model.state.value.operation)
assertEquals(1, actions.refreshCalls)
}
private fun TestScope.confirmed(actions: FakeActions): CatalogEnrollmentViewModel = model(actions).also {
it.updateDraft(code)
it.setTrustConfirmed(true)
}
private class FakeActions(
var enrollResult: RecipeCatalogEnrollmentServiceResult = RecipeCatalogEnrollmentServiceResult.Created,
var refreshResult: RecipeCatalogRefreshResult = RecipeCatalogRefreshResult.Available(preview),
var installResult: RecipeCatalogInstallServiceResult = RecipeCatalogInstallServiceResult.Applied(
eu.friedcutlet.yokan.services.extensions.recipe.InstalledRecipeRecord("catalog.primary", "recipe.one", 1, "1.0", "0".repeat(64), 1, byteArrayOf(0)),
),
) : CatalogEnrollmentActions {
var enrollCalls = 0
var refreshCalls = 0
val installs = mutableListOf<String>()
var cancelRefresh = false
override suspend fun enroll(proposal: CatalogEnrollmentCode): RecipeCatalogEnrollmentServiceResult {
enrollCalls++
return enrollResult
}
override suspend fun refresh(proposal: CatalogEnrollmentCode): RecipeCatalogRefreshResult {
refreshCalls++
if (cancelRefresh) throw CancellationException("cancelled")
return refreshResult
}
override suspend fun install(proposal: CatalogEnrollmentCode, stableId: String): RecipeCatalogInstallServiceResult {
installs += stableId
return installResult
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GenreSearchTest.kt
- Source · test / fixture · 45 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
10: class GenreSearchTest {
Exact file bytes / download · SHA-256 bbb713c02035782db31c60623c903f5f309ef57482b230cdc39aeba328c41748.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import kotlin.test.Test
import kotlin.test.assertEquals
import eu.friedcutlet.yokan.services.extensions.FilterEntry
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceFilterKind
class GenreSearchTest {
@Test fun multiSelectUsesExtensionValueAndClearsTheTextQuery() {
val request = genreSearchRequest("Action", listOf(SourceFilter("genres", "Genres", "Group", SourceFilterKind.MultiSelect, listOf(FilterEntry("Action", "17")))))
assertEquals("", request.query)
assertEquals(mapOf("genres" to FilterSelection.Multi(setOf("17"))), request.selections)
}
@Test fun individualGenreTogglesAndTriStatesIncludeTheGenre() {
val filters = listOf(
SourceFilter("a", "Genres: Action", "CheckBox", SourceFilterKind.Toggle),
SourceFilter("b", "Genres/Action", "TriState", SourceFilterKind.TriState),
)
assertEquals(mapOf("a" to FilterSelection.Toggle(true)), genreSearchRequest(" action ", filters.take(1)).selections)
assertEquals(mapOf("b" to FilterSelection.TriState(1)), genreSearchRequest(" action ", filters.drop(1)).selections)
}
@Test fun neverSelectsAnExclusionGroupWithTheSameGenre() {
val entries = listOf(FilterEntry("Action", "17"))
val filters = listOf(
SourceFilter("exclude", "Exclude genres", "Group", SourceFilterKind.MultiSelect, entries),
SourceFilter("include", "Genres", "Group", SourceFilterKind.MultiSelect, entries),
)
assertEquals(mapOf("include" to FilterSelection.Multi(setOf("17"))), genreSearchRequest("Action", filters).selections)
}
@Test fun singleSelectMatchesLabelsCaseInsensitively() {
val request = genreSearchRequest("SCI-FI", listOf(SourceFilter("genre", "Genre", "Select", SourceFilterKind.SingleSelect, listOf(FilterEntry("Sci-Fi", "science_fiction")))))
assertEquals(FilterSelection.Single("science_fiction"), request.selections["genre"])
}
@Test fun unsupportedGenreFallsBackToTextWithoutChangingUnrelatedFilters() {
val request = genreSearchRequest("Action", listOf(SourceFilter("sort", "Sort", "Select", SourceFilterKind.SingleSelect, listOf(FilterEntry("Latest", "0")))))
assertEquals("Action", request.query)
assertEquals(emptyMap(), request.selections)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SavedSearchesAndSourceBadgeTest.kt
- Source · test / fixture · 65 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
13: class SavedSearchesAndSourceBadgeTest {
17: fun savedSearchSerializesAndDeserializes() {
25: fun settingsPreservesSavedSearchesList() {
41: fun libraryShowSourceDefaultsToFalseAndConfiguresIndependently() {
58: fun userSettingsMapsLibraryShowSource() {
Exact file bytes / download · SHA-256 4be6f03fc72f92d7cd38c8c6fbe97f9faf12e47b8ec8550131794c0aebba1b07.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.UserSettings
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class SavedSearchesAndSourceBadgeTest {
private val json = Json { ignoreUnknownKeys = true; prettyPrint = false }
@Test
fun savedSearchSerializesAndDeserializes() {
val search = DbSavedSearch(sourceId = 42L, name = "Action Fantasy", query = "genre:action genre:fantasy")
val encoded = json.encodeToString(DbSavedSearch.serializer(), search)
val decoded = json.decodeFromString(DbSavedSearch.serializer(), encoded)
assertEquals(search, decoded)
}
@Test
fun settingsPreservesSavedSearchesList() {
val settings = DbSettings(
savedSearches = listOf(
DbSavedSearch(sourceId = 1L, name = "Isekai", query = "isekai"),
DbSavedSearch(sourceId = 1L, name = "Romance", query = "romcom"),
DbSavedSearch(sourceId = 2L, name = "Sci-Fi", query = "mecha"),
),
)
val encoded = json.encodeToString(DbSettings.serializer(), settings)
val decoded = json.decodeFromString(DbSettings.serializer(), encoded)
assertEquals(3, decoded.savedSearches?.size)
assertEquals("Isekai", decoded.savedSearches?.get(0)?.name)
assertEquals("Sci-Fi", decoded.savedSearches?.get(2)?.name)
}
@Test
fun libraryShowSourceDefaultsToFalseAndConfiguresIndependently() {
val settings = DbSettings()
assertFalse(settings.libraryShowSource)
assertFalse(settings.animeLibraryShowSource)
assertFalse(settings.novelLibraryShowSource)
val updated = settings.copy(
libraryShowSource = true,
animeLibraryShowSource = false,
novelLibraryShowSource = true,
)
assertTrue(updated.libraryShowSource)
assertFalse(updated.animeLibraryShowSource)
assertTrue(updated.novelLibraryShowSource)
}
@Test
fun userSettingsMapsLibraryShowSource() {
val userSettings = UserSettings(libraryShowSource = true)
assertTrue(userSettings.libraryShowSource)
val defaultUserSettings = UserSettings()
assertFalse(defaultUserSettings.libraryShowSource)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogSheetStateTest.kt
- Source · test / fixture · 54 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
9: class SignedCatalogSheetStateTest {
14: fun enrollmentRequiresExplicitTrustAndIdleState() {
26: fun failedOrRunningRefreshNeverOffersRetainedPreview() {
43: fun previewOwnsItsRowsAndBlockedInstallsRequireRefresh() {
Exact file bytes / download · SHA-256 44844b0d3b17ef961c509ee432dd219b1d33e2e690b15572fedadcd4f7b89f66.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class SignedCatalogSheetStateTest {
private val identity = SignedCatalogIdentity("catalog", "https://example.org/catalog", "key", "fingerprint")
private val preview = SignedCatalogPreview("1", "Tomorrow", listOf(SignedCatalogRecipe("recipe", "1", "1 KB")))
@Test
fun enrollmentRequiresExplicitTrustAndIdleState() {
val review = SignedCatalogSheetState(SignedCatalogStage.Review(identity))
assertFalse(review.canEnroll)
val confirmed = review.copy(stage = SignedCatalogStage.Review(identity, trustConfirmed = true))
assertTrue(confirmed.canEnroll)
assertFalse(confirmed.copy(operation = SignedCatalogOperation.Enrolling).canEnroll)
assertFalse(confirmed.copy(stage = SignedCatalogStage.Review(identity, true, SignedCatalogError.TrustMismatch)).canEnroll)
assertFalse(SignedCatalogSheetState().canReview)
assertTrue(SignedCatalogSheetState(SignedCatalogStage.Paste("pasted code")).canReview)
}
@Test
fun failedOrRunningRefreshNeverOffersRetainedPreview() {
val enrolled = SignedCatalogStage.Enrolled(identity, preview = preview)
val state = SignedCatalogSheetState(enrolled)
assertTrue(state.canInstall("recipe"))
assertFalse(state.canInstall("unknown"))
for (error in SignedCatalogError.entries) {
val failed = state.copy(stage = enrolled.copy(refreshError = error))
assertNull(failed.verifiedPreview)
assertFalse(failed.canInstall("recipe"))
}
val refreshing = state.copy(operation = SignedCatalogOperation.Refreshing)
assertNull(refreshing.verifiedPreview)
assertFalse(refreshing.canInstall("recipe"))
assertFalse(state.copy(operation = SignedCatalogOperation.Installing("recipe")).canInstall("recipe"))
}
@Test
fun previewOwnsItsRowsAndBlockedInstallsRequireRefresh() {
val rows = mutableListOf(SignedCatalogRecipe("recipe", "1", "1 KB", error = SignedCatalogError.Conflict))
val snapshot = SignedCatalogPreview("1", "Tomorrow", rows)
rows.clear()
assertEquals(1, snapshot.size)
assertFalse(SignedCatalogSheetState(SignedCatalogStage.Enrolled(identity, preview = snapshot)).canInstall("recipe"))
for (status in listOf(SignedCatalogRecipeStatus.Installed, SignedCatalogRecipeStatus.AlreadyInstalled)) {
val installed = SignedCatalogPreview("1", "Tomorrow", listOf(SignedCatalogRecipe("recipe", "1", "1 KB", status)))
assertFalse(SignedCatalogSheetState(SignedCatalogStage.Enrolled(identity, preview = installed)).canInstall("recipe"))
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeViewModelTest.kt
- Source · test / fixture · 347 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
42: class SourceHomeViewModelTest {
46: fun setUp() = Dispatchers.setMain(dispatcher)
49: fun tearDown() = Dispatchers.resetMain()
51: private class Entry : ViewModelStoreOwner {
55: private fun repository(): YokanRepository {
62: private fun Entry.sourceHome(
95: private fun CoroutineScope.settings(repository: YokanRepository) = SettingsStore(repository, this) {}
98: fun reopeningAClosedSourceInTheSameProfileRestoresItsListingWithoutReloading() = runTest(dispatcher) {
126: fun cacheKeepsTheMostRecentlyClosedSources() {
141: fun libraryOverlayFollowsFavouriteChanges() = runTest(dispatcher) {
154: fun presetsAreScopedAndRequireExplicitReplacementWhileRetainingTheirId() = runTest(dispatcher) {
190: fun filterOnlyPresetRestoresAcrossRestartAndTriggersExactlyOneFreshSearch() = runTest(dispatcher) {
234: fun incompatiblePresetDoesNotSearchUntilItsAvailableFiltersAreReviewed() = runTest(dispatcher) {
264: fun updateCancelAndRenameCollisionPreservePresetIdentityAndData() = runTest(dispatcher) {
293: fun applyingRefetchesSchemaAndCanRetryAfterAProviderFailure() = runTest(dispatcher) {
327: fun legacySavedQueryReplacesCurrentFilters() = runTest(dispatcher) {
Exact file bytes / download · SHA-256 7ab66c5855436f3ff4ea88255c3b2ffe0b1a6888d89ccc1926fd4145bbb1116d.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import eu.friedcutlet.yokan.app.profiles.ProfileSession
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceFilterKind
import eu.friedcutlet.yokan.services.extensions.FilterEntry
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.database.decodeDatabaseSnapshot
import eu.friedcutlet.yokan.database.encodeDatabaseSnapshot
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.services.extensions.SourceListing
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
@OptIn(ExperimentalCoroutinesApi::class)
class SourceHomeViewModelTest {
private val dispatcher = UnconfinedTestDispatcher()
@BeforeTest
fun setUp() = Dispatchers.setMain(dispatcher)
@AfterTest
fun tearDown() = Dispatchers.resetMain()
private class Entry : ViewModelStoreOwner {
override val viewModelStore = ViewModelStore()
}
private fun repository(): YokanRepository {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
database.upsertSource(DbSource(id = SourceId, name = "Src", lang = "en", isAdded = true))
database.upsertSource(DbSource(id = OtherSourceId, name = "Other", lang = "en", isAdded = true))
return DefaultYokanRepository(database)
}
private fun Entry.sourceHome(
repository: YokanRepository,
settings: SettingsStore,
cache: SourceHomeCache,
genre: String? = null,
filters: List<SourceFilter> = emptyList(),
filterProvider: suspend () -> List<SourceFilter> = { filters },
onRequest: (SourceTab, String, Int, List<SourceFilter>) -> Unit = { _, _, _, _ -> },
onLoad: () -> Unit = {},
): SourceHomeViewModel = ViewModelProvider.create(
this,
viewModelFactory {
initializer {
SourceHomeViewModel(
sourceId = SourceId,
genre = genre,
repository = repository,
settings = settings,
healPayload = {},
cache = cache,
loadListing = { _, tab, query, page, schema ->
onRequest(tab, query, page, schema)
onLoad()
RuntimeLoad(SourceListing(listOf(RemoteManga("$tab $query $page", "/$tab/$query/$page")), hasNextPage = true))
},
loadFilters = { filterProvider() },
loadLatestSupport = { true },
workDispatcher = dispatcher,
)
}
},
)[SourceHomeViewModel::class]
private fun CoroutineScope.settings(repository: YokanRepository) = SettingsStore(repository, this) {}
@Test
fun reopeningAClosedSourceInTheSameProfileRestoresItsListingWithoutReloading() = runTest(dispatcher) {
val repository = repository()
val settings = backgroundScope.settings(repository)
// Each Source Home route reads the cache from the profile session, as SourceHomeRoute does.
val owner = ProfileSession(ProfileId.Default, databaseFactory = { error("Unused database") }, dispatcher = dispatcher)
var loads = 0
val first = Entry()
val home = first.sourceHome(repository, settings, owner.sourceHomeCache) { loads++ }
home.selectListing(SourceTab.Latest)
home.state.first { it.loadedKey?.tab == SourceTab.Latest }
first.viewModelStore.clear()
val reopened = Entry().sourceHome(repository, settings, owner.sourceHomeCache) { loads++ }
assertEquals(SourceTab.Latest, reopened.state.value.selectedTab)
assertEquals(listOf("/Latest//1"), reopened.state.value.items.map { it.url })
assertEquals(2, loads)
// A genre search is a different home: it runs its own request.
val genre = Entry().sourceHome(repository, settings, owner.sourceHomeCache, genre = " Action ") { loads++ }
val loaded = genre.state.first { it.loadedKey != null }
assertEquals(SourceTab.Search, loaded.selectedTab)
assertEquals(listOf("/Search/Action/1"), loaded.items.map { it.url })
assertEquals(3, loads)
owner.close()
}
@Test
fun cacheKeepsTheMostRecentlyClosedSources() {
val cache = SourceHomeCache(capacity = 2)
val state = SourceHomeUiState(source = null)
cache.put(1, null, state)
cache.put(2, null, state)
cache.put(1, null, state)
cache.put(3, "Action", state)
assertNull(cache.get(2, null))
assertEquals(state, cache.get(1, null))
assertEquals(state, cache.get(3, "Action"))
assertNull(cache.get(3, null))
}
@Test
fun libraryOverlayFollowsFavouriteChanges() = runTest(dispatcher) {
val repository = repository()
val home = Entry().sourceHome(repository, backgroundScope.settings(repository), SourceHomeCache(capacity = 5))
val source = repository.source(SourceId)!!
repository.upsertRemoteTitle(source, RemoteManga("Title", "/title"), favorite = true)
home.state.first { "/title" in it.libraryLinks }
repository.upsertRemoteTitle(source, RemoteManga("Title", "/title"), favorite = false)
home.state.first { "/title" !in it.libraryLinks }
}
@Test
fun presetsAreScopedAndRequireExplicitReplacementWhileRetainingTheirId() = runTest(dispatcher) {
val repository = repository()
val settings = backgroundScope.settings(repository)
val other = DbSavedSearch(sourceId = OtherSourceId, name = "Preset", query = "other")
settings.updateDb { it.copy(savedSearches = listOf(other)) }
val home = Entry().sourceHome(repository, settings, SourceHomeCache(capacity = 5))
home.state.first { it.filterSchemaReady }
home.setSearchQuery(" typed but unsubmitted ")
home.onPresetEvent(SourcePresetEvent.SaveCurrent)
home.onPresetEvent(SourcePresetEvent.NameChanged("Preset"))
home.onPresetEvent(SourcePresetEvent.Commit())
val saved = home.state.first { it.savedSearches.size == 1 }.savedSearches.single()
assertEquals("typed but unsubmitted", saved.query)
assertNotNull(saved.sourceIdentity)
assertTrue(saved.filterSchemaRecorded)
home.setSearchQuery("new query")
home.onPresetEvent(SourcePresetEvent.SaveCurrent)
home.onPresetEvent(SourcePresetEvent.NameChanged("Preset"))
home.onPresetEvent(SourcePresetEvent.Commit())
assertEquals(saved.id, home.state.value.presetEditor?.conflictId)
assertEquals(saved, home.state.value.savedSearches.single())
home.onPresetEvent(SourcePresetEvent.Commit(replace = true))
val updated = home.state.first { it.savedSearches.single().query == "new query" }.savedSearches.single()
assertEquals(saved.id, updated.id)
home.onPresetEvent(SourcePresetEvent.Rename(saved.id))
home.onPresetEvent(SourcePresetEvent.NameChanged("Renamed"))
home.onPresetEvent(SourcePresetEvent.Commit())
val renamed = home.state.first { it.savedSearches.single().name == "Renamed" }.savedSearches.single()
assertEquals(updated.copy(name = "Renamed"), renamed)
home.onPresetEvent(SourcePresetEvent.Delete(saved.id))
home.state.first { it.savedSearches.isEmpty() }
assertEquals(listOf(other), settings.db.value.savedSearches)
}
@Test
fun filterOnlyPresetRestoresAcrossRestartAndTriggersExactlyOneFreshSearch() = runTest(dispatcher) {
val filter = SourceFilter("genre", "Genre", "GroupFilter", SourceFilterKind.MultiSelect,
entries = listOf(FilterEntry("Action", "action"), FilterEntry("Drama", "drama")), hasStableId = true)
val repo = repository()
val settings = backgroundScope.settings(repo)
val home = Entry().sourceHome(repo, settings, SourceHomeCache(5), filters = listOf(filter))
home.state.first { it.filterSchemaReady }
home.setFilterSelection("genre", FilterSelection.Multi(setOf("action")))
home.onPresetEvent(SourcePresetEvent.SaveCurrent)
home.onPresetEvent(SourcePresetEvent.NameChanged("Action only"))
home.onPresetEvent(SourcePresetEvent.Commit())
val a = home.state.first { it.savedSearches.size == 1 }.savedSearches.single()
home.setSearchQuery("drama query")
home.setFilterSelection("genre", FilterSelection.Multi(setOf("drama")))
home.onPresetEvent(SourcePresetEvent.SaveCurrent)
home.onPresetEvent(SourcePresetEvent.NameChanged("Drama"))
home.onPresetEvent(SourcePresetEvent.Commit())
home.state.first { it.savedSearches.size == 2 }
val restarted = DefaultYokanRepository(InMemoryYokanDatabase(checkNotNull(decodeDatabaseSnapshot(encodeDatabaseSnapshot(repo.snapshots.value)))))
val requests = mutableListOf<Pair<String, List<SourceFilter>>>()
val reopened = Entry().sourceHome(restarted, backgroundScope.settings(restarted), SourceHomeCache(5), filters = listOf(filter),
onRequest = { tab, query, _, schema -> if (tab == SourceTab.Search) requests += query to schema })
reopened.state.first { it.filterSchemaReady && !it.loading }
reopened.setSearchQuery("previous query")
reopened.submitSearch()
reopened.state.first { it.loadedKey?.query == "previous query" }
reopened.loadMore()
reopened.state.first { it.page == 2 }
val before = requests.size
reopened.onPresetEvent(SourcePresetEvent.Apply(a.id))
val applied = reopened.state.first { it.loadedKey?.revision == 1L }
assertEquals(1, requests.size - before)
assertEquals("", applied.searchQuery)
assertEquals("", requests.last().first)
assertEquals(FilterSelection.Multi(setOf("action")), requests.last().second.single().selection)
assertEquals(1, applied.page)
assertEquals(listOf("/Search//1"), applied.items.map { it.url })
reopened.onPresetEvent(SourcePresetEvent.Apply(a.id))
reopened.state.first { it.loadedKey?.revision == 2L }
assertEquals(2, requests.size - before, "Applying the same preset should perform one refresh")
}
@Test
fun incompatiblePresetDoesNotSearchUntilItsAvailableFiltersAreReviewed() = runTest(dispatcher) {
val original = SourceFilter("old", "Old genre", "Toggle", SourceFilterKind.Toggle, hasStableId = true)
val repo = repository()
val settings = backgroundScope.settings(repo)
val first = Entry().sourceHome(repo, settings, SourceHomeCache(5), filters = listOf(original))
first.state.first { it.filterSchemaReady }
first.setFilterSelection("old", FilterSelection.Toggle(true))
first.onPresetEvent(SourcePresetEvent.SaveCurrent)
first.onPresetEvent(SourcePresetEvent.NameChanged("Saved"))
first.onPresetEvent(SourcePresetEvent.Commit())
val saved = first.state.first { it.savedSearches.isNotEmpty() }.savedSearches.single()
var searches = 0
val changed = Entry().sourceHome(repo, settings, SourceHomeCache(5), filters = emptyList(),
onRequest = { tab, _, _, _ -> if (tab == SourceTab.Search) searches++ })
changed.state.first { it.filterSchemaReady }
changed.onPresetEvent(SourcePresetEvent.Apply(saved.id))
assertNotNull(changed.state.value.presetReview)
assertEquals(0, searches)
changed.onPresetEvent(SourcePresetEvent.CancelReview)
assertEquals(SourceTab.Popular, changed.state.value.selectedTab)
changed.onPresetEvent(SourcePresetEvent.Apply(saved.id))
changed.onPresetEvent(SourcePresetEvent.ReviewFilters)
assertEquals(true, changed.state.value.reviewFiltersRequested)
assertEquals(0, searches)
changed.applyFilters()
changed.state.first { it.loadedKey?.tab == SourceTab.Search }
assertEquals(1, searches)
}
@Test
fun updateCancelAndRenameCollisionPreservePresetIdentityAndData() = runTest(dispatcher) {
val repo = repository()
val settings = backgroundScope.settings(repo)
val home = Entry().sourceHome(repo, settings, SourceHomeCache(5))
home.state.first { it.filterSchemaReady }
for (name in listOf("First", "Second")) {
home.onPresetEvent(SourcePresetEvent.SaveCurrent)
home.onPresetEvent(SourcePresetEvent.NameChanged(name))
home.onPresetEvent(SourcePresetEvent.Commit())
}
val saved = home.state.first { it.savedSearches.size == 2 }.savedSearches.first { it.name == "First" }
home.setSearchQuery("updated query")
home.onPresetEvent(SourcePresetEvent.Update(saved.id))
home.onPresetEvent(SourcePresetEvent.CancelEdit)
assertEquals(saved, home.state.value.savedSearches.first { it.id == saved.id })
home.onPresetEvent(SourcePresetEvent.Update(saved.id))
home.onPresetEvent(SourcePresetEvent.Commit())
val updated = home.state.first { it.savedSearches.first { p -> p.id == saved.id }.query == "updated query" }
.savedSearches.first { it.id == saved.id }
assertEquals("First", updated.name)
home.onPresetEvent(SourcePresetEvent.Rename(saved.id))
home.onPresetEvent(SourcePresetEvent.NameChanged("Second"))
home.onPresetEvent(SourcePresetEvent.Commit(replace = true))
assertNotNull(home.state.value.presetEditor?.conflictId)
assertEquals(updated, home.state.value.savedSearches.first { it.id == saved.id })
assertEquals(2, home.state.value.savedSearches.size)
}
@Test
fun applyingRefetchesSchemaAndCanRetryAfterAProviderFailure() = runTest(dispatcher) {
val repo = repository()
val settings = backgroundScope.settings(repo)
val filter = SourceFilter("check", "Check", "Toggle", hasStableId = true)
var schema = listOf(filter)
var fail = false
var requests = 0
val home = Entry().sourceHome(repo, settings, SourceHomeCache(5),
filterProvider = { if (fail) error("Unavailable") else schema },
onRequest = { tab, _, _, _ -> if (tab == SourceTab.Search) requests++ })
home.state.first { it.filterSchemaReady }
home.setFilterSelection("check", FilterSelection.Toggle(true))
home.onPresetEvent(SourcePresetEvent.SaveCurrent)
home.onPresetEvent(SourcePresetEvent.NameChanged("Saved"))
home.onPresetEvent(SourcePresetEvent.Commit())
val saved = home.state.first { it.savedSearches.isNotEmpty() }.savedSearches.single()
schema = emptyList()
home.onPresetEvent(SourcePresetEvent.Apply(saved.id))
assertNotNull(home.state.value.presetReview)
assertEquals(0, requests)
home.onPresetEvent(SourcePresetEvent.CancelReview)
fail = true
home.onPresetEvent(SourcePresetEvent.Apply(saved.id))
assertEquals(eu.friedcutlet.yokan.services.extensions.PresetIssueReason.SchemaUnavailable,
home.state.value.presetReview?.validation?.issues?.single()?.reason)
assertEquals(0, requests)
fail = false
schema = listOf(filter)
home.onPresetEvent(SourcePresetEvent.Apply(saved.id))
home.state.first { it.loadedKey?.revision == 1L }
assertEquals(1, requests)
}
@Test
fun legacySavedQueryReplacesCurrentFilters() = runTest(dispatcher) {
val repo = repository()
val settings = backgroundScope.settings(repo)
val old = DbSavedSearch(SourceId, "Legacy", "legacy query")
settings.updateDb { it.copy(savedSearches = listOf(old)) }
val filter = SourceFilter("check", "Check", "Toggle")
val home = Entry().sourceHome(repo, settings, SourceHomeCache(5), filters = listOf(filter))
home.state.first { it.filterSchemaReady }
home.setFilterSelection("check", FilterSelection.Toggle(true))
home.applyFilters()
home.onPresetEvent(SourcePresetEvent.Apply(old.id))
val applied = home.state.first { it.loadedKey?.query == "legacy query" }
assertEquals(emptyMap(), applied.appliedFilterValues)
assertEquals(emptyMap(), applied.selectedFilterValues)
}
private companion object {
const val SourceId = 7L
const val OtherSourceId = 8L
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceLibraryHidingTest.kt
- Source · test / fixture · 153 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
34: class SourceLibraryHidingTest {
38: fun setUp() = Dispatchers.setMain(dispatcher)
41: fun tearDown() = Dispatchers.resetMain()
43: private class Entry : ViewModelStoreOwner {
47: private fun repository(): YokanRepository {
53: private fun hide(settings: SettingsStore, type: ItemType, value: Boolean) = settings.updateDb {
58: private fun Entry.sourceHome(repository: YokanRepository, settings: SettingsStore, requests: MutableList<Int>, hiddenPages: Int) =
78: fun filterIsPerMediaTypeAndKeepsNonLibraryEntries() {
91: fun togglingAndLibraryChangesRefilterWithoutRefetching() = runTest(dispatcher) {
117: fun allHiddenPageLoadsTheNextPage() = runTest(dispatcher) {
132: fun automaticPageFillsAreBounded() = runTest(dispatcher) {
Exact file bytes / download · SHA-256 7d550b9a16043ec93251e07d5d4592f3a17bb34697c7cf54a5b95fc2a71b1cb8.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbBrowsePreferences
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceListing
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
@OptIn(ExperimentalCoroutinesApi::class)
class SourceLibraryHidingTest {
private val dispatcher = UnconfinedTestDispatcher()
@BeforeTest
fun setUp() = Dispatchers.setMain(dispatcher)
@AfterTest
fun tearDown() = Dispatchers.resetMain()
private class Entry : ViewModelStoreOwner {
override val viewModelStore = ViewModelStore()
}
private fun repository(): YokanRepository {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
database.upsertSource(DbSource(id = SourceId, name = "Src", lang = "en", isAdded = true))
return DefaultYokanRepository(database)
}
private fun hide(settings: SettingsStore, type: ItemType, value: Boolean) = settings.updateDb {
it.copy(features = it.features.copy(browse = it.features.browse.withHideLibrary(type, value)))
}
/** Pages up to [hiddenPages] only contain "/fav"; later pages contain "/p<page>" and "/fav". */
private fun Entry.sourceHome(repository: YokanRepository, settings: SettingsStore, requests: MutableList<Int>, hiddenPages: Int) =
ViewModelProvider.create(this, viewModelFactory {
initializer {
SourceHomeViewModel(
sourceId = SourceId, genre = null, repository = repository, settings = settings, healPayload = {},
cache = SourceHomeCache(capacity = 5),
loadListing = { _, _, _, page, _ ->
requests += page
val items = if (page <= hiddenPages) listOf(RemoteManga("Fav", "/fav"))
else listOf(RemoteManga("P$page", "/p$page"), RemoteManga("Fav", "/fav"))
RuntimeLoad(SourceListing(items, hasNextPage = true))
},
loadFilters = { emptyList() },
loadLatestSupport = { true },
workDispatcher = dispatcher,
)
}
})[SourceHomeViewModel::class]
@Test
fun filterIsPerMediaTypeAndKeepsNonLibraryEntries() {
val items = listOf(RemoteManga("A", "/a"), RemoteManga("B", "/b"))
assertEquals(items, items.withoutLibrary(hide = false, libraryLinks = setOf("/a")))
assertEquals(listOf("/b"), items.withoutLibrary(hide = true, libraryLinks = setOf("/a")).map { it.url })
assertEquals(items, items.withoutLibrary(hide = true, libraryLinks = emptySet()))
val prefs = DbBrowsePreferences().withHideLibrary(ItemType.Anime, true)
assertTrue(prefs.hidesLibrary(ItemType.Anime))
assertFalse(prefs.hidesLibrary(ItemType.Manga))
assertFalse(prefs.hidesLibrary(ItemType.Novel))
}
@Test
fun togglingAndLibraryChangesRefilterWithoutRefetching() = runTest(dispatcher) {
val repository = repository()
val settings = SettingsStore(repository, backgroundScope) {}
val requests = mutableListOf<Int>()
val home = Entry().sourceHome(repository, settings, requests, hiddenPages = 0)
home.state.first { it.loadedKey != null }
repository.upsertRemoteTitle(repository.source(SourceId)!!, RemoteManga("Fav", "/fav"), favorite = true)
home.state.first { "/fav" in it.libraryLinks }
assertEquals(listOf("/p1", "/fav"), home.state.value.visibleItems.map { it.url })
home.setHideLibrary(true)
assertEquals(listOf("/p1"), home.state.first { it.hideLibrary }.visibleItems.map { it.url })
// Another media type's preference leaves this manga source alone.
hide(settings, ItemType.Anime, false)
assertTrue(settings.db.value.features.browse.hideLibraryManga)
repository.upsertRemoteTitle(repository.source(SourceId)!!, RemoteManga("Fav", "/fav"), favorite = false)
assertEquals(listOf("/p1", "/fav"), home.state.first { "/fav" !in it.libraryLinks }.visibleItems.map { it.url })
hide(settings, ItemType.Manga, false)
home.state.first { !it.hideLibrary }
advanceUntilIdle()
assertEquals(listOf(1), requests)
}
@Test
fun allHiddenPageLoadsTheNextPage() = runTest(dispatcher) {
val repository = repository()
val settings = SettingsStore(repository, backgroundScope) {}
repository.upsertRemoteTitle(repository.source(SourceId)!!, RemoteManga("Fav", "/fav"), favorite = true)
hide(settings, ItemType.Manga, true)
val requests = mutableListOf<Int>()
val home = Entry().sourceHome(repository, settings, requests, hiddenPages = 1)
val shown = home.state.first { it.visibleItems.isNotEmpty() }
advanceUntilIdle()
assertEquals(listOf("/p2"), shown.visibleItems.map { it.url })
assertEquals(listOf(1, 2), requests)
}
@Test
fun automaticPageFillsAreBounded() = runTest(dispatcher) {
val repository = repository()
val settings = SettingsStore(repository, backgroundScope) {}
repository.upsertRemoteTitle(repository.source(SourceId)!!, RemoteManga("Fav", "/fav"), favorite = true)
hide(settings, ItemType.Manga, true)
val requests = mutableListOf<Int>()
val home = Entry().sourceHome(repository, settings, requests, hiddenPages = Int.MAX_VALUE)
home.state.first { it.loadedKey != null }
advanceUntilIdle()
assertEquals((1..1 + MaxHiddenPageFills).toList(), requests)
assertTrue(home.state.value.visibleItems.isEmpty())
// The manual Load more tile still works after the bound.
home.loadMore()
advanceUntilIdle()
assertEquals(2 + MaxHiddenPageFills, requests.size)
}
private companion object {
const val SourceId = 77L
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresetPolicyTest.kt
- Source · test / fixture · 135 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
28: class SourcePresetPolicyTest {
44: private fun preset() = DbSavedSearch(source.id, "All", "", id = "preset-id", sourceIdentity = source.presetIdentity(),
Exact file bytes / download · SHA-256 607cc4f0f902ab45b15927c96e74c465a2922e06fb528e8106a20fa05da4f741.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.database.DbPresetSelection
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.adoptLegacySourcePresets
import eu.friedcutlet.yokan.database.presetIdentity
import eu.friedcutlet.yokan.services.extensions.FilterEntry
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.services.extensions.PresetIssueReason
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceFilterKind
import eu.friedcutlet.yokan.services.extensions.capturePresetFilters
import eu.friedcutlet.yokan.services.extensions.validateSourcePreset
import eu.friedcutlet.yokan.services.extensions.js.filtersFromJson
import eu.friedcutlet.yokan.services.extensions.js.sourceFiltersToJson
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class SourcePresetPolicyTest {
private val source = DbSource(id = 42, name = "Source", baseUrl = "https://source.test", lang = "en")
private val options = listOf(FilterEntry("A", "a"), FilterEntry("B", "b"))
private val schema = listOf(
SourceFilter("toggle", "Toggle", "CheckBox", SourceFilterKind.Toggle, hasStableId = true),
SourceFilter("single", "Single", "SelectFilter", SourceFilterKind.SingleSelect, entries = options, hasStableId = true),
SourceFilter("multi", "Multi", "GroupFilter", SourceFilterKind.MultiSelect, entries = options, hasStableId = true),
SourceFilter("tri", "Tri", "TriStateFilter", SourceFilterKind.TriState, hasStableId = true),
SourceFilter("text", "Text", "TextFilter", SourceFilterKind.Text, defaultValue = "default", hasStableId = true),
SourceFilter("sort", "Sort", "SortFilter", SourceFilterKind.Sort, entries = options, defaultValue = "a", hasStableId = true),
)
private val selections = mapOf(
"toggle" to FilterSelection.Toggle(true), "single" to FilterSelection.Single("b"),
"multi" to FilterSelection.Multi(setOf("a", "b")), "tri" to FilterSelection.TriState(-1),
"text" to FilterSelection.Text("日本語 🌙"), "sort" to FilterSelection.Sort("b", false),
)
private fun preset() = DbSavedSearch(source.id, "All", "", id = "preset-id", sourceIdentity = source.presetIdentity(),
filters = capturePresetFilters(schema, selections), filterSchemaRecorded = true)
@Test fun everySelectionKindRoundTripsWithoutChangingTheRuntimeRequest() {
val saved = preset()
val decoded = Json.decodeFromString(DbSavedSearch.serializer(), Json.encodeToString(DbSavedSearch.serializer(), saved))
val validation = validateSourcePreset(decoded, source, schema)
assertTrue(validation.issues.isEmpty())
assertEquals(selections, validation.selections)
assertEquals(sourceFiltersToJson(schema.map { it.copy(selection = selections[it.id]) }),
sourceFiltersToJson(schema.map { it.copy(selection = validation.selections[it.id]) }))
assertEquals("preset-id", decoded.copy(name = "Renamed").id)
}
@Test fun untouchedDefaultsRoundTripToTheIdenticalRequest() {
val saved = preset().copy(filters = capturePresetFilters(schema, emptyMap()))
val restored = validateSourcePreset(saved, source, schema)
assertTrue(restored.issues.isEmpty())
assertEquals(sourceFiltersToJson(schema), sourceFiltersToJson(schema.map { it.copy(selection = restored.selections[it.id]) }))
assertEquals("default", sourceFiltersToJson(schema).first { it.jsonObject["name"]?.jsonPrimitive?.content == "Text" }
.jsonObject.getValue("state").jsonPrimitive.content)
}
@Test fun sortParsingAndRequestsPreserveOptionAndDirection() {
val filters = filtersFromJson("""[{"id":"sort","name":"Sort","type_name":"SortFilter","state":{"index":1,"ascending":false},"values":["A","B"]}]""")
val sort = filters.single()
assertEquals(SourceFilterKind.Sort, sort.kind)
assertEquals("B", sort.defaultValue)
assertFalse(sort.defaultAscending)
val state = sourceFiltersToJson(filters).single().jsonObject.getValue("state").jsonObject
assertEquals(1, state.getValue("index").jsonPrimitive.int)
assertFalse(state.getValue("ascending").jsonPrimitive.boolean)
val selected = sourceFiltersToJson(listOf(sort.copy(selection = FilterSelection.Sort("A", true))))
.single().jsonObject.getValue("state").jsonObject
assertEquals(0, selected.getValue("index").jsonPrimitive.int)
assertTrue(selected.getValue("ascending").jsonPrimitive.boolean)
}
@Test fun changedOptionsTypesDefaultsAndRemovedFiltersRequireReview() {
val saved = preset()
val changed = schema.map { when (it.id) {
"single" -> it.copy(entries = options.reversed())
"text" -> it.copy(defaultValue = "changed")
"multi" -> it.copy(kind = SourceFilterKind.SingleSelect)
else -> it
} }.filter { it.id != "tri" }
val validation = validateSourcePreset(saved, source, changed)
assertEquals(setOf("Single", "Text", "Multi", "Tri"), validation.issues.map { it.filterName }.toSet())
assertFalse("single" in validation.selections)
assertTrue(validation.canReview)
}
@Test fun synthesizedIdsNeverResolveByTranslatedLabelsOrOptionPositions() {
val original = schema.first().copy(hasStableId = false)
val saved = preset().copy(filters = capturePresetFilters(listOf(original), mapOf(original.id to FilterSelection.Toggle(true))))
val renamed = validateSourcePreset(saved, source, listOf(original.copy(name = "Translated label")))
assertEquals(PresetIssueReason.Changed, renamed.issues.single().reason)
val replaced = validateSourcePreset(saved, source, listOf(original.copy(id = "new-id")))
assertTrue(replaced.selections.isEmpty())
assertEquals(setOf(PresetIssueReason.Removed, PresetIssueReason.Changed), replaced.issues.map { it.reason }.toSet())
}
@Test fun renamedFiltersNeedReviewSourceUpgradesRemainCompatibleAndIdReuseIsRejected() {
val renamed = validateSourcePreset(preset(), source, schema.map { it.copy(name = "New ${it.name}") })
assertTrue(renamed.issues.isNotEmpty())
assertTrue(renamed.canReview)
assertEquals(PresetIssueReason.SourceChanged,
validateSourcePreset(preset(), source.copy(baseUrl = "https://unrelated.test"), schema).issues.single().reason)
assertTrue(validateSourcePreset(preset(), source.copy(version = "2.0", sourceCode = "new"), schema).issues.isEmpty())
}
@Test fun malformedValuesUnsupportedVersionsAndDuplicateIdsFailClosed() {
val invalid = preset().copy(filters = preset().filters.map {
if (it.id == "tri") it.copy(selection = DbPresetSelection.TriState(9)) else it
})
assertEquals(PresetIssueReason.InvalidSelection, validateSourcePreset(invalid, source, schema).issues.single().reason)
assertFalse(validateSourcePreset(preset().copy(presetVersion = 2), source, schema).canReview)
assertFalse(validateSourcePreset(preset(), source, schema + schema.first()).canReview)
}
@Test fun legacyQueriesKeepStableIdsAndAreBoundBeforeTheirSourceCanBeReplaced() {
val raw = """{"sourceId":42,"name":"Legacy","query":"query"}"""
val legacy = Json.decodeFromString(DbSavedSearch.serializer(), raw)
assertEquals(legacy.id, Json.decodeFromString(DbSavedSearch.serializer(), raw).id)
val adopted = DbSettings(savedSearches = listOf(legacy)).adoptLegacySourcePresets(listOf(source)).savedSearches.orEmpty().single()
assertTrue(validateSourcePreset(adopted, source, schema).issues.isEmpty())
assertTrue(validateSourcePreset(adopted, source, schema).selections.isEmpty())
assertFalse(validateSourcePreset(adopted, source.copy(lang = "ja"), schema).canReview)
val missing = DbSettings(savedSearches = listOf(legacy)).adoptLegacySourcePresets(emptyList()).savedSearches.orEmpty().single()
assertFalse(validateSourcePreset(missing, source, schema).canReview)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresetsTest.kt
- Source · test / fixture · 61 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
11: class SourcePresetsTest {
16: private fun state(editor: PresetEditor?, schemaReady: Boolean = true) =
20: fun savingANewNameStoresATrimmedPresetAndClosesTheEditor() {
30: fun blankNamesAndConflictsKeepTheEditorOpen() {
41: fun confirmedReplaceReusesTheConflictingId() {
50: fun savingWithoutAFilterSchemaChangesNothing() {
55: fun applyingWithoutAFilterSchemaOpensTheReview() {
Exact file bytes / download · SHA-256 48681c8cd9411025de20af5bde5d0698721fb0b6306ec897c48fd088291fd3c8.
Complete file
package eu.friedcutlet.yokan.ui.screens.browse
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class SourcePresetsTest {
private val source = DbSource(id = 7, name = "Source")
private val existing = DbSavedSearch(sourceId = 7, name = "Taken", query = "old", id = "preset:taken")
private val db = DbSettings(savedSearches = listOf(existing))
private fun state(editor: PresetEditor?, schemaReady: Boolean = true) =
SourceHomeUiState(source = null, searchQuery = " query ", filterSchemaReady = schemaReady, presetEditor = editor)
@Test
fun savingANewNameStoresATrimmedPresetAndClosesTheEditor() {
val commit = commitPreset(state(PresetEditor(PresetEditMode.Save, " Fresh ")), db, source, replace = false) { "preset:new" }
assertEquals(null, commit?.editor)
assertEquals("preset:new", commit?.save?.id)
assertEquals("Fresh", commit?.save?.name)
assertEquals("query", commit?.save?.query)
}
@Test
fun blankNamesAndConflictsKeepTheEditorOpen() {
val blank = commitPreset(state(PresetEditor(PresetEditMode.Save, " ")), db, source, replace = false)
val conflict = commitPreset(state(PresetEditor(PresetEditMode.Save, "Taken")), db, source, replace = false)
assertEquals(true, blank?.editor?.invalidName)
assertNull(blank?.save)
assertEquals("preset:taken", conflict?.editor?.conflictId)
assertNull(conflict?.save)
}
@Test
fun confirmedReplaceReusesTheConflictingId() {
val editor = PresetEditor(PresetEditMode.Save, "Taken", conflictId = "preset:taken")
val commit = commitPreset(state(editor), db, source, replace = true) { "preset:new" }
assertEquals("preset:taken", commit?.save?.id)
}
@Test
fun savingWithoutAFilterSchemaChangesNothing() {
assertNull(commitPreset(state(PresetEditor(PresetEditMode.Save, "Fresh"), schemaReady = false), db, source, replace = false))
}
@Test
fun applyingWithoutAFilterSchemaOpensTheReview() {
val applied = state(null, schemaReady = false).withPresetApplied(existing, source)
assertEquals(existing, applied.presetReview?.preset)
assertEquals(" query ", applied.searchQuery)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterListDefaultsTest.kt
- Source · test / fixture · 101 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
25: class ChapterListDefaultsTest {
26: private fun title(id: Long, type: ItemType, favorite: Boolean = true) = Manga(id, "Title $id", link = "/$id", description = "",
Exact file bytes / download · SHA-256 cc33fc60ba44bf29f067703ec81c2dd043378deadeceb8c6ecfdcf2f98f1bef0.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import eu.friedcutlet.yokan.database.DatabaseJson
import eu.friedcutlet.yokan.database.DbChapterFilter
import eu.friedcutlet.yokan.database.DbChapterListDefaults
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSortChapter
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Status
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.services.library.ChapterFilterKind
import eu.friedcutlet.yokan.services.library.ChapterFilterTypes
import eu.friedcutlet.yokan.services.library.chapterFilters
import eu.friedcutlet.yokan.services.library.chapterSort
import eu.friedcutlet.yokan.services.library.visibleChapters
import eu.friedcutlet.yokan.services.library.withChapterFilterCycled
import eu.friedcutlet.yokan.services.library.withChapterListDefaultFrom
import eu.friedcutlet.yokan.services.library.withChapterSortToggled
class ChapterListDefaultsTest {
private fun title(id: Long, type: ItemType, favorite: Boolean = true) = Manga(id, "Title $id", link = "/$id", description = "",
status = Status.Ongoing, itemType = type, favorite = favorite, source = "Source", lang = "en", dateAddedMillis = 0, lastUpdateMillis = 0)
private val chapters = (1L..3L).map { Chapter(it, 0, "Chapter $it", "/$it", isRead = it == 2L) }
@Test fun withoutADefaultUnconfiguredTitlesKeepTheBuiltInSortAndNoFilters() {
val manga = title(1, ItemType.Anime)
assertEquals(DbSortChapter(mangaId = 1, index = 1, reverse = false), DbSettings().chapterSort(manga))
assertEquals(ChapterFilterTypes(0, 0, 0), DbSettings().chapterFilters(manga))
assertEquals(listOf(3L, 2L, 1L), visibleChapters(manga, chapters, DbSettings(), emptySet()).map { it.id })
}
@Test fun setAsDefaultAppliesToUnconfiguredTitlesOfTheSameTypeOnly() {
val source = title(1, ItemType.Anime)
val configured = DbSettings()
.withChapterSortToggled(source, 1) // re-selecting the current sort flips its direction
.withChapterFilterCycled(source, ChapterFilterKind.Unread)
val db = configured.withChapterListDefaultFrom(source, emptyList())
assertEquals(DbChapterListDefaults(sortIndex = 1, sortReverse = true, unread = 1), db.features.library.chapterListDefault(DbItemType.Anime))
val newAnime = title(2, ItemType.Anime, favorite = false)
assertEquals(listOf(1L, 3L), visibleChapters(newAnime, chapters, db, emptySet()).map { it.id })
assertEquals(listOf(3L, 2L, 1L), visibleChapters(title(3, ItemType.Manga), chapters, db, emptySet()).map { it.id })
// A title's own choice still wins over the default, per field.
val ownSort = db.copy(sortChapterList = db.sortChapterList.orEmpty() + DbSortChapter(mangaId = 2, index = 1, reverse = false))
assertEquals(listOf(3L, 1L), visibleChapters(newAnime, chapters, ownSort, emptySet()).map { it.id })
val ownFilter = db.copy(chapterFilterUnreadList = db.chapterFilterUnreadList.orEmpty() + DbChapterFilter(mangaId = 2, type = 0))
assertEquals(listOf(1L, 2L, 3L), visibleChapters(newAnime, chapters, ownFilter, emptySet()).map { it.id })
}
@Test fun applyingToTheLibraryResetsOnlyLibraryTitlesOfThatMediaType() {
val source = title(1, ItemType.Anime)
val libraryAnime = title(2, ItemType.Anime)
val libraryManga = title(3, ItemType.Manga)
val browsedAnime = title(4, ItemType.Anime, favorite = false)
val own = listOf(2L, 3L, 4L)
val db = DbSettings(
sortChapterList = own.map { DbSortChapter(mangaId = it, index = 3) },
chapterFilterBookmarkedList = own.map { DbChapterFilter(mangaId = it, type = 2) },
).withChapterFilterCycled(source, ChapterFilterKind.Downloaded)
val applied = db.withChapterListDefaultFrom(source, listOf(source, libraryAnime, libraryManga, browsedAnime))
assertEquals(listOf(3L, 4L), applied.sortChapterList?.map { it.mangaId })
assertEquals(listOf(3L, 4L), applied.chapterFilterBookmarkedList?.map { it.mangaId })
assertEquals(ChapterFilterTypes(1, 0, 0), applied.chapterFilters(libraryAnime))
assertEquals(DbSortChapter(mangaId = 3, index = 3), applied.chapterSort(libraryManga))
// Outside the library: keeps its own bookmark filter, unset fields follow the new default.
assertEquals(ChapterFilterTypes(1, 0, 2), applied.chapterFilters(browsedAnime))
}
@Test fun settingsJsonWithoutDefaultsStillDecodesAndDefaultsRoundTrip() {
val legacy = DatabaseJson.decodeFromString(DbSettings.serializer(), """{"features":{"library":{"defaultCategoryIds":{"Anime":3}}},"sortChapterList":[{"mangaId":1,"index":2}]}""")
assertEquals(3L, legacy.features.library.defaultCategory(DbItemType.Anime))
assertTrue(legacy.features.library.chapterListDefaults.isEmpty())
assertEquals(DbSortChapter(mangaId = 1, index = 2), legacy.chapterSort(title(1, ItemType.Manga)))
val withDefault = legacy.copy(features = legacy.features.copy(library = legacy.features.library
.withChapterListDefault(DbItemType.Novel, DbChapterListDefaults(sortIndex = 3, bookmarked = 1))))
val decoded = DatabaseJson.decodeFromString(DbSettings.serializer(), DatabaseJson.encodeToString(DbSettings.serializer(), withDefault))
assertEquals(DbChapterListDefaults(sortIndex = 3, bookmarked = 1), decoded.features.library.chapterListDefault(DbItemType.Novel))
// Choosing the built-in values again stores nothing.
assertTrue(decoded.features.library.withChapterListDefault(DbItemType.Novel, DbChapterListDefaults()).chapterListDefaults.isEmpty())
}
@Test fun fillerFilterUsesTheEffectiveMarkAndBecomesPartOfTheDefault() {
val show = title(1, ItemType.Anime)
// Episode 1: source filler the user unmarked; episode 3: user-marked filler.
val episodes = listOf(chapters[0].copy(isFiller = false, fillerOverride = false), chapters[1], chapters[2].copy(isFiller = true, fillerOverride = true))
val hide = DbSettings().withChapterFilterCycled(show, ChapterFilterKind.Filler).withChapterFilterCycled(show, ChapterFilterKind.Filler)
assertEquals(listOf(2L, 1L), visibleChapters(show, episodes, hide, emptySet()).map { it.id })
val only = DbSettings().withChapterFilterCycled(show, ChapterFilterKind.Filler)
assertEquals(listOf(3L), visibleChapters(show, episodes, only, emptySet()).map { it.id })
val other = title(2, ItemType.Anime)
val applied = hide.withChapterListDefaultFrom(show, listOf(show, other))
assertEquals(2, applied.features.library.chapterListDefault(DbItemType.Anime).filler)
assertTrue(applied.features.library.chapterFillerFilters.isEmpty())
assertEquals(listOf(2L, 1L), visibleChapters(other, episodes, applied, emptySet()).map { it.id })
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterSelectionTest.kt
- Source · test / fixture · 49 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class ChapterSelectionTest {
Exact file bytes / download · SHA-256 71c3bf317f1538f71a5c80feb1be396607068fd9edca569fe8d23cd954349143.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import eu.friedcutlet.yokan.domain.Chapter
import kotlin.test.Test
import kotlin.test.assertEquals
class ChapterSelectionTest {
private val chapters = (1L..6L).map { Chapter(it, 1, "Chapter $it", "/$it", isRead = it % 2L == 0L, isBookmarked = it == 3L, downloadSize = if (it == 4L) "1 MB" else null) }
@Test fun statusShortcutsAndInversionOnlyUseShownChapters() {
val shown = chapters.take(4)
var selection = ChapterSelectionState().select(shown, ChapterSelectionOption.Unread)
assertEquals(setOf(1L, 3L), selection.ids)
selection = selection.select(shown, ChapterSelectionOption.Invert)
assertEquals(setOf(2L, 4L), selection.ids)
selection = selection.select(shown, ChapterSelectionOption.Downloaded)
assertEquals(setOf(4L), selection.ids)
selection = selection.select(shown, ChapterSelectionOption.Bookmarked)
assertEquals(setOf(3L), selection.ids)
}
@Test fun rangeFollowsDisplayOrderAndKeepsTheFirstAnchor() {
val reversed = chapters.reversed()
var selection = ChapterSelectionState().toggle(5).rangeTo(reversed, 2)
assertEquals(setOf(5L, 4L, 3L, 2L), selection.ids)
assertEquals(5L, selection.anchorId)
selection = selection.rangeTo(reversed, 1)
assertEquals(setOf(5L, 4L, 3L, 2L, 1L), selection.ids)
}
@Test fun numericRangeUsesRowsRatherThanChapterIdsAndRejectsInvalidBounds() {
val selection = ChapterSelectionState().selectRange(chapters.reversed(), 2, 4)
assertEquals(setOf(5L, 4L, 3L), selection.ids)
assertEquals(selection, selection.selectRange(chapters, 0, 4).selectRange(chapters, 4, 2))
}
@Test fun aboveAndBelowIncludeTheAnchor() {
var selection = ChapterSelectionState().toggle(3).select(chapters, ChapterSelectionOption.Above)
assertEquals(setOf(1L, 2L, 3L), selection.ids)
selection = selection.select(chapters, ChapterSelectionOption.Below)
assertEquals(chapters.map { it.id }.toSet(), selection.ids)
}
@Test fun filteringOrRemovalDropsInvisibleSelectionsAndAnchor() {
val selection = ChapterSelectionState().select(chapters, ChapterSelectionOption.All).retainVisible(chapters.drop(1))
assertEquals(setOf(2L, 3L, 4L, 5L, 6L), selection.ids)
assertEquals(null, selection.anchorId)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/CoverInspectionTest.kt
- Source · test / fixture · 58 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
10: class CoverInspectionTest {
12: fun fittedBoundsClampAgainstTheImageRatherThanTheWindow() {
23: fun focalZoomKeepsThePointUnderThePointerUntilBoundsAreReached() {
37: fun resizeReclampsPanAndResetZoomCentersTheCover() {
52: fun keyboardCanDismissAndRestoreHiddenControls() {
Exact file bytes / download · SHA-256 aa090af1d1d0172c62098571431f078aea4b3f5c156781199d86f8d72b7dc699.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.unit.IntSize
import kotlin.test.Test
import kotlin.test.assertEquals
class CoverInspectionTest {
@Test
fun fittedBoundsClampAgainstTheImageRatherThanTheWindow() {
val image = IntSize(600, 900)
val viewport = IntSize(1000, 600)
assertEquals(Size(400f, 600f), fittedCoverSize(image, viewport))
assertEquals(
Offset(0f, 300f),
constrainCoverOffset(Offset(900f, 900f), 2f, image, viewport),
)
}
@Test
fun focalZoomKeepsThePointUnderThePointerUntilBoundsAreReached() {
val transformed = transformCover(
current = CoverTransform(1f, Offset.Zero),
focalPoint = Offset(750f, 500f),
pan = Offset.Zero,
zoomChange = 2f,
imageSize = IntSize(1000, 1000),
viewportSize = IntSize(1000, 1000),
)
assertEquals(2f, transformed.scale)
assertEquals(Offset(-250f, 0f), transformed.offset)
}
@Test
fun resizeReclampsPanAndResetZoomCentersTheCover() {
val reclamped = constrainCoverOffset(
offset = Offset(600f, -600f),
scale = 2f,
imageSize = IntSize(1600, 900),
viewportSize = IntSize(600, 900),
)
assertEquals(Offset(300f, 0f), reclamped)
assertEquals(
Offset.Zero,
constrainCoverOffset(reclamped, 1f, IntSize(1600, 900), IntSize(600, 900)),
)
}
@Test
fun keyboardCanDismissAndRestoreHiddenControls() {
assertEquals(CoverInspectionKeyAction.Dismiss, coverInspectionKeyAction(Key.Escape))
assertEquals(CoverInspectionKeyAction.ToggleControls, coverInspectionKeyAction(Key.Spacebar))
assertEquals(CoverInspectionKeyAction.ToggleControls, coverInspectionKeyAction(Key.Enter))
assertEquals(CoverInspectionKeyAction.None, coverInspectionKeyAction(Key.DirectionLeft))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailSwipeTest.kt
- Source · test / fixture · 47 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class DetailSwipeTest {
10: fun committedSwipesInvokeTheirActionThenReset() = runTest {
30: fun settledAndRepeatedSwipesDoNotLeaveAnUnresetAction() = runTest {
Exact file bytes / download · SHA-256 f4e1bee7cb4ecd06f5d5d9475e85a39bd81782366ce45e945af3727efbf6302b.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.material3.SwipeToDismissBoxValue
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
class DetailSwipeTest {
@Test
fun committedSwipesInvokeTheirActionThenReset() = runTest {
val events = mutableListOf<String>()
completeChapterSwipeDismiss(
direction = SwipeToDismissBoxValue.StartToEnd,
onBookmark = { events += "bookmark" },
onReadToggle = { events += "read" },
reset = { events += "reset" },
)
completeChapterSwipeDismiss(
direction = SwipeToDismissBoxValue.EndToStart,
onBookmark = { events += "bookmark" },
onReadToggle = { events += "read" },
reset = { events += "reset" },
)
assertEquals(listOf("bookmark", "reset", "read", "reset"), events)
}
@Test
fun settledAndRepeatedSwipesDoNotLeaveAnUnresetAction() = runTest {
val events = mutableListOf<String>()
val handle: suspend (SwipeToDismissBoxValue) -> Unit = { direction ->
completeChapterSwipeDismiss(
direction = direction,
onBookmark = { events += "bookmark" },
onReadToggle = { events += "read" },
reset = { events += "reset" },
)
}
handle(SwipeToDismissBoxValue.Settled)
handle(SwipeToDismissBoxValue.StartToEnd)
handle(SwipeToDismissBoxValue.StartToEnd)
assertEquals(listOf("bookmark", "reset", "bookmark", "reset"), events)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailViewModelTest.kt
- Source · test / fixture · 331 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
46: class DetailViewModelTest {
59: fun tearDown() = host.close()
61: private fun viewModel(
89: fun castOnlyUpdatesReachTheObservedDetailWithoutChangingChapters() = runTest {
102: fun seasonSelectionScopesEpisodesContinuationAndActionsAndRecoversAfterRemoval() = runTest {
110: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { requests += request.chapterId }
144: fun seasonsTitleListsItsSeasonRecordsWithTheirOwnProgressAndContinuation() = runTest {
165: fun explicitUncategorizedSelectionOverridesDefaultButOrdinaryAddUsesIt() = runTest {
183: fun togetherEventAndRoomObservationUseTheInjectedControllerAndTransport() = runTest {
203: fun selectionTogglesSplitByCurrentFlagAndClearTheSelection() = runTest {
222: fun releasePreferencesChooseOneWinnerPreserveFilesAndSupportGroupActionsAndAlternates() = runTest {
229: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { requests += request.chapterId }
259: fun noteSaveCancelAndClearOnlyCommitSavedDrafts() = runTest {
288: fun chapterFilterHidesChaptersAndDropsThemFromTheSelection() = runTest {
302: private object NoDownloads : DownloadService {
303: override suspend fun initialize(poolSize: Int) = Unit
304: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
305: override fun cancel(taskId: String) = Unit
306: override fun pause(taskId: String) = Unit
307: override fun resume(taskId: String) = Unit
308: override fun retry(taskId: String): Boolean = false
309: override fun storageLocation(taskId: String): String? = null
310: override fun deleteArtifacts(taskId: String) = Unit
311: override fun activeDownloads(): List<DownloadProgress> = emptyList()
314: private object NoRuntimeFactory : ExtensionRuntimeFactory {
315: override fun create(source: DbSource): ExtensionRuntimeService = error("No extension runtime in tests")
318: private object NoMetadata : MetadataService {
319: override suspend fun health(baseUrl: String) = false
320: override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int): List<MetadataMedia> = emptyList()
321: override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> = emptyList()
322: override suspend fun upsertLibraryEntry(
Exact file bytes / download · SHA-256 2fd106e2a96ae9168455c521695957dd50c0519c54c806b03f2c7905b6bb2f60.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.chapterReleasePreference
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import eu.friedcutlet.yokan.services.together.ProfileTogetherSession
import kotlinx.coroutines.awaitCancellation
import eu.friedcutlet.yokan.services.download.ChapterDownloads
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.download.DownloadRequest
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.files.NoFiles
import eu.friedcutlet.yokan.services.metadata.MetadataLibraryEntry
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.services.metadata.MetadataService
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import eu.friedcutlet.yokan.services.library.ChapterFilterKind
@OptIn(ExperimentalCoroutinesApi::class)
class DetailViewModelTest {
// No source id: a title without an installed source never triggers the remote refresh.
private val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "Title", link = "/t", source = "Src", itemType = DbItemType.Manga, favorite = true)),
chapters = (1L..3L).map { DbChapter(id = it, mangaId = 1, url = "/c$it", name = "Chapter $it", isRead = it == 2L) },
),
)
private val repository = DefaultYokanRepository(database)
private val host = ViewModelTestHost()
private val dispatcher = host.dispatcher
@AfterTest
fun tearDown() = host.close()
private fun viewModel(
scope: CoroutineScope,
downloader: DownloadService = NoDownloads,
together: ProfileTogetherSession? = null,
http: HttpService? = null,
): DetailViewModel {
val settings = SettingsStore(repository, scope, onSchedulingChanged = {})
val downloads = ChapterDownloads(repository, database, downloader, NoNotifications, settings, NoFiles, scope)
return host.create {
DetailViewModel(
mangaId = 1,
repository = repository,
settings = settings,
libraryIndex = LibraryIndexStore(repository, scope),
downloads = downloads,
metadata = NoMetadata,
runtimeFactory = NoRuntimeFactory,
database = database,
allTrackers = emptyList(),
files = NoFiles,
workDispatcher = dispatcher,
together = together,
togetherHttp = http,
)
}
}
@Test
fun castOnlyUpdatesReachTheObservedDetailWithoutChangingChapters() = runTest {
val vm = viewModel(backgroundScope)
vm.state.filterNotNull().first { it.content.loaded }
val ids = database.chapters(1).map { it.id }
val credit = eu.friedcutlet.yokan.domain.TitleCredit("Actor", "Voice actor", "Hero")
database.upsertManga(requireNotNull(database.manga(1)).copy(cast = listOf(credit)))
val changed = vm.state.filterNotNull().first { it.content.manga.cast == listOf(credit) }
assertEquals(ids.toSet(), changed.content.chapters.map { it.id }.toSet())
database.upsertManga(requireNotNull(database.manga(1)).copy(cast = emptyList()))
vm.state.filterNotNull().first { it.content.manga.cast.isEmpty() }
}
@Test
fun seasonSelectionScopesEpisodesContinuationAndActionsAndRecoversAfterRemoval() = runTest {
database.upsertManga(requireNotNull(database.manga(1)).copy(itemType = DbItemType.Anime))
database.upsertChapter(DbChapter(id = 1, mangaId = 1, url = "/special", name = "Special", number = 1.0, season = 0))
database.upsertChapter(DbChapter(id = 2, mangaId = 1, url = "/premiere", name = "Premiere", number = 1.0, season = 2))
database.upsertChapter(DbChapter(id = 3, mangaId = 1, url = "/second", name = "S02E02"))
database.upsertChapter(DbChapter(id = 4, mangaId = 1, url = "/ova", name = "Unnumbered OVA"))
val requests = mutableListOf<Long>()
val downloader = object : DownloadService by NoDownloads {
override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { requests += request.chapterId }
}
val vm = viewModel(backgroundScope, downloader)
val all = vm.state.filterNotNull().first { it.content.loaded && it.content.chapters.size == 4 }
assertEquals(listOf(0, 2), all.content.seasons)
assertEquals(null, all.content.selectedSeason)
vm.onEvent(DetailEvent.ToggleSelection(1))
vm.onEvent(DetailEvent.SelectSeason(2))
val second = vm.state.filterNotNull().first { it.content.selectedSeason == 2 }
assertEquals(setOf(2L, 3L), second.content.chapters.map { it.id }.toSet())
assertTrue(second.selection.ids.isEmpty())
assertTrue(second.content.continueChapter?.id in setOf(2L, 3L))
vm.onEvent(DetailEvent.DownloadAll(repository.chapters(1), DetailDownloadOption.All, null))
assertEquals(setOf(2L, 3L), requests.toSet())
vm.onEvent(DetailEvent.SetRead(setOf(2), true))
assertEquals(false, database.chapter(1)?.isRead)
assertEquals(true, database.chapter(2)?.isRead)
vm.onEvent(DetailEvent.SelectSeason(99))
assertEquals(2, vm.state.value?.selectedSeason)
vm.onEvent(DetailEvent.SelectSeason(0))
val specials = vm.state.filterNotNull().first { it.content.selectedSeason == 0 }
assertEquals(listOf(1L), specials.content.chapters.map { it.id })
assertEquals(1L, specials.content.continueChapter?.id)
vm.onEvent(DetailEvent.SelectSeason(null))
vm.state.filterNotNull().first { it.content.selectedSeason == null && it.content.chapters.size == 4 }
vm.onEvent(DetailEvent.SelectSeason(2))
vm.state.filterNotNull().first { it.content.selectedSeason == 2 }
database.batch { database.removeChapter(2); database.removeChapter(3) }
val removed = vm.state.filterNotNull().first { it.selectedSeason == null && it.content.chapters.size == 2 }
assertEquals(listOf(0), removed.content.seasons)
assertEquals(setOf(1L, 4L), removed.content.chapters.map { it.id }.toSet())
}
@Test
fun seasonsTitleListsItsSeasonRecordsWithTheirOwnProgressAndContinuation() = runTest {
database.upsertManga(requireNotNull(database.manga(1)).copy(itemType = DbItemType.Anime, fetchType = eu.friedcutlet.yokan.database.DbFetchType.Seasons))
database.chapters(1).forEach { database.removeChapter(it.id) }
database.upsertManga(DbManga(id = 21, name = "Second", link = "/s2", itemType = DbItemType.Anime, parentId = 1, seasonNumber = 2.0))
database.upsertManga(DbManga(id = 20, name = "First", link = "/s1", itemType = DbItemType.Anime, parentId = 1, seasonNumber = 1.0))
database.upsertManga(DbManga(id = 22, name = "Unrelated", link = "/x", itemType = DbItemType.Anime))
database.upsertChapter(DbChapter(id = 30, mangaId = 20, url = "/s1/e1", name = "Episode 1", isRead = true))
database.upsertChapter(DbChapter(id = 31, mangaId = 20, url = "/s1/e2", name = "Episode 2"))
database.upsertChapter(DbChapter(id = 32, mangaId = 21, url = "/s2/e1", name = "Episode 1", isRead = true))
val vm = viewModel(backgroundScope)
val state = vm.state.filterNotNull().first { it.content.loaded && it.content.seasonTitles.size == 2 }
assertEquals(listOf(20L, 21L), state.content.seasonTitles.map { it.title.id })
assertEquals(listOf(2 to 1, 1 to 1), state.content.seasonTitles.map { it.episodeCount to it.watchedCount })
assertEquals(listOf(31L, null), state.content.seasonTitles.map { it.continueChapter?.id })
assertTrue(state.content.chapters.isEmpty())
database.upsertChapter(DbChapter(id = 33, mangaId = 21, url = "/s2/e2", name = "Episode 2"))
val updated = vm.state.filterNotNull().first { it.content.seasonTitles.getOrNull(1)?.continueChapter?.id == 33L }
assertEquals(2, updated.content.seasonTitles[1].episodeCount)
}
@Test
fun explicitUncategorizedSelectionOverridesDefaultButOrdinaryAddUsesIt() = runTest {
val category = repository.createCategory(eu.friedcutlet.yokan.domain.ItemType.Manga, "Default")
repository.updateDbSettings { db -> db.copy(features = db.features.copy(
library = db.features.library.withDefaultCategory(DbItemType.Manga, category.id),
)) }
repository.setMangaFavorite(1, false)
val vm = viewModel(backgroundScope)
vm.state.filterNotNull().first { it.content.loaded && !it.content.manga.favorite }
vm.onEvent(DetailEvent.SetFavorite(true))
assertEquals(listOf(category.id), repository.manga(1)?.categories)
vm.onEvent(DetailEvent.SetFavorite(false))
vm.onEvent(DetailEvent.SetCategories(emptyList(), favorite = true))
assertEquals(true, repository.manga(1)?.favorite)
assertEquals(emptyList(), repository.manga(1)?.categories)
vm.state.filterNotNull().first { it.content.manga.favorite && it.content.manga.categories.isEmpty() }
}
@Test
fun togetherEventAndRoomObservationUseTheInjectedControllerAndTransport() = runTest {
database.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://captured-hub.test", authToken = "captured-token", deviceId = "captured-device"))
val engine = ProfileTestEngine(dispatcher) { awaitCancellation() }
val together = ProfileTogetherSession(ProfileId.Default, database, backgroundScope) { engine }
val http = RecordingHttpService { HttpResponse(201, "{\"code\":\"ABCDEF\",\"join_url\":\"join\"}") }
val vm = viewModel(backgroundScope, together = together, http = http)
vm.state.filterNotNull().first { it.content.loaded }
vm.onEvent(DetailEvent.Together)
assertEquals(DetailEffect.OpenTogetherSettings, vm.effects.first())
assertTrue((vm.effects.first() as DetailEffect.ShowMessage).text.startsWith("Room ABCDEF"))
val state = vm.state.filterNotNull().first { it.togetherRoom?.code == "ABCDEF" }
assertEquals("ABCDEF", state.togetherRoom?.code)
assertEquals("https://captured-hub.test/api/v1/rooms", http.requests.single().url)
assertEquals("Bearer captured-token", http.requests.single().headers["Authorization"])
together.leave()
vm.state.filterNotNull().first { it.togetherRoom == null }
together.closeAndJoin()
}
@Test
fun selectionTogglesSplitByCurrentFlagAndClearTheSelection() = runTest {
val vm = viewModel(backgroundScope)
vm.state.filterNotNull().first { it.content.loaded }
vm.onEvent(DetailEvent.Select(ChapterSelectionOption.All))
vm.onEvent(DetailEvent.ToggleSelectedRead)
assertEquals(listOf(true, false, true), (1L..3L).map { database.chapter(it)?.isRead })
assertTrue(checkNotNull(vm.state.value).selection.ids.isEmpty())
vm.state.filterNotNull().first { it.content.chapters.count { chapter -> chapter.isRead } == 2 }
vm.onEvent(DetailEvent.ToggleSelection(1))
vm.onEvent(DetailEvent.ToggleSelectedBookmarks)
vm.state.filterNotNull().first { it.content.chapters.single { chapter -> chapter.id == 1L }.isBookmarked }
vm.onEvent(DetailEvent.ToggleSelection(1))
vm.onEvent(DetailEvent.ToggleSelection(2))
vm.onEvent(DetailEvent.ToggleSelectedBookmarks)
assertEquals(listOf(false, true, false), (1L..3L).map { database.chapter(it)?.isBookmarked })
assertTrue(checkNotNull(vm.state.value).selection.ids.isEmpty())
}
@Test
fun releasePreferencesChooseOneWinnerPreserveFilesAndSupportGroupActionsAndAlternates() = runTest {
database.upsertChapter(checkNotNull(database.chapter(1)).copy(scanlator = "Fallback", isRead = true, archivePath = "/kept"))
database.upsertChapter(DbChapter(id = 4, mangaId = 1, name = "Chapter 1", url = "/preferred", scanlator = "Preferred"))
database.updateSettings(database.settings().copy(chapterReleasePreferences = listOf(DbChapterReleasePreference(
scanlatorPriority = listOf("Fallback", "Preferred"), skipDuplicateReleases = true))))
val requests = mutableListOf<Long>()
val downloader = object : DownloadService by NoDownloads {
override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { requests += request.chapterId }
}
val vm = viewModel(backgroundScope, downloader)
vm.state.filterNotNull().first { it.content.loaded && it.content.chapters.size == 3 }
vm.onEvent(DetailEvent.MoveScanlator("Preferred", -1))
val preferred = vm.state.filterNotNull().first { it.content.chapters.any { chapter -> chapter.id == 4L } }
assertTrue(preferred.content.chapters.single { it.id == 4L }.isRead)
assertEquals("/kept", database.chapter(1)?.archivePath)
vm.onEvent(DetailEvent.SetRead(setOf(4), false))
vm.state.filterNotNull().first { !it.content.chapters.single { chapter -> chapter.id == 4L }.isRead }
assertEquals(false, database.chapter(1)?.isRead)
assertEquals(false, database.chapter(4)?.isRead)
vm.onEvent(DetailEvent.SetBookmarked(setOf(4), true))
vm.state.filterNotNull().first { it.content.chapters.single { chapter -> chapter.id == 4L }.isBookmarked }
assertTrue(checkNotNull(database.chapter(1)).isBookmarked)
assertTrue(checkNotNull(database.chapter(4)).isBookmarked)
vm.onEvent(DetailEvent.DownloadAll(checkNotNull(vm.state.value).content.chapters, DetailDownloadOption.All, null))
assertEquals(setOf(2L, 3L, 4L), requests.toSet())
vm.onEvent(DetailEvent.ShowAllReleases(true))
vm.state.filterNotNull().first { it.content.chapters.size == 4 }
vm.onEvent(DetailEvent.ShowAllReleases(false))
vm.state.filterNotNull().first { it.content.chapters.size == 3 }
vm.onEvent(DetailEvent.ResetReleaseOverride)
vm.state.filterNotNull().first { it.content.chapters.any { chapter -> chapter.id == 1L } }
assertEquals(listOf("Fallback", "Preferred"), database.settings().chapterReleasePreference(1).scanlatorPriority)
assertEquals(4, database.chapters(1).size)
assertEquals("/kept", database.chapter(1)?.archivePath)
}
@Test
fun noteSaveCancelAndClearOnlyCommitSavedDrafts() = runTest {
val vm = viewModel(backgroundScope)
vm.state.filterNotNull().first { it.content.loaded }
val note = "日本語 🌙\nSecond line"
vm.onEvent(DetailEvent.EditNote)
vm.onEvent(DetailEvent.ChangeNote(note))
assertEquals("", repository.manga(1)?.privateNote)
vm.onEvent(DetailEvent.SaveNote)
assertEquals(note, repository.manga(1)?.privateNote)
assertEquals(null, vm.state.value?.noteDraft)
vm.onEvent(DetailEvent.EditNote)
vm.onEvent(DetailEvent.ChangeNote("discard me"))
vm.onEvent(DetailEvent.CancelNote)
assertEquals(note, repository.manga(1)?.privateNote)
vm.onEvent(DetailEvent.EditNote)
vm.onEvent(DetailEvent.ChangeNote(""))
vm.onEvent(DetailEvent.CancelNote)
assertEquals(note, repository.manga(1)?.privateNote)
vm.onEvent(DetailEvent.EditNote)
vm.onEvent(DetailEvent.ChangeNote(""))
vm.onEvent(DetailEvent.SaveNote)
assertEquals("", repository.manga(1)?.privateNote)
vm.onEvent(DetailEvent.SetFavorite(false))
vm.state.filterNotNull().first { !it.content.manga.favorite }
vm.onEvent(DetailEvent.EditNote)
assertEquals(null, vm.state.value?.noteDraft)
}
@Test
fun chapterFilterHidesChaptersAndDropsThemFromTheSelection() = runTest {
val vm = viewModel(backgroundScope)
val loaded = vm.state.filterNotNull().first { it.content.loaded }
assertEquals(listOf(3L, 2L, 1L), loaded.content.chapters.map { it.id })
vm.onEvent(DetailEvent.Select(ChapterSelectionOption.All))
vm.onEvent(DetailEvent.CycleFilter(ChapterFilterKind.Unread))
val filtered = vm.state.filterNotNull().first { it.content.chapters.size == 2 }
assertEquals(listOf(3L, 1L), filtered.content.chapters.map { it.id })
assertEquals(setOf(3L, 1L), filtered.selection.ids)
}
}
private object NoDownloads : DownloadService {
override suspend fun initialize(poolSize: Int) = Unit
override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
override fun cancel(taskId: String) = Unit
override fun pause(taskId: String) = Unit
override fun resume(taskId: String) = Unit
override fun retry(taskId: String): Boolean = false
override fun storageLocation(taskId: String): String? = null
override fun deleteArtifacts(taskId: String) = Unit
override fun activeDownloads(): List<DownloadProgress> = emptyList()
}
private object NoRuntimeFactory : ExtensionRuntimeFactory {
override fun create(source: DbSource): ExtensionRuntimeService = error("No extension runtime in tests")
}
private object NoMetadata : MetadataService {
override suspend fun health(baseUrl: String) = false
override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int): List<MetadataMedia> = emptyList()
override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> = emptyList()
override suspend fun upsertLibraryEntry(
baseUrl: String,
token: String,
mediaId: String,
status: String,
progress: Int,
score: Int?,
isFavorite: Boolean,
) = false
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationSelectionTest.kt
- Source · test / fixture · 105 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
21: class MassMigrationSelectionTest {
40: fun tearDown() = host.close()
42: private fun viewModel(scope: CoroutineScope): MassMigrationPreviewViewModel {
49: fun startsWithEveryFavoriteTitleOfTheSourceSelected() = runTest {
58: fun toggleAllDeselectsThenSelectsEverything() = runTest {
69: fun longPressTogglesWithoutAnchorAndSelectsTheRangeFromTheLastToggle() = runTest {
83: fun toggledAddsAndRemoves() {
89: fun plusRangeWorksInEitherDirection() {
96: fun plusRangeKeepsTheExistingSelection() {
101: fun plusRangeClampsOutOfBoundsIndices() {
Exact file bytes / download · SHA-256 66b90cde06f207631270b972e585da73e3375451dc4ae37dabff5ff7a11ab54b.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
@OptIn(ExperimentalCoroutinesApi::class)
class MassMigrationSelectionTest {
private val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
sources = listOf(DbSource(id = 1, name = "Old", lang = "en", itemType = DbItemType.Manga, isAdded = true)),
mangas = listOf(
DbManga(id = 1, name = "A", link = "/a", source = "Old", sourceId = 1, itemType = DbItemType.Manga, favorite = true),
DbManga(id = 2, name = "B", link = "/b", source = "Old", sourceId = 1, itemType = DbItemType.Manga, favorite = true),
DbManga(id = 3, name = "C", link = "/c", source = "Old", sourceId = 1, itemType = DbItemType.Manga, favorite = true),
DbManga(id = 4, name = "Browsed", link = "/d", source = "Old", sourceId = 1, itemType = DbItemType.Manga),
DbManga(id = 5, name = "Other", link = "/e", source = "Elsewhere", itemType = DbItemType.Manga, favorite = true),
),
chapters = emptyList(),
),
)
private val repository = DefaultYokanRepository(database)
private val host = ViewModelTestHost()
private val dispatcher = host.dispatcher
@AfterTest
fun tearDown() = host.close()
private fun viewModel(scope: CoroutineScope): MassMigrationPreviewViewModel {
val settings = SettingsStore(repository, scope, onSchedulingChanged = {})
val index = LibraryIndexStore(repository, scope)
return host.create { MassMigrationPreviewViewModel(1, repository, settings, index, workDispatcher = dispatcher) }
}
@Test
fun startsWithEveryFavoriteTitleOfTheSourceSelected() = runTest {
val state = viewModel(backgroundScope).state.first { it.items != null }
assertEquals(listOf(1L, 2L, 3L), state.items?.map { it.manga.id })
assertEquals(listOf(1L, 2L, 3L), state.selectedMangaIds)
assertEquals(true, state.allSelected)
}
@Test
fun toggleAllDeselectsThenSelectsEverything() = runTest {
val vm = viewModel(backgroundScope)
vm.state.first { it.items != null }
vm.toggleAll()
assertEquals(emptyList(), vm.state.value.selectedMangaIds)
vm.toggleAll()
assertEquals(listOf(1L, 2L, 3L), vm.state.value.selectedMangaIds)
}
@Test
fun longPressTogglesWithoutAnchorAndSelectsTheRangeFromTheLastToggle() = runTest {
val vm = viewModel(backgroundScope)
vm.state.first { it.items != null }
vm.toggleAll()
vm.selectRangeTo(0)
assertEquals(listOf(1L), vm.state.value.selectedMangaIds)
vm.toggle(0)
assertEquals(emptyList(), vm.state.value.selectedMangaIds)
vm.selectRangeTo(2)
assertEquals(listOf(1L, 2L, 3L), vm.state.value.selectedMangaIds)
}
@Test
fun toggledAddsAndRemoves() {
assertEquals(setOf(1L, 3L), setOf(1L, 2L, 3L).toggled(2L))
assertEquals(setOf(1L, 2L, 3L), setOf(1L, 3L).toggled(2L))
}
@Test
fun plusRangeWorksInEitherDirection() {
val ids = listOf(10L, 20L, 30L, 40L, 50L)
assertEquals(setOf(20L, 30L, 40L), emptySet<Long>().plusRange(1, 3, ids))
assertEquals(setOf(30L, 40L, 50L), emptySet<Long>().plusRange(4, 2, ids))
}
@Test
fun plusRangeKeepsTheExistingSelection() {
assertEquals(setOf(10L, 40L, 50L), setOf(10L).plusRange(3, 4, listOf(10L, 20L, 30L, 40L, 50L)))
}
@Test
fun plusRangeClampsOutOfBoundsIndices() {
assertEquals(setOf(100L, 200L, 300L), emptySet<Long>().plusRange(-10, 50, listOf(100L, 200L, 300L)))
assertEquals(setOf(7L), setOf(7L).plusRange(0, 3, emptyList()))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/migration/SmarterMigrationViewModelTest.kt
- Source · test / fixture · 86 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
21: class SmarterMigrationViewModelTest {
46: private fun <T : ViewModel> track(vm: T): T = vm.also { viewModelJobs += checkNotNull(it.viewModelScope.coroutineContext[Job]) }
49: fun destinationsKeepSelectionOrderAndRemoveUnavailableSources() = runTest {
65: fun runnerReattachesWithoutRepeatingDiscoveryAndExposesReviewActions() = runTest {
69: fun runner(key: String, ids: List<Long>): MassMigrationRunnerViewModel = track(ViewModelProvider.create(store,
Exact file bytes / download · SHA-256 b3408afc000b1fbaf89d7a0d81724d4817ff11669acf90bdc9fbceccf937fc5a.
Complete file
package eu.friedcutlet.yokan.ui.screens.migration
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.migration.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.*
import kotlin.test.*
@OptIn(ExperimentalCoroutinesApi::class)
class SmarterMigrationViewModelTest {
private val store = ViewModelStore()
private val viewModelJobs = mutableListOf<Job>()
private val dispatcher = UnconfinedTestDispatcher()
private val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
sources = listOf(
DbSource(id = 1, name = "Old", lang = "en", itemType = DbItemType.Manga, isAdded = true),
DbSource(id = 2, name = "A", lang = "en", itemType = DbItemType.Manga, isAdded = true),
DbSource(id = 3, name = "B", lang = "all", itemType = DbItemType.Manga, isAdded = true),
DbSource(id = 4, name = "French", lang = "fr", itemType = DbItemType.Manga, isAdded = true),
DbSource(id = 5, name = "Disabled", lang = "en", itemType = DbItemType.Manga, isAdded = true, isActive = false),
DbSource(id = 6, name = "Not installed", lang = "en", itemType = DbItemType.Manga, isAdded = false),
),
mangas = listOf(DbManga(id = 10, name = "Title", link = "/old", sourceId = 1, source = "Old", lang = "en", itemType = DbItemType.Manga, favorite = true)),
chapters = emptyList(),
))
private val repository = DefaultYokanRepository(db)
@BeforeTest fun setup() = Dispatchers.setMain(dispatcher)
@AfterTest fun teardown() = runTest {
store.clear()
viewModelJobs.forEach { it.join() }
Dispatchers.resetMain()
}
private fun <T : ViewModel> track(vm: T): T = vm.also { viewModelJobs += checkNotNull(it.viewModelScope.coroutineContext[Job]) }
@Test
fun destinationsKeepSelectionOrderAndRemoveUnavailableSources() = runTest {
val vm = track(ViewModelProvider.create(store, viewModelFactory { initializer { MassMigrationDestinationViewModel(1, repository) } })[MassMigrationDestinationViewModel::class])
assertEquals(listOf(2L, 3L), vm.state.first { it.destinations != null }.destinations?.map { it.id })
vm.toggle(3)
vm.toggle(2)
vm.toggle(4)
assertEquals(listOf(3L, 2L), vm.state.value.selectedIds)
vm.move(2, -1)
assertEquals(listOf(2L, 3L), vm.state.value.selectedIds)
vm.move(2, -1)
assertEquals(listOf(2L, 3L), vm.state.value.selectedIds)
db.upsertSource(checkNotNull(db.source(2)).copy(isAdded = false))
assertEquals(listOf(3L), vm.state.first { it.destinations?.size == 1 }.selectedIds)
}
@Test
fun runnerReattachesWithoutRepeatingDiscoveryAndExposesReviewActions() = runTest {
val factory = MigrationTestFactory()
val service = MigrationService(repository, db, factory, SettingsStore(repository, backgroundScope, {}), backgroundScope,
workDispatcher = StandardTestDispatcher(testScheduler))
fun runner(key: String, ids: List<Long>): MassMigrationRunnerViewModel = track(ViewModelProvider.create(store,
viewModelFactory { initializer { MassMigrationRunnerViewModel(1, ids, listOf(10), service) } })[key, MassMigrationRunnerViewModel::class])
val first = runner("first", listOf(2, 3))
runCurrent()
assertEquals(MigrationPhase.Reviewing, first.state.value.progress?.phase)
val second = runner("second", listOf(2, 3))
assertEquals(first.state.value.progress, second.state.value.progress)
assertEquals(2, factory.searchCalls.size)
assertTrue(runner("other", listOf(3)).state.value.busyWithAnotherRun)
second.select(10, null)
assertEquals(1, first.state.value.progress?.skipped)
second.commit()
runCurrent()
assertTrue(db.manga(10)?.favorite == true)
second.cancel()
assertEquals(MigrationPhase.Cancelled, first.state.value.progress?.phase)
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailActionRowTest.kt
- Source · test / fixture · 70 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
17: class DetailActionRowTest {
26: private fun checkActions(width: Int, showWeb: Boolean) {
47: fun render() = onUi { time += 100_000_000L; scene.render(time).close() }
49: fun click(fraction: Float) {
65: private fun <T> onUi(block: () -> T): T {
Exact file bytes / download · SHA-256 47a1cbbde52e42809afc4b117e36e408ef06479a7f3653eaf8135bcf0b7b7dbf.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.Column
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventType
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.test.Test
import kotlin.test.assertEquals
class DetailActionRowTest {
@Test fun migrationImmediatelyFollowsWebViewOnPhoneAndDesktop() {
for (width in listOf(360, 1024)) checkActions(width, showWeb = true)
}
@Test fun migrationRemainsAvailableWhenWebViewIsHidden() {
checkActions(360, showWeb = false)
}
private fun checkActions(width: Int, showWeb: Boolean) {
val repository = DefaultYokanRepository(InMemoryYokanDatabase(emptySnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "Test title")),
)))
val manga = checkNotNull(repository.manga(1))
val clicks = mutableListOf<String>()
val scene = onUi { ImageComposeScene(width, 140) {
YokanTheme(darkTheme = false) {
Column {
DetailActionRow(
manga = manga, trackCount = 0, showWeb = showWeb,
onFavorite = { clicks += "favorite" }, onFavoriteLongClick = null,
automaticUpdateDays = null, onSmartUpdate = { clicks += "updates" },
onTrack = { clicks += "track" }, onWeb = { clicks += "web" },
onMigrate = { clicks += "migrate" },
)
}
}
} }
try {
var time = 0L
fun render() = onUi { time += 100_000_000L; scene.render(time).close() }
repeat(4) { render() }
fun click(fraction: Float) {
onUi {
val point = Offset(width * fraction, 24f)
scene.sendPointerEvent(PointerEventType.Press, point)
scene.sendPointerEvent(PointerEventType.Release, point)
}
render()
}
if (showWeb) click(.7f) // Fourth of five equal-width actions.
click(if (showWeb) .9f else 5f / 6f)
assertEquals(if (showWeb) listOf("web", "migrate") else listOf("migrate"), clicks)
} finally {
onUi { scene.close() }
}
}
private fun <T> onUi(block: () -> T): T {
val task = FutureTask<T> { block() }
SwingUtilities.invokeAndWait(task)
return task.get()
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailScreenRenderTest.kt
- Source · test / fixture · 136 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
29: class DetailScreenRenderTest {
88: fun save(name: String) {
97: fun click(x: Float, y: Float) {
131: private fun <T> onUi(block: () -> T): T {
Exact file bytes / download · SHA-256 f43d0b11736bde2c888e257a65d138b881b9585bfe22e591d103c803657852ec.
Complete file
package eu.friedcutlet.yokan.ui.screens.detail
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.remember
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.use
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.meanChapterUpdateDays
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.io.File
import javax.swing.SwingUtilities
import java.util.concurrent.FutureTask
import kotlin.test.Test
import kotlin.test.assertEquals
import eu.friedcutlet.yokan.services.library.sortedChapters
/** Real Compose layout smoke test; exported images support the bounded visual review. */
class DetailScreenRenderTest {
@Test fun rendersPhoneAndDesktopWithAutomaticCadenceAndGenreActions() {
run {
val db = InMemoryYokanDatabase(emptySnapshot().copy(
mangas = listOf(DbManga(
id = 1, name = "Frieren: Beyond Journey’s End", itemType = DbItemType.Anime,
description = "An elven mage retraces a journey with new companions, discovering what the time they shared meant to her.",
favorite = true, source = "Test extension", lang = "en", sourceId = 2,
genre = listOf("Adventure", "Drama", "Fantasy", "Slice of Life"),
cast = listOf(
eu.friedcutlet.yokan.domain.TitleCredit("Sample Voice Actor", "Voice actor", "Sample hero"),
eu.friedcutlet.yokan.domain.TitleCredit("Another Performer With a Long Name", "Guest voice", "A supporting character"),
),
)),
chapters = (1L..12L).map { DbChapter(
id = it, mangaId = 1, name = "Episode $it", url = "/episode/$it",
dateUpload = (1_767_225_600_000L + it * 604_800_000L).toString(),
isRead = it <= 3, isBookmarked = it == 5L,
) },
sources = listOf(DbSource(id = 2, name = "Test extension", itemType = DbItemType.Anime, lang = "en", isAdded = true)),
))
val repository = DefaultYokanRepository(db)
val manga = checkNotNull(repository.manga(1))
val settings = repository.dbSettings()
val chapters = sortedChapters(manga, repository.chapters(1), settings)
val state = DetailState(
DetailContent(
manga = manga,
settings = settings,
source = repository.source(2),
chapters = chapters,
continueChapter = chapters.firstOrNull { !it.isRead },
automaticUpdateDays = meanChapterUpdateDays(chapters.map { it.dateUpload }),
genreSources = repository.sources(manga.itemType).filter { it.isAdded && it.isActive },
loaded = true,
seasons = listOf(0, 1, 2),
),
)
val owner = object : LifecycleOwner {
override val lifecycle = LifecycleRegistry.createUnsafe(this)
}
onUi { owner.lifecycle.currentState = Lifecycle.State.RESUMED }
try {
listOf(Triple(360, 1100, true), Triple(1024, 800, false)).forEach { (width, height, dark) ->
val scene = onUi { ImageComposeScene(width, height) {
CompositionLocalProvider(LocalLifecycleOwner provides owner) {
YokanTheme(darkTheme = dark) {
Surface(Modifier.fillMaxSize()) {
DetailScreen(
state, remember { SnackbarHostState() }, downloadRoot = "", onEvent = {}, onNavigate = {},
onLibrarySearch = {}, onBack = {}, onSaveCover = { "" }, onShareCover = { "" }, onChangeCover = { "" },
)
}
}
}
} }
try {
repeat(8) { onUi { scene.render(it * 16_000_000L).close() } }
var time = 200_000_000L
fun save(name: String) {
repeat(4) { time += 100_000_000L; onUi { scene.render(time).close() } }
onUi { scene.render(time).use { image ->
assertEquals(width, image.width)
val output = File("build/reports/detail-ui/$name.png")
output.parentFile.mkdirs()
checkNotNull(image.encodeToData()).use { output.writeBytes(it.bytes) }
} }
}
fun click(x: Float, y: Float) {
onUi {
scene.sendPointerEvent(PointerEventType.Press, Offset(x, y))
scene.sendPointerEvent(PointerEventType.Release, Offset(x, y))
}
repeat(4) { time += 100_000_000L; onUi { scene.render(time).close() } }
}
save("detail-$width")
if (width == 1024) {
click(60f, 420f)
save("genre-menu")
click(5f, 60f)
time += 100_000_000L
onUi { scene.render(time).close() }
click(960f, 100f)
save("selection-menu")
}
if (width == 1024) click(5f, 60f)
onUi {
scene.sendPointerEvent(PointerEventType.Scroll, Offset(180f, 500f), scrollDelta = Offset(0f, 4f))
}
repeat(8) { time += 100_000_000L; onUi { scene.render(time).close() } }
save("detail-cast-$width")
} finally {
onUi { scene.close() }
}
}
} finally {
onUi { owner.lifecycle.currentState = Lifecycle.State.DESTROYED }
}
}
}
// Return to the event loop between frames so popup transitions can complete.
private fun <T> onUi(block: () -> T): T {
val task = FutureTask<T> { block() }
SwingUtilities.invokeAndWait(task)
return task.get()
}
}