I need to render Markdown in Compose (on Android)....
# compose
m
I need to render Markdown in Compose (on Android). Does anyone have any recommendation for a library or solution? I'm currently considering this library: https://github.com/jeziellago/compose-markdown Or using this JetBrains library for parsing the Markdown: https://github.com/JetBrains/markdown and writing the Compose code myself to render the parsed text. Does anyone have any insight?
o
We have pretty sophisticated code to render markdown, because we support tables and code blocks, quotes, paragraph spacing, etc. Unfortunately I can’t share it, but what I mean if you want to implement it yourself be prepared to invest quite some time.
m
I'm controlling the input Markdown, and should only need to support bold, italics, and headings, so I am assuming it wouldn't be that bad to implement.
o
Yeah, in that case any markdown parser and AnnotatedString would work just fine and easy. But if you generate it or it’s some internal representation of rich text, consider more specific format that you can parse unambiguously
c
@Halil Ozercan didn't you have a markdown parser in compose?
m
m
That looks promising, thank you.
h
If your requirement is just to convert text styling of markdown into AnnotatedString, Richtext commonmark library can be an overkill. Please take a look at
computeRichTextString
function here. https://github.com/halilozercan/compose-richtext/blob/3c5b38f51e824bd88d6e5785fd90[…]nMain/kotlin/com/halilibo/richtext/markdown/MarkdownRichText.kt Although it returns RichTextString, not AnnotatedString,
computeRichTextString
can give you a general idea of how to accomplish your goal. It's a preorder traversal of markdown tree that commonmark produces. While traversing you can simply build an AnnotatedString node by node.
m
I ended up using https://github.com/commonmark/commonmark-java to parse the Markdown, then traverse the AST to build an AnnotatedString, similar to Halil's example. Works fine.
p
@Marcin Wisniowski is your code to build an AnnotatedString from commonmark’s AST something you’re able to share? Running into the same challenge
m
Sure, will do later today
p
thank you!
m
@Peter Farlow https://gist.github.com/Nohus/bac151623a287777208f8d66b4731497 Of course this uses the styles I needed for my use case, and handles the parts of Markdown I needed, so needs adapting. The
Parser
class is from Commonmark.
gratitude thank you 1
o
It doesn't properly support nested bullet/ordered lists, does it? Because of that and also code blocks, paragraph spacing and some other stuff (mostly GitHub flavor) I had to invent my own "RichText" structure, because AnnotatedString is not sufficient…
m
Yes it doesn't, because my text (not user supplied) doesn't have them. Could be updated to support them though.
👍 1
1474 Views