appstore: render Markdown and HTML in app descriptions (#902)
- Commit
bd884be933869e04ccd88ad5ff9aa9c82afe8d61- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-05 00:09 UTC (1 month ago)
- Parents
7f72d42
Fastlane-sourced descriptions mix inline HTML tags and Markdown into plain text with meaningful line breaks; they were shown raw. Normalise them to the HTML subset Html parsing supports (bullets, headings, bold/italic, links, code) and render via AnnotatedString.fromHtml on phone and TV detail pages. Real HTML (Play) passes through. Images/scripts are stripped and only http(s)/mailto links stay clickable.
Diff
appstore/src/main/java/com/vayunmathur/appstore/domain/DescriptionMarkup.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/domain/DescriptionMarkup.kt b/appstore/src/main/java/com/vayunmathur/appstore/domain/DescriptionMarkup.ktnew file mode 100644index 0000000000..99e69238d3--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/domain/DescriptionMarkup.kt@@ -0,0 +1,106 @@+package com.vayunmathur.appstore.domain++/**+ * Normalises a store description to the HTML subset Android's Html parser renders.+ *+ * Sources disagree on format: Play sends real HTML, while fastlane-sourced repos send+ * plain text whose line breaks are meaningful, often with inline HTML tags and Markdown+ * (`- ` bullets, `**bold**`, `[text](url)`) mixed in. Text without block-level HTML is+ * treated as the latter.+ */+object DescriptionMarkup {++ fun toHtml(raw: String): String {+ val text = raw.replace("\r\n", "\n").replace('\r', '\n')+ .replace(STRIPPED, "")+ .replace(ANCHOR_OPEN) { if (isSafeUrl(hrefOf(it.value))) it.value else "<a>" }+ .trim()+ if (BLOCK_HTML.containsMatchIn(text)) return text++ var inFence = false+ val lines = text.replace(EXCESS_NEWLINES, "\n\n").split('\n').mapNotNull { line ->+ when {+ FENCE.matches(line) -> { inFence = !inFence; null }+ inFence -> "<tt>${escape(line)}</tt>"+ else -> blockLine(line)+ }+ }+ return lines.joinToString("<br>")+ }++ private fun blockLine(line: String): String {+ if (RULE.matches(line)) return ""+ HEADING.matchEntire(line)?.let { return "<b>${inline(it.groupValues[1])}</b>" }+ BULLET.matchEntire(line)?.let {+ val indent = " ".repeat(it.groupValues[1].length / 2)+ return "$indent• ${inline(it.groupValues[2])}"+ }+ QUOTE.matchEntire(line)?.let { return "<i>${inline(it.groupValues[1])}</i>" }+ return inline(line)+ }++ /** Markdown inline syntax, applied only to text between tags and code spans. */+ private fun inline(line: String): String = buildString {+ var last = 0+ for (token in INLINE_TOKEN.findAll(line)) {+ append(markdownInline(line.substring(last, token.range.first)))+ val value = token.value+ when {+ value.startsWith('`') -> append("<tt>${escape(value.trim('`'))}</tt>")+ AUTOLINK.matches(value) -> value.trim('<', '>').let { append("<a href=\"$it\">$it</a>") }+ else -> append(value)+ }+ last = token.range.last + 1+ }+ append(markdownInline(line.substring(last)))+ }++ private fun markdownInline(text: String): String = text+ .replace(IMAGE, "")+ .replace(LINK) {+ val (label, url) = it.destructured+ if (isSafeUrl(url)) "<a href=\"$url\">$label</a>" else label+ }+ .replace(BOLD, "<b>$2</b>")+ .replace(ITALIC_STAR, "<i>$1</i>")+ .replace(ITALIC_UNDERSCORE, "<i>$1</i>")+ .replace(STRIKE, "<s>$1</s>")++ private fun hrefOf(tag: String): String? =+ HREF.find(tag)?.let { m -> m.groupValues[2].ifEmpty { m.groupValues[3] } }++ /** Links open through ACTION_VIEW, so anything but web/mail could launch another app. */+ private fun isSafeUrl(url: String?): Boolean {+ val u = url?.trim()?.lowercase() ?: return false+ return u.startsWith("https://") || u.startsWith("http://") || u.startsWith("mailto:")+ }++ private fun escape(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">")++ private val IGNORE_CASE = setOf(RegexOption.IGNORE_CASE)++ // Html.fromHtml turns <img> into an object-replacement glyph and prints script/style bodies.+ private val STRIPPED = Regex(+ "<!--[\\s\\S]*?-->|<(script|style)\\b[\\s\\S]*?</\\1\\s*>|<img\\b[^>]*>",+ IGNORE_CASE,+ )+ private val ANCHOR_OPEN = Regex("<a\\b[^>]*>", IGNORE_CASE)+ private val HREF = Regex("href\\s*=\\s*(?:([\"'])(.*?)\\1|([^\\s>]+))", IGNORE_CASE)+ private val BLOCK_HTML = Regex("<(br|p|div|ul|ol|li|h[1-6]|table)\\b", IGNORE_CASE)+ private val EXCESS_NEWLINES = Regex("\\n{3,}")++ private val FENCE = Regex("\\s*```.*")+ private val RULE = Regex("\\s*([-*_])(\\s*\\1){2,}\\s*")+ private val HEADING = Regex("\\s{0,3}#{1,6}\\s+(.*?)\\s*#*\\s*")+ private val BULLET = Regex("(\\s*)[-*+•]\\s+(.*)")+ private val QUOTE = Regex("\\s*>\\s?(.*)")++ private val INLINE_TOKEN = Regex("`[^`]+`|<[^<>]+>")+ private val AUTOLINK = Regex("<(https?://|mailto:)[^\\s<>]+>", IGNORE_CASE)+ private val IMAGE = Regex("!\\[[^\\]]*]\\([^)]*\\)")+ private val LINK = Regex("\\[([^\\]]+)]\\(\\s*<?([^\\s)<>\"]+)>?(?:\\s+\"[^\"]*\")?\\s*\\)")+ private val BOLD = Regex("(\\*\\*|__)(?=\\S)(.+?)(?<=\\S)\\1")+ private val ITALIC_STAR = Regex("(?<![*\\w])\\*(?=\\S)(.+?)(?<=\\S)\\*(?![*\\w])")+ private val ITALIC_UNDERSCORE = Regex("(?<![_\\w])_(?=\\S)(.+?)(?<=\\S)_(?![_\\w])")+ private val STRIKE = Regex("~~(?=\\S)(.+?)(?<=\\S)~~")+}
appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetailSections.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetailSections.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetailSections.ktindex 86e615998e..1cc1b1894b 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetailSections.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreDetailSections.kt@@ -28,6 +28,7 @@ import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.security.TrustProfile import com.vayunmathur.appstore.ui.formatCount+import com.vayunmathur.appstore.ui.rememberDescriptionText import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.image.compose.AsyncImageState import com.vayunmathur.library.tv.TvAspect@@ -66,7 +67,7 @@ internal fun TvStoreDetailBody( if (app.description.isNotBlank() && app.description != app.summary) { var expanded by remember(app.packageName) { mutableStateOf(false) } Text(- text = app.description,+ text = rememberDescriptionText(app.description, MaterialTheme.colorScheme.primary), style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.9f), maxLines = if (expanded) Int.MAX_VALUE else 5,
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.ktindex 49d4c4cd7d..92f06c3356 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.kt@@ -171,7 +171,7 @@ internal fun AppDetailDescription(app: UnifiedApp) { } if (app.description.isNotBlank() && app.description != app.summary) { Text(- app.description,+ rememberDescriptionText(app.description, MaterialTheme.colorScheme.primary), style = MaterialTheme.typography.bodyMedium, maxLines = if (expanded) Int.MAX_VALUE else 5, overflow = TextOverflow.Ellipsis,
appstore/src/main/java/com/vayunmathur/appstore/ui/DescriptionText.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/DescriptionText.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/DescriptionText.ktnew file mode 100644index 0000000000..2c0a5ad2a7--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/DescriptionText.kt@@ -0,0 +1,22 @@+package com.vayunmathur.appstore.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.TextLinkStyles+import androidx.compose.ui.text.fromHtml+import androidx.compose.ui.text.style.TextDecoration+import com.vayunmathur.appstore.domain.DescriptionMarkup++@Composable+internal fun rememberDescriptionText(raw: String, linkColor: Color): AnnotatedString =+ remember(raw, linkColor) {+ AnnotatedString.fromHtml(+ DescriptionMarkup.toHtml(raw),+ linkStyles = TextLinkStyles(+ SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline),+ ),+ )+ }
appstore/src/test/java/com/vayunmathur/appstore/domain/DescriptionMarkupTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/domain/DescriptionMarkupTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/domain/DescriptionMarkupTest.ktnew file mode 100644index 0000000000..30010eacba--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/domain/DescriptionMarkupTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.appstore.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class DescriptionMarkupTest {++ @Test+ fun `fastlane text keeps inline html and turns newlines and dashes into breaks and bullets`() {+ val raw = "<b>ColorBlendr</b> modifies colors.\n\n<b>Features:</b>\n\n- Accent\n- Background"+ assertEquals(+ "<b>ColorBlendr</b> modifies colors.<br><br><b>Features:</b><br><br>• Accent<br>• Background",+ DescriptionMarkup.toHtml(raw),+ )+ }++ @Test+ fun `markdown inline syntax is converted`() {+ assertEquals(+ "<b>bold</b> <i>it</i> <i>u</i> <s>gone</s> <tt>a<b</tt> <a href=\"https://x.org\">site</a>",+ DescriptionMarkup.toHtml("**bold** *it* _u_ ~~gone~~ `a<b` [site](https://x.org)"),+ )+ }++ @Test+ fun `headings become bold lines and rules and images are dropped`() {+ assertEquals(+ "<b>Title</b><br><br>text",+ DescriptionMarkup.toHtml("## Title\n---\ntext"),+ )+ }++ @Test+ fun `snake case identifiers are not italicised`() {+ assertEquals("QUERY_ALL_PACKAGES", DescriptionMarkup.toHtml("QUERY_ALL_PACKAGES"))+ }++ @Test+ fun `real html is passed through without adding breaks`() {+ val raw = "<p>One</p>\n<ul><li>Two</li></ul>"+ assertEquals(raw, DescriptionMarkup.toHtml(raw))+ }++ @Test+ fun `images comments and scripts are stripped`() {+ assertEquals(+ "<p>ok</p>",+ DescriptionMarkup.toHtml("<img src=\"a.png\"><!-- hi --><script>x()</script><p>ok</p>"),+ )+ }++ @Test+ fun `non web links lose their target`() {+ val html = DescriptionMarkup.toHtml(+ "<a href=\"intent://evil\">a</a> [b](market://details?id=x) <a href='https://ok.org'>c</a>",+ )+ assertFalse(html.contains("intent://"))+ assertFalse(html.contains("market://"))+ assertTrue(html.contains("<a>a</a>"))+ assertTrue(html.contains(" b "))+ assertTrue(html.contains("<a href='https://ok.org'>c</a>"))+ }++ @Test+ fun `autolinks become anchors`() {+ assertEquals(+ "see <a href=\"https://x.org\">https://x.org</a>",+ DescriptionMarkup.toHtml("see <https://x.org>"),+ )+ }+}