feat(phase-1/m4.3b): AppGraph seam + first commonMain ViewModel (§6.4 probe GREEN)

M4.3's container seam, proven with the smallest ViewModel:

* commonMain di/AppGraph.kt — the platform-neutral container face
  (noteRepository + settingsRepository) plus LocalAppGraph /
  requireAppGraph. Scope discipline per §9: only services BOTH platforms
  can honestly serve; Keystore/SecurityManager/BackupManager/CarnetImporter
  stay on the concrete AppContainer.
* :core:settings + lifecycle-viewmodel enter commonMain (settings as api —
  AppGraph exposes it). Lifecycle coordinates are the SAME
  org.jetbrains.androidx.lifecycle 2.8.4 aliases androidMain already
  resolved since M4.1, so the §6.4 "verify the artifact set" question is
  answered GREEN for both targets and the state-holder fallback is NOT
  needed: DrawerViewModel moves with its androidx.lifecycle.* imports
  UNCHANGED (offline set keeps the androidx FQCNs).
* DrawerViewModel.Factory(APPLICATION_KEY as IncidoApplication) →
  factory(graph: AppGraph). AppContainer implements AppGraph; IncidoApp
  provides LocalAppGraph at the root (same fallback chain it already used).

Verification (one run):
  ./gradlew :composeApp:compileKotlinJvm assembleDebug → BUILD SUCCESSFUL
  (jvm target = first compile of a commonMain ViewModel on desktop deps)
This commit is contained in:
Incido Developer committed 2026-10-06 16:33:53 +13:00
1 parent 5bce1934c1
commit cd363c7aa5
6 files changed
+230 -156

No files matched your search

+13
View File
@@ -47,11 +47,24 @@ kotlin {
implementation(compose.foundation) implementation(compose.foundation)
implementation(compose.material3) implementation(compose.material3)
implementation(libs.kotlinx.coroutines.core) implementation(libs.kotlinx.coroutines.core)
// Phase 1 (M4.3b): the §6.4 artifact check resolves GREEN —
// these org.jetbrains.androidx.lifecycle coordinates are what
// androidMain has been resolving since M4.1 (assembleDebug
// proves they coexist with the AndroidX BOM on the android
// target), and the desktopApp runtime already carried the
// matching -desktop jars. Here they enter commonMain so the
// ViewModels move with their `androidx.lifecycle.*` imports
// UNCHANGED (the offline set keeps the androidx FQCNs).
implementation(libs.androidx.lifecycle.viewmodel)
// Phase 1 (M4.2): :core:domain is multiplatform now (M4.2's own // Phase 1 (M4.2): :core:domain is multiplatform now (M4.2's own
// conversion), so commonMain can see it — this is what let // conversion), so commonMain can see it — this is what let
// NoteColors.kt move up. api: screens/ViewModels across all // NoteColors.kt move up. api: screens/ViewModels across all
// targets consume Note/NoteColor/NoteRepository from it. // targets consume Note/NoteColor/NoteRepository from it.
api(project(":core:domain")) api(project(":core:domain"))
// Phase 1 (M4.3a): :core:settings converted in the same shape —
// M4.3's AppGraph exposes SettingsRepository/UserSettings to
// commonMain, so this has to be api too.
api(project(":core:settings"))
} }
androidMain.dependencies { androidMain.dependencies {
@@ -6,6 +6,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.rememberDrawerState import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -30,6 +31,7 @@ import androidx.navigation.navArgument
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.incido.compose.data.security.SecurityManager import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.SettingsRepository import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.di.LocalAppGraph
import org.incido.compose.share.SharedIntentBuffer import org.incido.compose.share.SharedIntentBuffer
import org.incido.compose.ui.drawer.IncidoDrawer import org.incido.compose.ui.drawer.IncidoDrawer
import org.incido.compose.ui.editor.NoteEditorScreen import org.incido.compose.ui.editor.NoteEditorScreen
@@ -108,155 +110,159 @@ fun IncidoApp(
) )
val lockState by resolvedSecurity.lockState.collectAsStateWithLifecycle() val lockState by resolvedSecurity.lockState.collectAsStateWithLifecycle()
IncidoTheme( // M4.3: the platform graph reaches the screens through the composition —
darkTheme = settings.themeMode.resolveDark(isSystemInDarkTheme()), // the same face DesktopContainer implements (commonMain di/AppGraph.kt).
dynamicColor = settings.dynamicColor, CompositionLocalProvider(LocalAppGraph provides app.container) {
) { IncidoTheme(
// v0.3.2.0: hard lock gate. If the app is locked we render darkTheme = settings.themeMode.resolveDark(isSystemInDarkTheme()),
// the PIN entry screen in place of the regular UI. dynamicColor = settings.dynamicColor,
if (lockState is SecurityManager.LockState.Locked) {
PinEntryScreen()
return@IncidoTheme
}
val navController = rememberNavController()
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>(NoteFilter.Home) }
// v0.3.1.0: consume any inbound share-into payload once at
// composition. The buffer is single-shot — first composition
// wins. If a payload is present, we open a fresh editor with
// the shared content pre-filled.
val shareHolder = remember { ShareIntoHolder() }
LaunchedEffect(Unit) {
val payload = SharedIntentBuffer.consume()
if (payload != null && !payload.isEmpty) {
shareHolder.text = payload.text
shareHolder.images = payload.images
shareHolder.subject = payload.subject
navController.navigate(Routes.editor(null)) {
popUpTo(Routes.LIST)
}
}
}
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()
}
// v0.3.2.0: forward app foreground/background transitions to
// the SecurityManager so it can re-lock when the timeout
// elapses. LifecycleEventObserver wires ON_RESUME / ON_STOP
// automatically.
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> resolvedSecurity.onAppForegrounded()
Lifecycle.Event.ON_STOP -> resolvedSecurity.onAppBackgrounded()
else -> Unit
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
ModalNavigationDrawer(
drawerState = drawerState,
gesturesEnabled = isListRoute,
drawerContent = {
IncidoDrawer(
currentFilter = filterMode,
onSelectFilter = { picked ->
filterMode = picked
scope.launch { drawerState.close() }
},
onOpenSettings = {
scope.launch { drawerState.close() }
navController.navigate(Routes.SETTINGS)
},
)
},
) { ) {
NavHost(navController = navController, startDestination = Routes.LIST) { // v0.3.2.0: hard lock gate. If the app is locked we render
composable(Routes.LIST) { // the PIN entry screen in place of the regular UI.
NoteListScreen( if (lockState is SecurityManager.LockState.Locked) {
filterMode = filterMode, PinEntryScreen()
onOpenDrawer = { scope.launch { drawerState.open() } }, return@IncidoTheme
onOpenEditor = { id -> navController.navigate(Routes.editor(id)) }, }
// v0.3.1.0: thread the NoteRepository through so the
// card thumbnail composables can fetch image bytes. val navController = rememberNavController()
repository = repository, 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>(NoteFilter.Home) }
// v0.3.1.0: consume any inbound share-into payload once at
// composition. The buffer is single-shot — first composition
// wins. If a payload is present, we open a fresh editor with
// the shared content pre-filled.
val shareHolder = remember { ShareIntoHolder() }
LaunchedEffect(Unit) {
val payload = SharedIntentBuffer.consume()
if (payload != null && !payload.isEmpty) {
shareHolder.text = payload.text
shareHolder.images = payload.images
shareHolder.subject = payload.subject
navController.navigate(Routes.editor(null)) {
popUpTo(Routes.LIST)
}
} }
composable( }
route = Routes.EDITOR,
arguments = listOf( val currentBackStack by navController.currentBackStackEntryAsState()
navArgument("noteId") { val currentRoute = currentBackStack?.destination?.route?.substringBefore("/")
type = NavType.LongType // Disable the drawer on the editor so back arrow / gesture do
defaultValue = -1L // 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()
}
// v0.3.2.0: forward app foreground/background transitions to
// the SecurityManager so it can re-lock when the timeout
// elapses. LifecycleEventObserver wires ON_RESUME / ON_STOP
// automatically.
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> resolvedSecurity.onAppForegrounded()
Lifecycle.Event.ON_STOP -> resolvedSecurity.onAppBackgrounded()
else -> Unit
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
ModalNavigationDrawer(
drawerState = drawerState,
gesturesEnabled = isListRoute,
drawerContent = {
IncidoDrawer(
currentFilter = filterMode,
onSelectFilter = { picked ->
filterMode = picked
scope.launch { drawerState.close() }
},
onOpenSettings = {
scope.launch { drawerState.close() }
navController.navigate(Routes.SETTINGS)
}, },
),
) { entry ->
val raw = entry.arguments?.getLong("noteId") ?: -1L
val id = if (raw <= 0L) null else raw
// Read the share payload ONCE (consume) so back-then-reopen
// doesn't re-route us into the editor with stale data.
val sharedText = shareHolder.text.also { shareHolder.text = null }
val sharedImages = shareHolder.images.also { shareHolder.images = emptyList() }
// v0.3.6.0: also drain the page-title subject from the
// share intent so the editor can format the note
// with title on the first line.
val sharedSubject = shareHolder.subject.also { shareHolder.subject = null }
NoteEditorScreen(
noteId = id,
onClose = { navController.popBackStack() },
initialSharedText = sharedText,
initialSharedImages = sharedImages,
initialSharedSubject = sharedSubject,
repository = repository,
// v0.3.4.0 hotfix: suppress auto-lock around
// the editor's picker / camera / system-viewer
// round-trips.
securityManager = resolvedSecurity,
)
}
composable(Routes.SETTINGS) {
SettingsScreen(
onBack = { navController.popBackStack() },
onRequestPinSetup = { navController.navigate(Routes.PIN_SETUP) },
// v0.3.3.0: "Reset PIN" row navigates here.
onRequestPinChange = { navController.navigate(Routes.PIN_CHANGE) },
// v0.3.4.0 hotfix: suppress auto-lock around
// the backup export/import SAF pickers.
securityManager = resolvedSecurity,
)
}
composable(Routes.PIN_SETUP) {
PinSetupScreen(
onDone = { navController.popBackStack() },
onCancel = { navController.popBackStack() },
)
}
composable(Routes.PIN_CHANGE) {
PinChangeScreen(
onDone = { navController.popBackStack() },
onCancel = { 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)) },
// v0.3.1.0: thread the NoteRepository through so the
// card thumbnail composables can fetch image bytes.
repository = repository,
)
}
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
// Read the share payload ONCE (consume) so back-then-reopen
// doesn't re-route us into the editor with stale data.
val sharedText = shareHolder.text.also { shareHolder.text = null }
val sharedImages = shareHolder.images.also { shareHolder.images = emptyList() }
// v0.3.6.0: also drain the page-title subject from the
// share intent so the editor can format the note
// with title on the first line.
val sharedSubject = shareHolder.subject.also { shareHolder.subject = null }
NoteEditorScreen(
noteId = id,
onClose = { navController.popBackStack() },
initialSharedText = sharedText,
initialSharedImages = sharedImages,
initialSharedSubject = sharedSubject,
repository = repository,
// v0.3.4.0 hotfix: suppress auto-lock around
// the editor's picker / camera / system-viewer
// round-trips.
securityManager = resolvedSecurity,
)
}
composable(Routes.SETTINGS) {
SettingsScreen(
onBack = { navController.popBackStack() },
onRequestPinSetup = { navController.navigate(Routes.PIN_SETUP) },
// v0.3.3.0: "Reset PIN" row navigates here.
onRequestPinChange = { navController.navigate(Routes.PIN_CHANGE) },
// v0.3.4.0 hotfix: suppress auto-lock around
// the backup export/import SAF pickers.
securityManager = resolvedSecurity,
)
}
composable(Routes.PIN_SETUP) {
PinSetupScreen(
onDone = { navController.popBackStack() },
onCancel = { navController.popBackStack() },
)
}
composable(Routes.PIN_CHANGE) {
PinChangeScreen(
onDone = { navController.popBackStack() },
onCancel = { navController.popBackStack() },
)
}
} }
} }
} }
@@ -19,6 +19,7 @@ import org.incido.compose.data.security.ObjectBoxKeyProvider
import org.incido.compose.data.security.SecurityManager import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.SettingsRepository import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.data.settings.settingsDataStore import org.incido.compose.data.settings.settingsDataStore
import org.incido.compose.di.AppGraph
/** /**
* Hand-rolled DI container. Replaces Hilt/Dagger for v0.1 — keeps the * Hand-rolled DI container. Replaces Hilt/Dagger for v0.1 — keeps the
@@ -41,8 +42,14 @@ import org.incido.compose.data.settings.settingsDataStore
* After startup the [encryptionVerifier] re-checks every encrypted row * After startup the [encryptionVerifier] re-checks every encrypted row
* by trial-decrypting it; only rows that pass earn the "Encrypted" * by trial-decrypting it; only rows that pass earn the "Encrypted"
* badge on the note cards. * badge on the note cards.
*
* Phase 1 (M4.3): implements [AppGraph] — the platform-neutral face the
* commonMain ViewModels consume. Android-only services (Keystore key
* provider, SecurityManager, BackupManager, CarnetImporter) stay on this
* concrete class; the graph is exactly what the desktop
* `DesktopContainer` can implement too.
*/ */
class AppContainer(context: Context) { class AppContainer(context: Context) : AppGraph {
private val appContext: Context = context.applicationContext private val appContext: Context = context.applicationContext
@@ -53,7 +60,7 @@ class AppContainer(context: Context) {
// Phase 1 (M3 task 1): the store is injected — SettingsRepository moved // Phase 1 (M3 task 1): the store is injected — SettingsRepository moved
// to :core:settings so the desktop build can share it. Android supplies // to :core:settings so the desktop build can share it. Android supplies
// the Context-backed `incido_settings.preferences_pb` store here. // the Context-backed `incido_settings.preferences_pb` store here.
val settingsRepository: SettingsRepository = override val settingsRepository: SettingsRepository =
SettingsRepository(appContext.settingsDataStore) SettingsRepository(appContext.settingsDataStore)
val objectBoxKeyProvider: ObjectBoxKeyProvider = ObjectBoxKeyProvider(appContext) val objectBoxKeyProvider: ObjectBoxKeyProvider = ObjectBoxKeyProvider(appContext)
@@ -83,7 +90,7 @@ class AppContainer(context: Context) {
} }
} }
val noteRepository: NoteRepository = NoteRepositoryImpl( override val noteRepository: NoteRepository = NoteRepositoryImpl(
boxStore, boxStore,
cipherHolder, cipherHolder,
// Phase 1 (M1a) platform seam: EXIF rotation needs a bitmap decoder, // Phase 1 (M1a) platform seam: EXIF rotation needs a bitmap decoder,
@@ -42,6 +42,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.compose.viewModel
import org.incido.compose.di.requireAppGraph
import org.incido.compose.ui.theme.AllNoteColors import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.toComposeColor import org.incido.compose.ui.theme.toComposeColor
import org.incido.domain.model.HashtagUsage import org.incido.domain.model.HashtagUsage
@@ -78,7 +79,7 @@ fun IncidoDrawer(
onSelectFilter: (NoteFilter) -> Unit, onSelectFilter: (NoteFilter) -> Unit,
onOpenSettings: () -> Unit, onOpenSettings: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.Factory), viewModel: DrawerViewModel = viewModel(factory = DrawerViewModel.factory(requireAppGraph())),
) { ) {
val recent by viewModel.recentHashtags.collectAsStateWithLifecycle() val recent by viewModel.recentHashtags.collectAsStateWithLifecycle()
@@ -0,0 +1,45 @@
package org.incido.compose.di
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
import org.incido.compose.data.settings.SettingsRepository
import org.incido.domain.repository.NoteRepository
/**
* Phase 1 (M4.3) — the platform-neutral face of the DI container.
*
* The seam that lets the ViewModels leave `IncidoApplication` /
* `AndroidViewModelFactory.APPLICATION_KEY` behind: they receive an
* [AppGraph] (via the screen's `viewModel(factory = …)` construction site)
* instead of digging the Application out of CreationExtras. Android's
* `AppContainer` and the desktop `DesktopContainer` implement the same
* face — that is the M4.3 exit proof.
*
* Scope discipline (§9, no silently widened seams): only what BOTH
* platforms can honestly serve lives here — the note store and the
* settings stream. Android-only services (Keystore key provider,
* SecurityManager lock state, BackupManager's Uri IO, CarnetImporter)
* stay on `AppContainer`; the cipher services reach the shared ViewModels
* through [EncryptionBadge] instead of the concrete `EncryptionVerifier`.
* ViewModels that genuinely need the Android extras (SettingsViewModel
* today) stay in androidMain and take the concrete `AppContainer`.
*/
interface AppGraph {
val noteRepository: NoteRepository
val settingsRepository: SettingsRepository
}
/**
* Where the screens find the graph: provided at the root composable of
* each platform (`IncidoApp` on Android; the desktop window in M4.5), read
* at composition time to build ViewModel factories. Nullable so a screen
* rendered outside a provider (preview/test) fails at the factory call
* with a clear message instead of a CompositionLocal-absent crash.
*/
val LocalAppGraph = compositionLocalOf<AppGraph?> { null }
/** Read [LocalAppGraph] or throw with the M4.3 context — call at composition. */
@Composable
fun requireAppGraph(): AppGraph = checkNotNull(LocalAppGraph.current) {
"No AppGraph provided — wrap the screen in CompositionLocalProvider(LocalAppGraph provides …)."
}
@@ -2,14 +2,13 @@ package org.incido.compose.ui.drawer
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import org.incido.compose.IncidoApplication import org.incido.compose.di.AppGraph
import org.incido.domain.model.HashtagUsage import org.incido.domain.model.HashtagUsage
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
@@ -18,6 +17,12 @@ import org.incido.domain.repository.NoteRepository
* tags" list. Kept separate from [NoteListViewModel] because the * tags" list. Kept separate from [NoteListViewModel] because the
* drawer may render even before the list screen is created (and * drawer may render even before the list screen is created (and
* vice-versa). * vice-versa).
*
* Phase 1 (M4.3b): first ViewModel in commonMain — the §6.4 probe. It
* compiles for both targets with its `androidx.lifecycle.*` imports
* unchanged (the org.jetbrains.androidx.lifecycle offline set keeps the
* androidx FQCNs), and takes the [AppGraph] instead of digging
* `IncidoApplication` out of CreationExtras via APPLICATION_KEY.
*/ */
class DrawerViewModel( class DrawerViewModel(
repository: NoteRepository, repository: NoteRepository,
@@ -32,11 +37,8 @@ class DrawerViewModel(
) )
companion object { companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory { fun factory(graph: AppGraph): ViewModelProvider.Factory = viewModelFactory {
initializer { initializer { DrawerViewModel(graph.noteRepository) }
val app = this[APPLICATION_KEY] as IncidoApplication
DrawerViewModel(app.container.noteRepository)
}
} }
} }
} }