diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bc1d6b0..aa090d8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -140,10 +140,18 @@ under AGPL-3.0 before opening the PR. ## Release process (for maintainers) -1. Bump `versionCode` + `versionName` in `app/build.gradle.kts`. -2. Update the Development Plan §10 history table. -3. Tag the commit: `git tag -s vX.Y.Z -m "vX.Y.Z — short summary"`. -4. `./gradlew assembleRelease` → upload APK to Gitea Releases. -5. Push the tag: `git push origin vX.Y.Z`. +> **Version scheme (from v0.3.0.0 onwards):** `MAJOR.MINOR.MAINTENANCE.EMERGENCY` — +> e.g. `0.3.0.0`. `MAJOR.MINOR.MAINTENANCE` are normal release numbers; +> `EMERGENCY` is non-zero only for hotfixes shipped out-of-band. +> `versionCode` is a monotonic int and always +1 per release. +> A build with a `versionName` that doesn't match `^\d+\.\d+\.\d+\.\d+$` +> fails immediately — there's a validator in `app/build.gradle.kts`. + +1. Bump `versionCode` (+1) and `versionName` in `app/build.gradle.kts`. +2. Update the Development Plan §10 history table with the new dot-name. +3. Tag the commit: `git tag -s vX.Y.Z.W -m "vX.Y.Z.W — short summary"`. +4. `./gradlew assembleDebug assembleRelease` — confirm both green. +5. Upload `app/build/outputs/apk/release/app-release.apk` to Gitea Releases. +6. Push the tag: `git push origin vX.Y.Z.W`. Thanks again for contributing! 🙏 diff --git a/Incido Development Plan.txt b/Incido Development Plan.txt index 337a08d..bed94d6 100644 --- a/Incido Development Plan.txt +++ b/Incido Development Plan.txt @@ -361,12 +361,19 @@ A short reference for AI assistants: ## 10. Document History +> **Version scheme (from v0.3.0.0 onwards):** `MAJOR.MINOR.MAINTENANCE.EMERGENCY` — +> e.g. `0.3.0.0`. `MAJOR.MINOR.MAINTENANCE` are normal release numbers; +> `EMERGENCY` is non-zero only for hotfixes shipped out-of-band. +> `versionCode` is a monotonic int and always +1 per release. +> The build refuses to compile if `versionName` doesn't match this shape. + | Version | Date | Notes | |---------|------|-------| -| 0.1 | 2026-08-14 | Initial plan drafted via interview | -| 0.1.1 | 2026-08-14 | Added F1 explicit "list of currently saved notes" requirement + F7 auto-refresh + clarified UI section | -| 0.1.1 | 2026-08-14 | Editor IME fix (Scaffold contentWindowInsets + adjustResize) + title/body display on list cards | -| 0.2 | 2026-08-14 | Polish + first Keep-parity features. Discard-confirm dialog; release signing config (dev keystore). Favorites (renamed from Pinned Notes), full-text search, 6 colour-coded notes, inline GFM checklists (open/done counts). ObjectBox KMP migration deferred to v0.5 (tracked). | +| 0.1.0.0 | 2026-08-14 | Initial plan drafted via interview | +| 0.1.1.0 | 2026-08-14 | F1 explicit "list of currently saved notes" requirement + F7 auto-refresh + clarified UI section + editor IME fix (contentWindowInsets + adjustResize) + title/body on cards | +| 0.2.0.0 | 2026-08-14 | Polish + first Keep-parity features. Discard-confirm dialog; release signing config (dev keystore). Favorites (renamed from Pinned Notes), full-text search, 6 colour-coded notes, inline GFM checklists (open/done counts). ObjectBox KMP migration deferred to v0.5 (tracked). | +| 0.2.0.1 | 2026-08-14 | Hotfix: search-active flag folded into uiState so the search icon actually opens the field. | +| 0.3.0.0 | 2026-08-14 | Hashtags (separate entity + cross-ref, 5-tag cap, autocomplete, persistent chips on editor, search() also matches tag names) + bolder colour accent (14 dp gradient stripe + tinted card background + corner chip) + nav drawer (Home / Favorites / Untagged + recent tags) + centred app-bar title + new version scheme adopted (validator in app/build.gradle.kts). | --- diff --git a/README.md b/README.md index 8978bd1..3f0f549 100644 --- a/README.md +++ b/README.md @@ -6,48 +6,82 @@ Incido is a privacy-first, on-device note-taking application for Android. All data stays on your device by default — no accounts, no cloud, no trackers. -This repository contains the **v0.2** release: a single-user, offline note -app with favourites, full-text search, colour-coded notes, and inline -checklists. The architecture is multi-module Android today and is -structured so iOS / Desktop ports can happen later without UI rewrites. +This repository contains the **v0.3.0.0** release: a single-user, offline +note app with hashtags, favourites, full-text search, colour-coded +notes, and a navigation drawer. The architecture is multi-module Android +today and is structured so iOS / Desktop ports can happen later without +UI rewrites. -**Current release:** v0.2 (see [Changelog](#changelog) below). +**Current release:** v0.3.0.0 (see [Changelog](#changelog) below). + +> **Version scheme (from v0.3.0.0 onwards):** `MAJOR.MINOR.MAINTENANCE.EMERGENCY` — +> e.g. `0.3.0.0`. `MAJOR.MINOR.MAINTENANCE` are normal release numbers; +> `EMERGENCY` is non-zero only for hotfixes shipped out-of-band. +> `versionCode` is a monotonic int and always +1 per release. +> An empty MAINTENANCE/EMERGENCY slot is written as `0`. +> The build refuses to compile if `versionName` doesn't match this shape. --- ## Features -### v0.2 highlights +### v0.3.0.0 highlights + +- **Hashtags.** Tag any note with up to 5 hashtags. Tags are always + visible as chips above the editor text field; tap ✕ to remove. Tap + `#` (or `+ add`) to open a sheet with autocomplete suggestions from + your existing tags. Hashtags are searchable from the list (typing + `work` finds notes containing the word *and* notes tagged `#work`). +- **Bolder colour accent on list cards.** Each colour-tagged note now + gets a 14 dp vertical gradient stripe on the left, a subtle 12 % + tinted card background, and a 10 dp solid colour chip in the + top-right — so different-coloured notes are visually distinct at a + glance without you needing to focus on the stripe. +- **Navigation drawer.** Hamburger top-left opens a drawer with + **Home**, **Favorites**, **Untagged**, a divider, then a live scrollable + list of the most-recently-used hashtags. Tap any entry to filter the + list to just those notes. +- **Centred app-bar title.** Both the list screen (`Incido`) and the + editor (`Edit note` / `New note`) now centre their titles via + Material 3's `CenterAlignedTopAppBar`. +- **New version scheme.** All version bumps from now on follow the + `MAJOR.MINOR.MAINTENANCE.EMERGENCY` pattern; the build refuses anything + that doesn't match. + +### v0.2.0.0 - **Favourites.** Tap the star icon on any card to pin it to the top of - the list. (Replaces the §6.1 "Pinned Notes" item; renamed per - maintainer request.) + the list. - **Full-text search.** Tap the search icon in the top app bar; the list - filters live as you type. Backed by ObjectBox's `contains` query — - case-insensitive, no extra dependencies. + filters live as you type. - **Color-coded notes.** Pick from six preset accent colours in the - editor (none / blue / green / amber / red / purple). Each list card - gets a 4dp vertical stripe on the left edge. -- **Inline checklists.** Lines beginning with `- [ ]` or `- [x]` are - parsed; the card preview shows the open/done counts (e.g. - "2 open · 1 done"). No DB schema migration — the text stays plain. + editor; each list card gets a 4 dp vertical stripe. +- **Inline checklists.** Lines beginning with `- [ ]` or `- [x]` show + open/done counts on the card preview. - **Discard-confirm dialog.** Closing the editor with unsaved changes - now prompts "Discard changes?" with Discard / Keep-editing buttons. - Applies to both the Back arrow and the hardware back gesture. + prompts `Discard changes?` (works for both Back arrow and hardware + back gesture). +- **Release signing** — dev keystore in `keystore/`, `assembleRelease` + produces a v2-signed APK out of the box. -### v0.1.1 polish +### v0.2.0.1 (hotfix) -- **Editor respects the soft keyboard.** With edge-to-edge enabled, the - editor's `Scaffold` unions `WindowInsets.systemBars` with - `WindowInsets.ime`, so the text field automatically shrinks above the - keyboard instead of being hidden behind it. `adjustResize` is also set - on `MainActivity` as a pre-Android-15 fallback. -- **List cards now show a title + body preview.** The first non-empty line - of a note is treated as its title and rendered in a larger / bolder - style; the remainder is shown as an abbreviated preview below it - (max 2 lines, ellipsised). Empty notes display as "Untitled". +- **Search icon actually opens the search bar.** v0.2.0.0's + search-active flag was on a separate `StateFlow` the composable never + observed; folded into `uiState` so tapping the icon now lights up the + field. -### v0.1.0 (original MVP) +### v0.1.1.0 + +- **Editor respects the soft keyboard.** `Scaffold` unions + `WindowInsets.systemBars` with `WindowInsets.ime` so the text field + shrinks above the keyboard. `adjustResize` set as pre-Android-15 + fallback. +- **List cards now show a title + body preview.** First non-empty line + = title; remainder = body preview (max 2 lines, ellipsised). + Empty notes display as "Untitled". + +### v0.1.0.0 - Create, edit, and delete plain-text notes - ObjectBox-backed persistence ([objectbox.io](https://objectbox.io/)) @@ -67,11 +101,13 @@ cross-platform ports, end-to-end sync, and security features. ## Changelog -| Version | Date | Highlights | -|---------|------|------------| -| 0.1 | 2026-08-14 | First MVP: list + editor, ObjectBox, Material 3 | -| 0.1.1 | 2026-08-14 | Editor IME fix + title/body on list cards | -| 0.2 | 2026-08-14 | Polish + favourites, search, colours, checklists, discard dialog, release signing | +| Version | Date | Highlights | +|-----------|------------|------------| +| 0.1.0.0 | 2026-08-14 | First MVP: list + editor, ObjectBox, Material 3 | +| 0.1.1.0 | 2026-08-14 | Editor IME fix + title/body on list cards | +| 0.2.0.0 | 2026-08-14 | Polish + favourites, search, colours, checklists, discard dialog, release signing | +| 0.2.0.1 | 2026-08-14 | Hotfix: search icon now actually opens the search bar | +| 0.3.0.0 | 2026-08-14 | Hashtags (visible chips on editor, 5-tag cap, autocomplete) + bolder colour accent + nav drawer (Home / Favorites / Untagged + recent tags) + centred app-bar title + new version scheme | --- @@ -154,6 +190,10 @@ Uses the dev keystore at `keystore/release.jks` — see **Replace this keystore with a production key before any external distribution.** +The build will **fail** if `versionName` doesn't match +`^\d+\.\d+\.\d+\.\d+$` (the new scheme). Update `app/build.gradle.kts` +to fix. + ### 5. Install on a device ```bash @@ -187,19 +227,21 @@ After the first push: --- -## Manual Smoke Test (Development Plan §7.2 + v0.2 additions) +## Manual Smoke Test (Development Plan §7.2 + v0.3.0.0 additions) ``` -[ ] Launch app — see empty state message ("No notes yet. Tap + to start.") -[ ] Tap FAB — editor opens, cursor in text field -[ ] Type "Test note 1" — tap save — returns to list, "Test note 1" card visible -[ ] Tap star on card 1 — it floats to the top -[ ] Tap search icon — type "Test" — only matching card remains -[ ] Close search — full list returns, favourite still on top -[ ] Edit "Test note 2" → tap a colour swatch → save → card shows coloured stripe -[ ] Create a note with "- [ ] milk\n- [x] eggs" → card preview shows "1 open · 1 done" -[ ] Open a note → type extra content → tap Back → discard dialog appears -[ ] Force-stop app from system settings, reopen → all notes + favourites still present +[ ] Launch app — "Incido" title centred, hamburger top-left +[ ] Tap hamburger → drawer slides in with Home / Favorites / Untagged + divider + Recent tags +[ ] Tap "Favorites" → list shows only starred notes +[ ] Tap "Untagged" → list shows only notes with zero hashtags +[ ] Tap a recent hashtag → list filters to that tag +[ ] Tap "Home" → back to all notes +[ ] Open a note → chip row above text field shows current tags (empty placeholder if none) +[ ] Tap "#" icon → sheet opens, type "wo" → suggestions filter +[ ] Add a new tag → chip appears, counter goes from N/5 to (N+1)/5 +[ ] Tap chip ✕ → removed +[ ] Add 5 tags, attempt 6th → Snackbar "Maximum 5 tags reached" +[ ] Force-stop + reopen → all notes + hashtags + favourites + colours persist ``` --- diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 1a1133e..6577954 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,6 +1,17 @@ // :app — Android application entry point. Hosts MainActivity and the // application manifest, including the launcher icon and theme. -import java.io.FileInputStream +// +// Version scheme (v0.3.0.0 onwards): +// versionName = "MAJOR.MINOR.MAINTENANCE.EMERGENCY" +// - MAJOR: large breaking redesigns (rare in v0.x) +// - MINOR: normal feature releases +// - MAINTENANCE: bug fixes / refactors on a given MINOR +// - EMERGENCY: 0 in normal releases; non-zero only for hotfixes +// shipped out-of-band (e.g. v0.2.0.1 — search-icon fix) +// versionCode: monotonic int. Always +1 per release. +// +// The validator below fails the build if versionName doesn't match the +// required dotted format, so we can't regress the scheme by accident. import java.util.Properties plugins { @@ -17,22 +28,13 @@ android { applicationId = "org.incido.app" minSdk = 26 targetSdk = 35 - versionCode = 3 - versionName = "0.2" + versionCode = 5 + versionName = "0.3.0.0" } // --- Signing --- - // - // v0.2 introduces a real release signing config so `./gradlew - // assembleRelease` produces an installable APK out of the box. The - // keystore file itself is gitignored — see keystore/README.md for - // generation instructions and for the (deliberately weak) dev - // passwords baked into this build script. **Replace with a real - // production keystore before publishing.** signingConfigs { create("release") { - // Resolve paths relative to the project root so the same - // config works from both Android Studio and CLI. val keystoreFilePath = rootProject.file("keystore/release.jks") if (keystoreFilePath.exists()) { storeFile = keystoreFilePath @@ -40,9 +42,6 @@ android { keyAlias = "incido" keyPassword = "incido_dev_keystore" } - // If the keystore doesn't exist, the release build will fail - // with a clear "Keystore file not set for signing config - // release" message — by design. } } @@ -51,7 +50,7 @@ android { isMinifyEnabled = false } release { - isMinifyEnabled = false // TODO(v0.3): enable R8 + isMinifyEnabled = false // TODO(v0.3.0.0+): enable R8 signingConfig = signingConfigs.getByName("release") } } @@ -81,7 +80,6 @@ dependencies { implementation(libs.androidx.core.ktx) implementation(libs.kotlinx.coroutines.android) - // Compose BOM keeps all Compose artefact versions aligned val composeBom = platform(libs.composeBom) implementation(composeBom) @@ -89,3 +87,20 @@ dependencies { implementation(libs.compose.ui) implementation(libs.compose.material3) } + +// --- Version-name scheme validator --- +// +// MAJOR.MINOR.MAINTENANCE.EMERGENCY — exactly four dotted integers. +// Fails fast so we can't accidentally publish a "0.3" again. +val versionScheme = Regex("""^\d+\.\d+\.\d+\.\d+$""") + +gradle.taskGraph.whenReady { + val vn = android.defaultConfig.versionName + if (vn != null && !versionScheme.matches(vn)) { + throw GradleException( + "app versionName = \"$vn\" doesn't match the required " + + "MAJOR.MINOR.MAINTENANCE.EMERGENCY scheme (e.g. 0.3.0.0). " + + "Update app/build.gradle.kts." + ) + } +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/App.kt b/composeApp/src/main/kotlin/org/incido/compose/App.kt index 8174370..8f04861 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/App.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/App.kt @@ -1,49 +1,119 @@ package org.incido.compose +import androidx.compose.material3.DrawerValue +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ModalNavigationDrawer +import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.SnapshotStateList +import androidx.compose.runtime.toMutableStateList +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable +import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument +import kotlinx.coroutines.launch +import org.incido.compose.ui.drawer.IncidoDrawer import org.incido.compose.ui.editor.NoteEditorScreen import org.incido.compose.ui.notelist.NoteListScreen import org.incido.compose.ui.theme.IncidoTheme +import org.incido.domain.model.NoteFilter /** Top-level navigation destinations. */ private object Routes { const val LIST = "list" const val EDITOR = "editor/{noteId}" - fun editor(noteId: Long?): String = - "editor/${noteId ?: -1L}" + fun editor(noteId: Long?): String = "editor/${noteId ?: -1L}" } +/** Stable serialisation for [NoteFilter] so `rememberSaveable` works. */ +private fun NoteFilter.toSaveableKey(): String = key() + +private fun String.toNoteFilter(): NoteFilter = when { + this == "home" -> NoteFilter.Home + this == "favorites" -> NoteFilter.Favorites + this == "untagged" -> NoteFilter.Untagged + startsWith("tag:") -> NoteFilter.ByTag(this.removePrefix("tag:")) + else -> NoteFilter.Home +} + +@OptIn(ExperimentalMaterial3Api::class) @Composable fun IncidoApp() { IncidoTheme { val navController = rememberNavController() - NavHost(navController = navController, startDestination = Routes.LIST) { - composable(Routes.LIST) { - NoteListScreen( - onOpenEditor = { id -> navController.navigate(Routes.editor(id)) }, - ) - } - composable( - route = Routes.EDITOR, - arguments = listOf( - navArgument("noteId") { - type = NavType.LongType - defaultValue = -1L + val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) + val scope = rememberCoroutineScope() + var filterMode by rememberSaveable( + stateSaver = androidx.compose.runtime.saveable.Saver( + save = { it.toSaveableKey() }, + restore = { it.toNoteFilter() }, + ), + ) { mutableStateOf(NoteFilter.Home) } + + val currentBackStack by navController.currentBackStackEntryAsState() + val currentRoute = currentBackStack?.destination?.route?.substringBefore("/") + // Disable the drawer on the editor so back arrow / gesture do + // exactly what the user expects there. + val isListRoute = currentRoute == Routes.LIST + + LaunchedEffect(currentRoute) { + // If we land on the editor via deep link without a list in + // the back stack, snap the drawer closed. + if (!isListRoute && drawerState.isOpen) drawerState.close() + } + + ModalNavigationDrawer( + drawerState = drawerState, + gesturesEnabled = isListRoute, + drawerContent = { + IncidoDrawer( + currentFilter = filterMode, + onSelectFilter = { picked -> + filterMode = picked + scope.launch { drawerState.close() } }, - ), - ) { entry -> - val raw = entry.arguments?.getLong("noteId") ?: -1L - val id = if (raw <= 0L) null else raw - NoteEditorScreen( - noteId = id, - onClose = { navController.popBackStack() }, ) + }, + ) { + NavHost(navController = navController, startDestination = Routes.LIST) { + composable(Routes.LIST) { + NoteListScreen( + filterMode = filterMode, + onOpenDrawer = { scope.launch { drawerState.open() } }, + onOpenEditor = { id -> navController.navigate(Routes.editor(id)) }, + ) + } + composable( + route = Routes.EDITOR, + arguments = listOf( + navArgument("noteId") { + type = NavType.LongType + defaultValue = -1L + }, + ), + ) { entry -> + val raw = entry.arguments?.getLong("noteId") ?: -1L + val id = if (raw <= 0L) null else raw + NoteEditorScreen( + noteId = id, + onClose = { navController.popBackStack() }, + ) + } } } } } + +// Suppress unused-import lint for the snapshots helper that may be +// re-introduced in future filter-state extensions. +@Suppress("unused") +private fun List.toSnapshotStateList(): SnapshotStateList = toMutableStateList() diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/DrawerViewModel.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/DrawerViewModel.kt new file mode 100644 index 0000000..b5745fe --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/DrawerViewModel.kt @@ -0,0 +1,42 @@ +package org.incido.compose.ui.drawer + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.stateIn +import org.incido.compose.IncidoApplication +import org.incido.domain.model.HashtagUsage +import org.incido.domain.repository.NoteRepository + +/** + * Tiny ViewModel the navigation drawer uses to source its "Recent + * tags" list. Kept separate from [NoteListViewModel] because the + * drawer may render even before the list screen is created (and + * vice-versa). + */ +class DrawerViewModel( + repository: NoteRepository, +) : ViewModel() { + + val recentHashtags: StateFlow> = + repository.observeHashtagsByRecentUse() + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5_000), + initialValue = emptyList(), + ) + + companion object { + val Factory: ViewModelProvider.Factory = viewModelFactory { + initializer { + val app = this[APPLICATION_KEY] as IncidoApplication + DrawerViewModel(app.container.noteRepository) + } + } + } +} diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/IncidoDrawer.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/IncidoDrawer.kt new file mode 100644 index 0000000..f400fae --- /dev/null +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/drawer/IncidoDrawer.kt @@ -0,0 +1,145 @@ +package org.incido.compose.ui.drawer + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.LabelOff +import androidx.compose.material.icons.filled.Star +import androidx.compose.material.icons.filled.Tag +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalDrawerSheet +import androidx.compose.material3.NavigationDrawerItem +import androidx.compose.material3.NavigationDrawerItemDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import org.incido.domain.model.HashtagUsage +import org.incido.domain.model.NoteFilter + +/** + * Left-side navigation drawer. Top section has three fixed entries + * (Home / Favorites / Untagged); a `HorizontalDivider`; then a live + * scrollable list of the user's most-recently-used hashtags. + * + * Tapping any entry calls [onSelectFilter] and the caller (root) is + * responsible for closing the drawer. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun IncidoDrawer( + currentFilter: NoteFilter, + onSelectFilter: (NoteFilter) -> Unit, + modifier: Modifier = Modifier, + viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.Factory), +) { + val recent by viewModel.recentHashtags.collectAsStateWithLifecycle() + + ModalDrawerSheet(modifier = modifier) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), + ) { + Text( + text = "Incido", + style = MaterialTheme.typography.headlineSmall, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.padding(start = 12.dp, top = 4.dp, bottom = 16.dp), + ) + + NavigationDrawerItem( + label = { Text("Home") }, + selected = currentFilter == NoteFilter.Home, + onClick = { onSelectFilter(NoteFilter.Home) }, + icon = { Icon(Icons.Filled.Home, contentDescription = null) }, + ) + NavigationDrawerItem( + label = { Text("Favorites") }, + selected = currentFilter == NoteFilter.Favorites, + onClick = { onSelectFilter(NoteFilter.Favorites) }, + icon = { Icon(Icons.Filled.Star, contentDescription = null) }, + ) + NavigationDrawerItem( + label = { Text("Untagged") }, + selected = currentFilter == NoteFilter.Untagged, + onClick = { onSelectFilter(NoteFilter.Untagged) }, + icon = { Icon(Icons.Filled.LabelOff, contentDescription = null) }, + ) + + HorizontalDivider(modifier = Modifier.padding(vertical = 12.dp)) + + Text( + text = "Recent tags", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 12.dp, bottom = 4.dp), + ) + + if (recent.isEmpty()) { + Text( + text = "No tags yet — add some from the editor.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp), + ) + } else { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + recent.forEach { usage -> + DrawerHashtagEntry( + usage = usage, + selected = currentFilter == NoteFilter.ByTag(usage.name), + onClick = { onSelectFilter(NoteFilter.ByTag(usage.name)) }, + ) + } + } + } + + Spacer(modifier = Modifier.height(16.dp)) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun DrawerHashtagEntry( + usage: HashtagUsage, + selected: Boolean, + onClick: () -> Unit, +) { + NavigationDrawerItem( + label = { Text("#${usage.name}") }, + badge = { + val n = usage.noteCount + val label = if (n == 1) "1 note" else "$n notes" + Text(label, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + }, + selected = selected, + onClick = onClick, + icon = { Icon(Icons.Filled.Tag, contentDescription = null) }, + ) +} + +@Suppress("unused") +private val _ignored: Color = Color.Unspecified diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorScreen.kt index 0dbd13c..f4bfadc 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorScreen.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorScreen.kt @@ -7,7 +7,8 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -21,28 +22,39 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Done import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Star +import androidx.compose.material.icons.filled.Tag import androidx.compose.material.icons.outlined.StarOutline import androidx.compose.material3.AlertDialog +import androidx.compose.material3.AssistChip +import androidx.compose.material3.AssistChipDefaults +import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SuggestionChip import androidx.compose.material3.Text import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar +import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier @@ -54,9 +66,14 @@ import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel +import kotlinx.coroutines.launch +import org.incido.compose.ui.theme.AllNoteColors +import org.incido.compose.ui.theme.swatchBorderColor +import org.incido.compose.ui.theme.toComposeColor +import org.incido.domain.model.Hashtag import org.incido.domain.model.NoteColor -@OptIn(ExperimentalMaterial3Api::class) +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable fun NoteEditorScreen( noteId: Long?, @@ -70,6 +87,8 @@ fun NoteEditorScreen( val focusRequester = remember { FocusRequester() } var menuExpanded by remember { mutableStateOf(false) } var showDiscardDialog by rememberSaveable { mutableStateOf(false) } + val snackbarHost = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() LaunchedEffect(state.isLoading) { if (!state.isLoading && state.existing != null) { @@ -80,12 +99,21 @@ fun NoteEditorScreen( if (noteId == null) focusRequester.requestFocus() } + LaunchedEffect(state.snackbar) { + val msg = state.snackbar ?: return@LaunchedEffect + scope.launch { + snackbarHost.showSnackbar(msg) + viewModel.consumeSnackbar() + } + } + fun isDirty(): Boolean { if (state.isLoading) return false return state.isDirty( initialContent = viewModel.initialContent, initialFavorite = viewModel.initialFavorite, initialColor = viewModel.initialColor, + initialTags = viewModel.initialHashtags, ) } @@ -93,7 +121,6 @@ fun NoteEditorScreen( if (isDirty()) showDiscardDialog = true else onClose() } - // Intercept hardware / gesture back to honour the same discard rule. BackHandler(enabled = true) { tryClose() } if (showDiscardDialog) { @@ -118,14 +145,10 @@ fun NoteEditorScreen( } Scaffold( - // Union systemBars + IME insets so the Scaffold's contentPadding - // shrinks the available area when the soft keyboard opens. With - // edge-to-edge enabled (MainActivity.enableEdgeToEdge), the IME - // inset is NOT applied by default, which previously caused the - // OutlinedTextField to extend behind the keyboard. contentWindowInsets = WindowInsets.systemBars.union(WindowInsets.ime), + snackbarHost = { SnackbarHost(hostState = snackbarHost) }, topBar = { - TopAppBar( + CenterAlignedTopAppBar( title = { Text(if (state.isEditing) "Edit note" else "New note") }, navigationIcon = { IconButton(onClick = { tryClose() }) { @@ -133,6 +156,18 @@ fun NoteEditorScreen( } }, actions = { + IconButton( + onClick = { viewModel.openAddTagSheet() }, + enabled = state.canAddMoreTags, + ) { + Icon( + Icons.Filled.Tag, + contentDescription = "Add tag", + tint = if (state.canAddMoreTags) + MaterialTheme.colorScheme.onSurfaceVariant + else MaterialTheme.colorScheme.outlineVariant, + ) + } IconButton(onClick = { viewModel.toggleFavorite() }) { Icon( imageVector = if (state.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline, @@ -176,14 +211,25 @@ fun NoteEditorScreen( .fillMaxSize() .padding(padding), ) { - // Colour-picker row (above the editor). + HashtagChipRow( + tags = state.hashtags, + canAddMore = state.canAddMoreTags, + onAddClick = { viewModel.openAddTagSheet() }, + onRemove = { viewModel.removeTag(it) }, + ) + + // Colour-picker row above the editor text field. LazyRow( modifier = Modifier .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), + .padding(horizontal = 16.dp, vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - items(items = AllNoteColors, key = { it.storageKey.toInt() }) { color -> + items( + count = AllNoteColors.size, + key = { idx -> AllNoteColors[idx].storageKey.toInt() }, + ) { idx -> + val color = AllNoteColors[idx] ColorSwatch( color = color, selected = state.color == color, @@ -191,6 +237,7 @@ fun NoteEditorScreen( ) } } + OutlinedTextField( value = state.content, onValueChange = viewModel::onContentChange, @@ -207,14 +254,134 @@ fun NoteEditorScreen( ) } } + + if (state.isAddingTag) { + AddTagSheet( + tagInput = state.tagInput, + suggestions = state.tagSuggestions, + canCreate = Hashtag.parseOrNull(state.tagInput) != null && + Hashtag.normalise(state.tagInput) !in state.hashtags, + onInputChange = viewModel::onTagInputChange, + onPickSuggestion = { picked -> + viewModel.addTag(picked) + viewModel.closeAddTagSheet() + }, + onCreate = { + if (viewModel.addTag(state.tagInput)) { + viewModel.closeAddTagSheet() + } + }, + onDismiss = { viewModel.closeAddTagSheet() }, + ) + } } -private fun androidx.compose.foundation.lazy.LazyListScope.items( - items: List, - key: (NoteColor) -> Any, - itemContent: @Composable (NoteColor) -> Unit, +@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class) +@Composable +private fun HashtagChipRow( + tags: List, + canAddMore: Boolean, + onAddClick: () -> Unit, + onRemove: (String) -> Unit, ) { - items(items.size, key = { key(items[it]) }) { idx -> itemContent(items[idx]) } + if (tags.isEmpty() && !canAddMore) return + FlowRow( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + if (tags.isEmpty()) { + Text( + text = "Tags", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + tags.forEach { tag -> + AssistChip( + onClick = { onRemove(tag) }, + label = { Text("#$tag") }, + trailingIcon = { + Icon(Icons.Filled.Close, contentDescription = "Remove $tag", modifier = Modifier.size(16.dp)) + }, + ) + } + if (canAddMore) { + AssistChip( + onClick = onAddClick, + label = { Text("+ add") }, + leadingIcon = { Icon(Icons.Filled.Add, contentDescription = null, modifier = Modifier.size(16.dp)) }, + colors = AssistChipDefaults.assistChipColors( + labelColor = MaterialTheme.colorScheme.primary, + leadingIconContentColor = MaterialTheme.colorScheme.primary, + ), + ) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun AddTagSheet( + tagInput: String, + suggestions: List, + canCreate: Boolean, + onInputChange: (String) -> Unit, + onPickSuggestion: (String) -> Unit, + onCreate: () -> Unit, + onDismiss: () -> Unit, +) { + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = sheetState, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text("Add a tag", style = MaterialTheme.typography.titleMedium) + OutlinedTextField( + value = tagInput, + onValueChange = onInputChange, + placeholder = { Text("#tag-name") }, + singleLine = true, + leadingIcon = { Icon(Icons.Filled.Tag, contentDescription = null) }, + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None), + modifier = Modifier.fillMaxWidth(), + ) + if (suggestions.isNotEmpty()) { + Text( + "Suggestions", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + items(count = suggestions.size, key = { idx -> suggestions[idx] }) { idx -> + val s = suggestions[idx] + SuggestionChip( + onClick = { onPickSuggestion(s) }, + label = { Text("#$s") }, + ) + } + } + } + if (canCreate) { + TextButton(onClick = onCreate) { + Text("+ Create \"${Hashtag.normalise(tagInput)}\"") + } + } + Text( + "Tags help you find notes later. Up to ${NoteEditorUiState.MAX_TAGS} per note.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } } @Composable diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorViewModel.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorViewModel.kt index b1cdc23..67fd372 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorViewModel.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteEditorViewModel.kt @@ -12,35 +12,46 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.incido.compose.IncidoApplication +import org.incido.domain.model.Hashtag import org.incido.domain.model.Note import org.incido.domain.model.NoteColor import org.incido.domain.repository.NoteRepository /** - * Immutable UI state for [NoteEditorScreen]. The editor is in "new" - * mode when [existing] is null, otherwise it edits an existing note. + * Immutable UI state for [NoteEditorScreen]. */ data class NoteEditorUiState( val existing: Note? = null, val content: String = "", val isFavorite: Boolean = false, val color: NoteColor = NoteColor.NONE, + /** Normalised, sorted ascending. */ + val hashtags: List = emptyList(), + /** True while the add-tag sheet is open. */ + val isAddingTag: Boolean = false, + /** Latest typing in the add-tag sheet (raw, before normalisation). */ + val tagInput: String = "", + /** Autocomplete suggestions for the add-tag sheet. */ + val tagSuggestions: List = emptyList(), val isLoading: Boolean = true, val isSaving: Boolean = false, val isDeleted: Boolean = false, + val snackbar: String? = null, ) { val canSave: Boolean get() = content.isNotBlank() && !isSaving val isEditing: Boolean get() = existing != null + val canAddMoreTags: Boolean get() = hashtags.size < MAX_TAGS - /** - * True when the editor has changes that haven't been saved. Used by - * the discard-confirm dialog in [NoteEditorScreen] to decide whether - * to prompt before closing. - */ - fun isDirty(initialContent: String, initialFavorite: Boolean, initialColor: NoteColor): Boolean { + fun isDirty(initialContent: String, initialFavorite: Boolean, initialColor: NoteColor, initialTags: List): Boolean { return content != initialContent || isFavorite != initialFavorite || - color != initialColor + color != initialColor || + hashtags != initialTags + } + + companion object { + /** Hard cap on tags per note (matches Development Plan §6.1). */ + const val MAX_TAGS = 5 } } @@ -52,29 +63,48 @@ class NoteEditorViewModel( private val _state = MutableStateFlow(NoteEditorUiState()) val state: StateFlow = _state.asStateFlow() - /** - * Snapshot of the initial state when the editor loaded. Used by - * [NoteEditorScreen] to compute the discard-confirm predicate. - */ + /** Snapshot of initial values for the dirty predicate (see [NoteEditorScreen]). */ var initialContent: String = "" private set var initialFavorite: Boolean = false private set var initialColor: NoteColor = NoteColor.NONE private set + var initialHashtags: List = emptyList() + private set + + /** Internal: re-emits suggestions whenever the tag input changes. */ + private val tagInputFlow = MutableStateFlow("") + private val tagSuggestionsFlow = MutableStateFlow>(emptyList()) init { + // Tag autocomplete — re-query on every keystroke (debounced upstream + // would be nice but ObjectBox is plenty fast for this size). + viewModelScope.launch { + tagInputFlow.collect { raw -> + val prefix = Hashtag.normalise(raw) + val pool = if (prefix.isEmpty()) { + repository.observeAllHashtags() + } else { + repository.searchHashtags(prefix) + } + pool.collect { suggestions -> + _state.update { it.copy(tagSuggestions = suggestions) } + } + } + } + + // Load the note if editing. if (noteId == null || noteId == 0L) { - // New note _state.update { it.copy(isLoading = false) } } else { viewModelScope.launch { repository.observeById(noteId).collect { note -> if (note != null && _state.value.isLoading) { - // First non-null load — capture the initial snapshot. initialContent = note.content initialFavorite = note.isFavorite initialColor = note.color + initialHashtags = note.hashtags } _state.update { it.copy( @@ -82,6 +112,7 @@ class NoteEditorViewModel( content = note?.content ?: it.content, isFavorite = note?.isFavorite ?: it.isFavorite, color = note?.color ?: it.color, + hashtags = note?.hashtags ?: it.hashtags, isLoading = false, ) } @@ -102,23 +133,74 @@ class NoteEditorViewModel( _state.update { it.copy(color = color) } } + fun openAddTagSheet() { + _state.update { + it.copy( + isAddingTag = true, + tagInput = "", + tagSuggestions = emptyList(), + ) + } + } + + fun closeAddTagSheet() { + _state.update { it.copy(isAddingTag = false, tagInput = "", tagSuggestions = emptyList()) } + } + + fun onTagInputChange(raw: String) { + tagInputFlow.value = raw + _state.update { it.copy(tagInput = raw) } + } + + /** Add an existing tag to the note (idempotent). Returns false if the cap is hit. */ + fun addTag(name: String): Boolean { + val normalised = Hashtag.normalise(name) + if (normalised.isEmpty()) return false + if (!normalised.matches(Regex("^[a-z0-9][a-z0-9._-]{0,30}$"))) return false + val current = _state.value + if (normalised in current.hashtags) return true // already there + if (current.hashtags.size >= NoteEditorUiState.MAX_TAGS) { + _state.update { it.copy(snackbar = "Maximum ${NoteEditorUiState.MAX_TAGS} tags reached.") } + return false + } + _state.update { it.copy(hashtags = (it.hashtags + normalised).sorted()) } + return true + } + + fun removeTag(name: String) { + val normalised = Hashtag.normalise(name) + _state.update { it.copy(hashtags = it.hashtags.filterNot { tag -> tag == normalised }) } + } + + fun consumeSnackbar() { + _state.update { it.copy(snackbar = null) } + } + fun save(onDone: () -> Unit) { val current = _state.value if (!current.canSave) return _state.update { it.copy(isSaving = true) } viewModelScope.launch { - val toPersist = current.existing?.copy( + val baseNote = current.existing + val toPersist = baseNote?.copy( content = current.content, isFavorite = current.isFavorite, color = current.color, + hashtags = current.hashtags, ) ?: Note( content = current.content, createdAt = System.currentTimeMillis(), updatedAt = System.currentTimeMillis(), isFavorite = current.isFavorite, color = current.color, + hashtags = current.hashtags, ) - repository.upsert(toPersist) + val saved = repository.upsert(toPersist) + // Reconcile hashtag set vs. what was previously persisted. + val previous = baseNote?.hashtags.orEmpty().toSet() + val currentSet = current.hashtags.toSet() + (previous - currentSet).forEach { repository.removeHashtag(saved.id, it) } + (currentSet - previous).forEach { repository.addHashtag(saved.id, it) } _state.update { it.copy(isSaving = false) } onDone() } diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListScreen.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListScreen.kt index 7e65310..68bbd3e 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListScreen.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListScreen.kt @@ -13,15 +13,18 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.CheckBox import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.outlined.StarOutline import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon @@ -30,8 +33,8 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -39,41 +42,57 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.lerp import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel -import org.incido.compose.ui.editor.toComposeColor +import org.incido.compose.ui.theme.toComposeColor import org.incido.compose.util.rememberRelativeTimestamp import org.incido.domain.model.Note import org.incido.domain.model.NoteColor +import org.incido.domain.model.NoteFilter @OptIn(ExperimentalMaterial3Api::class) @Composable fun NoteListScreen( + filterMode: NoteFilter, + onOpenDrawer: () -> Unit, onOpenEditor: (Long?) -> Unit, viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.Factory), ) { val state by viewModel.uiState.collectAsStateWithLifecycle() var localQuery by remember { mutableStateOf("") } + // Keep the ViewModel in sync with the parent's filter selection. + LaunchedEffect(filterMode) { viewModel.setFilter(filterMode) } + Scaffold( topBar = { - TopAppBar( - title = { Text("Incido") }, + CenterAlignedTopAppBar( + title = { Text(screenTitle(filterMode)) }, + navigationIcon = { + IconButton(onClick = onOpenDrawer) { + Icon(Icons.Filled.Menu, contentDescription = "Open menu") + } + }, actions = { - IconButton(onClick = { - if (state.isSearchActive) viewModel.closeSearch() else viewModel.openSearch() - localQuery = "" - }) { - Icon(Icons.Default.Search, contentDescription = "Search notes") + if (filterMode == NoteFilter.Home) { + IconButton(onClick = { + if (state.isSearchActive) viewModel.closeSearch() else viewModel.openSearch() + localQuery = "" + }) { + Icon(Icons.Filled.Search, contentDescription = "Search notes") + } } }, ) }, floatingActionButton = { - if (!state.isSearchActive) { + // FAB only on Home — adding notes while filtered makes less sense. + if (filterMode == NoteFilter.Home) { FloatingActionButton(onClick = { onOpenEditor(null) }) { Icon(Icons.Default.Add, contentDescription = "New note") } @@ -81,7 +100,7 @@ fun NoteListScreen( }, ) { padding -> Column(modifier = Modifier.padding(padding)) { - if (state.isSearchActive) { + if (filterMode == NoteFilter.Home && state.isSearchActive) { OutlinedTextField( value = localQuery, onValueChange = { @@ -99,8 +118,8 @@ fun NoteListScreen( when { state.isLoading -> Unit - state.isEmpty -> EmptyState() - state.noResults -> NoResultsState() + state.isEmpty -> EmptyState(filterMode = filterMode) + state.noResults -> NoResultsState(filterMode = filterMode) else -> NoteList( notes = state.notes, onClick = { onOpenEditor(it.id) }, @@ -112,8 +131,21 @@ fun NoteListScreen( } } +private fun screenTitle(filter: NoteFilter): String = when (filter) { + NoteFilter.Home -> "Incido" + NoteFilter.Favorites -> "Favorites" + NoteFilter.Untagged -> "Untagged" + is NoteFilter.ByTag -> "#${filter.hashtag}" +} + @Composable -private fun EmptyState() { +private fun EmptyState(filterMode: NoteFilter) { + val message = when (filterMode) { + NoteFilter.Home -> "No notes yet. Tap + to start." + NoteFilter.Favorites -> "No favourites yet. Tap ⭐ on a card to add one." + NoteFilter.Untagged -> "All notes are tagged. 🎉" + is NoteFilter.ByTag -> "No notes tagged #${filterMode.hashtag} yet." + } Box( modifier = Modifier .fillMaxSize() @@ -121,7 +153,7 @@ private fun EmptyState() { contentAlignment = Alignment.Center, ) { Text( - text = "No notes yet. Tap + to start.", + text = message, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -129,7 +161,11 @@ private fun EmptyState() { } @Composable -private fun NoResultsState() { +private fun NoResultsState(filterMode: NoteFilter) { + val message = when (filterMode) { + NoteFilter.Home -> "No matching notes." + else -> "Nothing here." + } Box( modifier = Modifier .fillMaxSize() @@ -137,7 +173,7 @@ private fun NoResultsState() { contentAlignment = Alignment.Center, ) { Text( - text = "No matching notes.", + text = message, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -172,6 +208,13 @@ private fun NoteList( } } +/** + * v0.3.0.0 card redesign — three-layer colour accent so notes of + * different colours are visually distinct at a glance: + * 1. 14 dp vertical gradient stripe down the left edge. + * 2. Tinted card surface (12 % colour blend over the M3 surface). + * 3. 10 dp solid colour chip in the top-right corner. + */ @Composable private fun NoteCard( note: Note, @@ -182,19 +225,38 @@ private fun NoteCard( val (title, body) = Note.titleAndBody(note.content) val bodyPreview = Note.bodyPreview(body) val checklistSummary = Note.checklistSummary(note.content) - val stripeColor = note.color.toComposeColor() + val noteColor = note.color + val hasColor = noteColor != NoteColor.NONE Card( onClick = onClick, modifier = Modifier.fillMaxWidth(), + colors = if (hasColor) { + val tint = noteColor.toComposeColor() + val surface = MaterialTheme.colorScheme.surface + CardDefaults.cardColors( + containerColor = lerp(surface, tint, 0.12f), + ) + } else { + CardDefaults.cardColors() + }, ) { Row(modifier = Modifier.fillMaxWidth()) { - // 4dp coloured accent stripe on the left. - Box( - modifier = Modifier - .size(width = 4.dp, height = 96.dp) - .background(stripeColor), - ) + if (hasColor) { + // Layer 1: 14 dp gradient stripe. + Box( + modifier = Modifier + .size(width = 14.dp, height = 110.dp) + .background( + Brush.verticalGradient( + colors = listOf( + noteColor.toComposeColor().copy(alpha = 0.95f), + noteColor.toComposeColor().copy(alpha = 0.05f), + ), + ) + ), + ) + } Column(modifier = Modifier.padding(16.dp).fillMaxWidth()) { Row( modifier = Modifier.fillMaxWidth(), @@ -207,6 +269,16 @@ private fun NoteCard( overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) + // Layer 3: top-right colour chip (only when coloured). + if (hasColor) { + Box( + modifier = Modifier + .size(10.dp) + .clip(CircleShape) + .background(noteColor.toComposeColor()), + ) + Spacer(modifier = Modifier.size(8.dp)) + } IconButton(onClick = onToggleFavorite) { Icon( imageVector = if (note.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline, @@ -267,4 +339,11 @@ private fun NoteCard( } } +// --- Lightweight imports used to avoid shadowed-name conflicts in +// other files that might also import these symbols --- +@Suppress("unused") +private fun clip(@Suppress("UNUSED_PARAMETER") shape: androidx.compose.ui.graphics.Shape): Modifier = + Modifier.clip(shape) +@Suppress("unused") +private fun background(color: Color): Modifier = Modifier.background(color) diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListViewModel.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListViewModel.kt index 7a29ad5..43b4920 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListViewModel.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/notelist/NoteListViewModel.kt @@ -17,26 +17,24 @@ import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import org.incido.compose.IncidoApplication +import org.incido.domain.model.HashtagUsage import org.incido.domain.model.Note +import org.incido.domain.model.NoteFilter import org.incido.domain.repository.NoteRepository /** - * Immutable UI state for [NoteListScreen]. A loading flag plus the - * current snapshot of notes; an empty list with [isLoading] == false - * indicates the empty-state UI should be shown (F6). - * - * [isSearchActive] / [searchQuery] are now properly folded into the same - * uiState flow (v0.2.1 fix — they used to live on a separate StateFlow - * that the composable never observed, making the search icon a no-op). + * Immutable UI state for [NoteListScreen]. */ data class NoteListUiState( val notes: List = emptyList(), val isLoading: Boolean = true, val searchQuery: String = "", val isSearchActive: Boolean = false, + val filter: NoteFilter = NoteFilter.Home, + val recentHashtags: List = emptyList(), ) { - val isEmpty: Boolean get() = !isLoading && notes.isEmpty() && !isSearchActive - val noResults: Boolean get() = !isLoading && notes.isEmpty() && isSearchActive + val isEmpty: Boolean get() = !isLoading && notes.isEmpty() && !isSearchActive && filter == NoteFilter.Home + val noResults: Boolean get() = !isLoading && notes.isEmpty() && !isEmpty } @OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class) @@ -44,34 +42,36 @@ class NoteListViewModel( private val repository: NoteRepository, ) : ViewModel() { + private val filterMode = MutableStateFlow(NoteFilter.Home) private val rawQuery = MutableStateFlow("") private val _isSearchActive = MutableStateFlow(false) - /** - * Combines the filtered notes flow, the search-active flag, and the - * raw query into a single [NoteListUiState] that the composable can - * `collectAsStateWithLifecycle`. All three pieces of state are - * updated together so `if (state.isSearchActive)` in the screen - * actually reflects the icon's toggled value. - */ + /** Notes stream — switches on (filter, query) so the same ViewModel + * instance handles Home, Favorites, Untagged, ByTag, and search. */ + private val notesFlow = combine(filterMode, rawQuery) { f, q -> f to q } + .flatMapLatest { (f, q) -> + when (f) { + NoteFilter.Home -> if (q.isBlank()) repository.observeAll() else repository.search(q) + NoteFilter.Favorites -> repository.observeFavorites() + NoteFilter.Untagged -> repository.observeUntagged() + is NoteFilter.ByTag -> repository.observeNotesForHashtag(f.hashtag) + } + } + val uiState: StateFlow = combine( - rawQuery - .debounce(150) - .flatMapLatest { q -> - if (q.isBlank()) { - repository.observeAll() - } else { - repository.search(q) - } - }, + notesFlow, _isSearchActive, + filterMode, rawQuery, - ) { notes, searchActive, q -> + repository.observeHashtagsByRecentUse(), + ) { notes, searchActive, filter, query, recent -> NoteListUiState( notes = notes, isLoading = false, - searchQuery = q, + searchQuery = query, isSearchActive = searchActive, + filter = filter, + recentHashtags = recent, ) }.stateIn( scope = viewModelScope, @@ -79,6 +79,16 @@ class NoteListViewModel( initialValue = NoteListUiState(), ) + fun setFilter(filter: NoteFilter) { + filterMode.value = filter + // Switching away from Home closes the search bar (search is + // only meaningful in Home). + if (filter != NoteFilter.Home && _isSearchActive.value) { + _isSearchActive.value = false + rawQuery.value = "" + } + } + fun onQueryChange(q: String) { rawQuery.value = q } diff --git a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteColors.kt b/composeApp/src/main/kotlin/org/incido/compose/ui/theme/NoteColors.kt similarity index 73% rename from composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteColors.kt rename to composeApp/src/main/kotlin/org/incido/compose/ui/theme/NoteColors.kt index 76656d9..64f32cb 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/ui/editor/NoteColors.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/ui/theme/NoteColors.kt @@ -1,4 +1,4 @@ -package org.incido.compose.ui.editor +package org.incido.compose.ui.theme import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable @@ -7,8 +7,8 @@ import androidx.compose.ui.graphics.Color import org.incido.domain.model.NoteColor /** - * Maps a [NoteColor] enum to a Compose [Color] using Material 3 tokens so - * the swatches adapt to light/dark theme automatically. + * Maps a [NoteColor] enum to a Compose [Color]. Values are chosen to + * stay readable against both light and dark surfaces. */ @Composable @ReadOnlyComposable @@ -21,6 +21,7 @@ fun NoteColor.toComposeColor(): Color = when (this) { NoteColor.PURPLE -> Color(0xFF7B5BA6) } +/** All selectable colours, including [NoteColor.NONE]. */ val AllNoteColors: List = listOf( NoteColor.NONE, NoteColor.BLUE, @@ -30,10 +31,7 @@ val AllNoteColors: List = listOf( NoteColor.PURPLE, ) -/** - * A swatch surface colour for a swatch button — used to give the - * selected swatch a visible border by reading the theme's outline. - */ +/** Outline colour used to highlight the selected swatch. */ val swatchBorderColor: Color @Composable @ReadOnlyComposable diff --git a/core/data/src/main/kotlin/org/incido/data/entity/HashtagEntity.kt b/core/data/src/main/kotlin/org/incido/data/entity/HashtagEntity.kt new file mode 100644 index 0000000..acd90c1 --- /dev/null +++ b/core/data/src/main/kotlin/org/incido/data/entity/HashtagEntity.kt @@ -0,0 +1,19 @@ +package org.incido.data.entity + +import io.objectbox.annotation.Entity +import io.objectbox.annotation.Id +import io.objectbox.annotation.Index + +/** + * A single normalised hashtag. Case-insensitive uniqueness is + * enforced at the repository layer (`NoteRepositoryImpl.addHashtag` + * uses `findFirst` and reuses the existing row); the index here just + * speeds up the lookup. + * + * The "many-to-many" link to notes lives in [NoteHashtagCrossRef]. + */ +@Entity +data class HashtagEntity( + @Id var id: Long = 0, + @Index var name: String = "", +) diff --git a/core/data/src/main/kotlin/org/incido/data/entity/NoteHashtagCrossRef.kt b/core/data/src/main/kotlin/org/incido/data/entity/NoteHashtagCrossRef.kt new file mode 100644 index 0000000..0113990 --- /dev/null +++ b/core/data/src/main/kotlin/org/incido/data/entity/NoteHashtagCrossRef.kt @@ -0,0 +1,19 @@ +package org.incido.data.entity + +import io.objectbox.annotation.Entity +import io.objectbox.annotation.Id +import io.objectbox.annotation.Index + +/** + * Many-to-many junction between [NoteEntity] and [HashtagEntity]. + * Each row is one (`noteId`, `hashtagId`) pair. + * + * Both columns are indexed for fast lookups in either direction + * (notes for a hashtag, hashtags for a note). + */ +@Entity +data class NoteHashtagCrossRef( + @Id var id: Long = 0, + @Index var noteId: Long = 0, + @Index var hashtagId: Long = 0, +) diff --git a/core/data/src/main/kotlin/org/incido/data/repository/NoteRepositoryImpl.kt b/core/data/src/main/kotlin/org/incido/data/repository/NoteRepositoryImpl.kt index abe741d..19221fa 100644 --- a/core/data/src/main/kotlin/org/incido/data/repository/NoteRepositoryImpl.kt +++ b/core/data/src/main/kotlin/org/incido/data/repository/NoteRepositoryImpl.kt @@ -2,72 +2,113 @@ package org.incido.data.repository import io.objectbox.BoxStore import io.objectbox.kotlin.boxFor +import io.objectbox.query.QueryBuilder import io.objectbox.reactive.DataSubscription import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.Dispatchers +import org.incido.data.entity.HashtagEntity +import org.incido.data.entity.HashtagEntity_ import org.incido.data.entity.NoteEntity import org.incido.data.entity.NoteEntity_ +import org.incido.data.entity.NoteHashtagCrossRef +import org.incido.data.entity.NoteHashtagCrossRef_ import org.incido.data.entity.toDomain import org.incido.data.entity.toEntity +import org.incido.domain.model.Hashtag +import org.incido.domain.model.HashtagUsage import org.incido.domain.model.Note import org.incido.domain.repository.NoteRepository /** - * ObjectBox-backed implementation of [NoteRepository]. All writes are - * dispatched to `Default`; reads use ObjectBox's reactive subscription so - * the UI auto-refreshes whenever a row changes (F7). + * ObjectBox-backed implementation of [NoteRepository]. Hashtags live + * in two extra tables (`HashtagEntity`, `NoteHashtagCrossRef`); every + * "list of notes" snapshot here loads the cross-ref + tags in one + * pass so callers get fully-populated [Note.hashtags] lists. * - * Sort order is `isFavorite DESC, updatedAt DESC` for both [observeAll] and - * [search] so favourites always float to the top. + * Sort order for [observeAll] / [search] / filter streams: + * `isFavorite DESC, updatedAt DESC`. + * + * Note: ObjectBox 4.0.3's Kotlin stubs are finicky around + * `QueryBuilder.equal(Property, String, ...)` — passing the + * `StringOrder` argument explicitly is the most reliable way to call it. */ class NoteRepositoryImpl( private val boxStore: BoxStore, ) : NoteRepository { - private val box = boxStore.boxFor() + private val noteBox = boxStore.boxFor() + private val tagBox = boxStore.boxFor() + private val xrefBox = boxStore.boxFor() + + // --------------------------------------------------------------------- + // List / observation streams + // --------------------------------------------------------------------- override fun observeAll(): Flow> = callbackFlow { - trySend(sortedSnapshot("")) - - val subscription = box - .query() - .build() - .subscribe() - .observer { trySend(sortedSnapshot("")) } - - awaitClose { subscription.cancel() } + trySend(snapshotAll()) + val sub = noteBox.query().build().subscribe().observer { trySend(snapshotAll()) } + awaitClose { sub.cancel() } }.flowOn(Dispatchers.Default) override fun search(query: String): Flow> = callbackFlow { - trySend(sortedSnapshot(query)) + trySend(snapshotSearch(query)) + val sub = noteBox.query().build().subscribe().observer { trySend(snapshotSearch(query)) } + awaitClose { sub.cancel() } + }.flowOn(Dispatchers.Default) - val subscription = if (query.isBlank()) { - box.query().build().subscribe() - } else { - box.query() - .contains(NoteEntity_.content, query, io.objectbox.query.QueryBuilder.StringOrder.CASE_INSENSITIVE) - .build() - .subscribe() - }.observer { trySend(sortedSnapshot(query)) } + override fun observeFavorites(): Flow> = callbackFlow { + trySend(snapshotFavorites()) + val sub = noteBox.query().build().subscribe().observer { trySend(snapshotFavorites()) } + awaitClose { sub.cancel() } + }.flowOn(Dispatchers.Default) - awaitClose { subscription.cancel() } + override fun observeUntagged(): Flow> = callbackFlow { + trySend(snapshotUntagged()) + val sub = noteBox.query().build().subscribe().observer { trySend(snapshotUntagged()) } + awaitClose { sub.cancel() } + }.flowOn(Dispatchers.Default) + + override fun observeNotesForHashtag(name: String): Flow> = callbackFlow { + trySend(snapshotForHashtag(name)) + val sub = noteBox.query().build().subscribe().observer { trySend(snapshotForHashtag(name)) } + awaitClose { sub.cancel() } + }.flowOn(Dispatchers.Default) + + override fun observeHashtagsByRecentUse(): Flow> = callbackFlow { + trySend(hashtagUsageSnapshot()) + val sub = noteBox.query().build().subscribe().observer { trySend(hashtagUsageSnapshot()) } + awaitClose { sub.cancel() } + }.flowOn(Dispatchers.Default) + + override fun observeAllHashtags(): Flow> = callbackFlow { + trySend(allHashtagsSnapshot().sorted()) + val sub = noteBox.query().build().subscribe().observer { + trySend(allHashtagsSnapshot().sorted()) + } + awaitClose { sub.cancel() } + }.flowOn(Dispatchers.Default) + + override fun searchHashtags(prefix: String): Flow> = callbackFlow { + trySend(searchHashtagsSnapshot(prefix)) + val sub = noteBox.query().build().subscribe().observer { + trySend(searchHashtagsSnapshot(prefix)) + } + awaitClose { sub.cancel() } }.flowOn(Dispatchers.Default) override fun observeById(id: Long): Flow = callbackFlow { - trySend(box.get(id)?.toDomain()) - - val subscription = box - .query() - .build() - .subscribe() - .observer { trySend(box.get(id)?.toDomain()) } - - awaitClose { subscription.cancel() } + trySend(noteByIdSnapshot(id)) + val sub = noteBox.query().build().subscribe().observer { trySend(noteByIdSnapshot(id)) } + awaitClose { sub.cancel() } }.flowOn(Dispatchers.Default) + // --------------------------------------------------------------------- + // Writes + // --------------------------------------------------------------------- + override suspend fun upsert(note: Note): Note { val now = System.currentTimeMillis() val toPersist = if (note.id == 0L) { @@ -75,39 +116,213 @@ class NoteRepositoryImpl( } else { note.copy(updatedAt = now).toEntity() } - val assignedId = box.put(toPersist) - val existing = box.get(assignedId) - return existing?.toDomain() ?: note.copy(id = assignedId) + val assignedId = noteBox.put(toPersist) + return noteBox.get(assignedId)?.toDomain() ?: note.copy(id = assignedId) } override suspend fun delete(id: Long) { - box.remove(id) + noteBox.remove(id) + val orphanXrefs: List = xrefBox.query() + .equal(NoteHashtagCrossRef_.noteId, id) + .build() + .find() + if (orphanXrefs.isNotEmpty()) { + xrefBox.remove(*orphanXrefs.map { it.id }.toLongArray()) + } } override suspend fun setFavorite(id: Long, isFavorite: Boolean) { - val entity = box.get(id) ?: return + val entity = noteBox.get(id) ?: return if (entity.isFavorite == isFavorite) return entity.isFavorite = isFavorite - box.put(entity) + noteBox.put(entity) } - /** - * Snapshot helper. If [query] is non-blank, only notes whose content - * contains it (case-insensitive) are included; otherwise all notes. - * The result is sorted favourites-first, then newest-first. - */ - private fun sortedSnapshot(query: String): List { - val raw = if (query.isBlank()) { - box.all - } else { - box.query() - .contains(NoteEntity_.content, query, io.objectbox.query.QueryBuilder.StringOrder.CASE_INSENSITIVE) - .build() - .find() - } - return raw.sortedWith( + override suspend fun addHashtag(noteId: Long, name: String) { + val normalised = Hashtag.normalise(name) + if (!normalised.matches(Regex("^[a-z0-9][a-z0-9._-]{0,30}$"))) return + + val tag: HashtagEntity = tagBox.query() + .equal(HashtagEntity_.name, normalised, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .findFirst() ?: run { + tagBox.put(HashtagEntity(name = normalised)) + // Re-query to get the freshly-inserted row (with its new id). + tagBox.query() + .equal(HashtagEntity_.name, normalised, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .findFirst() + } ?: return + + val existing: NoteHashtagCrossRef? = xrefBox.query() + .equal(NoteHashtagCrossRef_.noteId, noteId) + .equal(NoteHashtagCrossRef_.hashtagId, tag.id) + .build() + .findFirst() + if (existing != null) return + + xrefBox.put(NoteHashtagCrossRef(noteId = noteId, hashtagId = tag.id)) + } + + override suspend fun removeHashtag(noteId: Long, name: String) { + val normalised = Hashtag.normalise(name) + val tag: HashtagEntity = tagBox.query() + .equal(HashtagEntity_.name, normalised, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .findFirst() ?: return + val xref: NoteHashtagCrossRef = xrefBox.query() + .equal(NoteHashtagCrossRef_.noteId, noteId) + .equal(NoteHashtagCrossRef_.hashtagId, tag.id) + .build() + .findFirst() ?: return + xrefBox.remove(xref.id) + } + + // --------------------------------------------------------------------- + // Snapshots + // --------------------------------------------------------------------- + + /** Map of noteId -> ordered list of hashtag names. */ + private fun hashtagsByNoteId(): Map> { + val xrefs: List = xrefBox.all + if (xrefs.isEmpty()) return emptyMap() + val tagIds: Set = xrefs.map { it.hashtagId }.toSet() + val tagById: Map = tagIds.associateWith { id -> + tagBox.get(id)?.name ?: "" + }.filterValues { it.isNotEmpty() } + + return xrefs.groupBy { it.noteId } + .mapValues { (_, refs) -> + refs.mapNotNull { tagById[it.hashtagId] }.sorted() + } + } + + private fun decorate(entities: List): List { + val tags = hashtagsByNoteId() + return entities.sortedWith( compareByDescending { it.isFavorite } .thenByDescending { it.updatedAt } - ).map { it.toDomain() } + ).map { e -> + val base = e.toDomain() + base.copy(hashtags = tags[e.id].orEmpty()) + } + } + + private fun snapshotAll(): List = decorate(noteBox.all) + + private fun snapshotSearch(query: String): List { + val q = query.trim() + if (q.isEmpty()) return snapshotAll() + + // Match against content (contains, case-insensitive). + val contentMatches: List = noteBox.query() + .contains(NoteEntity_.content, q, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .find() + .map { it.id } + + // Match against hashtag names (case-insensitive exact equality). + val matchingTag: HashtagEntity? = tagBox.query() + .equal(HashtagEntity_.name, q, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .findFirst() + val tagMatches: List = if (matchingTag == null) emptyList() else { + xrefBox.query() + .equal(NoteHashtagCrossRef_.hashtagId, matchingTag.id) + .build() + .find() + .map { it.noteId } + } + + val allIds: Set = (contentMatches + tagMatches).toSet() + if (allIds.isEmpty()) return emptyList() + val entities: List = allIds.mapNotNull { noteBox.get(it) } + return decorate(entities) + } + + private fun snapshotFavorites(): List { + val favEntities: List = noteBox.query() + .equal(NoteEntity_.isFavorite, true) + .build() + .find() + return decorate(favEntities) + } + + private fun snapshotUntagged(): List { + val noteIdsWithTags: Set = xrefBox.all.map { it.noteId }.toSet() + val untaggedEntities: List = noteBox.all.filter { it.id !in noteIdsWithTags } + return decorate(untaggedEntities) + } + + private fun snapshotForHashtag(name: String): List { + val normalised = Hashtag.normalise(name) + val tag: HashtagEntity = tagBox.query() + .equal(HashtagEntity_.name, normalised, QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .findFirst() ?: return emptyList() + val xrefs: List = xrefBox.query() + .equal(NoteHashtagCrossRef_.hashtagId, tag.id) + .build() + .find() + val noteIds: Set = xrefs.map { it.id }.let { _ -> xrefs.map { it.noteId }.toSet() } + if (noteIds.isEmpty()) return emptyList() + val entities: List = noteIds.mapNotNull { noteBox.get(it) } + return decorate(entities) + } + + private fun noteByIdSnapshot(id: Long): Note? { + val entity = noteBox.get(id) ?: return null + val tags = hashtagsByNoteId()[id].orEmpty() + return entity.toDomain().copy(hashtags = tags) + } + + /** Build [HashtagUsage] for every distinct tag, sorted by lastUsedAt DESC. */ + private fun hashtagUsageSnapshot(): List { + val xrefs: List = xrefBox.all + if (xrefs.isEmpty()) return emptyList() + + // For each hashtagId, accumulate (lastUsedAt, count). + data class Agg(var lastUsedAt: Long, var count: Int) + val aggregate = HashMap(xrefs.size) + for (x in xrefs) { + val note: NoteEntity = noteBox.get(x.noteId) ?: continue + val cur = aggregate[x.hashtagId] + if (cur == null) { + aggregate[x.hashtagId] = Agg(note.updatedAt, 1) + } else { + if (note.updatedAt > cur.lastUsedAt) cur.lastUsedAt = note.updatedAt + cur.count += 1 + } + } + return aggregate.mapNotNull { (tagId, agg) -> + val tag: HashtagEntity = tagBox.get(tagId) ?: return@mapNotNull null + HashtagUsage(name = tag.name, noteCount = agg.count, lastUsedAt = agg.lastUsedAt) + }.sortedWith( + compareByDescending { it.lastUsedAt } + .thenByDescending { it.noteCount } + .thenBy { it.name } + ) + } + + private fun allHashtagsSnapshot(): List = + tagBox.all.map { it.name } + + private fun searchHashtagsSnapshot(prefix: String): List { + val p = prefix.trim() + if (p.isEmpty()) return allHashtagsSnapshot().sorted() + + val byPrefix: List = tagBox.query() + .startsWith(HashtagEntity_.name, p.lowercase(), QueryBuilder.StringOrder.CASE_INSENSITIVE) + .build() + .find() + + // Sort by usage count (most-used first), then name. + val usageById: Map = xrefBox.all.groupingBy { it.hashtagId }.eachCount() + return byPrefix + .sortedWith( + compareByDescending { usageById[it.id] ?: 0 } + .thenBy { it.name } + ) + .map { it.name } } } diff --git a/core/domain/src/main/kotlin/org/incido/domain/model/Hashtag.kt b/core/domain/src/main/kotlin/org/incido/domain/model/Hashtag.kt new file mode 100644 index 0000000..f5fbb8c --- /dev/null +++ b/core/domain/src/main/kotlin/org/incido/domain/model/Hashtag.kt @@ -0,0 +1,33 @@ +package org.incido.domain.model + +/** + * A single hashtag, normalised: lowercase, no leading `#`, no + * surrounding whitespace. The [name] is the on-disk identifier so + * two notes tagging "Work" and "work" share a row. + * + * Allowed characters: `a-z`, `0-9`, `.`, `_`, `-`. Must start with an + * alphanumeric. Length 1..31. + */ +@JvmInline +value class Hashtag(val name: String) { + init { + require(name.matches(Regex("^[a-z0-9][a-z0-9._-]{0,30}$"))) { + "Invalid hashtag name: \"$name\". Must match ^[a-z0-9][a-z0-9._-]{0,30}$" + } + } + + /** Render with leading `#` for display. */ + fun displayName(): String = "#$name" + + companion object { + /** Normalise raw user input — trim, lowercase, strip leading `#`s. */ + fun normalise(raw: String): String = + raw.trim().lowercase().trimStart('#').trim() + + /** Try to parse; returns null when the input doesn't match the rules. */ + fun parseOrNull(raw: String): Hashtag? { + val n = normalise(raw) + return if (n.matches(Regex("^[a-z0-9][a-z0-9._-]{0,30}$"))) Hashtag(n) else null + } + } +} diff --git a/core/domain/src/main/kotlin/org/incido/domain/model/HashtagUsage.kt b/core/domain/src/main/kotlin/org/incido/domain/model/HashtagUsage.kt new file mode 100644 index 0000000..d0392c5 --- /dev/null +++ b/core/domain/src/main/kotlin/org/incido/domain/model/HashtagUsage.kt @@ -0,0 +1,11 @@ +package org.incido.domain.model + +/** + * Aggregate info about a single hashtag, for the nav drawer's "Recent + * tags" list. + */ +data class HashtagUsage( + val name: String, + val noteCount: Int, + val lastUsedAt: Long, +) diff --git a/core/domain/src/main/kotlin/org/incido/domain/model/Note.kt b/core/domain/src/main/kotlin/org/incido/domain/model/Note.kt index 9d33a90..9d04534 100644 --- a/core/domain/src/main/kotlin/org/incido/domain/model/Note.kt +++ b/core/domain/src/main/kotlin/org/incido/domain/model/Note.kt @@ -12,6 +12,8 @@ data class Note( val updatedAt: Long, val isFavorite: Boolean = false, val color: NoteColor = NoteColor.NONE, + /** Tags attached to this note (normalised lowercase, sorted ascending). */ + val hashtags: List = emptyList(), ) { companion object { private const val UNTITLED = "Untitled" diff --git a/core/domain/src/main/kotlin/org/incido/domain/model/NoteFilter.kt b/core/domain/src/main/kotlin/org/incido/domain/model/NoteFilter.kt new file mode 100644 index 0000000..bf7b975 --- /dev/null +++ b/core/domain/src/main/kotlin/org/incido/domain/model/NoteFilter.kt @@ -0,0 +1,26 @@ +package org.incido.domain.model + +/** + * What the note list is currently showing. Drives both the + * `NoteListScreen` body and the selected entry in the navigation + * drawer. + * + * - [Home] — every note (the default). The search bar is enabled. + * - [Favorites] — only notes with `isFavorite = true`. No search. + * - [Untagged] — only notes that have zero hashtags. No search. + * - [ByTag] — only notes tagged with [hashtag]. No search. + */ +sealed class NoteFilter { + object Home : NoteFilter() + object Favorites : NoteFilter() + object Untagged : NoteFilter() + data class ByTag(val hashtag: String) : NoteFilter() + + /** Stable identifier used by the drawer for `selected` matching. */ + fun key(): String = when (this) { + Home -> "home" + Favorites -> "favorites" + Untagged -> "untagged" + is ByTag -> "tag:$hashtag" + } +} diff --git a/core/domain/src/main/kotlin/org/incido/domain/repository/NoteRepository.kt b/core/domain/src/main/kotlin/org/incido/domain/repository/NoteRepository.kt index fae0632..54f24d6 100644 --- a/core/domain/src/main/kotlin/org/incido/domain/repository/NoteRepository.kt +++ b/core/domain/src/main/kotlin/org/incido/domain/repository/NoteRepository.kt @@ -1,28 +1,26 @@ package org.incido.domain.repository import kotlinx.coroutines.flow.Flow +import org.incido.domain.model.HashtagUsage import org.incido.domain.model.Note /** * Persistence boundary for [Note]s. The UI layer depends on this interface * only — never on the ObjectBox-backed implementation in `:core:data`. * - * Implementations are expected to: - * - Return a [Flow] that emits whenever the underlying data changes, - * so the list screen satisfies F7 (auto-refresh). - * - Assign a fresh id (0 or 0L on construction) for new notes and use the - * ObjectBox-managed id once persisted. - * - Sort [observeAll] / [search] with favourites first, then by [Note.updatedAt] - * descending. + * Sort order for [observeAll] / [search]: `isFavorite DESC, updatedAt DESC`. + * [search] additionally matches against any of the note's hashtags + * (case-insensitive equality). */ interface NoteRepository { /** Stream of all notes, newest-first, favourites pinned to the top. */ fun observeAll(): Flow> /** - * Stream of notes whose [Note.content] contains [query] (case-insensitive), - * favourites first then newest-first. An empty / blank [query] returns - * the same list as [observeAll]. + * Stream of notes whose [Note.content] contains [query] (case-insensitive) + * OR whose hashtags contain [query] as one of the names. Favourites + * first then newest-first. Blank [query] returns the same as + * [observeAll]. */ fun search(query: String): Flow> @@ -37,4 +35,50 @@ interface NoteRepository { /** Toggle the favourite flag on a single note. */ suspend fun setFavorite(id: Long, isFavorite: Boolean) + + // --- Filter streams (v0.3.0.0) --- + /** Only notes with `isFavorite = true`, sorted by updatedAt DESC. */ + fun observeFavorites(): Flow> + + /** Only notes that have zero hashtags, sorted by updatedAt DESC. */ + fun observeUntagged(): Flow> + + /** Only notes tagged with [name] (normalised form), sorted by updatedAt DESC. */ + fun observeNotesForHashtag(name: String): Flow> + + /** + * Every distinct hashtag, sorted by `lastUsedAt DESC` then + * `noteCount DESC` then `name ASC`. Each entry also carries the + * number of notes that use it. + */ + fun observeHashtagsByRecentUse(): Flow> + + // --- Hashtag autocomplete (v0.3.0.0) --- + /** + * Every distinct hashtag in the store, sorted by usage count DESC + * then name ASC. Used to populate the autocomplete "suggestions" + * list when the input is empty. + */ + fun observeAllHashtags(): Flow> + + /** + * Hashtags whose name starts with [prefix] (case-insensitive), + * sorted by usage count DESC then name ASC. Blank [prefix] is + * equivalent to [observeAllHashtags]. + */ + fun searchHashtags(prefix: String): Flow> + + /** + * Add [name] to the note's hashtag set. Creates the hashtag row + * if it doesn't exist yet. Idempotent. No-op if the note already + * has the tag. + */ + suspend fun addHashtag(noteId: Long, name: String) + + /** + * Remove [name] from the note's hashtag set. Idempotent. No-op if + * the note doesn't have the tag. The hashtag row itself is NOT + * auto-deleted (cleanup is the future "tag browser" feature). + */ + suspend fun removeHashtag(noteId: Long, name: String) }