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/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 42f4159f..03ba0fa3 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.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -54,8 +55,10 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha 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.LocalContext import androidx.compose.ui.platform.testTag @@ -66,6 +69,7 @@ import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.Role 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 @@ -92,11 +96,17 @@ import com.android.polybazaar.chat.viewmodel.PendingPhoto import com.android.polybazaar.chat.viewmodel.PendingPhotoStatus 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 com.android.polybazaar.listing.ui.CameraPermissionDialog import com.android.polybazaar.listing.ui.decodePhotoPreview import com.android.polybazaar.listing.ui.loadPhotoPreview import com.android.polybazaar.listing.ui.rememberPhotoCamera import java.time.Instant +import java.time.LocalDate import java.time.ZoneId import java.time.ZoneOffset import java.time.format.DateTimeFormatter @@ -107,6 +117,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" @@ -131,6 +147,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" + /** Tag of the photo of the message with [id], or of its placeholder while it loads. */ fun messagePhoto(id: String) = "conversation_message_photo_$id" @@ -260,7 +279,8 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { * user taps a photo that failed to load. * @param onRetryPhoto called with the message ID of a failed photo when the user taps Retry. * @param onDiscardPhoto called with the message ID of a failed photo when the user taps Remove. - * @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( @@ -277,6 +297,7 @@ fun ConversationContent( onRetryPhoto: (String) -> Unit = {}, onDiscardPhoto: (String) -> Unit = {}, zone: ZoneId = ZoneId.systemDefault(), + now: Instant = Instant.now(), ) { val body = conversationBody(uiState) val deleted = uiState.listingStatus == ConversationListingStatus.DELETED @@ -296,7 +317,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) { @@ -313,6 +345,7 @@ fun ConversationContent( MessageList( uiState = uiState, zone = zone, + today = now.atZone(zone).toLocalDate(), onRetry = onRetry, photoActions = PhotoActions(onLoadPhoto, onRetryPhoto, onDiscardPhoto), ) @@ -341,9 +374,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), @@ -364,8 +406,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, @@ -374,10 +423,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), + ) + } +} + +/** + * 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) } - HorizontalDivider(color = AuthColors.Outline) } +/** 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. @@ -396,43 +569,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) { @@ -451,6 +661,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, @@ -495,12 +710,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 = @@ -523,6 +733,15 @@ 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), + ) + } } } @@ -534,18 +753,20 @@ private class PhotoActions( ) /** - * The messages, oldest at the top, then the photos being sent, 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, then the photos being sent, + * with the load error and Retry above them when a reload failed. */ @Composable private fun MessageList( uiState: ConversationUiState, zone: ZoneId, + today: LocalDate, onRetry: () -> Unit, photoActions: PhotoActions, ) { val messages = uiState.shownMessages val pendingPhotos = uiState.pendingPhotos + val items = remember(messages, zone) { conversationItems(messages, zone).asReversed() } val listState = rememberLazyListState() // Decoded above the list: a bubble that scrolls out of view and back shows its photo at once. val decodedPhotos = rememberDecodedPhotos(uiState.messagePhotos) @@ -573,28 +794,59 @@ private fun MessageList( 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( + 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 -> { + val message = item.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) }, + ) + }, + ) + } + 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) { @@ -1223,11 +1475,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( @@ -1241,7 +1497,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( @@ -1249,14 +1505,27 @@ 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/java/com/android/polybazaar/chat/ui/InboxScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt index c74abe61..f8dcdde5 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), @@ -464,35 +453,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. @@ -580,16 +540,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. 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 f6e920d0..15508db5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -77,7 +77,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 @@ -88,6 +99,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 6d1c76f4..4f9241e0 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 @@ -43,6 +43,7 @@ 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 @@ -72,7 +73,9 @@ import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.ListingCategory +import com.android.polybazaar.listing.model.ListingLocation import com.android.polybazaar.listing.model.PhotoStorage +import com.android.polybazaar.listing.model.ServiceListing import com.android.polybazaar.listing.model.TakenPhoto import com.android.polybazaar.listing.ui.CreateListingScreenTags import com.android.polybazaar.profile.model.FakeProfileRepository @@ -80,6 +83,7 @@ import com.android.polybazaar.profile.ui.redPhoto import java.io.File import java.net.UnknownHostException import java.time.Instant +import java.time.LocalDate import java.time.ZoneOffset import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope @@ -126,10 +130,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 = {}, @@ -159,6 +167,7 @@ class ConversationScreenTest { onRetryPhoto = onRetryPhoto, onDiscardPhoto = onDiscardPhoto, zone = ZoneOffset.UTC, + now = now, ) } } @@ -212,6 +221,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, @@ -361,6 +384,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() } @@ -488,8 +514,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() } @@ -509,7 +536,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() @@ -917,6 +945,175 @@ class ConversationScreenTest { 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") + } + // Photo button and attached photo // A photo that cannot be read, which shows the placeholder: Robolectric throws for an unknown