├── .github
├── FUNDING.yml
└── 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
│ │ ├── AnimationSample.kt
│ │ ├── Demo.kt
│ │ ├── DocumentSample.kt
│ │ ├── LazyMarkdownSample.kt
│ │ ├── MarkdownSample.kt
│ │ ├── PagedSample.kt
│ │ ├── RichTextSample.kt
│ │ ├── SampleActivity.kt
│ │ ├── SampleLauncher.kt
│ │ ├── SampleTheme.kt
│ │ ├── ScreenPreview.kt
│ │ ├── SlideshowSample.kt
│ │ └── TextDemo.kt
│ └── res
│ ├── drawable-v24
│ └── ic_launcher_foreground.xml
│ ├── drawable
│ └── ic_launcher_background.xml
│ ├── mipmap-anydpi-v26
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-mdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle.kts
├── buildSrc
├── build.gradle.kts
└── src
│ └── main
│ └── kotlin
│ ├── Dependencies.kt
│ ├── richtext-android-library.gradle.kts
│ └── richtext-kmp-library.gradle.kts
├── desktop-sample
├── build.gradle.kts
└── src
│ └── main
│ └── kotlin
│ └── com
│ └── halilibo
│ └── richtext
│ └── desktop
│ ├── MarkdownSampleApp.kt
│ └── RichTextSampleApp.kt
├── docs
├── img
│ ├── markdown-demo.png
│ ├── printing-demo.gif
│ ├── richtext-demo.png
│ ├── slideshow-demo.gif
│ └── slideshow-scrubbing-demo.gif
├── index.md
├── printing.md
├── richtext-commonmark.md
├── richtext-markdown.md
├── richtext-ui-material.md
├── richtext-ui-material3.md
├── richtext-ui.md
└── slideshow.md
├── gen_docs.sh
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── mkdocs.yml
├── printing
├── api
│ └── printing.api
├── build.gradle.kts
├── consumer-rules.pro
├── gradle.properties
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── zachklipp
│ └── richtext
│ └── ui
│ └── printing
│ ├── ComposePdfRenderer.kt
│ ├── ComposePrintAdapter.kt
│ ├── CoroutinePrintDocumentAdapter.kt
│ ├── Modifiers.kt
│ ├── Paged.kt
│ ├── Printable.kt
│ └── PrinterMetrics.kt
├── richtext-commonmark
├── build.gradle.kts
├── gradle.properties
└── src
│ ├── commonJvmAndroid
│ └── kotlin
│ │ └── com
│ │ └── halilibo
│ │ └── richtext
│ │ └── commonmark
│ │ └── AstNodeConvert.kt
│ ├── commonJvmAndroidTest
│ └── kotlin
│ │ └── com
│ │ └── halilibo
│ │ └── richtext
│ │ └── commonmark
│ │ └── AstNodeConvertKtTest.kt
│ └── commonMain
│ └── kotlin
│ └── com
│ └── halilibo
│ └── richtext
│ └── commonmark
│ ├── CommonMarkdownParseOptions.kt
│ ├── Markdown.kt
│ └── ParsedMarkdown.kt
├── richtext-markdown
├── build.gradle.kts
├── gradle.properties
└── src
│ ├── androidMain
│ ├── AndroidManifest.xml
│ └── kotlin
│ │ └── com
│ │ └── halilibo
│ │ └── richtext
│ │ └── markdown
│ │ ├── HtmlBlock.kt
│ │ └── RemoteImage.kt
│ ├── commonMain
│ └── kotlin
│ │ └── com
│ │ └── halilibo
│ │ └── richtext
│ │ └── markdown
│ │ ├── BasicMarkdown.kt
│ │ ├── HtmlBlock.kt
│ │ ├── MarkdownRichText.kt
│ │ ├── RemoteImage.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-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
├── richtext-ui
├── build.gradle.kts
├── gradle.properties
└── src
│ ├── androidMain
│ ├── AndroidManifest.xml
│ └── kotlin
│ │ └── com
│ │ └── halilibo
│ │ └── richtext
│ │ └── ui
│ │ └── CodeBlock.android.kt
│ ├── commonJvmAndroid
│ └── kotlin
│ │ └── com
│ │ └── halilibo
│ │ └── richtext
│ │ └── ui
│ │ └── util
│ │ └── UUID.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
│ │ ├── Table.kt
│ │ ├── TableLayout.kt
│ │ ├── TableMeasurer.kt
│ │ ├── string
│ │ ├── InlineContent.kt
│ │ ├── RichTextRenderOptions.kt
│ │ ├── RichTextString.kt
│ │ └── Text.kt
│ │ └── util
│ │ ├── AnnotatedStringSegmenter.kt
│ │ ├── ConditionalTapGestureDetector.kt
│ │ └── UUID.kt
│ └── jvmMain
│ └── kotlin
│ └── com
│ └── halilibo
│ └── richtext
│ └── ui
│ └── CodeBlock.desktop.kt
├── settings.gradle.kts
└── slideshow
├── api
└── slideshow.api
├── build.gradle.kts
├── consumer-rules.pro
├── gradle.properties
├── proguard-rules.pro
└── src
└── main
├── AndroidManifest.xml
└── java
└── com
└── zachklipp
└── richtext
└── ui
└── slideshow
├── BodySlide.kt
├── NavigableContent.kt
├── SlideScope.kt
├── Slideshow.kt
├── SlideshowTheme.kt
└── TitleSlide.kt
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: halilozercan
4 | # patreon: # Replace with a single Patreon username
5 | # open_collective: # Replace with a single Open Collective username
6 | # ko_fi: # Replace with a single Ko-fi username
7 | # tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | # community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | # liberapay: # Replace with a single Liberapay username
10 | # issuehunt: # Replace with a single IssueHunt username
11 | # otechie: # Replace with a single Otechie username
12 | # custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 |
--------------------------------------------------------------------------------
/.github/workflows/android.yml:
--------------------------------------------------------------------------------
1 | name: Android CI
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v2
13 | - uses: gradle/wrapper-validation-action@v1
14 | - name: set up JDK 17
15 | uses: actions/setup-java@v1
16 | with:
17 | java-version: 17
18 | - uses: actions/cache@v4
19 | with:
20 | path: ~/.gradle/caches
21 | key: gradle-${{ runner.os }}-${{ hashFiles('buildSrc/**') }}-${{ hashFiles('**/*.gradle*') }}
22 | restore-keys: gradle-${{ runner.os }}-
23 | - run: ./gradlew build
24 |
--------------------------------------------------------------------------------
/.github/workflows/docs.yml:
--------------------------------------------------------------------------------
1 | name: Doc Site
2 |
3 | on:
4 | release:
5 | # Build docs when a new release is created, so the API docs don't get out of date.
6 | types: [ published ]
7 | push:
8 | branches:
9 | # A specific branch to only update docs without going through a release cycle
10 | - docs
11 |
12 | jobs:
13 | deploy:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v2
17 | - uses: actions/setup-java@v1
18 | with:
19 | java-version: 17
20 | - uses: actions/setup-python@v2
21 | with:
22 | python-version: 3.x
23 | - name: Install dependencies
24 | run: pip install mkdocs-material
25 | - name: Generate docs
26 | run: ./gen_docs.sh
27 | - run: mkdocs gh-deploy --force
28 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish
2 |
3 | on:
4 | release:
5 | types: [released]
6 | workflow_dispatch:
7 |
8 | jobs:
9 | publish:
10 | name: Release build and publish
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v2
14 | - uses: gradle/wrapper-validation-action@v1
15 | - name: set up JDK 17
16 | uses: actions/setup-java@v1
17 | with:
18 | java-version: 17
19 | - uses: actions/cache@v4
20 | with:
21 | path: ~/.gradle/caches
22 | key: gradle-${{ runner.os }}-${{ hashFiles('buildSrc/**') }}-${{ hashFiles('**/*.gradle*') }}
23 | restore-keys: gradle-${{ runner.os }}-
24 | - name: Release build
25 | run: ./gradlew :build
26 | - name: Publish to MavenCentral
27 | run: ./gradlew publishAllPublicationsToMavenRepository
28 | env:
29 | GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
30 | GPG_PRIVATE_PASSWORD: ${{ secrets.GPG_PRIVATE_PASSWORD }}
31 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }}
32 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }}
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | /.idea/compiler.xml
11 | /.idea/deploymentTargetDropDown.xml
12 | /.idea/deploymentTargetSelector.xml
13 | /.idea/gradle.xml
14 | /.idea/kotlinc.xml
15 | /.idea/migrations.xml
16 | /.idea/misc.xml
17 | /.idea/artifacts
18 | /.idea/vcs.xml
19 | /.idea/other.xml
20 | .DS_Store
21 | build/
22 | /captures
23 | .externalNativeBuild
24 | .cxx
25 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Changelog
2 | =========
3 |
4 | v0.11.0
5 | ------
6 |
7 | _2022_02_09_
8 |
9 | * Upgrade Coil to 2.0.0-alpha06 by @msfjarvis in https://github.com/halilozercan/compose-richtext/pull/72
10 |
11 | ## New Contributors
12 | * @msfjarvis made their first contribution in https://github.com/halilozercan/compose-richtext/pull/72
13 |
14 | **Full Changelog**: https://github.com/halilozercan/compose-richtext/compare/v0.10.0...v0.11.0
15 |
16 | v0.10.0
17 | ------
18 |
19 | _2021_12_05_
20 |
21 | This release celebrates the release of Compose Multiplatform 1.0.0 🎉🥳
22 |
23 | v0.9.0
24 | ------
25 |
26 | _2021_11_20_
27 |
28 | This release is mostly a version bump.
29 | - Jetpack Compose: 1.1.0-beta03
30 | - Jetbrains Compose: 1.0.0-beta5
31 | - Kotlin: 1.5.31
32 |
33 | Other changes:
34 |
35 | * Fix link formatting in index page of docs by in https://github.com/halilozercan/compose-richtext/pull/60
36 | * CodeBlock fixes in https://github.com/halilozercan/compose-richtext/pull/62
37 | * Update CHANGELOG.md to include releases after the transfer in https://github.com/halilozercan/compose-richtext/pull/64
38 | * Add info panels similar to bootstrap alerts #54 in https://github.com/halilozercan/compose-richtext/pull/63
39 |
40 |
41 | **Full Changelog**: https://github.com/halilozercan/compose-richtext/compare/v0.8.1...v0.9.0
42 |
43 | v0.8.1
44 | ------
45 |
46 | _2021-9-11_
47 |
48 | This release fixes JVM artifact issue #59
49 |
50 | v0.8.0
51 | ------
52 |
53 | _2021-9-8_
54 |
55 | Compose Richtext goes KMP, opening RichText UI and its extensions to both Android and Desktop (#50)
56 |
57 | Special thanks @zach-klippenstein @LouisCAD @russhwolf for their reviews and help.
58 |
59 | * Richtext UI, Richtext UI Material, and RichText Commonmark are now KMP Compose libraries
60 | * Slideshow, Printing remains Android only for the foreseeable future
61 | * Updated docs
62 | * A new CI compatible release configuration
63 |
64 | v0.7.0
65 | ------
66 |
67 | _2021-9-1_
68 |
69 | * Improved markdown rendering for editor like environments (#46)
70 | * Finalized MaterialRichText API. (#47)
71 | * Move from BasicRichText/RichText to RichText/MaterialRichText + SetupMaterialRichText
72 | * Update docs accordingly
73 | * Cleaned RichTextString rendering from hacks that were left from earlier compose versions (#48)
74 |
75 | v0.6.0
76 | ------
77 |
78 | _2021-8-6_
79 |
80 | * RichText UI no longer depends on Material (#45)
81 | * A new artifact richtext-ui-material is published to easily integrate RichText for apps that use Material design.
82 | * Upgraded compose to 1.0.1 and kotlin to 1.5.21
83 |
84 | v0.5.0
85 | ------
86 |
87 | _2021-7-29_
88 |
89 | * **Compose 1.0.0 support** (#43)
90 | * Upgrade to Gradle 7.0.2 (#40)
91 | * Fix wrong word used. portrait -> landscape (#37 - thanks @LouisCAD)
92 | * Repository has migrated from @zach-klippenstein to @halilozercan.
93 | * Artifacts have moved from com.zachklipp.compose-richtext to com.halilibo.compose-richtext.
94 | * Similarly, documentation is also now available at halilibo.com/compose-richtext
95 |
96 | v0.3.0
97 | ------
98 |
99 | _2021-5-18_
100 |
101 | * **Compose Beta 7 support!** (#36)
102 | * Fix several bugs in Table, RichTextStyle and improve InlineContent (#35 – thanks @halilozercan!)
103 |
104 | v0.2.0
105 | ------
106 |
107 | _2021-2-27_
108 |
109 | * **Compose Beta 1 support!**
110 | * Remove BulletList styling for different leading characters - Update markdown-demo.png to show new
111 | BulletList rendering (#28 – thanks @halilozercan!)
112 |
113 | v0.1.0+alpha06
114 | --------------
115 |
116 | _2020-11-06_
117 |
118 | * Initial release.
119 |
120 | Thanks to @halilozercan for implementing Markdown support!
121 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # compose-richtext
2 |
3 | [](https://search.maven.org/search?q=g:%22com.halilibo.compose-richtext%22)
4 | [](https://www.apache.org/licenses/LICENSE-2.0)
5 |
6 | > **Warning**
7 | > 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.
8 |
9 | A collection of Compose libraries for working with rich text formatting and documents.
10 |
11 | Aside from `printing`, and `slideshow`, all modules are Kotlin Multiplatform Compose Libraries.
12 |
13 | This repo is currently very experimental and really just proofs-of-concept: there are no tests and some things
14 | might be broken or very non-performant.
15 |
16 | ----
17 |
18 | **Documentation is available at [halilibo.com/compose-richtext](https://halilibo.com/compose-richtext).**
19 |
20 | ----
21 |
22 | ```kotlin
23 | @Composable fun App() {
24 | val printController = rememberPrintableController()
25 |
26 | Printable(printController) {
27 | RichText(Modifier.background(color = Color.White)) {
28 | Heading(0, "Title")
29 | Text("Summary paragraph.")
30 |
31 | HorizontalRule()
32 |
33 | BlockQuote {
34 | Text("A wise person once said…")
35 | }
36 | }
37 | }
38 |
39 | Button(onClick = { printController.print("README") }) {
40 | Text("PRINT ME")
41 | }
42 | }
43 | ```
44 |
45 | ## License
46 | ```
47 | Copyright 2022 Halil Ozercan
48 |
49 | Licensed under the Apache License, Version 2.0 (the "License");
50 | you may not use this file except in compliance with the License.
51 | You may obtain a copy of the License at
52 |
53 | http://www.apache.org/licenses/LICENSE-2.0
54 |
55 | Unless required by applicable law or agreed to in writing, software
56 | distributed under the License is distributed on an "AS IS" BASIS,
57 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
58 | See the License for the specific language governing permissions and
59 | limitations under the License.
60 | ```
61 |
--------------------------------------------------------------------------------
/android-sample/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.application")
3 | kotlin("android")
4 | id("org.jetbrains.compose") version Compose.desktopVersion
5 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
6 | }
7 |
8 | android {
9 | namespace = "com.zachklipp.richtext.sample"
10 | compileSdk = AndroidConfiguration.compileSdk
11 |
12 | defaultConfig {
13 | minSdk = AndroidConfiguration.minSdk
14 | targetSdk = AndroidConfiguration.targetSdk
15 | }
16 |
17 | buildFeatures {
18 | compose = true
19 | }
20 |
21 | compileOptions {
22 | sourceCompatibility = JavaVersion.VERSION_11
23 | targetCompatibility = JavaVersion.VERSION_11
24 | }
25 | kotlinOptions {
26 | jvmTarget = "11"
27 | }
28 | }
29 |
30 | dependencies {
31 | implementation(project(":printing"))
32 | implementation(project(":richtext-commonmark"))
33 | implementation(project(":richtext-ui-material3"))
34 | implementation(project(":slideshow"))
35 | implementation(AndroidX.appcompat)
36 | implementation(Compose.activity)
37 | implementation(compose.foundation)
38 | implementation(compose.materialIconsExtended)
39 | implementation(compose.material3)
40 | implementation(compose.uiTooling)
41 | }
42 |
--------------------------------------------------------------------------------
/android-sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/android-sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
12 |
13 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/android-sample/src/main/java/com/zachklipp/richtext/sample/AnimationSample.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.sample
2 |
3 | import androidx.compose.foundation.layout.Box
4 | import androidx.compose.foundation.layout.Column
5 | import androidx.compose.foundation.layout.Row
6 | import androidx.compose.foundation.layout.padding
7 | import androidx.compose.foundation.rememberScrollState
8 | import androidx.compose.foundation.verticalScroll
9 | import androidx.compose.material3.Checkbox
10 | import androidx.compose.material3.Surface
11 | import androidx.compose.material3.Text
12 | import androidx.compose.runtime.Composable
13 | import androidx.compose.runtime.LaunchedEffect
14 | import androidx.compose.runtime.getValue
15 | import androidx.compose.runtime.mutableStateOf
16 | import androidx.compose.runtime.remember
17 | import androidx.compose.runtime.setValue
18 | import androidx.compose.ui.Alignment
19 | import androidx.compose.ui.Modifier
20 | import androidx.compose.ui.tooling.preview.Preview
21 | import androidx.compose.ui.unit.dp
22 | import com.halilibo.richtext.commonmark.Markdown
23 | import com.halilibo.richtext.ui.material3.RichText
24 | import com.halilibo.richtext.ui.string.RichTextRenderOptions
25 | import kotlinx.coroutines.delay
26 | import kotlin.random.Random
27 |
28 | @Preview
29 | @Composable private fun AnimatedRichTextSamplePreview() {
30 | AnimatedRichTextSample()
31 | }
32 |
33 | @Composable fun AnimatedRichTextSample() {
34 | var isChunked by remember { mutableStateOf(false) }
35 |
36 | SampleTheme {
37 | Surface {
38 | Column {
39 | Row(verticalAlignment = Alignment.CenterVertically) {
40 | Text(
41 | "Chunking",
42 | modifier = Modifier
43 | .weight(1f)
44 | .padding(16.dp),
45 | )
46 | Checkbox(isChunked, onCheckedChange = { isChunked = it })
47 | }
48 | Box(Modifier.verticalScroll(rememberScrollState()).padding(16.dp)) {
49 | if (!isChunked) {
50 | CompleteTextSample()
51 | } else {
52 | ChunkingTextSample()
53 | }
54 | }
55 | }
56 | }
57 | }
58 | }
59 |
60 | @Composable
61 | private fun CompleteTextSample() {
62 | val markdownOptions = remember {
63 | RichTextRenderOptions(
64 | animate = true,
65 | textFadeInMs = 500,
66 | delayMs = 70,
67 | debounceMs = 200,
68 | )
69 | }
70 |
71 | RichText {
72 | Markdown(
73 | SampleText,
74 | richtextRenderOptions = markdownOptions,
75 | )
76 | }
77 | }
78 |
79 | @Composable
80 | private fun ChunkingTextSample() {
81 | var currentText by remember { mutableStateOf("") }
82 | var isComplete by remember { mutableStateOf(false) }
83 |
84 | LaunchedEffect(Unit) {
85 | var remaining = SampleText
86 | while (remaining.isNotEmpty()) {
87 | delay(200L + Random.nextInt(500))
88 | val chunkLength = 10 + Random.nextInt(100)
89 | currentText += remaining.take(chunkLength)
90 | remaining = remaining.drop(chunkLength)
91 | }
92 | isComplete = true
93 | }
94 |
95 | val markdownOptions = remember(isComplete) {
96 | RichTextRenderOptions(
97 | animate = !isComplete,
98 | textFadeInMs = 500,
99 | delayMs = 70,
100 | debounceMs = 200,
101 | )
102 | }
103 |
104 | RichText {
105 | Markdown(
106 | currentText,
107 | richtextRenderOptions = markdownOptions,
108 | )
109 | }
110 | }
111 |
112 | private const val SampleText = """
113 | 1-The quick brown fox jumps over the lazy dog.
114 | 1-The quick brown fox jumps over the lazy dog.
115 | 1-The quick brown fox jumps over the lazy dog.
116 | 1-The quick brown fox jumps over the lazy dog.
117 | 1-The quick brown fox jumps over the lazy dog.
118 |
119 | * Formatted list 1
120 | * Formatted list 2
121 | * Sub bullet point
122 |
123 | # Header 1
124 | 2-The quick brown fox jumps over the lazy dog.
125 | The quick brown fox jumps over the lazy dog.
126 |
127 | | Column A | Column B |
128 | |----------|----------|
129 | | The quick brown fox jumps over the lazy dog. | The quick brown fox jumps over the lazy dog. |
130 |
131 | ##### Header 5
132 | 4-The quick brown fox jumps over the lazy dog.
133 | The quick brown fox jumps over the lazy dog.
134 | The quick brown fox jumps over the lazy dog.
135 | The quick brown fox **jumps over the lazy dog.**
136 | """
137 |
--------------------------------------------------------------------------------
/android-sample/src/main/java/com/zachklipp/richtext/sample/PagedSample.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.sample
2 |
3 | import androidx.compose.foundation.layout.Column
4 | import androidx.compose.foundation.layout.Row
5 | import androidx.compose.foundation.layout.fillMaxSize
6 | import androidx.compose.foundation.layout.fillMaxWidth
7 | import androidx.compose.foundation.layout.padding
8 | import androidx.compose.material3.Button
9 | import androidx.compose.material3.Checkbox
10 | import androidx.compose.material3.Text
11 | import androidx.compose.material3.TextButton
12 | import androidx.compose.runtime.Composable
13 | import androidx.compose.runtime.Stable
14 | import androidx.compose.runtime.getValue
15 | import androidx.compose.runtime.mutableStateOf
16 | import androidx.compose.runtime.remember
17 | import androidx.compose.runtime.setValue
18 | import androidx.compose.ui.Alignment
19 | import androidx.compose.ui.Modifier
20 | import androidx.compose.ui.draw.shadow
21 | import androidx.compose.ui.unit.dp
22 | import androidx.compose.ui.unit.sp
23 | import com.zachklipp.richtext.ui.printing.Paged
24 | import com.zachklipp.richtext.ui.printing.Printable
25 | import com.zachklipp.richtext.ui.printing.isBeingPrinted
26 | import com.zachklipp.richtext.ui.printing.rememberPrintableController
27 |
28 | /**
29 | * Demonstrates the [Paged] composable. Pages can be browsed in the sample, or printed, using the
30 | * [Printable] composable.
31 | */
32 | @Composable fun PagedSample() {
33 | val controller = rememberPrintableController()
34 | val state = remember { PagedScreenState() }
35 | Printable(controller, printBreakpoints = state.drawBreakpoints) {
36 | PagedScreen(state, doPrint = {
37 | controller.print("Document Sample")
38 | })
39 | }
40 | }
41 |
42 | @Stable
43 | private class PagedScreenState {
44 | var pageIndex by mutableStateOf(0)
45 | var pageCount by mutableStateOf(0)
46 | var clipPage by mutableStateOf(true)
47 | var drawBreakpoints by mutableStateOf(true)
48 | }
49 |
50 | @Composable private fun PagedScreen(
51 | state: PagedScreenState,
52 | doPrint: () -> Unit
53 | ) {
54 | Column(
55 | modifier = Modifier.fillMaxSize()
56 | ) {
57 | if (isBeingPrinted) {
58 | // Nested Paged composables aren't supported.
59 | PagedContent()
60 | } else {
61 | Row {
62 | Text("Page index: ${state.pageIndex + 1} / ${state.pageCount}")
63 | TextButton(onClick = { state.pageIndex-- }) {
64 | Text("-")
65 | }
66 | TextButton(onClick = { state.pageIndex++ }) {
67 | Text("+")
68 | }
69 | Button(onClick = { doPrint() }) {
70 | Text("Print")
71 | }
72 | }
73 |
74 | Row(verticalAlignment = Alignment.CenterVertically) {
75 | Checkbox(
76 | checked = state.clipPage,
77 | onCheckedChange = { state.clipPage = !state.clipPage })
78 | Text("Clip page bottom")
79 | }
80 |
81 | Row(verticalAlignment = Alignment.CenterVertically) {
82 | Checkbox(
83 | checked = state.drawBreakpoints,
84 | onCheckedChange = { state.drawBreakpoints = !state.drawBreakpoints })
85 | Text("Show Breakpoints")
86 | }
87 |
88 | Paged(
89 | pageIndex = state.pageIndex,
90 | onPageLayout = { state.pageCount = it },
91 | clipLastBreakpoint = state.clipPage,
92 | drawBreakpoints = state.drawBreakpoints,
93 | modifier = Modifier
94 | .weight(1f)
95 | .fillMaxWidth()
96 | .padding(4.dp)
97 | .shadow(1.dp)
98 | ) {
99 | PagedContent()
100 | }
101 | }
102 | }
103 | }
104 |
105 | @Composable private fun PagedContent() {
106 | Column {
107 | for (i in 0 until 20) {
108 | // Staggered, to demonstrate breakpoints on overlapping nodes.
109 | Row(verticalAlignment = Alignment.CenterVertically) {
110 | Column {
111 | Text("${i * 3}", fontSize = 32.sp)
112 | Text("${i * 3 + 2}", fontSize = 32.sp)
113 | }
114 | Text("${i * 3 + 1}", fontSize = 32.sp)
115 | }
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/android-sample/src/main/java/com/zachklipp/richtext/sample/RichTextSample.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.sample
2 |
3 | import androidx.annotation.IntRange
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.interaction.MutableInteractionSource
6 | import androidx.compose.foundation.layout.Arrangement
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.Row
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.foundation.rememberScrollState
11 | import androidx.compose.foundation.text.selection.SelectionContainer
12 | import androidx.compose.foundation.verticalScroll
13 | import androidx.compose.material3.Card
14 | import androidx.compose.material3.CardDefaults
15 | import androidx.compose.material3.Checkbox
16 | import androidx.compose.material3.ExperimentalMaterial3Api
17 | import androidx.compose.material3.Slider
18 | import androidx.compose.material3.SliderColors
19 | import androidx.compose.material3.SliderDefaults
20 | import androidx.compose.material3.Surface
21 | import androidx.compose.material3.Text
22 | import androidx.compose.material3.darkColorScheme
23 | import androidx.compose.material3.lightColorScheme
24 | import androidx.compose.runtime.Composable
25 | import androidx.compose.runtime.getValue
26 | import androidx.compose.runtime.mutableStateOf
27 | import androidx.compose.runtime.remember
28 | import androidx.compose.runtime.setValue
29 | import androidx.compose.ui.Alignment
30 | import androidx.compose.ui.Modifier
31 | import androidx.compose.ui.tooling.preview.Preview
32 | import androidx.compose.ui.unit.DpSize
33 | import androidx.compose.ui.unit.dp
34 | import androidx.compose.ui.unit.sp
35 | import com.halilibo.richtext.ui.RichTextStyle
36 | import com.halilibo.richtext.ui.resolveDefaults
37 |
38 | @Preview
39 | @Composable private fun RichTextSamplePreview() {
40 | RichTextSample()
41 | }
42 |
43 | @Composable fun RichTextSample() {
44 | var richTextStyle by remember { mutableStateOf(RichTextStyle().resolveDefaults()) }
45 | var isDarkModeEnabled by remember { mutableStateOf(false) }
46 |
47 | val colors = if (isDarkModeEnabled) darkColorScheme() else lightColorScheme()
48 |
49 | SampleTheme(colorScheme = colors) {
50 | Surface {
51 | Column {
52 | // Config
53 | Card(elevation = CardDefaults.elevatedCardElevation()) {
54 | Column {
55 | Row(
56 | Modifier
57 | .clickable(onClick = { isDarkModeEnabled = !isDarkModeEnabled })
58 | .padding(8.dp),
59 | horizontalArrangement = Arrangement.spacedBy(8.dp),
60 | verticalAlignment = Alignment.CenterVertically
61 | ) {
62 | Checkbox(
63 | checked = isDarkModeEnabled,
64 | onCheckedChange = { isDarkModeEnabled = it },
65 |
66 | )
67 | Text("Dark Mode")
68 | }
69 | RichTextStyleConfig(
70 | richTextStyle = richTextStyle,
71 | onChanged = { richTextStyle = it }
72 | )
73 | }
74 | }
75 |
76 | SelectionContainer {
77 | Column(Modifier.verticalScroll(rememberScrollState())) {
78 | RichTextDemo(style = richTextStyle)
79 | }
80 | }
81 | }
82 | }
83 | }
84 | }
85 |
86 | @Composable
87 | fun RichTextStyleConfig(
88 | richTextStyle: RichTextStyle,
89 | onChanged: (RichTextStyle) -> Unit
90 | ) {
91 | Text("Paragraph spacing: ${richTextStyle.paragraphSpacing}")
92 | SliderForHumans(
93 | value = richTextStyle.paragraphSpacing!!.value,
94 | valueRange = 0f..20f,
95 | onValueChange = {
96 | onChanged(richTextStyle.copy(paragraphSpacing = it.sp))
97 | }
98 | )
99 |
100 | Text("Table cell padding: ${richTextStyle.tableStyle!!.cellPadding}")
101 | SliderForHumans(
102 | value = richTextStyle.tableStyle!!.cellPadding!!.value,
103 | valueRange = 0f..20f,
104 | onValueChange = {
105 | onChanged(
106 | richTextStyle.copy(
107 | tableStyle = richTextStyle.tableStyle!!.copy(
108 | cellPadding = it.sp
109 | )
110 | )
111 | )
112 | }
113 | )
114 |
115 | Text("Table border width padding: ${richTextStyle.tableStyle!!.borderStrokeWidth!!}")
116 | SliderForHumans(
117 | value = richTextStyle.tableStyle!!.borderStrokeWidth!!,
118 | valueRange = 0f..20f,
119 | onValueChange = {
120 | onChanged(
121 | richTextStyle.copy(
122 | tableStyle = richTextStyle.tableStyle!!.copy(
123 | borderStrokeWidth = it
124 | )
125 | )
126 | )
127 | }
128 | )
129 | }
130 |
131 | @OptIn(ExperimentalMaterial3Api::class)
132 | @Composable
133 | fun SliderForHumans(
134 | value: Float,
135 | onValueChange: (Float) -> Unit,
136 | modifier: Modifier = Modifier,
137 | enabled: Boolean = true,
138 | valueRange: ClosedFloatingPointRange = 0f..1f,
139 | @IntRange(from = 0) steps: Int = 0,
140 | onValueChangeFinished: (() -> Unit)? = null,
141 | colors: SliderColors = SliderDefaults.colors(),
142 | interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
143 | ) {
144 | Slider(
145 | value = value,
146 | onValueChange = onValueChange,
147 | modifier = modifier,
148 | enabled = enabled,
149 | valueRange = valueRange,
150 | steps = steps,
151 | onValueChangeFinished = onValueChangeFinished,
152 | colors = colors,
153 | interactionSource = interactionSource,
154 | thumb = {
155 | SliderDefaults.Thumb(
156 | interactionSource = interactionSource,
157 | thumbSize = DpSize(4.dp, 20.dp)
158 | )
159 | }
160 | )
161 | }
--------------------------------------------------------------------------------
/android-sample/src/main/java/com/zachklipp/richtext/sample/SampleActivity.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.sample
2 |
3 | import android.os.Bundle
4 | import androidx.activity.compose.setContent
5 | import androidx.appcompat.app.AppCompatActivity
6 |
7 | class MainActivity : AppCompatActivity() {
8 |
9 | override fun onCreate(savedInstanceState: Bundle?) {
10 | super.onCreate(savedInstanceState)
11 | setContent {
12 | SampleLauncher()
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/android-sample/src/main/java/com/zachklipp/richtext/sample/SampleLauncher.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.sample
2 |
3 | import android.widget.FrameLayout
4 | import androidx.activity.compose.BackHandler
5 | import androidx.compose.animation.Crossfade
6 | import androidx.compose.foundation.clickable
7 | import androidx.compose.foundation.layout.aspectRatio
8 | import androidx.compose.foundation.layout.height
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.foundation.layout.size
11 | import androidx.compose.foundation.layout.width
12 | import androidx.compose.foundation.lazy.LazyColumn
13 | import androidx.compose.foundation.lazy.itemsIndexed
14 | import androidx.compose.material3.ExperimentalMaterial3Api
15 | import androidx.compose.material3.ListItem
16 | import androidx.compose.material3.Scaffold
17 | import androidx.compose.material3.Surface
18 | import androidx.compose.material3.Text
19 | import androidx.compose.material3.TopAppBar
20 | import androidx.compose.material3.darkColorScheme
21 | import androidx.compose.runtime.Composable
22 | import androidx.compose.runtime.CompositionLocalProvider
23 | import androidx.compose.runtime.getValue
24 | import androidx.compose.runtime.mutableStateOf
25 | import androidx.compose.runtime.remember
26 | import androidx.compose.runtime.setValue
27 | import androidx.compose.ui.Modifier
28 | import androidx.compose.ui.draw.clipToBounds
29 | import androidx.compose.ui.graphics.TransformOrigin
30 | import androidx.compose.ui.graphics.graphicsLayer
31 | import androidx.compose.ui.platform.LocalContext
32 | import androidx.compose.ui.platform.LocalView
33 | import androidx.compose.ui.tooling.preview.Preview
34 | import androidx.compose.ui.unit.dp
35 |
36 | private val Samples = listOf Unit>>(
37 | "RichText Demo" to @Composable { RichTextSample() },
38 | "Markdown Demo" to @Composable { MarkdownSample() },
39 | "Lazy Markdown Demo" to @Composable { LazyMarkdownSample() },
40 | "Pagination" to @Composable { PagedSample() },
41 | "Printable Document" to @Composable { DocumentSample() },
42 | "Slideshow" to @Composable { SlideshowSample() },
43 | "Text Animation" to @Composable { AnimatedRichTextSample() },
44 | )
45 |
46 | @Preview(showBackground = true)
47 | @Composable private fun SampleLauncherPreview() {
48 | SamplesListScreen(onSampleClicked = {})
49 | }
50 |
51 | @Composable fun SampleLauncher() {
52 | var currentSampleIndex: Int? by remember { mutableStateOf(null) }
53 |
54 | Crossfade(currentSampleIndex) { index ->
55 | if (index != null) {
56 | BackHandler(onBack = { currentSampleIndex = null })
57 | Samples[index].second()
58 | } else {
59 | SamplesListScreen(onSampleClicked = { currentSampleIndex = it })
60 | }
61 | }
62 | }
63 |
64 | @OptIn(ExperimentalMaterial3Api::class)
65 | @Composable private fun SamplesListScreen(onSampleClicked: (Int) -> Unit) {
66 | SampleTheme(colorScheme = darkColorScheme()) {
67 | Scaffold(
68 | topBar = {
69 | TopAppBar(title = { Text("Samples") })
70 | }
71 | ) { contentPadding ->
72 | LazyColumn(modifier = Modifier.padding(contentPadding)) {
73 | itemsIndexed(Samples) { index, (title, sampleContent) ->
74 | ListItem(
75 | headlineContent = { Text(title) },
76 | modifier = Modifier.clickable(onClick = { onSampleClicked(index) }),
77 | leadingContent = {
78 | // Slideshow tries to take over the screen through LocalView. It needs to be
79 | // overridden to prevent the launcher from going fullscreen.
80 | // Overriding the local view can't be done always, because it causes AndroidView
81 | // usages to crash.
82 | val overrideLocalView = (title == "Slideshow")
83 | SamplePreview(overrideLocalView = overrideLocalView, sampleContent)
84 | }
85 | )
86 | }
87 | }
88 | }
89 | }
90 | }
91 |
92 | @Composable private fun SamplePreview(
93 | overrideLocalView: Boolean,
94 | content: @Composable () -> Unit,
95 | ) {
96 | val localView = if (overrideLocalView) {
97 | val context = LocalContext.current
98 | remember { FrameLayout(context.applicationContext) }
99 | } else {
100 | LocalView.current
101 | }
102 | CompositionLocalProvider(LocalView provides localView) {
103 | ScreenPreview(
104 | Modifier
105 | .size(50.dp)
106 | .aspectRatio(1f)
107 | .clipToBounds()
108 | // "Zoom in" to the top-start corner to make the preview more legible.
109 | .graphicsLayer(
110 | scaleX = 1.5f, scaleY = 1.5f,
111 | transformOrigin = TransformOrigin(0f, 0f)
112 | ),
113 | ) {
114 | SampleTheme(colorScheme = darkColorScheme()) {
115 | Surface(content = content)
116 | }
117 | }
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/android-sample/src/main/java/com/zachklipp/richtext/sample/SampleTheme.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.sample
2 |
3 | import androidx.compose.material3.ColorScheme
4 | import androidx.compose.material3.LocalTextStyle
5 | import androidx.compose.material3.MaterialTheme
6 | import androidx.compose.material3.Shapes
7 | import androidx.compose.material3.Typography
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.runtime.CompositionLocalProvider
10 | import androidx.compose.ui.unit.TextUnit
11 |
12 | @Composable
13 | fun SampleTheme(
14 | colorScheme: ColorScheme = MaterialTheme.colorScheme,
15 | shapes: Shapes = MaterialTheme.shapes,
16 | typography: Typography = MaterialTheme.typography,
17 | content: @Composable () -> Unit
18 | ) {
19 | MaterialTheme(colorScheme, shapes, typography) {
20 | val textStyle = LocalTextStyle.current.copy(lineHeight = TextUnit.Unspecified)
21 | CompositionLocalProvider(LocalTextStyle provides textStyle) {
22 | content()
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/android-sample/src/main/java/com/zachklipp/richtext/sample/ScreenPreview.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("DEPRECATION")
2 |
3 | package com.zachklipp.richtext.sample
4 |
5 | import android.content.Context
6 | import android.content.Context.DISPLAY_SERVICE
7 | import android.content.Context.WINDOW_SERVICE
8 | import android.hardware.display.DisplayManager
9 | import android.hardware.display.DisplayManager.DisplayListener
10 | import android.os.Handler
11 | import android.os.Looper
12 | import android.util.DisplayMetrics
13 | import android.view.WindowManager
14 | import android.widget.FrameLayout
15 | import androidx.compose.foundation.layout.BoxWithConstraints
16 | import androidx.compose.foundation.layout.aspectRatio
17 | import androidx.compose.foundation.text.selection.DisableSelection
18 | import androidx.compose.runtime.Composable
19 | import androidx.compose.runtime.CompositionLocalProvider
20 | import androidx.compose.runtime.RememberObserver
21 | import androidx.compose.runtime.mutableStateOf
22 | import androidx.compose.runtime.remember
23 | import androidx.compose.ui.Modifier
24 | import androidx.compose.ui.input.pointer.PointerEvent
25 | import androidx.compose.ui.input.pointer.PointerEventPass
26 | import androidx.compose.ui.input.pointer.PointerEventPass.Initial
27 | import androidx.compose.ui.input.pointer.PointerInputFilter
28 | import androidx.compose.ui.input.pointer.PointerInputModifier
29 | import androidx.compose.ui.input.pointer.consumeAllChanges
30 | import androidx.compose.ui.platform.LocalContext
31 | import androidx.compose.ui.platform.LocalDensity
32 | import androidx.compose.ui.platform.LocalView
33 | import androidx.compose.ui.semantics.disabled
34 | import androidx.compose.ui.semantics.semantics
35 | import androidx.compose.ui.unit.Density
36 | import androidx.compose.ui.unit.IntSize
37 |
38 | /**
39 | * Displays [content] according to the current layout constraints, but with the density adjusted so
40 | * that the content things it's rendering inside a full-size screen, where "full-size" is defined
41 | * by [screenSize]. The default [screenSize] is read from the current window's default display.
42 | */
43 | // TODO Disable focus
44 | // TODO Disable key events (maybe covered by focus?)
45 | // TODO use this for Slideshow as well.
46 | @Composable fun ScreenPreview(
47 | modifier: Modifier = Modifier,
48 | screenSize: IntSize = rememberDefaultDisplaySize(),
49 | content: @Composable () -> Unit
50 | ) {
51 | val aspectRatio = screenSize.width.toFloat() / screenSize.height.toFloat()
52 | BoxWithConstraints(
53 | modifier
54 | .aspectRatio(aspectRatio)
55 | // Disable touch input.
56 | .then(PassthroughTouchToParentModifier)
57 | .semantics(mergeDescendants = true) {
58 | // TODO Block semantics. Is this enough?
59 | disabled()
60 | }
61 | ) {
62 | val actualDensity = LocalDensity.current.density
63 | // Can use width or height to do the calculation, since the aspect ratio is enforced.
64 | val previewDensityScale = constraints.maxWidth / screenSize.width.toFloat()
65 | val previewDensity = actualDensity * previewDensityScale
66 |
67 | DisableSelection {
68 | CompositionLocalProvider(
69 | LocalDensity provides Density(previewDensity),
70 | content = content
71 | )
72 | }
73 | }
74 | }
75 |
76 | /**
77 | * Returns the size of the default display for the window manager of the window this composable is
78 | * currently attached to. Will also recompose if the display size changes, e.g. when the device is
79 | * rotated.
80 | *
81 | * If the display reports an empty size (0x0), e.g. when running in a preview, then a reasonable
82 | * fake size of a phone display in portrait orientation is returned instead.
83 | */
84 | @Composable private fun rememberDefaultDisplaySize(): IntSize {
85 | val context = LocalContext.current
86 | val state = remember { DisplaySizeCalculator(context) }
87 | return state.displaySize.value
88 | }
89 |
90 | private class DisplaySizeCalculator(context: Context) : RememberObserver,
91 | DisplayListener {
92 | private val windowManager = context.getSystemService(WINDOW_SERVICE) as WindowManager
93 | private val displayManager = context.getSystemService(DISPLAY_SERVICE) as DisplayManager
94 | private val display = windowManager.defaultDisplay
95 |
96 | val displaySize = mutableStateOf(getDisplaySize())
97 |
98 | override fun onAbandoned() {
99 | // Noop
100 | }
101 |
102 | override fun onRemembered() {
103 | // Update the preview on device rotation, for example.
104 | displayManager.registerDisplayListener(this, Handler(Looper.getMainLooper()))
105 | }
106 |
107 | override fun onForgotten() {
108 | displayManager.unregisterDisplayListener(this)
109 | }
110 |
111 | override fun onDisplayChanged(displayId: Int) {
112 | if (displayId != display.displayId) return
113 | displaySize.value = getDisplaySize()
114 | }
115 |
116 | override fun onDisplayAdded(displayId: Int) = Unit
117 | override fun onDisplayRemoved(displayId: Int) = Unit
118 |
119 | private fun getDisplaySize(): IntSize {
120 | val metrics = DisplayMetrics().also(display::getMetrics)
121 | return if (metrics.widthPixels != 0 && metrics.heightPixels != 0) {
122 | IntSize(metrics.widthPixels, metrics.heightPixels)
123 | } else {
124 | // Zero-sized display? Probably in a preview. Return some fake reasonable default.
125 | IntSize(1080, 1920)
126 | }
127 | }
128 | }
129 |
130 | /**
131 | * A [PointerInputModifier] that blocks all touch events to children of the composable to which it's
132 | * applied, and instead allows all those events to flow to any filters defined on the parent
133 | * composable.
134 | */
135 | private object PassthroughTouchToParentModifier : PointerInputModifier, PointerInputFilter() {
136 | override val pointerInputFilter: PointerInputFilter get() = this
137 |
138 | override fun onPointerEvent(
139 | pointerEvent: PointerEvent,
140 | pass: PointerEventPass,
141 | bounds: IntSize
142 | ) {
143 | if (pass == Initial) {
144 | // On the initial pass (ancestors -> descendants), mark all pointer events as completely
145 | // consumed. This prevents children from handling any pointer events.
146 | // These events are all marked as unconsumed by default.
147 | pointerEvent.changes.forEach {
148 | it.consumeAllChanges()
149 | }
150 | }
151 | }
152 |
153 | override fun onCancel() {
154 | // Noop.
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/android-sample/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/android-sample/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/android-sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android-sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #eeeeee
4 | #111111
5 | #2079c7
6 |
7 |
--------------------------------------------------------------------------------
/android-sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Rich Text Sample
3 |
--------------------------------------------------------------------------------
/android-sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/buildSrc/build.gradle.kts:
--------------------------------------------------------------------------------
1 | repositories {
2 | google()
3 | mavenCentral()
4 | }
5 |
6 | plugins {
7 | `kotlin-dsl`
8 | `kotlin-dsl-precompiled-script-plugins`
9 | }
10 |
11 | dependencies {
12 | // keep in sync with Dependencies.BuildPlugins.androidGradlePlugin
13 | implementation("com.android.tools.build:gradle:8.7.0")
14 | // keep in sync with Dependencies.Kotlin.gradlePlugin
15 | implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21")
16 | implementation(kotlin("script-runtime"))
17 | }
--------------------------------------------------------------------------------
/buildSrc/src/main/kotlin/Dependencies.kt:
--------------------------------------------------------------------------------
1 | object BuildPlugins {
2 | // keep in sync with buildSrc/build.gradle.kts
3 | val androidGradlePlugin = "com.android.tools.build:gradle:8.7.0"
4 | }
5 |
6 | object AndroidX {
7 | val appcompat = "androidx.appcompat:appcompat:1.7.0"
8 | }
9 |
10 | object Network {
11 | val okHttp = "com.squareup.okhttp3:okhttp:4.9.0"
12 | }
13 |
14 | object Kotlin {
15 | // keep in sync with buildSrc/build.gradle.kts
16 | val version = "2.0.21"
17 | val binaryCompatibilityValidatorPlugin = "org.jetbrains.kotlinx:binary-compatibility-validator:0.9.0"
18 | val gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$version"
19 |
20 | object Test {
21 | val common = "org.jetbrains.kotlin:kotlin-test-common"
22 | val annotations = "org.jetbrains.kotlin:kotlin-test-annotations-common"
23 | val jdk = "org.jetbrains.kotlin:kotlin-test-junit"
24 | }
25 | }
26 |
27 | val ktlint = "org.jlleitschuh.gradle:ktlint-gradle:10.0.0"
28 |
29 | object Compose {
30 | val desktopVersion = "1.7.1"
31 | val activity = "androidx.activity:activity-compose:1.9.1"
32 | val toolingData = "androidx.compose.ui:ui-tooling-data:1.7.8"
33 | val coil = "io.coil-kt:coil-compose:2.5.0"
34 | }
35 |
36 | object Commonmark {
37 | private val version = "0.21.0"
38 | val core = "org.commonmark:commonmark:$version"
39 | val tables = "org.commonmark:commonmark-ext-gfm-tables:$version"
40 | val strikethrough = "org.commonmark:commonmark-ext-gfm-strikethrough:$version"
41 | val autolink = "org.commonmark:commonmark-ext-autolink:$version"
42 | }
43 |
44 | object AndroidConfiguration {
45 | val minSdk = 21
46 | val targetSdk = 34
47 | val compileSdk = targetSdk
48 | }
49 |
--------------------------------------------------------------------------------
/buildSrc/src/main/kotlin/richtext-android-library.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.library")
3 | kotlin("android")
4 | }
5 |
6 | kotlin {
7 | explicitApi()
8 | }
9 |
10 | android {
11 | compileSdk = AndroidConfiguration.compileSdk
12 |
13 | defaultConfig {
14 | minSdk = AndroidConfiguration.minSdk
15 | targetSdk = AndroidConfiguration.targetSdk
16 | }
17 |
18 | compileOptions {
19 | sourceCompatibility = JavaVersion.VERSION_11
20 | targetCompatibility = JavaVersion.VERSION_11
21 | }
22 | kotlinOptions {
23 | jvmTarget = "11"
24 | }
25 |
26 | buildFeatures {
27 | compose = true
28 | }
29 |
30 | publishing {
31 | singleVariant("release") {
32 | withSourcesJar()
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/buildSrc/src/main/kotlin/richtext-kmp-library.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.library")
3 | kotlin("multiplatform")
4 | id("maven-publish")
5 | id("signing")
6 | }
7 |
8 | repositories {
9 | google()
10 | mavenCentral()
11 | }
12 |
13 | kotlin {
14 | jvm()
15 | android {
16 | publishLibraryVariants("release")
17 | compilations.all {
18 | kotlinOptions.jvmTarget = "11"
19 | }
20 | }
21 | explicitApi()
22 | }
23 |
24 | android {
25 | compileSdk = 34
26 | sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
27 |
28 | compileOptions {
29 | sourceCompatibility = JavaVersion.VERSION_11
30 | targetCompatibility = JavaVersion.VERSION_11
31 | }
32 |
33 | defaultConfig {
34 | minSdk = 21
35 | targetSdk = compileSdk
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/desktop-sample/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.jetbrains.compose.desktop.application.dsl.TargetFormat
2 |
3 | plugins {
4 | kotlin("jvm")
5 | id("org.jetbrains.compose") version Compose.desktopVersion
6 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
7 | }
8 |
9 | dependencies {
10 | implementation(project(":richtext-commonmark"))
11 | implementation(project(":richtext-ui-material"))
12 | implementation(compose.desktop.currentOs)
13 | }
14 |
15 | compose.desktop {
16 | application {
17 | mainClass = "com.halilibo.richtext.desktop.MainKt"
18 | nativeDistributions {
19 | targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
20 | packageName = "jvm"
21 | packageVersion = "1.0.0"
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/docs/img/markdown-demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/docs/img/markdown-demo.png
--------------------------------------------------------------------------------
/docs/img/printing-demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/docs/img/printing-demo.gif
--------------------------------------------------------------------------------
/docs/img/richtext-demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/docs/img/richtext-demo.png
--------------------------------------------------------------------------------
/docs/img/slideshow-demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/docs/img/slideshow-demo.gif
--------------------------------------------------------------------------------
/docs/img/slideshow-scrubbing-demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/docs/img/slideshow-scrubbing-demo.gif
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | # Overview
2 |
3 | [](https://search.maven.org/search?q=g:%22com.halilibo.compose-richtext%22)
4 | [](https://www.apache.org/licenses/LICENSE-2.0)
5 |
6 | Compose Richtext is a collection of Compose libraries for working with rich text formatting and
7 | documents. It includes a full feature markdown rendering library that conforms to commonmark specification.
8 |
9 | `richtext-ui`, `richtext-markdown`, `richtext-commonmark`, and `richtext-ui-material`|`richtext-ui-material3` are Kotlin Multiplatform(KMP) Compose Libraries with the exception of iOS.
10 | All these modules can be used in Android and Desktop Compose apps.
11 |
12 | Each library is documented separately, see the navigation menu for the list. This site also includes
13 | an API reference.
14 |
15 | !!! warning
16 | 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.
17 | There are no tests and some things might be broken or very non-performant.
18 |
19 | The API may also change between releases without deprecation cycles.
20 |
21 | ## Getting started
22 |
23 | These libraries are published to Maven Central, so just add a Gradle dependency:
24 |
25 | ```kotlin
26 | dependencies {
27 | implementation("com.halilibo.compose-richtext::${richtext_version}")
28 | }
29 | ```
30 |
31 | There is no difference for KMP artifacts. For instance, if you are adding `richtext-ui` to a Kotlin Multiplatform module
32 |
33 | ```kotlin
34 | val commonMain by getting {
35 | dependencies {
36 | implementation("com.halilibo.compose-richtext:richtext-ui:${richtext_version}")
37 | }
38 | }
39 | ```
40 |
41 | ### Library Artifacts
42 |
43 | The `LIBRARY_ARTIFACT`s for each individual library can be found on their respective pages.
44 |
45 | ## Samples
46 |
47 | 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)
48 | projects to see various use cases of RichText in both platforms.
--------------------------------------------------------------------------------
/docs/printing.md:
--------------------------------------------------------------------------------
1 | # Printing (DEPRECATED)
2 |
3 | !!! warning
4 | This artifact is deprecated and will no longer be published. You can use the already published versions from maven central or just look at its implementation as
5 | a reference. If you would like to contribute and maintain this library, please reach out to us by creating an issue on Github.
6 |
7 | [](https://developer.android.com/studio/build/dependencies)
8 |
9 | A library for using Compose to generated printed documents, using Android's printing services.
10 |
11 | ## Gradle
12 |
13 | ```groovy
14 | dependencies {
15 | implementation "com.halilibo.compose-richtext:printing:${richtext_version}"
16 | }
17 | ```
18 |
19 | ## Usage
20 |
21 | There are multiple entry points into this library. See their kdoc for usage and parameter
22 | documentation, and take a look at the samples for example code.
23 |
24 | ### [`Printable`](../api/printing/com.zachklipp.richtext.ui.printing/-printable.html)
25 |
26 | This is the simplest entry point. It's a composable function that displays its children on screen,
27 | but can also print itself. Printing is triggered by the [`PrintableController`](../api/printing/com.zachklipp.richtext.ui.printing/-printable-controller/index.html)
28 | passed to `Printable`. `PrintableController` is a hoisted state type, just like `ScrollState`,
29 | created by calling `rememberPrintableController`.
30 |
31 | ```kotlin
32 | val printController = rememberPrintableController()
33 | Printable(printController) {
34 | ScrollableColumn {
35 | Card { … }
36 | Card { … }
37 | Button(onClick = { printController.print("sales report") }) { … }
38 | }
39 | }
40 | ```
41 |
42 | ### [`ComposePrintAdapter`](../api/printing/com.zachklipp.richtext.ui.printing/-compose-print-adapter/-compose-print-adapter.html)
43 |
44 | This is a [`PrintDocumentAdapter`](https://developer.android.com/reference/android/print/PrintDocumentAdapter)
45 | that can be used directly with Android's printing APIs to print any composable function. It takes,
46 | at minimum, the `ComponentActivity` that owns the print adapter (as required by Android's printing
47 | framework), a string name for the document, and the composable function that defines the content to
48 | print. See the linked API documentation for more details.
49 |
50 | ### [`Paged`](../api/printing/com.zachklipp.richtext.ui.printing/-paged.html)
51 |
52 | This is another composable, but doesn't actually have anything to do with printing.
53 | Conceptually it's similar to a `ScrollableColumn` – it lays its contents out at full height, then
54 | can display them at various vertical offsets. However, it also tries to ensure that no composables
55 | are clipped at the bottom, by measuring where all the leaf composables (those without any
56 | children) are located clipping the content before them. It is used by the printing APIs to try to
57 | ensure that composable content looks decent when split into printer pages.
58 |
59 | See the [`PagedSample`](https://github.com/halilozercan/compose-richtext/blob/main/sample/src/main/java/com/zachklipp/richtext/sample/PagedSample.kt)
60 | for more information.
61 |
62 | ## Demo
63 |
64 | The [`DocumentSample`](https://github.com/halilozercan/compose-richtext/blob/main/sample/src/main/java/com/zachklipp/richtext/sample/DocumentSample.kt)
65 | tries to match the style of one of the Google Docs templates. It looks great
66 | on small phone screens, but also prints:
67 |
68 | 
69 |
--------------------------------------------------------------------------------
/docs/richtext-commonmark.md:
--------------------------------------------------------------------------------
1 | # Commonmark Markdown
2 |
3 | [](https://developer.android.com/studio/build/dependencies)
4 | [](https://kotlinlang.org/docs/mpp-intro.html)
5 |
6 | Library for parsing and rendering Markdown in Compose using [CommonMark](https://github.com/commonmark/commonmark-java)
7 | library/spec to parse, and `richtext-markdown` to render.
8 |
9 | ## Gradle
10 |
11 | ```kotlin
12 | dependencies {
13 | implementation("com.halilibo.compose-richtext:richtext-commonmark:${richtext_version}")
14 | }
15 | ```
16 |
17 | ## Parsing
18 |
19 | `richtext-markdown` module renders a given Markdown Abstract Syntax Tree. It accepts a root
20 | `AstNode`. This library gives you a parser called `CommonmarkAstNodeParser` to easily convert any
21 | String to an `AstNode` that represents the Markdown tree.
22 |
23 | ```kotlin
24 | val parser = CommonmarkAstNodeParser()
25 | val astNode = parser.parse(
26 | """
27 | # Demo
28 |
29 | 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.
30 |
31 | 1. First ordered list item
32 | 2. Another item
33 | * Unordered sub-list.
34 | 3. And another item.
35 | 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).
36 |
37 | * Unordered list can use asterisks
38 | - Or minuses
39 | + Or pluses
40 | """.trimIndent()
41 | )
42 | // ...
43 |
44 | RichTextScope.BasicMarkdown(astNode)
45 | ```
46 |
47 | ## Rendering
48 |
49 | The simplest way to render markdown is just pass a string to the [`Markdown`](../api/richtext-commonmark/com.halilibo.richtext.markdown/-markdown.html)
50 | composable under RichText scope:
51 |
52 | ~~~kotlin
53 | RichText(
54 | modifier = Modifier.padding(16.dp)
55 | ) {
56 | Markdown(
57 | """
58 | # Demo
59 |
60 | 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.
61 |
62 | 1. First ordered list item
63 | 2. Another item
64 | * Unordered sub-list.
65 | 3. And another item.
66 | 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).
67 |
68 | * Unordered list can use asterisks
69 | - Or minuses
70 | + Or pluses
71 | ---
72 |
73 | ```javascript
74 | var s = "code blocks use monospace font";
75 | alert(s);
76 | ```
77 |
78 | Markdown | Table | Extension
79 | --- | --- | ---
80 | *renders* | `beautiful images` | 
81 | 1 | 2 | 3
82 |
83 | > Blockquotes are very handy in email to emulate reply text.
84 | > This line is part of the same quote.
85 | """.trimIndent()
86 | )
87 | }
88 | ~~~
89 |
90 | Which produces something like this:
91 |
92 | 
93 |
94 | ## [`MarkdownParseOptions`](../api/richtext-commonmark/com.halilibo.richtext.commonmark/-markdown-parse-options.html)
95 |
96 | Passing `MarkdownParseOptions` into either `Markdown` composable or `CommonmarkAstNodeParser.parse` method provides the ability to control some aspects of the markdown parser:
97 |
98 | ```kotlin
99 | val markdownParseOptions = MarkdownParseOptions(
100 | autolink = false
101 | )
102 |
103 | Markdown(
104 | markdownParseOptions = markdownParseOptions
105 | )
106 | ```
107 |
--------------------------------------------------------------------------------
/docs/richtext-markdown.md:
--------------------------------------------------------------------------------
1 | # Markdown
2 |
3 | [](https://developer.android.com/studio/build/dependencies)
4 | [](https://kotlinlang.org/docs/mpp-intro.html)
5 |
6 | Library for rendering Markdown tree that is defined as an `AstNode`. This module would be useless
7 | for someone who is looking to just render a Markdown string. Please check out
8 | `richtext-commonmark` for such features. `richtext-markdown` behaves as sort of a building block.
9 | You can create your own parser or use 3rd party ones that converts any Markdown string to an
10 | `AstNode` tree.
11 |
12 | ## Gradle
13 |
14 | ```kotlin
15 | dependencies {
16 | implementation("com.halilibo.compose-richtext:richtext-markdown:${richtext_version}")
17 | }
18 | ```
19 |
20 | ## Rendering
21 |
22 | The simplest way to render markdown is just pass an `AstNode` to the [`Markdown`](../api/richtext-commonmark/com.halilibo.richtext.markdown/-markdown.html)
23 | composable under RichText scope:
24 |
25 | ~~~kotlin
26 | RichText(
27 | modifier = Modifier.padding(16.dp)
28 | ) {
29 | // requires richtext-commonmark module.
30 | val parser = remember(options) { CommonmarkAstNodeParser(options) }
31 | val astNode = remember(parser) {
32 | parser.parse(
33 | """
34 | # Demo
35 |
36 | 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.
37 |
38 | 1. First ordered list item
39 | 2. Another item
40 | * Unordered sub-list.
41 | 3. And another item.
42 | 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).
43 |
44 | * Unordered list can use asterisks
45 | - Or minuses
46 | + Or pluses
47 | """.trimIndent()
48 | )
49 | }
50 | BasicMarkdown(astNode)
51 | }
52 | ~~~
53 |
--------------------------------------------------------------------------------
/docs/richtext-ui-material.md:
--------------------------------------------------------------------------------
1 | # Richtext UI Material
2 |
3 | [](https://developer.android.com/studio/build/dependencies)
4 | [](https://kotlinlang.org/docs/mpp-intro.html)
5 |
6 | Library that makes RichText compatible with Material design in Compose.
7 |
8 | ## Gradle
9 |
10 | ```kotlin
11 | dependencies {
12 | implementation("com.halilibo.compose-richtext:richtext-ui-material:${richtext_version}")
13 | }
14 | ```
15 |
16 | ## Usage
17 |
18 | Material RichText library provides a single composable called `RichText` which automatically passes
19 | down Material theming attributes to `BasicRichText`.
20 |
21 | ### [`RichText`](../api/richtext-ui-material/com.halilibo.richtext.ui.material/-rich-text.html)
22 |
23 | `RichText` composable wraps around regular `BasicRichText` while introducing the necessary integration
24 | dependencies. `RichText` shares the exact arguments with regular `BasicRichText`.
25 |
26 | ```kotlin
27 | RichText(modifier = Modifier.background(color = Color.White)) {
28 | Heading(0, "Paragraphs")
29 | Text("Simple paragraph.")
30 | ...
31 | }
32 | ```
33 |
--------------------------------------------------------------------------------
/docs/richtext-ui-material3.md:
--------------------------------------------------------------------------------
1 | # Richtext UI Material 3
2 |
3 | [](https://developer.android.com/studio/build/dependencies)
4 | [](https://kotlinlang.org/docs/mpp-intro.html)
5 |
6 | Library that makes RichText compatible with Material design in Compose.
7 |
8 | ## Gradle
9 |
10 | ```kotlin
11 | dependencies {
12 | implementation("com.halilibo.compose-richtext:richtext-ui-material3:${richtext_version}")
13 | }
14 | ```
15 |
16 | ## Usage
17 |
18 | Material3 RichText library provides a single composable called `RichText` which automatically passes
19 | down Material3 theming attributes to `BasicRichText`.
20 |
21 | ### [`RichText`](../api/richtext-ui-material/com.halilibo.richtext.ui.material3/-rich-text.html)
22 |
23 | `RichText` composable wraps around regular `BasicRichText` while introducing the necessary integration
24 | dependencies. `RichText` shares the exact arguments with regular `BasicRichText`.
25 |
26 | ```kotlin
27 | RichText(modifier = Modifier.background(color = Color.White)) {
28 | Heading(0, "Paragraphs")
29 | Text("Simple paragraph.")
30 | ...
31 | }
32 | ```
33 |
--------------------------------------------------------------------------------
/docs/richtext-ui.md:
--------------------------------------------------------------------------------
1 | # Richtext UI
2 |
3 | [](https://developer.android.com/studio/build/dependencies)
4 | [](https://kotlinlang.org/docs/mpp-intro.html)
5 |
6 | A library of composables for formatting text using higher-level concepts than are supported by
7 | compose foundation, such as "bullet lists" and "headings".
8 |
9 | RichText UI is a base library that is non-opinionated about higher level design requirements.
10 | If you are already using `MaterialTheme` in your compose app, you can jump to [RichText UI Material](../richtext-ui-material/index.html)
11 | for quick start. There is also Material3 flavor at [RichText UI Material3](../richtext-ui-material3/index.html)
12 |
13 | ## Gradle
14 |
15 | ```kotlin
16 | dependencies {
17 | implementation("com.halilibo.compose-richtext:richtext-ui:${richtext_version}")
18 | }
19 | ```
20 |
21 | ## [`BasicRichText`](../api/richtext-ui/com.halilibo.richtext.ui/-basic-rich-text.html)
22 |
23 | Richtext UI does not depend on Material artifact of Compose. Design agnostic API allows anyone
24 | to adopt RichText UI and its extensions like Markdown to their own design and typography systems.
25 | Hence, just like `foundation` and `material` modules of Compose, this library also names the
26 | building block with `Basic` prefix.
27 |
28 | If you are planning to adopt RichText within your design system, please go ahead and check out [`RichText Material`](../richtext-ui-material/index.html)
29 | for inspiration.
30 |
31 | ## [`RichTextScope`](../api/richtext-ui/com.halilibo.richtext.ui/-rich-text-scope/index.html)
32 |
33 | `RichTextScope` is a context wrapper around composables that integrate and play well within RichText
34 | content.
35 |
36 | ## [`RichTextThemeProvider`](../api/richtext-ui/com.halilibo.richtext.ui/-rich-text-theme-provider.html)
37 |
38 | Entry point for integrating app's own typography and theme system with BasicRichText.
39 |
40 | API for this integration is highly influenced by how compose-material theming
41 | is designed. RichText library assumes that almost all Theme/Design systems would
42 | have composition locals that provide a TextStyle downstream.
43 |
44 | Moreover, text style should not include text color by best practice. Content color
45 | exists to figure out text color in the current context. Light/Dark theming leverages content
46 | color to influence not just text but other parts of theming as well.
47 |
48 | ## Example
49 |
50 | Open the `Demo.kt` file in the `sample` module to play with this. Although the mentioned demo
51 | uses Material integrated version of `RichText`, they share exactly the same API.
52 |
53 | ```kotlin
54 | BasicRichText(
55 | modifier = Modifier.background(color = Color.White)
56 | ) {
57 | Heading(0, "Paragraphs")
58 | Text("Simple paragraph.")
59 | Text("Paragraph with\nmultiple lines.")
60 | Text("Paragraph with really long line that should be getting wrapped.")
61 |
62 | Heading(0, "Lists")
63 | Heading(1, "Unordered")
64 | ListDemo(listType = Unordered)
65 | Heading(1, "Ordered")
66 | ListDemo(listType = Ordered)
67 |
68 | Heading(0, "Horizontal Line")
69 | Text("Above line")
70 | HorizontalRule()
71 | Text("Below line")
72 |
73 | Heading(0, "Code Block")
74 | CodeBlock(
75 | """
76 | {
77 | "Hello": "world!"
78 | }
79 | """.trimIndent()
80 | )
81 |
82 | Heading(0, "Block Quote")
83 | BlockQuote {
84 | Text("These paragraphs are quoted.")
85 | Text("More text.")
86 | BlockQuote {
87 | Text("Nested block quote.")
88 | }
89 | }
90 |
91 | Heading(0, "Info Panel")
92 | InfoPanel(InfoPanelType.Primary, "Only text primary info panel")
93 | InfoPanel(InfoPanelType.Success) {
94 | Column {
95 | Text("Successfully sent some data")
96 | HorizontalRule()
97 | BlockQuote {
98 | Text("This is a quote")
99 | }
100 | }
101 | }
102 |
103 | Heading(0, "Table")
104 | Table(headerRow = {
105 | cell { Text("Column 1") }
106 | cell { Text("Column 2") }
107 | }) {
108 | row {
109 | cell { Text("Hello") }
110 | cell {
111 | CodeBlock("Foo bar")
112 | }
113 | }
114 | row {
115 | cell {
116 | BlockQuote {
117 | Text("Stuff")
118 | }
119 | }
120 | cell { Text("Hello world this is a really long line that is going to wrap hopefully") }
121 | }
122 | }
123 | }
124 | ```
125 |
126 | Looks like this:
127 |
128 | 
129 |
--------------------------------------------------------------------------------
/docs/slideshow.md:
--------------------------------------------------------------------------------
1 | # Slideshow (DEPRECATED)
2 |
3 | !!! warning
4 | This artifact is deprecated and will no longer be published. You can use the already published versions from maven central or just look at its implementation as
5 | a reference. If you would like to contribute and maintain this library, please reach out to us by creating an issue on Github.
6 |
7 | [](https://developer.android.com/studio/build/dependencies)
8 |
9 | A library for presenting simple Powerpoint-like slideshows from a phone (e.g. you can share your
10 | phone screen to a Google Hangout and present that way). Slides can contain any composable content,
11 | although a few pre-fab scaffolds are provided for common slide layouts.
12 |
13 | 
14 |
15 | ## Gradle
16 |
17 | ```groovy
18 | dependencies {
19 | implementation "com.halilibo.compose-richtext:slideshow:${richtext_version}"
20 | }
21 | ```
22 |
23 | ## Setting up a slideshow
24 |
25 | There is a single, simple entry point to this library, that takes a vararg of composable functions
26 | that define your slides:
27 |
28 | ```kotlin
29 | Slideshow(
30 | { /* First slide. */ },
31 | { /* Second slide. */ },
32 | { /* etc… */ },
33 | )
34 | ```
35 |
36 | The `Slideshow` composable will automatically lock your phone to landscape and enter immersive
37 | fullscreen while it's composed. You can tap anywhere on the left or right of the screen to navigate.
38 | Currently the only supported slide transition is crossfade, but it shouldn't be hard to make the
39 | library more pluggable and support more advanced transition libraries (like
40 | [this one](https://github.com/zach-klippenstein/compose-backstack)).
41 |
42 | ## Creating slides
43 |
44 | Individual slides are centered by default, but you can put whatever you want in them. The library
45 | has a few scaffolds for common slide layouts that you might find useful.
46 |
47 | ### `TitleSlide`
48 |
49 | Very simple: a title and a subtitle, centered.
50 |
51 | ```kotlin
52 | Slideshow(
53 | {
54 | TitleSlide(
55 | title = { Text("Title") },
56 | subtitle = { Text("Subtitle") },
57 | )
58 | },
59 | )
60 | ```
61 |
62 | ### `BodySlide`
63 |
64 | The `BodySlide` composable gives you a top header, bottom footer, and middle body slot to put
65 | stuff into.
66 |
67 | ```kotlin
68 | Slideshow(
69 | { … },
70 | {
71 | BodySlide(
72 | header = { Text("Header") },
73 | footer = { Text("Footer") },
74 | body = {
75 | WebComponent(…)
76 | // or something
77 | },
78 | )
79 | },
80 | )
81 | ```
82 |
83 | Slide scaffolds like `BodySlide` and `TitleSlide`, as well as some other aspects of slideshow
84 | formatting like background color, are controlled by passing a `SlideshowTheme` to the `Slideshow`
85 | composable.
86 |
87 | ### Animating content on a single slide
88 |
89 | A corporate presentation wouldn't be a presentation without obtuse visual effects. The
90 | `NavigableContentContainer` composable is a flexible primitive for building such effects. It takes
91 | a slot inside of which `NavigableContent` composables define blocks of content that will be
92 | shown or hidden by slide navigation. Each `NavigableContent` block gets a `State`
93 | indicating whether content should be shown or not, and is free to show or hide content however it
94 | likes. For example, Compose comes with the `AnimatedVisibility` composable out of the box, which
95 | plays very nicely with this API. See the `SlideshowSample` to see it in action.
96 |
97 | ```kotlin
98 | NavigableContentContainer {
99 | Column {
100 | // Show this right away.
101 | Text("First paragraph")
102 |
103 | // Only show this after tapping to advance the show, then fade it in.
104 | NavigableContent { visible ->
105 | val opacity = animate(if (visible) 1f else 0f)
106 | Text("Second paragraph", Modifier.drawOpacity(opacity))
107 | }
108 | }
109 | }
110 | ```
111 |
112 | ## Running the show
113 |
114 | If you're in the middle of a presentation and lose your place, just drag up anywhere on the screen.
115 | A slider and preview will pop up to let you scrub through the deck.
116 |
117 | 
118 |
--------------------------------------------------------------------------------
/gen_docs.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2021 The Android Open Source Project
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License");
6 | # you may not use this file except in compliance with the License.
7 | # You may obtain a copy of the License at
8 | #
9 | # https://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing, software
12 | # distributed under the License is distributed on an "AS IS" BASIS,
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | # See the License for the specific language governing permissions and
15 | # limitations under the License.
16 |
17 | # Fail on any error
18 | set -ex
19 |
20 | DOCS_ROOT=docs-gen
21 |
22 | [ -d $DOCS_ROOT ] && rm -r $DOCS_ROOT
23 | mkdir $DOCS_ROOT
24 |
25 | # Clear out the old API docs
26 | [ -d docs/api ] && rm -r docs/api
27 | # Build the docs with dokka
28 | ./gradlew dokkaHtmlMultiModule --stacktrace
29 |
30 | # Create a copy of our docs at our $DOCS_ROOT
31 | cp -a docs/* $DOCS_ROOT
32 |
33 | # Convert docs/xxx.md links to just xxx/
34 | sed -i.bak 's/docs\/\([a-zA-Z-]*\).md/\1/' $DOCS_ROOT/index.md
35 |
36 | # Finally delete all of the backup files
37 | find . -name '*.bak' -delete
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=768m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 |
21 | # Required to publish to Nexus (see https://github.com/gradle/gradle/issues/11308)
22 | systemProp.org.gradle.internal.publish.checksums.insecure=true
23 |
24 | GROUP=com.halilibo.compose-richtext
25 | VERSION_NAME=1.0.0-alpha02
26 |
27 | POM_DESCRIPTION=A collection of Compose libraries for advanced text formatting and alternative display types.
28 |
29 | kotlin.mpp.stability.nowarn=true
30 | kotlin.mpp.androidSourceSetLayoutVersion=2
31 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 | @rem SPDX-License-Identifier: Apache-2.0
17 | @rem
18 |
19 | @if "%DEBUG%"=="" @echo off
20 | @rem ##########################################################################
21 | @rem
22 | @rem Gradle startup script for Windows
23 | @rem
24 | @rem ##########################################################################
25 |
26 | @rem Set local scope for the variables with windows NT shell
27 | if "%OS%"=="Windows_NT" setlocal
28 |
29 | set DIRNAME=%~dp0
30 | if "%DIRNAME%"=="" set DIRNAME=.
31 | @rem This is normally unused
32 | set APP_BASE_NAME=%~n0
33 | set APP_HOME=%DIRNAME%
34 |
35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
37 |
38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
40 |
41 | @rem Find java.exe
42 | if defined JAVA_HOME goto findJavaFromJavaHome
43 |
44 | set JAVA_EXE=java.exe
45 | %JAVA_EXE% -version >NUL 2>&1
46 | if %ERRORLEVEL% equ 0 goto execute
47 |
48 | echo. 1>&2
49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
50 | echo. 1>&2
51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
52 | echo location of your Java installation. 1>&2
53 |
54 | goto fail
55 |
56 | :findJavaFromJavaHome
57 | set JAVA_HOME=%JAVA_HOME:"=%
58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
59 |
60 | if exist "%JAVA_EXE%" goto execute
61 |
62 | echo. 1>&2
63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
64 | echo. 1>&2
65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
66 | echo location of your Java installation. 1>&2
67 |
68 | goto fail
69 |
70 | :execute
71 | @rem Setup the command line
72 |
73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
74 |
75 |
76 | @rem Execute Gradle
77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
78 |
79 | :end
80 | @rem End local scope for the variables with windows NT shell
81 | if %ERRORLEVEL% equ 0 goto mainEnd
82 |
83 | :fail
84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
85 | rem the _cmd.exe /c_ return code!
86 | set EXIT_CODE=%ERRORLEVEL%
87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
89 | exit /b %EXIT_CODE%
90 |
91 | :mainEnd
92 | if "%OS%"=="Windows_NT" endlocal
93 |
94 | :omega
95 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk17
3 | before_install:
4 | - sdk install java 17.0.1-open
5 | - sdk use java 17.0.1-open
6 | env:
7 | GRADLE_OPTS: "-Dorg.gradle.configuration-cache=true"
8 |
--------------------------------------------------------------------------------
/mkdocs.yml:
--------------------------------------------------------------------------------
1 | site_name: Compose Richtext
2 | repo_name: compose-richtext
3 | repo_url: https://github.com/halilozercan/compose-richtext
4 | site_description: "A collection of Compose libraries for advanced text formatting and alternative display types."
5 | site_author: Halil Ozercan
6 | site_url: https://halilibo.com/compose-richtext
7 | remote_branch: gh-pages
8 | edit_uri: edit/main/docs/
9 |
10 | docs_dir: docs-gen
11 |
12 | theme:
13 | name: material
14 | icon:
15 | repo: fontawesome/brands/github
16 | features:
17 | - navigation.instant
18 | - toc.autohide
19 |
20 | markdown_extensions:
21 | - toc:
22 | permalink: true
23 | - pymdownx.superfences
24 | - pymdownx.tabbed
25 | - admonition
26 |
27 | nav:
28 | - index.md
29 | - richtext-ui-material.md
30 | - richtext-ui-material3.md
31 | - richtext-ui.md
32 | - richtext-markdown.md
33 | - richtext-commonmark.md
34 | - printing.md
35 | - slideshow.md
36 | - 'API Reference': api/
37 | - Changelog: https://github.com/halilozercan/compose-richtext/releases
38 |
--------------------------------------------------------------------------------
/printing/api/printing.api:
--------------------------------------------------------------------------------
1 | public final class com/zachklipp/richtext/printing/BuildConfig {
2 | public static final field BUILD_TYPE Ljava/lang/String;
3 | public static final field DEBUG Z
4 | public static final field LIBRARY_PACKAGE_NAME Ljava/lang/String;
5 | public fun ()V
6 | }
7 |
8 | public final class com/zachklipp/richtext/ui/printing/ComposableSingletons$ComposePdfRendererKt {
9 | public static final field INSTANCE Lcom/zachklipp/richtext/ui/printing/ComposableSingletons$ComposePdfRendererKt;
10 | public static field lambda-1 Lkotlin/jvm/functions/Function2;
11 | public fun ()V
12 | public final fun getLambda-1$printing_release ()Lkotlin/jvm/functions/Function2;
13 | }
14 |
15 | public final class com/zachklipp/richtext/ui/printing/ComposableSingletons$PagedKt {
16 | public static final field INSTANCE Lcom/zachklipp/richtext/ui/printing/ComposableSingletons$PagedKt;
17 | public static field lambda-1 Lkotlin/jvm/functions/Function2;
18 | public static field lambda-2 Lkotlin/jvm/functions/Function2;
19 | public fun ()V
20 | public final fun getLambda-1$printing_release ()Lkotlin/jvm/functions/Function2;
21 | public final fun getLambda-2$printing_release ()Lkotlin/jvm/functions/Function2;
22 | }
23 |
24 | public final class com/zachklipp/richtext/ui/printing/ComposePrintAdapter : com/zachklipp/richtext/ui/printing/CoroutinePrintDocumentAdapter {
25 | public static final field $stable I
26 | public fun (Landroidx/activity/ComponentActivity;Ljava/lang/String;Landroidx/compose/ui/Modifier;IZLkotlin/coroutines/CoroutineContext;Lkotlinx/coroutines/CoroutineDispatcher;Lkotlin/jvm/functions/Function2;)V
27 | public synthetic fun (Landroidx/activity/ComponentActivity;Ljava/lang/String;Landroidx/compose/ui/Modifier;IZLkotlin/coroutines/CoroutineContext;Lkotlinx/coroutines/CoroutineDispatcher;Lkotlin/jvm/functions/Function2;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
28 | public fun onLayout (Landroid/print/PrintAttributes;Landroid/print/PrintAttributes;Landroid/os/Bundle;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
29 | public fun onWrite ([Landroid/print/PageRange;Landroid/os/ParcelFileDescriptor;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
30 | }
31 |
32 | public abstract class com/zachklipp/richtext/ui/printing/CoroutinePrintDocumentAdapter : android/print/PrintDocumentAdapter {
33 | public static final field $stable I
34 | public fun (Lkotlin/coroutines/CoroutineContext;)V
35 | public fun onFinish ()V
36 | public abstract fun onLayout (Landroid/print/PrintAttributes;Landroid/print/PrintAttributes;Landroid/os/Bundle;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
37 | public final fun onLayout (Landroid/print/PrintAttributes;Landroid/print/PrintAttributes;Landroid/os/CancellationSignal;Landroid/print/PrintDocumentAdapter$LayoutResultCallback;Landroid/os/Bundle;)V
38 | public final fun onWrite ([Landroid/print/PageRange;Landroid/os/ParcelFileDescriptor;Landroid/os/CancellationSignal;Landroid/print/PrintDocumentAdapter$WriteResultCallback;)V
39 | public abstract fun onWrite ([Landroid/print/PageRange;Landroid/os/ParcelFileDescriptor;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
40 | }
41 |
42 | public final class com/zachklipp/richtext/ui/printing/ModifiersKt {
43 | public static final fun responsivePadding (Landroidx/compose/ui/Modifier;[Lkotlin/Pair;)Landroidx/compose/ui/Modifier;
44 | }
45 |
46 | public final class com/zachklipp/richtext/ui/printing/PageBreakpoint {
47 | public fun (Lkotlin/Pair;IZ)V
48 | public final fun component1 ()Lkotlin/Pair;
49 | public final fun component2 ()I
50 | public final fun component3 ()Z
51 | public final fun copy (Lkotlin/Pair;IZ)Lcom/zachklipp/richtext/ui/printing/PageBreakpoint;
52 | public static synthetic fun copy$default (Lcom/zachklipp/richtext/ui/printing/PageBreakpoint;Lkotlin/Pair;IZILjava/lang/Object;)Lcom/zachklipp/richtext/ui/printing/PageBreakpoint;
53 | public fun equals (Ljava/lang/Object;)Z
54 | public final fun getForceBreak ()Z
55 | public final fun getXAnchorPx ()Lkotlin/Pair;
56 | public final fun getYPx ()I
57 | public fun hashCode ()I
58 | public fun toString ()Ljava/lang/String;
59 | }
60 |
61 | public abstract interface class com/zachklipp/richtext/ui/printing/PageLayoutResult {
62 | public abstract fun getBreakpoints ()Ljava/util/List;
63 | public abstract fun getPageOffsetsPx ()Ljava/util/List;
64 | public abstract fun getPageSizePx-YbymL2g ()J
65 | public abstract fun nextPageOffsetPx (I)Ljava/lang/Integer;
66 | }
67 |
68 | public final class com/zachklipp/richtext/ui/printing/PagedKt {
69 | public static final fun Paged (Landroidx/compose/ui/Modifier;ILandroidx/compose/ui/Modifier;ZZLkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Landroidx/compose/runtime/Composer;II)V
70 | public static final fun keepOnPageWithNext (Landroidx/compose/ui/Modifier;)Landroidx/compose/ui/Modifier;
71 | }
72 |
73 | public abstract class com/zachklipp/richtext/ui/printing/PrintableController {
74 | public static final field $stable I
75 | public fun ()V
76 | protected abstract fun doPrint (Ljava/lang/String;Ljava/lang/String;Landroidx/compose/ui/Modifier;IZLkotlin/jvm/functions/Function2;)V
77 | public final fun print (Ljava/lang/String;Ljava/lang/String;)V
78 | public static synthetic fun print$default (Lcom/zachklipp/richtext/ui/printing/PrintableController;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)V
79 | }
80 |
81 | public final class com/zachklipp/richtext/ui/printing/PrintableKt {
82 | public static final fun Printable (Lcom/zachklipp/richtext/ui/printing/PrintableController;Landroidx/compose/ui/Modifier;IZLkotlin/jvm/functions/Function2;Landroidx/compose/runtime/Composer;II)V
83 | public static final fun hideWhenPrinting (Landroidx/compose/ui/Modifier;)Landroidx/compose/ui/Modifier;
84 | public static final fun isBeingPrinted (Landroidx/compose/runtime/Composer;I)Z
85 | public static final fun rememberPrintableController (Landroidx/compose/runtime/Composer;I)Lcom/zachklipp/richtext/ui/printing/PrintableController;
86 | }
87 |
88 | public final class com/zachklipp/richtext/ui/printing/PrinterMetricsKt {
89 | public static final field DefaultPageDpi I
90 | }
91 |
92 |
--------------------------------------------------------------------------------
/printing/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("richtext-android-library")
3 | id("org.jetbrains.dokka")
4 | id("org.jetbrains.compose") version Compose.desktopVersion
5 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
6 | }
7 |
8 | android {
9 | namespace = "com.zachklipp.richtext.ui.printing"
10 | }
11 |
12 | dependencies {
13 | implementation(compose.foundation)
14 | implementation(compose.uiTooling)
15 | // For slot table analysis.
16 | implementation(Compose.toolingData)
17 | implementation(Compose.activity)
18 |
19 | // TODO Migrate off this.
20 | implementation(compose.material)
21 | }
22 |
23 | tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile::class.java).all {
24 | kotlinOptions {
25 | freeCompilerArgs = freeCompilerArgs + "-Xinline-classes"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/printing/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/printing/consumer-rules.pro
--------------------------------------------------------------------------------
/printing/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Compose Printing
2 | POM_DESCRIPTION=A library for rendering Composables to Android printers.
--------------------------------------------------------------------------------
/printing/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/printing/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/printing/src/main/java/com/zachklipp/richtext/ui/printing/ComposePrintAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.ui.printing
2 |
3 | import android.os.Bundle
4 | import android.os.ParcelFileDescriptor
5 | import android.print.PageRange
6 | import android.print.PrintAttributes
7 | import android.print.PrintDocumentInfo
8 | import android.print.PrintDocumentInfo.CONTENT_TYPE_DOCUMENT
9 | import android.print.pdf.PrintedPdfDocument
10 | import androidx.activity.ComponentActivity
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.getValue
13 | import androidx.compose.runtime.mutableStateOf
14 | import androidx.compose.runtime.setValue
15 | import androidx.compose.ui.Modifier
16 | import kotlinx.coroutines.CompletableDeferred
17 | import kotlinx.coroutines.CoroutineDispatcher
18 | import kotlinx.coroutines.Dispatchers
19 | import kotlinx.coroutines.withContext
20 | import kotlinx.coroutines.yield
21 | import java.io.FileOutputStream
22 | import kotlin.coroutines.CoroutineContext
23 |
24 | /**
25 | * A [PrintDocumentAdapter][android.print.PrintDocumentAdapter] that prints a composable function.
26 | * The composable content is paginated as best-effort to avoid cutting off composables in the
27 | * middle (see [Paged]).
28 | *
29 | * Long blocks of text and subcompositions are not fully supported: the paginator will try to not
30 | * split them, but if they don't fit on a page, they will be split arbitrarily.
31 | *
32 | * See [composeToPdf] for details on how the composable is actually written to the PDF.
33 | *
34 | * @param activity The [ComponentActivity] used to create various printing resources.
35 | * @param documentName The file name that will be reported to the printing system, e.g. to use as
36 | * the default for the Save to PDF virtual printer.
37 | * @param pageModifier A [Modifier] that will be applied to each individual page of the printed
38 | * content. [responsivePadding] is a good choice.
39 | * @param pageDpi The resolution to use for the `Density` of the composable.
40 | * @param printBreakpoints If true, horizontal lines are drawn at each breakpoint for debugging.
41 | * False by default.
42 | * @param mainContext The [CoroutineContext] to interact with the composable and view system on.
43 | */
44 | public class ComposePrintAdapter(
45 | private val activity: ComponentActivity,
46 | private val documentName: String,
47 | private val pageModifier: Modifier = Modifier,
48 | private val pageDpi: Int = DefaultPageDpi,
49 | private val printBreakpoints: Boolean = false,
50 | mainContext: CoroutineContext = Dispatchers.Main,
51 | private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
52 | private val content: @Composable () -> Unit
53 | ) : CoroutinePrintDocumentAdapter(mainContext) {
54 |
55 | private lateinit var pdfDocument: PrintedPdfDocument
56 |
57 | override suspend fun onLayout(
58 | oldAttributes: PrintAttributes?,
59 | newAttributes: PrintAttributes,
60 | extras: Bundle?
61 | ): PrintDocumentInfo {
62 | pdfDocument = PrintedPdfDocument(activity, newAttributes)
63 |
64 | // Don't bother trying to calculate the page count. The print manager will automatically get
65 | // the count from the initial preview.
66 | return PrintDocumentInfo.Builder(documentName)
67 | .setContentType(CONTENT_TYPE_DOCUMENT)
68 | .build()
69 | }
70 |
71 | override suspend fun onWrite(
72 | pages: Array,
73 | destination: ParcelFileDescriptor
74 | ): Array {
75 | var currentPageIndex by mutableStateOf(0)
76 | val pageCountDeferred = CompletableDeferred()
77 |
78 | // Initialize the composition, and reuse the same composition to render all the pages.
79 | composeToPdf(activity, pdfDocument, pageDpi, content = {
80 | // This is the actual composable that will be rendered to the PDF.
81 | // Paged tries to ensure that we don't cut off leaf composables in the middle.
82 | Paged(
83 | pageIndex = currentPageIndex,
84 | pageModifier = pageModifier,
85 | drawBreakpoints = printBreakpoints,
86 | onPageLayout = { pageCountDeferred.complete(it) },
87 | content = content
88 | )
89 | }) {
90 | // We need to know the total page count before we can start iterating. This waits for the
91 | // first composition and frame to commit.
92 | val pageCount = pageCountDeferred.await()
93 |
94 | (0 until pageCount).asSequence()
95 | .filter { page -> pages.any { page in it.start..it.end } }
96 | .forEach { pageNumber ->
97 | val page = pdfDocument.startPage(pageNumber)
98 |
99 | // Update the Paged to "flip" to the page.
100 | currentPageIndex = pageNumber
101 |
102 | // Render the page to the PDF. This function will automatically wait for the next frame to
103 | // finish drawing. It also does not do any IO, so we don't need to switch dispatchers.
104 | composePage(page)
105 | pdfDocument.finishPage(page)
106 |
107 | // We're on the main thread, so be a good citizen.
108 | // Also ensures we handle cancellation in a timely fashion.
109 | yield()
110 | }
111 | }
112 |
113 | // The PDF currently only exists in memory, so to dump it to the printing system we use a
114 | // background thread.
115 | withContext(ioDispatcher) {
116 | @Suppress("BlockingMethodInNonBlockingContext")
117 | pdfDocument.writeTo(FileOutputStream(destination.fileDescriptor))
118 | }
119 | pdfDocument.close()
120 | return pages
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/printing/src/main/java/com/zachklipp/richtext/ui/printing/CoroutinePrintDocumentAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.ui.printing
2 |
3 | import android.os.Bundle
4 | import android.os.CancellationSignal
5 | import android.os.ParcelFileDescriptor
6 | import android.print.PageRange
7 | import android.print.PrintAttributes
8 | import android.print.PrintDocumentAdapter
9 | import android.print.PrintDocumentInfo
10 | import kotlinx.coroutines.CancellationException
11 | import kotlinx.coroutines.CoroutineScope
12 | import kotlinx.coroutines.Job
13 | import kotlinx.coroutines.cancel
14 | import kotlinx.coroutines.launch
15 | import kotlin.coroutines.CoroutineContext
16 |
17 | /**
18 | * A [PrintDocumentAdapter] that exposes [onLayout] and [onWrite] functions as suspend functions
19 | * that will automatically invoke the correct callback methods.
20 | */
21 | public abstract class CoroutinePrintDocumentAdapter(context: CoroutineContext) :
22 | PrintDocumentAdapter() {
23 |
24 | private val printAdapterScope = CoroutineScope(context + Job(parent = context[Job]))
25 |
26 | override fun onFinish() {
27 | printAdapterScope.cancel("Print adapter finished")
28 | super.onFinish()
29 | }
30 |
31 | public abstract suspend fun onLayout(
32 | oldAttributes: PrintAttributes?,
33 | newAttributes: PrintAttributes,
34 | extras: Bundle?
35 | ): PrintDocumentInfo
36 |
37 | public abstract suspend fun onWrite(
38 | pages: Array,
39 | destination: ParcelFileDescriptor
40 | ): Array
41 |
42 | final override fun onLayout(
43 | oldAttributes: PrintAttributes?,
44 | newAttributes: PrintAttributes,
45 | cancellationSignal: CancellationSignal,
46 | callback: LayoutResultCallback,
47 | extras: Bundle?
48 | ) {
49 | val job = printAdapterScope.launch {
50 | try {
51 | val result = onLayout(oldAttributes, newAttributes, extras)
52 | callback.onLayoutFinished(result, true)
53 | } catch (e: CancellationException) {
54 | callback.onLayoutCancelled()
55 | } catch (e: Throwable) {
56 | callback.onLayoutFailed(e.message)
57 | }
58 | }
59 | cancellationSignal.setOnCancelListener { job.cancel() }
60 | }
61 |
62 | final override fun onWrite(
63 | pages: Array,
64 | destination: ParcelFileDescriptor,
65 | cancellationSignal: CancellationSignal,
66 | callback: WriteResultCallback
67 | ) {
68 | val job = printAdapterScope.launch {
69 | try {
70 | val writtenPages = onWrite(pages, destination)
71 | callback.onWriteFinished(writtenPages)
72 | } catch (e: CancellationException) {
73 | callback.onWriteCancelled()
74 | } catch (e: Throwable) {
75 | callback.onWriteFailed(e.message)
76 | }
77 | }
78 | cancellationSignal.setOnCancelListener { job.cancel() }
79 | }
80 | }
--------------------------------------------------------------------------------
/printing/src/main/java/com/zachklipp/richtext/ui/printing/Modifiers.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.ui.printing
2 |
3 | import androidx.compose.ui.Modifier
4 | import androidx.compose.ui.layout.LayoutModifier
5 | import androidx.compose.ui.layout.Measurable
6 | import androidx.compose.ui.layout.MeasureResult
7 | import androidx.compose.ui.layout.MeasureScope
8 | import androidx.compose.ui.unit.Constraints
9 | import androidx.compose.ui.unit.Dp
10 | import androidx.compose.ui.unit.constrainHeight
11 | import androidx.compose.ui.unit.constrainWidth
12 | import androidx.compose.ui.unit.offset
13 | import kotlin.math.min
14 |
15 | /**
16 | * A [Modifier] that adds different padding depending on the minimum dimension of the max
17 | * constraints.
18 | *
19 | * This modifier is especially useful when passed to the [Printable] composable, in which case the
20 | * modifier will be applied to every page of the printed document and can be used to create page
21 | * margins.
22 | */
23 | public fun Modifier.responsivePadding(vararg minDimensionsToPadding: Pair): Modifier =
24 | this.then(object : LayoutModifier {
25 | override fun MeasureScope.measure(
26 | measurable: Measurable,
27 | constraints: Constraints
28 | ): MeasureResult {
29 | val minDimension = min(constraints.maxWidth, constraints.maxHeight).toDp()
30 | val breakpoint = minDimensionsToPadding.reversed().last { it.first >= minDimension }
31 | val padding = breakpoint.second.roundToPx()
32 | val paddedConstraints = constraints.offset(-padding * 2, -padding * 2)
33 | val placeable = measurable.measure(paddedConstraints)
34 | val width = constraints.constrainWidth(placeable.width + padding)
35 | val height = constraints.constrainHeight(placeable.height + padding)
36 | return layout(width, height) {
37 | placeable.placeRelative(padding, padding)
38 | }
39 | }
40 | })
41 |
--------------------------------------------------------------------------------
/printing/src/main/java/com/zachklipp/richtext/ui/printing/PrinterMetrics.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("NOTHING_TO_INLINE")
2 |
3 | package com.zachklipp.richtext.ui.printing
4 |
5 | import androidx.compose.ui.unit.Density
6 |
7 | /** PDF dimensions are always given in points (1/72s of an inch). */
8 | private const val POSTSCRIPT_DPI = 72
9 |
10 | /** How many P's in an I. */
11 | private const val DP_DPI = 160
12 |
13 | public const val DefaultPageDpi: Int = 100
14 |
15 | /** Represents a PostScript point (1/72 of an inch). */
16 | @JvmInline
17 | internal value class Pts(val value: Int) {
18 | override fun toString(): String = "$value.pts"
19 | }
20 |
21 | internal inline val Int.pts get() = Pts(this)
22 |
23 | /**
24 | * Helps with converting between PostScript points and regular android units.
25 | */
26 | internal data class PrinterMetrics(
27 | val screenDensity: Density,
28 | val pageDpi: Int,
29 | val pageWidth: Pts,
30 | val pageHeight: Pts,
31 | ) : Density by screenDensity {
32 |
33 | /** The [Density] that should be used for composing pages. */
34 | val renderDensity: Density get() = Density(pageDpi / DP_DPI.toFloat())
35 | }
36 |
--------------------------------------------------------------------------------
/richtext-commonmark/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("richtext-kmp-library")
3 | id("org.jetbrains.compose") version Compose.desktopVersion
4 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
5 | id("org.jetbrains.dokka")
6 | }
7 |
8 | repositories {
9 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
10 | }
11 |
12 | android {
13 | namespace = "com.halilibo.richtext.commonmark"
14 | }
15 |
16 | kotlin {
17 | sourceSets {
18 | val commonMain by getting {
19 | dependencies {
20 | implementation(compose.runtime)
21 | api(Commonmark.core)
22 | api(project(":richtext-ui"))
23 | api(project(":richtext-markdown"))
24 | }
25 | }
26 | val commonTest by getting
27 |
28 | val androidMain by getting {
29 | kotlin.srcDir("src/commonJvmAndroid/kotlin")
30 | dependencies {
31 | implementation(Commonmark.core)
32 | implementation(Commonmark.tables)
33 | implementation(Commonmark.strikethrough)
34 | implementation(Commonmark.autolink)
35 | }
36 | }
37 |
38 | val jvmMain by getting {
39 | kotlin.srcDir("src/commonJvmAndroid/kotlin")
40 | dependencies {
41 | implementation(Commonmark.core)
42 | implementation(Commonmark.tables)
43 | implementation(Commonmark.strikethrough)
44 | implementation(Commonmark.autolink)
45 | }
46 | }
47 |
48 | val jvmTest by getting {
49 | kotlin.srcDir("src/commonJvmAndroidTest/kotlin")
50 | dependencies {
51 | implementation(Kotlin.Test.jdk)
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/richtext-commonmark/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Compose Richtext Commonmark
2 | POM_DESCRIPTION=A library for rendering markdown in Compose using the Commonmark library.
--------------------------------------------------------------------------------
/richtext-commonmark/src/commonJvmAndroidTest/kotlin/com/halilibo/richtext/commonmark/AstNodeConvertKtTest.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import com.halilibo.richtext.commonmark.convert
4 | import com.halilibo.richtext.markdown.node.AstImage
5 | import com.halilibo.richtext.markdown.node.AstNode
6 | import com.halilibo.richtext.markdown.node.AstNodeLinks
7 | import org.commonmark.node.Image
8 | import org.junit.Test
9 | import kotlin.test.assertEquals
10 |
11 | internal class AstNodeConvertKtTest {
12 |
13 | @Test
14 | fun `when image without title is converted, then the content description is empty`() {
15 | val destination = "/url"
16 | val image = Image(destination, null)
17 |
18 | val result = convert(image)
19 |
20 | assertEquals(
21 | expected = AstNode(
22 | type = AstImage(title = "", destination = destination),
23 | links = AstNodeLinks()
24 | ),
25 | actual = result
26 | )
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/richtext-commonmark/src/commonMain/kotlin/com/halilibo/richtext/commonmark/CommonMarkdownParseOptions.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.commonmark
2 |
3 | /**
4 | * Allows configuration of the Markdown parser
5 | *
6 | * @param autolink Detect plain text links and turn them into Markdown links.
7 | */
8 | public class CommonMarkdownParseOptions(
9 | public val autolink: Boolean
10 | ) {
11 |
12 | override fun toString(): String {
13 | return "CommonMarkdownParseOptions(autolink=$autolink)"
14 | }
15 |
16 | override fun equals(other: Any?): Boolean {
17 | if (this === other) return true
18 | if (other !is CommonMarkdownParseOptions) return false
19 |
20 | return autolink == other.autolink
21 | }
22 |
23 | override fun hashCode(): Int {
24 | return autolink.hashCode()
25 | }
26 |
27 | public fun copy(
28 | autolink: Boolean = this.autolink
29 | ): CommonMarkdownParseOptions = CommonMarkdownParseOptions(
30 | autolink = autolink
31 | )
32 |
33 | public companion object {
34 | public val Default: CommonMarkdownParseOptions = CommonMarkdownParseOptions(
35 | autolink = true
36 | )
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/richtext-commonmark/src/commonMain/kotlin/com/halilibo/richtext/commonmark/Markdown.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.commonmark
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.CompositionLocalProvider
5 | import androidx.compose.runtime.getValue
6 | import androidx.compose.runtime.produceState
7 | import androidx.compose.runtime.remember
8 | import androidx.compose.runtime.rememberUpdatedState
9 | import com.halilibo.richtext.markdown.AstBlockNodeComposer
10 | import com.halilibo.richtext.markdown.BasicMarkdown
11 | import com.halilibo.richtext.markdown.ContentOverride
12 | import com.halilibo.richtext.markdown.InlineContentOverride
13 | import com.halilibo.richtext.markdown.node.AstNode
14 | import com.halilibo.richtext.ui.RichTextScope
15 | import com.halilibo.richtext.ui.string.MarkdownAnimationState
16 | import com.halilibo.richtext.ui.string.RichTextRenderOptions
17 | import org.commonmark.node.Node
18 |
19 | /**
20 | * A composable that renders Markdown content according to Commonmark specification using RichText.
21 | *
22 | * @param content Markdown text. No restriction on length.
23 | * @param markdownParseOptions Options for the Markdown parser.
24 | * @param astBlockNodeComposer An interceptor to take control of composing any block type node's
25 | * rendering. Use it to render images, html text, tables with your own components.
26 | */
27 | @Composable
28 | public fun RichTextScope.Markdown(
29 | content: String,
30 | markdownParseOptions: CommonMarkdownParseOptions = CommonMarkdownParseOptions.Default,
31 | richtextRenderOptions: RichTextRenderOptions = RichTextRenderOptions.Default,
32 | contentOverride: ContentOverride? = null,
33 | inlineContentOverride: InlineContentOverride? = null,
34 | astBlockNodeComposer: AstBlockNodeComposer? = null
35 | ) {
36 | val commonmarkAstNodeParser = remember(markdownParseOptions) {
37 | CommonmarkAstNodeParser(markdownParseOptions)
38 | }
39 |
40 | val astRootNode by produceState(
41 | initialValue = null,
42 | key1 = commonmarkAstNodeParser,
43 | key2 = content
44 | ) {
45 | value = commonmarkAstNodeParser.parse(content)
46 | }
47 |
48 | astRootNode?.let {
49 | BasicMarkdown(
50 | astNode = it,
51 | contentOverride = contentOverride,
52 | inlineContentOverride = inlineContentOverride,
53 | richTextRenderOptions = richtextRenderOptions,
54 | astBlockNodeComposer = astBlockNodeComposer,
55 | )
56 | }
57 | }
58 |
59 | /**
60 | * A composable that renders Markdown node using RichText.
61 | *
62 | * @param content CommonMark node to render.
63 | * @param onLinkClicked A function to invoke when a link is clicked from rendered content.
64 | */
65 | @Composable
66 | public fun RichTextScope.Markdown(
67 | content: Node,
68 | richtextRenderOptions: RichTextRenderOptions = RichTextRenderOptions.Default,
69 | contentOverride: ContentOverride? = null,
70 | inlineContentOverride: InlineContentOverride? = null,
71 | astBlockNodeComposer: AstBlockNodeComposer? = null
72 | ) {
73 | val astNode = content.toAstNode() ?: return
74 | BasicMarkdown(
75 | astNode,
76 | contentOverride,
77 | inlineContentOverride,
78 | richtextRenderOptions,
79 | astBlockNodeComposer,
80 | )
81 | }
82 |
83 | /**
84 | * A helper class that can convert any text content into an ASTNode tree and return its root.
85 | */
86 | public expect class CommonmarkAstNodeParser(
87 | options: CommonMarkdownParseOptions = CommonMarkdownParseOptions.Default
88 | ) {
89 |
90 | /**
91 | * Parse markdown content and return Abstract Syntax Tree(AST).
92 | *
93 | * @param text Markdown text to be parsed.
94 | * @param options Options for the Commonmark Markdown parser.
95 | */
96 | public fun parse(text: String): AstNode
97 | }
98 |
--------------------------------------------------------------------------------
/richtext-commonmark/src/commonMain/kotlin/com/halilibo/richtext/commonmark/ParsedMarkdown.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.commonmark
2 |
3 | import androidx.compose.runtime.Composable
4 | import com.halilibo.richtext.markdown.node.AstNode
5 | import org.commonmark.node.Node
6 |
7 | /**
8 | * Convert CommonMark [Node] to [AstNode].
9 | */
10 | @Composable
11 | internal expect fun Node.toAstNode(): AstNode?
12 |
13 | /**
14 | * Parse markdown content and return Abstract Syntax Tree(AST).
15 | * Composable is efficient thanks to remember construct.
16 | *
17 | * @param text Markdown text to be parsed.
18 | * @param options Options for the Markdown parser.
19 | */
20 | @Composable
21 | internal expect fun parsedMarkdown(text: String, options: CommonMarkdownParseOptions): AstNode?
22 |
--------------------------------------------------------------------------------
/richtext-markdown/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("richtext-kmp-library")
3 | id("org.jetbrains.compose") version Compose.desktopVersion
4 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
5 | id("org.jetbrains.dokka")
6 | }
7 |
8 | repositories {
9 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
10 | }
11 |
12 | android {
13 | namespace = "com.halilibo.richtext.markdown"
14 | }
15 |
16 | kotlin {
17 | sourceSets {
18 | val commonMain by getting {
19 | dependencies {
20 | implementation(Commonmark.core)
21 | implementation(compose.runtime)
22 | implementation(compose.foundation)
23 | api(project(":richtext-ui"))
24 | }
25 | }
26 | val commonTest by getting
27 |
28 | val androidMain by getting {
29 | dependencies {
30 | implementation(Compose.coil)
31 | }
32 | }
33 |
34 | val jvmMain by getting {
35 | dependencies {
36 | implementation(compose.desktop.currentOs)
37 | implementation(Network.okHttp)
38 | }
39 | }
40 |
41 | val jvmTest by getting {
42 | dependencies {
43 | implementation(Kotlin.Test.jdk)
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/richtext-markdown/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Compose Richtext Markdown
2 | POM_DESCRIPTION=A library for rendering markdown represented as an AST in Compose.
--------------------------------------------------------------------------------
/richtext-markdown/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/richtext-markdown/src/androidMain/kotlin/com/halilibo/richtext/markdown/HtmlBlock.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.remember
5 | import androidx.compose.ui.text.AnnotatedString
6 | import androidx.compose.ui.text.fromHtml
7 | import com.halilibo.richtext.ui.RichTextScope
8 | import com.halilibo.richtext.ui.string.Text
9 | import com.halilibo.richtext.ui.string.richTextString
10 |
11 | @Composable
12 | internal actual fun RichTextScope.HtmlBlock(content: String) {
13 | val richTextString = remember(content) {
14 | richTextString {
15 | withAnnotatedString {
16 | append(AnnotatedString.Companion.fromHtml(content))
17 | }
18 | }
19 | }
20 | Text(richTextString)
21 | }
22 |
--------------------------------------------------------------------------------
/richtext-markdown/src/androidMain/kotlin/com/halilibo/richtext/markdown/RemoteImage.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import androidx.compose.foundation.Image
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.BoxWithConstraints
6 | import androidx.compose.foundation.layout.size
7 | import androidx.compose.runtime.Composable
8 | import androidx.compose.runtime.derivedStateOf
9 | import androidx.compose.runtime.getValue
10 | import androidx.compose.runtime.remember
11 | import androidx.compose.ui.Alignment
12 | import androidx.compose.ui.Modifier
13 | import androidx.compose.ui.geometry.isSpecified
14 | import androidx.compose.ui.layout.ContentScale
15 | import androidx.compose.ui.platform.LocalContext
16 | import androidx.compose.ui.platform.LocalDensity
17 | import androidx.compose.ui.unit.dp
18 | import coil.compose.rememberAsyncImagePainter
19 | import coil.request.ImageRequest
20 | import coil.size.Size
21 |
22 | private val DEFAULT_IMAGE_SIZE = 64.dp
23 |
24 | /**
25 | * Implementation of RemoteImage by using Coil library for Android.
26 | */
27 | @Composable
28 | internal actual fun RemoteImage(
29 | url: String,
30 | contentDescription: String?,
31 | modifier: Modifier,
32 | contentScale: ContentScale
33 | ) {
34 | val painter = rememberAsyncImagePainter(
35 | ImageRequest.Builder(LocalContext.current)
36 | .data(data = url)
37 | .size(Size.ORIGINAL)
38 | .crossfade(true)
39 | .build()
40 | )
41 |
42 | val density = LocalDensity.current
43 |
44 | BoxWithConstraints(
45 | modifier = modifier,
46 | contentAlignment = Alignment.Center) {
47 | val sizeModifier by remember(density, painter) {
48 | derivedStateOf {
49 | val painterIntrinsicSize = painter.state.painter?.intrinsicSize
50 | if (painterIntrinsicSize != null &&
51 | painterIntrinsicSize.isSpecified &&
52 | painterIntrinsicSize.width != Float.POSITIVE_INFINITY &&
53 | painterIntrinsicSize.height != Float.POSITIVE_INFINITY
54 | ) {
55 | val width = painterIntrinsicSize.width
56 | val height = painterIntrinsicSize.height
57 | val scale = if (width > constraints.maxWidth) {
58 | constraints.maxWidth.toFloat() / width
59 | } else {
60 | 1f
61 | }
62 |
63 | with(density) {
64 | Modifier.size(
65 | (width * scale).toDp(),
66 | (height * scale).toDp()
67 | )
68 | }
69 | } else {
70 | // if size is not defined at all, Coil fails to render the image
71 | // here, we give a default size for images until they are loaded.
72 | Modifier.size(DEFAULT_IMAGE_SIZE)
73 | }
74 | }
75 | }
76 |
77 | Image(
78 | painter = painter,
79 | contentDescription = contentDescription,
80 | modifier = sizeModifier,
81 | contentScale = contentScale
82 | )
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/HtmlBlock.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import androidx.compose.runtime.Composable
4 | import com.halilibo.richtext.ui.RichTextScope
5 |
6 | /**
7 | * Android and JVM can have different WebView or HTML rendering implementations.
8 | * We are leaving HTML rendering to platform side.
9 | */
10 | @Composable
11 | internal expect fun RichTextScope.HtmlBlock(content: String)
12 |
--------------------------------------------------------------------------------
/richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/RemoteImage.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.ui.Modifier
5 | import androidx.compose.ui.layout.ContentScale
6 |
7 | //TODO(halilozercan): This should be provided from consumer side.
8 | /**
9 | * Image rendering is highly platform dependent. Coil is the desired
10 | * way to show images but it doesn't exist in desktop.
11 | */
12 | @Composable
13 | internal expect fun RemoteImage(
14 | url: String,
15 | contentDescription: String?,
16 | modifier: Modifier = Modifier,
17 | contentScale: ContentScale
18 | )
19 |
--------------------------------------------------------------------------------
/richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/RenderTable.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.MutableState
5 | import com.halilibo.richtext.markdown.node.AstNode
6 | import com.halilibo.richtext.markdown.node.AstTableBody
7 | import com.halilibo.richtext.markdown.node.AstTableCell
8 | import com.halilibo.richtext.markdown.node.AstTableHeader
9 | import com.halilibo.richtext.markdown.node.AstTableRow
10 | import com.halilibo.richtext.ui.RichTextScope
11 | import com.halilibo.richtext.ui.Table
12 | import com.halilibo.richtext.ui.string.MarkdownAnimationState
13 | import com.halilibo.richtext.ui.string.RichTextRenderOptions
14 |
15 | @Composable
16 | internal fun RichTextScope.RenderTable(
17 | node: AstNode,
18 | inlineContentOverride: InlineContentOverride?,
19 | richtextRenderOptions: RichTextRenderOptions,
20 | markdownAnimationState: MarkdownAnimationState,
21 | ) {
22 | Table(
23 | headerRow = {
24 | node.filterChildrenType()
25 | .firstOrNull()
26 | ?.filterChildrenType()
27 | ?.firstOrNull()
28 | ?.filterChildrenType()
29 | ?.forEach { tableCell ->
30 | cell {
31 | MarkdownRichText(
32 | tableCell,
33 | inlineContentOverride,
34 | richtextRenderOptions,
35 | markdownAnimationState,
36 | )
37 | }
38 | }
39 | }
40 | ) {
41 | node.filterChildrenType()
42 | .firstOrNull()
43 | ?.filterChildrenType()
44 | ?.forEach { tableRow ->
45 | row {
46 | tableRow.filterChildrenType()
47 | .forEach { tableCell ->
48 | cell {
49 | MarkdownRichText(
50 | tableCell,
51 | inlineContentOverride,
52 | richtextRenderOptions,
53 | markdownAnimationState,
54 | )
55 | }
56 | }
57 | }
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/TraverseUtils.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import com.halilibo.richtext.markdown.node.AstCode
4 | import com.halilibo.richtext.markdown.node.AstHardLineBreak
5 | import com.halilibo.richtext.markdown.node.AstImage
6 | import com.halilibo.richtext.markdown.node.AstNode
7 | import com.halilibo.richtext.markdown.node.AstNodeType
8 | import com.halilibo.richtext.markdown.node.AstSoftLineBreak
9 | import com.halilibo.richtext.markdown.node.AstText
10 |
11 | internal fun AstNode.childrenSequence(
12 | reverse: Boolean = false
13 | ): Sequence {
14 | return if (!reverse) {
15 | generateSequence(this.links.firstChild) { it.links.next }
16 | } else {
17 | generateSequence(this.links.lastChild) { it.links.previous }
18 | }
19 | }
20 |
21 | /**
22 | * Markdown rendering is susceptible to have assumptions. Hence, some rendering rules
23 | * may force restrictions on children. So, valid children nodes should be selected
24 | * before traversing. This function returns a LinkedList of children which conforms to
25 | * [filter] function.
26 | *
27 | * @param filter A lambda to select valid children.
28 | */
29 | internal fun AstNode.filterChildren(
30 | reverse: Boolean = false,
31 | filter: (AstNode) -> Boolean
32 | ): Sequence {
33 | return childrenSequence(reverse).filter(filter)
34 | }
35 |
36 | internal inline fun AstNode.filterChildrenType(): Sequence {
37 | return filterChildren { it.type is T }
38 | }
39 |
40 | /**
41 | * These ASTNode types should never have any children. If any exists, ignore them.
42 | */
43 | internal fun AstNode.isRichTextTerminal(): Boolean {
44 | return type is AstText
45 | || type is AstCode
46 | || type is AstImage
47 | || type is AstSoftLineBreak
48 | || type is AstHardLineBreak
49 | }
50 |
--------------------------------------------------------------------------------
/richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/node/AstNode.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown.node
2 |
3 | /**
4 | * Generic AstNode implementation that can define any node in Abstract Syntax Tree.
5 | *
6 | * @param type A sealed class which is categorized into block and inline nodes.
7 | * @param links Pointers to parent, sibling, child nodes.
8 | */
9 | public class AstNode(
10 | public val type: AstNodeType,
11 | public val links: AstNodeLinks
12 | ) {
13 | override fun equals(other: Any?): Boolean {
14 | if (this === other) return true
15 | if (other !is AstNode) return false
16 |
17 | if (type != other.type) return false
18 | if (links != other.links) return false
19 |
20 | return true
21 | }
22 |
23 | override fun hashCode(): Int {
24 | var result = type.hashCode()
25 | result = 31 * result + links.hashCode()
26 | return result
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/node/AstNodeLinks.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown.node
2 |
3 | import androidx.compose.runtime.Immutable
4 |
5 | /**
6 | * All the pointers that can exist for a node in an AST.
7 | *
8 | * Links are mutable to make it possible to instantiate a Node which can then reconfigure its
9 | * children and siblings. Please do not modify the links after an ASTNode is created and the scope
10 | * is finished.
11 | */
12 | @Immutable
13 | public class AstNodeLinks(
14 | public var parent: AstNode? = null,
15 | public var firstChild: AstNode? = null,
16 | public var lastChild: AstNode? = null,
17 | public var previous: AstNode? = null,
18 | public var next: AstNode? = null
19 | ) {
20 |
21 | override fun equals(other: Any?): Boolean {
22 | if (other !is AstNodeLinks) return false
23 |
24 | return parent === other.parent &&
25 | firstChild === other.firstChild &&
26 | lastChild === other.lastChild &&
27 | previous === other.previous &&
28 | next === other.next
29 | }
30 |
31 | /**
32 | * Stop infinite loop and only calculate towards bottom-right direction
33 | */
34 | override fun hashCode(): Int {
35 | return (firstChild ?: 0).hashCode() * 11 + (next ?: 0).hashCode() * 7
36 | }
37 | }
--------------------------------------------------------------------------------
/richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/node/AstNodeType.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown.node
2 |
3 | import androidx.compose.runtime.Immutable
4 | import com.halilibo.richtext.ui.string.RichTextString
5 | import org.commonmark.node.Node
6 |
7 | /**
8 | * Refer to https://spec.commonmark.org/0.30/#precedence
9 | *
10 | * Commonmark specification defines 3 different types of AST nodes;
11 | *
12 | * - Container Block
13 | * - Leaf Block
14 | * - Inline Content
15 | *
16 | * Container blocks are the most generic nodes. They define a structure for their children but
17 | * do not impose any major restrictions, meaning that container blocks can contain any
18 | * type of child node.
19 | *
20 | * Leaf blocks are self-explanatory, they should not have any children. All the necessary content
21 | * to render a leaf block should already exist in its payload
22 | *
23 | * Inline Content is analogous to [RichTextString] and its styles. Most of the inline content
24 | * nodes are about styling(bold, italic, strikethrough, code). The rest contains links, images,
25 | * html content, and of course raw text.
26 | */
27 | public sealed class AstNodeType
28 |
29 | //region AstBlockNodeType
30 |
31 | public sealed class AstBlockNodeType: AstNodeType()
32 |
33 | //region AstContainerBlockNodeType
34 |
35 | /**
36 | * Defines a subtype of Block Node that can contain other nodes.
37 | */
38 | public sealed class AstContainerBlockNodeType: AstBlockNodeType()
39 |
40 | /**
41 | * Usually defines the root of a markdown document.
42 | */
43 | @Immutable
44 | public object AstDocument : AstContainerBlockNodeType()
45 |
46 | /**
47 | * A block quote container that will indent its contents relative to its own indentation.
48 | */
49 | @Immutable
50 | public object AstBlockQuote : AstContainerBlockNodeType()
51 |
52 | /**
53 | * Ordered or Unordered list item.
54 | */
55 | @Immutable
56 | public object AstListItem : AstContainerBlockNodeType()
57 |
58 | /**
59 | * A list type that marks its items with bullets to signify a lack of order.
60 | */
61 | @Immutable
62 | public data class AstUnorderedList(
63 | val bulletMarker: Char
64 | ) : AstContainerBlockNodeType()
65 |
66 | /**
67 | * A list type that uses numbers to mark its items.
68 | */
69 | @Immutable
70 | public data class AstOrderedList(
71 | val startNumber: Int,
72 | val delimiter: Char
73 | ) : AstContainerBlockNodeType()
74 |
75 | //endregion
76 |
77 | //region AstLeafBlockNodeType
78 |
79 | /**
80 | * Defines a subtype of Block Node that can only contain plain text and full-length annotations.
81 | */
82 | public sealed class AstLeafBlockNodeType: AstBlockNodeType()
83 |
84 | @Immutable
85 | public object AstThematicBreak : AstLeafBlockNodeType()
86 |
87 | @Immutable
88 | public data class AstHeading(
89 | val level: Int
90 | ) : AstLeafBlockNodeType()
91 |
92 | @Immutable
93 | public data class AstIndentedCodeBlock(
94 | val literal: String
95 | ) : AstLeafBlockNodeType()
96 |
97 | @Immutable
98 | public data class AstFencedCodeBlock(
99 | val fenceChar: Char,
100 | val fenceLength: Int,
101 | val fenceIndent: Int,
102 | val info: String,
103 | val literal: String
104 | ) : AstLeafBlockNodeType()
105 |
106 | @Immutable
107 | public data class AstHtmlBlock(
108 | val literal: String
109 | ) : AstLeafBlockNodeType()
110 |
111 | @Immutable
112 | public data class AstLinkReferenceDefinition(
113 | val label: String,
114 | val destination: String,
115 | val title: String
116 | ) : AstLeafBlockNodeType()
117 |
118 | @Immutable
119 | public object AstParagraph : AstLeafBlockNodeType()
120 |
121 | //endregion
122 |
123 | //endregion
124 |
125 | //region AstInlineNodeType
126 |
127 | /**
128 | * Defines a node type that can only apply to inline content.
129 | */
130 | public sealed class AstInlineNodeType: AstNodeType()
131 |
132 | @Immutable
133 | public data class AstCode(
134 | val literal: String
135 | ) : AstInlineNodeType()
136 |
137 | @Immutable
138 | public data class AstEmphasis(
139 | private val delimiter: String
140 | ) : AstInlineNodeType()
141 |
142 | @Immutable
143 | public data class AstStrongEmphasis(
144 | private val delimiter: String
145 | ) : AstInlineNodeType()
146 |
147 | @Immutable
148 | public data class AstStrikethrough(
149 | val delimiter: String
150 | ) : AstInlineNodeType()
151 |
152 | @Immutable
153 | public data class AstLink(
154 | val destination: String,
155 | val title: String
156 | ) : AstInlineNodeType()
157 |
158 | @Immutable
159 | public data class AstImage(
160 | val title: String,
161 | val destination: String
162 | ) : AstInlineNodeType()
163 |
164 | @Immutable
165 | public data class AstHtmlInline(
166 | val literal: String
167 | ) : AstInlineNodeType()
168 |
169 | @Immutable
170 | public object AstHardLineBreak : AstInlineNodeType()
171 |
172 | @Immutable
173 | public object AstSoftLineBreak : AstInlineNodeType()
174 |
175 | @Immutable
176 | public data class AstText(
177 | val literal: String
178 | ) : AstInlineNodeType()
179 |
180 | @Immutable
181 | public data class AstCustomNode(
182 | val node: Node
183 | ) : AstInlineNodeType()
184 |
185 | @Immutable
186 | public data class AstCustomBlock(
187 | val node: Node
188 | ) : AstInlineNodeType()
189 |
190 | //endregion
191 |
--------------------------------------------------------------------------------
/richtext-markdown/src/commonMain/kotlin/com/halilibo/richtext/markdown/node/AstTable.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown.node
2 |
3 | import androidx.compose.runtime.Immutable
4 |
5 | @Immutable
6 | public object AstTableRoot: AstContainerBlockNodeType()
7 |
8 | @Immutable
9 | public object AstTableBody: AstContainerBlockNodeType()
10 |
11 | @Immutable
12 | public object AstTableHeader: AstContainerBlockNodeType()
13 |
14 | @Immutable
15 | public object AstTableRow: AstContainerBlockNodeType()
16 |
17 | @Immutable
18 | public data class AstTableCell(
19 | val header: Boolean,
20 | val alignment: AstTableCellAlignment
21 | ) : AstContainerBlockNodeType()
22 |
23 | public enum class AstTableCellAlignment {
24 | LEFT,
25 | CENTER,
26 | RIGHT
27 | }
28 |
--------------------------------------------------------------------------------
/richtext-markdown/src/jvmMain/kotlin/com/halilibo/richtext/markdown/HtmlBlock.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import androidx.compose.foundation.text.BasicText
4 | import androidx.compose.runtime.Composable
5 | import androidx.compose.runtime.DisposableEffect
6 | import com.halilibo.richtext.ui.RichTextScope
7 |
8 | @Composable
9 | internal actual fun RichTextScope.HtmlBlock(content: String) {
10 | DisposableEffect(Unit) {
11 | println("Html blocks are rendered literally in Compose Desktop!")
12 | onDispose { }
13 | }
14 | BasicText(content)
15 | }
16 |
--------------------------------------------------------------------------------
/richtext-markdown/src/jvmMain/kotlin/com/halilibo/richtext/markdown/RemoteImage.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.markdown
2 |
3 | import androidx.compose.foundation.Image
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.runtime.getValue
7 | import androidx.compose.runtime.produceState
8 | import androidx.compose.ui.Modifier
9 | import androidx.compose.ui.graphics.ImageBitmap
10 | import androidx.compose.ui.graphics.asImageBitmap
11 | import androidx.compose.ui.graphics.toComposeImageBitmap
12 | import androidx.compose.ui.layout.ContentScale
13 | import kotlinx.coroutines.Dispatchers
14 | import kotlinx.coroutines.withContext
15 | import org.jetbrains.skia.Image.Companion.makeFromEncoded
16 | import java.awt.image.BufferedImage
17 | import java.io.ByteArrayOutputStream
18 | import java.io.InputStream
19 | import java.net.HttpURLConnection
20 | import java.net.URL
21 | import javax.imageio.ImageIO
22 |
23 | @Composable
24 | internal actual fun RemoteImage(
25 | url: String,
26 | contentDescription: String?,
27 | modifier: Modifier,
28 | contentScale: ContentScale
29 | ) {
30 | val image by produceState(null, url) {
31 | loadFullImage(url)?.let {
32 | value = makeFromEncoded(toByteArray(it)).toComposeImageBitmap()
33 | }
34 | }
35 |
36 | if (image != null) {
37 | Image(
38 | bitmap = image!!,
39 | contentDescription = contentDescription,
40 | modifier = modifier,
41 | contentScale = contentScale
42 | )
43 | }
44 | }
45 |
46 | private fun toByteArray(bitmap: BufferedImage): ByteArray {
47 | val baos = ByteArrayOutputStream()
48 | ImageIO.write(bitmap, "png", baos)
49 | return baos.toByteArray()
50 | }
51 |
52 | private suspend fun loadFullImage(source: String): BufferedImage? = withContext(Dispatchers.IO) {
53 | runCatching {
54 | val url = URL(source)
55 | val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
56 | connection.connectTimeout = 5000
57 | connection.connect()
58 |
59 | val input: InputStream = connection.inputStream
60 | val bitmap: BufferedImage? = ImageIO.read(input)
61 | bitmap
62 | }.getOrNull()
63 | }
64 |
--------------------------------------------------------------------------------
/richtext-ui-material/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("richtext-kmp-library")
3 | id("org.jetbrains.compose") version Compose.desktopVersion
4 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
5 | id("org.jetbrains.dokka")
6 | }
7 |
8 | repositories {
9 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
10 | }
11 |
12 | android {
13 | namespace = "com.halilibo.richtext.ui.material"
14 | }
15 |
16 | kotlin {
17 | sourceSets {
18 | val commonMain by getting {
19 | dependencies {
20 | implementation(compose.runtime)
21 | implementation(compose.foundation)
22 | implementation(compose.material)
23 | api(project(":richtext-ui"))
24 | }
25 | }
26 | val commonTest by getting
27 |
28 | val androidMain by getting
29 | val jvmMain by getting
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/richtext-ui-material/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Compose Richtext UI Material
2 | POM_DESCRIPTION=An extension library for RichText UI to easily bind with Material apps.
--------------------------------------------------------------------------------
/richtext-ui-material/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/richtext-ui-material/src/commonMain/kotlin/com/halilibo/richtext/ui/material/RichText.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui.material
2 |
3 | import androidx.compose.material.LocalContentColor
4 | import androidx.compose.material.LocalTextStyle
5 | import androidx.compose.material.ProvideTextStyle
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.runtime.CompositionLocalProvider
8 | import androidx.compose.runtime.compositionLocalOf
9 | import androidx.compose.ui.Modifier
10 | import com.halilibo.richtext.ui.BasicRichText
11 | import com.halilibo.richtext.ui.RichTextScope
12 | import com.halilibo.richtext.ui.RichTextStyle
13 | import com.halilibo.richtext.ui.RichTextThemeProvider
14 |
15 | /**
16 | * RichText implementation that integrates with Material design.
17 | *
18 | * If the consumer app has small composition trees or only uses RichText in
19 | * a single place, it would be ideal to call this function instead of wrapping
20 | * everything under [RichTextMaterialTheme].
21 | */
22 | @Composable
23 | public fun RichText(
24 | modifier: Modifier = Modifier,
25 | style: RichTextStyle? = null,
26 | children: @Composable RichTextScope.() -> Unit
27 | ) {
28 | RichTextMaterialTheme {
29 | BasicRichText(
30 | modifier = modifier,
31 | style = style,
32 | children = children
33 | )
34 | }
35 | }
36 |
37 | /**
38 | * Wraps the given [child] with Material Theme integration for [BasicRichText].
39 | *
40 | * This function also keeps track of the parent context by using CompositionLocals
41 | * to not apply Material Theming if it already exists in the current composition.
42 | */
43 | @Composable
44 | internal fun RichTextMaterialTheme(
45 | child: @Composable () -> Unit
46 | ) {
47 | val isApplied = LocalMaterialThemingApplied.current
48 |
49 | if (!isApplied) {
50 | RichTextThemeProvider(
51 | textStyleProvider = { LocalTextStyle.current },
52 | contentColorProvider = { LocalContentColor.current },
53 | textStyleBackProvider = { textStyle, content ->
54 | ProvideTextStyle(textStyle, content)
55 | },
56 | contentColorBackProvider = { color, content ->
57 | CompositionLocalProvider(LocalContentColor provides color) {
58 | content()
59 | }
60 | }
61 | ) {
62 | CompositionLocalProvider(LocalMaterialThemingApplied provides true) {
63 | child()
64 | }
65 | }
66 | } else {
67 | child()
68 | }
69 | }
70 |
71 | private val LocalMaterialThemingApplied = compositionLocalOf { false }
72 |
--------------------------------------------------------------------------------
/richtext-ui-material3/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("richtext-kmp-library")
3 | id("org.jetbrains.compose") version Compose.desktopVersion
4 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
5 | id("org.jetbrains.dokka")
6 | }
7 |
8 | repositories {
9 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
10 | }
11 |
12 | android {
13 | namespace = "com.halilibo.richtext.ui.material3"
14 | }
15 |
16 | kotlin {
17 | sourceSets {
18 | val commonMain by getting {
19 | dependencies {
20 | implementation(compose.runtime)
21 | implementation(compose.foundation)
22 |
23 | @OptIn(org.jetbrains.compose.ExperimentalComposeLibrary::class)
24 | implementation(compose.material3)
25 |
26 | api(project(":richtext-ui"))
27 | }
28 | }
29 | val commonTest by getting
30 |
31 | val androidMain by getting
32 | val jvmMain by getting
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/richtext-ui-material3/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Compose Richtext UI Material3
2 | POM_DESCRIPTION=An extension library for RichText UI to easily bind with Material3 apps.
--------------------------------------------------------------------------------
/richtext-ui-material3/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/richtext-ui-material3/src/commonMain/kotlin/com/halilibo/richtext/ui/material3/RichText.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui.material3
2 |
3 | import androidx.compose.material3.LocalContentColor
4 | import androidx.compose.material3.LocalTextStyle
5 | import androidx.compose.material3.ProvideTextStyle
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.runtime.CompositionLocalProvider
8 | import androidx.compose.runtime.compositionLocalOf
9 | import androidx.compose.ui.Modifier
10 | import com.halilibo.richtext.ui.BasicRichText
11 | import com.halilibo.richtext.ui.RichTextScope
12 | import com.halilibo.richtext.ui.RichTextStyle
13 | import com.halilibo.richtext.ui.RichTextThemeProvider
14 |
15 | /**
16 | * RichText implementation that integrates with Material 3 design.
17 | *
18 | * If the consumer app has small composition trees or only uses RichText in
19 | * a single place, it would be ideal to call this function instead of wrapping
20 | * everything under [RichTextMaterialTheme].
21 | */
22 | @Composable
23 | public fun RichText(
24 | modifier: Modifier = Modifier,
25 | style: RichTextStyle? = null,
26 | children: @Composable RichTextScope.() -> Unit
27 | ) {
28 | RichTextMaterialTheme {
29 | BasicRichText(
30 | modifier = modifier,
31 | style = style,
32 | children = children
33 | )
34 | }
35 | }
36 |
37 | /**
38 | * Wraps the given [child] with Material Theme integration for [BasicRichText].
39 | *
40 | * This function also keeps track of the parent context by using CompositionLocals
41 | * to not apply Material Theming if it already exists in the current composition.
42 | */
43 | @Composable
44 | internal fun RichTextMaterialTheme(
45 | child: @Composable () -> Unit
46 | ) {
47 | val isApplied = LocalMaterialThemingApplied.current
48 |
49 | if (!isApplied) {
50 | RichTextThemeProvider(
51 | textStyleProvider = { LocalTextStyle.current },
52 | contentColorProvider = { LocalContentColor.current },
53 | textStyleBackProvider = { textStyle, content ->
54 | ProvideTextStyle(textStyle, content)
55 | },
56 | contentColorBackProvider = { color, content ->
57 | CompositionLocalProvider(LocalContentColor provides color) {
58 | content()
59 | }
60 | }
61 | ) {
62 | CompositionLocalProvider(LocalMaterialThemingApplied provides true) {
63 | child()
64 | }
65 | }
66 | } else {
67 | child()
68 | }
69 | }
70 |
71 | private val LocalMaterialThemingApplied = compositionLocalOf { false }
--------------------------------------------------------------------------------
/richtext-ui/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("richtext-kmp-library")
3 | id("org.jetbrains.compose") version Compose.desktopVersion
4 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
5 | id("org.jetbrains.dokka")
6 | }
7 |
8 | repositories {
9 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
10 | }
11 |
12 | android {
13 | namespace = "com.halilibo.richtext.ui"
14 | }
15 | dependencies {
16 | implementation("androidx.lifecycle:lifecycle-runtime-compose-android:2.8.4")
17 | }
18 |
19 | kotlin {
20 | sourceSets {
21 | val commonMain by getting {
22 | dependencies {
23 | implementation(compose.runtime)
24 | implementation(compose.foundation)
25 | }
26 | }
27 | val commonTest by getting
28 |
29 | val androidMain by getting {
30 | kotlin.srcDir("src/commonJvmAndroid/kotlin")
31 | }
32 | val jvmMain by getting {
33 | kotlin.srcDir("src/commonJvmAndroid/kotlin")
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/richtext-ui/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Compose Richtext UI
2 | POM_DESCRIPTION=A library for rendering high-level text formatting in Compose.
--------------------------------------------------------------------------------
/richtext-ui/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/richtext-ui/src/androidMain/kotlin/com/halilibo/richtext/ui/CodeBlock.android.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.foundation.horizontalScroll
4 | import androidx.compose.foundation.rememberScrollState
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.ui.Modifier
7 |
8 | @Composable
9 | internal actual fun RichTextScope.CodeBlockLayout(
10 | wordWrap: Boolean,
11 | children: @Composable RichTextScope.(Modifier) -> Unit
12 | ) {
13 | if (!wordWrap) {
14 | val scrollState = rememberScrollState()
15 | children(Modifier.horizontalScroll(scrollState))
16 | } else {
17 | children(Modifier)
18 | }
19 | }
--------------------------------------------------------------------------------
/richtext-ui/src/commonJvmAndroid/kotlin/com/halilibo/richtext/ui/util/UUID.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui.util
2 |
3 | import java.util.UUID
4 |
5 | internal actual fun randomUUID(): String {
6 | return UUID.randomUUID().toString()
7 | }
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/BasicRichText.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry")
2 |
3 | package com.halilibo.richtext.ui
4 |
5 | import androidx.compose.foundation.layout.Arrangement.spacedBy
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.runtime.Composable
8 | import androidx.compose.ui.Modifier
9 | import androidx.compose.ui.platform.LocalDensity
10 |
11 | /**
12 | * Draws some rich text. Entry point to the compose-richtext library.
13 | */
14 | @Composable
15 | public fun BasicRichText(
16 | modifier: Modifier = Modifier,
17 | style: RichTextStyle? = null,
18 | children: @Composable RichTextScope.() -> Unit
19 | ) {
20 | with(RichTextScope) {
21 | RestartListLevel {
22 | WithStyle(style) {
23 | val resolvedStyle = currentRichTextStyle.resolveDefaults()
24 | val blockSpacing = with(LocalDensity.current) {
25 | resolvedStyle.paragraphSpacing!!.toDp()
26 | }
27 |
28 | Column(modifier = modifier, verticalArrangement = spacedBy(blockSpacing)) {
29 | children()
30 | }
31 | }
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/BlockQuote.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry")
2 |
3 | package com.halilibo.richtext.ui
4 |
5 | import androidx.compose.foundation.background
6 | import androidx.compose.foundation.layout.Box
7 | import androidx.compose.foundation.layout.padding
8 | import androidx.compose.foundation.layout.width
9 | import androidx.compose.foundation.shape.RoundedCornerShape
10 | import androidx.compose.runtime.Composable
11 | import androidx.compose.runtime.Immutable
12 | import androidx.compose.runtime.remember
13 | import androidx.compose.ui.Modifier
14 | import androidx.compose.ui.graphics.Color
15 | import androidx.compose.ui.layout.Layout
16 | import androidx.compose.ui.platform.LocalDensity
17 | import androidx.compose.ui.unit.Dp
18 | import androidx.compose.ui.unit.IntOffset
19 | import androidx.compose.ui.unit.TextUnit
20 | import androidx.compose.ui.unit.offset
21 | import androidx.compose.ui.unit.sp
22 | import com.halilibo.richtext.ui.BlockQuoteGutter.BarGutter
23 |
24 | internal val DefaultBlockQuoteGutter = BarGutter()
25 |
26 | /**
27 | * A composable function that draws the gutter beside a [BlockQuote].
28 | *
29 | * [BarGutter] is provided as the reasonable default of a simple vertical line.
30 | */
31 | public interface BlockQuoteGutter {
32 | @Composable public fun RichTextScope.drawGutter()
33 |
34 | public val verticalContentPadding: Dp?
35 |
36 | @Immutable
37 | public data class BarGutter(
38 | val startMargin: TextUnit = 6.sp,
39 | val barWidth: TextUnit = 3.sp,
40 | val endMargin: TextUnit = 6.sp,
41 | override val verticalContentPadding: Dp? = null,
42 | val color: (contentColor: Color) -> Color = { it.copy(alpha = .25f) }
43 | ) : BlockQuoteGutter {
44 |
45 | @Composable
46 | override fun RichTextScope.drawGutter() {
47 | with(LocalDensity.current) {
48 | val color = color(currentContentColor)
49 |
50 | val modifier = remember(startMargin, endMargin, barWidth, color) {
51 | // Padding must come before width.
52 | Modifier
53 | .padding(
54 | start = startMargin.toDp(),
55 | end = endMargin.toDp()
56 | )
57 | .width(barWidth.toDp())
58 | .background(color, RoundedCornerShape(50))
59 | }
60 |
61 | Box(modifier)
62 | }
63 | }
64 | }
65 | }
66 |
67 | /**
68 | * Draws a block quote, with a [BlockQuoteGutter] drawn beside the children on the start side.
69 | */
70 | @Composable public fun RichTextScope.BlockQuote(children: @Composable RichTextScope.() -> Unit) {
71 | val gutter = currentRichTextStyle.resolveDefaults().blockQuoteGutter!!
72 | val spacing = gutter.verticalContentPadding ?: with(LocalDensity.current) {
73 | currentRichTextStyle.resolveDefaults().paragraphSpacing!!.toDp() / 2
74 | }
75 |
76 | Layout(content = {
77 | with(gutter) { drawGutter() }
78 | BasicRichText(
79 | modifier = Modifier.padding(top = spacing, bottom = spacing),
80 | children = children
81 | )
82 | }) { measurables, constraints ->
83 | val gutterMeasurable = measurables[0]
84 | val contentsMeasurable = measurables[1]
85 |
86 | // First get the width of the gutter, so we can measure the contents with
87 | // the smaller width if bounded.
88 | val gutterWidth = gutterMeasurable.minIntrinsicWidth(constraints.maxHeight)
89 |
90 | // Measure the contents with the confined width.
91 | // This must be done before measuring the gutter so that the gutter gets
92 | // the correct height.
93 | val contentsConstraints = constraints.offset(horizontal = -gutterWidth)
94 | val contentsPlaceable = contentsMeasurable.measure(contentsConstraints)
95 | val layoutWidth = contentsPlaceable.width + gutterWidth
96 | val layoutHeight = contentsPlaceable.height
97 |
98 | // Measure the gutter to fit in its min intrinsic width and exactly the
99 | // height of the contents.
100 | val gutterConstraints = constraints.copy(
101 | maxWidth = gutterWidth,
102 | minHeight = layoutHeight,
103 | maxHeight = layoutHeight
104 | )
105 | val gutterPlaceable = gutterMeasurable.measure(gutterConstraints)
106 |
107 | layout(layoutWidth, layoutHeight) {
108 | gutterPlaceable.place(IntOffset.Zero)
109 | contentsPlaceable.place(gutterWidth, 0)
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/CodeBlock.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.layout.Box
5 | import androidx.compose.foundation.layout.padding
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.runtime.Immutable
8 | import androidx.compose.ui.Modifier
9 | import androidx.compose.ui.graphics.Color
10 | import androidx.compose.ui.platform.LocalDensity
11 | import androidx.compose.ui.text.TextStyle
12 | import androidx.compose.ui.text.font.FontFamily
13 | import androidx.compose.ui.unit.TextUnit
14 | import androidx.compose.ui.unit.sp
15 |
16 | /**
17 | * Defines how [CodeBlock]s are rendered.
18 | *
19 | * @param textStyle The [TextStyle] to use for the block.
20 | * @param modifier The [Modifier] to use for the block.
21 | * @param padding The amount of space between the edge of the text and the edge of the background.
22 | * @param wordWrap Whether a code block breaks the lines or scrolls horizontally.
23 | */
24 | @Immutable
25 | public data class CodeBlockStyle(
26 | val textStyle: TextStyle? = null,
27 | val modifier: Modifier? = null,
28 | val padding: TextUnit? = null,
29 | val wordWrap: Boolean? = null
30 | ) {
31 | public companion object {
32 | public val Default: CodeBlockStyle = CodeBlockStyle()
33 | }
34 | }
35 |
36 | private val DefaultCodeBlockTextStyle = TextStyle(
37 | fontFamily = FontFamily.Monospace
38 | )
39 | internal val DefaultCodeBlockBackgroundColor: Color = Color.LightGray.copy(alpha = .5f)
40 | private val DefaultCodeBlockModifier: Modifier =
41 | Modifier.background(color = DefaultCodeBlockBackgroundColor)
42 | private val DefaultCodeBlockPadding: TextUnit = 16.sp
43 | private const val DefaultCodeWordWrap: Boolean = true
44 |
45 | internal fun CodeBlockStyle.resolveDefaults() = CodeBlockStyle(
46 | textStyle = textStyle ?: DefaultCodeBlockTextStyle,
47 | modifier = modifier ?: DefaultCodeBlockModifier,
48 | padding = padding ?: DefaultCodeBlockPadding,
49 | wordWrap = wordWrap ?: DefaultCodeWordWrap
50 | )
51 |
52 | /**
53 | * A specially-formatted block of text that typically uses a monospace font with a tinted
54 | * background.
55 | *
56 | * @param wordWrap Overrides word wrap preference coming from [CodeBlockStyle]
57 | */
58 | @Composable public fun RichTextScope.CodeBlock(
59 | text: String,
60 | wordWrap: Boolean? = null
61 | ) {
62 | CodeBlock(wordWrap = wordWrap) {
63 | Text(text)
64 | }
65 | }
66 |
67 | /**
68 | * A specially-formatted block of text that typically uses a monospace font with a tinted
69 | * background.
70 | *
71 | * @param wordWrap Overrides word wrap preference coming from [CodeBlockStyle]
72 | */
73 | @Composable public fun RichTextScope.CodeBlock(
74 | wordWrap: Boolean? = null,
75 | children: @Composable RichTextScope.() -> Unit
76 | ) {
77 | val codeBlockStyle = currentRichTextStyle.resolveDefaults().codeBlockStyle!!
78 | val textStyle = currentTextStyle.merge(codeBlockStyle.textStyle)
79 | val modifier = codeBlockStyle.modifier!!
80 | val blockPadding = with(LocalDensity.current) {
81 | codeBlockStyle.padding!!.toDp()
82 | }
83 | val resolvedWordWrap = wordWrap ?: codeBlockStyle.wordWrap!!
84 |
85 | CodeBlockLayout(
86 | wordWrap = resolvedWordWrap
87 | ) { layoutModifier ->
88 | Box(
89 | modifier = layoutModifier
90 | .then(modifier)
91 | .padding(blockPadding)
92 | ) {
93 | textStyleBackProvider(textStyle) {
94 | children()
95 | }
96 | }
97 | }
98 | }
99 |
100 | /**
101 | * Desktop composable adds an optional horizontal scrollbar.
102 | */
103 | @Composable
104 | internal expect fun RichTextScope.CodeBlockLayout(
105 | wordWrap: Boolean,
106 | children: @Composable RichTextScope.(Modifier) -> Unit
107 | )
108 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/Heading.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry")
2 |
3 | package com.halilibo.richtext.ui
4 |
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.ui.Modifier
7 | import androidx.compose.ui.graphics.takeOrElse
8 | import androidx.compose.ui.platform.LocalLayoutDirection
9 | import androidx.compose.ui.semantics.heading
10 | import androidx.compose.ui.semantics.semantics
11 | import androidx.compose.ui.text.TextStyle
12 | import androidx.compose.ui.text.font.FontStyle.Companion.Italic
13 | import androidx.compose.ui.text.font.FontWeight
14 | import androidx.compose.ui.text.resolveDefaults
15 | import androidx.compose.ui.unit.sp
16 |
17 |
18 | /**
19 | * Function that computes the [TextStyle] for the given header level, given the current [TextStyle]
20 | * for this point in the composition. Note that the [TextStyle] passed into this function will be
21 | * fully resolved. The returned style will then be _merged_ with the passed-in text style, so any
22 | * unspecified properties will be inherited.
23 | */
24 | // TODO factor a generic "block style" thing out, use for code block, quote block, and this, to
25 | // also allow controlling top/bottom space.
26 | public typealias HeadingStyle = (level: Int, textStyle: TextStyle) -> TextStyle
27 |
28 | internal val DefaultHeadingStyle: HeadingStyle = { level, textStyle ->
29 | when (level) {
30 | 0 -> TextStyle(
31 | fontSize = 36.sp,
32 | fontWeight = FontWeight.Bold
33 | )
34 | 1 -> TextStyle(
35 | fontSize = 26.sp,
36 | fontWeight = FontWeight.Bold
37 | )
38 | 2 -> TextStyle(
39 | fontSize = 22.sp,
40 | fontWeight = FontWeight.Bold,
41 | color = textStyle.color.copy(alpha = .7F)
42 | )
43 | 3 -> TextStyle(
44 | fontSize = 20.sp,
45 | fontWeight = FontWeight.Bold,
46 | fontStyle = Italic
47 | )
48 | 4 -> TextStyle(
49 | fontSize = 18.sp,
50 | fontWeight = FontWeight.Bold,
51 | color = textStyle.color.copy(alpha = .7F)
52 | )
53 | 5 -> TextStyle(
54 | fontWeight = FontWeight.Bold,
55 | color = textStyle.color.copy(alpha = .5f)
56 | )
57 | else -> textStyle
58 | }
59 | }
60 |
61 | /**
62 | * A section heading.
63 | *
64 | * @param level The non-negative rank of the header, with 0 being the most important.
65 | */
66 | @Composable public fun RichTextScope.Heading(
67 | level: Int,
68 | text: String
69 | ) {
70 | Heading(level) {
71 | Text(text, Modifier.semantics { heading() })
72 | }
73 | }
74 |
75 | /**
76 | * A section heading.
77 | *
78 | * @param level The non-negative rank of the header, with 0 being the most important.
79 | */
80 | @Composable public fun RichTextScope.Heading(
81 | level: Int,
82 | children: @Composable RichTextScope.() -> Unit
83 | ) {
84 | require(level >= 0) { "Level must be at least 0" }
85 |
86 | val incomingStyle = currentTextStyle.let {
87 | it.copy(color = it.color.takeOrElse { currentContentColor })
88 | }
89 | val currentTextStyle = resolveDefaults(incomingStyle, LocalLayoutDirection.current)
90 |
91 | val headingStyleFunction = currentRichTextStyle.resolveDefaults().headingStyle!!
92 | val headingTextStyle = headingStyleFunction(level, currentTextStyle)
93 | val mergedTextStyle = currentTextStyle.merge(headingTextStyle)
94 |
95 | textStyleBackProvider(mergedTextStyle) {
96 | children()
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/HorizontalRule.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.layout.Box
5 | import androidx.compose.foundation.layout.fillMaxWidth
6 | import androidx.compose.foundation.layout.height
7 | import androidx.compose.foundation.layout.padding
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.runtime.Immutable
10 | import androidx.compose.ui.Modifier
11 | import androidx.compose.ui.graphics.Color
12 | import androidx.compose.ui.platform.LocalDensity
13 | import androidx.compose.ui.unit.Dp
14 | import androidx.compose.ui.unit.dp
15 |
16 | @Immutable
17 | public data class HorizontalRuleStyle(
18 | val color: Color? = null,
19 | val spacing: Dp? = null,
20 | ) {
21 | public companion object {
22 | public val Default: HorizontalRuleStyle = HorizontalRuleStyle()
23 | }
24 | }
25 |
26 | internal fun HorizontalRuleStyle.resolveDefaults() = HorizontalRuleStyle(
27 | color = color,
28 | spacing = spacing,
29 | )
30 |
31 | /**
32 | * A simple horizontal line drawn with the current content color.
33 | */
34 | @Composable public fun RichTextScope.HorizontalRule() {
35 | val resolvedStyle = currentRichTextStyle.resolveDefaults()
36 | val horizontalRuleStyle = resolvedStyle.horizontalRuleStyle
37 | val color = horizontalRuleStyle?.color ?: currentContentColor.copy(alpha = .2f)
38 | val spacing = horizontalRuleStyle?.spacing ?: with(LocalDensity.current) {
39 | resolvedStyle.paragraphSpacing!!.toDp()
40 | }
41 | Box(
42 | Modifier
43 | .padding(top = spacing, bottom = spacing)
44 | .fillMaxWidth()
45 | .height(1.dp)
46 | .background(color)
47 | )
48 | }
49 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/InfoPanel.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.border
5 | import androidx.compose.foundation.layout.Box
6 | import androidx.compose.foundation.layout.PaddingValues
7 | import androidx.compose.foundation.layout.padding
8 | import androidx.compose.foundation.shape.RoundedCornerShape
9 | import androidx.compose.runtime.Composable
10 | import androidx.compose.runtime.Stable
11 | import androidx.compose.runtime.remember
12 | import androidx.compose.ui.Modifier
13 | import androidx.compose.ui.graphics.Color
14 | import androidx.compose.ui.text.TextStyle
15 | import androidx.compose.ui.unit.dp
16 | import com.halilibo.richtext.ui.InfoPanelType.Danger
17 | import com.halilibo.richtext.ui.InfoPanelType.Primary
18 | import com.halilibo.richtext.ui.InfoPanelType.Secondary
19 | import com.halilibo.richtext.ui.InfoPanelType.Success
20 | import com.halilibo.richtext.ui.InfoPanelType.Warning
21 |
22 | @Stable
23 | public data class InfoPanelStyle(
24 | val contentPadding: PaddingValues? = null,
25 | val background: @Composable ((InfoPanelType) -> Modifier)? = null,
26 | val textStyle: @Composable ((InfoPanelType) -> TextStyle)? = null
27 | ) {
28 | public companion object {
29 | public val Default: InfoPanelStyle = InfoPanelStyle()
30 | }
31 | }
32 |
33 | public enum class InfoPanelType {
34 | Primary,
35 | Secondary,
36 | Success,
37 | Danger,
38 | Warning
39 | }
40 |
41 | private val DefaultContentPadding = PaddingValues(8.dp)
42 | private val DefaultInfoPanelBackground = @Composable { infoPanelType: InfoPanelType ->
43 | remember {
44 | val (borderColor, backgroundColor) = when (infoPanelType) {
45 | Primary -> Color(0xffb8daff) to Color(0xffcce5ff)
46 | Secondary -> Color(0xffd6d8db) to Color(0xffe2e3e5)
47 | Success -> Color(0xffc3e6cb) to Color(0xffd4edda)
48 | Danger -> Color(0xfff5c6cb) to Color(0xfff8d7da)
49 | Warning -> Color(0xffffeeba) to Color(0xfffff3cd)
50 | }
51 |
52 | Modifier
53 | .border(1.dp, borderColor, RoundedCornerShape(4.dp))
54 | .background(backgroundColor, RoundedCornerShape(4.dp))
55 | }
56 | }
57 |
58 | private val DefaultInfoPanelTextStyle = @Composable { infoPanelType: InfoPanelType ->
59 | remember {
60 | val color = when(infoPanelType) {
61 | Primary -> Color(0xff004085)
62 | Secondary -> Color(0xff383d41)
63 | Success -> Color(0xff155724)
64 | Danger -> Color(0xff721c24)
65 | Warning -> Color(0xff856404)
66 | }
67 | TextStyle(color = color)
68 | }
69 | }
70 |
71 | internal fun InfoPanelStyle.resolveDefaults() = InfoPanelStyle(
72 | contentPadding = contentPadding ?: DefaultContentPadding,
73 | background = background ?: DefaultInfoPanelBackground,
74 | textStyle = textStyle ?: DefaultInfoPanelTextStyle
75 | )
76 |
77 | /**
78 | * A panel to show content similar to Bootstrap alerts, categorized as [InfoPanelType].
79 | * This composable is a shortcut to show only [text] in an info panel.
80 | */
81 | @Composable
82 | public fun RichTextScope.InfoPanel(
83 | infoPanelType: InfoPanelType,
84 | text: String
85 | ) {
86 | InfoPanel(infoPanelType) {
87 | Text(text)
88 | }
89 | }
90 |
91 | /**
92 | * A panel to show content similar to Bootstrap alerts, categorized as [InfoPanelType].
93 | */
94 | @Composable
95 | public fun RichTextScope.InfoPanel(
96 | infoPanelType: InfoPanelType,
97 | content: @Composable () -> Unit
98 | ) {
99 | val infoPanelStyle = currentRichTextStyle.resolveDefaults().infoPanelStyle!!
100 | val backgroundModifier = infoPanelStyle.background!!.invoke(infoPanelType)
101 | val infoPanelTextStyle = infoPanelStyle.textStyle!!.invoke(infoPanelType)
102 |
103 | val resolvedTextStyle = currentTextStyle.merge(infoPanelTextStyle)
104 |
105 | textStyleBackProvider(resolvedTextStyle) {
106 | Box(modifier = backgroundModifier.padding(infoPanelStyle.contentPadding!!)) {
107 | content()
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextLocals.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.foundation.text.BasicText
4 | import androidx.compose.foundation.text.InlineTextContent
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.runtime.compositionLocalOf
7 | import androidx.compose.runtime.mutableStateOf
8 | import androidx.compose.runtime.remember
9 | import androidx.compose.ui.Modifier
10 | import androidx.compose.ui.geometry.Offset
11 | import androidx.compose.ui.graphics.Color
12 | import androidx.compose.ui.graphics.takeOrElse
13 | import androidx.compose.ui.input.pointer.pointerInput
14 | import androidx.compose.ui.text.AnnotatedString
15 | import androidx.compose.ui.text.TextLayoutResult
16 | import androidx.compose.ui.text.TextStyle
17 | import androidx.compose.ui.text.style.TextOverflow
18 | import com.halilibo.richtext.ui.util.detectTapGesturesIf
19 |
20 | /**
21 | * Carries the text style in Composition tree. [Heading], [CodeBlock],
22 | * [BlockQuote] are designed to change the ongoing [TextStyle] in composition,
23 | * so that their children can use the modified text style implicitly.
24 | *
25 | * LocalTextStyle also exists in Material package but this one is internal
26 | * to RichText.
27 | */
28 | internal val LocalInternalTextStyle = compositionLocalOf { TextStyle.Default }
29 |
30 | /**
31 | * Carries the content color in Composition tree. Default TextStyle
32 | * does not have text color specified. It defaults to [Color.Black]
33 | * in the "resolve chain" but Dark Mode is an exception. To also resolve
34 | * for Dark Mode, content color should be passed to [RichTextScope].
35 | */
36 | internal val LocalInternalContentColor = compositionLocalOf { Color.Black }
37 |
38 | /**
39 | * The current [TextStyle].
40 | */
41 | internal val RichTextScope.currentTextStyle: TextStyle
42 | @Composable get() = textStyleProvider()
43 |
44 | /**
45 | * The current content [Color].
46 | */
47 | internal val RichTextScope.currentContentColor: Color
48 | @Composable get() = contentColorProvider()
49 |
50 | /**
51 | * Intended for preview composables.
52 | */
53 | @Composable
54 | internal fun RichTextScope.Text(
55 | text: String,
56 | modifier: Modifier = Modifier,
57 | onTextLayout: (TextLayoutResult) -> Unit = {},
58 | overflow: TextOverflow = TextOverflow.Clip,
59 | softWrap: Boolean = true,
60 | maxLines: Int = Int.MAX_VALUE
61 | ) {
62 | val textColor = currentTextStyle.color.takeOrElse { currentContentColor }
63 | val style = currentTextStyle.copy(color = textColor)
64 |
65 | BasicText(
66 | text = text,
67 | modifier = modifier,
68 | style = style,
69 | onTextLayout = onTextLayout,
70 | overflow = overflow,
71 | softWrap = softWrap,
72 | maxLines = maxLines
73 | )
74 | }
75 |
76 | @Composable
77 | internal fun RichTextScope.Text(
78 | text: AnnotatedString,
79 | modifier: Modifier = Modifier,
80 | onTextLayout: (TextLayoutResult) -> Unit = {},
81 | overflow: TextOverflow = TextOverflow.Clip,
82 | softWrap: Boolean = true,
83 | maxLines: Int = Int.MAX_VALUE,
84 | inlineContent: Map = mapOf(),
85 | ) {
86 | val textColor = currentTextStyle.color.takeOrElse { currentContentColor }
87 | val style = currentTextStyle.copy(color = textColor)
88 |
89 | BasicText(
90 | text = text,
91 | modifier = modifier,
92 | style = style,
93 | onTextLayout = onTextLayout,
94 | overflow = overflow,
95 | softWrap = softWrap,
96 | maxLines = maxLines,
97 | inlineContent = inlineContent
98 | )
99 | }
100 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextScope.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry")
2 |
3 | package com.halilibo.richtext.ui
4 |
5 | import androidx.compose.runtime.CompositionLocal
6 | import androidx.compose.runtime.Immutable
7 | import androidx.compose.runtime.State
8 |
9 | /**
10 | * Scope object for composables that can draw rich text.
11 | *
12 | * RichTextScope facilitates a context for RichText elements. It does not
13 | * behave like a [State] or a [CompositionLocal]. Starting from [BasicRichText],
14 | * this scope carries information that should not be passed down as a state.
15 | */
16 | @Immutable
17 | public object RichTextScope
18 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextStyle.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.CompositionLocalProvider
5 | import androidx.compose.runtime.Immutable
6 | import androidx.compose.runtime.compositionLocalOf
7 | import androidx.compose.ui.unit.TextUnit
8 | import androidx.compose.ui.unit.sp
9 | import com.halilibo.richtext.ui.string.RichTextStringStyle
10 |
11 | internal val LocalRichTextStyle = compositionLocalOf { RichTextStyle.Default }
12 | internal val DefaultParagraphSpacing: TextUnit = 8.sp
13 |
14 | /**
15 | * Configures all formatting attributes for drawing rich text.
16 | *
17 | * @param paragraphSpacing The amount of space in between blocks of text.
18 | * @param headingStyle The [HeadingStyle] that defines how [Heading]s are drawn.
19 | * @param listStyle The [ListStyle] used to format [FormattedList]s.
20 | * @param blockQuoteGutter The [BlockQuoteGutter] used to draw [BlockQuote]s.
21 | * @param codeBlockStyle The [CodeBlockStyle] that defines how [CodeBlock]s are drawn.
22 | * @param tableStyle The [TableStyle] used to render [Table]s.
23 | * @param stringStyle The [RichTextStringStyle] used to render
24 | * [RichTextString][com.halilibo.richtext.ui.string.RichTextString]s
25 | */
26 | @Immutable
27 | public data class RichTextStyle(
28 | val paragraphSpacing: TextUnit? = null,
29 | val headingStyle: HeadingStyle? = null,
30 | val listStyle: ListStyle? = null,
31 | val blockQuoteGutter: BlockQuoteGutter? = null,
32 | val codeBlockStyle: CodeBlockStyle? = null,
33 | val tableStyle: TableStyle? = null,
34 | val horizontalRuleStyle: HorizontalRuleStyle? = null,
35 | val infoPanelStyle: InfoPanelStyle? = null,
36 | val stringStyle: RichTextStringStyle? = null,
37 | ) {
38 | public companion object {
39 | public val Default: RichTextStyle = RichTextStyle()
40 | }
41 | }
42 |
43 | public fun RichTextStyle.merge(otherStyle: RichTextStyle?): RichTextStyle = RichTextStyle(
44 | paragraphSpacing = otherStyle?.paragraphSpacing ?: paragraphSpacing,
45 | headingStyle = otherStyle?.headingStyle ?: headingStyle,
46 | listStyle = otherStyle?.listStyle ?: listStyle,
47 | blockQuoteGutter = otherStyle?.blockQuoteGutter ?: blockQuoteGutter,
48 | codeBlockStyle = otherStyle?.codeBlockStyle ?: codeBlockStyle,
49 | tableStyle = otherStyle?.tableStyle ?: tableStyle,
50 | horizontalRuleStyle = otherStyle?.horizontalRuleStyle ?: horizontalRuleStyle,
51 | infoPanelStyle = otherStyle?.infoPanelStyle ?: infoPanelStyle,
52 | stringStyle = stringStyle?.merge(otherStyle?.stringStyle) ?: otherStyle?.stringStyle,
53 | )
54 |
55 | public fun RichTextStyle.resolveDefaults(): RichTextStyle = RichTextStyle(
56 | paragraphSpacing = paragraphSpacing ?: DefaultParagraphSpacing,
57 | headingStyle = headingStyle ?: DefaultHeadingStyle,
58 | listStyle = (listStyle ?: ListStyle.Default).resolveDefaults(),
59 | blockQuoteGutter = blockQuoteGutter ?: DefaultBlockQuoteGutter,
60 | codeBlockStyle = (codeBlockStyle ?: CodeBlockStyle.Default).resolveDefaults(),
61 | tableStyle = (tableStyle ?: TableStyle.Default).resolveDefaults(),
62 | horizontalRuleStyle = (horizontalRuleStyle ?: HorizontalRuleStyle.Default).resolveDefaults(),
63 | infoPanelStyle = (infoPanelStyle ?: InfoPanelStyle.Default).resolveDefaults(),
64 | stringStyle = (stringStyle ?: RichTextStringStyle.Default).resolveDefaults()
65 | )
66 |
67 | /**
68 | * The current [RichTextStyle].
69 | */
70 | public val RichTextScope.currentRichTextStyle: RichTextStyle
71 | @Composable get() = LocalRichTextStyle.current
72 |
73 | /**
74 | * Sets the [RichTextStyle] for its [children].
75 | */
76 | @Composable
77 | public fun RichTextScope.WithStyle(
78 | style: RichTextStyle?,
79 | children: @Composable RichTextScope.() -> Unit
80 | ) {
81 | if (style == null) {
82 | children()
83 | } else {
84 | val mergedStyle = LocalRichTextStyle.current.merge(style)
85 | CompositionLocalProvider(LocalRichTextStyle provides mergedStyle) {
86 | children()
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextThemeConfiguration.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.CompositionLocalProvider
5 | import androidx.compose.runtime.ProvidableCompositionLocal
6 | import androidx.compose.runtime.compositionLocalOf
7 | import androidx.compose.ui.graphics.Color
8 | import androidx.compose.ui.text.TextStyle
9 |
10 | internal typealias TextStyleProvider = @Composable () -> TextStyle
11 | internal typealias TextStyleBackProvider = @Composable (TextStyle, @Composable () -> Unit) -> Unit
12 | internal typealias ContentColorProvider = @Composable () -> Color
13 | internal typealias ContentColorBackProvider = @Composable (Color, @Composable () -> Unit) -> Unit
14 |
15 | internal data class RichTextThemeConfiguration(
16 | val textStyleProvider: TextStyleProvider = { LocalInternalTextStyle.current },
17 | val textStyleBackProvider: TextStyleBackProvider = { newTextStyle, content ->
18 | CompositionLocalProvider(LocalInternalTextStyle provides newTextStyle) {
19 | content()
20 | }
21 | },
22 | val contentColorProvider: ContentColorProvider = { LocalInternalContentColor.current },
23 | val contentColorBackProvider: ContentColorBackProvider = { newColor, content ->
24 | CompositionLocalProvider(LocalInternalContentColor provides newColor) {
25 | content()
26 | }
27 | }
28 | ) {
29 | companion object {
30 | internal val Default = RichTextThemeConfiguration()
31 | }
32 | }
33 |
34 | internal val LocalRichTextThemeConfiguration: ProvidableCompositionLocal =
35 | compositionLocalOf { RichTextThemeConfiguration() }
36 |
37 | /**
38 | * Easy access delegations for [RichTextThemeProvider] within [RichTextScope]
39 | */
40 | internal val RichTextScope.textStyleProvider: @Composable () -> TextStyle
41 | @Composable get() = LocalRichTextThemeConfiguration.current.textStyleProvider
42 |
43 | internal val RichTextScope.textStyleBackProvider: @Composable (TextStyle, @Composable () -> Unit) -> Unit
44 | @Composable get() = LocalRichTextThemeConfiguration.current.textStyleBackProvider
45 |
46 | internal val RichTextScope.contentColorProvider: @Composable () -> Color
47 | @Composable get() = LocalRichTextThemeConfiguration.current.contentColorProvider
48 |
49 | internal val RichTextScope.contentColorBackProvider: @Composable (Color, @Composable () -> Unit) -> Unit
50 | @Composable get() = LocalRichTextThemeConfiguration.current.contentColorBackProvider
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/RichTextThemeProvider.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.CompositionLocalProvider
5 | import androidx.compose.ui.graphics.Color
6 | import androidx.compose.ui.text.TextStyle
7 |
8 | /**
9 | * Entry point for integrating app's own typography and theme system with RichText.
10 | *
11 | * API for this integration is highly influenced by how compose-material theming
12 | * is designed. RichText library assumes that almost all Theme/Design systems would
13 | * have composition locals that provide text style downstream.
14 | *
15 | * Moreover, text style should not include text color by best practice. Content color
16 | * exists to figure text color in current context. Light/Dark theming leverages content
17 | * color to influence not just text but other parts of theming as well.
18 | *
19 | * @param textStyleProvider Returns the current text style.
20 | * @param textStyleBackProvider RichText sometimes updates the current text style
21 | * e.g. Heading, CodeBlock, and etc. New style should be passed to the outer
22 | * theming to indicate that there is a need for update, so that children Text
23 | * composables use the correct styling.
24 | * @param contentColorProvider Returns the current content color.
25 | * @param contentColorBackProvider Similar to [textStyleBackProvider], does the same job
26 | * for content color.
27 | */
28 | @Composable
29 | public fun RichTextThemeProvider(
30 | textStyleProvider: @Composable (() -> TextStyle)? = null,
31 | textStyleBackProvider: @Composable ((TextStyle, @Composable () -> Unit) -> Unit)? = null,
32 | contentColorProvider: @Composable (() -> Color)? = null,
33 | contentColorBackProvider: @Composable ((Color, @Composable () -> Unit) -> Unit)? = null,
34 | content: @Composable () -> Unit
35 | ) {
36 | CompositionLocalProvider(
37 | LocalRichTextThemeConfiguration provides
38 | RichTextThemeConfiguration(
39 | textStyleProvider = textStyleProvider
40 | ?: RichTextThemeConfiguration.Default.textStyleProvider,
41 | textStyleBackProvider = textStyleBackProvider
42 | ?: RichTextThemeConfiguration.Default.textStyleBackProvider,
43 | contentColorProvider = contentColorProvider
44 | ?: RichTextThemeConfiguration.Default.contentColorProvider,
45 | contentColorBackProvider = contentColorBackProvider
46 | ?: RichTextThemeConfiguration.Default.contentColorBackProvider,
47 | )
48 | ) {
49 | content()
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/TableLayout.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.foundation.layout.Box
4 | import androidx.compose.runtime.Composable
5 | import androidx.compose.runtime.Immutable
6 | import androidx.compose.ui.Modifier
7 | import androidx.compose.ui.layout.SubcomposeLayout
8 | import androidx.compose.ui.unit.Constraints
9 | import kotlin.math.roundToInt
10 |
11 |
12 | /**
13 | * The offsets of rows and columns of a [TableLayout], centered inside their spacing.
14 | *
15 | * E.g. If a table is given a cell spacing of 2px, then the first column and row offset will each
16 | * be 1px.
17 | */
18 | @Immutable
19 | internal data class TableLayoutResult(
20 | val rowOffsets: List,
21 | val columnOffsets: List
22 | )
23 |
24 | @Composable
25 | internal fun TableLayout(
26 | columns: Int,
27 | rows: List Unit>>,
28 | hasHeader: Boolean,
29 | drawDecorations: (TableLayoutResult) -> Modifier,
30 | cellSpacing: Float,
31 | tableMeasurer: TableMeasurer,
32 | modifier: Modifier = Modifier
33 | ) {
34 | SubcomposeLayout(modifier = modifier) { constraints ->
35 | // Subcompose all cells in one pass.
36 | val measurables = subcompose("cells") {
37 | rows.forEach { row ->
38 | check(row.size == columns)
39 | row.forEach { cell -> cell() }
40 | }
41 | }
42 |
43 | val rowMeasurables = measurables.chunked(columns)
44 | val measurements = tableMeasurer.measure(rowMeasurables, constraints)
45 |
46 | val tableWidth = measurements.columnWidths.sum() +
47 | (cellSpacing * (columns + 1)).roundToInt()
48 |
49 | val tableHeight = measurements.rowHeights.sum() +
50 | (cellSpacing * (measurements.rowHeights.size + 1)).roundToInt()
51 |
52 | layout(tableWidth, tableHeight) {
53 | var y = cellSpacing
54 | val rowOffsets = mutableListOf()
55 | val columnOffsets = mutableListOf()
56 |
57 | measurements.rowPlaceables.forEachIndexed { rowIndex, cellPlaceables ->
58 | rowOffsets += y - cellSpacing / 2f
59 | var x = cellSpacing
60 |
61 | cellPlaceables.forEachIndexed { columnIndex, cell ->
62 | if (rowIndex == 0) {
63 | columnOffsets.add(x - cellSpacing / 2f)
64 | }
65 |
66 | val cellY = if (hasHeader && rowIndex == 0) {
67 | // Header is bottom-aligned
68 | y + (measurements.rowHeights[0] - cell.height)
69 | } else {
70 | y
71 | }
72 | cell.place(x.roundToInt(), cellY.roundToInt())
73 | x += measurements.columnWidths[columnIndex] + cellSpacing
74 | }
75 |
76 | if (rowIndex == 0) {
77 | // Add the right-most edge.
78 | columnOffsets.add(x - cellSpacing / 2f)
79 | }
80 |
81 | y += measurements.rowHeights[rowIndex] + cellSpacing
82 | }
83 |
84 | rowOffsets.add(y - cellSpacing / 2f)
85 |
86 | // Compose and draw the borders.
87 | val layoutResult = TableLayoutResult(rowOffsets, columnOffsets)
88 | subcompose(true) {
89 | Box(modifier = drawDecorations(layoutResult))
90 | }.single()
91 | .measure(Constraints.fixed(tableWidth, tableHeight))
92 | .placeRelative(0, 0)
93 | }
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/TableMeasurer.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.ui.layout.Measurable
4 | import androidx.compose.ui.layout.Placeable
5 | import androidx.compose.ui.unit.Constraints
6 | import androidx.compose.ui.unit.constrain
7 | import com.halilibo.richtext.ui.TableMeasurer.Measurements
8 | import kotlin.math.roundToInt
9 |
10 | private const val MinCellWidth = 10
11 |
12 | internal interface TableMeasurer {
13 | fun measure(
14 | rowMeasurables: List>,
15 | constraints: Constraints,
16 | ): Measurements
17 |
18 | data class Measurements(
19 | val rowPlaceables: List>,
20 | val columnWidths: List,
21 | val rowHeights: List,
22 | )
23 | }
24 |
25 | internal class AdaptiveTableMeasurer(
26 | private val maxCellWidthPx: Int,
27 | ): TableMeasurer {
28 | override fun measure(
29 | rowMeasurables: List>,
30 | constraints: Constraints,
31 | ): Measurements {
32 | val columns = rowMeasurables[0].size
33 | val cellConstraints = Constraints(maxWidth = maxCellWidthPx)
34 | val rowPlaceables = rowMeasurables.map { row ->
35 | row.map { measurable ->
36 | measurable.measure(cellConstraints)
37 | }
38 | }
39 |
40 | // Determine the width for each column
41 | val columnWidths = (0 until columns).map { colIndex ->
42 | val measuredMax = rowPlaceables.maxOfOrNull { it[colIndex].width } ?: 0
43 | maxOf(measuredMax, MinCellWidth)
44 | }
45 |
46 | // Each row’s height is the maximum cell height in that row.
47 | val rowHeights = rowPlaceables.map { row ->
48 | row.maxOf { it.height }
49 | }
50 |
51 | return Measurements(rowPlaceables, columnWidths, rowHeights)
52 | }
53 | }
54 |
55 | internal class UniformTableMeasurer(
56 | private val cellSpacing: Float
57 | ) : TableMeasurer {
58 | override fun measure(
59 | rowMeasurables: List>,
60 | constraints: Constraints,
61 | ): Measurements {
62 | check(constraints.hasBoundedWidth) { "Uniform tables must have bounded width" }
63 |
64 | val columns = rowMeasurables[0].size
65 | // Divide the width by the number of columns, then leave room for the padding.
66 | val cellSpacingWidth = cellSpacing * (columns + 1)
67 | val cellWidth = maxOf(
68 | (constraints.maxWidth - cellSpacingWidth) / columns,
69 | MinCellWidth.toFloat()
70 | )
71 | // TODO Handle bounded height constraints.
72 | //val cellSpacingHeight = cellSpacing * (rowMeasurables.size + 1)
73 | // val cellMaxHeight = if (!constraints.hasBoundedHeight) {
74 | // Float.MAX_VALUE
75 | // } else {
76 | // // Divide the height by the number of rows, then leave room for the padding.
77 | // (constraints.maxHeight - cellSpacingHeight) / rowMeasurables.size
78 | // }
79 | val cellConstraints = Constraints(maxWidth = cellWidth.roundToInt()).constrain(constraints)
80 |
81 | val rowPlaceables = rowMeasurables.map { cellMeasurables ->
82 | cellMeasurables.map { cell ->
83 | cell.measure(cellConstraints)
84 | }
85 | }
86 | val rowHeights = rowPlaceables.map { row -> row.maxByOrNull { it.height }!!.height }
87 | val columnWidths = List(columns) { cellWidth.roundToInt() }
88 |
89 | return Measurements(rowPlaceables, columnWidths, rowHeights)
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/string/InlineContent.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("RemoveEmptyParenthesesFromAnnotationEntry", "FunctionName")
2 |
3 | package com.halilibo.richtext.ui.string
4 |
5 | import androidx.compose.foundation.text.InlineTextContent
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.runtime.State
8 | import androidx.compose.runtime.getValue
9 | import androidx.compose.runtime.mutableStateOf
10 | import androidx.compose.runtime.remember
11 | import androidx.compose.runtime.setValue
12 | import androidx.compose.runtime.structuralEqualityPolicy
13 | import androidx.compose.ui.layout.Layout
14 | import androidx.compose.ui.platform.LocalDensity
15 | import androidx.compose.ui.text.Placeholder
16 | import androidx.compose.ui.text.PlaceholderVerticalAlign
17 | import androidx.compose.ui.text.PlaceholderVerticalAlign.Companion.AboveBaseline
18 | import androidx.compose.ui.unit.Constraints
19 | import androidx.compose.ui.unit.Density
20 | import androidx.compose.ui.unit.IntSize
21 | import androidx.compose.ui.unit.sp
22 |
23 | /**
24 | * A Composable that can be embedded inline in a [RichTextString] by passing to
25 | * [RichTextString.Builder.appendInlineContent].
26 | *
27 | * @param initialSize Optional function to calculate the initial size of the content. Not specifying
28 | * this may cause flicker.
29 | * @param placeholderVerticalAlign Used to specify how a placeholder is vertically aligned within a
30 | * text line.
31 | */
32 | public class InlineContent(
33 | internal val renderOnNewLine: Boolean = false,
34 | internal val initialSize: (Density.() -> IntSize)? = null,
35 | internal val placeholderVerticalAlign: PlaceholderVerticalAlign = AboveBaseline,
36 | internal val content: @Composable Density.(alternateText: String) -> Unit
37 | )
38 |
39 | /**
40 | * Converts a map of [InlineContent]s into a map of [InlineTextContent] that is ready to pass to
41 | * the core Text composable. Whenever any of the contents resize themselves, or if the map changes,
42 | * a new map will be returned with updated [Placeholder]s.
43 | */
44 | @Composable internal fun manageInlineTextContents(
45 | inlineContents: Map,
46 | textConstraints: State,
47 | ): Map {
48 | val density = LocalDensity.current
49 |
50 | return inlineContents.mapValues { (_, content) ->
51 | reifyInlineContent(content, textConstraints, density)
52 | }
53 | }
54 |
55 | /**
56 | * Given an [InlineContent] function, wraps it in a [InlineTextContent] that will allow the content
57 | * to measure itself inside the enclosing layout's maximum constraints, and automatically return a
58 | * new [InlineTextContent] whenever the content changes size to update how much space is reserved
59 | * in the text layout for the content.
60 | */
61 | @Composable private fun reifyInlineContent(
62 | content: InlineContent,
63 | contentConstraints: State,
64 | density: Density,
65 | ): InlineTextContent {
66 | var size by remember {
67 | mutableStateOf(
68 | content.initialSize?.invoke(density),
69 | structuralEqualityPolicy()
70 | )
71 | }
72 |
73 | // If size is null, content hasn't been measured yet, so just draw with zero width for now.
74 | // Set the height to 1 em so we can calculate how many pixels in an EM.
75 | val placeholder = with(density) {
76 | Placeholder(
77 | width = size?.width?.toSp() ?: 0.sp,
78 | height = size?.height?.toSp() ?: 1.sp,
79 | placeholderVerticalAlign = content.placeholderVerticalAlign
80 | )
81 | }
82 |
83 | return InlineTextContent(placeholder) { alternateText ->
84 | Layout(content = { content.content(density, alternateText) }) { measurables, _ ->
85 | // Measure the content with the constraints for the parent Text layout, not the actual.
86 | // This allows it to determine exactly how large it needs to be so we can update the
87 | // placeholder.
88 | val contentPlaceable = measurables.singleOrNull()?.measure(contentConstraints.value)
89 | ?: return@Layout layout(0, 0) {}
90 |
91 | // If the inline content changes in size, there will be one layout pass in which
92 | // the text layout placeholder and composable size will be out of sync.
93 | // In some cases, the composable will be larger than the placeholder.
94 | // If that happens, we need to offset the layout so that the composable starts
95 | // in the right place and overhangs the end. Without this, Compose will place the
96 | // composable centered inside of its smaller placeholder which makes the content shift
97 | // left for one frame and is more jarring.
98 | val extraWidth = (contentPlaceable.width - (size?.width ?: contentPlaceable.width))
99 | .coerceAtLeast(0)
100 | val extraHeight = (contentPlaceable.height - (size?.height ?: contentPlaceable.height))
101 | .coerceAtLeast(0)
102 |
103 | if (contentPlaceable.width != size?.width
104 | || contentPlaceable.height != size?.height
105 | ) {
106 | size = IntSize(contentPlaceable.width, contentPlaceable.height)
107 | }
108 |
109 | layout(contentPlaceable.width, contentPlaceable.height) {
110 | contentPlaceable.placeRelative(extraWidth / 2, extraHeight / 2)
111 | }
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/string/RichTextRenderOptions.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui.string
2 |
3 | /**
4 | * Allows configuration of the Markdown renderer
5 | */
6 | public data class RichTextRenderOptions(
7 | val animate: Boolean = false,
8 | val textFadeInMs: Int = 500,
9 | val debounceMs: Int = 100050,
10 | val delayMs: Int = 70,
11 | val delayExponent: Double = 0.7,
12 | val maxPhraseLength: Int = 30,
13 | val phraseMarkersOverride: List? = null,
14 | val onTextAnimate: () -> Unit = {},
15 | val onPhraseAnimate: () -> Unit = {},
16 | ) {
17 | public companion object {
18 | public val Default: RichTextRenderOptions = RichTextRenderOptions()
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/util/AnnotatedStringSegmenter.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui.util
2 |
3 | import androidx.compose.ui.text.AnnotatedString
4 | import com.halilibo.richtext.ui.string.RichTextRenderOptions
5 |
6 | public data class PhraseAnnotatedString(
7 | val annotatedString: AnnotatedString = AnnotatedString(""),
8 | val phraseSegments: List = emptyList(),
9 | val isComplete: Boolean = false
10 | ) {
11 | public fun makeCompletePhraseString(isComplete: Boolean): AnnotatedString {
12 | return when {
13 | isComplete -> annotatedString
14 | else -> annotatedString.subSequence(0,
15 | annotatedString.length.coerceAtMost(
16 | phraseSegments.lastOrNull() ?: annotatedString.length))
17 | }
18 | }
19 |
20 | public fun hasNewPhrasesFrom(other: PhraseAnnotatedString): Boolean {
21 | return phraseSegments.lastOrNull() != other.phraseSegments.lastOrNull()
22 | }
23 | }
24 |
25 | public fun AnnotatedString.segmentIntoPhrases(
26 | renderOptions: RichTextRenderOptions,
27 | isComplete: Boolean = false,
28 | ): PhraseAnnotatedString {
29 | val stylePhrases = stylePhrases()
30 | val phraseMarkers = renderOptions.phraseMarkersOverride ?: phraseMarkers
31 | val phrases = stylePhrases
32 | .map { it.split(delimiters = phraseMarkers.toCharArray(), ignoreCase = false) }
33 | .flatten()
34 | val phraseSegments = mutableListOf(0)
35 | for (phrase in phrases) {
36 | if (phrase != phrases.last()) {
37 | if (phrase.length > renderOptions.maxPhraseLength * 1.2) {
38 | phraseSegments.add(phraseSegments.last() + renderOptions.maxPhraseLength)
39 | }
40 | phraseSegments.add(text.length.coerceAtMost(phraseSegments.last() + phrase.length + 1))
41 | }
42 | }
43 | if (isComplete || phrases.lastOrNull()?.lastOrNull() in phraseMarkers) {
44 | phraseSegments.add(text.length)
45 | }
46 | return PhraseAnnotatedString(
47 | annotatedString = this,
48 | phraseSegments = phraseSegments.distinct().filter { it <= text.length },
49 | isComplete = isComplete,
50 | )
51 | }
52 |
53 | private fun AnnotatedString.stylePhrases(): List {
54 | val spans = (listOf(0, text.length) + spanStyles.map { listOf(it.start, it.end) }.flatten())
55 | .sortedBy { it }
56 | .filter { it <= text.length }
57 | .distinct()
58 | return spans.zipWithNext{ firstIndex, secondIndex -> text.substring(firstIndex, secondIndex) }
59 | }
60 |
61 | private val phraseMarkers = listOf(
62 | ' ', // Space
63 | '.', // Period
64 | '!', // Exclamation mark
65 | '?', // Question mark
66 | ',', // Comma
67 | ';', // Semicolon
68 | ':', // Colon
69 | '\n', // Newline
70 | '\r', // Carriage return
71 | '\t', // Tab
72 | '…', // Ellipsis
73 | '—', // Em dash
74 | '·', // Interpunct
75 | '¡', // Inverted exclamation mark
76 | '¿', // Inverted question mark
77 | '。', // Chinese/Japanese period
78 | '、', // Chinese/Japanese comma
79 | ',', // Chinese/Japanese full-width comma
80 | '?', // Full-width question mark
81 | '!', // Full-width exclamation mark
82 | ':', // Full-width colon
83 | ';', // Full-width semicolon
84 | '…', // Ellipsis
85 | '¡', // Inverted exclamation mark
86 | '¿', // Inverted question mark
87 | '።', // Ethiopic full stop
88 | '፣', // Ethiopic comma
89 | '፤', // Ethiopic semicolon
90 | '፥', // Ethiopic colon
91 | '፦', // Ethiopic preface colon
92 | '፧', // Ethiopic question mark
93 | '፨' // Ethiopic paragraph separator
94 | )
95 |
--------------------------------------------------------------------------------
/richtext-ui/src/commonMain/kotlin/com/halilibo/richtext/ui/util/UUID.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui.util
2 |
3 | internal expect fun randomUUID(): String
--------------------------------------------------------------------------------
/richtext-ui/src/jvmMain/kotlin/com/halilibo/richtext/ui/CodeBlock.desktop.kt:
--------------------------------------------------------------------------------
1 | package com.halilibo.richtext.ui
2 |
3 | import androidx.compose.foundation.HorizontalScrollbar
4 | import androidx.compose.foundation.horizontalScroll
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.rememberScrollState
7 | import androidx.compose.foundation.rememberScrollbarAdapter
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.runtime.CompositionLocalProvider
10 | import androidx.compose.runtime.compositionLocalOf
11 | import androidx.compose.ui.Modifier
12 |
13 | private val LocalScrollbarEnabled = compositionLocalOf { true }
14 |
15 | @Composable
16 | internal actual fun RichTextScope.CodeBlockLayout(
17 | wordWrap: Boolean,
18 | children: @Composable RichTextScope.(Modifier) -> Unit
19 | ) {
20 | if (!wordWrap) {
21 | val scrollState = rememberScrollState()
22 | Column {
23 | children(Modifier.horizontalScroll(scrollState))
24 | if (LocalScrollbarEnabled.current) {
25 | val horizontalScrollbarAdapter = rememberScrollbarAdapter(scrollState)
26 | HorizontalScrollbar(adapter = horizontalScrollbarAdapter)
27 | }
28 | }
29 | } else {
30 | children(Modifier)
31 | }
32 | }
33 |
34 | /**
35 | * Contextually disables scrollbar for Desktop CodeBlocks under [content] tree.
36 | */
37 | @Composable
38 | public fun DisableScrollbar(
39 | content: @Composable () -> Unit
40 | ) {
41 | CompositionLocalProvider(LocalScrollbarEnabled provides false) {
42 | content()
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | gradlePluginPortal()
5 | mavenCentral()
6 | maven { url = uri("https://maven.pkg.jetbrains.space/public/p/compose/dev") }
7 | }
8 | }
9 |
10 | include(":printing")
11 | include(":richtext-ui")
12 | include(":richtext-ui-material")
13 | include(":richtext-ui-material3")
14 | include(":richtext-commonmark")
15 | include(":richtext-markdown")
16 | include(":android-sample")
17 | include(":desktop-sample")
18 | include(":slideshow")
19 | rootProject.name = "compose-richtext"
20 |
--------------------------------------------------------------------------------
/slideshow/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("richtext-android-library")
3 | id("org.jetbrains.dokka")
4 | id("org.jetbrains.compose") version Compose.desktopVersion
5 | id("org.jetbrains.kotlin.plugin.compose") version Kotlin.version
6 | }
7 |
8 | android {
9 | namespace = "com.zachklipp.richtext.ui.slideshow"
10 | }
11 |
12 | dependencies {
13 | implementation(compose.foundation)
14 | implementation(compose.material)
15 | implementation(compose.uiTooling)
16 | }
17 |
--------------------------------------------------------------------------------
/slideshow/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/compose-richtext/c0bbd392c84d0a337208c57aff675d4de1099321/slideshow/consumer-rules.pro
--------------------------------------------------------------------------------
/slideshow/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Compose Slideshow
2 | POM_DESCRIPTION=A library for creating slideshows using Compose.
3 |
--------------------------------------------------------------------------------
/slideshow/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/slideshow/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/slideshow/src/main/java/com/zachklipp/richtext/ui/slideshow/BodySlide.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("unused")
2 |
3 | package com.zachklipp.richtext.ui.slideshow
4 |
5 | import androidx.compose.foundation.layout.Arrangement.spacedBy
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.foundation.layout.fillMaxSize
8 | import androidx.compose.foundation.layout.fillMaxWidth
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.foundation.layout.wrapContentWidth
11 | import androidx.compose.material.Divider
12 | import androidx.compose.material.ProvideTextStyle
13 | import androidx.compose.material.Text
14 | import androidx.compose.runtime.Composable
15 | import androidx.compose.ui.Alignment
16 | import androidx.compose.ui.Modifier
17 | import androidx.compose.ui.tooling.preview.Preview
18 |
19 | /**
20 | * A composable to define a [Slideshow] slide which displays a large header at the top of the
21 | * slide, an optional footer at the bottom, and some content in the middle. All children are
22 | * start-aligned.
23 | *
24 | * See [SlideDivider] and [SlideNumberFooter].
25 | */
26 | @Composable public fun SlideScope.BodySlide(
27 | header: @Composable () -> Unit,
28 | body: @Composable () -> Unit,
29 | footer: @Composable () -> Unit = { SlideNumberFooter() }
30 | ) {
31 | val theme = LocalSlideshowTheme.current
32 | Column(
33 | Modifier
34 | .fillMaxSize()
35 | .padding(theme.gap),
36 | verticalArrangement = spacedBy(theme.gap)
37 | ) {
38 | ProvideTextStyle(theme.headerStyle, header)
39 | Column(
40 | Modifier
41 | .fillMaxWidth()
42 | .weight(1f, fill = true)
43 | ) { body() }
44 | ProvideTextStyle(theme.footerStyle, footer)
45 | }
46 | }
47 |
48 | /**
49 | * A simple horizontal divider line which uses the [SlideshowTheme] content color.
50 | */
51 | @Composable public fun SlideScope.SlideDivider() {
52 | Divider(color = LocalSlideshowTheme.current.contentColor)
53 | }
54 |
55 | /**
56 | * A text composable which displays the current slide number from the [SlideScope], right-aligned in
57 | * its parent.
58 | */
59 | @Composable public fun SlideScope.SlideNumberFooter() {
60 | Text(
61 | slideNumber.toString(),
62 | Modifier
63 | .fillMaxWidth()
64 | .wrapContentWidth(Alignment.End)
65 | )
66 | }
67 |
68 | @Preview
69 | @Composable private fun BodySlidePreview() {
70 | PreviewSlideScope.BodySlide(
71 | header = {
72 | Text("Header")
73 | },
74 | body = {
75 | Text("Content 1")
76 | Text("Content 2")
77 | Text("Content 3")
78 | },
79 | footer = {
80 | Text("Footer")
81 | }
82 | )
83 | }
84 |
--------------------------------------------------------------------------------
/slideshow/src/main/java/com/zachklipp/richtext/ui/slideshow/NavigableContent.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.ui.slideshow
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.DisposableEffect
5 | import androidx.compose.runtime.MutableState
6 | import androidx.compose.runtime.SideEffect
7 | import androidx.compose.runtime.State
8 | import androidx.compose.runtime.mutableStateOf
9 | import androidx.compose.runtime.remember
10 |
11 | /**
12 | * Receiver type for [NavigableContentContainer] children.
13 | */
14 | public interface NavigableContentScope : SlideScope {
15 | /**
16 | * Defines a composable which will be initially passed `visible=false`, and then invoked with
17 | * `visible=true` as the slideshow is advanced.
18 | *
19 | * A [State] object is passed, instead of passing the boolean directly, to prevent unnecessary
20 | * recomposition if the value is not used in the immediate scope.
21 | */
22 | @Composable public fun NavigableContent(children: @Composable (visible: State) -> Unit)
23 | }
24 |
25 | /**
26 | * Wrapper for [Slideshow] slides that want to initially display a subset of their content, and
27 | * eventually reveal more content as the slideshow is advanced. The children of this content
28 | * receive a [NavigableContentScope], which can be used to define pieces of content which should
29 | * be gradually revealed. Every occurrence of [NavigableContentScope.NavigableContent] will be
30 | * initially invoked with `visible=false`, and then gradually invoked with `visible=true` as the
31 | * slideshow is advanced.
32 | *
33 | * This composable works really well with [androidx.compose.animation.AnimatedVisibility], which
34 | * takes a boolean visible flag and optional enter/exit animations.
35 | */
36 | @Composable
37 | public fun SlideScope.NavigableContentContainer(
38 | children: @Composable NavigableContentScope.() -> Unit
39 | ) {
40 | val state = remember { NavigableContentState(this) }
41 |
42 | // Unless all content is shown or hidden, we need to handle navigation events ourself.
43 | interceptNavigation(state::doInterceptNavigate)
44 |
45 | state.startRecordingModifiers()
46 | children(state)
47 | state.stopRecordingModifiers()
48 | SideEffect {
49 | state.onChildrenCommitted()
50 | }
51 | }
52 |
53 | private class NavigableContentState(private val slideScope: SlideScope) : NavigableContentScope,
54 | SlideScope by slideScope {
55 |
56 | private var recording = false
57 |
58 | /**
59 | * Used to track the order of calls, so that content is revealed in the correct order.
60 | */
61 | private var currentIndex = 0
62 |
63 | private val childVisibilities = mutableListOf>()
64 |
65 | /**
66 | * Controls how many [NavigableContent] children are currently "visible". When navigating forward,
67 | * no children are initially visible, but when navigating back, all children are. Note that this
68 | * max value will be clamped by [onChildrenCommitted].
69 | */
70 | private var numberChildrenVisible = if (navigatedForward) 0 else Int.MAX_VALUE
71 |
72 | /**
73 | * Handles navigation (via [SlideScope.interceptNavigation]) to either show or hide our child
74 | * content.
75 | */
76 | fun doInterceptNavigate(forward: Boolean): Boolean {
77 | if (forward) numberChildrenVisible++ else numberChildrenVisible--
78 | updateVisibilities()
79 |
80 | // If we're navigating back and all content is hidden, or forward and all content is shown, then
81 | // let the slideshow change slides.
82 | return numberChildrenVisible in 0..childVisibilities.size
83 | }
84 |
85 | fun startRecordingModifiers() {
86 | recording = true
87 | currentIndex = 0
88 | }
89 |
90 | @Composable override fun NavigableContent(children: @Composable (State) -> Unit) {
91 | // TODO I think this is not going to work for more complex compositions, since a child may
92 | // be added to the composition without recomposing the NavigableContentContainer. Not sure how
93 | // to do index tracking in that case.
94 | check(recording) { "Can't use NavigableContentScope outside of NavigableContentContainer." }
95 |
96 | val visibleState = remember {
97 | val initiallyVisible = currentIndex++ < numberChildrenVisible
98 | mutableStateOf(initiallyVisible)
99 | }
100 |
101 | // When the content is initially committed, start tracking the visibility, and then stop
102 | // tracking it if it is removed from the composition.
103 | DisposableEffect(Unit) {
104 | childVisibilities += visibleState
105 | onDispose {
106 | childVisibilities -= visibleState
107 | }
108 | }
109 |
110 | children(visibleState)
111 | }
112 |
113 | fun stopRecordingModifiers() {
114 | recording = false
115 | }
116 |
117 | /**
118 | * Ensures that the visibility states of all children are correct given the current [numberChildrenVisible]
119 | * after children are added or removed.
120 | *
121 | * TODO This might not get called in more complex compositions where the [NavigableContent] is
122 | * composed without the container being composed. Figure out how to handle that case.
123 | */
124 | fun onChildrenCommitted() {
125 | numberChildrenVisible = numberChildrenVisible.coerceAtMost(childVisibilities.size)
126 | updateVisibilities()
127 | }
128 |
129 | private fun updateVisibilities() {
130 | childVisibilities.forEachIndexed { i, visible ->
131 | visible.value = i < numberChildrenVisible
132 | }
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/slideshow/src/main/java/com/zachklipp/richtext/ui/slideshow/SlideScope.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.ui.slideshow
2 |
3 | import androidx.compose.runtime.Composable
4 |
5 | public typealias NavigationInterceptor = (forward: Boolean) -> Boolean
6 |
7 | /**
8 | * Receiver for slide composables passed to [Slideshow] that provides some context about the current
9 | * slide, as well as functions for controlling navigation.
10 | */
11 | public interface SlideScope {
12 | /** The index of the current slide in the slideshow. */
13 | public val slideNumber: Int
14 |
15 | /** If true, this slide was shown via forward navigation, coming from the previous slide. */
16 | public val navigatedForward: Boolean
17 |
18 | /**
19 | * Register a callback to be invoked when navigation is requested from this slide. If the callback
20 | * returns true, the slideshow will not navigate. If it returns false, the next interceptor will
21 | * have a chance to handle it, or if there are no other interceptors then the slideshow will
22 | * navigate between slides.
23 | */
24 | @Composable public fun interceptNavigation(handler: NavigationInterceptor)
25 | }
26 |
27 | internal object PreviewSlideScope : SlideScope {
28 | override val slideNumber: Int get() = 42
29 | override val navigatedForward: Boolean get() = false
30 |
31 | @Composable override fun interceptNavigation(handler: NavigationInterceptor) = Unit
32 | }
33 |
--------------------------------------------------------------------------------
/slideshow/src/main/java/com/zachklipp/richtext/ui/slideshow/SlideshowTheme.kt:
--------------------------------------------------------------------------------
1 | package com.zachklipp.richtext.ui.slideshow
2 |
3 | import androidx.compose.runtime.Immutable
4 | import androidx.compose.runtime.ProvidableCompositionLocal
5 | import androidx.compose.runtime.staticCompositionLocalOf
6 | import androidx.compose.ui.graphics.Color
7 | import androidx.compose.ui.text.TextStyle
8 | import androidx.compose.ui.text.font.FontWeight
9 | import androidx.compose.ui.text.style.TextAlign.Companion.Center
10 | import androidx.compose.ui.unit.Dp
11 | import androidx.compose.ui.unit.dp
12 | import androidx.compose.ui.unit.sp
13 |
14 | /**
15 | * Defines the visual styling for a [Slideshow].
16 | *
17 | * @param contentColor Default color used for text and [SlideDivider].
18 | * @param backgroundColor Color used as the background for slides.
19 | * @param baseTextStyle Default [TextStyle] used for all slide content. Some scaffolds use other
20 | * styles from the theme for certain slots.
21 | * @param titleStyle Default [TextStyle] used for [TitleSlide] titles.
22 | * @param subtitleStyle Default [TextStyle] used for [TitleSlide] subtitles.
23 | * @param headerStyle Default [TextStyle] used for [BodySlide] headers.
24 | * @param footerStyle Default [TextStyle] used for [BodySlide] footers.
25 | * @param gap Default margins used for [BodySlide]s and spacing between header, body, and footer.
26 | * @param aspectRatio The aspect ratio for the entire slideshow.
27 | */
28 | @Immutable
29 | public data class SlideshowTheme(
30 | val contentColor: Color = Color.White,
31 | val backgroundColor: Color = Color.DarkGray,
32 | val baseTextStyle: TextStyle = TextStyle(fontSize = 18.sp),
33 | val titleStyle: TextStyle = TextStyle(
34 | fontSize = 48.sp,
35 | textAlign = Center,
36 | fontWeight = FontWeight.Bold
37 | ),
38 | val subtitleStyle: TextStyle = TextStyle(
39 | fontSize = 36.sp,
40 | textAlign = Center
41 | ),
42 | val headerStyle: TextStyle = TextStyle(fontSize = 28.sp),
43 | val footerStyle: TextStyle = TextStyle(fontSize = 12.sp),
44 | val gap: Dp = 16.dp,
45 | val aspectRatio: Float = 16 / 9f
46 | )
47 |
48 | public val LocalSlideshowTheme: ProvidableCompositionLocal =
49 | staticCompositionLocalOf { SlideshowTheme() }
50 |
--------------------------------------------------------------------------------
/slideshow/src/main/java/com/zachklipp/richtext/ui/slideshow/TitleSlide.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("unused")
2 |
3 | package com.zachklipp.richtext.ui.slideshow
4 |
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.material.ProvideTextStyle
7 | import androidx.compose.material.Text
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.ui.Alignment.Companion.CenterHorizontally
10 | import androidx.compose.ui.text.TextStyle
11 | import androidx.compose.ui.text.style.TextAlign.Companion.Center
12 | import androidx.compose.ui.tooling.preview.Preview
13 |
14 | /**
15 | * A composable to define a [Slideshow] slide that shows a large, bold title in the center of the
16 | * slide with an optional subtitle below it.
17 | */
18 | @Composable public fun SlideScope.TitleSlide(
19 | title: @Composable () -> Unit,
20 | subtitle: (@Composable () -> Unit)? = null
21 | ) {
22 | val theme = LocalSlideshowTheme.current
23 | Column(horizontalAlignment = CenterHorizontally) {
24 | ProvideTextStyle(TextStyle(textAlign = Center)) {
25 | ProvideTextStyle(theme.titleStyle, content = title)
26 | if (subtitle != null) {
27 | ProvideTextStyle(theme.subtitleStyle, content = subtitle)
28 | }
29 | }
30 | }
31 | }
32 |
33 | @Preview
34 | @Composable private fun TitlePreview() {
35 | PreviewSlideScope.TitleSlide(
36 | title = { Text("Title") },
37 | subtitle = { Text("Subtitle") }
38 | )
39 | }
40 |
--------------------------------------------------------------------------------