@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) package com.cottondb.android.ui.traffic.email import com.cottondb.android.traffic.email.EmailMarkReadState 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.Row import androidx.compose.foundation.layout.FlowRow 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.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.pulltorefresh.PullToRefreshBox import androidx.compose.material3.Text import androidx.compose.material3.TextButton 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.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.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.traffic.email.EmailMailboxFilter import com.cottondb.android.traffic.email.EmailMailboxModel import com.cottondb.android.traffic.email.EmailMailboxState import com.cottondb.android.traffic.email.EmailMessage import com.cottondb.android.traffic.email.EmailMutation import com.cottondb.android.traffic.email.EmailPerson import com.cottondb.android.traffic.email.EmailSender import com.cottondb.android.traffic.email.EmailThread import com.cottondb.android.traffic.email.EmailDetailModel import com.cottondb.android.traffic.email.EmailRouteMutationState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch private val EmailMailboxFilter.label: String get() = when (this) { EmailMailboxFilter.Inbox -> "Inbox" EmailMailboxFilter.Starred -> "Starred" EmailMailboxFilter.Archived -> "Archived" EmailMailboxFilter.Senders -> "By sender" } @Composable fun EmailArchiveScreen( model: EmailMailboxModel, onOpenThread: (String) -> Unit, writerScope: CoroutineScope, onBack: () -> Unit, eventRevision: Long, ) { val scope = rememberCoroutineScope() val selection by model.selection.collectAsState() val mailbox by model.state.collectAsState() val mutation by model.mutation.collectAsState() var menuExpanded by remember { mutableStateOf(false) } var blockAddress by remember { mutableStateOf(null) } val read = mailbox.readOrNull() val showingSenders = selection.filter == EmailMailboxFilter.Senders && selection.sender == null val refresh: () -> Unit = { scope.launch { model.refresh() } } LaunchedEffect(model, eventRevision) { model.refresh() } Column( Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding(), ) { EmailTopBar("Email", onBack) Row( Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin), verticalAlignment = Alignment.CenterVertically, ) { Box { Text( selection.filter.label, Modifier.clickable(role = Role.Button) { menuExpanded = true } .semantics { contentDescription = "Choose email folder" } .padding(vertical = 10.dp), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.ink, ) DropdownMenu(expanded = menuExpanded, onDismissRequest = { menuExpanded = false }) { EmailMailboxFilter.entries.forEach { choice -> DropdownMenuItem( text = { Text(choice.label) }, onClick = { menuExpanded = false scope.launch { model.choose(choice) } }, ) } } } unreadLine(read?.threads.orEmpty(), selection.filter)?.let { unread -> Text(" · $unread", style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) } } selection.sender?.let { sender -> Text( "From ${senderTitle(sender)} ×", Modifier.clickable(role = Role.Button) { scope.launch { model.clearSender() } } .padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp) .semantics { contentDescription = "Clear sender filter" }, style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary, ) } OutlinedTextField( value = selection.query, onValueChange = model::setQuery, modifier = Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 4.dp), singleLine = true, label = { Text(if (showingSenders) "Search senders" else "Search email") }, ) PullToRefreshBox( isRefreshing = (mailbox as? EmailMailboxState.Data)?.refreshing == true, onRefresh = refresh, modifier = Modifier.weight(1f), ) { when { read != null && showingSenders -> EmailSenderList( senders = read.senders.filter { senderMatches(it, selection.query) }, onOpen = { sender -> scope.launch { model.selectSender(sender) } }, onToggleBlock = { sender -> writerScope.launch { model.mutate { toggleBlock(sender.address, sender.blocked) } } }, onAskBlock = { sender -> blockAddress = sender.address }, ) read != null -> EmailThreadList( threads = visibleThreads(read.threads, selection.filter, selection.query), onOpen = onOpenThread, onToggleRead = { thread -> writerScope.launch { model.mutate { toggleRead(thread) } } }, onToggleStar = { thread -> writerScope.launch { model.mutate { toggleStar(thread) } } }, onToggleInbox = { thread -> writerScope.launch { model.mutate { toggleInbox(thread) } } }, onToggleBin = { thread -> writerScope.launch { model.mutate { toggleBin(thread) } } }, ) mailbox is EmailMailboxState.Loading -> EmailSkeleton() mailbox is EmailMailboxState.Error -> EmailReadFailure( message = (mailbox as EmailMailboxState.Error).message, onRetry = refresh, ) } } } blockAddress?.let { address -> AlertDialog( onDismissRequest = { blockAddress = null }, title = { Text("Block this sender?") }, text = { Text("Mail already here from $address goes to the bin. Nothing is erased until you empty the bin.") }, confirmButton = { TextButton(onClick = { blockAddress = null writerScope.launch { model.mutate { toggleBlock(address, blocked = false) } } }) { Text("Block") } }, dismissButton = { TextButton(onClick = { blockAddress = null }) { Text("Cancel") } }, ) } } @Composable fun EmailThreadScreen( model: EmailDetailModel, writerScope: CoroutineScope, onBack: () -> Unit, eventRevision: Long, ) { val scope = rememberCoroutineScope() val readerState by model.state.collectAsState() val mutation by model.mutation.collectAsState() val markRead by model.markRead.markRead.collectAsState() val state = model.current() val error = model.failure() val thread = state?.thread val ownAddresses = state?.ownAddresses.orEmpty().map(String::lowercase).toSet() val refresh: () -> Unit = { scope.launch { model.refresh() } } var blockAddress by remember { mutableStateOf(null) } LaunchedEffect(model, eventRevision) { model.refresh() } // The retained model preserves write admission and errors through a remount. LaunchedEffect(thread?.id, thread?.unread, model) { thread?.let { model.markRead.markUnreadThreadIfNeeded(it, writerScope) } } Column(Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding()) { EmailTopBar(threadTitle(thread), onBack) EmailMarkReadNotice(markRead) { model.markRead.retryMarkRead(writerScope) } if (state != null && error != null) EmailCachedFailureNotice(error, refresh) if (mutation is EmailRouteMutationState.Failure) EmailCachedFailureNotice((mutation as EmailRouteMutationState.Failure).message, refresh, "Refresh") if (thread != null) { FlowRow(Modifier.padding(horizontal = CottonMetrics.contentMargin)) { if (thread.trashedAt == null) { ThreadAction(thread.starred.then("Unstar") ?: "Star") { writerScope.launch { model.mutate { toggleStar(thread) } } } ThreadAction(thread.inInbox.then("Archive") ?: "Move to inbox") { writerScope.launch { model.mutate { toggleInbox(thread) } } } } ThreadAction((thread.trashedAt != null).then("Restore") ?: "Bin") { writerScope.launch { model.mutate { toggleBin(thread) } } } state.emails.firstOrNull()?.from?.email?.takeIf(String::isNotBlank)?.let { address -> ThreadAction("Block sender") { blockAddress = address } } } } when { state != null && state.emails.isEmpty() -> EmailEmpty("Nothing in this thread yet.") state != null -> LazyColumn( Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(18.dp), ) { items(state.emails, key = { it.id }) { message -> EmailLetter(message, state.thread.subject, ownAddresses) } } readerState is com.cottondb.android.traffic.email.EmailReaderState.Loading || readerState is com.cottondb.android.traffic.email.EmailReaderState.Data -> EmailSkeleton() else -> EmailReadFailure(error ?: "This thread could not be read.", refresh) } } blockAddress?.let { address -> AlertDialog( onDismissRequest = { blockAddress = null }, title = { Text("Block this sender?") }, text = { Text("Mail already here from $address goes to the bin. Nothing is erased until you empty the bin.") }, confirmButton = { TextButton(onClick = { blockAddress = null writerScope.launch { model.mutate { toggleBlock(address, blocked = false) } } }) { Text("Block") } }, dismissButton = { TextButton(onClick = { blockAddress = null }) { Text("Cancel") } }, ) } } @Composable private fun EmailCachedFailureNotice(message: String, retry: () -> Unit, actionLabel: String = "Try again") = 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) ThreadAction(actionLabel, retry) } @Composable private fun EmailMarkReadNotice( state: EmailMarkReadState, retry: () -> Unit, ) { when (state) { EmailMarkReadState.Idle, EmailMarkReadState.Marked -> Unit EmailMarkReadState.Saving -> Text( "Marking this thread read…", Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, ) is EmailMarkReadState.Error -> Row( Modifier.fillMaxWidth().background(CottonPalette.groundElevated) .padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( "This thread was opened, but could not be marked read: ${state.message}", Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.statusError, ) ThreadAction("Try again", retry) } } } @Composable private fun EmailTopBar(title: String, onBack: () -> Unit) = Row( Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( "Back", Modifier.clickable(role = Role.Button, onClick = onBack).padding(8.dp), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary, ) Text( title, Modifier.weight(1f).padding(start = 8.dp), style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } @Composable private fun EmailThreadList( threads: List, onOpen: (String) -> Unit, onToggleRead: (EmailThread) -> Unit, onToggleStar: (EmailThread) -> Unit, onToggleInbox: (EmailThread) -> Unit, onToggleBin: (EmailThread) -> Unit, ) { if (threads.isEmpty()) { EmailEmpty("No email here.") return } LazyColumn( Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(9.dp), ) { items(threads, key = { it.id }) { thread -> EmailThreadStrip(thread, onOpen, onToggleRead, onToggleStar, onToggleInbox, onToggleBin) } } } @Composable private fun EmailThreadStrip( thread: EmailThread, onOpen: (String) -> Unit, onToggleRead: (EmailThread) -> Unit, onToggleStar: (EmailThread) -> Unit, onToggleInbox: (EmailThread) -> Unit, onToggleBin: (EmailThread) -> Unit, ) = Column( Modifier.padding(horizontal = CottonMetrics.contentMargin) .shadow(2.dp, RoundedCornerShape(CottonMetrics.cardRadius)) .background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)), ) { Row( Modifier.fillMaxWidth().clickable(role = Role.Button) { onOpen(thread.id) } .semantics { contentDescription = "Open ${threadTitle(thread)}" }.padding(12.dp), verticalAlignment = Alignment.Top, ) { Text(if (thread.unread) "•" else " ", color = CottonPalette.statusError) Column(Modifier.weight(1f).padding(start = 8.dp)) { Text(senderFor(thread), style = CottonTextStyles.rowTitleCompact.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) Text(threadTitle(thread), style = CottonTextStyles.preview, color = CottonPalette.ink, maxLines = 1, overflow = TextOverflow.Ellipsis) thread.preview?.takeIf(String::isNotBlank)?.let { Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis) } } if (thread.starred) Text("★", color = CottonPalette.statusError) } HorizontalDivider(color = CottonPalette.hairline) FlowRow(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) { ThreadAction(if (thread.unread) "Mark read" else "Mark unread") { onToggleRead(thread) } ThreadAction(if (thread.starred) "Unstar" else "Star") { onToggleStar(thread) } ThreadAction(if (thread.inInbox) "Archive" else "Inbox") { onToggleInbox(thread) } ThreadAction(if (thread.trashedAt == null) "Bin" else "Restore") { onToggleBin(thread) } } } @Composable private fun EmailSenderList( senders: List, onOpen: (EmailSender) -> Unit, onToggleBlock: (EmailSender) -> Unit, onAskBlock: (EmailSender) -> Unit, ) { if (senders.isEmpty()) { EmailEmpty("Nobody by that name.") return } LazyColumn(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(9.dp)) { items(senders, key = { it.address }) { sender -> Column( Modifier.padding(horizontal = CottonMetrics.contentMargin) .background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)), ) { Row( Modifier.fillMaxWidth().clickable(role = Role.Button) { onOpen(sender) }.padding(12.dp), verticalAlignment = Alignment.Top, ) { Column(Modifier.weight(1f)) { Text(senderTitle(sender), style = CottonTextStyles.rowTitleCompact.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) if (!sender.name.equals(sender.address, ignoreCase = true)) { Text(sender.address, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } Text(senderCounts(sender), style = CottonTextStyles.caption, color = if (sender.blocked) CottonPalette.statusError else CottonPalette.inkSecondary) } Text(sender.lastAt.take(10), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } HorizontalDivider(color = CottonPalette.hairline) ThreadAction(if (sender.blocked) "Unblock" else "Block") { if (sender.blocked) onToggleBlock(sender) else onAskBlock(sender) } } } } } @Composable private fun EmailLetter(message: EmailMessage, threadSubject: String?, ownAddresses: Set) { val mine = message.from.email.lowercase() in ownAddresses val paper = if (mine) CottonPalette.selection else CottonPalette.groundElevated Column( Modifier.padding(horizontal = CottonMetrics.contentMargin) .shadow(2.dp, RoundedCornerShape(CottonMetrics.cardRadius)) .background(paper, RoundedCornerShape(CottonMetrics.cardRadius)).padding(20.dp), ) { Row(Modifier.fillMaxWidth()) { Column(Modifier.weight(1f)) { Text(personName(message.from), style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) if (!message.from.name.equals(message.from.email, ignoreCase = true)) { Text(message.from.email, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } Text(message.sentAt.take(10), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } recipientLine("to", message.to, ownAddresses)?.let { RecipientLine(it) } recipientLine("cc", message.cc, ownAddresses)?.let { RecipientLine(it) } message.subject?.takeIf { it.isNotBlank() && it != threadSubject }?.let { Text(it, Modifier.padding(top = 18.dp), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) } message.body?.takeIf(String::isNotEmpty)?.let { Text(it, Modifier.padding(top = 16.dp), style = CottonTextStyles.body, color = CottonPalette.ink) } message.attachments.forEach { attachment -> Text( "${attachment.name} · ${attachmentKind(attachment.name, attachment.mime)}", Modifier.padding(top = 12.dp).background(CottonPalette.ground, RoundedCornerShape(5.dp)).padding(8.dp), style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.ink, ) } } } @Composable private fun RecipientLine(text: String) = Text( text, Modifier.padding(top = 4.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, ) @Composable private fun ThreadAction(label: String, onClick: () -> Unit) = Text( label, Modifier.clickable(role = Role.Button, onClick = onClick).padding(8.dp), style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.accent, ) @Composable private fun EmailSkeleton() = Box( Modifier.fillMaxSize().padding(CottonMetrics.contentMargin) .background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)), ) @Composable private fun EmailEmpty(text: String) = Text( text, Modifier.padding(CottonMetrics.contentMargin), style = CottonTextStyles.body, color = CottonPalette.inkSecondary, ) @Composable private fun EmailReadFailure(message: String, onRetry: () -> Unit) = Column( Modifier.padding(CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text(message, style = CottonTextStyles.body, color = CottonPalette.statusError) ThreadAction("Try again", onRetry) } private fun EmailMailboxState.readOrNull() = when (this) { is EmailMailboxState.Data -> read is EmailMailboxState.Error -> last EmailMailboxState.Loading -> null } private fun visibleThreads(threads: List, filter: EmailMailboxFilter, query: String): List = threads.filter { filter != EmailMailboxFilter.Starred || it.starred }.filter { threadMatches(it, query) } private fun threadMatches(thread: EmailThread, query: String): Boolean { val needle = query.trim().lowercase() if (needle.length < 2) return true return listOf(threadTitle(thread), senderFor(thread), thread.preview.orEmpty(), thread.participants.joinToString { it.email }) .any { it.lowercase().contains(needle) } } private fun senderMatches(sender: EmailSender, query: String): Boolean { val needle = query.trim().lowercase() return needle.length < 2 || sender.name.lowercase().contains(needle) || sender.address.lowercase().contains(needle) } private fun unreadLine(threads: List, filter: EmailMailboxFilter): String? { if (filter == EmailMailboxFilter.Senders) return null return threads.count { it.unread }.takeIf { it > 0 }?.let { "$it unread" } } private fun senderFor(thread: EmailThread): String = personName(thread.participants.firstOrNull { it.role == "from" } ?: thread.participants.firstOrNull()) private fun threadTitle(thread: EmailThread?): String = thread?.subject?.takeIf { it.isNotBlank() } ?: "Email" private fun personName(person: EmailPerson?): String = person?.name?.takeIf { it.isNotBlank() } ?: person?.email ?: "Unknown sender" private fun senderTitle(sender: EmailSender): String = sender.name.takeIf { it.isNotBlank() } ?: sender.address private fun senderCounts(sender: EmailSender): String = buildList { if (sender.blocked) add("Blocked") add(if (sender.count == 1) "1 email" else "${sender.count} emails") if (sender.unread > 0) add("${sender.unread} unread") }.joinToString(" · ") private fun recipientLine(label: String, people: List, own: Set): String? = people .filterNot { it.email.lowercase() in own }.map(::personName).filter(String::isNotBlank) .takeIf { it.isNotEmpty() }?.joinToString(", ")?.let { "$label $it" } private fun attachmentKind(name: String, mime: String?): String = when { mime == "application/pdf" || name.endsWith(".pdf", true) -> "PDF" mime?.startsWith("image/") == true -> "Image" mime?.startsWith("audio/") == true -> "Audio" mime?.startsWith("video/") == true -> "Video" name.substringAfterLast('.', "").takeIf(String::isNotEmpty) != null -> name.substringAfterLast('.').uppercase() else -> "File" } private fun Boolean.then(value: String): String? = if (this) value else null