weather: carry active location in Route.Home(locationId) (#nav)
- Commit
b13fe69ecb9741444060b5ee28e0a29bee916730- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 20:04 UTC (19 days ago)
- Parents
ac619bb
Replace HomePage's remember { mutableStateOf(locations.first().id) }
active-location selection with the back stack: Route.Home is now a
data class with a nullable locationId (null = default/first saved
location, which also keeps old serialized Home entries decodable).
Navigation passes the route arg into HomePage, which resolves a
null or since-deleted id to the first location. Drawer selection
rewrites the top route (setLast when Home is on top, reset
otherwise) instead of mutating local state, so the selection
survives rotation/process recreation and stays in exactly one
place: the stack.
SearchLocation previously just popped back to whatever Home held;
picking a result now resets Route.Home(newId). WeatherViewModel
.addLocation reports the inserted (or exact-duplicate existing)
row id so that navigation can target it.
Tests: Route.Home serialization round-trips for the default and
locationId=42; new tests pin that drawer selection lives in the
back stack, that the route arg selects Paris over the first
location, and that addLocation reports new and duplicate ids.
Verified: ./gradlew :weather:compileDevKotlin :weather:testDevUnitTestDiff
weather/src/main/java/com/vayunmathur/weather/Navigation.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/Navigation.kt b/weather/src/main/java/com/vayunmathur/weather/Navigation.ktindex 4da53fff63..fd8373d1ba 100644--- a/weather/src/main/java/com/vayunmathur/weather/Navigation.kt+++ b/weather/src/main/java/com/vayunmathur/weather/Navigation.kt@@ -11,13 +11,13 @@ import com.vayunmathur.weather.ui.WeatherMapPage @Composable fun Navigation(viewModel: WeatherViewModel) {- val backStack = rememberNavBackStack<Route>(Route.Home)+ val backStack = rememberNavBackStack<Route>(Route.Home()) // No list-detail metadata: Home is not a list and the map is not its // detail, so every destination is a full-screen push. Marking both as // list panes squeezed the forecast into a narrow pane beside an empty // void on wide windows (same shape as web #864). MainNavigation(backStack) {- entry<Route.Home> { HomePage(backStack, viewModel) }+ entry<Route.Home> { HomePage(backStack, viewModel, it.locationId) } entry<Route.SearchLocation>(metadata = DialogPage()) { SearchLocationPage(backStack, viewModel) } entry<Route.WeatherMap> { WeatherMapPage(backStack, it.latitude, it.longitude, it.isoTime, it.metric)
weather/src/main/java/com/vayunmathur/weather/Route.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/Route.kt b/weather/src/main/java/com/vayunmathur/weather/Route.ktindex 00e968283f..094e50fb7d 100644--- a/weather/src/main/java/com/vayunmathur/weather/Route.kt+++ b/weather/src/main/java/com/vayunmathur/weather/Route.kt@@ -6,9 +6,15 @@ import kotlinx.serialization.Serializable /** Contract for route. */ @Serializable sealed interface Route : NavKey {- /** Singleton holding home state and operations. */+ /**+ * Home forecast for [locationId]. Null (the start destination and any+ * restored entry without a selection) means the first saved location;+ * [com.vayunmathur.weather.ui.HomePage] resolves null โ and any id whose+ * row was deleted โ to that first location, so the selection lives+ * exactly here in the back stack, never in remembered UI state.+ */ @Serializable- data object Home : Route+ data class Home(val locationId: Long? = null) : Route /** Singleton holding search location state and operations. */ @Serializable
weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.ktindex 10455c7e1e..81f3a21fac 100644--- a/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt+++ b/weather/src/main/java/com/vayunmathur/weather/platform/WeatherViewModel.kt@@ -234,7 +234,18 @@ class WeatherViewModel( } } - fun addLocation(name: String, country: String, latitude: Double, longitude: Double) {+ /**+ * Adds (or, for an exact-coordinate duplicate, re-selects) a location.+ * [onAdded] receives the new or existing row id so the caller can put+ * the selection in the back stack as `Route.Home(id)`.+ */+ fun addLocation(+ name: String,+ country: String,+ latitude: Double,+ longitude: Double,+ onAdded: (Long) -> Unit = {},+ ) { viewModelScope.launch { addMutex.withLock { val existing = repository.getLocations()@@ -243,10 +254,14 @@ class WeatherViewModel( // only ever matches true duplicates โ never two distinct // nearby places. The live-GPS row is excluded: pinning the // city you're standing in is deliberate, not a duplicate.- if (existing.any { !it.isCurrent && it.latitude == latitude && it.longitude == longitude }) {+ val duplicate = existing.firstOrNull {+ !it.isCurrent && it.latitude == latitude && it.longitude == longitude+ }+ if (duplicate != null) {+ onAdded(duplicate.id) return@withLock }- repository.insertLocation(+ val newId = repository.insertLocation( SavedLocation( name = name, country = country,@@ -256,6 +271,7 @@ class WeatherViewModel( isCurrent = false, ) )+ onAdded(newId) } } }
weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.ktindex 0710ddbfee..25188317db 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt@@ -38,9 +38,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext@@ -76,10 +73,18 @@ import com.vayunmathur.weather.platform.rememberDisplayUnits import kotlinx.coroutines.delay import kotlinx.coroutines.launch -/** Binds [WeatherViewModel] and the back stack to the stateless [HomeScreen]. */+/**+ * Binds [WeatherViewModel] and the back stack to the stateless [HomeScreen].+ * [locationId] is the selected location carried by `Route.Home`; null (or a+ * since-deleted id) resolves to the first saved location.+ */ @OptIn(ExperimentalMaterial3Api::class) @Composable-fun HomePage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) {+fun HomePage(+ backStack: NavBackStack<Route>,+ viewModel: WeatherViewModel,+ locationId: Long? = null,+) { val locations = viewModel.savedLocations.collectAsState().value if (locations == null) {@@ -100,8 +105,7 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) { return } - var activeLocationId by remember { mutableStateOf(locations.first().id) }- val activeLocation = locations.firstOrNull { it.id == activeLocationId } ?: locations.first()+ val activeLocation = locations.firstOrNull { it.id == locationId } ?: locations.first() val forecasts by viewModel.forecasts.collectAsState() val selected by viewModel.selectedDateOrTime.collectAsState()@@ -165,7 +169,13 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: WeatherViewModel) { viewModel = viewModel, activeLocation = activeLocation, onLocationSelect = { picked ->- activeLocationId = picked.id+ // The selection lives exactly in the back stack: rewrite+ // the current Home entry (never push a second Home).+ if (backStack.backStack.lastOrNull() is Route.Home) {+ backStack.setLast(Route.Home(picked.id))+ } else {+ backStack.reset(Route.Home(picked.id))+ } viewModel.clearSelection() closeDrawer() },
weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.ktindex 9ba09bd82b..cc0943e3ef 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/SearchLocationPage.kt@@ -53,7 +53,8 @@ import kotlinx.coroutines.flow.flow * Search-location screen registered as a `DialogPage()` route entry. * Hosted by Navigation3's `DialogSceneStrategy` so it renders as a system * dialog instead of a full page. Picking a result inserts the location- * and pops the back stack.+ * and resets the back stack to `Route.Home(newId)` so the new location is+ * the selected one. */ @OptIn( ExperimentalMaterial3Api::class,@@ -184,8 +185,12 @@ fun SearchLocationPage(backStack: NavBackStack<Route>, viewModel: WeatherViewMod country = r.country.orEmpty(), latitude = r.latitude, longitude = r.longitude,- )- backStack.pop()+ ) { newId ->+ // Select the added location in the+ // stack itself (replaces this dialog+ // entry and any default Home beneath).+ backStack.reset(Route.Home(newId))+ } }, ) }
weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt b/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.ktindex 88a7933ee6..9e3bb15005 100644--- a/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/platform/ViewModelFetchTest.kt@@ -196,6 +196,19 @@ class ViewModelAddLocationTest { assertEquals(1, repo.rows.value.size, "rows=${repo.rows.value}") } + @Test fun addLocationCallbackReportsNewAndDuplicateIds() {+ var addedId: Long? = null+ vm.addLocation("Berlin", "Germany", 52.52006, 13.40495) { addedId = it }+ drainMain()+ assertEquals(100L, addedId)+ // A duplicate tap re-selects the existing row instead of adding one.+ var duplicateId: Long? = null+ vm.addLocation("Berlin", "Germany", 52.52006, 13.40495) { duplicateId = it }+ drainMain()+ assertEquals(100L, duplicateId)+ assertEquals(1, repo.rows.value.size, "rows=${repo.rows.value}")+ }+ @Test fun distinctNearbyPlacesBothKept() { vm.addLocation("Home", "Germany", 52.52006, 13.40495) vm.addLocation("Office", "Germany", 52.52007, 13.40496)
weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.ktindex e7bdacac62..c445ec470e 100644--- a/weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/ui/ComposeScreensTest.kt@@ -239,8 +239,16 @@ class ComposeScreensTest { @Test fun routeSerialization() { val json = Json { ignoreUnknownKeys = true }- val home = json.encodeToString(Route.serializer(), Route.Home)- assertEquals(Route.Home, json.decodeFromString(Route.serializer(), home))+ // Default Home carries no selection (null -> first saved location).+ val home = json.encodeToString(Route.serializer(), Route.Home())+ assertEquals(Route.Home(), json.decodeFromString(Route.serializer(), home))+ assertEquals(null, Route.Home().locationId)+ // A selected location round-trips through the route arg.+ val selected = Route.Home(locationId = 42L)+ val decodedHome = json.decodeFromString(+ Route.serializer(), json.encodeToString(Route.serializer(), selected),+ ) as Route.Home+ assertEquals(42L, decodedHome.locationId) val map = Route.WeatherMap(52.5, 13.4, "Berlin", "2026-07-15T14:00", "Temperature") val decoded = json.decodeFromString( Route.serializer(), json.encodeToString(Route.serializer(), map),
weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.ktindex fc30dfb67d..5881e3254a 100644--- a/weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/ui/HomeAndLocationsExtraTest.kt@@ -87,7 +87,7 @@ class HomeAndLocationsExtraTest { @Test fun homePageHoldsPlaceholderWhileLocationsLoad() { val repo = NeverLocationsRepository(app) val vm = WeatherViewModel(app, repo)- val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home())) rule.setContent { HomePage(backStack, vm) } rule.waitForIdle() // Neither the empty state nor a forecast is shown yet.
weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.ktindex c63d1f84e8..58b94b7274 100644--- a/weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/ui/MapPageTest.kt@@ -14,7 +14,7 @@ class MapPageTest { @get:Rule val rule = createComposeRule() @Test fun weatherMapPageRenders() {- val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home())) rule.setContent { WeatherMapPage(backStack, 52.5, 13.4, "2026-07-15T14:00", "Temperature") }@@ -22,7 +22,7 @@ class MapPageTest { } @Test fun weatherMapPageBadMetricRenders() {- val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home())) rule.setContent { WeatherMapPage(backStack, 0.0, 0.0, null, "bogus") }
weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.ktindex 017652d922..1736115f95 100644--- a/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/ui/PagesTest.kt@@ -78,7 +78,7 @@ class PagesTest { ) @Test fun homePageEmptyStateNavigatesToSearch() {- val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home())) rule.setContent { HomePage(backStack, vm) } rule.onNodeWithText("No locations yet").assertIsDisplayed() rule.onNodeWithText("Add a location").performClick()@@ -89,15 +89,23 @@ class PagesTest { repo.rows.value = listOf(loc()) // Seed a forecast directly so the column renders without network. vm.ensureForecast(loc())- val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home())) rule.setContent { HomePage(backStack, vm) } rule.waitForIdle() rule.onAllNodesWithText("Berlin", substring = true)[0].assertIsDisplayed() } + @Test fun homePageShowsLocationSelectedByRouteArg() {+ repo.rows.value = listOf(loc(1, "Berlin"), loc(2, "Paris"))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home(locationId = 2L)))+ rule.setContent { HomePage(backStack, vm, locationId = 2L) }+ rule.waitForIdle()+ rule.onAllNodesWithText("Paris", substring = true)[0].assertIsDisplayed()+ }+ @Test fun locationsPageRendersRows() { repo.rows.value = listOf(loc(1, "Berlin"), loc(2, "Paris"))- val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home())) rule.setContent { LocationsPage( backStack = backStack, viewModel = vm, activeLocation = loc(),@@ -109,7 +117,7 @@ class PagesTest { } @Test fun searchPageTypingShowsField() {- val backStack = NavBackStack<Route>(arrayOf(Route.Home, Route.SearchLocation))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home(), Route.SearchLocation)) rule.setContent { SearchLocationPage(backStack, vm) } rule.onNodeWithText("Search location").assertIsDisplayed() rule.onNodeWithText("City name").performTextInput("Ber")@@ -161,11 +169,24 @@ class PagesTest { } @Test fun navigationRoutesConstruct() {- val stack = NavBackStack<Route>(arrayOf(Route.Home))+ val stack = NavBackStack<Route>(arrayOf(Route.Home())) stack.add(Route.WeatherMap(52.0, 13.0, "Berlin", null, "Temperature")) assertEquals("Berlin", (stack.last() as Route.WeatherMap).name) stack.pop()- assertEquals(Route.Home, stack.last())+ assertEquals(Route.Home(), stack.last())+ }++ @Test fun homeLocationSelectionLivesInBackStack() {+ // Drawer selection rewrites the Home entry in place (setLast), it+ // never pushes a second Home; the arg is the selected location id.+ val stack = NavBackStack<Route>(arrayOf(Route.Home()))+ stack.setLast(Route.Home(locationId = 7L))+ assertEquals(1, stack.backStack.size)+ assertEquals(7L, (stack.last() as Route.Home).locationId)+ // Search-add selection resets the stack to the new location's Home.+ stack.add(Route.SearchLocation)+ stack.reset(Route.Home(locationId = 9L))+ assertEquals(listOf(Route.Home(locationId = 9L)), stack.backStack.toList()) } }
weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.ktindex b6433e51b2..b71d719647 100644--- a/weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/ui/Wave3WeatherCoverageTest.kt@@ -319,7 +319,7 @@ class Wave3WeatherCoverageTest { rule.setContent { Navigation(vm) } rule.waitForIdle() assertTrue(rule.onAllNodesWithText("Berlin", substring = true).fetchSemanticsNodes().isNotEmpty())- val stack = NavBackStack<Route>(arrayOf(Route.Home))- assertEquals(Route.Home, stack.last())+ val stack = NavBackStack<Route>(arrayOf(Route.Home()))+ assertEquals(Route.Home(), stack.last()) } }
weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.kt b/weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.ktindex 17b632f405..173a1c1267 100644--- a/weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/ui/Wave3bWeatherCoverageTest.kt@@ -59,7 +59,7 @@ class Wave3bWeatherCoverageTest { SavedLocation(2, "Paris", "France", 48.85, 2.35), ) val vm = WeatherViewModel(app, repo)- val stack = NavBackStack<Route>(arrayOf(Route.Home))+ val stack = NavBackStack<Route>(arrayOf(Route.Home())) rule.setContent { HomePage(stack, vm) } rule.waitForIdle() // Tapping the search bar opens the locations drawer (LocationsPage binding).@@ -72,7 +72,7 @@ class Wave3bWeatherCoverageTest { } @Test fun weatherMapPageMeasureSelectorInteraction() {- val stack = NavBackStack<Route>(arrayOf(Route.Home))+ val stack = NavBackStack<Route>(arrayOf(Route.Home())) rule.setContent { WeatherMapPage(stack, 52.5, 13.4, "2026-07-15T14:00", "Temperature") } rule.waitForIdle() rule.mainClock.advanceTimeBy(3_000)@@ -122,7 +122,7 @@ class Wave3bWeatherCoverageTest { val repo = FakeRepository(app) repo.rows.value = listOf(SavedLocation(1, "Berlin", "Germany", 52.5, 13.4)) val vm = WeatherViewModel(app, repo)- val stack = NavBackStack<Route>(arrayOf(Route.Home))+ val stack = NavBackStack<Route>(arrayOf(Route.Home())) // Forecast with no current: headline/blocks skipped, hourly/daily remain. rule.setContent { HomePage(stack, vm) } rule.waitForIdle()