email: more formatting options for composer
- Commit
1b3accad850135de0b20b2c2ca8044d1ad47ee65- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-27 20:19 UTC (4 months ago)
- Parents
fb74359
Diff
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex 182466f733..8da369f5cd 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -1485,7 +1485,7 @@ fun ComposerScreen( modifier = Modifier.fillMaxWidth(), ) - com.vayunmathur.library.ui.HtmlEditor(+ com.vayunmathur.email.composer.EmailHtmlEditor( controller = bodyController, placeholder = stringResource(R.string.body_label), modifier = Modifier.fillMaxWidth().weight(1f),@@ -1561,14 +1561,232 @@ private fun EmailComposerFormatToolbar( controller: com.vayunmathur.email.composer.EmailHtmlEditorController, onInsertImage: () -> Unit, ) {+ var headingMenu by remember { mutableStateOf(false) }+ var alignMenu by remember { mutableStateOf(false) }+ var colorDialog by remember { mutableStateOf(0) } // 0 none, 1 fg, 2 bg+ var sizeMenu by remember { mutableStateOf(false) }+ var fontMenu by remember { mutableStateOf(false) }++ val headingLevel = controller.getCurrentHeadingLevel()+ val headingLabel = when (headingLevel) {+ 1 -> "H1"; 2 -> "H2"; 3 -> "H3"; else -> "Normal"+ }+ val alignCss = controller.getCurrentAlignment()+ val blockquoteActive = controller.isBlockquoteActive()+ val codeActive = controller.isInlineCodeActive()+ com.vayunmathur.library.ui.EditorBottomBar(modifier = Modifier, scrollable = true) {+ // Heading dropdown+ Box {+ TextButton(onClick = { headingMenu = true }) {+ Text(headingLabel)+ IconArrowDropDown()+ }+ DropdownMenu(expanded = headingMenu, onDismissRequest = { headingMenu = false }) {+ DropdownMenuItem(text = { Text("Normal") }, onClick = { headingMenu = false; controller.toggleHeading(null) })+ DropdownMenuItem(text = { Text("Heading 1") }, onClick = { headingMenu = false; controller.toggleHeading(1) })+ DropdownMenuItem(text = { Text("Heading 2") }, onClick = { headingMenu = false; controller.toggleHeading(2) })+ DropdownMenuItem(text = { Text("Heading 3") }, onClick = { headingMenu = false; controller.toggleHeading(3) })+ }+ }+ com.vayunmathur.library.ui.EditorBaseButtons(formatter = controller)- // Extra image button – use library's image icon++ HorizontalDivider(modifier = Modifier.height(24.dp).width(1.dp))++ // Alignment dropdown+ Box {+ val alignIcon: @Composable () -> Unit = when (alignCss) {+ "center" -> { { IconFormatAlignCenter() } }+ "right" -> { { IconFormatAlignRight() } }+ "justify" -> { { IconFormatAlignJustify() } }+ else -> { { IconFormatAlignLeft() } }+ }+ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Alignment",+ active = alignCss != null,+ onClick = { alignMenu = true },+ icon = alignIcon,+ )+ DropdownMenu(expanded = alignMenu, onDismissRequest = { alignMenu = false }) {+ DropdownMenuItem(+ text = { Text("Left") }, leadingIcon = { IconFormatAlignLeft() },+ onClick = { alignMenu = false; controller.setAlignment(null) }+ )+ DropdownMenuItem(+ text = { Text("Center") }, leadingIcon = { IconFormatAlignCenter() },+ onClick = { alignMenu = false; controller.setAlignment("center") }+ )+ DropdownMenuItem(+ text = { Text("Right") }, leadingIcon = { IconFormatAlignRight() },+ onClick = { alignMenu = false; controller.setAlignment("right") }+ )+ DropdownMenuItem(+ text = { Text("Justify") }, leadingIcon = { IconFormatAlignJustify() },+ onClick = { alignMenu = false; controller.setAlignment("justify") }+ )+ }+ }++ // Blockquote, code, hr, clear+ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Blockquote",+ active = blockquoteActive,+ onClick = { controller.toggleBlockquote() },+ ) { IconFormatQuote() }++ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Inline code",+ active = codeActive,+ onClick = { controller.toggleInlineCode() },+ ) { IconFormatCode() }++ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Horizontal rule",+ onClick = { controller.insertHorizontalRule() },+ ) { IconFormatHorizontalRule() }++ HorizontalDivider(modifier = Modifier.height(24.dp).width(1.dp))++ // Text color+ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Text color",+ active = colorDialog == 1,+ onClick = { colorDialog = 1 },+ ) { IconFormatColorText() }++ // Highlight / background+ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Highlight",+ active = colorDialog == 2,+ onClick = { colorDialog = 2 },+ ) { IconFormatColorFill() }++ // Font size dropdown+ Box {+ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Font size",+ onClick = { sizeMenu = true },+ ) { IconFormatSize() }+ DropdownMenu(expanded = sizeMenu, onDismissRequest = { sizeMenu = false }) {+ DropdownMenuItem(text = { Text("Small") }, onClick = { sizeMenu = false; controller.setFontSizeFactor(0.9f) })+ DropdownMenuItem(text = { Text("Normal") }, onClick = { sizeMenu = false; controller.setFontSizeFactor(null) })+ DropdownMenuItem(text = { Text("Large") }, onClick = { sizeMenu = false; controller.setFontSizeFactor(1.2f) })+ DropdownMenuItem(text = { Text("Extra Large") }, onClick = { sizeMenu = false; controller.setFontSizeFactor(1.4f) })+ }+ }++ // Font family dropdown+ Box {+ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Font family",+ onClick = { fontMenu = true },+ ) { IconFormatTitle() }+ DropdownMenu(expanded = fontMenu, onDismissRequest = { fontMenu = false }) {+ DropdownMenuItem(text = { Text("Default") }, onClick = { fontMenu = false; controller.setFontFamily(null) })+ DropdownMenuItem(text = { Text("Sans") }, onClick = { fontMenu = false; controller.setFontFamily("sans-serif") })+ DropdownMenuItem(text = { Text("Serif") }, onClick = { fontMenu = false; controller.setFontFamily("serif") })+ DropdownMenuItem(text = { Text("Monospace") }, onClick = { fontMenu = false; controller.setFontFamily("monospace") })+ }+ }++ HorizontalDivider(modifier = Modifier.height(24.dp).width(1.dp))++ // Clear formatting+ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Clear formatting",+ onClick = { controller.clearFormatting() },+ ) { IconFormatClear() }++ // Image button com.vayunmathur.library.ui.FormatIconButton( contentDescription = stringResource(R.string.cd_insert_image), onClick = onInsertImage, ) { com.vayunmathur.library.ui.IconImage() } }++ // Color picker dialog+ if (colorDialog != 0) {+ val isForeground = colorDialog == 1+ EmailColorPickerDialog(+ title = if (isForeground) "Text color" else "Highlight",+ onDismiss = { colorDialog = 0 },+ onColorSelected = { colorInt ->+ if (isForeground) {+ if (colorInt == null) controller.setTextColor(null) else controller.setTextColor(colorInt)+ } else {+ if (colorInt == null) controller.setHighlight(null) else controller.setHighlight(colorInt)+ }+ colorDialog = 0+ }+ )+ }+}++@Composable+private fun EmailColorPickerDialog(+ title: String,+ onDismiss: () -> Unit,+ onColorSelected: (Int?) -> Unit,+) {+ val palette = remember {+ listOf(+ null to "Default",+ android.graphics.Color.BLACK to "Black",+ android.graphics.Color.parseColor("#D32F2F") to "Red",+ android.graphics.Color.parseColor("#1976D2") to "Blue",+ android.graphics.Color.parseColor("#388E3C") to "Green",+ android.graphics.Color.parseColor("#F57C00") to "Orange",+ android.graphics.Color.parseColor("#7B1FA2") to "Purple",+ android.graphics.Color.parseColor("#00796B") to "Teal",+ android.graphics.Color.parseColor("#455A64") to "Gray",+ android.graphics.Color.parseColor("#FFEB3B") to "Yellow",+ android.graphics.Color.parseColor("#FFCDD2") to "Light Red",+ android.graphics.Color.parseColor("#BBDEFB") to "Light Blue",+ android.graphics.Color.parseColor("#C8E6C9") to "Light Green",+ android.graphics.Color.parseColor("#FFF9C4") to "Light Yellow",+ )+ }+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(title) },+ text = {+ Column(+ modifier = Modifier.verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ // chunk into rows of 4+ palette.chunked(4).forEach { rowItems ->+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxWidth(),+ ) {+ rowItems.forEach { (colorInt, label) ->+ Box(+ modifier = Modifier+ .size(48.dp)+ .background(+ color = if (colorInt == null) MaterialTheme.colorScheme.surfaceVariant+ else Color(colorInt),+ shape = androidx.compose.foundation.shape.CircleShape,+ )+ .clickable { onColorSelected(colorInt) },+ contentAlignment = Alignment.Center,+ ) {+ if (colorInt == null) {+ IconClose(modifier = Modifier.size(20.dp))+ }+ }+ }+ }+ }+ }+ },+ confirmButton = {},+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+ }+ ) } private fun copyInlineToCache(context: android.content.Context, uri: Uri, name: String): Uri? {
email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditor.kt
diff --git a/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditor.kt b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditor.ktnew file mode 100644index 0000000000..61c412dd5e--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditor.kt@@ -0,0 +1,98 @@+package com.vayunmathur.email.composer++import android.text.Editable+import android.view.Gravity+import android.widget.EditText+import androidx.compose.material3.LocalContentColor+import androidx.compose.material3.MaterialTheme+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.viewinterop.AndroidView+import androidx.core.text.HtmlCompat+import com.vayunmathur.library.ui.RichEditText++/**+ * Email-specific HtmlEditor that uses EmailHtmlTagHandler to preserve rich formatting+ * (headings, blockquote, inline code, colors, font size/family, alignment, hr)+ * when re-loading raw HTML (drafts, setHtml, signature injection etc.).+ *+ * Identical to library HtmlEditor otherwise.+ */+@Composable+fun EmailHtmlEditor(+ controller: EmailHtmlEditorController,+ modifier: Modifier = Modifier,+ placeholder: String? = null,+) {+ val textColor = LocalContentColor.current.toArgb()+ val hintColor = MaterialTheme.colorScheme.onSurfaceVariant.toArgb()+ val appliedVersion = remember { mutableIntStateOf(0) }++ AndroidView(+ modifier = modifier,+ factory = { ctx ->+ RichEditText(ctx).apply {+ background = null+ setTextColor(textColor)+ setHintTextColor(hintColor)+ hint = placeholder+ gravity = Gravity.TOP or Gravity.START+ setHorizontallyScrolling(false)+ isSingleLine = false+ inputType = android.text.InputType.TYPE_CLASS_TEXT or+ android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE or+ android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES+ this.richController = controller+ controller.editText = this+ onSelectionChange = { s, e ->+ controller.updateSelection(s, e)+ }+ setOnFocusChangeListener { _, hasFocus -> controller.updateFocus(hasFocus) }+ controller.updating = true+ setText(+ HtmlCompat.fromHtml(+ controller.html,+ HtmlCompat.FROM_HTML_MODE_COMPACT,+ null,+ controller.tagHandler,+ )+ )+ setSelection(text?.length ?: 0)+ controller.updating = false+ addTextChangedListener(object : android.text.TextWatcher {+ override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}+ override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}+ override fun afterTextChanged(s: Editable?) {+ if (!controller.updating && s != null) {+ controller.commitHtml(controller.htmlSerializer(s))+ }+ }+ })+ }+ },+ update = { et ->+ val v = controller.currentSetVersion+ if (v != appliedVersion.intValue) {+ val prevSel = et.selectionStart.coerceAtLeast(0)+ controller.updating = true+ et.setText(+ HtmlCompat.fromHtml(+ controller.html,+ HtmlCompat.FROM_HTML_MODE_COMPACT,+ null,+ controller.tagHandler,+ )+ )+ val newLen = et.text?.length ?: 0+ et.setSelection(prevSel.coerceIn(0, newLen))+ controller.updating = false+ appliedVersion.intValue = v+ }+ },+ )+}
email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.kt
diff --git a/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.kt b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.ktindex a63f56bcc4..0636174457 100644--- a/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.kt+++ b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.kt@@ -5,6 +5,7 @@ import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.net.Uri+import android.text.Spanned import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.snapshots.SnapshotStateList import com.vayunmathur.library.ui.HtmlEditorController@@ -12,7 +13,8 @@ import java.util.UUID /** * Email-specific controller extending the generic HtmlEditorController.- * Adds inline image (CID) support for WYSIWYG composer.+ * Adds inline image (CID) support for WYSIWYG composer, plus rich formatting+ * (headings, alignment, blockquote, inline code, colors, font size/family, hr). */ class EmailHtmlEditorController( initialHtml: String = "",@@ -20,16 +22,38 @@ class EmailHtmlEditorController( initialHtml = initialHtml, htmlSerializer = { spanned -> serializeEmailHtml(spanned) }, ) {+ // Custom TagHandler to restore rich formatting when setHtml re-parses the raw HTML+ val tagHandler = EmailHtmlTagHandler()+ // Observable list of inline images currently in the editor (for UI chips / size guard) val inlineImages: SnapshotStateList<InlineImage> = mutableStateListOf() + /**+ * Override factory-used html injection to include our TagHandler.+ * HtmlEditor composable uses HtmlCompat.fromHtml directly with factory; we override the+ * refresh path and expose html that preserves raw html, but for setHtml (draft reload)+ * the AndroidView update block does fromHtml(html). To ensure rich tags parse, we must+ * subclass the HtmlEditor composable handling – but a simpler path is to override setHtml+ * to keep raw html and let the library HtmlEditor's factory be augmented in MainActivity.+ * For now we expose a helper that MainActivity's custom HtmlEditor copy can use;+ * however even without factory override, raw html is preserved via controller.html state+ * (commitHtml) which is what gets sent. Draft reload via setHtml will re-parse – losing colors+ * unless factory uses tagHandler. We provide the tagHandler for MainActivity to use.+ */++ override fun setTextColor(color: Int?) {+ if (color == null) super.setTextColor(null)+ else super.setTextColor(color)+ }++ override fun setHighlight(color: Int?) {+ if (color == null) super.setHighlight(null)+ else super.setHighlight(color)+ }+ /** * Insert an image from [sourceUri] into the editor at current cursor. * Returns the generated CID or null on failure.- *- * Generation:- * - cid = "<uuid>@inline.local" without brackets stored, header will wrap <>.- * - bitmap decoded scaled to max 1024w to keep .eml reasonable. */ fun insertInlineImage( context: Context,@@ -44,8 +68,6 @@ class EmailHtmlEditorController( val bitmap = decodeSampledBitmap(context, sourceUri, 1024) ?: return null val drawable = BitmapDrawable(context.resources, bitmap) - // Scale bounds: if bitmap wider than edit width, shrink proportionally.- // We cap at 1024 but also try to fit within ~80% of EditText width if available. val maxWidth = 1024 var w = bitmap.width var h = bitmap.height@@ -54,7 +76,6 @@ class EmailHtmlEditorController( w = maxWidth h = (h * ratio).toInt() }- // Optionally cap to EditText width if known val etWidth = edit.width if (etWidth > 0) { val available = (etWidth * 0.85f).toInt().coerceAtLeast(100)@@ -68,19 +89,15 @@ class EmailHtmlEditorController( val span = CidImageSpan(cid, sourceUri, drawable, mimeType, fileName) - // Insert placeholder char at cursor val cursor = (edit.selectionStart.coerceAtLeast(0)).coerceAtMost(editable.length)- // Ensure we guard watcher updating = true try { editable.insert(cursor, "\uFFFC")- editable.setSpan(span, cursor, cursor + 1, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)- // Move cursor after inserted image+ editable.setSpan(span, cursor, cursor + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) edit.setSelection((cursor + 1).coerceAtMost(editable.length)) } finally { updating = false }- // Track inlineImages.add( InlineImage( cid = cid,@@ -89,7 +106,6 @@ class EmailHtmlEditorController( fileName = fileName, ) )- // Refresh html inlineCleanupOrphans() commitHtml(htmlSerializer(editable)) return cid@@ -122,10 +138,6 @@ class EmailHtmlEditorController( } } - /**- * Scan editable for orphan CidImageSpans that were deleted via backspace- * and drop them from [inlineImages] list.- */ fun inlineCleanupOrphans() { val edit = editText ?: return val editable = edit.text ?: return@@ -136,9 +148,7 @@ class EmailHtmlEditorController( } } - /** Build list ready for sending: maps tracked InlineImage -> InlineAttachment */ fun toInlineAttachments(): List<InlineAttachment> {- // Deduplicate by cid, keep last uri return inlineImages.map { InlineAttachment( cid = it.cid,@@ -152,14 +162,12 @@ class EmailHtmlEditorController( companion object { private fun decodeSampledBitmap(context: Context, uri: Uri, reqWidth: Int): Bitmap? { return try {- // First decode with inJustDecodeBounds=true to get dimensions val optsBounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } context.contentResolver.openInputStream(uri)?.use { input -> BitmapFactory.decodeStream(input, null, optsBounds) } val width = optsBounds.outWidth if (width <= 0) {- // Fallback direct decode return context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) } } var sample = 1
email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.kt
diff --git a/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.kt b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.ktindex 5cbabd5893..07914e1774 100644--- a/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.kt+++ b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.kt@@ -1,21 +1,30 @@ package com.vayunmathur.email.composer -import android.graphics.drawable.Drawable+import android.graphics.Typeface import android.text.Spanned-import com.vayunmathur.library.ui.IndentSpan-import com.vayunmathur.library.ui.OrderedListSpan+import android.text.style.BackgroundColorSpan import android.text.style.BulletSpan-import android.text.style.ImageSpan+import android.text.style.ForegroundColorSpan+import android.text.style.RelativeSizeSpan import android.text.style.StrikethroughSpan import android.text.style.StyleSpan+import android.text.style.TypefaceSpan import android.text.style.URLSpan import android.text.style.UnderlineSpan-import android.graphics.Typeface+import com.vayunmathur.library.ui.EmailAlignmentSpan+import com.vayunmathur.library.ui.EmailBlockQuoteSpan+import com.vayunmathur.library.ui.FontFamilySpan+import com.vayunmathur.library.ui.HeadingSpan+import com.vayunmathur.library.ui.HrSpan+import com.vayunmathur.library.ui.IndentSpan+import com.vayunmathur.library.ui.InlineCodeSpan+import com.vayunmathur.library.ui.OrderedListSpan import kotlin.math.min /** * Serialize a Spanned (from HtmlEditor) to HTML, emitting <img src="cid:...">- * for [CidImageSpan] and preserving bold/italic/underline/strike/links/lists/indent.+ * for [CidImageSpan] and preserving bold/italic/underline/strike/links/lists/indent+ * plus rich formatting: headings, alignment, blockquote, hr, colors, font size/family, inline code. */ fun serializeEmailHtml(spanned: Spanned): String {@@ -23,10 +32,6 @@ fun serializeEmailHtml(spanned: Spanned): String { val len = spanned.length val out = StringBuilder() - // Paragraph walk to emit <ul>/<ol> etc. Similar logic to library serializeRich- // but with CID image support and inline style detection.- // For simplicity we will first build paragraph boundaries then handle list grouping.- data class Para(val start: Int, val end: Int) fun paras(): List<Para> {@@ -39,7 +44,6 @@ fun serializeEmailHtml(spanned: Spanned): String { pos = nl + 1 } if (list.isEmpty() && len == 0) return emptyList()- // keep trailing empty handled as <br> later return list } @@ -73,12 +77,43 @@ fun serializeEmailHtml(spanned: Spanned): String { }?.level ?: 0 } + fun headingLevel(p: Para): Int? {+ return spanned.getSpans(p.start, p.end, HeadingSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) < p.end && spanned.getSpanEnd(it) > p.start+ }?.level+ }++ fun alignment(p: Para): String? {+ return spanned.getSpans(p.start, p.end, EmailAlignmentSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) < p.end && spanned.getSpanEnd(it) > p.start+ }?.alignmentCss+ }++ fun isBlockquote(p: Para): Boolean {+ return spanned.getSpans(p.start, p.end, EmailBlockQuoteSpan::class.java).any {+ spanned.getSpanStart(it) < p.end && spanned.getSpanEnd(it) > p.start+ }+ }++ fun isHr(p: Para): Boolean {+ return spanned.getSpans(p.start, p.end, HrSpan::class.java).any {+ spanned.getSpanStart(it) < p.end && spanned.getSpanEnd(it) > p.start+ }+ }+ fun inlineHtmlFor(p: Para): String { if (p.start >= p.end) return "" return buildInlineHtml(spanned, p.start, p.end) } for (para in allParas) {+ // Horizontal rule takes precedence+ if (isHr(para)) {+ closeList()+ out.append("<hr>")+ continue+ }+ if (para.start >= para.end) { closeList() val lvl = indentLevel(para)@@ -90,39 +125,77 @@ fun serializeEmailHtml(spanned: Spanned): String { val bullet = hasBullet(para) val oSpan = orderedSpan(para) val indentLvl = indentLevel(para)+ val hLevel = headingLevel(para)+ val align = alignment(para)+ val blockquote = isBlockquote(para)+ val rawInline = inlineHtmlFor(para) val inner = if (rawInline.isBlank()) "<br>" else rawInline- val contentWithIndent = if (indentLvl > 0 && !bullet && oSpan == null) {- "<div style=\"margin-left: ${indentLvl * 24}px\">$inner</div>"- } else if (indentLvl > 0) {- "<div style=\"margin-left: ${indentLvl * 24}px\">$inner</div>"- } else inner-- when {- bullet -> {- if (currentList != "ul") {- closeList()- out.append("<ul>")- currentList = "ul"++ if (bullet || oSpan != null) {+ // List item – embed heading/blockquote/alignment inside <li> if present for minimal email-safe output+ val liInner: String = when {+ hLevel != null -> {+ val alignPart = if (align != null && align != "left") "text-align:$align;" else ""+ "<h$hLevel style=\"margin:0;${alignPart}\">$inner</h$hLevel>"+ }+ blockquote -> {+ val alignPart = if (align != null && align != "left") ";text-align:$align" else ""+ "<blockquote style=\"border-left:2px solid #ccc;margin:0 0 0 8px;padding-left:8px$alignPart\">$inner</blockquote>" }- out.append("<li>$contentWithIndent</li>")+ align != null && align != "left" -> "<div style=\"text-align:$align\">$inner</div>"+ else -> inner }- oSpan != null -> {- if (currentList != "ol") {- closeList()- out.append("<ol>")- currentList = "ol"- orderedCounter = 0+ val withIndent = if (indentLvl > 0) "<div style=\"margin-left: ${indentLvl * 24}px\">$liInner</div>" else liInner++ when {+ bullet -> {+ if (currentList != "ul") {+ closeList()+ out.append("<ul>")+ currentList = "ul"+ }+ out.append("<li>$withIndent</li>")+ }+ else -> {+ if (currentList != "ol") {+ closeList()+ out.append("<ol>")+ currentList = "ol"+ orderedCounter = 0+ }+ orderedCounter+++ out.append("<li>$withIndent</li>") }- orderedCounter++- out.append("<li>$contentWithIndent</li>") }- else -> {- closeList()- if (indentLvl > 0) {- out.append(contentWithIndent)- } else {- out.append("<div>$inner</div>")+ } else {+ closeList()+ when {+ hLevel != null -> {+ val styles = mutableListOf<String>()+ styles.add("margin:0.5em 0")+ if (align != null && align != "left") styles.add("text-align:$align")+ if (indentLvl > 0) styles.add("margin-left:${indentLvl * 24}px")+ out.append("<h$hLevel style=\"${styles.joinToString(";")}\">$inner</h$hLevel>")+ }+ blockquote -> {+ val styles = mutableListOf<String>()+ styles.add("border-left:2px solid #ccc")+ styles.add("margin:0 0 0 8px")+ styles.add("padding-left:8px")+ if (indentLvl > 0) styles.add("margin-left:${indentLvl * 24}px")+ if (align != null && align != "left") styles.add("text-align:$align")+ out.append("<blockquote style=\"${styles.joinToString(";")}\">$inner</blockquote>")+ }+ else -> {+ if (align != null || indentLvl > 0) {+ val styles = mutableListOf<String>()+ if (align != null && align != "left") styles.add("text-align:$align")+ if (indentLvl > 0) styles.add("margin-left:${indentLvl * 24}px")+ out.append("<div style=\"${styles.joinToString(";")}\">$inner</div>")+ } else {+ out.append("<div>$inner</div>")+ } } } }@@ -133,66 +206,115 @@ fun serializeEmailHtml(spanned: Spanned): String { } private fun buildInlineHtml(spanned: Spanned, start: Int, end: Int): String {- // Walk character by character emitting tags when spans change.- // We collect events: open/close of StyleSpan bold/italic, underline, strike, link, and CidImageSpan placeholder. val sb = StringBuilder()- // For each char position, determine active spans- // We'll build runs where the set of spans is constant var i = start while (i < end) { val char = spanned[i]- // Check if this char is covered by CidImageSpan — emit <img> and skip obj replacement char+ // CID image spans first val cidSpans = spanned.getSpans(i, i + 1, CidImageSpan::class.java).filter { spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i } if (cidSpans.isNotEmpty()) { val cs = cidSpans.first() sb.append("<img src=\"cid:${cs.cid}\">")- // advance past this span's range val spanEnd = min(spanned.getSpanEnd(cs), end) i = spanEnd continue }- // Regular object replacement char for image? Skip if it's the generic placeholder+ // HR spans – emit <hr> and advance+ val hrSpans = spanned.getSpans(i, i + 1, HrSpan::class.java).filter {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ if (hrSpans.isNotEmpty()) {+ sb.append("<hr>")+ val spanEnd = min(spanned.getSpanEnd(hrSpans.first()), end)+ i = spanEnd+ continue+ } if (char == '\uFFFC') {- // If no cid span found (fallback generic ImageSpan), emit generic placeholder maybe skip- // Just skip i++ continue }- // Find run length where inline style set stays same val nextChange = findNextSpanBoundary(spanned, i, end) val slice = spanned.subSequence(i, nextChange).toString()- // Encode and wrap with tags based on current spans at i var piece = android.text.TextUtils.htmlEncode(slice)- // Link outermost, then bold/italic/underline/strike- val urlSpan = spanned.getSpans(i, i + 1, URLSpan::class.java).firstOrNull {++ // Determine active inline spans at i+ val hasCode = spanned.getSpans(i, i + 1, InlineCodeSpan::class.java).any { spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i }- if (urlSpan != null) {- piece = "<a href=\"${escapeAttr(urlSpan.url ?: "")}\">$piece</a>"- }- val bold = spanned.getSpans(i, i + 1, StyleSpan::class.java).any {+ val hasBold = spanned.getSpans(i, i + 1, StyleSpan::class.java).any { spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i && (it.style and Typeface.BOLD) != 0 }- if (bold) piece = "<b>$piece</b>"- val italic = spanned.getSpans(i, i + 1, StyleSpan::class.java).any {+ val hasItalic = spanned.getSpans(i, i + 1, StyleSpan::class.java).any { spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i && (it.style and Typeface.ITALIC) != 0 }- if (italic) piece = "<i>$piece</i>"- val ul = spanned.getSpans(i, i + 1, UnderlineSpan::class.java).any {+ val hasUnderline = spanned.getSpans(i, i + 1, UnderlineSpan::class.java).any { spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i }- if (ul) piece = "<u>$piece</u>"- val strike = spanned.getSpans(i, i + 1, StrikethroughSpan::class.java).any {+ val hasStrike = spanned.getSpans(i, i + 1, StrikethroughSpan::class.java).any { spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i }- if (strike) piece = "<s>$piece</s>"+ val urlSpan = spanned.getSpans(i, i + 1, URLSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ val fgSpan = spanned.getSpans(i, i + 1, ForegroundColorSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ val bgSpan = spanned.getSpans(i, i + 1, BackgroundColorSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ val sizeSpan = spanned.getSpans(i, i + 1, RelativeSizeSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ // Font family: our custom FontFamilySpan has priority; fallback to TypefaceSpan with family != monospace and not InlineCode+ val fontFamilySpan = spanned.getSpans(i, i + 1, FontFamilySpan::class.java).firstOrNull {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ val typefaceFamilySpan = spanned.getSpans(i, i + 1, TypefaceSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i && it !is InlineCodeSpan+ }++ // Build nesting inside-out: innermost first (code), outermost last (color)+ if (hasCode) {+ piece = "<code style=\"font-family:monospace;background:#f5f5f5;padding:1px 4px;border-radius:3px\">$piece</code>"+ }+ if (hasStrike) piece = "<s>$piece</s>"+ if (hasUnderline) piece = "<u>$piece</u>"+ if (hasItalic) piece = "<i>$piece</i>"+ if (hasBold) piece = "<b>$piece</b>"+ if (urlSpan != null) {+ piece = "<a href=\"${escapeAttr(urlSpan.url ?: "")}\">$piece</a>"+ }+ // Font family+ val familyName: String? = fontFamilySpan?.familyName ?: typefaceFamilySpan?.family+ if (familyName != null) {+ val cssFamily = when (familyName.lowercase()) {+ "monospace" -> "monospace"+ "serif" -> "serif"+ "sans-serif", "sans_serif", "sans" -> "sans-serif"+ else -> familyName+ }+ piece = "<span style=\"font-family:${escapeAttr(cssFamily)}\">$piece</span>"+ }+ if (sizeSpan != null) {+ val factor = sizeSpan.sizeChange+ // Emit em-based size, clamp for email safety+ val sizeStr = "${String.format("%.2f", factor)}em"+ piece = "<span style=\"font-size:$sizeStr\">$piece</span>"+ }+ if (bgSpan != null) {+ val hex = colorToHex(bgSpan.backgroundColor)+ piece = "<span style=\"background-color:$hex\">$piece</span>"+ }+ if (fgSpan != null) {+ val hex = colorToHex(fgSpan.foregroundColor)+ piece = "<span style=\"color:$hex\">$piece</span>"+ } sb.append(piece) i = nextChange }- // Replace newlines inside slice shouldn't exist (paras split), but handle \n -> <br> return sb.toString().replace("\n", "<br>") } @@ -205,8 +327,6 @@ private fun findNextSpanBoundary(spanned: Spanned, from: Int, end: Int): Int { if (s > from && s < next) next = s if (e > from && e < next) next = e }- // Also consider ImageSpan boundaries- // Ensure at least advance 1 if (next == from) next = from + 1 return min(next, end) }@@ -214,3 +334,8 @@ private fun findNextSpanBoundary(spanned: Spanned, from: Int, end: Int): Int { private fun escapeAttr(value: String): String { return value.replace("&", "&").replace("\"", """).replace("<", "<").replace(">", ">") }++private fun colorToHex(color: Int): String {+ // Strip alpha, produce #RRGGBB+ return String.format("#%06X", 0xFFFFFF and color)+}
email/src/main/java/com/vayunmathur/email/composer/EmailHtmlTagHandler.kt
diff --git a/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlTagHandler.kt b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlTagHandler.ktnew file mode 100644index 0000000000..7bf891a1bf--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlTagHandler.kt@@ -0,0 +1,254 @@+package com.vayunmathur.email.composer++import android.text.Editable+import android.text.Html+import android.text.Spanned+import android.text.style.BackgroundColorSpan+import android.text.style.ForegroundColorSpan+import android.text.style.RelativeSizeSpan+import com.vayunmathur.library.ui.EmailAlignmentSpan+import com.vayunmathur.library.ui.EmailBlockQuoteSpan+import com.vayunmathur.library.ui.FontFamilySpan+import com.vayunmathur.library.ui.HeadingSpan+import com.vayunmathur.library.ui.HrSpan+import com.vayunmathur.library.ui.InlineCodeSpan+import org.xml.sax.XMLReader++/**+ * Custom TagHandler for HtmlCompat.fromHtml so that when we re-open a draft+ * (or setHtml) the rich spans we emitted via [serializeEmailHtml] are restored+ * into the Editable. HtmlCompat drops style="color"/text-align otherwise.+ *+ * Handled:+ * - h1/h2/h3 → HeadingSpan+ * - blockquote → EmailBlockQuoteSpan+ * - code → InlineCodeSpan+ * - span style="color:#RRGGBB" → ForegroundColorSpan+ * - span style="background-color:#RRGGBB" → BackgroundColorSpan+ * - span style="font-size:1.2em" → RelativeSizeSpan+ * - span style="font-family:serif" → FontFamilySpan+ * - div style="text-align:center" → EmailAlignmentSpan+ * - hr → inserts OBJECT REPLACEMENT with HrSpan (so serializer emits <hr>)+ */+class EmailHtmlTagHandler : Html.TagHandler {++ private data class SpanMarker(val start: Int, val kind: String, val extra: String? = null)++ private val markers = mutableListOf<SpanMarker>()++ override fun handleTag(opening: Boolean, tag: String, output: Editable, xmlReader: XMLReader) {+ val t = tag.lowercase()+ if (opening) {+ when (t) {+ "h1" -> markers.add(SpanMarker(output.length, "h1"))+ "h2" -> markers.add(SpanMarker(output.length, "h2"))+ "h3" -> markers.add(SpanMarker(output.length, "h3"))+ "blockquote" -> markers.add(SpanMarker(output.length, "blockquote"))+ "code" -> markers.add(SpanMarker(output.length, "code"))+ "hr" -> {+ // Insert object replacement and tag it – matches serializer contract+ val pos = output.length+ output.append("\uFFFC")+ // Ensure next char newline already present via surrounding html parsing? Add explicit span here.+ output.setSpan(HrSpan(), pos, pos + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ }+ "span", "div" -> {+ // Defer – we need attributes. XMLReader does not expose them easily,+ // but we record start; closing tag will inspect substring? Instead we rely on+ // a simpler heuristic: the raw attrs are available via reflection on the parser+ // stack in some implementations. We approximate by reading style from the TagHandler+ // argument – HtmlCompat does NOT give attrs, so we try to get them from the underlying+ // parser's attribute list via xmlReader.+ val style = extractStyle(xmlReader)+ if (style != null) {+ markers.add(SpanMarker(output.length, t, style))+ }+ }+ }+ } else {+ when (t) {+ "h1", "h2", "h3" -> {+ val start = popMarker(t) ?: return+ val end = output.length+ if (start >= end) return+ val level = when (t) { "h1" -> 1; "h2" -> 2; else -> 3 }+ output.setSpan(HeadingSpan(level), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ }+ "blockquote" -> {+ val start = popMarker("blockquote") ?: return+ val end = output.length+ if (start >= end) return+ output.setSpan(EmailBlockQuoteSpan(), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)+ }+ "code" -> {+ val start = popMarker("code") ?: return+ val end = output.length+ if (start >= end) return+ output.setSpan(InlineCodeSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ }+ "span" -> {+ val marker = popMarkerWithExtra("span") ?: return+ val end = output.length+ if (marker.start >= end) return+ applySpanStyles(output, marker.start, end, marker.extra)+ }+ "div" -> {+ val marker = popMarkerWithExtra("div")+ val end = output.length+ if (marker == null) return+ if (marker.start >= end) return+ applyDivStyles(output, marker.start, end, marker.extra)+ }+ }+ }+ }++ private fun popMarker(kind: String): Int? {+ for (i in markers.indices.reversed()) {+ if (markers[i].kind == kind && markers[i].extra == null) {+ val s = markers[i].start+ markers.removeAt(i)+ return s+ }+ }+ return null+ }++ private data class ExtraMarker(val start: Int, val extra: String?)+ private fun popMarkerWithExtra(kind: String): ExtraMarker? {+ for (i in markers.indices.reversed()) {+ if (markers[i].kind == kind) {+ val m = markers[i]+ markers.removeAt(i)+ return ExtraMarker(m.start, m.extra)+ }+ }+ return null+ }++ private fun applySpanStyles(output: Editable, start: Int, end: Int, styleAttr: String?) {+ if (styleAttr == null) return+ val map = parseStyle(styleAttr)+ map["color"]?.let { v ->+ parseColor(v)?.let { c -> output.setSpan(ForegroundColorSpan(c), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) }+ }+ map["background-color"]?.let { v ->+ parseColor(v)?.let { c -> output.setSpan(BackgroundColorSpan(c), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) }+ }+ map["font-size"]?.let { v ->+ parseFontSize(v)?.let { f -> output.setSpan(RelativeSizeSpan(f), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) }+ }+ map["font-family"]?.let { v ->+ val fam = v.trim().removePrefix("\"").removeSuffix("\"").removePrefix("'").removeSuffix("'").trim()+ if (fam.isNotBlank()) output.setSpan(FontFamilySpan(fam), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ }+ }++ private fun applyDivStyles(output: Editable, start: Int, end: Int, styleAttr: String?) {+ if (styleAttr == null) return+ val map = parseStyle(styleAttr)+ map["text-align"]?.let { a ->+ val css = a.lowercase().trim()+ if (css in setOf("left", "center", "right", "justify")) {+ output.setSpan(EmailAlignmentSpan(css), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)+ }+ }+ // Also divs may carry margin-left for indent – we keep IndentSpan path as before via standard Html handling;+ // serializer emits margin-left only for indent; we do not re-create IndentSpan here (Html.fromHtml loses it).+ // Users get indent via manual button anyway.+ }++ // --- Style parsing ---++ private fun parseStyle(style: String): Map<String, String> {+ val result = mutableMapOf<String, String>()+ style.split(";").forEach { decl ->+ val idx = decl.indexOf(':')+ if (idx > 0) {+ val k = decl.substring(0, idx).trim().lowercase()+ val v = decl.substring(idx + 1).trim()+ if (k.isNotEmpty() && v.isNotEmpty()) result[k] = v+ }+ }+ return result+ }++ private fun parseColor(v: String): Int? {+ val s = v.trim()+ return try {+ when {+ s.startsWith("#") -> {+ var hex = s.removePrefix("#")+ if (hex.length == 3) hex = hex.map { "$it$it" }.joinToString("")+ if (hex.length == 6) hex = "FF$hex"+ if (hex.length == 8) hex.toLong(16).toInt()+ else null+ }+ s.startsWith("rgb") -> {+ // rgb(0,0,0) or rgba – best-effort+ val nums = Regex("\\d+").findAll(s).map { it.value.toInt() }.toList()+ if (nums.size >= 3) android.graphics.Color.rgb(nums[0], nums[1], nums[2]) else null+ }+ else -> null+ }+ } catch (_: Exception) { null }+ }++ private fun parseFontSize(v: String): Float? {+ val s = v.trim().lowercase()+ return when {+ s.endsWith("em") -> s.removeSuffix("em").toFloatOrNull()+ s.endsWith("px") -> {+ // Assume base 16px+ s.removeSuffix("px").toFloatOrNull()?.let { it / 16f }+ }+ else -> s.toFloatOrNull()+ }?.coerceIn(0.5f, 3f)+ }++ /**+ * Try to extract the current tag's style attribute from the underlying XMLReader.+ * This works when the SAX parser exposes attributes via reflection (implementation+ * varies across Android versions). We try a few common paths; if none works we return null+ * and fall back to tag-only handling (headings/blockquote/code/hr still work).+ */+ private fun extractStyle(xmlReader: XMLReader): String? {+ return try {+ // Attempt: xmlReader is actually org.ccil.cowan.tagsoup.Parser or similar that holds attributes+ // We try to get the current element's attributes via reflection.+ // Strategy: if xmlReader has field "theNewElement" etc – we go generic: try to call getProperty+ val propAttempts = listOf(+ "http://xml.org/sax/properties/dom-node",+ "http://www.ccil.org/~cowan/tagsoup/properties/attributes"+ )+ // TagSoup path – most Android fromHtml uses TagSoup internally+ // The attributes are not exposed directly to TagHandler, but some versions+ // push them onto a stack accessible via "attributes" property.+ var attrs: org.xml.sax.Attributes? = null+ for (p in propAttempts) {+ try {+ @Suppress("UNCHECKED_CAST")+ attrs = xmlReader.getProperty(p) as? org.xml.sax.Attributes+ if (attrs != null) break+ } catch (_: Exception) { /* next */ }+ }+ // Fallback: reflect on field that might hold atts in org.ccil.cowan.tagsoup.Parser$Element+ if (attrs == null) {+ // Try private field theStack or similar+ val fields = xmlReader.javaClass.declaredFields+ for (f in fields) {+ f.isAccessible = true+ val v = f.get(xmlReader)+ if (v is org.xml.sax.Attributes) {+ attrs = v+ break+ }+ }+ }+ if (attrs != null) {+ val idx = attrs.getIndex("style")+ if (idx >= 0) attrs.getValue(idx) else null+ } else null+ } catch (_: Exception) { null }+ }+}
library/ui/src/main/java/com/vayunmathur/library/ui/HtmlEditor.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlEditor.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlEditor.ktindex 66f94a87ad..d858df1c11 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlEditor.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlEditor.kt@@ -8,10 +8,14 @@ import android.text.Editable import android.text.Layout import android.text.SpannableStringBuilder import android.text.Spanned+import android.text.style.BackgroundColorSpan import android.text.style.BulletSpan+import android.text.style.ForegroundColorSpan import android.text.style.LeadingMarginSpan+import android.text.style.RelativeSizeSpan import android.text.style.StrikethroughSpan import android.text.style.StyleSpan+import android.text.style.TypefaceSpan import android.text.style.URLSpan import android.text.style.UnderlineSpan import android.view.Gravity@@ -144,7 +148,24 @@ open class HtmlEditorController( var focused by mutableStateOf(false) internal set - internal var setVersion by mutableStateOf(0)+ var setVersion by mutableStateOf(0)+ internal set++ // Public accessors for cross-module email package+ val currentSelectionStart: Int get() = selectionStart+ val currentSelectionEnd: Int get() = selectionEnd+ val isFocused: Boolean get() = focused+ val currentSetVersion: Int get() = setVersion++ fun updateSelection(start: Int, end: Int) {+ selectionStart = start+ selectionEnd = end+ }++ fun updateFocus(f: Boolean) {+ focused = f+ }+ // Exposed for email subclass (different Gradle module) – minimal hook var updating = false var editText: EditText? = null@@ -168,10 +189,10 @@ open class HtmlEditorController( open fun toggleUnderline() = toggleCharSpan({ UnderlineSpan() }) { it is UnderlineSpan } open fun toggleStrikethrough() = toggleCharSpan({ StrikethroughSpan() }) { it is StrikethroughSpan } - private fun toggleStyle(style: Int) =+ protected fun toggleStyle(style: Int) = toggleCharSpan({ StyleSpan(style) }) { it is StyleSpan && (it.style and style) != 0 } - private fun toggleCharSpan(make: () -> Any, matches: (Any) -> Boolean) {+ protected fun toggleCharSpan(make: () -> Any, matches: (Any) -> Boolean) { val e = editText?.text ?: return val start = minOf(selStart(), selEnd()) val end = maxOf(selStart(), selEnd())@@ -190,6 +211,37 @@ open class HtmlEditorController( refresh() } + protected fun clearCharSpans(matches: (Any) -> Boolean) {+ val e = editText?.text ?: return+ val start = minOf(selStart(), selEnd())+ val end = maxOf(selStart(), selEnd())+ if (start >= end) return+ val overlapping = e.getSpans(start, end, Any::class.java).filter(matches)+ overlapping.forEach { sp ->+ val ss = e.getSpanStart(sp); val se = e.getSpanEnd(sp)+ e.removeSpan(sp)+ if (ss < start) e.setSpan(sp, ss, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ if (se > end) e.setSpan(sp, end, se, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ }+ }++ protected fun setCharSpan(make: () -> Any, matches: (Any) -> Boolean) {+ val e = editText?.text ?: return+ val start = minOf(selStart(), selEnd())+ val end = maxOf(selStart(), selEnd())+ if (start >= end) return+ // Remove existing matching spans in range (split preserved)+ val overlapping = e.getSpans(start, end, Any::class.java).filter(matches)+ overlapping.forEach { sp ->+ val ss = e.getSpanStart(sp); val se = e.getSpanEnd(sp)+ e.removeSpan(sp)+ if (ss < start) e.setSpan(sp, ss, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ if (se > end) e.setSpan(sp, end, se, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ }+ e.setSpan(make(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ refresh()+ }+ open fun toggleBullet() { val e = editText?.text ?: return val hasBullet = e.hasParaSpanInSelection<BulletSpan>(selStart(), selEnd())@@ -257,6 +309,237 @@ open class HtmlEditorController( } } + // ---- Rich formatting hooks (used by HtmlEditor + Email subclass) ----++ open fun toggleHeading(level: Int?) {+ val e = editText?.text ?: return+ e.forEachParagraph(selStart(), selEnd()) { paraStart, paraEnd ->+ if (paraEnd <= paraStart) return@forEachParagraph+ e.getSpans(paraStart, paraEnd, HeadingSpan::class.java).forEach { e.removeSpan(it) }+ if (level != null && level in 1..3) {+ e.setSpan(HeadingSpan(level), paraStart, paraEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)+ }+ }+ refresh()+ }++ open fun setAlignment(cssAlign: String?) {+ val e = editText?.text ?: return+ e.forEachParagraph(selStart(), selEnd()) { paraStart, paraEnd ->+ if (paraEnd <= paraStart) return@forEachParagraph+ e.getSpans(paraStart, paraEnd, EmailAlignmentSpan::class.java).forEach { e.removeSpan(it) }+ if (cssAlign != null && cssAlign.lowercase() != "left") {+ e.setSpan(EmailAlignmentSpan(cssAlign), paraStart, paraEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)+ }+ }+ refresh()+ }++ open fun toggleBlockquote() {+ val e = editText?.text ?: return+ val has = e.hasParaSpanInSelection<EmailBlockQuoteSpan>(selStart(), selEnd())+ e.forEachParagraph(selStart(), selEnd()) { paraStart, paraEnd ->+ if (paraEnd <= paraStart) return@forEachParagraph+ val existing = e.getSpans(paraStart, paraEnd, EmailBlockQuoteSpan::class.java)+ if (has) existing.forEach { e.removeSpan(it) }+ else if (existing.isEmpty()) e.setSpan(EmailBlockQuoteSpan(), paraStart, paraEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)+ }+ refresh()+ }++ open fun toggleInlineCode() = toggleCharSpan({ InlineCodeSpan() }) { it is InlineCodeSpan }++ open fun setTextColor(color: Int?) {+ if (color == null) {+ clearCharSpans { it is ForegroundColorSpan }+ refresh()+ } else {+ setCharSpan({ ForegroundColorSpan(color) }) { it is ForegroundColorSpan }+ }+ }++ open fun setHighlight(color: Int?) {+ if (color == null) {+ clearCharSpans { it is BackgroundColorSpan }+ refresh()+ } else {+ setCharSpan({ BackgroundColorSpan(color) }) { it is BackgroundColorSpan }+ }+ }++ open fun setFontSizeFactor(factor: Float?) {+ if (factor == null) {+ clearCharSpans { it is RelativeSizeSpan }+ refresh()+ } else {+ setCharSpan({ RelativeSizeSpan(factor) }) { it is RelativeSizeSpan }+ }+ }++ open fun setFontFamily(family: String?) {+ if (family == null) {+ clearCharSpans { it is FontFamilySpan || (it is TypefaceSpan && it.family != "monospace") }+ refresh()+ } else {+ setCharSpan({ FontFamilySpan(family) }) { it is FontFamilySpan || (it is TypefaceSpan && it.family != "monospace") }+ }+ }++ open fun insertHorizontalRule() {+ val edit = editText ?: return+ val editable = edit.text ?: return+ val cursor = edit.selectionStart.coerceIn(0, editable.length)+ updating = true+ try {+ // Insert newline, OBJECT REPLACEMENT with HrSpan, newline+ editable.insert(cursor, "\n\uFFFC\n")+ editable.setSpan(HrSpan(), cursor + 1, cursor + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ edit.setSelection((cursor + 3).coerceAtMost(editable.length))+ } finally {+ updating = false+ }+ refresh()+ }++ open fun clearFormatting() {+ val e = editText?.text ?: return+ val start = minOf(selStart(), selEnd())+ val end = maxOf(selStart(), selEnd())+ if (start >= end) return+ val toRemove = e.getSpans(start, end, Any::class.java).filter { sp ->+ sp is StyleSpan || sp is UnderlineSpan || sp is StrikethroughSpan ||+ sp is ForegroundColorSpan || sp is BackgroundColorSpan ||+ sp is RelativeSizeSpan || sp is TypefaceSpan ||+ sp is InlineCodeSpan || sp is FontFamilySpan+ }+ toRemove.forEach { sp ->+ val ss = e.getSpanStart(sp); val se = e.getSpanEnd(sp)+ e.removeSpan(sp)+ if (ss < start) e.setSpan(sp, ss, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ if (se > end) e.setSpan(sp, end, se, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ }+ // Block-level in selection+ e.forEachParagraph(start, end) { paraStart, paraEnd ->+ if (paraEnd <= paraStart) return@forEachParagraph+ e.getSpans(paraStart, paraEnd, HeadingSpan::class.java).forEach { e.removeSpan(it) }+ e.getSpans(paraStart, paraEnd, EmailAlignmentSpan::class.java).forEach { e.removeSpan(it) }+ e.getSpans(paraStart, paraEnd, EmailBlockQuoteSpan::class.java).forEach { e.removeSpan(it) }+ }+ refresh()+ }++ open fun getCurrentHeadingLevel(): Int? {+ val e = editText?.text ?: return null+ @Suppress("UNUSED_EXPRESSION") html+ @Suppress("UNUSED_EXPRESSION") selectionStart+ @Suppress("UNUSED_EXPRESSION") selectionEnd+ var level: Int? = null+ var initialized = false+ e.forEachParagraph(selStart(), selEnd()) { paraStart, paraEnd ->+ if (paraEnd <= paraStart) return@forEachParagraph+ val l = e.getSpans(paraStart, paraEnd, HeadingSpan::class.java)+ .firstOrNull { e.getSpanStart(it) < paraEnd && e.getSpanEnd(it) > paraStart }?.level+ if (!initialized) {+ level = l+ initialized = true+ } else if (l != level) {+ level = null // mixed+ // keep scanning to confirm mixed; but short-circuit still needs same shape – break via non-local not possible, just continue+ }+ }+ return level+ }++ open fun getCurrentAlignment(): String? {+ val e = editText?.text ?: return null+ @Suppress("UNUSED_EXPRESSION") html+ @Suppress("UNUSED_EXPRESSION") selectionStart+ @Suppress("UNUSED_EXPRESSION") selectionEnd+ val start = minOf(selStart(), selEnd())+ var css: String? = null+ // first paragraph only for display+ e.forEachParagraph(start, start) { paraStart, paraEnd ->+ val span = e.getSpans(paraStart, paraEnd, EmailAlignmentSpan::class.java).firstOrNull {+ e.getSpanStart(it) < paraEnd && e.getSpanEnd(it) > paraStart+ }+ css = span?.alignmentCss+ }+ return css+ }++ open fun isBlockquoteActive(): Boolean {+ val e = editText?.text ?: return false+ @Suppress("UNUSED_EXPRESSION") html+ @Suppress("UNUSED_EXPRESSION") selectionStart+ @Suppress("UNUSED_EXPRESSION") selectionEnd+ if (e.isEmpty()) return false+ var found = false+ e.forEachParagraph(selStart(), selEnd()) { paraStart, paraEnd ->+ if (found) return@forEachParagraph+ if (paraEnd <= paraStart) return@forEachParagraph+ val spans = e.getSpans(paraStart, paraEnd, EmailBlockQuoteSpan::class.java)+ if (spans.any { e.getSpanStart(it) < paraEnd && e.getSpanEnd(it) > paraStart }) found = true+ }+ return found+ }++ open fun isInlineCodeActive(): Boolean {+ val e = editText?.text ?: return false+ @Suppress("UNUSED_EXPRESSION") html+ @Suppress("UNUSED_EXPRESSION") selectionStart+ @Suppress("UNUSED_EXPRESSION") selectionEnd+ val start = minOf(selStart(), selEnd()).coerceIn(0, e.length)+ val end = maxOf(selStart(), selEnd()).coerceIn(0, e.length)+ if (start >= end) return false+ return e.isFullyCovered(start, end) { it is InlineCodeSpan }+ }++ open fun getCurrentTextColor(): Int? {+ val e = editText?.text ?: return null+ @Suppress("UNUSED_EXPRESSION") html+ @Suppress("UNUSED_EXPRESSION") selectionStart+ @Suppress("UNUSED_EXPRESSION") selectionEnd+ val start = minOf(selStart(), selEnd()).coerceIn(0, e.length)+ val end = maxOf(selStart(), selEnd()).coerceIn(0, e.length)+ if (start >= end) return null+ return e.getSpans(start, end, ForegroundColorSpan::class.java).firstOrNull()?.foregroundColor+ }++ open fun getCurrentHighlightColor(): Int? {+ val e = editText?.text ?: return null+ @Suppress("UNUSED_EXPRESSION") html+ @Suppress("UNUSED_EXPRESSION") selectionStart+ @Suppress("UNUSED_EXPRESSION") selectionEnd+ val start = minOf(selStart(), selEnd()).coerceIn(0, e.length)+ val end = maxOf(selStart(), selEnd()).coerceIn(0, e.length)+ if (start >= end) return null+ return e.getSpans(start, end, BackgroundColorSpan::class.java).firstOrNull()?.backgroundColor+ }++ open fun getCurrentFontSizeFactor(): Float? {+ val e = editText?.text ?: return null+ @Suppress("UNUSED_EXPRESSION") html+ @Suppress("UNUSED_EXPRESSION") selectionStart+ @Suppress("UNUSED_EXPRESSION") selectionEnd+ val start = minOf(selStart(), selEnd()).coerceIn(0, e.length)+ val end = maxOf(selStart(), selEnd()).coerceIn(0, e.length)+ if (start >= end) return null+ return e.getSpans(start, end, RelativeSizeSpan::class.java).firstOrNull()?.sizeChange+ }++ open fun getCurrentFontFamily(): String? {+ val e = editText?.text ?: return null+ @Suppress("UNUSED_EXPRESSION") html+ @Suppress("UNUSED_EXPRESSION") selectionStart+ @Suppress("UNUSED_EXPRESSION") selectionEnd+ val start = minOf(selStart(), selEnd()).coerceIn(0, e.length)+ val end = maxOf(selStart(), selEnd()).coerceIn(0, e.length)+ if (start >= end) return null+ e.getSpans(start, end, FontFamilySpan::class.java).firstOrNull()?.let { return it.familyName }+ e.getSpans(start, end, TypefaceSpan::class.java).firstOrNull { it !is InlineCodeSpan }?.let { return it.family }+ return null+ }+ override fun linkContext(): LinkContext? = computeLinkContext() private fun computeLinkContext(): LinkContext? {
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 2df2b1eeff..53415d16b5 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@@ -114,6 +114,19 @@ fun HtmlText( } } 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>@@ -138,6 +151,11 @@ fun HtmlText( 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>@@ -166,6 +184,7 @@ fun HtmlText( } img, table { max-width: 100% !important; } img { height: auto; }+ $richCss $quoteCss </style> </head>
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 27880325fc..30f4f80a92 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -29,7 +29,12 @@ import androidx.compose.material.icons.filled.ArrowRightAlt import androidx.compose.material.icons.filled.ChangeHistory import androidx.compose.material.icons.filled.ChatBubbleOutline import androidx.compose.material.icons.filled.Circle+import androidx.compose.material.icons.filled.Code import androidx.compose.material.icons.filled.Diamond+import androidx.compose.material.icons.filled.FormatClear+import androidx.compose.material.icons.filled.FormatColorFill+import androidx.compose.material.icons.filled.FormatQuote+import androidx.compose.material.icons.filled.FormatSize import androidx.compose.material.icons.filled.FormatUnderlined import androidx.compose.material.icons.filled.Gesture import androidx.compose.material.icons.filled.Hexagon@@ -46,6 +51,7 @@ import androidx.compose.material.icons.filled.StarOutline import androidx.compose.material.icons.filled.StrikethroughS import androidx.compose.material.icons.filled.Style import androidx.compose.material.icons.filled.TextFields+import androidx.compose.material.icons.filled.Title import androidx.compose.material.icons.filled.Waves import androidx.compose.material.icons.outlined.ArrowRightAlt import androidx.compose.material.icons.outlined.ChangeHistory@@ -1019,3 +1025,32 @@ fun IconShapeArrowOutline(modifier: Modifier = Modifier, tint: Color = LocalCont @Composable fun IconWallpaper(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.Wallpaper, "Wallpaper", modifier, tint)++// --- Email composer rich formatting ---+@Composable+fun IconFormatQuote(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.FormatQuote, "Blockquote", modifier, tint)++@Composable+fun IconFormatCode(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Code, "Code", modifier, tint)++@Composable+fun IconFormatHorizontalRule(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.HorizontalRule, "Horizontal rule", modifier, tint)++@Composable+fun IconFormatTitle(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Title, "Heading", modifier, tint)++@Composable+fun IconFormatClear(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.FormatClear, "Clear formatting", modifier, tint)++@Composable+fun IconFormatColorFill(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.FormatColorFill, "Highlight", modifier, tint)++@Composable+fun IconFormatSize(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.FormatSize, "Font size", modifier, tint)
library/ui/src/main/java/com/vayunmathur/library/ui/RichEmailSpans.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/RichEmailSpans.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/RichEmailSpans.ktnew file mode 100644index 0000000000..05c9f6beb4--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/RichEmailSpans.kt@@ -0,0 +1,95 @@+package com.vayunmathur.library.ui++import android.graphics.Color+import android.graphics.Typeface+import android.text.Layout+import android.text.TextPaint+import android.text.style.AlignmentSpan+import android.text.style.MetricAffectingSpan+import android.text.style.QuoteSpan+import android.text.style.TypefaceSpan++/**+ * Extended spans for rich email formatting (headings, alignment, blockquote, code, hr, fonts).+ * Email-safe HTML is emitted via EmailHtmlSerializer.+ */++// ---------------------------------------------------------------------------+// Paragraph-level spans+// ---------------------------------------------------------------------------++class HeadingSpan(val level: Int) : MetricAffectingSpan() {+ val proportion: Float = when (level) {+ 1 -> 1.6f+ 2 -> 1.35f+ 3 -> 1.15f+ else -> 1f+ }++ override fun updateDrawState(tp: TextPaint) {+ tp.textSize = tp.textSize * proportion+ tp.isFakeBoldText = true+ }++ override fun updateMeasureState(tp: TextPaint) {+ tp.textSize = tp.textSize * proportion+ tp.isFakeBoldText = true+ }+}++/**+ * Holds a CSS alignment string so we can emit `justify` which Layout.Alignment does not represent.+ * Rendering in EditText falls back to NORMAL/CENTER/OPPOSITE.+ */+class EmailAlignmentSpan(val cssAlign: String) : AlignmentSpan.Standard(+ when (cssAlign.lowercase()) {+ "center" -> Layout.Alignment.ALIGN_CENTER+ "right" -> Layout.Alignment.ALIGN_OPPOSITE+ "justify" -> Layout.Alignment.ALIGN_NORMAL // EditText does not render justify, but we emit CSS+ else -> Layout.Alignment.ALIGN_NORMAL+ }+) {+ val alignmentCss: String = cssAlign.lowercase()+}++/** Visual blockquote – reuses QuoteSpan drawing (left border) with a neutral color. */+class EmailBlockQuoteSpan : QuoteSpan(Color.GRAY)++// ---------------------------------------------------------------------------+// Inline-level spans+// ---------------------------------------------------------------------------++/** Monospace inline code – rendered as monospace in the editor; HTML adds background. */+class InlineCodeSpan : TypefaceSpan("monospace") {+ override fun updateDrawState(ds: TextPaint) {+ super.updateDrawState(ds)+ ds.typeface = Typeface.MONOSPACE+ }++ override fun updateMeasureState(paint: TextPaint) {+ super.updateMeasureState(paint)+ paint.typeface = Typeface.MONOSPACE+ }+}++/** Marker for a horizontal rule paragraph (object replacement char). */+class HrSpan++/** Font family – e.g., "sans-serif", "serif", "monospace". */+class FontFamilySpan(val familyName: String) : TypefaceSpan(familyName)++// ---------------------------------------------------------------------------+// Helpers for serializer+// ---------------------------------------------------------------------------++fun Layout.Alignment.toCssAlign(): String = when (this) {+ Layout.Alignment.ALIGN_CENTER -> "center"+ Layout.Alignment.ALIGN_OPPOSITE -> "right"+ else -> "left"+}++fun cssAlignToLayout(align: String): Layout.Alignment = when (align.lowercase()) {+ "center" -> Layout.Alignment.ALIGN_CENTER+ "right", "end" -> Layout.Alignment.ALIGN_OPPOSITE+ else -> Layout.Alignment.ALIGN_NORMAL+}