Cotton code
612 lines · 32.0 KB · KotlinRaw
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)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.heightimport 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.DropdownMenuimport androidx.compose.material3.DropdownMenuItemimport androidx.compose.material3.pulltorefresh.PullToRefreshBoximport androidx.compose.material3.Textimport androidx.compose.material3.TextFieldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.platform.testTagimport 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.LocalVoiceNotePlayerimport com.cottondb.android.ui.traffic.messages.media.MessageGalleryScreenimport com.cottondb.android.ui.traffic.messages.media.MessageGalleryTargetimport com.cottondb.android.ui.traffic.messages.media.MessageVoiceStripimport com.cottondb.android.ui.traffic.messages.media.rememberMessageVoiceNotePlayerimport com.cottondb.android.media.MediaSourceimport com.cottondb.android.navigation.Routeimport com.cottondb.android.traffic.messages.MessageMediaimport com.cottondb.android.traffic.messages.MessageMutationimport com.cottondb.android.traffic.messages.MessageArchiveModelimport com.cottondb.android.traffic.messages.ThreadActionsModelimport com.cottondb.android.traffic.messages.ThreadActionsStateimport com.cottondb.android.traffic.messages.MessageStarModelimport com.cottondb.android.traffic.messages.MessageStarStateimport com.cottondb.android.traffic.messages.MarkReadStateimport com.cottondb.android.traffic.messages.MessageThreadModelimport com.cottondb.android.traffic.messages.MessageSearchModelimport com.cottondb.android.traffic.messages.MessageSearchReadimport com.cottondb.android.traffic.messages.MessageThreadRowimport com.cottondb.android.traffic.messages.MessagesRepositoryimport com.cottondb.android.traffic.messages.MessagesStateimport com.cottondb.android.traffic.messages.StarredMessageimport com.cottondb.android.traffic.messages.StarredReadimport com.cottondb.android.traffic.messages.ThreadMessageimport com.cottondb.android.traffic.messages.ThreadReadimport com.cottondb.android.ui.media.CottonAvatarimport com.cottondb.android.ui.media.MediaImageimport java.time.Clockimport java.time.Instantimport java.time.ZoneIdimport java.time.format.DateTimeFormatterimport java.time.format.FormatStyleimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launch/** * `/messages`, the imported message archive. This reader never offers a * composer: Cotton preserves imported conversations; it does not send them. * Search uses the same `read.threads` query contract as the Swift reader. */@Composablefun MessagesArchiveScreen(    repository: MessagesRepository,    media: MediaSource,    eventRevision: Long,    clock: Clock,    zoneId: ZoneId,    writerScope: CoroutineScope,    search: MessageSearchModel,    starActions: MessageStarModel,    archive: MessageArchiveModel,    actions: ThreadActionsModel,    onBack: () -> Unit,    onNavigate: (String) -> Unit,) {    val archived by archive.archived.collectAsState()    val actionState by actions.state.collectAsState()    var searching by rememberSaveable { mutableStateOf(false) }    var query by rememberSaveable { mutableStateOf("") }    val searchState by search.state.collectAsState()    LaunchedEffect(search, query) { search.search(query) }    val state by archive.state.collectAsState()    val scope = rememberCoroutineScope()    val refresh: () -> Unit = { scope.launch { archive.refresh() } }    LaunchedEffect(archive, eventRevision) { archive.refresh() }    val cached = state.lastOrNull()    Column(        Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding(),    ) {        ArchiveTopBar(            title = if (archived) "Archived" else "Messages",            onBack = onBack,            search = { searching = !searching },            starred = { onNavigate(Route.MessagesStarred.path) },        )        Row(Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin)) {            ArchiveAction("Import WhatsApp chat") { onNavigate(Route.MessagesImport.path) }        }        when (val change = actionState) {            ThreadActionsState.Idle -> Unit            is ThreadActionsState.Saving -> Text("Saving…", Modifier.padding(horizontal = CottonMetrics.contentMargin), style = CottonTextStyles.caption)            is ThreadActionsState.Error -> ArchiveError(change.message) { actions.retry(writerScope, archive::refresh) }        }        if (searching) {            TextField(                value = query,                onValueChange = { query = it },                modifier = Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 4.dp)                    .semantics { contentDescription = "Search messages" }.testTag("messages-search-input"),                placeholder = { Text("Search messages") },                singleLine = true,            )        }        PullToRefreshBox(            isRefreshing = (state as? MessagesState.Data)?.refreshing == true,            onRefresh = refresh,            modifier = Modifier.weight(1f),        ) {            when {                cached != null -> Column(Modifier.fillMaxSize()) {                    (state as? MessagesState.Error)?.let { ArchiveError(it.message, refresh) }                    if (searching && query.trim().length >= MessageSearchModel.MINIMUM_QUERY) {                        MessageSearchResults(searchState, query.trim(), clock, zoneId, onNavigate) { scope.launch { search.search(query) } }                    } else ThreadsList(                        threads = cached.threads,                        archived = archived,                        archivedCount = cached.archivedCount,                        media = media,                        eventRevision = eventRevision,                        clock = clock,                        zoneId = zoneId,                        writerScope = writerScope,                        actions = actions,                        refreshCurrent = archive::refresh,                        onToggleArchive = { scope.launch { archive.toggleArchived() } },                        onNavigate = onNavigate,                    )                }                state is MessagesState.Loading -> ArchiveSkeleton()                state is MessagesState.Error -> ArchiveFailure((state as MessagesState.Error).message, refresh)            }        }    }}@Composableprivate fun ArchiveTopBar(    title: String,    onBack: () -> Unit,    search: (() -> Unit)? = null,    starred: (() -> Unit)? = null,) = Column(Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp)) {    Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {        Text("Back", Modifier.weight(1f).clickable(role = Role.Button, onClick = onBack)            .padding(vertical = 8.dp), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary)        starred?.let { open ->            Text("Starred", Modifier.clickable(role = Role.Button, onClick = open)                .semantics { contentDescription = "Starred messages" }.padding(8.dp),                style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.accent)        }        search?.let { open ->            Text("Search", Modifier.clickable(role = Role.Button, onClick = open)                .semantics { contentDescription = "Search messages" }.padding(8.dp),                style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.accent)        }    }    Text(title, Modifier.fillMaxWidth().padding(bottom = 8.dp), maxLines = 2,        overflow = TextOverflow.Ellipsis, style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display),        color = CottonPalette.ink)}@Composableprivate fun MessageSearchResults(    state: MessagesState<MessageSearchRead>,    asked: String,    clock: Clock,    zoneId: ZoneId,    onNavigate: (String) -> Unit,    retry: () -> Unit,) {    val cached = state.lastOrNull()?.takeIf { it.query == asked }    Column(Modifier.fillMaxSize()) {        (state as? MessagesState.Error)?.let { ArchiveError(it.message, retry) }        when {        cached != null && cached.matches.isNotEmpty() -> LazyColumn(            Modifier.fillMaxSize(),            contentPadding = PaddingValues(horizontal = CottonMetrics.contentMargin, vertical = 10.dp),            verticalArrangement = Arrangement.spacedBy(10.dp),        ) {            items(cached.matches, key = { it.message.id }) { hit ->                val preview = hit.message.body ?: hit.message.media.firstOrNull()?.name ?: "Attachment"                Row(                    Modifier.fillMaxWidth().background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))                        .clickable(role = Role.Button) { onNavigate(Route.MessagesThread(hit.threadId).path) }                        .semantics { contentDescription = "${hit.threadName}, $preview" }.padding(12.dp),                ) {                    Column(Modifier.weight(1f)) {                        Text(hit.threadName, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink)                        Text(if (hit.message.direction == "out") "You: $preview" else preview, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, maxLines = 2, overflow = TextOverflow.Ellipsis)                    }                    Text(threadTime(hit.message.sentAt, clock, zoneId), style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary)                }            }        }        cached != null -> ArchiveSearchEmpty()        state is MessagesState.Loading -> ArchiveSkeleton()        state is MessagesState.Error -> ArchiveFailure((state as MessagesState.Error).message, retry)        else -> ArchiveSkeleton()        }    }}@Composableprivate fun ArchiveSearchEmpty() = Column(    Modifier.fillMaxWidth().padding(top = 42.dp, start = CottonMetrics.contentMargin, end = CottonMetrics.contentMargin),) { Text("No message says that.", style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) }@Composableprivate fun ThreadsList(    threads: List<MessageThreadRow>,    archived: Boolean,    archivedCount: Long,    media: MediaSource,    eventRevision: Long,    clock: Clock,    zoneId: ZoneId,    writerScope: CoroutineScope,    actions: ThreadActionsModel,    refreshCurrent: suspend () -> Unit,    onToggleArchive: () -> Unit,    onNavigate: (String) -> Unit,) {    val ordered = remember(threads) { threads.sortedWith(compareByDescending<MessageThreadRow> { it.pinnedAt != null }) }    if (ordered.isEmpty()) {        ArchiveEmpty(archived, archivedCount, onToggleArchive)        return    }    LazyColumn(        Modifier.fillMaxSize(),        contentPadding = PaddingValues(horizontal = CottonMetrics.contentMargin, vertical = 10.dp),        verticalArrangement = Arrangement.spacedBy(10.dp),    ) {        items(ordered, key = { it.id }) { thread ->            ThreadStrip(thread, media, eventRevision, clock, zoneId, writerScope, actions, refreshCurrent) {                onNavigate(Route.MessagesThread(thread.id).path)            }        }        item("archive-lid") {            Text(                if (archived) "Back to inbox" else "Archived ($archivedCount)",                Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onToggleArchive)                    .semantics { contentDescription = if (archived) "Back to inbox" else "Open archived conversations" }                    .padding(vertical = 20.dp),                style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type),                color = CottonPalette.inkSecondary,            )        }    }}@Composableprivate fun ThreadStrip(    thread: MessageThreadRow,    media: MediaSource,    eventRevision: Long,    clock: Clock,    zoneId: ZoneId,    writerScope: CoroutineScope,    actions: ThreadActionsModel,    refreshCurrent: suspend () -> Unit,    onOpen: () -> Unit,) {    var menuOpen by remember(thread.id) { mutableStateOf(false) }    val unread = thread.unreadMarkedAt != null    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {        Row(            Modifier.fillMaxWidth().shadow(2.dp, RoundedCornerShape(CottonMetrics.cardRadius))                .background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))                .clickable(role = Role.Button, onClick = onOpen)                .semantics { contentDescription = "${thread.name}, ${thread.preview.orEmpty()}${if (unread) ", unread" else ""}" }                .padding(12.dp),            verticalAlignment = Alignment.CenterVertically,        ) {            CottonAvatar(thread.id, thread.name, thread.pictureKey, media, eventRevision, 46.dp)            Column(Modifier.weight(1f).padding(horizontal = 12.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {                Text(thread.name, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink, maxLines = 1, overflow = TextOverflow.Ellipsis)                Text(thread.preview ?: "No messages here yet.", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis)            }            Column(horizontalAlignment = Alignment.End) {                Text(threadTime(thread.lastMessageAt, clock, zoneId), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary)                if (unread) Box(Modifier.padding(top = 7.dp).size(8.dp).background(CottonPalette.statusError, RoundedCornerShape(4.dp)))                Text(                    "More",                    Modifier.clickable(role = Role.Button, onClick = { menuOpen = true }).semantics { contentDescription = "Actions for ${thread.name}" }.padding(top = 6.dp),                    style = CottonTextStyles.caption,                    color = CottonPalette.accent,                )                DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {                    ThreadActions(                        thread = thread,                        actions = actions,                        writerScope = writerScope,                        refreshCurrent = refreshCurrent,                        close = { menuOpen = false },                    )                }            }        }    }}@Composableprivate fun ThreadActions(    thread: MessageThreadRow,    actions: ThreadActionsModel,    writerScope: CoroutineScope,    refreshCurrent: suspend () -> Unit,    close: () -> Unit,) {    DropdownMenuItem(text = { Text(if (thread.unreadMarkedAt == null) "Mark unread" else "Mark read") },        onClick = { close(); actions.markReadOrUnread(thread, writerScope, refreshCurrent) })    DropdownMenuItem(text = { Text(if (thread.pinnedAt == null) "Pin" else "Unpin") },        onClick = { close(); actions.togglePinned(thread, writerScope, refreshCurrent) })    DropdownMenuItem(text = { Text(if (thread.mutedUntil == null) "Mute" else "Unmute") },        onClick = { close(); actions.toggleMuted(thread, writerScope, refreshCurrent) })    DropdownMenuItem(text = { Text(if (thread.archived) "Move out of archive" else "Archive") },        onClick = { close(); actions.toggleArchived(thread, writerScope, refreshCurrent) })}@Composableprivate fun ArchiveEmpty(archived: Boolean, archivedCount: Long, onToggleArchive: () -> Unit) = Column(    Modifier.fillMaxWidth().padding(top = 42.dp, start = CottonMetrics.contentMargin, end = CottonMetrics.contentMargin),    verticalArrangement = Arrangement.spacedBy(8.dp),) {    Text(if (archived) "Nothing archived" else "No conversations yet.", style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink)    Text(if (archived) "Archived conversations stay in your database." else "Import a WhatsApp export here, or import your message history on the Mac.", style = CottonTextStyles.body, color = CottonPalette.inkSecondary)    ArchiveAction(if (archived) "Back to inbox" else "Archived ($archivedCount)", onToggleArchive)}@Composableprivate fun ArchiveSkeleton() = LazyColumn(    Modifier.fillMaxSize().padding(horizontal = CottonMetrics.contentMargin),    verticalArrangement = Arrangement.spacedBy(10.dp),) { items(7) { Box(Modifier.fillMaxWidth().height(76.dp).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))) } }@Composableprivate fun ArchiveError(message: String, retry: () -> Unit) = Row(    Modifier.fillMaxWidth().background(CottonPalette.groundElevated).padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp),    verticalAlignment = Alignment.CenterVertically,) { Text(message, Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.statusError); ArchiveAction("Try again", retry) }@Composableprivate fun ArchiveFailure(message: String, retry: () -> Unit) = Column(    Modifier.padding(top = 42.dp, start = CottonMetrics.contentMargin, end = CottonMetrics.contentMargin),    verticalArrangement = Arrangement.spacedBy(8.dp),) { Text("Messages could not be read", style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink); Text(message, style = CottonTextStyles.body, color = CottonPalette.inkSecondary); ArchiveAction("Try again", retry) }@Composableprivate fun ArchiveAction(label: String, onClick: () -> Unit) = Text(label, Modifier.clickable(role = Role.Button, onClick = onClick).semantics { contentDescription = label }.padding(vertical = 8.dp), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.accent)/** Reader for an archive thread; there is intentionally no composer. */@Composablefun MessageThreadScreen(    model: MessageThreadModel,    repository: MessagesRepository,    media: MediaSource,    eventRevision: Long,    clock: Clock,    zoneId: ZoneId,    writerScope: CoroutineScope,    starActions: MessageStarModel,    onBack: () -> Unit,    onInfo: (() -> Unit)? = null,) {    val voice = rememberMessageVoiceNotePlayer(media)    var gallery by remember(model) { mutableStateOf<MessageGalleryTarget?>(null) }    val openedGallery = gallery    if (openedGallery != null) {        MessageGalleryScreen(openedGallery, media, eventRevision, zoneId) { gallery = null }        return    }    val state by model.state.collectAsState()    val markRead by model.markRead.collectAsState()    val scope = rememberCoroutineScope()    val refresh: () -> Unit = { scope.launch { model.open(writerScope) } }    LaunchedEffect(model, eventRevision) { model.open(writerScope) }    val cached = state.lastOrNull()    Column(Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding()) {        ArchiveTopBar(cached?.thread?.name ?: "Conversation", onBack)        onInfo?.let { open ->            Row(Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin)) {                ArchiveAction("Conversation info", open)            }        }        MarkReadNotice(markRead) { model.retryMarkRead(writerScope) }        PullToRefreshBox(            isRefreshing = (state as? MessagesState.Data)?.refreshing == true,            onRefresh = refresh,            modifier = Modifier.weight(1f),        ) {            when {                cached != null -> Column(Modifier.fillMaxSize()) {                    (state as? MessagesState.Error)?.let { ArchiveError(it.message, refresh) }                    ThreadTimeline(cached, media, eventRevision, clock, zoneId, writerScope, model, repository, starActions, voice) { gallery = it }                }                state is MessagesState.Loading -> ThreadSkeleton()                state is MessagesState.Error -> ArchiveFailure((state as MessagesState.Error).message, refresh)            }        }    }}@Composableprivate fun MarkReadNotice(state: MarkReadState, retry: () -> Unit) {    when (state) {        MarkReadState.Idle, MarkReadState.Marked -> Unit        MarkReadState.Saving -> Text(            "Marking this conversation read…",            Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp),            style = CottonTextStyles.caption,            color = CottonPalette.inkSecondary,        )        is MarkReadState.Error -> Row(            Modifier.fillMaxWidth().background(CottonPalette.groundElevated)                .padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp),            verticalAlignment = Alignment.CenterVertically,        ) {            Text(                "This conversation was opened, but could not be marked read: ${state.message}",                Modifier.weight(1f),                style = CottonTextStyles.caption,                color = CottonPalette.statusError,            )            ArchiveAction("Try again", retry)        }    }}@Composableprivate fun ThreadTimeline(read: ThreadRead, media: MediaSource, eventRevision: Long, clock: Clock, zoneId: ZoneId, writerScope: CoroutineScope, model: MessageThreadModel, repository: MessagesRepository, starActions: MessageStarModel, voice: LocalVoiceNotePlayer, onGallery: (MessageGalleryTarget) -> Unit) = LazyColumn(    Modifier.fillMaxSize(),    contentPadding = PaddingValues(horizontal = CottonMetrics.contentMargin, vertical = 8.dp),    verticalArrangement = Arrangement.spacedBy(10.dp),) {    if (read.hasMore) item("older") { ArchiveAction("Load older messages") { model.loadOlder(writerScope) } }    items(read.messages.sortedBy { it.sentAt }, key = { it.id }) { message -> MessageBubble(        message,        media,        eventRevision,        clock,        zoneId,        writerScope,        repository,        starActions,        voice,        onGallery,        refresh = { model.refreshCurrent() },    ) }    if (read.messages.isEmpty()) item("empty") { Text("No messages here yet.", Modifier.padding(top = 36.dp), style = CottonTextStyles.body, color = CottonPalette.inkSecondary) }}@Composableprivate fun MessageBubble(message: ThreadMessage, media: MediaSource, eventRevision: Long, clock: Clock, zoneId: ZoneId, writerScope: CoroutineScope, repository: MessagesRepository, starActions: MessageStarModel, voice: LocalVoiceNotePlayer, onGallery: (MessageGalleryTarget) -> Unit, refresh: suspend () -> Unit) {    val mine = message.direction == "out"    Row(Modifier.fillMaxWidth(), horizontalArrangement = if (mine) Arrangement.End else Arrangement.Start) {        Column(            Modifier.fillMaxWidth(if (message.body.orEmpty().length > 280) .9f else .76f)                .shadow(1.dp, RoundedCornerShape(CottonMetrics.cardRadius))                .background(if (mine) CottonPalette.selection else CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))                .padding(12.dp),            verticalArrangement = Arrangement.spacedBy(7.dp),        ) {            message.from?.takeIf { !mine && it.isNotBlank() }?.let { Text(it, style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.display), color = CottonPalette.statusError) }            if (message.deleted) Text("This message was deleted.", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)            message.body?.takeIf(String::isNotBlank)?.let { Text(it, style = CottonTextStyles.body, color = CottonPalette.inkBody) }            val images = message.media.filter { it.kind == "image" || it.contentType.startsWith("image/") }            message.media.forEach { item ->                Attachment(item, media, eventRevision, voice) {                    val index = images.indexOf(item)                    if (index >= 0) onGallery(MessageGalleryTarget(images, index, message.body, message.from, message.sentAt))                }            }            Text("${threadTime(message.sentAt, clock, zoneId)}${if (message.edited) " · edited" else ""}", Modifier.fillMaxWidth(), style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary)            if (!message.system && !message.deleted) {                StarAction(                    messageId = message.id,                    starred = message.starredAt == null,                    label = if (message.starredAt == null) "Keep" else "Stop keeping",                    model = starActions,                    writerScope = writerScope,                    refresh = refresh,                )            }        }    }}@Composableprivate fun Attachment(media: MessageMedia, source: MediaSource, eventRevision: Long, voice: LocalVoiceNotePlayer, onOpen: () -> Unit) {    val image = media.kind == "image" || media.contentType.startsWith("image/")    if (image && media.key != null) {        MediaImage(media.key, source, eventRevision, 176.dp, Modifier.size(176.dp).clickable(role = Role.Button, onClick = onOpen), "Open message image")    } else if (media.kind == "voice" || media.contentType.startsWith("audio/")) {        MessageVoiceStrip(media, voice)    } else {        val label = when {            media.kind == "voice" || media.contentType.startsWith("audio/") -> "Voice note${media.durationMs?.let { " · ${it / 1000}s" }.orEmpty()}"            else -> media.name ?: "Attachment"        }        Text(label, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)    }}@Composableprivate fun ThreadSkeleton() = LazyColumn(Modifier.fillMaxSize().padding(horizontal = CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(12.dp)) { items(6) { index -> Box(Modifier.fillMaxWidth(if (index % 2 == 0) .7f else .56f).height(if (index % 3 == 0) 72.dp else 50.dp).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))) } }/** `/messages/starred`: the records returned by `read.starred`, with unstar only. */@Composablefun StarredMessagesScreen(repository: MessagesRepository, eventRevision: Long, clock: Clock, zoneId: ZoneId, writerScope: CoroutineScope, starActions: MessageStarModel, onBack: () -> Unit, onNavigate: (String) -> Unit) {    val state by repository.starred.collectAsState()    val scope = rememberCoroutineScope()    val refresh: () -> Unit = { scope.launch { repository.refreshStarred() } }    LaunchedEffect(repository, eventRevision) { repository.refreshStarred() }    val cached = state.lastOrNull()    Column(Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding()) {        ArchiveTopBar("Starred", onBack)        when {            cached != null -> Column(Modifier.fillMaxSize()) {                (state as? MessagesState.Error)?.let { ArchiveError(it.message, refresh) }                StarredList(cached, clock, zoneId, writerScope, repository, starActions, onNavigate)            }            state is MessagesState.Loading -> ArchiveSkeleton()            state is MessagesState.Error -> ArchiveFailure((state as MessagesState.Error).message, refresh)        }    }}@Composableprivate fun StarredList(read: StarredRead, clock: Clock, zoneId: ZoneId, writerScope: CoroutineScope, repository: MessagesRepository, starActions: MessageStarModel, onNavigate: (String) -> Unit) {    if (read.messages.isEmpty()) { ArchiveEmptyStarred(); return }    LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(10.dp)) {        items(read.messages, key = { it.id }) { message -> StarredStrip(message, clock, zoneId, writerScope, repository, starActions) { onNavigate(Route.MessagesThread(message.threadId).path) } }    }}@Composableprivate fun StarredStrip(message: StarredMessage, clock: Clock, zoneId: ZoneId, writerScope: CoroutineScope, repository: MessagesRepository, starActions: MessageStarModel, onOpen: () -> Unit) = Row(    Modifier.fillMaxWidth().background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)).clickable(role = Role.Button, onClick = onOpen).padding(12.dp),    verticalAlignment = Alignment.CenterVertically,) {    Column(Modifier.weight(1f)) { Text(message.threadName ?: "Conversation", style = CottonTextStyles.body.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink); Text(message.body ?: message.media.firstOrNull()?.name ?: "Attachment", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, maxLines = 2, overflow = TextOverflow.Ellipsis) }    Column(horizontalAlignment = Alignment.End) { Text(threadTime(message.sentAt, clock, zoneId), style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary); StarAction(message.id, false, "Stop keeping", starActions, writerScope) { repository.refreshStarred() } }}@Composableprivate fun StarAction(    messageId: String,    starred: Boolean,    label: String,    model: MessageStarModel,    writerScope: CoroutineScope,    refresh: suspend () -> Unit,) {    val state by model.state.collectAsState()    val relevant = when (val current = state) {        is MessageStarState.Saving -> current.takeIf { it.messageId == messageId }        is MessageStarState.Error -> current.takeIf { it.messageId == messageId }        MessageStarState.Idle -> null    }    when (relevant) {        is MessageStarState.Saving -> Text("Saving…", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)        is MessageStarState.Error -> {            Text(relevant.message, style = CottonTextStyles.caption, color = CottonPalette.statusError)            ArchiveAction("Try again") { model.retry(writerScope, refresh) }        }        else -> ArchiveAction(label) { model.setStarred(messageId, starred, writerScope, refresh) }    }}@Composableprivate fun ArchiveEmptyStarred() = Column(Modifier.padding(top = 42.dp, start = CottonMetrics.contentMargin, end = CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text("No starred messages", style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink); Text("Messages you star appear here.", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) }private fun <T> MessagesState<T>.lastOrNull(): T? = when (this) { is MessagesState.Data -> read; is MessagesState.Error -> last; MessagesState.Loading -> null }private fun threadTime(iso: String?, clock: Clock, zoneId: ZoneId): String = iso?.let { runCatching { DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withZone(zoneId).format(Instant.parse(it)) }.getOrNull() } ?: ""