537 lines · 25.0 KB · KotlinRaw
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)package com.cottondb.android.ui.traffic.emailimport com.cottondb.android.traffic.email.EmailMarkReadStateimport 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.Rowimport androidx.compose.foundation.layout.FlowRowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.DropdownMenuimport androidx.compose.material3.DropdownMenuItemimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.pulltorefresh.PullToRefreshBoximport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport 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.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.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.traffic.email.EmailMailboxFilterimport com.cottondb.android.traffic.email.EmailMailboxModelimport com.cottondb.android.traffic.email.EmailMailboxStateimport com.cottondb.android.traffic.email.EmailMessageimport com.cottondb.android.traffic.email.EmailMutationimport com.cottondb.android.traffic.email.EmailPersonimport com.cottondb.android.traffic.email.EmailSenderimport com.cottondb.android.traffic.email.EmailThreadimport com.cottondb.android.traffic.email.EmailDetailModelimport com.cottondb.android.traffic.email.EmailRouteMutationStateimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchprivate val EmailMailboxFilter.label: String get() = when (this) { EmailMailboxFilter.Inbox -> "Inbox" EmailMailboxFilter.Starred -> "Starred" EmailMailboxFilter.Archived -> "Archived" EmailMailboxFilter.Senders -> "By sender"}@Composablefun 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<String?>(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") } }, ) }}@Composablefun 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<String?>(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") } }, ) }}@Composableprivate 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)}@Composableprivate 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) } }}@Composableprivate 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, )}@Composableprivate fun EmailThreadList( threads: List<EmailThread>, 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) } }}@Composableprivate 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) } }}@Composableprivate fun EmailSenderList( senders: List<EmailSender>, 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) } } } }}@Composableprivate fun EmailLetter(message: EmailMessage, threadSubject: String?, ownAddresses: Set<String>) { 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<EmailThread>, filter: EmailMailboxFilter, query: String): List<EmailThread> = 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<EmailThread>, 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.addressprivate 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<EmailPerson>, own: Set<String>): 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