From 0940c384165618669c34bcdd8c85652f623dd42f Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Tue, 17 Nov 2026 21:06:27 +0100 Subject: [PATCH 1/5] refactor(chat): share the attempt helper between the chat ViewModels --- .../polybazaar/chat/viewmodel/Attempt.kt | 20 +++++++++++++++++++ .../chat/viewmodel/InboxViewModel.kt | 16 --------------- 2 files changed, 20 insertions(+), 16 deletions(-) create mode 100644 app/src/main/java/com/android/polybazaar/chat/viewmodel/Attempt.kt diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/Attempt.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/Attempt.kt new file mode 100644 index 00000000..c8a9184a --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/Attempt.kt @@ -0,0 +1,20 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.chat.viewmodel + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive + +/** + * Runs [block] and returns its result, or its failure. A [CancellationException] is rethrown only + * when the calling coroutine is itself cancelled, so cancelling a load still stops it. One thrown + * by a call that was cancelled on its own, such as a cancelled Firebase task, is returned as a + * failure like any other, so it cannot leave a screen loading forever. + */ +internal suspend fun attempt(block: suspend () -> T): Result = + try { + Result.success(block()) + } catch (exception: Exception) { + if (exception is CancellationException) currentCoroutineContext().ensureActive() + Result.failure(exception) + } diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/InboxViewModel.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/InboxViewModel.kt index 9728f9fc..a20969e9 100644 --- a/app/src/main/java/com/android/polybazaar/chat/viewmodel/InboxViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/InboxViewModel.kt @@ -17,8 +17,6 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -267,20 +265,6 @@ class InboxViewModel( } } -/** - * Runs [block] and returns its result, or its failure. A [CancellationException] is rethrown only - * when the calling coroutine is itself cancelled, so loading again still drops the old load. One - * thrown by a call that was cancelled on its own, such as a cancelled Firebase task, is returned as - * a failure like any other, so it cannot leave the inbox loading forever. - */ -private suspend fun attempt(block: suspend () -> T): Result = - try { - Result.success(block()) - } catch (exception: Exception) { - if (exception is CancellationException) currentCoroutineContext().ensureActive() - Result.failure(exception) - } - /** A listing as read for the inbox: [listing] is null when it could not be read. */ private data class ListingLookup(val listing: Listing?, val status: ListingStatus) From 4a4b0b18f0ac86311b85b3f8c4dba8ec02b97a69 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Tue, 17 Nov 2026 21:12:05 +0100 Subject: [PATCH 2/5] feat(chat): expose the listing, the role and both photos to the conversation screen --- .../chat/viewmodel/ConversationViewModel.kt | 60 ++++++++++++++++++- .../viewmodel/ConversationViewModelTest.kt | 2 +- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt index 56bc3770..33a388b5 100644 --- a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt @@ -43,8 +43,16 @@ enum class ConversationListingStatus { * conversation. Null until either is known. * @property listingStatus the state of the listing, kept up to date while the screen is open, or * null until it is known. + * @property listing the listing as last observed. Kept after it is deleted, and null when it was + * never read. + * @property listingPhoto the listing's first photo, or null while it is missing, downloading or + * failed to download. + * @property isRenter whether the signed-in user is the renter, so the other participant is the + * lender. * @property otherUser profile of the other participant, or null while it loads, after a failure, or * when they have no profile. + * @property otherUserPhoto the other participant's profile photo, or null while it is missing, + * downloading or failed to download. * @property draft the message being typed. * @property canSend whether the draft can be sent now. * @property firstMessageBlockedByPause true when the renter has no conversation yet and the listing @@ -62,7 +70,11 @@ data class ConversationUiState( val conversation: Conversation? = null, val listingTitle: String? = null, val listingStatus: ConversationListingStatus? = null, + val listing: Listing? = null, + val listingPhoto: ByteArray? = null, + val isRenter: Boolean = false, val otherUser: User? = null, + val otherUserPhoto: ByteArray? = null, val draft: String = "", val canSend: Boolean = false, val firstMessageBlockedByPause: Boolean = false, @@ -93,7 +105,8 @@ class ConversationViewModel( private val listingRepository: ListingRepository, ) : ViewModel() { - private val _uiState = MutableStateFlow(ConversationUiState(myUid = myUid)) + private val _uiState = + MutableStateFlow(ConversationUiState(myUid = myUid, isRenter = myUid == renterUid)) val uiState: StateFlow = _uiState.asStateFlow() // Read by derived(), which a write failure can run from a Firestore background thread. @@ -113,6 +126,14 @@ class ConversationViewModel( private var sendInFlight = false private var lastMarkedReadAt: Instant? = null private var isVisible = false + private val listingPhoto = + PhotoDownload(listingRepository::loadListingImage) { state, photo -> + state.copy(listingPhoto = photo) + } + private val otherUserPhoto = + PhotoDownload(profileRepository::loadProfilePhoto) { state, photo -> + state.copy(otherUserPhoto = photo) + } init { observeListing() @@ -276,6 +297,7 @@ class ConversationViewModel( _uiState.update { (if (clearError) it.copy(loadError = null) else it).derived() } updateLoading() observeOtherUser() + listingPhoto.show(loaded.listing?.imagePaths?.firstOrNull()) } private fun observeConversation() { @@ -351,7 +373,10 @@ class ConversationViewModel( // The chat works without the profile, so no error is shown; toAppError() still logs // unrecognised failures. .catch { exception -> exception.toAppError() } - .collect { user -> _uiState.update { it.copy(otherUser = user) } } + .collect { user -> + _uiState.update { it.copy(otherUser = user) } + otherUserPhoto.show(user?.photoPath) + } } } @@ -375,6 +400,7 @@ class ConversationViewModel( return copy( listingTitle = listing?.title ?: conversation?.listingTitle, listingStatus = status, + listing = listing, canSend = sendable, firstMessageBlockedByPause = status == ConversationListingStatus.PAUSED && @@ -383,4 +409,34 @@ class ConversationViewModel( conversationKnown, ) } + + /** + * One photo of the screen, set into the state by [set]. It is downloaded with [download] once per + * Storage path, and again only when the path changes, which drops the older photo and any + * download of it still running. A failed download, a stray [CancellationException] included, + * leaves the photo missing without an error: the screen shows a placeholder. Only used on the + * main thread. + */ + private inner class PhotoDownload( + private val download: suspend (String) -> ByteArray, + private val set: (ConversationUiState, ByteArray?) -> ConversationUiState, + ) { + private var path: String? = null + private var job: Job? = null + + fun show(newPath: String?) { + if (newPath == path) return + path = newPath + job?.cancel() + _uiState.update { set(it, null) } + if (newPath == null) return + job = viewModelScope.launch { + attempt { download(newPath) } + .onSuccess { photo -> + // A download that ignored its cancellation must not replace a newer photo. + if (path == newPath) _uiState.update { set(it, photo) } + } + } + } + } } diff --git a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt index bb884ba0..80a907cb 100644 --- a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt @@ -110,7 +110,7 @@ class ConversationViewModelTest { val viewModel = viewModel() - assertEquals(ConversationUiState(myUid = renter.uid), viewModel.uiState.value) + assertEquals(ConversationUiState(myUid = renter.uid, isRenter = true), viewModel.uiState.value) advance() val state = viewModel.uiState.value assertFalse(state.isLoading) From ddad095dd1ab3681893a4be9b742158f39c5bb5f Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Tue, 17 Nov 2026 21:06:27 +0100 Subject: [PATCH 3/5] refactor(chat): share the photo helpers and badge colours between chat screens --- .../polybazaar/chat/ui/ChatComponents.kt | 74 +++++++++++++++++++ .../android/polybazaar/chat/ui/InboxScreen.kt | 52 +------------ 2 files changed, 75 insertions(+), 51 deletions(-) create mode 100644 app/src/main/java/com/android/polybazaar/chat/ui/ChatComponents.kt diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ChatComponents.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ChatComponents.kt new file mode 100644 index 00000000..c2dc19aa --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ChatComponents.kt @@ -0,0 +1,74 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.chat.ui + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.painter.BitmapPainter +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.android.polybazaar.R +import com.android.polybazaar.auth.ui.AuthColors +import com.android.polybazaar.listing.ui.decodePhotoPreview + +/** Text of the "Paused" listing badges, from the Figma. */ +internal val PausedBadgeText = Color(0xFF8C491F) + +/** Fill of the "Deleted" listing badges, from the Figma. */ +internal val DeletedBadgeBackground = Color(0xFFF2EAE5) + +/** Text of the "Deleted" listing badges, from the Figma. */ +internal val DeletedBadgeText = Color(0xFF67564D) + +/** The listing's photo, or a placeholder with an image icon while it is missing. */ +@Composable +internal fun ListingPhoto(photo: ImageBitmap?, size: Dp, modifier: Modifier = Modifier) { + Box( + modifier = + modifier + .size(size) + .clip(RoundedCornerShape(12.dp)) + .background(AuthColors.AccentContainer), + contentAlignment = Alignment.Center, + ) { + if (photo != null) { + // Decorative: the text next to it names the listing. + Image( + painter = BitmapPainter(photo), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.size(size), + ) + } else { + Icon( + painter = painterResource(R.drawable.ic_image), + contentDescription = null, + tint = AuthColors.TextSecondary, + modifier = Modifier.size(20.dp), + ) + } + } +} + +/** Decodes the downloaded [photo] off the main thread. Null while missing or decoding. */ +@Composable +internal fun rememberPhoto(photo: ByteArray?): ImageBitmap? { + val decoded by + produceState(initialValue = null, photo) { + value = photo?.let { decodePhotoPreview(it) } + } + return decoded +} diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt index 8a659be2..a8a56260 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt @@ -29,7 +29,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.produceState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -61,7 +60,6 @@ import com.android.polybazaar.chat.viewmodel.InboxViewModel import com.android.polybazaar.chat.viewmodel.ListingStatus import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message -import com.android.polybazaar.listing.ui.decodePhotoPreview import java.time.Duration import java.time.Instant @@ -120,15 +118,6 @@ internal fun inboxBody(state: InboxUiState): InboxBody = /** Side margin of the page, the x of the header and the rows in the Figma. */ private val PageMargin = 18.dp -/** Text of the "Listing paused" badge, from the Figma. */ -private val PausedBadgeText = Color(0xFF8C491F) - -/** Fill of the "Listing deleted" badge, from the Figma. */ -private val DeletedBadgeBackground = Color(0xFFF2EAE5) - -/** Text of the "Listing deleted" badge, from the Figma. */ -private val DeletedBadgeText = Color(0xFF67564D) - /** * The inbox screen: loads the conversations of [myUid], the signed-in user, into [viewModel] and * shows them. Retry loads them again. @@ -360,7 +349,7 @@ private fun ConversationRow( horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically, ) { - ListingPhoto(photo = rememberPhoto(row.listingPhotoPath?.let { photos[it] })) + ListingPhoto(photo = rememberPhoto(row.listingPhotoPath?.let { photos[it] }), size = 48.dp) Column( modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp), @@ -446,35 +435,6 @@ private fun UnreadDot(isUnread: Boolean) { } } -/** The listing's photo, or a placeholder with an image icon while it is missing. */ -@Composable -private fun ListingPhoto(photo: ImageBitmap?) { - Box( - modifier = - Modifier.size(48.dp) - .clip(RoundedCornerShape(12.dp)) - .background(AuthColors.AccentContainer), - contentAlignment = Alignment.Center, - ) { - if (photo != null) { - // Decorative: the title next to it names the listing. - Image( - painter = BitmapPainter(photo), - contentDescription = null, - contentScale = ContentScale.Crop, - modifier = Modifier.size(48.dp), - ) - } else { - Icon( - painter = painterResource(R.drawable.ic_image), - contentDescription = null, - tint = AuthColors.TextSecondary, - modifier = Modifier.size(20.dp), - ) - } - } -} - /** * The other person's photo (the default one while missing) and "@username". Without a profile, only * the default photo shows. @@ -562,16 +522,6 @@ private fun Footer() { ) } -/** Decodes the downloaded [photo] off the main thread. Null while missing or decoding. */ -@Composable -private fun rememberPhoto(photo: ByteArray?): ImageBitmap? { - val decoded by - produceState(initialValue = null, photo) { - value = photo?.let { decodePhotoPreview(it) } - } - return decoded -} - /** * A row in each listing status, for the IDE preview: an unread one, read ones with and without * "You: ", and one without a preview. Internal so a test can render it too. From 29f1b6011e18c6a0f7e6b14b008f1473c6e5a0e3 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Tue, 17 Nov 2026 21:12:05 +0100 Subject: [PATCH 4/5] test(chat): cover the conversation's listing, role and photos --- .../viewmodel/ConversationViewModelTest.kt | 204 ++++++++++++++++++ .../profile/model/FakeProfileRepository.kt | 29 ++- 2 files changed, 225 insertions(+), 8 deletions(-) diff --git a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt index 80a907cb..1725074b 100644 --- a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt @@ -10,6 +10,7 @@ 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.ListingRepository import com.android.polybazaar.profile.model.FakeProfileRepository import com.google.firebase.firestore.FirebaseFirestoreException import java.net.UnknownHostException @@ -17,14 +18,18 @@ import java.time.Instant import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withContext import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame import org.junit.Assert.assertNull +import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -966,4 +971,203 @@ class ConversationViewModelTest { assertEquals(listOf(unreadReply.id), chat.markedRead) } + + @Test + fun listing_isExposed_andKeptAfterItIsDeleted() { + val viewModel = loadedViewModel() + assertEquals(listing, viewModel.uiState.value.listing) + + listings.allListings = emptyList() + advance() + + val state = viewModel.uiState.value + assertEquals(ConversationListingStatus.DELETED, state.listingStatus) + assertEquals(listing, state.listing) + } + + @Test + fun listing_deletedBeforeTheScreenOpened_isNull() { + listings = FakeListingRepository() + givenConversation(messages = arrayOf(hello)) + + val state = loadedViewModel().uiState.value + + assertEquals(ConversationListingStatus.DELETED, state.listingStatus) + assertNull(state.listing) + assertNull(state.listingPhoto) + assertEquals(0, listings.loadedImagePaths.size) + } + + @Test + fun isRenter_tellsTheRenterFromTheLender() { + assertTrue(viewModel(renter.uid).uiState.value.isRenter) + assertFalse(viewModel(lender.uid).uiState.value.isRenter) + } + + @Test + fun listingPhoto_isDownloadedOnce_andAgainOnlyWhenTheFirstPathChanges() { + val first = byteArrayOf(1) + val replaced = byteArrayOf(3) + listings.images["drill/1"] = first + listings.images["drill/3"] = replaced + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/1", "drill/2"))) + val viewModel = loadedViewModel() + assertSame(first, viewModel.uiState.value.listingPhoto) + + listings.allListings = + listOf(listing.copy(title = "Bosch drill and bits", imagePaths = listOf("drill/1"))) + advance() + assertEquals(listOf("drill/1"), listings.loadedImagePaths) + assertSame(first, viewModel.uiState.value.listingPhoto) + + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/3"))) + advance() + assertEquals(listOf("drill/1", "drill/3"), listings.loadedImagePaths) + assertSame(replaced, viewModel.uiState.value.listingPhoto) + } + + @Test + fun listingPhoto_isKeptAfterTheListingIsDeleted_andDroppedWhenTheListingLosesItsPhotos() { + val photo = byteArrayOf(1) + listings.images["drill/1"] = photo + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/1"))) + val viewModel = loadedViewModel() + + listings.allListings = emptyList() + advance() + assertSame(photo, viewModel.uiState.value.listingPhoto) + assertEquals(listOf("drill/1"), listings.loadedImagePaths) + + listings.allListings = listOf(listing) + advance() + assertNull(viewModel.uiState.value.listingPhoto) + } + + @Test + fun listingPhoto_failedDownload_isMissingWithoutError_andNotRetriedForTheSamePath() { + listings.imageFailure = UnknownHostException("offline") + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/1"))) + givenConversation(messages = arrayOf(hello)) + val viewModel = loadedViewModel() + + listings.allListings = listOf(listing.copy(title = "Renamed", imagePaths = listOf("drill/1"))) + advance() + + val state = viewModel.uiState.value + assertNull(state.listingPhoto) + assertNull(state.loadError) + assertEquals(listOf(hello), state.messages) + assertEquals(listOf("drill/1"), listings.loadedImagePaths) + } + + @Test + fun listingPhoto_aStaleDownloadFinishingAfterANewerPath_doesNotReplaceTheNewerPhoto() { + val stale = byteArrayOf(1) + val current = byteArrayOf(3) + listings.images["drill/3"] = current + val staleGate = CompletableDeferred() + // The old path's download ignores its cancellation, like a Storage call that can't be stopped, + // so only the ViewModel's own check keeps its photo out. + val repository = + object : ListingRepository by listings { + override suspend fun loadListingImage(imagePath: String): ByteArray = + if (imagePath == "drill/1") { + withContext(NonCancellable) { staleGate.await() } + stale + } else listings.loadListingImage(imagePath) + } + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/1"))) + val viewModel = + ConversationViewModel( + listing.listingId!!, + renter.uid, + renter.uid, + chat, + profiles, + repository, + ) + advance() + + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/3"))) + advance() + assertSame(current, viewModel.uiState.value.listingPhoto) + + staleGate.complete(Unit) + advance() + assertSame(current, viewModel.uiState.value.listingPhoto) + } + + @Test + fun otherUserPhoto_isDownloadedOnce() { + profiles = + FakeProfileRepository( + listOf(lender.copy(photoPath = "profiles/lender"), renter).associateBy { it.uid } + ) + givenConversation(messages = arrayOf(hello)) + + val state = loadedViewModel().uiState.value + + assertNotNull(state.otherUserPhoto) + assertEquals(mapOf("profiles/lender" to 1), profiles.photoLoads) + } + + @Test + fun otherUserPhoto_failedDownload_isMissingWithoutError() { + profiles = + FakeProfileRepository( + listOf(lender.copy(photoPath = "profiles/lender"), renter).associateBy { it.uid } + ) + profiles.failingPhotoPaths += "profiles/lender" + + val state = loadedViewModel().uiState.value + + assertEquals(lender.copy(photoPath = "profiles/lender"), state.otherUser) + assertNull(state.otherUserPhoto) + assertNull(state.loadError) + } + + @Test + fun otherUserWithoutAPhoto_downloadsNothing() { + val state = loadedViewModel().uiState.value + + assertEquals(lender, state.otherUser) + assertNull(state.otherUserPhoto) + assertTrue(profiles.photoLoads.isEmpty()) + } + + @Test + fun otherUserPhoto_isNotDownloadedAgainWhenTheProfileChangesWithTheSamePath() { + val withPhoto = lender.copy(photoPath = "profiles/lender") + profiles = FakeProfileRepository(listOf(withPhoto, renter).associateBy { it.uid }) + val viewModel = loadedViewModel() + val photo = viewModel.uiState.value.otherUserPhoto + + profiles.users = listOf(withPhoto.copy(bio = "Tools for rent"), renter).associateBy { it.uid } + advance() + + assertEquals("Tools for rent", viewModel.uiState.value.otherUser?.bio) + assertSame(photo, viewModel.uiState.value.otherUserPhoto) + assertEquals(mapOf("profiles/lender" to 1), profiles.photoLoads) + } + + @Test + fun otherUserPhoto_isReplacedWhenThePathChanges_andClearedWhenThePhotoIsRemoved() { + val withPhoto = lender.copy(photoPath = "profiles/lender") + profiles = FakeProfileRepository(listOf(withPhoto, renter).associateBy { it.uid }) + val viewModel = loadedViewModel() + val old = viewModel.uiState.value.otherUserPhoto + assertNotNull(old) + + profiles.users = + listOf(withPhoto.copy(photoPath = "profiles/lender-2"), renter).associateBy { it.uid } + advance() + val new = viewModel.uiState.value.otherUserPhoto + assertNotNull(new) + assertNotSame(old, new) + assertEquals(mapOf("profiles/lender" to 1, "profiles/lender-2" to 1), profiles.photoLoads) + + profiles.users = listOf(lender, renter).associateBy { it.uid } + advance() + assertNull(viewModel.uiState.value.otherUserPhoto) + } } diff --git a/app/src/test/java/com/android/polybazaar/profile/model/FakeProfileRepository.kt b/app/src/test/java/com/android/polybazaar/profile/model/FakeProfileRepository.kt index 28783d15..5a210e79 100644 --- a/app/src/test/java/com/android/polybazaar/profile/model/FakeProfileRepository.kt +++ b/app/src/test/java/com/android/polybazaar/profile/model/FakeProfileRepository.kt @@ -6,20 +6,33 @@ import com.android.polybazaar.auth.model.User import java.net.UnknownHostException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map /** * A [ProfileRepository] for tests. * * [observeProfile] emits the user with that uid from [users], or null when there is none, like the - * real repository for a missing profile. For a uid in [failingUids] it fails with [failure] - * instead, a network error unless the test sets another. [lookups] counts how many times each uid's - * profile was collected. Set [gate] to keep every lookup waiting until the test completes it, to - * look at one in progress. [loadProfilePhoto] returns an empty photo, counted per path in - * [photoLoads]. It waits for [photoGate] when set, and fails with [failure] for a path in - * [failingPhotoPaths]. The other calls do nothing. + * real repository for a missing profile, and emits again whenever a test sets [users], like a new + * snapshot. For a uid in [failingUids] it fails with [failure] instead, a network error unless the + * test sets another. [lookups] counts how many times each uid's profile was collected. Set [gate] + * to keep every lookup waiting until the test completes it, to look at one in progress. + * [loadProfilePhoto] returns an empty photo, counted per path in [photoLoads]. It waits for + * [photoGate] when set, and fails with [failure] for a path in [failingPhotoPaths]. The other calls + * do nothing. */ -class FakeProfileRepository(private val users: Map = emptyMap()) : ProfileRepository { +class FakeProfileRepository(users: Map = emptyMap()) : ProfileRepository { + // A flow, so that observeProfile sees every change a test makes. + private val usersFlow = MutableStateFlow(users) + + var users: Map + get() = usersFlow.value + set(value) { + usersFlow.value = value + } + val failingUids = mutableSetOf() var gate: CompletableDeferred? = null val failingPhotoPaths = mutableSetOf() @@ -41,7 +54,7 @@ class FakeProfileRepository(private val users: Map = emptyMap()) : lookupCounts[uid] = (lookupCounts[uid] ?: 0) + 1 gate?.await() if (uid in failingUids) throw failure - emit(users[uid]) + emitAll(usersFlow.map { it[uid] }) } override suspend fun uploadProfilePhoto(uid: String, photoUri: Uri) = "" From 5e0228e12592878f570f523cacbd6207d57abfc2 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Tue, 17 Nov 2026 21:06:27 +0100 Subject: [PATCH 5/5] feat(chat): match the conversation screen to its Figma --- .../polybazaar/chat/ui/ConversationDays.kt | 70 ++++ .../polybazaar/chat/ui/ConversationScreen.kt | 359 ++++++++++++++++-- app/src/main/res/drawable/ic_archive.xml | 15 + app/src/main/res/drawable/ic_pause_circle.xml | 15 + app/src/main/res/drawable/ic_wifi_off.xml | 15 + app/src/main/res/values/strings.xml | 14 +- .../chat/ui/ConversationDaysTest.kt | 102 +++++ .../chat/ui/ConversationScreenTest.kt | 204 +++++++++- 8 files changed, 751 insertions(+), 43 deletions(-) create mode 100644 app/src/main/java/com/android/polybazaar/chat/ui/ConversationDays.kt create mode 100644 app/src/main/res/drawable/ic_archive.xml create mode 100644 app/src/main/res/drawable/ic_pause_circle.xml create mode 100644 app/src/main/res/drawable/ic_wifi_off.xml create mode 100644 app/src/test/java/com/android/polybazaar/chat/ui/ConversationDaysTest.kt diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationDays.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationDays.kt new file mode 100644 index 00000000..496f2462 --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationDays.kt @@ -0,0 +1,70 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.chat.ui + +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.res.stringResource +import com.android.polybazaar.R +import com.android.polybazaar.chat.model.ChatMessage +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter + +/** One row of the message list: a message, or the day the messages under it were sent on. */ +internal sealed interface ConversationItem { + data class DayDivider(val date: LocalDate) : ConversationItem + + data class Message(val message: ChatMessage) : ConversationItem +} + +/** + * [messages], oldest first, with a [ConversationItem.DayDivider] before the first message of each + * day in [zone]. The days only move forward: a message dated before the day above it, such as a + * pending one stamped by a device clock that is behind, stays under that day, so no day is listed + * twice. + */ +internal fun conversationItems(messages: List, zone: ZoneId): List { + val items = mutableListOf() + var day: LocalDate? = null + for (message in messages) { + val date = message.sentAt.atZone(zone).toLocalDate() + if (day == null || date.isAfter(day)) { + items += ConversationItem.DayDivider(date) + day = date + } + items += ConversationItem.Message(message) + } + return items +} + +/** How a day divider names its day. */ +internal sealed interface ConversationDay { + /** Today, or later when the device clock is behind the sender's. */ + data object Today : ConversationDay + + data object Yesterday : ConversationDay + + /** An earlier day, with its year when it is not this year. */ + data class Date(val date: LocalDate, val withYear: Boolean) : ConversationDay +} + +/** How the divider of [date] names it, seen on [today]. */ +internal fun conversationDay(date: LocalDate, today: LocalDate): ConversationDay = + when { + !date.isBefore(today) -> ConversationDay.Today + date == today.minusDays(1) -> ConversationDay.Yesterday + else -> ConversationDay.Date(date, withYear = date.year != today.year) + } + +/** "Today", "Yesterday", "4 May" or "4 May 2025", in the app's locale. */ +@Composable +internal fun ConversationDay.label(): String = + when (this) { + ConversationDay.Today -> stringResource(R.string.conversation_day_today) + ConversationDay.Yesterday -> stringResource(R.string.conversation_day_yesterday) + is ConversationDay.Date -> { + // From the configuration, so the date follows a change of locale. + val locale = LocalConfiguration.current.locales[0] + date.format(DateTimeFormatter.ofPattern(if (withYear) "d MMM yyyy" else "d MMM", locale)) + } + } diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt index 1bbdd0e2..a21ca903 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt @@ -1,6 +1,8 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.ui +import androidx.annotation.DrawableRes +import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement @@ -20,6 +22,7 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions @@ -32,9 +35,15 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.painter.BitmapPainter +import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource @@ -42,6 +51,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.TextStyle @@ -66,7 +76,13 @@ import com.android.polybazaar.chat.viewmodel.ConversationUiState import com.android.polybazaar.chat.viewmodel.ConversationViewModel import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message +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.ServiceListing +import com.android.polybazaar.listing.model.formatChf import java.time.Instant +import java.time.LocalDate import java.time.ZoneId import java.time.ZoneOffset import java.time.format.DateTimeFormatter @@ -77,6 +93,12 @@ object ConversationScreenTags { const val BACK_BUTTON = "conversation_back_button" const val LISTING_TITLE = "conversation_listing_title" const val OTHER_USERNAME = "conversation_other_username" + const val OTHER_AVATAR = "conversation_other_avatar" + const val LISTING_SUMMARY = "conversation_listing_summary" + const val LISTING_STATUS_PILL = "conversation_listing_status_pill" + const val NOTICE_ICON = "conversation_notice_icon" + const val LOAD_ERROR_ICON = "conversation_load_error_icon" + const val EMPTY_TAGLINE = "conversation_empty_tagline" const val PAUSED_NOTICE = "conversation_paused_notice" const val DELETED_NOTICE = "conversation_deleted_notice" const val LOADING_INDICATOR = "conversation_loading_indicator" @@ -94,6 +116,9 @@ object ConversationScreenTags { /** Tag of the bubble of the other participant's message with [id]. */ fun theirMessage(id: String) = "conversation_their_message_$id" + + /** Tag of the divider above the messages sent on [date]. */ + fun dayDivider(date: LocalDate) = "conversation_day_divider_$date" } /** What the screen shows between the header and the composer, decided by [conversationBody]. */ @@ -165,7 +190,8 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { * @param onRetry called when the user taps Retry after a load failed. * @param onDismissSendError called before [onDraftChange] when the user edits the draft while a * send error shows. - * @param zone time zone of the message times. + * @param zone time zone of the message times and days. + * @param now the current time, which the day dividers count "Today" and "Yesterday" from. */ @Composable fun ConversationContent( @@ -176,6 +202,7 @@ fun ConversationContent( onRetry: () -> Unit = {}, onDismissSendError: () -> Unit = {}, zone: ZoneId = ZoneId.systemDefault(), + now: Instant = Instant.now(), ) { val body = conversationBody(uiState) val deleted = uiState.listingStatus == ConversationListingStatus.DELETED @@ -191,7 +218,18 @@ fun ConversationContent( .safeDrawingPadding() .testTag(ConversationScreenTags.SCREEN) ) { - Header(listingTitle = uiState.listingTitle, otherUser = uiState.otherUser, onBack = onBack) + Header( + listingTitle = uiState.listingTitle, + otherUser = uiState.otherUser, + otherUserPhoto = rememberPhoto(uiState.otherUserPhoto), + isRenter = uiState.isRenter, + onBack = onBack, + ) + val listingPhoto = rememberPhoto(uiState.listingPhoto) + uiState.listingStatus?.let { + ListingSummary(uiState = uiState, status = it, photo = listingPhoto) + } + HorizontalDivider(color = AuthColors.Outline) uiState.listingStatus?.let { ListingNotice(it, uiState.firstMessageBlockedByPause) } Box(modifier = Modifier.weight(1f).fillMaxWidth()) { when (body) { @@ -204,7 +242,13 @@ fun ConversationContent( listingTitle = uiState.listingTitle, listingStatus = uiState.listingStatus, ) - ConversationBody.MESSAGES -> MessageList(uiState = uiState, zone = zone, onRetry = onRetry) + ConversationBody.MESSAGES -> + MessageList( + uiState = uiState, + zone = zone, + today = now.atZone(zone).toLocalDate(), + onRetry = onRetry, + ) } } Composer( @@ -222,9 +266,18 @@ fun ConversationContent( } } -/** Back, then the listing's title with the other participant's username under it. */ +/** + * Back, the listing's title with the other participant's username and role under it, then their + * photo. + */ @Composable -private fun Header(listingTitle: String?, otherUser: User?, onBack: () -> Unit) { +private fun Header( + listingTitle: String?, + otherUser: User?, + otherUserPhoto: ImageBitmap?, + isRenter: Boolean, + onBack: () -> Unit, +) { Row( modifier = Modifier.fillMaxWidth().padding(horizontal = PageMargin, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), @@ -245,8 +298,15 @@ private fun Header(listingTitle: String?, otherUser: User?, onBack: () -> Unit) modifier = Modifier.testTag(ConversationScreenTags.LISTING_TITLE), ) otherUser?.let { + val role = + if (isRenter) R.string.conversation_role_lender else R.string.conversation_role_renter Text( - text = stringResource(R.string.conversation_other_username, it.username), + text = + stringResource( + R.string.conversation_other_username, + it.username, + stringResource(role), + ), color = AuthColors.TextSecondary, fontSize = 12.sp, maxLines = 1, @@ -255,10 +315,134 @@ private fun Header(listingTitle: String?, otherUser: User?, onBack: () -> Unit) ) } } + // Decorative: the username next to it says who it is. + Image( + painter = + otherUserPhoto?.let { BitmapPainter(it) } + ?: painterResource(R.drawable.default_profile_photo), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = + Modifier.size(38.dp).clip(CircleShape).testTag(ConversationScreenTags.OTHER_AVATAR), + ) } - HorizontalDivider(color = AuthColors.Outline) } +/** + * The listing the conversation is about: its photo, its lender, its price and place, and whether it + * is a rental or a service, paused or deleted. Without the listing, as when it was deleted before + * the screen opened, only the lender and the status show. + */ +@Composable +private fun ListingSummary( + uiState: ConversationUiState, + status: ConversationListingStatus, + photo: ImageBitmap?, +) { + val listing = uiState.listing + // The other participant is the lender when the signed-in user is the renter. + val lender = + if (uiState.isRenter) uiState.otherUser?.username + else stringResource(R.string.conversation_summary_you) + // Replaces the lender's name in the card's merged semantics, so TalkBack says whose listing it + // is, + // then its details, without also saying the bare name. + val spokenLender = + if (uiState.isRenter) + uiState.otherUser?.let { + stringResource(R.string.conversation_summary_spoken_lender, it.username) + } + else stringResource(R.string.conversation_summary_spoken_mine) + val perDay = stringResource(R.string.browse_price_per_day) + // Only items are rented by the day; a service has a price alone. + val details = listing?.let { + val price = if (it is ItemListing) "${formatChf(it.price)} $perDay" else formatChf(it.price) + listOfNotNull(price, it.location?.name).joinToString(" · ") + } + val shape = RoundedCornerShape(14.dp) + Row( + modifier = + Modifier.fillMaxWidth() + .padding(start = PageMargin, end = PageMargin, top = 4.dp, bottom = 12.dp) + .background(AuthColors.CardBackground, shape) + .border(1.dp, AuthColors.Outline, shape) + .padding(10.dp) + // One TalkBack item for the whole card. + .semantics(mergeDescendants = true) {} + .testTag(ConversationScreenTags.LISTING_SUMMARY), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + ListingPhoto(photo = photo, size = 46.dp) + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + lender?.let { + Text( + text = it, + color = AuthColors.TextPrimary, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = + Modifier.clearAndSetSemantics { spokenLender?.let { contentDescription = it } }, + ) + } + details?.let { + Text( + text = it, + color = AuthColors.TextSecondary, + fontSize = 12.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + StatusPill(status = status, isService = listing is ServiceListing) + } +} + +/** Rental or Service while the listing is active, else Paused or Deleted. */ +@Composable +private fun StatusPill(status: ConversationListingStatus, isService: Boolean) { + val (text, background, color) = + when (status) { + ConversationListingStatus.ACTIVE -> + PillStyle( + stringResource( + if (isService) R.string.conversation_status_service + else R.string.conversation_status_rental + ), + AuthColors.AccentContainer, + AuthColors.Accent, + ) + ConversationListingStatus.PAUSED -> + PillStyle( + stringResource(R.string.conversation_status_paused), + AuthColors.AccentContainer, + PausedBadgeText, + ) + ConversationListingStatus.DELETED -> + PillStyle( + stringResource(R.string.conversation_status_deleted), + DeletedBadgeBackground, + DeletedBadgeText, + ) + } + Text( + text = text, + color = color, + fontSize = 11.sp, + fontWeight = FontWeight.SemiBold, + modifier = + Modifier.background(background, RoundedCornerShape(12.dp)) + .padding(horizontal = 9.dp, vertical = 5.dp) + .testTag(ConversationScreenTags.LISTING_STATUS_PILL), + ) +} + +/** The text and colors of the listing's status pill. */ +private data class PillStyle(val text: String, val background: Color, val color: Color) + /** * What happened to the listing, while it is paused or deleted. [firstMessageBlockedByPause] adds * why Send stays off on a paused listing without a conversation. @@ -277,43 +461,80 @@ private fun ListingNotice(status: ConversationListingStatus, firstMessageBlocked stringResource(R.string.conversation_paused_first_message_body) } else null, tag = ConversationScreenTags.PAUSED_NOTICE, + icon = R.drawable.ic_pause_circle, + iconTint = AuthColors.Accent, + background = AuthColors.AccentContainer, ) ConversationListingStatus.DELETED -> Notice( title = stringResource(R.string.conversation_deleted_title), body = stringResource(R.string.conversation_deleted_body), tag = ConversationScreenTags.DELETED_NOTICE, + icon = R.drawable.ic_archive, + iconTint = DeletedBadgeText, + background = DeletedBadgeBackground, ) } } @Composable -private fun Notice(title: String, body: String?, tag: String) { +private fun Notice( + title: String, + body: String?, + tag: String, + @DrawableRes icon: Int, + iconTint: Color, + background: Color, +) { val shape = RoundedCornerShape(14.dp) - Column( + Row( modifier = Modifier.fillMaxWidth() .padding(start = PageMargin, end = PageMargin, top = 10.dp) - .background(AuthColors.CardBackground, shape) - .border(1.dp, AuthColors.Outline, shape) - .padding(horizontal = 14.dp, vertical = 10.dp) + .background(background, shape) + .padding(12.dp) // One TalkBack announcement for the title and its explanation. .semantics(mergeDescendants = true) {} .testTag(tag), - verticalArrangement = Arrangement.spacedBy(2.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), ) { - Text( - text = title, - color = AuthColors.TextPrimary, - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, + // Decorative: the title says what happened to the listing. + Icon( + painter = painterResource(icon), + contentDescription = null, + tint = iconTint, + modifier = Modifier.size(18.dp).testTag(ConversationScreenTags.NOTICE_ICON), ) - body?.let { - Text(text = it, color = AuthColors.TextSecondary, fontSize = 12.sp, lineHeight = 17.sp) + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + text = title, + color = AuthColors.TextPrimary, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + ) + body?.let { + Text(text = it, color = AuthColors.TextSecondary, fontSize = 12.sp, lineHeight = 17.sp) + } } } } +/** A decorative [icon] in a tinted circle, above the text of an empty or failed conversation. */ +@Composable +private fun CircledIcon(@DrawableRes icon: Int, modifier: Modifier = Modifier) { + Box( + modifier = modifier.size(64.dp).background(AuthColors.AccentContainer, CircleShape), + contentAlignment = Alignment.Center, + ) { + Icon( + painter = painterResource(icon), + contentDescription = null, + tint = AuthColors.Accent, + modifier = Modifier.size(28.dp), + ) + } +} + @Composable private fun LoadingIndicator() { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { @@ -332,6 +553,11 @@ private fun LoadError(text: String, onRetry: () -> Unit) { horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically), ) { + // Decorative: the title under it says what failed. + CircledIcon( + icon = R.drawable.ic_wifi_off, + modifier = Modifier.testTag(ConversationScreenTags.LOAD_ERROR_ICON), + ) Text( text = stringResource(R.string.conversation_load_error_title), color = AuthColors.TextPrimary, @@ -376,12 +602,7 @@ private fun EmptyState( verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically), ) { // Decorative: the text under it says what the empty conversation is for. - Icon( - painter = painterResource(R.drawable.ic_message_circle), - contentDescription = null, - tint = AuthColors.Accent, - modifier = Modifier.size(32.dp), - ) + CircledIcon(icon = R.drawable.ic_message_circle) if (invites) { Text( text = @@ -404,15 +625,31 @@ private fun EmptyState( lineHeight = 18.sp, textAlign = TextAlign.Center, ) + if (invites) { + Text( + text = stringResource(R.string.conversation_empty_tagline), + color = AuthColors.Accent, + fontSize = 12.sp, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 8.dp).testTag(ConversationScreenTags.EMPTY_TAGLINE), + ) + } } } /** - * The messages, oldest at the top, with the load error and Retry above them when a reload failed. + * The messages, oldest at the top, under the day they were sent on, with the load error and Retry + * above them when a reload failed. */ @Composable -private fun MessageList(uiState: ConversationUiState, zone: ZoneId, onRetry: () -> Unit) { +private fun MessageList( + uiState: ConversationUiState, + zone: ZoneId, + today: LocalDate, + onRetry: () -> Unit, +) { val messages = uiState.messages + val items = remember(messages, zone) { conversationItems(messages, zone).asReversed() } val listState = rememberLazyListState() // The list keeps its place by key, so a new message would arrive below the view without this. LaunchedEffect(messages.lastOrNull()?.id) { listState.scrollToItem(0) } @@ -427,18 +664,47 @@ private fun MessageList(uiState: ConversationUiState, zone: ZoneId, onRetry: () reverseLayout = true, verticalArrangement = Arrangement.spacedBy(8.dp), ) { - items(messages.asReversed(), key = { it.id }) { message -> - MessageBubble( - message = message, - isMine = message.senderUid == uiState.myUid, - otherUsername = uiState.otherUser?.username, - zone = zone, - ) + items( + items, + key = { item -> + when (item) { + is ConversationItem.Message -> item.message.id + // Firestore document ids cannot contain "/", so a day never shares a message's key. + is ConversationItem.DayDivider -> "day/${item.date}" + } + }, + ) { item -> + when (item) { + is ConversationItem.Message -> + MessageBubble( + message = item.message, + isMine = item.message.senderUid == uiState.myUid, + otherUsername = uiState.otherUser?.username, + zone = zone, + ) + is ConversationItem.DayDivider -> DayDivider(date = item.date, today = today) + } } } } } +/** The day the messages under it were sent on: "Today", "Yesterday" or the date. */ +@Composable +private fun DayDivider(date: LocalDate, today: LocalDate) { + Text( + text = conversationDay(date, today).label(), + color = AuthColors.TextSecondary, + fontSize = 12.sp, + textAlign = TextAlign.Center, + modifier = + Modifier.fillMaxWidth() + .padding(vertical = 4.dp) + .semantics { heading() } + .testTag(ConversationScreenTags.dayDivider(date)), + ) +} + /** A reload error above messages that stay shown, with Retry as a text button. */ @Composable private fun LoadErrorRow(text: String, onRetry: () -> Unit) { @@ -666,11 +932,15 @@ private fun MessageField( ) } -/** A paused listing with a few messages, for the IDE preview. Internal so a test can render it. */ +/** + * A paused listing with messages over two days, for the IDE preview. Internal so a test can render + * it. + */ @Preview(showBackground = true, widthDp = 412, heightDp = 917) @Composable internal fun ConversationContentPreview() { val start = Instant.parse("2026-05-04T09:12:00Z") + val nextDay = start.plusSeconds(24 * 60 * 60) ConversationContent( uiState = ConversationUiState( @@ -684,7 +954,7 @@ internal fun ConversationContentPreview() { "Yes, from 10:00. I can add a second battery if you need one.", start.plusSeconds(120), ), - ChatMessage("3", "renter", "Perfect, see you then.", start.plusSeconds(300)), + ChatMessage("3", "renter", "Perfect, see you then.", nextDay), ), conversation = Conversation( @@ -692,13 +962,26 @@ internal fun ConversationContentPreview() { listingTitle = "Bosch drill set", renterUid = "renter", lenderUid = "lender", - lastMessageAt = start.plusSeconds(300), + lastMessageAt = nextDay, ), listingTitle = "Bosch drill set", listingStatus = ConversationListingStatus.PAUSED, + listing = + ItemListing( + ListingCategory.ITEM_TOOLS, + 8.0, + "Bosch drill set", + "Cordless drill with bits.", + listingId = "drill", + ownerUid = "lender", + isPaused = true, + location = ListingLocation(46.5376, 6.5804, "Renens VD"), + ), + isRenter = true, otherUser = User(uid = "lender", email = "", username = "james"), isLoading = false, ), zone = ZoneOffset.UTC, + now = nextDay, ) } diff --git a/app/src/main/res/drawable/ic_archive.xml b/app/src/main/res/drawable/ic_archive.xml new file mode 100644 index 00000000..492372bf --- /dev/null +++ b/app/src/main/res/drawable/ic_archive.xml @@ -0,0 +1,15 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_pause_circle.xml b/app/src/main/res/drawable/ic_pause_circle.xml new file mode 100644 index 00000000..13955099 --- /dev/null +++ b/app/src/main/res/drawable/ic_pause_circle.xml @@ -0,0 +1,15 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_wifi_off.xml b/app/src/main/res/drawable/ic_wifi_off.xml new file mode 100644 index 00000000..66e96cb1 --- /dev/null +++ b/app/src/main/res/drawable/ic_wifi_off.xml @@ -0,0 +1,15 @@ + + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ac2de988..967ccc9f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -76,7 +76,18 @@ The lender isn\'t taking bookings right now. - @%1$s + @%1$s · %2$s + Lender + Renter + You + Listing by %1$s + Your listing + Rental + Service + Paused + Deleted + Today + Yesterday This listing is paused You can send a message once it’s active again. This listing has been deleted @@ -87,6 +98,7 @@ Say hello No messages yet. Ask about “%1$s”, its availability or a good time to meet. No messages yet. + Good tools. Great neighbours. You · %1$s %1$s · %2$s Write a message… diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationDaysTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationDaysTest.kt new file mode 100644 index 00000000..8b0d0e87 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationDaysTest.kt @@ -0,0 +1,102 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.chat.ui + +import com.android.polybazaar.chat.model.ChatMessage +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.ZoneOffset +import org.junit.Assert.assertEquals +import org.junit.Test + +class ConversationDaysTest { + + private fun message(id: String, at: String) = ChatMessage(id, "renter", id, Instant.parse(at)) + + @Test + fun conversationItems_putsADividerBeforeTheFirstMessageOfEachDay() { + val a = message("a", "2026-11-10T08:00:00Z") + val b = message("b", "2026-11-10T20:00:00Z") + val c = message("c", "2026-11-11T09:00:00Z") + + assertEquals( + listOf( + ConversationItem.DayDivider(LocalDate.parse("2026-11-10")), + ConversationItem.Message(a), + ConversationItem.Message(b), + ConversationItem.DayDivider(LocalDate.parse("2026-11-11")), + ConversationItem.Message(c), + ), + conversationItems(listOf(a, b, c), ZoneOffset.UTC), + ) + } + + @Test + fun conversationItems_splitsTheDaysAtMidnightInTheGivenZone() { + // 22:30 and 23:30 UTC on the 10th are 23:30 on the 10th and 00:30 on the 11th in Zurich. + val beforeMidnight = message("a", "2026-11-10T22:30:00Z") + val afterMidnight = message("b", "2026-11-10T23:30:00Z") + val zurich = ZoneId.of("Europe/Zurich") + + assertEquals( + listOf( + ConversationItem.DayDivider(LocalDate.parse("2026-11-10")), + ConversationItem.Message(beforeMidnight), + ConversationItem.DayDivider(LocalDate.parse("2026-11-11")), + ConversationItem.Message(afterMidnight), + ), + conversationItems(listOf(beforeMidnight, afterMidnight), zurich), + ) + assertEquals( + listOf( + ConversationItem.DayDivider(LocalDate.parse("2026-11-10")), + ConversationItem.Message(beforeMidnight), + ConversationItem.Message(afterMidnight), + ), + conversationItems(listOf(beforeMidnight, afterMidnight), ZoneOffset.UTC), + ) + } + + @Test + fun conversationItems_neverGoesBackADay() { + // The pending last message was stamped by a device clock a day behind. + val older = message("a", "2026-11-16T09:00:00Z") + val theirs = message("b", "2026-11-17T09:00:00Z") + val pending = message("c", "2026-11-16T22:00:00Z") + + assertEquals( + listOf( + ConversationItem.DayDivider(LocalDate.parse("2026-11-16")), + ConversationItem.Message(older), + ConversationItem.DayDivider(LocalDate.parse("2026-11-17")), + ConversationItem.Message(theirs), + ConversationItem.Message(pending), + ), + conversationItems(listOf(older, theirs, pending), ZoneOffset.UTC), + ) + } + + @Test + fun conversationItems_withoutMessages_isEmpty() { + assertEquals(emptyList(), conversationItems(emptyList(), ZoneOffset.UTC)) + } + + @Test + fun conversationDay_namesTodayYesterdayAndEarlierDays() { + val today = LocalDate.parse("2026-01-02") + + assertEquals(ConversationDay.Today, conversationDay(today, today)) + // A message from tomorrow, when the device clock is behind the sender's. + assertEquals(ConversationDay.Today, conversationDay(today.plusDays(1), today)) + assertEquals(ConversationDay.Yesterday, conversationDay(LocalDate.parse("2026-01-01"), today)) + assertEquals( + ConversationDay.Date(LocalDate.parse("2025-12-31"), withYear = true), + conversationDay(LocalDate.parse("2025-12-31"), today), + ) + val later = LocalDate.parse("2026-03-10") + assertEquals( + ConversationDay.Date(LocalDate.parse("2026-03-01"), withYear = false), + conversationDay(LocalDate.parse("2026-03-01"), later), + ) + } +} diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt index e2a27c36..e4d360fa 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt @@ -26,7 +26,7 @@ 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.performScrollToIndex +import androidx.compose.ui.test.performScrollToNode import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performTextReplacement import androidx.compose.ui.text.AnnotatedString @@ -50,9 +50,12 @@ 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.ServiceListing import com.android.polybazaar.profile.model.FakeProfileRepository import java.net.UnknownHostException import java.time.Instant +import java.time.LocalDate import java.time.ZoneOffset import kotlinx.coroutines.CompletableDeferred import org.junit.Assert.assertEquals @@ -95,10 +98,14 @@ class ConversationScreenTest { conversation = conversation, listingTitle = "Bosch drill set", listingStatus = ConversationListingStatus.ACTIVE, + isRenter = true, otherUser = james, isLoading = false, ) + /** The time the tests look at the screen: the day of [question] and [answer]. */ + private val now = Instant.parse("2026-11-11T12:00:00Z") + private fun setContent( uiState: ConversationUiState, onBack: () -> Unit = {}, @@ -116,6 +123,7 @@ class ConversationScreenTest { onRetry = onRetry, onDismissSendError = onDismissSendError, zone = ZoneOffset.UTC, + now = now, ) } } @@ -169,6 +177,20 @@ class ConversationScreenTest { useUnmergedTree = true, ) + /** Every text of the listing summary. */ + private fun summaryTexts() = + composeTestRule.onAllNodes( + hasAnyAncestor(hasTestTag(ConversationScreenTags.LISTING_SUMMARY)) and + SemanticsMatcher.keyIsDefined(SemanticsProperties.Text), + useUnmergedTree = true, + ) + + private fun pill() = + composeTestRule.onNodeWithTag( + ConversationScreenTags.LISTING_STATUS_PILL, + useUnmergedTree = true, + ) + private val drill = ItemListing( ListingCategory.ITEM_TOOLS, @@ -286,6 +308,9 @@ class ConversationScreenTest { text(string(R.string.conversation_empty_title, "james")).assertIsDisplayed() text("No messages yet. Ask about “Bosch drill set”, its availability or a good time to meet.") .assertIsDisplayed() + composeTestRule + .onNodeWithTag(ConversationScreenTags.EMPTY_TAGLINE, useUnmergedTree = true) + .assertTextEquals("Good tools. Great neighbours.") node(ConversationScreenTags.MESSAGE_FIELD).assertIsEnabled() } @@ -413,8 +438,9 @@ class ConversationScreenTest { uiState = uiState.copy(messages = many + ChatMessage("m50", "renter", "On my way", start)) assertFullyInTheList(node(ConversationScreenTags.myMessage("m50"))) - // The oldest message was only out of view: the list holds it last, newest first. - node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(50) + // The oldest message was only out of view, at the top of the list. + node(ConversationScreenTags.MESSAGE_LIST) + .performScrollToNode(hasTestTag(ConversationScreenTags.myMessage("m0"))) node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() } @@ -434,7 +460,8 @@ class ConversationScreenTest { setContent(loaded, onBack = { backs++ }) node(ConversationScreenTags.LISTING_TITLE).assertTextEquals("Bosch drill set") - node(ConversationScreenTags.OTHER_USERNAME).assertTextEquals("@james") + node(ConversationScreenTags.OTHER_USERNAME).assertTextEquals("@james · Lender") + node(ConversationScreenTags.OTHER_AVATAR).assertIsDisplayed() node(ConversationScreenTags.PAUSED_NOTICE).assertDoesNotExist() node(ConversationScreenTags.DELETED_NOTICE).assertDoesNotExist() node(ConversationScreenTags.BACK_BUTTON).performClick() @@ -830,4 +857,173 @@ class ConversationScreenTest { node(ConversationScreenTags.SEND_ERROR).assertDoesNotExist() node(ConversationScreenTags.MESSAGE_FIELD).assert(hasDraft("Is it free on Saturday?!")) } + + @Test + fun summary_forAnItem_showsTheLenderThePricePerDayAndThePlace_asARental() { + setContent( + loaded.copy(listing = drill.copy(location = ListingLocation(46.54, 6.58, "Renens VD"))) + ) + + node(ConversationScreenTags.LISTING_SUMMARY) + .assertIsDisplayed() + .assertContentDescriptionEquals( + string(R.string.conversation_summary_spoken_lender, "james") + ) + text("CHF 8 / day · Renens VD").assertIsDisplayed() + pill().assertTextEquals("Rental") + } + + @Test + fun summary_forAService_showsThePriceAlone_asAService() { + val tutoring = + ServiceListing( + ListingCategory.SERVICE_TUTORING, + 25.0, + "Calculus tutoring", + "Analysis I and II.", + listingId = "tutoring", + ownerUid = james.uid, + ) + + setContent(loaded.copy(listingTitle = "Calculus tutoring", listing = tutoring)) + + text("CHF 25").assertIsDisplayed() + pill().assertTextEquals("Service") + } + + @Test + fun summary_followsTheListingStatus() { + var uiState by mutableStateOf(loaded.copy(listing = drill)) + composeTestRule.setContent { + ConversationContent(uiState = uiState, zone = ZoneOffset.UTC, now = now) + } + pill().assertTextEquals("Rental") + + uiState = + uiState.copy( + listing = drill.copy(isPaused = true), + listingStatus = ConversationListingStatus.PAUSED, + ) + pill().assertTextEquals("Paused") + + uiState = uiState.copy(listingStatus = ConversationListingStatus.DELETED) + pill().assertTextEquals("Deleted") + } + + @Test + fun summary_ofAListingDeletedBeforeTheScreenOpened_showsOnlyTheLenderAndTheStatus() { + setContent(loaded.copy(listing = null, listingStatus = ConversationListingStatus.DELETED)) + + // The lender is spoken through its content description, so the status is the only text. + summaryTexts().assertCountEquals(1) + node(ConversationScreenTags.LISTING_SUMMARY) + .assertContentDescriptionEquals( + string(R.string.conversation_summary_spoken_lender, "james") + ) + pill().assertTextEquals("Deleted") + } + + @Test + fun lender_seesThemselvesAsTheLender_andTheOtherPersonAsTheRenter() { + val remi = User(uid = "renter", email = "remi@epfl.ch", username = "remi") + + setContent(loaded.copy(myUid = james.uid, isRenter = false, otherUser = remi, listing = drill)) + + node(ConversationScreenTags.LISTING_SUMMARY) + .assertContentDescriptionEquals(string(R.string.conversation_summary_spoken_mine)) + node(ConversationScreenTags.OTHER_USERNAME).assertTextEquals("@remi · Renter") + } + + @Test + fun summary_isHiddenWhileTheListingIsUnknown() { + setContent(ConversationUiState(myUid = "renter")) + + node(ConversationScreenTags.LISTING_SUMMARY).assertDoesNotExist() + node(ConversationScreenTags.OTHER_AVATAR).assertIsDisplayed() + } + + @Test + fun notices_showTheirIcons() { + var uiState by mutableStateOf(loaded.copy(listingStatus = ConversationListingStatus.PAUSED)) + composeTestRule.setContent { + ConversationContent(uiState = uiState, zone = ZoneOffset.UTC, now = now) + } + composeTestRule + .onNodeWithTag(ConversationScreenTags.NOTICE_ICON, useUnmergedTree = true) + .assertIsDisplayed() + + uiState = uiState.copy(listingStatus = ConversationListingStatus.DELETED) + composeTestRule + .onNodeWithTag(ConversationScreenTags.NOTICE_ICON, useUnmergedTree = true) + .assertIsDisplayed() + } + + @Test + fun loadError_showsItsIcon() { + setContent(ConversationUiState(myUid = "renter", loadError = AppError.NETWORK)) + + node(ConversationScreenTags.LOAD_ERROR_ICON).assertIsDisplayed() + } + + @Test + // Tall enough for every message and divider to be laid out. + @Config(qualifiers = "w412dp-h1400dp") + fun dayDividers_nameEachDay_aboveItsFirstMessage() { + fun message(id: String, at: String) = + ChatMessage(id, "renter", "Message $id", Instant.parse(at)) + val lastYear = message("m1", "2025-12-31T18:00:00Z") + val earlier = message("m2", "2026-11-09T10:00:00Z") + val yesterdayFirst = message("m3", "2026-11-10T08:00:00Z") + val yesterdayLast = message("m4", "2026-11-10T20:00:00Z") + val today = message("m5", "2026-11-11T09:00:00Z") + + setContent( + loaded.copy(messages = listOf(lastYear, earlier, yesterdayFirst, yesterdayLast, today)) + ) + + fun divider(date: String) = node(ConversationScreenTags.dayDivider(LocalDate.parse(date))) + divider("2025-12-31").assertTextEquals("31 Dec 2025") + divider("2026-11-09").assertTextEquals("9 Nov") + divider("2026-11-10").assertTextEquals("Yesterday") + divider("2026-11-11").assertTextEquals("Today") + val above = node(ConversationScreenTags.myMessage("m2")).getBoundsInRoot() + val yesterday = divider("2026-11-10").getBoundsInRoot() + val first = node(ConversationScreenTags.myMessage("m3")).getBoundsInRoot() + val last = node(ConversationScreenTags.myMessage("m4")).getBoundsInRoot() + assertTrue(above.bottom <= yesterday.top) + assertTrue(yesterday.bottom <= first.top) + assertTrue(first.bottom <= last.top) + } + + @Test + fun messageWithTheIdOfADayKey_showsBesideThatDaysDivider() { + // A message id can look like a day key with another separator; the "/" in the divider's key + // keeps them apart. + val odd = + ChatMessage("day:2026-11-11", "renter", "Odd id", Instant.parse("2026-11-11T10:00:00Z")) + + setContent(loaded.copy(messages = listOf(question, odd))) + + node(ConversationScreenTags.myMessage("day:2026-11-11")).assertIsDisplayed() + node(ConversationScreenTags.dayDivider(LocalDate.parse("2026-11-11"))).assertTextEquals("Today") + } + + @Test + fun listingSummary_tellsTalkBackWhoseListingItIs() { + var uiState by mutableStateOf(loaded.copy(listing = drill)) + composeTestRule.setContent { + ConversationContent(uiState = uiState, zone = ZoneOffset.UTC, now = now) + } + // The merged card: who it belongs to, then the details and the status, without the bare name. + node(ConversationScreenTags.LISTING_SUMMARY) + .assertContentDescriptionEquals( + string(R.string.conversation_summary_spoken_lender, "james") + ) + .assertTextEquals("CHF 8 / day", "Rental") + + uiState = uiState.copy(myUid = james.uid, isRenter = false) + node(ConversationScreenTags.LISTING_SUMMARY) + .assertContentDescriptionEquals(string(R.string.conversation_summary_spoken_mine)) + .assertTextEquals("CHF 8 / day", "Rental") + } }