├── .github └── workflows │ └── release-demo-app-apk.yaml ├── .gitignore ├── LICENSE ├── README.md ├── assets ├── android-dark.png ├── android-light.png ├── android-studio-config.png ├── basic-dark.png ├── basic-light.png ├── custom-color-dark.png ├── custom-color-light.png ├── desktop-dark.png ├── desktop-light.png ├── different-style-dark.png ├── different-style-light.png ├── ios-dark.png ├── ios-light.png ├── make-matcher-dark.png ├── make-matcher-light.png ├── make-rule-dark.png ├── make-rule-light.png ├── not-clickable-dark.png ├── not-clickable-light.png ├── web-dark.png └── web-light.png ├── autolinktext ├── build.gradle.kts └── src │ ├── androidMain │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ ├── MatchUrlProvider.android.kt │ │ ├── TextMatcher.android.kt │ │ └── TextRule.android.kt │ ├── androidUnitTest │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ ├── Ignore.android.kt │ │ └── TextRuleTest.android.kt │ ├── commonMain │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ ├── AnnotatedString+autoLinkText.kt │ │ ├── BackUpRegex.kt │ │ ├── MatchClickHandler.kt │ │ ├── MatchFilter.kt │ │ ├── MatchStylesProvider.kt │ │ ├── MatchUrlProvider.kt │ │ ├── NotForAndroid.kt │ │ ├── SimpleTextMatchResult.kt │ │ ├── TextMatchResult.kt │ │ ├── TextMatcher.kt │ │ └── TextRule.kt │ ├── commonTest │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ ├── Ignore.kt │ │ ├── SimpleTextMatchResultTest.kt │ │ ├── TextMatchResultTest.kt │ │ ├── TextMatcherTest.kt │ │ ├── TextRuleTest.kt │ │ └── helpers.kt │ ├── iosMain │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ ├── MatchUrlProvider.ios.kt │ │ ├── TextMatcher.ios.kt │ │ └── TextRule.ios.kt │ ├── iosTest │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ └── Ignore.ios.kt │ ├── jsMain │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ ├── MatchUrlProvider.js.kt │ │ ├── TextMatcher.js.kt │ │ └── TextRule.js.kt │ ├── jsTest │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ └── Ignore.js.kt │ ├── jvmMain │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ ├── MatchUrlProvider.jvm.kt │ │ ├── TextMatcher.jvm.kt │ │ └── TextRule.jvm.kt │ ├── jvmTest │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ └── Ignore.jvm.kt │ ├── wasmJsMain │ └── kotlin │ │ └── sh │ │ └── calvin │ │ └── autolinktext │ │ ├── MatchUrlProvider.wasmJs.kt │ │ ├── TextMatcher.wasmJs.kt │ │ └── TextRule.wasmJs.kt │ └── wasmJsTest │ └── kotlin │ └── sh │ └── calvin │ └── autolinktext │ └── Ignore.wasmJs.kt ├── build.gradle.kts ├── demoApp ├── composeApp │ ├── build.gradle.kts │ └── src │ │ ├── androidMain │ │ ├── AndroidManifest.xml │ │ ├── kotlin │ │ │ └── sh │ │ │ │ └── calvin │ │ │ │ └── autolinktext │ │ │ │ └── demo │ │ │ │ └── MainActivity.kt │ │ └── res │ │ │ ├── drawable │ │ │ ├── ic_launcher_background.xml │ │ │ └── ic_launcher_foreground.xml │ │ │ ├── mipmap-anydpi-v26 │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── values │ │ │ ├── colors.xml │ │ │ ├── strings.xml │ │ │ └── themes.xml │ │ │ └── xml │ │ │ ├── backup_rules.xml │ │ │ └── data_extraction_rules.xml │ │ ├── commonMain │ │ └── kotlin │ │ │ └── sh │ │ │ └── calvin │ │ │ └── autolinktext │ │ │ └── demo │ │ │ ├── App.kt │ │ │ └── ui.theme │ │ │ ├── Color.kt │ │ │ ├── Theme.kt │ │ │ └── Type.kt │ │ ├── iosMain │ │ └── kotlin │ │ │ └── main.kt │ │ ├── jsMain │ │ ├── kotlin │ │ │ └── main.kt │ │ └── resources │ │ │ └── index.html │ │ ├── jvmMain │ │ └── kotlin │ │ │ └── main.kt │ │ └── wasmJsMain │ │ ├── kotlin │ │ └── main.kt │ │ └── resources │ │ └── index.html ├── iosApp │ ├── iosApp.xcodeproj │ │ ├── project.pbxproj │ │ └── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ └── iosApp │ │ ├── Assets.xcassets │ │ ├── AccentColor.colorset │ │ │ └── Contents.json │ │ ├── AppIcon.appiconset │ │ │ └── Contents.json │ │ └── Contents.json │ │ ├── Info.plist │ │ ├── Preview Content │ │ └── Preview Assets.xcassets │ │ │ └── Contents.json │ │ └── iosApp.swift └── proguard-rules.pro ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── kotlin-js-store └── yarn.lock └── settings.gradle.kts /.github/workflows/release-demo-app-apk.yaml: -------------------------------------------------------------------------------- 1 | name: Release demo app APK 2 | # add demo app APK to the latest release 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | release: 10 | runs-on: ubuntu-latest 11 | permissions: 12 | contents: write 13 | steps: 14 | - name: Checkout 15 | uses: actions/checkout@v4 16 | - name: Set up Java 17 | uses: actions/setup-java@v4 18 | with: 19 | distribution: temurin 20 | java-version: 21 21 | - name: Build APK 22 | run: ./gradlew assembleDebug --stacktrace 23 | - name: Build Jar 24 | run: ./gradlew packageUberJarForCurrentOS --stacktrace 25 | - name: Get latest release 26 | id: latest_release 27 | uses: pozetroninc/github-action-get-latest-release@master 28 | with: 29 | repository: ${{ github.repository }} 30 | token: ${{ secrets.GITHUB_TOKEN }} 31 | excludes: prerelease, draft 32 | - name: Upload APK 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | run: gh release upload ${{ steps.latest_release.outputs.release }} demoApp/composeApp/build/outputs/apk/debug/composeApp-debug.apk#demoApp.apk --clobber 36 | - name: Upload Jar 37 | env: 38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | run: gh release upload ${{ steps.latest_release.outputs.release }} $(ls demoApp/composeApp/build/compose/jars/* | head -n1)#demoApp.jar --clobber 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | .idea 4 | .DS_Store 5 | build 6 | captures 7 | .externalNativeBuild 8 | .cxx 9 | local.properties 10 | xcuserdata 11 | .kotlin 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AutoLinkText 2 | 3 | AutoLinkText is a simple library that makes links, emails, and phone numbers clickable in text in Jetpack Compose and Kotlin Compose Multiplatform. 4 | 5 | The latest demo app APK can be found in the [releases](https://github.com/Calvin-LL/AutoLinkText/releases) section under the "Assets" section of the latest release. 6 | 7 | ## Motivation 8 | 9 | [`TextView`](https://developer.android.com/reference/android/widget/TextView) has [`autoLink`](https://developer.android.com/reference/android/widget/TextView#attr_android:autoLink) and [`Linkify`](https://developer.android.com/reference/android/text/util/Linkify) but Compose doesn't have an equivalent. This library aims to fill that gap. 10 | 11 | | Android | iOS | 12 | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 13 | | A screenshot of the demo app in Android | A screenshot of the demo app in iOS | 14 | 15 | | Desktop | Web | 16 | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 17 | | A screenshot of the demo app in Desktop | A screenshot of the demo app in Web | 18 | 19 | ## Features 20 | 21 | - Make links, emails, and phone numbers clickable in your text out of the box 22 | - Create custom matchers for your own patterns (e.g. hashtags, mentions, etc.) 23 | - Customizable styling for links 24 | - Customizable click listeners for links 25 | - Supports Compose Multiplatform (Android, iOS, Desktop/JVM, Wasm, JS) 26 | 27 | ## Usage 28 | 29 | ### Version Catalog 30 | 31 | If you're using Version Catalog, add the following to your `libs.versions.toml` file: 32 | 33 | ```toml 34 | [versions] 35 | #... 36 | autolinktext = "2.0.2" 37 | 38 | [libraries] 39 | #... 40 | autolinktext = { module = "sh.calvin.autolinktext:autolinktext", version.ref = "autolinktext" } 41 | ``` 42 | 43 | or 44 | 45 | ```toml 46 | [libraries] 47 | #... 48 | autolinktext = { module = "sh.calvin.autolinktext:autolinktext", version = "2.0.2" } 49 | ``` 50 | 51 | then 52 | 53 | ``` 54 | dependencies { 55 | // ... 56 | implementation(libs.autolinktext) 57 | } 58 | ``` 59 | 60 | ### Gradle 61 | 62 | If you're using Gradle instead, add the following to your `build.gradle` file: 63 | 64 | #### Kotlin DSL 65 | 66 | ```kotlin 67 | dependencies { 68 | // ... 69 | implementation("sh.calvin.autolinktext:autolinktext:2.0.2") 70 | } 71 | ``` 72 | 73 | #### Groovy DSL 74 | 75 | ```groovy 76 | dependencies { 77 | // ... 78 | implementation 'sh.calvin.autolinktext:autolinktext:2.0.2' 79 | } 80 | ``` 81 | 82 | ### Examples 83 | 84 | See [demo app code](demoApp/composeApp/src/commonMain/kotlin/sh/calvin/autolinktext/demo/App.kt) for more examples. 85 | 86 | #### Basic Usage 87 | 88 | 89 | 90 | By default `AutoLinkText` turns URLs, emails, and phone numbers into clickable links, set the color to `MaterialTheme.colorScheme.primary`, and underline the links. 91 | 92 | ```kotlin 93 | Text( 94 | AnnotatedString.rememberAutoLinkText( 95 | """ 96 | |Visit https://www.google.com 97 | |Visit www.google.com 98 | |Email test@example.com 99 | |Call 6045557890 100 | |Call +1 (604) 555-7890 101 | |Call 604-555-7890 102 | """.trimMargin() 103 | ) 104 | ) 105 | ``` 106 | 107 | #### Customize Link Color 108 | 109 | 110 | 111 | You can override the default styling by providing a `TextLinkStyles` object. 112 | 113 | ```kotlin 114 | Text( 115 | AnnotatedString.rememberAutoLinkText( 116 | "...", 117 | defaultLinkStyles = TextLinkStyles( 118 | SpanStyle( 119 | color = Color.Blue, 120 | textDecoration = TextDecoration.Underline 121 | ) 122 | ) 123 | ) 124 | ) 125 | ``` 126 | 127 | #### Make Your Own Rules 128 | 129 | 130 | 131 | There are 3 types of `TextRule`s: `Url`, `Clickable`, and `Styleable`. 132 | 133 | - `Url` turns matched text into a clickable link, and when clicked, opens the URL. 134 | - `Clickable` turns matched text into a clickable link, and when clicked, calls the `onClick` lambda. 135 | - `Styleable` applies a `SpanStyle` to the matched text. 136 | 137 | ```kotlin 138 | Text( 139 | AnnotatedString.rememberAutoLinkText( 140 | "Make your own rules like #hashtag and @mention", 141 | textRules = listOf( 142 | TextRule.Styleable( 143 | textMatcher = TextMatcher.StringMatcher("Make"), 144 | style = SpanStyle(fontWeight = FontWeight.Bold) 145 | ), 146 | TextRule.Clickable( 147 | textMatcher = TextMatcher.RegexMatcher(Regex("#\\w+")), 148 | onClick = { 149 | println("Hashtag ${it.matchedText} clicked") 150 | }, 151 | ), 152 | TextRule.Url( 153 | textMatcher = TextMatcher.RegexMatcher(Regex("@\\w+")), 154 | styles = TextLinkStyles( 155 | SpanStyle( 156 | color = Color.Blue 157 | ) 158 | ), 159 | urlProvider = { "https://twitter.com/${it.matchedText}" } 160 | ) 161 | ) 162 | ) 163 | ) 164 | ``` 165 | 166 | #### Different Styles for Different Matches 167 | 168 | 169 | 170 | Provide a `stylesProvider` lambda that returns a `TextLinkStyles` object based on the matched text. 171 | 172 | ```kotlin 173 | Text( 174 | AnnotatedString.rememberAutoLinkText( 175 | "Style the same rule differently like #hashtag1 and #hashtag2", 176 | textRules = listOf( 177 | TextRule.Clickable( 178 | textMatcher = TextMatcher.RegexMatcher(Regex("#\\w+")), 179 | stylesProvider = { 180 | val hashtag = it.matchedText 181 | if (hashtag == "#hashtag1") { 182 | TextLinkStyles( 183 | SpanStyle( 184 | color = Color.Red, 185 | textDecoration = TextDecoration.Underline 186 | ) 187 | ) 188 | } else { 189 | TextLinkStyles( 190 | SpanStyle( 191 | color = Color.Blue, 192 | textDecoration = TextDecoration.Underline 193 | ) 194 | ) 195 | } 196 | }, 197 | onClick = { 198 | println("Hashtag ${it.matchedText} clicked") 199 | }, 200 | ), 201 | ) 202 | ) 203 | ) 204 | ``` 205 | 206 | #### `TextRule`s don't have to be clickable 207 | 208 | 209 | 210 | You can create `TextRule`s that are not clickable by using `TextRule.Styleable`. 211 | 212 | ```kotlin 213 | Text( 214 | AnnotatedString.rememberAutoLinkText( 215 | "This is very important", 216 | textRules = listOf( 217 | TextRule.Styleable( 218 | textMatcher = TextMatcher.StringMatcher("important"), 219 | style = SpanStyle(color = Color.Red), 220 | ) 221 | ), 222 | ) 223 | ) 224 | ``` 225 | 226 | #### Make Your Own Matcher 227 | 228 | 229 | 230 | Create your own matchers with `TextMatcher.FunctionMatcher` that takes the given text and returns a list of `SimpleTextMatchResult`s. 231 | 232 | ```kotlin 233 | Text( 234 | AnnotatedString.rememberAutoLinkText( 235 | "Make every other word blue", 236 | textRules = listOf( 237 | TextRule.Styleable( 238 | textMatcher = TextMatcher.FunctionMatcher { 239 | val matches = mutableListOf>() 240 | var currentWordStart = 0 241 | "$it ".forEachIndexed { index, char -> 242 | if (char.isWhitespace()) { 243 | val match = SimpleTextMatchResult( 244 | start = currentWordStart, 245 | end = index, 246 | ) 247 | if (it.slice(match).isNotBlank()) { 248 | matches.add(match) 249 | } 250 | currentWordStart = index + 1 251 | } 252 | } 253 | matches.filterIndexed { index, _ -> index % 2 == 0 } 254 | }, 255 | style = SpanStyle(color = Color.Blue), 256 | ), 257 | ), 258 | ) 259 | ) 260 | ``` 261 | 262 | ## API 263 | 264 | - [AutoLinkText](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/AutoLinkText.kt) 265 | - [TextRule](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 266 | - [Url](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 267 | - [Clickable](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 268 | - [Styleable](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 269 | - [TextRuleDefaults](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 270 | - [webUrl](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 271 | - [emailAddress](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 272 | - [phoneNumber](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 273 | - [defaultList](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt) 274 | - [TextMatcher](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt) 275 | - [RegexMatcher](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt) 276 | - [StringMatcher](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt) 277 | - [FunctionMatcher](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt) 278 | - [TextMatcherDefaults](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt) 279 | - [webUrl](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt) 280 | - [emailAddress](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt) 281 | - [phoneNumber](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt) 282 | - [MatchFilter](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchFilter.kt) 283 | - [MatchFilterDefaults](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchFilter.kt) 284 | - [NoOp](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchFilter.kt) 285 | - [WebUrls](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchFilter.kt) 286 | - [PhoneNumber](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchFilter.kt) 287 | - [MatchStylesProvider](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchStylesProvider.kt) 288 | - [SimpleTextMatchResult](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/SimpleTextMatchResult.kt) 289 | - [TextMatchResult](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatchResult.kt) 290 | - [MatchClickHandlerDefaults](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchClickHandler.kt) 291 | - [webUrl](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchClickHandler.kt) 292 | - [emailAddress](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchClickHandler.kt) 293 | - [phoneNumber](autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchClickHandler.kt) 294 | 295 | ## Running the demo app 296 | 297 | To run the Android demo app, open the project in Android Studio and run the app. 298 | 299 | To run the iOS demo app, open the iosApp project in Xcode and run the app or add the following Configuration to the Android Studio project, you may need to install the [Kotlin Multiplatform Mobile plugin](https://plugins.jetbrains.com/plugin/14936-kotlin-multiplatform-mobile) first. 300 | 301 | ![Android Studio Debug Configuration Page](assets/android-studio-config.png) 302 | 303 | To run the web demo app, run `./gradlew :composeApp:wasmJsBrowserDevelopmentRun`. 304 | 305 | To run the desktop demo app, run `./gradlew :demoApp:ComposeApp:run`. 306 | 307 | ## Contributing 308 | 309 | Open this project with Android Studio Preview. 310 | 311 | You'll want to install the [Kotlin Multiplatform Mobile plugin](https://plugins.jetbrains.com/plugin/14936-kotlin-multiplatform-mobile) in Android Studio before you open this project. 312 | 313 | ## License 314 | 315 | ``` 316 | Copyright 2023 Calvin Liang 317 | 318 | Licensed under the Apache License, Version 2.0 (the "License"); 319 | you may not use this file except in compliance with the License. 320 | You may obtain a copy of the License at 321 | 322 | http://www.apache.org/licenses/LICENSE-2.0 323 | 324 | Unless required by applicable law or agreed to in writing, software 325 | distributed under the License is distributed on an "AS IS" BASIS, 326 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 327 | See the License for the specific language governing permissions and 328 | limitations under the License. 329 | ``` 330 | -------------------------------------------------------------------------------- /assets/android-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/android-dark.png -------------------------------------------------------------------------------- /assets/android-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/android-light.png -------------------------------------------------------------------------------- /assets/android-studio-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/android-studio-config.png -------------------------------------------------------------------------------- /assets/basic-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/basic-dark.png -------------------------------------------------------------------------------- /assets/basic-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/basic-light.png -------------------------------------------------------------------------------- /assets/custom-color-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/custom-color-dark.png -------------------------------------------------------------------------------- /assets/custom-color-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/custom-color-light.png -------------------------------------------------------------------------------- /assets/desktop-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/desktop-dark.png -------------------------------------------------------------------------------- /assets/desktop-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/desktop-light.png -------------------------------------------------------------------------------- /assets/different-style-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/different-style-dark.png -------------------------------------------------------------------------------- /assets/different-style-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/different-style-light.png -------------------------------------------------------------------------------- /assets/ios-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/ios-dark.png -------------------------------------------------------------------------------- /assets/ios-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/ios-light.png -------------------------------------------------------------------------------- /assets/make-matcher-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/make-matcher-dark.png -------------------------------------------------------------------------------- /assets/make-matcher-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/make-matcher-light.png -------------------------------------------------------------------------------- /assets/make-rule-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/make-rule-dark.png -------------------------------------------------------------------------------- /assets/make-rule-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/make-rule-light.png -------------------------------------------------------------------------------- /assets/not-clickable-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/not-clickable-dark.png -------------------------------------------------------------------------------- /assets/not-clickable-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/not-clickable-light.png -------------------------------------------------------------------------------- /assets/web-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/web-dark.png -------------------------------------------------------------------------------- /assets/web-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/assets/web-light.png -------------------------------------------------------------------------------- /autolinktext/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi 2 | import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl 3 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget 4 | import org.jetbrains.kotlin.gradle.dsl.KotlinVersion 5 | 6 | plugins { 7 | alias(libs.plugins.kotlin.multiplatform) 8 | alias(libs.plugins.android.library) 9 | alias(libs.plugins.compose) 10 | alias(libs.plugins.compose.compiler) 11 | alias(libs.plugins.maven.publish) 12 | } 13 | 14 | group = "sh.calvin.autolinktext" 15 | version = "2.0.2" 16 | 17 | kotlin { 18 | coreLibrariesVersion = "1.9.0" 19 | @OptIn(ExperimentalKotlinGradlePluginApi::class) 20 | compilerOptions.languageVersion.set(KotlinVersion.KOTLIN_1_9) 21 | 22 | androidTarget { 23 | publishLibraryVariants("release", "debug") 24 | compilations.all { 25 | compileTaskProvider.configure { 26 | compilerOptions { 27 | jvmTarget.set(JvmTarget.JVM_1_8) 28 | } 29 | } 30 | } 31 | } 32 | 33 | jvm { 34 | compilations.all { 35 | compileTaskProvider.configure { 36 | compilerOptions { 37 | jvmTarget.set(JvmTarget.JVM_1_8) 38 | } 39 | } 40 | } 41 | } 42 | 43 | @OptIn(ExperimentalWasmDsl::class) 44 | wasmJs { 45 | browser() 46 | binaries.executable() 47 | } 48 | 49 | js { 50 | browser() 51 | binaries.executable() 52 | } 53 | 54 | listOf( 55 | iosX64(), 56 | iosArm64(), 57 | iosSimulatorArm64() 58 | ).forEach { 59 | it.binaries.framework { 60 | baseName = "autolinktext" 61 | isStatic = true 62 | } 63 | } 64 | 65 | sourceSets { 66 | commonMain.dependencies { 67 | implementation(compose.runtime) 68 | implementation(compose.material3) 69 | implementation(libs.kermit) 70 | } 71 | commonTest.dependencies { 72 | implementation(libs.kotlin.test) 73 | } 74 | 75 | androidMain.dependencies { 76 | implementation(libs.androidx.core.ktx) 77 | implementation(libs.libphonenumber) 78 | } 79 | val androidUnitTest by getting { 80 | dependencies { 81 | implementation(libs.robolectric) 82 | } 83 | } 84 | 85 | jvmMain.dependencies { 86 | implementation(libs.libphonenumber) 87 | } 88 | } 89 | } 90 | 91 | android { 92 | namespace = project.group.toString() 93 | compileSdk = 35 94 | defaultConfig { 95 | minSdk = 21 96 | } 97 | buildTypes { 98 | release { 99 | isMinifyEnabled = false 100 | } 101 | } 102 | buildFeatures { 103 | compose = true 104 | } 105 | testOptions { 106 | unitTests { 107 | isIncludeAndroidResources = true 108 | } 109 | } 110 | compileOptions { 111 | sourceCompatibility = JavaVersion.VERSION_1_8 112 | targetCompatibility = JavaVersion.VERSION_1_8 113 | } 114 | } 115 | 116 | mavenPublishing { 117 | pom { 118 | name = "AutoLinkText" 119 | description = "A library for Compose to automatically linkify text" 120 | url = "https://github.com/Calvin-LL/AutoLinkText" 121 | inceptionYear = "2024" 122 | 123 | licenses { 124 | license { 125 | name = "The Apache Software License, Version 2.0" 126 | url = "http://www.apache.org/licenses/LICENSE-2.0.txt" 127 | distribution = "http://www.apache.org/licenses/LICENSE-2.0.txt" 128 | } 129 | } 130 | scm { 131 | connection = "scm:git:git://github.com/Calvin-LL/AutoLinkText.git" 132 | developerConnection = "scm:git:ssh://github.com/Calvin-LL/AutoLinkText.git" 133 | url = "https://github.com/Calvin-LL/AutoLinkText" 134 | } 135 | developers { 136 | developer { 137 | name = "Calvin Liang" 138 | email = "me@calvin.sh" 139 | url = "https://calvin.sh" 140 | } 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /autolinktext/src/androidMain/kotlin/sh/calvin/autolinktext/MatchUrlProvider.android.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import android.telephony.PhoneNumberUtils 4 | import androidx.core.net.toUri 5 | import java.net.URL 6 | 7 | internal actual fun getMatchUrlProviderDefaults() = 8 | object : MatchUrlProviderDefaultsInterface { 9 | override val WebUrl: MatchUrlProvider<*> 10 | get() = { result -> 11 | val url = result.matchedText.toUri().let { uri -> 12 | if (uri.scheme == null) 13 | URL("https://${result.matchedText}").toString().toUri() 14 | else 15 | uri 16 | } 17 | url.toString() 18 | } 19 | 20 | override val EmailAddress: MatchUrlProvider<*> 21 | get() = { 22 | "mailto:${it.matchedText}" 23 | } 24 | 25 | override val PhoneNumber: MatchUrlProvider<*> 26 | get() = { 27 | val phone = PhoneNumberUtils.normalizeNumber(it.matchedText) 28 | "tel:${phone}" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /autolinktext/src/androidMain/kotlin/sh/calvin/autolinktext/TextMatcher.android.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import android.annotation.SuppressLint 4 | import android.os.Build 5 | import android.telephony.TelephonyManager 6 | import androidx.core.util.PatternsCompat 7 | import com.google.i18n.phonenumbers.PhoneNumberUtil 8 | import java.util.Locale 9 | import java.util.regex.Pattern 10 | 11 | private fun matchPattern( 12 | text: String, 13 | pattern: Pattern, 14 | matchFilter: MatchFilter = MatchFilterDefaults.NoOp, 15 | ): List> { 16 | val matcher = pattern.matcher(text) 17 | val matches = mutableListOf>() 18 | while (matcher.find()) { 19 | val result = SimpleTextMatchResult( 20 | matcher.start(), 21 | matcher.end() 22 | ) 23 | if (matchFilter(text, result)) { 24 | matches.add(result) 25 | } 26 | } 27 | return matches 28 | } 29 | 30 | internal actual fun getMatcherDefaults() = object : TextMatcherDefaultsInterface { 31 | @NotForAndroid 32 | @SuppressLint("RestrictedApi") 33 | override fun webUrl(contextData: ContextData): TextMatcher { 34 | return TextMatcher.FunctionMatcher { text -> 35 | matchPattern(text, PatternsCompat.AUTOLINK_WEB_URL, MatchFilterDefaults.WebUrls) 36 | } 37 | } 38 | 39 | @NotForAndroid 40 | @SuppressLint("RestrictedApi") 41 | override fun emailAddress(contextData: ContextData): TextMatcher { 42 | return TextMatcher.FunctionMatcher { text -> 43 | matchPattern(text, PatternsCompat.AUTOLINK_EMAIL_ADDRESS) 44 | } 45 | } 46 | 47 | @NotForAndroid 48 | override fun phoneNumber(contextData: ContextData): TextMatcher { 49 | val simCountryIso = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 50 | (contextData as AndroidContextData).context.getSystemService(TelephonyManager::class.java)?.simCountryIso?.let { 51 | if (it.isNotEmpty()) it.uppercase() else null 52 | } 53 | } else { 54 | null 55 | } 56 | 57 | return TextMatcher.FunctionMatcher { text -> 58 | val phoneUtil = PhoneNumberUtil.getInstance() 59 | val regionCode = simCountryIso ?: Locale.getDefault().country 60 | val matches = phoneUtil.findNumbers( 61 | text, 62 | regionCode, PhoneNumberUtil.Leniency.POSSIBLE, Long.MAX_VALUE, 63 | ) 64 | 65 | matches.mapNotNull { 66 | val result = SimpleTextMatchResult(it.start(), it.end()) 67 | if (MatchFilterDefaults.PhoneNumber(text, result)) result else null 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /autolinktext/src/androidMain/kotlin/sh/calvin/autolinktext/TextRule.android.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import android.content.Context 4 | import androidx.compose.runtime.Composable 5 | import androidx.compose.ui.platform.LocalContext 6 | 7 | class AndroidContextData(val context: Context) : ContextData 8 | 9 | internal actual fun getTextRuleDefaults() = object : TextRuleDefaultsInterface { 10 | @NotForAndroid 11 | override fun webUrl(contextData: ContextData): TextRule.Url { 12 | assert(contextData is AndroidContextData) { "ContextData must be AndroidContextData" } 13 | 14 | return super.webUrl(contextData) 15 | } 16 | 17 | @NotForAndroid 18 | override fun emailAddress(contextData: ContextData): TextRule.Url { 19 | assert(contextData is AndroidContextData) { "ContextData must be AndroidContextData" } 20 | 21 | return super.emailAddress(contextData) 22 | } 23 | 24 | @NotForAndroid 25 | override fun phoneNumber(contextData: ContextData): TextRule.Url { 26 | assert(contextData is AndroidContextData) { "ContextData must be AndroidContextData" } 27 | 28 | return super.phoneNumber(contextData) 29 | } 30 | 31 | @NotForAndroid 32 | override fun defaultList(contextData: ContextData): List> { 33 | assert(contextData is AndroidContextData) { "ContextData must be AndroidContextData" } 34 | 35 | return super.defaultList(contextData) 36 | } 37 | 38 | @OptIn(NotForAndroid::class) 39 | @Composable 40 | override fun webUrl(): TextRule.Url { 41 | val context = AndroidContextData(context = LocalContext.current) 42 | 43 | return webUrl(context) 44 | } 45 | 46 | @OptIn(NotForAndroid::class) 47 | @Composable 48 | override fun emailAddress(): TextRule.Url { 49 | val context = AndroidContextData(context = LocalContext.current) 50 | 51 | return emailAddress(context) 52 | } 53 | 54 | @OptIn(NotForAndroid::class) 55 | @Composable 56 | override fun phoneNumber(): TextRule.Url { 57 | val context = AndroidContextData(context = LocalContext.current) 58 | 59 | return phoneNumber(context) 60 | } 61 | 62 | @OptIn(NotForAndroid::class) 63 | @Composable 64 | override fun defaultList(): List> { 65 | val context = AndroidContextData(context = LocalContext.current) 66 | 67 | return defaultList(context) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /autolinktext/src/androidUnitTest/kotlin/sh/calvin/autolinktext/Ignore.android.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 4 | actual annotation class IgnoreIos 5 | 6 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 7 | actual annotation class IgnoreJvm 8 | 9 | actual typealias IgnoreAndroid = org.junit.Ignore 10 | 11 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 12 | actual annotation class IgnoreWasmJs 13 | 14 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 15 | actual annotation class IgnoreJs 16 | -------------------------------------------------------------------------------- /autolinktext/src/androidUnitTest/kotlin/sh/calvin/autolinktext/TextRuleTest.android.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import androidx.compose.ui.text.ExperimentalTextApi 4 | import androidx.compose.ui.text.LinkAnnotation 5 | import org.junit.runner.RunWith 6 | import org.robolectric.RobolectricTestRunner 7 | import org.robolectric.RuntimeEnvironment 8 | import org.robolectric.annotation.Config 9 | import kotlin.test.Test 10 | import kotlin.test.assertEquals 11 | 12 | @RunWith(RobolectricTestRunner::class) 13 | @Config(sdk = [33]) 14 | class AndroidTextRuleTest { 15 | @OptIn(NotForAndroid::class) 16 | @Test 17 | fun emailsShouldBeMatched() { 18 | val context = RuntimeEnvironment.getApplication() 19 | val contextData = AndroidContextData(context) 20 | 21 | val text = "test someone@example.com test" 22 | val rule = listOf(TextRuleDefaults.emailAddress(contextData)) 23 | val matches = rule.getAllMatches(text) 24 | 25 | assertEquals(1, matches.size) 26 | assertEquals("someone@example.com", text.slice(matches[0])) 27 | } 28 | 29 | @OptIn(NotForAndroid::class) 30 | @Test 31 | fun phoneNumbersShouldBeMatched() { 32 | val context = RuntimeEnvironment.getApplication() 33 | val contextData = AndroidContextData(context) 34 | 35 | val text = "test 123-456-7890 test" 36 | val rule = listOf(TextRuleDefaults.phoneNumber(contextData)) 37 | val matches = rule.getAllMatches(text) 38 | 39 | assertEquals(1, matches.size) 40 | assertEquals("123-456-7890", text.slice(matches[0])) 41 | } 42 | 43 | @OptIn(NotForAndroid::class) 44 | @Test 45 | fun webUrlsShouldBeMatched() { 46 | val context = RuntimeEnvironment.getApplication() 47 | val contextData = AndroidContextData(context) 48 | 49 | val text = "test http://example.com test example.com" 50 | val rule = listOf(TextRuleDefaults.webUrl(contextData)) 51 | val matches = rule.getAllMatches(text) 52 | 53 | assertEquals(2, matches.size) 54 | assertEquals("http://example.com", text.slice(matches[0])) 55 | assertEquals("example.com", text.slice(matches[1])) 56 | } 57 | 58 | @OptIn(NotForAndroid::class) 59 | @Test 60 | fun emailShouldNotBeConfusedWithWebUrl() { 61 | val context = RuntimeEnvironment.getApplication() 62 | val contextData = AndroidContextData(context) 63 | 64 | val text = "test someone@example.com test" 65 | val rules = listOf( 66 | TextRuleDefaults.webUrl(contextData), 67 | TextRuleDefaults.emailAddress(contextData), 68 | ) 69 | val matches = rules.getAllMatches(text) 70 | 71 | assertEquals(1, matches.size) 72 | assertEquals("someone@example.com", text.slice(matches[0])) 73 | assertEquals(rules[1], matches[0].rule) 74 | } 75 | 76 | @OptIn(NotForAndroid::class) 77 | @Test 78 | fun shouldMatchComplexText() { 79 | val context = RuntimeEnvironment.getApplication() 80 | val contextData = AndroidContextData(context) 81 | 82 | val text = "Visit https://www.google.com\n" + 83 | "Visit www.google.com\n" + 84 | "Email test@example.com\n" + 85 | "Call 6045557890\n" + 86 | "Call +1 (604) 555-7890\n" + 87 | "Call 604-555-7890\n" 88 | val rules = listOf( 89 | TextRuleDefaults.webUrl(contextData), 90 | TextRuleDefaults.emailAddress(contextData), 91 | TextRuleDefaults.phoneNumber(contextData), 92 | ) 93 | val matches = rules.getAllMatches(text) 94 | 95 | assertEquals(6, matches.size) 96 | assertEquals("https://www.google.com", text.slice(matches[0])) 97 | assertEquals(rules[0], matches[0].rule) 98 | assertEquals("www.google.com", text.slice(matches[1])) 99 | assertEquals(rules[0], matches[1].rule) 100 | assertEquals("test@example.com", text.slice(matches[2])) 101 | assertEquals(rules[1], matches[2].rule) 102 | assertEquals("6045557890", text.slice(matches[3])) 103 | assertEquals(rules[2], matches[3].rule) 104 | assertEquals("+1 (604) 555-7890", text.slice(matches[4])) 105 | assertEquals(rules[2], matches[4].rule) 106 | assertEquals("604-555-7890", text.slice(matches[5])) 107 | assertEquals(rules[2], matches[5].rule) 108 | } 109 | 110 | @OptIn(NotForAndroid::class, ExperimentalTextApi::class) 111 | @Test 112 | fun testAnnotateString() { 113 | val context = RuntimeEnvironment.getApplication() 114 | val contextData = AndroidContextData(context) 115 | 116 | val text = "Visit https://www.google.com\n" + 117 | "Visit www.google.com\n" + 118 | "Email test@example.com\n" + 119 | "Call 6045557890\n" + 120 | "Call +1 (604) 555-7890\n" + 121 | "Call 604-555-7890\n" 122 | val rules = listOf( 123 | TextRuleDefaults.webUrl(contextData), 124 | TextRuleDefaults.emailAddress(contextData), 125 | TextRuleDefaults.phoneNumber(contextData), 126 | ) 127 | val matches = rules.getAllMatches(text) 128 | val annotatedString = matches.annotateString(text) 129 | 130 | fun getUrlAtMatch(index: Int) = (annotatedString.getLinkAnnotations( 131 | matches[index].start, matches[index].endExclusive 132 | ).first().item as? LinkAnnotation.Url)?.url 133 | 134 | assertEquals("https://www.google.com", getUrlAtMatch(0)) 135 | assertEquals("https://www.google.com", getUrlAtMatch(1)) 136 | assertEquals("mailto:test@example.com", getUrlAtMatch(2)) 137 | assertEquals("tel:6045557890", getUrlAtMatch(3)) 138 | assertEquals("tel:+16045557890", getUrlAtMatch(4)) 139 | assertEquals("tel:6045557890", getUrlAtMatch(5)) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/AnnotatedString+autoLinkText.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import androidx.compose.material3.MaterialTheme 4 | import androidx.compose.runtime.Composable 5 | import androidx.compose.runtime.remember 6 | import androidx.compose.ui.text.AnnotatedString 7 | import androidx.compose.ui.text.SpanStyle 8 | import androidx.compose.ui.text.TextLinkStyles 9 | import androidx.compose.ui.text.style.TextDecoration 10 | 11 | /** 12 | * Creates an [AnnotatedString] with all the text turned into clickable links based on the 13 | * provided [TextRule]s. 14 | * 15 | * @param text The text to auto-link. 16 | * @param textRules A list of rules to match the text and handle click events. Each rule 17 | * contains a [TextMatcher], a [MatchStylesProvider] and a [MatchClickHandler]. The [TextMatcher] 18 | * is used to find the matches in the text. The [MatchStylesProvider] is used to provide style 19 | * for the matched text. The [MatchClickHandler] is used to handle click events on the matched 20 | * text. 21 | * @param defaultLinkStyles The default [TextLinkStyles] to apply to the auto-linked text. 22 | */ 23 | @Composable 24 | fun AnnotatedString.Companion.rememberAutoLinkText( 25 | text: String, 26 | textRules: Collection> = TextRuleDefaults.defaultList(), 27 | defaultLinkStyles: TextLinkStyles? = TextLinkStyles( 28 | style = SpanStyle( 29 | color = MaterialTheme.colorScheme.primary, 30 | textDecoration = TextDecoration.Underline 31 | ), 32 | ), 33 | ): AnnotatedString { 34 | val matches = remember(text, textRules) { 35 | textRules.map { 36 | if (it.stylesProvider == null && defaultLinkStyles != null) 37 | it.copy(styles = defaultLinkStyles) 38 | else 39 | it 40 | } 41 | .getAllMatches(text) 42 | } 43 | val annotatedString = remember(text, matches) { 44 | matches.annotateString(text) 45 | } 46 | 47 | return annotatedString 48 | } 49 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/BackUpRegex.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | /** 4 | * A [BackUpRegex] is used when a platform has no native support for matching particular types of text. 5 | */ 6 | internal object BackUpRegex { 7 | // from https://regexr.com/39nr7 8 | internal val WebUrl = Regex( 9 | "[(http(s)?):\\/\\/(www\\.)?a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)" 10 | ) 11 | 12 | // from https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address 13 | internal val Email = Regex( 14 | "[a-zA-Z0-9.!#\$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*" 15 | ) 16 | 17 | internal val PhoneNumber = Regex( 18 | "[\\+]?[(]?[0-9]{3}[)]?[-\\s\\.]?[0-9]{3}[-\\s\\.]?[0-9]{4,6}" 19 | ) 20 | } 21 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchClickHandler.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | typealias MatchClickHandler = (match: TextMatchResult) -> Unit 4 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchFilter.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | // from https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/text/util/Linkify.java;l=209;drc=4f9480b13d3cab52255608ac5913922ca4269ac5 4 | /** 5 | * Examines the character span matched by the pattern and determines 6 | * if the match should be turned into an actionable link. 7 | * 8 | * For example: when matching web URLs you would like things like 9 | * http://www.example.com to match, as well as just example.com itself. 10 | * However, you would not want to match against the domain in 11 | * support@example.com. So, when matching against a web URL pattern you 12 | * might also include a MatchFilter that disallows the match if it is 13 | * immediately preceded by an at-sign (@). 14 | * 15 | * @return Whether this match should be turned into a link 16 | */ 17 | typealias MatchFilter = (fullText: String, match: SimpleTextMatchResult) -> Boolean 18 | 19 | object MatchFilterDefaults { 20 | val NoOp: MatchFilter = { _, _ -> true } 21 | 22 | // from https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/text/util/Linkify.java;l=151;drc=4f9480b13d3cab52255608ac5913922ca4269ac5 23 | /** 24 | * Filters out web URL matches that occur after an at-sign (@). This is 25 | * to prevent turning the domain name in an email address into a web link. 26 | */ 27 | val WebUrls: MatchFilter = 28 | fun(fullText: String, match: SimpleTextMatchResult<*>): Boolean { 29 | if (match.start == 0) { 30 | return true 31 | } 32 | 33 | if (fullText[match.start - 1] == '@') { 34 | return false 35 | } 36 | 37 | if (fullText.slice(match).contains("@")) { 38 | return false 39 | } 40 | 41 | return true 42 | } 43 | 44 | private const val PHONE_NUMBER_MINIMUM_DIGITS = 5 45 | 46 | // from https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/text/util/Linkify.java;l=169;drc=4f9480b13d3cab52255608ac5913922ca4269ac5 47 | /** 48 | * Filters out URL matches that don't have enough digits to be a 49 | * phone number. 50 | */ 51 | val PhoneNumber: MatchFilter = 52 | fun(fullText: String, match: SimpleTextMatchResult<*>): Boolean { 53 | var digitCount = 0 54 | 55 | for (i in match.start until match.endExclusive) { 56 | if (fullText[i].isDigit()) { 57 | digitCount++ 58 | if (digitCount >= PHONE_NUMBER_MINIMUM_DIGITS) { 59 | return true 60 | } 61 | } 62 | } 63 | return false 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchStylesProvider.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import androidx.compose.ui.text.TextLinkStyles 4 | 5 | typealias MatchStylesProvider = (match: TextMatchResult) -> TextLinkStyles? 6 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/MatchUrlProvider.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | /** 4 | * A function that provides an url for a match 5 | * Should return a string that will be used as the URL for the match 6 | * If the function returns null, the match will not be annotated 7 | */ 8 | typealias MatchUrlProvider = (match: TextMatchResult) -> String? 9 | 10 | interface MatchUrlProviderDefaultsInterface { 11 | val NoUrl: MatchUrlProvider<*> 12 | get() = { null } 13 | 14 | /** 15 | * A [MatchUrlProvider] that uses the matched text as the URL 16 | * This lets screen readers know that the text is clickable, but doesn't provide a different URL 17 | */ 18 | val Verbatim: MatchUrlProvider<*> 19 | get() = { it.matchedText } 20 | 21 | val WebUrl: MatchUrlProvider<*> 22 | get() = { it.matchedText } 23 | 24 | val EmailAddress: MatchUrlProvider<*> 25 | get() = { "mailto:${it.matchedText}" } 26 | 27 | val PhoneNumber: MatchUrlProvider<*> 28 | get() = { "tel:${normalizePhoneNumber(it.matchedText)}" } 29 | } 30 | 31 | internal expect fun getMatchUrlProviderDefaults(): MatchUrlProviderDefaultsInterface 32 | 33 | val MatchUrlProviderDefaults = getMatchUrlProviderDefaults() 34 | 35 | /** 36 | * only allow digits and "+" 37 | */ 38 | internal fun normalizePhoneNumber(phone: String): String { 39 | return phone.filter { it.isDigit() || it == '+' } 40 | } 41 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/NotForAndroid.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | @RequiresOptIn( 4 | message = "In Android, [ContextData] is extended by [AndroidContextData] to provide a [Context] object.\n" + 5 | "In other platforms, [ContextData] is a simple interface with no methods.\n" + 6 | "Calling this function on Android without [AndroidContextData] will throw an exception.", 7 | level = RequiresOptIn.Level.ERROR 8 | ) 9 | @Target(AnnotationTarget.FUNCTION) 10 | @Retention(AnnotationRetention.RUNTIME) 11 | annotation class NotForAndroid 12 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/SimpleTextMatchResult.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | open class SimpleTextMatchResult( 4 | override val start: Int, 5 | override val endExclusive: Int, 6 | val data: T, 7 | ) : OpenEndRange { 8 | fun slice(text: String) = text.substring(start, endExclusive) 9 | } 10 | 11 | fun SimpleTextMatchResult(start: Int, end: Int) = SimpleTextMatchResult(start, end, null) 12 | 13 | fun String.slice(match: SimpleTextMatchResult<*>) = match.slice(this) 14 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatchResult.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | class TextMatchResult( 4 | /** 5 | * The rule that was used to match the text 6 | */ 7 | val rule: TextRule, 8 | /** 9 | * The text that was matched 10 | */ 11 | val matchedText: String, 12 | start: Int, 13 | endExclusive: Int, 14 | data: T, 15 | ) : SimpleTextMatchResult(start, endExclusive, data) { 16 | constructor( 17 | rule: TextRule, 18 | /** 19 | * The full text that was matched against 20 | */ 21 | fullText: String, 22 | match: SimpleTextMatchResult, 23 | ) : this(rule, fullText.slice(match), match.start, match.endExclusive, match.data) 24 | } 25 | 26 | fun TextMatchResult(rule: TextRule, fullText: String, start: Int, end: Int) = 27 | TextMatchResult(rule, fullText, start, end, null) 28 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextMatcher.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import androidx.compose.runtime.Composable 4 | 5 | interface TextMatcherDefaultsInterface { 6 | @NotForAndroid 7 | fun webUrl(contextData: ContextData): TextMatcher = 8 | TextMatcher.RegexMatcher(BackUpRegex.WebUrl, MatchFilterDefaults.WebUrls) 9 | 10 | @NotForAndroid 11 | fun emailAddress(contextData: ContextData): TextMatcher = 12 | TextMatcher.RegexMatcher(BackUpRegex.Email) 13 | 14 | @NotForAndroid 15 | fun phoneNumber(contextData: ContextData): TextMatcher = 16 | TextMatcher.RegexMatcher(BackUpRegex.PhoneNumber, MatchFilterDefaults.PhoneNumber) 17 | 18 | @OptIn(NotForAndroid::class) 19 | @Composable 20 | fun webUrl() = webUrl(NullContextData) 21 | 22 | @OptIn(NotForAndroid::class) 23 | @Composable 24 | fun emailAddress() = emailAddress(NullContextData) 25 | 26 | @OptIn(NotForAndroid::class) 27 | @Composable 28 | fun phoneNumber() = phoneNumber(NullContextData) 29 | } 30 | 31 | internal expect fun getMatcherDefaults(): TextMatcherDefaultsInterface 32 | 33 | val TextMatcherDefaults = getMatcherDefaults() 34 | 35 | /** 36 | * A [TextMatcher] is used to match text in a string. 37 | */ 38 | sealed class TextMatcher { 39 | abstract fun apply(text: String): List> 40 | 41 | /** 42 | * A [TextMatcher] that matches a [Regex] in the text. 43 | */ 44 | class RegexMatcher( 45 | val regex: Regex, 46 | val matchFilter: MatchFilter = MatchFilterDefaults.NoOp, 47 | ) : TextMatcher() { 48 | override fun apply(text: String): List> { 49 | val matches = mutableListOf>() 50 | regex.findAll(text).forEach { 51 | val result = SimpleTextMatchResult( 52 | start = it.range.first, 53 | endExclusive = it.range.last + 1, 54 | it 55 | ) 56 | if (matchFilter(text, result)) { 57 | matches.add(result) 58 | } 59 | } 60 | return matches 61 | } 62 | } 63 | 64 | /** 65 | * A [TextMatcher] that matches all instances of a string in the text. 66 | */ 67 | class StringMatcher( 68 | val string: String, 69 | val matchFilter: MatchFilter = MatchFilterDefaults.NoOp, 70 | ) : TextMatcher() { 71 | override fun apply(text: String): List> { 72 | val matches = mutableListOf>() 73 | var index = text.indexOf(string) 74 | while (index != -1) { 75 | val result = SimpleTextMatchResult(index, index + string.length) 76 | if (matchFilter(text, result)) { 77 | matches.add(result) 78 | } 79 | index = text.indexOf(string, index + 1) 80 | } 81 | return matches 82 | } 83 | } 84 | 85 | /** 86 | * A [TextMatcher] that matches based on a function. 87 | */ 88 | class FunctionMatcher(val function: (String) -> List>) : 89 | TextMatcher() { 90 | override fun apply(text: String): List> { 91 | return function(text) 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /autolinktext/src/commonMain/kotlin/sh/calvin/autolinktext/TextRule.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import androidx.compose.runtime.Composable 4 | import androidx.compose.ui.text.AnnotatedString 5 | import androidx.compose.ui.text.LinkAnnotation 6 | import androidx.compose.ui.text.SpanStyle 7 | import androidx.compose.ui.text.TextLinkStyles 8 | 9 | interface ContextData 10 | 11 | val NullContextData: ContextData = object : ContextData {} 12 | 13 | interface TextRuleDefaultsInterface { 14 | @NotForAndroid 15 | fun webUrl(contextData: ContextData = NullContextData) = TextRule.Url( 16 | textMatcher = TextMatcherDefaults.webUrl(contextData), 17 | urlProvider = MatchUrlProviderDefaults.WebUrl, 18 | ) 19 | 20 | @NotForAndroid 21 | fun emailAddress(contextData: ContextData = NullContextData) = TextRule.Url( 22 | textMatcher = TextMatcherDefaults.emailAddress(contextData), 23 | urlProvider = MatchUrlProviderDefaults.EmailAddress, 24 | ) 25 | 26 | @NotForAndroid 27 | fun phoneNumber(contextData: ContextData = NullContextData) = TextRule.Url( 28 | textMatcher = TextMatcherDefaults.phoneNumber(contextData), 29 | urlProvider = MatchUrlProviderDefaults.PhoneNumber, 30 | ) 31 | 32 | @NotForAndroid 33 | fun defaultList(contextData: ContextData = NullContextData) = listOf( 34 | webUrl(contextData), 35 | emailAddress(contextData), 36 | phoneNumber(contextData), 37 | ) 38 | 39 | @OptIn(NotForAndroid::class) 40 | @Composable 41 | fun webUrl() = webUrl(NullContextData) 42 | 43 | @OptIn(NotForAndroid::class) 44 | @Composable 45 | fun emailAddress() = emailAddress(NullContextData) 46 | 47 | @OptIn(NotForAndroid::class) 48 | @Composable 49 | fun phoneNumber() = phoneNumber(NullContextData) 50 | 51 | @OptIn(NotForAndroid::class) 52 | @Composable 53 | fun defaultList() = defaultList(NullContextData) 54 | } 55 | 56 | internal expect fun getTextRuleDefaults(): TextRuleDefaultsInterface 57 | 58 | val TextRuleDefaults = getTextRuleDefaults() 59 | 60 | /** 61 | * A rule to match text and apply style and click handling. 62 | * 63 | * @param textMatcher The matcher to find the text in the input. 64 | * @param stylesProvider The provider to provide style for the matched text. 65 | */ 66 | sealed class TextRule private constructor( 67 | open val textMatcher: TextMatcher, 68 | open val stylesProvider: MatchStylesProvider?, 69 | ) { 70 | /** 71 | * A rule to match text and apply style and url. 72 | * 73 | * @param textMatcher The matcher to find the text in the input. 74 | * @param stylesProvider The provider to provide style for the matched text. 75 | * @param urlProvider The provider to provide urls for the matched text. 76 | */ 77 | data class Url( 78 | override val textMatcher: TextMatcher, 79 | override val stylesProvider: MatchStylesProvider? = null, 80 | val urlProvider: MatchUrlProvider = MatchUrlProviderDefaults.Verbatim 81 | ) : TextRule(textMatcher, stylesProvider) { 82 | constructor( 83 | textMatcher: TextMatcher, 84 | styles: TextLinkStyles? = null, 85 | urlProvider: MatchUrlProvider = MatchUrlProviderDefaults.Verbatim 86 | ) : this(textMatcher, stylesProvider = styles?.let { s -> { s } }, urlProvider) 87 | 88 | constructor( 89 | textMatcher: TextMatcher, 90 | urlProvider: MatchUrlProvider = MatchUrlProviderDefaults.Verbatim 91 | ) : this(textMatcher, stylesProvider = null, urlProvider) 92 | 93 | fun copy( 94 | textMatcher: TextMatcher = this.textMatcher, 95 | styles: TextLinkStyles?, 96 | urlProvider: MatchUrlProvider = this.urlProvider, 97 | ) = Url( 98 | textMatcher = textMatcher, 99 | stylesProvider = styles?.let { s -> { s } }, 100 | urlProvider = urlProvider, 101 | ) 102 | 103 | override fun copy( 104 | textMatcher: TextMatcher, 105 | styles: TextLinkStyles, 106 | ) = Url( 107 | textMatcher = textMatcher, 108 | stylesProvider = styles.let { s -> { s } }, 109 | urlProvider = this.urlProvider, 110 | ) 111 | } 112 | 113 | /** 114 | * A rule to match text and apply style and click handling. 115 | * 116 | * @param textMatcher The matcher to find the text in the input. 117 | * @param stylesProvider The provider to provide style for the matched text. 118 | * @param onClick The handler to handle click events on the matched text. 119 | */ 120 | data class Clickable( 121 | override val textMatcher: TextMatcher, 122 | override val stylesProvider: MatchStylesProvider? = null, 123 | val onClick: MatchClickHandler, 124 | ) : TextRule(textMatcher, stylesProvider) { 125 | constructor( 126 | textMatcher: TextMatcher, 127 | styles: TextLinkStyles? = null, 128 | onClick: MatchClickHandler, 129 | ) : this(textMatcher, stylesProvider = styles?.let { s -> { s } }, onClick) 130 | 131 | constructor( 132 | textMatcher: TextMatcher, 133 | onClick: MatchClickHandler, 134 | ) : this(textMatcher, stylesProvider = null, onClick) 135 | 136 | fun copy( 137 | textMatcher: TextMatcher = this.textMatcher, 138 | styles: TextLinkStyles?, 139 | onClick: MatchClickHandler = this.onClick, 140 | ) = Clickable( 141 | textMatcher = textMatcher, 142 | stylesProvider = styles?.let { s -> { s } }, 143 | onClick = onClick, 144 | ) 145 | 146 | override fun copy( 147 | textMatcher: TextMatcher, 148 | styles: TextLinkStyles, 149 | ) = Clickable( 150 | textMatcher = textMatcher, 151 | stylesProvider = styles.let { s -> { s } }, 152 | onClick = this.onClick, 153 | ) 154 | } 155 | 156 | /** 157 | * A rule to match text and apply style. 158 | * 159 | * @param textMatcher The matcher to find the text in the input. 160 | * @param stylesProvider The provider to provide style for the matched text. 161 | */ 162 | data class Styleable( 163 | override val textMatcher: TextMatcher, 164 | override val stylesProvider: MatchStylesProvider, 165 | ) : TextRule(textMatcher, stylesProvider) { 166 | constructor( 167 | textMatcher: TextMatcher, 168 | styles: TextLinkStyles, 169 | ) : this(textMatcher, { styles }) 170 | 171 | constructor( 172 | textMatcher: TextMatcher, 173 | style: SpanStyle, 174 | ) : this(textMatcher, { TextLinkStyles(style) }) 175 | 176 | override fun copy( 177 | textMatcher: TextMatcher, 178 | styles: TextLinkStyles, 179 | ) = Styleable( 180 | textMatcher = textMatcher, 181 | stylesProvider = styles.let { s -> { s } }, 182 | ) 183 | } 184 | 185 | abstract fun copy( 186 | textMatcher: TextMatcher = this.textMatcher, 187 | styles: TextLinkStyles, 188 | ): TextRule 189 | } 190 | 191 | internal fun Collection>.getAllMatches(text: String): List> = 192 | flatMap { rule -> 193 | rule.textMatcher.apply(text).map { match -> 194 | TextMatchResult(rule, text, match) 195 | } 196 | }.pruneOverlaps() 197 | 198 | // from https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/text/util/Linkify.java;l=737;drc=4f9480b13d3cab52255608ac5913922ca4269ac5 199 | private fun List>.pruneOverlaps(): List> { 200 | val sortedList = sortedWith { a, b -> 201 | if (a.start < b.start) { 202 | return@sortedWith -1 203 | } 204 | 205 | if (a.start > b.start) { 206 | return@sortedWith 1 207 | } 208 | 209 | if (a.endExclusive < b.endExclusive) { 210 | return@sortedWith 1 211 | } 212 | 213 | if (a.endExclusive > b.endExclusive) { 214 | return@sortedWith -1 215 | } 216 | 217 | return@sortedWith 0 218 | }.toMutableList() 219 | 220 | var len: Int = sortedList.size 221 | var i = 0 222 | 223 | while (i < len - 1) { 224 | val a = sortedList[i] 225 | val b = sortedList[i + 1] 226 | var remove = -1 227 | if (a.start <= b.start && a.endExclusive > b.start) { 228 | if (b.endExclusive <= a.endExclusive) { 229 | remove = i + 1 230 | } else if (a.endExclusive - a.start > b.endExclusive - b.start) { 231 | remove = i + 1 232 | } else if (a.endExclusive - a.start < b.endExclusive - b.start) { 233 | remove = i 234 | } 235 | if (remove != -1) { 236 | sortedList.removeAt(remove) 237 | len-- 238 | continue 239 | } 240 | } 241 | i++ 242 | } 243 | 244 | return sortedList 245 | } 246 | 247 | internal fun List>.annotateString(text: String): AnnotatedString { 248 | val annotatedString = AnnotatedString.Builder(text) 249 | forEach { match -> 250 | annotatedString.addMatch(match) 251 | } 252 | 253 | return annotatedString.toAnnotatedString() 254 | } 255 | 256 | fun AnnotatedString.Builder.addMatch( 257 | match: TextMatchResult 258 | ) { 259 | val styles = match.rule.stylesProvider?.invoke(match) 260 | when (match.rule) { 261 | is TextRule.Url -> { 262 | val url = match.rule.urlProvider(match) 263 | 264 | if (url != null) { 265 | addLink( 266 | url = LinkAnnotation.Url( 267 | url = url, 268 | styles = styles, 269 | ), 270 | start = match.start, 271 | end = match.endExclusive, 272 | ) 273 | } 274 | } 275 | 276 | is TextRule.Clickable -> { 277 | addLink( 278 | clickable = LinkAnnotation.Clickable( 279 | tag = "", 280 | styles = styles, 281 | linkInteractionListener = { 282 | match.rule.onClick(match) 283 | } 284 | ), 285 | start = match.start, 286 | end = match.endExclusive, 287 | ) 288 | } 289 | 290 | is TextRule.Styleable -> { 291 | styles?.style?.let { 292 | addStyle( 293 | it, 294 | match.start, 295 | match.endExclusive 296 | ) 297 | } 298 | } 299 | } 300 | } 301 | 302 | fun Collection>.annotateString(text: String): AnnotatedString { 303 | val matches = getAllMatches(text) 304 | return matches.annotateString(text) 305 | } -------------------------------------------------------------------------------- /autolinktext/src/commonTest/kotlin/sh/calvin/autolinktext/Ignore.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 4 | expect annotation class IgnoreIos() 5 | 6 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 7 | expect annotation class IgnoreJvm() 8 | 9 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 10 | expect annotation class IgnoreAndroid() 11 | 12 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 13 | expect annotation class IgnoreWasmJs() 14 | 15 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 16 | expect annotation class IgnoreJs() 17 | -------------------------------------------------------------------------------- /autolinktext/src/commonTest/kotlin/sh/calvin/autolinktext/SimpleTextMatchResultTest.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import kotlin.test.Test 4 | import kotlin.test.assertEquals 5 | 6 | class SimpleTextMatchResultTest { 7 | @Test 8 | fun shouldReturnCorrectSubstring() { 9 | val text = "123abc456def789" 10 | val match = SimpleTextMatchResult(3, 6) 11 | 12 | val result = text.slice(match) 13 | 14 | assertEquals("abc", result) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /autolinktext/src/commonTest/kotlin/sh/calvin/autolinktext/TextMatchResultTest.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import androidx.compose.ui.text.SpanStyle 4 | import kotlin.test.Test 5 | import kotlin.test.assertEquals 6 | import kotlin.test.assertNull 7 | 8 | class TextMatchResultTest { 9 | @Test 10 | fun shouldReturnCorrectSubstring() { 11 | val rule = TextRule.Styleable(TextMatcher.StringMatcher("test"), SpanStyle()) 12 | val text = "123abc456def789" 13 | val match = TextMatchResult(rule, text, 3, 6) 14 | 15 | val result = text.slice(match) 16 | 17 | assertEquals("abc", result) 18 | } 19 | 20 | @Test 21 | fun shouldConstructWithoutData() { 22 | val rule = TextRule.Styleable(TextMatcher.StringMatcher("test"), SpanStyle()) 23 | val text = "123abc456def789" 24 | 25 | val result = TextMatchResult( 26 | rule, 27 | text, 28 | 3, 29 | 6, 30 | ) 31 | 32 | assertEquals(rule, result.rule) 33 | assertEquals(3, result.start) 34 | assertEquals(6, result.endExclusive) 35 | assertNull(result.data) 36 | } 37 | 38 | @Test 39 | fun shouldConstructFromSimpleTextMatchResultWithoutData() { 40 | val rule = TextRule.Styleable(TextMatcher.StringMatcher("test"), SpanStyle()) 41 | val text = "123abc456def789" 42 | 43 | val textMatchResult = SimpleTextMatchResult(3, 6) 44 | val result = TextMatchResult( 45 | rule, 46 | text, 47 | textMatchResult, 48 | ) 49 | 50 | assertEquals(rule, result.rule) 51 | assertEquals(3, result.start) 52 | assertEquals(6, result.endExclusive) 53 | assertNull(result.data) 54 | } 55 | 56 | @Test 57 | fun shouldConstructFromSimpleTextMatchResultWithData() { 58 | val rule = TextRule.Styleable(TextMatcher.RegexMatcher(Regex("abc")), SpanStyle()) 59 | val text = "123abc456def789" 60 | val matchResult = Regex("abc").find(text)!! 61 | 62 | val textMatchResult = SimpleTextMatchResult(3, 6, matchResult) 63 | val result = TextMatchResult( 64 | rule, 65 | text, 66 | textMatchResult, 67 | ) 68 | 69 | assertEquals(rule, result.rule) 70 | assertEquals(3, result.start) 71 | assertEquals(6, result.endExclusive) 72 | assertEquals(matchResult, result.data) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /autolinktext/src/commonTest/kotlin/sh/calvin/autolinktext/TextMatcherTest.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import kotlin.test.Test 4 | import kotlin.test.assertEquals 5 | 6 | class TextMatcherTest { 7 | @Test 8 | fun testRegexMatcher() { 9 | val regex = Regex("\\d+") // match digits 10 | val text = "123abc456def789" 11 | val matcher = TextMatcher.RegexMatcher(regex) 12 | val matches = matcher.apply(text) 13 | 14 | assertEquals(3, matches.size) 15 | assertEquals(0, matches[0].start) 16 | assertEquals(3, matches[0].endExclusive) 17 | assertEquals(6, matches[1].start) 18 | assertEquals(9, matches[1].endExclusive) 19 | assertEquals(12, matches[2].start) 20 | assertEquals(15, matches[2].endExclusive) 21 | 22 | assertEquals("123", text.slice(matches[0])) 23 | assertEquals("456", text.slice(matches[1])) 24 | assertEquals("789", text.slice(matches[2])) 25 | } 26 | 27 | @Test 28 | fun testStringMatcher() { 29 | val string = "abc" 30 | val text = "123abc456abc789" 31 | val matcher = TextMatcher.StringMatcher(string) 32 | val matches = matcher.apply(text) 33 | 34 | assertEquals(2, matches.size) 35 | assertEquals(3, matches[0].start) 36 | assertEquals(6, matches[0].endExclusive) 37 | assertEquals(9, matches[1].start) 38 | assertEquals(12, matches[1].endExclusive) 39 | 40 | assertEquals("abc", text.slice(matches[0])) 41 | assertEquals("abc", text.slice(matches[1])) 42 | } 43 | 44 | @Test 45 | fun testFunctionMatcher() { 46 | val text = "123abc456def789" 47 | val matcher = TextMatcher.FunctionMatcher { 48 | listOf( 49 | SimpleTextMatchResult(3, 6), 50 | SimpleTextMatchResult(6, 9) 51 | ) 52 | } 53 | val matches = matcher.apply(text) 54 | 55 | assertEquals(2, matches.size) 56 | assertEquals(3, matches[0].start) 57 | assertEquals(6, matches[0].endExclusive) 58 | assertEquals(6, matches[1].start) 59 | assertEquals(9, matches[1].endExclusive) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /autolinktext/src/commonTest/kotlin/sh/calvin/autolinktext/TextRuleTest.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import androidx.compose.ui.text.ExperimentalTextApi 4 | import androidx.compose.ui.text.LinkAnnotation 5 | import androidx.compose.ui.text.SpanStyle 6 | import kotlin.test.Test 7 | import kotlin.test.assertEquals 8 | 9 | class TextRuleTest { 10 | @Test 11 | fun testAListOfMatcherShouldHandleOverlaps() { 12 | val text = "123abc456def789" 13 | val rules = listOf( 14 | TextRule.Styleable( 15 | textMatcher = TextMatcher.RegexMatcher(Regex("123a")), 16 | style = SpanStyle() 17 | ), 18 | TextRule.Styleable( 19 | textMatcher = TextMatcher.RegexMatcher(Regex("abc")), 20 | style = SpanStyle() 21 | ), 22 | ) 23 | val matches = rules.getAllMatches(text) 24 | 25 | assertEquals(1, matches.size) 26 | assertEquals(0, matches[0].start) 27 | assertEquals(4, matches[0].endExclusive) 28 | assertEquals("123a", text.slice(matches[0])) 29 | assertEquals(rules[0], matches[0].rule) 30 | } 31 | 32 | @OptIn(NotForAndroid::class) 33 | @IgnoreAndroid 34 | @Test 35 | fun emailsShouldBeMatched() { 36 | val text = "test someone@example.com test" 37 | val rules = listOf(TextRuleDefaults.emailAddress(NullContextData)) 38 | val matches = rules.getAllMatches(text) 39 | 40 | assertEquals(1, matches.size) 41 | assertEquals("someone@example.com", text.slice(matches[0])) 42 | } 43 | 44 | @OptIn(NotForAndroid::class) 45 | @IgnoreAndroid 46 | @Test 47 | fun phoneNumbersShouldBeMatched() { 48 | val text = "test 123-456-7890 test" 49 | val rules = listOf(TextRuleDefaults.phoneNumber(NullContextData)) 50 | val matches = rules.getAllMatches(text) 51 | 52 | assertEquals(1, matches.size) 53 | assertEquals("123-456-7890", text.slice(matches[0])) 54 | } 55 | 56 | @OptIn(NotForAndroid::class) 57 | @IgnoreAndroid 58 | @Test 59 | fun webUrlsShouldBeMatched() { 60 | val text = "test http://example.com test example.com" 61 | val rules = listOf(TextRuleDefaults.webUrl(NullContextData)) 62 | val matches = rules.getAllMatches(text) 63 | 64 | assertEquals(2, matches.size) 65 | assertEquals("http://example.com", text.slice(matches[0])) 66 | assertEquals("example.com", text.slice(matches[1])) 67 | } 68 | 69 | @OptIn(NotForAndroid::class) 70 | @IgnoreAndroid 71 | @Test 72 | fun emailShouldNotBeConfusedWithWebUrl() { 73 | val text = "test someone@example.com test" 74 | val rules = listOf( 75 | TextRuleDefaults.webUrl(NullContextData), 76 | TextRuleDefaults.emailAddress(NullContextData), 77 | ) 78 | val matches = rules.getAllMatches(text) 79 | 80 | assertEquals(1, matches.size) 81 | assertEquals("someone@example.com", text.slice(matches[0])) 82 | assertEquals(rules[1], matches[0].rule) 83 | } 84 | 85 | @OptIn(NotForAndroid::class) 86 | @IgnoreAndroid 87 | @Test 88 | fun shouldMatchComplexText() { 89 | val text = "Visit https://www.google.com\n" + 90 | "Visit www.google.com\n" + 91 | "Email test@example.com\n" + 92 | "Call 6045557890\n" + 93 | "Call +1 (604) 555-7890\n" + 94 | "Call 604-555-7890\n" 95 | val rules = listOf( 96 | TextRuleDefaults.webUrl(NullContextData), 97 | TextRuleDefaults.emailAddress(NullContextData), 98 | TextRuleDefaults.phoneNumber(NullContextData), 99 | ) 100 | val matches = rules.getAllMatches(text) 101 | 102 | assertEquals(6, matches.size) 103 | assertEquals("https://www.google.com", text.slice(matches[0])) 104 | assertEquals(rules[0], matches[0].rule) 105 | assertEquals("www.google.com", text.slice(matches[1])) 106 | assertEquals(rules[0], matches[1].rule) 107 | assertEquals("test@example.com", text.slice(matches[2])) 108 | assertEquals(rules[1], matches[2].rule) 109 | assertEquals("6045557890", text.slice(matches[3])) 110 | assertEquals(rules[2], matches[3].rule) 111 | assertEqualsOneOf(listOf("+1 (604) 555-7890", "(604) 555-7890"), text.slice(matches[4])) 112 | assertEquals(rules[2], matches[4].rule) 113 | assertEquals("604-555-7890", text.slice(matches[5])) 114 | assertEquals(rules[2], matches[5].rule) 115 | } 116 | 117 | @OptIn(NotForAndroid::class, ExperimentalTextApi::class) 118 | @IgnoreAndroid 119 | @Test 120 | fun testAnnotateString() { 121 | val text = "Visit https://www.google.com\n" + 122 | "Visit www.google.com\n" + 123 | "Email test@example.com\n" + 124 | "Call 6045557890\n" + 125 | "Call +1 (604) 555-7890\n" + 126 | "Call 604-555-7890\n" 127 | val rules = listOf( 128 | TextRuleDefaults.webUrl(NullContextData), 129 | TextRuleDefaults.emailAddress(NullContextData), 130 | TextRuleDefaults.phoneNumber(NullContextData), 131 | ) 132 | val matches = rules.getAllMatches(text) 133 | val annotatedString = matches.annotateString(text) 134 | 135 | fun getUrlAtMatch(index: Int) = (annotatedString.getLinkAnnotations( 136 | matches[index].start, matches[index].endExclusive 137 | ).first().item as? LinkAnnotation.Url)?.url 138 | 139 | assertEquals("https://www.google.com", getUrlAtMatch(0)) 140 | assertEqualsOneOf( 141 | listOf("https://www.google.com", "http://www.google.com"), 142 | getUrlAtMatch(1) ?: "" 143 | ) 144 | assertEquals("mailto:test@example.com", getUrlAtMatch(2)) 145 | assertEquals("tel:6045557890", getUrlAtMatch(3)) 146 | assertEquals("tel:+16045557890", getUrlAtMatch(4)) 147 | assertEquals("tel:6045557890", getUrlAtMatch(5)) 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /autolinktext/src/commonTest/kotlin/sh/calvin/autolinktext/helpers.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import kotlin.test.assertTrue 4 | 5 | fun assertEqualsOneOf(expected: List, actual: String) { 6 | assertTrue(expected.contains(actual), "Expected one of $expected, but was $actual") 7 | } 8 | -------------------------------------------------------------------------------- /autolinktext/src/iosMain/kotlin/sh/calvin/autolinktext/MatchUrlProvider.ios.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import platform.Foundation.NSURL 4 | import platform.Foundation.NSURLComponents 5 | 6 | object IosMatchUrlProviderDefaults : MatchUrlProviderDefaultsInterface { 7 | override val WebUrl: MatchUrlProvider<*> 8 | get() = { 9 | val url = when (val data = it.data) { 10 | is NSURL -> data 11 | else -> NSURLComponents(it.matchedText).apply { 12 | scheme = scheme ?: "https" 13 | }.URL 14 | } 15 | url?.absoluteString 16 | } 17 | 18 | override val EmailAddress: MatchUrlProvider<*> 19 | get() = { 20 | val url = when (val data = it.data) { 21 | is NSURL -> data 22 | else -> NSURL(string = "mailto:${it.matchedText}") 23 | } 24 | url.absoluteString 25 | } 26 | 27 | override val PhoneNumber: MatchUrlProvider<*> 28 | get() = { 29 | val url = when (val data = it.data) { 30 | is NSURL -> data 31 | else -> NSURL(string = "tel:${normalizePhoneNumber(it.matchedText)}") 32 | } 33 | url.absoluteString 34 | } 35 | } 36 | 37 | internal actual fun getMatchUrlProviderDefaults(): MatchUrlProviderDefaultsInterface = 38 | IosMatchUrlProviderDefaults 39 | -------------------------------------------------------------------------------- /autolinktext/src/iosMain/kotlin/sh/calvin/autolinktext/TextMatcher.ios.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import kotlinx.cinterop.ExperimentalForeignApi 4 | import kotlinx.cinterop.useContents 5 | import platform.Foundation.NSDataDetector 6 | import platform.Foundation.NSMakeRange 7 | import platform.Foundation.NSTextCheckingResult 8 | import platform.Foundation.NSTextCheckingTypeLink 9 | import platform.Foundation.NSTextCheckingTypePhoneNumber 10 | import platform.Foundation.URL 11 | import platform.Foundation.matchesInString 12 | 13 | object IosTextMatcherDefaults : TextMatcherDefaultsInterface { 14 | @NotForAndroid 15 | @OptIn(ExperimentalForeignApi::class) 16 | override fun webUrl(contextData: ContextData): TextMatcher { 17 | return TextMatcher.FunctionMatcher { text -> 18 | val detector = NSDataDetector(types = NSTextCheckingTypeLink, error = null) 19 | val range = NSMakeRange(0u, text.length.toULong()) 20 | val matches = detector.matchesInString( 21 | text, 22 | options = 0u, 23 | range = range 24 | ) as List 25 | 26 | matches.mapNotNull { match -> 27 | if (match.resultType == NSTextCheckingTypeLink && match.URL?.scheme != "mailto") { 28 | match.range.useContents { 29 | val start = location.toInt() 30 | val end = start + length.toInt() 31 | SimpleTextMatchResult(start, end, match.URL) 32 | } 33 | } else { 34 | null 35 | } 36 | } 37 | } 38 | } 39 | 40 | @NotForAndroid 41 | @OptIn(ExperimentalForeignApi::class) 42 | override fun emailAddress(contextData: ContextData): TextMatcher { 43 | return TextMatcher.FunctionMatcher { text -> 44 | val detector = NSDataDetector(types = NSTextCheckingTypeLink, error = null) 45 | val range = NSMakeRange(0u, text.length.toULong()) 46 | val matches = detector.matchesInString( 47 | text, 48 | options = 0u, 49 | range = range 50 | ) as List 51 | 52 | matches.mapNotNull { match -> 53 | if (match.resultType == NSTextCheckingTypeLink && match.URL?.scheme == "mailto") { 54 | match.range.useContents { 55 | val start = location.toInt() 56 | val end = start + length.toInt() 57 | SimpleTextMatchResult(start, end, match.URL) 58 | } 59 | } else { 60 | null 61 | } 62 | } 63 | } 64 | } 65 | 66 | @NotForAndroid 67 | @OptIn(ExperimentalForeignApi::class) 68 | override fun phoneNumber(contextData: ContextData): TextMatcher { 69 | return TextMatcher.FunctionMatcher { text -> 70 | val detector = NSDataDetector(types = NSTextCheckingTypePhoneNumber, error = null) 71 | val range = NSMakeRange(0u, text.length.toULong()) 72 | val matches = detector.matchesInString( 73 | text, 74 | options = 0u, 75 | range = range 76 | ) as List 77 | 78 | matches.mapNotNull { match -> 79 | if (match.resultType == NSTextCheckingTypePhoneNumber) { 80 | match.range.useContents { 81 | val start = location.toInt() 82 | val end = start + length.toInt() 83 | SimpleTextMatchResult(start, end, match.URL) 84 | } 85 | } else { 86 | null 87 | } 88 | } 89 | } 90 | } 91 | } 92 | 93 | internal actual fun getMatcherDefaults(): TextMatcherDefaultsInterface = IosTextMatcherDefaults 94 | -------------------------------------------------------------------------------- /autolinktext/src/iosMain/kotlin/sh/calvin/autolinktext/TextRule.ios.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | object IosTextRuleDefaults : TextRuleDefaultsInterface 4 | 5 | internal actual fun getTextRuleDefaults(): TextRuleDefaultsInterface = IosTextRuleDefaults 6 | -------------------------------------------------------------------------------- /autolinktext/src/iosTest/kotlin/sh/calvin/autolinktext/Ignore.ios.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | actual typealias IgnoreIos = kotlin.test.Ignore 4 | 5 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 6 | actual annotation class IgnoreJvm 7 | 8 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 9 | actual annotation class IgnoreAndroid 10 | 11 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 12 | actual annotation class IgnoreWasmJs 13 | 14 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 15 | actual annotation class IgnoreJs 16 | -------------------------------------------------------------------------------- /autolinktext/src/jsMain/kotlin/sh/calvin/autolinktext/MatchUrlProvider.js.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | internal actual fun getMatchUrlProviderDefaults() = 4 | object : MatchUrlProviderDefaultsInterface { 5 | override val WebUrl: MatchUrlProvider<*> 6 | get() = { 7 | var url = it.matchedText 8 | val protocolRegex = Regex("^\\S+://.+$") 9 | val hasProtocol = protocolRegex.matches(url) 10 | if (!hasProtocol) { 11 | url = "https://$url" 12 | } 13 | url 14 | } 15 | 16 | override val EmailAddress: MatchUrlProvider<*> 17 | get() = { 18 | "mailto:${it.matchedText}" 19 | } 20 | 21 | override val PhoneNumber: MatchUrlProvider<*> 22 | get() = { 23 | "tel:${normalizePhoneNumber(it.matchedText)}" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /autolinktext/src/jsMain/kotlin/sh/calvin/autolinktext/TextMatcher.js.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | internal actual fun getMatcherDefaults() = object : TextMatcherDefaultsInterface {} 4 | -------------------------------------------------------------------------------- /autolinktext/src/jsMain/kotlin/sh/calvin/autolinktext/TextRule.js.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | internal actual fun getTextRuleDefaults() = object : TextRuleDefaultsInterface {} 4 | -------------------------------------------------------------------------------- /autolinktext/src/jsTest/kotlin/sh/calvin/autolinktext/Ignore.js.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 4 | actual annotation class IgnoreIos 5 | 6 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 7 | actual annotation class IgnoreJvm 8 | 9 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 10 | actual annotation class IgnoreAndroid 11 | 12 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 13 | actual annotation class IgnoreWasmJs 14 | 15 | actual typealias IgnoreJs = kotlin.test.Ignore 16 | -------------------------------------------------------------------------------- /autolinktext/src/jvmMain/kotlin/sh/calvin/autolinktext/MatchUrlProvider.jvm.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import java.net.URI 4 | 5 | internal actual fun getMatchUrlProviderDefaults() = 6 | object : MatchUrlProviderDefaultsInterface { 7 | override val WebUrl: MatchUrlProvider<*> 8 | get() = { result -> 9 | val url = URI(result.matchedText).let { 10 | if (it.scheme == null || it.scheme.isEmpty()) { 11 | URI("https://${result.matchedText}") 12 | } else { 13 | it 14 | } 15 | } 16 | url.toString() 17 | } 18 | 19 | override val EmailAddress: MatchUrlProvider<*> 20 | get() = { 21 | "mailto:${it.matchedText}" 22 | } 23 | 24 | override val PhoneNumber: MatchUrlProvider<*> 25 | get() = { 26 | "tel:${normalizePhoneNumber(it.matchedText)}" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /autolinktext/src/jvmMain/kotlin/sh/calvin/autolinktext/TextMatcher.jvm.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | import com.google.i18n.phonenumbers.PhoneNumberUtil 4 | import java.util.Locale 5 | 6 | internal actual fun getMatcherDefaults() = object : TextMatcherDefaultsInterface { 7 | @NotForAndroid 8 | override fun phoneNumber(contextData: ContextData): TextMatcher { 9 | return TextMatcher.FunctionMatcher { text -> 10 | val phoneUtil = PhoneNumberUtil.getInstance() 11 | val regionCode = Locale.getDefault().country 12 | val matches = phoneUtil.findNumbers( 13 | text, 14 | regionCode, PhoneNumberUtil.Leniency.POSSIBLE, Long.MAX_VALUE, 15 | ) 16 | 17 | matches.mapNotNull { 18 | val result = SimpleTextMatchResult(it.start(), it.end()) 19 | if (MatchFilterDefaults.PhoneNumber(text, result)) result else null 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /autolinktext/src/jvmMain/kotlin/sh/calvin/autolinktext/TextRule.jvm.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | internal actual fun getTextRuleDefaults() = object : TextRuleDefaultsInterface {} 4 | -------------------------------------------------------------------------------- /autolinktext/src/jvmTest/kotlin/sh/calvin/autolinktext/Ignore.jvm.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 4 | actual annotation class IgnoreIos 5 | 6 | actual typealias IgnoreJvm = org.junit.Ignore 7 | 8 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 9 | actual annotation class IgnoreAndroid 10 | 11 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 12 | actual annotation class IgnoreWasmJs 13 | 14 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 15 | actual annotation class IgnoreJs 16 | -------------------------------------------------------------------------------- /autolinktext/src/wasmJsMain/kotlin/sh/calvin/autolinktext/MatchUrlProvider.wasmJs.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | internal actual fun getMatchUrlProviderDefaults() = 4 | object : MatchUrlProviderDefaultsInterface { 5 | override val WebUrl: MatchUrlProvider<*> 6 | get() = { 7 | var url = it.matchedText 8 | val protocolRegex = Regex("^\\S+://.+$") 9 | val hasProtocol = protocolRegex.matches(url) 10 | if (!hasProtocol) { 11 | url = "https://$url" 12 | } 13 | url 14 | } 15 | 16 | override val EmailAddress: MatchUrlProvider<*> 17 | get() = { 18 | "mailto:${it.matchedText}" 19 | } 20 | 21 | override val PhoneNumber: MatchUrlProvider<*> 22 | get() = { 23 | "tel:${normalizePhoneNumber(it.matchedText)}" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /autolinktext/src/wasmJsMain/kotlin/sh/calvin/autolinktext/TextMatcher.wasmJs.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | internal actual fun getMatcherDefaults() = object : TextMatcherDefaultsInterface {} 4 | -------------------------------------------------------------------------------- /autolinktext/src/wasmJsMain/kotlin/sh/calvin/autolinktext/TextRule.wasmJs.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | internal actual fun getTextRuleDefaults() = object : TextRuleDefaultsInterface {} 4 | -------------------------------------------------------------------------------- /autolinktext/src/wasmJsTest/kotlin/sh/calvin/autolinktext/Ignore.wasmJs.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext 2 | 3 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 4 | actual annotation class IgnoreIos 5 | 6 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 7 | actual annotation class IgnoreJvm 8 | 9 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 10 | actual annotation class IgnoreAndroid 11 | 12 | actual typealias IgnoreWasmJs = kotlin.test.Ignore 13 | 14 | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) 15 | actual annotation class IgnoreJs 16 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.android.application).apply(false) 3 | alias(libs.plugins.android.library).apply(false) 4 | alias(libs.plugins.kotlin.multiplatform).apply(false) 5 | alias(libs.plugins.compose).apply(false) 6 | alias(libs.plugins.compose.compiler).apply(false) 7 | alias(libs.plugins.maven.publish).apply(false) 8 | } 9 | -------------------------------------------------------------------------------- /demoApp/composeApp/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.compose.desktop.application.dsl.TargetFormat 2 | import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl 3 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget 4 | 5 | plugins { 6 | alias(libs.plugins.android.application) 7 | alias(libs.plugins.kotlin.multiplatform) 8 | alias(libs.plugins.compose) 9 | alias(libs.plugins.compose.compiler) 10 | } 11 | 12 | kotlin { 13 | androidTarget { 14 | compilations.all { 15 | compileTaskProvider.configure { 16 | compilerOptions { 17 | jvmTarget.set(JvmTarget.JVM_1_8) 18 | } 19 | } 20 | } 21 | } 22 | 23 | jvm() 24 | 25 | @OptIn(ExperimentalWasmDsl::class) 26 | wasmJs { 27 | moduleName = "composeApp" 28 | browser { 29 | commonWebpackConfig { 30 | outputFileName = "composeApp.js" 31 | } 32 | } 33 | binaries.executable() 34 | } 35 | 36 | js { 37 | moduleName = "composeApp" 38 | browser { 39 | commonWebpackConfig { 40 | outputFileName = "composeApp.js" 41 | } 42 | } 43 | binaries.executable() 44 | } 45 | 46 | listOf( 47 | iosX64(), 48 | iosArm64(), 49 | iosSimulatorArm64() 50 | ).forEach { 51 | it.binaries.framework { 52 | baseName = "ComposeApp" 53 | isStatic = true 54 | } 55 | } 56 | 57 | sourceSets { 58 | commonMain.dependencies { 59 | implementation(compose.runtime) 60 | implementation(compose.material3) 61 | implementation(project(":autolinktext")) 62 | } 63 | 64 | androidMain.dependencies { 65 | implementation(compose.uiTooling) 66 | implementation(libs.androidx.activity.compose) 67 | } 68 | 69 | jvmMain.dependencies { 70 | implementation(compose.desktop.common) 71 | implementation(compose.desktop.macos_x64) 72 | implementation(compose.desktop.macos_arm64) 73 | implementation(compose.desktop.windows_x64) 74 | implementation(compose.desktop.linux_x64) 75 | } 76 | } 77 | } 78 | 79 | android { 80 | namespace = "sh.calvin.autolinktext.demo" 81 | compileSdk = 35 82 | 83 | defaultConfig { 84 | applicationId = "sh.calvin.autolinktext.demo" 85 | minSdk = 24 86 | targetSdk = 35 87 | versionCode = 1 88 | versionName = "1.0" 89 | 90 | vectorDrawables { 91 | useSupportLibrary = true 92 | } 93 | } 94 | sourceSets["main"].apply { 95 | manifest.srcFile("src/androidMain/AndroidManifest.xml") 96 | res.srcDirs("src/androidMain/res") 97 | resources.srcDirs("src/commonMain/resources") 98 | } 99 | buildTypes { 100 | release { 101 | isMinifyEnabled = false 102 | proguardFiles( 103 | getDefaultProguardFile("proguard-android-optimize.txt"), 104 | "proguard-rules.pro" 105 | ) 106 | } 107 | } 108 | compileOptions { 109 | sourceCompatibility = JavaVersion.VERSION_1_8 110 | targetCompatibility = JavaVersion.VERSION_1_8 111 | } 112 | buildFeatures { 113 | compose = true 114 | } 115 | packaging { 116 | resources { 117 | excludes += "/META-INF/{AL2.0,LGPL2.1}" 118 | } 119 | } 120 | } 121 | 122 | compose.desktop { 123 | application { 124 | mainClass = "MainKt" 125 | 126 | nativeDistributions { 127 | targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) 128 | packageName = "sh.calvin.autolinktext.demo" 129 | packageVersion = "1.0.0" 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 15 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/kotlin/sh/calvin/autolinktext/demo/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package sh.calvin.autolinktext.demo 2 | 3 | import android.os.Bundle 4 | import androidx.activity.ComponentActivity 5 | import androidx.activity.compose.setContent 6 | 7 | class MainActivity : ComponentActivity() { 8 | override fun onCreate(savedInstanceState: Bundle?) { 9 | super.onCreate(savedInstanceState) 10 | 11 | setContent { 12 | App() 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/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 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/drawable/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calvin-LL/AutoLinkText/d59e9146208423fec3778b57503240d71d46df67/demoApp/composeApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AutoLinkText 3 | -------------------------------------------------------------------------------- /demoApp/composeApp/src/androidMain/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |