Modern Apps git

← Modern-Apps.git

securemail: Out tab (Drafts / Outbox / Sent) and drafts

Commit
b96e4dff2ad353073c052972851a4fe61df98433
Author
Vayun Mathur <[email protected]>
When
2026-11-02 05:22 UTC (1 month ago)
Parents
0f85696
Sent and Outbox were two separate tabs and there was no way to keep an
unfinished message: backing out of the composer threw it away. They
are merged into one "Out" tab and drafts are added.

Navigation
- Bottom bar is now Inbox / Spam / Out / Trash / Settings (five, the
  Material maximum, down from six). Out carries the outbox badge.
- Route.Outbox -> Route.Out. Sent mail no longer goes through the
  folder list; MailFolder.tab() maps SENT and DRAFTS to OUT.

Out page (ui/OutScreen.kt, replaces OutboxScreen)
- No app bar; three vertically stacked sections, each with a title and
  a thick divider between them: Drafts, Outbox, Sent. Each shows a short
  line when empty.
- Drafts: tap to reopen, swipe left to delete (Undo restores it).
- Outbox: the queued sends with last error and attempt count, plus
  "Retry all", as before.
- Sent: the shared MessageRow (swipe right read/unread, swipe left to
  Trash with Undo back to Sent), tap opens the reader.

Drafts
- Stored as MailFolder.DRAFTS rows in the existing message table, so no
  schema migration: subject/body use the decrypted columns like Sent
  copies, and To/Cc/Bcc plus reply threading ride as JSON in toJson.
  Drafts never leave the device. platform/DraftsController owns save /
  delete / decode and the Drafts + Sent flows.
- Composer: system Back saves a draft ("Draft saved") or, if nothing was
  written, drops it; the old Cancel button is now Discard, which drops
  the composition and deletes a reopened draft. A successful send
  deletes the draft. Each composition gets a stable draft id, so
  reopening and saving again updates one draft instead of piling up
  copies.
- Route.Composer gains draftId, cc and bcc; seedDraft restores all
  three recipient fields when a draft is reopened.

Navigation's composer and Out entries moved into EntryProviderScope
helpers (pattern from calculator), shrinking Navigation from 150 to 109
lines.

Store screenshot 4 is now the Out tab (was Settings); 2 shows the new
five-item bar.

Verified: :securemail:compileDevKotlin, unit tests, :securemail:lint
clean, detekt unchanged at 40 (nothing in new files; Navigation's two
existing findings both shrank), previews rendered and the Out page
checked visually. Draft save/reopen/discard flows not yet exercised on
a device.

Diff

metadata_data/photos/securemail/phone/2.png
diff --git a/metadata_data/photos/securemail/phone/2.png b/metadata_data/photos/securemail/phone/2.pngindex c661f6eff1..92f7db099a 100644Binary files a/metadata_data/photos/securemail/phone/2.png and b/metadata_data/photos/securemail/phone/2.png differ
metadata_data/photos/securemail/phone/4.png
diff --git a/metadata_data/photos/securemail/phone/4.png b/metadata_data/photos/securemail/phone/4.pngindex 794a36f3d3..6b9886e96f 100644Binary files a/metadata_data/photos/securemail/phone/4.png and b/metadata_data/photos/securemail/phone/4.png differ
securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.ktindex 29a6c2b314..6393bb0094 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt@@ -7,12 +7,15 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.fragment.app.FragmentActivity+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.library.util.EntryProviderScope import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.SiblingPage import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.securemail.data.MailFolder import com.vayunmathur.securemail.domain.mail.AddressValidator+import com.vayunmathur.securemail.platform.Draft import com.vayunmathur.securemail.platform.MailViewModel import com.vayunmathur.securemail.ui.ComposeScreen import com.vayunmathur.securemail.ui.FolderActions@@ -21,7 +24,8 @@ import com.vayunmathur.securemail.ui.LockScreen import com.vayunmathur.securemail.ui.MailBottomBar import com.vayunmathur.securemail.ui.MailTab import com.vayunmathur.securemail.ui.OnboardingScreen-import com.vayunmathur.securemail.ui.OutboxScreen+import com.vayunmathur.securemail.ui.OutActions+import com.vayunmathur.securemail.ui.OutScreen import com.vayunmathur.securemail.ui.ReaderScreen import com.vayunmathur.securemail.ui.SettingsScreen import com.vayunmathur.securemail.ui.tab@@ -33,7 +37,6 @@ fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) {     val folderMessages by viewModel.folderMessages.collectAsState(emptyList())     val allMessages by viewModel.messages.collectAsState(emptyList())     val outbox by viewModel.outboxCount.collectAsState(0)-    val outboxMessages by viewModel.outboxMessages.collectAsState(emptyList())     // The stack follows the account flag, not navigation events: once an address     // is claimed there is no going back to onboarding, and a locked key gates     // everything. reset() rather than add() for the same reason as backup/.@@ -110,41 +113,7 @@ fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) {                 messages = folderMessages,             )         }-        entry<Route.Composer> { route ->-            LaunchedEffect(route.to, route.subject, route.body) {-                viewModel.seedDraft(-                    to = AddressValidator.parseRecipients(route.to),-                )-            }-            ComposeScreen(-                state = state,-                draftTo = viewModel.draftTo,-                draftCc = viewModel.draftCc,-                draftBcc = viewModel.draftBcc,-                initialSubject = route.subject,-                initialBody = route.body,-                onAddRecipient = viewModel::addDraftRecipient,-                onRemoveRecipient = viewModel::removeDraftRecipient,-                onSend = { to, cc, bcc, subject, body, inReplyTo ->-                    viewModel.send(-                        to = to,-                        cc = cc,-                        bcc = bcc,-                        subject = subject,-                        body = body,-                        inReplyTo = inReplyTo,-                        onDone = { sent ->-                            if (sent) {-                                viewModel.clearDraft()-                                backStack.pop()-                            }-                        },-                    )-                },-                onBack = { backStack.pop() },-                onConsumeMessage = viewModel::dismissMessages,-            )-        }+        composerEntry(viewModel, backStack)         entry<Route.Reader> { route ->             val msg = remember(route.messageId, allMessages, folderMessages) {                 folderMessages.firstOrNull { it.id == route.messageId }@@ -169,13 +138,7 @@ fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) {                 message = msg,             )         }-        entry<Route.Outbox>(metadata = SiblingPage()) {-            OutboxScreen(-                onRetry = viewModel::retryOutbox,-                onCompose = { backStack.add(Route.Composer()) },-                pending = outboxMessages,-            )-        }+        outEntry(viewModel, backStack)         entry<Route.Settings>(metadata = SiblingPage()) {             SettingsScreen(                 state = state,@@ -187,22 +150,138 @@ fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) {     } } +/**+ * Composer. Leaving with Back saves a draft (or updates the reopened one);+ * Discard drops it; a successful send deletes it.+ */+private fun EntryProviderScope<Route>.composerEntry(viewModel: MailViewModel, backStack: NavBackStack<Route>) {+    entry<Route.Composer> { route ->+        // Stable for this composition so repeated saves update one draft row.+        val draftId = remember(route) { route.draftId ?: Draft().id }+        LaunchedEffect(route) {+            viewModel.seedDraft(+                to = AddressValidator.parseRecipients(route.to),+                cc = AddressValidator.parseRecipients(route.cc),+                bcc = AddressValidator.parseRecipients(route.bcc),+            )+        }+        fun close() {+            viewModel.clearDraft()+            backStack.pop()+        }+        ComposeScreen(+            state = viewModel.state,+            draftTo = viewModel.draftTo,+            draftCc = viewModel.draftCc,+            draftBcc = viewModel.draftBcc,+            initialSubject = route.subject,+            initialBody = route.body,+            onAddRecipient = viewModel::addDraftRecipient,+            onRemoveRecipient = viewModel::removeDraftRecipient,+            onSend = { to, cc, bcc, subject, body, inReplyTo ->+                viewModel.send(+                    to = to,+                    cc = cc,+                    bcc = bcc,+                    subject = subject,+                    body = body,+                    inReplyTo = inReplyTo,+                    onDone = { sent ->+                        if (sent) {+                            viewModel.drafts.delete(draftId)+                            close()+                        }+                    },+                )+            },+            onLeave = { subject, body ->+                saveOrDropDraft(viewModel, draftId, subject, body, route.inReplyTo)+                close()+            },+            onDiscard = {+                viewModel.drafts.delete(draftId)+                close()+            },+            onConsumeMessage = viewModel::dismissMessages,+        )+    }+}++/** Saves the composition as a draft, or removes the draft when nothing was written. */+private fun saveOrDropDraft(+    viewModel: MailViewModel,+    draftId: String,+    subject: String,+    body: String,+    inReplyTo: String?,+) {+    val draft = Draft(+        id = draftId,+        to = viewModel.draftTo,+        cc = viewModel.draftCc,+        bcc = viewModel.draftBcc,+        subject = subject,+        body = body,+        inReplyTo = inReplyTo,+    )+    if (draft.isEmpty) {+        viewModel.drafts.delete(draftId)+    } else {+        viewModel.drafts.save(draft)+        AppMessages.show("Draft saved")+    }+}++/** The Out tab: Drafts, Outbox and Sent on one page. */+private fun EntryProviderScope<Route>.outEntry(viewModel: MailViewModel, backStack: NavBackStack<Route>) {+    entry<Route.Out>(metadata = SiblingPage()) {+        val drafts by viewModel.drafts.drafts.collectAsState(emptyList())+        val sent by viewModel.drafts.sent.collectAsState(emptyList())+        val outbox by viewModel.outboxMessages.collectAsState(emptyList())+        val actions = remember(viewModel) {+            OutActions(+                onCompose = { backStack.add(Route.Composer()) },+                onOpenDraft = { d ->+                    backStack.add(+                        Route.Composer(+                            to = d.to.joinToString(", "),+                            cc = d.cc.joinToString(", "),+                            bcc = d.bcc.joinToString(", "),+                            subject = d.subject,+                            body = d.body,+                            inReplyTo = d.inReplyTo,+                            draftId = d.id,+                        ),+                    )+                },+                onDeleteDraft = viewModel.drafts::delete,+                onRestoreDraft = viewModel.drafts::save,+                onRetryOutbox = viewModel::retryOutbox,+                onOpenSent = { backStack.add(Route.Reader(it)) },+                onTrashSent = viewModel::moveToTrash,+                onUntrashSent = { viewModel.moveTo(it, MailFolder.SENT) },+                onSetRead = viewModel::setRead,+            )+        }+        OutScreen(drafts = drafts, outbox = outbox, sent = sent, actions = actions)+    }+}+ /** The bottom-bar tab for the top route, or null when the bar should hide (reader, composer, gates). */ private fun currentTab(top: Route, folder: MailFolder): MailTab? = when (top) {     Route.Inbox -> folder.tab()-    Route.Outbox -> MailTab.OUTBOX+    Route.Out -> MailTab.OUT     Route.Settings -> MailTab.SETTINGS     else -> null }  private fun selectTab(tab: MailTab, backStack: NavBackStack<Route>, viewModel: MailViewModel) {     val target = when (tab) {-        MailTab.OUTBOX -> Route.Outbox+        MailTab.OUT -> Route.Out         MailTab.SETTINGS -> Route.Settings-        else -> {+        MailTab.INBOX, MailTab.SPAM, MailTab.TRASH -> {             viewModel.selectFolder(                 when (tab) {-                    MailTab.SENT -> MailFolder.SENT                     MailTab.SPAM -> MailFolder.SPAM                     MailTab.TRASH -> MailFolder.TRASH                     else -> MailFolder.INBOX
securemail/src/main/java/com/vayunmathur/securemail/Route.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/Route.kt b/securemail/src/main/java/com/vayunmathur/securemail/Route.ktindex 9767280064..5dfe2ef0d6 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/Route.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/Route.kt@@ -25,13 +25,18 @@ sealed interface Route : NavKey {         val subject: String = "",         val body: String = "",         val inReplyTo: String? = null,+        /** Set when reopening a saved draft; saving again updates that draft. */+        val draftId: String? = null,+        val cc: String = "",+        val bcc: String = "",     ) : Route      @Serializable     data class Reader(val messageId: String) : Route +    /** Everything outgoing: Drafts, Outbox (queued sends) and Sent. */     @Serializable-    data object Outbox : Route+    data object Out : Route      @Serializable     data object Settings : Route
securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.ktindex 71d3236135..6651110bf1 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt@@ -17,13 +17,15 @@ import kotlinx.coroutines.flow.Flow /**  * Mail folders. Stored as the enum name in [StoredMessage.folder]; the Outbox  * stays a separate queue table, not a folder value. Spam is assigned by the- * server verdict at ingest ([InboundStore]); Trash is local-only.+ * server verdict at ingest ([InboundStore]); Trash is local-only. Drafts are+ * local, unsent compositions (see [com.vayunmathur.securemail.platform.DraftsController]).  */ enum class MailFolder {     INBOX,     SENT,     SPAM,     TRASH,+    DRAFTS, }  /**
securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.ktnew file mode 100644index 0000000000..999a96c05b--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt@@ -0,0 +1,89 @@+package com.vayunmathur.securemail.platform++import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailRepository+import com.vayunmathur.securemail.data.StoredMessage+import java.util.UUID+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.launch+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/** An unsent composition. [id] is stable across saves so re-saving updates in place. */+data class Draft(+    val id: String = "draft-${UUID.randomUUID()}",+    val to: List<String> = emptyList(),+    val cc: List<String> = emptyList(),+    val bcc: List<String> = emptyList(),+    val subject: String = "",+    val body: String = "",+    val inReplyTo: String? = null,+) {+    val isEmpty: Boolean+        get() = to.isEmpty() && cc.isEmpty() && bcc.isEmpty() && subject.isBlank() && body.isBlank()+}++/**+ * Drafts live in the message table as [MailFolder.DRAFTS] rows (local only,+ * never sent to the relay). Recipients and reply threading ride in the row's+ * `toJson` as JSON; subject/body use the decrypted columns like Sent copies.+ */+class DraftsController(+    private val repo: MailRepository,+    private val scope: CoroutineScope,+    private val ownAddress: () -> String,+) {+    val drafts: Flow<List<StoredMessage>> = repo.messageDao().observeFolder(MailFolder.DRAFTS)+    val sent: Flow<List<StoredMessage>> = repo.messageDao().observeFolder(MailFolder.SENT)++    fun save(draft: Draft) {+        scope.launch(Dispatchers.IO) {+            repo.messageDao().upsert(+                StoredMessage(+                    id = draft.id,+                    from = ownAddress(),+                    toJson = json.encodeToString(Envelope(draft.to, draft.cc, draft.bcc, draft.inReplyTo)),+                    dateMillis = System.currentTimeMillis(),+                    messageId = draft.id,+                    blobBase64 = "",+                    decryptedBody = draft.body,+                    decryptedSubject = draft.subject,+                    isRead = true,+                    folder = MailFolder.DRAFTS,+                ),+            )+        }+    }++    fun delete(id: String) {+        scope.launch(Dispatchers.IO) { repo.messageDao().deleteAll(listOf(id)) }+    }++    @Serializable+    private data class Envelope(+        val to: List<String> = emptyList(),+        val cc: List<String> = emptyList(),+        val bcc: List<String> = emptyList(),+        val inReplyTo: String? = null,+    )++    companion object {+        private val json = Json { ignoreUnknownKeys = true }++        /** Reads a [MailFolder.DRAFTS] row back into a [Draft]. */+        fun decode(row: StoredMessage): Draft {+            val env = runCatching { json.decodeFromString<Envelope>(row.toJson) }.getOrDefault(Envelope())+            return Draft(+                id = row.id,+                to = env.to,+                cc = env.cc,+                bcc = env.bcc,+                subject = row.decryptedSubject.orEmpty(),+                body = row.decryptedBody.orEmpty(),+                inReplyTo = env.inReplyTo,+            )+        }+    }+}
securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.ktindex 594e16acdb..e1431e31b3 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt@@ -76,6 +76,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) {     val messages = repo.messageDao().observeAll()     val outboxCount = repo.outboxDao().observeCount()     val outboxMessages = repo.outboxDao().observeAll()+    val drafts = DraftsController(repo, viewModelScope) { state.address }      /**      * Selected folder driving the message list (drawer selection). Outbox is@@ -110,11 +111,11 @@ class MailViewModel(app: Application) : AndroidViewModel(app) {     var draftBcc by mutableStateOf(listOf<String>())         private set -    /** Seeds the draft (reply/forward prefill, share-intent entry). */-    fun seedDraft(to: List<String> = emptyList()) {+    /** Seeds the draft recipients (reply prefill, share-intent entry, reopened draft). */+    fun seedDraft(to: List<String> = emptyList(), cc: List<String> = emptyList(), bcc: List<String> = emptyList()) {         draftTo = to.filter { it.isNotBlank() }.distinct()-        draftCc = emptyList()-        draftBcc = emptyList()+        draftCc = cc.filter { it.isNotBlank() }.distinct()+        draftBcc = bcc.filter { it.isNotBlank() }.distinct()     }      /** Clears the draft after a successful send. */
securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.ktindex 1470f6e403..ca933202b9 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/ComposeScreen.kt@@ -3,6 +3,7 @@ package com.vayunmathur.securemail.ui import android.app.Activity import android.content.Intent import android.provider.ContactsContract+import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement@@ -55,7 +56,8 @@ fun ComposeScreen(     onAddRecipient: (Int, String) -> Boolean,     onRemoveRecipient: (Int, String) -> Unit,     onSend: (List<String>, List<String>, List<String>, String, String, String?) -> Unit,-    onBack: () -> Unit,+    onLeave: (subject: String, body: String) -> Unit,+    onDiscard: () -> Unit,     onConsumeMessage: () -> Unit = {}, ) {     val context = LocalContext.current@@ -89,6 +91,8 @@ fun ComposeScreen(         }     }     val allRecipients = draftTo + draftCc + draftBcc+    // Back saves the composition as a draft (handled by the caller); Discard drops it.+    BackHandler { onLeave(subject, body) }     // No top app bar by design; systemBarsPadding keeps the form clear of     // the status bar / camera cutout, imePadding keeps Send above the keyboard.     DesktopMaxWidthContainer(@@ -161,7 +165,7 @@ fun ComposeScreen(                     enabled = !state.busy && allRecipients.isNotEmpty() && body.isNotBlank(),                     modifier = Modifier.weight(1f),                 ) { Text(if (state.busy) "Sending…" else "Send") }-                Button(onClick = onBack, modifier = Modifier.weight(1f)) { Text("Cancel") }+                Button(onClick = onDiscard, modifier = Modifier.weight(1f)) { Text("Discard") }             }         }     }
securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.ktindex 26ef9741e9..6b80117331 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.kt@@ -206,6 +206,7 @@ private fun SelectionBar( private fun emptyText(folder: MailFolder): String = when (folder) {     MailFolder.INBOX -> "No mail yet. Share your address to receive encrypted mail."     MailFolder.SENT -> "Nothing sent yet."+    MailFolder.DRAFTS -> "No drafts."     MailFolder.SPAM -> "No spam. Verification failures land here."     MailFolder.TRASH -> "Trash is empty." }
securemail/src/main/java/com/vayunmathur/securemail/ui/MailBottomBar.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/MailBottomBar.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/MailBottomBar.ktindex 860bdcf0b8..1bdbadd8a4 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/MailBottomBar.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/MailBottomBar.kt@@ -5,7 +5,6 @@ import com.vayunmathur.library.ui.Badge import com.vayunmathur.library.ui.BadgedBox import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconInbox-import com.vayunmathur.library.ui.IconMail import com.vayunmathur.library.ui.IconSend import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.IconWarning@@ -14,33 +13,32 @@ import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.BottomNavBarItem import com.vayunmathur.securemail.data.MailFolder -/** Top-level destinations: the four vault folders, the send queue, and settings. */-enum class MailTab { INBOX, SENT, SPAM, OUTBOX, TRASH, SETTINGS }+/** Top-level destinations. OUT groups Drafts, the Outbox queue and Sent on one page. */+enum class MailTab { INBOX, SPAM, OUT, TRASH, SETTINGS } -/** Bottom navigation across the vault folders, Outbox (badged with its queue) and Settings. */+/** Bottom navigation: Inbox, Spam, Out (badged with queued sends), Trash, Settings. */ @Composable fun MailBottomBar(selected: MailTab, outboxCount: Int, onSelect: (MailTab) -> Unit) {     BottomNavBar {         BottomNavBarItem(selected == MailTab.INBOX, { onSelect(MailTab.INBOX) }, { IconInbox() }, "Inbox")-        BottomNavBarItem(selected == MailTab.SENT, { onSelect(MailTab.SENT) }, { IconSend() }, "Sent")         BottomNavBarItem(selected == MailTab.SPAM, { onSelect(MailTab.SPAM) }, { IconWarning() }, "Spam")         BottomNavBarItem(-            selected = selected == MailTab.OUTBOX,-            onClick = { onSelect(MailTab.OUTBOX) },+            selected = selected == MailTab.OUT,+            onClick = { onSelect(MailTab.OUT) },             icon = {-                BadgedBox(badge = { if (outboxCount > 0) Badge { Text("$outboxCount") } }) { IconMail() }+                BadgedBox(badge = { if (outboxCount > 0) Badge { Text("$outboxCount") } }) { IconSend() }             },-            label = "Outbox",+            label = "Out",         )         BottomNavBarItem(selected == MailTab.TRASH, { onSelect(MailTab.TRASH) }, { IconDelete() }, "Trash")         BottomNavBarItem(selected == MailTab.SETTINGS, { onSelect(MailTab.SETTINGS) }, { IconSettings() }, "Settings")     } } -/** The tab a vault folder belongs to. */+/** The tab a vault folder belongs to (Sent and Drafts live on the Out page). */ fun MailFolder.tab(): MailTab = when (this) {     MailFolder.INBOX -> MailTab.INBOX-    MailFolder.SENT -> MailTab.SENT     MailFolder.SPAM -> MailTab.SPAM     MailFolder.TRASH -> MailTab.TRASH+    MailFolder.SENT, MailFolder.DRAFTS -> MailTab.OUT }
securemail/src/main/java/com/vayunmathur/securemail/ui/OutScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/OutScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/OutScreen.ktnew file mode 100644index 0000000000..9d167c7860--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/OutScreen.kt@@ -0,0 +1,221 @@+package com.vayunmathur.securemail.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.FloatingActionButton+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SwipeActionSide+import com.vayunmathur.library.ui.SwipeActionsBox+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.securemail.data.OutboxMessage+import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.platform.Draft+import com.vayunmathur.securemail.platform.DraftsController++/** Callbacks for the Out page. */+class OutActions(+    val onCompose: () -> Unit,+    val onOpenDraft: (Draft) -> Unit,+    val onDeleteDraft: (String) -> Unit,+    val onRestoreDraft: (Draft) -> Unit,+    val onRetryOutbox: () -> Unit,+    val onOpenSent: (String) -> Unit,+    val onTrashSent: (List<String>) -> Unit,+    val onUntrashSent: (List<String>) -> Unit,+    val onSetRead: (List<String>, Boolean) -> Unit,+)++/**+ * Everything outgoing on one page, no app bar: Drafts, then the Outbox queue,+ * then Sent, each under a title and separated by dividers.+ */+@Composable+fun OutScreen(+    drafts: List<StoredMessage>,+    outbox: List<OutboxMessage>,+    sent: List<StoredMessage>,+    actions: OutActions,+) {+    val messenger = rememberMessenger()+    AppScaffold(+        topBar = {},+        floatingActionButton = { FloatingActionButton(onClick = actions.onCompose) { IconAdd() } },+    ) { padding ->+        LazyColumn(Modifier.padding(padding).fillMaxSize()) {+            section("Drafts", drafts.isEmpty(), "No drafts.")+            itemsIndexed(drafts, key = { _, row -> "d-${row.id}" }) { i, row ->+                val draft = DraftsController.decode(row)+                DraftRow(+                    draft = draft,+                    onOpen = { actions.onOpenDraft(draft) },+                    onDelete = {+                        actions.onDeleteDraft(draft.id)+                        messenger.show("Draft deleted", actionLabel = "Undo") { actions.onRestoreDraft(draft) }+                    },+                )+                if (i < drafts.lastIndex) HorizontalDivider()+            }+            item(key = "div-outbox") { SectionDivider() }+            section("Outbox", outbox.isEmpty(), "Nothing waiting to send.")+            if (outbox.isNotEmpty()) {+                item(key = "retry") {+                    TextButton(onClick = actions.onRetryOutbox, modifier = Modifier.padding(horizontal = 8.dp)) {+                        Text("Retry all")+                    }+                }+            }+            itemsIndexed(outbox, key = { _, entry -> "o-${entry.rowId}" }) { i, entry ->+                OutboxRow(entry)+                if (i < outbox.lastIndex) HorizontalDivider()+            }+            item(key = "div-sent") { SectionDivider() }+            section("Sent", sent.isEmpty(), "Nothing sent yet.")+            items(sent, key = { "s-${it.id}" }) { msg ->+                MessageRow(+                    msg = msg,+                    showRecipient = true,+                    isSelected = false,+                    onClick = { actions.onOpenSent(msg.id) },+                    onLongClick = {},+                    onToggleRead = { actions.onSetRead(listOf(msg.id), !msg.isRead) },+                    onSwipeDelete = {+                        actions.onTrashSent(listOf(msg.id))+                        messenger.show("Moved to Trash", actionLabel = "Undo") { actions.onUntrashSent(listOf(msg.id)) }+                    },+                    inTrash = false,+                )+                HorizontalDivider()+            }+        }+    }+}++private fun LazyListScope.section(title: String, empty: Boolean, emptyText: String) {+    item(key = "h-$title") {+        Text(+            title,+            style = MaterialTheme.typography.titleMedium,+            color = MaterialTheme.colorScheme.primary,+            modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp),+        )+    }+    if (empty) {+        item(key = "e-$title") {+            Text(+                emptyText,+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 12.dp),+            )+        }+    }+}++@Composable+private fun SectionDivider() {+    HorizontalDivider(modifier = Modifier.padding(top = 8.dp), thickness = 4.dp)+}++@Composable+private fun DraftRow(draft: Draft, onOpen: () -> Unit, onDelete: () -> Unit) {+    SwipeActionsBox(+        enableStartToEnd = false,+        onEndToStart = onDelete,+        background = { side ->+            if (side == SwipeActionSide.EndToStart) {+                Box(Modifier.fillMaxSize().padding(horizontal = 20.dp), contentAlignment = Alignment.CenterEnd) {+                    IconDelete(Modifier.size(24.dp))+                }+            }+        },+    ) {+        ListItem(+            modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen).padding(start = 4.dp),+            supportingContent = {+                Column {+                    val recipients = (draft.to + draft.cc + draft.bcc).joinToString(", ")+                    Text(+                        if (recipients.isEmpty()) "No recipients" else "To: $recipients",+                        style = MaterialTheme.typography.titleSmall,+                        maxLines = 1,+                        overflow = TextOverflow.Ellipsis,+                    )+                    Text(+                        draft.body.lineSequence().map { it.trim() }.firstOrNull { it.isNotEmpty() }.orEmpty(),+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                        maxLines = 1,+                        overflow = TextOverflow.Ellipsis,+                    )+                }+            },+        ) {+            Text(+                draft.subject.ifBlank { "(no subject)" },+                style = MaterialTheme.typography.bodyLarge,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+            )+        }+    }+}++@Composable+private fun OutboxRow(entry: OutboxMessage) {+    ListItem(+        modifier = Modifier.padding(start = 4.dp),+        supportingContent = {+            Column {+                Text(+                    "To: ${entry.toJson}",+                    style = MaterialTheme.typography.titleSmall,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                )+                entry.lastError?.let {+                    Text(+                        it,+                        color = MaterialTheme.colorScheme.error,+                        style = MaterialTheme.typography.bodySmall,+                        maxLines = 1,+                        overflow = TextOverflow.Ellipsis,+                    )+                }+            }+        },+        trailingContent = {+            Text(+                "${entry.attemptCount} ${if (entry.attemptCount == 1) "try" else "tries"}",+                style = MaterialTheme.typography.labelSmall,+            )+        },+    ) {+        Text(+            entry.subject.ifBlank { "(no subject)" },+            style = MaterialTheme.typography.bodyLarge,+            maxLines = 1,+            overflow = TextOverflow.Ellipsis,+        )+    }+}
securemail/src/main/java/com/vayunmathur/securemail/ui/OutboxScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/OutboxScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/OutboxScreen.ktdeleted file mode 100644index e77420015e..0000000000--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/OutboxScreen.kt+++ /dev/null@@ -1,88 +0,0 @@-package com.vayunmathur.securemail.ui--import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.runtime.Composable-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.text.style.TextOverflow-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.FloatingActionButton-import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.IconAdd-import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton-import com.vayunmathur.securemail.data.OutboxMessage--/** Outbox: queued sends awaiting reconnect, with manual retry. No app bar (it is a tab). */-@Composable-fun OutboxScreen(-    onRetry: () -> Unit,-    onCompose: () -> Unit = {},-    pending: List<OutboxMessage> = emptyList(),-) {-    AppScaffold(-        topBar = {},-        floatingActionButton = { FloatingActionButton(onClick = onCompose) { IconAdd() } },-    ) { padding ->-        Column(Modifier.padding(padding).fillMaxSize()) {-            if (pending.isEmpty()) {-                Box(Modifier.fillMaxSize().padding(32.dp), contentAlignment = Alignment.Center) {-                    Text(-                        "Outbox is empty.",-                        style = MaterialTheme.typography.bodyMedium,-                        color = MaterialTheme.colorScheme.onSurfaceVariant,-                    )-                }-            } else {-                TextButton(onClick = onRetry, modifier = Modifier.padding(horizontal = 8.dp)) { Text("Retry all") }-                LazyColumn(Modifier.fillMaxSize()) {-                    items(pending, key = { it.rowId }) { entry ->-                        ListItem(-                            supportingContent = {-                                Column {-                                    Text(-                                        "To: ${entry.toJson}",-                                        style = MaterialTheme.typography.titleSmall,-                                        maxLines = 1,-                                        overflow = TextOverflow.Ellipsis,-                                    )-                                    entry.lastError?.let {-                                        Text(-                                            it,-                                            color = MaterialTheme.colorScheme.error,-                                            style = MaterialTheme.typography.bodySmall,-                                            maxLines = 1,-                                            overflow = TextOverflow.Ellipsis,-                                        )-                                    }-                                }-                            },-                            trailingContent = {-                                Text(-                                    "${entry.attemptCount} ${if (entry.attemptCount == 1) "try" else "tries"}",-                                    style = MaterialTheme.typography.labelSmall,-                                )-                            },-                        ) {-                            Text(-                                entry.subject.ifBlank { "(no subject)" },-                                style = MaterialTheme.typography.bodyLarge,-                                maxLines = 1,-                                overflow = TextOverflow.Ellipsis,-                            )-                        }-                        HorizontalDivider()-                    }-                }-            }-        }-    }-}
securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.kt
diff --git a/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.kt b/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.ktindex e6a3aaed27..96ebc56862 100644--- a/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.kt+++ b/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/MetadataPreviews.kt@@ -115,25 +115,58 @@ class MetadataPreviews {                 onAddRecipient = { _, _ -> true },                 onRemoveRecipient = { _, _ -> },                 onSend = { _, _, _, _, _, _ -> },-                onBack = {},+                onLeave = { _, _ -> },+                onDiscard = {},             )         }     }      @PreviewTest-    @Preview(name = "4-settings", device = PHONE, group = "phone", showSystemUi = true)+    @Preview(name = "4-out", device = PHONE, group = "phone", showSystemUi = true)     @Composable-    fun Preview4Settings() {+    fun Preview4Out() {         DynamicTheme(darkTheme = true) {-            WithBottomBar(MailTab.SETTINGS) {-                SettingsScreen(-                    state = MailUiState(-                        address = "[email protected]",-                        fingerprintHex = "A1B2C3D4E5F60718293A4B5C6D7E8F90",-                        socketConnected = true,+            WithBottomBar(MailTab.OUT) {+                OutScreen(+                    drafts = listOf(+                        StoredMessage(+                            id = "draft-1",+                            from = "[email protected]",+                            toJson = "{\"to\":[\"[email protected]\"]}",+                            dateMillis = 1_792_772_800_000L,+                            messageId = "draft-1",+                            blobBase64 = "",+                            decryptedSubject = "Trip plans",+                            decryptedBody = "Thinking we leave Friday morning.",+                            folder = MailFolder.DRAFTS,+                        ),+                    ),+                    outbox = emptyList(),+                    sent = listOf(+                        StoredMessage(+                            id = "sent-1",+                            from = "[email protected]",+                            toJson = "[email protected]",+                            dateMillis = 1_792_770_000_000L,+                            messageId = "sent-1",+                            blobBase64 = "",+                            decryptedSubject = "Re: Lunch",+                            decryptedBody = "Sounds good, see you at noon.",+                            isRead = true,+                            folder = MailFolder.SENT,+                        ),+                    ),+                    actions = OutActions(+                        onCompose = {},+                        onOpenDraft = {},+                        onDeleteDraft = {},+                        onRestoreDraft = {},+                        onRetryOutbox = {},+                        onOpenSent = {},+                        onTrashSent = {},+                        onUntrashSent = {},+                        onSetRead = { _, _ -> },                     ),-                    onExportPublicKey = {},-                    onForget = {},                 )             }         }