Skip to content

Async highlight API to fix performance #28

@Nek-12

Description

@Nek-12

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions