package com.cottondb.android.ui.traffic.messages import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.cottondb.android.design.CottonFonts import com.cottondb.android.design.CottonMetrics import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette import com.cottondb.android.media.LocalMediaSource import com.cottondb.android.navigation.Route import com.cottondb.android.traffic.messages.MessageMedia import com.cottondb.android.traffic.messages.ThreadDetailsRepository import com.cottondb.android.traffic.messages.ThreadDetailsMutationModel import com.cottondb.android.traffic.messages.ThreadDetailAction import com.cottondb.android.traffic.messages.ThreadDetailActionState import com.cottondb.android.traffic.messages.ThreadPrivateFieldsModel import com.cottondb.android.traffic.messages.ThreadPrivateFieldsState import com.cottondb.android.traffic.messages.ThreadDetailsState import com.cottondb.android.traffic.messages.ThreadInfoRead import com.cottondb.android.traffic.messages.ThreadMediaRead import com.cottondb.android.ui.media.MediaImage import com.cottondb.android.ui.traffic.messages.media.MessageGalleryTarget import java.time.Clock import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch /** `/messages/[thread]/info`: imported archive facts and the owner's private settings. */ @Composable fun ThreadInfoScreen( route: Route.MessagesInfo, repository: ThreadDetailsRepository, mutation: ThreadDetailsMutationModel, privateFields: ThreadPrivateFieldsModel, eventRevision: Long, writerScope: CoroutineScope, onBack: () -> Unit, onDeleted: () -> Unit, onNavigate: (String) -> Unit, ) { val state by repository.info.collectAsState() val action by mutation.state.collectAsState() val scope = rememberCoroutineScope() val privateState by privateFields.state.collectAsState() LaunchedEffect(repository, route.thread, eventRevision) { repository.refreshInfo(route.thread) } LaunchedEffect(action) { if (action == ThreadDetailActionState.Deleted && mutation.consumeDeleted()) onDeleted() } val cached = state.previous() LaunchedEffect(cached?.thread) { cached?.thread?.let(privateFields::updateFromRead) } Column(Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding()) { ThreadDetailsTopBar(cached?.thread?.title ?: "Conversation", onBack) when { cached != null -> LazyColumn( Modifier.fillMaxSize().testTag("thread-info-sections"), contentPadding = PaddingValues(horizontal = CottonMetrics.contentMargin, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { (state as? ThreadDetailsState.Error)?.let { error -> item("read-error") { ThreadDetailsError(error.message) { scope.launch { repository.refreshInfo(route.thread) } } } } item("about") { ThreadPaperCard("About") { DetailPair("Kind", if (cached.thread.kind == "group") "Group" else "One-to-one chat") cached.thread.description?.takeIf(String::isNotBlank)?.let { DetailPair("Description", it) } DetailPair("Archive", if (cached.thread.archived) "Archived" else "In messages") cached.thread.lastMessageAt?.let { DetailPair("Last message", formatInstant(it, ZoneId.systemDefault())) } } } item("media") { ThreadPaperCard("Media") { val attachmentCount = cached.media.sumOf { it.media.size } ThreadLink("$attachmentCount attachments") { onNavigate(Route.MessagesMedia(route.thread).path) } } } item("members") { ThreadPaperCard("People") { cached.participants.filter { it.leftAt == null }.forEach { participant -> val name = if (participant.isSelf) "You" else participant.displayName ?: "Unknown" val annotation = when { participant.role == "admin" -> "admin" participant.contactId == null && !participant.isSelf -> "not identified" else -> null } DetailPair(name, annotation ?: "") } } } item("summary") { ThreadPaperCard("Your note") { when (val fields = privateState) { is ThreadPrivateFieldsState.Editing -> { TextField( value = fields.draft, onValueChange = privateFields::changeDraft, modifier = Modifier.fillMaxWidth().semantics { contentDescription = "Conversation note" }, textStyle = CottonTextStyles.body, ) fields.error?.let { ThreadDetailsError(it) { privateFields.saveSummary(writerScope) } } Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { ThreadLink("Cancel", onClick = privateFields::cancelEdit) ThreadLink("Save", onClick = { privateFields.saveSummary(writerScope) }) } } is ThreadPrivateFieldsState.Saving -> Text("Saving…", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) is ThreadPrivateFieldsState.Viewing -> { Text(fields.summary ?: "No private note yet.", style = CottonTextStyles.body, color = CottonPalette.ink) ThreadLink("Edit note", onClick = privateFields::editSummary) } } } } item("settings") { val fields = privateState val viewing = fields as? ThreadPrivateFieldsState.Viewing val saving = fields is ThreadPrivateFieldsState.Saving ThreadPaperCard("Private settings") { ThreadLink(if (viewing?.muted == true) "Unmute conversation" else "Mute conversation", enabled = viewing != null && !saving) { privateFields.toggleMuted(writerScope) } ThreadLink(if (viewing?.pinned == true) "Unpin conversation" else "Pin conversation", enabled = viewing != null && !saving) { privateFields.togglePinned(writerScope) } viewing?.error?.let { ThreadDetailsError(it) { privateFields.retry(writerScope) } } } } item("clear") { ThreadPaperCard("Archive actions") { Text("Nothing is sent from Cotton. This is an archive of a conversation that happened somewhere else.", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) ThreadLink("Clear chat", color = CottonPalette.statusError) { mutation.request(ThreadDetailAction.ClearChat) } ThreadLink("Delete chat", color = CottonPalette.statusError) { mutation.request(ThreadDetailAction.DeleteChat) } } } } state is ThreadDetailsState.Loading -> ThreadDetailsLoading() state is ThreadDetailsState.Error -> ThreadDetailsFailure((state as ThreadDetailsState.Error).message) { scope.launch { repository.refreshInfo(route.thread) } } } } ThreadDetailsConfirmation(action, mutation, writerScope) } /** `/messages/[thread]/media`: a local-path-only attachment index. */ @Composable fun ThreadMediaScreen( route: Route.MessagesMedia, repository: ThreadDetailsRepository, source: LocalMediaSource, eventRevision: Long, clock: Clock, zoneId: ZoneId, onBack: () -> Unit, onNavigate: (String) -> Unit, onOpenGallery: (MessageGalleryTarget) -> Unit, modifier: Modifier = Modifier, ) { val state by repository.media.collectAsState() val scope = rememberCoroutineScope() LaunchedEffect(repository, route.thread, eventRevision) { repository.refreshMedia(route.thread) } val cached = state.previous() Column(Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding()) { ThreadDetailsTopBar("Media", onBack) when { cached != null -> Column(Modifier.fillMaxSize()) { (state as? ThreadDetailsState.Error)?.let { error -> ThreadDetailsError(error.message) { scope.launch { repository.refreshMedia(route.thread) } } } ThreadMediaList(cached, source, eventRevision, clock, zoneId, route.thread, onNavigate, onOpenGallery, Modifier.weight(1f)) } state is ThreadDetailsState.Loading -> ThreadDetailsLoading() state is ThreadDetailsState.Error -> ThreadDetailsFailure((state as ThreadDetailsState.Error).message) { scope.launch { repository.refreshMedia(route.thread) } } } } } @Composable private fun ThreadMediaList( read: ThreadMediaRead, source: LocalMediaSource, eventRevision: Long, clock: Clock, zoneId: ZoneId, threadId: String, onNavigate: (String) -> Unit, onOpenGallery: (MessageGalleryTarget) -> Unit, modifier: Modifier = Modifier, ) { val rows = read.media.flatMapIndexed { rowIndex, row -> row.media.mapIndexed { mediaIndex, item -> Triple(rowIndex, mediaIndex, row to item) } } if (rows.isEmpty()) { Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text("Photos, videos, files and voice notes collect here.", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) } return } LazyColumn( modifier.fillMaxSize(), contentPadding = PaddingValues(horizontal = CottonMetrics.contentMargin, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { items(rows, key = { (rowIndex, mediaIndex, pair) -> "${pair.first.messageId}:$rowIndex:$mediaIndex" }) { (_, _, pair) -> val (row, item) = pair val visual = item.isVisual() Row( Modifier.fillMaxWidth().background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)) .clickable(role = Role.Button) { if (item.isPicture()) { val pictures = row.media.filter { it.isPicture() } val index = pictures.indexOf(item) if (index >= 0) onOpenGallery(MessageGalleryTarget(pictures, index, null, null, row.sentAt)) } else { onNavigate(Route.MessagesThread(threadId).path) } } .padding(12.dp), verticalAlignment = Alignment.CenterVertically, ) { if (item.isPicture() && item.key != null) { // This renderer resolves an already-local key only; it never calls media.ensure. MediaImage(item.key, source, eventRevision, 58.dp, Modifier.size(58.dp), "Message attachment") } else { Box(Modifier.size(58.dp).background(CottonPalette.selection, RoundedCornerShape(CottonMetrics.cardRadius)), contentAlignment = Alignment.Center) { Text(if (visual) "Video" else item.kindLabel(), style = CottonTextStyles.caption, color = CottonPalette.ink) } } Column(Modifier.weight(1f).padding(start = 12.dp)) { Text(item.name ?: item.contentType.ifBlank { "Attachment" }, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink, maxLines = 1, overflow = TextOverflow.Ellipsis) Text("${item.kindLabel()} · ${formatInstant(row.sentAt, zoneId)}", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } } } } @Composable private fun ThreadDetailsConfirmation( state: ThreadDetailActionState, model: ThreadDetailsMutationModel, writerScope: CoroutineScope, ) { val action = when (state) { is ThreadDetailActionState.Confirming -> state.action is ThreadDetailActionState.Refused -> state.action else -> return } val refusal = (state as? ThreadDetailActionState.Refused)?.message AlertDialog( onDismissRequest = model::dismissConfirmation, title = { Text(action.confirmationTitle(), fontFamily = CottonFonts.display) }, text = { Text(refusal ?: action.confirmationBody()) }, confirmButton = { TextButton(modifier = Modifier.testTag("thread-action-confirm"), onClick = { if (state is ThreadDetailActionState.Refused) model.retry(writerScope) else model.confirm(writerScope) }) { Text(if (state is ThreadDetailActionState.Refused) "Try again" else action.confirmationVerb()) } }, dismissButton = { TextButton(modifier = Modifier.testTag("thread-action-cancel"), onClick = model::dismissConfirmation) { Text("Cancel") } }, ) } @Composable private fun ThreadDetailsTopBar(title: String, onBack: () -> Unit) = Column( Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { ThreadLink("Back", onClick = onBack) Text(title, Modifier.fillMaxWidth(), style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) } @Composable private fun ThreadPaperCard(title: String, content: @Composable () -> Unit) = Column( Modifier.fillMaxWidth().background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)).padding(14.dp), verticalArrangement = Arrangement.spacedBy(9.dp), ) { Text(title, style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary); content() } @Composable private fun DetailPair(label: String, value: String) = Row(Modifier.fillMaxWidth()) { Text(label, Modifier.weight(1f), style = CottonTextStyles.body, color = CottonPalette.ink) if (value.isNotBlank()) Text(value, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } @Composable private fun ThreadLink(label: String, enabled: Boolean = true, color: androidx.compose.ui.graphics.Color = CottonPalette.accent, onClick: () -> Unit) = Text( label, Modifier.clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = label }.padding(vertical = 4.dp), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = if (enabled) color else CottonPalette.inkSecondary, ) @Composable private fun ThreadDetailsError(message: String, retry: () -> Unit) = Row(Modifier.fillMaxWidth().background(CottonPalette.groundElevated).padding(10.dp)) { Text(message, Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.statusError) ThreadLink("Try again", onClick = retry) } @Composable private fun ThreadDetailsLoading() = Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text("Reading conversation…", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) } @Composable private fun ThreadDetailsFailure(message: String, retry: () -> Unit) = Column( Modifier.fillMaxSize().padding(CottonMetrics.contentMargin), verticalArrangement = Arrangement.Center, ) { Text("Conversation could not be read", style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink); Text(message, style = CottonTextStyles.body, color = CottonPalette.inkSecondary); ThreadLink("Try again", onClick = retry) } private fun ThreadDetailAction.confirmationTitle() = when (this) { is ThreadDetailAction.HideMessages -> "Hide selected messages?" ThreadDetailAction.ClearChat -> "Clear this chat?" ThreadDetailAction.DeleteChat -> "Delete this chat?" } private fun ThreadDetailAction.confirmationBody() = when (this) { is ThreadDetailAction.HideMessages -> "The selected messages disappear from your copy. Nobody else’s archive changes." ThreadDetailAction.ClearChat -> "Everything before now is hidden from your copy. This cannot be undone here." ThreadDetailAction.DeleteChat -> "This removes the conversation, messages, people entries, receipts and reactions from this database. There is no bin." } private fun ThreadDetailAction.confirmationVerb() = when (this) { is ThreadDetailAction.HideMessages -> "Hide" ThreadDetailAction.ClearChat -> "Clear chat" ThreadDetailAction.DeleteChat -> "Delete chat" } private fun MessageMedia.isVisual() = kind in setOf("image", "video") || contentType.startsWith("image/") || contentType.startsWith("video/") private fun MessageMedia.isPicture() = kind == "image" || (kind !in setOf("video", "voice", "audio", "file", "contact") && contentType.startsWith("image/")) private fun MessageMedia.kindLabel() = when (kind) { "voice", "audio" -> "Voice note"; "contact" -> "Contact"; "video" -> "Video"; "image" -> "Photo"; else -> if (contentType.startsWith("audio/")) "Voice note" else "File" } private fun formatInstant(value: String, zoneId: ZoneId): String = runCatching { Instant.parse(value) }.getOrNull()?.atZone(zoneId)?.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(zoneId)) ?: value private fun ThreadDetailsState.previous(): T? = when (this) { is ThreadDetailsState.Data -> value; is ThreadDetailsState.Error -> last; ThreadDetailsState.Loading -> null }