email: make dialog routes and screenshot coverage lint-clean
- Commit
e707d12ac2a11e622f42af8ef1c0a51bc7917dbc- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 03:31 UTC (4 days ago)
- Parents
31a81d3
Convert the locally gated unsubscribe confirmation and message-details sheet into Route destinations (UnsubscribeDialog and MessageDetailsDialog) with DialogPage() metadata, their arguments in the route, and stateless contents under ui/dialogs/ hosted by EmailDialogEntries. MessageItem, MessageFooter, MessageThreadScreen, MessageThreadPage and NavigationEntries now push those routes instead of holding show-state, and performUnsubscribe is shared from EmailUiHelpers. The compose tests host the dialog content the way the route entry does. Give every route a deterministic screenshot capture: rename the inbox and conversation previews to their route keys and add composer, outbox, drafts, settings, EML viewer, unsubscribe-dialog and message-details-dialog previews. Outbox, Drafts, Settings and the EML viewer gain stateless Content slices (in their own files) so the previews render from fixed literals without a ViewModel, database or SAF URI. Split MimeParser's decoding helpers into MimeDecoding (with MimeParser delegating) to satisfy the file-length limit, and update email/AGENTS.md for the new routes, files and slices. No exemption markers are added, so docs/structure/exceptions.tsv is unchanged. Verified: ./gradlew :email:lint :email:lintVitalRelease :email:testDevUnitTest :email:compileReleaseKotlin all pass, and :email:compileDevScreenshotTestKotlin compiles the new previews.
Diff
email/AGENTS.md
diff --git a/email/AGENTS.md b/email/AGENTS.mdindex c0aef7657d..2b798f749b 100644--- a/email/AGENTS.md+++ b/email/AGENTS.md@@ -18,7 +18,7 @@ _Install: ./install email (dev by default)._ - Composer with inline images (HTML editor + CID spans) and an EML file viewer - Home-screen widget, rich notifications with actions, and assistant read/search intents **Architecture / data-flow:** `ui/` Compose screens → `platform/EmailViewModel` (+ `EmailManager`, send/draft action helpers) → `data/` Room stores (`*Dao`/`*Store` pairs + `EmailRepository`) fed by workers (`EmailSyncWorker`, `ImapIdleService`, `OutboxSendWorker`, `SnoozeWorker`) → `network/` raw IMAP/SMTP clients. `MainActivity.onCreateBeforeContent`: `NetworkClient.init(SYSTEM)` first, then widget previews, intent handling, hourly-sync schedule, outbox flush, IDLE start, and two one-time backfills.-**Entry points + reading order:** `Route` (`MessageList` / `MessageThread` / `Composer` / `Outbox` / `Drafts` / `AddAccount` / `Settings` / `EmlViewer`) → `MainActivity.kt` → `Navigation.kt` → `ui/MainContent.kt` → `platform/EmailViewModel.kt` → `data/EmailRepository.kt`.+**Entry points + reading order:** `Route` (`MessageList` / `MessageThread` / `Composer` / `Outbox` / `Drafts` / `AddAccount` / `AddAccountForm` / `Settings` / `EmlViewer` / `UnsubscribeDialog` / `MessageDetailsDialog`) → `MainActivity.kt` → `Navigation.kt` → `ui/MainContent.kt` → `platform/EmailViewModel.kt` → `data/EmailRepository.kt`. **Gotchas:** - `NetworkClient.init(this, TrustBundle.SYSTEM)` must stay first in `onCreateBeforeContent` — mail servers need system CAs, not the first-party bundle - `DateMillisBackfill`/`PeekContentBackfill` are one-time migrations gated on `runIfNeeded`; skipping them breaks sort order and snippet previews@@ -63,6 +63,7 @@ _Install: ./install email (dev by default)._ - com/vayunmathur/email/network/imap/ImapParser.kt - com/vayunmathur/email/network/imap/ImapFetchPipeline.kt - com/vayunmathur/email/network/imap/MimeParser.kt+- com/vayunmathur/email/network/imap/MimeDecoding.kt — quoted-printable/charset/RFC2047/date/filename/multipart decoding extracted from MimeParser (MimeParser delegates) - com/vayunmathur/email/network/imap/MimeParserParts.kt - com/vayunmathur/email/network/imap/ImapAuthException.kt - com/vayunmathur/email/network/imap/TrustAll.kt — debug only@@ -105,7 +106,11 @@ _Install: ./install email (dev by default)._ - com/vayunmathur/email/ui/composer/EmailHtmlInline.kt - com/vayunmathur/email/ui/composer/InlineImage.kt - com/vayunmathur/email/ui/composer/CidImageSpan.kt-- com/vayunmathur/email/ui/DraftsScreen.kt+- com/vayunmathur/email/ui/DraftsContent.kt, OutboxContent.kt, SettingsContent.kt, EmlViewerContent.kt — stateless slices for previews+- com/vayunmathur/email/ui/EmailDialogEntries.kt — `DialogPage()` entries for `UnsubscribeDialog` + `MessageDetailsDialog`+- com/vayunmathur/email/ui/dialogs/UnsubscribeDialogContent.kt — stateless unsubscribe confirmation+- com/vayunmathur/email/ui/dialogs/MessageDetailsDialogContent.kt — stateless message-details sheet+- com/vayunmathur/email/ui/NavigationEntries.kt - com/vayunmathur/email/ui/OutboxScreen.kt - com/vayunmathur/email/ui/EmlViewerScreen.kt - com/vayunmathur/email/ui/AddAccountScreen.kt
email/src/main/java/com/vayunmathur/email/Route.kt
diff --git a/email/src/main/java/com/vayunmathur/email/Route.kt b/email/src/main/java/com/vayunmathur/email/Route.ktindex e2e285b094..97c39ea4bb 100644--- a/email/src/main/java/com/vayunmathur/email/Route.kt+++ b/email/src/main/java/com/vayunmathur/email/Route.kt@@ -40,4 +40,26 @@ sealed interface Route : NavKey { @Serializable /** Destination viewing an opened .eml file identified by its URI string. */ data class EmlViewer(val uriString: String) : Route++ /**+ * Unsubscribe confirmation dialog. The detected method travels as+ * [kind] (`one-click`, `open-web` or `send-mail`) plus its [target]+ * URL/address, never as pending state in the thread screen.+ */+ @Serializable+ data class UnsubscribeDialog(val kind: String, val target: String) : Route++ /**+ * Message-details sheet dialog for one message. The sender/date/folder+ * values it shows travel in the route, never as local sheet state.+ */+ @Serializable+ data class MessageDetailsDialog(+ val accountEmail: String,+ val senderName: String,+ val senderEmail: String,+ val date: String,+ val folderName: String,+ val toEmail: String,+ ) : Route }
email/src/main/java/com/vayunmathur/email/network/imap/MimeDecoding.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/MimeDecoding.kt b/email/src/main/java/com/vayunmathur/email/network/imap/MimeDecoding.ktnew file mode 100644index 0000000000..85ad26c686--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/network/imap/MimeDecoding.kt@@ -0,0 +1,240 @@+package com.vayunmathur.email.network.imap++import android.util.Base64+import java.io.ByteArrayOutputStream+import java.nio.charset.Charset+import java.util.regex.Pattern++/** Text/multipart decoding helpers extracted from [MimeParser]. */+internal object MimeDecoding {+ private const val QP_HEX_RADIX = 16+ private const val QP_HEX_PAIR_LEN = 3+ private const val QP_SOFT_BREAK_LEN = 3+ private const val QP_SOFT_BREAK_LF_LEN = 2+ private const val MAX_FILENAME_LEN = 120++fun decodeQuotedPrintable(bytes: ByteArray): ByteArray {+ val out = ByteArrayOutputStream()+ var i = 0+ while (i < bytes.size) {+ i = QpDecoder.decodeNext(bytes, i, out)+ }+ return out.toByteArray()+}++private object QpDecoder {+ fun decodeNext(bytes: ByteArray, i: Int, out: ByteArrayOutputStream): Int {+ val b = bytes[i]+ if (b != '='.code.toByte()) {+ out.write(b.toInt())+ return i + 1+ }+ if (i + 1 >= bytes.size) return bytes.size+ val softBreak = softBreakLen(bytes, i)+ if (softBreak > 0) return i + softBreak+ return decodeHex(bytes, i, out)+ }++ private fun softBreakLen(bytes: ByteArray, i: Int): Int {+ val next = bytes[i + 1]+ if (next == '\r'.code.toByte()) {+ if (i + QP_SOFT_BREAK_LEN - 1 < bytes.size &&+ bytes[i + QP_SOFT_BREAK_LEN - 1] == '\n'.code.toByte()+ ) {+ return QP_HEX_PAIR_LEN+ }+ return 0+ }+ if (next == '\n'.code.toByte()) return QP_SOFT_BREAK_LF_LEN+ return 0+ }++ private fun decodeHex(bytes: ByteArray, i: Int, out: ByteArrayOutputStream): Int {+ if (i + QP_HEX_PAIR_LEN - 1 < bytes.size) {+ val h1 = bytes[i + 1].toInt().toChar()+ val h2 = bytes[i + 2].toInt().toChar()+ try {+ out.write("$h1$h2".toInt(QP_HEX_RADIX))+ return i + QP_HEX_PAIR_LEN+ } catch (_: Exception) {}+ }+ out.write(bytes[i].toInt())+ return i + 1+ }+}++fun decodeCharset(bytes: ByteArray, charsetName: String): String {+ val name = charsetName.trim().lowercase()+ val candidates = listOf(+ name,+ when (name) {+ "utf8" -> "utf-8"+ "latin1", "iso8859-1", "iso-8859-1" -> "iso-8859-1"+ "windows-1252", "cp1252" -> "windows-1252"+ "windows-1250", "cp1250" -> "windows-1250"+ "us-ascii", "ascii" -> "us-ascii"+ else -> name+ },+ "utf-8",+ "iso-8859-1"+ ).distinct()+ for (cs in candidates) {+ try {+ return String(bytes, Charset.forName(cs))+ } catch (_: Exception) {}+ }+ return String(bytes, Charsets.UTF_8)+}++private val rfc2047Pattern = Pattern.compile("=\\?([^?]+)\\?([bBqQ])\\?([^?]+)\\?=", Pattern.CASE_INSENSITIVE)++fun decodeHeader(raw: String): String {+ var result = raw+ try {+ val matcher = rfc2047Pattern.matcher(raw)+ val sb = StringBuffer()+ while (matcher.find()) {+ val charset = matcher.group(1) ?: "utf-8"+ val enc = matcher.group(2)?.uppercase() ?: "B"+ val encoded = matcher.group(3) ?: ""+ val decoded = try {+ if (enc == "B") {+ val bytes = Base64.decode(encoded, Base64.DEFAULT)+ decodeCharset(bytes, charset)+ } else {+ val qpStr = encoded.replace('_', ' ')+ val decodedBytes = decodeQuotedPrintable(qpStr.toByteArray(Charsets.ISO_8859_1))+ decodeCharset(decodedBytes, charset)+ }+ } catch (_: Exception) { encoded }+ matcher.appendReplacement(sb, java.util.regex.Matcher.quoteReplacement(decoded))+ }+ matcher.appendTail(sb)+ result = sb.toString()+ } catch (_: Exception) {}+ return result+}++fun parseDateToMillis(dateStr: String): Long {+ if (dateStr.isBlank()) return 0L+ val formats = listOf(+ "EEE, dd MMM yyyy HH:mm:ss Z",+ "EEE, dd MMM yyyy HH:mm:ss zzz",+ "EEE, dd MMM yyyy HH:mm:ss",+ "dd MMM yyyy HH:mm:ss Z",+ "dd MMM yyyy HH:mm:ss zzz",+ "EEE MMM dd HH:mm:ss Z yyyy",+ "EEE MMM dd HH:mm:ss zzz yyyy",+ "EEE MMM dd HH:mm:ss yyyy",+ "yyyy-MM-dd HH:mm:ss Z",+ "yyyy-MM-dd'T'HH:mm:ss'Z'",+ "yyyy-MM-dd'T'HH:mm:ssZ",+ "yyyy-MM-dd'T'HH:mm:ss.SSSZ",+ "dd-MMM-yyyy HH:mm:ss Z"+ )+ for (fmtStr in formats) {+ try {+ val fmt = java.text.SimpleDateFormat(fmtStr, java.util.Locale.US)+ fmt.isLenient = true+ val d = fmt.parse(dateStr.trim())+ if (d != null) return d.time+ } catch (_: Exception) {}+ }+ try {+ @Suppress("DEPRECATION")+ val d = java.util.Date(dateStr)+ if (d.time != 0L) return d.time+ } catch (_: Exception) {}+ return 0L+}++fun sanitizeFilename(name: String): String {+ var n = name.trim()+ if (n.contains("=?")) n = decodeHeader(n)+ n = n.substringAfterLast('/').substringAfterLast('\\')+ n = n.replace(Regex("[\\r\\n\"]"), "_")+ if (n.length > MAX_FILENAME_LEN) n = n.take(MAX_FILENAME_LEN)+ return n.ifBlank { "attachment" }+}++fun splitMultipart(bodyBytes: ByteArray, boundary: String): List<ByteArray> {+ if (boundary.isBlank()) return emptyList()+ val bodyStr = String(bodyBytes, Charsets.ISO_8859_1)+ val delim = "--$boundary"+ val positions = MultipartSplitter.scan(bodyStr, delim)++ if (positions.size < 2) {+ return MultipartSplitter.singleFallback(bodyStr, positions)+ }++ val result = mutableListOf<ByteArray>()+ for (i in 0 until positions.size - 1) {+ val cur = positions[i]+ if (cur.isClose) break+ MultipartSplitter.slice(bodyStr, cur, positions[i + 1])?.let { result.add(it) }+ }+ return result+}++private data class DelimPos(val start: Int, val end: Int, val isClose: Boolean)++private object MultipartSplitter {+ fun scan(bodyStr: String, delim: String): List<DelimPos> {+ val positions = mutableListOf<DelimPos>()+ var searchFrom = 0+ var done = false+ while (!done) {+ val idx = bodyStr.indexOf(delim, searchFrom)+ if (idx == -1) {+ done = true+ } else {+ positions.add(scanOne(bodyStr, delim, idx))+ if (positions.last().isClose) {+ done = true+ } else {+ searchFrom = positions.last().end+ }+ }+ }+ return positions+ }++ private fun scanOne(bodyStr: String, delim: String, idx: Int): DelimPos {+ var lineEnd = bodyStr.indexOf('\n', idx)+ if (lineEnd == -1) lineEnd = bodyStr.length else lineEnd+++ return DelimPos(idx, lineEnd, isCloseDelimiter(bodyStr, delim, idx))+ }++ private fun isCloseDelimiter(bodyStr: String, delim: String, idx: Int): Boolean {+ if (idx + delim.length >= bodyStr.length) return false+ val nl = bodyStr.indexOf('\n', idx)+ val afterDelimPart = if (nl == -1) {+ bodyStr.substring(idx + delim.length)+ } else {+ bodyStr.substring(idx + delim.length, nl)+ }+ return afterDelimPart.trim().startsWith("--")+ }++ fun singleFallback(bodyStr: String, positions: List<DelimPos>): List<ByteArray> {+ if (positions.size == 1 && !positions[0].isClose) {+ val start = positions[0].end+ if (start < bodyStr.length) {+ return listOf(bodyStr.substring(start).toByteArray(Charsets.ISO_8859_1))+ }+ }+ return emptyList()+ }++ fun slice(bodyStr: String, cur: DelimPos, next: DelimPos): ByteArray? {+ val partStart = cur.end+ var partEnd = next.start+ if (partEnd >= 2 && bodyStr[partEnd - 1] == '\n') {+ partEnd--+ if (partEnd > 0 && bodyStr[partEnd - 1] == '\r') partEnd--+ }+ if (partStart > partEnd) return null+ return bodyStr.substring(partStart, partEnd).toByteArray(Charsets.ISO_8859_1)+ }+}+}
email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.kt b/email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.ktindex 69dd0bb693..d0d48ce5ee 100644--- a/email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.kt+++ b/email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.kt@@ -686,230 +686,19 @@ object MimeParser { } } - fun decodeQuotedPrintable(bytes: ByteArray): ByteArray {- val out = ByteArrayOutputStream()- var i = 0- while (i < bytes.size) {- i = QpDecoder.decodeNext(bytes, i, out)- }- return out.toByteArray()- }-- private object QpDecoder {- fun decodeNext(bytes: ByteArray, i: Int, out: ByteArrayOutputStream): Int {- val b = bytes[i]- if (b != '='.code.toByte()) {- out.write(b.toInt())- return i + 1- }- if (i + 1 >= bytes.size) return bytes.size- val softBreak = softBreakLen(bytes, i)- if (softBreak > 0) return i + softBreak- return decodeHex(bytes, i, out)- }-- private fun softBreakLen(bytes: ByteArray, i: Int): Int {- val next = bytes[i + 1]- if (next == '\r'.code.toByte()) {- if (i + QP_SOFT_BREAK_LEN - 1 < bytes.size &&- bytes[i + QP_SOFT_BREAK_LEN - 1] == '\n'.code.toByte()- ) {- return QP_HEX_PAIR_LEN- }- return 0- }- if (next == '\n'.code.toByte()) return QP_SOFT_BREAK_LF_LEN- return 0- }-- private fun decodeHex(bytes: ByteArray, i: Int, out: ByteArrayOutputStream): Int {- if (i + QP_HEX_PAIR_LEN - 1 < bytes.size) {- val h1 = bytes[i + 1].toInt().toChar()- val h2 = bytes[i + 2].toInt().toChar()- try {- out.write("$h1$h2".toInt(QP_HEX_RADIX))- return i + QP_HEX_PAIR_LEN- } catch (_: Exception) {}- }- out.write(bytes[i].toInt())- return i + 1- }- }-- fun decodeCharset(bytes: ByteArray, charsetName: String): String {- val name = charsetName.trim().lowercase()- val candidates = listOf(- name,- when (name) {- "utf8" -> "utf-8"- "latin1", "iso8859-1", "iso-8859-1" -> "iso-8859-1"- "windows-1252", "cp1252" -> "windows-1252"- "windows-1250", "cp1250" -> "windows-1250"- "us-ascii", "ascii" -> "us-ascii"- else -> name- },- "utf-8",- "iso-8859-1"- ).distinct()- for (cs in candidates) {- try {- return String(bytes, Charset.forName(cs))- } catch (_: Exception) {}- }- return String(bytes, Charsets.UTF_8)- }-- private val rfc2047Pattern = Pattern.compile("=\\?([^?]+)\\?([bBqQ])\\?([^?]+)\\?=", Pattern.CASE_INSENSITIVE)-- fun decodeHeader(raw: String): String {- var result = raw- try {- val matcher = rfc2047Pattern.matcher(raw)- val sb = StringBuffer()- while (matcher.find()) {- val charset = matcher.group(1) ?: "utf-8"- val enc = matcher.group(2)?.uppercase() ?: "B"- val encoded = matcher.group(3) ?: ""- val decoded = try {- if (enc == "B") {- val bytes = Base64.decode(encoded, Base64.DEFAULT)- decodeCharset(bytes, charset)- } else {- val qpStr = encoded.replace('_', ' ')- val decodedBytes = decodeQuotedPrintable(qpStr.toByteArray(Charsets.ISO_8859_1))- decodeCharset(decodedBytes, charset)- }- } catch (_: Exception) { encoded }- matcher.appendReplacement(sb, java.util.regex.Matcher.quoteReplacement(decoded))- }- matcher.appendTail(sb)- result = sb.toString()- } catch (_: Exception) {}- return result- }-- fun parseDateToMillis(dateStr: String): Long {- if (dateStr.isBlank()) return 0L- val formats = listOf(- "EEE, dd MMM yyyy HH:mm:ss Z",- "EEE, dd MMM yyyy HH:mm:ss zzz",- "EEE, dd MMM yyyy HH:mm:ss",- "dd MMM yyyy HH:mm:ss Z",- "dd MMM yyyy HH:mm:ss zzz",- "EEE MMM dd HH:mm:ss Z yyyy",- "EEE MMM dd HH:mm:ss zzz yyyy",- "EEE MMM dd HH:mm:ss yyyy",- "yyyy-MM-dd HH:mm:ss Z",- "yyyy-MM-dd'T'HH:mm:ss'Z'",- "yyyy-MM-dd'T'HH:mm:ssZ",- "yyyy-MM-dd'T'HH:mm:ss.SSSZ",- "dd-MMM-yyyy HH:mm:ss Z"- )- for (fmtStr in formats) {- try {- val fmt = java.text.SimpleDateFormat(fmtStr, java.util.Locale.US)- fmt.isLenient = true- val d = fmt.parse(dateStr.trim())- if (d != null) return d.time- } catch (_: Exception) {}- }- try {- @Suppress("DEPRECATION")- val d = java.util.Date(dateStr)- if (d.time != 0L) return d.time- } catch (_: Exception) {}- return 0L- }+ fun decodeQuotedPrintable(bytes: ByteArray): ByteArray = MimeDecoding.decodeQuotedPrintable(bytes) - fun sanitizeFilename(name: String): String {- var n = name.trim()- if (n.contains("=?")) n = decodeHeader(n)- n = n.substringAfterLast('/').substringAfterLast('\\')- n = n.replace(Regex("[\\r\\n\"]"), "_")- if (n.length > MAX_FILENAME_LEN) n = n.take(MAX_FILENAME_LEN)- return n.ifBlank { "attachment" }- }+ fun decodeCharset(bytes: ByteArray, charsetName: String): String =+ MimeDecoding.decodeCharset(bytes, charsetName) - fun splitMultipart(bodyBytes: ByteArray, boundary: String): List<ByteArray> {- if (boundary.isBlank()) return emptyList()- val bodyStr = String(bodyBytes, Charsets.ISO_8859_1)- val delim = "--$boundary"- val positions = MultipartSplitter.scan(bodyStr, delim)+ fun decodeHeader(raw: String): String = MimeDecoding.decodeHeader(raw) - if (positions.size < 2) {- return MultipartSplitter.singleFallback(bodyStr, positions)- }+ fun parseDateToMillis(dateStr: String): Long = MimeDecoding.parseDateToMillis(dateStr) - val result = mutableListOf<ByteArray>()- for (i in 0 until positions.size - 1) {- val cur = positions[i]- if (cur.isClose) break- MultipartSplitter.slice(bodyStr, cur, positions[i + 1])?.let { result.add(it) }- }- return result- }+ fun sanitizeFilename(name: String): String = MimeDecoding.sanitizeFilename(name) - private data class DelimPos(val start: Int, val end: Int, val isClose: Boolean)-- private object MultipartSplitter {- fun scan(bodyStr: String, delim: String): List<DelimPos> {- val positions = mutableListOf<DelimPos>()- var searchFrom = 0- var done = false- while (!done) {- val idx = bodyStr.indexOf(delim, searchFrom)- if (idx == -1) {- done = true- } else {- positions.add(scanOne(bodyStr, delim, idx))- if (positions.last().isClose) {- done = true- } else {- searchFrom = positions.last().end- }- }- }- return positions- }-- private fun scanOne(bodyStr: String, delim: String, idx: Int): DelimPos {- var lineEnd = bodyStr.indexOf('\n', idx)- if (lineEnd == -1) lineEnd = bodyStr.length else lineEnd++- return DelimPos(idx, lineEnd, isCloseDelimiter(bodyStr, delim, idx))- }-- private fun isCloseDelimiter(bodyStr: String, delim: String, idx: Int): Boolean {- if (idx + delim.length >= bodyStr.length) return false- val nl = bodyStr.indexOf('\n', idx)- val afterDelimPart = if (nl == -1) {- bodyStr.substring(idx + delim.length)- } else {- bodyStr.substring(idx + delim.length, nl)- }- return afterDelimPart.trim().startsWith("--")- }-- fun singleFallback(bodyStr: String, positions: List<DelimPos>): List<ByteArray> {- if (positions.size == 1 && !positions[0].isClose) {- val start = positions[0].end- if (start < bodyStr.length) {- return listOf(bodyStr.substring(start).toByteArray(Charsets.ISO_8859_1))- }- }- return emptyList()- }-- fun slice(bodyStr: String, cur: DelimPos, next: DelimPos): ByteArray? {- val partStart = cur.end- var partEnd = next.start- if (partEnd >= 2 && bodyStr[partEnd - 1] == '\n') {- partEnd--- if (partEnd > 0 && bodyStr[partEnd - 1] == '\r') partEnd--- }- if (partStart > partEnd) return null- return bodyStr.substring(partStart, partEnd).toByteArray(Charsets.ISO_8859_1)- }- }+ fun splitMultipart(bodyBytes: ByteArray, boundary: String): List<ByteArray> =+ MimeDecoding.splitMultipart(bodyBytes, boundary) fun extractHeaderValue(headers: Map<String, String>, name: String): String? { return headers[name.lowercase()]?.let { decodeHeader(it) }
email/src/main/java/com/vayunmathur/email/ui/DraftsContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/DraftsContent.kt b/email/src/main/java/com/vayunmathur/email/ui/DraftsContent.ktnew file mode 100644index 0000000000..d3b7bfaad2--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/DraftsContent.kt@@ -0,0 +1,57 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.email.R+import com.vayunmathur.email.data.DraftEntry+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.sharedText++/** Stateless drafts list slice, rendered by previews with fixed drafts. */+@Composable+fun DraftsContent(+ drafts: List<DraftEntry>,+ hasLoaded: Boolean,+ onOpenDraft: (Long) -> Unit,+ onDelete: (Long) -> Unit,+ modifier: Modifier = Modifier,+) {+ if (!hasLoaded && drafts.isEmpty()) {+ Box(Modifier.fillMaxSize().then(modifier))+ } else if (drafts.isEmpty()) {+ EmptyState(title = stringResource(R.string.no_drafts), modifier = Modifier.fillMaxSize().then(modifier))+ } else {+ LazyColumn(modifier = Modifier.fillMaxSize().then(modifier)) {+ items(drafts, key = { it.id }) { d ->+ ListItem(+ content = {+ Text(+ d.subject.ifBlank { stringResource(R.string.no_subject) },+ modifier = Modifier.sharedText("email-draft-subject-${d.id}"),+ )+ },+ supportingContent = {+ val prefix = if (d.to.isNotBlank()) "To: ${d.to} " else ""+ Text(prefix + d.body.replace("\n", " ").take(80), maxLines = 2)+ },+ modifier = Modifier.clickable { onOpenDraft(d.id) },+ trailingContent = {+ IconButton(onClick = { onDelete(d.id) }) { com.vayunmathur.library.ui.IconDelete() }+ },+ )+ HorizontalDivider()+ }+ }+ }+}
email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.ktindex d21a886d6b..23c684bd69 100644--- a/email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.kt@@ -35,39 +35,12 @@ fun DraftsScreen( onNavigateBack = onBack, isRefreshing = !hasLoaded && drafts.isEmpty(), ) { padding ->- if (!hasLoaded && drafts.isEmpty()) {- // First load: empty placeholder under the scaffold's top indicator,- // never the empty state before loaded.- Box(Modifier.fillMaxSize().padding(padding))- } else if (drafts.isEmpty()) {- EmptyState(- title = stringResource(R.string.no_drafts),- modifier = Modifier.fillMaxSize().padding(padding),- )- } else {- LazyColumn(modifier = Modifier.fillMaxSize().padding(padding)) {- items(drafts, key = { it.id }) { d ->- ListItem(- content = {- Text(- d.subject.ifBlank { stringResource(R.string.no_subject) },- modifier = Modifier.sharedText("email-draft-subject-${d.id}"),- )- },- supportingContent = {- val prefix = if (d.to.isNotBlank()) "To: ${d.to} " else ""- Text(prefix + d.body.replace("\n", " ").take(80), maxLines = 2)- },- modifier = Modifier.clickable { onOpenDraft(d.id) },- trailingContent = {- IconButton(onClick = { viewModel.draftsActions.delete(d.id) }) {- com.vayunmathur.library.ui.IconDelete()- }- },- )- HorizontalDivider()- }- }- }+ DraftsContent(+ drafts = drafts,+ hasLoaded = hasLoaded,+ onOpenDraft = onOpenDraft,+ onDelete = { id -> viewModel.draftsActions.delete(id) },+ modifier = Modifier.padding(padding),+ ) } }
email/src/main/java/com/vayunmathur/email/ui/EmailDialogEntries.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/EmailDialogEntries.kt b/email/src/main/java/com/vayunmathur/email/ui/EmailDialogEntries.ktnew file mode 100644index 0000000000..a62a72e723--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/EmailDialogEntries.kt@@ -0,0 +1,65 @@+package com.vayunmathur.email.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.email.Route+import com.vayunmathur.email.data.UnsubscribeMethod+import com.vayunmathur.email.platform.MessageThreadActions+import com.vayunmathur.email.ui.dialogs.MessageDetailsDialogContent+import com.vayunmathur.email.ui.dialogs.UnsubscribeDialogContent+import com.vayunmathur.library.util.DialogPage+import com.vayunmathur.library.util.EntryProviderScope+import com.vayunmathur.library.util.NavBackStack++/** Dialog destinations for email: DialogPage routes with stateless contents. */+internal fun EntryProviderScope<Route>.emailDialogEntries(+ backStack: NavBackStack<Route>,+ actions: MessageThreadActions,+ onCompose: (String, String) -> Unit,+) {+ entry<Route.UnsubscribeDialog>(metadata = DialogPage()) { route ->+ UnsubscribeDialogHost(backStack, route, actions, onCompose)+ }+ entry<Route.MessageDetailsDialog>(metadata = DialogPage()) { route ->+ MessageDetailsDialogContent(+ accountEmail = route.accountEmail,+ senderName = route.senderName,+ senderEmail = route.senderEmail,+ date = route.date,+ folderName = route.folderName,+ toEmail = route.toEmail,+ onDismiss = { backStack.pop() },+ )+ }+}++@Composable+private fun UnsubscribeDialogHost(+ backStack: NavBackStack<Route>,+ route: Route.UnsubscribeDialog,+ actions: MessageThreadActions,+ onCompose: (String, String) -> Unit,+) {+ val context = LocalContext.current+ val method = when (route.kind) {+ "one-click" -> UnsubscribeMethod.OneClickPost(route.target)+ "send-mail" -> UnsubscribeMethod.SendMail(route.target)+ else -> UnsubscribeMethod.OpenWeb(route.target)+ }+ UnsubscribeDialogContent(+ method = method,+ onDismiss = { backStack.pop() },+ onConfirm = {+ backStack.pop()+ performUnsubscribe(method, context, actions, onCompose)+ },+ )+}++/** Route for the unsubscribe method detected on a message. */+internal fun unsubscribeRoute(method: UnsubscribeMethod): Route.UnsubscribeDialog =+ when (method) {+ is UnsubscribeMethod.OneClickPost -> Route.UnsubscribeDialog("one-click", method.url)+ is UnsubscribeMethod.OpenWeb -> Route.UnsubscribeDialog("open-web", method.url)+ is UnsubscribeMethod.SendMail -> Route.UnsubscribeDialog("send-mail", method.address)+ }
email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.kt b/email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.ktindex c55b85cc31..65c644b567 100644--- a/email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.kt@@ -3,17 +3,11 @@ package com.vayunmathur.email.ui import android.content.Context import android.content.Intent import android.net.Uri-import androidx.compose.runtime.Composable-import androidx.compose.ui.res.stringResource import com.vayunmathur.email.R import com.vayunmathur.email.data.UnsubscribeMethod import com.vayunmathur.email.platform.MessageThreadActions-import com.vayunmathur.library.ui.AlertDialog-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.util.AppMessages import androidx.core.net.toUri-import com.vayunmathur.library.ui.R as UiR internal fun uriName(context: android.content.Context, uri: android.net.Uri): String = runCatching {@@ -80,32 +74,8 @@ private fun splitQuotedText(body: String): Pair<String, String> { return body to "" } -/** Confirmation dialog shown before acting on a detected unsubscribe option. */-@Composable-private fun UnsubscribeDialog(- method: UnsubscribeMethod,- onDismiss: () -> Unit,- onConfirm: () -> Unit,-) {- val (message, confirmLabel) = when (method) {- is UnsubscribeMethod.OneClickPost ->- "Send an unsubscribe request to the sender?" to "Unsubscribe"- is UnsubscribeMethod.OpenWeb ->- "Open the unsubscribe page in your browser?" to "Open"- is UnsubscribeMethod.SendMail ->- "Compose an unsubscribe email to ${method.address}?" to "Compose"- }- AlertDialog(- onDismissRequest = onDismiss,- title = { Text(stringResource(R.string.unsubscribe)) },- text = { Text(message) },- confirmButton = { TextButton(onClick = onConfirm) { Text(confirmLabel) } },- dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) } },- )-}- /** Act on a confirmed unsubscribe option. */-private fun performUnsubscribe(+internal fun performUnsubscribe( method: UnsubscribeMethod, context: android.content.Context, actions: MessageThreadActions,
email/src/main/java/com/vayunmathur/email/ui/EmlViewerContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/EmlViewerContent.kt b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerContent.ktnew file mode 100644index 0000000000..4eaea9d944--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerContent.kt@@ -0,0 +1,81 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.email.R+import com.vayunmathur.email.platform.ParsedEml+import com.vayunmathur.library.ui.HtmlText+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/** Stateless parsed-.eml slice, rendered by previews with a fixed plain-text message. */+@Composable+fun EmlViewerContent(+ parsed: ParsedEml,+ onComposeForward: (subject: String, body: String) -> Unit = { _, _ -> },+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val msg = parsed.message+ val emlAtts = parsed.emlAttachments+ val cidMap = parsed.inlineCidMap+ BoxWithConstraints(modifier = modifier.fillMaxSize()) {+ val attachmentsMaxHeight = maxHeight * EML_ATTACHMENTS_MAX_FRACTION+ Column(modifier = Modifier.fillMaxSize()) {+ EmlHeader(msg.from, msg.date, msg.to, msg.cc, msg.subject)+ if (msg.isHtml && msg.body != null) {+ val settings = remember(context) { com.vayunmathur.email.data.EmailSettings.get(context) }+ val loadRemoteByDefault by settings.loadRemoteImages.collectAsStateWithLifecycle()+ var loadImages by remember(msg.id, loadRemoteByDefault) { mutableStateOf(loadRemoteByDefault) }+ if (!loadImages && cidMap.isEmpty()) {+ Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+ Text(stringResource(R.string.remote_images_blocked), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ TextButton(onClick = { loadImages = true }) { Text(stringResource(R.string.load_images)) }+ }+ }+ HtmlText(+ html = msg.body,+ blockRemoteImages = !loadImages && cidMap.isEmpty(),+ cidMap = cidMap,+ javaScriptEnabled = false,+ scrollInternally = true,+ fitContentToWidth = true,+ modifier = Modifier.weight(1f).fillMaxWidth().padding(horizontal = 8.dp),+ )+ if (emlAtts.isNotEmpty()) {+ Column(Modifier.fillMaxWidth().heightIn(max = attachmentsMaxHeight).verticalScroll(rememberScrollState())) {+ EmlAttachments(emlAtts)+ }+ }+ } else {+ Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {+ Text(text = msg.body ?: stringResource(R.string.no_content_1), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp))+ EmlAttachments(emlAtts)+ Spacer(Modifier.height(24.dp))+ }+ }+ }+ }+}
email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.ktindex 22dcf7040d..c465c28522 100644--- a/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt@@ -150,61 +150,21 @@ fun EmlViewerScreen( Box(modifier = Modifier.fillMaxSize().padding(padding)) } else -> {- val msg = parsed!!.message- val emlAtts = parsed!!.emlAttachments- val cidMap = parsed!!.inlineCidMap-- // Same layout as the thread screen (#900): header fixed on top, an- // HTML body that fills the rest and scrolls itself, never a- // wrap-content WebView inside a scrolling column.- BoxWithConstraints(modifier = Modifier.fillMaxSize().padding(padding)) {- val attachmentsMaxHeight = maxHeight * EML_ATTACHMENTS_MAX_FRACTION- Column(modifier = Modifier.fillMaxSize()) {- EmlHeader(msg.from, msg.date, msg.to, msg.cc, msg.subject)- if (msg.isHtml && msg.body != null) {- val settings = remember(context) { com.vayunmathur.email.data.EmailSettings.get(context) }- val loadRemoteByDefault by settings.loadRemoteImages.collectAsStateWithLifecycle()- var loadImages by remember(uriString, loadRemoteByDefault) { mutableStateOf(loadRemoteByDefault) }- if (!loadImages && cidMap.isEmpty()) {- Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {- Text(stringResource(R.string.remote_images_blocked), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- TextButton(onClick = { loadImages = true }) { Text(stringResource(R.string.load_images)) }- }- }- HtmlText(- html = msg.body,- blockRemoteImages = !loadImages && cidMap.isEmpty(),- cidMap = cidMap,- // An .eml file is received mail too: never run its scripts.- javaScriptEnabled = false,- scrollInternally = true,- fitContentToWidth = true,- modifier = Modifier.weight(1f).fillMaxWidth().padding(horizontal = 8.dp),- )- if (emlAtts.isNotEmpty()) {- Column(Modifier.fillMaxWidth().heightIn(max = attachmentsMaxHeight).verticalScroll(rememberScrollState())) {- EmlAttachments(emlAtts)- }- }- } else {- Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {- Text(text = msg.body ?: stringResource(R.string.no_content_1), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp))- EmlAttachments(emlAtts)- Spacer(Modifier.height(24.dp))- }- }- }- }+ EmlViewerContent(+ parsed = parsed!!,+ onComposeForward = onComposeForward,+ modifier = Modifier.padding(padding),+ ) } } } } /** Share of the pane the attachment list under an HTML body may take before it scrolls. */-private const val EML_ATTACHMENTS_MAX_FRACTION = 0.3f+internal const val EML_ATTACHMENTS_MAX_FRACTION = 0.3f @Composable-private fun EmlHeader(from: String, date: String, to: String?, cc: String?, subject: String) {+internal fun EmlHeader(from: String, date: String, to: String?, cc: String?, subject: String) { val senderName = senderDisplayName(from).ifEmpty { from } val avatarColor = Color(accountColor(from.ifBlank { "eml-viewer" })) Row(modifier = Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically) {@@ -225,7 +185,7 @@ private fun EmlHeader(from: String, date: String, to: String?, cc: String?, subj } @Composable-private fun EmlAttachments(attachments: List<EmlAttachment>) {+internal fun EmlAttachments(attachments: List<EmlAttachment>) { if (attachments.isEmpty()) return Spacer(Modifier.height(16.dp)) Text(stringResource(R.string.attachments_2), style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(horizontal = 16.dp))
email/src/main/java/com/vayunmathur/email/ui/MessageFooter.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MessageFooter.kt b/email/src/main/java/com/vayunmathur/email/ui/MessageFooter.ktindex f2eeff23f2..42d758edab 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageFooter.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageFooter.kt@@ -1,7 +1,5 @@ package com.vayunmathur.email.ui -import android.content.Context-import android.content.Intent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row@@ -10,23 +8,17 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp-import androidx.core.net.toUri import com.vayunmathur.email.R import com.vayunmathur.email.data.Attachment import com.vayunmathur.email.data.EmailMessage import com.vayunmathur.email.data.UnsubscribeMethod import com.vayunmathur.email.data.detectUnsubscribe import com.vayunmathur.email.platform.MessageThreadActions-import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.IconForward import com.vayunmathur.library.ui.IconUndo import com.vayunmathur.library.ui.MaterialTheme@@ -48,8 +40,8 @@ fun MessageFooter( onReply: (String, String, String?) -> Unit, onForward: (String, String?) -> Unit, onCompose: (String, String) -> Unit,+ onShowUnsubscribe: (UnsubscribeMethod) -> Unit = {}, ) {- val context = LocalContext.current val resources = LocalResources.current if (attachments.isNotEmpty()) { Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {@@ -68,36 +60,8 @@ fun MessageFooter( Row(modifier = Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { val unsubscribe = remember(msg.listUnsubscribe, msg.listUnsubscribePost, msg.body, msg.isHtml) { msg.detectUnsubscribe() } if (unsubscribe != null) {- var showConfirm by remember(msg.id) { mutableStateOf(false) }- TextButton(onClick = { showConfirm = true }) { Text(stringResource(R.string.unsubscribe)) }- if (showConfirm) {- UnsubscribeDialog(method = unsubscribe, onDismiss = { showConfirm = false }, onConfirm = { showConfirm = false; performUnsubscribe(unsubscribe, context, actions, onCompose) })- }+ TextButton(onClick = { onShowUnsubscribe(unsubscribe) }) { Text(stringResource(R.string.unsubscribe)) } } TextButton(onClick = { actions.blockSender(msg.from); AppMessages.show(resources.getString(R.string.sender_blocked)); onBack() }) { Text(stringResource(R.string.block_sender)) } } }--@Composable-private fun UnsubscribeDialog(method: UnsubscribeMethod, onDismiss: () -> Unit, onConfirm: () -> Unit) {- val (message, confirmLabel) = when (method) {- is UnsubscribeMethod.OneClickPost -> "Send an unsubscribe request to the sender?" to "Unsubscribe"- is UnsubscribeMethod.OpenWeb -> "Open the unsubscribe page in your browser?" to "Open"- is UnsubscribeMethod.SendMail -> "Compose an unsubscribe email to ${method.address}?" to "Compose"- }- AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(R.string.unsubscribe)) }, text = { Text(message) }, confirmButton = { TextButton(onClick = onConfirm) { Text(confirmLabel) } }, dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(com.vayunmathur.library.ui.R.string.cancel)) } })-}--private fun performUnsubscribe(method: UnsubscribeMethod, context: Context, actions: MessageThreadActions, onCompose: (String, String) -> Unit) {- when (method) {- is UnsubscribeMethod.OneClickPost -> {- AppMessages.show(context.getString(R.string.unsubscribing))- actions.oneClickUnsubscribe(method.url) { ok -> AppMessages.show(if (ok) "Unsubscribed" else "Unsubscribe failed") }- }- is UnsubscribeMethod.OpenWeb -> {- val opened = runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, method.url.toUri())) }.isSuccess- if (!opened) AppMessages.show(context.getString(R.string.couldn_t_open_unsubscribe_page))- }- is UnsubscribeMethod.SendMail -> onCompose(method.address, "Unsubscribe")- }-}
email/src/main/java/com/vayunmathur/email/ui/MessageItem.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MessageItem.kt b/email/src/main/java/com/vayunmathur/email/ui/MessageItem.ktindex f6a87006a8..6b1bc694a2 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageItem.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageItem.kt@@ -47,19 +47,16 @@ import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.HtmlText import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconInbox import com.vayunmathur.library.ui.IconMarkRead import com.vayunmathur.library.ui.IconMarkUnread import com.vayunmathur.library.ui.IconMoreVert import com.vayunmathur.library.ui.IconSave import com.vayunmathur.library.ui.IconUndo import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.ModalBottomSheet import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.contentColorOn-import com.vayunmathur.library.ui.rememberModalBottomSheetState import com.vayunmathur.library.util.AppMessages /** Test tag on the HTML body view of the open message. */@@ -91,10 +88,10 @@ fun MessageItem( onCompose: (String, String) -> Unit, modifier: Modifier = Modifier, onExportEml: (EmailMessage) -> Unit = {},+ onShowUnsubscribe: (com.vayunmathur.email.data.UnsubscribeMethod) -> Unit = {},+ onShowMessageDetails: (EmailMessage) -> Unit = {}, ) { var attachments by remember { mutableStateOf<List<Attachment>>(emptyList()) }- var showDetails by remember { mutableStateOf(false) }- val sheetState = rememberModalBottomSheetState() LaunchedEffect(msg.id) { attachments = actions.getAttachments(msg.accountEmail, msg.id) if (msg.body == null) actions.fetchBodyIfNeeded(msg)@@ -103,12 +100,12 @@ fun MessageItem( val senderEmail = msg.from.substringAfter("<").substringBefore(">").trim() val avatarColor = Color(accountColor(msg.accountEmail)) val footer: @Composable ColumnScope.() -> Unit = {- MessageFooter(msg = msg, attachments = attachments, actions = actions, onBack = onBack, onReply = onReply, onForward = onForward, onCompose = onCompose)+ MessageFooter(msg = msg, attachments = attachments, actions = actions, onBack = onBack, onReply = onReply, onForward = onForward, onCompose = onCompose, onShowUnsubscribe = onShowUnsubscribe) } BoxWithConstraints(modifier.fillMaxSize()) { val footerMaxHeight = maxHeight * FOOTER_MAX_FRACTION Column(Modifier.fillMaxSize()) {- MessageHeader(msg, senderName, avatarColor, actions, onBack, onReply, onExportEml, onShowDetails = { showDetails = true })+ MessageHeader(msg, senderName, avatarColor, actions, onBack, onReply, onExportEml, onShowDetails = { onShowMessageDetails(msg) }) if (msg.isHtml && msg.body != null) { HtmlMessageBody(msg, msg.body, actions, footerMaxHeight, footer) } else {@@ -116,22 +113,6 @@ fun MessageItem( } } }- if (showDetails) {- ModalBottomSheet(onDismissRequest = { showDetails = false }, sheetState = sheetState) {- Column(modifier = Modifier.padding(16.dp).fillMaxWidth()) {- Text(text = msg.date, style = MaterialTheme.typography.labelSmall, modifier = Modifier.align(Alignment.End))- DetailItem(label = stringResource(R.string.from_label), name = senderName, email = senderEmail, avatarColor = avatarColor)- DetailItem(label = stringResource(R.string.to_label), name = "me", email = msg.to ?: "", avatarColor = MaterialTheme.colorScheme.surfaceVariant)- Spacer(Modifier.height(16.dp))- Row(verticalAlignment = Alignment.CenterVertically) {- IconInbox(modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)- Spacer(Modifier.width(12.dp))- Text(text = msg.folderName, style = MaterialTheme.typography.bodyMedium)- }- Spacer(Modifier.height(32.dp))- }- }- } } @Composable
email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.kt b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.ktindex 8324f50435..e2773d2f36 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.kt@@ -16,7 +16,9 @@ fun MessageThreadPage( onBack: () -> Unit, onReply: (String, String, String?) -> Unit, onForward: (String, String?) -> Unit,- onCompose: (String, String) -> Unit+ onCompose: (String, String) -> Unit,+ onShowUnsubscribe: (com.vayunmathur.email.data.UnsubscribeMethod) -> Unit = {},+ onShowMessageDetails: (com.vayunmathur.email.data.EmailMessage) -> Unit = {}, ) { val messages by viewModel.getThread(accountEmail, threadId).collectAsStateWithLifecycle(emptyList()) val context = LocalContext.current@@ -24,5 +26,5 @@ fun MessageThreadPage( LaunchedEffect(messages) { if (messages.isNotEmpty()) EmailNotifications.cancelForMessages(context, messages) }- MessageThreadScreen(messages = messages, actions = viewModel, threadId = threadId, onBack = onBack, onReply = onReply, onForward = onForward, onCompose = onCompose)+ MessageThreadScreen(messages = messages, actions = viewModel, threadId = threadId, onBack = onBack, onReply = onReply, onForward = onForward, onCompose = onCompose, onShowUnsubscribe = onShowUnsubscribe, onShowMessageDetails = onShowMessageDetails) }
email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.ktindex eb897c9217..c70dec484c 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt@@ -42,6 +42,8 @@ fun MessageThreadScreen( onReply: (String, String, String?) -> Unit = { _, _, _ -> }, onForward: (String, String?) -> Unit = { _, _ -> }, onCompose: (String, String) -> Unit = { _, _ -> },+ onShowUnsubscribe: (com.vayunmathur.email.data.UnsubscribeMethod) -> Unit = {},+ onShowMessageDetails: (EmailMessage) -> Unit = {}, ) { var hasMarkedAsRead by remember(threadId) { mutableStateOf(false) } var pendingExport by remember { mutableStateOf<EmailMessage?>(null) }@@ -108,6 +110,8 @@ fun MessageThreadScreen( onReply = onReply, onForward = onForward, onCompose = onCompose,+ onShowUnsubscribe = onShowUnsubscribe,+ onShowMessageDetails = onShowMessageDetails, onExportEml = { toExport -> pendingExport = toExport val fileName = EmlUtils.sanitizeFileName(toExport.subject.ifBlank { "email_${toExport.id}" })
email/src/main/java/com/vayunmathur/email/ui/NavigationEntries.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/NavigationEntries.kt b/email/src/main/java/com/vayunmathur/email/ui/NavigationEntries.ktindex 43387c7a5f..eac8c1cf94 100644--- a/email/src/main/java/com/vayunmathur/email/ui/NavigationEntries.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/NavigationEntries.kt@@ -44,8 +44,26 @@ internal fun EntryProviderScope<Route>.emailEntries( backStack.add(Route.Composer(subject = subject, body = quote)) }, onCompose = { to, sub -> backStack.add(Route.Composer(to = to, subject = sub)) },+ onShowUnsubscribe = { method -> backStack.add(unsubscribeRoute(method)) },+ onShowMessageDetails = { msg ->+ backStack.add(+ Route.MessageDetailsDialog(+ accountEmail = msg.accountEmail,+ senderName = com.vayunmathur.email.data.senderDisplayName(msg.from).ifEmpty { msg.from },+ senderEmail = msg.from.substringAfter("<").substringBefore(">").trim(),+ date = msg.date,+ folderName = msg.folderName,+ toEmail = msg.to ?: "",+ ),+ )+ }, ) }+ emailDialogEntries(+ backStack = backStack,+ actions = viewModel,+ onCompose = { to, sub -> backStack.add(Route.Composer(to = to, subject = sub)) },+ ) // Morph: a draft's subject line travels out of the drafts list into the subject field. // The other five ways in carry no draft id, so their subject key is null and the screen // simply crossfades.
email/src/main/java/com/vayunmathur/email/ui/OutboxContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/OutboxContent.kt b/email/src/main/java/com/vayunmathur/email/ui/OutboxContent.ktnew file mode 100644index 0000000000..bddbdbb15f--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/OutboxContent.kt@@ -0,0 +1,35 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.email.R+import com.vayunmathur.email.data.OutboxEntry+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.HorizontalDivider++/** Stateless outbox list slice, rendered by previews with fixed entries. */+@Composable+fun OutboxContent(+ outbox: List<OutboxEntry>,+ hasLoaded: Boolean,+ onDelete: (OutboxEntry) -> Unit,+ modifier: Modifier = Modifier,+) {+ if (!hasLoaded && outbox.isEmpty()) {+ Box(modifier.fillMaxSize())+ } else if (outbox.isEmpty()) {+ EmptyState(title = stringResource(R.string.outbox_is_empty), modifier = modifier.fillMaxSize())+ } else {+ LazyColumn(modifier = modifier.fillMaxSize()) {+ items(outbox, key = { it.id }) { entry ->+ OutboxRow(entry = entry, onDelete = { onDelete(entry) })+ HorizontalDivider()+ }+ }+ }+}
email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.ktindex 96f014df3d..be11756476 100644--- a/email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.kt@@ -61,36 +61,19 @@ fun OutboxScreen( } }, ) { padding ->- if (!hasLoaded && outbox.isEmpty()) {- // First load: empty placeholder under the scaffold's top indicator,- // never the empty state before loaded.- Box(Modifier.padding(padding).fillMaxSize())- } else if (outbox.isEmpty()) {- EmptyState(- title = stringResource(R.string.outbox_is_empty),- modifier = Modifier.padding(padding).fillMaxSize(),- )- } else {- LazyColumn(- modifier = Modifier.padding(padding).fillMaxSize(),- ) {- items(outbox, key = { it.id }) { entry ->- OutboxRow(- entry = entry,- onDelete = {- viewModel.send.deleteOutboxEntry(entry)- AppMessages.show(resources.getString(R.string.deleted_from_outbox))- },- )- HorizontalDivider()- }- }- }+ OutboxContent(+ outbox = outbox,+ hasLoaded = hasLoaded,+ onDelete = { entry ->+ viewModel.send.deleteOutboxEntry(entry)+ AppMessages.show(resources.getString(R.string.deleted_from_outbox))+ },+ modifier = Modifier.padding(padding),+ ) } }- @Composable-private fun OutboxRow(entry: OutboxEntry, onDelete: () -> Unit) {+internal fun OutboxRow(entry: OutboxEntry, onDelete: () -> Unit) { Column( modifier = Modifier .fillMaxWidth()
email/src/main/java/com/vayunmathur/email/ui/SettingsContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/SettingsContent.kt b/email/src/main/java/com/vayunmathur/email/ui/SettingsContent.ktnew file mode 100644index 0000000000..15f8df0567--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/SettingsContent.kt@@ -0,0 +1,90 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.email.R+import com.vayunmathur.email.data.BlockedSender+import com.vayunmathur.email.data.EmailAccount+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.R as UiR++/** Stateless settings slice, rendered by previews with fixed accounts. */+@Composable+fun SettingsContent(+ accounts: List<EmailAccount>,+ blocked: List<BlockedSender>,+ loadRemoteImages: Boolean,+ onLoadRemoteImagesChange: (Boolean) -> Unit,+ onSaveSignature: (String, String) -> Unit,+ onAllowInsecureChange: (String, Boolean) -> Unit,+ onUnblock: (String) -> Unit,+) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(stringResource(R.string.reading), style = MaterialTheme.typography.titleMedium)+ SettingsSwitchRow(+ title = stringResource(R.string.load_remote_images),+ supportingText = stringResource(R.string.load_remote_images_summary),+ checked = loadRemoteImages,+ onCheckedChange = onLoadRemoteImagesChange,+ )+ HorizontalDivider()+ Text(stringResource(R.string.signatures), style = MaterialTheme.typography.titleMedium)+ if (accounts.isEmpty()) {+ Text(stringResource(R.string.select_account))+ }+ accounts.forEach { acc ->+ var sig by remember(acc.email) { mutableStateOf(acc.signature) }+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(acc.email, style = MaterialTheme.typography.labelLarge)+ OutlinedTextField(+ value = sig,+ onValueChange = { sig = it },+ modifier = Modifier.fillMaxWidth(),+ minLines = 3,+ placeholder = { Text(stringResource(R.string.your_signature)) },+ )+ Button(+ onClick = { onSaveSignature(acc.email, sig) },+ modifier = Modifier.align(Alignment.End),+ ) { Text(stringResource(UiR.string.save)) }+ SettingsSwitchRow(+ title = stringResource(R.string.allow_insecure_certificates),+ supportingText = stringResource(R.string.allow_insecure_certificates_summary),+ checked = acc.allowInsecureCertificates,+ onCheckedChange = { onAllowInsecureChange(acc.email, it) },+ )+ }+ HorizontalDivider()+ }+ Text(stringResource(R.string.blocked_senders), style = MaterialTheme.typography.titleMedium)+ if (blocked.isEmpty()) {+ Text(stringResource(R.string.none), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ blocked.forEach { b ->+ ListItem(+ content = { Text(b.address) },+ trailingContent = {+ TextButton(onClick = { onUnblock(b.address) }) { Text(stringResource(R.string.unblock)) }+ },+ )+ HorizontalDivider()+ }+ }+}
email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.ktindex 03447886c2..b954678d51 100644--- a/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt@@ -36,70 +36,26 @@ import com.vayunmathur.library.ui.R as UiR @Composable fun SettingsScreen(viewModel: EmailViewModel, onBack: () -> Unit) { val accounts by viewModel.accounts.collectAsStateWithLifecycle(emptyList())+ val blocked by viewModel.blockedSenders.collectAsStateWithLifecycle(emptyList()) val context = LocalContext.current val resources = LocalResources.current+ val settings = remember(context) { com.vayunmathur.email.data.EmailSettings.get(context) }+ val loadRemoteImages by settings.loadRemoteImages.collectAsStateWithLifecycle() DetailScaffold( title = stringResource(UiR.string.settings), onNavigateBack = onBack, ) {- val settings = remember(context) { com.vayunmathur.email.data.EmailSettings.get(context) }- val loadRemoteImages by settings.loadRemoteImages.collectAsStateWithLifecycle()- Text(stringResource(R.string.reading), style = MaterialTheme.typography.titleMedium)- com.vayunmathur.library.ui.SettingsSwitchRow(- title = stringResource(R.string.load_remote_images),- supportingText = stringResource(R.string.load_remote_images_summary),- checked = loadRemoteImages,- onCheckedChange = { settings.setLoadRemoteImages(it) },+ SettingsContent(+ accounts = accounts,+ blocked = blocked,+ loadRemoteImages = loadRemoteImages,+ onLoadRemoteImagesChange = { settings.setLoadRemoteImages(it) },+ onSaveSignature = { email, sig ->+ viewModel.setSignature(email, sig)+ AppMessages.show(resources.getString(R.string.signature_saved))+ },+ onAllowInsecureChange = { email, v -> viewModel.setAllowInsecureCertificates(email, v) },+ onUnblock = { viewModel.unblockSender(it) }, )- HorizontalDivider()-- Text(stringResource(R.string.signatures), style = MaterialTheme.typography.titleMedium)- if (accounts.isEmpty()) {- Text(stringResource(R.string.select_account))- }- accounts.forEach { acc ->- var sig by remember(acc.email) { mutableStateOf(acc.signature) }- Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text(acc.email, style = MaterialTheme.typography.labelLarge)- OutlinedTextField(- value = sig,- onValueChange = { sig = it },- modifier = Modifier.fillMaxWidth(),- minLines = 3,- placeholder = { Text(stringResource(R.string.your_signature)) },- )- Button(- onClick = {- viewModel.setSignature(acc.email, sig)- AppMessages.show(resources.getString(R.string.signature_saved))- },- modifier = Modifier.align(Alignment.End),- ) {- Text(stringResource(UiR.string.save))- }- com.vayunmathur.library.ui.SettingsSwitchRow(- title = stringResource(R.string.allow_insecure_certificates),- supportingText = stringResource(R.string.allow_insecure_certificates_summary),- checked = acc.allowInsecureCertificates,- onCheckedChange = { viewModel.setAllowInsecureCertificates(acc.email, it) },- )- }- HorizontalDivider()- }-- val blocked by viewModel.blockedSenders.collectAsStateWithLifecycle(emptyList())- Text(stringResource(R.string.blocked_senders), style = MaterialTheme.typography.titleMedium)- if (blocked.isEmpty()) {- Text(stringResource(R.string.none), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- blocked.forEach { b ->- ListItem(- content = { Text(b.address) },- trailingContent = {- TextButton(onClick = { viewModel.unblockSender(b.address) }) { Text(stringResource(R.string.unblock)) }- },- )- HorizontalDivider()- } } }
email/src/main/java/com/vayunmathur/email/ui/dialogs/MessageDetailsDialogContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/dialogs/MessageDetailsDialogContent.kt b/email/src/main/java/com/vayunmathur/email/ui/dialogs/MessageDetailsDialogContent.ktnew file mode 100644index 0000000000..a047faab4b--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/dialogs/MessageDetailsDialogContent.kt@@ -0,0 +1,60 @@+package com.vayunmathur.email.ui.dialogs++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.email.R+import com.vayunmathur.email.data.accountColor+import com.vayunmathur.email.ui.DetailItem+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconInbox+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ModalBottomSheet+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberModalBottomSheetState++/** Stateless message-details sheet shown by the MessageDetailsDialog route. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun MessageDetailsDialogContent(+ accountEmail: String,+ senderName: String,+ senderEmail: String,+ date: String,+ folderName: String,+ toEmail: String,+ onDismiss: () -> Unit,+) {+ val sheetState = rememberModalBottomSheetState()+ val avatarColor = Color(accountColor(accountEmail))+ ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {+ Column(modifier = Modifier.padding(16.dp).fillMaxWidth()) {+ Text(text = date, style = MaterialTheme.typography.labelSmall, modifier = Modifier.align(Alignment.End))+ DetailItem(label = stringResource(R.string.from_label), name = senderName, email = senderEmail, avatarColor = avatarColor)+ DetailItem(+ label = stringResource(R.string.to_label),+ name = "me",+ email = toEmail,+ avatarColor = MaterialTheme.colorScheme.surfaceVariant,+ )+ Spacer(Modifier.height(16.dp))+ Row(verticalAlignment = Alignment.CenterVertically) {+ IconInbox(modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)+ Spacer(Modifier.width(12.dp))+ Text(text = folderName, style = MaterialTheme.typography.bodyMedium)+ }+ Spacer(Modifier.height(32.dp))+ }+ }+}
email/src/main/java/com/vayunmathur/email/ui/dialogs/UnsubscribeDialogContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/dialogs/UnsubscribeDialogContent.kt b/email/src/main/java/com/vayunmathur/email/ui/dialogs/UnsubscribeDialogContent.ktnew file mode 100644index 0000000000..2f2265d963--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/dialogs/UnsubscribeDialogContent.kt@@ -0,0 +1,32 @@+package com.vayunmathur.email.ui.dialogs++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.email.R+import com.vayunmathur.email.data.UnsubscribeMethod+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/** Stateless unsubscribe confirmation shown by the UnsubscribeDialog route. */+@Composable+fun UnsubscribeDialogContent(+ method: UnsubscribeMethod,+ onDismiss: () -> Unit,+ onConfirm: () -> Unit,+) {+ val (message, confirmLabel) = when (method) {+ is UnsubscribeMethod.OneClickPost -> "Send an unsubscribe request to the sender?" to "Unsubscribe"+ is UnsubscribeMethod.OpenWeb -> "Open the unsubscribe page in your browser?" to "Open"+ is UnsubscribeMethod.SendMail -> "Compose an unsubscribe email to ${method.address}?" to "Compose"+ }+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.unsubscribe)) },+ text = { Text(message) },+ confirmButton = { TextButton(onClick = onConfirm) { Text(confirmLabel) } },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(com.vayunmathur.library.ui.R.string.cancel)) }+ },+ )+}
email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt
diff --git a/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt b/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.ktindex b241078c54..de9c5098c7 100644--- a/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt+++ b/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt@@ -12,6 +12,22 @@ import com.vayunmathur.email.ui.AddAccountScreen import com.vayunmathur.email.ui.EmailDrawerContent import com.vayunmathur.email.ui.MessageListScreen import com.vayunmathur.email.ui.MessageThreadScreen+import com.vayunmathur.email.data.BlockedSender+import com.vayunmathur.email.data.DraftEntry+import com.vayunmathur.email.data.OutboxEntry+import com.vayunmathur.email.data.UnsubscribeMethod+import com.vayunmathur.email.platform.ParsedEml+import com.vayunmathur.email.ui.ComposerForm+import com.vayunmathur.email.ui.DraftsContent+import com.vayunmathur.email.ui.EmlViewerContent+import com.vayunmathur.email.ui.OutboxContent+import com.vayunmathur.email.ui.SettingsContent+import com.vayunmathur.email.ui.composer.EmailHtmlEditorController+import com.vayunmathur.email.ui.dialogs.MessageDetailsDialogContent+import com.vayunmathur.email.ui.dialogs.UnsubscribeDialogContent+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.ui.platform.LocalContext+import androidx.compose.runtime.remember import com.vayunmathur.email.platform.MessageListActions import com.vayunmathur.email.platform.MessageListUiState import com.vayunmathur.email.platform.MessageThreadActions@@ -50,17 +66,16 @@ private const val EXPANDED = "spec:width=1280dp,height=800dp,dpi=240" * JUnit tests and needs a real class to attach them to — top-level functions land in a * synthetic `…Kt` facade and are silently skipped. *- * Coverage: `MessageList` (inbox/search/drawer), `MessageThread` (detail) and- * `AddAccount` + `AddAccountForm` on phone, plus the thread on large-tablet.- * Exceptions: `Composer` hosts an `AndroidView` HTML editor (WebView) which- * Layoutlib cannot render; `Outbox`, `Drafts` and `Settings` have no stateless- * slice (EmailViewModel + Room/DataStore), and `EmlViewer` reads a SAF URI's- * bytes — none can be shown honestly from literals.+ * Coverage: every route has a capture. `MessageList` (list/search/drawer),+ * `MessageThread`, `AddAccount` + `AddAccountForm`, `Composer`, `Outbox`,+ * `Drafts`, `Settings`, the plain-text `EmlViewer` slice, and the+ * `UnsubscribeDialog` / `MessageDetailsDialog` dialog routes are rendered+ * from fixed literals through their stateless slices. */ class MetadataPreviews { @PreviewTest- @Preview(name = "1-inbox", device = PHONE, group = "phone", showSystemUi = true)+ @Preview(name = "1-message-list", device = PHONE, group = "phone", showSystemUi = true) @Composable fun Preview1Inbox() { DynamicTheme(darkTheme = true) {@@ -74,7 +89,7 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "2-conversation", device = PHONE, group = "phone", showSystemUi = true)+ @Preview(name = "2-message-thread", device = PHONE, group = "phone", showSystemUi = true) @Composable fun Preview2Conversation() { DynamicTheme(darkTheme = true) {@@ -115,7 +130,7 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "8-inbox-expanded", device = EXPANDED, group = "large-tablet", showSystemUi = true)+ @Preview(name = "8-message-list-expanded", device = EXPANDED, group = "large-tablet", showSystemUi = true) @Composable fun Preview8InboxExpanded() { DynamicTheme(darkTheme = true) {@@ -136,7 +151,7 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "5-conversation-expanded", device = EXPANDED, group = "large-tablet", showSystemUi = true)+ @Preview(name = "5-message-thread-expanded", device = EXPANDED, group = "large-tablet", showSystemUi = true) @Composable fun Preview5ConversationExpanded() { DynamicTheme(darkTheme = true) {@@ -185,6 +200,129 @@ class MetadataPreviews { } } }++ @PreviewTest+ @Preview(name = "9-composer", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview9Composer() {+ DynamicTheme(darkTheme = true) {+ val account = EmailAccount(email = WORK, signature = "Sam")+ val controller = remember { EmailHtmlEditorController("<p>Thanks for the update.</p>") }+ ComposerForm(+ padding = PaddingValues(),+ accounts = listOf(account),+ fromAccount = account,+ showAccountPicker = false,+ onOpenAccountPicker = {},+ onDismissAccountPicker = {},+ onSelectAccount = {},+ to = "[email protected]",+ onToChange = {},+ cc = "",+ onCcChange = {},+ bcc = "",+ onBccChange = {},+ showCcBcc = false,+ onToggleCcBcc = {},+ onPickContact = {},+ subject = "Re: Northgate rebrand",+ onSubjectChange = {},+ draftId = null,+ bodyController = controller,+ context = LocalContext.current,+ attachments = emptyList(),+ onRemoveAttachment = {},+ )+ }+ }++ @PreviewTest+ @Preview(name = "10-outbox", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview10Outbox() {+ DynamicTheme(darkTheme = true) {+ OutboxContent(+ outbox = listOf(+ OutboxEntry(id = 1, accountEmail = WORK, to = "[email protected]", subject = "Rebrand files", body = "Attached are the final files.", createdAt = 1785566534600, attemptCount = 1),+ ),+ hasLoaded = true,+ onDelete = {},+ )+ }+ }++ @PreviewTest+ @Preview(name = "11-drafts", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview11Drafts() {+ DynamicTheme(darkTheme = true) {+ DraftsContent(+ drafts = listOf(+ DraftEntry(id = 1, accountEmail = WORK, to = "[email protected]", subject = "Trail run", body = "Thinking of Saturday morning.", updatedAt = 1785566534600),+ ),+ hasLoaded = true,+ onOpenDraft = {},+ onDelete = {},+ )+ }+ }++ @PreviewTest+ @Preview(name = "12-settings", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview12Settings() {+ DynamicTheme(darkTheme = true) {+ SettingsContent(+ accounts = listOf(EmailAccount(email = WORK, signature = "Sam Whitfield")),+ blocked = listOf(BlockedSender(address = "[email protected]")),+ loadRemoteImages = false,+ onLoadRemoteImagesChange = {},+ onSaveSignature = { _, _ -> },+ onAllowInsecureChange = { _, _ -> },+ onUnblock = {},+ )+ }+ }++ @PreviewTest+ @Preview(name = "13-eml-viewer", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview13EmlViewer() {+ DynamicTheme(darkTheme = true) {+ EmlViewerContent(+ parsed = ParsedEml(+ message = message(WORK, 7001, "Signed copy", "Hannah Boyce <[email protected]>", "Mon Jul 27 10:05:52 GMT 2026", "Both parties have now signed."),+ emlAttachments = emptyList(),+ ),+ )+ }+ }++ @PreviewTest+ @Preview(name = "14-unsubscribe-dialog", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview14UnsubscribeDialog() {+ DynamicTheme(darkTheme = true) {+ UnsubscribeDialogContent(method = UnsubscribeMethod.OpenWeb("https://example.com/unsubscribe"), onDismiss = {}, onConfirm = {})+ }+ }++ @PreviewTest+ @Preview(name = "15-message-details-dialog", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview15MessageDetailsDialog() {+ DynamicTheme(darkTheme = true) {+ MessageDetailsDialogContent(+ accountEmail = WORK,+ senderName = "Priya Raman",+ senderEmail = "[email protected]",+ date = "Tue Jul 28 09:14:02 GMT 2026",+ folderName = "INBOX",+ toEmail = WORK,+ onDismiss = {},+ )+ }+ } } private const val ME = "[email protected]"
email/src/test/java/com/vayunmathur/email/ui/MessageItemBranchesW5Test.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/MessageItemBranchesW5Test.kt b/email/src/test/java/com/vayunmathur/email/ui/MessageItemBranchesW5Test.ktindex c9eb8c1efe..1d0c76ea2f 100644--- a/email/src/test/java/com/vayunmathur/email/ui/MessageItemBranchesW5Test.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/MessageItemBranchesW5Test.kt@@ -9,6 +9,11 @@ import androidx.compose.ui.test.performClick import com.vayunmathur.email.data.Attachment import com.vayunmathur.email.data.EmailMessage import com.vayunmathur.email.platform.MessageThreadActions+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.email.ui.dialogs.UnsubscribeDialogContent+import com.vayunmathur.email.data.UnsubscribeMethod import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue@@ -70,6 +75,8 @@ class MessageItemBranchesW5Test { backs: MutableList<Unit> = mutableListOf(), ) { rule.setContent {+ val pending = remember { mutableStateOf<UnsubscribeMethod?>(null) }+ val context = LocalContext.current MessageItem( msg = message, actions = actions, onBack = { backs += Unit },@@ -77,7 +84,18 @@ class MessageItemBranchesW5Test { onForward = { subject, _ -> forwards += subject }, onCompose = { to, subject -> composed += to to subject }, onExportEml = { exported += it },+ onShowUnsubscribe = { pending.value = it }, )+ pending.value?.let { method ->+ UnsubscribeDialogContent(+ method = method,+ onDismiss = { pending.value = null },+ onConfirm = {+ pending.value = null+ performUnsubscribe(method, context, actions) { to, subject -> composed += to to subject }+ },+ )+ } } rule.waitForIdle() }
email/src/test/java/com/vayunmathur/email/ui/MessageThreadScreenTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/MessageThreadScreenTest.kt b/email/src/test/java/com/vayunmathur/email/ui/MessageThreadScreenTest.ktindex 18fddd4f12..9f55d893f3 100644--- a/email/src/test/java/com/vayunmathur/email/ui/MessageThreadScreenTest.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/MessageThreadScreenTest.kt@@ -16,6 +16,13 @@ import androidx.test.core.app.ApplicationProvider import com.vayunmathur.email.data.Attachment import com.vayunmathur.email.data.EmailMessage import com.vayunmathur.email.platform.MessageThreadActions+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.email.data.UnsubscribeMethod+import com.vayunmathur.email.ui.dialogs.UnsubscribeDialogContent import java.io.File import kotlin.test.Test import kotlin.test.assertEquals@@ -92,6 +99,30 @@ class MessageThreadScreenTest { listUnsubscribePost = listUnsubscribePost, ) ++ /** Hosts the unsubscribe dialog route content the way EmailDialogEntries does. */+ @androidx.compose.runtime.Composable+ private fun UnsubscribeHost(+ actions: MessageThreadActions,+ onCompose: (String, String) -> Unit = { _, _ -> },+ onShow: (androidx.compose.runtime.MutableState<UnsubscribeMethod?>) -> Unit = {},+ ): androidx.compose.runtime.MutableState<UnsubscribeMethod?> {+ val pending = remember { mutableStateOf<UnsubscribeMethod?>(null) }+ onShow(pending)+ val context = LocalContext.current+ pending.value?.let { method ->+ UnsubscribeDialogContent(+ method = method,+ onDismiss = { pending.value = null },+ onConfirm = {+ pending.value = null+ performUnsubscribe(method, context, actions, onCompose)+ },+ )+ }+ return pending+ }+ @Test fun `thread renders subject and message bodies`() { composeRule.setContent {@@ -229,6 +260,7 @@ class MessageThreadScreenTest { fun `unsubscribe flow confirms and posts one-click`() { val actions = FakeActions() composeRule.setContent {+ val pending = UnsubscribeHost(actions) MessageThreadScreen( messages = listOf( msg(@@ -238,6 +270,7 @@ class MessageThreadScreenTest { ) ), actions = actions,+ onShowUnsubscribe = { pending.value = it }, ) } composeRule.onNodeWithText("Unsubscribe").performScrollTo()@@ -256,6 +289,7 @@ class MessageThreadScreenTest { fun `unsubscribe confirm posts the one-click request`() { val actions = FakeActions() composeRule.setContent {+ val pending = UnsubscribeHost(actions) MessageThreadScreen( messages = listOf( msg(@@ -265,6 +299,7 @@ class MessageThreadScreenTest { ) ), actions = actions,+ onShowUnsubscribe = { pending.value = it }, ) } composeRule.onNodeWithText("Unsubscribe").performScrollTo()@@ -282,10 +317,13 @@ class MessageThreadScreenTest { fun `unsubscribe by mail routes to the composer`() { var composed: Pair<String, String>? = null composeRule.setContent {+ val actions2 = FakeActions()+ val pending = UnsubscribeHost(actions2, onCompose = { address, subject -> composed = address to subject }) MessageThreadScreen( messages = listOf(msg(1L, listUnsubscribe = "<mailto:[email protected]>")),- actions = FakeActions(),+ actions = actions2, onCompose = { address, subject -> composed = address to subject },+ onShowUnsubscribe = { pending.value = it }, ) } composeRule.onNodeWithText("Unsubscribe").performScrollTo()@@ -300,9 +338,12 @@ class MessageThreadScreenTest { @Test fun `unsubscribe by web opens the browser intent`() { composeRule.setContent {+ val actions2 = FakeActions()+ val pending = UnsubscribeHost(actions2) MessageThreadScreen( messages = listOf(msg(1L, listUnsubscribe = "<https://x.com/leave>")),- actions = FakeActions(),+ actions = actions2,+ onShowUnsubscribe = { pending.value = it }, ) } composeRule.onNodeWithText("Unsubscribe").performScrollTo()