Repository: zach-klippenstein/compose-richtext Branch: main Commit: 7ba9a5d18f59 Files: 105 Total size: 298.4 KB Directory structure: gitextract_y6p53me7/ ├── .github/ │ └── workflows/ │ ├── android.yml │ ├── docs.yml │ └── publish.yml ├── .gitignore ├── .idea/ │ └── codeStyles/ │ ├── Project.xml │ └── codeStyleConfig.xml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── android-sample/ │ ├── build.gradle.kts │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── zachklipp/ │ │ └── richtext/ │ │ └── sample/ │ │ ├── Demo.kt │ │ ├── LazyMarkdownSample.kt │ │ ├── MarkdownSample.kt │ │ ├── RichTextSample.kt │ │ ├── SampleActivity.kt │ │ ├── SampleLauncher.kt │ │ ├── SampleTheme.kt │ │ ├── ScreenPreview.kt │ │ └── TextDemo.kt │ └── res/ │ ├── drawable/ │ │ └── ic_launcher_background.xml │ ├── drawable-v24/ │ │ └── ic_launcher_foreground.xml │ ├── mipmap-anydpi-v26/ │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ └── values/ │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle.kts ├── buildSrc/ │ ├── build.gradle.kts │ └── src/ │ └── main/ │ └── kotlin/ │ ├── Dependencies.kt │ └── richtext-kmp-library.gradle.kts ├── desktop-sample/ │ ├── build.gradle.kts │ └── src/ │ └── main/ │ └── kotlin/ │ └── com/ │ └── halilibo/ │ └── richtext/ │ └── desktop/ │ ├── MarkdownSampleApp.kt │ └── RichTextSampleApp.kt ├── docs/ │ ├── index.md │ ├── richtext-commonmark.md │ ├── richtext-markdown.md │ ├── richtext-ui-material.md │ ├── richtext-ui-material3.md │ └── richtext-ui.md ├── gen_dokka_docs.sh ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── mkdocs.yml ├── richtext-commonmark/ │ ├── build.gradle.kts │ ├── gradle.properties │ └── src/ │ ├── commonMain/ │ │ └── kotlin/ │ │ └── com/ │ │ └── halilibo/ │ │ └── richtext/ │ │ └── commonmark/ │ │ ├── CommonMarkdownParseOptions.kt │ │ └── Markdown.kt │ ├── jvmAndroidMain/ │ │ └── kotlin/ │ │ └── com/ │ │ └── halilibo/ │ │ └── richtext/ │ │ └── commonmark/ │ │ └── AstNodeConvert.kt │ └── jvmAndroidTest/ │ └── kotlin/ │ └── com/ │ └── halilibo/ │ └── richtext/ │ └── commonmark/ │ └── AstNodeConvertKtTest.kt ├── richtext-markdown/ │ ├── build.gradle.kts │ ├── gradle.properties │ └── src/ │ ├── androidMain/ │ │ ├── AndroidManifest.xml │ │ └── kotlin/ │ │ └── com/ │ │ └── halilibo/ │ │ └── richtext/ │ │ └── markdown/ │ │ ├── HtmlBlock.kt │ │ └── MarkdownImage.kt │ ├── commonMain/ │ │ └── kotlin/ │ │ └── com/ │ │ └── halilibo/ │ │ └── richtext/ │ │ └── markdown/ │ │ ├── BasicMarkdown.kt │ │ ├── HtmlBlock.kt │ │ ├── MarkdownImage.kt │ │ ├── MarkdownRichText.kt │ │ ├── RenderTable.kt │ │ ├── TraverseUtils.kt │ │ └── node/ │ │ ├── AstNode.kt │ │ ├── AstNodeLinks.kt │ │ ├── AstNodeType.kt │ │ └── AstTable.kt │ └── jvmMain/ │ └── kotlin/ │ └── com/ │ └── halilibo/ │ └── richtext/ │ └── markdown/ │ ├── HtmlBlock.kt │ └── RemoteImage.kt ├── richtext-ui/ │ ├── build.gradle.kts │ ├── gradle.properties │ └── src/ │ ├── androidMain/ │ │ ├── AndroidManifest.xml │ │ └── kotlin/ │ │ └── com/ │ │ └── halilibo/ │ │ └── richtext/ │ │ └── ui/ │ │ └── CodeBlock.android.kt │ ├── commonMain/ │ │ └── kotlin/ │ │ └── com/ │ │ └── halilibo/ │ │ └── richtext/ │ │ └── ui/ │ │ ├── BasicRichText.kt │ │ ├── BlockQuote.kt │ │ ├── CodeBlock.kt │ │ ├── FormattedList.kt │ │ ├── Heading.kt │ │ ├── HorizontalRule.kt │ │ ├── InfoPanel.kt │ │ ├── RichTextLocals.kt │ │ ├── RichTextScope.kt │ │ ├── RichTextStyle.kt │ │ ├── RichTextThemeConfiguration.kt │ │ ├── RichTextThemeProvider.kt │ │ ├── SimpleTableLayout.kt │ │ ├── Table.kt │ │ ├── string/ │ │ │ ├── InlineContent.kt │ │ │ ├── RichTextString.kt │ │ │ └── Text.kt │ │ └── util/ │ │ ├── ConditionalTapGestureDetector.kt │ │ └── UUID.kt │ ├── jvmAndroidMain/ │ │ └── kotlin/ │ │ └── com/ │ │ └── halilibo/ │ │ └── richtext/ │ │ └── ui/ │ │ └── util/ │ │ └── UUID.kt │ └── jvmMain/ │ └── kotlin/ │ └── com/ │ └── halilibo/ │ └── richtext/ │ └── ui/ │ └── CodeBlock.desktop.kt ├── richtext-ui-material/ │ ├── build.gradle.kts │ ├── gradle.properties │ └── src/ │ ├── androidMain/ │ │ └── AndroidManifest.xml │ └── commonMain/ │ └── kotlin/ │ └── com/ │ └── halilibo/ │ └── richtext/ │ └── ui/ │ └── material/ │ └── RichText.kt ├── richtext-ui-material3/ │ ├── build.gradle.kts │ ├── gradle.properties │ └── src/ │ ├── androidMain/ │ │ └── AndroidManifest.xml │ └── commonMain/ │ └── kotlin/ │ └── com/ │ └── halilibo/ │ └── richtext/ │ └── ui/ │ └── material3/ │ └── RichText.kt └── settings.gradle.kts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/android.yml ================================================ name: Android CI on: pull_request: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: gradle/wrapper-validation-action@v1 - name: set up JDK 21 uses: actions/setup-java@v1 with: java-version: 21 - uses: actions/cache@v4 with: path: ~/.gradle/caches key: gradle-${{ runner.os }}-${{ hashFiles('buildSrc/**') }}-${{ hashFiles('**/*.gradle*') }} restore-keys: gradle-${{ runner.os }}- - run: ./gradlew build ================================================ FILE: .github/workflows/docs.yml ================================================ name: Doc Site on: workflow_dispatch: jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 with: java-version: 21 - uses: actions/setup-python@v2 with: python-version: 3.x - name: Install dependencies run: pip install mkdocs-material - name: Generate docs run: ./gen_dokka_docs.sh - run: mkdocs gh-deploy --force ================================================ FILE: .github/workflows/publish.yml ================================================ name: Publish on: workflow_dispatch: jobs: publish: name: Release build and publish runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: gradle/wrapper-validation-action@v1 - name: set up JDK 21 uses: actions/setup-java@v1 with: java-version: 21 - uses: actions/cache@v4 with: path: ~/.gradle/caches key: gradle-${{ runner.os }}-${{ hashFiles('buildSrc/**') }}-${{ hashFiles('**/*.gradle*') }} restore-keys: gradle-${{ runner.os }}- - name: Release build run: ./gradlew :build - name: Publish to MavenCentral run: ./gradlew publishAllPublicationsToMavenCentralRepository env: GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }} GPG_PRIVATE_PASSWORD: ${{ secrets.GPG_PRIVATE_PASSWORD }} ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.ORG_GRADLE_PROJECT_MAVENCENTRALUSERNAME }} ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.ORG_GRADLE_PROJECT_MAVENCENTRALPASSWORD }} ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea/caches /.idea/libraries /.idea/modules.xml /.idea/workspace.xml /.idea/navEditor.xml /.idea/assetWizardSettings.xml .DS_Store build/ /captures .externalNativeBuild .cxx site/ docs-gen/ ================================================ FILE: .idea/codeStyles/Project.xml ================================================ ================================================ FILE: .idea/codeStyles/codeStyleConfig.xml ================================================ ================================================ FILE: CHANGELOG.md ================================================ Changelog ========= 1.0.0-alpha03 ------- This release removes the `printing` and `slideshow` modules to focus on the core Markdown and RichText functionalities. It also adds support for inline base64 images. ### Breaking Changes - The `printing` and `slideshow` modules have been removed. If you were using them, you will need to find an alternative or use a previous version of the library. ### New Features - **Inline Base64 Image Rendering**: Markdown images can now be rendered from inline base64-encoded data URIs. ### Updates & Maintenance - **Dependencies Updated**: - Compose Multiplatform updated to `1.8.2`. - Commonmark updated to `0.25.0`. - Dokka updated to `2.0.0`. - **Build & CI**: - Android Gradle Plugin and other dependencies have been updated. - CI now uses `actions/cache@v4`. - **Sample App**: - The Android sample app has been updated to reflect the removal of the `printing` and `slideshow` modules. - Theme handling in the sample app has been simplified. v0.11.0 ------ _2022_02_09_ * Upgrade Coil to 2.0.0-alpha06 by @msfjarvis in https://github.com/halilozercan/compose-richtext/pull/72 ## New Contributors * @msfjarvis made their first contribution in https://github.com/halilozercan/compose-richtext/pull/72 **Full Changelog**: https://github.com/halilozercan/compose-richtext/compare/v0.10.0...v0.11.0 v0.10.0 ------ _2021_12_05_ This release celebrates the release of Compose Multiplatform 1.0.0 🎉🥳 v0.9.0 ------ _2021_11_20_ This release is mostly a version bump. - Jetpack Compose: 1.1.0-beta03 - Jetbrains Compose: 1.0.0-beta5 - Kotlin: 1.5.31 Other changes: * Fix link formatting in index page of docs by in https://github.com/halilozercan/compose-richtext/pull/60 * CodeBlock fixes in https://github.com/halilozercan/compose-richtext/pull/62 * Update CHANGELOG.md to include releases after the transfer in https://github.com/halilozercan/compose-richtext/pull/64 * Add info panels similar to bootstrap alerts #54 in https://github.com/halilozercan/compose-richtext/pull/63 **Full Changelog**: https://github.com/halilozercan/compose-richtext/compare/v0.8.1...v0.9.0 v0.8.1 ------ _2021-9-11_ This release fixes JVM artifact issue #59 v0.8.0 ------ _2021-9-8_ Compose Richtext goes KMP, opening RichText UI and its extensions to both Android and Desktop (#50) Special thanks @zach-klippenstein @LouisCAD @russhwolf for their reviews and help. * Richtext UI, Richtext UI Material, and RichText Commonmark are now KMP Compose libraries * Slideshow, Printing remains Android only for the foreseeable future * Updated docs * A new CI compatible release configuration v0.7.0 ------ _2021-8-6_ * RichText UI no longer depends on Material (#45) * A new artifact richtext-ui-material is published to easily integrate RichText for apps that use Material design. * Upgraded compose to 1.0.1 and kotlin to 1.5.21 v0.6.0 ------ _2021-7-29_ * **Compose 1.0.0 support** (#43) * Upgrade to Gradle 7.0.2 (#40) * Fix wrong word used. portrait -> landscape (#37 - thanks @LouisCAD) * Repository has migrated from @zach-klippenstein to @halilozercan. * Artifacts have moved from com.zachklipp.compose-richtext to com.halilibo.compose-richtext. * Similarly, documentation is also now available at halilibo.com/compose-richtext v0.5.0 ------ _2021-5-18_ * **Compose Beta 7 support!** (#36) * Fix several bugs in Table, RichTextStyle and improve InlineContent (#35 – thanks @halilozercan!) v0.2.0 ------ _2021-2-27_ * **Compose Beta 1 support!** * Remove BulletList styling for different leading characters - Update markdown-demo.png to show new BulletList rendering (#28 – thanks @halilozercan!) v0.1.0+alpha06 -------------- _2020-11-06_ * Initial release. Thanks to @halilozercan for implementing Markdown support! ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed 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.0 Unless required by applicable law or agreed to in writing, software distributed 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 and limitations under the License. ================================================ FILE: README.md ================================================ # Compose Markdown and Rich Text [![Maven Central](https://img.shields.io/maven-central/v/com.halilibo.compose-richtext/richtext-ui.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22com.halilibo.compose-richtext%22) [![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0) > **Warning** > compose-richtext library and all its modules are very experimental. The roadmap is unclear at the moment. Thanks for your patience. Fork option is available as always. A collection of Compose libraries for working with Markdown rendering and rich text formatting. All modules are Compose Multiplatform compatible but lacks iOS support. ---- **Documentation is available at [halilibo.com/compose-richtext](https://halilibo.com/compose-richtext).** ---- ```kotlin @Composable fun App() { RichText(Modifier.background(color = Color.LightGray)) { Heading(0, "Title") Text("Summary paragraph.") HorizontalRule() BlockQuote { Text("A wise person once said…") } Markdown("**Hello** `World`") } } ``` ## License ``` Copyright 2025 Halil Ozercan Licensed 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.0 Unless required by applicable law or agreed to in writing, software distributed 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 and limitations under the License. ``` ================================================ FILE: android-sample/build.gradle.kts ================================================ import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { id("com.android.application") kotlin("android") id("org.jetbrains.compose") id("org.jetbrains.kotlin.plugin.compose") } android { namespace = "com.zachklipp.richtext.sample" compileSdk = AndroidConfiguration.compileSdk defaultConfig { minSdk = AndroidConfiguration.minSdk targetSdk = AndroidConfiguration.targetSdk } buildFeatures { compose = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } } kotlin { compilerOptions { jvmTarget = JvmTarget.JVM_11 } } dependencies { implementation(project(":richtext-commonmark")) implementation(project(":richtext-ui-material3")) implementation(AndroidX.appcompat) implementation(Compose.activity) implementation(compose.foundation) implementation(compose.materialIconsExtended) implementation(compose.material3) implementation(compose.uiTooling) } ================================================ FILE: android-sample/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: android-sample/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/Demo.kt ================================================ @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry") package com.zachklipp.richtext.sample import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.LocalContentColor import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.halilibo.richtext.ui.BlockQuote import com.halilibo.richtext.ui.CodeBlock import com.halilibo.richtext.ui.FormattedList import com.halilibo.richtext.ui.Heading import com.halilibo.richtext.ui.HorizontalRule import com.halilibo.richtext.ui.InfoPanel import com.halilibo.richtext.ui.InfoPanelType import com.halilibo.richtext.ui.ListType import com.halilibo.richtext.ui.ListType.Ordered import com.halilibo.richtext.ui.ListType.Unordered import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.Table import com.halilibo.richtext.ui.material3.RichText @Preview(widthDp = 300, heightDp = 1000) @Composable fun RichTextDemoOnWhite() { Box(Modifier.background(color = Color.White)) { RichTextDemo() } } @Preview(widthDp = 300, heightDp = 1000) @Composable fun RichTextDemoOnBlack() { CompositionLocalProvider(LocalContentColor provides Color.White) { Box(Modifier.background(color = Color.Black)) { RichTextDemo() } } } @Composable fun RichTextDemo( style: RichTextStyle? = null, header: String = "" ) { RichText( modifier = Modifier.padding(8.dp), style = style ) { Heading(0, "Paragraphs $header") Text("Simple paragraph.") Text("Paragraph with\nmultiple lines.") Text("Paragraph with really long line that should be getting wrapped.") TextPreview() Heading(0, "Lists") Heading(1, "Unordered") ListDemo(listType = Unordered) Heading(1, "Ordered") ListDemo(listType = Ordered) Heading(0, "Horizontal Line") Text("Above line") HorizontalRule() Text("Below line") Heading(0, "Code Block") CodeBlock( """ { "Hello": "world!" } """.trimIndent() ) Heading(0, "Block Quote") BlockQuote { Text("These paragraphs are quoted.") Text("More text.") BlockQuote { Text("Nested block quote.") } } Heading(0, "Info Panel") InfoPanel(InfoPanelType.Primary, "Only text primary info panel") InfoPanel(InfoPanelType.Success) { Column { Text("Successfully sent some data") HorizontalRule() BlockQuote { Text("This is a quote") } } } Heading(0, "Table") Table( modifier = Modifier.fillMaxWidth(), headerRow = { cell { Text("Column 1") } cell { Text("Column 2") } }) { row { cell { Text("Hello") } cell { CodeBlock("Foo bar") } } row { cell { BlockQuote { Text("Stuff") } } cell { Text("Hello world this is a really long line that is going to wrap hopefully") } } } } } @Composable private fun RichTextScope.ListDemo(listType: ListType) { FormattedList(listType, @Composable { Text("First list item") FormattedList(listType, @Composable { Text("Indented 1") } ) }, @Composable { Text("Second list item.") FormattedList(listType, @Composable { Text("Indented 2") } ) } ) } ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/LazyMarkdownSample.kt ================================================ package com.zachklipp.richtext.sample import android.widget.Toast import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Checkbox import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.platform.UriHandler import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.halilibo.richtext.commonmark.CommonMarkdownParseOptions import com.halilibo.richtext.commonmark.CommonmarkAstNodeParser import com.halilibo.richtext.markdown.BasicMarkdown import com.halilibo.richtext.markdown.node.AstDocument import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.currentRichTextStyle import com.halilibo.richtext.ui.material3.RichText import com.halilibo.richtext.ui.resolveDefaults @Preview @Composable private fun LazyMarkdownSamplePreview() { LazyMarkdownSample() } @OptIn(ExperimentalLayoutApi::class) @Composable fun LazyMarkdownSample() { var richTextStyle by remember { mutableStateOf(RichTextStyle().resolveDefaults()) } var isDarkModeEnabled by remember { mutableStateOf(false) } var isWordWrapEnabled by remember { mutableStateOf(true) } var markdownParseOptions by remember { mutableStateOf(CommonMarkdownParseOptions.Default) } var isAutolinkEnabled by remember { mutableStateOf(true) } LaunchedEffect(isWordWrapEnabled) { richTextStyle = richTextStyle.copy( codeBlockStyle = richTextStyle.codeBlockStyle!!.copy( wordWrap = isWordWrapEnabled ) ) } LaunchedEffect(isAutolinkEnabled) { markdownParseOptions = markdownParseOptions.copy( autolink = isAutolinkEnabled ) } val context = LocalContext.current SampleTheme(isDarkModeEnabled) { Surface { Column { // Config Card(elevation = CardDefaults.elevatedCardElevation()) { Column { FlowRow { CheckboxPreference( onClick = { isDarkModeEnabled = !isDarkModeEnabled }, checked = isDarkModeEnabled, label = "Dark Mode" ) CheckboxPreference( onClick = { isWordWrapEnabled = !isWordWrapEnabled }, checked = isWordWrapEnabled, label = "Word Wrap" ) CheckboxPreference( onClick = { isAutolinkEnabled = !isAutolinkEnabled }, checked = isAutolinkEnabled, label = "Autolink" ) } RichTextStyleConfig( richTextStyle = richTextStyle, onChanged = { richTextStyle = it } ) } } SelectionContainer { val parser = remember(markdownParseOptions) { CommonmarkAstNodeParser(markdownParseOptions) } val astNode = remember(parser) { parser.parse(sampleMarkdown) } ProvideToastUriHandler(context) { RichText( style = richTextStyle, modifier = Modifier.padding(8.dp), ) { LazyMarkdown(astNode) } } } } } } } /** * A function that renders Markdown content lazily at the top level. All markdown trees start with * an AstDocument. If a document is long enough, usually there are more than hundred child nodes * under the root. Then in turn rendering the whole content into the internal column of * `BasicRichText` becomes extremely inefficient. Instead, this renderer at least relieves the top * level rendering by turning the internal column into a LazyColumn. All other nodes below the * first level are rendered as usual. * * @param astNode Root node of Markdown tree. This can be obtained via a parser. */ @Composable fun RichTextScope.LazyMarkdown(astNode: AstNode) { require(astNode.type == AstDocument) { "Lazy Markdown rendering requires root level node to have a type of AstDocument." } // keep the same blockSpacing val currentStyle = currentRichTextStyle val resolvedStyle = remember(currentStyle) { currentStyle.resolveDefaults() } val blockSpacing = with(LocalDensity.current) { resolvedStyle.paragraphSpacing!!.toDp() } LazyColumn(verticalArrangement = Arrangement.spacedBy(blockSpacing)) { var iter = astNode.links.firstChild while (iter != null) { // We need to store iter in a final variable because composition of `item` happens after // iteration val node = iter item { BasicMarkdown(node) } iter = iter.links.next } } } @Composable private fun CheckboxPreference( onClick: () -> Unit, checked: Boolean, label: String ) { Row( Modifier.clickable(onClick = onClick), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically ) { Checkbox( checked = checked, onCheckedChange = { onClick() }, ) Text(label) } } private val sampleMarkdown = """ # Demo Based on [this cheatsheet][cheatsheet] --- ## Headers --- # Header 1 ## Header 2 ### Header 3 #### Header 4 ##### Header 5 ###### Header 6 --- ## Full-bleed Image ![](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1920px-Image_created_with_a_mobile_phone.png) ## Images smaller than the width should center ![](https://cdn.nostr.build/p/4a84.png) On LineHeight bug, the image below goes over this text. ![](https://cdn.nostr.build/p/PxZ0.jpg) ## Emphasis Emphasis, aka italics, with *asterisks* or _underscores_. Strong emphasis, aka bold, with **asterisks** or __underscores__. Combined emphasis with **asterisks and _underscores_**. --- ## Lists 1. First ordered list item 2. Another item * Unordered sub-list. 1. Actual numbers don't matter, just that it's a number 1. Ordered sub-list 4. And another item. You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown). To have a line break without a paragraph, you will need to use two trailing spaces. Note that this line is separate, but within the same paragraph. (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.) * Unordered list can use asterisks - Or minuses + Or pluses 2. Ordered list starting with `2.` 3. Another item 0. Ordered list starting with `0.` 003. Ordered list starting with `003.` -1. Starting with `-1.` should not be list --- ## Links [I'm an inline-style link](https://www.google.com) [I'm a reference-style link][Arbitrary case-insensitive reference text] [I'm a relative reference to a repository file](../blob/master/LICENSE) [You can use numbers for reference-style link definitions][1] Or leave it empty and use the [link text itself]. Autolink option will detect text links like https://www.google.com and turn them into Markdown links automatically. --- ## Code Inline `code` has `back-ticks around` it. ```javascript var s = "JavaScript syntax highlighting"; alert(s); ``` ```python s = "Python syntax highlighting" print s ``` ```java /** * Helper method to obtain a Parser with registered strike-through & table extensions * & task lists (added in 1.0.1) * * @return a Parser instance that is supported by this library * @since 1.0.0 */ @NonNull public static Parser createParser() { return new Parser.Builder() .extensions(Arrays.asList( StrikethroughExtension.create(), TablesExtension.create(), TaskListExtension.create() )) .build(); } ``` ```xml ``` ``` No language indicated, so no syntax highlighting. But let's throw in a tag. ``` --- ## Images Inline-style: ![random image](https://picsum.photos/seed/picsum/400/400) ![random image](https://picsum.photos/seed/picsum/400/400 "Text 1") Reference-style: ![random image][logo] [logo]: https://picsum.photos/seed/picsum2/400/400 "Text 2" --- ## Tables Colons can be used to align columns. | Tables | Are | Cool | | ------------- |:-------------:| -----:| | col 3 is | right-aligned | ${'$'}1600 | | col 2 is | centered | ${'$'}12 | | zebra stripes | are neat | ${'$'}1 | There must be at least 3 dashes separating each header cell. The outer pipes (|) are optional, and you don't need to make the raw Markdown line up prettily. You can also use inline Markdown. Markdown | Less | Pretty --- | --- | --- *Still* | `renders` | ![random image](https://picsum.photos/seed/picsum/400/400 "Text 1") 1 | 2 | 3 --- ## Blockquotes > Blockquotes are very handy in email to emulate reply text. > This line is part of the same quote. Quote break. > This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote. Nested quotes > Hello! >> And to you! --- ## Inline HTML ```html HTML ``` HTML --- ## Horizontal Rule Three or more... --- Hyphens (`-`) *** Asterisks (`*`) ___ Underscores (`_`) ## License ``` Copyright 2019 Dimitry Ivanov (legal@noties.io) Licensed 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.0 Unless required by applicable law or agreed to in writing, software distributed 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 and limitations under the License. ``` [cheatsheet]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet [arbitrary case-insensitive reference text]: https://www.mozilla.org [1]: http://slashdot.org [link text itself]: http://www.reddit.com """.trimIndent() ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/MarkdownSample.kt ================================================ package com.zachklipp.richtext.sample import android.widget.Toast import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Checkbox import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.halilibo.richtext.commonmark.CommonMarkdownParseOptions import com.halilibo.richtext.commonmark.CommonmarkAstNodeParser import com.halilibo.richtext.markdown.AstBlockNodeComposer import com.halilibo.richtext.markdown.BasicMarkdown import com.halilibo.richtext.markdown.node.AstBlockNodeType import com.halilibo.richtext.markdown.node.AstHeading import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.ui.Heading import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.material3.RichText import com.halilibo.richtext.ui.resolveDefaults @Preview @Composable private fun MarkdownSamplePreview() { MarkdownSample() } @OptIn(ExperimentalLayoutApi::class) @Composable fun MarkdownSample() { var richTextStyle by remember { mutableStateOf(RichTextStyle().resolveDefaults()) } var isWordWrapEnabled by remember { mutableStateOf(true) } var markdownParseOptions by remember { mutableStateOf(CommonMarkdownParseOptions.Default) } var isAutolinkEnabled by remember { mutableStateOf(true) } var isRtl by remember { mutableStateOf(false) } LaunchedEffect(isWordWrapEnabled) { richTextStyle = richTextStyle.copy( codeBlockStyle = richTextStyle.codeBlockStyle!!.copy( wordWrap = isWordWrapEnabled ) ) } LaunchedEffect(isAutolinkEnabled) { markdownParseOptions = markdownParseOptions.copy( autolink = isAutolinkEnabled ) } val context = LocalContext.current CompositionLocalProvider( LocalLayoutDirection provides if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr ) { Column { // Config Card(elevation = CardDefaults.elevatedCardElevation()) { Column { FlowRow { CheckboxPreference( onClick = { isWordWrapEnabled = !isWordWrapEnabled }, checked = isWordWrapEnabled, label = "Word Wrap" ) CheckboxPreference( onClick = { isAutolinkEnabled = !isAutolinkEnabled }, checked = isAutolinkEnabled, label = "Autolink" ) CheckboxPreference( onClick = { isRtl = !isRtl }, checked = isRtl, label = "RTL Layout" ) } RichTextStyleConfig( richTextStyle = richTextStyle, onChanged = { richTextStyle = it } ) } } SelectionContainer { Column(Modifier.verticalScroll(rememberScrollState())) { val parser = remember(markdownParseOptions) { CommonmarkAstNodeParser(markdownParseOptions) } val astNode = remember(parser) { parser.parse(sampleMarkdown) } ProvideToastUriHandler(context) { RichText( style = richTextStyle, modifier = Modifier.padding(8.dp), ) { BasicMarkdown(astNode, HeadingAstBlockNodeComposer) } } } } } } } val HeadingAstBlockNodeComposer = object : AstBlockNodeComposer { override fun predicate(astBlockNodeType: AstBlockNodeType): Boolean { return astBlockNodeType is AstHeading } @Composable override fun RichTextScope.Compose( astNode: AstNode, visitChildren: @Composable (AstNode) -> Unit ) { val headingNode = astNode.type as? AstHeading ?: return Column { Heading(level = headingNode.level) { visitChildren(astNode) } Text("Custom rendering is used for this heading!", fontSize = 8.sp) } } } @Composable private fun CheckboxPreference( onClick: () -> Unit, checked: Boolean, label: String ) { Row( Modifier.clickable(onClick = onClick), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically ) { Checkbox( checked = checked, onCheckedChange = { onClick() }, ) Text(label) } } private val sampleMarkdown = """ # Demo Based on [this cheatsheet][cheatsheet] --- ## Headers --- # Header 1 ## Header 2 ### Header 3 #### Header 4 ##### Header 5 ###### Header 6 --- ## Full-bleed Image ![](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1920px-Image_created_with_a_mobile_phone.png) ## Images smaller than the width should center ![](https://cdn.nostr.build/p/4a84.png) On LineHeight bug, the image below goes over this text. ![](https://cdn.nostr.build/p/PxZ0.jpg) ## Emphasis Emphasis, aka italics, with *asterisks* or _underscores_. Strong emphasis, aka bold, with **asterisks** or __underscores__. Combined emphasis with **asterisks and _underscores_**. --- ## Lists 1. First ordered list item 2. Another item * Unordered sub-list. 1. Actual numbers don't matter, just that it's a number 1. Ordered sub-list 4. And another item. You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown). To have a line break without a paragraph, you will need to use two trailing spaces. Note that this line is separate, but within the same paragraph. (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.) * Unordered list can use asterisks - Or minuses + Or pluses 2. Ordered list starting with `2.` 3. Another item 0. Ordered list starting with `0.` 003. Ordered list starting with `003.` -1. Starting with `-1.` should not be list --- ## Links [I'm an inline-style link](https://www.google.com) [I'm a reference-style link][Arbitrary case-insensitive reference text] [I'm a relative reference to a repository file](../blob/master/LICENSE) [You can use numbers for reference-style link definitions][1] Or leave it empty and use the [link text itself]. Autolink option will detect text links like https://www.google.com and turn them into Markdown links automatically. --- ## Code Inline `code` has `back-ticks around` it. ```javascript var s = "JavaScript syntax highlighting"; alert(s); ``` ```python s = "Python syntax highlighting" print s ``` ```java /** * Helper method to obtain a Parser with registered strike-through & table extensions * & task lists (added in 1.0.1) * * @return a Parser instance that is supported by this library * @since 1.0.0 */ @NonNull public static Parser createParser() { return new Parser.Builder() .extensions(Arrays.asList( StrikethroughExtension.create(), TablesExtension.create(), TaskListExtension.create() )) .build(); } ``` ```xml ``` ``` No language indicated, so no syntax highlighting. But let's throw in a tag. ``` --- ## Images Inline-style: ![random image](https://picsum.photos/seed/picsum/400/400) ![random image](https://picsum.photos/seed/picsum/400/400 "Text 1") Reference-style: ![random image][logo] [logo]: https://picsum.photos/seed/picsum2/400/400 "Text 2" Base64 Inline ![][image1] --- ## Tables Colons can be used to align columns. | Tables | Are | Cool | | ------------- |:-------------:| -----:| | col 3 is | right-aligned | ${'$'}1600 | | col 2 is | centered | ${'$'}12 | | zebra stripes | are neat | ${'$'}1 | There must be at least 3 dashes separating each header cell. The outer pipes (|) are optional, and you don't need to make the raw Markdown line up prettily. You can also use inline Markdown. Markdown | Less | Pretty --- | --- | --- *Still* | `renders` | ![random image](https://picsum.photos/seed/picsum/400/400 "Text 1") 1 | 2 | 3 --- ## Blockquotes > Blockquotes are very handy in email to emulate reply text. > This line is part of the same quote. Quote break. > This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote. Nested quotes > Hello! >> And to you! --- ## Inline HTML ```html HTML ``` HTML --- ## Horizontal Rule Three or more... --- Hyphens (`-`) *** Asterisks (`*`) ___ Underscores (`_`) ## License ``` Copyright 2019 Dimitry Ivanov (legal@noties.io) Licensed 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.0 Unless required by applicable law or agreed to in writing, software distributed 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 and limitations under the License. ``` [cheatsheet]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet [arbitrary case-insensitive reference text]: https://www.mozilla.org [1]: http://slashdot.org [link text itself]: http://www.reddit.com [image1]: """.trimIndent() ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/RichTextSample.kt ================================================ package com.zachklipp.richtext.sample import androidx.annotation.IntRange import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Checkbox import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Slider import androidx.compose.material3.SliderColors import androidx.compose.material3.SliderDefaults import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.resolveDefaults @Preview @Composable private fun RichTextSamplePreview() { RichTextSample() } @Composable fun RichTextSample() { var richTextStyle by remember { mutableStateOf(RichTextStyle().resolveDefaults()) } Column { // Config Card(elevation = CardDefaults.elevatedCardElevation()) { Column { RichTextStyleConfig( richTextStyle = richTextStyle, onChanged = { richTextStyle = it } ) } } SelectionContainer { Column(Modifier.verticalScroll(rememberScrollState())) { RichTextDemo(style = richTextStyle) } } } } @Composable fun RichTextStyleConfig( richTextStyle: RichTextStyle, onChanged: (RichTextStyle) -> Unit ) { Text("Paragraph spacing: ${richTextStyle.paragraphSpacing}") SliderForHumans( value = richTextStyle.paragraphSpacing!!.value, valueRange = 0f..20f, onValueChange = { onChanged(richTextStyle.copy(paragraphSpacing = it.sp)) } ) Text("Table cell padding: ${richTextStyle.tableStyle!!.cellPadding}") SliderForHumans( value = richTextStyle.tableStyle!!.cellPadding!!.value, valueRange = 0f..20f, onValueChange = { onChanged( richTextStyle.copy( tableStyle = richTextStyle.tableStyle!!.copy( cellPadding = it.sp ) ) ) } ) Text("Table border width padding: ${richTextStyle.tableStyle!!.borderStrokeWidth!!}") SliderForHumans( value = richTextStyle.tableStyle!!.borderStrokeWidth!!, valueRange = 0f..20f, onValueChange = { onChanged( richTextStyle.copy( tableStyle = richTextStyle.tableStyle!!.copy( borderStrokeWidth = it ) ) ) } ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun SliderForHumans( value: Float, onValueChange: (Float) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, valueRange: ClosedFloatingPointRange = 0f..1f, @IntRange(from = 0) steps: Int = 0, onValueChangeFinished: (() -> Unit)? = null, colors: SliderColors = SliderDefaults.colors(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() } ) { Slider( value = value, onValueChange = onValueChange, modifier = modifier, enabled = enabled, valueRange = valueRange, steps = steps, onValueChangeFinished = onValueChangeFinished, colors = colors, interactionSource = interactionSource, thumb = { SliderDefaults.Thumb( interactionSource = interactionSource, thumbSize = DpSize(4.dp, 20.dp) ) } ) } ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/SampleActivity.kt ================================================ package com.zachklipp.richtext.sample import android.os.Bundle import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { SampleLauncher() } } } ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/SampleLauncher.kt ================================================ package com.zachklipp.richtext.sample import androidx.activity.compose.BackHandler import androidx.compose.animation.Crossfade import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DarkMode import androidx.compose.material.icons.filled.LightMode import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp private val Samples = listOf Unit>>( "RichText Demo" to @Composable { RichTextSample() }, "Markdown Demo" to @Composable { MarkdownSample() }, "Lazy Markdown Demo" to @Composable { LazyMarkdownSample() }, ) @Preview(showBackground = true) @Composable private fun SampleLauncherPreview() { SamplesListScreen(isDarkTheme = true, onSampleClicked = {}, onThemeToggleClicked = {}) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun SampleLauncher() { val systemDarkTheme = isSystemInDarkTheme() var isDarkTheme by remember(systemDarkTheme) { mutableStateOf(systemDarkTheme) } var currentSampleIndex: Int? by remember { mutableStateOf(null) } SampleTheme(isDarkTheme) { Crossfade(currentSampleIndex) { index -> if (index != null) { BackHandler(onBack = { currentSampleIndex = null }) Scaffold( topBar = { TopAppBar(title = { Text(Samples[index].first) }, actions = { val icon = if (isDarkTheme) Icons.Filled.LightMode else Icons.Filled.DarkMode IconButton(onClick = { isDarkTheme = !isDarkTheme }) { Icon(icon, contentDescription = "Change color scheme") } }) } ) { Surface(Modifier.padding(it)) { Samples[index].second() } } } else { SamplesListScreen( isDarkTheme, onSampleClicked = { currentSampleIndex = it }, onThemeToggleClicked = { isDarkTheme = !isDarkTheme } ) } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun SamplesListScreen( isDarkTheme: Boolean, onSampleClicked: (Int) -> Unit, onThemeToggleClicked: () -> Unit, ) { Scaffold( topBar = { TopAppBar(title = { Text("Samples") }, actions = { val icon = if (isDarkTheme) Icons.Filled.LightMode else Icons.Filled.DarkMode IconButton(onClick = onThemeToggleClicked) { Icon(icon, contentDescription = "Change color scheme") } }) } ) { contentPadding -> LazyColumn(modifier = Modifier.padding(contentPadding)) { itemsIndexed(Samples) { index, (title, sampleContent) -> ListItem( headlineContent = { Text(title) }, modifier = Modifier.clickable(onClick = { onSampleClicked(index) }), leadingContent = { SamplePreview(sampleContent) } ) } } } } @Composable private fun SamplePreview(content: @Composable () -> Unit) { ScreenPreview( Modifier .size(50.dp) .aspectRatio(1f) .clipToBounds() // "Zoom in" to the top-start corner to make the preview more legible. .graphicsLayer( scaleX = 1.5f, scaleY = 1.5f, transformOrigin = TransformOrigin(0f, 0f) ), ) { SampleTheme { Surface(content = content) } } } ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/SampleTheme.kt ================================================ package com.zachklipp.richtext.sample import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.ColorScheme import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Shapes import androidx.compose.material3.Typography import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.TextUnit @Composable fun SampleTheme( isDarkTheme: Boolean = isSystemInDarkTheme(), shapes: Shapes = MaterialTheme.shapes, typography: Typography = MaterialTheme.typography, content: @Composable () -> Unit ) { val supportsDynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S val lightColorScheme = lightColorScheme(primary = Color(0xFF1EB980)) val darkColorScheme = darkColorScheme(primary = Color(0xFF66ffc7)) val colorScheme = when { supportsDynamicColor && isDarkTheme -> { dynamicDarkColorScheme(LocalContext.current) } supportsDynamicColor && !isDarkTheme -> { dynamicLightColorScheme(LocalContext.current) } isDarkTheme -> darkColorScheme else -> lightColorScheme } MaterialTheme(colorScheme, shapes, typography) { val textStyle = LocalTextStyle.current.copy(lineHeight = TextUnit.Unspecified) CompositionLocalProvider(LocalTextStyle provides textStyle) { content() } } } ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/ScreenPreview.kt ================================================ @file:Suppress("DEPRECATION") package com.zachklipp.richtext.sample import android.content.Context import android.content.Context.DISPLAY_SERVICE import android.content.Context.WINDOW_SERVICE import android.hardware.display.DisplayManager import android.hardware.display.DisplayManager.DisplayListener import android.os.Handler import android.os.Looper import android.util.DisplayMetrics import android.view.WindowManager import android.widget.FrameLayout import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.text.selection.DisableSelection import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.RememberObserver import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventPass.Initial import androidx.compose.ui.input.pointer.PointerInputFilter import androidx.compose.ui.input.pointer.PointerInputModifier import androidx.compose.ui.input.pointer.consumeAllChanges import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalView import androidx.compose.ui.semantics.disabled import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize /** * Displays [content] according to the current layout constraints, but with the density adjusted so * that the content things it's rendering inside a full-size screen, where "full-size" is defined * by [screenSize]. The default [screenSize] is read from the current window's default display. */ // TODO Disable focus // TODO Disable key events (maybe covered by focus?) // TODO use this for Slideshow as well. @Composable fun ScreenPreview( modifier: Modifier = Modifier, screenSize: IntSize = rememberDefaultDisplaySize(), content: @Composable () -> Unit ) { val aspectRatio = screenSize.width.toFloat() / screenSize.height.toFloat() BoxWithConstraints( modifier .aspectRatio(aspectRatio) // Disable touch input. .then(PassthroughTouchToParentModifier) .semantics(mergeDescendants = true) { // TODO Block semantics. Is this enough? disabled() } ) { val actualDensity = LocalDensity.current.density // Can use width or height to do the calculation, since the aspect ratio is enforced. val previewDensityScale = constraints.maxWidth / screenSize.width.toFloat() val previewDensity = actualDensity * previewDensityScale // Provide a fake host view, since the preview doesn't really belong to this host view. val context = LocalContext.current val previewView = remember { val previewContext = context.applicationContext FrameLayout(previewContext) } DisableSelection { CompositionLocalProvider( LocalDensity provides Density(previewDensity), LocalView provides previewView, content = content ) } } } /** * Returns the size of the default display for the window manager of the window this composable is * currently attached to. Will also recompose if the display size changes, e.g. when the device is * rotated. * * If the display reports an empty size (0x0), e.g. when running in a preview, then a reasonable * fake size of a phone display in portrait orientation is returned instead. */ @Composable private fun rememberDefaultDisplaySize(): IntSize { val context = LocalContext.current val state = remember { DisplaySizeCalculator(context) } return state.displaySize.value } private class DisplaySizeCalculator(context: Context) : RememberObserver, DisplayListener { private val windowManager = context.getSystemService(WINDOW_SERVICE) as WindowManager private val displayManager = context.getSystemService(DISPLAY_SERVICE) as DisplayManager private val display = windowManager.defaultDisplay val displaySize = mutableStateOf(getDisplaySize()) override fun onAbandoned() { // Noop } override fun onRemembered() { // Update the preview on device rotation, for example. displayManager.registerDisplayListener(this, Handler(Looper.getMainLooper())) } override fun onForgotten() { displayManager.unregisterDisplayListener(this) } override fun onDisplayChanged(displayId: Int) { if (displayId != display.displayId) return displaySize.value = getDisplaySize() } override fun onDisplayAdded(displayId: Int) = Unit override fun onDisplayRemoved(displayId: Int) = Unit private fun getDisplaySize(): IntSize { val metrics = DisplayMetrics().also(display::getMetrics) return if (metrics.widthPixels != 0 && metrics.heightPixels != 0) { IntSize(metrics.widthPixels, metrics.heightPixels) } else { // Zero-sized display? Probably in a preview. Return some fake reasonable default. IntSize(1080, 1920) } } } /** * A [PointerInputModifier] that blocks all touch events to children of the composable to which it's * applied, and instead allows all those events to flow to any filters defined on the parent * composable. */ private object PassthroughTouchToParentModifier : PointerInputModifier, PointerInputFilter() { override val pointerInputFilter: PointerInputFilter get() = this override fun onPointerEvent( pointerEvent: PointerEvent, pass: PointerEventPass, bounds: IntSize ) { if (pass == Initial) { // On the initial pass (ancestors -> descendants), mark all pointer events as completely // consumed. This prevents children from handling any pointer events. // These events are all marked as unconsumed by default. pointerEvent.changes.forEach { it.consumeAllChanges() } } } override fun onCancel() { // Noop. } } ================================================ FILE: android-sample/src/main/java/com/zachklipp/richtext/sample/TextDemo.kt ================================================ package com.zachklipp.richtext.sample import android.content.Context import android.widget.Toast import androidx.compose.animation.Animatable import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.keyframes import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.drawscope.withTransform import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.platform.UriHandler import androidx.compose.ui.text.TextStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp import com.halilibo.richtext.ui.material3.RichText import com.halilibo.richtext.ui.string.InlineContent import com.halilibo.richtext.ui.string.RichTextString.Builder import com.halilibo.richtext.ui.string.RichTextString.Format import com.halilibo.richtext.ui.string.RichTextString.Format.Bold import com.halilibo.richtext.ui.string.RichTextString.Format.Code import com.halilibo.richtext.ui.string.RichTextString.Format.Italic import com.halilibo.richtext.ui.string.RichTextString.Format.Link import com.halilibo.richtext.ui.string.RichTextString.Format.Strikethrough import com.halilibo.richtext.ui.string.RichTextString.Format.Subscript import com.halilibo.richtext.ui.string.RichTextString.Format.Superscript import com.halilibo.richtext.ui.string.RichTextString.Format.Underline import com.halilibo.richtext.ui.string.Text import com.halilibo.richtext.ui.string.richTextString import com.halilibo.richtext.ui.string.withFormat import kotlinx.coroutines.delay import kotlinx.coroutines.launch @Preview(showBackground = true) @Composable fun TextPreview() { val context = LocalContext.current var toggleLink by remember { mutableStateOf(false) } val text = remember(context, toggleLink) { richTextString { appendPreviewSentence(Bold) appendPreviewSentence(Italic) appendPreviewSentence(Underline) appendPreviewSentence(Strikethrough) appendPreviewSentence(Subscript) appendPreviewSentence(Superscript) appendPreviewSentence(Code) appendPreviewSentence( Link("") { toggleLink = !toggleLink }, if (toggleLink) "clicked link" else "link" ) append("Here, ") appendInlineContent(content = spinningCross) append(", is an inline image. ") append("And here, ") appendInlineContent(content = slowLoadingImage) append(", is an inline image that loads after some delay.") append("\n\n") append("Here ") withFormat(Underline) { append("is a ") withFormat(Italic) { append("longer sentence ") withFormat(Bold) { append("with many ") withFormat(Code) { append("different ") withFormat(Strikethrough) { append("nested") } append(" ") } } append("styles.") } } } } RichText { Text(text) } } private val spinningCross = InlineContent { val angle = remember { Animatable(0f) } val color = remember { Animatable(Color.Red) } LaunchedEffect(Unit) { val angleAnim = infiniteRepeatable( animation = tween(durationMillis = 1000, easing = LinearEasing) ) launch { angle.animateTo(360f, angleAnim) } val colorAnim = infiniteRepeatable( animation = keyframes { durationMillis = 2500 Color.Blue at 500 Color.Cyan at 1000 Color.Green at 1500 Color.Magenta at 2000 } ) launch { color.animateTo(Color.Yellow, colorAnim) } } Canvas(modifier = Modifier .size(12.sp.toDp(), 12.sp.toDp()) .padding(2.dp)) { withTransform({ rotate(angle.value, center) }) { val strokeWidth = 3.dp.toPx() val strokeCap = Round drawLine( color.value, start = Offset(0f, size.height / 2), end = Offset(size.width, size.height / 2), strokeWidth = strokeWidth, cap = strokeCap ) drawLine( color.value, start = Offset(size.width / 2, 0f), end = Offset(size.width / 2, size.height), strokeWidth = strokeWidth, cap = strokeCap ) } } } val slowLoadingImage = InlineContent { var loaded by rememberSaveable { mutableStateOf(false) } LaunchedEffect(loaded) { if (!loaded) { delay(3000) loaded = true } } if (!loaded) { LoadingSpinner() } else { Box(Modifier.clickable(onClick = { loaded = false })) { val size = remember { Animatable(16f) } LaunchedEffect(Unit) { size.animateTo(100f) } Picture(Modifier.size(size.value.sp.toDp())) Text( "click to refresh", modifier = Modifier .padding(3.dp) .align(Alignment.Center), fontSize = 8.sp, style = TextStyle(background = Color.LightGray) ) } } } @Composable private fun LoadingSpinner() { val alpha = remember { Animatable(1f) } LaunchedEffect(Unit) { val anim = infiniteRepeatable( animation = keyframes { durationMillis = 500 0f at 250 1f at 500 }) alpha.animateTo(0f, anim) } Text( "⏳", fontSize = 3.em, modifier = Modifier .wrapContentSize(Alignment.Center) .graphicsLayer(alpha = alpha.value) ) } @Composable private fun Picture(modifier: Modifier) { Canvas(modifier) { drawRect(Color.LightGray) drawLine(Color.Red, Offset(0f, 0f), Offset(size.width, size.height)) drawLine(Color.Red, Offset(0f, size.height), Offset(size.width, 0f)) } } @OptIn(ExperimentalStdlibApi::class) private fun Builder.appendPreviewSentence( format: Format, text: String = format.javaClass.simpleName.replaceFirstChar { it.lowercase() } ) { append("Here is some ") withFormat(format) { append(text) } append(" text. ") } @Composable fun ProvideToastUriHandler(context: Context, content: @Composable () -> Unit) { val uriHandler = remember(context) { object : UriHandler { override fun openUri(uri: String) { Toast.makeText(context, uri, Toast.LENGTH_SHORT).show() } } } CompositionLocalProvider(LocalUriHandler provides uriHandler, content) } ================================================ FILE: android-sample/src/main/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: android-sample/src/main/res/drawable-v24/ic_launcher_foreground.xml ================================================ ================================================ FILE: android-sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: android-sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml ================================================ ================================================ FILE: android-sample/src/main/res/values/colors.xml ================================================ #eeeeee #111111 #2079c7 ================================================ FILE: android-sample/src/main/res/values/strings.xml ================================================ Rich Text Sample ================================================ FILE: android-sample/src/main/res/values/styles.xml ================================================ ================================================ FILE: build.gradle.kts ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { id("org.jetbrains.dokka") } repositories { mavenCentral() } dokka { dokkaPublications.configureEach { outputDirectory.set(rootProject.file("docs/api")) } } dependencies { dokka(project(":richtext-ui")) dokka(project(":richtext-ui-material")) dokka(project(":richtext-ui-material3")) dokka(project(":richtext-markdown")) dokka(project(":richtext-commonmark")) } // See https://stackoverflow.com/questions/25324880/detect-ide-environment-with-gradle fun isRunningFromIde(): Boolean { return project.properties["android.injected.invoked.from.ide"] == "true" } subprojects { repositories { google() mavenCentral() } tasks.withType().all { compilerOptions { // TODO(stable); Disable warnings as errors until we get to 1.0.0 // Allow warnings when running from IDE, makes it easier to experiment. // if (!isRunningFromIde()) { // allWarningsAsErrors = true // } freeCompilerArgs = listOf("-opt-in=kotlin.RequiresOptIn", "-Xexpect-actual-classes") } } // taken from https://github.com/google/accompanist/blob/main/build.gradle afterEvaluate { if (tasks.findByName("dokkaHtmlPartial") == null) { // If dokka isn't enabled on this module, skip return@afterEvaluate } } } //disable until the library reaches 1.0.0-beta01 //apply plugin: 'binary-compatibility-validator' //apiValidation { // // Ignore all sample projects, since they're not part of our API. // // Only leaf project name is valid configuration, and every project must be individually ignored. // // See https://github.com/Kotlin/binary-compatibility-validator/issues/3 // ignoredProjects += project('sample').name // ignoredProjects += project('desktop').name // ignoredProjects += project('richtext-ui-kmm').name // ignoredProjects += project('richtext-commonmark-kmm').name //} ================================================ FILE: buildSrc/build.gradle.kts ================================================ repositories { google() mavenCentral() } plugins { `kotlin-dsl` `kotlin-dsl-precompiled-script-plugins` } dependencies { // keep in sync with Dependencies.BuildPlugins.androidGradlePlugin implementation("com.android.tools.build:gradle:9.1.0") implementation("com.vanniktech.maven.publish:com.vanniktech.maven.publish.gradle.plugin:0.36.0") // keep in sync with Dependencies.Kotlin.gradlePlugin implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:2.3.10") // keep in sync with Dependencies.Compose.desktopVersion implementation("org.jetbrains.compose:org.jetbrains.compose.gradle.plugin:1.11.0-beta01") // keep in sync with Dependencies.Kotlin.version implementation("org.jetbrains.kotlin:compose-compiler-gradle-plugin:2.3.10") implementation("org.jetbrains.dokka:dokka-gradle-plugin:2.2.0") implementation(kotlin("script-runtime")) } ================================================ FILE: buildSrc/src/main/kotlin/Dependencies.kt ================================================ object BuildPlugins { // keep in sync with buildSrc/build.gradle.kts val androidGradlePlugin = "com.android.tools.build:gradle:9.1.0" } object AndroidX { val appcompat = "androidx.appcompat:appcompat:1.7.1" } object Network { val okHttp = "com.squareup.okhttp3:okhttp:4.9.0" } object Kotlin { // keep in sync with buildSrc/build.gradle.kts val version = "2.3.10" val binaryCompatibilityValidatorPlugin = "org.jetbrains.kotlinx:binary-compatibility-validator:0.9.0" val gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$version" val composeCompilerPlugin = "org.jetbrains.kotlin.plugin.compose:org.jetbrains.kotlin.plugin.compose.gradle.plugin:$version" object Test { val common = "org.jetbrains.kotlin:kotlin-test-common" val annotations = "org.jetbrains.kotlin:kotlin-test-annotations-common" val jdk = "org.jetbrains.kotlin:kotlin-test-junit" } } val ktlint = "org.jlleitschuh.gradle:ktlint-gradle:10.0.0" object Compose { val desktopVersion = "1.11.0-beta01" val jetbrainsComposePlugin = "org.jetbrains.compose:org.jetbrains.compose.gradle.plugin:$desktopVersion" val activity = "androidx.activity:activity-compose:1.8.2" val toolingData = "androidx.compose.ui:ui-tooling-data:1.6.0" val coil = "io.coil-kt.coil3:coil-compose:3.3.0" val coilHttp = "io.coil-kt.coil3:coil-network-okhttp:3.3.0" } object Commonmark { private val version = "0.26.0" val core = "org.commonmark:commonmark:$version" val tables = "org.commonmark:commonmark-ext-gfm-tables:$version" val strikethrough = "org.commonmark:commonmark-ext-gfm-strikethrough:$version" val autolink = "org.commonmark:commonmark-ext-autolink:$version" } object AndroidConfiguration { val minSdk = 23 val targetSdk = 36 val compileSdk = targetSdk } ================================================ FILE: buildSrc/src/main/kotlin/richtext-kmp-library.gradle.kts ================================================ import AndroidConfiguration.compileSdk import AndroidConfiguration.minSdk import AndroidConfiguration.targetSdk import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { kotlin("multiplatform") id("com.android.kotlin.multiplatform.library") id("org.jetbrains.kotlin.plugin.compose") id("org.jetbrains.compose") id("com.vanniktech.maven.publish") id("org.jetbrains.dokka") signing } repositories { google() mavenCentral() } signing { val signingKey = System.getenv("GPG_PRIVATE_KEY")?.replace("\\n", "\n") val signingPassword = System.getenv("GPG_PRIVATE_PASSWORD") if (signingKey != null && signingPassword != null) { useInMemoryPgpKeys(signingKey, signingPassword) } } // Maven Central credentials are provided via ORG_GRADLE_PROJECT_mavenCentralUsername // and ORG_GRADLE_PROJECT_mavenCentralPassword environment variables. mavenPublishing { publishToMavenCentral() signAllPublications() } kotlin { jvm() explicitApi() android { compileSdk = 36 compilerOptions { jvmTarget.set(JvmTarget.JVM_11) } } } ================================================ FILE: desktop-sample/build.gradle.kts ================================================ import org.jetbrains.compose.desktop.application.dsl.TargetFormat plugins { kotlin("jvm") id("org.jetbrains.compose") id("org.jetbrains.kotlin.plugin.compose") } dependencies { implementation(project(":richtext-commonmark")) implementation(project(":richtext-ui-material")) implementation(compose.desktop.currentOs) implementation("org.jetbrains.compose.material:material-icons-extended:1.7.3") } compose.desktop { application { mainClass = "com.halilibo.richtext.desktop.MarkdownSampleAppKt" nativeDistributions { targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) packageName = "jvm" packageVersion = "1.0.0" } } } ================================================ FILE: desktop-sample/src/main/kotlin/com/halilibo/richtext/desktop/MarkdownSampleApp.kt ================================================ package com.halilibo.richtext.desktop import androidx.compose.foundation.LocalScrollbarStyle import androidx.compose.foundation.background import androidx.compose.foundation.defaultScrollbarStyle import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.input.rememberTextFieldState import androidx.compose.foundation.text.selection.DisableSelection import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll import androidx.compose.material.Icon import androidx.compose.material.LeadingIconTab import androidx.compose.material.Slider import androidx.compose.material.Surface import androidx.compose.material.TabRow import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Info import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.platform.UriHandler import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.singleWindowApplication import com.halilibo.richtext.commonmark.CommonmarkAstNodeParser import com.halilibo.richtext.commonmark.Markdown import com.halilibo.richtext.markdown.BasicMarkdown import com.halilibo.richtext.markdown.node.AstDocument import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.ui.CodeBlockStyle import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.currentRichTextStyle import com.halilibo.richtext.ui.material.RichText import com.halilibo.richtext.ui.resolveDefaults fun main(): Unit = singleWindowApplication( title = "RichText KMP" ) { var richTextStyle by remember { mutableStateOf( RichTextStyle( codeBlockStyle = CodeBlockStyle(wordWrap = true) ).resolveDefaults() ) } Surface { CompositionLocalProvider( LocalScrollbarStyle provides defaultScrollbarStyle().copy( hoverColor = Color.DarkGray, unhoverColor = Color.Gray ) ) { SelectionContainer { val state = rememberTextFieldState(sampleMarkdown) Row( modifier = Modifier .padding(32.dp) .fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(32.dp) ) { Column(modifier = Modifier.weight(1f)) { DisableSelection { RichTextStyleConfig(richTextStyle = richTextStyle, onChanged = { richTextStyle = it }) } BasicTextField( state = state, modifier = Modifier .fillMaxHeight() .background(Color.LightGray) .padding(8.dp) ) } var selectedTab by remember { mutableStateOf(0) } Column(Modifier.weight(1f)) { DisableSelection { TabRow(selectedTab) { LeadingIconTab( selected = selectedTab == 0, onClick = { selectedTab = 0 }, text = { Text("Normal") }, icon = { Icon(Icons.Default.Info, "") }) LeadingIconTab( selected = selectedTab == 1, onClick = { selectedTab = 1 }, text = { Text("Lazy") }, icon = { Icon(Icons.Default.Favorite, "") }) } } ProvidePrintUriHandler { if (selectedTab == 0) { RichText( modifier = Modifier.verticalScroll(rememberScrollState()), style = richTextStyle, ) { Markdown(content = state.text.toString()) } } else { val parser = remember { CommonmarkAstNodeParser() } val astNode = remember(parser) { parser.parse(sampleMarkdown) } RichText( style = richTextStyle, ) { LazyMarkdown(astNode) } } } } } } } } } /** * A function that renders Markdown content lazily at the top level. All markdown trees start with * an AstDocument. If a document is long enough, usually there are more than hundred child nodes * under the root. Then in turn rendering the whole content into the internal column of * `BasicRichText` becomes extremely inefficient. Instead, this renderer at least relieves the top * level rendering by turning the internal column into a LazyColumn. All other nodes below the * first level are rendered as usual. * * @param astNode Root node of Markdown tree. This can be obtained via a parser. */ @Composable fun RichTextScope.LazyMarkdown(astNode: AstNode) { require(astNode.type == AstDocument) { "Lazy Markdown rendering requires root level node to have a type of AstDocument." } // keep the same blockSpacing val currentStyle = currentRichTextStyle val resolvedStyle = remember(currentStyle) { currentStyle.resolveDefaults() } val blockSpacing = with(LocalDensity.current) { resolvedStyle.paragraphSpacing!!.toDp() } LazyColumn(verticalArrangement = Arrangement.spacedBy(blockSpacing)) { var iter = astNode.links.firstChild while (iter != null) { // We need to store iter in a final variable because composition of `item` happens after // iteration val node = iter item { BasicMarkdown(node) } iter = iter.links.next } } } @Composable fun RichTextStyleConfig( richTextStyle: RichTextStyle, onChanged: (RichTextStyle) -> Unit ) { Column(modifier = Modifier.fillMaxWidth()) { Row { Column(Modifier.weight(1f)) { Text("Paragraph spacing:\n${richTextStyle.paragraphSpacing}") Slider( value = richTextStyle.paragraphSpacing!!.value, valueRange = 0f..20f, onValueChange = { onChanged(richTextStyle.copy(paragraphSpacing = it.sp)) } ) } Column(Modifier.weight(1f)) { Text("List item spacing:\n${richTextStyle.listStyle!!.itemSpacing}") Slider( value = richTextStyle.listStyle!!.itemSpacing!!.value, valueRange = 0f..20f, onValueChange = { onChanged( richTextStyle.copy( listStyle = richTextStyle.listStyle!!.copy( itemSpacing = it.sp ) ) ) } ) } } Row { Column(Modifier.weight(1f)) { Text("Table cell padding:\n${richTextStyle.tableStyle!!.cellPadding}") Slider( value = richTextStyle.tableStyle!!.cellPadding!!.value, valueRange = 0f..20f, onValueChange = { onChanged( richTextStyle.copy( tableStyle = richTextStyle.tableStyle!!.copy( cellPadding = it.sp ) ) ) } ) } Column(Modifier.weight(1f)) { Text("Table border width padding:\n${richTextStyle.tableStyle!!.borderStrokeWidth!!}") Slider( value = richTextStyle.tableStyle!!.borderStrokeWidth!!, valueRange = 0f..20f, onValueChange = { onChanged( richTextStyle.copy( tableStyle = richTextStyle.tableStyle!!.copy( borderStrokeWidth = it ) ) ) } ) } } } } @Composable fun ProvidePrintUriHandler(content: @Composable () -> Unit) { val uriHandler = remember { object : UriHandler { override fun openUri(uri: String) { println("Link clicked destination=$uri") } } } CompositionLocalProvider(LocalUriHandler provides uriHandler, content) } private val sampleMarkdown = """ # Demo Based on [this cheatsheet][cheatsheet] --- ## Headers --- # Header 1 ## Header 2 ### Header 3 #### Header 4 ##### Header 5 ###### Header 6 --- ## Full-bleed Image ![](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1920px-Image_created_with_a_mobile_phone.png) ## Images smaller than the width should center ![](https://cdn.nostr.build/p/4a84.png) On LineHeight bug, the image below goes over this text. ![](https://cdn.nostr.build/p/PxZ0.jpg) ## Emphasis Emphasis, aka italics, with *asterisks* or _underscores_. Strong emphasis, aka bold, with **asterisks** or __underscores__. Combined emphasis with **asterisks and _underscores_**. --- ## Lists 1. First ordered list item 2. Another item * Unordered sub-list. 1. Actual numbers don't matter, just that it's a number 1. Ordered sub-list 4. And another item. You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown). To have a line break without a paragraph, you will need to use two trailing spaces. Note that this line is separate, but within the same paragraph. (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.) * Unordered list can use asterisks - Or minuses + Or pluses 2. Ordered list starting with `2.` 3. Another item 0. Ordered list starting with `0.` 003. Ordered list starting with `003.` -1. Starting with `-1.` should not be list --- ## Links [I'm an inline-style link](https://www.google.com) [I'm a reference-style link][Arbitrary case-insensitive reference text] [I'm a relative reference to a repository file](../blob/master/LICENSE) [You can use numbers for reference-style link definitions][1] Or leave it empty and use the [link text itself]. Autolink option will detect text links like https://www.google.com and turn them into Markdown links automatically. --- ## Code Inline `code` has `back-ticks around` it. ```javascript var s = "JavaScript syntax highlighting"; alert(s); ``` ```python s = "Python syntax highlighting" print s ``` ```java /** * Helper method to obtain a Parser with registered strike-through & table extensions * & task lists (added in 1.0.1) * * @return a Parser instance that is supported by this library * @since 1.0.0 */ @NonNull public static Parser createParser() { return new Parser.Builder() .extensions(Arrays.asList( StrikethroughExtension.create(), TablesExtension.create(), TaskListExtension.create() )) .build(); } ``` ```xml ``` ``` No language indicated, so no syntax highlighting. But let's throw in a tag. ``` --- ## Images Inline-style: ![random image](https://picsum.photos/seed/picsum/400/400) ![random image](https://picsum.photos/seed/picsum/400/400 "Text 1") Reference-style: ![random image][logo] [logo]: https://picsum.photos/seed/picsum2/400/400 "Text 2" Base64 Inline ![][image1] --- ## Tables Colons can be used to align columns. | Tables | Are | Cool | | ------------- |:-------------:| -----:| | col 3 is | right-aligned | ${'$'}1600 | | col 2 is | centered | ${'$'}12 | | zebra stripes | are neat | ${'$'}1 | There must be at least 3 dashes separating each header cell. The outer pipes (|) are optional, and you don't need to make the raw Markdown line up prettily. You can also use inline Markdown. Markdown | Less | Pretty --- | --- | --- *Still* | `renders` | ![random image](https://picsum.photos/seed/picsum/400/400 "Text 1") 1 | 2 | 3 --- ## Blockquotes > Blockquotes are very handy in email to emulate reply text. > This line is part of the same quote. Quote break. > This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote. Nested quotes > Hello! >> And to you! --- ## Inline HTML ```html HTML ``` HTML --- ## Horizontal Rule Three or more... --- Hyphens (`-`) *** Asterisks (`*`) ___ Underscores (`_`) ## License ``` Copyright 2019 Dimitry Ivanov (legal@noties.io) Licensed 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.0 Unless required by applicable law or agreed to in writing, software distributed 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 and limitations under the License. ``` [cheatsheet]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet [arbitrary case-insensitive reference text]: https://www.mozilla.org [1]: http://slashdot.org [link text itself]: http://www.reddit.com [image1]: """.trimIndent() ================================================ FILE: desktop-sample/src/main/kotlin/com/halilibo/richtext/desktop/RichTextSampleApp.kt ================================================ package com.halilibo.richtext.desktop import androidx.compose.animation.Animatable import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.keyframes import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.LocalScrollbarStyle import androidx.compose.foundation.clickable import androidx.compose.foundation.defaultScrollbarStyle import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.withTransform import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp import androidx.compose.ui.window.singleWindowApplication import com.halilibo.richtext.ui.BlockQuote import com.halilibo.richtext.ui.CodeBlock import com.halilibo.richtext.ui.CodeBlockStyle import com.halilibo.richtext.ui.FormattedList import com.halilibo.richtext.ui.Heading import com.halilibo.richtext.ui.HorizontalRule import com.halilibo.richtext.ui.InfoPanel import com.halilibo.richtext.ui.InfoPanelType import com.halilibo.richtext.ui.ListType import com.halilibo.richtext.ui.ListType.Ordered import com.halilibo.richtext.ui.ListType.Unordered import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.Table import com.halilibo.richtext.ui.material.RichText import com.halilibo.richtext.ui.resolveDefaults import com.halilibo.richtext.ui.string.InlineContent import com.halilibo.richtext.ui.string.RichTextString.Builder import com.halilibo.richtext.ui.string.RichTextString.Format import com.halilibo.richtext.ui.string.RichTextString.Format.Bold import com.halilibo.richtext.ui.string.RichTextString.Format.Code import com.halilibo.richtext.ui.string.RichTextString.Format.Italic import com.halilibo.richtext.ui.string.RichTextString.Format.Link import com.halilibo.richtext.ui.string.RichTextString.Format.Strikethrough import com.halilibo.richtext.ui.string.RichTextString.Format.Subscript import com.halilibo.richtext.ui.string.RichTextString.Format.Superscript import com.halilibo.richtext.ui.string.RichTextString.Format.Underline import com.halilibo.richtext.ui.string.Text import com.halilibo.richtext.ui.string.richTextString import com.halilibo.richtext.ui.string.withFormat import kotlinx.coroutines.delay import kotlinx.coroutines.launch fun main(): Unit = singleWindowApplication( title = "RichText KMP" ) { var richTextStyle by remember { mutableStateOf( RichTextStyle( codeBlockStyle = CodeBlockStyle(wordWrap = true) ).resolveDefaults() ) } Surface { CompositionLocalProvider( LocalScrollbarStyle provides defaultScrollbarStyle().copy( hoverColor = Color.DarkGray, unhoverColor = Color.Gray ) ) { SelectionContainer { Row( modifier = Modifier .padding(32.dp) .fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(32.dp) ) { Column(modifier = Modifier.weight(1f)) { RichTextStyleConfig(richTextStyle = richTextStyle, onChanged = { richTextStyle = it }) } Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) { RichTextDemo(style = richTextStyle) } } } } } } @Composable fun RichTextDemo( style: RichTextStyle? = null, header: String = "" ) { RichText( modifier = Modifier.padding(8.dp), style = style ) { Heading(0, "Paragraphs $header") Text("Simple paragraph.") Text("Paragraph with\nmultiple lines.") Text("Paragraph with really long line that should be getting wrapped.") TextPreview() Heading(0, "Lists") Heading(1, "Unordered") ListDemo(listType = Unordered) Heading(1, "Ordered") ListDemo(listType = Ordered) Heading(0, "Horizontal Line") Text("Above line") HorizontalRule() Text("Below line") Heading(0, "Code Block") CodeBlock( """ { "Hello": "world!" } """.trimIndent() ) Heading(0, "Block Quote") BlockQuote { Text("These paragraphs are quoted.") Text("More text.") BlockQuote { Text("Nested block quote.") } } Heading(0, "Info Panel") InfoPanel(InfoPanelType.Primary, "Only text primary info panel") InfoPanel(InfoPanelType.Success) { Column { Text("Successfully sent some data") HorizontalRule() BlockQuote { Text("This is a quote") } } } Heading(0, "Table") Table( modifier = Modifier.fillMaxWidth(), headerRow = { cell { Text("Column 1") } cell { Text("Column 2") } }) { row { cell { Text("Hello") } cell { CodeBlock("Foo bar") } } row { cell { BlockQuote { Text("Stuff") } } cell { Text("Hello world this is a really long line that is going to wrap hopefully") } } } } } @Composable private fun RichTextScope.ListDemo(listType: ListType) { FormattedList(listType, @Composable { Text("First list item") FormattedList(listType, @Composable { Text("Indented 1") } ) }, @Composable { Text("") }, @Composable { Text("hello") }, @Composable { Text("Second list item.") FormattedList(listType, @Composable { Text("Indented 2") } ) } ) } @Composable fun TextPreview() { var toggleLink by remember { mutableStateOf(false) } val text = remember(toggleLink) { richTextString { appendPreviewSentence(Bold) appendPreviewSentence(Italic) appendPreviewSentence(Underline) appendPreviewSentence(Strikethrough) appendPreviewSentence(Subscript) appendPreviewSentence(Superscript) appendPreviewSentence(Code) appendPreviewSentence( Link("") { toggleLink = !toggleLink }, if (toggleLink) "clicked link" else "link" ) append("Here, ") appendInlineContent(content = spinningCross) append(", is an inline image. ") append("And here, ") appendInlineContent(content = slowLoadingImage) append(", is an inline image that loads after some delay.") append("\n\n") append("Here ") withFormat(Underline) { append("is a ") withFormat(Italic) { append("longer sentence ") withFormat(Bold) { append("with many ") withFormat(Code) { append("different ") withFormat(Strikethrough) { append("nested") } append(" ") } } append("styles.") } } } } RichText { Text(text) } } private val spinningCross = InlineContent { val angle = remember { Animatable(0f) } val color = remember { Animatable(Color.Red) } LaunchedEffect(Unit) { val angleAnim = infiniteRepeatable( animation = tween(durationMillis = 1000, easing = LinearEasing) ) launch { angle.animateTo(360f, angleAnim) } val colorAnim = infiniteRepeatable( animation = keyframes { durationMillis = 2500 Color.Blue at 500 Color.Cyan at 1000 Color.Green at 1500 Color.Magenta at 2000 } ) launch { color.animateTo(Color.Yellow, colorAnim) } } Canvas(modifier = Modifier .size(12.sp.toDp(), 12.sp.toDp()) .padding(2.dp)) { withTransform({ rotate(angle.value, center) }) { val strokeWidth = 3.dp.toPx() val strokeCap = StrokeCap.Round drawLine( color.value, start = Offset(0f, size.height / 2), end = Offset(size.width, size.height / 2), strokeWidth = strokeWidth, cap = strokeCap ) drawLine( color.value, start = Offset(size.width / 2, 0f), end = Offset(size.width / 2, size.height), strokeWidth = strokeWidth, cap = strokeCap ) } } } val slowLoadingImage = InlineContent { var loaded by rememberSaveable { mutableStateOf(false) } LaunchedEffect(loaded) { if (!loaded) { delay(3000) loaded = true } } if (!loaded) { LoadingSpinner() } else { Box(Modifier.clickable(onClick = { loaded = false })) { val size = remember { Animatable(16f) } LaunchedEffect(Unit) { size.animateTo(100f) } Picture(Modifier.size(size.value.sp.toDp())) Text( "click to refresh", modifier = Modifier .padding(3.dp) .align(Alignment.Center), fontSize = 8.sp, style = TextStyle(background = Color.LightGray) ) } } } @Composable private fun LoadingSpinner() { val alpha = remember { Animatable(1f) } LaunchedEffect(Unit) { val anim = infiniteRepeatable( animation = keyframes { durationMillis = 500 0f at 250 1f at 500 }) alpha.animateTo(0f, anim) } Text( "⏳", fontSize = 3.em, modifier = Modifier .wrapContentSize(Alignment.Center) .graphicsLayer(alpha = alpha.value) ) } @Composable private fun Picture(modifier: Modifier) { Canvas(modifier) { drawRect(Color.LightGray) drawLine(Color.Red, Offset(0f, 0f), Offset(size.width, size.height)) drawLine(Color.Red, Offset(0f, size.height), Offset(size.width, 0f)) } } @OptIn(ExperimentalStdlibApi::class) private fun Builder.appendPreviewSentence( format: Format, text: String = format.javaClass.simpleName.replaceFirstChar { it.lowercase() } ) { append("Here is some ") withFormat(format) { append(text) } append(" text. ") } ================================================ FILE: docs/index.md ================================================ # Overview [![Maven Central](https://img.shields.io/maven-central/v/com.halilibo.compose-richtext/richtext-ui.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22com.halilibo.compose-richtext%22) [![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0) Compose Richtext is a collection of Compose libraries for working with rich text formatting and Markdown rendering. `richtext-ui`, `richtext-markdown`, `richtext-commonmark`, and `richtext-ui-material`|`richtext-ui-material3` are Kotlin Multiplatform(KMP) Compose Libraries with the exception of iOS. All these modules can be used in Android and Desktop Compose apps. Each library is documented separately, see the navigation menu for the list. This site also includes an API reference. !!! warning This project is currently on its way to reach `1.0.0` release. The timeline is not clear and the release date will remain TBD for a while. There are no tests and some things might be broken or very non-performant. The API may also change between releases without deprecation cycles. ## Getting started These libraries are published to Maven Central, so just add a Gradle dependency: ```kotlin dependencies { implementation("com.halilibo.compose-richtext::${richtext_version}") } ``` There is no difference for KMP artifacts. For instance, if you are adding `richtext-ui` to a Kotlin Multiplatform module ```kotlin val commonMain by getting { dependencies { implementation("com.halilibo.compose-richtext:richtext-ui:${richtext_version}") } } ``` ### Library Artifacts The `LIBRARY_ARTIFACT`s for each individual library can be found on their respective pages. ## Samples Please check out [Android](https://github.com/halilozercan/compose-richtext/tree/main/android-sample) and [Desktop](https://github.com/halilozercan/compose-richtext/tree/main/desktop-sample) projects to see various use cases of RichText in both platforms. ================================================ FILE: docs/richtext-commonmark.md ================================================ # Commonmark Markdown [![Android Library](https://img.shields.io/badge/Platform-Android-green.svg?style=for-the-badge)](https://developer.android.com/studio/build/dependencies) [![JVM Library](https://img.shields.io/badge/Platform-JVM-red.svg?style=for-the-badge)](https://kotlinlang.org/docs/mpp-intro.html) Library for parsing and rendering Markdown in Compose using [CommonMark](https://github.com/commonmark/commonmark-java) library/spec to parse, and [richtext-markdown](../richtext-markdown/) to render. ## Gradle ```kotlin dependencies { implementation("com.halilibo.compose-richtext:richtext-commonmark:${richtext_version}") } ``` ## Parsing `richtext-markdown` module renders a given Markdown Abstract Syntax Tree. It accepts a root `AstNode`. This library gives you a parser called `CommonmarkAstNodeParser` to easily convert any String to an `AstNode` that represents the Markdown tree. ```kotlin val parser = CommonmarkAstNodeParser() val astNode = parser.parse( """ # Demo Emphasis, aka italics, with *asterisks* or _underscores_. Strong emphasis, aka bold, with **asterisks** or __underscores__. Combined emphasis with **asterisks and _underscores_**. [Links with two blocks, text in square-brackets, destination is in parentheses.](https://www.example.com). Inline `code` has `back-ticks around` it. 1. First ordered list item 2. Another item * Unordered sub-list. 3. And another item. You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown). * Unordered list can use asterisks - Or minuses + Or pluses """.trimIndent() ) // ... RichTextScope.BasicMarkdown(astNode) ``` ## Rendering The simplest way to render markdown is just pass a string to the [`Markdown`](../api/richtext-commonmark/com.halilibo.richtext.markdown/-markdown.html) composable under RichText scope: ~~~kotlin RichText( modifier = Modifier.padding(16.dp) ) { Markdown( """ # Demo Emphasis, aka italics, with *asterisks* or _underscores_. Strong emphasis, aka bold, with **asterisks** or __underscores__. Combined emphasis with **asterisks and _underscores_**. [Links with two blocks, text in square-brackets, destination is in parentheses.](https://www.example.com). Inline `code` has `back-ticks around` it. 1. First ordered list item 2. Another item * Unordered sub-list. 3. And another item. You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown). * Unordered list can use asterisks - Or minuses + Or pluses --- ```javascript var s = "code blocks use monospace font"; alert(s); ``` Markdown | Table | Extension --- | --- | --- *renders* | `beautiful images` | ![random image](https://picsum.photos/seed/picsum/400/400 "Text 1") 1 | 2 | 3 > Blockquotes are very handy in email to emulate reply text. > This line is part of the same quote. """.trimIndent() ) } ~~~ Which produces something like this: ![markdown demo](img/markdown-demo.png) ## [`MarkdownParseOptions`](../api/richtext-commonmark/com.halilibo.richtext.commonmark/-markdown-parse-options.html) Passing `MarkdownParseOptions` into either `Markdown` composable or `CommonmarkAstNodeParser.parse` method provides the ability to control some aspects of the markdown parser: ```kotlin val markdownParseOptions = MarkdownParseOptions( autolink = false ) Markdown( markdownParseOptions = markdownParseOptions ) ``` ================================================ FILE: docs/richtext-markdown.md ================================================ # Markdown [![Android Library](https://img.shields.io/badge/Platform-Android-green.svg?style=for-the-badge)](https://developer.android.com/studio/build/dependencies) [![JVM Library](https://img.shields.io/badge/Platform-JVM-red.svg?style=for-the-badge)](https://kotlinlang.org/docs/mpp-intro.html) Library for rendering Markdown tree that is defined as an `AstNode`. This module would be useless for someone who is looking to just render a Markdown string. Please check out `richtext-commonmark` for such features. `richtext-markdown` behaves as sort of a building block. You can create your own parser or use 3rd party ones that converts any Markdown string to an `AstNode` tree. ## Gradle ```kotlin dependencies { implementation("com.halilibo.compose-richtext:richtext-markdown:${richtext_version}") } ``` ## Rendering The simplest way to render markdown is just pass an `AstNode` to the [`BasicMarkdown`](../api/richtext-markdown/com.halilibo.richtext.markdown/-basic-markdown.html) composable under RichText scope: ~~~kotlin RichText( modifier = Modifier.padding(16.dp) ) { // requires richtext-commonmark module. val parser = remember(options) { CommonmarkAstNodeParser(options) } val astNode = remember(parser) { parser.parse( """ # Demo Emphasis, aka italics, with *asterisks* or _underscores_. Strong emphasis, aka bold, with **asterisks** or __underscores__. Combined emphasis with **asterisks and _underscores_**. [Links with two blocks, text in square-brackets, destination is in parentheses.](https://www.example.com). Inline `code` has `back-ticks around` it. 1. First ordered list item 2. Another item * Unordered sub-list. 3. And another item. You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown). * Unordered list can use asterisks - Or minuses + Or pluses """.trimIndent() ) } BasicMarkdown(astNode) } ~~~ ================================================ FILE: docs/richtext-ui-material.md ================================================ # Richtext UI Material [![Android Library](https://img.shields.io/badge/Platform-Android-green.svg?style=for-the-badge)](https://developer.android.com/studio/build/dependencies) [![JVM Library](https://img.shields.io/badge/Platform-JVM-red.svg?style=for-the-badge)](https://kotlinlang.org/docs/mpp-intro.html) Library that makes RichText compatible with Material design in Compose. ## Gradle ```kotlin dependencies { implementation("com.halilibo.compose-richtext:richtext-ui-material:${richtext_version}") } ``` ## Usage Material RichText library provides a single composable called `RichText` which automatically passes down Material theming attributes to `BasicRichText`. ### [`RichText`](../api/richtext-ui-material/com.halilibo.richtext.ui.material/-rich-text.html) `RichText` composable wraps around regular `BasicRichText` while introducing the necessary integration dependencies. `RichText` shares the exact arguments with regular `BasicRichText`. ```kotlin RichText(modifier = Modifier.background(color = Color.White)) { Heading(0, "Paragraphs") Text("Simple paragraph.") ... } ``` ================================================ FILE: docs/richtext-ui-material3.md ================================================ # Richtext UI Material 3 [![Android Library](https://img.shields.io/badge/Platform-Android-green.svg?style=for-the-badge)](https://developer.android.com/studio/build/dependencies) [![JVM Library](https://img.shields.io/badge/Platform-JVM-red.svg?style=for-the-badge)](https://kotlinlang.org/docs/mpp-intro.html) Library that makes RichText compatible with Material design in Compose. ## Gradle ```kotlin dependencies { implementation("com.halilibo.compose-richtext:richtext-ui-material3:${richtext_version}") } ``` ## Usage Material3 RichText library provides a single composable called `RichText` which automatically passes down Material3 theming attributes to `BasicRichText`. ### [`RichText`](../api/richtext-ui-material/com.halilibo.richtext.ui.material3/-rich-text.html) `RichText` composable wraps around regular `BasicRichText` while introducing the necessary integration dependencies. `RichText` shares the exact arguments with regular `BasicRichText`. ```kotlin RichText(modifier = Modifier.background(color = Color.White)) { Heading(0, "Paragraphs") Text("Simple paragraph.") ... } ``` ================================================ FILE: docs/richtext-ui.md ================================================ # Richtext UI [![Android Library](https://img.shields.io/badge/Platform-Android-green.svg?style=for-the-badge)](https://developer.android.com/studio/build/dependencies) [![JVM Library](https://img.shields.io/badge/Platform-JVM-red.svg?style=for-the-badge)](https://kotlinlang.org/docs/mpp-intro.html) A library of Composables for formatting text using higher-level concepts than are not supported by compose foundation, such as "ordered lists" and "headings". Richtext UI is a base library that is non-opinionated about higher level design requirements. If you are already using `MaterialTheme` in your compose app, you can jump to [RichText UI Material](../richtext-ui-material/index.html) for a quick start. There is also Material3 flavor at [RichText UI Material3](../richtext-ui-material3/index.html) ## Gradle ```kotlin dependencies { implementation("com.halilibo.compose-richtext:richtext-ui:${richtext_version}") } ``` ## [`BasicRichText`](../api/richtext-ui/com.halilibo.richtext.ui/-basic-rich-text.html) Richtext UI does not depend on Material artifact of Compose. Design agnostic API allows anyone to adopt Richtext UI and its extensions like Markdown to their own design and typography systems. Hence, just like `foundation` and `material` modules of Compose, this library also names the building block with `Basic` prefix. If you are planning to adopt RichText within your design system, please go ahead and check out [`RichText Material`](../richtext-ui-material/index.html) for inspiration. ## [`RichTextScope`](../api/richtext-ui/com.halilibo.richtext.ui/-rich-text-scope/index.html) `RichTextScope` is a context wrapper around Composables that integrate and play well within Richtext content. ## [`RichTextThemeProvider`](../api/richtext-ui/com.halilibo.richtext.ui/-rich-text-theme-provider.html) Entry point for integrating app's own typography and theme system with BasicRichText. API for this integration is highly influenced by how compose-material theming is designed. RichText library assumes that almost all Theme/Design systems would have composition locals that provide a TextStyle downstream. Moreover, text style should not include text color by best practice. Content color exists to figure out text color in the current context. Light/Dark theming leverages content color to influence not just text but other parts of theming as well. ## Example Open the `Demo.kt` file in the `sample` module to play with this. Although the mentioned demo uses Material integrated version of `RichText`, they share exactly the same API. ```kotlin BasicRichText( modifier = Modifier.background(color = Color.White) ) { Heading(0, "Paragraphs") Text("Simple paragraph.") Text("Paragraph with\nmultiple lines.") Text("Paragraph with really long line that should be getting wrapped.") Heading(0, "Lists") Heading(1, "Unordered") ListDemo(listType = Unordered) Heading(1, "Ordered") ListDemo(listType = Ordered) Heading(0, "Horizontal Line") Text("Above line") HorizontalRule() Text("Below line") Heading(0, "Code Block") CodeBlock( """ { "Hello": "world!" } """.trimIndent() ) Heading(0, "Block Quote") BlockQuote { Text("These paragraphs are quoted.") Text("More text.") BlockQuote { Text("Nested block quote.") } } Heading(0, "Info Panel") InfoPanel(InfoPanelType.Primary, "Only text primary info panel") InfoPanel(InfoPanelType.Success) { Column { Text("Successfully sent some data") HorizontalRule() BlockQuote { Text("This is a quote") } } } Heading(0, "Table") Table(headerRow = { cell { Text("Column 1") } cell { Text("Column 2") } }) { row { cell { Text("Hello") } cell { CodeBlock("Foo bar") } } row { cell { BlockQuote { Text("Stuff") } } cell { Text("Hello world this is a really long line that is going to wrap hopefully") } } } } ``` Looks like this: ![demo rendering](img/richtext-demo.png) ================================================ FILE: gen_dokka_docs.sh ================================================ #!/bin/bash # Fail on any error set -ex DOCS_ROOT=docs-gen [ -d $DOCS_ROOT ] && rm -r $DOCS_ROOT mkdir $DOCS_ROOT # Clear out the old API docs [ -d docs/api ] && rm -r docs/api # Build the docs with dokka ./gradlew dokkaGenerate --stacktrace # Create a copy of our docs at our $DOCS_ROOT cp -a docs/* $DOCS_ROOT # Convert docs/xxx.md links to just xxx/ sed -i.bak 's/docs\/\([a-zA-Z-]*\).md/\1/' $DOCS_ROOT/index.md # Finally delete all of the backup files find . -name '*.bak' -delete ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=768m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app"s APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Kotlin code style for this project: "official" or "obsolete": kotlin.code.style=official # Required to publish to Nexus (see https://github.com/gradle/gradle/issues/11308) systemProp.org.gradle.internal.publish.checksums.insecure=true GROUP=com.halilibo.compose-richtext VERSION_NAME=1.0.0-alpha04 POM_DESCRIPTION=A collection of Compose libraries for advanced text formatting and alternative display types. POM_INCEPTION_YEAR=2020 POM_URL=https://github.com/halilozercan/compose-richtext POM_SCM_URL=https://github.com/halilozercan/compose-richtext/ POM_SCM_CONNECTION=scm:git:git://github.com/halilozercan/compose-richtext.git POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/halilozercan/compose-richtext.git POM_LICENSE_NAME=The Apache Software License, Version 2.0 POM_LICENSE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENSE_DIST=repo POM_DEVELOPER_ID=halilozercan POM_DEVELOPER_NAME=Halil Ozercan org.jetbrains.dokka.experimental.gradle.pluginMode=V2EnabledWithHelpers kotlin.mpp.stability.nowarn=true kotlin.mpp.androidSourceSetLayoutVersion=2 android.defaults.buildfeatures.resvalues=true android.sdk.defaultTargetSdkToCompileSdkIfUnset=false android.enableAppCompileTimeRClass=false android.usesSdkInManifest.disallowed=false android.uniquePackageNames=false android.dependency.useConstraints=true android.r8.strictFullModeForKeepRules=false android.r8.optimizedResourceShrinking=false android.builtInKotlin=false android.newDsl=false ================================================ FILE: gradlew ================================================ #!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed 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 and # limitations under the License. # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: mkdocs.yml ================================================ site_name: Compose Richtext repo_name: compose-richtext repo_url: https://github.com/halilozercan/compose-richtext site_description: "A collection of Compose libraries for advanced text formatting and alternative display types." site_author: Halil Ozercan site_url: https://halilibo.com/compose-richtext remote_branch: gh-pages edit_uri: edit/main/docs/ docs_dir: docs-gen theme: name: material icon: repo: fontawesome/brands/github features: - navigation.instant - toc.autohide markdown_extensions: - toc: permalink: true - pymdownx.superfences - pymdownx.tabbed - admonition nav: - index.md - richtext-ui-material.md - richtext-ui-material3.md - richtext-ui.md - richtext-markdown.md - richtext-commonmark.md - 'API Reference': api/ - Changelog: https://github.com/halilozercan/compose-richtext/releases ================================================ FILE: richtext-commonmark/build.gradle.kts ================================================ plugins { id("richtext-kmp-library") id("org.jetbrains.dokka") } kotlin { android { namespace = "com.halilibo.richtext.commonmark" } sourceSets { val commonMain by getting { dependencies { implementation(compose.runtime) api(project(":richtext-ui")) api(project(":richtext-markdown")) } } val commonTest by getting val jvmAndroidMain by creating { dependsOn(commonMain) dependencies { implementation(Commonmark.core) implementation(Commonmark.tables) implementation(Commonmark.strikethrough) implementation(Commonmark.autolink) } } val jvmAndroidTest by creating { dependsOn(commonTest) dependencies { implementation(Kotlin.Test.jdk) } } val androidMain by getting { dependsOn(jvmAndroidMain) } val jvmMain by getting { dependsOn(jvmAndroidMain) } val jvmTest by getting { dependsOn(jvmAndroidTest) } } } ================================================ FILE: richtext-commonmark/gradle.properties ================================================ POM_NAME=Compose Richtext Commonmark POM_DESCRIPTION=A library for rendering markdown in Compose using the Commonmark library. ================================================ FILE: richtext-commonmark/src/commonMain/kotlin/com/halilibo/richtext/commonmark/CommonMarkdownParseOptions.kt ================================================ package com.halilibo.richtext.commonmark /** * Allows configuration of the Markdown parser * * @param autolink Detect plain text links and turn them into Markdown links. */ public class CommonMarkdownParseOptions( public val autolink: Boolean ) { override fun toString(): String { return "CommonMarkdownParseOptions(autolink=$autolink)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CommonMarkdownParseOptions) return false return autolink == other.autolink } override fun hashCode(): Int { return autolink.hashCode() } public fun copy( autolink: Boolean = this.autolink ): CommonMarkdownParseOptions = CommonMarkdownParseOptions( autolink = autolink ) public companion object { public val Default: CommonMarkdownParseOptions = CommonMarkdownParseOptions( autolink = true ) } } ================================================ FILE: richtext-commonmark/src/commonMain/kotlin/com/halilibo/richtext/commonmark/Markdown.kt ================================================ package com.halilibo.richtext.commonmark import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import com.halilibo.richtext.markdown.AstBlockNodeComposer import com.halilibo.richtext.markdown.BasicMarkdown import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.ui.RichTextScope /** * A composable that renders Markdown content according to Commonmark specification using RichText. * * @param content Markdown text. No restriction on length. * @param markdownParseOptions Options for the Markdown parser. * @param astBlockNodeComposer An interceptor to take control of composing any block type node's * rendering. Use it to render images, html text, tables with your own components. */ @Composable public fun RichTextScope.Markdown( content: String, markdownParseOptions: CommonMarkdownParseOptions = CommonMarkdownParseOptions.Default, astBlockNodeComposer: AstBlockNodeComposer? = null ) { val commonmarkAstNodeParser = remember(markdownParseOptions) { CommonmarkAstNodeParser(markdownParseOptions) } val astRootNode by produceState( initialValue = null, key1 = commonmarkAstNodeParser, key2 = content ) { value = commonmarkAstNodeParser.parse(content) } astRootNode?.let { BasicMarkdown(astNode = it, astBlockNodeComposer = astBlockNodeComposer) } } /** * A helper class that can convert any text content into an ASTNode tree and return its root. */ public expect class CommonmarkAstNodeParser( options: CommonMarkdownParseOptions = CommonMarkdownParseOptions.Default ) { /** * Parse markdown content and return Abstract Syntax Tree(AST). * * @param text Markdown text to be parsed. * @param options Options for the Commonmark Markdown parser. */ public fun parse(text: String): AstNode } ================================================ FILE: richtext-commonmark/src/jvmAndroidMain/kotlin/com/halilibo/richtext/commonmark/AstNodeConvert.kt ================================================ package com.halilibo.richtext.commonmark import com.halilibo.richtext.markdown.node.AstBlockQuote import com.halilibo.richtext.markdown.node.AstCode import com.halilibo.richtext.markdown.node.AstDocument import com.halilibo.richtext.markdown.node.AstEmphasis import com.halilibo.richtext.markdown.node.AstFencedCodeBlock import com.halilibo.richtext.markdown.node.AstHardLineBreak import com.halilibo.richtext.markdown.node.AstHeading import com.halilibo.richtext.markdown.node.AstHtmlBlock import com.halilibo.richtext.markdown.node.AstHtmlInline import com.halilibo.richtext.markdown.node.AstImage import com.halilibo.richtext.markdown.node.AstIndentedCodeBlock import com.halilibo.richtext.markdown.node.AstLink import com.halilibo.richtext.markdown.node.AstLinkReferenceDefinition import com.halilibo.richtext.markdown.node.AstListItem import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.markdown.node.AstNodeLinks import com.halilibo.richtext.markdown.node.AstNodeType import com.halilibo.richtext.markdown.node.AstOrderedList import com.halilibo.richtext.markdown.node.AstParagraph import com.halilibo.richtext.markdown.node.AstSoftLineBreak import com.halilibo.richtext.markdown.node.AstStrikethrough import com.halilibo.richtext.markdown.node.AstStrongEmphasis import com.halilibo.richtext.markdown.node.AstTableBody import com.halilibo.richtext.markdown.node.AstTableCell import com.halilibo.richtext.markdown.node.AstTableCellAlignment import com.halilibo.richtext.markdown.node.AstTableHeader import com.halilibo.richtext.markdown.node.AstTableRoot import com.halilibo.richtext.markdown.node.AstTableRow import com.halilibo.richtext.markdown.node.AstText import com.halilibo.richtext.markdown.node.AstThematicBreak import com.halilibo.richtext.markdown.node.AstUnorderedList import org.commonmark.ext.autolink.AutolinkExtension import org.commonmark.ext.gfm.strikethrough.Strikethrough import org.commonmark.ext.gfm.strikethrough.StrikethroughExtension import org.commonmark.ext.gfm.tables.TableBlock import org.commonmark.ext.gfm.tables.TableBody import org.commonmark.ext.gfm.tables.TableCell import org.commonmark.ext.gfm.tables.TableCell.Alignment.CENTER import org.commonmark.ext.gfm.tables.TableCell.Alignment.LEFT import org.commonmark.ext.gfm.tables.TableCell.Alignment.RIGHT import org.commonmark.ext.gfm.tables.TableHead import org.commonmark.ext.gfm.tables.TableRow import org.commonmark.ext.gfm.tables.TablesExtension import org.commonmark.node.BlockQuote import org.commonmark.node.BulletList import org.commonmark.node.Code import org.commonmark.node.CustomBlock import org.commonmark.node.CustomNode import org.commonmark.node.Document import org.commonmark.node.Emphasis import org.commonmark.node.FencedCodeBlock import org.commonmark.node.HardLineBreak import org.commonmark.node.Heading import org.commonmark.node.HtmlBlock import org.commonmark.node.HtmlInline import org.commonmark.node.Image import org.commonmark.node.IndentedCodeBlock import org.commonmark.node.Link import org.commonmark.node.LinkReferenceDefinition import org.commonmark.node.ListItem import org.commonmark.node.Node import org.commonmark.node.OrderedList import org.commonmark.node.Paragraph import org.commonmark.node.SoftLineBreak import org.commonmark.node.StrongEmphasis import org.commonmark.node.Text import org.commonmark.node.ThematicBreak import org.commonmark.parser.Parser /** * Holds the data for a pending conversion task in the iterative tree traversal. */ private class ConvertWorkItem( val startNode: Node, val parentAstNode: AstNode?, val initialPrev: AstNode?, val onFirstCreated: (AstNode?) -> Unit ) /** * Maps a CommonMark [Node] to its corresponding [AstNodeType]. * Returns null for unrecognized node types (CustomNode, CustomBlock, etc.). */ private fun convertNodeType(node: Node): AstNodeType? = when (node) { is BlockQuote -> AstBlockQuote is BulletList -> AstUnorderedList(bulletMarker = node.bulletMarker) is Code -> AstCode(literal = node.literal) is Document -> AstDocument is Emphasis -> AstEmphasis(delimiter = node.openingDelimiter) is FencedCodeBlock -> AstFencedCodeBlock( literal = node.literal, fenceChar = node.fenceChar, fenceIndent = node.fenceIndent, fenceLength = node.fenceLength, info = node.info ) is HardLineBreak -> AstHardLineBreak is Heading -> AstHeading( level = node.level ) is ThematicBreak -> AstThematicBreak is HtmlInline -> AstHtmlInline( literal = node.literal ) is HtmlBlock -> AstHtmlBlock( literal = node.literal ) is Image -> { if (node.destination == null) { null } else { AstImage( title = node.title ?: "", destination = node.destination ) } } is IndentedCodeBlock -> AstIndentedCodeBlock( literal = node.literal ) is Link -> AstLink( title = node.title ?: "", destination = node.destination ) is ListItem -> AstListItem is OrderedList -> AstOrderedList( startNumber = node.startNumber, delimiter = node.delimiter ) is Paragraph -> AstParagraph is SoftLineBreak -> AstSoftLineBreak is StrongEmphasis -> AstStrongEmphasis( delimiter = node.openingDelimiter ) is Text -> AstText( literal = node.literal ) is LinkReferenceDefinition -> AstLinkReferenceDefinition( title = node.title ?: "", destination = node.destination, label = node.label ) is TableBlock -> AstTableRoot is TableHead -> AstTableHeader is TableBody -> AstTableBody is TableRow -> AstTableRow is TableCell -> AstTableCell( header = node.isHeader, alignment = when (node.alignment) { LEFT -> AstTableCellAlignment.LEFT CENTER -> AstTableCellAlignment.CENTER RIGHT -> AstTableCellAlignment.RIGHT null -> AstTableCellAlignment.LEFT else -> AstTableCellAlignment.LEFT } ) is Strikethrough -> AstStrikethrough( node.openingDelimiter ) is CustomNode -> null is CustomBlock -> null else -> null } /** * Converts common-markdown tree to AstNode tree iteratively using an explicit stack, * avoiding StackOverflowError on deeply nested or long markdown documents. */ internal fun convert( node: Node?, parentNode: AstNode? = null, previousNode: AstNode? = null, ): AstNode? { node ?: return null var result: AstNode? = null val stack = ArrayDeque() stack.addLast(ConvertWorkItem(node, parentNode, previousNode) { result = it }) while (stack.isNotEmpty()) { val item = stack.removeLast() var prev: AstNode? = null var firstCreated: AstNode? = null var cmNode: Node? = item.startNode var nullTypeNode: Node? = null // Iterate through siblings instead of recursing while (cmNode != null) { val nodeType = convertNodeType(cmNode) val newNode = nodeType?.let { AstNode(it, AstNodeLinks( parent = item.parentAstNode, previous = prev ?: item.initialPrev )) } if (newNode != null) { if (firstCreated == null) firstCreated = newNode prev?.links?.next = newNode // Push child processing onto the explicit stack instead of recursing val child = cmNode.firstChild if (child != null) { stack.addLast(ConvertWorkItem(child, newNode, null) { newNode.links.firstChild = it }) } prev = newNode cmNode = cmNode.next } else { // Unrecognized node type — stop sibling chain (preserves original behavior) nullTypeNode = cmNode cmNode = null } } // Set lastChild on the parent, matching the original recursive behavior if (nullTypeNode != null) { if (nullTypeNode.next == null) { item.parentAstNode?.links?.lastChild = null } } else { item.parentAstNode?.links?.lastChild = prev } item.onFirstCreated(firstCreated) } return result } public actual class CommonmarkAstNodeParser actual constructor( options: CommonMarkdownParseOptions ) { private val parser = Parser.builder() .extensions( listOfNotNull( TablesExtension.create(), StrikethroughExtension.create(), if (options.autolink) AutolinkExtension.create() else null ) ) .build() public actual fun parse(text: String): AstNode { val commonmarkNode = parser.parse(text) ?: throw IllegalArgumentException( "Could not parse the given text content into a meaningful Markdown representation!" ) return convert(commonmarkNode) ?: throw IllegalArgumentException( "Could not convert the generated Commonmark Node into an ASTNode!" ) } } ================================================ FILE: richtext-commonmark/src/jvmAndroidTest/kotlin/com/halilibo/richtext/commonmark/AstNodeConvertKtTest.kt ================================================ package com.halilibo.richtext.markdown import com.halilibo.richtext.commonmark.CommonMarkdownParseOptions import com.halilibo.richtext.commonmark.CommonmarkAstNodeParser import com.halilibo.richtext.commonmark.convert import com.halilibo.richtext.markdown.node.AstBlockQuote import com.halilibo.richtext.markdown.node.AstDocument import com.halilibo.richtext.markdown.node.AstHeading import com.halilibo.richtext.markdown.node.AstImage import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.markdown.node.AstNodeLinks import com.halilibo.richtext.markdown.node.AstParagraph import com.halilibo.richtext.markdown.node.AstText import org.commonmark.node.Document import org.commonmark.node.Image import org.commonmark.node.Paragraph import org.commonmark.node.Text import org.junit.Test import java.util.concurrent.atomic.AtomicReference import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue import kotlin.test.fail internal class AstNodeConvertKtTest { private val parser = CommonmarkAstNodeParser(CommonMarkdownParseOptions.Default) @Test fun `when image without title is converted, then the content description is empty`() { val destination = "/url" val image = Image(destination, null) val result = convert(image) assertEquals( expected = AstNode( type = AstImage(title = "", destination = destination), links = AstNodeLinks() ), actual = result ) } @Test fun `tree links are correctly wired for a document with siblings`() { val root = parser.parse("# Heading\n\nParagraph text") // Root should be a Document assertEquals(AstDocument, root.type) assertNull(root.links.parent) // First child should be the heading val heading = root.links.firstChild assertNotNull(heading) assertEquals(AstHeading(level = 1), heading.type) assertSame(root, heading.links.parent) assertNull(heading.links.previous) // Second child should be the paragraph val paragraph = heading.links.next assertNotNull(paragraph) assertEquals(AstParagraph, paragraph.type) assertSame(root, paragraph.links.parent) assertSame(heading, paragraph.links.previous) assertNull(paragraph.links.next) // lastChild should point to the paragraph assertSame(paragraph, root.links.lastChild) } @Test fun `tree links are correctly wired for nested structures`() { val root = parser.parse("> quoted text") val blockquote = root.links.firstChild assertNotNull(blockquote) assertEquals(AstBlockQuote, blockquote.type) assertSame(root, blockquote.links.parent) val paragraph = blockquote.links.firstChild assertNotNull(paragraph) assertEquals(AstParagraph, paragraph.type) assertSame(blockquote, paragraph.links.parent) val text = paragraph.links.firstChild assertNotNull(text) assertEquals(AstText(literal = "quoted text"), text.type) assertSame(paragraph, text.links.parent) } @Test fun `document with many sibling paragraphs does not overflow`() { // 2000 paragraphs would cause ~2000 frames of sibling recursion val markdown = (1..2000).joinToString("\n\n") { "Paragraph $it" } val root = parser.parse(markdown) assertEquals(AstDocument, root.type) // Walk the sibling chain and count paragraphs var count = 0 var node = root.links.firstChild while (node != null) { assertEquals(AstParagraph, node.type) count++ node = node.links.next } assertEquals(2000, count) // lastChild should be the final paragraph assertNotNull(root.links.lastChild) assertNull(root.links.lastChild!!.links.next) } @Test fun `deeply nested blockquotes do not overflow`() { // 500 levels of nested blockquotes would cause ~500 frames of child recursion val markdown = ">".repeat(500) + " deep text" val root = parser.parse(markdown) assertEquals(AstDocument, root.type) // Walk down the child chain counting blockquotes var depth = 0 var node = root.links.firstChild while (node != null && node.type is AstBlockQuote) { depth++ node = node.links.firstChild } assertEquals(500, depth) // The innermost blockquote should contain a paragraph with text assertNotNull(node) assertEquals(AstParagraph, node.type) } /** * Proves that the sibling chain depth we test would overflow a recursive implementation * on a constrained thread stack (similar to Android's ~1MB default), while our iterative * convert() handles it without issue. */ @Test fun `convert handles long sibling chains that would overflow a recursive implementation`() { val siblingCount = 5000 // Build a CommonMark tree directly: Document -> Paragraph("1") -> Paragraph("2") -> ... val doc = Document() for (i in 1..siblingCount) { val para = Paragraph() para.appendChild(Text("$i")) doc.appendChild(para) } val stackSize = 256L * 1024 // 256KB — smaller than Android's default ~1MB // First, prove this stack size is too small for equivalent-depth recursion. // A simple recursive chain of siblingCount depth will overflow. val recursionOverflowed = AtomicReference(false) val recursionThread = Thread(null, { try { countRecursively(siblingCount) } catch (_: StackOverflowError) { recursionOverflowed.set(true) } }, "recursion-test", stackSize) recursionThread.start() recursionThread.join() assertTrue( recursionOverflowed.get(), "Expected StackOverflowError for $siblingCount recursive calls on ${stackSize / 1024}KB stack" ) // Now prove our iterative convert() handles the same depth on the same stack size. val convertError = AtomicReference(null) val convertResult = AtomicReference(null) val convertThread = Thread(null, { try { convertResult.set(convert(doc)) } catch (e: Throwable) { convertError.set(e) } }, "convert-test", stackSize) convertThread.start() convertThread.join() val error = convertError.get() if (error != null) { fail("convert() should not throw on a long sibling chain, but threw: $error") } val root = convertResult.get() assertNotNull(root, "convert() should return a non-null root") assertEquals(AstDocument, root.type) // Verify the full sibling chain was converted var count = 0 var node = root.links.firstChild while (node != null) { count++ node = node.links.next } assertEquals(siblingCount, count) } } /** Simple recursive function that recurses [n] times to demonstrate stack overflow. */ private fun countRecursively(n: Int): Int { if (n <= 0) return 0 return 1 + countRecursively(n - 1) } ================================================ FILE: richtext-markdown/build.gradle.kts ================================================ plugins { id("richtext-kmp-library") } kotlin { android { namespace = "com.halilibo.richtext.markdown" } sourceSets { val commonMain by getting { dependencies { implementation(compose.runtime) implementation(compose.foundation) api(project(":richtext-ui")) } } val commonTest by getting val androidMain by getting { dependencies { implementation(Compose.coil) implementation(Compose.coilHttp) } } val jvmMain by getting { dependencies { implementation(compose.desktop.currentOs) implementation(Network.okHttp) } } val jvmTest by getting { dependencies { implementation(Kotlin.Test.jdk) } } } } ================================================ FILE: richtext-markdown/gradle.properties ================================================ POM_NAME=Compose Richtext Markdown POM_DESCRIPTION=A library for rendering markdown represented as an AST in Compose. ================================================ FILE: richtext-markdown/src/androidMain/AndroidManifest.xml ================================================ ================================================ FILE: richtext-markdown/src/androidMain/kotlin/com/halilibo/richtext/markdown/HtmlBlock.kt ================================================ package com.halilibo.richtext.markdown import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.fromHtml import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.string.Text import com.halilibo.richtext.ui.string.richTextString @Composable internal actual fun RichTextScope.HtmlBlock(content: String) { val richTextString = remember(content) { richTextString { withAnnotatedString { append(AnnotatedString.Companion.fromHtml(content)) } } } Text(richTextString) } ================================================ FILE: richtext-markdown/src/androidMain/kotlin/com/halilibo/richtext/markdown/MarkdownImage.kt ================================================ package com.halilibo.richtext.markdown import android.annotation.SuppressLint import android.util.Base64 import androidx.compose.foundation.Image import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.BoxWithConstraintsScope import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.isSpecified import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp import coil3.compose.rememberAsyncImagePainter import coil3.request.ImageRequest import coil3.request.crossfade import coil3.size.Size private val DEFAULT_IMAGE_SIZE = 64.dp /** * Implementation of MarkdownImage by using Coil library for Android. */ @Composable internal actual fun MarkdownImage( url: String, contentDescription: String?, modifier: Modifier, contentScale: ContentScale ) { val data = if (url.startsWith("data:image") && url.contains("base64")) { val base64ImageString = url.substringAfter("base64,") Base64.decode(base64ImageString, Base64.DEFAULT) } else { url } val painter = rememberAsyncImagePainter( ImageRequest.Builder(LocalContext.current) .data(data = data) .size(Size.ORIGINAL) .crossfade(true) .build() ) @SuppressLint("UnusedBoxWithConstraintsScope") BoxWithConstraints(modifier, contentAlignment = Alignment.Center) { val painterState by painter.state.collectAsState() val sizeModifier = renderInSize(painterState.painter?.intrinsicSize) Image( painter = painter, contentDescription = contentDescription, modifier = sizeModifier, contentScale = contentScale ) } } @Composable public fun BoxWithConstraintsScope.renderInSize( painterIntrinsicSize: androidx.compose.ui.geometry.Size?, ): Modifier { val density = LocalDensity.current val sizeModifier = if (painterIntrinsicSize != null && painterIntrinsicSize.isSpecified && painterIntrinsicSize.width != Float.POSITIVE_INFINITY && painterIntrinsicSize.height != Float.POSITIVE_INFINITY ) { val width = painterIntrinsicSize.width val height = painterIntrinsicSize.height val scale = if (width > constraints.maxWidth) { constraints.maxWidth.toFloat() / width } else { 1f } with(density) { Modifier.size( (width * scale).toDp(), (height * scale).toDp() ) } } else { // if size is not defined at all, Coil fails to render the image // here, we give a default size for images until they are loaded. Modifier.size(DEFAULT_IMAGE_SIZE) } return sizeModifier } ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/BasicMarkdown.kt ================================================ package com.halilibo.richtext.markdown import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics import com.halilibo.richtext.markdown.node.AstBlockNodeType import com.halilibo.richtext.markdown.node.AstBlockQuote import com.halilibo.richtext.markdown.node.AstDocument import com.halilibo.richtext.markdown.node.AstFencedCodeBlock import com.halilibo.richtext.markdown.node.AstHeading import com.halilibo.richtext.markdown.node.AstHtmlBlock import com.halilibo.richtext.markdown.node.AstIndentedCodeBlock import com.halilibo.richtext.markdown.node.AstInlineNodeType import com.halilibo.richtext.markdown.node.AstLinkReferenceDefinition import com.halilibo.richtext.markdown.node.AstListItem import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.markdown.node.AstOrderedList import com.halilibo.richtext.markdown.node.AstParagraph import com.halilibo.richtext.markdown.node.AstTableBody import com.halilibo.richtext.markdown.node.AstTableCell import com.halilibo.richtext.markdown.node.AstTableHeader import com.halilibo.richtext.markdown.node.AstTableRoot import com.halilibo.richtext.markdown.node.AstTableRow import com.halilibo.richtext.markdown.node.AstText import com.halilibo.richtext.markdown.node.AstThematicBreak import com.halilibo.richtext.markdown.node.AstUnorderedList import com.halilibo.richtext.ui.BlockQuote import com.halilibo.richtext.ui.CodeBlock import com.halilibo.richtext.ui.FormattedList import com.halilibo.richtext.ui.Heading import com.halilibo.richtext.ui.HorizontalRule import com.halilibo.richtext.ui.ListType.Ordered import com.halilibo.richtext.ui.ListType.Unordered import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.string.InlineContent import com.halilibo.richtext.ui.string.Text import com.halilibo.richtext.ui.string.richTextString /** * A composable that renders Markdown content pointed by [astNode] into this [RichTextScope]. * Designed to be a building block that should be wrapped with a specific parser. * * @param astNode Root node of Markdown tree. This can be obtained via a parser. * @param astBlockNodeComposer An interceptor to take control of composing any block type node's * rendering. Use it to render images, html text, tables with your own components. */ @Composable public fun RichTextScope.BasicMarkdown( astNode: AstNode, astBlockNodeComposer: AstBlockNodeComposer? = null ) { RecursiveRenderMarkdownAst(astNode, astBlockNodeComposer) } /** * An interface used to intercept block type AstNode rendering logic to inject custom composables * for nodes that satisfy [predicate]. */ public interface AstBlockNodeComposer { /** * Returns true if [Compose] function would handle this [astBlockNodeType]. */ public fun predicate(astBlockNodeType: AstBlockNodeType): Boolean /** * A composable that's responsible for composing the given [astNode] if its [AstNode.type] * returned true from [predicate]. This composable should also decide when and where to render * its children, then call [visitChildren] with a reference to which node's children to visit. * This is not an enforced behavior but unknowingly failing to do so can cause loss of * information during rendering. */ @Composable public fun RichTextScope.Compose( astNode: AstNode, visitChildren: @Composable (AstNode) -> Unit ) } /** * When parsed, markdown content or any other rich text can be represented as a tree. * The default markdown parser that is used in this project `common-markdown` also * utilizes the said approach. Although there are ways to iteratively traverse a tree, * it is more readable and compose-friendly to do it recursively. * * This function basically receives a node from the tree, root or any node, and then * recursively travels along the nodes while spitting out or wrapping composables around * the content. RichText API is highly compatible with this method. * * However, there are multiple assumptions to increase predictability. Despite the fact * that every [AstNode] can have another [AstNode] as a child, it should not be that * generic in Markdown content. For example, a Text node must not have any other children. * That's why this function does not have 100% coverage for all [AstNode] types. * * Heading, Paragraph are considered to be main text containers. Their content is regarded * as one block and children traversal happens separately. * * FormattedList, OrderedList are also content blocks. Their children are filtered before * being traversed. Only ListItems are accepted as valid children for these blocks. * * For now, only tables are rendered from CustomBlock or CustomNode. * * @param astNode Root node to start rendering. */ @Composable internal fun RichTextScope.RecursiveRenderMarkdownAst( astNode: AstNode?, astNodeComposer: AstBlockNodeComposer? ) { astNode ?: return if (astNodeComposer != null && astNode.type is AstBlockNodeType && astNodeComposer.predicate(astNode.type) ) { with(astNodeComposer) { Compose(astNode) { renderChildren(it, astNodeComposer) } } } else { with(DefaultAstNodeComposer) { Compose( astNode = astNode, visitChildren = { renderChildren(it, astNodeComposer) } ) } } } private val DefaultAstNodeComposer = object : AstBlockNodeComposer { override fun predicate(astBlockNodeType: AstBlockNodeType): Boolean = true @Composable override fun RichTextScope.Compose( astNode: AstNode, visitChildren: @Composable (AstNode) -> Unit ) { when (val astNodeType = astNode.type) { is AstDocument -> visitChildren(astNode) is AstBlockQuote -> { BlockQuote { visitChildren(astNode) } } is AstUnorderedList -> { FormattedList( listType = Unordered, items = astNode.filterChildrenType().toList() ) { astListItem -> // if this list item has no child, it should at least emit a single pixel layout. if (astListItem.links.firstChild == null) { BasicText("") } else { visitChildren(astListItem) } } } is AstOrderedList -> { FormattedList( listType = Ordered, items = astNode.childrenSequence().toList(), startIndex = astNodeType.startNumber - 1, ) { astListItem -> // if this list item has no child, it should at least emit a single pixel layout. if (astListItem.links.firstChild == null) { BasicText("") } else { visitChildren(astListItem) } } } is AstThematicBreak -> { HorizontalRule() } is AstHeading -> { Heading(level = astNodeType.level) { MarkdownRichText(astNode, Modifier.semantics { heading() }) } } is AstIndentedCodeBlock -> { CodeBlock(text = astNodeType.literal.trim()) } is AstFencedCodeBlock -> { CodeBlock(text = astNodeType.literal.trim()) } is AstHtmlBlock -> { Text(text = richTextString { appendInlineContent(content = InlineContent { HtmlBlock(astNodeType.literal) }) }) } is AstLinkReferenceDefinition -> { // TODO(halilozercan) /* no-op */ } is AstParagraph -> { MarkdownRichText(astNode) } is AstTableRoot -> { RenderTable(astNode) } // This should almost never happen. All the possible text // nodes must be under either Heading, Paragraph or CustomNode // In any case, we should include it here to prevent any // non-rendered text problems. is AstText -> { // TODO(halilozercan) use multiplatform compatible stderr logging println("Unexpected raw text while traversing the Abstract Syntax Tree.") Text(richTextString { append(astNodeType.literal) }) } is AstListItem -> { println("MarkdownRichText: Unexpected AstListItem while traversing the Abstract Syntax Tree.") } is AstInlineNodeType -> { // ignore println("MarkdownRichText: Unexpected AstInlineNodeType $astNodeType while traversing the Abstract Syntax Tree.") } AstTableBody, AstTableHeader, AstTableRow, is AstTableCell -> { println("MarkdownRichText: Unexpected Table node while traversing the Abstract Syntax Tree.") } }.let {} } } /** * Visit and render children from first to last. * * @param node Root ASTNode whose children will be visited. */ @Composable internal fun RichTextScope.renderChildren( node: AstNode?, astNodeComposer: AstBlockNodeComposer? ) { node?.childrenSequence()?.forEach { RecursiveRenderMarkdownAst(astNode = it, astNodeComposer = astNodeComposer) } } ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/HtmlBlock.kt ================================================ package com.halilibo.richtext.markdown import androidx.compose.runtime.Composable import com.halilibo.richtext.ui.RichTextScope /** * Android and JVM can have different WebView or HTML rendering implementations. * We are leaving HTML rendering to platform side. */ @Composable internal expect fun RichTextScope.HtmlBlock(content: String) ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/MarkdownImage.kt ================================================ package com.halilibo.richtext.markdown import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale //TODO(halilozercan): This should be provided from consumer side. /** * Image rendering is highly platform dependent. Coil is the desired * way to show images but it doesn't exist in desktop. */ @Composable internal expect fun MarkdownImage( url: String, contentDescription: String?, modifier: Modifier = Modifier, contentScale: ContentScale ) ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/MarkdownRichText.kt ================================================ package com.halilibo.richtext.markdown import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import com.halilibo.richtext.markdown.node.AstBlockQuote import com.halilibo.richtext.markdown.node.AstCode import com.halilibo.richtext.markdown.node.AstEmphasis import com.halilibo.richtext.markdown.node.AstFencedCodeBlock import com.halilibo.richtext.markdown.node.AstHardLineBreak import com.halilibo.richtext.markdown.node.AstHeading import com.halilibo.richtext.markdown.node.AstImage import com.halilibo.richtext.markdown.node.AstIndentedCodeBlock import com.halilibo.richtext.markdown.node.AstLink import com.halilibo.richtext.markdown.node.AstLinkReferenceDefinition import com.halilibo.richtext.markdown.node.AstListItem import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.markdown.node.AstParagraph import com.halilibo.richtext.markdown.node.AstSoftLineBreak import com.halilibo.richtext.markdown.node.AstStrikethrough import com.halilibo.richtext.markdown.node.AstStrongEmphasis import com.halilibo.richtext.markdown.node.AstText import com.halilibo.richtext.ui.BlockQuote import com.halilibo.richtext.ui.FormattedList import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.string.InlineContent import com.halilibo.richtext.ui.string.RichTextString import com.halilibo.richtext.ui.string.Text import com.halilibo.richtext.ui.string.withFormat /** * Only render the text content that exists below [astNode]. All the content blocks * like [AstBlockQuote] or [AstFencedCodeBlock] are ignored. This composable is * suited for [AstHeading] and [AstParagraph] since they are strictly text blocks. * * Some notes about commonmark and in general Markdown parsing. * * - Paragraph and Heading are the only RichTextString containers in base implementation. * - RichTextString is build by traversing the children of Heading or Paragraph. * - RichTextString can include; * - Emphasis * - StrongEmphasis * - Image * - Link * - Code * - Code blocks should not have any children. Their whole content must reside in * [AstIndentedCodeBlock.literal] or [AstFencedCodeBlock.literal]. * - Blocks like [BlockQuote], [FormattedList], [AstListItem] must have an [AstParagraph] * as a child to include any further RichText. * - CustomNode and CustomBlock can have their own scope, no idea about that. * * @param astNode Root node to accept as Text Content container. */ @Composable internal fun RichTextScope.MarkdownRichText(astNode: AstNode, modifier: Modifier = Modifier) { // Assume that only RichText nodes reside below this level. val richText = remember(astNode) { computeRichTextString(astNode) } Text(text = richText, modifier = modifier) } private fun computeRichTextString(astNode: AstNode): RichTextString { val richTextStringBuilder = RichTextString.Builder() // Modified pre-order traversal with pushFormat, popFormat support. var iteratorStack = listOf( AstNodeTraversalEntry( astNode = astNode, isVisited = false, formatIndex = null ) ) while (iteratorStack.isNotEmpty()) { val (currentNode, isVisited, formatIndex) = iteratorStack.first().copy() iteratorStack = iteratorStack.drop(1) if (!isVisited) { val newFormatIndex = when (val currentNodeType = currentNode.type) { is AstCode -> { richTextStringBuilder.withFormat(RichTextString.Format.Code) { append(currentNodeType.literal) } null } is AstEmphasis -> richTextStringBuilder.pushFormat(RichTextString.Format.Italic) is AstStrikethrough -> richTextStringBuilder.pushFormat( RichTextString.Format.Strikethrough ) is AstImage -> { richTextStringBuilder.appendInlineContent( content = InlineContent( initialSize = { IntSize(128.dp.roundToPx(), 128.dp.roundToPx()) } ) { MarkdownImage( url = currentNodeType.destination, contentDescription = currentNodeType.title, modifier = Modifier.fillMaxWidth(), contentScale = ContentScale.Inside ) } ) null } is AstLink -> richTextStringBuilder.pushFormat(RichTextString.Format.Link( destination = currentNodeType.destination )) is AstSoftLineBreak -> { richTextStringBuilder.append(" ") null } is AstHardLineBreak -> { richTextStringBuilder.append("\n") null } is AstStrongEmphasis -> richTextStringBuilder.pushFormat(RichTextString.Format.Bold) is AstText -> { richTextStringBuilder.append(currentNodeType.literal) null } is AstLinkReferenceDefinition -> richTextStringBuilder.pushFormat( RichTextString.Format.Link(destination = currentNodeType.destination)) else -> null } iteratorStack = iteratorStack.addFirst( AstNodeTraversalEntry( astNode = currentNode, isVisited = true, formatIndex = newFormatIndex ) ) // Do not visit children of terminals such as Text, Image, etc. if (!currentNode.isRichTextTerminal()) { currentNode.childrenSequence(reverse = true).forEach { iteratorStack = iteratorStack.addFirst( AstNodeTraversalEntry( astNode = it, isVisited = false, formatIndex = null ) ) } } } if (formatIndex != null) { richTextStringBuilder.pop(formatIndex) } } return richTextStringBuilder.toRichTextString() } private data class AstNodeTraversalEntry( val astNode: AstNode, val isVisited: Boolean, val formatIndex: Int? ) private inline fun List.addFirst(item: T): List { return listOf(item) + this } ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/RenderTable.kt ================================================ package com.halilibo.richtext.markdown import androidx.compose.runtime.Composable import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.markdown.node.AstTableBody import com.halilibo.richtext.markdown.node.AstTableCell import com.halilibo.richtext.markdown.node.AstTableHeader import com.halilibo.richtext.markdown.node.AstTableRow import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.Table @Composable internal fun RichTextScope.RenderTable(node: AstNode) { Table( headerRow = { node.filterChildrenType() .firstOrNull() ?.filterChildrenType() ?.firstOrNull() ?.filterChildrenType() ?.forEach { tableCell -> cell { MarkdownRichText(tableCell) } } } ) { node.filterChildrenType() .firstOrNull() ?.filterChildrenType() ?.forEach { tableRow -> row { tableRow.filterChildrenType() .forEach { tableCell -> cell { MarkdownRichText(tableCell) } } } } } } ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/TraverseUtils.kt ================================================ package com.halilibo.richtext.markdown import com.halilibo.richtext.markdown.node.AstCode import com.halilibo.richtext.markdown.node.AstHardLineBreak import com.halilibo.richtext.markdown.node.AstImage import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.markdown.node.AstNodeType import com.halilibo.richtext.markdown.node.AstSoftLineBreak import com.halilibo.richtext.markdown.node.AstText internal fun AstNode.childrenSequence( reverse: Boolean = false ): Sequence { return if (!reverse) { generateSequence(this.links.firstChild) { it.links.next } } else { generateSequence(this.links.lastChild) { it.links.previous } } } /** * Markdown rendering is susceptible to have assumptions. Hence, some rendering rules * may force restrictions on children. So, valid children nodes should be selected * before traversing. This function returns a LinkedList of children which conforms to * [filter] function. * * @param filter A lambda to select valid children. */ internal fun AstNode.filterChildren( reverse: Boolean = false, filter: (AstNode) -> Boolean ): Sequence { return childrenSequence(reverse).filter(filter) } internal inline fun AstNode.filterChildrenType(): Sequence { return filterChildren { it.type is T } } /** * These ASTNode types should never have any children. If any exists, ignore them. */ internal fun AstNode.isRichTextTerminal(): Boolean { return type is AstText || type is AstCode || type is AstImage || type is AstSoftLineBreak || type is AstHardLineBreak } ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/node/AstNode.kt ================================================ package com.halilibo.richtext.markdown.node /** * Generic AstNode implementation that can define any node in Abstract Syntax Tree. * * @param type A sealed class which is categorized into block and inline nodes. * @param links Pointers to parent, sibling, child nodes. */ public class AstNode( public val type: AstNodeType, public val links: AstNodeLinks ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is AstNode) return false if (type != other.type) return false if (links != other.links) return false return true } override fun hashCode(): Int { var result = type.hashCode() result = 31 * result + links.hashCode() return result } } ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/node/AstNodeLinks.kt ================================================ package com.halilibo.richtext.markdown.node import androidx.compose.runtime.Immutable /** * All the pointers that can exist for a node in an AST. * * Links are mutable to make it possible to instantiate a Node which can then reconfigure its * children and siblings. Please do not modify the links after an ASTNode is created and the scope * is finished. */ @Immutable public class AstNodeLinks( public var parent: AstNode? = null, public var firstChild: AstNode? = null, public var lastChild: AstNode? = null, public var previous: AstNode? = null, public var next: AstNode? = null ) { override fun equals(other: Any?): Boolean { if (other !is AstNodeLinks) return false return parent === other.parent && firstChild === other.firstChild && lastChild === other.lastChild && previous === other.previous && next === other.next } /** * Stop infinite loop and only calculate towards bottom-right direction */ override fun hashCode(): Int { return (firstChild ?: 0).hashCode() * 11 + (next ?: 0).hashCode() * 7 } } ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/node/AstNodeType.kt ================================================ package com.halilibo.richtext.markdown.node import androidx.compose.runtime.Immutable import com.halilibo.richtext.ui.string.RichTextString /** * Refer to https://spec.commonmark.org/0.30/#precedence * * Commonmark specification defines 3 different types of AST nodes; * * - Container Block * - Leaf Block * - Inline Content * * Container blocks are the most generic nodes. They define a structure for their children but * do not impose any major restrictions, meaning that container blocks can contain any * type of child node. * * Leaf blocks are self-explanatory, they should not have any children. All the necessary content * to render a leaf block should already exist in its payload * * Inline Content is analogous to [RichTextString] and its styles. Most of the inline content * nodes are about styling(bold, italic, strikethrough, code). The rest contains links, images, * html content, and of course raw text. */ public sealed class AstNodeType //region AstBlockNodeType public sealed class AstBlockNodeType: AstNodeType() //region AstContainerBlockNodeType /** * Defines a subtype of Block Node that can contain other nodes. */ public sealed class AstContainerBlockNodeType: AstBlockNodeType() /** * Usually defines the root of a markdown document. */ @Immutable public object AstDocument : AstContainerBlockNodeType() /** * A block quote container that will indent its contents relative to its own indentation. */ @Immutable public object AstBlockQuote : AstContainerBlockNodeType() /** * Ordered or Unordered list item. */ @Immutable public object AstListItem : AstContainerBlockNodeType() /** * A list type that marks its items with bullets to signify a lack of order. */ @Immutable public data class AstUnorderedList( val bulletMarker: Char ) : AstContainerBlockNodeType() /** * A list type that uses numbers to mark its items. */ @Immutable public data class AstOrderedList( val startNumber: Int, val delimiter: Char ) : AstContainerBlockNodeType() //endregion //region AstLeafBlockNodeType /** * Defines a subtype of Block Node that can only contain plain text and full-length annotations. */ public sealed class AstLeafBlockNodeType: AstBlockNodeType() @Immutable public object AstThematicBreak : AstLeafBlockNodeType() @Immutable public data class AstHeading( val level: Int ) : AstLeafBlockNodeType() @Immutable public data class AstIndentedCodeBlock( val literal: String ) : AstLeafBlockNodeType() @Immutable public data class AstFencedCodeBlock( val fenceChar: Char, val fenceLength: Int, val fenceIndent: Int, val info: String, val literal: String ) : AstLeafBlockNodeType() @Immutable public data class AstHtmlBlock( val literal: String ) : AstLeafBlockNodeType() @Immutable public data class AstLinkReferenceDefinition( val label: String, val destination: String, val title: String ) : AstLeafBlockNodeType() @Immutable public object AstParagraph : AstLeafBlockNodeType() //endregion //endregion //region AstInlineNodeType /** * Defines a node type that can only apply to inline content. */ public sealed class AstInlineNodeType: AstNodeType() @Immutable public data class AstCode( val literal: String ) : AstInlineNodeType() @Immutable public data class AstEmphasis( private val delimiter: String ) : AstInlineNodeType() @Immutable public data class AstStrongEmphasis( private val delimiter: String ) : AstInlineNodeType() @Immutable public data class AstStrikethrough( val delimiter: String ) : AstInlineNodeType() @Immutable public data class AstLink( val destination: String, val title: String ) : AstInlineNodeType() @Immutable public data class AstImage( val title: String, val destination: String ) : AstInlineNodeType() @Immutable public data class AstHtmlInline( val literal: String ) : AstInlineNodeType() @Immutable public object AstHardLineBreak : AstInlineNodeType() @Immutable public object AstSoftLineBreak : AstInlineNodeType() @Immutable public data class AstText( val literal: String ) : AstInlineNodeType() //endregion ================================================ FILE: richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/node/AstTable.kt ================================================ package com.halilibo.richtext.markdown.node import androidx.compose.runtime.Immutable @Immutable public object AstTableRoot: AstContainerBlockNodeType() @Immutable public object AstTableBody: AstContainerBlockNodeType() @Immutable public object AstTableHeader: AstContainerBlockNodeType() @Immutable public object AstTableRow: AstContainerBlockNodeType() @Immutable public data class AstTableCell( val header: Boolean, val alignment: AstTableCellAlignment ) : AstContainerBlockNodeType() public enum class AstTableCellAlignment { LEFT, CENTER, RIGHT } ================================================ FILE: richtext-markdown/src/jvmMain/kotlin/com/halilibo/richtext/markdown/HtmlBlock.kt ================================================ package com.halilibo.richtext.markdown import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import com.halilibo.richtext.ui.RichTextScope @Composable internal actual fun RichTextScope.HtmlBlock(content: String) { DisposableEffect(Unit) { println("Html blocks are rendered literally in Compose Desktop!") onDispose { } } BasicText(content) } ================================================ FILE: richtext-markdown/src/jvmMain/kotlin/com/halilibo/richtext/markdown/RemoteImage.kt ================================================ package com.halilibo.richtext.markdown import androidx.compose.foundation.Image import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.toComposeImageBitmap import androidx.compose.ui.layout.ContentScale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.skia.Image.Companion.makeFromEncoded import java.awt.image.BufferedImage import java.io.ByteArrayOutputStream import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import java.util.Base64 import javax.imageio.ImageIO @Composable internal actual fun MarkdownImage( url: String, contentDescription: String?, modifier: Modifier, contentScale: ContentScale ) { val image by produceState(null, url) { if (url.startsWith("data:image") && url.contains("base64")) { val base64ImageString = url.substringAfter("base64,") value = makeFromEncoded(Base64.getDecoder().decode(base64ImageString)).toComposeImageBitmap() } else { loadFullImage(url)?.let { value = makeFromEncoded(toByteArray(it)).toComposeImageBitmap() } } } if (image != null) { Image( bitmap = image!!, contentDescription = contentDescription, modifier = modifier, contentScale = contentScale ) } } private fun toByteArray(bitmap: BufferedImage): ByteArray { val baos = ByteArrayOutputStream() ImageIO.write(bitmap, "png", baos) return baos.toByteArray() } private suspend fun loadFullImage(source: String): BufferedImage? = withContext(Dispatchers.IO) { runCatching { val url = URL(source) val connection: HttpURLConnection = url.openConnection() as HttpURLConnection connection.connectTimeout = 5000 connection.connect() val input: InputStream = connection.inputStream val bitmap: BufferedImage? = ImageIO.read(input) bitmap }.getOrNull() } ================================================ FILE: richtext-ui/build.gradle.kts ================================================ plugins { id("richtext-kmp-library") id("org.jetbrains.dokka") } kotlin { android { namespace = "com.halilibo.richtext.ui" } sourceSets { val commonMain by getting { dependencies { implementation(compose.runtime) implementation(compose.foundation) } } val commonTest by getting val jvmAndroidMain by creating { dependsOn(commonMain) } val androidMain by getting { dependsOn(jvmAndroidMain) } val jvmMain by getting { dependsOn(jvmAndroidMain) } } } ================================================ FILE: richtext-ui/gradle.properties ================================================ POM_NAME=Compose Richtext UI POM_DESCRIPTION=A library for rendering high-level text formatting in Compose. ================================================ FILE: richtext-ui/src/androidMain/AndroidManifest.xml ================================================ ================================================ FILE: richtext-ui/src/androidMain/kotlin/com/halilibo/richtext/ui/CodeBlock.android.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.rememberScrollState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable internal actual fun RichTextScope.CodeBlockLayout( wordWrap: Boolean, children: @Composable RichTextScope.(Modifier) -> Unit ) { if (!wordWrap) { val scrollState = rememberScrollState() children(Modifier.horizontalScroll(scrollState)) } else { children(Modifier) } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/BasicRichText.kt ================================================ @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry") package com.halilibo.richtext.ui import androidx.compose.foundation.layout.Arrangement.spacedBy import androidx.compose.foundation.layout.Column import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity /** * Draws some rich text. Entry point to the compose-richtext library. */ @Composable public fun BasicRichText( modifier: Modifier = Modifier, style: RichTextStyle? = null, children: @Composable RichTextScope.() -> Unit ) { with(RichTextScope) { RestartListLevel { WithStyle(style) { val resolvedStyle = currentRichTextStyle.resolveDefaults() val blockSpacing = with(LocalDensity.current) { resolvedStyle.paragraphSpacing!!.toDp() } Column(modifier = modifier, verticalArrangement = spacedBy(blockSpacing)) { children() } } } } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/BlockQuote.kt ================================================ @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry") package com.halilibo.richtext.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Layout import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.offset import androidx.compose.ui.unit.sp import com.halilibo.richtext.ui.BlockQuoteGutter.BarGutter internal val DefaultBlockQuoteGutter = BarGutter() /** * A composable function that draws the gutter beside a [BlockQuote]. * * [BarGutter] is provided as the reasonable default of a simple vertical line. */ public interface BlockQuoteGutter { @Composable public fun RichTextScope.drawGutter() @Immutable public data class BarGutter( val startMargin: TextUnit = 6.sp, val barWidth: TextUnit = 3.sp, val endMargin: TextUnit = 6.sp, val color: (contentColor: Color) -> Color = { it.copy(alpha = .25f) } ) : BlockQuoteGutter { @Composable override fun RichTextScope.drawGutter() { with(LocalDensity.current) { val color = color(currentContentColor) val modifier = remember(startMargin, endMargin, barWidth, color) { // Padding must come before width. Modifier .padding( start = startMargin.toDp(), end = endMargin.toDp() ) .width(barWidth.toDp()) .background(color, RoundedCornerShape(50)) } Box(modifier) } } } } /** * Draws a block quote, with a [BlockQuoteGutter] drawn beside the children on the start side. */ @Composable public fun RichTextScope.BlockQuote(children: @Composable RichTextScope.() -> Unit) { val gutter = currentRichTextStyle.resolveDefaults().blockQuoteGutter!! val spacing = with(LocalDensity.current) { currentRichTextStyle.resolveDefaults().paragraphSpacing!!.toDp() / 2 } Layout(content = { with(gutter) { drawGutter() } BasicRichText( modifier = Modifier.padding(top = spacing, bottom = spacing), children = children ) }) { measurables, constraints -> val gutterMeasurable = measurables[0] val contentsMeasurable = measurables[1] // First get the width of the gutter, so we can measure the contents with // the smaller width if bounded. val gutterWidth = gutterMeasurable.minIntrinsicWidth(constraints.maxHeight) // Measure the contents with the confined width. // This must be done before measuring the gutter so that the gutter gets // the correct height. val contentsConstraints = constraints.offset(horizontal = -gutterWidth) val contentsPlaceable = contentsMeasurable.measure(contentsConstraints) val layoutWidth = contentsPlaceable.width + gutterWidth val layoutHeight = contentsPlaceable.height // Measure the gutter to fit in its min intrinsic width and exactly the // height of the contents. val gutterConstraints = constraints.copy( maxWidth = gutterWidth, minHeight = layoutHeight, maxHeight = layoutHeight ) val gutterPlaceable = gutterMeasurable.measure(gutterConstraints) layout(layoutWidth, layoutHeight) { gutterPlaceable.place(IntOffset.Zero) contentsPlaceable.place(gutterWidth, 0) } } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/CodeBlock.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp /** * Defines how [CodeBlock]s are rendered. * * @param textStyle The [TextStyle] to use for the block. * @param modifier The [Modifier] to use for the block. * @param padding The amount of space between the edge of the text and the edge of the background. * @param wordWrap Whether a code block breaks the lines or scrolls horizontally. */ @Immutable public data class CodeBlockStyle( val textStyle: TextStyle? = null, val modifier: Modifier? = null, val padding: TextUnit? = null, val wordWrap: Boolean? = null ) { public companion object { public val Default: CodeBlockStyle = CodeBlockStyle() } } private val DefaultCodeBlockTextStyle = TextStyle( fontFamily = FontFamily.Monospace ) internal val DefaultCodeBlockBackgroundColor: Color = Color.LightGray.copy(alpha = .5f) private val DefaultCodeBlockModifier: Modifier = Modifier.background(color = DefaultCodeBlockBackgroundColor) private val DefaultCodeBlockPadding: TextUnit = 16.sp private const val DefaultCodeWordWrap: Boolean = true internal fun CodeBlockStyle.resolveDefaults() = CodeBlockStyle( textStyle = textStyle ?: DefaultCodeBlockTextStyle, modifier = modifier ?: DefaultCodeBlockModifier, padding = padding ?: DefaultCodeBlockPadding, wordWrap = wordWrap ?: DefaultCodeWordWrap ) /** * A specially-formatted block of text that typically uses a monospace font with a tinted * background. * * @param wordWrap Overrides word wrap preference coming from [CodeBlockStyle] */ @Composable public fun RichTextScope.CodeBlock( text: String, wordWrap: Boolean? = null ) { CodeBlock(wordWrap = wordWrap) { Text(text) } } /** * A specially-formatted block of text that typically uses a monospace font with a tinted * background. * * @param wordWrap Overrides word wrap preference coming from [CodeBlockStyle] */ @Composable public fun RichTextScope.CodeBlock( wordWrap: Boolean? = null, children: @Composable RichTextScope.() -> Unit ) { val codeBlockStyle = currentRichTextStyle.resolveDefaults().codeBlockStyle!! val textStyle = currentTextStyle.merge(codeBlockStyle.textStyle) val modifier = codeBlockStyle.modifier!! val blockPadding = with(LocalDensity.current) { codeBlockStyle.padding!!.toDp() } val resolvedWordWrap = wordWrap ?: codeBlockStyle.wordWrap!! CodeBlockLayout( wordWrap = resolvedWordWrap ) { layoutModifier -> Box( modifier = layoutModifier .then(modifier) .padding(blockPadding) ) { textStyleBackProvider(textStyle) { children() } } } } /** * Desktop composable adds an optional horizontal scrollbar. */ @Composable internal expect fun RichTextScope.CodeBlockLayout( wordWrap: Boolean, children: @Composable RichTextScope.(Modifier) -> Unit ) ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/FormattedList.kt ================================================ @file:Suppress("ComposableNaming") package com.halilibo.richtext.ui import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.selection.DisableSelection import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.paint import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.Layout import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp import com.halilibo.richtext.ui.ListType.Ordered import com.halilibo.richtext.ui.ListType.Unordered import kotlin.math.max public enum class ListType { /** * An ordered (numbered) list. */ Ordered, /** * An unordered (bullet) list. */ Unordered } /** * Defines how to draw list markers for [FormattedList]s that are [Ordered]. * * These are typically some sort of ordinal text. */ public interface OrderedMarkers { @Composable public fun drawMarker( level: Int, index: Int ) public companion object { /** * Creates an [OrderedMarkers] from an arbitrary composable given the indentation level and * the index. */ public operator fun invoke( drawMarker: @Composable (level: Int, index: Int) -> Unit ): OrderedMarkers = object : OrderedMarkers { @Composable override fun drawMarker( level: Int, index: Int ) { drawMarker(level, index) } } } } /** * Creates an [OrderedMarkers] that will cycle through the values in [markers] for each * indentation level given the index. */ public fun RichTextScope.textOrderedMarkers( vararg markers: (index: Int) -> String ): OrderedMarkers = OrderedMarkers { level, index -> Text(markers[level % markers.size](index)) } /** * Defines how to draw list markers for [FormattedList]s that are [Unordered]. * * These are typically some sort of bullet point. */ public interface UnorderedMarkers { @Composable public fun drawMarker(level: Int) public companion object { /** * Creates an [UnorderedMarkers] from an arbitrary composable given the indentation level. */ public operator fun invoke(drawMarker: @Composable (level: Int) -> Unit): UnorderedMarkers = object : UnorderedMarkers { @Composable override fun drawMarker(level: Int) = drawMarker(level) } } } /** * Creates an [UnorderedMarkers] that will cycle through the values in [markers] for each * indentation level. */ public fun RichTextScope.textUnorderedMarkers( vararg markers: String ): UnorderedMarkers = UnorderedMarkers { Text(markers[it % markers.size]) } /** * Creates an [UnorderedMarkers] that will cycle through the values in [painters] for each * indentation level. */ public fun painterUnorderedMarkers(vararg painters: Painter): UnorderedMarkers = UnorderedMarkers { Box(Modifier.paint(painters[it % painters.size])) } /** * Defines how [FormattedList]s should look. * * @param markerIndent The padding before each marker. * @param contentsIndent The padding after each marker. */ @Immutable public data class ListStyle( val markerIndent: TextUnit? = null, val contentsIndent: TextUnit? = null, val itemSpacing: TextUnit? = null, val orderedMarkers: (RichTextScope.() -> OrderedMarkers)? = null, val unorderedMarkers: (RichTextScope.() -> UnorderedMarkers)? = null ) { public companion object { public val Default: ListStyle = ListStyle() } } private val DefaultMarkerIndent = 8.sp private val DefaultContentsIndent = 4.sp private val DefaultItemSpacing = 4.sp private val DefaultOrderedMarkers: RichTextScope.() -> OrderedMarkers = { textOrderedMarkers( { "${it + 1}." }, { ('a'..'z').drop(it % 26) .first() + "." }, { "${it + 1})" }, { ('a'..'z').drop(it % 26) .first() + ")" } ) } private val DefaultUnorderedMarkers: RichTextScope.() -> UnorderedMarkers = { textUnorderedMarkers("•", "◦", "▸", "▹") } internal fun ListStyle.resolveDefaults(): ListStyle = ListStyle( markerIndent = markerIndent ?: DefaultMarkerIndent, contentsIndent = contentsIndent ?: DefaultContentsIndent, itemSpacing = itemSpacing ?: DefaultItemSpacing, orderedMarkers = orderedMarkers ?: DefaultOrderedMarkers, unorderedMarkers = unorderedMarkers ?: DefaultUnorderedMarkers ) private val LocalListLevel = compositionLocalOf { 0 } /** * Composes [children] with their [LocalListLevel] reset back to 0. */ @Composable internal fun RestartListLevel(children: @Composable () -> Unit) { CompositionLocalProvider(LocalListLevel provides 0) { children() } } /** * Creates a formatted list such as a bullet list or numbered list. */ // inline is required for https://github.com/halilozercan/compose-richtext/issues/7 @Suppress("NOTHING_TO_INLINE") @Composable public inline fun RichTextScope.FormattedList( listType: ListType, vararg children: @Composable RichTextScope.() -> Unit ): Unit = FormattedList(listType, children.asList(), 0) { it() } /** * Creates a formatted list such as a bullet list or numbered list. */ @Composable public fun RichTextScope.FormattedList( listType: ListType, items: List, startIndex: Int = 0, drawItem: @Composable RichTextScope.(T) -> Unit ) { val listStyle = currentRichTextStyle.resolveDefaults().listStyle!! val density = LocalDensity.current val markerIndent = with(density) { listStyle.markerIndent!!.toDp() } val contentsIndent = with(density) { listStyle.contentsIndent!!.toDp() } val itemSpacing = with(density) { listStyle.itemSpacing!!.toDp() } val currentLevel = LocalListLevel.current PrefixListLayout( count = items.size, itemSpacing = itemSpacing, prefixPadding = PaddingValues(start = markerIndent, end = contentsIndent), prefixForIndex = { index -> when (listType) { Ordered -> listStyle.orderedMarkers!!().drawMarker(currentLevel, startIndex + index) Unordered -> listStyle.unorderedMarkers!!().drawMarker(currentLevel) } }, itemForIndex = { index -> BasicRichText( style = currentRichTextStyle.copy(paragraphSpacing = listStyle.itemSpacing), ) { CompositionLocalProvider(LocalListLevel provides currentLevel + 1) { drawItem(items[index]) } } } ) } @Composable private fun PrefixListLayout( count: Int, itemSpacing: Dp, prefixPadding: PaddingValues, prefixForIndex: @Composable (index: Int) -> Unit, itemForIndex: @Composable (index: Int) -> Unit ) { Layout(content = { // List markers aren't selectable. DisableSelection { // Draw the markers first. for (i in 0 until count) { // TODO Use the padding in the calculation directly instead of wrapping. Box(Modifier.padding(prefixPadding)) { prefixForIndex(i) } } } // Then draw the items. for (i in 0 until count) { itemForIndex(i) } }) { measurables, constraints -> check(measurables.size == count * 2) val prefixMeasureables = measurables.asSequence() .take(count) val itemMeasurables = measurables.asSequence() .drop(count) // Measure the prefixes first. val prefixPlaceables = prefixMeasureables.map { marker -> marker.measure(constraints) } .toList() val widestPrefix = prefixPlaceables.maxByOrNull { it.width }!! // Then measure the items, offset to the right to allow space for the prefixes and gap. val itemConstraints = constraints.copy( maxWidth = (constraints.maxWidth - widestPrefix.width).coerceAtLeast(0) ) val itemPlaceables = itemMeasurables.map { item -> item.measure(itemConstraints) } .toList() val widestItem = itemPlaceables.maxByOrNull { it.width }!! val listWidth = widestPrefix.width + widestItem.width val itemsHeight = itemPlaceables.sumOf { it.height } + (itemPlaceables.size - 1) * itemSpacing.roundToPx() val prefixesHeight = prefixPlaceables.sumOf { it.height } + (prefixPlaceables.size - 1) * itemSpacing.roundToPx() val listHeight = maxOf(itemsHeight, prefixesHeight) layout(listWidth, listHeight) { var y = 0 // Flow the rows vertically, much like Column. for (i in 0 until count) { val prefix = prefixPlaceables[i] val item = itemPlaceables[i] val rowHeight = max(prefix.height, item.height) + itemSpacing.roundToPx() val size = IntSize( width = widestPrefix.width - prefix.width, height = rowHeight - prefix.height ) val prefixOffset = Alignment.TopEnd.align( size = size, space = size, layoutDirection = layoutDirection ) prefix.placeRelative(prefixOffset.x, y + prefixOffset.y) item.placeRelative(widestPrefix.width, y) y += rowHeight } } } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/Heading.kt ================================================ @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry") package com.halilibo.richtext.ui import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontStyle.Companion.Italic import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.resolveDefaults import androidx.compose.ui.unit.sp /** * Function that computes the [TextStyle] for the given header level, given the current [TextStyle] * for this point in the composition. Note that the [TextStyle] passed into this function will be * fully resolved. The returned style will then be _merged_ with the passed-in text style, so any * unspecified properties will be inherited. */ // TODO factor a generic "block style" thing out, use for code block, quote block, and this, to // also allow controlling top/bottom space. public typealias HeadingStyle = (level: Int, textStyle: TextStyle) -> TextStyle internal val DefaultHeadingStyle: HeadingStyle = { level, textStyle -> when (level) { 0 -> TextStyle( fontSize = 36.sp, fontWeight = FontWeight.Bold ) 1 -> TextStyle( fontSize = 26.sp, fontWeight = FontWeight.Bold ) 2 -> TextStyle( fontSize = 22.sp, fontWeight = FontWeight.Bold, color = textStyle.color.copy(alpha = .7F) ) 3 -> TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Bold, fontStyle = Italic ) 4 -> TextStyle( fontSize = 18.sp, fontWeight = FontWeight.Bold, color = textStyle.color.copy(alpha = .7F) ) 5 -> TextStyle( fontWeight = FontWeight.Bold, color = textStyle.color.copy(alpha = .5f) ) else -> textStyle } } /** * A section heading. * * @param level The non-negative rank of the header, with 0 being the most important. */ @Composable public fun RichTextScope.Heading( level: Int, text: String ) { Heading(level) { Text(text, Modifier.semantics { heading() }) } } /** * A section heading. * * @param level The non-negative rank of the header, with 0 being the most important. */ @Composable public fun RichTextScope.Heading( level: Int, children: @Composable RichTextScope.() -> Unit ) { require(level >= 0) { "Level must be at least 0" } val incomingStyle = currentTextStyle.let { it.copy(color = it.color.takeOrElse { currentContentColor }) } val currentTextStyle = resolveDefaults(incomingStyle, LocalLayoutDirection.current) val headingStyleFunction = currentRichTextStyle.resolveDefaults().headingStyle!! val headingTextStyle = headingStyleFunction(level, currentTextStyle) val mergedTextStyle = currentTextStyle.merge(headingTextStyle) textStyleBackProvider(mergedTextStyle) { children() } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/HorizontalRule.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp /** * A simple horizontal line drawn with the current content color. */ @Composable public fun RichTextScope.HorizontalRule() { val color = currentContentColor.copy(alpha = .2f) val spacing = with(LocalDensity.current) { currentRichTextStyle.resolveDefaults().paragraphSpacing!!.toDp() } Box( Modifier .padding(top = spacing, bottom = spacing) .fillMaxWidth() .height(1.dp) .background(color) ) } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/InfoPanel.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import com.halilibo.richtext.ui.InfoPanelType.Danger import com.halilibo.richtext.ui.InfoPanelType.Primary import com.halilibo.richtext.ui.InfoPanelType.Secondary import com.halilibo.richtext.ui.InfoPanelType.Success import com.halilibo.richtext.ui.InfoPanelType.Warning @Stable public data class InfoPanelStyle( val contentPadding: PaddingValues? = null, val background: @Composable ((InfoPanelType) -> Modifier)? = null, val textStyle: @Composable ((InfoPanelType) -> TextStyle)? = null ) { public companion object { public val Default: InfoPanelStyle = InfoPanelStyle() } } public enum class InfoPanelType { Primary, Secondary, Success, Danger, Warning } private val DefaultContentPadding = PaddingValues(8.dp) private val DefaultInfoPanelBackground = @Composable { infoPanelType: InfoPanelType -> remember { val (borderColor, backgroundColor) = when (infoPanelType) { Primary -> Color(0xffb8daff) to Color(0xffcce5ff) Secondary -> Color(0xffd6d8db) to Color(0xffe2e3e5) Success -> Color(0xffc3e6cb) to Color(0xffd4edda) Danger -> Color(0xfff5c6cb) to Color(0xfff8d7da) Warning -> Color(0xffffeeba) to Color(0xfffff3cd) } Modifier .border(1.dp, borderColor, RoundedCornerShape(4.dp)) .background(backgroundColor, RoundedCornerShape(4.dp)) } } private val DefaultInfoPanelTextStyle = @Composable { infoPanelType: InfoPanelType -> remember { val color = when(infoPanelType) { Primary -> Color(0xff004085) Secondary -> Color(0xff383d41) Success -> Color(0xff155724) Danger -> Color(0xff721c24) Warning -> Color(0xff856404) } TextStyle(color = color) } } internal fun InfoPanelStyle.resolveDefaults() = InfoPanelStyle( contentPadding = contentPadding ?: DefaultContentPadding, background = background ?: DefaultInfoPanelBackground, textStyle = textStyle ?: DefaultInfoPanelTextStyle ) /** * A panel to show content similar to Bootstrap alerts, categorized as [InfoPanelType]. * This composable is a shortcut to show only [text] in an info panel. */ @Composable public fun RichTextScope.InfoPanel( infoPanelType: InfoPanelType, text: String ) { InfoPanel(infoPanelType) { Text(text) } } /** * A panel to show content similar to Bootstrap alerts, categorized as [InfoPanelType]. */ @Composable public fun RichTextScope.InfoPanel( infoPanelType: InfoPanelType, content: @Composable () -> Unit ) { val infoPanelStyle = currentRichTextStyle.resolveDefaults().infoPanelStyle!! val backgroundModifier = infoPanelStyle.background!!.invoke(infoPanelType) val infoPanelTextStyle = infoPanelStyle.textStyle!!.invoke(infoPanelType) val resolvedTextStyle = currentTextStyle.merge(infoPanelTextStyle) textStyleBackProvider(resolvedTextStyle) { Box(modifier = backgroundModifier.padding(infoPanelStyle.contentPadding!!)) { content() } } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextLocals.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.text.InlineTextContent import androidx.compose.runtime.Composable import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextOverflow import com.halilibo.richtext.ui.util.detectTapGesturesIf /** * Carries the text style in Composition tree. [Heading], [CodeBlock], * [BlockQuote] are designed to change the ongoing [TextStyle] in composition, * so that their children can use the modified text style implicitly. * * LocalTextStyle also exists in Material package but this one is internal * to RichText. */ internal val LocalInternalTextStyle = compositionLocalOf { TextStyle.Default } /** * Carries the content color in Composition tree. Default TextStyle * does not have text color specified. It defaults to [Color.Black] * in the "resolve chain" but Dark Mode is an exception. To also resolve * for Dark Mode, content color should be passed to [RichTextScope]. */ internal val LocalInternalContentColor = compositionLocalOf { Color.Black } /** * The current [TextStyle]. */ internal val RichTextScope.currentTextStyle: TextStyle @Composable get() = textStyleProvider() /** * The current content [Color]. */ internal val RichTextScope.currentContentColor: Color @Composable get() = contentColorProvider() /** * Intended for preview composables. */ @Composable internal fun RichTextScope.Text( text: String, modifier: Modifier = Modifier, onTextLayout: (TextLayoutResult) -> Unit = {}, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE ) { val textColor = currentTextStyle.color.takeOrElse { currentContentColor } val style = currentTextStyle.copy(color = textColor) BasicText( text = text, modifier = modifier, style = style, onTextLayout = onTextLayout, overflow = overflow, softWrap = softWrap, maxLines = maxLines ) } @Composable internal fun RichTextScope.Text( text: AnnotatedString, modifier: Modifier = Modifier, onTextLayout: (TextLayoutResult) -> Unit = {}, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, inlineContent: Map = mapOf(), ) { val textColor = currentTextStyle.color.takeOrElse { currentContentColor } val style = currentTextStyle.copy(color = textColor) BasicText( text = text, modifier = modifier, style = style, onTextLayout = onTextLayout, overflow = overflow, softWrap = softWrap, maxLines = maxLines, inlineContent = inlineContent ) } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextScope.kt ================================================ @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry") package com.halilibo.richtext.ui import androidx.compose.runtime.CompositionLocal import androidx.compose.runtime.Immutable import androidx.compose.runtime.State /** * Scope object for composables that can draw rich text. * * RichTextScope facilitates a context for RichText elements. It does not * behave like a [State] or a [CompositionLocal]. Starting from [BasicRichText], * this scope carries information that should not be passed down as a state. */ @Immutable public object RichTextScope ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextStyle.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp import com.halilibo.richtext.ui.string.RichTextStringStyle internal val LocalRichTextStyle = compositionLocalOf { RichTextStyle.Default } internal val DefaultParagraphSpacing: TextUnit = 8.sp /** * Configures all formatting attributes for drawing rich text. * * @param paragraphSpacing The amount of space in between blocks of text. * @param headingStyle The [HeadingStyle] that defines how [Heading]s are drawn. * @param listStyle The [ListStyle] used to format [FormattedList]s. * @param blockQuoteGutter The [BlockQuoteGutter] used to draw [BlockQuote]s. * @param codeBlockStyle The [CodeBlockStyle] that defines how [CodeBlock]s are drawn. * @param tableStyle The [TableStyle] used to render [Table]s. * @param stringStyle The [RichTextStringStyle] used to render * [RichTextString][com.halilibo.richtext.ui.string.RichTextString]s */ @Immutable public data class RichTextStyle( val paragraphSpacing: TextUnit? = null, val headingStyle: HeadingStyle? = null, val listStyle: ListStyle? = null, val blockQuoteGutter: BlockQuoteGutter? = null, val codeBlockStyle: CodeBlockStyle? = null, val tableStyle: TableStyle? = null, val infoPanelStyle: InfoPanelStyle? = null, val stringStyle: RichTextStringStyle? = null ) { public companion object { public val Default: RichTextStyle = RichTextStyle() } } public fun RichTextStyle.merge(otherStyle: RichTextStyle?): RichTextStyle = RichTextStyle( paragraphSpacing = otherStyle?.paragraphSpacing ?: paragraphSpacing, headingStyle = otherStyle?.headingStyle ?: headingStyle, listStyle = otherStyle?.listStyle ?: listStyle, blockQuoteGutter = otherStyle?.blockQuoteGutter ?: blockQuoteGutter, codeBlockStyle = otherStyle?.codeBlockStyle ?: codeBlockStyle, tableStyle = otherStyle?.tableStyle ?: tableStyle, infoPanelStyle = otherStyle?.infoPanelStyle ?: infoPanelStyle, stringStyle = stringStyle?.merge(otherStyle?.stringStyle) ?: otherStyle?.stringStyle ) public fun RichTextStyle.resolveDefaults(): RichTextStyle = RichTextStyle( paragraphSpacing = paragraphSpacing ?: DefaultParagraphSpacing, headingStyle = headingStyle ?: DefaultHeadingStyle, listStyle = (listStyle ?: ListStyle.Default).resolveDefaults(), blockQuoteGutter = blockQuoteGutter ?: DefaultBlockQuoteGutter, codeBlockStyle = (codeBlockStyle ?: CodeBlockStyle.Default).resolveDefaults(), tableStyle = (tableStyle ?: TableStyle.Default).resolveDefaults(), infoPanelStyle = (infoPanelStyle ?: InfoPanelStyle.Default).resolveDefaults(), stringStyle = (stringStyle ?: RichTextStringStyle.Default).resolveDefaults() ) /** * The current [RichTextStyle]. */ public val RichTextScope.currentRichTextStyle: RichTextStyle @Composable get() = LocalRichTextStyle.current /** * Sets the [RichTextStyle] for its [children]. */ @Composable public fun RichTextScope.WithStyle( style: RichTextStyle?, children: @Composable RichTextScope.() -> Unit ) { if (style == null) { children() } else { val mergedStyle = LocalRichTextStyle.current.merge(style) CompositionLocalProvider(LocalRichTextStyle provides mergedStyle) { children() } } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextThemeConfiguration.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle internal typealias TextStyleProvider = @Composable () -> TextStyle internal typealias TextStyleBackProvider = @Composable (TextStyle, @Composable () -> Unit) -> Unit internal typealias ContentColorProvider = @Composable () -> Color internal typealias ContentColorBackProvider = @Composable (Color, @Composable () -> Unit) -> Unit internal data class RichTextThemeConfiguration( val textStyleProvider: TextStyleProvider = { LocalInternalTextStyle.current }, val textStyleBackProvider: TextStyleBackProvider = { newTextStyle, content -> CompositionLocalProvider(LocalInternalTextStyle provides newTextStyle) { content() } }, val contentColorProvider: ContentColorProvider = { LocalInternalContentColor.current }, val contentColorBackProvider: ContentColorBackProvider = { newColor, content -> CompositionLocalProvider(LocalInternalContentColor provides newColor) { content() } } ) { companion object { internal val Default = RichTextThemeConfiguration() } } internal val LocalRichTextThemeConfiguration: ProvidableCompositionLocal = compositionLocalOf { RichTextThemeConfiguration() } /** * Easy access delegations for [RichTextThemeProvider] within [RichTextScope] */ internal val RichTextScope.textStyleProvider: @Composable () -> TextStyle @Composable get() = LocalRichTextThemeConfiguration.current.textStyleProvider internal val RichTextScope.textStyleBackProvider: @Composable (TextStyle, @Composable () -> Unit) -> Unit @Composable get() = LocalRichTextThemeConfiguration.current.textStyleBackProvider internal val RichTextScope.contentColorProvider: @Composable () -> Color @Composable get() = LocalRichTextThemeConfiguration.current.contentColorProvider internal val RichTextScope.contentColorBackProvider: @Composable (Color, @Composable () -> Unit) -> Unit @Composable get() = LocalRichTextThemeConfiguration.current.contentColorBackProvider ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextThemeProvider.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle /** * Entry point for integrating app's own typography and theme system with RichText. * * API for this integration is highly influenced by how compose-material theming * is designed. RichText library assumes that almost all Theme/Design systems would * have composition locals that provide text style downstream. * * Moreover, text style should not include text color by best practice. Content color * exists to figure text color in current context. Light/Dark theming leverages content * color to influence not just text but other parts of theming as well. * * @param textStyleProvider Returns the current text style. * @param textStyleBackProvider RichText sometimes updates the current text style * e.g. Heading, CodeBlock, and etc. New style should be passed to the outer * theming to indicate that there is a need for update, so that children Text * composables use the correct styling. * @param contentColorProvider Returns the current content color. * @param contentColorBackProvider Similar to [textStyleBackProvider], does the same job * for content color. */ @Composable public fun RichTextThemeProvider( textStyleProvider: @Composable (() -> TextStyle)? = null, textStyleBackProvider: @Composable ((TextStyle, @Composable () -> Unit) -> Unit)? = null, contentColorProvider: @Composable (() -> Color)? = null, contentColorBackProvider: @Composable ((Color, @Composable () -> Unit) -> Unit)? = null, content: @Composable () -> Unit ) { CompositionLocalProvider( LocalRichTextThemeConfiguration provides RichTextThemeConfiguration( textStyleProvider = textStyleProvider ?: RichTextThemeConfiguration.Default.textStyleProvider, textStyleBackProvider = textStyleBackProvider ?: RichTextThemeConfiguration.Default.textStyleBackProvider, contentColorProvider = contentColorProvider ?: RichTextThemeConfiguration.Default.contentColorProvider, contentColorBackProvider = contentColorBackProvider ?: RichTextThemeConfiguration.Default.contentColorBackProvider, ) ) { content() } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/SimpleTableLayout.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.SubcomposeLayout import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.constrain import kotlin.math.roundToInt /** * The offsets of rows and columns of a [SimpleTableLayout], centered inside their spacing. * * E.g. If a table is given a cell spacing of 2px, then the first column and row offset will each * be 1px. */ @Immutable internal data class TableLayoutResult( val rowOffsets: List, val columnOffsets: List ) /** * A simple table that sizes all columns equally. * * @param cellSpacing The space in between each cell, and between each outer cell and the edge of * the table. */ @OptIn(ExperimentalStdlibApi::class) @Composable internal fun SimpleTableLayout( columns: Int, rows: List Unit>>, drawDecorations: (TableLayoutResult) -> Modifier, cellSpacing: Float, modifier: Modifier ) { SubcomposeLayout(modifier = modifier) { constraints -> val measurables = subcompose(false) { rows.forEach { row -> check(row.size == columns) row.forEach { cell -> cell() } } } val rowMeasurables = measurables.chunked(columns) check(rowMeasurables.size == rows.size) check(constraints.hasBoundedWidth) { "Table must have bounded width" } // Divide the width by the number of columns, then leave room for the padding. val cellSpacingWidth = cellSpacing * (columns + 1) val cellWidth = (constraints.maxWidth - cellSpacingWidth) / columns val cellSpacingHeight = cellSpacing * (rowMeasurables.size + 1) // TODO Handle bounded height constraints. // val cellMaxHeight = if (!constraints.hasBoundedHeight) { // Float.MAX_VALUE // } else { // // Divide the height by the number of rows, then leave room for the padding. // (constraints.maxHeight - cellSpacingHeight) / rowMeasurables.size // } val cellConstraints = Constraints(maxWidth = cellWidth.roundToInt()).constrain(constraints) val rowPlaceables = rowMeasurables.map { cellMeasurables -> cellMeasurables.map { cell -> cell.measure(cellConstraints) } } val rowHeights = rowPlaceables.map { row -> row.maxByOrNull { it.height }!!.height } val tableWidth = constraints.maxWidth val tableHeight = (rowHeights.sumOf { it } + cellSpacingHeight).roundToInt() layout(tableWidth, tableHeight) { var y = cellSpacing val rowOffsets = mutableListOf() val columnOffsets = mutableListOf() rowPlaceables.forEachIndexed { rowIndex, cellPlaceables -> rowOffsets += y - cellSpacing / 2f var x = cellSpacing cellPlaceables.forEach { cell -> if (rowIndex == 0) { columnOffsets.add(x - cellSpacing / 2f) } cell.place(x.roundToInt(), y.roundToInt()) x += cellWidth + cellSpacing } if (rowIndex == 0) { // Add the right-most edge. columnOffsets.add(x - cellSpacing / 2f) } y += rowHeights[rowIndex] + cellSpacing } rowOffsets.add(y - cellSpacing / 2f) // Compose and draw the borders. val layoutResult = TableLayoutResult(rowOffsets, columnOffsets) subcompose(true) { Box(modifier = drawDecorations(layoutResult)) }.single() .measure(Constraints.fixed(tableWidth, tableHeight)) .placeRelative(0, 0) } } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/Table.kt ================================================ @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry") package com.halilibo.richtext.ui import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp import kotlin.math.max /** * Defines the visual style for a [Table]. * * @param headerTextStyle The [TextStyle] used for header rows. * @param cellPadding The spacing between the contents of each cell and the borders. * @param borderColor The [Color] of the table border. * @param borderStrokeWidth The width of the table border. */ @Immutable public data class TableStyle( val headerTextStyle: TextStyle? = null, val cellPadding: TextUnit? = null, val borderColor: Color? = null, val borderStrokeWidth: Float? = null ) { public companion object { public val Default: TableStyle = TableStyle() } } private val DefaultTableHeaderTextStyle = TextStyle(fontWeight = FontWeight.Bold) private val DefaultCellPadding = 8.sp private val DefaultBorderColor = Color.Unspecified private const val DefaultBorderStrokeWidth = 1f internal fun TableStyle.resolveDefaults() = TableStyle( headerTextStyle = headerTextStyle ?: DefaultTableHeaderTextStyle, cellPadding = cellPadding ?: DefaultCellPadding, borderColor = borderColor ?: DefaultBorderColor, borderStrokeWidth = borderStrokeWidth ?: DefaultBorderStrokeWidth ) public interface RichTextTableRowScope { public fun row(children: RichTextTableCellScope.() -> Unit) } public interface RichTextTableCellScope { public fun cell(children: @Composable RichTextScope.() -> Unit) } @Immutable private data class TableRow(val cells: List<@Composable RichTextScope.() -> Unit>) private class TableBuilder : RichTextTableRowScope { val rows = mutableListOf() override fun row(children: RichTextTableCellScope.() -> Unit) { rows += RowBuilder().apply(children) } } private class RowBuilder : RichTextTableCellScope { var row = TableRow(emptyList()) override fun cell(children: @Composable RichTextScope.() -> Unit) { row = TableRow(row.cells + children) } } /** * Draws a table with an optional header row, and an arbitrary number of body rows. * * The style of the table is defined by the [RichTextStyle.tableStyle] [TableStyle]. */ @OptIn(ExperimentalStdlibApi::class) @Composable public fun RichTextScope.Table( modifier: Modifier = Modifier, headerRow: (RichTextTableCellScope.() -> Unit)? = null, bodyRows: RichTextTableRowScope.() -> Unit ) { val tableStyle = currentRichTextStyle.resolveDefaults().tableStyle!! val contentColor = currentContentColor val header = remember(headerRow) { headerRow?.let { RowBuilder().apply(headerRow).row } } val rows = remember(bodyRows) { TableBuilder().apply(bodyRows).rows.map { it.row } } val columns = remember(header, rows) { max( header?.cells?.size ?: 0, rows.maxByOrNull { it.cells.size }?.cells?.size ?: 0 ) } val headerStyle = currentTextStyle.merge(tableStyle.headerTextStyle) val cellPadding = with(LocalDensity.current) { tableStyle.cellPadding!!.toDp() } val cellModifier = Modifier .clipToBounds() .padding(cellPadding) val styledRows = remember(header, rows, cellModifier) { buildList { header?.let { headerRow -> // Type inference seems to puke without explicit parameters. @Suppress("RemoveExplicitTypeArguments") add(headerRow.cells.map<@Composable RichTextScope.() -> Unit, @Composable () -> Unit> { cell -> @Composable { textStyleBackProvider(headerStyle) { BasicRichText( modifier = cellModifier, children = cell ) } } }) } rows.mapTo(this) { row -> @Suppress("RemoveExplicitTypeArguments") row.cells.map<@Composable RichTextScope.() -> Unit, @Composable () -> Unit> { cell -> @Composable { BasicRichText( modifier = cellModifier, children = cell ) } } } } } // For some reason borders don't get drawn in the Preview, but they work on-device. SimpleTableLayout( columns = columns, rows = styledRows, cellSpacing = tableStyle.borderStrokeWidth!!, drawDecorations = { layoutResult -> Modifier.drawTableBorders( rowOffsets = layoutResult.rowOffsets, columnOffsets = layoutResult.columnOffsets, borderColor = tableStyle.borderColor!!.takeOrElse { contentColor }, borderStrokeWidth = tableStyle.borderStrokeWidth ) }, modifier = modifier ) } private fun Modifier.drawTableBorders( rowOffsets: List, columnOffsets: List, borderColor: Color, borderStrokeWidth: Float ) = drawBehind { // Draw horizontal borders. rowOffsets.forEach { position -> drawLine( borderColor, start = Offset(0f, position), end = Offset(size.width, position), borderStrokeWidth ) } // Draw vertical borders. columnOffsets.forEach { position -> drawLine( borderColor, Offset(position, 0f), Offset(position, size.height), borderStrokeWidth ) } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/string/InlineContent.kt ================================================ @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry", "FunctionName") package com.halilibo.richtext.ui.string import androidx.compose.foundation.text.InlineTextContent import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.structuralEqualityPolicy import androidx.compose.ui.layout.Layout import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.Placeholder import androidx.compose.ui.text.PlaceholderVerticalAlign import androidx.compose.ui.text.PlaceholderVerticalAlign.Companion.AboveBaseline import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.sp /** * A Composable that can be embedded inline in a [RichTextString] by passing to * [RichTextString.Builder.appendInlineContent]. * * @param initialSize Optional function to calculate the initial size of the content. Not specifying * this may cause flicker. * @param placeholderVerticalAlign Used to specify how a placeholder is vertically aligned within a * text line. */ public class InlineContent( internal val initialSize: (Density.() -> IntSize)? = null, internal val placeholderVerticalAlign: PlaceholderVerticalAlign = AboveBaseline, internal val content: @Composable Density.(alternateText: String) -> Unit ) /** * Converts a map of [InlineContent]s into a map of [InlineTextContent] that is ready to pass to * the core Text composable. Whenever any of the contents resize themselves, or if the map changes, * a new map will be returned with updated [Placeholder]s. */ @Composable internal fun manageInlineTextContents( inlineContents: Map, textConstraints: Constraints ): Map { val density = LocalDensity.current return inlineContents.mapValues { (_, content) -> reifyInlineContent( content, Constraints(maxWidth = textConstraints.maxWidth, maxHeight = textConstraints.maxHeight), density ) } } /** * Given an [InlineContent] function, wraps it in a [InlineTextContent] that will allow the content * to measure itself inside the enclosing layout's maximum constraints, and automatically return a * new [InlineTextContent] whenever the content changes size to update how much space is reserved * in the text layout for the content. */ @Composable private fun reifyInlineContent( content: InlineContent, contentConstraints: Constraints, density: Density ): InlineTextContent { var size by remember { mutableStateOf( content.initialSize?.invoke(density), structuralEqualityPolicy() ) } with(density) { // If size is null, content hasn't been measured yet, so just draw with zero width for now. // Set the height to 1 em so we can calculate how many pixels in an EM. val placeholder = Placeholder( width = size?.width?.toSp() ?: 0.sp, height = size?.height?.toSp() ?: 1.sp, placeholderVerticalAlign = content.placeholderVerticalAlign ) return InlineTextContent(placeholder) { alternateText -> Layout(content = { content.content(this, alternateText) }) { measurables, _ -> // Measure the content with the constraints for the parent Text layout, not the actual. // This allows it to determine exactly how large it needs to be so we can update the // placeholder. val contentPlaceable = measurables.singleOrNull()?.measure(contentConstraints) ?: return@Layout layout(0, 0) {} if (contentPlaceable.width != size?.width || contentPlaceable.height != size?.height ) { size = IntSize(contentPlaceable.width, contentPlaceable.height) } layout(contentPlaceable.width, contentPlaceable.height) { contentPlaceable.place(0, 0) } } } } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/string/RichTextString.kt ================================================ @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry", "SuspiciousCollectionReassignment") package com.halilibo.richtext.ui.string import androidx.compose.foundation.text.appendInlineContent import androidx.compose.runtime.Immutable import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.LinkInteractionListener import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.sp import com.halilibo.richtext.ui.DefaultCodeBlockBackgroundColor import com.halilibo.richtext.ui.string.RichTextString.Builder import com.halilibo.richtext.ui.string.RichTextString.Format import com.halilibo.richtext.ui.string.RichTextString.Format.Bold import com.halilibo.richtext.ui.string.RichTextString.Format.Code import com.halilibo.richtext.ui.string.RichTextString.Format.Companion.FormatAnnotationScope import com.halilibo.richtext.ui.string.RichTextString.Format.Italic import com.halilibo.richtext.ui.string.RichTextString.Format.Link import com.halilibo.richtext.ui.string.RichTextString.Format.Strikethrough import com.halilibo.richtext.ui.string.RichTextString.Format.Subscript import com.halilibo.richtext.ui.string.RichTextString.Format.Superscript import com.halilibo.richtext.ui.string.RichTextString.Format.Underline import com.halilibo.richtext.ui.util.randomUUID import kotlin.LazyThreadSafetyMode.NONE /** Copied from inline content. */ @PublishedApi internal const val REPLACEMENT_CHAR: String = "\uFFFD" /** * Defines the [SpanStyle]s that are used for various [RichTextString] formatting directives. */ @Immutable public class RichTextStringStyle( public val boldStyle: SpanStyle? = null, public val italicStyle: SpanStyle? = null, public val underlineStyle: SpanStyle? = null, public val strikethroughStyle: SpanStyle? = null, public val subscriptStyle: SpanStyle? = null, public val superscriptStyle: SpanStyle? = null, public val codeStyle: SpanStyle? = null, public val linkStyle: TextLinkStyles? = null ) { public fun copy( boldStyle: SpanStyle? = this.boldStyle, italicStyle: SpanStyle? = this.italicStyle, underlineStyle: SpanStyle? = this.underlineStyle, strikethroughStyle: SpanStyle? = this.strikethroughStyle, subscriptStyle: SpanStyle? = this.subscriptStyle, superscriptStyle: SpanStyle? = this.superscriptStyle, codeStyle: SpanStyle? = this.codeStyle, linkStyle: TextLinkStyles? = this.linkStyle ): RichTextStringStyle = RichTextStringStyle( boldStyle = boldStyle, italicStyle = italicStyle, underlineStyle = underlineStyle, strikethroughStyle = strikethroughStyle, subscriptStyle = subscriptStyle, superscriptStyle = superscriptStyle, codeStyle = codeStyle, linkStyle = linkStyle ) internal fun merge(otherStyle: RichTextStringStyle?): RichTextStringStyle { if (otherStyle == null) return this return RichTextStringStyle( boldStyle = boldStyle.merge(otherStyle.boldStyle), italicStyle = italicStyle.merge(otherStyle.italicStyle), underlineStyle = underlineStyle.merge(otherStyle.underlineStyle), strikethroughStyle = strikethroughStyle.merge(otherStyle.strikethroughStyle), subscriptStyle = subscriptStyle.merge(otherStyle.subscriptStyle), superscriptStyle = superscriptStyle.merge(otherStyle.superscriptStyle), codeStyle = codeStyle.merge(otherStyle.codeStyle), linkStyle = linkStyle?.merge(otherStyle.linkStyle) ?: otherStyle.linkStyle ) } internal fun resolveDefaults(): RichTextStringStyle = RichTextStringStyle( boldStyle = boldStyle ?: Bold.DefaultStyle, italicStyle = italicStyle ?: Italic.DefaultStyle, underlineStyle = underlineStyle ?: Underline.DefaultStyle, strikethroughStyle = strikethroughStyle ?: Strikethrough.DefaultStyle, subscriptStyle = subscriptStyle ?: Subscript.DefaultStyle, superscriptStyle = superscriptStyle ?: Superscript.DefaultStyle, codeStyle = codeStyle ?: Code.DefaultStyle, linkStyle = linkStyle ?: Link.DefaultStyle ) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is RichTextStringStyle) return false if (boldStyle != other.boldStyle) return false if (italicStyle != other.italicStyle) return false if (underlineStyle != other.underlineStyle) return false if (strikethroughStyle != other.strikethroughStyle) return false if (subscriptStyle != other.subscriptStyle) return false if (superscriptStyle != other.superscriptStyle) return false if (codeStyle != other.codeStyle) return false if (linkStyle != other.linkStyle) return false return true } override fun hashCode(): Int { var result = boldStyle?.hashCode() ?: 0 result = 31 * result + (italicStyle?.hashCode() ?: 0) result = 31 * result + (underlineStyle?.hashCode() ?: 0) result = 31 * result + (strikethroughStyle?.hashCode() ?: 0) result = 31 * result + (subscriptStyle?.hashCode() ?: 0) result = 31 * result + (superscriptStyle?.hashCode() ?: 0) result = 31 * result + (codeStyle?.hashCode() ?: 0) result = 31 * result + (linkStyle?.hashCode() ?: 0) return result } override fun toString(): String { return "RichTextStringStyle(boldStyle=$boldStyle, " + "italicStyle=$italicStyle, " + "underlineStyle=$underlineStyle, " + "strikethroughStyle=$strikethroughStyle, " + "subscriptStyle=$subscriptStyle, " + "superscriptStyle=$superscriptStyle, " + "codeStyle=$codeStyle, " + "linkStyle=$linkStyle)" } public companion object { public val Default: RichTextStringStyle = RichTextStringStyle() private fun SpanStyle?.merge(otherStyle: SpanStyle?): SpanStyle? = this?.merge(otherStyle) ?: otherStyle } } /** * Convenience function for creating a [RichTextString] using a [Builder]. */ public inline fun richTextString(builder: Builder.() -> Unit): RichTextString = Builder().apply(builder) .toRichTextString() /** * A special type of [AnnotatedString] that is formatted using higher-level directives that are * configured using a [RichTextStringStyle]. */ @Immutable public class RichTextString internal constructor( private val taggedString: AnnotatedString, internal val formatObjects: Map ) { private val length: Int get() = taggedString.length public val text: String get() = taggedString.text public operator fun plus(other: RichTextString): RichTextString = Builder(length + other.length).run { append(this@RichTextString) append(other) toRichTextString() } internal fun toAnnotatedString( style: RichTextStringStyle, contentColor: Color ): AnnotatedString = buildAnnotatedString { append(taggedString) // Get all of our format annotations. val tags = taggedString.getStringAnnotations(FormatAnnotationScope, 0, taggedString.length) // And apply their actual SpanStyles to the string. tags.forEach { range -> val format = Format.findTag(range.item, formatObjects) ?: return@forEach format.getAnnotation(style, contentColor) ?.let { annotation -> if (annotation is SpanStyle) { addStyle(annotation, range.start, range.end) } else if (annotation is LinkAnnotation.Url) { addLink(annotation, range.start, range.end) } } } } internal fun getInlineContents(): Map = formatObjects.asSequence() .mapNotNull { (tag, format) -> tag.removePrefix("inline:") // If no prefix was found then we ignore it. .takeUnless { it === tag } ?.let { Pair(it, format as InlineContent) } } .toMap() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is RichTextString) return false if (taggedString != other.taggedString) return false if (formatObjects != other.formatObjects) return false return true } override fun hashCode(): Int { var result = taggedString.hashCode() result = 31 * result + formatObjects.hashCode() return result } public sealed class Format(private val simpleTag: String? = null) { /** * This function should either return [SpanStyle] or [LinkAnnotation.Url]. In future releases of * Compose these classes will have a common supertype called `AnnotatedString.Annotation`. Then * we can stop returning [Any]. */ internal open fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ): Any? = null public object Italic : Format("italic") { internal val DefaultStyle = SpanStyle(fontStyle = FontStyle.Italic) override fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ) = richTextStyle.italicStyle } public object Bold : Format(simpleTag = "foo") { internal val DefaultStyle = SpanStyle(fontWeight = FontWeight.Bold) override fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ) = richTextStyle.boldStyle } public object Underline : Format("underline") { internal val DefaultStyle = SpanStyle(textDecoration = TextDecoration.Underline) override fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ) = richTextStyle.underlineStyle } public object Strikethrough : Format("strikethrough") { internal val DefaultStyle = SpanStyle(textDecoration = TextDecoration.LineThrough) override fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ) = richTextStyle.strikethroughStyle } public object Subscript : Format("subscript") { internal val DefaultStyle = SpanStyle( baselineShift = BaselineShift(-0.2f), // TODO this should be relative to current font size fontSize = 10.sp ) override fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ) = richTextStyle.subscriptStyle } public object Superscript : Format("superscript") { internal val DefaultStyle = SpanStyle( baselineShift = BaselineShift.Superscript, fontSize = 10.sp ) override fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ) = richTextStyle.superscriptStyle } public object Code : Format("code") { internal val DefaultStyle = SpanStyle( fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, background = DefaultCodeBlockBackgroundColor ) override fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ) = richTextStyle.codeStyle } public class Link( public val destination: String, public val linkInteractionListener: LinkInteractionListener? = null ) : Format() { override fun getAnnotation( richTextStyle: RichTextStringStyle, contentColor: Color ) = LinkAnnotation.Url( url = destination, styles = richTextStyle.linkStyle, linkInteractionListener = linkInteractionListener ) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Link) return false if (destination != other.destination) return false if (linkInteractionListener != other.linkInteractionListener) return false return true } override fun hashCode(): Int { var result = destination.hashCode() result = 31 * result + linkInteractionListener.hashCode() return result } override fun toString(): String { return "Link(destination='$destination', linkInteractionListener=$linkInteractionListener)" } internal companion object { val DefaultStyle = TextLinkStyles( style = SpanStyle(color = Color.Blue), hoveredStyle = SpanStyle( textDecoration = TextDecoration.Underline, color = Color.Blue ) ) } } internal fun registerTag(tags: MutableMap): String { simpleTag?.let { return it } val uuid = randomUUID() tags[uuid] = this return "format:$uuid" } internal companion object { val FormatAnnotationScope = Format::class.qualifiedName!! // For some reason, if this isn't lazy, Bold will always be null. Is Compose messing up static // initialization order? private val simpleTags by lazy(NONE) { listOf(Bold, Italic, Underline, Strikethrough, Subscript, Superscript, Code) } fun findTag( tag: String, tags: Map ): Format? { val stripped = tag.removePrefix("format:") return if (stripped === tag) { // If the original string was returned, it means the string did not have the prefix. simpleTags.firstOrNull { it.simpleTag == tag } } else { tags[stripped] as? Format } } } } public class Builder(capacity: Int = 16) { private val builder = AnnotatedString.Builder(capacity) private val formatObjects = mutableMapOf() public fun addFormat( format: Format, start: Int, end: Int ) { val tag = format.registerTag(formatObjects) builder.addStringAnnotation(FormatAnnotationScope, tag, start, end) } public fun pushFormat(format: Format): Int { val tag = format.registerTag(formatObjects) return builder.pushStringAnnotation(FormatAnnotationScope, tag) } public fun pop(): Unit = builder.pop() public fun pop(index: Int): Unit = builder.pop(index) public fun append(text: String): Unit = builder.append(text) public fun append(text: RichTextString) { builder.append(text.taggedString) formatObjects.putAll(text.formatObjects) } public fun appendInlineContent( alternateText: String = REPLACEMENT_CHAR, content: InlineContent ) { val tag = randomUUID() formatObjects["inline:$tag"] = content builder.appendInlineContent(tag, alternateText) } /** * Provides access to the underlying builder, which can be used to add arbitrary formatting, * including mixed with formatting from this Builder. */ public fun withAnnotatedString(block: AnnotatedString.Builder.() -> T): T = builder.block() public fun toRichTextString(): RichTextString = RichTextString( builder.toAnnotatedString(), formatObjects.toMap() ) } } public inline fun Builder.withFormat( format: Format, block: Builder.() -> Unit ) { val index = pushFormat(format) block() pop(index) } private fun TextLinkStyles.merge(other: TextLinkStyles?): TextLinkStyles { return if (other == null) { TextLinkStyles() } else { TextLinkStyles( style = this.style?.merge(other.style) ?: other.style, focusedStyle = this.style?.merge(other.focusedStyle) ?: other.focusedStyle, hoveredStyle = this.style?.merge(other.hoveredStyle) ?: other.hoveredStyle, pressedStyle = this.style?.merge(other.pressedStyle) ?: other.pressedStyle, ) } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/string/Text.kt ================================================ package com.halilibo.richtext.ui.string import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.style.TextOverflow import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.Text import com.halilibo.richtext.ui.currentContentColor import com.halilibo.richtext.ui.currentRichTextStyle import com.halilibo.richtext.ui.string.RichTextString.Format /** * Renders a [RichTextString] as created with [richTextString]. */ @Suppress("UnusedBoxWithConstraintsScope") @Composable public fun RichTextScope.Text( text: RichTextString, modifier: Modifier = Modifier, onTextLayout: (TextLayoutResult) -> Unit = {}, softWrap: Boolean = true, overflow: TextOverflow = TextOverflow.Clip, maxLines: Int = Int.MAX_VALUE ) { val style = currentRichTextStyle.stringStyle val contentColor = currentContentColor val annotated = remember(text, style, contentColor) { val resolvedStyle = (style ?: RichTextStringStyle.Default).resolveDefaults() text.toAnnotatedString(resolvedStyle, contentColor) } val inlineContents = remember(text) { text.getInlineContents() } if (inlineContents.isEmpty()) { Text( text = annotated, onTextLayout = onTextLayout, softWrap = softWrap, overflow = overflow, maxLines = maxLines ) } else { // expensive constraints reading path BoxWithConstraints(modifier = modifier) { val inlineTextContents = manageInlineTextContents( inlineContents = inlineContents, textConstraints = constraints ) Text( text = annotated, onTextLayout = onTextLayout, inlineContent = inlineTextContents, softWrap = softWrap, overflow = overflow, maxLines = maxLines, ) } } } private fun AnnotatedString.getConsumableAnnotations(textFormatObjects: Map, offset: Int): Sequence = getStringAnnotations(Format.FormatAnnotationScope, offset, offset) .asSequence() .mapNotNull { Format.findTag( it.item, textFormatObjects ) as? Format.Link } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/util/ConditionalTapGestureDetector.kt ================================================ @file:OptIn(ExperimentalComposeUiApi::class) package com.halilibo.richtext.ui.util import androidx.compose.foundation.gestures.GestureCancellationException import androidx.compose.foundation.gestures.PressGestureScope import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.AwaitPointerEventScope import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventTimeoutCancellationException import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.input.pointer.changedToUp import androidx.compose.ui.input.pointer.isOutOfBounds import androidx.compose.ui.platform.ViewConfiguration import androidx.compose.ui.unit.Density import androidx.compose.ui.util.fastAll import androidx.compose.ui.util.fastAny import androidx.compose.ui.util.fastForEach import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex private val NoPressGesture: suspend PressGestureScope.(Offset) -> Unit = { } /** * If predicate returns true: detects tap, double-tap, and long press gestures and calls [onTap], * [onDoubleTap], and [onLongPress], respectively, when detected. [onPress] is called when the press * is detected and the [PressGestureScope.tryAwaitRelease] and [PressGestureScope.awaitRelease] * can be used to detect when pointers have released or the gesture was canceled. * The first pointer down and final pointer up are consumed, and in the * case of long press, all changes after the long press is detected are consumed. * * Each function parameter receives an [Offset] representing the position relative to the containing * element. The [Offset] can be outside the actual bounds of the element itself meaning the numbers * can be negative or larger than the element bounds if the touch target is smaller than the * [ViewConfiguration.minimumTouchTargetSize]. * * When [onDoubleTap] is provided, the tap gesture is detected only after * the [ViewConfiguration.doubleTapMinTimeMillis] has passed and [onDoubleTap] is called if the * second tap is started before [ViewConfiguration.doubleTapTimeoutMillis]. If [onDoubleTap] is not * provided, then [onTap] is called when the pointer up has been received. * * After the initial [onPress], if the pointer moves out of the input area, the position change * is consumed, or another gesture consumes the down or up events, the gestures are considered * canceled. That means [onDoubleTap], [onLongPress], and [onTap] will not be called after a * gesture has been canceled. * * If the first down event is consumed somewhere else, the entire gesture will be skipped, * including [onPress]. */ public suspend fun PointerInputScope.detectTapGesturesIf( predicate: (Offset) -> Boolean = { true }, onDoubleTap: ((Offset) -> Unit)? = null, onLongPress: ((Offset) -> Unit)? = null, onPress: suspend PressGestureScope.(Offset) -> Unit = NoPressGesture, onTap: ((Offset) -> Unit)? = null ): Unit = coroutineScope { // special signal to indicate to the sending side that it shouldn't intercept and consume // cancel/up events as we're only require down events val pressScope = PressGestureScopeImpl(this@detectTapGesturesIf) awaitEachGesture { val down = awaitFirstDown() if (!predicate(down.position)) { pressScope.reset() return@awaitEachGesture } down.consume() pressScope.reset() if (onPress !== NoPressGesture) launch { pressScope.onPress(down.position) } val longPressTimeout = onLongPress?.let { viewConfiguration.longPressTimeoutMillis } ?: (Long.MAX_VALUE / 2) var upOrCancel: PointerInputChange? = null try { // wait for first tap up or long press upOrCancel = withTimeout(longPressTimeout) { waitForUpOrCancellation() } if (upOrCancel == null) { pressScope.cancel() // tap-up was canceled } else { upOrCancel.consume() pressScope.release() } } catch (_: PointerEventTimeoutCancellationException) { onLongPress?.invoke(down.position) consumeUntilUp() pressScope.release() } if (upOrCancel != null) { // tap was successful. if (onDoubleTap == null) { onTap?.invoke(upOrCancel.position) // no need to check for double-tap. } else { // check for second tap val secondDown = awaitSecondDown(upOrCancel) if (secondDown == null) { onTap?.invoke(upOrCancel.position) // no valid second tap started } else { // Second tap down detected pressScope.reset() if (onPress !== NoPressGesture) { launch { pressScope.onPress(secondDown.position) } } try { // Might have a long second press as the second tap withTimeout(longPressTimeout) { val secondUp = waitForUpOrCancellation() if (secondUp != null) { secondUp.consume() pressScope.release() onDoubleTap(secondUp.position) } else { pressScope.cancel() onTap?.invoke(upOrCancel.position) } } } catch (e: PointerEventTimeoutCancellationException) { // The first tap was valid, but the second tap is a long press. // notify for the first tap onTap?.invoke(upOrCancel.position) // notify for the long press onLongPress?.invoke(secondDown.position) consumeUntilUp() pressScope.release() } } } } } } /** * Consumes all pointer events until nothing is pressed and then returns. This method assumes * that something is currently pressed. */ private suspend fun AwaitPointerEventScope.consumeUntilUp() { do { val event = awaitPointerEvent() event.changes.fastForEach { it.consume() } } while (event.changes.fastAny { it.pressed }) } /** * Waits for [ViewConfiguration.doubleTapTimeoutMillis] for a second press event. If a * second press event is received before the time out, it is returned or `null` is returned * if no second press is received. */ private suspend fun AwaitPointerEventScope.awaitSecondDown( firstUp: PointerInputChange ): PointerInputChange? = withTimeoutOrNull(viewConfiguration.doubleTapTimeoutMillis) { val minUptime = firstUp.uptimeMillis + viewConfiguration.doubleTapMinTimeMillis var change: PointerInputChange // The second tap doesn't count if it happens before DoubleTapMinTime of the first tap do { change = awaitFirstDown() } while (change.uptimeMillis < minUptime) change } /** * Reads events until all pointers are up or the gesture was canceled. The gesture * is considered canceled when a pointer leaves the event region, a position change * has been consumed or a pointer down change event was consumed in the [PointerEventPass.Main] * pass. If the gesture was not canceled, the final up change is returned or `null` if the * event was canceled. */ private suspend fun AwaitPointerEventScope.waitForUpOrCancellation(): PointerInputChange? { while (true) { val event = awaitPointerEvent(PointerEventPass.Main) if (event.changes.fastAll { it.changedToUp() }) { // All pointers are up return event.changes[0] } if (event.changes.fastAny { it.isConsumed || it.isOutOfBounds(size, extendedTouchPadding) } ) { return null // Canceled } // Check for cancel by position consumption. We can look on the Final pass of the // existing pointer event because it comes after the Main pass we checked above. val consumeCheck = awaitPointerEvent(PointerEventPass.Final) if (consumeCheck.changes.fastAny { it.isConsumed }) { return null } } } /** * [detectTapGesturesIf]'s implementation of [PressGestureScope]. */ private class PressGestureScopeImpl( density: Density ) : PressGestureScope, Density by density { private var isReleased = false private var isCanceled = false private val mutex = Mutex(locked = false) /** * Called when a gesture has been canceled. */ fun cancel() { isCanceled = true mutex.unlock() } /** * Called when all pointers are up. */ fun release() { isReleased = true mutex.unlock() } /** * Called when a new gesture has started. */ fun reset() { mutex.tryLock() // If tryAwaitRelease wasn't called, this will be unlocked. isReleased = false isCanceled = false } override suspend fun awaitRelease() { if (!tryAwaitRelease()) { throw GestureCancellationException("The press gesture was canceled.") } } override suspend fun tryAwaitRelease(): Boolean { if (!isReleased && !isCanceled) { mutex.lock() } return isReleased } } ================================================ FILE: richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/util/UUID.kt ================================================ package com.halilibo.richtext.ui.util internal expect fun randomUUID(): String ================================================ FILE: richtext-ui/src/jvmAndroidMain/kotlin/com/halilibo/richtext/ui/util/UUID.kt ================================================ package com.halilibo.richtext.ui.util import java.util.UUID internal actual fun randomUUID(): String { return UUID.randomUUID().toString() } ================================================ FILE: richtext-ui/src/jvmMain/kotlin/com/halilibo/richtext/ui/CodeBlock.desktop.kt ================================================ package com.halilibo.richtext.ui import androidx.compose.foundation.HorizontalScrollbar import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.Modifier private val LocalScrollbarEnabled = compositionLocalOf { true } @Composable internal actual fun RichTextScope.CodeBlockLayout( wordWrap: Boolean, children: @Composable RichTextScope.(Modifier) -> Unit ) { if (!wordWrap) { val scrollState = rememberScrollState() Column { children(Modifier.horizontalScroll(scrollState)) if (LocalScrollbarEnabled.current) { val horizontalScrollbarAdapter = rememberScrollbarAdapter(scrollState) HorizontalScrollbar(adapter = horizontalScrollbarAdapter) } } } else { children(Modifier) } } /** * Contextually disables scrollbar for Desktop CodeBlocks under [content] tree. */ @Composable public fun DisableScrollbar( content: @Composable () -> Unit ) { CompositionLocalProvider(LocalScrollbarEnabled provides false) { content() } } ================================================ FILE: richtext-ui-material/build.gradle.kts ================================================ plugins { id("richtext-kmp-library") id("org.jetbrains.dokka") } kotlin { android { namespace = "com.halilibo.richtext.ui.material" } sourceSets { val commonMain by getting { dependencies { implementation(compose.runtime) implementation(compose.foundation) implementation(compose.material) api(project(":richtext-ui")) } } val commonTest by getting val androidMain by getting val jvmMain by getting } } ================================================ FILE: richtext-ui-material/gradle.properties ================================================ POM_NAME=Compose Richtext UI Material POM_DESCRIPTION=An extension library for RichText UI to easily bind with Material apps. ================================================ FILE: richtext-ui-material/src/androidMain/AndroidManifest.xml ================================================ ================================================ FILE: richtext-ui-material/src/commonMain/kotlin/com/halilibo/richtext/ui/material/RichText.kt ================================================ package com.halilibo.richtext.ui.material import androidx.compose.material.LocalContentColor import androidx.compose.material.LocalTextStyle import androidx.compose.material.ProvideTextStyle import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.Modifier import com.halilibo.richtext.ui.BasicRichText import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.RichTextThemeProvider /** * RichText implementation that integrates with Material design. * * If the consumer app has small composition trees or only uses RichText in * a single place, it would be ideal to call this function instead of wrapping * everything under [RichTextMaterialTheme]. */ @Composable public fun RichText( modifier: Modifier = Modifier, style: RichTextStyle? = null, children: @Composable RichTextScope.() -> Unit ) { RichTextMaterialTheme { BasicRichText( modifier = modifier, style = style, children = children ) } } /** * Wraps the given [child] with Material Theme integration for [BasicRichText]. * * This function also keeps track of the parent context by using CompositionLocals * to not apply Material Theming if it already exists in the current composition. */ @Composable internal fun RichTextMaterialTheme( child: @Composable () -> Unit ) { val isApplied = LocalMaterialThemingApplied.current if (!isApplied) { RichTextThemeProvider( textStyleProvider = { LocalTextStyle.current }, contentColorProvider = { LocalContentColor.current }, textStyleBackProvider = { textStyle, content -> ProvideTextStyle(textStyle, content) }, contentColorBackProvider = { color, content -> CompositionLocalProvider(LocalContentColor provides color) { content() } } ) { CompositionLocalProvider(LocalMaterialThemingApplied provides true) { child() } } } else { child() } } private val LocalMaterialThemingApplied = compositionLocalOf { false } ================================================ FILE: richtext-ui-material3/build.gradle.kts ================================================ plugins { id("richtext-kmp-library") id("org.jetbrains.dokka") } kotlin { android { namespace = "com.halilibo.richtext.ui.material3" } sourceSets { val commonMain by getting { dependencies { implementation(compose.runtime) implementation(compose.foundation) implementation(compose.material3) api(project(":richtext-ui")) } } val commonTest by getting val androidMain by getting val jvmMain by getting } } ================================================ FILE: richtext-ui-material3/gradle.properties ================================================ POM_NAME=Compose Richtext UI Material3 POM_DESCRIPTION=An extension library for RichText UI to easily bind with Material3 apps. ================================================ FILE: richtext-ui-material3/src/androidMain/AndroidManifest.xml ================================================ ================================================ FILE: richtext-ui-material3/src/commonMain/kotlin/com/halilibo/richtext/ui/material3/RichText.kt ================================================ package com.halilibo.richtext.ui.material3 import androidx.compose.material3.LocalContentColor import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.ProvideTextStyle import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.Modifier import com.halilibo.richtext.ui.BasicRichText import com.halilibo.richtext.ui.RichTextScope import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.RichTextThemeProvider /** * RichText implementation that integrates with Material 3 design. * * If the consumer app has small composition trees or only uses RichText in * a single place, it would be ideal to call this function instead of wrapping * everything under [RichTextMaterialTheme]. */ @Composable public fun RichText( modifier: Modifier = Modifier, style: RichTextStyle? = null, children: @Composable RichTextScope.() -> Unit ) { RichTextMaterialTheme { BasicRichText( modifier = modifier, style = style, children = children ) } } /** * Wraps the given [child] with Material Theme integration for [BasicRichText]. * * This function also keeps track of the parent context by using CompositionLocals * to not apply Material Theming if it already exists in the current composition. */ @Composable internal fun RichTextMaterialTheme( child: @Composable () -> Unit ) { val isApplied = LocalMaterialThemingApplied.current if (!isApplied) { RichTextThemeProvider( textStyleProvider = { LocalTextStyle.current }, contentColorProvider = { LocalContentColor.current }, textStyleBackProvider = { textStyle, content -> ProvideTextStyle(textStyle, content) }, contentColorBackProvider = { color, content -> CompositionLocalProvider(LocalContentColor provides color) { content() } } ) { CompositionLocalProvider(LocalMaterialThemingApplied provides true) { child() } } } else { child() } } private val LocalMaterialThemingApplied = compositionLocalOf { false } ================================================ FILE: settings.gradle.kts ================================================ pluginManagement { repositories { google() gradlePluginPortal() mavenCentral() } } include(":richtext-ui") include(":richtext-ui-material") include(":richtext-ui-material3") include(":richtext-commonmark") include(":richtext-markdown") include(":android-sample") include(":desktop-sample") rootProject.name = "compose-richtext"