From aff4d874e0839908f820a0c3188e26a6131d5b33 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:21:10 +0100 Subject: [PATCH 1/4] feat(listing): add the map pin icon and the location picker strings --- app/src/main/res/drawable/ic_map_pin.xml | 3 ++- app/src/main/res/values/strings.xml | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/app/src/main/res/drawable/ic_map_pin.xml b/app/src/main/res/drawable/ic_map_pin.xml index 5fb65db3..5b58633a 100644 --- a/app/src/main/res/drawable/ic_map_pin.xml +++ b/app/src/main/res/drawable/ic_map_pin.xml @@ -1,6 +1,7 @@ - + %1$s: %2$s When can you lend it? When can you offer it? + Pickup location (optional) + Meeting place (optional) + Choose on the map + + %1$s: %2$s + Move the pin + Remove location + Name the place… + Give the place a name. + Choose the location + Move the map to place the pin + Connect to the internet to choose a location + Show my location + Confirm location + Map to choose where the listing is offered Previous month From 70011ccc9de14f6ffdb6920354aa6338ccff18a1 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:22:58 +0100 Subject: [PATCH 2/4] feat(listing): choose the pickup location or meeting place on a map Add one location field, opens a full-screen picker with a fixed centre pin, and once a point is set the field becomes the editable place name with buttons to move the pin or remove it. \"Show my location\" asks for the approximate location only when tapped, and the map follows the lender's position until they move it. Offline, choosing on the map is disabled with a hint, while removing or renaming the place still works --- .../listing/ui/CreateListingScreen.kt | 25 +- .../listing/ui/EditListingScreen.kt | 5 +- .../listing/ui/ListingLocationField.kt | 369 ++++++++++++++ .../listing/ui/ListingLocationFieldTest.kt | 480 ++++++++++++++++++ 4 files changed, 875 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/com/android/polybazaar/listing/ui/ListingLocationField.kt create mode 100644 app/src/test/java/com/android/polybazaar/listing/ui/ListingLocationFieldTest.kt diff --git a/app/src/main/java/com/android/polybazaar/listing/ui/CreateListingScreen.kt b/app/src/main/java/com/android/polybazaar/listing/ui/CreateListingScreen.kt index ebd7c887..a20be1ac 100644 --- a/app/src/main/java/com/android/polybazaar/listing/ui/CreateListingScreen.kt +++ b/app/src/main/java/com/android/polybazaar/listing/ui/CreateListingScreen.kt @@ -60,6 +60,7 @@ import com.android.polybazaar.listing.model.ListingRules.MAX_TITLE_LENGTH import com.android.polybazaar.listing.model.ListingType import com.android.polybazaar.listing.viewmodel.ListingFormUiState import com.android.polybazaar.listing.viewmodel.ListingFormViewModel +import com.android.polybazaar.map.model.Coordinates import java.time.LocalDate import kotlinx.coroutines.Dispatchers @@ -147,6 +148,12 @@ class ListingFormActions( /** Returns the URI the camera app writes the photo to, or null when none can be created. */ val startTakingPhoto: (retakeIndex: Int?) -> Uri? = { null }, val finishTakingPhoto: (saved: Boolean) -> Unit = {}, + /** Sets the location to the point confirmed on the map. */ + val onConfirmLocation: (Coordinates) -> Unit = {}, + val onLocationNameChange: (String) -> Unit = {}, + val onClearLocation: () -> Unit = {}, + /** Asks for the lender's position, for the map picker to open there. */ + val onLocateLender: () -> Unit = {}, val onSave: () -> Unit = {}, ) @@ -168,6 +175,10 @@ internal fun listingFormActions(viewModel: ListingFormViewModel) = onStoredPhotoShown = viewModel::loadStoredPhoto, startTakingPhoto = viewModel::startTakingPhoto, finishTakingPhoto = viewModel::finishTakingPhoto, + onConfirmLocation = viewModel::setLocationPoint, + onLocationNameChange = viewModel::updateLocationName, + onClearLocation = viewModel::clearLocation, + onLocateLender = viewModel::locateLender, onSave = viewModel::save, ) @@ -201,9 +212,14 @@ fun CreateListingScreen( * [ListingType]: items get a daily price and a refund value, services an hourly price. * * @param actions called when the user edits the form, adds photos or creates the listing. + * @param locationMap the location picker's map, replaced in tests. */ @Composable -fun CreateListingContent(uiState: ListingFormUiState, actions: ListingFormActions) { +fun CreateListingContent( + uiState: ListingFormUiState, + actions: ListingFormActions, + locationMap: ListingLocationMap = DefaultListingLocationMap, +) { Column( modifier = Modifier.fillMaxSize() @@ -221,7 +237,7 @@ fun CreateListingContent(uiState: ListingFormUiState, actions: ListingFormAction // The repository is still reading these photos, so none may be removed or replaced. enabled = !uiState.isSaving, ) - ListingDetailsFields(uiState = uiState, actions = actions) + ListingDetailsFields(uiState = uiState, actions = actions, locationMap = locationMap) } CreateListingFooter(uiState = uiState, onCreate = actions.onSave) } @@ -296,7 +312,8 @@ internal fun ListingTypeSelector( } /** - * Title, description, price, category, for items the refund value, and the available days. + * Title, description, price, category, for items the refund value, the available days and the + * location. * * @param priceHint shown under the price, such as when a price change only applies to new bookings. */ @@ -305,6 +322,7 @@ internal fun ListingDetailsFields( uiState: ListingFormUiState, actions: ListingFormActions, priceHint: String? = null, + locationMap: ListingLocationMap = DefaultListingLocationMap, ) { val texts = formTextsFor(uiState.type) FormField( @@ -363,6 +381,7 @@ internal fun ListingDetailsFields( // Not while saving: an edit form then shows the listing as saved, and would lose the change. enabled = uiState.canEdit && !uiState.isSaving, ) + ListingLocationField(uiState = uiState, actions = actions, map = locationMap) } /** diff --git a/app/src/main/java/com/android/polybazaar/listing/ui/EditListingScreen.kt b/app/src/main/java/com/android/polybazaar/listing/ui/EditListingScreen.kt index 3498059f..1e4f0512 100644 --- a/app/src/main/java/com/android/polybazaar/listing/ui/EditListingScreen.kt +++ b/app/src/main/java/com/android/polybazaar/listing/ui/EditListingScreen.kt @@ -1,4 +1,4 @@ -// Co-authored-by: Claude Code (Claude Fable 5.2) +// Co-authored-by: Claude Code (Claude Opus 5.5, Claude Fable 5.2) package com.android.polybazaar.listing.ui import androidx.activity.compose.BackHandler @@ -110,6 +110,7 @@ fun EditListingScreen( * @param onRetry loads the listing again after a failure. * @param storedPhotoBytes the saved photos downloaded so far, by Storage path, for their * thumbnails. + * @param locationMap the location picker's map, replaced in tests. */ @Composable fun EditListingContent( @@ -118,6 +119,7 @@ fun EditListingContent( onBack: () -> Unit, onRetry: () -> Unit, storedPhotoBytes: Map = emptyMap(), + locationMap: ListingLocationMap = DefaultListingLocationMap, ) { Column( modifier = @@ -161,6 +163,7 @@ fun EditListingContent( uiState = uiState, actions = actions, priceHint = stringResource(R.string.edit_listing_price_hint), + locationMap = locationMap, ) } EditListingFooter(uiState = uiState, onCancel = onBack, onSave = actions.onSave) diff --git a/app/src/main/java/com/android/polybazaar/listing/ui/ListingLocationField.kt b/app/src/main/java/com/android/polybazaar/listing/ui/ListingLocationField.kt new file mode 100644 index 00000000..37614c64 --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/listing/ui/ListingLocationField.kt @@ -0,0 +1,369 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.listing.ui + +import android.Manifest +import android.content.pm.PackageManager +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.core.content.ContextCompat +import com.android.polybazaar.R +import com.android.polybazaar.auth.ui.AuthBackButton +import com.android.polybazaar.auth.ui.AuthColors +import com.android.polybazaar.auth.ui.AuthPrimaryButton +import com.android.polybazaar.listing.model.ListingRules.MAX_LOCATION_NAME_LENGTH +import com.android.polybazaar.listing.model.ListingType +import com.android.polybazaar.listing.viewmodel.ListingFormUiState +import com.android.polybazaar.map.model.Coordinates +import com.google.android.gms.maps.model.CameraPosition +import com.google.android.gms.maps.model.LatLng +import com.google.maps.android.compose.CameraPositionState +import com.google.maps.android.compose.GoogleMap +import com.google.maps.android.compose.MapProperties +import com.google.maps.android.compose.MapUiSettings +import com.google.maps.android.compose.rememberCameraPositionState +import kotlin.math.abs + +object ListingLocationFieldTags { + const val FIELD = "listing_location_field" + const val MOVE_PIN = "listing_location_move_pin" + const val REMOVE = "listing_location_remove" + const val NAME_FIELD = "listing_location_name_field" + const val NAME_ERROR = "listing_location_name_error" + const val OFFLINE_HINT = "listing_location_offline_hint" + const val PICKER = "listing_location_picker" + const val PICKER_CLOSE = "listing_location_picker_close" + const val CENTRE_PIN = "listing_location_centre_pin" + const val SHOW_MY_LOCATION = "listing_location_show_my_location" + const val CONFIRM = "listing_location_confirm" +} + +/** + * The picker's map: it shows and moves `camera`, and shows the device once `showMyLocation` (the + * approximate location permission is granted). A parameter so tests can replace the Google map. + */ +typealias ListingLocationMap = + @Composable (camera: CameraPositionState, showMyLocation: Boolean) -> Unit + +val DefaultListingLocationMap: ListingLocationMap = { camera, showMyLocation -> + GoogleMap( + modifier = Modifier.fillMaxSize(), + cameraPositionState = camera, + contentDescription = stringResource(R.string.listing_location_map_description), + properties = MapProperties(isMyLocationEnabled = showMyLocation), + uiSettings = + MapUiSettings( + compassEnabled = false, + mapToolbarEnabled = false, + myLocationButtonEnabled = showMyLocation, + rotationGesturesEnabled = false, + tiltGesturesEnabled = false, + zoomControlsEnabled = false, + ), + ) +} + +private const val MAP_ZOOM = 16f +private val PIN_SIZE = 44.dp + +/** About 1 m: the map writes back a slightly different target after it lays out. */ +private const val FOLLOW_TOLERANCE_DEGREES = 1e-5 + +private fun LatLng.isNear(other: LatLng) = + abs(latitude - other.latitude) < FOLLOW_TOLERANCE_DEGREES && + abs(longitude - other.longitude) < FOLLOW_TOLERANCE_DEGREES + +private fun Coordinates.toLatLng() = LatLng(latitude, longitude) + +/** + * "Pickup location" (items) or "Meeting place" (services): "Choose on the map", which opens + * [ListingLocationPicker], or once chosen the place's name to edit, with move-pin and remove + * buttons. + */ +@Composable +internal fun ListingLocationField( + uiState: ListingFormUiState, + actions: ListingFormActions, + map: ListingLocationMap, +) { + var isPicking by rememberSaveable { mutableStateOf(false) } + // Not while saving: an edit form then shows the listing as saved, and would lose the change. + val enabled = uiState.canEdit && !uiState.isSaving + // The map needs the internet; removing the place or renaming it does not. + val canPick = enabled && uiState.isOnline + val location = uiState.location + val shape = RoundedCornerShape(14.dp) + val label = + stringResource( + if (uiState.type == ListingType.ITEM) R.string.listing_location_item_label + else R.string.listing_location_service_label + ) + val placeholder = stringResource(R.string.listing_location_placeholder) + val description = stringResource(R.string.listing_location_description, label, placeholder) + FormField( + label = label, + counter = location?.let { "${it.name.length}/$MAX_LOCATION_NAME_LENGTH" }, + ) { + if (location == null) { + Row( + modifier = + Modifier.fillMaxWidth() + .heightIn(min = 48.dp) + .alpha(if (canPick) 1f else 0.45f) + .background(AuthColors.Background, shape) + .border(1.dp, AuthColors.Outline, shape) + .clickable(enabled = canPick, role = Role.Button) { isPicking = true } + .semantics { contentDescription = description } + .padding(12.dp) + .testTag(ListingLocationFieldTags.FIELD), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = placeholder, + color = AuthColors.TextSecondary, + fontSize = 13.sp, + modifier = Modifier.weight(1f), + ) + Icon( + painter = painterResource(R.drawable.ic_map_pin), + contentDescription = null, + tint = AuthColors.TextSecondary, + modifier = Modifier.size(16.dp), + ) + } + } else { + Row(verticalAlignment = Alignment.CenterVertically) { + Box(modifier = Modifier.weight(1f)) { + FormTextField( + value = location.name, + onValueChange = actions.onLocationNameChange, + placeholder = stringResource(R.string.listing_location_name_placeholder), + tag = ListingLocationFieldTags.NAME_FIELD, + ) + } + LocationIconButton( + icon = R.drawable.ic_map_pin, + description = stringResource(R.string.listing_location_move_pin), + enabled = canPick, + tag = ListingLocationFieldTags.MOVE_PIN, + ) { + isPicking = true + } + LocationIconButton( + icon = R.drawable.ic_close, + description = stringResource(R.string.listing_location_remove), + enabled = enabled, + tag = ListingLocationFieldTags.REMOVE, + onClick = actions.onClearLocation, + ) + } + } + } + if (uiState.showLocationNameError) { + FieldError( + text = stringResource(R.string.listing_location_name_error), + tag = ListingLocationFieldTags.NAME_ERROR, + ) + } + if (!uiState.isOnline) { + Text( + text = stringResource(R.string.listing_location_offline), + color = AuthColors.TextSecondary, + fontSize = 12.sp, + modifier = Modifier.testTag(ListingLocationFieldTags.OFFLINE_HINT), + ) + } + if (isPicking) { + ListingLocationPicker( + suggestedPoint = uiState.suggestedPoint, + isOnline = uiState.isOnline, + onLocateLender = actions.onLocateLender, + onConfirm = { point -> + actions.onConfirmLocation(point) + isPicking = false + }, + onClose = { isPicking = false }, + map = map, + ) + } +} + +@Composable +private fun LocationIconButton( + icon: Int, + description: String, + enabled: Boolean, + tag: String, + onClick: () -> Unit, +) { + IconButton(onClick = onClick, enabled = enabled, modifier = Modifier.testTag(tag)) { + Icon( + painter = painterResource(icon), + contentDescription = description, + tint = AuthColors.TextSecondary, + modifier = Modifier.size(20.dp), + ) + } +} + +/** + * A full-screen map under a pin fixed at its centre: the user pans the map, then confirms the point + * under the pin. Closing it saves nothing. A dialog rather than a route, so it shares the form's + * ViewModel. + */ +@Composable +private fun ListingLocationPicker( + suggestedPoint: Coordinates, + isOnline: Boolean, + onLocateLender: () -> Unit, + onConfirm: (Coordinates) -> Unit, + onClose: () -> Unit, + map: ListingLocationMap, +) { + val camera = rememberCameraPositionState { + position = CameraPosition.fromLatLngZoom(suggestedPoint.toLatLng(), MAP_ZOOM) + } + // The camera follows the suggested point (the lender's position arriving, say) until the user + // moves the map away from the last point it followed. + var followed by remember { mutableStateOf(suggestedPoint.toLatLng()) } + LaunchedEffect(suggestedPoint) { + if (camera.position.target.isNear(followed)) { + followed = suggestedPoint.toLatLng() + camera.position = CameraPosition.fromLatLngZoom(followed, camera.position.zoom) + } + } + val context = LocalContext.current + var showMyLocation by remember { + mutableStateOf( + ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == + PackageManager.PERMISSION_GRANTED + ) + } + val requestPermission = + rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { + showMyLocation = it + } + LaunchedEffect(showMyLocation) { if (showMyLocation) onLocateLender() } + Dialog( + onDismissRequest = onClose, + properties = + DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false), + ) { + Column( + modifier = + Modifier.fillMaxSize() + .background(AuthColors.Background) + .safeDrawingPadding() + .testTag(ListingLocationFieldTags.PICKER) + ) { + Row( + modifier = Modifier.fillMaxWidth().height(54.dp).padding(horizontal = 18.dp), + horizontalArrangement = Arrangement.spacedBy(15.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + AuthBackButton( + onClick = onClose, + modifier = Modifier.testTag(ListingLocationFieldTags.PICKER_CLOSE), + ) + Text( + text = stringResource(R.string.listing_location_picker_title), + modifier = Modifier.semantics { heading() }, + color = AuthColors.TextPrimary, + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + ) + } + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + map(camera, showMyLocation) + Icon( + painter = painterResource(R.drawable.ic_map_pin), + contentDescription = null, + tint = Color.Unspecified, + modifier = + Modifier.align(Alignment.Center) + // Lifts the pin so its tip, at 22/24 of its height, marks the centre. + .offset(y = -PIN_SIZE * 5 / 12) + .size(PIN_SIZE) + .testTag(ListingLocationFieldTags.CENTRE_PIN), + ) + } + Column( + modifier = Modifier.padding(horizontal = 18.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = stringResource(R.string.listing_location_picker_hint), + color = AuthColors.TextSecondary, + fontSize = 13.sp, + ) + if (!showMyLocation) { + TextButton( + onClick = { requestPermission.launch(Manifest.permission.ACCESS_COARSE_LOCATION) }, + modifier = Modifier.fillMaxWidth().testTag(ListingLocationFieldTags.SHOW_MY_LOCATION), + ) { + Text( + text = stringResource(R.string.listing_location_show_mine), + color = AuthColors.Accent, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + ) + } + } + AuthPrimaryButton( + text = stringResource(R.string.listing_location_confirm), + onClick = { + // Read now, so it is what is under the pin at this moment, even mid-fling. + val target = camera.position.target + onConfirm(Coordinates(target.latitude, target.longitude)) + }, + enabled = isOnline, + modifier = + Modifier.fillMaxWidth().height(48.dp).testTag(ListingLocationFieldTags.CONFIRM), + ) + } + } + } +} diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/ListingLocationFieldTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/ListingLocationFieldTest.kt new file mode 100644 index 00000000..d3827966 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/listing/ui/ListingLocationFieldTest.kt @@ -0,0 +1,480 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.listing.ui + +import android.Manifest +import android.app.Application +import android.content.Context +import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.result.ActivityResultRegistry +import androidx.activity.result.ActivityResultRegistryOwner +import androidx.activity.result.contract.ActivityResultContract +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.assertContentDescriptionContains +import androidx.compose.ui.test.assertContentDescriptionEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertTextContains +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isHeading +import androidx.compose.ui.test.junit4.StateRestorationTester +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.test.performScrollTo +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextReplacement +import androidx.compose.ui.unit.dp +import androidx.core.app.ActivityOptionsCompat +import androidx.lifecycle.SavedStateHandle +import androidx.test.core.app.ApplicationProvider +import androidx.test.espresso.Espresso +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.polybazaar.R +import com.android.polybazaar.connectivity.model.FakeConnectivityRepository +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.listing.model.FakeListingRepository +import com.android.polybazaar.listing.model.FilePhotoStorage +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.ListingRules.MAX_LOCATION_NAME_LENGTH +import com.android.polybazaar.listing.model.ListingType +import com.android.polybazaar.listing.viewmodel.ListingFormUiState +import com.android.polybazaar.listing.viewmodel.ListingFormViewModel +import com.android.polybazaar.map.model.Campus +import com.android.polybazaar.map.model.Coordinates +import com.android.polybazaar.map.model.FakeLocationRepository +import com.google.android.gms.maps.model.CameraPosition +import com.google.android.gms.maps.model.LatLng +import java.time.LocalDate +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 +import org.robolectric.Shadows.shadowOf + +/** + * The "Pickup location" / "Meeting place" field of the listing forms and its map picker (#339), + * with a fake map that records the camera it shows and pans to [panTo] when tapped. + */ +@RunWith(AndroidJUnit4::class) +class ListingLocationFieldTest { + + @get:Rule val composeTestRule = createComposeRule() + + private val context = ApplicationProvider.getApplicationContext() + private val today = LocalDate.of(2026, 11, 17) + private val renens = Coordinates(46.5399, 6.5881) + private val lausanne = Coordinates(46.5197, 6.6323) + private val onRenens = + ListingFormUiState( + today = today, + location = ListingLocation(renens.latitude, renens.longitude, "Renens"), + suggestedPoint = renens, + ) + + /** The camera the map last showed, and whether it showed the device's location. */ + private var shownCamera: CameraPosition? = null + private var myLocationShown: Boolean? = null + private var panTo = renens + + /** Whether the map writes back a slightly different target once shown, as GoogleMap does. */ + private var nudge = false + + private val fakeMap: ListingLocationMap = { camera, showMyLocation -> + shownCamera = camera.position + myLocationShown = showMyLocation + if (nudge) + LaunchedEffect(Unit) { + val (lat, lng) = camera.position.target.let { it.latitude to it.longitude } + camera.position = CameraPosition.fromLatLngZoom(LatLng(lat + 1e-9, lng + 1e-9), 16f) + } + Box( + Modifier.size(40.dp).testTag(FAKE_MAP).clickable { + camera.position = + CameraPosition.fromLatLngZoom(LatLng(panTo.latitude, panTo.longitude), 16f) + } + ) + } + + private fun mapCentre() = shownCamera?.target?.let { Coordinates(it.latitude, it.longitude) } + + /** What the field asked for, in order. */ + private val calls = mutableListOf() + private val actions = + ListingFormActions( + onConfirmLocation = { calls += it }, + onLocationNameChange = { calls += "name:$it" }, + onClearLocation = { calls += "clear" }, + onLocateLender = { calls += "locate" }, + ) + + private var uiState by mutableStateOf(ListingFormUiState(today = today)) + + private fun node(tag: String) = composeTestRule.onNodeWithTag(tag) + + private fun string(id: Int, vararg args: Any) = context.getString(id, *args) + + private fun setContent( + registry: FakePermissionRegistry = FakePermissionRegistry(), + restoration: StateRestorationTester? = null, + content: @Composable () -> Unit, + ) { + val owner = + object : ActivityResultRegistryOwner { + override val activityResultRegistry = registry + } + val provided = + @Composable { + CompositionLocalProvider( + LocalActivityResultRegistryOwner provides owner, + content = content, + ) + } + if (restoration != null) restoration.setContent(provided) + else composeTestRule.setContent(provided) + } + + /** Shows the field alone, reading [uiState] so tests can change it. */ + private fun showField( + state: ListingFormUiState, + registry: FakePermissionRegistry = FakePermissionRegistry(), + restoration: StateRestorationTester? = null, + map: ListingLocationMap = fakeMap, + ) { + uiState = state + setContent(registry, restoration) { + Column(Modifier.verticalScroll(rememberScrollState())) { + ListingLocationField(uiState = uiState, actions = actions, map = map) + } + } + } + + /** + * Opens the picker from "Choose on the map", or with a location set from [tag], the pin button. + */ + private fun openPicker(tag: String = ListingLocationFieldTags.FIELD) { + node(tag).performScrollTo().performClick() + node(ListingLocationFieldTags.PICKER).assertIsDisplayed() + } + + private fun assertNameIs(name: String) { + node(ListingLocationFieldTags.NAME_FIELD).assertTextContains(name) + } + + @Test + fun withoutLocation_offersTheMapWithoutRemoveOrName() { + showField(ListingFormUiState(today = today)) + + node(ListingLocationFieldTags.FIELD) + .assertContentDescriptionEquals( + string( + R.string.listing_location_description, + string(R.string.listing_location_item_label), + string(R.string.listing_location_placeholder), + ) + ) + uiState = uiState.copy(type = ListingType.SERVICE) + node(ListingLocationFieldTags.FIELD) + .assertContentDescriptionContains(string(R.string.listing_location_service_label), true) + node(ListingLocationFieldTags.REMOVE).assertDoesNotExist() + node(ListingLocationFieldTags.NAME_FIELD).assertDoesNotExist() + node(ListingLocationFieldTags.NAME_ERROR).assertDoesNotExist() + node(ListingLocationFieldTags.PICKER).assertDoesNotExist() + node(ListingLocationFieldTags.OFFLINE_HINT).assertDoesNotExist() + } + + @Test + fun withANamedLocation_showsItAndEditsOrRemovesIt() { + showField(onRenens) + + assertNameIs("Renens") + node(ListingLocationFieldTags.FIELD).assertDoesNotExist() + composeTestRule.onNodeWithText("6/$MAX_LOCATION_NAME_LENGTH").assertIsDisplayed() + node(ListingLocationFieldTags.NAME_ERROR).assertDoesNotExist() + node(ListingLocationFieldTags.NAME_FIELD).performTextReplacement("Gare") + node(ListingLocationFieldTags.REMOVE).performClick() + + assertEquals(listOf("name:Gare", "clear"), calls) + } + + @Test + fun withABlankName_asksForAName() { + showField(onRenens.copy(location = onRenens.location!!.copy(name = ""))) + + composeTestRule.onNodeWithText("0/$MAX_LOCATION_NAME_LENGTH").assertIsDisplayed() + node(ListingLocationFieldTags.NAME_ERROR) + .assertTextEquals(string(R.string.listing_location_name_error)) + } + + @Test + fun whenTheFormCannotBeEditedIsSavingOrOffline_theFieldIsDisabled() { + showField(onRenens.copy(loadError = AppError.NETWORK)) + for (state in + listOf(onRenens.copy(loadError = AppError.NETWORK), onRenens.copy(isSaving = true))) { + uiState = state + node(ListingLocationFieldTags.MOVE_PIN).assertIsNotEnabled().performClick() + node(ListingLocationFieldTags.REMOVE).assertIsNotEnabled().performClick() + node(ListingLocationFieldTags.PICKER).assertDoesNotExist() + } + uiState = ListingFormUiState(today = today, isSaving = true) + node(ListingLocationFieldTags.FIELD).assertIsNotEnabled().performClick() + node(ListingLocationFieldTags.PICKER).assertDoesNotExist() + // Offline the map cannot be opened, but the place can still be removed. + uiState = onRenens.copy(isOnline = false) + node(ListingLocationFieldTags.OFFLINE_HINT).assertIsDisplayed() + node(ListingLocationFieldTags.MOVE_PIN).assertIsNotEnabled() + node(ListingLocationFieldTags.REMOVE).assertIsEnabled() + uiState = ListingFormUiState(today = today, isOnline = false) + node(ListingLocationFieldTags.FIELD).assertIsNotEnabled() + assertTrue(calls.isEmpty()) + } + + @Test + fun picker_opensOnTheSuggestedPointAndConfirmsIt() { + showField(onRenens) + openPicker(ListingLocationFieldTags.MOVE_PIN) + + assertEquals(renens, mapCentre()) + assertEquals(16f, shownCamera!!.zoom) + node(ListingLocationFieldTags.CENTRE_PIN).assertIsDisplayed() + node(ListingLocationFieldTags.CONFIRM).performClick() + + assertEquals(listOf(renens), calls) + node(ListingLocationFieldTags.PICKER).assertDoesNotExist() + } + + @Test + fun picker_confirmsThePointUnderThePinAfterPanning() { + showField(ListingFormUiState(today = today)) + openPicker() + assertEquals(Campus.EPFL.centre, mapCentre()) + + node(FAKE_MAP).performClick() + node(ListingLocationFieldTags.CONFIRM).performClick() + + assertEquals(listOf(renens), calls) + node(ListingLocationFieldTags.PICKER).assertDoesNotExist() + } + + @Test + fun picker_closeAndSystemBackSaveNothing() { + showField(ListingFormUiState(today = today)) + + openPicker() + node(FAKE_MAP).performClick() + node(ListingLocationFieldTags.PICKER_CLOSE).performClick() + node(ListingLocationFieldTags.PICKER).assertDoesNotExist() + + openPicker() + node(FAKE_MAP).performClick() + uiState = uiState.copy(isOnline = false) + node(ListingLocationFieldTags.CONFIRM).assertIsNotEnabled().performClick() + Espresso.pressBack() + node(ListingLocationFieldTags.PICKER).assertDoesNotExist() + node(ListingLocationFieldTags.FIELD).assertExists() + + assertTrue(calls.isEmpty()) + } + + @Test + fun picker_staysOpenWhereItWasWhenTheScreenIsRecreated() { + val restoration = StateRestorationTester(composeTestRule) + showField(ListingFormUiState(today = today), restoration = restoration) + openPicker() + node(FAKE_MAP).performClick() + + restoration.emulateSavedInstanceStateRestore() + + node(ListingLocationFieldTags.PICKER).assertIsDisplayed() + assertEquals(renens, mapCentre()) + } + + @Test + fun picker_followsTheSuggestedPointUntilTheMapIsMoved() { + showField(ListingFormUiState(today = today)) + openPicker() + + uiState = uiState.copy(suggestedPoint = lausanne) + composeTestRule.waitForIdle() + assertEquals(lausanne, mapCentre()) + assertEquals(16f, shownCamera!!.zoom) + + node(FAKE_MAP).performClick() + uiState = uiState.copy(suggestedPoint = Campus.UNIL.centre) + composeTestRule.waitForIdle() + assertEquals(renens, mapCentre()) + } + + @Test + fun picker_followsTheSuggestedPointAfterTheMapNudgesTheCamera() { + nudge = true + showField(ListingFormUiState(today = today)) + openPicker() + val title = string(R.string.listing_location_picker_title) + composeTestRule.onNode(hasText(title) and isHeading()).assertExists() + assertNotEquals(Campus.EPFL.centre, mapCentre()) + + uiState = uiState.copy(suggestedPoint = lausanne) + composeTestRule.waitForIdle() + assertEquals(lausanne, mapCentre()) + } + + @Test + fun showMyLocation_withoutPermission_asksWhenTappedAndLocatesOnceGranted() { + val registry = FakePermissionRegistry(ArrayDeque(listOf(false, true))) + showField(ListingFormUiState(today = today), registry) + openPicker() + assertEquals(false, myLocationShown) + + // Refused: nothing changes, and the button stays to ask again. + node(ListingLocationFieldTags.SHOW_MY_LOCATION).performClick() + assertEquals(false, myLocationShown) + assertTrue(calls.isEmpty()) + + node(ListingLocationFieldTags.SHOW_MY_LOCATION).performClick() + + assertEquals(List(2) { Manifest.permission.ACCESS_COARSE_LOCATION }, registry.requested) + node(ListingLocationFieldTags.SHOW_MY_LOCATION).assertDoesNotExist() + assertEquals(true, myLocationShown) + assertEquals(listOf("locate"), calls) + } + + @Test + fun showMyLocation_withPermission_locatesWithoutAsking() { + shadowOf(context as Application).grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION) + val registry = FakePermissionRegistry() + showField(ListingFormUiState(today = today), registry) + openPicker() + + node(ListingLocationFieldTags.SHOW_MY_LOCATION).assertDoesNotExist() + assertEquals(true, myLocationShown) + assertTrue(registry.requested.isEmpty()) + assertEquals(listOf("locate"), calls) + } + + // Through a real ListingFormViewModel: the confirmed location is saved with the listing. + + private fun viewModel(repository: FakeListingRepository, listingId: String?) = + ListingFormViewModel( + listingId, + repository, + FilePhotoStorage( + context, + if (listingId == null) FilePhotoStorage.CREATE_FORM else FilePhotoStorage.EDIT_FORM, + ), + SavedStateHandle(), + FakeLocationRepository(lausanne), + FakeConnectivityRepository(), + ) { + today + } + + @Test + fun create_opensOnTheLenderAndSavesTheNamedLocation() { + shadowOf(context as Application).grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION) + val repository = FakeListingRepository() + val viewModel = viewModel(repository, listingId = null) + setContent { + CreateListingContent( + uiState = viewModel.uiState.collectAsState().value, + actions = listingFormActions(viewModel), + locationMap = fakeMap, + ) + } + node(CreateListingScreenTags.TITLE_FIELD).performTextInput("Drill") + node(CreateListingScreenTags.DESCRIPTION_FIELD).performTextInput("Works well") + node(CreateListingScreenTags.PRICE_FIELD).performTextInput("5") + node(CreateListingScreenTags.CATEGORY_FIELD).performClick() + node(CreateListingScreenTags.categoryOption(ListingCategory.ITEM_TOOLS)).performClick() + + openPicker() + composeTestRule.waitForIdle() + assertEquals(lausanne, mapCentre()) + node(ListingLocationFieldTags.CONFIRM).performClick() + node(ListingLocationFieldTags.NAME_ERROR).performScrollTo().assertIsDisplayed() + node(ListingLocationFieldTags.NAME_FIELD).performTextReplacement("Flon") + node(CreateListingScreenTags.CREATE_BUTTON).performScrollTo().performClick() + composeTestRule.waitForIdle() + + assertEquals( + ListingLocation(lausanne.latitude, lausanne.longitude, "Flon"), + repository.allListings.single().location, + ) + } + + @Test + fun edit_savesTheCampusPickedOnTheMap() { + val drill = + ItemListing( + listingId = "drill", + category = ListingCategory.ITEM_TOOLS, + price = 12.0, + title = "Bosch drill", + description = "Cordless", + ) + val repository = FakeListingRepository(myListings = listOf(drill)) + val viewModel = viewModel(repository, listingId = "drill") + panTo = Campus.UNIL.centre + setContent { + EditListingContent( + uiState = viewModel.uiState.collectAsState().value, + actions = listingFormActions(viewModel), + onBack = {}, + onRetry = {}, + locationMap = fakeMap, + ) + } + + openPicker() + node(FAKE_MAP).performClick() + node(ListingLocationFieldTags.CONFIRM).performClick() + assertNameIs("UNIL campus") + node(EditListingScreenTags.SAVE_BUTTON).performScrollTo().performClick() + composeTestRule.waitForIdle() + + assertEquals( + ListingLocation(Campus.UNIL.centre.latitude, Campus.UNIL.centre.longitude, "UNIL campus"), + repository.updatedListings.single().location, + ) + } + + /** Stands in for the permission dialog: answers each request with the next of [answers]. */ + private class FakePermissionRegistry(private val answers: ArrayDeque = ArrayDeque()) : + ActivityResultRegistry() { + val requested = mutableListOf() + + override fun onLaunch( + requestCode: Int, + contract: ActivityResultContract, + input: I, + options: ActivityOptionsCompat?, + ) { + requested += input + dispatchResult(requestCode, answers.removeFirst()) + } + } + + private companion object { + const val FAKE_MAP = "fake_location_map" + } +} From 431c6a8dbf81dc2f7d75de65a409e6c1dcab8614 Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:58:32 +0100 Subject: [PATCH 3/4] fix(listing): flag a missing place name once its field loses focus #366 now shows the location name error only after leaveLocationNameField(), like price and refund. Call it when the name field loses focus, so the error appears after the lender leaves the field blank instead of never. Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/listing/ui/CreateListingScreen.kt | 3 +++ .../polybazaar/listing/ui/ListingLocationField.kt | 1 + .../listing/ui/ListingLocationFieldTest.kt | 12 ++++++++++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/listing/ui/CreateListingScreen.kt b/app/src/main/java/com/android/polybazaar/listing/ui/CreateListingScreen.kt index a20be1ac..5f169823 100644 --- a/app/src/main/java/com/android/polybazaar/listing/ui/CreateListingScreen.kt +++ b/app/src/main/java/com/android/polybazaar/listing/ui/CreateListingScreen.kt @@ -151,6 +151,8 @@ class ListingFormActions( /** Sets the location to the point confirmed on the map. */ val onConfirmLocation: (Coordinates) -> Unit = {}, val onLocationNameChange: (String) -> Unit = {}, + /** The location's name field lost focus: a missing name is flagged from then on. */ + val onLocationNameFieldLeft: () -> Unit = {}, val onClearLocation: () -> Unit = {}, /** Asks for the lender's position, for the map picker to open there. */ val onLocateLender: () -> Unit = {}, @@ -177,6 +179,7 @@ internal fun listingFormActions(viewModel: ListingFormViewModel) = finishTakingPhoto = viewModel::finishTakingPhoto, onConfirmLocation = viewModel::setLocationPoint, onLocationNameChange = viewModel::updateLocationName, + onLocationNameFieldLeft = viewModel::leaveLocationNameField, onClearLocation = viewModel::clearLocation, onLocateLender = viewModel::locateLender, onSave = viewModel::save, diff --git a/app/src/main/java/com/android/polybazaar/listing/ui/ListingLocationField.kt b/app/src/main/java/com/android/polybazaar/listing/ui/ListingLocationField.kt index 37614c64..0d8f8999 100644 --- a/app/src/main/java/com/android/polybazaar/listing/ui/ListingLocationField.kt +++ b/app/src/main/java/com/android/polybazaar/listing/ui/ListingLocationField.kt @@ -182,6 +182,7 @@ internal fun ListingLocationField( onValueChange = actions.onLocationNameChange, placeholder = stringResource(R.string.listing_location_name_placeholder), tag = ListingLocationFieldTags.NAME_FIELD, + onFocusLost = actions.onLocationNameFieldLeft, ) } LocationIconButton( diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/ListingLocationFieldTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/ListingLocationFieldTest.kt index d3827966..a0e7851a 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/ListingLocationFieldTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/ListingLocationFieldTest.kt @@ -218,10 +218,14 @@ class ListingLocationFieldTest { } @Test - fun withABlankName_asksForAName() { - showField(onRenens.copy(location = onRenens.location!!.copy(name = ""))) + fun withABlankName_asksForANameOnceTheFieldWasLeft() { + val unnamed = onRenens.copy(location = onRenens.location!!.copy(name = "")) + showField(unnamed) composeTestRule.onNodeWithText("0/$MAX_LOCATION_NAME_LENGTH").assertIsDisplayed() + node(ListingLocationFieldTags.NAME_ERROR).assertDoesNotExist() + + uiState = unnamed.copy(locationNameTouched = true) node(ListingLocationFieldTags.NAME_ERROR) .assertTextEquals(string(R.string.listing_location_name_error)) } @@ -411,6 +415,10 @@ class ListingLocationFieldTest { composeTestRule.waitForIdle() assertEquals(lausanne, mapCentre()) node(ListingLocationFieldTags.CONFIRM).performClick() + // No error before the lender has had a chance to name the place. + node(ListingLocationFieldTags.NAME_ERROR).assertDoesNotExist() + node(ListingLocationFieldTags.NAME_FIELD).performScrollTo().performClick() + node(CreateListingScreenTags.TITLE_FIELD).performScrollTo().performClick() node(ListingLocationFieldTags.NAME_ERROR).performScrollTo().assertIsDisplayed() node(ListingLocationFieldTags.NAME_FIELD).performTextReplacement("Flon") node(CreateListingScreenTags.CREATE_BUTTON).performScrollTo().performClick() From 3c3f3a58d96fd2ea8794060d631a203e5868986d Mon Sep 17 00:00:00 2001 From: thanna23 <148076306+thanna23@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:09:23 +0100 Subject: [PATCH 4/4] fix(listing): keep the map picker from crashing on Android 9+ --- 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 fae0ddb6..842d2724 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -55,6 +55,13 @@ + + \ No newline at end of file