GlobalSearchViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/GlobalSearchViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.browse23import eu.friedcutlet.yokan.services.extensions.SourceListing45import androidx.lifecycle.ViewModel6import androidx.lifecycle.viewModelScope7import eu.friedcutlet.yokan.data.SettingsStore8import eu.friedcutlet.yokan.data.YokanRepository9import eu.friedcutlet.yokan.domain.ItemType10import eu.friedcutlet.yokan.domain.Source11import eu.friedcutlet.yokan.services.catchingNonCancellation12import eu.friedcutlet.yokan.services.extensions.RemoteManga13import kotlinx.coroutines.CoroutineDispatcher14import kotlinx.coroutines.Dispatchers15import kotlinx.coroutines.delay16import kotlinx.coroutines.flow.MutableStateFlow17import kotlinx.coroutines.flow.StateFlow18import kotlinx.coroutines.flow.asStateFlow19import kotlinx.coroutines.flow.collectLatest20import kotlinx.coroutines.flow.distinctUntilChanged21import kotlinx.coroutines.flow.map22import kotlinx.coroutines.flow.update23import kotlinx.coroutines.launch24import kotlinx.coroutines.withContext2526internal data class SourceSearchState(27 val loading: Boolean = false,28 val results: List<RemoteManga> = emptyList(),29 val error: String? = null,30)3132internal data class GlobalSearchUiState(33 val query: String = "",34 val submittedQuery: String = "",35 /** Installed, active sources of the item type, narrowed by the pinned-only and NSFW settings. */36 val sources: List<Source> = emptyList(),37 val results: Map<Long, SourceSearchState> = emptyMap(),38)3940/** Searches every eligible source of [itemType] one after another for the submitted query. */41internal class GlobalSearchViewModel(42 private val itemType: ItemType,43 initialQuery: String,44 private val repository: YokanRepository,45 settings: SettingsStore,46 private val searchSource: suspend (Source, String) -> RuntimeLoad<SourceListing>,47 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,48) : ViewModel() {49 private val _state = MutableStateFlow(GlobalSearchUiState(query = initialQuery, submittedQuery = initialQuery.trim()))50 val state: StateFlow<GlobalSearchUiState> = _state.asStateFlow()5152 init {53 viewModelScope.launch {54 // Only these settings re-pick the sources; source rows changing mid-search do not restart it.55 settings.db.map { it.onlyIncludePinnedSources to it.showNsfw }56 .distinctUntilChanged()57 .collect { (pinnedOnly, showNsfw) ->58 val sources = repository.sources(itemType)59 .filter { it.isActive && it.isAdded }60 .filter { !pinnedOnly || it.isPinned }61 .filter { showNsfw || !it.isNsfw }62 _state.update { it.copy(sources = sources) }63 }64 }65 viewModelScope.launch {66 _state.map { it.submittedQuery to it.sources }67 .distinctUntilChanged()68 .collectLatest { (query, sources) -> search(query, sources) }69 }70 }7172 private suspend fun search(query: String, sources: List<Source>) {73 if (query.isBlank()) {74 _state.update { it.copy(results = emptyMap()) }75 return76 }77 delay(250)78 _state.update { it.copy(results = sources.associate { source -> source.id to SourceSearchState(loading = true) }) }79 sources.forEach { source ->80 val result = catchingNonCancellation {81 withContext(workDispatcher) {82 searchSource(source, query)83 }84 }.fold(85 onSuccess = { SourceSearchState(results = it.value.items, error = it.warning) },86 onFailure = { SourceSearchState(error = it.message.orEmpty().ifBlank { it::class.simpleName.orEmpty() }) },87 )88 _state.update { it.copy(results = it.results + (source.id to result)) }89 }90 }9192 fun setQuery(query: String) = _state.update { it.copy(query = query) }9394 fun submit() = _state.update { it.copy(submittedQuery = it.query.trim()) }9596 /** Caches [remote] as a browsed title and returns its id for the Detail route. */97 fun cacheRemote(source: Source, remote: RemoteManga): Long = repository.upsertRemoteTitle(source, remote).id98}99