Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Markdown renderer for Kotlin Multiplatform Projects (Android, iOS, Desktop), using Compose.

License

NotificationsYou must be signed in to change notification settings

AlbertZhang411/multiplatform-markdown-renderer

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

... a Kotlin Multiplatform Markdown Renderer. (Android, Desktop, ...) powered by Compose Multiplatform



What's included 🚀Setup 🛠️Usage 🛠️License 📓


What's included 🚀

  • Super simple setup
  • Cross-platform ready
  • Lightweight

Setup

Using Gradle

Multiplatform

For multiplatform projects specify this single dependency:

dependencies {    implementation("com.mikepenz:multiplatform-markdown-renderer:${version}")// Offers Material 2 defaults for Material 2 themed apps (com.mikepenz.markdown.m2.Markdown)    implementation("com.mikepenz:multiplatform-markdown-renderer-m2:${version}")// Offers Material 3 defaults for Material 3 themed apps (com.mikepenz.markdown.m3.Markdown)    implementation("com.mikepenz:multiplatform-markdown-renderer-m3:${version}")}

JVM

To use the library on JVM, you have to include:

dependencies {    implementation("com.mikepenz:multiplatform-markdown-renderer-jvm:${version}")}

Android

For Android a special dependency is available:

dependencies {    implementation("com.mikepenz:multiplatform-markdown-renderer-android:${version}")}

Tip

Since 0.13.0 the core library does not depend on a Material theme anymore. Include the-m2or-m3 module to getaccess to the defaults.


Usage

val markdown="""### What's included 🚀- Super simple setup- Cross-platform ready- Lightweight""".trimIndent()//Markdown(markdown)
Advanced Usage

The library offers the ability to modify different behaviour when rendering the markdown.

Provided custom style

Markdown(    content,    colors= markdownColors(text=Color.Red),    typography= markdownTypography(h1=MaterialTheme.typography.body1))

Extended spans

Starting with 0.16.0 the library includes supportforextended-spans.

The library was integrated to to make it multiplatform compatible. All credits for itsfunctionality goes toSaket Narayan.

It is not enabled by default, however you can enable it quickly by configuring theextendedSpansfor yourMarkdown composeable.Define theExtendedSpans you want to apply (including optionally your own custom ones) and returnit.

Markdown(    content,    extendedSpans= markdownExtendedSpans {val animator= rememberSquigglyUnderlineAnimator()        remember {ExtendedSpans(RoundedCornerSpanPainter(),SquigglyUnderlineSpanPainter(animator= animator)            )        }    })

Extend Annotated string handling

The library already handles a significant amount of different tokens, however not all. To allowspecial integrations expand this, you can pass in a customannotator to theMarkdowncomposeable. Thisannotator allows you to customize existing handled tokens, but also add newones.

Markdown(    content,    annotator= markdownAnnotator { content, child->if (child.type==GFMElementTypes.STRIKETHROUGH) {            append("Replaced you :)")true// return true to consume this ASTNode child        }elsefalse    })

Adjust List Ordering

// Use the bullet list symbol from the original markdownCompositionLocalProvider(LocalBulletListHandler provides {"$it" }) {Markdown(content)}// Replace the ordered list symbol with `A.)` instead.CompositionLocalProvider(LocalOrderedListHandler provides {"A.)" }) {Markdown(content,Modifier.fillMaxSize().padding(16.dp).verticalScroll(scrollState))}

Custom Components

Since v0.9.0 it is possible to provide custom components, instead of the default ones.This can be done by providing the componentsMarkdownComponents to theMarkdown composable.

Use themarkdownComponents() to keep defaults for non overwritten components.

TheMarkdownComponent will expose access tothecontent: String,node: ASTNode,typography: MarkdownTypography,offering full flexibility.

// Simple adjusted paragraph with different Modifier.val customParagraphComponent:MarkdownComponent= {MarkdownParagraph(it.content, it.node,Modifier.align(Alignment.End))}// Full custom paragraph exampleval customParagraphComponent:MarkdownComponent= {// build a styled paragraph. (util function provided by the library)val styledText= buildAnnotatedString {        pushStyle(LocalMarkdownTypography.current.paragraph.toSpanStyle())        buildMarkdownAnnotatedString(content, it.node)        pop()    }// define the `Text` composableText(        styledText,        modifier=Modifier.align(Alignment.End),        textAlign=TextAlign.End    )}// Define the `Markdown` composable and pass in the custom paragraph componentMarkdown(    content,    components= markdownComponents(        paragraph= customParagraphComponent    ))

Another example to of a custom component is changing the rendering of an unordered list.

// Define a custom component for rendering unordered list items in Markdownval customUnorderedListComponent:MarkdownComponent= {// Use the MarkdownListItems composable to render the list itemsMarkdownListItems(it.content, it.node, level=0) { index, child->// Create a row layout for each list item with spacing between elementsRow(Modifier.fillMaxWidth(), horizontalArrangement=Arrangement.spacedBy(8.dp)) {// Render an icon for the bullet point with a green tintIcon(                imageVector= icon,                tint=Color.Green,                contentDescription=null,                modifier=Modifier.size(20.dp),            )// Extract the bullet marker text from the child nodeval bulletMarker:String= child.findChildOfType(MarkdownTokenTypes.LIST_BULLET)?.getTextInNode(it.content).toString()// Extract the item text and remove the bullet marker from itval itemText= child.getTextInNode(it.content).toString().replace(bulletMarker,"")// Render the item text using the MarkdownText composableMarkdownText(content= itemText)        }    }}// Define the `Markdown` composable and pass in the custom unorderedList componentMarkdown(    content,    components= markdownComponents(        unorderedList= customUnorderedListComponent    ))

Image Loading

Starting with 0.21.0 the library does not include image loading by default, however exposes 2modules for either coil2 or coil3 dependencies.The chosen image transformer implementation has to be passed to theMarkdown API.

coil2

// Offers coil2 (Coil2ImageTransformerImpl)implementation("com.mikepenz:multiplatform-markdown-renderer-coil2:${version}")
Markdown(MARKDOWN,    imageTransformer=Coil2ImageTransformerImpl,)

Note

0.21.0 adds JVM support for this dependency viaHTTPUrlConnection -> however this is expected to be removed in thefuture.

Note

Please refer to the official coil2 documentation on how to adjust theImageLoader

coil3

// Offers coil3 (Coil3ImageTransformerImpl)implementation("com.mikepenz:multiplatform-markdown-renderer-coil3:${version}")
Markdown(MARKDOWN,    imageTransformer=Coil3ImageTransformerImpl,)

Note

Please refer to the official coil3 documentation on how to adjust theSingletonImageLoader

Note

Thecoil3 module does depend on SNAPSHOT builds of coil3

Syntax Highlighting

The library (introduced with 0.27.0) offers optional support for syntax highlighting viatheHighlights project.This support is not included in the core, and can be enabled by adding themultiplatform-markdown-renderer-codedependency.

implementation("com.mikepenz:multiplatform-markdown-renderer-code:${version}")

Once added, theMarkdown has to be configured to use the alternative code highlighter.

// Use default color schemeMarkdown(MARKDOWN,    components= markdownComponents(        codeBlock= highlightedCodeBlock,        codeFence= highlightedCodeFence,    ))// ADVANCED: Customize Highlights library by defining different themeval isDarkTheme= isSystemInDarkTheme()val highlightsBuilder= remember(isDarkTheme) {Highlights.Builder().theme(SyntaxThemes.atom(darkMode= isDarkTheme))}Markdown(MARKDOWN,    components= markdownComponents(        codeBlock= {MarkdownHighlightedCodeBlock(it.content, it.node, highlightsBuilder) },        codeFence= {MarkdownHighlightedCodeFence(it.content, it.node, highlightsBuilder) },    ))

Dependency

This project uses JetBrainsmarkdown MultiplatformMarkdown processor asdependency to parse the markdown content.

Developed By

Contributors

This free, open source software was also made possible by a group of volunteers that put many hoursof hard work intoit. See theCONTRIBUTORS.md file for details.

Credits

Big thanks toErik Hellman and his awesome articleonRendering Markdown with Jetpack Compose,and the related sourceMarkdownComposer.

Also huge thanks toSaket Narayan for his great work ontheextended-spans project. Ported into this project tomake it multiplatform.

Fork License

Copyright for portions of the code are held by [Erik Hellman, 2020] as part ofprojectMarkdownComposer under the MIT license.All other copyrightfor project multiplatform-markdown-renderer are held by [Mike Penz, 2023] under the Apache License,Version 2.0.

License

Copyright 2024 Mike PenzLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at   http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.

About

Markdown renderer for Kotlin Multiplatform Projects (Android, iOS, Desktop), using Compose.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Kotlin96.4%
  • HTML2.0%
  • Ruby1.5%
  • JavaScript0.1%

[8]ページ先頭

©2009-2025 Movatter.jp