email: give the open message a self-scrolling body pane (#900)
- Commit
41bc5dca3febe5e93e8296a6f21a0567e84b4263- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-12 04:43 UTC (24 days ago)
- Parents
3038373
Symptom (#900, two reporters, v2.6.11b and several earlier versions,
Pixel 10 / Pixel 10 Pro): in portrait, scrolling a long email stops
after a few pixels. Landscape works, and rotating to landscape, scrolling
and rotating back is the reported workaround.
Suspected root cause (not reproduced on a device, so treat as a
hypothesis): the thread screen put each HTML body in a wrap-content
WebView inside the thread's LazyColumn. That setup dates from July
(575e77627) and only works if the WebView reports a height equal to its
laid-out content. HtmlText sets useWideViewPort, and the stylesheet
only capped img/table widths, so fixed-width newsletter HTML (~600 CSS
px) overflows a ~410dp portrait viewport. The zoomed-out layout height
and the height the WebView measures to then disagree. The WebView ends
up much shorter than its content, so the list runs out of scroll range
almost at once. In landscape the content fits the wider viewport and
the two heights agree. Triage ruled out the WebView grabbing the
gesture, Compose's interop touch handling, the drawer/scaffold
handlers and reload loops.
The fix does not depend on that mechanism being right: no layout asks
the WebView for its content height any more, and nothing scrolls on the
same axis around it.
Changes
- Thread screen: no outer vertical scroller. The pane shows one open
message filling the remaining height. When the thread has more than
one message, a compact selectable strip above it lists every message
(sender, date, snippet; capped at 30% of the pane, scrolls on its
own) and tapping a row opens that message. A thread opens on its
oldest unread message, else the newest. The selection is saved
across rotation, and marking mail read on open does not move it.
- MessageItem (moved to its own file, as the one-public-composable
rule and the 350-line UI file cap require) is laid out as header /
body / footer. An HTML body is a WebView with
`Modifier.weight(1f)` that scrolls internally; the footer (quote
toggle, attachments, Reply/Forward, Unsubscribe/Block) sits below it,
capped at 40% of the pane and scrolling on its own past that. A
plain-text body scrolls together with its footer, as before. The
footer moved to MessageFooter.kt and the strip lives in
ThreadMessageStrip.kt.
- .eml viewer: same treatment, since it nested a wrap-content WebView
in a verticalScroll column the same way.
- HtmlText (library/ui) gets two new parameters. Both default to
false, so the old behaviour is unchanged for other callers:
- `scrollInternally`: MATCH_PARENT layout params so the view fills
the bounded height it is given, a vertical scrollbar, and
pinch-zoom (built-in zoom without on-screen buttons).
- `fitContentToWidth`: a viewport that still opens at
width=device-width, initial-scale=1 (14px body text stays 14px)
but allows pinch from 0.25x to 5x, and the sender's own viewport
tags are stripped so e.g. `width=600` cannot override it. CSS caps
the common containers (div, p, table, center, section, ...,
img/video/iframe/svg) at max-width:100% and resets inline
min-width on table/td/th/div, and td/th/a get overflow-wrap:anywhere
so long URLs break instead of widening the page.
The document wrapper moved to a pure HtmlTextDocument object so it
can be unit-tested. With both flags off its output is unchanged
apart from whitespace.
- HtmlText now reloads only when the document (or the image/JS
settings) actually changes, instead of on every run of the
AndroidView update block. This helps every caller: an identical
reload resets the reader's scroll position and re-measures the view
mid-read. Callers checked: email MessageThreadScreen and
EmlViewerScreen (both switched to the new modes here), and
securemail MessageBodyView (unchanged; it keeps the inline defaults
and only gains the redundant-reload guard).
Alternatives considered
- Bounded-height WebView per message inside the LazyColumn, with
nested-scroll handoff: rejected. Chromium's WebView does not
implement NestedScrollingChild. It scrolls on the compositor thread,
so a shim cannot know synchronously how much of a drag it consumed,
and its flings cannot be handed to the parent. Compose's scrollable
parent also takes over a drag at touch slop and cancels the
WebView's gesture unless the WebView claims it. The result would
depend on exactly the kind of WebView/Compose gesture interplay that
is unverifiable here.
- Collapsing header rendered inside the WebView: would need the header
and actions in HTML plus script or JS bridges, which received mail
should not have.
- Measuring the content height via JS / getContentHeight and sizing
the WebView to it: that is the number suspected to be wrong.
User-visible effect
- A long email scrolls smoothly in portrait inside its own pane, with a
scrollbar. Header and actions stay put, and pinch-zoom works on
the body.
- Wide newsletters fit the screen width at normal text size instead of
overflowing. Anything that still cannot shrink can be panned or
pinched.
- Threads show one message at a time with a strip to switch between
messages, instead of every message expanded in one long list.
- Short emails leave empty space below the body, because the body
pane always fills the screen.
Verification (toolchain container, gbuild.sh)
- :email:compileDevKotlin, :library:ui:compileDebugKotlin: pass.
- :email:testDevUnitTest: all thread, layout and EML viewer tests pass.
New MessageThreadLayoutTest (portrait w411dp-h891dp) checks that the
HTML body node has no vertically scrollable ancestor (the old
LazyColumn exposes a scroll action, so the old layout would fail
this), fills more than 40% of the screen even though Robolectric
reports a 0 content height (the old wrap-content view would
collapse), is MATCH_PARENT with a scrollbar, loads the
fit-to-width CSS, and that the strip selects and switches messages.
MessageThreadScreenTest was updated for the strip and for header
controls that no longer sit in a scroller. All email unit tests
pass on the final run (523).
- :library:ui:testDebugUnitTest (HtmlText*): new HtmlTextDocumentTest
(wrapper, fit CSS, viewport stripping) and HtmlTextScrollModeTest
(default stays inline wrap-content; scrollInternally fills its
bounds; an unchanged document is not reloaded; a changed one is)
pass, as does the existing HtmlTextComposeSlice1Test.
- :email:lint: pass. :email:detekt: the same 11 findings as on main,
none in touched files. :library:ui:detekt: the same single finding
as on main (LargeClass in IconsSliceTest.kt), nothing new.
Needs on-device confirmation (not tested on hardware)
- Portrait on a Pixel: open a long, fixed-width newsletter and a long
plain reply. Both should scroll to the end with no stall, fling
smoothly, show text at normal size, and pinch-zoom on the HTML body.
- A multi-message thread: the strip switches messages, rotation keeps
the open message, and Reply/Forward/Unsubscribe/Block and
attachments still work from the footer.
- An .eml file opened from Files renders and scrolls the same way.Diff
email/AGENTS.md
diff --git a/email/AGENTS.md b/email/AGENTS.mdindex ff1401861e..b3c68c1c5e 100644--- a/email/AGENTS.md+++ b/email/AGENTS.md@@ -85,7 +85,10 @@ _Install: ./install email (dev by default)._ ### ui/ — list, thread, composer, account flows - com/vayunmathur/email/ui/MainContent.kt - com/vayunmathur/email/ui/MessageListScreen.kt-- com/vayunmathur/email/ui/MessageThreadScreen.kt+- com/vayunmathur/email/ui/MessageThreadScreen.kt — thread pane: strip + one open message, no outer scroller (#900)+- com/vayunmathur/email/ui/ThreadMessageStrip.kt+- com/vayunmathur/email/ui/MessageItem.kt — header / self-scrolling body / footer+- com/vayunmathur/email/ui/MessageFooter.kt - com/vayunmathur/email/ui/FolderList.kt - com/vayunmathur/email/ui/DetailItem.kt - com/vayunmathur/email/ui/ComposerScreen.kt
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 0b4a511cea..f2fede1522 100644--- a/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt@@ -6,12 +6,14 @@ import android.net.Uri import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box+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.layout.size import androidx.compose.foundation.rememberScrollState@@ -136,62 +138,80 @@ fun EmlViewerScreen( val emlAtts = parsed!!.emlAttachments val cidMap = parsed!!.inlineCidMap - Column(- modifier = Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()),- ) {- val senderName = senderDisplayName(msg.from).ifEmpty { msg.from }- val senderEmail = msg.from.substringAfter("<").substringBefore(">").trim()- val initial = senderName.take(1).uppercase()- val avatarColor = Color(accountColor(msg.from.ifBlank { "eml-viewer" }))-- Row(modifier = Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically) {- Surface(shape = CircleShape, color = avatarColor, modifier = Modifier.size(40.dp)) {- Box(contentAlignment = Alignment.Center) {- Text(text = initial, color = contentColorOn(avatarColor), style = MaterialTheme.typography.titleMedium)+ // 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)) }+ } }- }- Column(modifier = Modifier.weight(1f).padding(horizontal = 12.dp)) {- Text(text = senderName, style = MaterialTheme.typography.titleSmall, maxLines = 1)- Text(text = msg.date, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- if (!msg.to.isNullOrBlank()) Text(text = stringResource(R.string.to, msg.to), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- if (!msg.cc.isNullOrBlank()) Text(text = stringResource(R.string.cc_1, msg.cc), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- }-- Text(text = msg.subject, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 16.dp))- Spacer(Modifier.height(12.dp))-- 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,+ 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)) } }- HtmlText(- html = msg.body,- blockRemoteImages = !loadImages && cidMap.isEmpty(),- cidMap = cidMap,- modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),- )- } else {- Text(text = msg.body ?: stringResource(R.string.no_content_1), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) }+ }+ }+ }+ }+} - if (emlAtts.isNotEmpty()) {- Spacer(Modifier.height(16.dp))- Text(stringResource(R.string.attachments_2), style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(horizontal = 16.dp))- emlAtts.forEach { att -> EmlAttachmentItem(attachment = att) }- }+/** 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 - Spacer(Modifier.height(24.dp))- }+@Composable+private 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) {+ Surface(shape = CircleShape, color = avatarColor, modifier = Modifier.size(40.dp)) {+ Box(contentAlignment = Alignment.Center) {+ Text(text = senderName.take(1).uppercase(), color = contentColorOn(avatarColor), style = MaterialTheme.typography.titleMedium) } }+ Column(modifier = Modifier.weight(1f).padding(horizontal = 12.dp)) {+ Text(text = senderName, style = MaterialTheme.typography.titleSmall, maxLines = 1)+ Text(text = date, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ if (!to.isNullOrBlank()) Text(text = stringResource(R.string.to, to), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ if (!cc.isNullOrBlank()) Text(text = stringResource(R.string.cc_1, cc), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ } }+ Text(text = subject, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 16.dp))+ Spacer(Modifier.height(12.dp))+}++@Composable+private 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))+ attachments.forEach { att -> EmlAttachmentItem(attachment = att) } } @Composable
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.ktnew file mode 100644index 0000000000..f2eeff23f2--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageFooter.kt@@ -0,0 +1,103 @@+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+import androidx.compose.foundation.layout.Spacer+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+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.AppMessages++/**+ * Everything under a message body: its attachments, the Reply/Forward row,+ * and Unsubscribe (when the message offers one) and Block sender.+ */+@Composable+fun MessageFooter(+ msg: EmailMessage,+ attachments: List<Attachment>,+ actions: MessageThreadActions,+ onBack: () -> Unit,+ onReply: (String, String, String?) -> Unit,+ onForward: (String, String?) -> Unit,+ onCompose: (String, String) -> Unit,+) {+ val context = LocalContext.current+ val resources = LocalResources.current+ if (attachments.isNotEmpty()) {+ Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {+ Text(stringResource(R.string.attachments_2), style = MaterialTheme.typography.labelLarge)+ attachments.forEach { att -> AttachmentItem(att, actions) }+ }+ }+ Row(modifier = Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(onClick = { onReply(msg.from, msg.subject, msg.serverId) }, modifier = Modifier.weight(1f)) {+ IconUndo(modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.reply))+ }+ OutlinedButton(onClick = { onForward(msg.subject, msg.body) }, modifier = Modifier.weight(1f)) {+ IconForward(modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.forward))+ }+ }+ 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 = { 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.ktnew file mode 100644index 0000000000..3d12def5a9--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageItem.kt@@ -0,0 +1,267 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+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.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+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.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalResources+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.email.R+import com.vayunmathur.email.data.Attachment+import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.EmailSettings+import com.vayunmathur.email.data.accountColor+import com.vayunmathur.email.data.senderDisplayName+import com.vayunmathur.email.platform.MessageThreadActions+import com.vayunmathur.library.ui.DropdownMenu+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. */+internal const val MESSAGE_HTML_BODY_TAG = "message-html-body"++/** Share of the message pane the footer (quotes, attachments, actions) may take before it scrolls. */+private const val FOOTER_MAX_FRACTION = 0.4f++/**+ * One message, laid out to fill the height it is given: the sender header on+ * top, the body in the middle taking all remaining space, and the footer+ * (quote toggle, attachments, reply/forward, unsubscribe/block) below.+ *+ * The body scrolls itself and nothing around it scrolls on the same axis+ * (#900). An HTML body is a WebView that fills its slot and scrolls+ * internally; it is never wrap-content inside a scrolling list, which needed+ * the WebView to report its full content height and broke portrait scrolling+ * on wide newsletters when it didn't. A plain-text body is ordinary Compose+ * text and scrolls together with its footer.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun MessageItem(+ msg: EmailMessage,+ actions: MessageThreadActions,+ onBack: () -> Unit,+ onReply: (String, String, String?) -> Unit,+ onForward: (String, String?) -> Unit,+ onCompose: (String, String) -> Unit,+ onExportEml: (EmailMessage) -> Unit = {},+ modifier: Modifier = Modifier,+) {+ 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)+ }+ val senderName = senderDisplayName(msg.from).ifEmpty { msg.from }+ 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)+ }+ BoxWithConstraints(modifier.fillMaxSize()) {+ val footerMaxHeight = maxHeight * FOOTER_MAX_FRACTION+ Column(Modifier.fillMaxSize()) {+ MessageHeader(msg, senderName, avatarColor, actions, onBack, onReply, onExportEml, onShowDetails = { showDetails = true })+ if (msg.isHtml && msg.body != null) {+ HtmlMessageBody(msg, msg.body, actions, footerMaxHeight, footer)+ } else {+ PlainMessageBody(msg, footer)+ }+ }+ }+ 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+private fun MessageHeader(+ msg: EmailMessage,+ senderName: String,+ avatarColor: Color,+ actions: MessageThreadActions,+ onBack: () -> Unit,+ onReply: (String, String, String?) -> Unit,+ onExportEml: (EmailMessage) -> Unit,+ onShowDetails: () -> Unit,+) {+ val resources = LocalResources.current+ var showOverflow by remember { mutableStateOf(false) }+ Row(modifier = Modifier.fillMaxWidth().clickable(onClick = onShowDetails).padding(16.dp), verticalAlignment = Alignment.CenterVertically) {+ Surface(shape = CircleShape, color = avatarColor, modifier = Modifier.size(40.dp)) {+ Box(contentAlignment = Alignment.Center) { Text(text = senderName.take(1).uppercase(), color = contentColorOn(avatarColor), style = MaterialTheme.typography.titleMedium) }+ }+ Column(modifier = Modifier.weight(1f).padding(horizontal = 12.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(text = senderName, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))+ Text(text = " \u2022 ${msg.date.substringBeforeLast(":")}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ Text(text = stringResource(R.string.to_me), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ Row(verticalAlignment = Alignment.CenterVertically) {+ var showSnooze by remember { mutableStateOf(false) }+ Box {+ TextButton(onClick = { showSnooze = true }) { Text(stringResource(R.string.snooze)) }+ DropdownMenu(expanded = showSnooze, onDismissRequest = { showSnooze = false }) {+ val snooze = { at: Long ->+ showSnooze = false+ actions.snoozeMessage(msg.accountEmail, msg.folderName, msg.id, at)+ AppMessages.show(resources.getString(R.string.snoozed))+ onBack()+ }+ DropdownMenuItem(text = { Text(stringResource(R.string.later_today_6_pm)) }, onClick = { snooze(scheduleTime(18, sameDay = true)) })+ DropdownMenuItem(text = { Text(stringResource(R.string.tomorrow_8_am)) }, onClick = { snooze(scheduleTime(8, sameDay = false)) })+ DropdownMenuItem(text = { Text(stringResource(R.string.in_1_week)) }, onClick = { snooze(System.currentTimeMillis() + 7L * 24 * 3600_000) })+ }+ }+ IconButton(onClick = { onReply(msg.from, msg.subject, msg.serverId) }) { IconUndo() }+ IconButton(onClick = { actions.markAsRead(msg.accountEmail, msg.folderName, msg.id, !msg.isRead); if (msg.isRead) onBack() }) {+ if (msg.isRead) IconMarkUnread() else IconMarkRead()+ }+ Box {+ IconButton(onClick = { showOverflow = true }) { IconMoreVert() }+ DropdownMenu(expanded = showOverflow, onDismissRequest = { showOverflow = false }) {+ DropdownMenuItem(text = { Text(stringResource(R.string.save_as_eml)) }, leadingIcon = { IconSave(modifier = Modifier.size(20.dp)) }, onClick = { showOverflow = false; onExportEml(msg) })+ }+ }+ }+ }+}++/**+ * Remote-images banner, then the WebView filling every pixel the header and+ * footer leave, then the footer capped at [footerMaxHeight] (it scrolls on its+ * own past that, so a long attachment list can't squeeze the body away).+ */+@Composable+private fun ColumnScope.HtmlMessageBody(+ msg: EmailMessage,+ body: String,+ actions: MessageThreadActions,+ footerMaxHeight: Dp,+ footer: @Composable ColumnScope.() -> Unit,+) {+ val context = LocalContext.current+ val settings = remember(context) { EmailSettings.get(context) }+ val loadRemoteByDefault by settings.loadRemoteImages.collectAsStateWithLifecycle()+ var loadImages by remember(msg.id, loadRemoteByDefault) { mutableStateOf(loadRemoteByDefault) }+ var showQuotes by remember(msg.id) { mutableStateOf(false) }+ var cidMap by remember(msg.id) { mutableStateOf<Map<String, java.io.File>>(emptyMap()) }+ val bodyHasCid = remember(body) { body.contains("cid:", ignoreCase = true) }+ LaunchedEffect(msg.id, body) { if (bodyHasCid) { val map = actions.loadCidMap(context, msg); if (map.isNotEmpty()) cidMap = map } }+ val hasQuotes = remember(body) { listOf("gmail_quote", "yahoo_quoted", "moz-cite-prefix", "<blockquote").any { body.contains(it, ignoreCase = true) } }+ val remoteBlocked = !loadImages && cidMap.isEmpty() && !bodyHasCid+ if (remoteBlocked) {+ 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 = body,+ blockRemoteImages = remoteBlocked,+ hideQuotes = hasQuotes && !showQuotes,+ cidMap = cidMap,+ scrollInternally = true,+ fitContentToWidth = true,+ // 8dp here plus the document's 8px body padding lines text up with the+ // 16dp header while leaving fixed-width mail as much width as possible.+ modifier = Modifier.weight(1f).fillMaxWidth().padding(horizontal = 8.dp).testTag(MESSAGE_HTML_BODY_TAG),+ )+ Column(Modifier.fillMaxWidth().heightIn(max = footerMaxHeight).verticalScroll(rememberScrollState())) {+ if (hasQuotes) {+ TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) { Text(if (showQuotes) stringResource(R.string.hide_quoted_text) else stringResource(R.string.show_quoted_text)) }+ }+ footer()+ }+}++/** Plain text is ordinary Compose text: it and the footer scroll together below the header. */+@Composable+private fun ColumnScope.PlainMessageBody(msg: EmailMessage, footer: @Composable ColumnScope.() -> Unit) {+ var showQuotes by remember(msg.id) { mutableStateOf(false) }+ val (mainText, quotedText) = remember(msg.body) { splitQuotedText(msg.body ?: "(No Content)") }+ Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {+ Text(text = if (showQuotes || quotedText.isEmpty()) (msg.body ?: stringResource(R.string.no_content)) else mainText, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp))+ if (quotedText.isNotEmpty()) {+ TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) { Text(if (showQuotes) stringResource(R.string.hide_quoted_text) else stringResource(R.string.show_quoted_text)) }+ }+ footer()+ }+}++private fun splitQuotedText(body: String): Pair<String, String> {+ val lines = body.split("\n")+ val onWrote = Regex("^On .+ wrote:\\s*$")+ val origMsg = Regex("^-{2,}\\s*Original Message\\s*-{2,}\\s*$", RegexOption.IGNORE_CASE)+ for (i in lines.indices) {+ val line = lines[i].trim()+ val isBoundary = onWrote.matches(line) || origMsg.matches(line) || line.startsWith(">")+ if (isBoundary && i > 0) {+ val main = lines.subList(0, i).joinToString("\n").trimEnd()+ val quoted = lines.subList(i, lines.size).joinToString("\n")+ return main to quoted+ }+ }+ return body to ""+}
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 26d6cf3899..e31e689080 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt@@ -1,80 +1,34 @@ package com.vayunmathur.email.ui -import android.content.Intent import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.PaddingValues-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.layout.size-import androidx.compose.foundation.layout.width-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.graphics.Color-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 androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.email.R-import com.vayunmathur.email.data.Attachment import com.vayunmathur.email.data.EmailMessage-import com.vayunmathur.email.data.EmailSettings-import com.vayunmathur.email.data.accountColor-import com.vayunmathur.email.data.detectUnsubscribe-import com.vayunmathur.email.data.senderDisplayName import com.vayunmathur.email.platform.EmailViewModel import com.vayunmathur.email.platform.EmlUtils import com.vayunmathur.email.platform.MessageThreadActions-import com.vayunmathur.email.data.UnsubscribeMethod-import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DesktopMaxWidthContainer-import com.vayunmathur.library.ui.DropdownMenu-import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.HtmlText-import com.vayunmathur.library.ui.IconAttachment-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconClose-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconDownload-import com.vayunmathur.library.ui.IconForward-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.IconNavigation-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.OutlinedButton-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.ui.appBarScrollBehavior import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.sharedText@@ -105,7 +59,6 @@ fun MessageThreadScreen( onCompose: (String, String) -> Unit = { _, _ -> }, ) { var hasMarkedAsRead by remember(threadId) { mutableStateOf(false) }- val context = LocalContext.current var pendingExport by remember { mutableStateOf<EmailMessage?>(null) } val exportLauncher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("message/rfc822")) { targetUri -> val msg = pendingExport@@ -122,6 +75,15 @@ fun MessageThreadScreen( hasMarkedAsRead = true } }+ // The message being read, saved by key so rotation (the issue #900+ // workaround) keeps the same message open. Fixed to the default once the+ // thread first has messages: marking mail read on open re-emits the list and+ // must not move the selection, now or after a configuration change.+ var selectedKey by rememberSaveable(threadId) { mutableStateOf<String?>(null) }+ LaunchedEffect(threadId, messages.isNotEmpty()) {+ if (selectedKey == null) selectedKey = defaultMessage(messages)?.threadKey()+ }+ val selected = messages.firstOrNull { it.threadKey() == selectedKey } ?: defaultMessage(messages) AppScaffold( title = { val first = messages.firstOrNull()@@ -137,193 +99,55 @@ fun MessageThreadScreen( // Detail pane: letterboxed on expanded windows so message cards keep a // readable measure on desktop. DesktopMaxWidthContainer(Modifier.padding(padding)) {- LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- items(messages, key = { "${it.accountEmail}|${it.folderName}|${it.id}" }) { msg ->- MessageItem(msg = msg, actions = actions, onBack = onBack, onReply = onReply, onForward = onForward, onCompose = onCompose, onExportEml = { toExport ->- pendingExport = toExport- val fileName = EmlUtils.sanitizeFileName(toExport.subject.ifBlank { "email_${toExport.id}" })- exportLauncher.launch(fileName)- })- }- }- }- }-}--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun MessageItem(- msg: EmailMessage,- actions: MessageThreadActions,- onBack: () -> Unit,- onReply: (String, String, String?) -> Unit,- onForward: (String, String?) -> Unit,- onCompose: (String, String) -> Unit,- onExportEml: (EmailMessage) -> Unit = {},-) {- var attachments by remember { mutableStateOf<List<Attachment>>(emptyList()) }- var showDetails by remember { mutableStateOf(false) }- val sheetState = rememberModalBottomSheetState()- val context = LocalContext.current- val resources = LocalResources.current- var showOverflow by remember { mutableStateOf(false) }- LaunchedEffect(msg.id) {- attachments = actions.getAttachments(msg.accountEmail, msg.id)- if (msg.body == null) actions.fetchBodyIfNeeded(msg)- }- val senderName = senderDisplayName(msg.from).ifEmpty { msg.from }- val senderEmail = msg.from.substringAfter("<").substringBefore(">").trim()- val initial = senderName.take(1).uppercase()- val avatarColor = Color(accountColor(msg.accountEmail))- Column {- Row(modifier = Modifier.fillMaxWidth().clickable { showDetails = true }.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {- Surface(shape = CircleShape, color = avatarColor, modifier = Modifier.size(40.dp)) {- Box(contentAlignment = Alignment.Center) { Text(text = initial, color = contentColorOn(avatarColor), style = MaterialTheme.typography.titleMedium) }- }- Column(modifier = Modifier.weight(1f).padding(horizontal = 12.dp)) {- Row(verticalAlignment = Alignment.CenterVertically) {- Text(text = senderName, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))- Text(text = " \u2022 ${msg.date.substringBeforeLast(":")}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- Text(text = stringResource(R.string.to_me), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- Row(verticalAlignment = Alignment.CenterVertically) {- var showSnooze by remember { mutableStateOf(false) }- Box {- TextButton(onClick = { showSnooze = true }) { Text(stringResource(R.string.snooze)) }- DropdownMenu(expanded = showSnooze, onDismissRequest = { showSnooze = false }) {- val snooze = { at: Long ->- showSnooze = false- actions.snoozeMessage(msg.accountEmail, msg.folderName, msg.id, at)- AppMessages.show(resources.getString(R.string.snoozed))- onBack()- }- DropdownMenuItem(text = { Text(stringResource(R.string.later_today_6_pm)) }, onClick = { snooze(scheduleTime(18, sameDay = true)) })- DropdownMenuItem(text = { Text(stringResource(R.string.tomorrow_8_am)) }, onClick = { snooze(scheduleTime(8, sameDay = false)) })- DropdownMenuItem(text = { Text(stringResource(R.string.in_1_week)) }, onClick = { snooze(System.currentTimeMillis() + 7L * 24 * 3600_000) })+ // No outer vertical scroller (#900): the open message fills the pane and+ // its body scrolls itself, so the WebView never has to report a content+ // height to a parent list. Other messages in the thread are picked from+ // a short strip above it, which scrolls on its own.+ BoxWithConstraints(Modifier.fillMaxSize()) {+ val stripMaxHeight = maxHeight * THREAD_STRIP_MAX_FRACTION+ Column(Modifier.fillMaxSize()) {+ if (messages.size > 1 && selected != null) {+ ThreadMessageStrip(+ messages = messages,+ selectedKey = selected.threadKey(),+ onSelect = { selectedKey = it.threadKey() },+ modifier = Modifier.fillMaxWidth().heightIn(max = stripMaxHeight),+ )+ HorizontalDivider() }- }- IconButton(onClick = { onReply(msg.from, msg.subject, msg.serverId) }) { IconUndo() }- IconButton(onClick = { actions.markAsRead(msg.accountEmail, msg.folderName, msg.id, !msg.isRead); if (msg.isRead) onBack() }) {- if (msg.isRead) IconMarkUnread() else IconMarkRead()- }- Box {- IconButton(onClick = { showOverflow = true }) { IconMoreVert() }- DropdownMenu(expanded = showOverflow, onDismissRequest = { showOverflow = false }) {- DropdownMenuItem(text = { Text(stringResource(R.string.save_as_eml)) }, leadingIcon = { IconSave(modifier = Modifier.size(20.dp)) }, onClick = { showOverflow = false; onExportEml(msg) })+ if (selected != null) {+ key(selected.threadKey()) {+ MessageItem(+ msg = selected,+ actions = actions,+ onBack = onBack,+ onReply = onReply,+ onForward = onForward,+ onCompose = onCompose,+ onExportEml = { toExport ->+ pendingExport = toExport+ val fileName = EmlUtils.sanitizeFileName(toExport.subject.ifBlank { "email_${toExport.id}" })+ exportLauncher.launch(fileName)+ },+ modifier = Modifier.weight(1f),+ )+ } } } } }- if (msg.isHtml && msg.body != null) {- val settings = remember(context) { EmailSettings.get(context) }- val loadRemoteByDefault by settings.loadRemoteImages.collectAsStateWithLifecycle()- var loadImages by remember(msg.id, loadRemoteByDefault) { mutableStateOf(loadRemoteByDefault) }- var showQuotes by remember(msg.id) { mutableStateOf(false) }- var cidMap by remember(msg.id) { mutableStateOf<Map<String, java.io.File>>(emptyMap()) }- val bodyHasCid = remember(msg.body) { msg.body.contains("cid:", ignoreCase = true) }- LaunchedEffect(msg.id, msg.body) { if (bodyHasCid) { val map = actions.loadCidMap(context, msg); if (map.isNotEmpty()) cidMap = map } }- val hasQuotes = remember(msg.body) { listOf("gmail_quote", "yahoo_quoted", "moz-cite-prefix", "<blockquote").any { msg.body.contains(it, ignoreCase = true) } }- val remoteBlocked = !loadImages && cidMap.isEmpty() && !bodyHasCid- if (remoteBlocked) {- 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 = remoteBlocked, hideQuotes = hasQuotes && !showQuotes, cidMap = cidMap, modifier = Modifier.padding(horizontal = 16.dp).fillMaxWidth())- if (hasQuotes) {- TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) { Text(if (showQuotes) stringResource(R.string.hide_quoted_text) else stringResource(R.string.show_quoted_text)) }- }- } else {- var showQuotes by remember(msg.id) { mutableStateOf(false) }- val (mainText, quotedText) = remember(msg.body) { splitQuotedText(msg.body ?: "(No Content)") }- Text(text = if (showQuotes || quotedText.isEmpty()) (msg.body ?: stringResource(R.string.no_content)) else mainText, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp))- if (quotedText.isNotEmpty()) {- TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) { Text(if (showQuotes) stringResource(R.string.hide_quoted_text) else stringResource(R.string.show_quoted_text)) }- }- }- if (attachments.isNotEmpty()) {- Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {- Text(stringResource(R.string.attachments_2), style = MaterialTheme.typography.labelLarge)- attachments.forEach { att -> AttachmentItem(att, actions) }- }- }- Row(modifier = Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {- OutlinedButton(onClick = { onReply(msg.from, msg.subject, msg.serverId) }, modifier = Modifier.weight(1f)) {- IconUndo(modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.reply))- }- OutlinedButton(onClick = { onForward(msg.subject, msg.body) }, modifier = Modifier.weight(1f)) {- IconForward(modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.forward))- }- }- 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 = { actions.blockSender(msg.from); AppMessages.show(resources.getString(R.string.sender_blocked)); onBack() }) { Text(stringResource(R.string.block_sender)) }- }- HorizontalDivider()- }- 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))- }- } } } -private fun splitQuotedText(body: String): Pair<String, String> {- val lines = body.split("\n")- val onWrote = Regex("^On .+ wrote:\\s*$")- val origMsg = Regex("^-{2,}\\s*Original Message\\s*-{2,}\\s*$", RegexOption.IGNORE_CASE)- for (i in lines.indices) {- val line = lines[i].trim()- val isBoundary = onWrote.matches(line) || origMsg.matches(line) || line.startsWith(">")- if (isBoundary && i > 0) {- val main = lines.subList(0, i).joinToString("\n").trimEnd()- val quoted = lines.subList(i, lines.size).joinToString("\n")- return main to quoted- }- }- return body to ""-}+/** Share of the pane the thread strip may take before it scrolls. */+private const val THREAD_STRIP_MAX_FRACTION = 0.3f -@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)) } })-}+/** Stable identity of a message within a thread (accounts and folders can share UIDs). */+internal fun EmailMessage.threadKey(): String = "$accountEmail|$folderName|$id" -private fun performUnsubscribe(method: UnsubscribeMethod, context: android.content.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")- }-}+/**+ * The message a thread opens on: the oldest unread one, so a run of new+ * replies is read in order, or else the newest.+ */+internal fun defaultMessage(messages: List<EmailMessage>): EmailMessage? =+ messages.firstOrNull { !it.isRead } ?: messages.lastOrNull()
email/src/main/java/com/vayunmathur/email/ui/ThreadMessageStrip.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/ThreadMessageStrip.kt b/email/src/main/java/com/vayunmathur/email/ui/ThreadMessageStrip.ktnew file mode 100644index 0000000000..829115824d--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/ThreadMessageStrip.kt@@ -0,0 +1,84 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.selection.selectable+import androidx.compose.foundation.shape.CircleShape+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.semantics.Role+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.accountColor+import com.vayunmathur.email.data.senderDisplayName+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.contentColorOn++/**+ * Compact, selectable list of a thread's messages (sender, date, snippet),+ * shown above the open message when the thread has more than one. Tapping a+ * row opens that message in the pane below. It scrolls on its own and is never+ * an ancestor of the message body, so it cannot compete with the body's+ * scrolling (#900).+ */+@Composable+fun ThreadMessageStrip(+ messages: List<EmailMessage>,+ selectedKey: String,+ onSelect: (EmailMessage) -> Unit,+ modifier: Modifier = Modifier,+) {+ val initialIndex = messages.indexOfFirst { it.threadKey() == selectedKey }.coerceAtLeast(0)+ val listState = rememberLazyListState(initialFirstVisibleItemIndex = initialIndex)+ LazyColumn(modifier = modifier, state = listState) {+ items(messages, key = { it.threadKey() }) { msg ->+ ThreadMessageRow(msg = msg, selected = msg.threadKey() == selectedKey, onClick = { onSelect(msg) })+ }+ }+}++@Composable+private fun ThreadMessageRow(msg: EmailMessage, selected: Boolean, onClick: () -> Unit) {+ val senderName = senderDisplayName(msg.from).ifEmpty { msg.from }+ val avatarColor = Color(accountColor(msg.accountEmail))+ val background = if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surface+ Surface(color = background, modifier = Modifier.fillMaxWidth().selectable(selected = selected, role = Role.Tab, onClick = onClick)) {+ Row(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Surface(shape = CircleShape, color = avatarColor, modifier = Modifier.size(28.dp)) {+ Box(contentAlignment = Alignment.Center) {+ Text(text = senderName.take(1).uppercase(), color = contentColorOn(avatarColor), style = MaterialTheme.typography.labelMedium)+ }+ }+ Column(modifier = Modifier.weight(1f)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(+ text = senderName,+ style = MaterialTheme.typography.titleSmall,+ fontWeight = if (msg.isRead) FontWeight.Normal else FontWeight.Bold,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f, fill = false),+ )+ Text(text = " \u2022 ${msg.date.substringBeforeLast(":")}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)+ }+ if (msg.peekContent.isNotBlank()) {+ Text(text = msg.peekContent, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ }+ }+}
email/src/test/java/com/vayunmathur/email/ui/MessageThreadLayoutTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/MessageThreadLayoutTest.kt b/email/src/test/java/com/vayunmathur/email/ui/MessageThreadLayoutTest.ktnew file mode 100644index 0000000000..b44487e2da--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/ui/MessageThreadLayoutTest.kt@@ -0,0 +1,169 @@+package com.vayunmathur.email.ui++import android.content.Context+import android.net.Uri+import android.view.View+import android.view.ViewGroup+import android.webkit.WebView+import androidx.activity.ComponentActivity+import androidx.compose.ui.test.assert+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsNotSelected+import androidx.compose.ui.test.assertIsSelected+import androidx.compose.ui.test.getBoundsInRoot+import androidx.compose.ui.test.hasAnyAncestor+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.isSelectable+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithTag+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+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 java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Layout guarantees behind the #900 fix ("email pane scrolling broken" in+ * portrait): the open message's HTML body is a self-scrolling WebView that+ * fills the pane, never a wrap-content WebView inside a vertically scrolling+ * list, and threads with several messages open one at a time from a strip.+ *+ * Portrait phone geometry, the configuration the bug was reported in.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w411dp-h891dp-port")+class MessageThreadLayoutTest {++ @get:Rule+ val rule = createAndroidComposeRule<ComponentActivity>()++ private object NoopActions : MessageThreadActions {+ override fun markAsRead(accountEmail: String, folderName: String, uid: Long, isRead: Boolean) = Unit+ override fun snoozeMessage(accountEmail: String, folderName: String, uid: Long, until: Long) = Unit+ override fun blockSender(from: String) = Unit+ override fun fetchBodyIfNeeded(message: EmailMessage) = Unit+ override suspend fun getAttachments(accountEmail: String, messageId: Long): List<Attachment> = emptyList()+ override suspend fun loadCidMap(context: Context, message: EmailMessage): Map<String, File> = emptyMap()+ override fun downloadAttachment(attachment: Attachment, onSuccess: (String) -> Unit, onError: (String) -> Unit) = Unit+ override fun oneClickUnsubscribe(url: String, onResult: (Boolean) -> Unit) = Unit+ override fun exportEml(accountEmail: String, folderName: String, uid: Long, targetUri: Uri, onResult: (Boolean, String?) -> Unit) = Unit+ }++ /** A long, fixed-width (600px) newsletter: the shape of mail #900 was reported on. */+ private val newsletter = buildString {+ append("<table width=\"600\" style=\"width:600px\" align=\"center\">")+ repeat(200) { append("<tr><td><p>Paragraph $it of a long newsletter.</p></td></tr>") }+ append("</table>")+ }++ private fun msg(uid: Long, body: String, isHtml: Boolean = false, isRead: Boolean = true) = EmailMessage(+ accountEmail = "[email protected]", folderName = "INBOX", id = uid,+ subject = "Weekly digest", from = "News <[email protected]>", date = "Wed Nov 27 10:00",+ body = body, isHtml = isHtml, isRead = isRead,+ )++ private fun webView(): WebView {+ var found: WebView? = null+ rule.runOnUiThread {+ val q = ArrayDeque<View>()+ q.add(rule.activity.findViewById(android.R.id.content))+ while (q.isNotEmpty() && found == null) {+ val v = q.removeFirst()+ if (v is WebView) found = v+ if (v is ViewGroup) for (i in 0 until v.childCount) q.add(v.getChildAt(i))+ }+ }+ return assertNotNull(found, "no WebView in the hierarchy")+ }++ @Test+ fun `html body is not inside any vertically scrolling container`() {+ rule.setContent { MessageThreadScreen(messages = listOf(msg(1L, newsletter, isHtml = true)), actions = NoopActions) }+ rule.waitForIdle()+ rule.onNodeWithTag(MESSAGE_HTML_BODY_TAG).assert(!hasAnyAncestor(hasScrollAction()))+ }++ @Test+ fun `html body fills the pane and scrolls itself instead of wrapping its content`() {+ rule.setContent { MessageThreadScreen(messages = listOf(msg(1L, newsletter, isHtml = true)), actions = NoopActions) }+ rule.waitForIdle()+ val root = rule.onRoot().getBoundsInRoot()+ val body = rule.onNodeWithTag(MESSAGE_HTML_BODY_TAG).getBoundsInRoot()+ val rootHeight = root.bottom - root.top+ val bodyHeight = body.bottom - body.top+ // Header, banner, footer and the app bar take the rest; the body gets the+ // bulk of a portrait screen regardless of what the WebView says its+ // content height is (0 under Robolectric).+ assertTrue(bodyHeight > rootHeight * 0.4f, "body $bodyHeight of root $rootHeight")+ assertTrue(body.bottom <= root.bottom, "body must end on screen: $body vs $root")+ val view = webView()+ assertEquals(ViewGroup.LayoutParams.MATCH_PARENT, view.layoutParams.height)+ assertTrue(view.isVerticalScrollBarEnabled, "the WebView owns its scrolling")+ }++ @Test+ fun `html body loads with fit-to-width css`() {+ rule.setContent { MessageThreadScreen(messages = listOf(msg(1L, newsletter, isHtml = true)), actions = NoopActions) }+ rule.waitForIdle()+ val data = org.robolectric.Shadows.shadowOf(webView()).lastLoadDataWithBaseURL?.data.orEmpty()+ assertTrue(data.contains("overflow-wrap: anywhere"), data.take(2000))+ assertTrue(data.contains("user-scalable=yes"), data.take(500))+ }++ @Test+ fun `single message thread shows no strip`() {+ rule.setContent { MessageThreadScreen(messages = listOf(msg(1L, "Only one")), actions = NoopActions) }+ rule.waitForIdle()+ assertEquals(0, rule.onAllNodes(isSelectable()).fetchSemanticsNodes().size)+ }++ @Test+ fun `thread opens on its first unread message and the strip switches messages`() {+ rule.setContent {+ MessageThreadScreen(+ messages = listOf(+ msg(1L, "Body one"),+ msg(2L, "Body two", isRead = false),+ msg(3L, "Body three", isRead = false),+ ),+ actions = NoopActions,+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("Body two").assertIsDisplayed()+ rule.onNodeWithText("Body one").assertDoesNotExist()+ val rows = rule.onAllNodes(isSelectable())+ rows[1].assertIsSelected()+ rows[0].assertIsNotSelected()+ rows[2].performClick()+ rule.waitForIdle()+ rule.onNodeWithText("Body three").assertIsDisplayed()+ rule.onNodeWithText("Body two").assertDoesNotExist()+ rule.onAllNodes(isSelectable())[2].assertIsSelected()+ }++ @Test+ fun `html message in a multi-message thread still fills the pane below the strip`() {+ rule.setContent {+ MessageThreadScreen(+ messages = listOf(msg(1L, "Earlier note"), msg(2L, newsletter, isHtml = true)),+ actions = NoopActions,+ )+ }+ rule.waitForIdle()+ rule.onNodeWithTag(MESSAGE_HTML_BODY_TAG).assert(!hasAnyAncestor(hasScrollAction()))+ val root = rule.onRoot().getBoundsInRoot()+ val body = rule.onNodeWithTag(MESSAGE_HTML_BODY_TAG).getBoundsInRoot()+ assertTrue(body.bottom - body.top > (root.bottom - root.top) * 0.25f, "body $body of root $root")+ }+}
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 abf5a7a690..94b8e07b62 100644--- a/email/src/test/java/com/vayunmathur/email/ui/MessageThreadScreenTest.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/MessageThreadScreenTest.kt@@ -5,6 +5,7 @@ import android.content.Context import android.content.Intent import android.net.Uri import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.isSelectable import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithContentDescription@@ -102,9 +103,13 @@ class MessageThreadScreenTest { ) } composeRule.onNodeWithText("Trip plans").assertIsDisplayed()- composeRule.onNodeWithText("Hello there").assertIsDisplayed()- composeRule.onNodeWithText("Second reply").performScrollTo()+ // A read thread opens on its newest message; the strip opens the others. composeRule.onNodeWithText("Second reply").assertIsDisplayed()+ composeRule.onNodeWithText("Hello there").assertDoesNotExist()+ composeRule.onAllNodes(isSelectable())[0].performClick()+ composeRule.waitForIdle()+ composeRule.onNodeWithText("Hello there").assertIsDisplayed()+ composeRule.onNodeWithText("Second reply").assertDoesNotExist() } @Test@@ -184,7 +189,6 @@ class MessageThreadScreenTest { composeRule.setContent { MessageThreadScreen(messages = listOf(msg(1L)), actions = FakeActions()) }- composeRule.onNodeWithText("Snooze").performScrollTo() composeRule.onNodeWithText("Snooze").performClick() composeRule.waitForIdle() composeRule.onNodeWithText("Tomorrow", substring = true).assertIsDisplayed()@@ -196,7 +200,6 @@ class MessageThreadScreenTest { composeRule.setContent { MessageThreadScreen(messages = listOf(msg(1L, isRead = true)), actions = actions) }- composeRule.onNodeWithContentDescription("Mark Unread").performScrollTo() composeRule.onNodeWithContentDescription("Mark Unread").performClick() composeRule.waitForIdle() assertTrue(actions.reads.any { it.second == 1L && !it.third }, "reads: ${actions.reads}")@@ -207,7 +210,6 @@ class MessageThreadScreenTest { composeRule.setContent { MessageThreadScreen(messages = listOf(msg(1L)), actions = FakeActions()) }- composeRule.onNodeWithContentDescription("More").performScrollTo() composeRule.onNodeWithContentDescription("More").performClick() composeRule.waitForIdle() composeRule.onNodeWithText("Save as .eml").assertIsDisplayed()@@ -329,7 +331,6 @@ class MessageThreadScreenTest { onBack = { backs++ }, ) }- composeRule.onNodeWithText("Snooze").performScrollTo() composeRule.onNodeWithText("Snooze").performClick() composeRule.waitForIdle() composeRule.onNodeWithText("In 1 week").performClick()@@ -344,7 +345,6 @@ class MessageThreadScreenTest { composeRule.setContent { MessageThreadScreen(messages = listOf(msg(1L)), actions = FakeActions()) }- composeRule.onNodeWithContentDescription("More").performScrollTo() composeRule.onNodeWithContentDescription("More").performClick() composeRule.waitForIdle() composeRule.onNodeWithText("Save as .eml").performClick()
library/ui/AGENTS.md
diff --git a/library/ui/AGENTS.md b/library/ui/AGENTS.mdindex 23327102b8..8509e5e386 100644--- a/library/ui/AGENTS.md+++ b/library/ui/AGENTS.md@@ -114,7 +114,8 @@ - com/vayunmathur/library/ui/HtmlEditorControllerCore.kt - com/vayunmathur/library/ui/HtmlEditorSpans.kt - com/vayunmathur/library/ui/HtmlSerialize.kt-- com/vayunmathur/library/ui/HtmlText.kt+- com/vayunmathur/library/ui/HtmlText.kt — `scrollInternally`/`fitContentToWidth` for long untrusted mail (#900)+- com/vayunmathur/library/ui/HtmlTextDocument.kt — pure document wrapper (viewport, CSP, fit CSS) - com/vayunmathur/library/ui/RichEmailSpans.kt - com/vayunmathur/library/ui/EditorFormatter.kt - com/vayunmathur/library/ui/EditorLink.kt
library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.ktindex e46412ec1a..6886ce22e5 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt@@ -16,20 +16,33 @@ import androidx.compose.ui.viewinterop.AndroidView import java.io.File /**- * Renders an HTML fragment (an email body, typically) in an inline, wrap-content- * [WebView].+ * Renders an HTML fragment (an email body, typically) in a [WebView].+ *+ * By default the view is inline and wrap-content: it sizes itself to its+ * content for embedding in a scrolling column. That depends on the WebView+ * reporting its content height accurately, which it does not reliably do for+ * wide, fixed-layout mail; a reader that shows long untrusted HTML should use+ * [scrollInternally] instead. * * @param openLinksExternally hands tapped links to the system browser rather than- * letting them navigate inside this view. The view is sized to its content and- * embedded in a scrolling column, so in-place navigation would strand the user- * on a full web page inside a message. Only turn this off for content that is- * genuinely meant to be browsed in place.+ * letting them navigate inside this view. An inline view is sized to its+ * content and embedded in a scrolling column, so in-place navigation would+ * strand the user on a full web page inside a message. Only turn this off for+ * content that is genuinely meant to be browsed in place. * @param javaScriptEnabled runs scripts in the content. Untrusted mail should * pass false: a sender's script otherwise executes on open. * @param blockRemoteContent refuses every network fetch (images, CSS, fonts, * iframes, script requests) - not just `<img>` like [blockRemoteImages] - so * opening a message cannot ping the sender's server. Inline `cid:` images * and `data:` URIs still load.+ * @param scrollInternally makes the view fill the bounded height it is given+ * (e.g. `Modifier.weight(1f)` in a non-scrolling column) and scroll its own+ * content, with a scrollbar and pinch-zoom. Never place such a view inside a+ * vertically scrolling parent: the two scrollers would fight over every drag.+ * @param fitContentToWidth makes fixed-width layouts (600px newsletter tables,+ * inline `min-width`, long unbreakable links) fit the view width at a+ * readable 1:1 scale, and drops any viewport tag the sender embedded. See+ * [HtmlTextDocument.FIT_TO_WIDTH_CSS]. */ @Composable fun HtmlText(@@ -41,6 +54,8 @@ fun HtmlText( openLinksExternally: Boolean = true, javaScriptEnabled: Boolean = true, blockRemoteContent: Boolean = false,+ scrollInternally: Boolean = false,+ fitContentToWidth: Boolean = false, ) { val backgroundColor = MaterialTheme.colorScheme.surface val onSurfaceColor = MaterialTheme.colorScheme.onSurface@@ -48,19 +63,11 @@ fun HtmlText( val backgroundHex = String.format("#%06X", 0xFFFFFF and backgroundColor.toArgb()) val textHex = String.format("#%06X", 0xFFFFFF and onSurfaceColor.toArgb())- val quoteCss = if (hideQuotes) {- "blockquote, .gmail_quote, .yahoo_quoted, .moz-cite-prefix, .gmail_extra, .protonmail_quote { display: none !important; }"- } else "" // Rewrite cid: -> https://cid.local/ to allow intercept without network permission val rewrittenHtml = remember(html, cidMap) { if (cidMap.isEmpty()) html- else {- var h = html- // Replace src="cid:xxx" with src="https://cid.local/xxx" (case insensitive)- h = h.replace(Regex("cid:", RegexOption.IGNORE_CASE), "https://cid.local/")- h- }+ else html.replace(Regex("cid:", RegexOption.IGNORE_CASE), "https://cid.local/") } // One client instance for the life of the view, mutated in place. Swapping in a // new WebViewClient on every recomposition used to be how the cid map was@@ -70,121 +77,60 @@ fun HtmlText( webClient.openLinksExternally = openLinksExternally webClient.blockRemoteContent = blockRemoteContent // Defence in depth alongside the request interceptor: the document itself- // forbids any non-local fetch when remote content is blocked.- val csp = if (blockRemoteContent) {- "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; " +- "img-src data: https://cid.local; style-src 'unsafe-inline'; font-src data:\">"- } else ""+ // forbids any non-local fetch when remote content is blocked (CSP in the spec).+ val spec = HtmlTextDocumentSpec(+ backgroundHex = backgroundHex,+ textHex = textHex,+ isDark = isDark,+ hideQuotes = hideQuotes,+ blockRemoteContent = blockRemoteContent,+ fitContentToWidth = fitContentToWidth,+ ) AndroidView( modifier = modifier, factory = { context -> WebView(context).apply {- layoutParams = ViewGroup.LayoutParams(- ViewGroup.LayoutParams.MATCH_PARENT,- ViewGroup.LayoutParams.WRAP_CONTENT,- )- isVerticalScrollBarEnabled = false- settings.javaScriptEnabled = javaScriptEnabled- settings.useWideViewPort = true+ // Before the view is attached: AndroidView sizes it from these params.+ applyHtmlTextLayout(scrollInternally) settings.loadWithOverviewMode = false- settings.builtInZoomControls = false settings.displayZoomControls = false- settings.blockNetworkImage = blockRemoteImages setBackgroundColor(backgroundColor.toArgb())- webViewClient = webClient } }, update = { webView ->+ webView.applyHtmlTextLayout(scrollInternally)+ webView.settings.useWideViewPort = true webView.settings.blockNetworkImage = blockRemoteImages || blockRemoteContent webView.settings.javaScriptEnabled = javaScriptEnabled- val htmlToLoad = if (cidMap.isEmpty()) html else rewrittenHtml- val richCss = """- h1,h2,h3 { margin:0.5em 0; font-weight:600; line-height:1.25; }- h1 { font-size:1.6em; }- h2 { font-size:1.35em; }- h3 { font-size:1.15em; }- blockquote { border-left:2px solid #ccc; margin:0 0 0 8px; padding-left:8px; color:#666; font-style:italic; }- code { font-family:monospace; background:rgba(0,0,0,0.06); padding:2px 4px; border-radius:3px; word-break:break-word; }- hr { border:none; border-top:1px solid #ccc; margin:12px 0; }- pre { background:#f5f5f5; padding:8px; overflow-x:auto; border-radius:4px; font-family:monospace; white-space:pre-wrap; }- ul, ol { margin:0.5em 0; padding-left:24px; }- li { margin:0.25em 0; }- """.trimIndent()-- if (isDark) {- val darkModeHtml = """- <html>- <head>- <meta name="viewport" content="width=device-width, initial-scale=1">- $csp- <style>- * { box-sizing: border-box; }- html, body { max-width: 100%; }- body {- margin: 0;- padding: 8px;- background-color: $backgroundHex;- font-family: sans-serif;- font-size: 14px;- line-height: 1.5;- word-wrap: break-word;- overflow-wrap: break-word;- filter: invert(1) hue-rotate(180deg);- }- img, video, iframe, svg, table { max-width: 100% !important; }- img, video, iframe, svg {- filter: invert(1) hue-rotate(180deg) brightness(0.9);- height: auto;- }- code {- filter: invert(1) hue-rotate(180deg);- background: rgba(255,255,255,0.12) !important;- }- $richCss- $quoteCss- </style>- </head>- <body>$htmlToLoad</body>- </html>- """.trimIndent()- webView.loadDataWithBaseURL("https://cid.local/", darkModeHtml, "text/html", "UTF-8", null)- } else {- val lightHtml = """- <html>- <head>- <meta name="viewport" content="width=device-width, initial-scale=1">- $csp- <style>- * { box-sizing: border-box; }- html, body { max-width: 100%; }- body {- margin: 0;- padding: 8px;- color: $textHex;- background-color: $backgroundHex;- font-family: sans-serif;- font-size: 14px;- line-height: 1.5;- word-wrap: break-word;- overflow-wrap: break-word;- }- img, table { max-width: 100% !important; }- img { height: auto; }- $richCss- $quoteCss- </style>- </head>- <body>$htmlToLoad</body>- </html>- """.trimIndent()- webView.loadDataWithBaseURL("https://cid.local/", lightHtml, "text/html", "UTF-8", null)+ val document = HtmlTextDocument.build(rewrittenHtml, spec)+ // Only reload when what would be shown changed. `update` re-runs whenever+ // anything it captures changes (layout mode, a new cidMap instance with+ // the same files, ...), and reloading identical content resets the+ // scroll position and re-measures the view mid-read.+ val loadKey = "$blockRemoteImages|$javaScriptEnabled|$document"+ if (webView.tag != loadKey) {+ webView.tag = loadKey+ webView.loadDataWithBaseURL("https://cid.local/", document, "text/html", "UTF-8", null) } }, ) } +/**+ * Inline (wrap-content, no scrollbar, no zoom) or self-scrolling (fills its+ * bounds, scrollbar, pinch-zoom without on-screen buttons).+ */+private fun WebView.applyHtmlTextLayout(scrollInternally: Boolean) {+ val height = if (scrollInternally) ViewGroup.LayoutParams.MATCH_PARENT else ViewGroup.LayoutParams.WRAP_CONTENT+ if (layoutParams?.width != ViewGroup.LayoutParams.MATCH_PARENT || layoutParams?.height != height) {+ layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height)+ }+ isVerticalScrollBarEnabled = scrollInternally+ settings.builtInZoomControls = scrollInternally+}+ /** * Serves `cid:` inline attachments from local files and keeps navigation out of * the view.
library/ui/src/main/java/com/vayunmathur/library/ui/HtmlTextDocument.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlTextDocument.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlTextDocument.ktnew file mode 100644index 0000000000..7349dc3868--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlTextDocument.kt@@ -0,0 +1,177 @@+package com.vayunmathur.library.ui++/**+ * Everything besides the HTML fragment itself that shapes the document+ * [HtmlText] hands to its WebView.+ *+ * @property backgroundHex page background, `#RRGGBB`.+ * @property textHex body text colour, `#RRGGBB` (light theme only; dark mode+ * inverts instead).+ * @property isDark selects the inverting dark-mode stylesheet.+ * @property hideQuotes hides quoted history (blockquote and the common client+ * quote containers).+ * @property blockRemoteContent adds a Content-Security-Policy that forbids+ * every non-local fetch.+ * @property fitContentToWidth makes fixed-width mail fit the screen width; see+ * [HtmlTextDocument.FIT_TO_WIDTH_CSS].+ */+internal data class HtmlTextDocumentSpec(+ val backgroundHex: String,+ val textHex: String,+ val isDark: Boolean,+ val hideQuotes: Boolean = false,+ val blockRemoteContent: Boolean = false,+ val fitContentToWidth: Boolean = false,+)++/**+ * Builds the standalone document [HtmlText] loads around an HTML fragment.+ *+ * Kept free of Android and Compose so the wrapper (viewport, CSP, theme and+ * fit-to-width CSS) is unit-testable on the JVM.+ */+internal object HtmlTextDocument {++ /** The fixed viewport every document gets: layout at device width, 1:1. */+ const val DEFAULT_VIEWPORT = "width=device-width, initial-scale=1"++ /**+ * Viewport for [HtmlTextDocumentSpec.fitContentToWidth]: still laid out at+ * device width and opened at 1:1 so body text keeps its 14px size, but+ * the reader may pinch out to see anything that still overflows, or in to+ * read small print. Only an [HtmlText] that scrolls internally turns+ * pinch-zoom on; elsewhere the extra bounds are inert.+ */+ const val FIT_VIEWPORT =+ "width=device-width, initial-scale=1, minimum-scale=0.25, maximum-scale=5, user-scalable=yes"++ /**+ * Fixed-width newsletter markup (a 600px `<table>` or `<div>`, inline+ * `min-width`, unbreakable URLs) otherwise lays out wider than a portrait+ * phone. These rules cap the common containers at the viewport width and+ * let long words and links break, so the page fits at its 1:1 scale+ * instead of being zoomed out to unreadable text or panned sideways.+ */+ const val FIT_TO_WIDTH_CSS = """+html, body { max-width: 100% !important; min-width: 0 !important; }+div, p, table, center, section, article, header, footer, main, aside, figure, blockquote, pre, ul, ol, li,+img, video, iframe, svg, canvas, embed, object, input, textarea { max-width: 100% !important; }+table, td, th, div { min-width: 0 !important; }+td, th, a { overflow-wrap: anywhere; word-break: normal; }+"""++ private const val QUOTE_CSS =+ "blockquote, .gmail_quote, .yahoo_quoted, .moz-cite-prefix, .gmail_extra, .protonmail_quote " ++ "{ display: none !important; }"++ private const val CSP_META = "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; " ++ "img-src data: https://cid.local; style-src 'unsafe-inline'; font-src data:\">"++ /** A sender's own viewport tag; it would override ours, e.g. `width=600`. */+ private val SENDER_VIEWPORT = Regex(+ """<meta\b[^>]*\bname\s*=\s*["']?viewport\b[^>]*>""",+ RegexOption.IGNORE_CASE,+ )++ private val RICH_CSS = """+ h1,h2,h3 { margin:0.5em 0; font-weight:600; line-height:1.25; }+ h1 { font-size:1.6em; }+ h2 { font-size:1.35em; }+ h3 { font-size:1.15em; }+ blockquote { border-left:2px solid #ccc; margin:0 0 0 8px; padding-left:8px; color:#666; font-style:italic; }+ code { font-family:monospace; background:rgba(0,0,0,0.06); padding:2px 4px; border-radius:3px; word-break:break-word; }+ hr { border:none; border-top:1px solid #ccc; margin:12px 0; }+ pre { background:#f5f5f5; padding:8px; overflow-x:auto; border-radius:4px; font-family:monospace; white-space:pre-wrap; }+ ul, ol { margin:0.5em 0; padding-left:24px; }+ li { margin:0.25em 0; }+ """.trimIndent()++ /** Removes viewport tags the sender embedded, so [FIT_VIEWPORT] wins. */+ fun stripSenderViewport(html: String): String = html.replace(SENDER_VIEWPORT, "")++ /** The complete document for [body] under [spec]. */+ fun build(body: String, spec: HtmlTextDocumentSpec): String {+ val fit = spec.fitContentToWidth+ val content = if (fit) stripSenderViewport(body) else body+ val viewport = if (fit) FIT_VIEWPORT else DEFAULT_VIEWPORT+ val csp = if (spec.blockRemoteContent) CSP_META else ""+ val quoteCss = if (spec.hideQuotes) QUOTE_CSS else ""+ val fitCss = if (fit) FIT_TO_WIDTH_CSS else ""+ return if (spec.isDark) {+ darkDocument(content, spec.backgroundHex, viewport, csp, quoteCss + fitCss)+ } else {+ lightDocument(content, spec, viewport, csp, quoteCss + fitCss)+ }+ }++ private fun darkDocument(body: String, backgroundHex: String, viewport: String, csp: String, extraCss: String) = """+ <html>+ <head>+ <meta name="viewport" content="$viewport">+ $csp+ <style>+ * { box-sizing: border-box; }+ html, body { max-width: 100%; }+ body {+ margin: 0;+ padding: 8px;+ background-color: $backgroundHex;+ font-family: sans-serif;+ font-size: 14px;+ line-height: 1.5;+ word-wrap: break-word;+ overflow-wrap: break-word;+ filter: invert(1) hue-rotate(180deg);+ }+ img, video, iframe, svg, table { max-width: 100% !important; }+ img, video, iframe, svg {+ filter: invert(1) hue-rotate(180deg) brightness(0.9);+ height: auto;+ }+ code {+ filter: invert(1) hue-rotate(180deg);+ background: rgba(255,255,255,0.12) !important;+ }+ $RICH_CSS+ $extraCss+ </style>+ </head>+ <body>$body</body>+ </html>+ """.trimIndent()++ private fun lightDocument(+ body: String,+ spec: HtmlTextDocumentSpec,+ viewport: String,+ csp: String,+ extraCss: String,+ ) = """+ <html>+ <head>+ <meta name="viewport" content="$viewport">+ $csp+ <style>+ * { box-sizing: border-box; }+ html, body { max-width: 100%; }+ body {+ margin: 0;+ padding: 8px;+ color: ${spec.textHex};+ background-color: ${spec.backgroundHex};+ font-family: sans-serif;+ font-size: 14px;+ line-height: 1.5;+ word-wrap: break-word;+ overflow-wrap: break-word;+ }+ img, table { max-width: 100% !important; }+ img { height: auto; }+ $RICH_CSS+ $extraCss+ </style>+ </head>+ <body>$body</body>+ </html>+ """.trimIndent()+}
library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextDocumentTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextDocumentTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextDocumentTest.ktnew file mode 100644index 0000000000..f568b9f5e5--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextDocumentTest.kt@@ -0,0 +1,88 @@+package com.vayunmathur.library.ui++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The document [HtmlText] wraps around a mail body, tested as a pure string+ * transform: default output keeps the historical wrapper for existing callers,+ * and fit-to-width adds the width caps, the zoomable viewport and drops the+ * sender's own viewport tag (#900).+ */+class HtmlTextDocumentTest {++ private val light = HtmlTextDocumentSpec(backgroundHex = "#FFFFFF", textHex = "#111111", isDark = false)+ private val newsletter =+ "<meta name=\"viewport\" content=\"width=600\">" ++ "<table width=\"600\" style=\"width:600px;min-width:600px\"><tr><td>Deal of the week</td></tr></table>"++ @Test+ fun `default document keeps the fixed device-width viewport and no fit css`() {+ val doc = HtmlTextDocument.build("<p>hi</p>", light)+ assertTrue(doc.contains("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"), doc)+ assertFalse(doc.contains("overflow-wrap: anywhere"), doc)+ assertFalse(doc.contains("user-scalable"), doc)+ assertTrue(doc.contains("<body><p>hi</p></body>"), doc)+ }++ @Test+ fun `default document leaves a sender viewport tag alone`() {+ val doc = HtmlTextDocument.build(newsletter, light)+ assertTrue(doc.contains("content=\"width=600\""), doc)+ }++ @Test+ fun `fit to width caps fixed-width containers and lets long links break`() {+ val doc = HtmlTextDocument.build(newsletter, light.copy(fitContentToWidth = true))+ assertTrue(doc.contains(HtmlTextDocument.FIT_TO_WIDTH_CSS.trim()), doc)+ assertTrue(doc.contains("table, td, th, div { min-width: 0 !important; }"), doc)+ assertTrue(doc.contains("max-width: 100% !important"), doc)+ assertTrue(doc.contains("overflow-wrap: anywhere"), doc)+ // The body itself is untouched apart from the viewport tag.+ assertTrue(doc.contains("<table width=\"600\" style=\"width:600px;min-width:600px\">"), doc)+ }++ @Test+ fun `fit to width opens at 1 to 1 so text stays readable`() {+ val doc = HtmlTextDocument.build(newsletter, light.copy(fitContentToWidth = true))+ assertTrue(doc.contains("<meta name=\"viewport\" content=\"${HtmlTextDocument.FIT_VIEWPORT}\">"), doc)+ assertTrue(HtmlTextDocument.FIT_VIEWPORT.contains("width=device-width"))+ assertTrue(HtmlTextDocument.FIT_VIEWPORT.contains("initial-scale=1,"))+ assertTrue(doc.contains("font-size: 14px"), doc)+ }++ @Test+ fun `fit to width drops the sender viewport tag`() {+ val doc = HtmlTextDocument.build(newsletter, light.copy(fitContentToWidth = true))+ assertFalse(doc.contains("width=600\""), doc)+ assertEquals(1, Regex("name=\"viewport\"").findAll(doc).count(), doc)+ }++ @Test+ fun `sender viewport stripping handles case, quoting and attribute order`() {+ val html = "<META content='width=640' NAME='Viewport'/><p>x</p><meta name=viewport content=width=700>" ++ "<meta name=\"description\" content=\"keep me\">"+ assertEquals(+ "<p>x</p><meta name=\"description\" content=\"keep me\">",+ HtmlTextDocument.stripSenderViewport(html),+ )+ }++ @Test+ fun `fit to width applies in dark mode too`() {+ val doc = HtmlTextDocument.build(newsletter, light.copy(isDark = true, fitContentToWidth = true))+ assertTrue(doc.contains("filter: invert(1) hue-rotate(180deg);"), doc)+ assertTrue(doc.contains("overflow-wrap: anywhere"), doc)+ }++ @Test+ fun `quotes and csp still compose with fit to width`() {+ val spec = light.copy(hideQuotes = true, blockRemoteContent = true, fitContentToWidth = true)+ val doc = HtmlTextDocument.build("<p>hi</p>", spec)+ assertTrue(doc.contains(".gmail_quote"), doc)+ assertTrue(doc.contains("Content-Security-Policy"), doc)+ assertTrue(doc.contains("overflow-wrap: anywhere"), doc)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextScrollModeTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextScrollModeTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextScrollModeTest.ktnew file mode 100644index 0000000000..3efa4a669c--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextScrollModeTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.library.ui++import android.view.View+import android.view.ViewGroup+import android.webkit.WebView+import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.test.assertHeightIsEqualTo+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithTag+import androidx.compose.ui.unit.dp+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertSame+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * [HtmlText]'s layout modes (#900): the default stays an inline wrap-content+ * view for existing callers; `scrollInternally` fills its bounds and scrolls+ * itself. Also pins that recomposing with unchanged content does not reload+ * the page (a reload resets the reader's scroll position).+ */+@RunWith(RobolectricTestRunner::class)+class HtmlTextScrollModeTest {++ @get:Rule+ val rule = createAndroidComposeRule<ComponentActivity>()++ private fun webView(): WebView {+ var found: WebView? = null+ rule.runOnUiThread {+ val q = ArrayDeque<View>()+ q.add(rule.activity.findViewById(android.R.id.content))+ while (q.isNotEmpty() && found == null) {+ val v = q.removeFirst()+ if (v is WebView) found = v+ if (v is ViewGroup) for (i in 0 until v.childCount) q.add(v.getChildAt(i))+ }+ }+ return assertNotNull(found, "no WebView in the hierarchy")+ }++ @Test+ fun `default html text stays inline and wrap-content`() {+ rule.setContent { HtmlText(html = "<p>hello</p>") }+ rule.waitForIdle()+ val view = webView()+ assertEquals(ViewGroup.LayoutParams.WRAP_CONTENT, view.layoutParams.height)+ assertFalse(view.isVerticalScrollBarEnabled)+ assertFalse(view.settings.builtInZoomControls)+ assertTrue(view.settings.useWideViewPort)+ }++ @Test+ fun `scrolling html text fills its bounds and scrolls itself`() {+ rule.setContent {+ Column(Modifier.fillMaxSize()) {+ HtmlText(html = "<p>hello</p>", scrollInternally = true, modifier = Modifier.height(300.dp).testTag("body"))+ }+ }+ rule.waitForIdle()+ val view = webView()+ assertEquals(ViewGroup.LayoutParams.MATCH_PARENT, view.layoutParams.height)+ assertTrue(view.isVerticalScrollBarEnabled)+ assertTrue(view.settings.builtInZoomControls)+ assertFalse(view.settings.displayZoomControls)+ // The slot keeps the bounded height it was given; Robolectric reports the+ // WebView's own content height as 0, so a wrap-content view would collapse.+ rule.onNodeWithTag("body").assertHeightIsEqualTo(300.dp)+ }++ @Test+ fun `fit to width reaches the loaded document`() {+ rule.setContent { HtmlText(html = "<table width=600><tr><td>x</td></tr></table>", fitContentToWidth = true) }+ rule.waitForIdle()+ val data = shadowOf(webView()).lastLoadDataWithBaseURL?.data.orEmpty()+ assertTrue(data.contains(HtmlTextDocument.FIT_VIEWPORT), data.take(500))+ assertTrue(data.contains("overflow-wrap: anywhere"), data.take(2000))+ }++ @Test+ fun `re-running update with unchanged content does not reload the page`() {+ var scroll by mutableStateOf(false)+ rule.setContent {+ // Flipping a parameter the update block reads, but that does not change+ // the document, re-runs update exactly like any other recomposition.+ HtmlText(html = "<p>same</p>", scrollInternally = scroll, modifier = Modifier.height(200.dp))+ }+ rule.waitForIdle()+ val first = shadowOf(webView()).lastLoadDataWithBaseURL+ scroll = true+ rule.waitForIdle()+ assertEquals(ViewGroup.LayoutParams.MATCH_PARENT, webView().layoutParams.height, "update ran")+ assertSame(first, shadowOf(webView()).lastLoadDataWithBaseURL)+ }++ @Test+ fun `changed content still reloads`() {+ var body by mutableStateOf("<p>one</p>")+ rule.setContent { HtmlText(html = body) }+ rule.waitForIdle()+ assertTrue(shadowOf(webView()).lastLoadDataWithBaseURL?.data.orEmpty().contains("one"))+ body = "<p>two</p>"+ rule.waitForIdle()+ assertTrue(shadowOf(webView()).lastLoadDataWithBaseURL?.data.orEmpty().contains("two"))+ }+}