Currently, using the CodeView is very painful (including #21) because if we highlight large chunks of code on main thread, it can take a very long time for the page to render. A 50-line code snipped slows down rendering by as much as 1 second, which will quickly lead to ANRs. Right now we have devised a custom fork of the composable that looks like this:
val Highlights.annotatedString
get() = buildAnnotatedString {
append(getCode())
getHighlights().forEach {
when (it) {
is BoldHighlight -> addStyle(
SpanStyle(fontWeight = FontWeight.Bold),
start = it.location.start,
end = it.location.end,
)
is ColorHighlight -> addStyle(
SpanStyle(color = Color(it.rgb).copy(alpha = 1f)),
start = it.location.start,
end = it.location.end,
)
}
}
}
@Composable
fun CodeText(
code: String,
vararg emphasis: PhraseLocation,
modifier: Modifier = Modifier,
darkMode: Boolean = isSystemInDarkTheme(),
language: SyntaxLanguage = SyntaxLanguage.KOTLIN,
) {
var string by remember { mutableStateOf(AnnotatedString(code)) }
LaunchedEffect(code, darkMode, language, emphasis) {
withContext(Dispatchers.Default) {
string = Highlights.Builder().run {
theme(SyntaxThemes.atom(darkMode))
code(code)
emphasis(locations = emphasis)
language(language)
build()
}.annotatedString
}
}
Box(modifier = modifier.horizontalScroll(rememberScrollState())) {
SelectionContainer {
Text(
text = string,
fontSize = 13.sp,
fontFamily = FontFamily.Monospace,
textAlign = TextAlign.Start,
overflow = TextOverflow.Visible,
softWrap = false,
lineHeight = 16.sp,
modifier = Modifier.fillMaxWidth(),
)
}
}
}
This renders the code async on the computation dispatcher, but it would be nice to have the library (including the parent Highlights) support this out of the box and in a thread-safe way.
Currently, using the CodeView is very painful (including #21) because if we highlight large chunks of code on main thread, it can take a very long time for the page to render. A 50-line code snipped slows down rendering by as much as 1 second, which will quickly lead to ANRs. Right now we have devised a custom fork of the composable that looks like this:
This renders the code async on the computation dispatcher, but it would be nice to have the library (including the parent Highlights) support this out of the box and in a thread-safe way.