Skip to content
212 changes: 175 additions & 37 deletions app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
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
Expand Down Expand Up @@ -32,12 +33,14 @@
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
Expand All @@ -49,7 +52,11 @@
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
Expand Down Expand Up @@ -101,6 +108,7 @@
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

object ConversationScreenTags {
const val SCREEN = "conversation_screen"
Expand All @@ -124,6 +132,7 @@
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"
Expand Down Expand Up @@ -169,6 +178,47 @@
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<ChatMessage>,
pendingIds: List<String>,
myUid: String,
previousNewestId: String?,
previousPendingIds: List<String>,
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

Expand Down Expand Up @@ -533,9 +583,12 @@
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(
Expand All @@ -546,55 +599,140 @@
) {
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<String?>(null) }
var previousPendingIds by rememberSaveable { mutableStateOf(ArrayList<String>()) }

Check warning on line 613 in app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Creating a MutableState object with a mutable collection type

See more on https://sonarcloud.io/project/issues?id=polybazaar-project_polybazaar&issues=AaHx3d2QjukvljkZYX95&open=AaHx3d2QjukvljkZYX95&pullRequest=381
var previousBottomKey by rememberSaveable { mutableStateOf<String?>(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
Comment thread
alexxg20 marked this conversation as resolved.
Resolved
}
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) {
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
<string name="conversation_placeholder">Write a message…</string>
<string name="conversation_placeholder_closed">Conversation closed</string>
<string name="conversation_send">Send</string>
<string name="conversation_new_message">New message</string>
Comment thread
alexxg20 marked this conversation as resolved.
Resolved
<string name="conversation_placeholder_caption">Add a caption…</string>
<string name="conversation_photo_button">Add a photo</string>
<string name="conversation_take_photo">Take photo</string>
Expand Down
Loading
Loading