Cotton code
364 lines · 19.6 KB · KotlinRaw
package com.cottondb.android.ui.traffic.messagesimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.material3.TextFieldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.media.LocalMediaSourceimport com.cottondb.android.navigation.Routeimport com.cottondb.android.traffic.messages.MessageMediaimport com.cottondb.android.traffic.messages.ThreadDetailsRepositoryimport com.cottondb.android.traffic.messages.ThreadDetailsMutationModelimport com.cottondb.android.traffic.messages.ThreadDetailActionimport com.cottondb.android.traffic.messages.ThreadDetailActionStateimport com.cottondb.android.traffic.messages.ThreadPrivateFieldsModelimport com.cottondb.android.traffic.messages.ThreadPrivateFieldsStateimport com.cottondb.android.traffic.messages.ThreadDetailsStateimport com.cottondb.android.traffic.messages.ThreadInfoReadimport com.cottondb.android.traffic.messages.ThreadMediaReadimport com.cottondb.android.ui.media.MediaImageimport com.cottondb.android.ui.traffic.messages.media.MessageGalleryTargetimport java.time.Clockimport java.time.Instantimport java.time.ZoneIdimport java.time.format.DateTimeFormatterimport java.time.format.FormatStyleimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launch/** `/messages/[thread]/info`: imported archive facts and the owner's private settings. */@Composablefun 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. */@Composablefun 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) }            }        }    }}@Composableprivate 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)                }            }        }    }}@Composableprivate 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") } },    )}@Composableprivate 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)}@Composableprivate 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() }@Composableprivate 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)}@Composableprivate 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,)@Composableprivate 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)}@Composableprivate fun ThreadDetailsLoading() = Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {    Text("Reading conversation…", style = CottonTextStyles.body, color = CottonPalette.inkSecondary)}@Composableprivate 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)) ?: valueprivate fun <T> ThreadDetailsState<T>.previous(): T? = when (this) { is ThreadDetailsState.Data -> value; is ThreadDetailsState.Error -> last; ThreadDetailsState.Loading -> null }