is there a "simple" way to make a Text() highlight...
# compose-desktop
z
is there a "simple" way to make a Text() highlight web links and make them clickable, preferably with a warning dialog before actually opening the link?
d
Hello, you may try this code snippet:
Copy code
import androidx.compose.foundation.text.ClickableText
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import java.awt.Desktop
import java.net.URI

fun main() = application {
    Window(onCloseRequest = ::exitApplication, title = "SampleForAllReproducers") {
        val urlTag = "URL"
        val urlToNavigate = "<https://github.com/JetBrains/compose-multiplatform>"
        val annotatedText = buildAnnotatedString {
            append("Click to link: ")
            withStyle(SpanStyle(color = Color.Blue, fontWeight = FontWeight.Bold)) {
                val linkText = "Compose Multiplatform"
                append(linkText)
                addStringAnnotation(
                    tag = urlTag,
                    annotation = urlToNavigate,
                    start = length - linkText.length,
                    end = length
                )
            }
            append(" and some text after")
        }
        ClickableText(
            text = annotatedText,
            onClick = { offset ->
                val isClickedToUrl = annotatedText.getStringAnnotations(
                    start = offset,
                    end = offset
                ).any { it.tag == urlTag }
                if (isClickedToUrl) {
                    Desktop.getDesktop().browse(URI(urlToNavigate))
                }
            }
        )

    }
}
z
oh thanks. but i meant find all urls with regex make the clickable. also is there a way to change the mouse pointer to show the user that its clickable?
z
Official support for links in text is being worked on!
👍 1
r
@Zoff Here's what I'm using to achieve nicely hyperlinked spans with a touch indication. It was way harder than it should have been due to (maybe) some bugs/unexpected features (😉 ) in layout of InlineTextContent Haven't tested on Desktop, but theoretically should work: https://gist.github.com/iamcalledrob/66a02ab7792501d4e3e4440baf138b40 You'd use it like this:
Copy code
LinkableText(
        text = "Here a [lovely website](<https://www.oracle.com/>) for you",
        style = TextStyle.Default,
    ) {
        // "it" will contain "<https://www.oracle.com/>", do something with it.
    }
👍 1
z
thanks i will have a look and try it
m
I have asked this here recently, have a look at the previous discussion: https://kotlinlang.slack.com/archives/C01D6HTPATV/p1707103705980749