notes: tags with filter, search and rename (#913)
- Commit
76cb092dc54698ba5122b66644d41cd05a0d0b7b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-12 19:27 UTC (23 days ago)
- Parents
c929c4b
Request (#913): all notes live in one list, which gets overwhelming as
it grows. The issue asks for labels/tags on notes so the list can be
filtered by them (tags, not folders).
Design
- Storage: Note gains `tags: List<String>` (default empty), stored as
one TEXT column holding a JSON array (`["work","home"]`, `[]` when
untagged) through a new NoteConverters ColumnTypeConverter. A tag
table would add joins and a second sync surface for <= 20 short
strings per note that we only ever filter in memory.
- Normalisation lives in a new pure domain/NoteTags.kt: trim, collapse
internal whitespace to one space, drop empties, dedupe
case-insensitively keeping the first spelling, cut each tag to 40
chars (never splitting a surrogate pair), keep at most 20 per note.
Tags compare case-insensitively everywhere; typing "Work" when
"work" already exists reuses the existing spelling.
- Editor: a tag row under the title. Each tag is an input chip (tap it
or its x to remove); an "Add tag" field commits on Done or a comma
("a, b" adds two). While the field has focus, matching tags already
used elsewhere are offered as one-tap suggestions, most used first
(prefix matches first). At 20 tags the field is replaced by a note.
Tag edits go through the existing editableNote debounced save, the
same path as a title edit, so they bump updatedAt and sync like any
other edit.
- List: when any note is tagged, a horizontal filter row sits under
the search bar: "All" (total count) plus one chip per tag with its
note count, sorted by count then name. The filter is SINGLE-select:
tap a tag to show only notes carrying it, tap it again or All to
clear. One tag at a time avoids the AND-vs-OR ambiguity a
multi-select row raises; the selected chip is filled with a check
mark, and Back clears it. Search now also matches tag names, and
composes with the filter (search within a tag). Note cards show
their tags on one compact line (tag icon, names joined by a middle dot,
ellipsised); untagged cards look as before.
- Long-press a tag chip for Rename / Delete. Rename applies to every
note and merges when the new name is an existing tag (the dialog
says so before you confirm; a case-only rename is allowed). Delete
asks first, then removes the tag from every note and never deletes a
note. Both run in the repository as one batch upsert of only the
changed notes, which bumps their updatedAt so the change syncs.
Tombstoned notes are left alone.
- Reorder rule: while a tag is selected the drag handles are hidden
(exactly as while searching) and a one-line hint says to select All
to reorder. Positions stay global, so no position remapping exists
or is needed.
Sync compatibility
- `tags: List<String> = emptyList()` is added as the LAST field of
notes' RelayNoteJson and of everysync's RemoteNote (data/
RemoteModels.kt). That is the one file touched outside notes/: the
two classes are a field-for-field mirror of the relay envelope, and
everysync re-serialises every note through RemoteNote, so without it
everysync would strip tags on every sync. NoteSink and NoteKind are
unchanged.
- Both Json instances omit defaults, so an untagged note's envelope is
byte-identical to the pre-tags one, its content hash is unchanged,
and nothing mass re-syncs after the update. A tag edit is a content
change (it is part of the canonical hash); a reorder still is not.
- Received tags are normalised in RelayNoteJson.toNote.
- Caveat: an older app version on another device does not know the
field. Older notes builds decode a tagged envelope with
ignoreUnknownKeys and drop the tags; if that device then edits and
re-sends the note, the newer (tagless) copy wins LWW and the tags are
lost on every device. The same holds for an older everysync build,
which drops tags whenever it re-serialises a note. Update notes and
everysync on every synced device before relying on tags.
- Not changed: the assistant-intent DTOs (library.intents.notes
NoteData / InsertNoteData) live in :library, outside this change's
scope, so assistant reads/inserts stay tag-free. Backup/restore
copies the whole database file, so tags ride along with no format
change (an old v3 backup is migrated on open like any v3 database).
Markdown export/share is unchanged (no tags in the .md).
Migration
- Database version 3 -> 4 with a hand-written MIGRATION_3_4:
ALTER TABLE `Note` ADD COLUMN `tags` TEXT NOT NULL DEFAULT '[]'.
Every existing row reads back as untagged; no backfill, and
updatedAt is untouched, so the migration itself triggers no sync.
exportSchema stays false, hence the explicit migration tests below.
Other
- library/ui Icons.kt: IconTag (outlined label) and IconClear (an "x"
with a caller-supplied content description) for the chips.
- One public composable per new file: TagFilterChip (custom chip,
because the shared FilterChip owns its click handling and an outer
long-press never fires), TagFilterRow, NoteTagsLine, NoteTagEditor,
dialogs/RenameTagDialog. List filtering moved to ui/NoteListFilter.kt.
- Store-listing previews: sample notes now carry tags, the editor
preview shows the tag row, and a new 4-tags preview shows the filter
with "Work" selected. metadata_data/photos/notes/phone/1-4.png are
regenerated by `./gradlew :notes:metadata` in the builder container
(not hand-edited); 4.png is new.
User-visible effect: notes can be tagged in the editor; the list gets
a tag filter row with counts, tags on each card, tag-aware search, and
long-press rename/merge and delete for tags. Untagged users see no
change until they add a first tag.
Verification
- New unit tests: NoteTagsTest (normalisation, canonical spelling,
rename/merge, delete, counts, suggestions); NoteTagsMigrationTest
(MIGRATION_3_4 on a real SQLite db with existing rows -> `[]`,
column NOT NULL DEFAULT '[]') and NoteTagsRoomMigrationTest (Room
opens a real v3 file, migrates, validates the schema, rows read back
untagged, version 4); NoteTagsRepositoryTest (column round trip,
converter tolerance, rename/merge and delete across notes, updatedAt
bump, tombstones untouched); NoteListFilterTest (filter + tag
search); NoteRelayTagsTest and everysync RemoteNoteTagsParityTest
(untagged payload and canonical hash byte-identical to the pre-tags
shape, tagged payload pinned to the same literal on both sides and
round-trips, receive normalises, tag edit changes the hash, reorder
does not); NoteTagsComposeTest (Robolectric: add on Done, comma
split, suggestion tap, remove; filter row selection, hidden reorder
handles + hint, All; tag search; long-press rename with merge notice
and delete with confirmation; standalone rename dialog; the 20-tag
limit).
- Builder container: :notes:compileDevKotlin, :notes:testDevUnitTest
(204 tests, 0 failures), :notes:lint (0 errors; no warnings in the
changed files), :notes:detekt (clean, with the follow-up masks
commit), :everysync:compileDevKotlin, :everysync:testDevUnitTest
(150 tests, 0 failures), :library:ui:compileDebugKotlin and
:notes:metadata all succeed.
- The tests caught one real bug before commit: aapt strips unescaped
double quotes in strings.xml, so the merge notice and the delete
title use \" escapes.Diff
everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.ktindex 113bb3129d..e928e0bf28 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/RemoteModels.kt@@ -113,6 +113,13 @@ data class RemoteNote( val deleted: Boolean = false, /** Last local-or-remote modification (epoch ms); drives relay LWW. */ val updatedAt: Long = 0L,+ /**+ * Note tags (notes #913). Mirror of notes' `RelayNoteJson.tags`: same name,+ * same last position. Defaults are omitted on encode, so an untagged note+ * hashes exactly as it did before tags existed; a tag edit is a content+ * change and syncs like any other.+ */+ val tags: List<String> = emptyList(), ) /**
everysync/src/test/java/com/vayunmathur/everysync/data/RemoteNoteTagsParityTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/data/RemoteNoteTagsParityTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/data/RemoteNoteTagsParityTest.ktnew file mode 100644index 0000000000..b514ba89be--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/data/RemoteNoteTagsParityTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.everysync.data++import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.sync.adapters.NoteKind+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals++/**+ * [RemoteNote] carries note tags (notes #913) and must stay byte-compatible+ * with notes' `RelayNoteJson`. The two literals below are pinned verbatim in+ * notes' `NoteRelayTagsTest`; if either side reorders or renames a field one+ * of the two tests fails.+ */+class RemoteNoteTagsParityTest {++ /** RemoteNote exactly as it was before tags. */+ @Serializable+ private data class PreTagsRemoteNote(+ val uid: String,+ val title: String = "",+ val content: String = "",+ val blocksJson: String? = null,+ val position: Double = 0.0,+ val deleted: Boolean = false,+ val updatedAt: Long = 0L,+ )++ private val json = Json { ignoreUnknownKeys = true }++ private val untagged = RemoteNote(+ uid = "abc123", title = "Plan", content = "body", blocksJson = """{"blocks":[]}""",+ position = 2.5, deleted = false, updatedAt = 1_700_000_000_000,+ )++ @Test fun untaggedEnvelopeAndHashAreUnchanged() {+ assertEquals(UNTAGGED_GOLDEN, NoteKind.toJson(untagged))+ val before = PreTagsRemoteNote("abc123", "Plan", "body", """{"blocks":[]}""", 2.5, false, 1_700_000_000_000)+ assertEquals(json.encodeToString(PreTagsRemoteNote.serializer(), before), NoteKind.toJson(untagged))+ val canonicalBefore = json.encodeToString(+ PreTagsRemoteNote.serializer(),+ PreTagsRemoteNote("", "Plan", "body", """{"blocks":[]}"""),+ )+ assertEquals(canonicalBefore, NoteKind.canonical(untagged))+ }++ @Test fun taggedEnvelopeMatchesNotesAndRoundTrips() {+ val tagged = untagged.copy(tags = listOf("work", "home office"))+ assertEquals(TAGGED_GOLDEN, NoteKind.toJson(tagged))+ assertEquals(tagged, NoteKind.fromJson(TAGGED_GOLDEN))+ assertEquals(tagged, NoteSink.fromPayload(TAGGED_GOLDEN))+ }++ @Test fun aTagEditIsAContentChange() {+ val tagged = untagged.copy(tags = listOf("work"))+ assertNotEquals(NoteKind.contentHash(untagged), NoteKind.contentHash(tagged))+ // ...but a reorder still is not.+ assertEquals(NoteKind.contentHash(tagged), NoteKind.contentHash(tagged.copy(position = 99.0)))+ }++ @Test fun tagsPayloadFromAnOlderNotesBuildDecodesUntagged() {+ assertEquals(emptyList(), NoteKind.fromJson(UNTAGGED_GOLDEN)!!.tags)+ }++ private companion object {+ const val UNTAGGED_GOLDEN =+ """{"uid":"abc123","title":"Plan","content":"body","blocksJson":"{\"blocks\":[]}",""" ++ """"position":2.5,"updatedAt":1700000000000}"""+ const val TAGGED_GOLDEN =+ """{"uid":"abc123","title":"Plan","content":"body","blocksJson":"{\"blocks\":[]}",""" ++ """"position":2.5,"updatedAt":1700000000000,"tags":["work","home office"]}"""+ }+}
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex a88435b8a3..d417afb903 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -120,6 +120,7 @@ import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material.icons.automirrored.filled.WrapText import androidx.compose.material.icons.automirrored.outlined.ArrowRightAlt+import androidx.compose.material.icons.automirrored.outlined.Label import androidx.compose.material.icons.filled.AccessTime import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.AddPhotoAlternate@@ -1864,3 +1865,23 @@ fun IconChecklist(modifier: Modifier = Modifier, tint: Color = LocalContentColor @Composable fun IconSnooze(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.Snooze, "Snooze", modifier, tint)++/** A label - note tags in notes. [contentDescription] defaults to "Tag"; pass null when decorative. */+@Composable+fun IconTag(+ modifier: Modifier = Modifier,+ tint: Color = LocalContentColor.current,+ contentDescription: String? = "Tag",+) = AppIcon(Icons.AutoMirrored.Outlined.Label, contentDescription, modifier, tint)++/**+ * Small "x" that clears or removes one item, e.g. the remove affordance on an input chip.+ * [contentDescription] defaults to "Clear"; pass the control's own label (or null when the+ * enclosing control already carries one).+ */+@Composable+fun IconClear(+ modifier: Modifier = Modifier,+ tint: Color = LocalContentColor.current,+ contentDescription: String? = "Clear",+) = AppIcon(Icons.Filled.Close, contentDescription, modifier, tint)
metadata_data/photos/notes/phone/1.png
diff --git a/metadata_data/photos/notes/phone/1.png b/metadata_data/photos/notes/phone/1.pngindex d255ce7004..8790c0cb12 100644Binary files a/metadata_data/photos/notes/phone/1.png and b/metadata_data/photos/notes/phone/1.png differ
metadata_data/photos/notes/phone/2.png
diff --git a/metadata_data/photos/notes/phone/2.png b/metadata_data/photos/notes/phone/2.pngindex c357e0898c..7ca03f40da 100644Binary files a/metadata_data/photos/notes/phone/2.png and b/metadata_data/photos/notes/phone/2.png differ
metadata_data/photos/notes/phone/3.png
diff --git a/metadata_data/photos/notes/phone/3.png b/metadata_data/photos/notes/phone/3.pngindex edeaa3f979..a54975fbe8 100644Binary files a/metadata_data/photos/notes/phone/3.png and b/metadata_data/photos/notes/phone/3.png differ
metadata_data/photos/notes/phone/4.png
diff --git a/metadata_data/photos/notes/phone/4.png b/metadata_data/photos/notes/phone/4.pngnew file mode 100644index 0000000000..58ae6cc934Binary files /dev/null and b/metadata_data/photos/notes/phone/4.png differ
notes/AGENTS.md
diff --git a/notes/AGENTS.md b/notes/AGENTS.mdindex d6583c2bc3..d67a9b7554 100644--- a/notes/AGENTS.md+++ b/notes/AGENTS.md@@ -5,7 +5,7 @@ _Install: ./install notes (dev by default)._ <!-- last-reviewed: 2026-10-16 --> - Gradle: :notes / dir: notes/-- Package roots present: ui, data, platform, intents+- Package roots present: ui, data, domain, platform, intents, sync - Entry files: MainActivity.kt, Route.kt, Navigation.kt - Deps: :library:room, :library:ink, :library:image - Metadata: metadata_data/notes.md (present)@@ -34,6 +34,9 @@ _Install: ./install notes (dev by default)._ - com/vayunmathur/notes/data/NoteBlock.kt - com/vayunmathur/notes/data/NoteDatabase.kt - com/vayunmathur/notes/data/NotesRepository.kt+- com/vayunmathur/notes/data/NoteConverters.kt — `tags` JSON-array column (#913)+### domain/ — pure rules (no Android)+- com/vayunmathur/notes/domain/NoteTags.kt — tag normalisation, rename/merge, counts, suggestions ### platform/ — ViewModel, contract, stores, export - com/vayunmathur/notes/platform/NotesViewModel.kt - com/vayunmathur/notes/platform/NotesUiContract.kt
notes/src/main/java/com/vayunmathur/notes/data/Note.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/Note.kt b/notes/src/main/java/com/vayunmathur/notes/data/Note.ktindex c460d14942..2d6cc05570 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/Note.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/Note.kt@@ -18,6 +18,9 @@ data class Note( val syncId: String = newSyncId(), val updatedAt: Long = System.currentTimeMillis(), val deleted: Boolean = false,+ // User tags (#913), normalised by domain.normalizeTags before they are+ // written. Stored as one JSON-array TEXT column (see NoteConverters).+ val tags: List<String> = emptyList(), ): ReorderableDatabaseItem<Note> { override fun withPosition(position: Double) = copy(position = position) }
notes/src/main/java/com/vayunmathur/notes/data/NoteConverters.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NoteConverters.kt b/notes/src/main/java/com/vayunmathur/notes/data/NoteConverters.ktnew file mode 100644index 0000000000..c7b119284f--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/data/NoteConverters.kt@@ -0,0 +1,27 @@+package com.vayunmathur.notes.data++import androidx.room3.ColumnTypeConverter+import kotlinx.serialization.SerializationException+import kotlinx.serialization.json.Json++/**+ * Room column converters for [Note]. [Note.tags] is stored as one TEXT column+ * holding a JSON array of strings (`["work","home"]`, `[]` when untagged).+ * A tag table would need joins on every list query and a second sync surface;+ * at <= 20 short tags per note a JSON column is simpler and indexes nothing we+ * query by anyway (filtering happens in memory over the loaded list).+ */+class NoteConverters {+ @ColumnTypeConverter+ fun fromTags(value: List<String>): String = Json.encodeToString(value)++ /** Tolerant: a malformed value reads as untagged instead of failing the whole query. */+ @ColumnTypeConverter+ fun toTags(value: String): List<String> = try {+ Json.decodeFromString<List<String>>(value)+ } catch (_: SerializationException) {+ emptyList()+ } catch (_: IllegalArgumentException) {+ emptyList()+ }+}
notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.ktindex c7777dfdbd..62e6f2741a 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt@@ -1,6 +1,7 @@ package com.vayunmathur.notes.data import android.content.Context+import androidx.room3.ColumnTypeConverters import androidx.room3.Dao import androidx.room3.Database import androidx.room3.Delete@@ -80,7 +81,8 @@ interface NoteSyncSnapshotDao { suspend fun deleteAll() } -@Database(entities = [Note::class, SyncSnapshot::class], version = 3, exportSchema = false)+@Database(entities = [Note::class, SyncSnapshot::class], version = 4, exportSchema = false)+@ColumnTypeConverters(NoteConverters::class) abstract class NoteDatabase : RoomDatabase() { abstract fun noteDao(): NoteDao abstract fun syncSnapshotDao(): NoteSyncSnapshotDao@@ -90,6 +92,14 @@ abstract class NoteDatabase : RoomDatabase() { // rows keep blocks = NULL and are read as a single text block. // v3 adds relay sync identity (mirrors passwords 2->3 backfill): syncId / // updatedAt / deleted on Note plus the SyncSnapshot baseline table.+ // v4 adds `tags` (#913), a JSON array of strings. NOT NULL DEFAULT '[]'+ // so every existing row reads back as untagged; no backfill needed.++ /** v3 -> v4: the `tags` column. Hand-written (exportSchema is off). */+ val MIGRATION_3_4 = Migration(3, 4) {+ it.execSQL("ALTER TABLE `Note` ADD COLUMN `tags` TEXT NOT NULL DEFAULT '[]'")+ }+ override val migrations = listOf( Migration(1, 2) { it.execSQL("ALTER TABLE Note ADD COLUMN blocks TEXT")@@ -112,6 +122,7 @@ abstract class NoteDatabase : RoomDatabase() { )""", ) },+ MIGRATION_3_4, ) } }
notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt b/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.ktindex 7f165d7db2..8ac5829d9e 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt@@ -2,6 +2,8 @@ package com.vayunmathur.notes.data import android.content.Context import com.vayunmathur.library.room.RoomRepository+import com.vayunmathur.notes.domain.withTagRenamed+import com.vayunmathur.notes.domain.withoutTag import kotlinx.coroutines.flow.Flow class NotesRepository private constructor(context: Context) :@@ -37,6 +39,26 @@ class NotesRepository private constructor(context: Context) : suspend fun deleteBySyncId(syncId: String): Int = dao.deleteBySyncId(syncId) suspend fun upsertAll(values: List<Note>) = dao.upsertAll(values) + /**+ * Renames tag [from] to [to] on every live note (case-insensitive match). A+ * note that already carries [to] merges the two. Returns how many notes+ * changed. Local writes, so updatedAt is bumped and the change syncs.+ */+ suspend fun renameTag(from: String, to: String): Int = rewriteTags { withTagRenamed(it, from, to) }++ /** Removes [tag] from every live note. Notes themselves are never deleted. */+ suspend fun deleteTag(tag: String): Int = rewriteTags { withoutTag(it, tag) }++ private suspend fun rewriteTags(transform: (List<String>) -> List<String>): Int {+ val changed = dao.getAll().mapNotNull { note ->+ val tags = transform(note.tags)+ if (tags != note.tags) note.copy(tags = tags) else null+ }+ // One batch upsert (a single Room transaction) for every changed note.+ if (changed.isNotEmpty()) dao.upsertAll(changed)+ return changed.size+ }+ /** Removes every note (including tombstones). Used when a relay vault is purged. */ suspend fun purge() = dao.deleteAll()
notes/src/main/java/com/vayunmathur/notes/domain/NoteTags.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/domain/NoteTags.kt b/notes/src/main/java/com/vayunmathur/notes/domain/NoteTags.ktnew file mode 100644index 0000000000..8e5bdf22b4--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/domain/NoteTags.kt@@ -0,0 +1,125 @@+package com.vayunmathur.notes.domain++/**+ * Pure tag rules for notes (#913). No Android, no Room: the editor, the list,+ * the repository's rename/delete and the relay receive path all call these, so+ * every way a tag can enter the database produces the same normalised form.+ *+ * Tags compare case-insensitively everywhere ([tagKey]); the first spelling a+ * note was given is the one it keeps.+ */++/** Longest tag, in UTF-16 chars, after whitespace is collapsed. */+const val MAX_TAG_LENGTH = 40++/** Most tags one note can carry; extras are dropped from the end. */+const val MAX_TAGS_PER_NOTE = 20++private val whitespaceRun = Regex("\\s+")++/** Identity used to compare tags: "Work", "work" and "WORK" are the same tag. */+fun tagKey(tag: String): String = tag.lowercase()++/**+ * One tag in canonical form: trimmed, internal whitespace runs collapsed to a+ * single space, cut to [MAX_TAG_LENGTH] (never splitting a surrogate pair).+ * Null when nothing is left.+ */+fun normalizeTag(raw: String): String? {+ val collapsed = raw.trim().replace(whitespaceRun, " ")+ if (collapsed.isEmpty()) return null+ var cut = collapsed.take(MAX_TAG_LENGTH)+ if (cut.length < collapsed.length && cut.last().isHighSurrogate()) cut = cut.dropLast(1)+ return cut.trimEnd().ifEmpty { null }+}++/**+ * A note's tag list in canonical form: each tag normalised ([normalizeTag]),+ * empties dropped, case-insensitive duplicates removed keeping the first+ * spelling, and at most [MAX_TAGS_PER_NOTE] kept. Order is preserved.+ */+fun normalizeTags(raw: List<String>): List<String> {+ val seen = HashSet<String>()+ val out = ArrayList<String>(minOf(raw.size, MAX_TAGS_PER_NOTE))+ for (tag in raw) {+ val clean = normalizeTag(tag) ?: continue+ if (seen.add(tagKey(clean))) out += clean+ if (out.size == MAX_TAGS_PER_NOTE) break+ }+ return out+}++/** True when [tags] contains [tag], ignoring case. */+fun hasTag(tags: List<String>, tag: String): Boolean {+ val key = tagKey(tag)+ return tags.any { tagKey(it) == key }+}++/**+ * The spelling to store for user input [raw]: normalised, and if a tag with the+ * same key already exists in [known] that spelling wins, so typing "Work" when+ * "work" exists does not split one tag in two. Null for blank input.+ */+fun canonicalTag(raw: String, known: List<String>): String? {+ val clean = normalizeTag(raw) ?: return null+ val key = tagKey(clean)+ return known.firstOrNull { tagKey(it) == key } ?: clean+}++/** [tags] with [tag] removed (case-insensitive); unchanged when absent. */+fun withoutTag(tags: List<String>, tag: String): List<String> {+ val key = tagKey(tag)+ return tags.filterNot { tagKey(it) == key }+}++/**+ * [tags] with [from] renamed to [to], in place. When the note already carries+ * [to] (any case) the two merge: [from] is dropped and the existing spelling+ * stays where it was. Unchanged when [from] is absent or [to] is blank.+ */+fun withTagRenamed(tags: List<String>, from: String, to: String): List<String> {+ val target = normalizeTag(to) ?: return tags+ val fromKey = tagKey(from)+ if (tags.none { tagKey(it) == fromKey }) return tags+ // normalizeTags keeps the first spelling per key, so an existing [to] that+ // sits before [from] wins the merge, and a later one is dropped.+ return normalizeTags(tags.map { if (tagKey(it) == fromKey) target else it })+}++/** A tag and how many notes carry it. */+data class TagCount(val name: String, val count: Int)++/**+ * Every tag across [tagLists] (one list per note) with its note count, most+ * used first, then by name. Tags group case-insensitively; the displayed+ * spelling is the one most notes use (ties go to the first seen).+ */+fun tagCounts(tagLists: List<List<String>>): List<TagCount> {+ // key -> (spelling -> count), insertion-ordered so ties resolve to the first seen.+ val byKey = LinkedHashMap<String, LinkedHashMap<String, Int>>()+ for (tags in tagLists) {+ for (tag in tags.distinctBy(::tagKey)) {+ val spellings = byKey.getOrPut(tagKey(tag)) { LinkedHashMap() }+ spellings[tag] = (spellings[tag] ?: 0) + 1+ }+ }+ return byKey.values+ .map { spellings ->+ val name = spellings.entries.maxBy { it.value }.key+ TagCount(name, spellings.values.sum())+ }+ .sortedWith(compareByDescending<TagCount> { it.count }.thenBy { tagKey(it.name) }.thenBy { it.name })+}++/**+ * Autocomplete for the tag field: [known] tags (already most-used first) that+ * contain [query] (case-insensitive; prefix matches first), minus those the+ * note already has, capped at [limit]. A blank query suggests the top tags.+ */+fun suggestTags(known: List<String>, query: String, exclude: List<String>, limit: Int): List<String> {+ val excluded = exclude.mapTo(HashSet(), ::tagKey)+ val q = tagKey(query.trim())+ val candidates = known.filter { tagKey(it) !in excluded && tagKey(it).contains(q) }+ val (prefix, rest) = candidates.partition { tagKey(it).startsWith(q) }+ return (prefix + rest).filterNot { q.isNotEmpty() && tagKey(it) == q }.take(limit)+}
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 0401217f5e..2de9d5ec4f 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt@@ -31,15 +31,24 @@ interface NotesListActions { /** Persists a reordered list; each note already carries its new position. */ fun upsertAll(notes: List<Note>) {} + /** Renames tag [from] to [to] on every note, merging into [to] where it already exists. */+ fun renameTag(from: String, to: String) {}++ /** Removes [tag] from every note. Never deletes a note. */+ fun deleteTag(tag: String) {}+ companion object { val Noop: NotesListActions = object : NotesListActions {} } } -/** Everything the note editor draws: the title plus the ordered body blocks. */+/** Everything the note editor draws: the title, the note's tags, and the ordered body blocks. */ data class NoteUiState( val title: String = "", val blocks: List<NoteBlock> = emptyList(),+ val tags: List<String> = emptyList(),+ /** Every tag used by any note, most used first: the autocomplete source for the tag field. */+ val knownTags: List<String> = emptyList(), ) /** Note editor callbacks. Same no-op-default arrangement as [NotesListActions]. */@@ -47,6 +56,10 @@ interface NoteActions { fun back() {} fun setTitle(title: String) {} + /** Adds a tag typed or picked in the tag field (normalised by the binder). */+ fun addTag(tag: String) {}+ fun removeTag(tag: String) {}+ /** The text block [id] was edited to [markdown]. */ fun setBlockMarkdown(id: String, markdown: String) {}
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 972b89a98b..739da85d5f 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt@@ -24,6 +24,8 @@ import com.vayunmathur.library.util.IntentHelper 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.tagCounts as countTags import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.MutableSharedFlow@@ -36,6 +38,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -50,6 +53,11 @@ class NotesViewModel( val notes: StateFlow<List<Note>> = repository.notes .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) + /** Every tag across the live notes, most used first: the list filter row and editor autocomplete. */+ val tagCounts: StateFlow<List<TagCount>> = notes+ .map { list -> countTags(list.map { it.tags }) }+ .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>()@@ -63,6 +71,14 @@ class NotesViewModel( viewModelScope.launch(Dispatchers.IO) { repository.upsertAll(notes) } } + fun renameTag(from: String, to: String) {+ viewModelScope.launch(Dispatchers.IO) { repository.renameTag(from, to) }+ }++ fun deleteTag(tag: String) {+ viewModelScope.launch(Dispatchers.IO) { repository.deleteTag(tag) }+ }+ @OptIn(FlowPreview::class) @Composable fun editableNote(initialId: Long, default: () -> Note): MutableState<Note> {
notes/src/main/java/com/vayunmathur/notes/sync/RelayNoteProvider.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/sync/RelayNoteProvider.kt b/notes/src/main/java/com/vayunmathur/notes/sync/RelayNoteProvider.ktindex 10861b1528..af5accd90d 100644--- a/notes/src/main/java/com/vayunmathur/notes/sync/RelayNoteProvider.kt+++ b/notes/src/main/java/com/vayunmathur/notes/sync/RelayNoteProvider.kt@@ -12,6 +12,7 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.notes.data.Note import com.vayunmathur.notes.data.NotesRepository import com.vayunmathur.notes.data.SyncSnapshot+import com.vayunmathur.notes.domain.normalizeTags import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.serialization.Serializable@@ -341,6 +342,14 @@ internal data class RelayNoteJson( val deleted: Boolean = false, /** Last local-or-remote modification (epoch ms); drives relay LWW. */ val updatedAt: Long = 0L,+ /**+ * User tags (#913). Last on purpose and empty by default: `json` does not+ * encode defaults, so an untagged note's envelope — and so its content+ * hash — is byte-identical to the pre-tags shape and nothing re-syncs.+ * Must stay in the same position as `RemoteNote.tags` (the hash is over+ * the encoded bytes, which follow declaration order).+ */+ val tags: List<String> = emptyList(), ) internal fun RelayNoteJson.toNote(id: Long): Note = Note(@@ -352,6 +361,9 @@ internal fun RelayNoteJson.toNote(id: Long): Note = Note( syncId = uid, updatedAt = updatedAt, deleted = deleted,+ // Normalise on receive: another device's build is not trusted to have+ // applied the same rules (length, count, case-insensitive dedupe).+ tags = normalizeTags(tags), ) // Envelope mapper: native <-> relay-log bytes.@@ -363,4 +375,5 @@ internal fun Note.toRelayJson(): RelayNoteJson = RelayNoteJson( position = position, deleted = deleted, updatedAt = updatedAt,+ tags = tags, )
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.ktnew file mode 100644index 0000000000..89a821f1fc--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NoteListFilter.kt@@ -0,0 +1,30 @@+package com.vayunmathur.notes.ui++import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.domain.hasTag++/**+ * 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.+ */+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) }++/**+ * 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.+ */+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))+ }+}
notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.ktindex ad1e2540b5..7caf5c730f 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt@@ -16,6 +16,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue+import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.ui.platform.ClipEntry import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.LocalContext@@ -29,6 +30,9 @@ import com.vayunmathur.notes.data.NoteBody import com.vayunmathur.notes.data.body import com.vayunmathur.notes.data.randomBlockId import com.vayunmathur.notes.data.withBody+import com.vayunmathur.notes.domain.canonicalTag+import com.vayunmathur.notes.domain.normalizeTags+import com.vayunmathur.notes.domain.withoutTag import com.vayunmathur.notes.platform.NoteActions import com.vayunmathur.notes.platform.NoteImageStore import com.vayunmathur.notes.platform.NoteUiState@@ -58,6 +62,8 @@ fun NotePage( val scope = rememberCoroutineScope() val shareNoteLabel = stringResource(R.string.share_note) val noteClipLabel = stringResource(R.string.note)+ val tagCounts by notesViewModel.tagCounts.collectAsStateWithLifecycle()+ val knownTags = remember(tagCounts) { tagCounts.map { it.name } } // Local, editable copy of the note body: an ordered list of inline blocks // (text / image / ink). Every change is written back to [note], which persists@@ -132,13 +138,22 @@ fun NotePage( } NoteScreen(- state = NoteUiState(title = note.title, blocks = blocks.toList()),+ state = NoteUiState(title = note.title, blocks = blocks.toList(), tags = note.tags, knownTags = knownTags), sharedTextKey = "note-title-$noteID", actions = object : NoteActions { override fun back() = backStack.pop() override fun setTitle(title: String) { note = note.copy(title = title) } + // Tags save through the same debounced editableNote write as the title,+ // so they get the same updatedAt bump and sync as any other edit.+ override fun addTag(tag: String) {+ val clean = canonicalTag(tag, knownTags) ?: return+ note = note.copy(tags = normalizeTags(note.tags + clean))+ }++ override fun removeTag(tag: String) { note = note.copy(tags = withoutTag(note.tags, tag)) }+ override fun setBlockMarkdown(id: String, markdown: String) { val i = blocks.indexOfFirst { it.id == id } if (i >= 0) {
notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.ktindex e7f6b31d62..5a39d482df 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.kt@@ -51,6 +51,7 @@ import com.vayunmathur.notes.platform.NoteImageStore import com.vayunmathur.notes.platform.NoteUiState import com.vayunmathur.notes.ui.components.ImageBlock import com.vayunmathur.notes.ui.components.InkBlock+import com.vayunmathur.notes.ui.components.NoteTagEditor /** * The note editor, with no dependency on the ViewModel or the back stack so it can be@@ -128,6 +129,14 @@ fun NoteScreen(state: NoteUiState, actions: NoteActions, sharedTextKey: Any? = n }, ) + NoteTagEditor(+ tags = state.tags,+ knownTags = state.knownTags,+ onAdd = { actions.addTag(it) },+ onRemove = { actions.removeTag(it) },+ modifier = Modifier.padding(vertical = 4.dp),+ )+ state.blocks.forEach { block -> key(block.id) { when (block) {
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 6a2bc39373..e61fa3eeed 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt@@ -69,6 +69,8 @@ fun NotesListPage(backStack: NavBackStack<Route>, viewModel: NotesViewModel) { override fun createNote() { backStack.add(Route.Note(0)) } override fun delete(note: Note) { viewModel.delete(note) } 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) } } }
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 84329c54f0..ab846bfb2d 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt@@ -3,6 +3,8 @@ package com.vayunmathur.notes.ui import androidx.activity.compose.BackHandler import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope@@ -17,6 +19,7 @@ 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@@ -49,21 +52,13 @@ import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.animatedDp import com.vayunmathur.notes.R import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.domain.tagCounts+import com.vayunmathur.notes.domain.tagKey+import com.vayunmathur.notes.ui.components.NoteTagsLine+import com.vayunmathur.notes.ui.components.TagFilterRow import com.vayunmathur.notes.platform.NotesListActions import com.vayunmathur.notes.platform.NotesListUiState -/**- * List search predicate: a note matches when the query appears in its title- * or its plain-text content (which [com.vayunmathur.notes.data.withBody]- * keeps in sync with the text blocks). 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.- */-internal fun noteMatchesSearch(note: Note, query: String): Boolean =- note.title.contains(query, ignoreCase = true) ||- note.content.contains(query, ignoreCase = true)- /** * The notes list, with no dependency on the ViewModel or the back stack so it can be * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing@@ -81,16 +76,24 @@ fun NotesListScreen( * 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) }- val filtered = remember(state.notes, searchQuery) {- if (searchQuery.isBlank()) state.notes- else state.notes.filter { noteMatchesSearch(it, searchQuery) }- }+ // 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) }+ 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) } BackHandler(enabled = searchQuery.isNotEmpty()) { searchQuery = "" }+ BackHandler(enabled = searchQuery.isEmpty() && activeTag != null) {+ selectedTag = null+ } val hapticFeedback = LocalHapticFeedback.current val selectedIds = remember { mutableStateListOf<Long>() }@@ -172,7 +175,7 @@ fun NotesListScreen( } LazyListScaffold(- topBar = {+ topBar = { Column { if (isSelectionMode) { TopAppBar( title = { Text(selectedIds.size.toString()) },@@ -204,7 +207,31 @@ fun NotesListScreen( actions = backupButtons ) }- },+ if (tags.isNotEmpty()) {+ TagFilterRow(+ tags = tags,+ totalCount = state.notes.size,+ selected = activeTag,+ onSelect = { selectedTag = it },+ onRename = { from, to ->+ if (activeTag != null && tagKey(activeTag) == tagKey(from)) selectedTag = to+ actions.renameTag(from, to)+ },+ onDelete = { tag ->+ if (activeTag != null && tagKey(activeTag) == tagKey(tag)) selectedTag = null+ actions.deleteTag(tag)+ },+ )+ }+ if (activeTag != null) {+ Text(+ stringResource(R.string.tag_filter_reorder_hint),+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 2.dp),+ style = MaterialTheme.typography.labelMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ } }, floatingActionButton = { if (state.showAddButton && !isSelectionMode) { FloatingActionButton(onClick = { actions.createNote() }) {@@ -252,14 +279,17 @@ fun NotesListScreen( } ), supportingContent = {- Text(note.content.substringBefore('\n').take(40))+ Column {+ Text(note.content.substringBefore('\n').take(40))+ NoteTagsLine(note.tags)+ } }, trailingContent = { Row(verticalAlignment = Alignment.CenterVertically) {- // No drag handle while searching: onMove reassigns positions within- // the visible (filtered) subset and upsertAll persists them, which- // would corrupt the global order of the hidden notes.- if (searchQuery.isBlank() && localData.size > 1 && selectedIds.size < localData.size && (!isSelectionMode || isContiguous)) {+ // No drag handle while searching or tag-filtering: onMove reassigns+ // positions within the visible (filtered) subset and upsertAll persists+ // them, which would corrupt the global order of the hidden notes.+ if (searchQuery.isBlank() && activeTag == null && localData.size > 1 && selectedIds.size < localData.size && (!isSelectionMode || isContiguous)) { IconButton( modifier = Modifier.reorderDragHandle( reorderState = reorderState,
notes/src/main/java/com/vayunmathur/notes/ui/components/NoteTagEditor.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/components/NoteTagEditor.kt b/notes/src/main/java/com/vayunmathur/notes/ui/components/NoteTagEditor.ktnew file mode 100644index 0000000000..b4945b94f0--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/ui/components/NoteTagEditor.kt@@ -0,0 +1,177 @@+package com.vayunmathur.notes.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+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.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AssistChip+import com.vayunmathur.library.ui.IconClear+import com.vayunmathur.library.ui.IconTag+import com.vayunmathur.library.ui.InputChip+import com.vayunmathur.library.ui.LocalContentColor+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.notes.R+import com.vayunmathur.notes.domain.MAX_TAGS_PER_NOTE+import com.vayunmathur.notes.domain.suggestTags++private const val MAX_SUGGESTIONS = 8++/**+ * The editor's tag row, under the title: the note's [tags] as chips (tap the+ * chip or its x to remove), then an "Add tag" field. Done or a comma commits+ * what was typed (leaving the field does not); while it has focus, [knownTags] (every tag in use,+ * most used first) that match the text are offered as one-tap suggestions.+ * At [MAX_TAGS_PER_NOTE] the field is replaced by a short note saying so.+ */+@OptIn(ExperimentalLayoutApi::class)+@Composable+fun NoteTagEditor(+ tags: List<String>,+ knownTags: List<String>,+ onAdd: (String) -> Unit,+ onRemove: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ var input by rememberSaveable { mutableStateOf("") }+ var focused by rememberSaveable { mutableStateOf(false) }+ val commit = {+ if (input.isNotBlank()) onAdd(input)+ input = ""+ }++ Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ tags.forEach { tag ->+ val removeLabel = stringResource(R.string.remove_tag, tag)+ InputChip(+ selected = false,+ onClick = { onRemove(tag) },+ label = { Text(tag, Modifier.widthIn(max = 200.dp), maxLines = 1, overflow = TextOverflow.Ellipsis) },+ modifier = Modifier.semantics { contentDescription = removeLabel },+ trailingIcon = { IconClear(Modifier.size(18.dp), contentDescription = null) },+ )+ }+ if (tags.size < MAX_TAGS_PER_NOTE) {+ TagInputField(+ value = input,+ onValueChange = { typed ->+ // A comma ends a tag, so "a, b, c" pasted or typed adds three.+ if (',' in typed) {+ typed.split(',').dropLast(1).filter { it.isNotBlank() }.forEach(onAdd)+ input = typed.substringAfterLast(',')+ } else {+ input = typed+ }+ },+ onDone = commit,+ // Leaving the field keeps any half-typed text there rather than+ // committing it, so tapping elsewhere never creates a stray tag.+ onFocusChange = { focused = it },+ )+ } else {+ Text(+ pluralStringResource(R.plurals.tag_limit_reached, MAX_TAGS_PER_NOTE, MAX_TAGS_PER_NOTE),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ val suggestions = if (focused) suggestTags(knownTags, input, tags, MAX_SUGGESTIONS) else emptyList()+ if (suggestions.isNotEmpty() && tags.size < MAX_TAGS_PER_NOTE) {+ Row(+ Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ suggestions.forEach { s ->+ AssistChip(+ onClick = {+ onAdd(s)+ input = ""+ },+ label = { Text(s, maxLines = 1) },+ )+ }+ }+ }+ }+}++@Composable+private fun TagInputField(+ value: String,+ onValueChange: (String) -> Unit,+ onDone: () -> Unit,+ onFocusChange: (Boolean) -> Unit,+) {+ val style = MaterialTheme.typography.bodyMedium.copy(color = LocalContentColor.current)+ BasicTextField(+ value = value,+ onValueChange = onValueChange,+ modifier = Modifier+ .widthIn(min = 120.dp, max = 240.dp)+ .onFocusChanged { onFocusChange(it.isFocused) },+ singleLine = true,+ textStyle = style,+ cursorBrush = SolidColor(LocalContentColor.current),+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ imeAction = ImeAction.Done,+ ),+ keyboardActions = KeyboardActions(onDone = { onDone() }),+ decorationBox = { inner ->+ // 48dp: the chips' touch-target height, so the field lines up with them in the row.+ Row(+ Modifier.heightIn(min = 48.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ IconTag(+ Modifier.size(18.dp),+ tint = MaterialTheme.colorScheme.onSurfaceVariant,+ contentDescription = null,+ )+ Box(contentAlignment = Alignment.CenterStart) {+ if (value.isEmpty()) {+ Text(+ stringResource(R.string.add_tag),+ style = style.copy(color = MaterialTheme.colorScheme.onSurfaceVariant),+ )+ }+ inner()+ }+ }+ },+ )+}
notes/src/main/java/com/vayunmathur/notes/ui/components/NoteTagsLine.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/components/NoteTagsLine.kt b/notes/src/main/java/com/vayunmathur/notes/ui/components/NoteTagsLine.ktnew file mode 100644index 0000000000..50d72fef81--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/ui/components/NoteTagsLine.kt@@ -0,0 +1,38 @@+package com.vayunmathur.notes.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconTag+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * A note card's tags, compact: one line, a small tag icon, names separated by+ * a middle dot, ellipsised when they run out of room. Draws nothing for an+ * untagged note, so untagged cards look exactly as before.+ */+@Composable+fun NoteTagsLine(tags: List<String>, modifier: Modifier = Modifier) {+ if (tags.isEmpty()) return+ Row(+ modifier.padding(top = 2.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ IconTag(Modifier.size(14.dp), tint = MaterialTheme.colorScheme.primary, contentDescription = null)+ Text(+ tags.joinToString(" · "),+ style = MaterialTheme.typography.labelMedium,+ color = MaterialTheme.colorScheme.primary,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+}
notes/src/main/java/com/vayunmathur/notes/ui/components/TagFilterChip.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/components/TagFilterChip.kt b/notes/src/main/java/com/vayunmathur/notes/ui/components/TagFilterChip.ktnew file mode 100644index 0000000000..a347a23341--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/ui/components/TagFilterChip.kt@@ -0,0 +1,88 @@+package com.vayunmathur.notes.ui.components++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.shape.RoundedCornerShape+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.semantics.Role+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.selected+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text++private val ChipShape = RoundedCornerShape(8.dp)++/**+ * One chip in the notes list's tag filter row: [label] plus its note [count],+ * filled with a check mark while [selected]. Single-select, so it carries+ * radio-button semantics.+ *+ * Drawn here rather than with the shared `FilterChip` because the row needs a+ * long-press (Rename / Delete menu) and `FilterChip` owns its click handling,+ * so an outer long-press modifier never sees the gesture.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+fun TagFilterChip(+ label: String,+ count: Int,+ selected: Boolean,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ onLongClick: (() -> Unit)? = null,+ onLongClickLabel: String? = null,+) {+ val colors = MaterialTheme.colorScheme+ Surface(+ modifier = modifier+ .clip(ChipShape)+ .combinedClickable(+ role = Role.RadioButton,+ onLongClickLabel = onLongClickLabel,+ onLongClick = onLongClick,+ onClick = onClick,+ )+ .semantics { this.selected = selected },+ shape = ChipShape,+ color = if (selected) colors.secondaryContainer else Color.Transparent,+ contentColor = if (selected) colors.onSecondaryContainer else colors.onSurfaceVariant,+ border = if (selected) null else BorderStroke(1.dp, colors.outlineVariant),+ ) {+ Row(+ Modifier.height(32.dp).padding(horizontal = 12.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ // The check is decoration: `selected` semantics already say it.+ if (selected) IconCheck(Modifier.size(18.dp).clearAndSetSemantics {})+ Text(+ label,+ modifier = Modifier.widthIn(max = 160.dp),+ style = MaterialTheme.typography.labelLarge,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Text(+ count.toString(),+ style = MaterialTheme.typography.labelMedium,+ color = if (selected) colors.onSecondaryContainer else colors.outline,+ )+ }+ }+}
notes/src/main/java/com/vayunmathur/notes/ui/components/TagFilterRow.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/components/TagFilterRow.kt b/notes/src/main/java/com/vayunmathur/notes/ui/components/TagFilterRow.ktnew file mode 100644index 0000000000..1538761ece--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/ui/components/TagFilterRow.kt@@ -0,0 +1,115 @@+package com.vayunmathur.notes.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+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.Modifier+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconEdit+import com.vayunmathur.library.ui.Text+import com.vayunmathur.notes.R+import com.vayunmathur.notes.domain.TagCount+import com.vayunmathur.notes.domain.tagKey+import com.vayunmathur.notes.ui.dialogs.RenameTagDialog+import com.vayunmathur.library.ui.R as UiR++/**+ * The notes list's tag filter: an "All" chip (with the total note count) and+ * one chip per tag (with its note count), in [tags] order — most used first.+ *+ * Single-select: tapping a tag shows only notes carrying it, tapping it again+ * or tapping All shows everything. [selected] is the active tag, null for All.+ * Long-pressing a tag chip opens a small menu: Rename (every note; merges into+ * an existing tag of that name) and Delete (strips the tag from every note,+ * never deletes a note), each confirmed in a dialog.+ */+@Composable+fun TagFilterRow(+ tags: List<TagCount>,+ totalCount: Int,+ selected: String?,+ onSelect: (String?) -> Unit,+ onRename: (from: String, to: String) -> Unit,+ onDelete: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ var menuFor by rememberSaveable { mutableStateOf<String?>(null) }+ var renaming by rememberSaveable { mutableStateOf<String?>(null) }+ var deleting by rememberSaveable { mutableStateOf<String?>(null) }+ val selectedKey = selected?.let(::tagKey)++ LazyRow(+ modifier = modifier.fillMaxWidth(),+ contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ item(key = "all") {+ TagFilterChip(+ label = stringResource(UiR.string.all),+ count = totalCount,+ selected = selectedKey == null,+ onClick = { onSelect(null) },+ )+ }+ items(tags, key = { "tag:" + tagKey(it.name) }) { tag ->+ val isSelected = tagKey(tag.name) == selectedKey+ Box {+ TagFilterChip(+ label = tag.name,+ count = tag.count,+ selected = isSelected,+ onClick = { onSelect(if (isSelected) null else tag.name) },+ onLongClick = { menuFor = tag.name },+ onLongClickLabel = stringResource(R.string.tag_options),+ )+ DropdownMenu(expanded = menuFor == tag.name, onDismissRequest = { menuFor = null }) {+ DropdownMenuItem(+ text = { Text(stringResource(UiR.string.rename)) },+ leadingIcon = { IconEdit() },+ onClick = { menuFor = null; renaming = tag.name },+ )+ DropdownMenuItem(+ text = { Text(stringResource(UiR.string.delete)) },+ leadingIcon = { IconDelete() },+ onClick = { menuFor = null; deleting = tag.name },+ )+ }+ }+ }+ }++ renaming?.let { from ->+ RenameTagDialog(+ tag = from,+ existingTags = tags.map { it.name },+ onRename = { to -> onRename(from, to) },+ onDismiss = { renaming = null },+ )+ }+ deleting?.let { tag ->+ val count = tags.firstOrNull { tagKey(it.name) == tagKey(tag) }?.count ?: 0+ ConfirmDialog(+ title = stringResource(R.string.delete_tag_title, tag),+ message = pluralStringResource(R.plurals.delete_tag_message, count, count),+ confirmLabel = stringResource(UiR.string.delete),+ dismissLabel = stringResource(UiR.string.cancel),+ destructive = true,+ onConfirm = { onDelete(tag) },+ onDismiss = { deleting = null },+ )+ }+}
notes/src/main/java/com/vayunmathur/notes/ui/dialogs/RenameTagDialog.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/dialogs/RenameTagDialog.kt b/notes/src/main/java/com/vayunmathur/notes/ui/dialogs/RenameTagDialog.ktnew file mode 100644index 0000000000..795cd7e00a--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/ui/dialogs/RenameTagDialog.kt@@ -0,0 +1,75 @@+package com.vayunmathur.notes.ui.dialogs++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+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.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.notes.R+import com.vayunmathur.notes.domain.normalizeTag+import com.vayunmathur.notes.domain.tagKey+import com.vayunmathur.library.ui.R as UiR++/**+ * Renames [tag] across every note. [existingTags] lets the dialog say up front+ * when the new name is another tag that already exists, in which case the two+ * merge. Rename is disabled while the name is blank or unchanged.+ */+@Composable+fun RenameTagDialog(+ tag: String,+ existingTags: List<String>,+ onRename: (String) -> Unit,+ onDismiss: () -> Unit,+) {+ var input by rememberSaveable(tag) { mutableStateOf(tag) }+ val target = normalizeTag(input)+ val mergesInto = target?.let { t ->+ existingTags.firstOrNull { tagKey(it) == tagKey(t) && tagKey(it) != tagKey(tag) }+ }+ // A case-only change ("work" -> "Work") is a real rename; an identical name is not.+ val canRename = target != null && target != tag+ val confirm = { if (canRename && target != null) { onDismiss(); onRename(target) } }+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.rename_tag_title)) },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedTextField(+ value = input,+ onValueChange = { input = it },+ modifier = Modifier.fillMaxWidth(),+ label = { Text(stringResource(R.string.tag_name)) },+ singleLine = true,+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+ keyboardActions = KeyboardActions(onDone = { confirm() }),+ )+ if (mergesInto != null) {+ Text(+ stringResource(R.string.rename_tag_merges, mergesInto),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ },+ confirmButton = {+ TextButton(onClick = confirm, enabled = canRename) { Text(stringResource(UiR.string.rename)) }+ },+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) } },+ )+}
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 36aacedf62..48ddc170f9 100644--- a/notes/src/main/res/values/strings.xml+++ b/notes/src/main/res/values/strings.xml@@ -19,4 +19,30 @@ <!-- NotePage: Clipboard label for note content. Noun, lowercase intentional. --> <string name="note">note</string> <string name="share_note">Share Note</string>+ <!-- NotePage tag row: placeholder of the field that adds a tag to the note. Verb phrase. -->+ <string name="add_tag">Add tag</string>+ <!-- NotePage tag row: accessibility label of the x on a tag chip. %1$s is the tag. -->+ <string name="remove_tag">Remove tag %1$s</string>+ <!-- NotePage tag row: shown instead of the add field once a note has the maximum number of tags. -->+ <plurals name="tag_limit_reached">+ <item quantity="one">A note can have up to %1$d tag</item>+ <item quantity="other">A note can have up to %1$d tags</item>+ </plurals>+ <!-- NotesList filter row: accessibility action for long-pressing a tag chip (opens Rename / Delete). -->+ <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>+ <!-- Rename tag dialog: title. -->+ <string name="rename_tag_title">Rename tag</string>+ <!-- Rename tag dialog: text field label. Noun. -->+ <string name="tag_name">Tag name</string>+ <!-- Rename tag dialog: shown when the new name is an existing tag. %1$s is that tag. -->+ <string name="rename_tag_merges">Merges into the existing tag \"%1$s\"</string>+ <!-- Delete tag dialog: title. %1$s is the tag. -->+ <string name="delete_tag_title">Delete tag \"%1$s\"?</string>+ <!-- Delete tag dialog: body. %1$d is how many notes carry the tag. -->+ <plurals name="delete_tag_message">+ <item quantity="one">Removes the tag from %1$d note. The note itself is kept.</item>+ <item quantity="other">Removes the tag from %1$d notes. The notes themselves are kept.</item>+ </plurals> </resources>
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 4b0843f469..1834bd60c6 100644--- a/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt+++ b/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt@@ -34,24 +34,28 @@ class MetadataPreviews { title = "Weekend plans", content = "Saturday: farmers market + hike at Twin Peaks. Sunday: brunch with Sam, then finish the book.", position = 0.0,+ tags = listOf("Personal", "Plans"), ), Note( id = 2, title = "Groceries", content = "Oat milk, eggs, sourdough, spinach, cherry tomatoes, olive oil, dark chocolate.", position = 1.0,+ tags = listOf("Personal", "Lists"), ), Note( id = 3, title = "Project ideas", content = "1. Auto-generate app screenshots 2. Offline map tiles 3. A tiny synth in Compose.", position = 2.0,+ tags = listOf("Work", "Ideas"), ), Note( id = 4, title = "Meeting notes", content = "Ship the metadata pipeline. Add dark-mode shots. Review the release checklist.", position = 3.0,+ tags = listOf("Work"), ), Note( id = 5,@@ -99,6 +103,8 @@ class MetadataPreviews { id = "weekend-body", ), ),+ tags = listOf("Personal", "Plans"),+ knownTags = listOf("Personal", "Work", "Plans", "Lists", "Ideas"), ), actions = NoteActions.Noop, )@@ -117,4 +123,18 @@ class MetadataPreviews { ) } }++ /** The tag filter (#913): "Work" selected, so only work notes show and reordering is paused. */+ @PreviewTest+ @Preview(name = "4-tags", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview4Tags() {+ DynamicTheme(darkTheme = true) {+ NotesListScreen(+ state = NotesListUiState(notes = samples),+ actions = NotesListActions.Noop,+ initialTagFilter = "Work",+ )+ }+ } }
notes/src/test/java/com/vayunmathur/notes/data/NoteDaoTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/data/NoteDaoTest.kt b/notes/src/test/java/com/vayunmathur/notes/data/NoteDaoTest.ktindex 3ad464589c..19549b8586 100644--- a/notes/src/test/java/com/vayunmathur/notes/data/NoteDaoTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/data/NoteDaoTest.kt@@ -87,7 +87,7 @@ class NoteDaoTest { @Test fun dbNameAndConfigsShape() { assertEquals("notes-db", DB_NAME) assertNotNull(NoteDatabase.migrations)- assertEquals(listOf(1 to 2, 2 to 3), NoteDatabase.migrations.map { it.startVersion to it.endVersion })+ assertEquals(listOf(1 to 2, 2 to 3, 3 to 4), NoteDatabase.migrations.map { it.startVersion to it.endVersion }) } }
notes/src/test/java/com/vayunmathur/notes/data/NoteTagsMigrationTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/data/NoteTagsMigrationTest.kt b/notes/src/test/java/com/vayunmathur/notes/data/NoteTagsMigrationTest.ktnew file mode 100644index 0000000000..f18c2373a1--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/data/NoteTagsMigrationTest.kt@@ -0,0 +1,128 @@+package com.vayunmathur.notes.data++import android.content.Context+import android.database.sqlite.SQLiteDatabase+import androidx.room3.Room+import androidx.sqlite.SQLiteConnection+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.sqlite.execSQL+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** The exact v3 `Note` DDL Room generated before tags existed (columns in entity order). */+private const val V3_NOTE_DDL =+ "CREATE TABLE IF NOT EXISTS `Note` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++ "`title` TEXT NOT NULL, `content` TEXT NOT NULL, `position` REAL NOT NULL, `blocks` TEXT, " ++ "`syncId` TEXT NOT NULL, `updatedAt` INTEGER NOT NULL, `deleted` INTEGER NOT NULL)"++private const val V3_SNAPSHOT_DDL =+ "CREATE TABLE IF NOT EXISTS `SyncSnapshot` (`syncId` TEXT NOT NULL, `kind` TEXT NOT NULL, " ++ "`contentHash` TEXT NOT NULL, `localUpdatedAt` INTEGER NOT NULL, `remoteModified` INTEGER NOT NULL, " ++ "`lastSyncedAt` INTEGER NOT NULL, PRIMARY KEY(`syncId`))"++/**+ * v3 -> v4 (#913) on raw SQLite: [NoteDatabase.MIGRATION_3_4] adds `tags`+ * NOT NULL DEFAULT '[]', and rows that existed before read back as `[]`.+ */+class NoteTagsMigrationTest {+ private val conn: SQLiteConnection = BundledSQLiteDriver().open(":memory:").apply {+ execSQL(V3_NOTE_DDL)+ execSQL(V3_SNAPSHOT_DDL)+ execSQL(+ "INSERT INTO Note (title, content, position, blocks, syncId, updatedAt, deleted) VALUES " ++ "('kept', 'body', 1.0, NULL, 'aaaa', 100, 0), ('gone', '', 2.0, '{}', 'bbbb', 200, 1)",+ )+ }++ @AfterTest fun close() = conn.close()++ @Test fun addsNotNullTagsColumnDefaultingToEmptyArray() {+ runBlocking { NoteDatabase.MIGRATION_3_4.migrate(conn) }+ conn.prepare("PRAGMA table_info(`Note`)").use {+ var found = false+ while (it.step()) {+ if (it.getText(1) == "tags") {+ found = true+ assertEquals("TEXT", it.getText(2))+ assertEquals(1L, it.getLong(3), "tags must be NOT NULL")+ assertEquals("'[]'", it.getText(4))+ }+ }+ assertTrue(found, "tags column missing")+ }+ conn.prepare("SELECT title, tags, syncId, updatedAt, deleted FROM Note ORDER BY id").use {+ assertTrue(it.step())+ assertEquals("kept", it.getText(0)); assertEquals("[]", it.getText(1))+ assertEquals("aaaa", it.getText(2)); assertEquals(100L, it.getLong(3)); assertEquals(0L, it.getLong(4))+ assertTrue(it.step())+ assertEquals("gone", it.getText(0)); assertEquals("[]", it.getText(1)); assertEquals(1L, it.getLong(4))+ }+ }++ @Test fun isRegisteredAsTheLastMigrationAndBumpsToFour() {+ val last = NoteDatabase.migrations.last()+ assertEquals(3 to 4, last.startVersion to last.endVersion)+ assertTrue(last === NoteDatabase.MIGRATION_3_4)+ }+}++/**+ * The same upgrade through Room itself on a real v3 database file, so Room's+ * own schema validation runs against the migrated table (a mismatch between+ * the hand-written DDL and the entity would throw on open), and the old rows+ * come back through the DAO as untagged notes that can then be tagged.+ */+@RunWith(RobolectricTestRunner::class)+class NoteTagsRoomMigrationTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val name = "notes-tags-migration-test.db"++ @AfterTest fun cleanup() {+ ctx.deleteDatabase(name)+ }++ @Test fun roomOpensV3FileMigratesAndValidates() = runTest {+ ctx.deleteDatabase(name)+ val path = ctx.getDatabasePath(name)+ path.parentFile?.mkdirs()+ SQLiteDatabase.openOrCreateDatabase(path, null).apply {+ execSQL(V3_NOTE_DDL)+ execSQL(V3_SNAPSHOT_DDL)+ execSQL(+ "INSERT INTO Note (title, content, position, blocks, syncId, updatedAt, deleted) " ++ "VALUES ('old note', 'old body', 3.0, NULL, 'sync-old', 1234, 0)",+ )+ version = 3+ close()+ }++ val db = Room.databaseBuilder(ctx, NoteDatabase::class.java, name)+ .addMigrations(*NoteDatabase.migrations.toTypedArray())+ .allowMainThreadQueries()+ .build()+ try {+ val dao = db.noteDao()+ val old = dao.getBySyncId("sync-old")!!+ assertEquals("old note", old.title)+ assertEquals(emptyList(), old.tags)+ // Migration is not an edit: the sync clock is untouched.+ assertEquals(1234L, old.updatedAt)+ dao.upsertRaw(old.copy(tags = listOf("work", "home office")))+ assertEquals(listOf("work", "home office"), dao.getBySyncId("sync-old")!!.tags)+ } finally {+ db.close()+ SQLiteDatabase.openDatabase(path.path, null, SQLiteDatabase.OPEN_READONLY).use {+ assertEquals(4, it.version)+ }+ File(path.path + "-wal").delete(); File(path.path + "-shm").delete()+ }+ }+}
notes/src/test/java/com/vayunmathur/notes/data/NoteTagsRepositoryTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/data/NoteTagsRepositoryTest.kt b/notes/src/test/java/com/vayunmathur/notes/data/NoteTagsRepositoryTest.ktnew file mode 100644index 0000000000..8f7576e5a8--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/data/NoteTagsRepositoryTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.notes.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.notes.seedNotesDb+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Tags through Room (#913): column round trip, and the repository's rename/merge and delete. */+@RunWith(RobolectricTestRunner::class)+class NoteTagsRepositoryTest {+ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val repo get() = seedNotesDb(context)++ @BeforeTest fun purge() = runTest {+ repo.purge(); repo.deleteAllSnapshots()+ }++ private suspend fun tagsOf(syncId: String) = repo.getBySyncId(syncId)!!.tags++ @Test fun tagsRoundTripThroughTheColumn() = runTest {+ repo.upsertRaw(Note(title = "t", content = "", syncId = "rt", tags = listOf("Work", "記 😀", "a \"quoted\" tag")))+ assertEquals(listOf("Work", "記 😀", "a \"quoted\" tag"), tagsOf("rt"))+ repo.upsertRaw(Note(title = "u", content = "", syncId = "untagged"))+ assertEquals(emptyList(), tagsOf("untagged"))+ }++ @Test fun converterStoresJsonAndToleratesGarbage() {+ val c = NoteConverters()+ assertEquals("[]", c.fromTags(emptyList()))+ assertEquals("""["a","b c"]""", c.fromTags(listOf("a", "b c")))+ assertEquals(listOf("a", "b c"), c.toTags("""["a","b c"]"""))+ assertEquals(emptyList(), c.toTags("not json"))+ assertEquals(emptyList(), c.toTags("""{"a":1}"""))+ }++ @Test fun renameAppliesToEveryNoteAndBumpsUpdatedAt() = runTest {+ repo.upsertRaw(Note(title = "1", content = "", syncId = "n1", updatedAt = 10, tags = listOf("work", "x")))+ repo.upsertRaw(Note(title = "2", content = "", syncId = "n2", updatedAt = 10, tags = listOf("Work")))+ repo.upsertRaw(Note(title = "3", content = "", syncId = "n3", updatedAt = 10, tags = listOf("home")))+ assertEquals(2, repo.renameTag("work", "office"))+ assertEquals(listOf("office", "x"), tagsOf("n1"))+ assertEquals(listOf("office"), tagsOf("n2"))+ assertEquals(listOf("home"), tagsOf("n3"))+ // Changed notes sync (local write bumps updatedAt); untouched ones do not.+ assertTrue(repo.getBySyncId("n1")!!.updatedAt > 10)+ assertTrue(repo.getBySyncId("n2")!!.updatedAt > 10)+ assertEquals(10L, repo.getBySyncId("n3")!!.updatedAt)+ }++ @Test fun renameIntoAnExistingTagMerges() = runTest {+ repo.upsertRaw(Note(title = "both", content = "", syncId = "b", tags = listOf("Home", "house")))+ repo.upsertRaw(Note(title = "old", content = "", syncId = "o", tags = listOf("house")))+ repo.renameTag("house", "home")+ assertEquals(listOf("Home"), tagsOf("b"))+ assertEquals(listOf("home"), tagsOf("o"))+ }++ @Test fun deleteStripsTheTagButKeepsEveryNote() = runTest {+ repo.upsertRaw(Note(title = "1", content = "", syncId = "d1", tags = listOf("trash", "keep")))+ repo.upsertRaw(Note(title = "2", content = "", syncId = "d2", tags = listOf("TRASH")))+ repo.upsertRaw(Note(title = "3", content = "", syncId = "d3"))+ assertEquals(2, repo.deleteTag("trash"))+ assertEquals(listOf("keep"), tagsOf("d1"))+ assertEquals(emptyList(), tagsOf("d2"))+ assertEquals(setOf("d1", "d2", "d3"), repo.getAll().map { it.syncId }.toSet())+ assertTrue(repo.getAll().none { it.deleted })+ }++ @Test fun tombstonesAreLeftAlone() = runTest {+ repo.upsertRaw(Note(title = "dead", content = "", syncId = "t", updatedAt = 5, deleted = true, tags = listOf("x")))+ assertEquals(0, repo.renameTag("x", "y"))+ assertEquals(0, repo.deleteTag("x"))+ assertEquals(listOf("x"), tagsOf("t"))+ assertEquals(5L, repo.getBySyncId("t")!!.updatedAt)+ }+}
notes/src/test/java/com/vayunmathur/notes/domain/NoteTagsTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/domain/NoteTagsTest.kt b/notes/src/test/java/com/vayunmathur/notes/domain/NoteTagsTest.ktnew file mode 100644index 0000000000..075685625e--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/domain/NoteTagsTest.kt@@ -0,0 +1,154 @@+package com.vayunmathur.notes.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Pins the pure tag rules (#913): normalisation, rename/merge, delete, counts, suggestions. */+class NoteTagsTest {++ // ---- normalizeTag / normalizeTags ----++ @Test fun `trims and collapses internal whitespace`() {+ assertEquals("home office", normalizeTag(" home \t\n office "))+ assertEquals("a b c", normalizeTag("a b\u00a0c".replace('\u00a0', ' ')))+ }++ @Test fun `blank input is dropped`() {+ assertNull(normalizeTag(""))+ assertNull(normalizeTag(" \t\n"))+ assertEquals(listOf("x"), normalizeTags(listOf("", " ", "x", "\n")))+ }++ @Test fun `long tags are cut to the limit and re-trimmed`() {+ val long = "a".repeat(MAX_TAG_LENGTH + 10)+ assertEquals(MAX_TAG_LENGTH, normalizeTag(long)!!.length)+ // A cut landing on a space must not leave a trailing space.+ val spaced = "b".repeat(MAX_TAG_LENGTH - 1) + " tail"+ assertEquals("b".repeat(MAX_TAG_LENGTH - 1), normalizeTag(spaced))+ }++ @Test fun `cut never splits a surrogate pair`() {+ val tag = "a".repeat(MAX_TAG_LENGTH - 1) + "😀" + "zz"+ val cut = normalizeTag(tag)!!+ assertEquals("a".repeat(MAX_TAG_LENGTH - 1), cut)+ assertFalse(cut.last().isHighSurrogate())+ // An emoji that fits whole is kept whole.+ assertEquals("😀 work", normalizeTag(" 😀 work "))+ }++ @Test fun `dedupes case-insensitively keeping the first spelling and order`() {+ assertEquals(listOf("Work", "home"), normalizeTags(listOf("Work", "home", "work", "WORK ", " Home")))+ }++ @Test fun `keeps at most the per-note maximum`() {+ val many = (1..MAX_TAGS_PER_NOTE + 5).map { "t$it" }+ val out = normalizeTags(many)+ assertEquals(MAX_TAGS_PER_NOTE, out.size)+ assertEquals("t1", out.first())+ assertEquals("t$MAX_TAGS_PER_NOTE", out.last())+ // Duplicates do not use up the budget.+ val withDupes = listOf("a", "A", "a") + (1..MAX_TAGS_PER_NOTE).map { "u$it" }+ assertEquals(MAX_TAGS_PER_NOTE, normalizeTags(withDupes).size)+ assertEquals("a", normalizeTags(withDupes).first())+ }++ @Test fun `normalisation is idempotent`() {+ val raw = listOf(" Work ", "work", "a b", "", "x".repeat(60))+ val once = normalizeTags(raw)+ assertEquals(once, normalizeTags(once))+ }++ // ---- canonical / has ----++ @Test fun `typed tag adopts an existing spelling`() {+ assertEquals("Work", canonicalTag(" work ", listOf("Home", "Work")))+ assertEquals("new tag", canonicalTag("new tag", listOf("Work")))+ assertNull(canonicalTag(" ", listOf("Work")))+ }++ @Test fun `hasTag ignores case`() {+ assertTrue(hasTag(listOf("Work"), "work"))+ assertFalse(hasTag(listOf("Work"), "wor"))+ assertFalse(hasTag(emptyList(), "work"))+ }++ // ---- rename / merge / delete ----++ @Test fun `rename replaces in place`() {+ assertEquals(listOf("a", "office", "c"), withTagRenamed(listOf("a", "work", "c"), "Work", "office"))+ }++ @Test fun `rename into an existing tag merges and keeps the existing spelling`() {+ // existing target before the source: target stays, source dropped+ assertEquals(listOf("Home", "a"), withTagRenamed(listOf("Home", "a", "house"), "house", "home"))+ // existing target after the source: merged at the source's position, first spelling wins+ assertEquals(listOf("home", "a"), withTagRenamed(listOf("house", "a", "Home"), "house", "home"))+ }++ @Test fun `rename can change only the case`() {+ assertEquals(listOf("Work"), withTagRenamed(listOf("work"), "work", "Work"))+ }++ @Test fun `rename is a no-op when absent or the target is blank`() {+ val tags = listOf("a", "b")+ assertEquals(tags, withTagRenamed(tags, "zzz", "c"))+ assertEquals(tags, withTagRenamed(tags, "a", " "))+ }++ @Test fun `rename normalises the target`() {+ assertEquals(listOf("new name"), withTagRenamed(listOf("old"), "old", " new name "))+ }++ @Test fun `delete removes case-insensitively and leaves others`() {+ assertEquals(listOf("a", "c"), withoutTag(listOf("a", "B", "c"), "b"))+ assertEquals(listOf("a"), withoutTag(listOf("a"), "missing"))+ }++ // ---- counts ----++ @Test fun `counts sort by count then name and group case-insensitively`() {+ val counts = tagCounts(+ listOf(+ listOf("work", "home"),+ listOf("Work", "travel"),+ listOf("work", "Home", "alpha"),+ emptyList(),+ ),+ )+ assertEquals(+ listOf(TagCount("work", 3), TagCount("home", 2), TagCount("alpha", 1), TagCount("travel", 1)),+ counts,+ )+ }++ @Test fun `display spelling is the most used one, ties to the first seen`() {+ assertEquals("Work", tagCounts(listOf(listOf("Work"), listOf("Work"), listOf("work"))).single().name)+ assertEquals("b", tagCounts(listOf(listOf("b"), listOf("B"))).single().name)+ }++ @Test fun `a note counts once even if it repeats a tag`() {+ assertEquals(listOf(TagCount("x", 1)), tagCounts(listOf(listOf("x", "X"))))+ assertTrue(tagCounts(emptyList()).isEmpty())+ }++ // ---- suggestions ----++ @Test fun `suggestions keep usage order, prefer prefixes and skip existing`() {+ val known = listOf("work", "homework", "home", "wishlist")+ assertEquals(listOf("work", "homework"), suggestTags(known, "wor", exclude = emptyList(), limit = 5))+ assertEquals(listOf("homework", "home"), suggestTags(known, "ho", exclude = emptyList(), limit = 5))+ assertEquals(listOf("homework"), suggestTags(known, "wor", exclude = listOf("WORK"), limit = 5))+ }++ @Test fun `blank query suggests top tags and the limit applies`() {+ val known = listOf("a", "b", "c")+ assertEquals(listOf("a", "b"), suggestTags(known, " ", exclude = emptyList(), limit = 2))+ }++ @Test fun `an exact match is not suggested back`() {+ assertEquals(listOf("work trip"), suggestTags(listOf("work", "work trip"), "Work", emptyList(), 5))+ }+}
notes/src/test/java/com/vayunmathur/notes/sync/NoteRelayTagsTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/sync/NoteRelayTagsTest.kt b/notes/src/test/java/com/vayunmathur/notes/sync/NoteRelayTagsTest.ktnew file mode 100644index 0000000000..f370763df7--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/sync/NoteRelayTagsTest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.notes.sync++import com.vayunmathur.notes.data.Note+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Relay envelope compatibility for tags (#913).+ *+ * The same two literals are pinned on the everysync side+ * (`RemoteNoteTagsParityTest`), which is the cross-module parity check: both+ * shapes must produce these exact bytes, because the relay log stores them and+ * the merge driver hashes them.+ */+class NoteRelayTagsTest {++ /** RelayNoteJson exactly as it was before tags (main 34d3e1c9d). */+ @Serializable+ private data class PreTagsRelayNoteJson(+ val uid: String = "",+ val title: String = "",+ val content: String = "",+ val blocksJson: String? = null,+ val position: Double = 0.0,+ val deleted: Boolean = false,+ val updatedAt: Long = 0L,+ )++ // Same configuration as RelayNoteProvider's `json`.+ private val json = Json { ignoreUnknownKeys = true }++ private val note = Note(+ id = 9, title = "Plan", content = "body", position = 2.5,+ blocks = """{"blocks":[]}""", syncId = "abc123", updatedAt = 1_700_000_000_000, deleted = false,+ )++ @Test fun `untagged note encodes byte-identical to the pre-tags envelope`() {+ val now = json.encodeToString(RelayNoteJson.serializer(), note.toRelayJson())+ val before = json.encodeToString(+ PreTagsRelayNoteJson.serializer(),+ PreTagsRelayNoteJson("abc123", "Plan", "body", """{"blocks":[]}""", 2.5, false, 1_700_000_000_000),+ )+ assertEquals(before, now)+ assertEquals(UNTAGGED_GOLDEN, now)+ // The content hash is over the canonical bytes; identical bytes mean an identical hash.+ val canonicalNow = json.encodeToString(+ RelayNoteJson.serializer(),+ note.toRelayJson().copy(uid = "", position = 0.0, updatedAt = 0L, deleted = false),+ )+ val canonicalBefore = json.encodeToString(+ PreTagsRelayNoteJson.serializer(),+ PreTagsRelayNoteJson("", "Plan", "body", """{"blocks":[]}"""),+ )+ assertEquals(canonicalBefore, canonicalNow)+ }++ @Test fun `tagged note encodes tags last and round-trips`() {+ val tagged = note.copy(tags = listOf("work", "home office"))+ val payload = json.encodeToString(RelayNoteJson.serializer(), tagged.toRelayJson())+ assertEquals(TAGGED_GOLDEN, payload)+ val back = json.decodeFromString(RelayNoteJson.serializer(), payload).toNote(9)+ assertEquals(tagged, back)+ }++ @Test fun `an older peer's tagless payload decodes as untagged`() {+ val back = json.decodeFromString(RelayNoteJson.serializer(), UNTAGGED_GOLDEN).toNote(1)+ assertEquals(emptyList(), back.tags)+ assertEquals("Plan", back.title)+ }++ @Test fun `a tagged payload decodes on a pre-tags build by dropping the unknown key`() {+ // What an older notes build does with a newer envelope: ignoreUnknownKeys, tags lost.+ val old = json.decodeFromString(PreTagsRelayNoteJson.serializer(), TAGGED_GOLDEN)+ assertEquals("Plan", old.title)+ assertEquals("abc123", old.uid)+ }++ @Test fun `received tags are normalised`() {+ val remote = RelayNoteJson(uid = "x", tags = listOf(" Work ", "work", "", "a b", "y".repeat(50)))+ val tags = remote.toNote(1).tags+ assertEquals(listOf("Work", "a b", "y".repeat(40)), tags)+ assertTrue(RelayNoteJson(uid = "x").toNote(1).tags.isEmpty())+ }++ companion object {+ const val UNTAGGED_GOLDEN =+ """{"uid":"abc123","title":"Plan","content":"body","blocksJson":"{\"blocks\":[]}",""" ++ """"position":2.5,"updatedAt":1700000000000}"""+ const val TAGGED_GOLDEN =+ """{"uid":"abc123","title":"Plan","content":"body","blocksJson":"{\"blocks\":[]}",""" ++ """"position":2.5,"updatedAt":1700000000000,"tags":["work","home office"]}"""+ }+}
notes/src/test/java/com/vayunmathur/notes/ui/NoteListFilterTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/ui/NoteListFilterTest.kt b/notes/src/test/java/com/vayunmathur/notes/ui/NoteListFilterTest.ktnew file mode 100644index 0000000000..5e7aae2773--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/ui/NoteListFilterTest.kt@@ -0,0 +1,49 @@+package com.vayunmathur.notes.ui++import com.vayunmathur.notes.data.Note+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Pins the list's tag filter and tag-aware search ([filterNotes], [noteMatchesSearch]) from #913. */+class NoteListFilterTest {+ private val notes = listOf(+ Note(id = 1, title = "Standup", content = "agenda", position = 1.0, tags = listOf("Work", "daily")),+ Note(id = 2, title = "Groceries", content = "eggs", position = 2.0, tags = listOf("home")),+ Note(id = 3, title = "Roadmap", content = "q3 plan", position = 3.0, tags = listOf("work")),+ Note(id = 4, title = "Untagged", content = "nothing", position = 4.0),+ )++ private fun ids(list: List<Note>) = list.map { it.id }++ @Test fun `no tag and no query keeps everything in order`() {+ assertEquals(notes, filterNotes(notes, "", null))+ assertEquals(notes, filterNotes(notes, " ", null))+ }++ @Test fun `tag filter is case-insensitive and keeps order`() {+ assertEquals(listOf(1L, 3L), ids(filterNotes(notes, "", "WORK")))+ assertEquals(listOf(2L), ids(filterNotes(notes, "", "home")))+ assertEquals(emptyList(), ids(filterNotes(notes, "", "missing")))+ }++ @Test fun `tag filter matches whole tags, not substrings`() {+ assertEquals(emptyList(), ids(filterNotes(notes, "", "wor")))+ }++ @Test fun `search matches tag names`() {+ assertTrue(noteMatchesSearch(notes[0], "dail"))+ assertTrue(noteMatchesSearch(notes[1], "HOME"))+ assertEquals(listOf(1L, 3L), ids(filterNotes(notes, "work", null)))+ }++ @Test fun `search still matches title and content`() {+ assertEquals(listOf(2L), ids(filterNotes(notes, "eggs", null)))+ assertEquals(listOf(3L), ids(filterNotes(notes, "roadmap", null)))+ }++ @Test fun `tag and search combine with AND`() {+ assertEquals(listOf(3L), ids(filterNotes(notes, "plan", "work")))+ assertEquals(emptyList(), ids(filterNotes(notes, "eggs", "work")))+ }+}
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.ktnew file mode 100644index 0000000000..4383ca6fca--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/ui/NoteTagsComposeTest.kt@@ -0,0 +1,221 @@+package com.vayunmathur.notes.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsSelected+import androidx.compose.ui.test.assertIsNotSelected+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.longClick+import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performImeAction+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTextReplacement+import androidx.compose.ui.test.performTouchInput+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteBlock+import com.vayunmathur.notes.domain.normalizeTags+import com.vayunmathur.notes.domain.withoutTag+import com.vayunmathur.notes.platform.NoteActions+import com.vayunmathur.notes.platform.NoteUiState+import com.vayunmathur.notes.platform.NotesListActions+import com.vayunmathur.notes.platform.NotesListUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Tag UI (#913): adding/removing in the editor, filtering and the rename/delete menu in the list. */+@RunWith(RobolectricTestRunner::class)+class NoteTagsComposeTest {+ @get:Rule val rule = createComposeRule()++ private class RecordingListActions : NotesListActions {+ val renamed = mutableListOf<Pair<String, String>>()+ val deleted = mutableListOf<String>()+ override fun renameTag(from: String, to: String) { renamed += from to to }+ override fun deleteTag(tag: String) { deleted += tag }+ }++ private fun notes() = listOf(+ Note(id = 1, title = "Standup", content = "agenda", position = 1.0, syncId = "s1", tags = listOf("Work")),+ Note(id = 2, title = "Groceries", content = "eggs", position = 2.0, syncId = "s2", tags = listOf("Home")),+ Note(id = 3, title = "Roadmap", content = "plan", position = 3.0, syncId = "s3", tags = listOf("Work", "Ideas")),+ Note(id = 4, title = "Loose", content = "none", position = 4.0, syncId = "s4"),+ )++ private fun shown(text: String) = rule.onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty()++ // ---- editor ----++ @Test fun editorAddsTagOnDoneAndRemovesOnChipTap() {+ var tags by mutableStateOf(listOf("Existing"))+ val actions = object : NoteActions {+ override fun addTag(tag: String) { tags = normalizeTags(tags + tag) }+ override fun removeTag(tag: String) { tags = withoutTag(tags, tag) }+ }+ rule.setContent {+ NoteScreen(+ NoteUiState("Title here", listOf(NoteBlock.Text("body", "b1")), tags = tags, knownTags = listOf("Existing", "Travel")),+ actions,+ )+ }+ rule.onNodeWithText("Existing").assertIsDisplayed()+ rule.onNode(hasSetTextAction() and hasText("Add tag")).performTextInput(" road trip ")+ // The placeholder is gone once there is text; find the field by what was typed.+ rule.onNode(hasSetTextAction() and hasText("road", substring = true)).performImeAction()+ rule.waitForIdle()+ assertEquals(listOf("Existing", "road trip"), tags)+ rule.onNodeWithText("road trip").assertIsDisplayed()++ rule.onNodeWithContentDescription("Remove tag Existing").performClick()+ rule.waitForIdle()+ assertEquals(listOf("road trip"), tags)+ // The chip is gone ("Existing" may still be offered as a suggestion while the field has focus).+ assertTrue(rule.onAllNodesWithContentDescription("Remove tag Existing").fetchSemanticsNodes().isEmpty())+ }++ @Test fun editorCommaAddsSeveralAndSuggestionAddsKnownTag() {+ var tags by mutableStateOf(emptyList<String>())+ val actions = object : NoteActions {+ override fun addTag(tag: String) { tags = normalizeTags(tags + tag) }+ }+ rule.setContent {+ NoteScreen(NoteUiState("T", listOf(NoteBlock.Text("b", "b1")), tags = tags, knownTags = listOf("Travel", "Work")), actions)+ }+ val field = rule.onNode(hasSetTextAction() and hasText("Add tag"))+ field.performTextInput("a, b,")+ rule.waitForIdle()+ assertEquals(listOf("a", "b"), tags)+ // Field is focused: typing narrows suggestions to known tags; tapping one adds it.+ rule.onNode(hasSetTextAction() and hasText("Add tag")).performTextInput("tra")+ rule.waitForIdle()+ rule.onNodeWithText("Travel").performClick()+ rule.waitForIdle()+ assertEquals(listOf("a", "b", "Travel"), tags)+ }++ @Test fun editorAtTheTagLimitReplacesTheFieldWithANote() {+ val full = (1..com.vayunmathur.notes.domain.MAX_TAGS_PER_NOTE).map { "t$it" }+ rule.setContent { NoteScreen(NoteUiState("T", listOf(NoteBlock.Text("b", "b1")), tags = full), object : NoteActions {}) }+ rule.onNodeWithText("A note can have up to 20 tags").assertExists()+ assertTrue(rule.onAllNodes(hasSetTextAction() and hasText("Add tag")).fetchSemanticsNodes().isEmpty())+ }++ // ---- list ----++ @Test fun filterRowShowsCountsAndFiltersTheList() {+ rule.setContent { NotesListScreen(NotesListUiState(notes()), RecordingListActions()) }+ // All + one chip per tag, most used first.+ rule.onNodeWithText("All").assertIsSelected()+ rule.onNode(hasText("Work") and hasText("2")).assertIsNotSelected()+ // (Robolectric's default window is short; the lazy list may not compose the 4th row.)+ assertTrue(shown("Standup") && shown("Groceries"))+ // Unfiltered: reorder handles exist.+ assertTrue(rule.onAllNodesWithContentDescription("Reorder").fetchSemanticsNodes().isNotEmpty())++ rule.onNode(hasText("Work") and hasText("2")).performClick()+ rule.waitForIdle()+ rule.onNode(hasText("Work") and hasText("2")).assertIsSelected()+ assertTrue(shown("Standup") && shown("Roadmap"))+ assertTrue(!shown("Groceries") && !shown("Loose"))+ // Filtered: no reorder handles, and the hint says why.+ assertTrue(rule.onAllNodesWithContentDescription("Reorder").fetchSemanticsNodes().isEmpty())+ rule.onNodeWithText("Showing one tag. Select All to reorder notes.").assertIsDisplayed()++ rule.onNodeWithText("All").performClick()+ rule.waitForIdle()+ assertTrue(shown("Groceries"))+ assertTrue(!shown("Showing one tag. Select All to reorder notes."))+ }++ @Test fun tappingTheSelectedTagAgainClearsTheFilter() {+ rule.setContent { NotesListScreen(NotesListUiState(notes()), RecordingListActions(), initialTagFilter = "home") }+ assertTrue(shown("Groceries") && !shown("Standup"))+ rule.onNode(hasText("Home") and hasText("1")).performClick()+ rule.waitForIdle()+ assertTrue(shown("Standup") && shown("Groceries"))+ }++ @Test fun searchMatchesTagNames() {+ rule.setContent { NotesListScreen(NotesListUiState(notes()), RecordingListActions(), initialSearchQuery = "idea") }+ assertTrue(shown("Roadmap"))+ assertTrue(!shown("Standup") && !shown("Groceries"))+ }++ @Test fun longPressRenameAndDelete() {+ val actions = RecordingListActions()+ rule.setContent { NotesListScreen(NotesListUiState(notes()), actions) }++ rule.onNode(hasText("Home") and hasText("1")).performTouchInput { longClick() }+ rule.waitForIdle()+ rule.onNodeWithText("Rename").performClick()+ rule.waitForIdle()+ rule.onNodeWithText("Tag name").performTextReplacement("work")+ rule.waitForIdle()+ // Renaming onto an existing tag says it will merge.+ rule.onNodeWithText("Merges into the existing tag \"Work\"").assertExists()+ rule.onNode(hasText("Rename") and androidx.compose.ui.test.hasClickAction()).performClick()+ rule.waitForIdle()+ assertEquals(listOf("Home" to "work"), actions.renamed)++ rule.onNode(hasText("Ideas") and hasText("1")).performTouchInput { longClick() }+ rule.waitForIdle()+ rule.onNodeWithText("Delete").performClick()+ rule.waitForIdle()+ rule.onNodeWithText("Delete tag \"Ideas\"?").assertExists()+ rule.onNodeWithText("Removes the tag from 1 note. The note itself is kept.").assertExists()+ rule.onNode(hasText("Delete") and androidx.compose.ui.test.hasClickAction()).performClick()+ rule.waitForIdle()+ assertEquals(listOf("Ideas"), actions.deleted)+ }++ @Test fun renameDialogWarnsAboutMergeAndConfirms() {+ var renamed: String? = null+ var dismissed = 0+ rule.setContent {+ RenameTagDialogHost(onRename = { renamed = it }, onDismiss = { dismissed++ })+ }+ // Unchanged name: Rename is disabled.+ rule.onNode(hasText("Rename") and androidx.compose.ui.test.hasClickAction()).performClick()+ assertEquals(null, renamed)+ rule.onNodeWithText("Tag name").performTextReplacement(" work ")+ rule.onNodeWithText("Merges into the existing tag \"Work\"").assertExists()+ rule.onNode(hasText("Rename") and androidx.compose.ui.test.hasClickAction()).performClick()+ assertEquals("work", renamed)+ assertEquals(1, dismissed)+ }++ @androidx.compose.runtime.Composable+ private fun RenameTagDialogHost(onRename: (String) -> Unit, onDismiss: () -> Unit) {+ com.vayunmathur.library.ui.DynamicTheme {+ com.vayunmathur.notes.ui.dialogs.RenameTagDialog(+ tag = "Home",+ existingTags = listOf("Work", "Home", "Ideas"),+ onRename = onRename,+ onDismiss = onDismiss,+ )+ }+ }++ @Test fun noFilterRowWithoutTagsAndCardsShowTags() {+ rule.setContent {+ NotesListScreen(NotesListUiState(listOf(Note(id = 1, title = "Only", content = "x", syncId = "o"))), RecordingListActions())+ }+ assertTrue(!shown("All"))+ }++ @Test fun cardsShowTheirTagsCompactly() {+ rule.setContent { NotesListScreen(NotesListUiState(notes()), RecordingListActions()) }+ assertTrue(shown("Work · Ideas"))+ }+}