maps: give search, routing and departures real loading states
- Commit
3ab285e99490e3bcc20debd9317b1c85fdc6c17b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 17:23 UTC (3 months ago)
- Parents
df2a6fd
Diff
maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.ktindex c574eb24ca..f441732849 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -15,6 +15,7 @@ import com.vayunmathur.library.ui.ButtonDefaults import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.PrimaryTabRow import com.vayunmathur.library.ui.Tab@@ -109,11 +110,21 @@ fun BottomSheetContent( } } is SpecificFeature.Route -> {- if(route != null) {+ val currentRoute = route+ if (currentRoute != null) { val userPosition by viewModel.userPosition.collectAsState()- RouteSheet(selectedFeature, route, selectedRouteType, setSelectedRouteType, navState, userPosition)+ RouteSheet(selectedFeature, currentRoute, selectedRouteType, setSelectedRouteType, navState, userPosition)+ } else {+ // Routes arrive asynchronously and start out null, so this is the state right+ // after asking for directions. It used to render nothing at all, inside a sheet+ // whose peek height is fixed — so the user got a blank card and no reason to+ // believe anything was happening. RouteSheet has a "generating" placeholder of+ // its own, but it was unreachable from here.+ LoadingState(message = stringResource(R.string.generating_route)) } }+ // `RoutableFeature` is an intermediate sealed interface, so this cannot be made+ // exhaustive over the leaves; `else` covers null and any future subtype. else -> Unit } }
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktindex c8c470aeca..bbfca329b0 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -25,7 +25,9 @@ import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconRefresh import com.vayunmathur.library.ui.MaterialTheme@@ -94,20 +96,17 @@ fun DeparturesSheet( Spacer(Modifier.height(8.dp)) when (state) {- is DeparturesState.Loading, DeparturesState.Idle -> {- Text(- stringResource(R.string.transit_departures_loading),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }+ // Loading and Idle were collapsed into one branch, both showing "loading" —+ // so a board that had not been asked for yet claimed to be fetching. Idle is+ // only reachable transiently as the sheet opens, and showing nothing for that+ // frame is more honest than showing a spinner for a request nobody made.+ is DeparturesState.Loading -> LoadingState(+ message = stringResource(R.string.transit_departures_loading),+ )+ DeparturesState.Idle -> Unit is DeparturesState.Loaded -> { if (state.departures.isEmpty()) {- Text(- stringResource(R.string.transit_departures_none),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )+ EmptyState(title = stringResource(R.string.transit_departures_none)) } else { DepartureList(state.departures, now) }
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 08a1520216..7c8b6793a9 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -168,6 +168,12 @@ fun MapPage( if (isNavigating) sheetState.hide() } + // Nothing selected means the sheet has nothing to draw, and its peek height is fixed — so+ // leaving it up would show a blank card rather than collapsing.+ LaunchedEffect(selectedFeature) {+ if (selectedFeature == null) sheetState.hide()+ }+ NavigationCameraFollow(camera, chrome, navProgress, isNavigating) // Poll the posted limit under the puck. Inert until the maxspeed tileset is hosted.
maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.ktindex 8dee0bef7d..ccfd9ff3ae 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt@@ -16,6 +16,8 @@ import com.vayunmathur.library.ui.AssistChip import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextField@@ -44,6 +46,7 @@ import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.SearchActions import com.vayunmathur.maps.util.SearchResult+import com.vayunmathur.maps.util.SearchPhase import com.vayunmathur.maps.util.SearchUiState import com.vayunmathur.maps.util.SelectedFeatureViewModel @@ -69,6 +72,7 @@ fun SearchPage( val searchQuery by searchViewModel.query.collectAsState() val results by searchViewModel.results.collectAsState() val recents by searchViewModel.recents.collectAsState()+ val searching by searchViewModel.searching.collectAsState() val savedHome by savedPlacesViewModel.home.collectAsState() val savedWork by savedPlacesViewModel.work.collectAsState() @@ -138,7 +142,10 @@ fun SearchPage( } } - SearchScreen(SearchUiState(searchQuery, results, recents, savedHome, savedWork), actions)+ SearchScreen(+ SearchUiState(searchQuery, results, recents, savedHome, savedWork, searching),+ actions,+ ) } /** The rendered half of [SearchPage]: query text in, results out, no ViewModel. */@@ -199,28 +206,22 @@ fun SearchScreen(state: SearchUiState, actions: SearchActions) { ) } Box(modifier = Modifier.fillMaxSize()) {- when {- state.query.length >= 2 && state.results.isEmpty() -> {- Text(- text = stringResource(R.string.no_results_found),- modifier = Modifier.align(Alignment.Center),- style = MaterialTheme.typography.bodyLarge- )- }- state.query.length >= 2 -> {- ResultsList(state.results, actions)- }- state.recents.isNotEmpty() -> {- RecentsList(state.recents, actions)- }- else -> {- Text(- text = stringResource(R.string.type_to_search),- modifier = Modifier.align(Alignment.Center),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant- )- }+ when (state.phase) {+ SearchPhase.Searching -> LoadingState(+ modifier = Modifier.align(Alignment.Center),+ )+ SearchPhase.Empty -> EmptyState(+ title = stringResource(R.string.no_results_found),+ modifier = Modifier.align(Alignment.Center),+ )+ SearchPhase.Results -> ResultsList(state.results, actions)+ SearchPhase.Recents -> RecentsList(state.recents, actions)+ SearchPhase.Idle -> Text(+ text = stringResource(R.string.type_to_search),+ modifier = Modifier.align(Alignment.Center),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ ) } } }
maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.ktindex 594a1bf7a6..beefe4b720 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -69,6 +69,18 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati private val _results = MutableStateFlow<List<SearchResult>>(emptyList()) val results: StateFlow<List<SearchResult>> = _results.asStateFlow() + /**+ * Whether a search is in flight.+ *+ * The view cannot infer this. "Query is long enough and results are empty" is true both+ * while a search runs and after one comes back with nothing, and the search page read it as+ * the second — so it showed "No results found" for the whole debounce plus the offline+ * lookup plus the network round-trip, then replaced it with the results. Only the thing+ * running the search knows which it is, so it is the thing that has to say.+ */+ private val _searching = MutableStateFlow(false)+ val searching: StateFlow<Boolean> = _searching.asStateFlow()+ /** Recent queries, most-recent first, for the pre-search suggestions. */ val recents: StateFlow<List<String>> = recentStore.recents .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), recentStore.current())@@ -90,30 +102,41 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati searchJob?.cancel() if (query.length < 2) { _results.value = emptyList()+ _searching.value = false return }+ // Set before the launch, not inside it: a coroutine does not necessarily start before+ // the next recomposition, and a frame rendered in that gap is the bug all over again.+ _searching.value = true searchJob = viewModelScope.launch {- delay(250)- // Try the offline OSM POI index first (P27): resolving a POI name- // locally avoids a Google call. Google stays the fallback (and- // handles addresses, which the POI index doesn't carry). Any offline- // failure (unmapped/poisoned index, decode error) is swallowed so the- // query still falls through to Google.- val app = getApplication<Application>()- val offline = withContext(Dispatchers.IO) {- runCatching {- PoiIndex.initialize(app)- PoiIndex.searchByName(query, nearLat, nearLon, limit = 20)- }.getOrDefault(emptyList())- }- if (offline.isNotEmpty()) {- _results.value = offline.map { it.toSearchResult() }- return@launch+ try {+ delay(250)+ // Try the offline OSM POI index first (P27): resolving a POI name+ // locally avoids a Google call. Google stays the fallback (and+ // handles addresses, which the POI index doesn't carry). Any offline+ // failure (unmapped/poisoned index, decode error) is swallowed so the+ // query still falls through to Google.+ val app = getApplication<Application>()+ val offline = withContext(Dispatchers.IO) {+ runCatching {+ PoiIndex.initialize(app)+ PoiIndex.searchByName(query, nearLat, nearLon, limit = 20)+ }.getOrDefault(emptyList())+ }+ if (offline.isNotEmpty()) {+ _results.value = offline.map { it.toSearchResult() }+ return@launch+ }+ // GoogleSearchDataSource.search does its own Dispatchers.IO + never+ // throws (empty list on any scrape/path failure).+ _results.value = GoogleSearchDataSource.search(query, nearLat, nearLon)+ .map { it.toSearchResult() }+ } finally {+ // `finally` because cancellation is the normal exit: every keystroke cancels+ // the previous job, and a cancelled search that never clears this flag leaves+ // the spinner up forever.+ _searching.value = false }- // GoogleSearchDataSource.search does its own Dispatchers.IO + never- // throws (empty list on any scrape/path failure).- _results.value = GoogleSearchDataSource.search(query, nearLat, nearLon)- .map { it.toSearchResult() } } }
maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.ktindex 62bfa1a84e..e96843af71 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.kt@@ -24,7 +24,45 @@ data class SearchUiState( // the map browse overlay onto the search page. Null = slot not set yet. val savedHome: SavedPlace? = null, val savedWork: SavedPlace? = null,-)+ /** Whether a search is running. See [SearchPhase]. */+ val searching: Boolean = false,+) {+ /**+ * What the results area should show.+ *+ * Derived here rather than at the call site because the view used to work it out from+ * `query.length >= 2 && results.isEmpty()`, which is equally true while a search is running+ * and after it found nothing — so a running search rendered "No results found". Naming the+ * phases makes the distinction impossible to collapse again, and makes the ordering+ * (searching wins over empty) a property of the state instead of the order of `when` branches.+ */+ val phase: SearchPhase+ get() = when {+ query.length < 2 && recents.isNotEmpty() -> SearchPhase.Recents+ query.length < 2 -> SearchPhase.Idle+ searching -> SearchPhase.Searching+ results.isEmpty() -> SearchPhase.Empty+ else -> SearchPhase.Results+ }+}++/** The five things the search results area can be showing. */+enum class SearchPhase {+ /** Nothing typed and nothing to suggest. */+ Idle,++ /** Nothing typed, but there are recent queries worth offering. */+ Recents,++ /** A search is in flight — including its debounce window. */+ Searching,++ /** The search finished and found nothing. */+ Empty,++ /** The search finished and found something. */+ Results,+} /** * Search callbacks. Every method has a no-op default so a preview can render the screen
maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt
diff --git a/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt b/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.ktindex 9ced387432..5797d1d75f 100644--- a/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt+++ b/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt@@ -86,6 +86,10 @@ class MetadataPreviews { SearchResult("3", "Golden Gate Ferry Terminal", "Pier 1, San Francisco", 37.7936, -122.3927, "Ferry terminal"), SearchResult("4", "Oakland Ferry Dock", "Clay St, Oakland", 37.7947, -122.2783, "Ferry terminal"), ),+ // Explicitly not searching: with results present and this left at its+ // default the state would resolve to Results anyway, but the listing image+ // should not depend on that inference.+ searching = false, ), SearchActions.Noop, )
maps/src/test/java/com/vayunmathur/maps/util/SearchUiStateTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/SearchUiStateTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/SearchUiStateTest.ktnew file mode 100644index 0000000000..51904ac0df--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/SearchUiStateTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.maps.util++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * The false-empty-state bug, encoded as a test.+ *+ * The search page used to decide what to draw from `query.length >= 2 && results.isEmpty()`,+ * which is equally true while a search is running and after one found nothing. So for the whole+ * debounce plus the offline lookup plus the network round-trip it told the user "No results+ * found" about a search that was still going, then replaced it with the results.+ *+ * [SearchUiState.phase] is where that distinction now lives, so this is where it gets defended.+ */+class SearchUiStateTest {++ private val results = listOf(+ SearchResult("1", "Ferry Building", null, 37.7955, -122.3933, null),+ )++ /** The regression. A running search must never look like a finished empty one. */+ @Test+ fun `a running search with no results yet is Searching, not Empty`() {+ val state = SearchUiState(query = "ferry", results = emptyList(), searching = true)+ assertEquals(SearchPhase.Searching, state.phase)+ }++ @Test+ fun `a finished search with no results is Empty`() {+ val state = SearchUiState(query = "ferry", results = emptyList(), searching = false)+ assertEquals(SearchPhase.Empty, state.phase)+ }++ @Test+ fun `a finished search with results is Results`() {+ val state = SearchUiState(query = "ferry", results = results, searching = false)+ assertEquals(SearchPhase.Results, state.phase)+ }++ /**+ * Stale results from the previous query are still on screen while the next one runs. Showing+ * them beats blanking the list, but the phase must say a search is in flight.+ */+ @Test+ fun `searching wins over stale results`() {+ val state = SearchUiState(query = "ferry b", results = results, searching = true)+ assertEquals(SearchPhase.Searching, state.phase)+ }++ /** Below the two-character floor nothing is searched, so recents are the useful thing. */+ @Test+ fun `a short query offers recents when there are any`() {+ val state = SearchUiState(query = "f", recents = listOf("ferry"))+ assertEquals(SearchPhase.Recents, state.phase)+ }++ @Test+ fun `a short query with no recents is Idle`() {+ assertEquals(SearchPhase.Idle, SearchUiState(query = "f").phase)+ }++ @Test+ fun `the initial state is Idle`() {+ assertEquals(SearchPhase.Idle, SearchUiState().phase)+ }++ /**+ * The two-character floor is the ViewModel's, and the phase has to agree with it: at one+ * character nothing has been asked for, so "no results" would be a lie.+ */+ @Test+ fun `the search floor is two characters`() {+ assertEquals(SearchPhase.Idle, SearchUiState(query = "f", searching = false).phase)+ assertEquals(SearchPhase.Empty, SearchUiState(query = "fe", searching = false).phase)+ }++ /** A short query cannot be searching, even if the flag says so mid-cancellation. */+ @Test+ fun `clearing the query back below the floor leaves the search phases`() {+ val state = SearchUiState(query = "f", results = results, searching = true)+ assertEquals(SearchPhase.Idle, state.phase)+ }+}