Performance improvement for chat search filtering (#188)

This commit is contained in:
M57 authored and GitHub committed 2026-06-21 00:00:36 +03:00
1 parent 4547861c71
commit 60c4096e9c
1 file changed
+38 -14
@@ -1018,23 +1018,47 @@ class ChatViewModel(
} }
} }
private var searchJob: Job? = null
fun setSearchQuery(query: String) { fun setSearchQuery(query: String) {
val messages = _uiState.value.messages searchJob?.cancel()
val indices =
if (query.isNotBlank()) { if (query.isBlank()) {
messages.indices.filter { idx -> _uiState.update {
messages[idx].content.contains(query, ignoreCase = true) it.copy(
} searchQuery = query,
} else { searchMatchIndices = emptyList(),
emptyList() currentSearchMatchIndex = -1,
)
} }
_uiState.update { return
it.copy(
searchQuery = query,
searchMatchIndices = indices,
currentSearchMatchIndex = if (indices.isNotEmpty()) 0 else -1,
)
} }
// Keep local state in sync immediately so UI feels responsive.
_uiState.update {
it.copy(searchQuery = query)
}
searchJob =
viewModelScope.launch(Dispatchers.Default) {
val messages = _uiState.value.messages
val indices =
messages.indices.filter { idx ->
messages[idx].content.contains(query, ignoreCase = true)
}
_uiState.update {
// Only update indices if the search query hasn't changed in the meantime
if (it.searchQuery == query) {
it.copy(
searchMatchIndices = indices,
currentSearchMatchIndex = if (indices.isNotEmpty()) 0 else -1,
)
} else {
it
}
}
}
} }
fun navigateSearchMatch(direction: Int) { fun navigateSearchMatch(direction: Int) {