@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) 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.height 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.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.pulltorefresh.PullToRefreshBox import androidx.compose.material3.Text 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.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.platform.testTag 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.LocalVoiceNotePlayer import com.cottondb.android.ui.traffic.messages.media.MessageGalleryScreen import com.cottondb.android.ui.traffic.messages.media.MessageGalleryTarget import com.cottondb.android.ui.traffic.messages.media.MessageVoiceStrip import com.cottondb.android.ui.traffic.messages.media.rememberMessageVoiceNotePlayer import com.cottondb.android.media.MediaSource import com.cottondb.android.navigation.Route import com.cottondb.android.traffic.messages.MessageMedia import com.cottondb.android.traffic.messages.MessageMutation import com.cottondb.android.traffic.messages.MessageArchiveModel import com.cottondb.android.traffic.messages.ThreadActionsModel import com.cottondb.android.traffic.messages.ThreadActionsState import com.cottondb.android.traffic.messages.MessageStarModel import com.cottondb.android.traffic.messages.MessageStarState import com.cottondb.android.traffic.messages.MarkReadState import com.cottondb.android.traffic.messages.MessageThreadModel import com.cottondb.android.traffic.messages.MessageSearchModel import com.cottondb.android.traffic.messages.MessageSearchRead import com.cottondb.android.traffic.messages.MessageThreadRow import com.cottondb.android.traffic.messages.MessagesRepository import com.cottondb.android.traffic.messages.MessagesState import com.cottondb.android.traffic.messages.StarredMessage import com.cottondb.android.traffic.messages.StarredRead import com.cottondb.android.traffic.messages.ThreadMessage import com.cottondb.android.traffic.messages.ThreadRead import com.cottondb.android.ui.media.CottonAvatar import com.cottondb.android.ui.media.MediaImage 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`, 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. */ @Composable fun 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) } } } } @Composable private 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) } @Composable private fun MessageSearchResults( state: MessagesState, 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() } } } @Composable private 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) } @Composable private fun ThreadsList( threads: List, 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 { 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, ) } } } @Composable private 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 }, ) } } } } } @Composable private 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) }) } @Composable private 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) } @Composable private 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))) } } @Composable private 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) } @Composable private 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) } @Composable private 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. */ @Composable fun 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(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) } } } } @Composable private 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) } } } @Composable private 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) } } @Composable private 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, ) } } } } @Composable private 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) } } @Composable private 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. */ @Composable fun 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) } } } @Composable private 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) } } } } @Composable private 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() } } } @Composable private 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) } } } @Composable private 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 MessagesState.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() } ?: ""