Modern Apps git

← Modern-Apps.git

todo: carry list view in Route.TodoList(viewKey) (#nav)

Commit
ac619bbe9c5b414ffe799975f0b78676b494723f
Author
Vayun Mathur <[email protected]>
When
2026-11-16 20:04 UTC (19 days ago)
Parents
8ad288d
Move the main list's view selection out of TodoViewModel's
SavedState-backed StateFlow<TodoView> and into the back stack:
Route.TodoList is now a data class carrying viewKey (TodoView.key,
round-tripped via TodoView.fromKey). The settings default view
seeds the initial route in Navigation instead of a VM-saved view.

TodoViewModel loses the persisted view, setView() and the global
model; modelFor(view) builds the TodoQuery model for the route's
view, and quickAdd/openEditor receive the route view explicitly
for their templates. TodoShell derives the drawer selection from
the deepest TodoList entry in the stack, drawer selection resets
Route.TodoList(view.key), a newly created list resets to its
InList route, and deleting the open list resets to Inbox from the
shell (the VM no longer owns that fallback). IntentEffect deep
links reset Route.TodoList(viewKey), preserving the current list
view for OpenTask/QuickAdd.

Tests: TodoViewModelTest covers modelFor per-view isolation and
that a stale saved view entry is ignored; NavigationAndMainActivityTest
pins TodoList(viewKey) equality/serialization and route-driven view
opening; TodoComposePagesTest asserts drawer clicks reset the stack.

Verified: ./gradlew :todo:compileDevKotlin :todo:testDevUnitTest

Diff

todo/src/androidTest/java/com/vayunmathur/todo/data/TodoRepoDeviceTest.kt
diff --git a/todo/src/androidTest/java/com/vayunmathur/todo/data/TodoRepoDeviceTest.kt b/todo/src/androidTest/java/com/vayunmathur/todo/data/TodoRepoDeviceTest.ktindex eaa99b2795..eb2e3f0c19 100644--- a/todo/src/androidTest/java/com/vayunmathur/todo/data/TodoRepoDeviceTest.kt+++ b/todo/src/androidTest/java/com/vayunmathur/todo/data/TodoRepoDeviceTest.kt@@ -139,9 +139,7 @@ class TodoRepoDeviceTest {         val app = context.applicationContext as Application         val settings = TodoSettings(context)         val vm = TodoViewModel(app, repo, settings, SavedStateHandle())-        vm.setView(TodoView.Today)-        pollUntil { vm.view.value == TodoView.Today }-        vm.setView(TodoView.InList("x")); pollUntil { vm.view.value == TodoView.InList("x") }+        // No VM view state: the selected view is Route.TodoList(viewKey).         vm.setSort(SortMode.TITLE); pollUntil { vm.sort.value == SortMode.TITLE }         vm.setSearchQuery("hello"); assertEquals("hello", vm.searchQuery.value)         vm.setSearchQuery("")@@ -149,7 +147,7 @@ class TodoRepoDeviceTest {         vm.clearQuickAddRequest(); assertNull(vm.quickAddRequest.value)         // quick add creates a task         val before = repo.getAll().size-        vm.quickAdd(listOf("Device quick task tomorrow #devtag", "  ", "Second device task"))+        vm.quickAdd(listOf("Device quick task tomorrow #devtag", "  ", "Second device task"), TodoView.Today)         // viewModel launches on io; poll         val deadline = System.currentTimeMillis() + 10000         while (System.currentTimeMillis() < deadline && repo.getAll().none { it.title == "Device quick task" }) Thread.sleep(50)@@ -171,7 +169,7 @@ class TodoRepoDeviceTest {         assertTrue(repo.getBySyncId(tid)!!.done)         assertEquals(repo.getBySyncId(tid)!!.id, vm.idForSyncId(tid))         assertNull(vm.idForSyncId("nope-xyz"))-        val editor = vm.openEditor(repo.getBySyncId(tid)!!.id, null)+        val editor = vm.openEditor(repo.getBySyncId(tid)!!.id, null, TodoView.Inbox)         assertNotNull(editor.state)         Unit     }@@ -180,7 +178,7 @@ class TodoRepoDeviceTest {         val app = context.applicationContext as Application         val vm = TodoViewModel(app, repo, TodoSettings(context), SavedStateHandle())         val newId = uid("ednew")-        val editor = vm.openEditor(0L, newId)+        val editor = vm.openEditor(0L, newId, TodoView.Inbox)         // wait for load         val dl = System.currentTimeMillis() + 10000         while (System.currentTimeMillis() < dl && editor.state.value == null) Thread.sleep(50)@@ -192,7 +190,7 @@ class TodoRepoDeviceTest {         assertEquals("Editor created", repo.getBySyncId(newId)?.title)         // edit existing, add subtask, setDone, duplicate, delete         val existing = repo.getBySyncId(newId)!!-        val ed2 = vm.openEditor(existing.id, null)+        val ed2 = vm.openEditor(existing.id, null, TodoView.Inbox)         val dl3 = System.currentTimeMillis() + 10000         while (System.currentTimeMillis() < dl3 && (ed2.state.value == null || ed2.state.value?.id == 0L)) Thread.sleep(50)         ed2.addSubtask("Editor sub")@@ -493,7 +491,7 @@ class TodoRepoDeviceTest {         val tid = uid("dup")         repo.upsert(Todo(syncId = tid, title = "Dup original"))         val existing = repo.getBySyncId(tid)!!-        val editor = vm.openEditor(existing.id, null)+        val editor = vm.openEditor(existing.id, null, TodoView.Inbox)         pollUntil { editor.state.value?.id == existing.id }         var createdId = -1L         editor.duplicate { createdId = it }
todo/src/main/java/com/vayunmathur/todo/Navigation.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/Navigation.kt b/todo/src/main/java/com/vayunmathur/todo/Navigation.ktindex 94cfe12e99..4b403ec623 100644--- a/todo/src/main/java/com/vayunmathur/todo/Navigation.kt+++ b/todo/src/main/java/com/vayunmathur/todo/Navigation.kt@@ -1,6 +1,8 @@ package com.vayunmathur.todo  import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.util.ListDetailPage import com.vayunmathur.library.util.ListPage import com.vayunmathur.library.util.MainNavigation@@ -17,13 +19,24 @@ import com.vayunmathur.todo.ui.rememberTodoShellState  @Composable fun Navigation(todoViewModel: TodoViewModel) {-    val backStack = rememberNavBackStack<Route>(Route.TodoList)+    // The initial route is the user's default view. Wait for its first emission+    // so the retained back stack is created with that view, not a placeholder;+    // later default-view changes do not rewrite the live stack.+    val defaultView by todoViewModel.settings.defaultView+        .collectAsStateWithLifecycle(initialValue = null)+    val initialView = defaultView ?: return+    val backStack = rememberNavBackStack<Route>(Route.TodoList(initialView.key))     val shell = rememberTodoShellState()     IntentEffect(backStack, todoViewModel)     TodoShell(shell, todoViewModel, backStack) {         MainNavigation(backStack) {-            entry<Route.TodoList>(metadata = ListPage()) {-                TodoListPage(backStack, todoViewModel, onMenu = if (shell.permanent) null else shell::openDrawer)+            entry<Route.TodoList>(metadata = ListPage()) { route ->+                TodoListPage(+                    backStack,+                    todoViewModel,+                    route,+                    onMenu = if (shell.permanent) null else shell::openDrawer,+                )             }             entry<Route.TodoDetail>(metadata = ListDetailPage() + MorphPage()) {                 TodoDetailPage(backStack, todoViewModel, it)
todo/src/main/java/com/vayunmathur/todo/Route.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/Route.kt b/todo/src/main/java/com/vayunmathur/todo/Route.ktindex 38180f7f4a..abdb0b178f 100644--- a/todo/src/main/java/com/vayunmathur/todo/Route.kt+++ b/todo/src/main/java/com/vayunmathur/todo/Route.kt@@ -5,8 +5,9 @@ import kotlinx.serialization.Serializable  @Serializable sealed interface Route : NavKey {+    /** The task list showing [viewKey] (a `TodoView.key`); the route is the source of truth for the selected view. */     @Serializable-    data object TodoList : Route+    data class TodoList(val viewKey: String) : Route      /** [id] 0 opens a new task, identified across saves by [newSyncId]. */     @Serializable
todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.ktindex 15a62a7b1d..14410c33b0 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt@@ -47,9 +47,6 @@ class TodoViewModel(     private val io = repository.io      val searchQuery: StateFlow<String> = savedState.getStateFlow(KEY_QUERY, "")-    val view: StateFlow<TodoView> = savedState.getStateFlow(KEY_VIEW, TodoView.Inbox.key)-        .map { TodoView.fromKey(it) }-        .stateIn(viewModelScope, SharingStarted.Eagerly, TodoView.Inbox)     val sort: StateFlow<SortMode> = savedState.getStateFlow(KEY_SORT, SortMode.MANUAL.name)         .map { runCatching { SortMode.valueOf(it) }.getOrDefault(SortMode.MANUAL) }         .stateIn(viewModelScope, SharingStarted.Eagerly, SortMode.MANUAL)@@ -67,14 +64,20 @@ class TodoViewModel(     val lists: StateFlow<List<TodoList>> = repository.lists         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), emptyList()) -    private data class Params(val view: TodoView, val query: String, val sort: SortMode, val now: Long)+    private data class Params(val query: String, val sort: SortMode, val now: Long) -    private val params = combine(view, searchQuery, sort, clock) { v, q, s, now -> Params(v, q, s, now) }+    private val params = combine(searchQuery, sort, clock) { q, s, now -> Params(q, s, now) } -    val model: StateFlow<Pair<TodoListModel, Long>> =+    /**+     * The list model for [view] (the view named by the current `Route.TodoList` entry).+     * The route is authoritative: callers pass its view explicitly and this flow is+     * derived from it, never from persisted view state. Each call creates a flow+     * scoped to [viewModelScope]; pages should remember one instance per view.+     */+    fun modelFor(view: TodoView): StateFlow<Pair<TodoListModel, Long>> =         combine(todos, lists, params, settings.showCompleted) { todos, lists, p, showDone ->             val zone = TimeZone.currentSystemDefault()-            val built = TodoQuery.build(TodoQuery.Input(todos, lists, p.view, p.query, p.sort, p.now, zone))+            val built = TodoQuery.build(TodoQuery.Input(todos, lists, view, p.query, p.sort, p.now, zone))             (if (showDone) built else built.copy(completed = emptyList())) to p.now         }.stateIn(             viewModelScope,@@ -93,7 +96,6 @@ class TodoViewModel(     init {         viewModelScope.launch(io) { repository.maintain() }         viewModelScope.launch {-            if (!savedState.contains(KEY_VIEW)) savedState[KEY_VIEW] = settings.defaultView.first().key             if (!savedState.contains(KEY_SORT)) savedState[KEY_SORT] = settings.defaultSort.first().name         }     }@@ -121,7 +123,8 @@ class TodoViewModel(     }      fun deleteList(list: TodoList) {-        if (view.value == TodoView.InList(list.syncId)) setView(TodoView.Inbox)+        // Fallback to Inbox when the deleted list is being viewed is a routing+        // decision: the shell resets the back stack, not this ViewModel.         viewModelScope.launch(io) { repository.tombstoneList(list) }     } @@ -162,8 +165,8 @@ class TodoViewModel(         savedState[KEY_QUERY] = query     } -    fun setView(view: TodoView) {-        savedState[KEY_VIEW] = view.key+    /** Changing view (a route change) starts with an empty search, as before. */+    fun clearSearchQuery() {         savedState[KEY_QUERY] = ""     } @@ -171,8 +174,8 @@ class TodoViewModel(         savedState[KEY_SORT] = sort.name     } -    fun quickAdd(texts: List<String>) {-        val currentView = view.value+    fun quickAdd(texts: List<String>, view: TodoView) {+        val currentView = view         viewModelScope.launch(io) {             val lists = repository.getLists().map { QuickAddParser.ListName(it.syncId, it.name) }             val zone = TimeZone.currentSystemDefault()@@ -237,14 +240,14 @@ class TodoViewModel(      fun setPriority(todos: List<Todo>, priority: Int) = upsertAll(todos.map { it.copy(priority = priority) }) -    fun openEditor(id: Long, newSyncId: String?): TodoEditor {-        val template = templateFor(view.value, System.currentTimeMillis(), TimeZone.currentSystemDefault())+    /** [view] is the route's current view, used only as the template for a new task. */+    fun openEditor(id: Long, newSyncId: String?, view: TodoView): TodoEditor {+        val template = templateFor(view, System.currentTimeMillis(), TimeZone.currentSystemDefault())         return TodoEditor(repository, repository.appScope, id, newSyncId, template)     }      companion object {         private const val KEY_QUERY = "search_query"-        private const val KEY_VIEW = "view"         private const val KEY_SORT = "sort"         private const val STOP_TIMEOUT_MS = 5_000L         private const val TICK_MS = 60_000L
todo/src/main/java/com/vayunmathur/todo/ui/IntentEffect.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/IntentEffect.kt b/todo/src/main/java/com/vayunmathur/todo/ui/IntentEffect.ktindex c2d0eaa963..02b8ffbdee 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/IntentEffect.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/IntentEffect.kt@@ -17,17 +17,22 @@ fun IntentEffect(backStack: NavBackStack<Route>, viewModel: TodoViewModel) {     LaunchedEffect(request) {         when (val r = request ?: return@LaunchedEffect) {             is IntentRouter.Request.OpenTask -> viewModel.idForSyncId(r.syncId)?.let { id ->-                backStack.reset(Route.TodoList, Route.TodoDetail(id))+                backStack.reset(Route.TodoList(currentViewKey(backStack)), Route.TodoDetail(id))             }             is IntentRouter.Request.OpenView -> {-                viewModel.setView(TodoView.fromKey(r.viewKey))-                backStack.reset(Route.TodoList)+                viewModel.clearSearchQuery()+                backStack.reset(Route.TodoList(TodoView.fromKey(r.viewKey).key))             }             is IntentRouter.Request.QuickAdd -> {-                backStack.reset(Route.TodoList)+                backStack.reset(Route.TodoList(currentViewKey(backStack)))                 viewModel.requestQuickAdd(r.text)             }         }         IntentRouter.consume()     } }++/** The view of the list entry already in the stack, so resets keep showing it. */+private fun currentViewKey(backStack: NavBackStack<Route>): String =+    backStack.backStack.filterIsInstance<Route.TodoList>().lastOrNull()?.viewKey+        ?: TodoView.Inbox.key
todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.ktindex ef77ae18b1..45be9d1b6b 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.kt@@ -9,6 +9,7 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.todo.Route import com.vayunmathur.todo.data.Todo import com.vayunmathur.todo.domain.TodoQuery+import com.vayunmathur.todo.domain.TodoView import com.vayunmathur.todo.platform.TodoActions import com.vayunmathur.todo.platform.TodoUiState import com.vayunmathur.todo.platform.TodoViewModel@@ -16,7 +17,10 @@ import com.vayunmathur.todo.platform.TodoViewModel /** Binds a [TodoEditor][com.vayunmathur.todo.platform.TodoEditor] session to the stateless [TodoDetailScreen]. */ @Composable fun TodoDetailPage(backStack: NavBackStack<Route>, viewModel: TodoViewModel, route: Route.TodoDetail) {-    val editor = remember(route) { viewModel.openEditor(route.id, route.newSyncId) }+    // A new task's template (list/tag/date) comes from the list route under this detail.+    val currentView = backStack.backStack.filterIsInstance<Route.TodoList>().lastOrNull()+        ?.let { TodoView.fromKey(it.viewKey) } ?: TodoView.Inbox+    val editor = remember(route, currentView) { viewModel.openEditor(route.id, route.newSyncId, currentView) }     DisposableEffect(editor) { onDispose { editor.close() } }     val todo by editor.state.collectAsStateWithLifecycle()     val subtasks by editor.subtasks.collectAsStateWithLifecycle(emptyList())
todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.ktindex 276df88fe1..3f0da9c0be 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.kt@@ -10,28 +10,35 @@ import com.vayunmathur.todo.data.Todo import com.vayunmathur.todo.data.newSyncId import com.vayunmathur.todo.domain.QuickAddParser import com.vayunmathur.todo.domain.SortMode+import com.vayunmathur.todo.domain.TodoView import com.vayunmathur.todo.platform.TodoListActions import com.vayunmathur.todo.platform.TodoListUiState import com.vayunmathur.todo.platform.TodoViewModel  /** Binds [TodoViewModel] and the nav back stack to the stateless [TodoListScreen]. */ @Composable-fun TodoListPage(backStack: NavBackStack<Route>, viewModel: TodoViewModel, onMenu: (() -> Unit)?) {-    val model by viewModel.model.collectAsStateWithLifecycle()+fun TodoListPage(+    backStack: NavBackStack<Route>,+    viewModel: TodoViewModel,+    route: Route.TodoList,+    onMenu: (() -> Unit)?,+) {+    val view = TodoView.fromKey(route.viewKey)+    val modelFlow = remember(viewModel, view) { viewModel.modelFor(view) }+    val model by modelFlow.collectAsStateWithLifecycle()     val query by viewModel.searchQuery.collectAsStateWithLifecycle()-    val view by viewModel.view.collectAsStateWithLifecycle()     val sort by viewModel.sort.collectAsStateWithLifecycle()     val lists by viewModel.lists.collectAsStateWithLifecycle()     val quickAddRequest by viewModel.quickAddRequest.collectAsStateWithLifecycle() -    val actions = remember(backStack, viewModel, onMenu) {+    val actions = remember(backStack, viewModel, onMenu, view) {         object : TodoListActions {             override fun openTodo(id: Long) { backStack.add(Route.TodoDetail(id)) }             override fun createTodo() { backStack.add(Route.TodoDetail(0, newSyncId())) }             override fun setSearchQuery(query: String) = viewModel.setSearchQuery(query)             override fun openDrawer() { onMenu?.invoke() }             override fun setSort(sort: SortMode) = viewModel.setSort(sort)-            override fun quickAdd(texts: List<String>) = viewModel.quickAdd(texts)+            override fun quickAdd(texts: List<String>) = viewModel.quickAdd(texts, view)             override fun toggleDone(todo: Todo) = viewModel.toggleDone(todo)             override fun delete(todos: List<Todo>) = viewModel.delete(todos)             override fun restore(todos: List<Todo>) = viewModel.restore(todos)@@ -62,7 +69,7 @@ fun TodoListPage(backStack: NavBackStack<Route>, viewModel: TodoViewModel, onMen         QuickAddSheet(             initialText = text,             lists = remember(lists) { lists.map { QuickAddParser.ListName(it.syncId, it.name) } },-            onAdd = viewModel::quickAdd,+            onAdd = { texts -> viewModel.quickAdd(texts, view) },             onDismiss = viewModel::clearQuickAddRequest,         )     }
todo/src/main/java/com/vayunmathur/todo/ui/TodoShell.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoShell.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoShell.ktindex 0191157b3a..659078161a 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoShell.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoShell.kt@@ -37,7 +37,10 @@ fun TodoShell(     backStack: NavBackStack<Route>,     content: @Composable () -> Unit, ) {-    val view by viewModel.view.collectAsStateWithLifecycle()+    // The selected view lives in the back stack: the deepest TodoList entry is+    // the list underneath any detail/settings entry pushed on top of it.+    val currentRoute = backStack.backStack.filterIsInstance<Route.TodoList>().lastOrNull()+    val view = currentRoute?.let { TodoView.fromKey(it.viewKey) } ?: TodoView.Inbox     val counts by viewModel.counts.collectAsStateWithLifecycle()     val lists by viewModel.lists.collectAsStateWithLifecycle()     val tags by viewModel.tags.collectAsStateWithLifecycle()@@ -49,8 +52,8 @@ fun TodoShell(     val state = DrawerUiState(view, counts, lists, tags, syncStatus(lastSync))     val actions = object : DrawerActions {         override fun select(view: TodoView) {-            viewModel.setView(view)-            backStack.reset(Route.TodoList)+            viewModel.clearSearchQuery()+            backStack.reset(Route.TodoList(view.key))             shell.closeDrawer()         }         override fun newList() { creating = true }@@ -83,7 +86,10 @@ fun TodoShell(             list = editing,             onSave = { list ->                 viewModel.saveList(list)-                if (editing == null) viewModel.setView(TodoView.InList(list.syncId))+                if (editing == null) {+                    viewModel.clearSearchQuery()+                    backStack.reset(Route.TodoList(TodoView.InList(list.syncId).key))+                }                 creating = false                 editing = null             },@@ -103,6 +109,9 @@ fun TodoShell(             destructive = true,             onConfirm = {                 viewModel.deleteList(list)+                if (view == TodoView.InList(list.syncId)) {+                    backStack.reset(Route.TodoList(TodoView.Inbox.key))+                }                 deleting = null                 editing = null             },
todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.kt b/todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.ktindex fff4fde08a..b3a3b62aaf 100644--- a/todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.kt+++ b/todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.kt@@ -21,6 +21,8 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.Robolectric@@ -69,8 +71,9 @@ class NavigationAndMainActivityTest {      @Test fun navigationComposesListPageFromRealViewModel() {         seed()+        // The initial Route.TodoList is the settings default view.+        runBlocking { TodoSettings(context).setDefaultView(TodoView.All) }         val vm = viewModel()-        vm.setView(TodoView.All)         rule.setContent { DynamicTheme { Navigation(vm) } }         rule.onNodeWithText("Nav alpha task").assertIsDisplayed()         rule.onNodeWithText("Nav beta task").assertIsDisplayed()@@ -101,7 +104,11 @@ class NavigationAndMainActivityTest {         IntentRouter.handle(Intent().putExtra(IntentRouter.EXTRA_VIEW, TodoView.All.key))         rule.setContent { DynamicTheme { Navigation(vm) } }         rule.waitUntil(timeoutMillis = 5_000) { IntentRouter.pending.value == null }-        assertEquals(TodoView.All, vm.view.value)+        // OpenView reset the stack to Route.TodoList(All.key), so both undated+        // seeded tasks are visible (the dedicated route test below pins the+        // exact viewKey round-trip).+        rule.onNodeWithText("Nav alpha task").assertIsDisplayed()+        rule.onNodeWithText("Nav beta task").assertIsDisplayed()         // A later quick-add request resets to the list and pre-fills the sheet.         rule.runOnIdle {             IntentRouter.handle(@@ -113,7 +120,12 @@ class NavigationAndMainActivityTest {     }      @Test fun routeTypesAreDistinctNavKeys() {-        assertEquals(Route.TodoList, Route.TodoList)+        assertEquals(Route.TodoList(TodoView.All.key), Route.TodoList("all"))+        assertTrue(Route.TodoList(TodoView.All.key) != Route.TodoList(TodoView.Inbox.key))+        // viewKey round-trips through TodoView and through serialization.+        val route = Route.TodoList(TodoView.InList("work").key)+        assertEquals(TodoView.InList("work"), TodoView.fromKey(route.viewKey))+        assertEquals(route, Json.decodeFromString<Route.TodoList>(Json.encodeToString(route)))         assertEquals(Route.Settings, Route.Settings)         assertEquals(Route.TodoDetail(7L, "sync"), Route.TodoDetail(7L, "sync"))         assertTrue(Route.TodoDetail(7L) != Route.TodoDetail(8L))@@ -127,8 +139,9 @@ class NavigationAndMainActivityTest {         val controller = Robolectric.buildActivity(MainActivity::class.java, intent).setup()         // The activity's own Navigation graph consumes the recorded view         // request as soon as it composes.-        org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()-        assertNull(IntentRouter.pending.value)+        // Navigation waits for the settings default view before creating the+        // retained stack, so consumption is asynchronous.+        rule.waitUntil(timeoutMillis = 5_000) { IntentRouter.pending.value == null }         // A fresh intent arriving while alive is recorded the same way and         // likewise recorded by the live activity (its graph may or may not         // have a frame in flight under Robolectric to consume it yet).
todo/src/test/java/com/vayunmathur/todo/platform/IntentRouterTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/platform/IntentRouterTest.kt b/todo/src/test/java/com/vayunmathur/todo/platform/IntentRouterTest.ktindex 4a6cac92a6..614572ba4d 100644--- a/todo/src/test/java/com/vayunmathur/todo/platform/IntentRouterTest.kt+++ b/todo/src/test/java/com/vayunmathur/todo/platform/IntentRouterTest.kt@@ -68,7 +68,10 @@ class IntentRouterTest {         IntentRouter.consume()     }     @Test fun routeTypes() {-        assertEquals(com.vayunmathur.todo.Route.TodoList, com.vayunmathur.todo.Route.TodoList)+        assertEquals(+            com.vayunmathur.todo.Route.TodoList(TodoView.Today.key),+            com.vayunmathur.todo.Route.TodoList("today"),+        )         assertEquals(5L, com.vayunmathur.todo.Route.TodoDetail(5L, "n").id)         assertEquals("n", com.vayunmathur.todo.Route.TodoDetail(5L, "n").newSyncId)         assertNull(com.vayunmathur.todo.Route.TodoDetail(0L).newSyncId)
todo/src/test/java/com/vayunmathur/todo/platform/TodoViewModelTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/platform/TodoViewModelTest.kt b/todo/src/test/java/com/vayunmathur/todo/platform/TodoViewModelTest.ktindex 9c374d5fe1..2bf25520ab 100644--- a/todo/src/test/java/com/vayunmathur/todo/platform/TodoViewModelTest.kt+++ b/todo/src/test/java/com/vayunmathur/todo/platform/TodoViewModelTest.kt@@ -64,7 +64,9 @@ class TodoViewModelTest {         assertTrue(awaitCondition { condition() }, "Timed out waiting for: $description")     } -    @Test fun savedStateRestoresViewSortAndQuery() {+    @Test fun savedStateRestoresSortAndQueryButNotView() {+        // The selected view lives in Route.TodoList, not SavedState: a stale+        // "view" entry must not resurrect a view (there is no view state to read).         val vm = viewModel(             mapOf(                 "search_query" to "report",@@ -73,22 +75,19 @@ class TodoViewModelTest {             ),         )         assertEquals("report", vm.searchQuery.value)-        assertEquals(TodoView.InList("work"), vm.view.value)         assertEquals(SortMode.TITLE, vm.sort.value)     } -    @Test fun invalidSavedSortFallsBackToManualAndUnknownViewToInbox() {-        val vm = viewModel(mapOf("view" to "nonsense", "sort" to "not-a-sort"))-        assertEquals(TodoView.Inbox, vm.view.value)+    @Test fun invalidSavedSortFallsBackToManual() {+        val vm = viewModel(mapOf("sort" to "not-a-sort"))         assertEquals(SortMode.MANUAL, vm.sort.value)     } -    @Test fun setViewClearsSearchAndSetSortAndQueryUpdateState() {+    @Test fun clearSearchQueryAndSetSortAndQueryUpdateState() {         val vm = viewModel()         vm.setSearchQuery("milk")         assertEquals("milk", vm.searchQuery.value)-        vm.setView(TodoView.Today)-        assertEquals(TodoView.Today, vm.view.value)+        vm.clearSearchQuery()         assertEquals("", vm.searchQuery.value)         vm.setSort(SortMode.PRIORITY)         assertEquals(SortMode.PRIORITY, vm.sort.value)@@ -108,8 +107,7 @@ class TodoViewModelTest {     @Test fun quickAddCreatesParsedTaskInCurrentListContext() { runBlocking {         repo.upsertList(TodoList(syncId = "home", name = "Home"))         val vm = viewModel()-        vm.setView(TodoView.InList("home"))-        vm.quickAdd(listOf("Buy milk tomorrow #errands", "  ", ""))+        vm.quickAdd(listOf("Buy milk tomorrow #errands", "  ", ""), TodoView.InList("home"))         await("quick add writes one task") { repo.getAll().size == 1 }         val task = repo.getAll().single()         assertEquals("Buy milk", task.title)@@ -120,21 +118,18 @@ class TodoViewModelTest {      @Test fun quickAddInTodayViewDatesTaskTodayAndInPriorityViewPrioritises() = runBlocking {         val vm = viewModel()-        vm.setView(TodoView.Today)-        vm.quickAdd(listOf("Call plumber"))+        vm.quickAdd(listOf("Call plumber"), TodoView.Today)         await("today quick add") { repo.getAll().any { it.title == "Call plumber" } }         assertNotNull(repo.getAll().first { it.title == "Call plumber" }.dueAt) -        vm.setView(TodoView.Priority)-        vm.quickAdd(listOf("Urgent fix"))+        vm.quickAdd(listOf("Urgent fix"), TodoView.Priority)         await("priority quick add") { repo.getAll().any { it.title == "Urgent fix" } }         assertEquals(1, repo.getAll().first { it.title == "Urgent fix" }.priority)     }      @Test fun quickAddInTaggedViewAppliesTheTag() = runBlocking {         val vm = viewModel()-        vm.setView(TodoView.Tagged("errands"))-        vm.quickAdd(listOf("Post parcel"))+        vm.quickAdd(listOf("Post parcel"), TodoView.Tagged("errands"))         await("tagged quick add") { repo.getAll().size == 1 }         assertEquals(listOf("errands"), repo.getAll().single().tags)     }@@ -190,21 +185,20 @@ class TodoViewModelTest {         assertTrue(repo.getAll().isEmpty())     } -    @Test fun saveListAssignsPositionToNewListAndDeleteListResetsView() = runBlocking {+    @Test fun saveListAssignsPositionToNewListAndDeleteListTombstonesIt() = runBlocking {         val vm = viewModel()         vm.saveList(TodoList(syncId = "work", name = "Work"))         await("save list") { repo.getListBySyncId("work") != null }         val saved = repo.getListBySyncId("work")!!         assertTrue(saved.position != 0.0 || repo.getLists().size == 1) -        vm.setView(TodoView.InList("work"))         vm.deleteList(saved)         await("delete list") {             runCatching { harness!!.database.todoListDao().getBySyncId("work")!!.deleted }                 .getOrDefault(false)         }-        // Deleting the list being viewed returns the user to the Inbox.-        assertEquals(TodoView.Inbox, vm.view.value)+        // Resetting the route to Inbox when the viewed list is deleted is the+        // shell's job (it owns the back stack), not the ViewModel's.     }      @Test fun reorderListsPersistsGivenOrder() = runBlocking {@@ -232,12 +226,12 @@ class TodoViewModelTest {         repo.upsert(Todo(syncId = "a", title = "Report", listSyncId = "work", tags = listOf("office")))         repo.upsert(Todo(syncId = "b", title = "Done", done = true, completedAt = 1L, tags = listOf("home")))         val vm = viewModel()-        vm.setView(TodoView.All)+        val model = vm.modelFor(TodoView.All)          // StateFlows are WhileSubscribed: collect them, then wait for real values.         val todosJob = launch { vm.todos.collect {} }         val listsJob = launch { vm.lists.collect {} }-        val modelJob = launch { vm.model.collect {} }+        val modelJob = launch { model.collect {} }         val countsJob = launch { vm.counts.collect {} }         val tagsJob = launch { vm.tags.collect {} }         try {@@ -246,7 +240,7 @@ class TodoViewModelTest {             await("tags flow") { vm.tags.value.containsAll(listOf("office", "home")) }             await("counts") { vm.counts.value.values.sum() >= 1 }             await("model") {-                vm.model.value.first.groups.flatMap { it.rows }.any { it.todo.syncId == "a" }+                model.value.first.groups.flatMap { it.rows }.any { it.todo.syncId == "a" }             }             assertEquals(1, vm.counts.value[TodoView.InList("work")])             assertFalse(TodoView.All in vm.counts.value.keys)@@ -255,20 +249,47 @@ class TodoViewModelTest {         }     } +    @Test fun modelForComputesPerRouteView() = runBlocking {+        repo.upsertList(TodoList(syncId = "work", name = "Work"))+        repo.upsert(Todo(syncId = "in", title = "In inbox"))+        repo.upsert(Todo(syncId = "wk", title = "In work", listSyncId = "work"))+        val vm = viewModel()+        val inboxModel = vm.modelFor(TodoView.Inbox)+        val workModel = vm.modelFor(TodoView.InList("work"))+        val inboxJob = launch { inboxModel.collect {} }+        val workJob = launch { workModel.collect {} }+        try {+            await("inbox model") {+                inboxModel.value.first.groups.flatMap { it.rows }.any { it.todo.syncId == "in" }+            }+            await("work model") {+                workModel.value.first.groups.flatMap { it.rows }.any { it.todo.syncId == "wk" }+            }+            assertTrue(+                inboxModel.value.first.groups.flatMap { it.rows }.none { it.todo.syncId == "wk" },+            )+            assertTrue(+                workModel.value.first.groups.flatMap { it.rows }.none { it.todo.syncId == "in" },+            )+        } finally {+            inboxJob.cancel(); workJob.cancel()+        }+    }+     @Test fun modelHidesCompletedWhenSettingOff() = runBlocking {         repo.upsert(Todo(syncId = "open", title = "Open"))         repo.upsert(Todo(syncId = "done", title = "Done", done = true, completedAt = 1L))         val vm = viewModel()-        vm.setView(TodoView.All)+        val model = vm.modelFor(TodoView.All)         vm.updateSettings { setShowCompleted(false) }-        val job = launch { vm.model.collect {} }+        val job = launch { model.collect {} }         try {             await("completed row hidden") {-                vm.model.value.first.groups.flatMap { it.rows }.any { it.todo.syncId == "open" } &&-                    vm.model.value.first.completed.isEmpty()+                model.value.first.groups.flatMap { it.rows }.any { it.todo.syncId == "open" } &&+                    model.value.first.completed.isEmpty()             }             assertTrue(-                vm.model.value.first.groups.flatMap { it.rows }.any { it.todo.syncId == "open" },+                model.value.first.groups.flatMap { it.rows }.any { it.todo.syncId == "open" },             )         } finally {             job.cancel()@@ -302,12 +323,11 @@ class TodoViewModelTest {     @Test fun openEditorForExistingAndNewTasks() = runBlocking {         repo.upsert(Todo(syncId = "a", title = "Existing"))         val vm = viewModel()-        val existing = vm.openEditor(repo.getBySyncId("a")!!.id, null)+        val existing = vm.openEditor(repo.getBySyncId("a")!!.id, null, TodoView.Inbox)         await("editor loads existing") { existing.state.value?.title == "Existing" }         existing.close() -        vm.setView(TodoView.InList("work"))-        val fresh = vm.openEditor(0L, "brand-new-sync")+        val fresh = vm.openEditor(0L, "brand-new-sync", TodoView.InList("work"))         await("editor loads template") { fresh.state.value != null }         assertEquals("brand-new-sync", fresh.state.value!!.syncId)         assertEquals("work", fresh.state.value!!.listSyncId)
todo/src/test/java/com/vayunmathur/todo/ui/TodoComposePagesTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/ui/TodoComposePagesTest.kt b/todo/src/test/java/com/vayunmathur/todo/ui/TodoComposePagesTest.ktindex 886454a844..a1b596a90e 100644--- a/todo/src/test/java/com/vayunmathur/todo/ui/TodoComposePagesTest.kt+++ b/todo/src/test/java/com/vayunmathur/todo/ui/TodoComposePagesTest.kt@@ -112,9 +112,9 @@ class TodoComposePagesTest {     @Test fun todoListPageShowsSeededTasksAndViewTitle() {         seed()         val vm = viewModel()-        vm.setView(TodoView.All)-        val stack = NavBackStack<Route>(arrayOf(Route.TodoList))-        rule.setContent { DynamicTheme { TodoListPage(stack, vm, onMenu = {}) } }+        val route = Route.TodoList(TodoView.All.key)+        val stack = NavBackStack<Route>(arrayOf(route))+        rule.setContent { DynamicTheme { TodoListPage(stack, vm, route, onMenu = {}) } }         rule.onNodeWithText("Page task alpha").assertIsDisplayed()         rule.onNodeWithText("Page task beta").assertIsDisplayed()     }@@ -122,8 +122,9 @@ class TodoComposePagesTest {     @Test fun todoListPageQuickAddRequestShowsSheet() {         seed()         val vm = viewModel()-        val stack = NavBackStack<Route>(arrayOf(Route.TodoList))-        rule.setContent { DynamicTheme { TodoListPage(stack, vm, onMenu = null) } }+        val route = Route.TodoList(TodoView.Inbox.key)+        val stack = NavBackStack<Route>(arrayOf(route))+        rule.setContent { DynamicTheme { TodoListPage(stack, vm, route, onMenu = null) } }         rule.runOnIdle { vm.requestQuickAdd("Sheet task") }         rule.onNodeWithText("Sheet task").assertExists()     }@@ -135,7 +136,7 @@ class TodoComposePagesTest {         }         val vm = viewModel()         val id = runBlocking { repo.getBySyncId("p")!!.id }-        val stack = NavBackStack<Route>(arrayOf(Route.TodoList, Route.TodoDetail(id)))+        val stack = NavBackStack<Route>(arrayOf(Route.TodoList(TodoView.Inbox.key), Route.TodoDetail(id)))         rule.setContent { DynamicTheme { TodoDetailPage(stack, vm, Route.TodoDetail(id)) } }         rule.onNodeWithText("Detail parent").assertIsDisplayed()         rule.onNodeWithText("Detail child").assertExists()@@ -143,7 +144,7 @@ class TodoComposePagesTest {      @Test fun todoDetailPageForNewTaskShowsTitleField() {         val vm = viewModel()-        val stack = NavBackStack<Route>(arrayOf(Route.TodoList, Route.TodoDetail(0, "fresh-page")))+        val stack = NavBackStack<Route>(arrayOf(Route.TodoList(TodoView.Inbox.key), Route.TodoDetail(0, "fresh-page")))         rule.setContent { DynamicTheme { TodoDetailPage(stack, vm, Route.TodoDetail(0, "fresh-page")) } }         // The page returns early until the editor's async load lands.         rule.waitUntil(timeoutMillis = 5_000) {@@ -174,16 +175,16 @@ class TodoComposePagesTest {     @Test fun todoShellShowsDrawerContentAndLists() {         seed()         val vm = viewModel()-        // Default view resolves to Today, which filters out the undated-        // seeded tasks; All shows them in the shell's list pane.-        vm.setView(TodoView.All)-        val stack = NavBackStack<Route>(arrayOf(Route.TodoList))+        // The route names All, which shows the undated seeded tasks in the+        // shell's list pane (Today would filter them out).+        val route = Route.TodoList(TodoView.All.key)+        val stack = NavBackStack<Route>(arrayOf(route))         lateinit var shell: TodoShellState         rule.setContent {             DynamicTheme {                 shell = rememberTodoShellState()                 TodoShell(shell, vm, stack) {-                    TodoListPage(stack, vm, onMenu = {})+                    TodoListPage(stack, vm, route, onMenu = {})                 }             }         }@@ -195,21 +196,21 @@ class TodoComposePagesTest {      @Test fun todoShellSelectsSmartViewThroughDrawerActions() {         val vm = viewModel()-        val stack = NavBackStack<Route>(arrayOf(Route.TodoList))+        val stack = NavBackStack<Route>(arrayOf(Route.TodoList(TodoView.Inbox.key)))+        lateinit var shell: TodoShellState         rule.setContent {             DynamicTheme {-                val shell = rememberTodoShellState()+                shell = rememberTodoShellState()                 TodoShell(shell, vm, stack) {                     com.vayunmathur.library.ui.Text("content")                 }-                // Expose the shell so the test can open the drawer if needed.-                androidx.compose.runtime.SideEffect { }             }         }         rule.onNodeWithText("content").assertIsDisplayed()-        assertEquals(TodoView.Inbox, vm.view.value)-        rule.runOnIdle { vm.setView(TodoView.Today) }-        assertEquals(TodoView.Today, vm.view.value)-        assertTrue(stack.last() == Route.TodoList)+        assertEquals(Route.TodoList(TodoView.Inbox.key), stack.last())+        // Drawer selection is a route reset carrying the view key.+        rule.runOnIdle { shell.openDrawer() }+        rule.onNodeWithText("Today").performClick()+        assertEquals(Route.TodoList(TodoView.Today.key), stack.last())     } }