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 42f4159f..c82e3b87 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 @@ -5,6 +5,7 @@ import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -32,12 +33,14 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -49,7 +52,11 @@ import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha @@ -101,6 +108,7 @@ import java.time.ZoneId import java.time.ZoneOffset import java.time.format.DateTimeFormatter import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch object ConversationScreenTags { const val SCREEN = "conversation_screen" @@ -124,6 +132,7 @@ object ConversationScreenTags { const val CHOOSE_PHOTO = "conversation_choose_photo" const val ATTACHED_PHOTO = "conversation_attached_photo" const val REMOVE_ATTACHED_PHOTO = "conversation_remove_attached_photo" + const val NEW_MESSAGE_HINT = "conversation_new_message_hint" /** Tag of the bubble of the signed-in user's message with [id]. */ fun myMessage(id: String) = "conversation_my_message_$id" @@ -169,6 +178,47 @@ internal fun conversationBody(state: ConversationUiState): ConversationBody = else -> ConversationBody.EMPTY } +/** How the message list answers a change in what it shows, decided by [messageListChange]. */ +internal enum class MessageListChange { + /** Scroll to the bottom: on opening, and for the user's own message or photo. */ + FOLLOW, + /** A message from the other participant came after the newest one. */ + THEIRS_ARRIVED, + /** Nothing arrived, so the list stays where it is. */ + NONE, +} + +/** + * Classifies the change from [previousNewestId] and [previousPendingIds] to the shown [messages], + * oldest first, and the [pendingIds] of the photos being sent. A message arrived only when it comes + * after the previous newest one, which a deletion's new newest does not. A photo's message that was + * pending did not arrive either: it takes the place of its pending bubble. + * + * @param firstLoad true until the list has shown anything. + */ +internal fun messageListChange( + messages: List, + pendingIds: List, + myUid: String, + previousNewestId: String?, + previousPendingIds: List, + firstLoad: Boolean, +): MessageListChange { + if (firstLoad) return MessageListChange.FOLLOW + val sentId = pendingIds.lastOrNull() + if (sentId != null && sentId !in previousPendingIds) return MessageListChange.FOLLOW + val newest = messages.lastOrNull() ?: return MessageListChange.NONE + val arrived = + newest.id != previousNewestId && + (previousNewestId == null || messages.any { it.id == previousNewestId }) && + newest.id !in previousPendingIds + return when { + !arrived -> MessageListChange.NONE + newest.senderUid == myUid -> MessageListChange.FOLLOW + else -> MessageListChange.THEIRS_ARRIVED + } +} + /** Side margin of the page, the same as on the listing detail. */ private val PageMargin = 18.dp @@ -533,9 +583,12 @@ private class PhotoActions( val discard: (messageId: String) -> Unit, ) +/** Key of [pending]'s item, prefixed: once sent, a photo's message arrives with the same ID. */ +private fun pendingPhotoKey(pending: PendingPhoto) = "pending_${pending.messageId}" + /** * The messages, oldest at the top, then the photos being sent, with the load error and Retry above - * them when a reload failed. + * them when a reload failed, and a hint over the bottom while a message has arrived below the view. */ @Composable private fun MessageList( @@ -546,55 +599,140 @@ private fun MessageList( ) { val messages = uiState.shownMessages val pendingPhotos = uiState.pendingPhotos + val newest = messages.lastOrNull() + val pendingIds = pendingPhotos.map { it.messageId } + // Item 0, at the bottom of the reversed list. + val bottomKey = pendingPhotos.lastOrNull()?.let(::pendingPhotoKey) ?: newest?.id val listState = rememberLazyListState() + val scope = rememberCoroutineScope() // Decoded above the list: a bubble that scrolls out of view and back shows its photo at once. val decodedPhotos = rememberDecodedPhotos(uiState.messagePhotos) - // The list keeps its place by key, so a new message or photo would arrive below the view without - // this. - LaunchedEffect(messages.lastOrNull()?.id, pendingPhotos.lastOrNull()?.messageId) { - listState.scrollToItem(0) + // What the list showed at the last change, and whether a message is waiting below the view. + // Saved across recreation, as the list's position is; the ids in an ArrayList, which it can save. + var previousNewestId by rememberSaveable { mutableStateOf(null) } + var previousPendingIds by rememberSaveable { mutableStateOf(ArrayList()) } + var previousBottomKey by rememberSaveable { mutableStateOf(null) } + var newestUnseen by rememberSaveable { mutableStateOf(false) } + // The list keeps its place by key, so an arrival lands below the view unless this follows it. + // One from the other participant is followed only when the previous bottom item's bottom edge is + // on screen: then the user is reading the end of the conversation. Looked up by key, that item is + // found whether or not the new one is laid out yet. + // requestScrollToItem takes no scroll lock, so a finger on the list cannot cancel the follow. + LaunchedEffect(newest?.id, pendingIds) { + val change = + messageListChange( + messages = messages, + pendingIds = pendingIds, + myUid = uiState.myUid, + previousNewestId = previousNewestId, + previousPendingIds = previousPendingIds, + firstLoad = previousBottomKey == null, + ) + val previousBottom = previousBottomKey + previousNewestId = newest?.id + previousPendingIds = ArrayList(pendingIds) + previousBottomKey = bottomKey + when (change) { + MessageListChange.FOLLOW -> listState.requestScrollToItem(0) + MessageListChange.THEIRS_ARRIVED -> { + val layout = listState.layoutInfo + val atTheEnd = + layout.visibleItemsInfo.any { + it.key == previousBottom && it.offset >= layout.viewportStartOffset + } + if (atTheEnd) listState.requestScrollToItem(0) else newestUnseen = true + } + MessageListChange.NONE -> Unit + } + } + // The hint goes once the newest message, or a photo being sent under it, is in view; a tap whose + // scroll is cut short leaves it up. Looked up by key, which holds whether or not the new message + // is laid out yet. + val endKeys by + rememberUpdatedState(setOfNotNull(newest?.id) + pendingPhotos.map(::pendingPhotoKey)) + LaunchedEffect(listState) { + snapshotFlow { + if (!newestUnseen) return@snapshotFlow false + val layout = listState.layoutInfo + layout.visibleItemsInfo.any { + it.key in endKeys && + it.offset + it.size > layout.viewportStartOffset && + it.offset < layout.viewportEndOffset + } + } + .collect { seen -> if (seen) newestUnseen = false } } Column(modifier = Modifier.fillMaxSize()) { uiState.loadError?.let { LoadErrorRow(text = it.message(), onRetry = onRetry) } - // Laid out from the bottom, newest first, so the newest message stays in view, footer - // included, however long it is and whatever shrinks the list. - LazyColumn( - state = listState, - modifier = Modifier.weight(1f).fillMaxWidth().testTag(ConversationScreenTags.MESSAGE_LIST), - contentPadding = PaddingValues(horizontal = PageMargin, vertical = 12.dp), - reverseLayout = true, - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - // Prefixed: once sent, a photo's message arrives with the same ID. - items(pendingPhotos.asReversed(), key = { "pending_${it.messageId}" }) { pending -> - PendingPhotoBubble( - pending = pending, - onRetry = { photoActions.retry(pending.messageId) }, - onDiscard = { photoActions.discard(pending.messageId) }, - ) + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + // Laid out from the bottom, newest first, so the newest message stays in view, footer + // included, however long it is and whatever shrinks the list. + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize().testTag(ConversationScreenTags.MESSAGE_LIST), + contentPadding = PaddingValues(horizontal = PageMargin, vertical = 12.dp), + reverseLayout = true, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + items(pendingPhotos.asReversed(), key = ::pendingPhotoKey) { pending -> + PendingPhotoBubble( + pending = pending, + onRetry = { photoActions.retry(pending.messageId) }, + onDiscard = { photoActions.discard(pending.messageId) }, + ) + } + items(messages.asReversed(), key = { it.id }) { message -> + MessageBubble( + message = message, + isMine = message.senderUid == uiState.myUid, + otherUsername = uiState.otherUser?.username, + zone = zone, + photo = + message.imagePath?.let { path -> + MessagePhoto( + downloaded = path in uiState.messagePhotos, + decoded = decodedPhotos[path] ?: DecodedPhoto.Loading, + loadError = uiState.photoLoadErrors[path], + pending = message.photoPending, + load = { photoActions.load(path) }, + ) + }, + ) + } } - items(messages.asReversed(), key = { it.id }) { message -> - MessageBubble( - message = message, - isMine = message.senderUid == uiState.myUid, - otherUsername = uiState.otherUser?.username, - zone = zone, - photo = - message.imagePath?.let { path -> - MessagePhoto( - downloaded = path in uiState.messagePhotos, - decoded = decodedPhotos[path] ?: DecodedPhoto.Loading, - loadError = uiState.photoLoadErrors[path], - pending = message.photoPending, - load = { photoActions.load(path) }, - ) - }, + if (newestUnseen) { + NewMessageHint( + onClick = { scope.launch { listState.animateScrollToItem(0) } }, + modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp), ) } } } } +/** Says a message arrived below the view; tapping it scrolls down to the bottom. */ +@Composable +private fun NewMessageHint(onClick: () -> Unit, modifier: Modifier = Modifier) { + OutlinedButton( + onClick = onClick, + modifier = + modifier + // Announced when it appears: TalkBack's focus is on the older message being read. + .semantics { liveRegion = LiveRegionMode.Polite } + .testTag(ConversationScreenTags.NEW_MESSAGE_HINT), + shape = RoundedCornerShape(20.dp), + border = BorderStroke(1.dp, AuthColors.Outline), + colors = ButtonDefaults.outlinedButtonColors(containerColor = AuthColors.CardBackground), + ) { + Text( + text = stringResource(R.string.conversation_new_message), + color = AuthColors.Accent, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + ) + } +} + /** A reload error above messages that stay shown, with Retry as a text button. */ @Composable private fun LoadErrorRow(text: String, onRetry: () -> Unit) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f6e920d0..7b76efea 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -93,6 +93,7 @@ Write a message… Conversation closed Send + New message Add a caption… Add a photo Take photo 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 6d1c76f4..35265bf2 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 @@ -10,10 +10,12 @@ import androidx.activity.result.ActivityResultRegistry import androidx.activity.result.ActivityResultRegistryOwner import androidx.activity.result.contract.ActivityResultContract import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toPixelMap import androidx.compose.ui.semantics.LiveRegionMode @@ -25,6 +27,7 @@ import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertContentDescriptionEquals import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertHasClickAction import androidx.compose.ui.test.assertHasNoClickAction import androidx.compose.ui.test.assertHeightIsEqualTo import androidx.compose.ui.test.assertIsDisplayed @@ -38,13 +41,17 @@ import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.hasText +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.performScrollToIndex +import androidx.compose.ui.test.performScrollToNode import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performTextReplacement +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipe import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp import androidx.core.app.ActivityOptionsCompat @@ -204,6 +211,48 @@ class ConversationScreenTest { ) } + /** When [manyMessages] were sent. */ + private val manyStart = Instant.parse("2026-11-11T08:00:00Z") + + /** More messages than fit on the screen, oldest first: the renter's are the even ones. */ + private val manyMessages = + List(50) { + ChatMessage("m$it", if (it % 2 == 0) "renter" else james.uid, "Message $it", manyStart) + } + + /** + * Shows [messages], through [restoration] when given, and returns how to make a new one arrive + * after them. + */ + private fun showManyMessages( + messages: List = manyMessages, + restoration: StateRestorationTester? = null, + ): (ChatMessage) -> Unit { + var uiState by mutableStateOf(loaded.copy(messages = messages)) + val content: @Composable () -> Unit = { + ConversationContent(uiState = uiState, zone = ZoneOffset.UTC) + } + if (restoration != null) restoration.setContent(content) + else composeTestRule.setContent(content) + return { message -> uiState = uiState.copy(messages = uiState.messages + message) } + } + + /** Scrolls up to the oldest of [manyMessages], at the top of the list. */ + private fun scrollToTheOldest() { + node(ConversationScreenTags.MESSAGE_LIST) + .performScrollToNode(hasTestTag(ConversationScreenTags.myMessage("m0"))) + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + } + + /** Shows [state], and returns how to change it. */ + private fun showChanging( + state: ConversationUiState + ): ((ConversationUiState) -> ConversationUiState) -> Unit { + var uiState by mutableStateOf(state) + composeTestRule.setContent { ConversationContent(uiState = uiState, zone = ZoneOffset.UTC) } + return { change -> uiState = change(uiState) } + } + /** Every text of the empty state. */ private fun emptyStateTexts() = composeTestRule.onAllNodes( @@ -474,18 +523,12 @@ class ConversationScreenTest { @Test fun manyMessages_openOnTheLatest_andFollowANewOne() { - val start = Instant.parse("2026-11-11T08:00:00Z") - val many = - List(50) { - ChatMessage("m$it", if (it % 2 == 0) "renter" else james.uid, "Message $it", start) - } - var uiState by mutableStateOf(loaded.copy(messages = many)) - composeTestRule.setContent { ConversationContent(uiState = uiState, zone = ZoneOffset.UTC) } + val arrive = showManyMessages() assertFullyInTheList(node(ConversationScreenTags.theirMessage("m49"))) node(ConversationScreenTags.myMessage("m0")).assertIsNotDisplayed() - uiState = uiState.copy(messages = many + ChatMessage("m50", "renter", "On my way", start)) + arrive(ChatMessage("m50", "renter", "On my way", manyStart)) assertFullyInTheList(node(ConversationScreenTags.myMessage("m50"))) // The oldest message was only out of view: the list holds it last, newest first. @@ -493,6 +536,295 @@ class ConversationScreenTest { node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() } + @Test + fun theirNewMessageWhileTheLatestIsInView_isFollowed_withoutTheHint() { + val arrive = showManyMessages() + + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + + assertFullyInTheList(node(ConversationScreenTags.theirMessage("m50"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun theirNewMessagesWhileReadingOlderOnes_keepThePlace_andShowTheHint() { + val arrive = showManyMessages() + scrollToTheOldest() + + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + composeTestRule.waitForIdle() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + arrive(ChatMessage("m51", james.uid, "At ten", manyStart)) + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.theirMessage("m50")).assertIsNotDisplayed() + node(ConversationScreenTags.theirMessage("m51")).assertIsNotDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT) + .assertIsDisplayed() + .assertTextEquals(string(R.string.conversation_new_message)) + .assertHasClickAction() + .assert(isPoliteLiveRegion()) + } + + @Test + fun theirNewMessageDuringADragAtTheLatest_isFollowedOnceTheFingerLifts() { + val arrive = showManyMessages() + // Past the touch slop, so the finger holds the list's scroll while it stays down. + node(ConversationScreenTags.MESSAGE_LIST).performTouchInput { + down(center) + moveBy(Offset(0f, viewConfiguration.touchSlop + 5f)) + moveBy(Offset(0f, 5f)) + } + node(ConversationScreenTags.theirMessage("m49")).assertIsDisplayed() + + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + composeTestRule.waitForIdle() + // Held still before lifting, so the list does not fling. + composeTestRule.mainClock.advanceTimeBy(500) + node(ConversationScreenTags.MESSAGE_LIST).performTouchInput { up() } + + assertFullyInTheList(node(ConversationScreenTags.theirMessage("m50"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + // Real text heights, and a window shorter than the long message, so its start and its end are + // not in view together. + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) + @Config(qualifiers = "w360dp-h480dp") + fun theirNewMessageWhileReadingTheStartOfALongNewestOne_keepsThePlace_andShowsTheHint() { + // The longest message the rules allow. + val long = + ChatMessage( + "m49", + james.uid, + "word ".repeat(ChatRules.MAX_MESSAGE_LENGTH / "word ".length), + manyStart, + ) + val arrive = showManyMessages(manyMessages.dropLast(1) + long) + node(ConversationScreenTags.MESSAGE_LIST).performTouchInput { + swipe(Offset(centerX, top + 20f), Offset(centerX, top + 220f), durationMillis = 2000) + } + val list = node(ConversationScreenTags.MESSAGE_LIST).fetchSemanticsNode().boundsInRoot + val reading = node(ConversationScreenTags.theirMessage("m49")).fetchSemanticsNode() + val readingTop = reading.positionInRoot.y + assertTrue("Its end is in view", readingTop + reading.size.height > list.bottom) + + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + + val after = node(ConversationScreenTags.theirMessage("m49")).fetchSemanticsNode() + assertEquals(readingTop, after.positionInRoot.y, 0.5f) + node(ConversationScreenTags.theirMessage("m50")).assertIsNotDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + } + + @Test + fun recreatedWhileTheHintShows_keepsTheHintAndThePlace() { + val restoration = StateRestorationTester(composeTestRule) + val arrive = showManyMessages(restoration = restoration) + scrollToTheOldest() + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + + restoration.emulateSavedInstanceStateRestore() + + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + } + + @Test + fun tappingTheHint_showsTheNewMessage_andHidesTheHint() { + val arrive = showManyMessages() + scrollToTheOldest() + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + + node(ConversationScreenTags.NEW_MESSAGE_HINT).performClick() + + assertFullyInTheList(node(ConversationScreenTags.theirMessage("m50"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun scrollingDownToTheNewMessage_hidesTheHint() { + val arrive = showManyMessages() + scrollToTheOldest() + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + + node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(0) + + node(ConversationScreenTags.theirMessage("m50")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun myNewMessageWhileReadingOlderOnes_isFollowed_withoutTheHint() { + val arrive = showManyMessages() + scrollToTheOldest() + + arrive(ChatMessage("m50", "renter", "On my way", manyStart)) + + assertFullyInTheList(node(ConversationScreenTags.myMessage("m50"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun photoSentWhileReadingOlderOnes_isFollowed() { + val change = showChanging(loaded.copy(messages = manyMessages)) + scrollToTheOldest() + + change { it.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50"))) } + + assertFullyInTheList(node(ConversationScreenTags.pendingPhoto("m50"))) + } + + @Test + fun theirNewMessageWhileAPhotoSendsAtTheEnd_staysAboveThePhoto_withoutTheHint() { + val change = + showChanging( + loaded.copy( + messages = manyMessages, + pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50")), + ) + ) + assertFullyInTheList(node(ConversationScreenTags.pendingPhoto("m50"))) + + change { it.copy(messages = manyMessages + ChatMessage("m51", james.uid, "Nice", manyStart)) } + + assertFullyInTheList(node(ConversationScreenTags.pendingPhoto("m50"))) + node(ConversationScreenTags.theirMessage("m51")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun uploadFinishingWhileReadingOlderOnes_keepsThePlace_withoutTheHint() { + val change = + showChanging( + loaded.copy( + messages = manyMessages + photoMessage("m50", "renter"), + pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50")), + ) + ) + scrollToTheOldest() + + change { it.copy(pendingPhotos = emptyList()) } + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.myMessage("m50")).assertIsNotDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun newerPhotoFinishingAboveAFailedOneWhileReadingOlderOnes_keepsThePlace() { + val change = + showChanging( + loaded.copy( + messages = + manyMessages + photoMessage("m50", "renter") + photoMessage("m51", "renter"), + pendingPhotos = + listOf( + pending(PendingPhotoStatus.FAILED, AppError.NETWORK, id = "m50"), + pending(PendingPhotoStatus.UPLOADING, id = "m51"), + ), + ) + ) + scrollToTheOldest() + + change { it.copy(pendingPhotos = it.pendingPhotos.dropLast(1)) } + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.myMessage("m51")).assertIsNotDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + // A window taller than a photo bubble, so the photo and the messages around it fit together. + @Test + @Config(qualifiers = "w360dp-h800dp") + fun uploadFinishingAtTheEnd_staysAtTheEnd() { + val change = + showChanging( + loaded.copy( + messages = manyMessages + photoMessage("m50", "renter"), + pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50")), + ) + ) + assertFullyInTheList(node(ConversationScreenTags.pendingPhoto("m50"))) + + change { it.copy(pendingPhotos = emptyList()) } + + assertFullyInTheList(node(ConversationScreenTags.myMessage("m50"))) + } + + @Test + fun newestMessageDeletedWhileReadingOlderOnes_withTheirsNowNewest_keepsThePlace_withoutTheHint() { + val change = + showChanging( + loaded.copy(messages = manyMessages + ChatMessage("m50", "renter", "Photo", manyStart)) + ) + scrollToTheOldest() + + change { it.copy(messages = manyMessages) } + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun newestMessageDeletedWhileReadingOlderOnes_withMineNowNewest_keepsThePlace() { + val change = showChanging(loaded.copy(messages = manyMessages)) + scrollToTheOldest() + + change { it.copy(messages = manyMessages.dropLast(1)) } + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + @Config(qualifiers = "w360dp-h800dp") + fun theirNewMessageFullyInViewAboveAFailedPhoto_hidesTheHint() { + val change = + showChanging( + loaded.copy( + messages = manyMessages, + pendingPhotos = + listOf(pending(PendingPhotoStatus.FAILED, AppError.NETWORK, id = "m50")), + ) + ) + scrollToTheOldest() + change { it.copy(messages = manyMessages + ChatMessage("m51", james.uid, "Nice", manyStart)) } + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + + // The new message first from the bottom, the failed photo under it scrolled away. + node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(1) + + assertFullyInTheList(node(ConversationScreenTags.theirMessage("m51"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + @Config(qualifiers = "w360dp-h800dp") + fun theirNewMessageLandingInViewAboveTwoFailedPhotos_leavesNoHint() { + val change = + showChanging( + loaded.copy( + messages = manyMessages, + pendingPhotos = + listOf( + pending(PendingPhotoStatus.FAILED, AppError.NETWORK, id = "m50"), + pending(PendingPhotoStatus.FAILED, AppError.NETWORK, id = "m51"), + ), + ) + ) + // The upper failed photo first from the bottom, the lower one scrolled away. + node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(1) + + change { it.copy(messages = manyMessages + ChatMessage("m52", james.uid, "Nice", manyStart)) } + + node(ConversationScreenTags.theirMessage("m52")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + @Test fun pausedNotice_showsWhileTheMessagesLoad() { setContent( @@ -1035,8 +1367,8 @@ class ConversationScreenTest { private val myPhoto = photoMessage("m3", "renter", caption = "Here it is") private val theirPhoto = photoMessage("m4", james.uid) - private fun pending(status: PendingPhotoStatus, error: AppError? = null) = - PendingPhoto("m5", galleryPhoto, "And the shelf", status, error) + private fun pending(status: PendingPhotoStatus, error: AppError? = null, id: String = "m5") = + PendingPhoto(id, galleryPhoto, "And the shelf", status, error) /** Waits until the photo of message [id] is drawn: [redPhoto] decoded, not the placeholder. */ private fun waitForRedPhoto(id: String) { diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/MessageListChangeTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/MessageListChangeTest.kt new file mode 100644 index 00000000..45a59eb9 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/chat/ui/MessageListChangeTest.kt @@ -0,0 +1,122 @@ +// 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 org.junit.Assert.assertEquals +import org.junit.Test + +class MessageListChangeTest { + + private val sentAt = Instant.parse("2026-11-11T09:00:00Z") + + private fun mine(id: String) = ChatMessage(id, "renter", "Mine", sentAt) + + private fun theirs(id: String) = ChatMessage(id, "lender", "Theirs", sentAt) + + private val shown = listOf(mine("m1"), theirs("m2")) + + /** The change to [messages] and [pendingIds] from [shown] with nothing pending, by default. */ + private fun change( + messages: List, + pendingIds: List = emptyList(), + previousNewestId: String? = "m2", + previousPendingIds: List = emptyList(), + firstLoad: Boolean = false, + ) = + messageListChange( + messages = messages, + pendingIds = pendingIds, + myUid = "renter", + previousNewestId = previousNewestId, + previousPendingIds = previousPendingIds, + firstLoad = firstLoad, + ) + + @Test + fun firstLoad_follows() { + assertEquals( + MessageListChange.FOLLOW, + change(shown, previousNewestId = null, firstLoad = true), + ) + } + + @Test + fun nothingNew_isNone() { + assertEquals(MessageListChange.NONE, change(shown)) + } + + @Test + fun theirMessageAfterTheNewest_arrives() { + assertEquals(MessageListChange.THEIRS_ARRIVED, change(shown + theirs("m3"))) + } + + @Test + fun myMessageAfterTheNewest_follows() { + assertEquals(MessageListChange.FOLLOW, change(shown + mine("m3"))) + } + + @Test + fun theirMessageWhenOnlyAPhotoWasShown_arrives() { + assertEquals( + MessageListChange.THEIRS_ARRIVED, + change( + listOf(theirs("m2")), + pendingIds = listOf("m1"), + previousNewestId = null, + previousPendingIds = listOf("m1"), + ), + ) + } + + @Test + fun photoBeingSent_follows() { + assertEquals(MessageListChange.FOLLOW, change(shown, pendingIds = listOf("m3"))) + } + + @Test + fun anotherPhotoBeingSentAfterAFailedOne_follows() { + assertEquals( + MessageListChange.FOLLOW, + change(shown, pendingIds = listOf("m3", "m4"), previousPendingIds = listOf("m3")), + ) + } + + @Test + fun uploadFinished_revealsThePhotoWithoutAnArrival() { + assertEquals( + MessageListChange.NONE, + change(shown + mine("m3"), previousPendingIds = listOf("m3")), + ) + } + + @Test + fun newerPhotoFinishedAboveAFailedOne_isNone() { + assertEquals( + MessageListChange.NONE, + change( + shown + mine("m4"), + pendingIds = listOf("m3"), + previousPendingIds = listOf("m3", "m4"), + ), + ) + } + + @Test + fun lastPhotoDiscarded_isNone() { + assertEquals( + MessageListChange.NONE, + change(shown, pendingIds = listOf("m3"), previousPendingIds = listOf("m3", "m4")), + ) + } + + @Test + fun newestDeleted_withTheirsNowNewest_isNone() { + assertEquals(MessageListChange.NONE, change(shown, previousNewestId = "m3")) + } + + @Test + fun newestDeleted_withMineNowNewest_isNone() { + assertEquals(MessageListChange.NONE, change(listOf(mine("m1")))) + } +}