feat(phase-1/m4.3c): ViewModels off APPLICATION_KEY; DesktopContainer implements AppGraph

Completes the M4.3 container seam:

* NoteListViewModel + NoteEditorViewModel (UiStates and SharedImage
  included) move to commonMain. NoteEditorViewModel had zero android.*
  imports; its four withContext(Dispatchers.IO) sites become
  withContext(ioDispatcher) — a new internal expect/actual whose ACTUALS
  are literally Dispatchers.IO on both targets, so Android behaviour is
  byte-identical (invariant §2.1), merely spelled through the seam.
* New commonMain EncryptionBadge/LibraryVerification: the read-only
  mirror of :core:data's EncryptionVerification. Required because
  :core:data is an androidLibrary invisible to commonMain and must stay
  so (invariant §2.3 — objectbox-android vs objectbox-java classpaths).
  AppGraph gains encryptionBadge; both containers map the real verifier
  result 1:1 at their own seam.
* SettingsViewModel stays in androidMain (SecurityManager, Keystore key
  provider, BackupManager Uri IO, CarnetImporter are genuine Android-only
  services — the graph was NOT widened to fake them, §9) but its factory
  now takes the concrete AppContainer via a new LocalAndroidContainer,
  provided alongside LocalAppGraph in IncidoApp. No APPLICATION_KEY /
  IncidoApplication reference survives in ANY ViewModel: all six call
  sites (drawer, list, editor, settings, pin setup, pin change) build
  factories from the graph/container locals at composition time.
* M4.3 exit proof: DesktopContainer : AppGraph — the same face
  (noteRepository/settingsRepository/encryptionBadge) the commonMain
  ViewModels consume, compiler-checked by :desktopApp building against
  :composeApp's jvm target. repository → noteRepository rename.
  The stand-in two-pane UI still runs (M4.5 consumes the real screens).

Verification (all green, one suite):
  ./gradlew assembleDebug :composeApp:compileKotlinJvm :desktopApp:build
      → BUILD SUCCESSFUL
  ./gradlew :desktopApp:run … --self-test --exit-after 6 → SELFTEST id=1, clean exit
  ./gradlew :core:data-jvm:smoke → RESULT: M1a PASS
  crypto legs (separate processes): leg-A ALL-OK → LEG-B PASS/ALL-OK
  git diff '*/objectbox-models/*' → empty
This commit is contained in:
Incido Developer committed 2026-10-06 16:42:48 +13:00
1 parent cd363c7aa5
commit 59bd6e106b
21 files changed
+176 -37

No files matched your search

@@ -31,6 +31,7 @@ import androidx.navigation.navArgument
import kotlinx.coroutines.launch
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.di.LocalAndroidContainer
import org.incido.compose.di.LocalAppGraph
import org.incido.compose.share.SharedIntentBuffer
import org.incido.compose.ui.drawer.IncidoDrawer
@@ -112,7 +113,10 @@ fun IncidoApp(
// M4.3: the platform graph reaches the screens through the composition —
// the same face DesktopContainer implements (commonMain di/AppGraph.kt).
CompositionLocalProvider(LocalAppGraph provides app.container) {
CompositionLocalProvider(
LocalAppGraph provides app.container,
LocalAndroidContainer provides app.container,
) {
IncidoTheme(
darkTheme = settings.themeMode.resolveDark(isSystemInDarkTheme()),
dynamicColor = settings.dynamicColor,
@@ -8,8 +8,10 @@ import org.incido.compose.di.AppContainer
* Application class. Constructs the singleton [AppContainer] holding the
* ObjectBox store and the note repository.
*
* ViewModels reach the container via `(application as IncidoApplication).container`
* (see `NoteListViewModel.Factory` and `NoteEditorViewModel.factory`).
* M4.3: the screens reach the container through `LocalAppGraph` (provided
* by `IncidoApp`); the graph-based ViewModel factories (`factory(graph)`)
* no longer touch the Application through CreationExtras. The Application
* still owns construction order.
*
* v0.3.2.0 — initialises the [SecurityManager] lock state during
* `onCreate` so the first composition of the root Compose tree
@@ -0,0 +1,21 @@
package org.incido.compose.di
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
/**
* M4.3c — Android-only bridge beside [LocalAppGraph].
*
* `SettingsViewModel` still needs the concrete [AppContainer] (Security
* Manager, Keystore key provider, BackupManager, CarnetImporter — the
* Android services M4.3 deliberately did NOT widen the graph with). The
* screen reads this local until M4.4/4.5 ports or hides that surface;
* `IncidoApp` provides the SAME container instance through both locals.
*/
val LocalAndroidContainer = compositionLocalOf<AppContainer?> { null }
/** Read [LocalAndroidContainer] or throw with context — call at composition. */
@Composable
fun requireAndroidContainer(): AppContainer = checkNotNull(LocalAndroidContainer.current) {
"No AppContainer provided — IncidoApp provides it at the root."
}
@@ -20,6 +20,9 @@ import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.data.settings.settingsDataStore
import org.incido.compose.di.AppGraph
import org.incido.compose.di.EncryptionBadge
import org.incido.compose.di.LibraryVerification
import kotlinx.coroutines.flow.map
/**
* Hand-rolled DI container. Replaces Hilt/Dagger for v0.1 — keeps the
@@ -110,6 +113,18 @@ class AppContainer(context: Context) : AppGraph {
/** Runs on every app open — feeds the verified-encryption badge. */
val encryptionVerifier = EncryptionVerifier(noteCryptoService, appScope)
/**
* M4.3c: [AppGraph]'s shared face over the concrete verifier — the
* 3-field copy is why `LibraryVerification` mirrors the data class
* (see EncryptionBadge.kt: :core:data is an androidLibrary, invisible
* to commonMain, and must stay that way per invariant §2.3).
*/
override val encryptionBadge: EncryptionBadge = object : EncryptionBadge {
override val verification = encryptionVerifier.verification.map { result ->
result?.let { LibraryVerification(it.verifiedNoteIds, it.failedNoteIds, it.checkedAt) }
}
}
/** Kick the startup verification off immediately. */
init {
encryptionVerifier.checkNow()
@@ -0,0 +1,6 @@
package org.incido.compose.di
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
internal actual val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
@@ -117,6 +117,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.di.requireAppGraph
import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.swatchBorderColor
import org.incido.compose.ui.theme.toComposeColor
@@ -150,6 +151,7 @@ fun NoteEditorScreen(
securityManager: SecurityManager? = null,
viewModel: NoteEditorViewModel = viewModel(
factory = NoteEditorViewModel.factory(
graph = requireAppGraph(),
noteId = noteId,
initialSharedText = initialSharedText,
initialSharedImages = initialSharedImages,
@@ -1,892 +0,0 @@
package org.incido.compose.ui.editor
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.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.IncidoApplication
import org.incido.compose.share.LinkedShareComposer
import org.incido.domain.model.ChecklistItem
import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository
/**
* 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<String> = emptyList(),
/** v0.3.8.0 — which editor surface the body uses (see [NoteType]). */
val type: NoteType = NoteType.TEXT,
/** v0.3.8.0 — title / preamble kept above the rows in list modes. */
val listHeader: String = "",
/** v0.3.8.0 — parsed checklist rows; always empty for [NoteType.TEXT]. */
val items: List<ChecklistItem> = 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<String> = emptyList(),
val isLoading: Boolean = true,
val isSaving: Boolean = false,
val isDeleted: Boolean = false,
val snackbar: String? = null,
/**
* v0.3.1.0 — attachments already persisted in the DB for this note.
* For new notes (no [existing] id yet), the editor shows these
* empty until save; in-flight attachments live in [pendingAttachments].
*/
val attachments: List<NoteAttachment> = emptyList(),
/**
* v0.3.1.0 — attachments staged for a not-yet-saved new note.
* Bytes are kept in [pendingAttachmentBytes] keyed by [PendingAttachment.tempId]
* so the UI can render thumbnails without the StateFlow holding large
* blobs. On save, each pending attachment is persisted via
* [NoteRepository.addAttachment] using the new note id.
*/
val pendingAttachments: List<PendingAttachment> = emptyList(),
/**
* v0.3.1.0 — bytes for each pending attachment. Stored outside
* [NoteEditorUiState] so the StateFlow doesn't keep large blobs
* alive; queried by the editor's thumbnail composables on demand.
*/
val pendingAttachmentBytes: Map<Long, ByteArray> = emptyMap(),
/**
* v0.3.1.0 — non-null while a single-attachment viewer is on screen.
* Tap a thumbnail in the editor to open; the editor passes the
* [PendingAttachment.tempId] for pending items or the persisted
* [NoteAttachment.id] for stored items.
*/
val fullScreenAttachmentId: ViewerAttachmentId? = null,
) {
/** `true` when editing an existing note (existing != null). */
val isEditing: Boolean get() = existing != null
/**
* v0.4.2.0 — `true` once a voice take exists (staged pending or
* already persisted as an attachment).
*/
val hasVoiceTake: Boolean get() =
pendingAttachments.any { it.mimeType.startsWith("audio/") } ||
attachments.any { it.mimeType.startsWith("audio/") }
/**
* `true` while content is non-blank and not in the middle of
* saving. v0.4.2.0: a VOICE_NOTE may also save on the strength of
* its recording alone — the take IS the note's content.
*/
val canSave: Boolean get() =
(content.isNotBlank() || (type == NoteType.VOICE_NOTE && hasVoiceTake)) &&
!isSaving
/** `true` while this note is an auto-saved draft (see Note.isDraft). */
val isDraft: Boolean get() = existing?.isDraft == true
/** `true` when there's still room to add another tag. */
val canAddMoreTags: Boolean get() = hashtags.size < MAX_TAGS
/** Dirty-check used by the editor's back button. */
fun isDirty(
initialContent: String,
initialFavorite: Boolean,
initialColor: NoteColor,
initialTags: List<String>,
initialType: NoteType,
): Boolean = content != initialContent ||
isFavorite != initialFavorite ||
color != initialColor ||
hashtags != initialTags ||
type != initialType
companion object {
/** Hard cap on tags per note (matches Development Plan §6.1). */
const val MAX_TAGS = 5
}
}
/**
* v0.3.1.0 — sealed id for the full-screen viewer. Lets the editor
* open either a persisted attachment or a pending (not-yet-saved)
* one through the same UI.
*/
sealed interface ViewerAttachmentId {
/** Open the persisted attachment with this DB id. */
data class Persisted(val id: Long) : ViewerAttachmentId
/** Open the pending attachment with this local temp id. */
data class Pending(val tempId: Long) : ViewerAttachmentId
}
/**
* v0.3.1.0 — metadata for an attachment that's been imported but
* not yet persisted (because we don't have a note id yet — the note
* is still being composed). Bytes for this row live in
* [NoteEditorUiState.pendingAttachmentBytes] keyed by [tempId].
*/
data class PendingAttachment(
val tempId: Long,
val mimeType: String,
val displayName: String,
val createdAt: Long,
val sizeBytes: Long,
) {
val isImage: Boolean get() = mimeType.startsWith("image/")
}
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class NoteEditorViewModel(
private val repository: NoteRepository,
private val noteId: Long?,
/** v0.3.1.0 — pre-filled content from a share-into intent (nullable). */
initialSharedText: String? = null,
/** v0.3.1.0 — pre-loaded image bytes from a share-into intent. */
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the share-into. Most
* browsers fill this with the page title for share-URL intents.
* Threaded through [LinkedShareComposer] so the note seeds with
* the title on its first line and the URL below. Null for plain
* text / image shares that have no subject.
*/
initialSharedSubject: String? = null,
) : ViewModel() {
/**
* v0.3.6.0 — the actual seed text used when there is no existing
* note. Composed from (subject, text) by the offline-only
* [LinkedShareComposer] so the resulting layout matches the rest
* of the app (title = first line, body = everything after).
*/
private val initialSeedContent: String =
LinkedShareComposer.compose(initialSharedSubject, initialSharedText)
private val _state = MutableStateFlow(NoteEditorUiState())
val state: StateFlow<NoteEditorUiState> = _state.asStateFlow()
/**
* Live stream of persisted attachments for an existing note.
* Empty until the note is saved (no note id → nothing to query).
*/
private val attachmentsFlow: StateFlow<List<NoteAttachment>> = if (noteId == null || noteId == 0L) {
MutableStateFlow(emptyList())
} else {
repository.observeAttachments(noteId)
.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
}
/** 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<String> = emptyList()
private set
var initialType: NoteType = NoteType.TEXT
private set
/** Internal: re-emits suggestions whenever the tag input changes. */
private val tagInputFlow = MutableStateFlow("")
private val tagSuggestionsFlow = MutableStateFlow<List<String>>(emptyList())
/**
* v0.3.1.0 — local temp-id counter for pending attachments.
* Starts at `-now` so generated ids never collide with real
* ObjectBox ids (which are positive).
*/
private var nextPendingTempId: Long = -System.currentTimeMillis()
/**
* Draft autosave. A NEW note (or one still flagged as a draft) is
* persisted automatically: every edit lands in the DB ~400 ms after
* the last keystroke (coalesced so typing doesn't write per char),
* and [flushDraft] forces an immediate write whenever the editor
* closes or disposes. A crash can therefore only ever lose the last
* few keystrokes — never a whole draft.
*/
private val draftAutosave = noteId == null || noteId == 0L
/** True while this session autosaves: brand-new notes and draft editing. */
val isDraftFlow: Boolean
get() = draftAutosave || _state.value.isDraft
private var draftPersistInProgress = false
init {
// Signature-driven debounced autosave: whenever anything a draft
// persists changes, write the draft row shortly after.
viewModelScope.launch {
_state
.map { s ->
listOf(s.content, s.isFavorite, s.color, s.type, s.hashtags)
}
.distinctUntilChanged()
.debounce(DRAFT_AUTOSAVE_DEBOUNCE_MS)
.collect { persistDraftNow() }
}
}
init {
// Tag autocomplete — re-query on every keystroke (debounced upstream
// would be nice but ObjectBox is plenty fast for this size).
// Tag autocomplete. v0.3.8.0 FIX: the previous nested
// `tagInputFlow.collect { pool.collect { … } }` never resumed
// past the first keystroke — observeAllHashtags()/searchHashtags()
// are infinite callbackFlows, so the outer lambda suspended in
// the inner collect forever and typing never re-queried (the
// sheet only ever showed "+ Create"). flatMapLatest cancels the
// previous subscription per keystroke, and each fresh flow
// try-sends its snapshot immediately ⇒ live filtering.
viewModelScope.launch {
tagInputFlow
.flatMapLatest { raw ->
val prefix = Hashtag.normalise(raw)
if (prefix.isEmpty()) {
repository.observeAllHashtags()
} else {
repository.searchHashtags(prefix)
}
}
.collect { suggestions ->
_state.update { it.copy(tagSuggestions = suggestions) }
}
}
// Live attachments: pump persisted rows into state.attachments.
viewModelScope.launch {
attachmentsFlow.collect { rows ->
_state.update { it.copy(attachments = rows) }
}
}
// Load the note if editing; otherwise seed with shared content.
if (noteId == null || noteId == 0L) {
val (pendingList, pendingBytes) = if (initialSharedImages.isNotEmpty()) {
val list = mutableListOf<PendingAttachment>()
val map = mutableMapOf<Long, ByteArray>()
initialSharedImages.forEach { img ->
// Use the same tempId generator as importAttachmentBytes so
// the pending list and the bytes map line up.
val tempId = nextPendingTempId--
list += PendingAttachment(
tempId = tempId,
mimeType = img.mimeType,
displayName = img.displayName,
createdAt = System.currentTimeMillis(),
sizeBytes = img.bytes.size.toLong(),
)
map[tempId] = img.bytes
}
list to map
} else {
emptyList<PendingAttachment>() to emptyMap<Long, ByteArray>()
}
val seed = NoteEditorUiState(
existing = null,
// v0.3.6.0: run the seed text through the LinkedShareComposer
// so a share-into URL seeds with the page title on the
// first line and the URL below (titleAndBody-friendly).
content = initialSeedContent,
isFavorite = false,
color = NoteColor.NONE,
hashtags = emptyList(),
isLoading = false,
isSaving = false,
pendingAttachments = pendingList,
pendingAttachmentBytes = pendingBytes,
)
_state.value = seed
initialContent = seed.content
initialFavorite = false
initialColor = NoteColor.NONE
initialHashtags = emptyList()
} else {
viewModelScope.launch {
repository.observeById(noteId).collect { note ->
val firstLoad = _state.value.isLoading
if (note != null && firstLoad) {
initialContent = note.content
initialFavorite = note.isFavorite
initialColor = note.color
initialHashtags = note.hashtags
initialType = note.type
}
// Draft echoes: emissions caused by our own autosave
// must not clobber in-progress edits mid-typing —
// the local state is authoritative while drafting.
if (note != null && note.isDraft && !firstLoad) return@collect
// Parse list rows once on first load; later DB
// emissions must not clobber in-progress edits.
val listSeed: Pair<String, List<ChecklistItem>>? =
if (note != null && firstLoad && note.type != NoteType.TEXT) {
Note.splitListContent(
note.content,
interpretCosts = note.type == NoteType.SHOPPING_LIST,
)
} else {
null
}
_state.update {
it.copy(
existing = note,
content = note?.content ?: it.content,
isFavorite = note?.isFavorite ?: it.isFavorite,
color = note?.color ?: it.color,
hashtags = note?.hashtags ?: it.hashtags,
type = note?.type ?: it.type,
listHeader = listSeed?.first ?: it.listHeader,
items = listSeed?.second ?: it.items,
isLoading = false,
)
}
}
}
}
}
fun onContentChange(newContent: String) {
_state.update { it.copy(content = newContent) }
}
fun toggleFavorite() {
_state.update { it.copy(isFavorite = !it.isFavorite) }
}
fun setColor(color: NoteColor) {
_state.update { it.copy(color = color) }
}
fun openAddTagSheet() {
// v0.3.8.0 FIX: push the empty query through the suggestion
// pipeline FIRST so the flatMapLatest collector re-emits every
// existing tag (most-used first) while the sheet opens — the
// old code just cleared the list to emptyList() here and the
// stuck collector never refilled it.
tagInputFlow.value = ""
_state.update { it.copy(isAddingTag = true, tagInput = "") }
}
fun closeAddTagSheet() {
tagInputFlow.value = ""
_state.update { it.copy(isAddingTag = false, tagInput = "") }
}
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 }) }
}
// ---- v0.3.8.0 task / shopping list editing ----
/**
* Keep the [NoteEditorUiState.items] / [NoteEditorUiState.listHeader]
* rows and the derived [NoteEditorUiState.content] in step, so the
* save path, dirty-check, search preview, and `canSave` gate all
* keep working off the single content string.
*/
private fun NoteEditorUiState.withListEdits(
header: String = this.listHeader,
items: List<ChecklistItem>,
): NoteEditorUiState = copy(
listHeader = header,
items = items,
content = Note.serializeListContent(header, items, type),
)
private fun List<ChecklistItem>.patched(
index: Int,
transform: (ChecklistItem) -> ChecklistItem,
): List<ChecklistItem> = mapIndexed { i, item ->
if (i == index) transform(item) else item
}
/**
* Convert the body to [target]; tapping the already-active mode
* converts back to [NoteType.TEXT]. Text moves losslessly between
* the plain editor and the checkbox serialisation — costs are only
* stored while the note is a shopping list (converting to a task
* list folds each cost back into the item text).
*/
fun convertTo(target: NoteType) {
_state.update { s ->
val next = if (s.type == target) NoteType.TEXT else target
if (next == NoteType.VOICE_NOTE) {
// v0.4.2.0 — voice mode keeps the plain text field
// (title = first line) exactly like TEXT; a list body
// folds back to its plain form first. The recording is
// NOT body content — it's an ordinary audio attachment,
// so it also survives converting back to plain text.
val source =
if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) s.content
else Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
s.copy(
type = next,
listHeader = "",
items = emptyList(),
content = source,
)
} else if (next == NoteType.TEXT) {
// Content already holds the serialised `- [ ]` rows;
// just drop out of the structured editor (the inline
// GFM checklist rendering from v0.2.0.0 still applies).
s.copy(type = NoteType.TEXT, listHeader = "", items = emptyList())
} else {
val source = if (s.type == NoteType.TEXT || s.type == NoteType.VOICE_NOTE) {
s.content
} else {
// Serialise through the FOLDED legacy form (plain
// "Milk 2 x 3.90" lines, never `{q…p…}` markers) so
// structured values survive the trip and re-parse
// cleanly under the target mode's rules.
Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
}
val (header, parsedRaw) = Note.splitListContent(
source,
interpretCosts = next == NoteType.SHOPPING_LIST,
)
val parsed = if (parsedRaw.isEmpty()) listOf(ChecklistItem("")) else parsedRaw
s.copy(
type = next,
listHeader = header,
items = parsed,
content = Note.serializeListContent(header, parsed, next),
)
}
}
_state.update {
it.copy(
snackbar = when (it.type) {
NoteType.TASK_LIST -> "Task list mode — first line stays the title."
NoteType.SHOPPING_LIST -> "Shopping list mode — check an item once it's in your basket."
NoteType.VOICE_NOTE -> "Voice note mode — record with the mic card above the text."
else -> "Back to plain text."
},
)
}
}
fun onHeaderChange(value: String) {
_state.update { it.withListEdits(header = value, items = it.items) }
}
fun addListItem() {
_state.update { s ->
if (s.type == NoteType.TEXT) return@update s
s.withListEdits(items = s.items + ChecklistItem(""))
}
}
/**
* Insert a blank row right after [index] (or append it on the last
* row). Driven by Enter/Return in the task/product field so the
* writer flows downward into a fresh row instead of tabbing sideways.
*/
fun addListItemAfter(index: Int) {
_state.update { s ->
if (s.type == NoteType.TEXT) return@update s
if (index !in s.items.indices) return@update s
val updated = s.items.toMutableList().also { it.add(index + 1, ChecklistItem("")) }
s.withListEdits(items = updated)
}
}
fun removeListItem(index: Int) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.filterIndexed { i, _ -> i != index })
}
}
fun setItemChecked(index: Int, checked: Boolean) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(checked = checked) })
}
}
fun setItemText(index: Int, text: String) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(text = text) })
}
}
/**
* Price field input — POS style: everything is reduced to cents
* digits ("199" ⇒ $1.99, separators typed or pasted are stripped).
*/
fun setItemCost(index: Int, rawCost: String) {
val sanitized = Note.normalisePriceInput(rawCost)
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(cost = sanitized) })
}
}
/**
* Quantity line input (free-text digits); blank means the default 1.
*
* v0.3.8.0: "1" now stays stored as "1" — the field is free text, so
* the typed digit must remain visible. The serialiser already omits
* `{q1}` and cards only show "×qty" when the quantity is > 1, so this
* is storage-neutral. "0" / blank normalise to "" (meaning 1).
*/
fun setItemQuantity(index: Int, rawQty: String) {
val stored = Note.normaliseQuantity(rawQty)
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(quantity = stored) })
}
}
fun consumeSnackbar() {
_state.update { it.copy(snackbar = null) }
}
// ---- v0.3.1.0 attachment + share-into actions ----
/**
* Import bytes from an arbitrary content Uri (file picker or
* share-into). Reads bytes on the IO dispatcher, then either:
* - persists immediately if the note already has an id, or
* - adds a [PendingAttachment] entry if this is a not-yet-saved note.
*/
fun importAttachmentBytes(
bytes: ByteArray,
mimeType: String,
displayName: String,
) {
viewModelScope.launch {
val existingId = _state.value.existing?.id
if (existingId != null && existingId > 0L) {
// Persist straight to the DB; observeAttachments will surface it.
withContext(Dispatchers.IO) {
repository.addAttachment(
noteId = existingId,
bytes = bytes,
mimeType = mimeType,
displayName = displayName,
)
}
} else {
// Stage as pending — bytes live in pendingAttachmentBytes
// until the user saves the note.
val tempId = nextPendingTempId--
val pending = PendingAttachment(
tempId = tempId,
mimeType = mimeType,
displayName = displayName,
createdAt = System.currentTimeMillis(),
sizeBytes = bytes.size.toLong(),
)
_state.update { ui ->
ui.copy(
pendingAttachments = ui.pendingAttachments + pending,
pendingAttachmentBytes = ui.pendingAttachmentBytes + (tempId to bytes),
)
}
}
}
}
fun removePendingAttachment(tempId: Long) {
_state.update { ui ->
val newBytes = ui.pendingAttachmentBytes.toMutableMap().apply { remove(tempId) }
ui.copy(
pendingAttachments = ui.pendingAttachments.filterNot { it.tempId == tempId },
pendingAttachmentBytes = newBytes,
)
}
}
/** Delete a persisted attachment by id (used by the ✕ on the thumbnail strip). */
fun deletePersistedAttachment(id: Long) {
viewModelScope.launch {
withContext(Dispatchers.IO) { repository.removeAttachment(id) }
}
}
/**
* v0.4.2.0 — stage/persist the finished take of a voice note.
* One take per note: any previous take (pending or already
* persisted) is discarded first. The bytes then ride the ordinary
* attachment pipeline — staged as a [PendingAttachment] while the
* note is unsaved, written straight to the DB afterwards — so
* encryption, backup/restore, and the trash cascade all apply
* without any voice-specific storage.
*
* [mimeType] is the container the recorder actually produced —
* `audio/ogg` (Opus, 32 kbps mono) on API 29+, `audio/mp4` (AAC)
* on API 26–28; the display-name extension follows suit.
*/
fun setVoiceRecording(bytes: ByteArray, mimeType: String = "audio/ogg") {
if (bytes.size < 2048) {
_state.update { it.copy(snackbar = "Recording too short \u2014 try again.") }
return
}
viewModelScope.launch {
_state.value.pendingAttachments
.filter { it.mimeType.startsWith("audio/") }
.forEach { removePendingAttachment(it.tempId) }
val stalePersisted = _state.value.attachments
.filter { it.mimeType.startsWith("audio/") }
if (stalePersisted.isNotEmpty()) {
withContext(Dispatchers.IO) {
stalePersisted.forEach { repository.removeAttachment(it.id) }
}
}
val stamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US)
.format(java.util.Date())
val ext = if (mimeType == "audio/mp4") "m4a" else "opus"
importAttachmentBytes(
bytes = bytes,
mimeType = mimeType,
displayName = "Voice_$stamp.$ext",
)
}
}
/** Open the full-screen image viewer for [viewerId]. */
fun openFullScreen(viewerId: ViewerAttachmentId) {
_state.update { it.copy(fullScreenAttachmentId = viewerId) }
}
/** Close the full-screen image viewer. */
fun closeFullScreen() {
_state.update { it.copy(fullScreenAttachmentId = null) }
}
// ---- save ----
/**
* Force-write the current draft state to the DB right now — used
* when the editor closes / disposes so pending edits never sit in
* the debounce window. No-op for non-draft sessions and blank
* content (see [persistDraftNow]).
*/
fun flushDraft() {
viewModelScope.launch { persistDraftNow() }
}
/** Write the draft row if this session is in the draft lifecycle. */
private suspend fun persistDraftNow() {
val current = _state.value
if (current.isLoading || current.isSaving) return
if (draftPersistInProgress) return
val baseNote = current.existing
if (baseNote != null && !baseNote.isDraft) return // already published
if (!draftAutosave && baseNote?.isDraft != true) return
if (current.content.isBlank()) return
draftPersistInProgress = true
try {
val now = System.currentTimeMillis()
val draft = baseNote?.copy(
content = current.content,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
isDraft = true,
) ?: Note(
content = current.content,
createdAt = now,
updatedAt = now,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
isDraft = true,
)
val previous = baseNote?.hashtags.orEmpty().toSet()
val currentSet = current.hashtags.toSet()
val saved = repository.saveNoteWithHashtags(
note = draft,
hashtagsToAdd = currentSet - previous,
hashtagsToRemove = previous - currentSet,
)
// Adopt the persisted row so every later write updates the
// SAME note — one draft per editing session.
_state.update {
it.copy(existing = saved.copy(isDraft = true, hashtags = current.hashtags))
}
} finally {
draftPersistInProgress = false
}
}
fun save(onDone: () -> Unit) {
val current = _state.value
if (!current.canSave) return
_state.update { it.copy(isSaving = true) }
viewModelScope.launch {
val baseNote = current.existing
// An explicit Save PUBLISHES the note: a draft row loses
// its flag here and joins the normal views for good.
val toPersist = baseNote?.copy(
content = current.content,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
isDraft = false,
) ?: Note(
content = current.content,
createdAt = System.currentTimeMillis(),
updatedAt = System.currentTimeMillis(),
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
)
val previous = baseNote?.hashtags.orEmpty().toSet()
val currentSet = current.hashtags.toSet()
val saved = repository.saveNoteWithHashtags(
note = toPersist,
hashtagsToAdd = currentSet - previous,
hashtagsToRemove = previous - currentSet,
)
// Persist any pending attachments against the now-known id.
current.pendingAttachments.forEach { pending ->
val bytes = current.pendingAttachmentBytes[pending.tempId]
if (bytes != null) {
withContext(Dispatchers.IO) {
repository.addAttachment(
noteId = saved.id,
bytes = bytes,
mimeType = pending.mimeType,
displayName = pending.displayName,
)
}
}
}
_state.update {
it.copy(
// v0.4.x FIX: adopt the PUBLISHED row into the UI
// state. Without this the state still reported
// isDraft = true, and the flushDraft() fired by the
// editor's disposal immediately re-persisted the
// note as a draft — every confirmed note landed in
// Drafts. With the published row adopted, the
// already-published guard in persistDraftNow() turns
// that flush into a no-op.
existing = saved.copy(
isDraft = false,
hashtags = current.hashtags,
),
isSaving = false,
pendingAttachments = emptyList(),
pendingAttachmentBytes = emptyMap(),
)
}
onDone()
}
}
fun delete(onDone: () -> Unit) {
val id = _state.value.existing?.id ?: return
_state.update { it.copy(isSaving = true) }
viewModelScope.launch {
repository.softDelete(id)
_state.update { it.copy(isSaving = false, isDeleted = true) }
onDone()
}
}
companion object {
/** Typing-pause before a draft autosave fires (ms). */
const val DRAFT_AUTOSAVE_DEBOUNCE_MS = 400L
fun factory(
noteId: Long?,
initialSharedText: String? = null,
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the share-into.
* Threaded through [LinkedShareComposer] so a shared URL
* seeds the note with the page title on the first line.
*/
initialSharedSubject: String? = null,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
NoteEditorViewModel(
repository = app.container.noteRepository,
noteId = noteId,
initialSharedText = initialSharedText,
initialSharedImages = initialSharedImages,
initialSharedSubject = initialSharedSubject,
)
}
}
}
}
/**
* v0.3.1.0 — bytes + metadata for an image passed in via share-into.
* Constructed by [org.incido.compose.share.SharedIntentBuffer.consume]
* after the [MainActivity] reads the incoming Intent.
*/
data class SharedImage(
val bytes: ByteArray,
val mimeType: String,
val displayName: String,
) {
/** Build a [PendingAttachment] for these bytes. */
fun toPending(): PendingAttachment = PendingAttachment(
tempId = -System.currentTimeMillis(), // overwritten by ViewModel on import
mimeType = mimeType,
displayName = displayName,
createdAt = System.currentTimeMillis(),
sizeBytes = bytes.size.toLong(),
)
}
@@ -75,6 +75,7 @@ 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.di.requireAppGraph
import org.incido.compose.ui.theme.toComposeColor
import org.incido.compose.util.rememberRelativeTimestamp
import org.incido.domain.model.Note
@@ -127,7 +128,7 @@ fun NoteListScreen(
onOpenEditor: (Long?) -> Unit,
/** v0.3.1.0 — used to fetch image bytes for card thumbnails. */
repository: NoteRepository? = null,
viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.Factory),
viewModel: NoteListViewModel = viewModel(factory = NoteListViewModel.factory(requireAppGraph())),
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
var localQuery by remember { mutableStateOf("") }
@@ -1,188 +0,0 @@
package org.incido.compose.ui.notelist
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.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
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].
*/
data class NoteListUiState(
val notes: List<Note> = emptyList(),
val isLoading: Boolean = true,
val searchQuery: String = "",
val isSearchActive: Boolean = false,
val filter: NoteFilter = NoteFilter.Home,
val recentHashtags: List<HashtagUsage> = emptyList(),
/**
* v0.3.5.0 — note ids whose ciphertext was **verified** (trial
* GCM-decrypt succeeded) by the startup / post-migration check.
* This — and ONLY this — drives the "Encrypted" badge on cards.
* Re-populated on every app open.
*/
val verifiedEncryptedNoteIds: Set<Long> = emptySet(),
/** Encrypted rows that FAILED verification (corrupted / wrong key). */
val unverifiedEncryptedNoteCount: Int = 0,
) {
val isEmpty: Boolean
get() = !isLoading && notes.isEmpty() && !isSearchActive &&
(filter == NoteFilter.Home || filter == NoteFilter.Trash ||
filter == NoteFilter.Drafts)
val noResults: Boolean get() = !isLoading && notes.isEmpty() && !isEmpty
}
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class NoteListViewModel(
private val repository: NoteRepository,
/** v0.3.5.0 — source of the verified-encryption badge set. */
private val encryptionVerifier: org.incido.data.crypto.EncryptionVerifier? = null,
) : ViewModel() {
private val filterMode = MutableStateFlow<NoteFilter>(NoteFilter.Home)
private val rawQuery = MutableStateFlow("")
private val _isSearchActive = MutableStateFlow(false)
/** Notes stream — switches on (filter, query) so the same ViewModel
* instance handles Home, Favorites, Untagged, ByTag, and search.
*
* v0.3.1.0: search is now **context-aware** — on Favorites,
* Untagged, and Trash, the typed query is intersected with the
* active filter rather than ignored. On Home, search spans all
* active notes. ByTag keeps the same behaviour (the tag itself is
* already the filter). */
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 -> if (q.isBlank()) repository.observeFavorites() else repository.searchFavorites(q)
NoteFilter.Untagged -> if (q.isBlank()) repository.observeUntagged() else repository.searchUntagged(q)
NoteFilter.Drafts -> if (q.isBlank()) repository.observeDrafts() else repository.searchDrafts(q)
NoteFilter.Trash -> if (q.isBlank()) repository.observeTrashed() else repository.searchTrashed(q)
is NoteFilter.ByTag -> repository.observeNotesForHashtag(f.hashtag)
is NoteFilter.ByColor ->
if (q.isBlank()) repository.observeByColor(f.color) else repository.searchByColor(q, f.color)
}
}
private val baseUiState: StateFlow<NoteListUiState> = combine(
notesFlow,
_isSearchActive,
filterMode,
rawQuery,
repository.observeHashtagsByRecentUse(),
) { notes, searchActive, filter, query, recent ->
NoteListUiState(
notes = notes,
isLoading = false,
searchQuery = query,
isSearchActive = searchActive,
filter = filter,
recentHashtags = recent,
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NoteListUiState(),
)
/**
* v0.3.5.0 — merge the verification results into the UI state. The
* verifier re-checks every encrypted row on every app open (and
* after each encryption migration), so a card's badge always
* reflects a fresh proof-of-decryptability, never just the
* settings flag.
*/
val uiState: StateFlow<NoteListUiState> = combine(
baseUiState,
encryptionVerifier?.verification
?: kotlinx.coroutines.flow.flowOf(null),
) { state, verification ->
state.copy(
verifiedEncryptedNoteIds = verification?.verifiedNoteIds ?: emptySet(),
unverifiedEncryptedNoteCount = verification?.failedNoteIds?.size ?: 0,
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NoteListUiState(),
)
fun setFilter(filter: NoteFilter) {
filterMode.value = filter
// v0.3.1.0: search is now context-aware on Home / Favorites /
// Untagged. Closing the search bar only makes sense when
// switching to a ByTag filter (the tag itself is the filter,
// so an additional text query would be ambiguous).
if (filter is NoteFilter.ByTag && _isSearchActive.value) {
_isSearchActive.value = false
rawQuery.value = ""
}
}
fun onQueryChange(q: String) {
rawQuery.value = q
}
fun openSearch() {
_isSearchActive.value = true
}
fun closeSearch() {
_isSearchActive.value = false
rawQuery.value = ""
}
/** Move an active note to Trash. */
fun softDelete(id: Long) {
viewModelScope.launch { repository.softDelete(id) }
}
/** Permanently destroy a note from the Trash view. */
fun permanentlyDelete(id: Long) {
viewModelScope.launch { repository.delete(id) }
}
/** "Empty Trash": permanently destroy every note in the Trash. */
fun emptyTrash() {
viewModelScope.launch { repository.deleteAllTrashed() }
}
/** Restore a note from Trash. */
fun restore(id: Long) {
viewModelScope.launch { repository.restore(id) }
}
fun toggleFavorite(id: Long, isFavorite: Boolean) {
viewModelScope.launch { repository.setFavorite(id, isFavorite) }
}
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
NoteListViewModel(
repository = app.container.noteRepository,
encryptionVerifier = app.container.encryptionVerifier,
)
}
}
}
}
@@ -52,6 +52,7 @@ import kotlinx.coroutines.launch
import org.incido.compose.data.backup.BackupPreview
import org.incido.compose.data.backup.EncryptedBackupCodec
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.di.requireAndroidContainer
import org.incido.compose.data.settings.AutoLockTimeout
import org.incido.compose.data.settings.ThemeMode
@@ -93,7 +94,7 @@ fun SettingsScreen(
* suppression (the pre-0.3.4.0 behaviour).
*/
securityManager: SecurityManager? = null,
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
) {
val settings by viewModel.userSettings.collectAsStateWithLifecycle()
val migrationState by viewModel.migrationState.collectAsStateWithLifecycle()
@@ -2,7 +2,6 @@ package org.incido.compose.ui.settings
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
@@ -12,7 +11,7 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication
import org.incido.compose.di.AppContainer
import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.backup.CarnetImporter
import org.incido.compose.data.security.ObjectBoxKeyProvider
@@ -362,10 +361,17 @@ class SettingsViewModel(
* — if you bump one, bump both. */
const val APP_VERSION = "0.4.2.0"
val Factory: ViewModelProvider.Factory = viewModelFactory {
/**
* M4.3c: graph-based factory — but this ViewModel genuinely needs
* the ANDROID services (SecurityManager, Keystore key provider,
* BackupManager's Uri IO, CarnetImporter), so it takes the
* concrete AppContainer, not just the AppGraph face. It stays in
* androidMain until those services gain desktop answers (or the
* UI hides them — plan §6.5).
*/
fun factory(container: AppContainer): ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
val c = app.container
val c = container
SettingsViewModel(
settings = c.settingsRepository,
security = c.securityManager,
@@ -40,6 +40,7 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.launch
import org.incido.compose.di.requireAndroidContainer
import org.incido.compose.ui.settings.SettingsViewModel
/**
@@ -57,7 +58,7 @@ import org.incido.compose.ui.settings.SettingsViewModel
* stored hash + salt. The screen pops on success and surfaces a
* "PIN updated." snackbar via the existing viewModel.snackbar flow.
*
* Reuses the existing [SettingsViewModel.Factory] — the new screen
* Reuses the existing [SettingsViewModel.factory] — the new screen
* doesn't need its own ViewModel because every operation goes through
* the existing security manager.
*/
@@ -66,7 +67,7 @@ import org.incido.compose.ui.settings.SettingsViewModel
fun PinChangeScreen(
onDone: () -> Unit,
onCancel: () -> Unit,
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
) {
val scope = rememberCoroutineScope()
var step by remember { mutableStateOf(Step.VerifyOld) }
@@ -36,6 +36,7 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.launch
import org.incido.compose.di.requireAndroidContainer
import org.incido.compose.ui.settings.SettingsViewModel
/**
@@ -60,7 +61,7 @@ import org.incido.compose.ui.settings.SettingsViewModel
fun PinSetupScreen(
onDone: () -> Unit,
onCancel: () -> Unit,
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.factory(requireAndroidContainer())),
) {
val scope = rememberCoroutineScope()