Ayfri
08/01/2022, 12:48 PM${Br()}
into a raw string ? For now it just prints the result of the method which is kotlin.Unit
hfhbd
08/01/2022, 1:19 PMAyfri
08/01/2022, 1:21 PMText("my text blah blah ${InsertBRTag} then blah blah")
So I don't have to do this
Text("my text blah blah ")
Br()
Text(" then blah blah")
For links it's even more verbose :)Big Chungus
08/01/2022, 1:21 PMhfhbd
08/01/2022, 1:23 PMAyfri
08/01/2022, 1:23 PMhfhbd
08/01/2022, 1:26 PM@Composable
fun Text(text: String) {
val components = text.split("<br>")
for ((index, component) in components.withIndex()) {
org.jetbrains.compose.web.dom.Text(component)
if (index != component.lastIndex) {
Br()
}
}
}
Ayfri
08/01/2022, 1:28 PMhfhbd
08/01/2022, 1:31 PMAyfri
08/01/2022, 1:45 PMhfhbd
08/01/2022, 1:50 PMAyfri
08/01/2022, 1:54 PMhfhbd
08/01/2022, 2:23 PMval regex = """<([^>]*)>""".toRegex()
fun String.getTokens(): Sequence<Pair<String, MatchResult?>> = sequence {
var last = 0
for (match in regex.findAll(this@getTokens)) {
yield(this@getTokens.substring(last until match.range.first) to null)
last = match.range.last + 1
yield(this@getTokens.substring(match.range) to match)
}
if (last != this@getTokens.length) {
yield(this@getTokens.substring(last) to null)
}
}
package app.softwork.markdowncompose
import androidx.compose.runtime.*
import org.jetbrains.compose.web.attributes.*
import org.jetbrains.compose.web.dom.*
@Composable
public fun renderMarkdown(markdown: String) {
val iterator = markdown.getTokens().iterator()
while (iterator.hasNext()) {
val (rawText, htmlTag) = iterator.next()
val htmlValue = htmlTag?.groups?.get(1)?.value
val markdownLink = htmlTag?.groups?.get(2)?.value
when {
markdownLink != null -> renderLink(markdownLink)
htmlValue == null -> Text(rawText)
htmlValue == "br" -> Br()
htmlValue.startsWith("a") -> renderA(htmlValue, iterator)
}
}
}
private const val markdownLink = """!\[([^\]]*)\]\(([^\)*])\)"""
private val markdownLinkRegex = markdownLink.toRegex()
private val regex = """<([^>]*)>|($markdownLink)""".toRegex()
private fun String.getTokens(): Sequence<Pair<String, MatchResult?>> = sequence {
var last = 0
for (match in regex.findAll(this@getTokens)) {
yield(substring(last until match.range.first) to null)
last = match.range.last + 1
yield(substring(match.range) to match)
}
if (last != length) {
yield(substring(last) to null)
}
}
@Composable
private fun renderA(htmlValue: String, iterator: Iterator<Pair<String, MatchResult?>>) {
val attrs = htmlValue.split(" ")
val content = iterator.next()
A(
attrs = {
for (attr in attrs) {
when {
attr.startsWith("href") -> href(attr.removePrefix("href=\"").dropLast(1))
}
}
}) {
Text(content.first)
}
iterator.next()
}
@Composable
private fun renderLink(markdown: String) {
val link = markdownLinkRegex.matchEntire(markdown)!!.groups
val content = link[1]!!.value
val href = link[2]!!.value
A(href = href) {
Text(content)
}
}
Ayfri
08/01/2022, 3:55 PMhfhbd
08/01/2022, 4:02 PMMichael Paus
08/01/2022, 7:13 PMAyfri
08/01/2022, 7:29 PM