perf(chat): memoize inline LaTeX and match bare URLs once (#1316) (#1342)

This commit is contained in:
m57
2026-09-28 00:49:17 +03:00
committed by GitHub
parent 4fc4d097cc
commit 18953e368b
2 changed files with 53 additions and 33 deletions
@@ -68,6 +68,9 @@ object MarkdownInlineStyler {
val src = text
while (i < src.length) {
// Cheap prefix gate: URL_PATTERN only matches at "http(s)://", so skip the regex elsewhere.
val urlMatch =
if (src.startsWith("http", i, ignoreCase = true)) URL_PATTERN.matchAt(src, i) else null
when {
// Inline code is opaque to emphasis parsing, and delimiters must match by run length.
src[i] == '`' -> {
@@ -312,9 +315,8 @@ object MarkdownInlineStyler {
}
// bare URL
URL_PATTERN.matchAt(src, i) != null -> {
val match = URL_PATTERN.matchAt(src, i)!!
val url = match.value
urlMatch != null -> {
val url = urlMatch.value
val urlToAppend = if (isRtl) BidiUtils.wrapLtrIsolate(url) else url
pushLink(LinkAnnotation.Url(url))
withStyle(
@@ -326,7 +328,7 @@ object MarkdownInlineStyler {
append(urlToAppend)
}
pop()
i = match.range.last + 1
i = urlMatch.range.last + 1
}
// Plain text / words in RTL
@@ -66,24 +66,41 @@ fun MarkdownInlineText(
}
val config =
remember(style.fontSize, textColor) {
LatexConfig(
fontSize = style.fontSize,
theme = LatexTheme.light(color = textColor, backgroundColor = Color.Transparent),
accessibilityEnabled = true,
)
val inlineContent = mutableMapOf<String, InlineTextContent>()
}
val inlineContent =
remember(segments, latexMeasurer, config) {
val map = mutableMapOf<String, InlineTextContent>()
segments.forEachIndexed { index, segment ->
if (segment is InlineMathSegment.Math) {
latexMeasurer.inlineContent(segment.latex, config)?.let { inlineContent["latex-$index"] = it }
latexMeasurer.inlineContent(segment.latex, config)?.let { map["latex-$index"] = it }
}
}
map
}
val annotated =
remember(
segments,
inlineContent,
textColor,
searchQuery,
isCurrentMatch,
linkColor,
highlights,
isRtl,
) {
buildAnnotatedString {
segments.forEachIndexed { index, segment ->
when (segment) {
is InlineMathSegment.Math -> {
val id = "latex-$index"
if (id in inlineContent) appendInlineContent(id, segment.latex) else append(segment.latex)
val measured = id in inlineContent
if (measured) appendInlineContent(id, segment.latex) else append(segment.latex)
}
is InlineMathSegment.Text -> {
@@ -102,6 +119,7 @@ fun MarkdownInlineText(
}
}
}
}
Text(
text = annotated,
inlineContent = inlineContent,