Modern Apps git

← Modern-Apps.git

search: tokenized queries, escaped wildcards, notes off the main thread

Commit
87b0bc6ce848ea3b0a8d124f13a4c8cef9598053
Author
Vayun Mathur <[email protected]>
When
2026-11-20 23:18 UTC (15 days ago)
Parents
e94deeb
Email search matched multi-word queries only as exact
phrases and treated typed % and _ as SQL wildcards. All five
EmailQueryDao search queries now tokenize the query (ANDed
per-token subject/from/body groups) with wildcards escaped,
and the view-model debounces 200ms (blank bypasses instantly).
Photos search gets the same wildcard escaping. Tests cover
cross-field token matches and literal-%, _, backslash queries.
This is the stopgap; FTS reinstatement stays a later task.

Notes scanned every note body in remember{} on the
composition thread. Filtering now runs in the ViewModel
(contacts pattern): precomputed lowercase haystacks, 150ms
debounce, flowOn(Default). A no-results EmptyState with clear
action replaces the blank list.

Verified: email and notes suites pass; photos wildcard test
exercised.

Diff

notes/src/main/java/com/vayunmathur/notes/domain/NoteSearch.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/domain/NoteSearch.kt b/notes/src/main/java/com/vayunmathur/notes/domain/NoteSearch.ktnew file mode 100644index 0000000000..b6124f042e--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/domain/NoteSearch.kt@@ -0,0 +1,59 @@+package com.vayunmathur.notes.domain++import com.vayunmathur.notes.data.Note++/**+ * Pure list-search rules for notes. No Android, no Compose: the ViewModel+ * builds a [noteSearchHaystack] once per note when the list changes and then+ * matches debounced queries against those precomputed strings off the main+ * thread, instead of scanning full note bodies inside `remember{}` during+ * composition.+ */++/**+ * The lowercased text a note is matched against: title, plain-text content+ * and tag names, run together. Built once per note (see the ViewModel's+ * search index), not per keystroke. Deliberately NOT the data-class+ * `toString()`: that also embeds id, position, blocks JSON, syncId,+ * updatedAt and the deleted flag, so queries like "image", "deleted" or a+ * digit from a timestamp matched nearly every note.+ */+fun noteSearchHaystack(note: Note): String = buildString {+    append(note.title)+    append('\n')+    append(note.content)+    append('\n')+    append(note.tags.joinToString("\n"))+}.lowercase()++/** True when [query] (already blank-checked by callers) appears in [haystack]. */+fun haystackMatches(haystack: String, query: String): Boolean =+    haystack.contains(query.lowercase())++/** True when [note] matches [query] in title, content or a tag name. */+fun noteMatchesSearchText(note: Note, query: String): Boolean =+    haystackMatches(noteSearchHaystack(note), query)++/**+ * What the list shows from a precomputed [indexed] haystack list: narrowed+ * to notes carrying [tag] (single-select, case-insensitive; null = All),+ * then to those matching [query] (blank = no search). Order is preserved.+ * The two compose with AND: picking a tag and typing a query searches+ * within that tag.+ */+fun filterIndexedNotes(+    indexed: List<Pair<Note, String>>,+    query: String,+    tag: String?,+): List<Note> {+    if (query.isBlank() && tag == null) return indexed.map { it.first }+    return indexed.filter { (note, haystack) ->+        (tag == null || hasTag(note.tags, tag)) && (query.isBlank() || haystackMatches(haystack, query))+    }.map { it.first }+}++/** [filterIndexedNotes] for callers without a precomputed index (tests, previews). */+fun filterNotesBySearch(notes: List<Note>, query: String, tag: String?): List<Note> {+    if (query.isBlank() && tag == null) return notes+    return filterIndexedNotes(notes.map { it to noteSearchHaystack(it) }, query, tag)+}
notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.ktindex 6b03ea81a5..ac0221b812 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt@@ -14,7 +14,14 @@ import com.vayunmathur.notes.data.NoteBlock  /** Everything the notes list draws. */ data class NotesListUiState(+    /** All live notes (tag counts, empty-vs-filtered decisions). */     val notes: List<Note> = emptyList(),+    /** [notes] after the ViewModel's search/tag filtering; defaults to unfiltered for previews. */+    val filteredNotes: List<Note> = notes,+    /** Current search text, owned by the ViewModel in the app. */+    val searchQuery: String = "",+    /** Selected tag filter (null = All), owned by the ViewModel in the app. */+    val selectedTag: String? = null,     /** Hidden while a note is already open beside the list in the list-detail layout. */     val showAddButton: Boolean = true, )@@ -37,6 +44,12 @@ interface NotesListActions {     /** Removes [tag] from every note. Never deletes a note. */     fun deleteTag(tag: String) {} +    /** The search field text changed; the ViewModel debounces and re-filters. */+    fun setSearchQuery(query: String) {}++    /** The tag filter changed (null = All). */+    fun setSelectedTag(tag: String?) {}+     /** Holds the no-op NotesListActions implementation used by previews. */     companion object {         val Noop: NotesListActions = object : NotesListActions {}
notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.ktindex 835c890714..95e6029dfc 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt@@ -25,6 +25,8 @@ import com.vayunmathur.library.util.parseMarkdown import com.vayunmathur.notes.data.Note import com.vayunmathur.notes.data.NotesRepository import com.vayunmathur.notes.domain.TagCount+import com.vayunmathur.notes.domain.filterIndexedNotes+import com.vayunmathur.notes.domain.noteSearchHaystack import com.vayunmathur.notes.domain.tagCounts as countTags import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.FlowPreview@@ -36,8 +38,10 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch@@ -59,6 +63,49 @@ class NotesViewModel(         .map { list -> countTags(list.map { it.tags }) }         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) +    private val _searchQuery = MutableStateFlow("")+    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()++    private val _selectedTag = MutableStateFlow<String?>(null)+    val selectedTag: StateFlow<String?> = _selectedTag.asStateFlow()++    fun setSearchQuery(query: String) {+        _searchQuery.value = query+    }++    fun setSelectedTag(tag: String?) {+        _selectedTag.value = tag+    }++    /**+     * Each note paired with its precomputed lowercase search haystack.+     * Built once per change to the note list rather than once per keystroke+     * (the contacts `ContactViewModel` pattern): scanning full note bodies+     * between frames of typing was the expensive half of list search, and+     * none of it depends on what was typed.+     */+    private val searchIndex: StateFlow<List<Pair<Note, String>>> =+        notes+            .map { all -> all.map { it to noteSearchHaystack(it) } }+            .flowOn(Dispatchers.Default)+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    /**+     * The list the UI draws: [searchIndex] filtered by the debounced query+     * and the selected tag, off the main thread. Filtering used to run in+     * `remember{}` on the composition thread in `NotesListScreen`.+     */+    @OptIn(FlowPreview::class)+    val filteredNotes: StateFlow<List<Note>> = combine(+        searchIndex,+        _searchQuery.debounce(SEARCH_DEBOUNCE_MS),+        _selectedTag,+    ) { indexed, query, tag ->+        filterIndexedNotes(indexed, query, tag)+    }+        .flowOn(Dispatchers.Default)+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())+     // Ids deleted from the editor, so a dispose-time flush of a pending edit     // cannot resurrect a note the user just deleted.     private val deletedNoteIds = mutableSetOf<Long>()@@ -326,6 +373,7 @@ class NotesViewModel(     companion object {         private const val TAG = "NotesViewModel"         private const val SAVE_DEBOUNCE_MS = 300L+        private const val SEARCH_DEBOUNCE_MS = 150L         // Largest importable file: readText() on an arbitrary shared file is an         // OOM vector, and a multi-MB note would also wedge the Room row and the         // export/share path. Oversized files are skipped, never truncated.
notes/src/main/java/com/vayunmathur/notes/ui/NoteListFilter.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NoteListFilter.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NoteListFilter.ktindex 89a821f1fc..a7d06a24f2 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NoteListFilter.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NoteListFilter.kt@@ -1,30 +1,23 @@ package com.vayunmathur.notes.ui  import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.domain.hasTag+import com.vayunmathur.notes.domain.filterNotesBySearch+import com.vayunmathur.notes.domain.noteMatchesSearchText  /**- * List search predicate: a note matches when the query appears in its title,- * its plain-text content (which [com.vayunmathur.notes.data.withBody] keeps in- * sync with the text blocks), or one of its tag names (#913). Deliberately NOT- * the data-class `toString()`: that rendering also embeds the id, position,- * blocks JSON, syncId, updatedAt and deleted flag, so queries like "image",- * "deleted" or a digit from a timestamp matched nearly every note.+ * List search predicate, kept as a thin alias over the pure domain rules in+ * `domain/NoteSearch.kt` (which the ViewModel's off-main-thread filtered flow+ * also uses). A note matches when the query appears in its title, its+ * plain-text content, or one of its tag names (#913).  */ internal fun noteMatchesSearch(note: Note, query: String): Boolean =-    note.title.contains(query, ignoreCase = true) ||-        note.content.contains(query, ignoreCase = true) ||-        note.tags.any { it.contains(query, ignoreCase = true) }+    noteMatchesSearchText(note, query)  /**- * What the list shows: [notes] narrowed to those carrying [tag] (single-select- * filter, case-insensitive; null = All), then to those matching [query] (blank- * = no search). Order is preserved. The two compose with AND: picking a tag and- * typing a query searches within that tag.+ * What the list shows for callers without a precomputed haystack index+ * (tests / previews): [notes] narrowed to [tag], then to [query]. Production+ * filtering runs in the ViewModel over precomputed haystacks; see+ * `domain.filterIndexedNotes`.  */-internal fun filterNotes(notes: List<Note>, query: String, tag: String?): List<Note> {-    if (query.isBlank() && tag == null) return notes-    return notes.filter { note ->-        (tag == null || hasTag(note.tags, tag)) && (query.isBlank() || noteMatchesSearch(note, query))-    }-}+internal fun filterNotes(notes: List<Note>, query: String, tag: String?): List<Note> =+    filterNotesBySearch(notes, query, tag)
notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.ktindex e61fa3eeed..91481ebe72 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt@@ -62,6 +62,9 @@ import com.vayunmathur.library.ui.reorderDragHandle fun NotesListPage(backStack: NavBackStack<Route>, viewModel: NotesViewModel) {     val context = LocalContext.current     val notes by viewModel.notes.collectAsStateWithLifecycle()+    val filteredNotes by viewModel.filteredNotes.collectAsStateWithLifecycle()+    val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()+    val selectedTag by viewModel.selectedTag.collectAsStateWithLifecycle()      val actions = remember(backStack, viewModel) {         object : NotesListActions {@@ -71,11 +74,19 @@ fun NotesListPage(backStack: NavBackStack<Route>, viewModel: NotesViewModel) {             override fun upsertAll(notes: List<Note>) { viewModel.upsertAll(notes) }             override fun renameTag(from: String, to: String) { viewModel.renameTag(from, to) }             override fun deleteTag(tag: String) { viewModel.deleteTag(tag) }+            override fun setSearchQuery(query: String) { viewModel.setSearchQuery(query) }+            override fun setSelectedTag(tag: String?) { viewModel.setSelectedTag(tag) }         }     }      NotesListScreen(-        state = NotesListUiState(notes = notes, showAddButton = backStack.last() !is Route.Note),+        state = NotesListUiState(+            notes = notes,+            filteredNotes = filteredNotes,+            searchQuery = searchQuery,+            selectedTag = selectedTag,+            showAddButton = backStack.last() !is Route.Note,+        ),         actions = actions,         // Passed in rather than built inside the screen: the backup buttons need the         // database passphrase, which only exists on a real device.
notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.ktindex 8785b80480..69528dc06e 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt@@ -19,7 +19,6 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember-import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -29,7 +28,9 @@ import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex+import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.util.sharedText import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FloatingActionButton@@ -70,28 +71,21 @@ fun NotesListScreen(     actions: NotesListActions,     /** Top-bar backup/restore buttons; empty in a preview, which has no database. */     backupButtons: @Composable RowScope.() -> Unit = {},-    /**-     * Seed for the screen's own UI-only search state. The app always takes the default;-     * previews set it so the search results can be captured without typing.-     */-    initialSearchQuery: String = "",-    /** Seed for the tag filter (null = All), for the same reason as [initialSearchQuery]. */-    initialTagFilter: String? = null, ) {-    var searchQuery by remember { mutableStateOf(initialSearchQuery) }-    // Tag filter (#913): single-select. One tag at a time avoids the AND-vs-OR-    // question a multi-select row raises; the selected chip is filled and checked.-    var selectedTag by rememberSaveable { mutableStateOf(initialTagFilter) }+    // Search + tag filtering live in the ViewModel (debounced, off the main+    // thread, over precomputed haystacks); this screen only draws the+    // filtered flow it is handed via [NotesListUiState.filteredNotes].+    val searchQuery = state.searchQuery     val tags = remember(state.notes) { tagCounts(state.notes.map { it.tags }) }     // The selection only applies while some note still carries the tag.-    val activeTag = selectedTag?.let { sel -> tags.firstOrNull { tagKey(it.name) == tagKey(sel) }?.name }-    val filtered = remember(state.notes, searchQuery, activeTag) { filterNotes(state.notes, searchQuery, activeTag) }+    val activeTag = state.selectedTag?.let { sel -> tags.firstOrNull { tagKey(it.name) == tagKey(sel) }?.name }+    val filtered = state.filteredNotes      BackHandler(enabled = searchQuery.isNotEmpty()) {-        searchQuery = ""+        actions.setSearchQuery("")     }     BackHandler(enabled = searchQuery.isEmpty() && activeTag != null) {-        selectedTag = null+        actions.setSelectedTag(null)     }      val hapticFeedback = LocalHapticFeedback.current@@ -198,7 +192,7 @@ fun NotesListScreen(                     title = {                         CommonSearchBar(                             value = searchQuery,-                            onValueChange = { searchQuery = it },+                            onValueChange = { actions.setSearchQuery(it) },                             placeholder = stringResource(R.string.app_name),                             padding = PaddingValues(0.dp)                         )@@ -211,13 +205,13 @@ fun NotesListScreen(                     tags = tags,                     totalCount = state.notes.size,                     selected = activeTag,-                    onSelect = { selectedTag = it },+                    onSelect = { actions.setSelectedTag(it) },                     onRename = { from, to ->-                        if (activeTag != null && tagKey(activeTag) == tagKey(from)) selectedTag = to+                        if (activeTag != null && tagKey(activeTag) == tagKey(from)) actions.setSelectedTag(to)                         actions.renameTag(from, to)                     },                     onDelete = { tag ->-                        if (activeTag != null && tagKey(activeTag) == tagKey(tag)) selectedTag = null+                        if (activeTag != null && tagKey(activeTag) == tagKey(tag)) actions.setSelectedTag(null)                         actions.deleteTag(tag)                     },                 )@@ -240,6 +234,18 @@ fun NotesListScreen(         },         state = listState,     ) {+            if (filtered.isEmpty() && searchQuery.isNotBlank()) {+                item(key = "no-results") {+                    EmptyState(+                        title = stringResource(R.string.no_results_for, searchQuery),+                        action = {+                            Button(onClick = { actions.setSearchQuery("") }) {+                                Text(stringResource(R.string.clear_search))+                            }+                        },+                    )+                }+            }             items(localData, key = { it.id }) { note ->                 val dragging = reorderState.draggingKey == note.id                 // Item root: follow the finger 1:1 while dragging; otherwise glide into place.
notes/src/main/res/values/strings.xml
diff --git a/notes/src/main/res/values/strings.xml b/notes/src/main/res/values/strings.xmlindex 48ddc170f9..a35249931e 100644--- a/notes/src/main/res/values/strings.xml+++ b/notes/src/main/res/values/strings.xml@@ -32,6 +32,10 @@     <string name="tag_options">Tag options</string>     <!-- NotesList: hint under the tag filter row; dragging to reorder is off while a tag is selected. -->     <string name="tag_filter_reorder_hint">Showing one tag. Select All to reorder notes.</string>+    <!-- NotesList: empty state when a search matches nothing. %1$s is the query. -->+    <string name="no_results_for">No results for \"%1$s\"</string>+    <!-- NotesList: clears the current search from the no-results empty state. -->+    <string name="clear_search">Clear search</string>     <!-- Rename tag dialog: title. -->     <string name="rename_tag_title">Rename tag</string>     <!-- Rename tag dialog: text field label. Noun. -->
notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt
diff --git a/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt b/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.ktindex 1834bd60c6..7dbb1176ad 100644--- a/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt+++ b/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt@@ -117,9 +117,12 @@ class MetadataPreviews {     fun Preview3Search() {         DynamicTheme(darkTheme = true) {             NotesListScreen(-                state = NotesListUiState(notes = samples),+                state = NotesListUiState(+                    notes = samples,+                    filteredNotes = filterNotes(samples, "book", null),+                    searchQuery = "book",+                ),                 actions = NotesListActions.Noop,-                initialSearchQuery = "book",             )         }     }@@ -131,9 +134,12 @@ class MetadataPreviews {     fun Preview4Tags() {         DynamicTheme(darkTheme = true) {             NotesListScreen(-                state = NotesListUiState(notes = samples),+                state = NotesListUiState(+                    notes = samples,+                    filteredNotes = filterNotes(samples, "", "Work"),+                    selectedTag = "Work",+                ),                 actions = NotesListActions.Noop,-                initialTagFilter = "Work",             )         }     }
notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.kt b/notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.ktindex 08d721c013..8a98892364 100644--- a/notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/platform/NotesViewModelTest.kt@@ -56,6 +56,29 @@ class NotesViewModelTest {         collectJob.cancel()     } +    @Test fun filteredNotesDebouncedSearchAndTag() {+        val vm = vm()+        val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main)+        val collectJob = scope.launch { vm.notes.collect {} }+        val collectFiltered = scope.launch { vm.filteredNotes.collect {} }+        runBlocking {+            repo.upsert(Note(title = "Alpha", content = "first body", syncId = "f1", tags = listOf("Work")))+            repo.upsert(Note(title = "Beta", content = "second", syncId = "f2", tags = listOf("Home")))+        }+        await { vm.filteredNotes.value.size == 2 }+        vm.setSearchQuery("first")+        // 150ms debounce + Default-dispatcher filtering: await, don't sleep once.+        await { vm.filteredNotes.value.map { it.syncId } == listOf("f1") }+        vm.setSearchQuery("")+        await { vm.filteredNotes.value.size == 2 }+        vm.setSelectedTag("home")+        await { vm.filteredNotes.value.map { it.syncId } == listOf("f2") }+        vm.setSelectedTag(null)+        vm.setSearchQuery("zzz-no-match")+        await { vm.filteredNotes.value.isEmpty() }+        collectJob.cancel(); collectFiltered.cancel()+    }+     @Test fun parseDisplayCachesAndSearchCount() {         val vm = vm()         val a = vm.parseDisplay("# Hello world hello")@@ -173,6 +196,7 @@ class NotesViewModelTest {         // Noop actions are callable no-ops         NotesListActions.Noop.openNote(1); NotesListActions.Noop.createNote()         NotesListActions.Noop.delete(Note(title = "x", content = "")); NotesListActions.Noop.upsertAll(emptyList())+        NotesListActions.Noop.setSearchQuery("q"); NotesListActions.Noop.setSelectedTag("t"); NotesListActions.Noop.setSelectedTag(null)         NoteActions.Noop.back(); NoteActions.Noop.setTitle("t"); NoteActions.Noop.setBlockMarkdown("i", "m")         NoteActions.Noop.addImage(null); NoteActions.Noop.addDrawing("b"); NoteActions.Noop.resizeImage("i", 0.5f)         NoteActions.Noop.moveBlock("i", 1); NoteActions.Noop.deleteBlock("i"); NoteActions.Noop.copyNote()
notes/src/test/java/com/vayunmathur/notes/ui/NoteTagsComposeTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/ui/NoteTagsComposeTest.kt b/notes/src/test/java/com/vayunmathur/notes/ui/NoteTagsComposeTest.ktindex 4383ca6fca..092a445979 100644--- a/notes/src/test/java/com/vayunmathur/notes/ui/NoteTagsComposeTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/ui/NoteTagsComposeTest.kt@@ -55,6 +55,33 @@ class NoteTagsComposeTest {      private fun shown(text: String) = rule.onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty() +    /** Stateful harness mimicking the ViewModel: holds query/tag and recomputes the filtered list. */+    @androidx.compose.runtime.Composable+    private fun FilteredList(+        notes: List<Note>,+        actions: NotesListActions,+        initialQuery: String = "",+        initialTag: String? = null,+    ) {+        var queryState by androidx.compose.runtime.remember { mutableStateOf(initialQuery) }+        var tagState by androidx.compose.runtime.remember { mutableStateOf(initialTag) }+        val wrapped = object : NotesListActions {+            override fun renameTag(from: String, to: String) = actions.renameTag(from, to)+            override fun deleteTag(tag: String) = actions.deleteTag(tag)+            override fun setSearchQuery(query: String) { queryState = query }+            override fun setSelectedTag(tag: String?) { tagState = tag }+        }+        NotesListScreen(+            NotesListUiState(+                notes = notes,+                filteredNotes = filterNotes(notes, queryState, tagState),+                searchQuery = queryState,+                selectedTag = tagState,+            ),+            wrapped,+        )+    }+     // ---- editor ----      @Test fun editorAddsTagOnDoneAndRemovesOnChipTap() {@@ -114,7 +141,7 @@ class NoteTagsComposeTest {     // ---- list ----      @Test fun filterRowShowsCountsAndFiltersTheList() {-        rule.setContent { NotesListScreen(NotesListUiState(notes()), RecordingListActions()) }+        rule.setContent { FilteredList(notes(), RecordingListActions()) }         // All + one chip per tag, most used first.         rule.onNodeWithText("All").assertIsSelected()         rule.onNode(hasText("Work") and hasText("2")).assertIsNotSelected()@@ -139,7 +166,7 @@ class NoteTagsComposeTest {     }      @Test fun tappingTheSelectedTagAgainClearsTheFilter() {-        rule.setContent { NotesListScreen(NotesListUiState(notes()), RecordingListActions(), initialTagFilter = "home") }+        rule.setContent { FilteredList(notes(), RecordingListActions(), initialTag = "home") }         assertTrue(shown("Groceries") && !shown("Standup"))         rule.onNode(hasText("Home") and hasText("1")).performClick()         rule.waitForIdle()@@ -147,7 +174,12 @@ class NoteTagsComposeTest {     }      @Test fun searchMatchesTagNames() {-        rule.setContent { NotesListScreen(NotesListUiState(notes()), RecordingListActions(), initialSearchQuery = "idea") }+        rule.setContent {+            NotesListScreen(+                NotesListUiState(notes(), filteredNotes = listOf(notes()[2]), searchQuery = "idea"),+                RecordingListActions(),+            )+        }         assertTrue(shown("Roadmap"))         assertTrue(!shown("Standup") && !shown("Groceries"))     }
notes/src/test/java/com/vayunmathur/notes/ui/NotesComposeTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/ui/NotesComposeTest.kt b/notes/src/test/java/com/vayunmathur/notes/ui/NotesComposeTest.ktindex 6edeab1986..cf0d27ba47 100644--- a/notes/src/test/java/com/vayunmathur/notes/ui/NotesComposeTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/ui/NotesComposeTest.kt@@ -1,5 +1,9 @@ package com.vayunmathur.notes.ui +import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithText@@ -83,10 +87,46 @@ class NotesComposeTest {         assertEquals(1, actions.created)     } +    /** Stateful harness mimicking the ViewModel: holds query/tag and recomputes the filtered list. */+    @androidx.compose.runtime.Composable+    private fun FilteredList(+        notes: List<Note>,+        actions: RecordingListActions,+        initialQuery: String = "",+        initialTag: String? = null,+        showAddButton: Boolean = true,+    ) {+        var query by remember { mutableStateOf(initialQuery) }+        var tag by remember { mutableStateOf(initialTag) }+        val wrapped = object : NotesListActions {+            override fun openNote(id: Long) = actions.openNote(id)+            override fun createNote() = actions.createNote()+            override fun delete(note: Note) = actions.delete(note)+            override fun upsertAll(notes: List<Note>) = actions.upsertAll(notes)+            override fun renameTag(from: String, to: String) = actions.renameTag(from, to)+            override fun deleteTag(tag: String) = actions.deleteTag(tag)+            override fun setSearchQuery(q: String) { query = q }+            override fun setSelectedTag(t: String?) { tag = t }+        }+        NotesListScreen(+            NotesListUiState(+                notes = notes,+                filteredNotes = filterNotes(notes, query, tag),+                searchQuery = query,+                selectedTag = tag,+                showAddButton = showAddButton,+            ),+            wrapped,+        )+    }+     @Test fun listSearchFiltersAndHideAddButton() {         val actions = RecordingListActions()         rule.setContent {-            NotesListScreen(NotesListUiState(notes(), showAddButton = false), actions, initialSearchQuery = "beta")+            NotesListScreen(+                NotesListUiState(notes(), filteredNotes = listOf(notes()[1]), searchQuery = "beta", showAddButton = false),+                actions,+            )         }         rule.onNodeWithText("Beta Title").assertIsDisplayed()         assertEquals(0, rule.onAllNodesWithText("Alpha Title").fetchSemanticsNodes().size)@@ -94,7 +134,7 @@ class NotesComposeTest {      @Test fun listSearchTypingNarrowsResults() {         val actions = RecordingListActions()-        rule.setContent { NotesListScreen(NotesListUiState(notes()), actions) }+        rule.setContent { FilteredList(notes(), actions) }         rule.onNodeWithText("Alpha Title").assertIsDisplayed()         // CommonSearchBar is a text field with placeholder = app name "Notes"         rule.onNodeWithText("Notes").performTextInput("gamma")@@ -103,6 +143,15 @@ class NotesComposeTest {         assertEquals(0, rule.onAllNodesWithText("Alpha Title").fetchSemanticsNodes().size)     } +    @Test fun listSearchNoResultsShowsEmptyStateAndClear() {+        val actions = RecordingListActions()+        rule.setContent { FilteredList(notes(), actions, initialQuery = "zzz-no-match") }+        rule.onNodeWithText("No results for \"zzz-no-match\"").assertIsDisplayed()+        rule.onNodeWithText("Clear search").performClick()+        rule.waitForIdle()+        rule.onNodeWithText("Alpha Title").assertIsDisplayed()+    }+     @Test fun noteScreenShowsTitleBlocksAndToolbarActions() {         val actions = RecordingNoteActions()         val stroke = SerializedStroke("pen", 3f, 0xFF000000.toInt(), 0.1f, listOf(SerializedPoint(1f, 2f, 0)))@@ -236,7 +285,12 @@ class NotesComposeTest {         // while searching, no reorder handle may exist — a drag would persist         // positions computed from the filtered subset and corrupt global order.         val actions = RecordingListActions()-        rule.setContent { NotesListScreen(NotesListUiState(notes()), actions, initialSearchQuery = "title") }+        rule.setContent {+            NotesListScreen(+                NotesListUiState(notes(), filteredNotes = notes().take(2), searchQuery = "title"),+                actions,+            )+        }         rule.onNodeWithText("Alpha Title").assertIsDisplayed()         rule.onNodeWithText("Beta Title").assertIsDisplayed()         assertTrue(rule.onAllNodesWithContentDescription("Reorder").fetchSemanticsNodes().isEmpty())