From 5dc00a9abed148be0b89a06aa85c99961561defe Mon Sep 17 00:00:00 2001 From: Julkzein Date: Thu, 19 Nov 2026 15:53:23 +0100 Subject: [PATCH 1/8] feat(map): turn listings into map markers New MapMarker (#341): a listing's id, title, type (item or service, so the map can draw them with different icons), coordinates and price, formatted by formatChf like the Browse cards. Listing.toMapMarker() builds it, or returns null for a listing that can't be placed: not saved yet, or without a location, which owners may not have set (#345 made it optional). Tests (MapMarkerTest): an item at its location, a service, no marker without a location, and none for an unsaved listing. --- .../polybazaar/map/viewmodel/MapMarker.kt | 39 +++++++++++ .../polybazaar/map/viewmodel/MapMarkerTest.kt | 67 +++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 app/src/main/java/com/android/polybazaar/map/viewmodel/MapMarker.kt create mode 100644 app/src/test/java/com/android/polybazaar/map/viewmodel/MapMarkerTest.kt diff --git a/app/src/main/java/com/android/polybazaar/map/viewmodel/MapMarker.kt b/app/src/main/java/com/android/polybazaar/map/viewmodel/MapMarker.kt new file mode 100644 index 00000000..2d7d887d --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/map/viewmodel/MapMarker.kt @@ -0,0 +1,39 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.map.viewmodel + +import com.android.polybazaar.listing.model.Listing +import com.android.polybazaar.listing.model.ListingType +import com.android.polybazaar.listing.model.formatChf +import com.android.polybazaar.map.model.Coordinates + +/** + * A listing as a marker on the map (#341). + * + * @property id the listing's id, to open its detail. + * @property type an item or a service: the map draws them with different icons. + * @property coordinates where the owner placed it (`Listing.location`). + * @property price formatted by [formatChf], like the Browse cards; the screen adds the unit. + */ +data class MapMarker( + val id: String, + val title: String, + val type: ListingType, + val coordinates: Coordinates, + val price: String, +) + +/** + * The marker of this listing, or null when it can't be placed: not saved yet (no id), or without a + * location, which the owner may not have set. + */ +internal fun Listing.toMapMarker(): MapMarker? { + val id = listingId ?: return null + val location = location ?: return null + return MapMarker( + id = id, + title = title, + type = type, + coordinates = Coordinates(location.latitude, location.longitude), + price = formatChf(price), + ) +} diff --git a/app/src/test/java/com/android/polybazaar/map/viewmodel/MapMarkerTest.kt b/app/src/test/java/com/android/polybazaar/map/viewmodel/MapMarkerTest.kt new file mode 100644 index 00000000..06c5dad5 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/map/viewmodel/MapMarkerTest.kt @@ -0,0 +1,67 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.map.viewmodel + +import com.android.polybazaar.listing.model.ItemListing +import com.android.polybazaar.listing.model.ListingCategory +import com.android.polybazaar.listing.model.ListingLocation +import com.android.polybazaar.listing.model.ListingType +import com.android.polybazaar.listing.model.ServiceListing +import com.android.polybazaar.map.model.Coordinates +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class MapMarkerTest { + + private val rolex = ListingLocation(46.5185, 6.5683, "Rolex Learning Center") + + private val drill = + ItemListing( + category = ListingCategory.ITEM_TOOLS, + price = 8.0, + title = "Bosch drill set", + description = "With bits", + listingId = "drill", + ownerUid = "lender", + location = rolex, + ) + + @Test + fun item_becomesAnItemMarkerAtItsLocation() { + assertEquals( + MapMarker( + id = "drill", + title = "Bosch drill set", + type = ListingType.ITEM, + coordinates = Coordinates(46.5185, 6.5683), + price = "CHF 8", + ), + drill.toMapMarker(), + ) + } + + @Test + fun service_becomesAServiceMarker() { + val tutoring = + ServiceListing( + category = ListingCategory.SERVICE_TUTORING, + price = 25.5, + title = "Analysis tutoring", + description = "Before the exam", + listingId = "tutoring", + location = rolex, + ) + + assertEquals(ListingType.SERVICE, tutoring.toMapMarker()?.type) + } + + @Test + fun listingWithoutALocation_hasNoMarker() { + assertNull(drill.copy(location = null).toMapMarker()) + } + + @Test + fun unsavedListing_hasNoMarker() { + assertNull(drill.copy(listingId = null).toMapMarker()) + } +} From 8c6325b3b67fe07761d05264f15f0f9c39bdb98b Mon Sep 17 00:00:00 2001 From: Julkzein Date: Thu, 19 Nov 2026 15:55:28 +0100 Subject: [PATCH 2/8] feat(map): load the listings to show on the map MapViewModel now also loads the markers for the map tab (#341): - MapUiState gets markers, isLoading and error. - loadListings(), called on creation and again on Retry or when the tab comes back, shows the same listings as Browse: every listing that isn't paused (getAllListings), except the signed-in user's own (currentUid), and only those with a location (toMapMarker). - Offline, Firestore answers from its cache; on failure the markers already shown are kept and error says why. A load while one runs is ignored, cancellation is rethrown and isLoading is cleared in a finally, as in BrowseViewModel. - The constructor takes the ListingRepository and the current uid; the existing tests pass a FakeListingRepository. Tests: 6 more in MapViewModelTest (21 in total): only other users' listings with a location (fails without the uid filter), isLoading, an error and its retry, a failed reload keeping the markers, a second load while one runs (fails without the guard), and a cancelled load. --- .../polybazaar/map/viewmodel/MapViewModel.kt | 59 +++++++- .../polybazaar/map/ui/MapLocationLayerTest.kt | 14 +- .../map/viewmodel/MapViewModelTest.kt | 131 +++++++++++++++++- 3 files changed, 192 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/map/viewmodel/MapViewModel.kt b/app/src/main/java/com/android/polybazaar/map/viewmodel/MapViewModel.kt index 301082fc..16dd8e17 100644 --- a/app/src/main/java/com/android/polybazaar/map/viewmodel/MapViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/map/viewmodel/MapViewModel.kt @@ -4,9 +4,13 @@ package com.android.polybazaar.map.viewmodel import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.error.model.toAppError +import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.map.model.Campus import com.android.polybazaar.map.model.Coordinates import com.android.polybazaar.map.model.LocationRepository +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -41,14 +45,26 @@ sealed interface MapCentre { * State of the map tab (#21). * * @property centre where the map is centred, or why it isn't yet. + * @property markers the listings to show on the map: the ones Browse shows (other users', not + * paused) that have a location. + * @property isLoading true while the listings are being loaded. + * @property error why the listings could not be loaded, or null. The markers already shown are + * kept. */ -data class MapUiState(val centre: MapCentre = MapCentre.Undecided) +data class MapUiState( + val centre: MapCentre = MapCentre.Undecided, + val markers: List = emptyList(), + val isLoading: Boolean = false, + val error: AppError? = null, +) /** * Centres the map on the renter's approximate location, or on a campus they pick when they don't - * share it (#340). The screen asks Android for the permission and reports the answer with - * [onPermissionResult]; this ViewModel never sees the permission itself. + * share it (#340), and loads the listings to show on it (#341). The screen asks Android for the + * permission and reports the answer with [onPermissionResult]; this ViewModel never sees the + * permission itself. * + * @param currentUid the signed-in user, whose own listings are left out, as in Browse. * @param savedStateHandle remembers the campus picked for the session: across tab switches, and * when Android kills the app in the background. Pass `createSavedStateHandle()` from the factory; * it has no default, since a handle made by hand is not restored by Android (and its constructor @@ -56,12 +72,49 @@ data class MapUiState(val centre: MapCentre = MapCentre.Undecided) */ class MapViewModel( private val locationRepository: LocationRepository, + private val listingRepository: ListingRepository, + private val currentUid: String, private val savedStateHandle: SavedStateHandle, ) : ViewModel() { private val _uiState = MutableStateFlow(MapUiState()) val uiState: StateFlow = _uiState.asStateFlow() + init { + loadListings() + } + + /** + * Loads the listings to show as markers, for example again after a failure (Retry) or when the + * tab comes back. Same listings as Browse: every listing that isn't paused, except the signed-in + * user's own, and only those with a location can be placed. Offline, Firestore answers from its + * cache; on failure the markers already shown are kept. Ignored while a load is already running. + */ + fun loadListings() { + // Two loads at once could finish in any order, and the older answer would overwrite the newer. + if (_uiState.value.isLoading) return + _uiState.update { it.copy(isLoading = true, error = null) } + viewModelScope.launch { + try { + listingRepository + .getAllListings() + .onSuccess { listings -> + val markers = + listings.filter { it.ownerUid != currentUid }.mapNotNull { it.toMapMarker() } + _uiState.update { it.copy(markers = markers) } + } + .onFailure { exception -> + // Cancellation means the map was closed: it is not an error to show. + if (exception is CancellationException) throw exception + _uiState.update { it.copy(error = exception.toAppError()) } + } + } finally { + // Also on cancellation, otherwise the guard above would block every later load. + _uiState.update { it.copy(isLoading = false) } + } + } + } + /** The campus picked earlier this session, or null. An unknown saved name reads as none. */ private val chosenCampus: Campus? get() = diff --git a/app/src/test/java/com/android/polybazaar/map/ui/MapLocationLayerTest.kt b/app/src/test/java/com/android/polybazaar/map/ui/MapLocationLayerTest.kt index d65f28e7..407bdbea 100644 --- a/app/src/test/java/com/android/polybazaar/map/ui/MapLocationLayerTest.kt +++ b/app/src/test/java/com/android/polybazaar/map/ui/MapLocationLayerTest.kt @@ -28,6 +28,7 @@ import androidx.lifecycle.SavedStateHandle import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.R +import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.map.model.Campus import com.android.polybazaar.map.model.Coordinates import com.android.polybazaar.map.model.FakeLocationRepository @@ -130,6 +131,7 @@ class MapLocationLayerTest { // ---- With the real ViewModel and Android's permission ---- + private val listings = FakeListingRepository() private val location = FakeLocationRepository(Coordinates(46.518, 6.568)) /** Stands in for Android's permission dialog: every request is answered [granted]. */ @@ -164,7 +166,7 @@ class MapLocationLayerTest { @Test fun permissionAlreadyGranted_skipsTheExplanation_andCentresOnTheRenter() { shadowOf(context as Application).grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION) - val viewModel = MapViewModel(location, SavedStateHandle()) + val viewModel = MapViewModel(location, listings, "renter", SavedStateHandle()) showLayer(viewModel) composeTestRule.waitForIdle() @@ -175,7 +177,7 @@ class MapLocationLayerTest { @Test fun permissionGrantedInSettingsWhileExplaining_readsTheLocationOnTheNextRedraw() { - val viewModel = MapViewModel(location, SavedStateHandle()) + val viewModel = MapViewModel(location, listings, "renter", SavedStateHandle()) var redraws by mutableIntStateOf(0) // A new modifier on each redraw, like a parent recomposing around the layer. composeTestRule.setContent { MapLocationLayer(viewModel, Modifier.testTag("layer_$redraws")) } @@ -193,7 +195,7 @@ class MapLocationLayerTest { @Test fun continue_asksForApproximateLocationOnly_andAGrantCentresOnTheRenter() { val asked = mutableListOf() - val viewModel = MapViewModel(location, SavedStateHandle()) + val viewModel = MapViewModel(location, listings, "renter", SavedStateHandle()) showLayer(viewModel, permissionDialog(granted = true) { asked += it }) node(MapLocationTags.CONTINUE_BUTTON).performClick() @@ -205,7 +207,7 @@ class MapLocationLayerTest { @Test fun aRefusal_showsTheChooser_andPickingACampusCentresOnIt() { - val viewModel = MapViewModel(location, SavedStateHandle()) + val viewModel = MapViewModel(location, listings, "renter", SavedStateHandle()) showLayer(viewModel, permissionDialog(granted = false)) node(MapLocationTags.CONTINUE_BUTTON).performClick() @@ -219,7 +221,7 @@ class MapLocationLayerTest { @Test fun notNow_showsTheChooser_withoutAskingAndroid() { val asked = mutableListOf() - val viewModel = MapViewModel(location, SavedStateHandle()) + val viewModel = MapViewModel(location, listings, "renter", SavedStateHandle()) showLayer(viewModel, permissionDialog(granted = true) { asked += it }) node(MapLocationTags.NOT_NOW_BUTTON).performClick() @@ -230,7 +232,7 @@ class MapLocationLayerTest { @Test fun changeThenCancel_goesBackToTheCampus() { - val viewModel = MapViewModel(location, SavedStateHandle()) + val viewModel = MapViewModel(location, listings, "renter", SavedStateHandle()) viewModel.chooseCampus(Campus.UNIL) showLayer(viewModel) diff --git a/app/src/test/java/com/android/polybazaar/map/viewmodel/MapViewModelTest.kt b/app/src/test/java/com/android/polybazaar/map/viewmodel/MapViewModelTest.kt index 3088063e..5a083d5a 100644 --- a/app/src/test/java/com/android/polybazaar/map/viewmodel/MapViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/map/viewmodel/MapViewModelTest.kt @@ -2,9 +2,16 @@ package com.android.polybazaar.map.viewmodel import androidx.lifecycle.SavedStateHandle +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.listing.model.FakeListingRepository +import com.android.polybazaar.listing.model.ItemListing +import com.android.polybazaar.listing.model.ListingCategory +import com.android.polybazaar.listing.model.ListingLocation import com.android.polybazaar.map.model.Campus import com.android.polybazaar.map.model.Coordinates import com.android.polybazaar.map.model.FakeLocationRepository +import java.net.UnknownHostException +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -13,6 +20,9 @@ import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -21,6 +31,7 @@ class MapViewModelTest { private val testDispatcher = StandardTestDispatcher() private val nearRolex = Coordinates(46.518, 6.568) + private val listings = FakeListingRepository() private val location = FakeLocationRepository(nearRolex) @Before @@ -35,7 +46,7 @@ class MapViewModelTest { private val handle = SavedStateHandle() - private fun viewModel() = MapViewModel(location, handle) + private fun viewModel() = MapViewModel(location, listings, "renter", handle) private fun MapViewModel.centre() = uiState.value.centre @@ -134,7 +145,13 @@ class MapViewModelTest { @Test fun locationUnavailable_withACampusChosen_goesBackToIt() { location.failure = IllegalStateException("No location available") - val viewModel = MapViewModel(location, SavedStateHandle(mapOf("map_chosen_campus" to "EPFL"))) + val viewModel = + MapViewModel( + location, + listings, + "renter", + SavedStateHandle(mapOf("map_chosen_campus" to "EPFL")), + ) viewModel.onPermissionResult(granted = true) testDispatcher.scheduler.advanceUntilIdle() @@ -144,7 +161,13 @@ class MapViewModelTest { @Test fun unknownSavedCampus_readsAsNone() { - val viewModel = MapViewModel(location, SavedStateHandle(mapOf("map_chosen_campus" to "ETHZ"))) + val viewModel = + MapViewModel( + location, + listings, + "renter", + SavedStateHandle(mapOf("map_chosen_campus" to "ETHZ")), + ) viewModel.onPermissionResult(granted = false) @@ -210,4 +233,106 @@ class MapViewModelTest { assertEquals(MapCentre.OnCampus(Campus.UNIL), viewModel.centre()) } + + // ---- Listings shown as markers (#341) ---- + + private val rolex = ListingLocation(46.5185, 6.5683, "Rolex Learning Center") + + private fun item(id: String, ownerUid: String, location: ListingLocation? = rolex) = + ItemListing( + category = ListingCategory.ITEM_TOOLS, + price = 8.0, + title = "Item $id", + description = "Description", + listingId = id, + ownerUid = ownerUid, + location = location, + ) + + private fun loadedViewModel(): MapViewModel { + val viewModel = viewModel() + testDispatcher.scheduler.advanceUntilIdle() + return viewModel + } + + @Test + fun init_showsOtherUsersListingsWithALocation_asMarkers() { + listings.allListings = + listOf( + item("drill", ownerUid = "lender"), + item("mine", ownerUid = "renter"), + item("nowhere", ownerUid = "lender", location = null), + item("paused", ownerUid = "lender").copy(isPaused = true), + ) + + val state = loadedViewModel().uiState.value + + assertEquals(listOf("drill"), state.markers.map { it.id }) + assertFalse(state.isLoading) + assertNull(state.error) + } + + @Test + fun loadListings_isLoadingOnlyWhileTheRepositoryAnswers() { + val gate = CompletableDeferred() + listings.gate = gate + + val viewModel = viewModel() + testDispatcher.scheduler.runCurrent() + assertTrue(viewModel.uiState.value.isLoading) + + gate.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + assertFalse(viewModel.uiState.value.isLoading) + } + + @Test + fun failedLoad_saysWhy_andRetryClearsIt() { + listings.failure = UnknownHostException("firestore.googleapis.com") + val viewModel = loadedViewModel() + assertEquals(AppError.NETWORK, viewModel.uiState.value.error) + + listings.failure = null + listings.allListings = listOf(item("drill", ownerUid = "lender")) + viewModel.loadListings() + testDispatcher.scheduler.advanceUntilIdle() + + assertNull(viewModel.uiState.value.error) + assertEquals(listOf("drill"), viewModel.uiState.value.markers.map { it.id }) + } + + @Test + fun failedReload_keepsTheMarkersShown() { + listings.allListings = listOf(item("drill", ownerUid = "lender")) + val viewModel = loadedViewModel() + + listings.failure = UnknownHostException("firestore.googleapis.com") + viewModel.loadListings() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(listOf("drill"), viewModel.uiState.value.markers.map { it.id }) + assertEquals(AppError.NETWORK, viewModel.uiState.value.error) + } + + @Test + fun loadListings_whileALoadIsRunning_isIgnored() { + listings.gate = CompletableDeferred() + val viewModel = viewModel() + testDispatcher.scheduler.runCurrent() + + viewModel.loadListings() + listings.gate?.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, listings.getAllListingsCalls) + } + + @Test + fun cancelledLoad_isNotAnError_andAllowsTheNextLoad() { + listings.failure = CancellationException("Map closed") + val viewModel = loadedViewModel() + + assertNull(viewModel.uiState.value.error) + assertFalse(viewModel.uiState.value.isLoading) + } } From 3f589f42cafdc40f5f30217831752a96869ea428 Mon Sep 17 00:00:00 2001 From: Julkzein Date: Thu, 19 Nov 2026 16:13:42 +0100 Subject: [PATCH 3/8] feat(map): show the map with item and skill markers New MapScreen for the Map tab (#341): - ListingsMap draws the Google map: the camera from cameraFor(), one MarkerComposable per listing with its icon (a box for items, a cap for skills, so they differ by icon and not only colour, #353), the renter's approximate circle (150 m) or their campus marker. The camera position is set rather than animated, since CameraUpdateFactory needs the map to be initialised first. - Every decision is in plain functions so it can be tested without Google Maps, which can't run in unit tests: cameraFor() (close on the renter or the campus, an overview of both campuses before that), markerIcon() and markerDescription() (read by TalkBack as "Bosch drill set, item, CHF 8 per day"). - MapContent draws the map, then the listings' state at the bottom (a loading pill on the first load, the error with a 48dp Retry, or "No listings with a location nearby yet"; nothing during a reload with markers, so the map doesn't flicker), then the location layer (#340) on top. MapScreen(viewModel) wires it; its map is a parameter, the Google map by default. Resources: ic_marker_item, ic_marker_service and 5 map_* strings. Tests (MapScreenTest, 14): the camera for each centre, different icons and descriptions per type, the marker label and pin, each listings state, Retry, and the screen with the real MapViewModel. --- .../android/polybazaar/map/ui/ListingsMap.kt | 84 ++++++ .../android/polybazaar/map/ui/MapScreen.kt | 240 ++++++++++++++++++ app/src/main/res/drawable/ic_marker_item.xml | 15 ++ .../main/res/drawable/ic_marker_service.xml | 15 ++ app/src/main/res/values/strings.xml | 5 + .../polybazaar/map/ui/MapScreenTest.kt | 210 +++++++++++++++ 6 files changed, 569 insertions(+) create mode 100644 app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt create mode 100644 app/src/main/java/com/android/polybazaar/map/ui/MapScreen.kt create mode 100644 app/src/main/res/drawable/ic_marker_item.xml create mode 100644 app/src/main/res/drawable/ic_marker_service.xml create mode 100644 app/src/test/java/com/android/polybazaar/map/ui/MapScreenTest.kt diff --git a/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt b/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt new file mode 100644 index 00000000..acb987ec --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt @@ -0,0 +1,84 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.map.ui + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Modifier +import com.android.polybazaar.R +import com.android.polybazaar.auth.ui.AuthColors +import com.android.polybazaar.map.model.Coordinates +import com.android.polybazaar.map.viewmodel.MapCentre +import com.android.polybazaar.map.viewmodel.MapMarker +import com.google.android.gms.maps.model.CameraPosition +import com.google.android.gms.maps.model.LatLng +import com.google.maps.android.compose.Circle +import com.google.maps.android.compose.GoogleMap +import com.google.maps.android.compose.MapUiSettings +import com.google.maps.android.compose.MarkerComposable +import com.google.maps.android.compose.rememberCameraPositionState +import com.google.maps.android.compose.rememberMarkerState + +/** Radius of the "approximate location" circle (Figma "Map — Centred on you"), in metres. */ +private const val APPROXIMATE_RADIUS_METRES = 150.0 + +private fun Coordinates.toLatLng() = LatLng(latitude, longitude) + +/** + * The Google map itself: camera from [cameraFor], one marker per listing with its item or skill + * icon, and the renter's approximate circle or their campus marker. Kept to drawing only, since + * Google Maps can't run in unit tests: every decision is in the tested functions of MapScreen.kt. + */ +@Composable +internal fun ListingsMap(centre: MapCentre, markers: List) { + val camera = cameraFor(centre) + val cameraState = rememberCameraPositionState { + position = CameraPosition.fromLatLngZoom(camera.target.toLatLng(), camera.zoom) + } + // Moves when the centre changes, for example once the location is read or a campus is picked. + // Setting the position rather than animating: CameraUpdateFactory needs the map to be + // initialised first, which isn't guaranteed this early on a slow device. + LaunchedEffect(camera) { + cameraState.position = CameraPosition.fromLatLngZoom(camera.target.toLatLng(), camera.zoom) + } + GoogleMap( + modifier = Modifier.fillMaxSize(), + cameraPositionState = cameraState, + // The location layer and the bottom bar already cover the edges: keep the map's own + // controls out of their way. + uiSettings = MapUiSettings(zoomControlsEnabled = false, mapToolbarEnabled = false), + ) { + markers.forEach { marker -> + MarkerComposable( + keys = arrayOf(marker.id, marker.type), + state = rememberMarkerState(key = marker.id, position = marker.coordinates.toLatLng()), + title = markerLabel(marker), + ) { + MarkerPin(icon = markerIcon(marker.type)) + } + } + when (centre) { + is MapCentre.Located -> + Circle( + center = centre.coordinates.toLatLng(), + radius = APPROXIMATE_RADIUS_METRES, + fillColor = AuthColors.Accent.copy(alpha = 0.15f), + strokeColor = AuthColors.Accent.copy(alpha = 0.4f), + strokeWidth = 2f, + ) + is MapCentre.OnCampus -> + MarkerComposable( + keys = arrayOf(centre.campus), + state = + rememberMarkerState( + key = centre.campus.name, + position = centre.campus.centre.toLatLng(), + ), + title = centre.campus.name, + ) { + MarkerPin(icon = R.drawable.ic_campus) + } + else -> Unit + } + } +} diff --git a/app/src/main/java/com/android/polybazaar/map/ui/MapScreen.kt b/app/src/main/java/com/android/polybazaar/map/ui/MapScreen.kt new file mode 100644 index 00000000..97ed7106 --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/map/ui/MapScreen.kt @@ -0,0 +1,240 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.map.ui + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.android.polybazaar.R +import com.android.polybazaar.auth.ui.AuthColors +import com.android.polybazaar.error.ui.message +import com.android.polybazaar.listing.model.ListingType +import com.android.polybazaar.map.model.Campus +import com.android.polybazaar.map.model.Coordinates +import com.android.polybazaar.map.viewmodel.MapCentre +import com.android.polybazaar.map.viewmodel.MapMarker +import com.android.polybazaar.map.viewmodel.MapUiState +import com.android.polybazaar.map.viewmodel.MapViewModel + +object MapScreenTags { + const val SCREEN = "map_screen" + const val LOADING = "map_loading_listings" + const val ERROR = "map_listings_error" + const val RETRY_BUTTON = "map_retry_button" + const val EMPTY = "map_no_listings" +} + +/** Where the map's camera points and how close. */ +internal data class MapCamera(val target: Coordinates, val zoom: Float) + +/** Street level: a few hundred metres around the renter or the campus. */ +private const val CLOSE_ZOOM = 15f + +/** Both campuses at once, before the renter's centre is known. */ +private const val OVERVIEW_ZOOM = 14f + +/** + * The camera for [centre]: close on the renter or their campus, and an overview of EPFL and UNIL + * while the centre isn't known yet (asking, locating, choosing). + */ +internal fun cameraFor(centre: MapCentre): MapCamera = + when (centre) { + is MapCentre.Located -> MapCamera(centre.coordinates, CLOSE_ZOOM) + is MapCentre.OnCampus -> MapCamera(centre.campus.centre, CLOSE_ZOOM) + MapCentre.Undecided, + MapCentre.Locating, + is MapCentre.NeedsChoice -> MapCamera(campusesMidpoint(), OVERVIEW_ZOOM) + } + +/** Halfway between the campuses, so the overview shows both. */ +private fun campusesMidpoint(): Coordinates = + Coordinates( + latitude = Campus.entries.map { it.centre.latitude }.average(), + longitude = Campus.entries.map { it.centre.longitude }.average(), + ) + +/** The marker icon of a listing: items and skills differ by icon, not only colour (#353). */ +@DrawableRes +internal fun markerIcon(type: ListingType): Int = + when (type) { + ListingType.ITEM -> R.drawable.ic_marker_item + ListingType.SERVICE -> R.drawable.ic_marker_service + } + +/** What TalkBack reads for a marker: its title, whether it's an item or a skill, and its price. */ +@StringRes +internal fun markerDescription(type: ListingType): Int = + when (type) { + ListingType.ITEM -> R.string.map_marker_item + ListingType.SERVICE -> R.string.map_marker_service + } + +/** + * The Map tab (#341): the listings around the renter or their campus on a map, item and skill + * markers drawn differently, with the location layer (#340) over it. + * + * @param map draws the map for the state; the Google map by default, a stand-in in tests. + */ +@Composable +fun MapScreen( + viewModel: MapViewModel, + modifier: Modifier = Modifier, + map: @Composable (MapUiState) -> Unit = { ListingsMap(it.centre, it.markers) }, +) { + val uiState by viewModel.uiState.collectAsState() + MapContent( + uiState = uiState, + onRetry = viewModel::loadListings, + map = { map(uiState) }, + locationLayer = { MapLocationLayer(viewModel) }, + modifier = modifier, + ) +} + +/** + * The map tab without its ViewModel: [map] draws the map (the Google map in the app, a stand-in in + * tests, where Google Maps can't run), then what the listings' state needs over it, then + * [locationLayer] on top. + * + * @param onRetry reloads the listings after a failure. + */ +@Composable +fun MapContent( + uiState: MapUiState, + onRetry: () -> Unit, + map: @Composable () -> Unit, + locationLayer: @Composable () -> Unit, + modifier: Modifier = Modifier, +) { + Box(modifier = modifier.fillMaxSize().testTag(MapScreenTags.SCREEN)) { + map() + ListingsStatus(uiState, onRetry) + // Last, so its cards and their dim cover the status too. + locationLayer() + } +} + +/** + * Why there are no markers, or a load in progress, at the bottom of the map. A reload while markers + * are shown (the tab coming back) shows nothing, so the map doesn't flicker. + */ +@Composable +private fun BoxScope.ListingsStatus(uiState: MapUiState, onRetry: () -> Unit) { + val error = uiState.error + when { + error != null -> + BottomPill(MapScreenTags.ERROR) { + Text( + text = error.message(), + color = AuthColors.Danger, + fontSize = 12.sp, + modifier = Modifier.weight(1f, fill = false), + ) + TextButton( + onClick = onRetry, + modifier = Modifier.heightIn(min = 48.dp).testTag(MapScreenTags.RETRY_BUTTON), + ) { + Text( + text = stringResource(R.string.map_retry), + color = AuthColors.Accent, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + ) + } + } + uiState.isLoading && uiState.markers.isEmpty() -> + BottomPill(MapScreenTags.LOADING) { + CircularProgressIndicator( + color = AuthColors.Accent, + strokeWidth = 2.dp, + modifier = Modifier.size(16.dp), + ) + Text( + text = stringResource(R.string.map_loading_listings), + color = AuthColors.TextSecondary, + fontSize = 12.sp, + modifier = Modifier.padding(vertical = 12.dp), + ) + } + !uiState.isLoading && uiState.markers.isEmpty() -> + BottomPill(MapScreenTags.EMPTY) { + Text( + text = stringResource(R.string.map_no_listings), + color = AuthColors.TextSecondary, + fontSize = 12.sp, + modifier = Modifier.padding(vertical = 12.dp), + ) + } + } +} + +/** A pill at the bottom of the map, styled like the location pills at the top. */ +@Composable +private fun BoxScope.BottomPill(tag: String, content: @Composable RowScope.() -> Unit) { + Row( + modifier = + Modifier.align(Alignment.BottomCenter) + .padding(start = 18.dp, end = 18.dp, bottom = 16.dp) + .shadow(2.dp, RoundedCornerShape(24.dp)) + .background(AuthColors.CardBackground, RoundedCornerShape(24.dp)) + .border(1.dp, AuthColors.Outline, RoundedCornerShape(24.dp)) + .padding(horizontal = 14.dp) + .testTag(tag), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + content() + } +} + +/** The round accent pin with a white icon, drawn for listing and campus markers. */ +@Composable +internal fun MarkerPin(@DrawableRes icon: Int, modifier: Modifier = Modifier) { + Box( + modifier = + modifier + .size(32.dp) + .background(AuthColors.Accent, CircleShape) + .border(2.dp, AuthColors.CardBackground, CircleShape), + contentAlignment = Alignment.Center, + ) { + Icon( + painter = painterResource(icon), + contentDescription = null, + tint = AuthColors.CardBackground, + modifier = Modifier.size(16.dp), + ) + } +} + +/** What TalkBack reads for [marker], for example "Bosch drill set, item, CHF 8 per day". */ +@Composable +internal fun markerLabel(marker: MapMarker): String = + stringResource(markerDescription(marker.type), marker.title, marker.price) diff --git a/app/src/main/res/drawable/ic_marker_item.xml b/app/src/main/res/drawable/ic_marker_item.xml new file mode 100644 index 00000000..40491161 --- /dev/null +++ b/app/src/main/res/drawable/ic_marker_item.xml @@ -0,0 +1,15 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_marker_service.xml b/app/src/main/res/drawable/ic_marker_service.xml new file mode 100644 index 00000000..2ca72dd6 --- /dev/null +++ b/app/src/main/res/drawable/ic_marker_service.xml @@ -0,0 +1,15 @@ + + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 022c209c..d48b7901 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -127,6 +127,11 @@ Showing %1$s Change Change campus + Loading listings… + No listings with a location nearby yet + Retry + %1$s, item, %2$s per day + %1$s, skill, %2$s per day Your bio was saved, but the photo couldn’t be removed. Tap Save to try again. diff --git a/app/src/test/java/com/android/polybazaar/map/ui/MapScreenTest.kt b/app/src/test/java/com/android/polybazaar/map/ui/MapScreenTest.kt new file mode 100644 index 00000000..94ea67cc --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/map/ui/MapScreenTest.kt @@ -0,0 +1,210 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.map.ui + +import android.content.Context +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.assertHeightIsAtLeast +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import androidx.lifecycle.SavedStateHandle +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.polybazaar.R +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.listing.model.FakeListingRepository +import com.android.polybazaar.listing.model.ItemListing +import com.android.polybazaar.listing.model.ListingCategory +import com.android.polybazaar.listing.model.ListingLocation +import com.android.polybazaar.listing.model.ListingType +import com.android.polybazaar.map.model.Campus +import com.android.polybazaar.map.model.Coordinates +import com.android.polybazaar.map.model.FakeLocationRepository +import com.android.polybazaar.map.viewmodel.MapCentre +import com.android.polybazaar.map.viewmodel.MapMarker +import com.android.polybazaar.map.viewmodel.MapUiState +import com.android.polybazaar.map.viewmodel.MapViewModel +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class MapScreenTest { + + @get:Rule val composeTestRule = createComposeRule() + + private val context: Context = ApplicationProvider.getApplicationContext() + + private val drill = + MapMarker("drill", "Bosch drill set", ListingType.ITEM, Coordinates(46.519, 6.567), "CHF 8") + + private fun node(tag: String) = composeTestRule.onNodeWithTag(tag, useUnmergedTree = true) + + /** The map tab with a stand-in map, since Google Maps can't run in unit tests. */ + private fun setContent(uiState: MapUiState, onRetry: () -> Unit = {}) { + composeTestRule.setContent { + MapContent( + uiState = uiState, + onRetry = onRetry, + map = { Box(Modifier.fillMaxSize().testTag("map")) }, + locationLayer = { Box(Modifier.fillMaxSize().testTag("location_layer")) }, + ) + } + } + + // ---- Camera ---- + + @Test + fun camera_isCloseOnTheRenter() { + val renter = Coordinates(46.52, 6.57) + + assertEquals(MapCamera(renter, 15f), cameraFor(MapCentre.Located(renter))) + } + + @Test + fun camera_isCloseOnTheCampus() { + assertEquals(MapCamera(Campus.UNIL.centre, 15f), cameraFor(MapCentre.OnCampus(Campus.UNIL))) + } + + @Test + fun camera_beforeTheCentreIsKnown_showsBothCampuses() { + listOf(MapCentre.Undecided, MapCentre.Locating, MapCentre.NeedsChoice()).forEach { centre -> + val camera = cameraFor(centre) + assertEquals(14f, camera.zoom) + // Between the campuses, on both axes. + val latitudes = Campus.entries.map { it.centre.latitude } + val longitudes = Campus.entries.map { it.centre.longitude } + assertTrue(camera.target.latitude in latitudes.min()..latitudes.max()) + assertTrue(camera.target.longitude in longitudes.min()..longitudes.max()) + } + } + + // ---- Markers ---- + + @Test + fun itemsAndSkills_haveDifferentIconsAndDescriptions() { + assertNotEquals(markerIcon(ListingType.ITEM), markerIcon(ListingType.SERVICE)) + assertNotEquals(markerDescription(ListingType.ITEM), markerDescription(ListingType.SERVICE)) + } + + @Test + fun markerLabel_readsTitleTypeAndPrice() { + var label = "" + composeTestRule.setContent { label = markerLabel(drill) } + composeTestRule.waitForIdle() + + assertEquals(context.getString(R.string.map_marker_item, "Bosch drill set", "CHF 8"), label) + } + + @Test + fun markerPin_drawsItsIcon() { + composeTestRule.setContent { + MarkerPin(icon = markerIcon(ListingType.SERVICE), modifier = Modifier.testTag("pin")) + } + + node("pin").assertIsDisplayed() + } + + // ---- Listings state over the map ---- + + @Test + fun mapAndLocationLayer_areBothDrawn() { + setContent(MapUiState(markers = listOf(drill))) + + node("map").assertIsDisplayed() + node("location_layer").assertIsDisplayed() + } + + @Test + fun firstLoad_showsLoading() { + setContent(MapUiState(isLoading = true)) + + node(MapScreenTags.LOADING).assertIsDisplayed() + composeTestRule + .onNodeWithText(context.getString(R.string.map_loading_listings)) + .assertIsDisplayed() + } + + @Test + fun reloadWithMarkersShown_showsNothing_soTheMapDoesNotFlicker() { + setContent(MapUiState(markers = listOf(drill), isLoading = true)) + + node(MapScreenTags.LOADING).assertDoesNotExist() + node(MapScreenTags.EMPTY).assertDoesNotExist() + } + + @Test + fun noListingWithALocation_saysSo() { + setContent(MapUiState()) + + node(MapScreenTags.EMPTY).assertIsDisplayed() + composeTestRule.onNodeWithText(context.getString(R.string.map_no_listings)).assertIsDisplayed() + } + + @Test + fun markersShown_showNoStatus() { + setContent(MapUiState(markers = listOf(drill))) + + node(MapScreenTags.LOADING).assertDoesNotExist() + node(MapScreenTags.EMPTY).assertDoesNotExist() + node(MapScreenTags.ERROR).assertDoesNotExist() + } + + @Test + fun failedLoad_saysWhy_andRetryReloads() { + var retries = 0 + setContent(MapUiState(error = AppError.NETWORK), onRetry = { retries++ }) + + node(MapScreenTags.ERROR).assertIsDisplayed() + composeTestRule.onNodeWithText(context.getString(R.string.error_network)).assertIsDisplayed() + node(MapScreenTags.RETRY_BUTTON).assertHeightIsAtLeast(48.dp).performClick() + + assertEquals(1, retries) + } + + @Test + fun failedReloadWithMarkersShown_stillOffersRetry() { + setContent(MapUiState(markers = listOf(drill), error = AppError.NETWORK)) + + node(MapScreenTags.RETRY_BUTTON).assertIsDisplayed() + } + + // ---- With the real ViewModel ---- + + @Test + fun screen_showsTheViewModelsMarkers_andRetryReloads() { + val listings = + FakeListingRepository( + allListings = + listOf( + ItemListing( + category = ListingCategory.ITEM_TOOLS, + price = 8.0, + title = "Bosch drill set", + description = "With bits", + listingId = "drill", + ownerUid = "lender", + location = ListingLocation(46.519, 6.567, "Rolex Learning Center"), + ) + ) + ) + val viewModel = MapViewModel(FakeLocationRepository(), listings, "renter", SavedStateHandle()) + var shown = emptyList() + + composeTestRule.setContent { MapScreen(viewModel, map = { shown = it.markers }) } + composeTestRule.waitForIdle() + + assertEquals(listOf("drill"), shown.map { it.id }) + // The location layer is drawn over the map: the explanation before asking. + node(MapLocationTags.REASON_CARD).assertIsDisplayed() + } +} From 9a69325dbcaee2a7ebe0264bc3955917841c1a18 Mon Sep 17 00:00:00 2001 From: Julkzein Date: Thu, 19 Nov 2026 16:13:56 +0100 Subject: [PATCH 4/8] test(map): run the Google map on the CI emulator ListingsMap can't run under Robolectric ("CameraUpdateFactory is not initialized"), so its lines would stay uncovered. The CI emulator is a google_apis image with Google Play services, and the coverage report already includes the connected tests, so ListingsMapTest (instrumented) builds the map with an item and a skill marker around the renter, then on a campus, then while choosing. Tiles need a valid key, so it checks that the map and its markers are built without crashing, not what the tiles show. --- .../android/polybazaar/map/ListingsMapTest.kt | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 app/src/androidTest/java/com/android/polybazaar/map/ListingsMapTest.kt diff --git a/app/src/androidTest/java/com/android/polybazaar/map/ListingsMapTest.kt b/app/src/androidTest/java/com/android/polybazaar/map/ListingsMapTest.kt new file mode 100644 index 00000000..4a1c9d90 --- /dev/null +++ b/app/src/androidTest/java/com/android/polybazaar/map/ListingsMapTest.kt @@ -0,0 +1,71 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.map + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.polybazaar.listing.model.ListingType +import com.android.polybazaar.map.model.Campus +import com.android.polybazaar.map.model.Coordinates +import com.android.polybazaar.map.ui.ListingsMap +import com.android.polybazaar.map.viewmodel.MapCentre +import com.android.polybazaar.map.viewmodel.MapMarker +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Runs the Google map on a real device (the CI emulator has Google Play services), which unit tests + * can't: an item and a skill marker, with the renter's circle and then a campus marker. Map tiles + * need a valid key, so this checks that the map, its markers and the overlays are built without + * crashing, not what the tiles show. + */ +@RunWith(AndroidJUnit4::class) +class ListingsMapTest { + + @get:Rule val composeTestRule = createComposeRule() + + private val markers = + listOf( + MapMarker( + "drill", + "Bosch drill set", + ListingType.ITEM, + Coordinates(46.519, 6.567), + "CHF 8", + ), + MapMarker( + "maths", + "Analysis tutoring", + ListingType.SERVICE, + Coordinates(46.522, 6.579), + "CHF 25", + ), + ) + + /** Gives the map time to be created, since its content is only composed once it's ready. */ + private fun letTheMapLoad() { + composeTestRule.waitForIdle() + Thread.sleep(MAP_LOAD_MILLIS) + composeTestRule.waitForIdle() + } + + @Test + fun mapWithMarkers_aroundTheRenter_thenOnACampus() { + var centre: MapCentre by mutableStateOf(MapCentre.Located(Coordinates(46.52, 6.57))) + composeTestRule.setContent { ListingsMap(centre = centre, markers = markers) } + letTheMapLoad() + + composeTestRule.runOnIdle { centre = MapCentre.OnCampus(Campus.EPFL) } + letTheMapLoad() + + composeTestRule.runOnIdle { centre = MapCentre.NeedsChoice() } + letTheMapLoad() + } + + private companion object { + const val MAP_LOAD_MILLIS = 3_000L + } +} From 0cefb3eb7d12e610e50d8ffae50d0fde363a60b8 Mon Sep 17 00:00:00 2001 From: Julkzein Date: Thu, 19 Nov 2026 16:52:50 +0100 Subject: [PATCH 5/8] fix(map): load Apache HTTP for Google Maps on Android 9+ ListingsMapTest crashed on the CI emulator with NoClassDefFoundError org/apache/http/ProtocolVersion, thrown from Play Services' Maps module, which still uses Apache HTTP; Android 9+ no longer loads it by default, so the map could crash in the app too. The manifest now declares , as Google's Maps SDK documentation asks; not required, so devices without it can still install the app. --- app/src/main/AndroidManifest.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6b2a57d6..53a113a8 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -51,6 +51,13 @@ + + \ No newline at end of file From 8362cbafdf3d8c1acd728c793ae8053ccecb17eb Mon Sep 17 00:00:00 2001 From: Julkzein Date: Thu, 19 Nov 2026 17:56:24 +0100 Subject: [PATCH 6/8] fix(map): key each marker by its listing Inside the forEach, rememberMarkerState's state was tied to the marker's position in the list (its key only names the saved state, and the position only counts the first time). After a reload that dropped the first listing, the second took its state and was drawn where the first had been, and a listing its owner moved kept its old pin (Mamel0uk on #391; rememberMarkerState is deprecated in maps-compose 9 for this reason). Each listing marker, and the campus marker, now sits in key(id) { } and uses rememberUpdatedMarkerState(position), so it keeps its own state and follows its current position. --- .../android/polybazaar/map/ui/ListingsMap.kt | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt b/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt index acb987ec..221d0e49 100644 --- a/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt +++ b/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt @@ -4,6 +4,7 @@ package com.android.polybazaar.map.ui import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.key import androidx.compose.ui.Modifier import com.android.polybazaar.R import com.android.polybazaar.auth.ui.AuthColors @@ -17,7 +18,7 @@ import com.google.maps.android.compose.GoogleMap import com.google.maps.android.compose.MapUiSettings import com.google.maps.android.compose.MarkerComposable import com.google.maps.android.compose.rememberCameraPositionState -import com.google.maps.android.compose.rememberMarkerState +import com.google.maps.android.compose.rememberUpdatedMarkerState /** Radius of the "approximate location" circle (Figma "Map — Centred on you"), in metres. */ private const val APPROXIMATE_RADIUS_METRES = 150.0 @@ -49,12 +50,17 @@ internal fun ListingsMap(centre: MapCentre, markers: List) { uiSettings = MapUiSettings(zoomControlsEnabled = false, mapToolbarEnabled = false), ) { markers.forEach { marker -> - MarkerComposable( - keys = arrayOf(marker.id, marker.type), - state = rememberMarkerState(key = marker.id, position = marker.coordinates.toLatLng()), - title = markerLabel(marker), - ) { - MarkerPin(icon = markerIcon(marker.type)) + // Keyed by listing, not by its place in the list: after a reload that drops or reorders + // listings, each marker keeps its own state instead of taking its neighbour's, and a listing + // its owner moved follows its new position (rememberUpdatedMarkerState). + key(marker.id) { + MarkerComposable( + keys = arrayOf(marker.id, marker.type), + state = rememberUpdatedMarkerState(position = marker.coordinates.toLatLng()), + title = markerLabel(marker), + ) { + MarkerPin(icon = markerIcon(marker.type)) + } } } when (centre) { @@ -67,16 +73,14 @@ internal fun ListingsMap(centre: MapCentre, markers: List) { strokeWidth = 2f, ) is MapCentre.OnCampus -> - MarkerComposable( - keys = arrayOf(centre.campus), - state = - rememberMarkerState( - key = centre.campus.name, - position = centre.campus.centre.toLatLng(), - ), - title = centre.campus.name, - ) { - MarkerPin(icon = R.drawable.ic_campus) + key(centre.campus) { + MarkerComposable( + keys = arrayOf(centre.campus), + state = rememberUpdatedMarkerState(position = centre.campus.centre.toLatLng()), + title = centre.campus.name, + ) { + MarkerPin(icon = R.drawable.ic_campus) + } } else -> Unit } From 1724c4c30bc40c5ec2ac2c322c204f4e9225637c Mon Sep 17 00:00:00 2001 From: Julkzein Date: Thu, 19 Nov 2026 17:57:53 +0100 Subject: [PATCH 7/8] test(map): wait for the Google map instead of sleeping ListingsMapTest slept 3 x 3 s and asserted nothing, so it was slow and could still be flaky on a slow emulator (Mamel0uk on #391). ListingsMap takes an onMapReady callback, called from MapEffect once the map is created, and the test waits up to 20 s for it, then checks the campus and overview states recompose. It waits for "created" rather than onMapLoaded, which waits for the tiles: our Maps key doesn't accept debug builds, so onMapLoaded might never fire on CI. --- .../android/polybazaar/map/ListingsMapTest.kt | 35 ++++++++++--------- .../android/polybazaar/map/ui/ListingsMap.kt | 17 +++++++-- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/app/src/androidTest/java/com/android/polybazaar/map/ListingsMapTest.kt b/app/src/androidTest/java/com/android/polybazaar/map/ListingsMapTest.kt index 4a1c9d90..d6d4238d 100644 --- a/app/src/androidTest/java/com/android/polybazaar/map/ListingsMapTest.kt +++ b/app/src/androidTest/java/com/android/polybazaar/map/ListingsMapTest.kt @@ -12,15 +12,16 @@ import com.android.polybazaar.map.model.Coordinates import com.android.polybazaar.map.ui.ListingsMap import com.android.polybazaar.map.viewmodel.MapCentre import com.android.polybazaar.map.viewmodel.MapMarker +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Runs the Google map on a real device (the CI emulator has Google Play services), which unit tests - * can't: an item and a skill marker, with the renter's circle and then a campus marker. Map tiles - * need a valid key, so this checks that the map, its markers and the overlays are built without - * crashing, not what the tiles show. + * can't: an item and a skill marker, with the renter's circle and then a campus marker. It waits + * for the map to be created (onMapReady) rather than loaded: tiles need a key that accepts this + * build, which debug builds don't have, so onMapLoaded might never fire. */ @RunWith(AndroidJUnit4::class) class ListingsMapTest { @@ -45,27 +46,27 @@ class ListingsMapTest { ), ) - /** Gives the map time to be created, since its content is only composed once it's ready. */ - private fun letTheMapLoad() { - composeTestRule.waitForIdle() - Thread.sleep(MAP_LOAD_MILLIS) - composeTestRule.waitForIdle() - } - @Test - fun mapWithMarkers_aroundTheRenter_thenOnACampus() { + fun mapWithMarkers_isCreated_aroundTheRenter_onACampus_andWhileChoosing() { var centre: MapCentre by mutableStateOf(MapCentre.Located(Coordinates(46.52, 6.57))) - composeTestRule.setContent { ListingsMap(centre = centre, markers = markers) } - letTheMapLoad() + var ready = false + composeTestRule.setContent { + ListingsMap(centre = centre, markers = markers, onMapReady = { ready = true }) + } - composeTestRule.runOnIdle { centre = MapCentre.OnCampus(Campus.EPFL) } - letTheMapLoad() + // The map exists, with its markers and the renter's circle: no crash so far. + composeTestRule.waitUntil(MAP_READY_MILLIS) { ready } + // Moving to a campus marker, then to the overview, recomposes without crashing. + composeTestRule.runOnIdle { centre = MapCentre.OnCampus(Campus.EPFL) } + composeTestRule.waitForIdle() composeTestRule.runOnIdle { centre = MapCentre.NeedsChoice() } - letTheMapLoad() + composeTestRule.waitForIdle() + assertTrue(ready) } private companion object { - const val MAP_LOAD_MILLIS = 3_000L + /** Generous for a cold emulator; the map is usually created within a second or two. */ + const val MAP_READY_MILLIS = 20_000L } } diff --git a/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt b/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt index 221d0e49..8c888b69 100644 --- a/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt +++ b/app/src/main/java/com/android/polybazaar/map/ui/ListingsMap.kt @@ -15,7 +15,9 @@ import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.Circle import com.google.maps.android.compose.GoogleMap +import com.google.maps.android.compose.MapEffect import com.google.maps.android.compose.MapUiSettings +import com.google.maps.android.compose.MapsComposeExperimentalApi import com.google.maps.android.compose.MarkerComposable import com.google.maps.android.compose.rememberCameraPositionState import com.google.maps.android.compose.rememberUpdatedMarkerState @@ -27,11 +29,17 @@ private fun Coordinates.toLatLng() = LatLng(latitude, longitude) /** * The Google map itself: camera from [cameraFor], one marker per listing with its item or skill - * icon, and the renter's approximate circle or their campus marker. Kept to drawing only, since - * Google Maps can't run in unit tests: every decision is in the tested functions of MapScreen.kt. + * icon, and the renter's approximate circle or their campus marker. [onMapReady] is called once the + * map is created (tests wait for it). Kept to drawing only, since Google Maps can't run in unit + * tests: every decision is in the tested functions of MapScreen.kt. */ +@OptIn(MapsComposeExperimentalApi::class) @Composable -internal fun ListingsMap(centre: MapCentre, markers: List) { +internal fun ListingsMap( + centre: MapCentre, + markers: List, + onMapReady: () -> Unit = {}, +) { val camera = cameraFor(centre) val cameraState = rememberCameraPositionState { position = CameraPosition.fromLatLngZoom(camera.target.toLatLng(), camera.zoom) @@ -49,6 +57,9 @@ internal fun ListingsMap(centre: MapCentre, markers: List) { // controls out of their way. uiSettings = MapUiSettings(zoomControlsEnabled = false, mapToolbarEnabled = false), ) { + // Once the map exists, whether or not its tiles can load: lets the instrumented test wait for + // the map instead of sleeping. + MapEffect(Unit) { onMapReady() } markers.forEach { marker -> // Keyed by listing, not by its place in the list: after a reload that drops or reorders // listings, each marker keeps its own state instead of taking its neighbour's, and a listing From 4533d2323d02e3ce38a810901c49b1ff8db18197 Mon Sep 17 00:00:00 2001 From: Julkzein Date: Thu, 19 Nov 2026 17:59:06 +0100 Subject: [PATCH 8/8] test(map): tap Retry in the map screen's Retry test screen_showsTheViewModelsMarkers_andRetryReloads never tapped Retry (Mamel0uk on #391). The first load now fails, as offline without a cache, so no marker is shown; Retry is tapped and the listing appears, and the error goes away. A campus is picked first, so the location card doesn't cover the bottom of the map where Retry is. --- .../com/android/polybazaar/map/ui/MapScreenTest.kt | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/com/android/polybazaar/map/ui/MapScreenTest.kt b/app/src/test/java/com/android/polybazaar/map/ui/MapScreenTest.kt index 94ea67cc..582a0cb5 100644 --- a/app/src/test/java/com/android/polybazaar/map/ui/MapScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/map/ui/MapScreenTest.kt @@ -30,6 +30,7 @@ import com.android.polybazaar.map.viewmodel.MapCentre import com.android.polybazaar.map.viewmodel.MapMarker import com.android.polybazaar.map.viewmodel.MapUiState import com.android.polybazaar.map.viewmodel.MapViewModel +import java.net.UnknownHostException import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertTrue @@ -197,14 +198,23 @@ class MapScreenTest { ) ) ) + // The first load fails, as offline without a cache. + listings.failure = UnknownHostException("firestore.googleapis.com") val viewModel = MapViewModel(FakeLocationRepository(), listings, "renter", SavedStateHandle()) + // A campus already picked, so the location card doesn't cover the bottom of the map. + viewModel.chooseCampus(Campus.EPFL) var shown = emptyList() composeTestRule.setContent { MapScreen(viewModel, map = { shown = it.markers }) } composeTestRule.waitForIdle() + assertEquals(emptyList(), shown.map { it.id }) + node(MapLocationTags.CAMPUS_PILL).assertIsDisplayed() + + listings.failure = null + node(MapScreenTags.RETRY_BUTTON).performClick() + composeTestRule.waitForIdle() assertEquals(listOf("drill"), shown.map { it.id }) - // The location layer is drawn over the map: the explanation before asking. - node(MapLocationTags.REASON_CARD).assertIsDisplayed() + node(MapScreenTags.ERROR).assertDoesNotExist() } }