Prerequisites: repository, runtime contract and navigation. File workbook.
How to write this chapter
Connect catalog browsing to title detail and migration. The main challenge is maintaining request and title identity while asynchronous searches, refreshes and preview/apply flows overlap.
The 80 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.
Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.
Implementation sequence:
- Step 1: Implement catalog/source search, filters, presets and enrollment UI.
- Step 2: Implement source preferences, languages, editing and local creation.
- Step 3: Build detail state, selection and policies before layout.
- Step 4: Render title, chapter, season and action components from that state.
- Step 5: Plan, preview and apply single or mass source migration.
- Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #
Step 1: source browsing
Implement BrowseViewModel and source/catalog rows, language/media filters, repository settings entry points, installed/update state and source badge summaries. Build SourceHomeViewModel/SourceListingLoader around listing/filter/page state, distinct query identity and cancellation. Old search results must not replace a newer query. Add global multi-source search with per-source failures and bounded concurrency.
Implement filter schema rendering and saved source presets, naming/reset/edit/apply behavior, genre links and source-library hiding. Hide already-followed entries according to profile/media/source policy without losing pagination state. Signed catalog enrollment from chapter 07 connects here.
Follow the code
Build listing state around query/filter/page identity before rendering rows. A new request replaces or cancels an older request, and a late completion must still check its identity before publication. Saved presets bind to a stable source/schema, not just a local row ID. Global search combines independent source results without turning one failure into a blank page. Enrollment screens call chapter 07's host-trust API; ordinary source creation does not grant trust.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceListingLoader.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/BrowseViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GlobalSearchViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresetState.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SavedSourcePresets.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/BrowseScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/CatalogEnrollmentViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GenreSearch.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GlobalSearchScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogEnrollment.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogSheet.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogSheetState.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogText.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceFilterSheet.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresets.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceListingLoader.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Treat query, filters and page cursor as one request identity. A cancellation request is not enough by itself when a delegate can return late; publication needs the matching identity.
The implementation below defines SourceTab, RuntimeLoad, SourceListingLoader, loadSourceListing, loadSourceFilters, loadSupportsLatest, withRuntimeFallback.
The source describes its contract as:
Whether the runtime offers a Latest listing; falls back to the stored flag when the runtime fails.
Cross-chapter imports used by this file: Source, ExtensionLogger, ExtensionRuntimeService, SourceFilter, SourceListing. Keep those contracts available as you connect this step.
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)
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SourceHomeLoadKey, SourceHomeUiState, List, SourceHomeCache, get, put, SourceHomeViewModel, collectSourceData, fillHiddenPages, initialize and 22 further declarations.
The source describes its contract as:
False while a genre request waits for the source's filter schema.
Cross-chapter imports used by this file: SettingsStore, YokanRepository, DbSavedSearch, DbSource, Source, FilterSelection. Keep those contracts available as you connect this step.
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,
)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/BrowseViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines BrowseSources, BrowseUiState, needsUpdate, sortedByLanguage, extensionSections, ExtensionSections, browseSources, allBrowseSources, BrowseViewModel, togglePinned and 4 further declarations.
The source describes its contract as:
One item type's Browse panes, grouped off the main thread.
Cross-chapter imports used by this file: SettingsStore, YokanRepository, DbSettings, ItemType, Source, SourceInstallService. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GlobalSearchViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SourceSearchState, GlobalSearchUiState, GlobalSearchViewModel, search, setQuery, submit, cacheRemote.
The source describes its contract as:
Installed, active sources of the item type, narrowed by the pinned-only and NSFW settings.
Cross-chapter imports used by this file: SourceListing, SettingsStore, YokanRepository, ItemType, Source, RemoteManga. Keep those contracts available as you connect this step.
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
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresetState.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines PresetEditMode, PresetEditor, PresetReview, SourcePresetEvent, SaveCurrent, Rename, Update, NameChanged, Commit, CancelEdit and 5 further declarations.
Cross-chapter imports used by this file: DbSavedSearch, PresetValidation. Keep those contracts available as you connect this step.
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
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SavedSourcePresets.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SourcePresetEditor, SavedSourcePresetsSheet, SourcePresetReview, presetIssueText.
Cross-chapter imports used by this file: DbSavedSearch, PresetIssue, PresetIssueReason. Keep those contracts available as you connect this step.
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)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/BrowseScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines BrowseRoute, BrowseMode, BrowseTab, BrowseScreen, SourcesPane, LocalLibraryTile, ExtensionsPane, SectionHeader, SourceRow, ExtensionRowMode and 3 further declarations.
The source describes its contract as:
Top-level mode within the Browse tab: installed sources vs. extension catalogue.
Cross-chapter imports used by this file: ItemType, Source, YokanScaffold, NavSection, Navigator, Route. Keep those contracts available as you connect this step.
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,
)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/CatalogEnrollmentViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines CatalogEnrollmentActions, enroll, refresh, install, InstallationServiceActions, CatalogEnrollmentOperation, CatalogEnrollmentDisplayError, CatalogEnrollmentRetry, Enroll, Refresh and 15 further declarations.
The source describes its contract as:
Small seam for lifecycle-safe UI tests; production uses [RecipeCatalogInstallationService].
Cross-chapter imports used by this file: CatalogEnrollmentCode, RecipeCatalogEnrollmentServiceResult, RecipeCatalogInstallServiceResult, RecipeCatalogInstallationService, RecipeCatalogPreview, RecipeCatalogPreviewArtifact. Keep those contracts available as you connect this step.
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)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GenreSearch.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines GenreSearchRequest, genreSearchRequest.
The source describes its contract as:
Use the extension's outbound filter values, never the displayed genre label as a value.
Cross-chapter imports used by this file: FilterSelection, SourceFilter, SourceFilterKind. Keep those contracts available as you connect this step.
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)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GlobalSearchScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines GlobalSearchRoute, GlobalSearchScreen, SearchSourceSection, RemoteMangaCard.
Cross-chapter imports used by this file: YokanScaffold, ItemType, Source, RemoteManga, YokanRuntime, AppBarSearchField. Keep those contracts available as you connect this step.
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() ?: "" },
)
},
)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogEnrollment.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SignedCatalogSheetSlot, rememberSignedCatalogSheet.
The source describes its contract as:
The "add signed catalog" entry point: [onAdd] opens [sheet]; null when enrollment is unavailable.
Cross-chapter imports used by this file: RecipeCatalogInstallationService. Keep those contracts available as you connect this step.
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,
)
}
},
)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogSheet.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SignedCatalogSheet, CatalogIdentity, CatalogValue, CatalogError.
The source describes its contract as:
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.
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)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogSheetState.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SignedCatalogIdentity, SignedCatalogError, SignedCatalogRecipeStatus, SignedCatalogRecipe, SignedCatalogPreview, recipeAt, SignedCatalogStage, Paste, Review, Enrolled and 10 further declarations.
The source describes its contract as:
Display data only. The owner retains the parsed proposal and performs all trust checks.
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
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogText.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines signedCatalogText, signedCatalogErrorText.
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."
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceFilterSheet.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SourceFilterSheet, FilterSheetContent, FilterRow, FilterChoiceRow.
The source describes its contract as:
Bottom sheet editing a source's filter schema; [onApply] commits the pending [selections].
Cross-chapter imports used by this file: FilterSelection, SourceFilter, SourceFilterKind. Keep those contracts available as you connect this step.
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,
)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SourceHomeRoute, healMissingPayload, SourceHomeScreen, SourceCoverCell, LoadMoreTile.
The source describes its contract as:
Fetches the payload of sources flagged added before their code was downloaded (legacy flag flip).
Cross-chapter imports used by this file: YokanRuntime, DbSavedSearch, Source, FilterSelection, RemoteManga, EmptyState. Keep those contracts available as you connect this step.
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,
)
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresets.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DbSettings.withSourcePreset, DbSettings.withoutSourcePreset, DbSettings.sourcePreset, newPresetId, PresetCommit, commitPreset, SourceHomeUiState.withPresetApplied.
The source describes its contract as:
Result of committing the open [PresetEditor]: the editor to show next and the preset to store, if any.
Cross-chapter imports used by this file: DbSavedSearch, DbSettings, DbSource, PresetIssue, PresetIssueReason, PresetValidation. Keep those contracts available as you connect this step.
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)
}
Check your understanding
Issue query A, then B, finish B first and A last. The visible rows and pagination cursor must still belong to B. [chapter-content-end]: #
Step 2: extension management
Build language/source-filter screens, extension detail, source preferences, code editor and create-source flow. Persist edits through the database/service boundary and evict changed runtimes. An edited source must be re-evaluated next time it is used. Keep validation/error state visible. Creating a local source is distinct from granting signed-catalog trust.
Follow the code
Extension editing persists through the source service and invalidates the runtime built from the previous source record. Separate draft editor state, validation and saved code. Language/source filters affect what is shown; source preference values affect runtime behavior and must retain their serialized type. Creating a local source and updating a signed installed recipe follow different authority paths.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionDetailViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CodeEditorViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CreateExtensionViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CodeEditorScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CreateExtensionScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionDetailScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionLanguagesScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ItemTypeSelector.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourceFiltersScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourceLanguagesViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourcePreferencesCard.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionDetailViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines YokanRepository.observeDbSource, YokanRepository.currentDbSource, ExtensionDetailUiState, ExtensionDetailViewModel, loadPreferences, refreshPreferences, setPreference, uninstall, deleteCookies.
The source describes its contract as:
The source row, re-read only when the sources table changes.
Cross-chapter imports used by this file: SettingsStore, YokanRepository, DbSource, YokanDatabase, Source, ExtensionRuntimeFactory. Keep those contracts available as you connect this step.
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}.") }
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CodeEditorViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines CodeEditorViewModel, save.
The source describes its contract as:
The stored source row behind the code editor; edits stay in the screen until saved.
Cross-chapter imports used by this file: YokanRepository, DbSource. Keep those contracts available as you connect this step.
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)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CreateExtensionViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Reviewed implementation — use this listing. Inject a narrow source-creation command instead of the entire database; expose mapped domain results and preserve cancellation. Architecture review.
Original pinned file for comparison.
The implementation below defines CreateExtensionUiState, CreateExtensionViewModel, create.
The source describes its contract as:
Saves a locally authored extension source.
Cross-chapter imports used by this file: DbSource, Source. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.extensions
import androidx.lifecycle.ViewModel
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.services.catchingNonCancellation
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 createSource: (DbSource) -> Source,
) : ViewModel() {
private val _state = MutableStateFlow(CreateExtensionUiState())
val state: StateFlow<CreateExtensionUiState> = _state.asStateFlow()
fun create(source: DbSource) {
catchingNonCancellation { createSource(source) }
.onSuccess { saved -> _state.update { it.copy(created = saved, error = null) } }
.onFailure { err -> _state.update { it.copy(error = err.message ?: "Could not create extension") } }
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CodeEditorScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines CodeEditorRoute, CodeEditorScreen.
Cross-chapter imports used by this file: YokanRuntime, DbSource, MissingRoute, Navigator, Route, YokanScaffold. Keep those contracts available as you connect this step.
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,
),
)
}
}
}
}
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/CreateExtensionScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Reviewed implementation — use this listing. Capture the source-creation dependency at the route boundary and pass a command to the ViewModel. Architecture review.
Original pinned file for comparison.
The implementation below defines CreateExtensionRoute, CreateExtensionScreen, sourceCodeLanguageLabel, javaScriptExtensionTemplate, DefaultExtension.
Cross-chapter imports used by this file: YokanRuntime, DbSource, DbSourceCodeLanguage, ItemType, RouteScaffold, Navigator. Keep those contracts available as you connect this step.
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.toDomain
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) {
// Capture the dependency at the route boundary; the command never looks up a later profile.
val database = YokanRuntime.services.database
val vm = viewModel { CreateExtensionViewModel { source -> database.upsertSource(source).toDomain() } }
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()
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionDetailScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ExtensionDetailRoute, ExtensionDetailScreen, ExtensionStat.
Cross-chapter imports used by this file: YokanRuntime, Source, RouteScaffold, MissingRoute, Navigator, Route. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionLanguagesScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ExtensionLanguagesRoute, ExtensionLanguagesScreen.
Cross-chapter imports used by this file: ItemType, YokanRuntime, Navigator, Route, YokanScaffold, languageName. Keep those contracts available as you connect this step.
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,
),
)
}
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ItemTypeSelector.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ItemTypeSelector.
Cross-chapter imports used by this file: ItemType. Keep those contracts available as you connect this step.
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) })
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourceFiltersScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SourceFiltersRoute, SourceFiltersScreen.
Cross-chapter imports used by this file: YokanRuntime, ItemType, Source, RouteScaffold, Navigator, Route. Keep those contracts available as you connect this step.
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) }),
)
}
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourceLanguagesViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Reviewed implementation — use this listing. Derive media selection from the public state and guard incoming projections atomically, removing a second mutable selection authority. Architecture review.
Original pinned file for comparison.
The implementation below defines SourceLanguagesUiState, languageGroups, SourceLanguagesViewModel, selectType, setLanguageActive, setAllActive, setAdded.
The source describes its contract as:
Sources grouped by normalized language code, groups by display name, rows by name.
Cross-chapter imports used by this file: YokanRepository, ItemType, Source, languageName, normalizedLanguageCode. Keep those contracts available as you connect this step.
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.flow.map
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.update
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()
init {
viewModelScope.launch {
state.map { it.itemType }.distinctUntilChanged().flatMapLatest { type ->
repository.observe({ it.sources }) { SourceLanguagesUiState(type, languageGroups(sources(type))) }
}.collect { next ->
_state.update { current ->
if (next.itemType == current.itemType) next else current
}
}
}
}
fun selectType(type: ItemType) {
val next = SourceLanguagesUiState(type, languageGroups(repository.sources(type)))
_state.update { next }
}
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)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/SourcePreferencesCard.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DbSettings.withSourcePreference, SourcePreferencesCard, SourcePreferenceField.
The source describes its contract as:
Stores [value] for the source's preference [key], replacing the previous value.
Cross-chapter imports used by this file: DbSettings, DbSource, DbSourceCodeLanguage, DbSourcePreference, SourcePreferenceValue. Keep those contracts available as you connect this step.
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(),
)
}
}
}
Check your understanding
Edit a source while its old runtime is leased. Let that call finish, then verify the next call evaluates the saved code and the editor shows any validation failure. [chapter-content-end]: #
Step 3: detail state before layout
DetailViewModel loads a title, source state, chapters/seasons, progress, downloads, tracks, credits and notes. Implement refresh and request ownership first. Build immutable derived chapter rows and counts; use stable chapter IDs, not list positions, for actions. Account for unavailable sources, deleted titles and partial metadata.
Implement favorite/category changes, read/unread/bookmark, manual filler/reset-to-source, chapter selection/bulk actions, scanlator exclusions/priorities, chapter sort/filter defaults, smart-update overrides, notes and cover inspection. Source refresh must preserve user overrides. Season parents need a separate season list and episode selection path.
Follow the code
The detail ViewModel observes the current title and combines chapters, source capability, downloads, tracking and notes. Commands use stable IDs and revalidate current records. Selection is derived from visible rows without confusing their display order with reading order. Filler overrides, scanlator priorities and private notes have different ownership from source metadata. Preserve those distinctions during refresh and bulk operations.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterSelection.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailDownloads.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailNotes.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/CoverInspection.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterSelection.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Selection ranges follow visible order while stored targets are stable chapter IDs. Retaining only still-visible/still-existing selections prevents bulk actions from hitting stale rows.
The implementation below defines ChapterSelectionOption, ChapterSelectionState, toggle, retainVisible, rangeTo, selectRange, select.
The source describes its contract as:
Selected chapter ids; [anchorId] is where range selections start. Chapter lists are in display order.
Cross-chapter imports used by this file: Chapter. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DetailContent, DetailSeasonTitle, TrackerSearchState, DetailState, DetailEvent, Refresh, RefreshMetadata, Share, ExportMetadata, EditNote and 62 further declarations.
The source describes its contract as:
What the detail screen shows about the title, rebuilt off the main thread when its data changes.
Cross-chapter imports used by this file: LibraryIndex, LibraryIndexStore, SettingsStore, YokanRepository, movedScanlator, equivalentReleaseIds. Keep those contracts available as you connect this step.
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" }
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailDownloads.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DownloadDestinationDialog, DownloadDestinationRow, DeleteChaptersDialog, PendingDownloadRequest, Single, Bulk, DetailDownloadOption, downloadOptionLabel, chaptersForDownloadOption.
The source describes its contract as:
Confirms deleting downloaded files, or local chapters when [isLocalEntry]; [deletesEntry] warns the whole title goes.
Cross-chapter imports used by this file: DbLocalFolder, Chapter, ItemType, ScrollbarBox. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailNotes.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DetailNotePreview, DetailNoteEditor.
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)) } },
)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/CoverInspection.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines CoverTransform, CoverInspectionKeyAction, coverInspectionKeyAction, CoverInspectionUiState, CoverInspectionViewModel, updateViewport, imageLoading, imageReady, imageFailed, retry and 26 further declarations.
Cross-chapter imports used by this file: Manga, HttpRequest, readerImageFormat, pickFile, shareImage. Keep those contracts available as you connect this step.
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) },
)
}
Check your understanding
Select a range, filter the chapter list, then refresh metadata. Verify selected IDs remain valid and manual filler/notes are not overwritten. [chapter-content-end]: #
Step 4: assemble detail components
Build header/top bar/quick actions, chapter and season lists, credit rows, notes, cover viewer, category/filter sheets, tracker search and download controls. Route Reader to the correct manga, novel or anime experience based on title type. Resume selects the saved/next unread item through the shared chapter sequence; do not guess from displayed descending order.
Connect related-source titles, recommendations, sequels and watch order to chapter 19. Keep the source relation contract distinct from metadata-provider relationships. A related title opens or ingests its target, not the current title with a new label.
Follow the code
Assemble the header, metadata/credits, season list and chapter list from the same detail state. Reader navigation chooses manga, novel or anime by ItemType and uses the shared sequence to resume; displayed descending order is not a resume algorithm. Sheets/dialogs edit preferences through callbacks and show busy/error states. Related-title actions resolve their target identity before opening it.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailHeader.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterList.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailSeasonList.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailQuickActions.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/CategoryEditorSheet.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterFilterSheet.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailTopBar.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/EpisodeSeasonSelector.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ScanlatorPriorityControls.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/SmartUpdateDialog.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/TitleCastCredits.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/TrackerSearchDialog.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DetailRoute, DetailDialog, Cover, Filter, Tracker, SmartUpdate, Categories, Range, Delete, Destination and 13 further declarations.
The source describes its contract as:
The one dialog or sheet the detail screen shows at a time; the note editor follows [DetailState.noteDraft].
Cross-chapter imports used by this file: YokanRuntime, ProfileSession, DbItemType, DbLocalFolder, Chapter, ItemType. Keep those contracts available as you connect this step.
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")
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailHeader.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DetailBackdropHeader, DetailSideHeader, TitleOptionsMenu, DetailDescription, String.initials.
Cross-chapter imports used by this file: Manga, CoverImage. Keep those contracts available as you connect this step.
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 { "?" }
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterList.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ChaptersHeaderRow, formatAnimeProgress, completeChapterSwipeDismiss, ChapterRow, ChapterSelectionTopBar, ChapterSelectionBottomBar, EmptyChaptersCard, formatChapterDate, Modifier.onSecondaryClick, chapterLabel.
Cross-chapter imports used by this file: DbSettings, Chapter, ItemType, Manga, CoverImage, formatAbsoluteDate. Keep those contracts available as you connect this step.
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"
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailSeasonList.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DetailSeasonsHeader, DetailSeasonRow.
The source describes its contract as:
One season record: opening it shows that season's own detail page; the button resumes its next episode.
Cross-chapter imports used by this file: CoverImage. Keep those contracts available as you connect this step.
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))
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailQuickActions.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DetailRelatedActions, RelatedAction, ChapterSelectionMenu, ChapterRangeDialog, DetailGenreTags, DetailActionRow, DetailActionButton.
Cross-chapter imports used by this file: Chapter, ItemType, Source, Manga. Keep those contracts available as you connect this step.
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,
)
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/CategoryEditorSheet.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines CategoryEditorSheet.
Cross-chapter imports used by this file: Category, Manga, ScrollbarBox. Keep those contracts available as you connect this step.
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)) }
}
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterFilterSheet.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ChapterFilterSheet, SetChapterListDefaultDialog, chapterSortLabel, chapterFilterLabel.
Cross-chapter imports used by this file: DbSettings, normalizeScanlator, ItemType, Manga, ScrollbarBox, ChapterFilterKind. Keep those contracts available as you connect this step.
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
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailTopBar.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DetailTopBar, Entry.
The source describes its contract as:
The detail app bar: back, bulk-download menu, chapter filter sheet, and the title's overflow actions.
Cross-chapter imports used by this file: ItemType, Manga, Source, RoomState, Route. Keep those contracts available as you connect this step.
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
},
),
)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/EpisodeSeasonSelector.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines EpisodeSeasonSelector.
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),
)
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ScanlatorPriorityControls.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ScanlatorPriorityControls.
Cross-chapter imports used by this file: orderedScanlators, normalizeScanlator. Keep those contracts available as you connect this step.
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))
}
}
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/SmartUpdateDialog.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines SmartUpdateDialog.
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)) },
)
}
}
}
},
)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/TitleCastCredits.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines TitleCastCredits.
Cross-chapter imports used by this file: TitleCredit, CoverImage. Keep those contracts available as you connect this step.
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)
}
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/TrackerSearchDialog.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines TrackerSearchDialog, submitTrackerSearch.
Cross-chapter imports used by this file: DbTrackSearch, Manga, ScrollbarBox. Keep those contracts available as you connect this step.
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
},
)
}
Check your understanding
Open a season parent and a normal title. Check that the appropriate rows/actions are shown and resume selects the intended release rather than the first displayed row. [chapter-content-end]: #
Step 5: implement source migration
Build MigrationPlanner/MigrationService first, then single and mass migration ViewModels/screens. Search/select destination sources, compare candidate matches and chapter mapping, preview retained data, then apply against the captured source/title identity. Preserve favorite/categories, notes, relevant progress/bookmarks and tracking where the migration policy specifies. Do not equate chapters solely by list index.
Mass migration has source selection, destination selection, preview and runner stages, progress/error/retry/skip handling and stable selection. A cancellation must not report all titles complete. A source/title edited or deleted during preview must be revalidated before apply.
Follow the code
The planner compares destination candidates and chapter correspondence without mutating the source library. A preview records what will transfer, but apply rereads the source/destination identities before committing. Preserve selected favorite/category/note/progress/tracker state according to the policy, not by list position. Mass migration is the same guarded operation repeated with independent progress, skip, error and cancellation outcomes.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MigrationPlanner.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MigrationService.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MassMigrationProgress.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationDestinationScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationDestinationViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationPreviewScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationPreviewViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationRunnerScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationRunnerViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationSourceScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationSourceViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationPreviewSheet.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationScreen.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MigrationPlanner.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Planning is inspectable and should not mutate the current library. Application validates its captured identities again after the user has had time to review the plan.
The implementation below defines MigrationSearchLimits, normalizeMigrationTitle, migrationMatchReason, migrationSourceCompatible, migrationChapterCoverage, MigrationPlanner, discover, search, rankedMigrationCandidates.
The source describes its contract as:
Bounds apply per title/source, including all alias searches and detail fetches.
Cross-chapter imports used by this file: YokanDatabase, Manga, Source, chapterReleaseIdentity, ExtensionRuntimeFactory, RemoteDetail. Keep those contracts available as you connect this step.
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 },
)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MigrationService.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MigrationService, migrate, migratePrepared, start, discover, select, retry, commitSelected, cancel, updateItem.
The source describes its contract as:
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.
Cross-chapter imports used by this file: SettingsStore, YokanRepository, YokanDatabase, Manga, Source, mergePrivateNotes. Keep those contracts available as you connect this step.
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 }) }
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MigrationPreview, MigrationState, MigrationViewModel, changeQuery, submit, clear, openPreview, dismissPreview, migrate, search and 1 further declarations.
The source describes its contract as:
The candidate the user tapped, with its destination detail.
Cross-chapter imports used by this file: YokanRepository, YokanDatabase, Manga, Source, ExtensionRuntimeFactory, RemoteDetail. Keep those contracts available as you connect this step.
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 }
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MassMigrationProgress.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MigrationPhase, MigrationItemStatus, MigrationMatchReason, MigrationSearchIssue, MigrationCandidateKey, MigrationCandidate, MigrationSourceResult, MigrationReviewItem, MassMigrationProgress.
The source describes its contract as:
One database-owned run. Discovery never mutates the library; transfer requires review.
Cross-chapter imports used by this file: Manga, Source, RemoteDetail. Keep those contracts available as you connect this step.
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
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationDestinationScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MassMigrationDestinationRoute, MassMigrationDestinationScreen.
Cross-chapter imports used by this file: YokanRuntime, RouteScaffold, Navigator, Route. Keep those contracts available as you connect this step.
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))
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationDestinationViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MassMigrationDestinationState, MassMigrationDestinationViewModel, toggle, move.
The source describes its contract as:
Installed (
isAdded) sources of the migrated source's type, excluding itself; migrating to an uninstalled extension would just fail at the runtime step.
Cross-chapter imports used by this file: YokanRepository, Source. Keep those contracts available as you connect this step.
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] }
})
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationPreviewScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MassMigrationPreviewRoute, MassMigrationPreviewScreen, MassMigrationPreviewCard.
Cross-chapter imports used by this file: YokanRuntime, Source, RouteScaffold, MissingRoute, Navigator, Route. Keep those contracts available as you connect this step.
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,
)
}
}
}
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationPreviewViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MassMigrationPreviewItem, MassMigrationPreviewState, MassMigrationPreviewViewModel, toggle, selectRangeTo, toggleAll, Set.
The source describes its contract as:
A library title of the migrated source with the chapters shown in its expandable section.
Cross-chapter imports used by this file: LibraryIndexStore, SettingsStore, YokanRepository, Manga, Source, sortedChapters. Keep those contracts available as you connect this step.
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)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationRunnerScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MassMigrationRunnerRoute, MassMigrationRunnerScreen, MigrationReviewCard, phaseLabel, itemStatusLabel, matchLabel, issueLabel.
Cross-chapter imports used by this file: YokanRuntime, RouteScaffold, Navigator, Route. Keep those contracts available as you connect this step.
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
})
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationRunnerViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MassMigrationRunnerState, MassMigrationRunnerViewModel, select, retry, commit, cancel.
The source describes its contract as:
Mirrors the run owned by this repository/session; route recreation does not restart it.
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()
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationSourceScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MassMigrationRoute, MassMigrationSourceScreen.
Cross-chapter imports used by this file: YokanRuntime, Source, EmptyState, RouteScaffold, Navigator, Route. Keep those contracts available as you connect this step.
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()
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationSourceViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MassMigrationSourceRow, MassMigrationSourceViewModel.
The source describes its contract as:
Sources of [itemType] that have favorite titles; null until the library has been read.
Cross-chapter imports used by this file: YokanRepository, ItemType, Source. Keep those contracts available as you connect this step.
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 }
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationPreviewSheet.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MigrationPreviewSheet.
The source describes its contract as:
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.
Cross-chapter imports used by this file: languageName. Keep those contracts available as you connect this step.
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))
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MigrateRoute, MigrationScreen, MigrationResultCard.
Cross-chapter imports used by this file: YokanRuntime, Source, RemoteManga, EmptyState, AppBarSearchField, Navigator. Keep those contracts available as you connect this step.
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,
)
}
}
Check your understanding
Create a preview, then delete/rebind a title before Apply. Expect a conflict or skipped/error result rather than recreation of the old title or a false completed count. [chapter-content-end]: #
Recreate the tests and verify the chapter
Recreate browse/preset/enrollment, detail/selection and migration test families. Run the shared ViewModel/policy fixtures on desktop, including out-of-order responses and cancellation. Then exercise browse → favorite → resume → migration through the UI with a controlled source rather than a changing public site.
These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/migration/MigrationServiceTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines MigrationServiceTest, TestScope.service, migrateMovesTheTitleAndClearsItsUpdateError, migrationRetainsDifferingDestinationNotes, startReviewsTheMatchBeforeMigratingThroughTheSamePath, FakeRuntimeFactory, create, FakeRuntime, search, detail.
The source describes its contract as:
Search offers a near miss before the exact title; detail serves "/new".
Read the setup, action and assertions in these cases before implementing their production paths:
migrateMovesTheTitleAndClearsItsUpdateErrormigrationRetainsDifferingDestinationNotesstartReviewsTheMatchBeforeMigratingThroughTheSamePath
Cross-chapter imports used by this file: DefaultYokanRepository, SettingsStore, DbChapter, DbItemType, DbManga, DbSource. Keep those contracts available as you connect this step.
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")))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/migration/SmarterMigrationTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines SmarterMigrationTest, database, TestScope.service, matchingUsesNormalizedTitlesAliasesAndConservativeSimilarity, coverageKeepsVolumesFractionsLanguagesSpecialsAndUncertainEntries, laterSourceWithMoreDistinctChaptersWinsAndCommitReusesReviewedDetails, explicitOverrideAndSkipPreserveAccurateTotalsIncludingUnmatchedAndFailures, rankingBreaksCoverageTiesByConfidenceSourceOrderAndUrl, candidate, paginationLimitsAndDetailErrorsAreVisibleAndRetryRefreshesTheProposal and 11 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
matchingUsesNormalizedTitlesAliasesAndConservativeSimilaritycoverageKeepsVolumesFractionsLanguagesSpecialsAndUncertainEntrieslaterSourceWithMoreDistinctChaptersWinsAndCommitReusesReviewedDetailsexplicitOverrideAndSkipPreserveAccurateTotalsIncludingUnmatchedAndFailuresrankingBreaksCoverageTiesByConfidenceSourceOrderAndUrlpaginationLimitsAndDetailErrorsAreVisibleAndRetryRefreshesTheProposalsearchesEveryCompatibleSourceWithBoundedConcurrencyAndIndependentTimeoutscancellationStopsDiscoveryAndNeverStartsTransferunavailableDestinationAtCommitFailsWithoutUnfavoritingTheOriginalfailedOrCancelledTransferLeavesTheOriginalFavoriteAndItsProgressIntactparentDeadlinePropagatesInsteadOfBecomingAnOrdinarySourceTimeoutaliasesDeduplicateCandidateFetchesAndCacheDetailsForTheRun
Cross-chapter imports used by this file: DefaultYokanRepository, SettingsStore, YokanRepository, ItemType. Keep those contracts available as you connect this step.
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)
}
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/CatalogEnrollmentViewModelTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines CatalogEnrollmentViewModelTest, TestScope.model, draftParsingNeverStartsEnrollment, confirmationAndValidCodeGateEnrollment, sheetProjectionOnlyReviewsAfterExplicitReviewAction, explicitSuccessTransitionsFromEnrollmentToPreviewToInstall, refreshFailureClearsPreviewAndProvidesTypedRetry, conflictInvalidatesPreviewAndRequiresRefresh, cancellationIsNotMappedToAnError, TestScope.confirmed and 4 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
draftParsingNeverStartsEnrollmentconfirmationAndValidCodeGateEnrollmentsheetProjectionOnlyReviewsAfterExplicitReviewActionexplicitSuccessTransitionsFromEnrollmentToPreviewToInstallrefreshFailureClearsPreviewAndProvidesTypedRetryconflictInvalidatesPreviewAndRequiresRefreshcancellationIsNotMappedToAnError
Cross-chapter imports used by this file: CatalogEnrollmentCode, RecipeCatalogEnrollmentServiceResult, RecipeCatalogInstallServiceResult, RecipeCatalogPreview, RecipeCatalogPreviewArtifact, RecipeCatalogRefreshError. Keep those contracts available as you connect this step.
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
}
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GenreSearchTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines GenreSearchTest.
Read the setup, action and assertions in these cases before implementing their production paths:
multiSelectUsesExtensionValueAndClearsTheTextQueryindividualGenreTogglesAndTriStatesIncludeTheGenreneverSelectsAnExclusionGroupWithTheSameGenresingleSelectMatchesLabelsCaseInsensitivelyunsupportedGenreFallsBackToTextWithoutChangingUnrelatedFilters
Cross-chapter imports used by this file: FilterEntry, FilterSelection, SourceFilter, SourceFilterKind. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SavedSearchesAndSourceBadgeTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines SavedSearchesAndSourceBadgeTest, savedSearchSerializesAndDeserializes, settingsPreservesSavedSearchesList, libraryShowSourceDefaultsToFalseAndConfiguresIndependently, userSettingsMapsLibraryShowSource.
Read the setup, action and assertions in these cases before implementing their production paths:
savedSearchSerializesAndDeserializessettingsPreservesSavedSearchesListlibraryShowSourceDefaultsToFalseAndConfiguresIndependentlyuserSettingsMapsLibraryShowSource
Cross-chapter imports used by this file: DbSavedSearch, DbSettings, ItemType, UserSettings. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SignedCatalogSheetStateTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines SignedCatalogSheetStateTest, enrollmentRequiresExplicitTrustAndIdleState, failedOrRunningRefreshNeverOffersRetainedPreview, previewOwnsItsRowsAndBlockedInstallsRequireRefresh.
Read the setup, action and assertions in these cases before implementing their production paths:
enrollmentRequiresExplicitTrustAndIdleStatefailedOrRunningRefreshNeverOffersRetainedPreviewpreviewOwnsItsRowsAndBlockedInstallsRequireRefresh
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"))
}
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeViewModelTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines SourceHomeViewModelTest, setUp, tearDown, Entry, repository, Entry.sourceHome, CoroutineScope.settings, reopeningAClosedSourceInTheSameProfileRestoresItsListingWithoutReloading, cacheKeepsTheMostRecentlyClosedSources, libraryOverlayFollowsFavouriteChanges and 6 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
reopeningAClosedSourceInTheSameProfileRestoresItsListingWithoutReloadingcacheKeepsTheMostRecentlyClosedSourceslibraryOverlayFollowsFavouriteChangespresetsAreScopedAndRequireExplicitReplacementWhileRetainingTheirIdfilterOnlyPresetRestoresAcrossRestartAndTriggersExactlyOneFreshSearchincompatiblePresetDoesNotSearchUntilItsAvailableFiltersAreReviewedupdateCancelAndRenameCollisionPreservePresetIdentityAndDataapplyingRefetchesSchemaAndCanRetryAfterAProviderFailurelegacySavedQueryReplacesCurrentFilters
Cross-chapter imports used by this file: ProfileSession, ProfileId, DefaultYokanRepository, SettingsStore, YokanRepository, DbSavedSearch. Keep those contracts available as you connect this step.
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
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceLibraryHidingTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines SourceLibraryHidingTest, setUp, tearDown, Entry, repository, hide, Entry.sourceHome, filterIsPerMediaTypeAndKeepsNonLibraryEntries, togglingAndLibraryChangesRefilterWithoutRefetching, allHiddenPageLoadsTheNextPage and 1 further declarations.
The source describes its contract as:
Pages up to [hiddenPages] only contain "/fav"; later pages contain "/p<page>" and "/fav".
Read the setup, action and assertions in these cases before implementing their production paths:
filterIsPerMediaTypeAndKeepsNonLibraryEntriestogglingAndLibraryChangesRefilterWithoutRefetchingallHiddenPageLoadsTheNextPageautomaticPageFillsAreBounded
Cross-chapter imports used by this file: DefaultYokanRepository, SettingsStore, YokanRepository, DbBrowsePreferences, DbSource, InMemoryYokanDatabase. Keep those contracts available as you connect this step.
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
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresetPolicyTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines SourcePresetPolicyTest, preset.
Read the setup, action and assertions in these cases before implementing their production paths:
everySelectionKindRoundTripsWithoutChangingTheRuntimeRequestuntouchedDefaultsRoundTripToTheIdenticalRequestsortParsingAndRequestsPreserveOptionAndDirectionchangedOptionsTypesDefaultsAndRemovedFiltersRequireReviewsynthesizedIdsNeverResolveByTranslatedLabelsOrOptionPositionsrenamedFiltersNeedReviewSourceUpgradesRemainCompatibleAndIdReuseIsRejectedmalformedValuesUnsupportedVersionsAndDuplicateIdsFailClosedlegacyQueriesKeepStableIdsAndAreBoundBeforeTheirSourceCanBeReplaced
Cross-chapter imports used by this file: DbPresetSelection, DbSavedSearch, DbSettings, DbSource, FilterEntry, FilterSelection. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourcePresetsTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines SourcePresetsTest, state, savingANewNameStoresATrimmedPresetAndClosesTheEditor, blankNamesAndConflictsKeepTheEditorOpen, confirmedReplaceReusesTheConflictingId, savingWithoutAFilterSchemaChangesNothing, applyingWithoutAFilterSchemaOpensTheReview.
Read the setup, action and assertions in these cases before implementing their production paths:
savingANewNameStoresATrimmedPresetAndClosesTheEditorblankNamesAndConflictsKeepTheEditorOpenconfirmedReplaceReusesTheConflictingIdsavingWithoutAFilterSchemaChangesNothingapplyingWithoutAFilterSchemaOpensTheReview
Cross-chapter imports used by this file: DbSavedSearch, DbSettings, DbSource. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterListDefaultsTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ChapterListDefaultsTest, title.
Read the setup, action and assertions in these cases before implementing their production paths:
withoutADefaultUnconfiguredTitlesKeepTheBuiltInSortAndNoFilterssetAsDefaultAppliesToUnconfiguredTitlesOfTheSameTypeOnlyapplyingToTheLibraryResetsOnlyLibraryTitlesOfThatMediaTypesettingsJsonWithoutDefaultsStillDecodesAndDefaultsRoundTripfillerFilterUsesTheEffectiveMarkAndBecomesPartOfTheDefault
Cross-chapter imports used by this file: DbChapterFilter, DbChapterListDefaults, DbItemType, DbSettings, DbSortChapter, Chapter. Keep those contracts available as you connect this step.
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 })
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/ChapterSelectionTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ChapterSelectionTest.
Read the setup, action and assertions in these cases before implementing their production paths:
statusShortcutsAndInversionOnlyUseShownChaptersrangeFollowsDisplayOrderAndKeepsTheFirstAnchornumericRangeUsesRowsRatherThanChapterIdsAndRejectsInvalidBoundsaboveAndBelowIncludeTheAnchorfilteringOrRemovalDropsInvisibleSelectionsAndAnchor
Cross-chapter imports used by this file: Chapter. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/CoverInspectionTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines CoverInspectionTest, fittedBoundsClampAgainstTheImageRatherThanTheWindow, focalZoomKeepsThePointUnderThePointerUntilBoundsAreReached, resizeReclampsPanAndResetZoomCentersTheCover, keyboardCanDismissAndRestoreHiddenControls.
Read the setup, action and assertions in these cases before implementing their production paths:
fittedBoundsClampAgainstTheImageRatherThanTheWindowfocalZoomKeepsThePointUnderThePointerUntilBoundsAreReachedresizeReclampsPanAndResetZoomCentersTheCoverkeyboardCanDismissAndRestoreHiddenControls
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))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailSwipeTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines DetailSwipeTest, committedSwipesInvokeTheirActionThenReset, settledAndRepeatedSwipesDoNotLeaveAnUnresetAction.
Read the setup, action and assertions in these cases before implementing their production paths:
committedSwipesInvokeTheirActionThenResetsettledAndRepeatedSwipesDoNotLeaveAnUnresetAction
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)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailViewModelTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines DetailViewModelTest, tearDown, viewModel, castOnlyUpdatesReachTheObservedDetailWithoutChangingChapters, seasonSelectionScopesEpisodesContinuationAndActionsAndRecoversAfterRemoval, enqueue, seasonsTitleListsItsSeasonRecordsWithTheirOwnProgressAndContinuation, explicitUncategorizedSelectionOverridesDefaultButOrdinaryAddUsesIt, togetherEventAndRoomObservationUseTheInjectedControllerAndTransport, selectionTogglesSplitByCurrentFlagAndClearTheSelection and 19 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
castOnlyUpdatesReachTheObservedDetailWithoutChangingChaptersseasonSelectionScopesEpisodesContinuationAndActionsAndRecoversAfterRemovalseasonsTitleListsItsSeasonRecordsWithTheirOwnProgressAndContinuationexplicitUncategorizedSelectionOverridesDefaultButOrdinaryAddUsesIttogetherEventAndRoomObservationUseTheInjectedControllerAndTransportselectionTogglesSplitByCurrentFlagAndClearTheSelectionreleasePreferencesChooseOneWinnerPreserveFilesAndSupportGroupActionsAndAlternatesnoteSaveCancelAndClearOnlyCommitSavedDraftschapterFilterHidesChaptersAndDropsThemFromTheSelection
Cross-chapter imports used by this file: ViewModelTestHost, NoNotifications, DefaultYokanRepository, LibraryIndexStore, SettingsStore, DbChapter. Keep those contracts available as you connect this step.
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
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/GuidedExtensionArchitectureTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
Reviewed implementation — use this listing. Regression tests for the reviewed constructor, state/publication, main-safety and cancellation boundaries. Architecture review.
The implementation below defines GuidedExtensionArchitectureTest, selectionAndGroupsStayOnTheLatestMediaType, sourceCreationUsesTheInjectedCommandAndClearsPreviousError, sourceCreationDoesNotConvertCancellationIntoUiFailure.
Read the setup, action and assertions in these cases before implementing their production paths:
selectionAndGroupsStayOnTheLatestMediaTypesourceCreationUsesTheInjectedCommandAndClearsPreviousErrorsourceCreationDoesNotConvertCancellationIntoUiFailure
Cross-chapter imports used by this file: GuidedViewModelFixture, DefaultYokanRepository, DbItemType, DbSource, InMemoryYokanDatabase, emptySnapshot. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.extensions
import eu.friedcutlet.yokan.architecture.GuidedViewModelFixture
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
@OptIn(ExperimentalCoroutinesApi::class)
internal class GuidedExtensionArchitectureTest : GuidedViewModelFixture() {
@Test
fun selectionAndGroupsStayOnTheLatestMediaType() = runTest {
val database = InMemoryYokanDatabase(emptySnapshot().copy(sources = listOf(
DbSource(id = 1, name = "Manga", lang = "EN", itemType = DbItemType.Manga),
DbSource(id = 2, name = "Anime", lang = "fr", itemType = DbItemType.Anime),
)))
val viewModel = own(SourceLanguagesViewModel(ItemType.Manga, DefaultYokanRepository(database)))
viewModel.selectType(ItemType.Anime)
assertEquals(ItemType.Anime, viewModel.state.value.itemType)
runCurrent()
assertEquals(listOf(2L), viewModel.state.value.groups.flatMap { it.second }.map { it.id })
viewModel.selectType(ItemType.Novel)
database.upsertSource(DbSource(id = 3, name = "Another manga", lang = "en", itemType = DbItemType.Manga))
runCurrent()
assertEquals(ItemType.Novel, viewModel.state.value.itemType)
assertTrue(viewModel.state.value.groups.isEmpty())
}
@Test
fun sourceCreationUsesTheInjectedCommandAndClearsPreviousError() {
val saved = Source(7, "Authored", "https://example.test", "en", ItemType.Manga, "local")
var failure = true
var calls = 0
val viewModel = own(CreateExtensionViewModel {
calls++
if (failure) error("Write failed")
saved
})
viewModel.create(DbSource())
assertEquals("Write failed", viewModel.state.value.error)
failure = false
viewModel.create(DbSource())
assertEquals(2, calls)
assertEquals(saved, viewModel.state.value.created)
assertNull(viewModel.state.value.error)
}
@Test
fun sourceCreationDoesNotConvertCancellationIntoUiFailure() {
val viewModel = own(CreateExtensionViewModel { throw CancellationException("Owner ended") })
assertFailsWith<CancellationException> { viewModel.create(DbSource()) }
assertNull(viewModel.state.value.error)
assertNull(viewModel.state.value.created)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationSelectionTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines MassMigrationSelectionTest, tearDown, viewModel, startsWithEveryFavoriteTitleOfTheSourceSelected, toggleAllDeselectsThenSelectsEverything, longPressTogglesWithoutAnchorAndSelectsTheRangeFromTheLastToggle, toggledAddsAndRemoves, plusRangeWorksInEitherDirection, plusRangeKeepsTheExistingSelection, plusRangeClampsOutOfBoundsIndices.
Read the setup, action and assertions in these cases before implementing their production paths:
startsWithEveryFavoriteTitleOfTheSourceSelectedtoggleAllDeselectsThenSelectsEverythinglongPressTogglesWithoutAnchorAndSelectsTheRangeFromTheLastToggletoggledAddsAndRemovesplusRangeWorksInEitherDirectionplusRangeKeepsTheExistingSelectionplusRangeClampsOutOfBoundsIndices
Cross-chapter imports used by this file: ViewModelTestHost, DefaultYokanRepository, LibraryIndexStore, SettingsStore, DbItemType, DbManga. Keep those contracts available as you connect this step.
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()))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/migration/SmarterMigrationViewModelTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines SmarterMigrationViewModelTest, track, destinationsKeepSelectionOrderAndRemoveUnavailableSources, runnerReattachesWithoutRepeatingDiscoveryAndExposesReviewActions, runner.
Read the setup, action and assertions in these cases before implementing their production paths:
destinationsKeepSelectionOrderAndRemoveUnavailableSourcesrunnerReattachesWithoutRepeatingDiscoveryAndExposesReviewActions
Cross-chapter imports used by this file: DefaultYokanRepository, SettingsStore. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailActionRowTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines DetailActionRowTest, checkActions, render, click, onUi.
Read the setup, action and assertions in these cases before implementing their production paths:
migrationImmediatelyFollowsWebViewOnPhoneAndDesktopmigrationRemainsAvailableWhenWebViewIsHidden
Cross-chapter imports used by this file: DefaultYokanRepository, DbManga, InMemoryYokanDatabase, emptySnapshot, YokanTheme. Keep those contracts available as you connect this step.
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()
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailScreenRenderTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines DetailScreenRenderTest, save, click, onUi.
The source describes its contract as:
Real Compose layout smoke test; exported images support the bounded visual review.
Read the setup, action and assertions in these cases before implementing their production paths:
rendersPhoneAndDesktopWithAutomaticCadenceAndGenreActions
Cross-chapter imports used by this file: DefaultYokanRepository, meanChapterUpdateDays, YokanTheme, sortedChapters. Keep those contracts available as you connect this step.
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()
}
}
Completion record
- [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
- [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
- [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
- [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry. [chapter-content-end]: #
Gate: controlled end-to-end browse→detail→favorite→read→migration works. Run SourceHome, presets, catalog UI, Detail, selection, related-source and migration test families. Include out-of-order responses and errors after navigating away.